Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,68 @@ Two files, both outside any repo:
Every key, its default, the files the scripts write and the exit codes are in
[`docs/config.md`](docs/config.md).

## Local model

**Status: experimental.** One supervised fire has completed a tick on a local model; no full night has
run yet. Use it supervised.

Tested on 2026-11-29: Qwen3.8 27B (Q4 quantization, 256k context) on an integrated GPU, behind an
Anthropic-compatible server. The fire took a trivial to-do from `pending` to `completed`: 27 turns, 58
minutes, file written, commit merged into the pre-production branch by `/git-staging`, HANDOFF updated,
correct result line. `claude` reported 5.10 USD for it; local mode counted 0.

`NS_BILLING=local` points every fire at a model server on your own machine that speaks the Anthropic
Messages API (Ollama does, at `http://127.0.0.1:11434`). A night then costs no API spend:

```sh
NS_BILLING=local
ANTHROPIC_BASE_URL=http://127.0.0.1:11434
ANTHROPIC_AUTH_TOKEN=local # whatever the server expects; Ollama accepts calls without one
NS_MODEL_CODE=my-local-model # the server's own model names, for each class you use
ANTHROPIC_DEFAULT_HAIKU_MODEL=my-local-model
ANTHROPIC_DEFAULT_SONNET_MODEL=my-local-model
ANTHROPIC_DEFAULT_OPUS_MODEL=my-local-model
CLAUDE_CODE_SUBAGENT_MODEL=my-local-model
```

What local mode changes:

- **Fail closed.** The loop refuses to start without `ANTHROPIC_BASE_URL`, or when it is not on
`127.0.0.1`, `localhost` or `[::1]` (`NS_LOCAL_REMOTE_OK=1` allows a model server on another machine
that bills nothing). Fires run without `ANTHROPIC_API_KEY`.
- **No budgets.** `claude` does not know a local model's price, so it prints a made-up one: a one-word
reply from an 8B model came back as about 0.017 USD. That figure lands in the kit's cost ledger. Local
mode passes no `--budget-remaining`, sets no per-tick cap, ignores the three budgets, logs no cost per
fire, and lists its fires in `local-fires.tsv` so every spend sum (the loop, `--check`, the morning
report) counts them as 0. The caps that still hold are the window, the fire caps and the kill switch.
- **Model names.** `NS_MODEL_TRIAGE`, `NS_MODEL_SYNTHESIS`, `NS_MODEL_CODE` and `model=` take the names
the server lists (`ollama list`). `claude` resolves its own aliases (`haiku`, `sonnet`, `opus`) and
subagent model through `ANTHROPIC_DEFAULT_*_MODEL` and `CLAUDE_CODE_SUBAGENT_MODEL`; set them to a
local model so no call asks the server for a Claude model it does not serve.

Coming next: the kit's own `local` backend (in development, not in a release yet) drives a local model
without `claude` in between and reports no cost by construction. Early runs of the same tick on the same
model took minutes instead of an hour. Once it ships in a kit version this recipe pins, it should replace
the gateway route described here.

Known limits, from the first tests:

- **Small models cannot do a tick.** On a real fire (2026-11-28, Ollama, `llama3.1:8b` with a 32k
context), the model answered the tick in one turn with no tool call: it described the steps, printed
`LOOP_TICK_RESULT: continue` and changed nothing. The 27B model above did the same to-do with 26 tool calls.
- **An `ok` fire is not proof of work.** The kit recorded that empty fire as `ok` / `completed`, so the
loop would fire the same repo again up to its cap. On a local model, check in the morning that the
to-dos actually moved before trusting the Done section.
- **Context length.** The `claude` system prompt and tool list are large. Ollama picks a default context
from the memory it sees (its runner started at 4096 tokens here, with context shift on, which drops the
start of a longer prompt). Raise it with `OLLAMA_CONTEXT_LENGTH` or a model with `PARAMETER num_ctx`.
`claude` reported a 1M-token window for the unknown model, so do not count on its own compaction to
stay under the server's limit.
- **Protocol.** The server must speak the Anthropic Messages API, tool use included. A server that only
offers the OpenAI chat API needs a translating proxy in front of it; Night Shift does not ship one.
- **Speed.** A local tick is much slower than a hosted one (58 minutes for a one-line file above). Raise `NS_FIRE_WINDOW_MIN` and `NS_STALL_MIN` so
a slow tick is not taken for a stall.

