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
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,16 @@ 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`.
that bills nothing). The host must be exactly one of those three, with an optional numeric port: a URL
with a user name or `@` in its host part counts as remote. 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.
Outside local mode the sums fail closed instead: a fire on a model `claude` cannot price (kit 6.26.0
and later record `cost_usd: null` with `cost_usd_reported` and `cost_basis: "unknown"`) counts at the
figure `claude` reported.
- **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
Expand Down Expand Up @@ -240,8 +244,8 @@ or misconfigured (exit 1); exit 5, a repo waiting for you, is declared a success
(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. 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.
local mode skips those lines, while under `subscription` or `api-key` they count at that figure, which
can be above or below the real bill.
- **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
6 changes: 4 additions & 2 deletions bin/night-shift
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ case $NS_BILLING in
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"
ns_err "NS_BILLING=local: ANTHROPIC_BASE_URL is not on 127.0.0.1, localhost or [::1] with an optional numeric port (a URL with userinfo counts as remote); 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.
Expand Down Expand Up @@ -248,8 +248,10 @@ fire() {
res=$(grep '^AGENT_KIT_RESULT ' "$flog" | tail -n 1)
if [ -n "$res" ]; then
json=${res#AGENT_KIT_RESULT }
# The cost follows the budget's rule (NS_JQ_COST in lib/common.sh): cost_usd_reported when it is a
# number (kit 6.26.0 and later, also for a model claude could not price), else cost_usd.
if fields=$(printf '%s' "$json" | jq -r '
[.outcome, .reason, .plan, .todo, .cost_usd]
[.outcome, .reason, .plan, .todo, ((.cost_usd_reported | numbers) // .cost_usd)]
| map(if . == null then "" else tostring | gsub("[\t\r\n\u001f]"; " ") end)
| join("\u001f")' 2>/dev/null); then
IFS=$'\x1f' read -r OUTCOME REASON PLAN TODO COST <<<"$fields"
Expand Down
4 changes: 4 additions & 0 deletions bin/night-shift-report
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ done <<<"$LAST"

spend=$(ns_spend "$SINCE" "$UNTIL" "$MONTH") || { ns_err "cost ledgers could not be read"; exit 1; }
night_usd=${spend%% *} month_usd=${spend##* }
unpriced=$(ns_unpriced "$SINCE" "$UNTIL") || { ns_err "cost ledgers could not be read"; exit 1; }

render() {
echo "# Night shift report: $NIGHT"
Expand Down Expand Up @@ -244,6 +245,9 @@ render() {
[ "$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 [ "$unpriced" -gt 0 ]; then
echo "$unpriced fire(s) tonight used a model claude could not price (cost basis unknown): they count at the figure claude reported, which may differ from your bill."
fi
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
Expand Down
11 changes: 7 additions & 4 deletions 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. `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_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]`: the host must be exactly one of those, with an optional numeric port, and a URL with userinfo (`@`) in its authority counts as remote. |
| `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 @@ -59,8 +59,11 @@ less, the night ends without firing. When countdown refuses a fire for the budge
set, no `--budget-remaining` is passed.

The ledgers are `<repo>/.cursor/context/cost-ledger.ndjson` in each listed repo, written by the kit on
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.
every fire. Each line counts `cost_usd_reported` when it is set (kit 6.26.0 and later), else `cost_usd`,
so a fire on a model `claude` cannot price (`cost_usd: null`, `cost_basis: "unknown"`) counts at the
figure `claude` reported, while fires listed in `local-fires.tsv` still count 0. 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

Expand Down Expand Up @@ -127,7 +130,7 @@ worktree anyway, give it its own config first:
| Path (under `NS_STATE_DIR`) | Written by | Content |
|---|---|---|
| `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. |
| `runs.tsv` | `night-shift` | One tab-separated line per fire and per start/end event: `time`, `night`, `repo`, `exit`, `outcome`, `cost_usd` (the figure the budget counts: `cost_usd_reported` when the kit printed one, else `cost_usd`; empty in local mode), `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. |
Expand Down
76 changes: 60 additions & 16 deletions lib/common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -103,25 +103,42 @@ ns_export_gateway() {
}

