From 79868bb47ffb5e1c3d7bd4c349305493f271ce4f Mon Sep 17 00:00:00 2001 From: agent-kit-startup <273612197+agent-kit-startup@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:23:35 -0300 Subject: [PATCH 1/4] feat: local billing mode and gateway variables reach every fire config.env is sourced but not exported, so ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN written there never reached a fire. The loader now exports the endpoint and model-name variables the claude CLI reads. NS_BILLING=local runs a night against a model served on this machine: - refuses to start without ANTHROPIC_BASE_URL on a loopback host (NS_LOCAL_REMOTE_OK=1 vouches for a non-billing remote server) - strips ANTHROPIC_API_KEY and AGENT_KIT_CLAUDE_MAX_BUDGET_USD - passes no --budget-remaining and ignores the three budgets - records its fires in local-fires.tsv so every spend sum skips the price claude makes up for an unknown model README documents the mode as experimental, with the limits found so far. Refs #1 --- README.md | 53 ++++++++++++++++++- bin/night-shift | 41 +++++++++++++-- bin/night-shift-report | 9 +++- config.env.example | 14 ++++- docs/config.md | 19 ++++++- lib/common.sh | 62 ++++++++++++++++++++-- plan-template.md | 2 +- tests/fake/agent-kit | 8 ++- tests/lib.sh | 4 +- tests/test_local.sh | 114 +++++++++++++++++++++++++++++++++++++++++ 10 files changed, 309 insertions(+), 17 deletions(-) create mode 100755 tests/test_local.sh diff --git a/README.md b/README.md index ade3853..9ab6480 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,53 @@ 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, not proven.** No full night has run on a local model yet. Use it supervised. + +`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 ignores it +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`). The `ANTHROPIC_DEFAULT_*_MODEL` and `CLAUDE_CODE_SUBAGENT_MODEL` + variables cover the calls `claude` makes on its own (background tasks, subagents); without them those + calls ask the server for a Claude model it does not have. + +Known limits, from the first tests: + +- **Small models cannot do a tick.** `llama3.1:8b` on Ollama answered a one-word prompt with 800 tokens + of tool-template text. A tick needs a model that follows tool calls reliably over a long context; the + next test is a 27B to 30B coding model. +- **Context length.** The `claude` system prompt and tool list are large. Ollama's default context is + much smaller (its runner started at 4096 tokens here), and it truncates silently; raise it + (`OLLAMA_CONTEXT_LENGTH`) to what the model supports. `claude` assumes a 1M-token window for a model it + does not know, so it will not compact before the server cuts the prompt. +- **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 slower than a hosted one. 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 | @@ -138,6 +185,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 @@ -175,7 +224,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. diff --git a/bin/night-shift b/bin/night-shift index 3585b4e..ac70e48 100755 --- a/bin/night-shift +++ b/bin/night-shift @@ -71,7 +71,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)" @@ -116,7 +131,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") @@ -169,7 +188,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 @@ -190,14 +211,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 "$flog" 2>&1 "$flog" 2>&1 >"$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 @@ -220,6 +254,7 @@ fire() { [ -n "$OUTCOME" ] || OUTCOME=broken fi fi + [ "$NS_BILLING" != local ] || COST='' log_line "$repo" "$RC" "$OUTCOME" "$COST" "$PLAN" "$TODO" "$REASON" "$branches" } diff --git a/bin/night-shift-report b/bin/night-shift-report index b5ec067..9dc2081 100755 --- a/bin/night-shift-report +++ b/bin/night-shift-report @@ -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)" diff --git a/config.env.example b/config.env.example index 6f8457f..11924d5 100644 --- a/config.env.example +++ b/config.env.example @@ -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 diff --git a/docs/config.md b/docs/config.md index d13fde6..849fc6c 100644 --- a/docs/config.md +++ b/docs/config.md @@ -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. | @@ -62,6 +62,23 @@ The ledgers are `/.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 | diff --git a/lib/common.sh b/lib/common.sh index e857035..0c6656b 100644 --- a/lib/common.sh +++ b/lib/common.sh @@ -85,10 +85,45 @@ ns_load_config() { NS_REPORT_FETCH=${NS_REPORT_FETCH:-0} NS_REPORT_FILE=${NS_REPORT_FILE:-} NS_REPORT_HOOK=${NS_REPORT_HOOK:-} + NS_LOCAL_REMOTE_OK=${NS_LOCAL_REMOTE_OK:-0} NS_RUN_LOG=$NS_STATE_DIR/runs.tsv + NS_LOCAL_FIRES=$NS_STATE_DIR/local-fires.tsv + ns_export_gateway return 0 } +# Endpoint and model-name variables the claude CLI reads. The config file is sourced, not exported, so a +# value set there would never reach a fire; ns_export_gateway exports the ones that are set. +NS_GATEWAY_VARS='ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN ANTHROPIC_DEFAULT_OPUS_MODEL ANTHROPIC_DEFAULT_SONNET_MODEL ANTHROPIC_DEFAULT_HAIKU_MODEL CLAUDE_CODE_SUBAGENT_MODEL' +ns_export_gateway() { + local v + for v in $NS_GATEWAY_VARS; do + if [ -n "$(eval "printf '%s' \"\${$v:-}\"")" ]; then export "${v?}"; fi + done +} + +# ns_endpoint_label: host:port of ANTHROPIC_BASE_URL when it is loopback, else "remote endpoint" (a remote +# address is kept out of the run log, like the kit keeps it out of its own logs). +ns_endpoint_label() { + if ns_is_loopback_url "${ANTHROPIC_BASE_URL:-}"; then + local hp=${ANTHROPIC_BASE_URL#*://} + echo "${hp%%/*}" + else + echo "remote endpoint" + fi +} + +# ns_is_loopback_url URL: true when URL is http(s) on 127.0.0.1, localhost or [::1], with any port and path. +ns_is_loopback_url() { + local rest=${1#http://} + [ "$rest" != "$1" ] || rest=${1#https://} + [ "$rest" != "$1" ] || return 1 + case $rest in + 127.0.0.1 | 127.0.0.1[:/]* | localhost | localhost[:/]* | '[::1]' | '[::1]'[:/]*) return 0 ;; + esac + return 1 +} + ns_is_uint() { case $1 in '' | *[!0-9]*) return 1 ;; esac; } ns_is_usd() { case $1 in @@ -163,6 +198,8 @@ ns_model_for() { # ns_spend SINCE UNTIL MONTH: prints " " in USD, summed over the cost ledgers of # every listed repo. SINCE and UNTIL are UTC stamps (YYYY-MM-DDTHH:MM:SS, UNTIL may be empty for "now"); # MONTH is YYYY-MM (UTC). Lines that are not JSON objects are skipped; a null cost counts as 0. +# Lines written by a fire on a local model (see NS_JQ_LOCAL) are skipped too: claude prints a made-up +# price for a model it does not know, and that money was never spent. ns_spend() { local files=() p f for p in "${NS_R_PATH[@]}"; do @@ -173,24 +210,39 @@ ns_spend() { echo "0 0" return 0 fi - jq -rRn --arg since "$1" --arg until "$2" --arg month "$3" ' - [inputs | fromjson? | select(type == "object")] as $l + jq -rRn --arg since "$1" --arg until "$2" --arg month "$3" --rawfile lf "$(ns_local_fires_file)" "$NS_JQ_LOCAL"' + [inputs | fromjson? | select(type == "object") | select(local_fire | not)] as $l | ($l | map(select((.at // "") >= $since and ($until == "" or (.at // "") < $until)) | (.cost_usd // 0) | numbers) | add // 0) as $night | ($l | map(select((.at // "") | startswith($month)) | (.cost_usd // 0) | numbers) | add // 0) as $mon | "\($night) \($mon)"' "${files[@]}" } -# ns_repo_spend REPO SINCE UNTIL: USD spent by one repo in the window. +# ns_repo_spend REPO SINCE UNTIL: USD spent by one repo in the window (local-model fires skipped). ns_repo_spend() { local f=$1/.cursor/context/cost-ledger.ndjson [ -f "$f" ] || { echo 0; return 0; } - jq -rRn --arg since "$2" --arg until "$3" ' - [inputs | fromjson? | select(type == "object") + jq -rRn --arg since "$2" --arg until "$3" --rawfile lf "$(ns_local_fires_file)" "$NS_JQ_LOCAL"' + [inputs | fromjson? | select(type == "object") | select(local_fire | not) | select((.at // "") >= $since and ($until == "" or (.at // "") < $until)) | (.cost_usd // 0) | numbers] | add // 0' "$f" } +# NS_LOCAL_FIRES ($NS_STATE_DIR/local-fires.tsv) holds one line per fire made with NS_BILLING=local: +# "\t\t", UTC stamps YYYY-MM-DDTHH:MM:SS. A ledger line belongs to such a fire +# when its repo matches and the first 19 characters of its "at" fall in [start, end). The kit stamps "at" +# when the fire begins, so the end is exclusive: the next fire may start in the second this one ended. +# shellcheck disable=SC2016 +NS_JQ_LOCAL=' + ($lf | split("\n") | map(select(length > 0) | split("\t") | select(length == 3))) as $fires + | def local_fire: (.repo // "") as $r | ((.at // "") | .[0:19]) as $a + | any($fires[]; .[0] == $r and .[1] <= $a and $a < .[2]); +' +# ns_local_fires_file: NS_LOCAL_FIRES when it exists, else /dev/null, so jq always gets a readable file. +ns_local_fires_file() { + if [ -f "${NS_LOCAL_FIRES:-}" ]; then echo "$NS_LOCAL_FIRES"; else echo /dev/null; fi +} + # ns_preprod_ref REPO: the ref merges are checked against: origin/ when it exists, else # the local branch, else nothing. ns_preprod_ref() { diff --git a/plan-template.md b/plan-template.md index fe1b522..25e7178 100644 --- a/plan-template.md +++ b/plan-template.md @@ -27,7 +27,7 @@ placed by the operator, never typed into an agent chat. mark each with `git -C config night-shift.owned true`. Write `~/.config/night-shift/repos`. 3. **HITL: budget ceilings.** Decide the night ceiling, the month ceiling and the per-tick cap (`NS_NIGHT_BUDGET_USD`, `NS_MONTH_BUDGET_USD`, `NS_TICK_BUDGET_USD`), and the billing mode - (`subscription` or `api-key`). Write `~/.config/night-shift/config.env` from `config.env.example`, + (`subscription`, `api-key`, or `local` for a model served on the operator's machine). Write `~/.config/night-shift/config.env` from `config.env.example`, `chmod 600`. 4. **HITL: API key placement (operator only, api-key billing).** The operator creates the key file (`NS_API_KEY_FILE`, mode `600`, outside every repo) or wires a secret manager that provides diff --git a/tests/fake/agent-kit b/tests/fake/agent-kit index f646e0a..78c2f41 100755 --- a/tests/fake/agent-kit +++ b/tests/fake/agent-kit @@ -2,7 +2,9 @@ # Fake agent-kit for the tests: no network, no agent, no kit. It answers `--version` and `countdown`. # # countdown --cwd REPO [flags]: -# - appends one line to $FAKE_CALLS: "key=set|unset" +# - appends one line to $FAKE_CALLS: "key=set|unset +# base=token=set|unsettickcap=" +# (the token value is never written, only whether it was present) # - takes the first line of $FAKE_DIR/.queue, " " # (an empty or missing queue behaves like "2 null - gate exit pending") # - with FAKE_KEY_SEEN set, writes the ANTHROPIC_API_KEY it received to that file @@ -28,7 +30,9 @@ done [ -n "$repo" ] || { echo "fake agent-kit: --cwd missing" >&2; exit 1; } name=$(basename "$repo") if [ -n "${ANTHROPIC_API_KEY:-}" ]; then keyset=set; else keyset=unset; fi -printf '%s\t%s\tkey=%s\n' "$name" "$args" "$keyset" >>"$FAKE_CALLS" +if [ -n "${ANTHROPIC_AUTH_TOKEN:-}" ]; then tokset=set; else tokset=unset; fi +printf '%s\t%s\tkey=%s\tbase=%s\ttoken=%s\ttickcap=%s\n' "$name" "$args" "$keyset" \ + "${ANTHROPIC_BASE_URL:-unset}" "$tokset" "${AGENT_KIT_CLAUDE_MAX_BUDGET_USD:-unset}" >>"$FAKE_CALLS" [ -z "${FAKE_KEY_SEEN:-}" ] || printf '%s' "${ANTHROPIC_API_KEY:-}" >"$FAKE_KEY_SEEN" queue=$FAKE_DIR/$name.queue diff --git a/tests/lib.sh b/tests/lib.sh index b4da4bd..2a4402b 100644 --- a/tests/lib.sh +++ b/tests/lib.sh @@ -31,7 +31,9 @@ setup() { export PATH="$ROOT/tests/fake:$PATH" export GIT_AUTHOR_NAME=test GIT_AUTHOR_EMAIL=test@example.com GIT_COMMITTER_NAME=test GIT_COMMITTER_EMAIL=test@example.com export GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=$TMP/gitconfig - unset ANTHROPIC_API_KEY NIGHT_SHIFT_CONFIG FAKE_KEY_SEEN FAKE_ADVANCE + unset ANTHROPIC_API_KEY NIGHT_SHIFT_CONFIG FAKE_KEY_SEEN FAKE_ADVANCE ANTHROPIC_BASE_URL ANTHROPIC_AUTH_TOKEN \ + AGENT_KIT_CLAUDE_MAX_BUDGET_USD ANTHROPIC_DEFAULT_OPUS_MODEL ANTHROPIC_DEFAULT_SONNET_MODEL \ + ANTHROPIC_DEFAULT_HAIKU_MODEL CLAUDE_CODE_SUBAGENT_MODEL mkdir -p "$XDG_CONFIG_HOME/night-shift" "$FAKE_DIR" "$TMP/repos" : >"$FAKE_CALLS" echo "$T0" >"$NIGHT_SHIFT_TEST_CLOCK" diff --git a/tests/test_local.sh b/tests/test_local.sh new file mode 100755 index 0000000..7b9a954 --- /dev/null +++ b/tests/test_local.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Gateway variables reach the fire, and NS_BILLING=local: fail-closed guards, no budgets, no made-up spend. +. "$(dirname "$0")/lib.sh" + +run_report() { OUT=$("$ROOT/bin/night-shift-report" "$@" 2>&1); RC=$?; } +calls() { cat "$FAKE_CALLS"; } + +echo "# gateway variables written in config.env (not exported) reach the fire" +setup +A=$(make_repo acme-app) +repos "$A" +write_config "ANTHROPIC_BASE_URL=http://127.0.0.1:11434" "ANTHROPIC_AUTH_TOKEN=gw-token-value-789" +queue acme-app "5 0.1 k1 agent requested stop: q" +export ANTHROPIC_API_KEY=test-not-a-real-key +run_loop +unset ANTHROPIC_API_KEY +contains "subscription: the base URL reached the fire" "$(calls)" "base=http://127.0.0.1:11434" +contains "subscription: the token reached the fire" "$(calls)" "token=set" +contains "subscription: the stray key is still stripped" "$(calls)" "key=unset" +lacks "the token is not in the loop output" "$OUT" "gw-token-value-789" +lacks "the token is not in the run log" "$(cat "$XDG_STATE_HOME/night-shift/runs.tsv")" "gw-token-value-789" + +echo "# local billing refuses to start without an endpoint" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_BILLING=local +run_loop +eq "no endpoint: exit 1" 1 "$RC" +contains "no endpoint: message" "$OUT" "NS_BILLING=local needs ANTHROPIC_BASE_URL" +eq "no endpoint: nothing fired" 0 "$(wc -l <"$FAKE_CALLS" | tr -d ' ')" + +echo "# local billing refuses a remote endpoint unless vouched for" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=https://gateway.example.com" +run_loop +eq "remote endpoint: exit 1" 1 "$RC" +contains "remote endpoint: message" "$OUT" "NS_LOCAL_REMOTE_OK=1" +eq "remote endpoint: nothing fired" 0 "$(wc -l <"$FAKE_CALLS" | tr -d ' ')" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=https://gateway.example.com" NS_LOCAL_REMOTE_OK=1 +queue acme-app "5 0.1 k1 agent requested stop: q" +run_loop +eq "vouched remote endpoint: fired" 1 "$(wc -l <"$FAKE_CALLS" | tr -d ' ')" +lacks "a remote address stays out of the run log" "$(cat "$XDG_STATE_HOME/night-shift/runs.tsv")" "gateway.example.com" +for u in http://localhost:8080/v1 "http://[::1]:11434" https://127.0.0.1; do + setup + A=$(make_repo acme-app) + repos "$A" + write_config NS_BILLING=local "ANTHROPIC_BASE_URL=$u" + run_loop --check + eq "loopback $u accepted" 0 "$RC" +done +for u in http://127.0.0.1.example.com http://localhost.example.com:80 ftp://127.0.0.1; do + setup + A=$(make_repo acme-app) + repos "$A" + write_config NS_BILLING=local "ANTHROPIC_BASE_URL=$u" + run_loop --check + eq "look-alike $u refused" 1 "$RC" +done + +echo "# a local night: no key, no budget flag, no tick cap, no cost in the run log" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=http://127.0.0.1:11434" "ANTHROPIC_AUTH_TOKEN=local-token" \ + NS_NIGHT_BUDGET_USD=1 NS_MONTH_BUDGET_USD=1 NS_TICK_BUDGET_USD=0.5 NS_MAX_FIRES_REPO=3 +# made-up prices well above the ceilings: a local night must not stop on them +queue acme-app "0 0.90 k1 completed" "0 0.90 k2 completed" "0 0.90 k3 completed" +export ANTHROPIC_API_KEY=test-not-a-real-key AGENT_KIT_CLAUDE_MAX_BUDGET_USD=2 +run_loop +unset ANTHROPIC_API_KEY AGENT_KIT_CLAUDE_MAX_BUDGET_USD +eq "all three fires ran" "acme-app acme-app acme-app" "$(order)" +lacks "no --budget-remaining" "$(calls)" "budget-remaining" +lacks "no key in any fire" "$(calls)" "key=set" +eq "no tick cap in any fire, inherited or configured" 3 "$(grep -c 'tickcap=unset$' "$FAKE_CALLS")" +contains "the endpoint reached the fire" "$(calls)" "base=http://127.0.0.1:11434" +contains "start event names local billing" "$OUT" "billing local (127.0.0.1:11434), budgets not applied" +eq "no cost in the run log" "- - -" "$(awk -F'\t' '$5 == "ok" { print $6 }' "$XDG_STATE_HOME/night-shift/runs.tsv" | paste -sd' ' -)" +eq "three local fires recorded" 3 "$(wc -l <"$XDG_STATE_HOME/night-shift/local-fires.tsv" | tr -d ' ')" +eq "the ledger still holds the kit's figures" 3 "$(wc -l <"$A/.cursor/context/cost-ledger.ndjson" | tr -d ' ')" +run_loop --check +contains "--check says the budget is not applied" "$OUT" "budget: not applied (billing: local, endpoint 127.0.0.1:11434)" + +echo "# the made-up spend of local fires does not count when billing changes back" +write_config NS_BILLING=api-key NS_MONTH_BUDGET_USD=1 +run_loop --check +contains "month budget untouched by local fires" "$OUT" "budget left for the next fire: 1.00" +# a fire that is not local still counts +queue acme-app "0 0.30 k4 completed" "5 0 k5 agent requested stop: q" +printf 'test-key-value-123\n' >"$TMP/key" +chmod 600 "$TMP/key" +write_config NS_BILLING=api-key NS_MONTH_BUDGET_USD=1 "NS_API_KEY_FILE=$TMP/key" +run_loop +run_loop --check +contains "only the paid fire is subtracted" "$OUT" "budget left for the next fire: 0.70" + +echo "# the morning report after a local night" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=http://127.0.0.1:11434" NS_NIGHT_BUDGET_USD=20 +queue acme-app "0 0.90 k1 completed" "5 0.10 k2 agent requested stop: q" +"$ROOT/bin/night-shift" >/dev/null 2>&1 +run_report --no-hook +eq "report exit 0" 0 "$RC" +contains "local spend is 0 tonight" "$OUT" "| Tonight | 0.00 | not applied |" +contains "per repo too" "$OUT" "| acme-app tonight | 0.00 | |" +contains "the report says why" "$OUT" "Billing is local" +lacks "no made-up cost on the done item" "$OUT" "\$0.90" + +finish From 7b22401df126530ce96576d6284d74f0f2f1c79d Mon Sep 17 00:00:00 2001 From: agent-kit-startup <273612197+agent-kit-startup@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:29:58 -0300 Subject: [PATCH 2/4] docs: local model limits from the first real fire Refs #1 --- README.md | 27 ++++++++++++++++----------- bin/night-shift | 2 ++ docs/config.md | 1 + 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 9ab6480..89806ec 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ Messages API (Ollama does, at `http://127.0.0.1:11434`). A night then costs no A ```sh NS_BILLING=local ANTHROPIC_BASE_URL=http://127.0.0.1:11434 -ANTHROPIC_AUTH_TOKEN=local # whatever the server expects; Ollama ignores it +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 @@ -122,19 +122,24 @@ What local mode changes: 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`). The `ANTHROPIC_DEFAULT_*_MODEL` and `CLAUDE_CODE_SUBAGENT_MODEL` - variables cover the calls `claude` makes on its own (background tasks, subagents); without them those - calls ask the server for a Claude model it does not have. + 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. Known limits, from the first tests: -- **Small models cannot do a tick.** `llama3.1:8b` on Ollama answered a one-word prompt with 800 tokens - of tool-template text. A tick needs a model that follows tool calls reliably over a long context; the - next test is a 27B to 30B coding model. -- **Context length.** The `claude` system prompt and tool list are large. Ollama's default context is - much smaller (its runner started at 4096 tokens here), and it truncates silently; raise it - (`OLLAMA_CONTEXT_LENGTH`) to what the model supports. `claude` assumes a 1M-token window for a model it - does not know, so it will not compact before the server cuts the prompt. +- **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. A tick needs a model that follows tool calls reliably + over a long context; the next test is a 27B to 30B coding model. +- **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 slower than a hosted one. Raise `NS_FIRE_WINDOW_MIN` and `NS_STALL_MIN` so diff --git a/bin/night-shift b/bin/night-shift index ac70e48..6f6d1eb 100755 --- a/bin/night-shift +++ b/bin/night-shift @@ -21,6 +21,8 @@ # (/.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=, 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 diff --git a/docs/config.md b/docs/config.md index 849fc6c..638f312 100644 --- a/docs/config.md +++ b/docs/config.md @@ -129,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/--.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/.md` | `night-shift-report` | Each report. | ## Exit codes From b05d28f9711a36394dbbbe40f0d37bba1320235b Mon Sep 17 00:00:00 2001 From: agent-kit-startup <273612197+agent-kit-startup@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:13:29 -0300 Subject: [PATCH 3/4] docs: first local tick completed on a 27B model Refs #1 --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 89806ec..b1ad467 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,13 @@ Every key, its default, the files the scripts write and the exit codes are in ## Local model -**Status: experimental, not proven.** No full night has run on a local model yet. Use it supervised. +**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: @@ -130,8 +136,7 @@ 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. A tick needs a model that follows tool calls reliably - over a long context; the next test is a 27B to 30B coding model. + `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. @@ -142,7 +147,7 @@ Known limits, from the first tests: 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 slower than a hosted one. Raise `NS_FIRE_WINDOW_MIN` and `NS_STALL_MIN` so +- **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 From 1299f8374e005a9d60ed8dc53b7d93d2696205b4 Mon Sep 17 00:00:00 2001 From: agent-kit-startup <273612197+agent-kit-startup@users.noreply.github.com> Date: Mon, 30 Nov 2026 07:18:53 -0300 Subject: [PATCH 4/4] docs: point to the kit's upcoming local backend Refs #1 --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index b1ad467..4dde618 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,11 @@ What local mode changes: 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