## What runs

| Piece | What it does |
Expand Down Expand Up @@ -138,6 +200,8 @@ config) applies. There is no per-plan key in Night Shift; per plan is the plan's
redacts it from its own logs as well.
- **Subscription stays subscription.** With `NS_BILLING=subscription`, fires run with `ANTHROPIC_API_KEY`
removed, so a key left in your shell does not turn a night into API spend.
- **Local stays local.** With `NS_BILLING=local`, the loop refuses an endpoint that is not on this machine
unless you vouch for it, and fires run without a key (see [Local model](#local-model)).
- **Kill switch.** `touch ~/.config/night-shift/STOP`: no further fire starts, and the key wrapper runs
nothing. Remove the file to resume.
- **A window that holds.** A fire starts only when its whole `--window-min` fits before the window end, so
Expand Down Expand Up @@ -175,7 +239,9 @@ or misconfigured (exit 1); exit 5, a repo waiting for you, is declared a success
overlapping paths. The kit's lease covers one checkout. Night Shift avoids the problem by being linear
(one fire at a time across all repos); a claim mechanism waits for the loop pattern to settle.
- **Cost comes from the backend.** The ledger holds what `claude` reports; other backends record no cost,
and the budget then counts them as 0.
and the budget then counts them as 0. For a model it does not know, `claude` reports a made-up price;
local mode skips those lines, but a gateway to an unknown model under `subscription` or `api-key` would
count them.
- **Spend outside the listed repos is invisible.** Daytime runs in other clones do not count against the
night or month budget unless you list those clones.
- **Daylight-saving nights** shift the window by an hour.
Expand Down
43 changes: 40 additions & 3 deletions bin/night-shift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
# (<repo>/.cursor/context/cost-ledger.ndjson, written by the kit): the night budget minus what was spent
# since tonight's window start, and the month budget minus what was spent this UTC month, whichever is
# smaller. It goes to countdown as --budget-remaining=<usd>, so the kit refuses a fire it cannot cover.
# With NS_BILLING=local (a model served on this machine) no budget applies: the loop passes no
# --budget-remaining, and the fires' ledger lines count as 0 (see docs/config.md, "Endpoint").
#
# Exit status: 0 the night ended normally; 5 at least one repo is waiting for you (gate or question) and
# none is broken; 3 at least one repo is broken; 1 a configuration or setup error (nothing fired, or the
Expand Down Expand Up @@ -71,7 +73,22 @@ case $NS_BILLING in
exit 1
fi
;;
*) ns_err "NS_BILLING must be subscription or api-key"; exit 1 ;;
local)
# A local model bills nothing, so the budgets do not apply. That makes this mode fail closed: it
# refuses to start unless the endpoint is set and on this machine (or vouched for explicitly).
if [ -z "${ANTHROPIC_BASE_URL:-}" ]; then
ns_err "NS_BILLING=local needs ANTHROPIC_BASE_URL (the local model server, see docs/config.md)"
exit 1
fi
if ! ns_is_loopback_url "$ANTHROPIC_BASE_URL" && [ "$NS_LOCAL_REMOTE_OK" != 1 ]; then
ns_err "NS_BILLING=local: ANTHROPIC_BASE_URL is not on 127.0.0.1, localhost or [::1]; set NS_LOCAL_REMOTE_OK=1 only if that server bills nothing"
exit 1
fi
# Budgets would be checked against made-up prices, and a per-tick cap would kill ticks on them.
NS_NIGHT_BUDGET_USD='' NS_MONTH_BUDGET_USD='' NS_TICK_BUDGET_USD=''
unset AGENT_KIT_CLAUDE_MAX_BUDGET_USD
;;
*) ns_err "NS_BILLING must be subscription, api-key or local"; exit 1 ;;
esac
if ! command -v "$NS_AGENT_KIT" >/dev/null 2>&1; then
ns_err "agent-kit CLI not found: $NS_AGENT_KIT (install the pinned version, see README)"
Expand Down Expand Up @@ -116,7 +133,11 @@ if [ "$CHECK_ONLY" = 1 ]; then
echo "window: $(ns_fmt "$night_start" '%Y-%m-%d %H:%M') to $(ns_fmt "$night_end" '%Y-%m-%d %H:%M') (local)"
if [ "$now" -lt "$night_end" ]; then echo "now: inside the window"; else echo "now: outside the window"; fi
left=$(budget_left) || { ns_err "cost ledgers could not be read"; exit 1; }
echo "budget left for the next fire: ${left:-no budget configured} (billing: $NS_BILLING)"
if [ "$NS_BILLING" = local ]; then
echo "budget: not applied (billing: local, endpoint $(ns_endpoint_label))"
else
echo "budget left for the next fire: ${left:-no budget configured} (billing: $NS_BILLING)"
fi
rc=0
for i in "${!NS_R_PATH[@]}"; do
p=${NS_R_PATH[$i]} m=$(ns_model_for "$i")
Expand Down Expand Up @@ -169,7 +190,9 @@ if [ "$now" -ge "$night_end" ]; then
fi

