diff --git a/README.md b/README.md index 4dde618..02874e8 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/bin/night-shift b/bin/night-shift index 6f6d1eb..e9179fb 100755 --- a/bin/night-shift +++ b/bin/night-shift @@ -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. @@ -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" diff --git a/bin/night-shift-report b/bin/night-shift-report index 9dc2081..169865f 100755 --- a/bin/night-shift-report +++ b/bin/night-shift-report @@ -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" @@ -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 diff --git a/docs/config.md b/docs/config.md index 638f312..2cd6a86 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. `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. | @@ -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 `/.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 @@ -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/--.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. | diff --git a/lib/common.sh b/lib/common.sh index 0c6656b..27d7c95 100644 --- a/lib/common.sh +++ b/lib/common.sh @@ -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; } @@ -197,7 +214,7 @@ 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. +# 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() { @@ -210,11 +227,11 @@ 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[@]}" } @@ -222,10 +239,28 @@ ns_spend() { 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: @@ -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 diff --git a/tests/fake/agent-kit b/tests/fake/agent-kit index 78c2f41..1fd079e 100755 --- a/tests/fake/agent-kit +++ b/tests/fake/agent-kit @@ -5,8 +5,11 @@ # - 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") +# - takes the first line of $FAKE_DIR/.queue, " " +# (an empty or missing queue behaves like "2 null - gate exit pending"). 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: ..." creates that branch in REPO with one commit of its own, like a # tick that opened one; "make-empty-branch: ..." creates it at HEAD with no commit @@ -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" diff --git a/tests/test_cost.sh b/tests/test_cost.sh new file mode 100755 index 0000000..3a38101 --- /dev/null +++ b/tests/test_cost.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Spend sums fail closed: a fire on a model claude could not price (kit 6.26.0: cost_usd null, +# cost_usd_reported set, cost_basis "unknown") counts at the reported figure in the paid modes, ledger +# lines in the older format still count, and fires on a local model still count 0. +. "$(dirname "$0")/lib.sh" + +run_report() { OUT=$("$ROOT/bin/night-shift-report" "$@" 2>&1); RC=$?; } +runlog() { cat "$XDG_STATE_HOME/night-shift/runs.tsv"; } +key_file() { + printf 'test-key-value-123\n' >"$TMP/key" + chmod 600 "$TMP/key" +} + +echo "# api-key: an unpriced fire counts at the reported figure and stops the night" +setup +A=$(make_repo acme-app) +repos "$A" +key_file +write_config NS_BILLING=api-key NS_NIGHT_BUDGET_USD=1 "NS_API_KEY_FILE=$TMP/key" +queue acme-app "0 unknown:1.5 k1 completed" "0 0.10 k2 completed" +run_loop +eq "only the first fire ran" "acme-app" "$(order)" +contains "the first fire had the whole night budget" "$(cat "$FAKE_CALLS")" "--budget-remaining=1.00" +contains "the night ends on the budget" "$(runlog)" "budget exhausted" +eq "the run log records the reported figure" "1.5" "$(awk -F'\t' '$5 == "ok" { print $6 }' "$XDG_STATE_HOME/night-shift/runs.tsv")" +run_loop --check +contains "--check counts it" "$OUT" "budget left for the next fire: -0.50" +run_report --no-hook +contains "the report counts it tonight" "$OUT" "| Tonight | 1.50 | 1 |" +contains "and per repo" "$OUT" "| acme-app tonight | 1.50 | |" +contains "the done item shows the reported figure" "$OUT" "to-do \`k1\`, \$1.50" +contains "the report notes the unknown basis" "$OUT" "1 fire(s) tonight used a model claude could not price" + +echo "# subscription: the month budget counts an unpriced line too" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_MONTH_BUDGET_USD=5 +mkdir -p "$A/.cursor/context" +{ + echo '{"at":"2026-11-10T02:00:00.000Z","repo":"acme-app","cost_usd":null,"exit":0,"outcome":"ok","cost_usd_reported":1.5,"cost_basis":"unknown"}' + echo '{"at":"2026-11-11T02:00:00.000Z","repo":"acme-app","cost_usd":1.25,"exit":0,"outcome":"ok"}' + echo '{"at":"2026-11-12T02:00:00.000Z","repo":"acme-app","cost_usd":1.85,"exit":0,"outcome":"ok","cost_usd_reported":1.85,"cost_basis":null}' + echo '{"at":"2026-11-13T02:00:00.000Z","repo":"acme-app","cost_usd":null,"exit":2,"outcome":"needs-operator","cost_usd_reported":null,"cost_basis":null}' + echo '{"at":"2026-11-14T02:00:00.000Z","repo":"acme-app","cost_usd":null,"exit":2,"outcome":"needs-operator"}' +} >"$A/.cursor/context/cost-ledger.ndjson" +run_loop --check +# 5 - (1.5 unpriced + 1.25 old format + 1.85 priced once + 0 + 0) = 0.40 +contains "unpriced, old-format and priced lines each count once" "$OUT" "budget left for the next fire: 0.40" + +echo "# old-format result lines still log their cost" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_NIGHT_BUDGET_USD=10 +queue acme-app "0 1.25 k1 completed" "0 priced:0.75 k2 completed" "5 null k3 agent requested stop: q" +run_loop +eq "old, priced and null costs in the run log" "1.25 0.75 -" \ + "$(awk -F'\t' '$3 != "-" { print $6 }' "$XDG_STATE_HOME/night-shift/runs.tsv" | paste -sd' ' -)" +eq "the third fire saw both costs" "--budget-remaining=8.00" "$(sed -n 3p "$FAKE_CALLS" | tr ' \t' '\n\n' | grep budget-remaining)" +run_report --no-hook +lacks "no unknown-basis note when every fire was priced" "$OUT" "could not price" + +echo "# local: an unpriced local fire still counts 0, also after billing changes back" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=http://127.0.0.1:11434" NS_MAX_FIRES_REPO=2 +queue acme-app "0 unknown:0.90 k1 completed" "0 unknown:0.90 k2 completed" +run_loop +eq "both local fires ran" "acme-app acme-app" "$(order)" +eq "no cost in the run log" "- -" "$(awk -F'\t' '$5 == "ok" { print $6 }' "$XDG_STATE_HOME/night-shift/runs.tsv" | paste -sd' ' -)" +run_report --no-hook +contains "local spend is 0 tonight" "$OUT" "| Tonight | 0.00 | not applied |" +lacks "no unknown-basis note for local fires" "$OUT" "could not price" +key_file +write_config NS_BILLING=api-key NS_MONTH_BUDGET_USD=1 "NS_API_KEY_FILE=$TMP/key" +run_loop --check +contains "month budget untouched by the local fires" "$OUT" "budget left for the next fire: 1.00" + +finish diff --git a/tests/test_local.sh b/tests/test_local.sh index 7b9a954..968d816 100755 --- a/tests/test_local.sh +++ b/tests/test_local.sh @@ -61,6 +61,42 @@ for u in http://127.0.0.1.example.com http://localhost.example.com:80 ftp://127. eq "look-alike $u refused" 1 "$RC" done +echo "# the loopback check: exact host, optional numeric port, no userinfo" +# Called directly: config.env is sourced as shell, which would mangle some of these forms. +loopback() ( . "$ROOT/lib/common.sh" && ns_is_loopback_url "$1" ) +for u in http://127.0.0.1 http://127.0.0.1:11434/v1 https://localhost/ "http://[::1]" "http://[::1]:11434/v1" \ + HTTP://127.0.0.1:8080 HTTPS://LOCALHOST http://LocalHost:11434 "http://127.0.0.1/%40x"; do + if loopback "$u"; then ok "loopback: $u accepted"; else fail "loopback: $u accepted"; fi +done +for u in "http://127.0.0.1:1@other-host/" "http://user:pw@127.0.0.1:11434" "http://[::1]@x" "http://localhost@x/" \ + "http://127.0.0.1%40other-host/" "http://127.0.0.1%2540x" http://localhost:abc "http://localhost:" \ + "http://localhost:80:90" "http://[::1]x" http://127.0.0.1.evil http://localhost. http://127.0.0.1. \ + "http://localhost?@x" "http://localhost#@x" 'http://127.0.0.1\@x' $'http://localhost\n' $'http://local\thost' \ + "http://127.0.0.1 " http://127.0.0.1x ftp://127.0.0.1 http:127.0.0.1 ""; do + if loopback "$u"; then fail "look-alike: $(printf '%q' "$u") refused"; else ok "look-alike: $(printf '%q' "$u") refused"; fi +done + +echo "# userinfo in a local endpoint: refused, and never printed even when vouched for" +setup +A=$(make_repo acme-app) +repos "$A" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=http://127.0.0.1:1@other-host/" +run_loop --check +eq "userinfo endpoint: --check exit 1" 1 "$RC" +contains "userinfo endpoint: message" "$OUT" "NS_LOCAL_REMOTE_OK=1" +run_loop +eq "userinfo endpoint: nothing fired" 0 "$(wc -l <"$FAKE_CALLS" | tr -d ' ')" +write_config NS_BILLING=local "ANTHROPIC_BASE_URL=http://user:secret-pw@127.0.0.1:11434" NS_LOCAL_REMOTE_OK=1 +queue acme-app "5 0.1 k1 agent requested stop: q" +run_loop +eq "vouched userinfo endpoint: fired" 1 "$(wc -l <"$FAKE_CALLS" | tr -d ' ')" +contains "the start event calls it remote" "$OUT" "billing local (remote endpoint)" +lacks "the password stays out of the loop output" "$OUT" "secret-pw" +lacks "the password stays out of the run log" "$(cat "$XDG_STATE_HOME/night-shift/runs.tsv")" "secret-pw" +run_loop --check +contains "--check calls it remote" "$OUT" "endpoint remote endpoint" +lacks "--check prints no password" "$OUT" "secret-pw" + echo "# a local night: no key, no budget flag, no tick cap, no cost in the run log" setup A=$(make_repo acme-app)