# 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).
# address is kept out of the run log, like the kit keeps it out of its own logs). A loopback URL has no
# userinfo (ns_is_loopback_url refuses one), so the label never carries a user name or password.
ns_endpoint_label() {
if ns_is_loopback_url "${ANTHROPIC_BASE_URL:-}"; then
local hp=${ANTHROPIC_BASE_URL#*://}
echo "${hp%%/*}"
local auth=${ANTHROPIC_BASE_URL#*://}
echo "${auth%%/*}"
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 URL: true when URL is http(s) on 127.0.0.1, localhost or [::1], with an optional
# numeric port, then the end of the URL or a path. Scheme and host match in any case. The authority (from
# "://" to the first "/") must be exactly that host and port: userinfo ("@", also percent-encoded), a
# trailing dot, a longer host name, a non-numeric or empty port, or a "?" or "#" right after the host are
# all refused. Parsed without command substitution, so a trailing newline is not silently dropped.
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 ;;
local auth host port
case $1 in
[Hh][Tt][Tt][Pp]://* | [Hh][Tt][Tt][Pp][Ss]://*) ;;
*) return 1 ;;
esac
auth=${1#*://}
auth=${auth%%/*}
case $auth in
'[::1]'*) host='[::1]' ;;
*) host=${auth%%:*} ;;
esac
port=${auth#"$host"}
case $host in
127.0.0.1 | [Ll][Oo][Cc][Aa][Ll][Hh][Oo][Ss][Tt] | '[::1]') ;;
*) return 1 ;;
esac
return 1
[ -n "$port" ] || return 0
case $port in :*) ;; *) return 1 ;; esac
ns_is_uint "${port#:}"
}

ns_is_uint() { case $1 in '' | *[!0-9]*) return 1 ;; esac; }
Expand Down Expand Up @@ -197,7 +214,7 @@ ns_model_for() {

# ns_spend SINCE UNTIL MONTH: prints "<night total> <month total>" 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.
# MONTH is YYYY-MM (UTC). Lines that are not JSON objects are skipped. Each line counts at NS_JQ_COST.
# 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() {
Expand All @@ -210,22 +227,40 @@ ns_spend() {
echo "0 0"
return 0
fi
jq -rRn --arg since "$1" --arg until "$2" --arg month "$3" --rawfile lf "$(ns_local_fires_file)" "$NS_JQ_LOCAL"'
jq -rRn --arg since "$1" --arg until "$2" --arg month "$3" --rawfile lf "$(ns_local_fires_file)" "$NS_JQ_LOCAL$NS_JQ_COST"'
[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
| line_cost) | add // 0) as $night
| ($l | map(select((.at // "") | startswith($month)) | line_cost) | add // 0) as $mon
| "\($night) \($mon)"' "${files[@]}"
}

# 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" --rawfile lf "$(ns_local_fires_file)" "$NS_JQ_LOCAL"'
jq -rRn --arg since "$2" --arg until "$3" --rawfile lf "$(ns_local_fires_file)" "$NS_JQ_LOCAL$NS_JQ_COST"'
[inputs | fromjson? | select(type == "object") | select(local_fire | not)
| select((.at // "") >= $since and ($until == "" or (.at // "") < $until))
| (.cost_usd // 0) | numbers] | add // 0' "$f"
| line_cost] | add // 0' "$f"
}

# ns_unpriced SINCE UNTIL: how many ledger lines in the window, across the listed repos, have cost_basis
# "unknown" (claude could not price the model). Local-model fires are not counted.
ns_unpriced() {
local files=() p f
for p in "${NS_R_PATH[@]}"; do
f=$p/.cursor/context/cost-ledger.ndjson
[ -f "$f" ] && files+=("$f")
done
if [ ${#files[@]} -eq 0 ]; then
echo 0
return 0
fi
jq -rRn --arg since "$1" --arg until "$2" --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))
| select(.cost_basis == "unknown")] | length' "${files[@]}"
}

# NS_LOCAL_FIRES ($NS_STATE_DIR/local-fires.tsv) holds one line per fire made with NS_BILLING=local:
Expand All @@ -238,6 +273,15 @@ NS_JQ_LOCAL='
| def local_fire: (.repo // "") as $r | ((.at // "") | .[0:19]) as $a
| any($fires[]; .[0] == $r and .[1] <= $a and $a < .[2]);
'
# NS_JQ_COST defines line_cost, what one ledger line (or result line) counts against a budget:
# cost_usd_reported when it is a number, else cost_usd, else 0. Since kit 6.26.0 a fire on a model claude
# cannot price records cost_usd null, cost_usd_reported (the figure claude printed) and cost_basis
# "unknown"; counting cost_usd_reported fails closed for a paid model claude does not know. Older lines
# only have cost_usd. Fires on a local model are skipped before this (local_fire), so they still count 0.
# shellcheck disable=SC2016
NS_JQ_COST='
def line_cost: (.cost_usd_reported | numbers) // (.cost_usd | numbers) // 0;
'
# 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
Expand Down
20 changes: 14 additions & 6 deletions tests/fake/agent-kit
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
# - appends one line to $FAKE_CALLS: "<repo name><TAB><args after countdown><TAB>key=set|unset<TAB>
# base=<ANTHROPIC_BASE_URL or unset><TAB>token=set|unset<TAB>tickcap=<AGENT_KIT_CLAUDE_MAX_BUDGET_USD or unset>"
# (the token value is never written, only whether it was present)
# - takes the first line of $FAKE_DIR/<repo name>.queue, "<exit> <cost|null> <todo|-> <reason...>"
# (an empty or missing queue behaves like "2 null - gate exit pending")
# - takes the first line of $FAKE_DIR/<repo name>.queue, "<exit> <cost> <todo|-> <reason...>"
# (an empty or missing queue behaves like "2 null - gate exit pending"). <cost> is a number or null
# (the ledger and result line in the format before kit 6.26.0, cost_usd only), "priced:X" (6.26.0
# format, priced: cost_usd X, cost_usd_reported X, cost_basis null) or "unknown:X" (6.26.0 format, a
# model claude could not price: cost_usd null, cost_usd_reported X, cost_basis "unknown")
# - with FAKE_KEY_SEEN set, writes the ANTHROPIC_API_KEY it received to that file
# - a reason of "make-branch:<name> ..." creates that branch in REPO with one commit of its own, like a
# tick that opened one; "make-empty-branch:<name> ..." creates it at HEAD with no commit
Expand Down Expand Up @@ -66,12 +69,17 @@ now=$(cat "$NIGHT_SHIFT_TEST_CLOCK")
at=$(date -u -d "@$now" +%Y-%m-%dT%H:%M:%S.000Z 2>/dev/null || date -u -r "$now" +%Y-%m-%dT%H:%M:%S.000Z)
echo $((now + ${FAKE_ADVANCE:-1800})) >"$NIGHT_SHIFT_TEST_CLOCK"
if [ "$todo" = - ]; then todo_json=null; else todo_json="\"$todo\""; fi
extra=''
case $cost in
priced:*) cost=${cost#priced:} extra=",\"cost_usd_reported\":$cost,\"cost_basis\":null" ;;
unknown:*) extra=",\"cost_usd_reported\":${cost#unknown:},\"cost_basis\":\"unknown\"" cost=null ;;
esac
mkdir -p "$repo/.cursor/context"
printf '{"at":"%s","repo":"%s","plan":"poc.plan.md","todo":%s,"job":"tick","backend":"claude","model":null,"cost_usd":%s,"input_tokens":null,"output_tokens":null,"exit":%s,"outcome":"%s"}\n' \
"$at" "$name" "$todo_json" "$cost" "$rc" "$outcome" >>"$repo/.cursor/context/cost-ledger.ndjson"
printf '{"at":"%s","repo":"%s","plan":"poc.plan.md","todo":%s,"job":"tick","backend":"claude","model":null,"cost_usd":%s,"input_tokens":null,"output_tokens":null,"exit":%s,"outcome":"%s"%s}\n' \
"$at" "$name" "$todo_json" "$cost" "$rc" "$outcome" "$extra" >>"$repo/.cursor/context/cost-ledger.ndjson"

echo "countdown: fetching origin"
echo "result success"
printf 'AGENT_KIT_RESULT {"outcome":"%s","reason":"%s","repo":"%s","plan":"poc.plan.md","todo":%s,"exit":%s,"cost_usd":%s}\n' \
"$outcome" "$reason" "$name" "$todo_json" "$rc" "$cost"
printf 'AGENT_KIT_RESULT {"outcome":"%s","reason":"%s","repo":"%s","plan":"poc.plan.md","todo":%s,"exit":%s,"cost_usd":%s%s}\n' \
"$outcome" "$reason" "$name" "$todo_json" "$rc" "$cost" "$extra"
exit "$rc"
Loading
Loading