[ -z "$NS_TICK_BUDGET_USD" ] || export AGENT_KIT_CLAUDE_MAX_BUDGET_USD="$NS_TICK_BUDGET_USD"
event start "repos ${#NS_R_PATH[@]}, until $(ns_fmt_utc "$night_end" %Y-%m-%dT%H:%M:%SZ), billing $NS_BILLING"
billing_label=$NS_BILLING
[ "$NS_BILLING" != local ] || billing_label="local ($(ns_endpoint_label)), budgets not applied"
event start "repos ${#NS_R_PATH[@]}, until $(ns_fmt_utc "$night_end" %Y-%m-%dT%H:%M:%SZ), billing $billing_label"

# --- the loop -------------------------------------------------------------------------------------
fires_night=0 broken=0 waiting=0 stop_cause='' final=0
Expand All @@ -190,14 +213,27 @@ fire() {
before=$(git -C "$repo" for-each-ref --format='%(refname:short)' refs/heads 2>/dev/null | sort)
base=$(ns_preprod_ref "$repo")
[ -n "$base" ] || base=$(git -C "$repo" rev-parse --verify --quiet HEAD)
local fstart
fstart=$(ns_fmt_utc "$(ns_now)" %Y-%m-%dT%H:%M:%S)
if [ "$NS_BILLING" = api-key ]; then
"$NS_BIN_DIR/night-shift-key" --config "$NS_CONFIG" -- "$NS_AGENT_KIT" "${args[@]}" >"$flog" 2>&1 </dev/null
elif [ "$NS_BILLING" = local ]; then
# Local model: no key at all (the endpoint gets ANTHROPIC_AUTH_TOKEN, if you set one).
env -u ANTHROPIC_API_KEY -u AGENT_KIT_CLAUDE_MAX_BUDGET_USD "$NS_AGENT_KIT" "${args[@]}" >"$flog" 2>&1 </dev/null
else
# Subscription billing: make sure a stray ANTHROPIC_API_KEY in this environment does not switch the
# agent to paid API billing behind your back.
env -u ANTHROPIC_API_KEY "$NS_AGENT_KIT" "${args[@]}" >"$flog" 2>&1 </dev/null
fi
RC=$?
if [ "$NS_BILLING" = local ]; then
# Mark this fire's ledger lines so ns_spend skips the price claude made up for the local model.
local fend
fend=$(ns_fmt_utc "$(ns_now)" %Y-%m-%dT%H:%M:%S)
# The end is exclusive; a fire that took less than a second still covers its own start.
[ "$fend" != "$fstart" ] || fend=$(ns_fmt_utc $(($(ns_now) + 1)) %Y-%m-%dT%H:%M:%S)
printf '%s\t%s\t%s\n' "$(basename "$repo")" "$fstart" "$fend" >>"$NS_LOCAL_FIRES"
fi
after=$(git -C "$repo" for-each-ref --format='%(refname:short)' refs/heads 2>/dev/null | sort)
# Branches this fire created that carry commits not yet in the pre-production branch (or, without one,
# not in the commit the fire started from). The morning report drops an item once all of them are
Expand All @@ -220,6 +256,7 @@ fire() {
[ -n "$OUTCOME" ] || OUTCOME=broken
fi
fi
[ "$NS_BILLING" != local ] || COST=''
log_line "$repo" "$RC" "$OUTCOME" "$COST" "$PLAN" "$TODO" "$REASON" "$branches"
}

Expand Down
9 changes: 7 additions & 2 deletions bin/night-shift-report
Original file line number Diff line number Diff line change
Expand Up @@ -234,14 +234,19 @@ render() {
echo
echo "| | Spent (USD) | Budget (USD) |"
echo "|---|---:|---:|"
echo "| Tonight | $(ns_money "$night_usd") | ${NS_NIGHT_BUDGET_USD:-none} |"
echo "| This month (UTC, to date) | $(ns_money "$month_usd") | ${NS_MONTH_BUDGET_USD:-none} |"
local nb=${NS_NIGHT_BUDGET_USD:-none} mb=${NS_MONTH_BUDGET_USD:-none}
[ "$NS_BILLING" != local ] || nb='not applied' mb='not applied'
echo "| Tonight | $(ns_money "$night_usd") | $nb |"
echo "| This month (UTC, to date) | $(ns_money "$month_usd") | $mb |"
for p in "${NS_R_PATH[@]}"; do
echo "| $(basename "$p") tonight | $(ns_money "$(ns_repo_spend "$p" "$SINCE" "$UNTIL")") | |"
done
[ "$budget_stops" -eq 0 ] || { echo; echo "The budget refused $budget_stops fire(s) tonight."; }
echo
echo "Spend is summed from the kit's cost ledgers; compare it with your provider's usage page."
if [ "$NS_BILLING" = local ]; then
echo "Billing is local: fires on the local model count as 0, and the budgets above are not applied to them."
fi
if [ "$n_dropped" -gt 0 ]; then
echo
echo "## Resolved since the night ($n_dropped)"
Expand Down
14 changes: 13 additions & 1 deletion config.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,25 @@ NS_MAX_FIRES_NIGHT=12
NS_PASSES=1 # 2+ revisits repos that still had work at their cap

# --- billing and budget ---------------------------------------------------------------------------
NS_BILLING=subscription # or api-key
NS_BILLING=subscription # or api-key, or local (a model served on this machine, see README)
# NS_API_KEY_FILE="$HOME/.config/night-shift/anthropic.key" # example; mode 600, used with api-key
# NS_KILL_SWITCH="$HOME/.config/night-shift/STOP"
NS_NIGHT_BUDGET_USD=20 # example
NS_MONTH_BUDGET_USD=200 # example
NS_TICK_BUDGET_USD=3 # example; exported as AGENT_KIT_CLAUDE_MAX_BUDGET_USD

# --- endpoint (gateway or local model) -------------------------------------------------------------
# Exported to every fire. Needed for NS_BILLING=local; with the other modes they route claude through a
# gateway. Leave them unset to talk to Anthropic directly.
# ANTHROPIC_BASE_URL=http://127.0.0.1:11434 # example: Ollama's Anthropic-compatible API
# ANTHROPIC_AUTH_TOKEN=local # example; sent as "Authorization: Bearer"
# NS_LOCAL_REMOTE_OK=0 # 1 = allow a non-loopback endpoint with NS_BILLING=local
# Model names the claude CLI uses for its own background calls; point them at a local model too:
# ANTHROPIC_DEFAULT_HAIKU_MODEL=my-local-model # example
# ANTHROPIC_DEFAULT_SONNET_MODEL=my-local-model # example
# ANTHROPIC_DEFAULT_OPUS_MODEL=my-local-model # example
# CLAUDE_CODE_SUBAGENT_MODEL=my-local-model # example

# --- model per task class (see README) --------------------------------------------------------------
NS_MODEL_TRIAGE=haiku # example alias; small model
NS_MODEL_SYNTHESIS=sonnet # example alias; mid model
Expand Down
20 changes: 19 additions & 1 deletion docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ On a daylight-saving change night the window is off by the shift (one hour).

| Key | Default | Meaning |
|---|---|---|
| `NS_BILLING` | `subscription` | `subscription`: fires run with `ANTHROPIC_API_KEY` removed from their environment, so a stray key cannot switch the agent to paid API billing. `api-key`: every fire goes through `bin/night-shift-key`, which injects the key into that fire only. `api-key` requires at least one of the two budgets below. |
| `NS_BILLING` | `subscription` | `subscription`: fires run with `ANTHROPIC_API_KEY` removed from their environment, so a stray key cannot switch the agent to paid API billing. `api-key`: every fire goes through `bin/night-shift-key`, which injects the key into that fire only. `api-key` requires at least one of the two budgets below. `local`: a model served on your own machine (see "Endpoint" below); fires run without `ANTHROPIC_API_KEY` or a per-tick cap, no `--budget-remaining` is passed, the three budgets are ignored and the fires' ledger lines count as 0 (claude prints a made-up price for a model it does not know). Refuses to start without `ANTHROPIC_BASE_URL` on `127.0.0.1`, `localhost` or `[::1]`. |
| `NS_API_KEY_FILE` | empty | File holding the API key (first line). Must be a regular file you own with mode exactly `600`. Empty: `night-shift-key` uses an `ANTHROPIC_API_KEY` already in its environment, else refuses. |
| `NS_KILL_SWITCH` | `~/.config/night-shift/STOP` | While this file exists, the loop fires nothing and `night-shift-key` runs nothing (exit 10). `touch` it to stop at once. |
| `NS_NIGHT_BUDGET_USD` | empty | Ceiling for tonight: spend summed from the cost ledgers since the window start. |
Expand All @@ -62,6 +62,23 @@ The ledgers are `<repo>/.cursor/context/cost-ledger.ndjson` in each listed repo,
every fire. Spend in a repo that is not on the list (a daytime clone, another machine) is not counted,
so leave headroom or list those clones too.

### Endpoint

The config file is sourced, not exported. These keys are the exception: when set, the loop exports them
to every fire, so a gateway or local model server written here reaches `claude`. Unset, `claude` talks to
Anthropic.

| Key | Default | Meaning |
|---|---|---|
| `ANTHROPIC_BASE_URL` | empty | Anthropic-protocol endpoint (gateway or local model server). Required with `NS_BILLING=local`. The kit redacts it from its logs; the run log names it only when it is loopback. |
| `ANTHROPIC_AUTH_TOKEN` | empty | Sent as `Authorization: Bearer`. Never printed by the loop or the kit. |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL` | empty | Model names `claude` uses for its aliases, background calls and subagents. With a local server, set them to a model it serves, or those calls ask it for a Claude model it does not have. |
| `NS_LOCAL_REMOTE_OK` | `0` | `1` lets `NS_BILLING=local` use an endpoint that is not loopback (a model server on another machine). Set it only when that server bills nothing: local mode applies no budget. |

Local fires are listed in `~/.local/state/night-shift/local-fires.tsv` (repo, start, end). The spend sums
skip the ledger lines those fires wrote, so switching back to `api-key` later in the month does not
count money that was never spent.

### Model per task class

| Key | Default | Meaning |
Expand Down Expand Up @@ -112,6 +129,7 @@ worktree anyway, give it its own config first:
| `lock/` | `night-shift` | Single-instance lock (a directory holding the pid). A lock whose pid is gone is taken over. |
| `runs.tsv` | `night-shift` | One tab-separated line per fire and per start/end event: `time`, `night`, `repo`, `exit`, `outcome`, `cost_usd`, `plan`, `todo`, `reason`, `branches` (branches the fire created). `-` marks an empty field. |
| `fires/<stamp>-<repo>-<n>.log` | `night-shift` | The full output of one fire (already redacted by the kit). |
| `local-fires.tsv` | `night-shift` | One line per fire made with `NS_BILLING=local`: repo, start, end (UTC). Spend sums skip the ledger lines written inside those intervals. |
| `reports/<night>.md` | `night-shift-report` | Each report. |

## Exit codes
Expand Down
Loading
Loading