pi-todo-ledger 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRACT.md +38 -2
- package/README.md +1 -0
- package/package.json +1 -1
- package/src/index.ts +3 -1
- package/src/ledger/finish-call.ts +22 -1
- package/src/ledger/herdr-owner.ts +2 -2
- package/src/ledger/herdr-runs.ts +20 -0
- package/src/ledger/herdr-spend.ts +133 -0
- package/src/ledger/spend.ts +103 -0
- package/src/state/replay.ts +14 -0
- package/src/state/session-lock.ts +5 -0
- package/src/tool/response-envelope.ts +3 -0
package/CONTRACT.md
CHANGED
|
@@ -183,7 +183,7 @@ A match issues a normal guarded `update`: `owner` becomes the full `details.name
|
|
|
183
183
|
`pane` is the acknowledged `details.worktree.paneId` and is absent for ordinary launches.
|
|
184
184
|
The top-level fields always describe the latest assignment. An old pane id does not carry forward. For example, after a reviewer joins a worker on the same task, `owner` and `metadata.herdr.id` identify the reviewer.
|
|
185
185
|
|
|
186
|
-
New writers also store `metadata.herdr.runs`: up to six `{ name, id, pane?, session?, agent? }` records, unique by run id, newest last. `session` is the launch acknowledgement's `sessionFile`. Once the list exceeds six, `metadata.herdr.older` counts the discarded records. An earlier v1 record without `runs` counts as one binding. A reader that finds a repeated run id (in imported or hand-edited metadata) keeps that id's last record in its last position, then applies the cap of six, so the next write is unique again. The snapshot version remains 1.
|
|
186
|
+
New writers also store `metadata.herdr.runs`: up to six `{ name, id, pane?, session?, agent?, also? }` records, unique by run id, newest last. `session` is the launch acknowledgement's `sessionFile`. `also` lists the session files the run ended on besides its own ([Run spend](#run-spend-metadataherdrspend)); a resume of any of them binds as one of `session` does. Once the list exceeds six, `metadata.herdr.older` counts the discarded records. An earlier v1 record without `runs` counts as one binding. A reader that finds a repeated run id (in imported or hand-edited metadata) keeps that id's last record in its last position, then applies the cap of six, so the next write is unique again. The snapshot version remains 1.
|
|
187
187
|
|
|
188
188
|
A successful `subagent_resume` appends its new run id when its acknowledged `sessionPath` matches a retained session path on exactly one non-deleted task in the calling session. An unknown or ambiguous path binds nothing.
|
|
189
189
|
Other metadata stays intact; a refusal leaves the launch successful but adds the reason to its response.
|
|
@@ -195,6 +195,42 @@ For names longer than 24 UTF-16 units, Straw Boss displays just the first 23 uni
|
|
|
195
195
|
Resolve the live pane at read time rather than targeting that cosmetic label or a saved pane id.
|
|
196
196
|
This namespace needs no new status, schema field, or contract version.
|
|
197
197
|
|
|
198
|
+
### Run spend (`metadata.herdr.spend`)
|
|
199
|
+
|
|
200
|
+
Since 0.10.0, when a bound run ends, the ledger records what it spent on its task.
|
|
201
|
+
A run's end arrives two ways:
|
|
202
|
+
|
|
203
|
+
- the host's event `subagent:run-end` on `pi.events`, `{ v: 1, id, kind, name?, item?, sessionFile?, elapsed?, attempts? }`: `id` is the run id the launch acknowledged (`details.id`), `kind` is `"result"` or `"ping"`, `elapsed` the run's wall time in seconds, and `attempts` every spawned attempt of the run in order, `{ model?, sessionFile?, elapsed }`, a fallback's failed ones included. Only `v`, `id`, and `kind` are required: a run that failed before it wrote a session file ends without `sessionFile` and counts its time, and the ledger never reads `name` or an attempt's `model`. The host sends it as it delivers the end, so an end still counts when its message never reaches the model (a steer cleared before the turn);
|
|
204
|
+
- the custom message in the calling session: `subagent_result` when the run finished or `subagent_ping` when it stopped to ask. Its `details` carry the same `id`, `item`, `sessionFile`, `elapsed`, and `attempts` when the host supplies them (Maestro since `sb-host-a5a9c43`).
|
|
205
|
+
|
|
206
|
+
The ledger finds the task as the launch bound it: the non-deleted task whose `metadata.herdr.runs` hold the run id, else one of the end's session files, else, by `item`, the task with that uid.
|
|
207
|
+
A bare `<session8>#<id>` is never looked up by its number at the end: after `clear` or a branch switch the number names another task, and the launch's binding is what proves the identity.
|
|
208
|
+
No match, several matches, or a deleted task leave the list unchanged.
|
|
209
|
+
|
|
210
|
+
It reads each session file the end names (each attempt's, else `sessionFile`) and sums the `usage` of every assistant turn in it (every branch: all of it was spent), except the turns a fork copied from the launcher: a turn older than the file's `session` header, or one whose entry id the calling session holds.
|
|
211
|
+
Then it writes `metadata.herdr.spend` as an `update` of that task, keeping every other `metadata` key:
|
|
212
|
+
|
|
213
|
+
```json
|
|
214
|
+
{
|
|
215
|
+
"input": 1500, "output": 300, "cacheRead": 3000, "cacheWrite": 0, "tokens": 4800, "cost": 0.75,
|
|
216
|
+
"ms": 125000, "runs": 1, "models": ["anthropic/claude-opus-5-5"], "ended": [{ "id": "0accb6d1-4380-4d51-a6d7-81dd0408d82f", "by": "event", "proc": "5f0c…" }],
|
|
217
|
+
"sessions": [{ "session": "/path/child.jsonl", "input": 1500, "output": 300, "cacheRead": 3000, "cacheWrite": 0, "tokens": 4800, "cost": 0.75, "models": ["anthropic/claude-opus-5-5"] }]
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The top-level figures are the task's totals over all its runs: `tokens` is pi's `totalTokens`, `cost` its `cost.total` in US dollars, `ms` the sum of the ends' wall time (an end with `attempts` adds its attempts' `elapsed`, else its own), `runs` the number of ended runs (results and pings), and `models` the `provider/model` ids seen, first seen first, at most eight.
|
|
222
|
+
`ended` holds a proof for each run counted by one half of its end (`by`: `"event"` or `"message"`) while the other half may still come, so the event and the message of one run count once however many other runs end in between. Both halves belong to the pi process that sent them (`proc`): the host emits the event as it sends the message, and a queued message is lost with its process. A proof leaves at the task's next write once its other half came, or when it was left by another process; a message cleared before the model read it leaves its proof until its process ends.
|
|
223
|
+
When an end tied to its launch by its run id names a final session file other than the launch's (a fallback's last attempt), the ledger adds that file to the bound run's `also` in `metadata.herdr.runs` (at most four), so a `subagent_resume` of it binds to the same task and its spend is counted there.
|
|
224
|
+
A resume continues the same session file, so the ledger replaces that session's figures with the file's new total instead of adding them again; `sessions` keeps up to twelve, newest last, and an older one stays in the totals but is no longer told apart.
|
|
225
|
+
A file that cannot be read adds the run and its time, not tokens.
|
|
226
|
+
A later launch keeps `spend` when it rebinds `metadata.herdr`.
|
|
227
|
+
|
|
228
|
+
The write is synchronous: in one tick it reads the list from the branch pi is on (its newest `todo/v1` snapshot, not the in-memory list, which a `session_tree` replay still to run may hold from the branch before), reads the files, and appends the snapshot.
|
|
229
|
+
No branch switch, replay, or shutdown can come between the read and the append, so the write lands on the branch pi is on, with that branch's tasks: a branch that does not hold the bound task records nothing.
|
|
230
|
+
A `todo` call of the session that is running or queued holds the list while its guards run; the write then waits its turn in the session's queue and does the same there, and one queued before `session_shutdown` is dropped.
|
|
231
|
+
Namespace validators judge the write as any `update`; change guards (see [Change guards](#4-change-guards)) are not asked: they are awaited, and the write records a run that already happened (the boss's decision, 2026-11-28: 「不經過關卡」). A guard such as Straw Boss's train guard therefore never sees or refuses a spend write, which changes only `metadata.herdr`. A validator's refusal leaves the list unchanged and appends `Todo spend: <reason>` to the message.
|
|
232
|
+
The figures are an estimate from what pi wrote in the child's transcript, bookkeeping rather than a bill. `get` shows them on a `spend:` line.
|
|
233
|
+
|
|
198
234
|
## 4. Change guards
|
|
199
235
|
|
|
200
236
|
A namespace validator judges one task's value.
|
|
@@ -215,7 +251,7 @@ const register = () =>
|
|
|
215
251
|
|
|
216
252
|
A later registration of the same `id` replaces the earlier one; the extension ignores, with a console warning, a payload whose `v` is not 1, whose `id` is empty, or whose `check` is not a function.
|
|
217
253
|
|
|
218
|
-
The extension calls `check(change)` for every call that would change the list: `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `update`, `delete`, and `clear`.
|
|
254
|
+
The extension calls `check(change)` for every call that would change the list (the ledger's own [run spend](#run-spend-metadataherdrspend) record does not reach them): `create` (a single task or a `tasks[]` batch, with or without metadata), `import`, `update`, `delete`, and `clear`.
|
|
219
255
|
On import, namespace validators see each relevant task as a `create`.
|
|
220
256
|
Guard registration accepts an optional `imports: true` field within v1.
|
|
221
257
|
If any registered guard has not opted in, the tool returns `Error: guard <id> refused: guard does not accept imports` without calling the guards or committing the list.
|
package/README.md
CHANGED
|
@@ -46,6 +46,7 @@ The new fields are optional parameters of `create` (and of each `tasks[]` item)
|
|
|
46
46
|
Pass that value as a Herdr `subagent`'s `item` (or use `<session8>#<id>` from the same session).
|
|
47
47
|
Once the launch is acknowledged, the ledger sets `owner` to the child's full name and records its run id in [`metadata.herdr`](CONTRACT.md#optional-herdr-launch-identity-metadataherdr).
|
|
48
48
|
Use `metadata.herdr.id` to resolve or message the worker by its run key.
|
|
49
|
+
When a bound run ends, the ledger adds its tokens, cost, wall time, and models to [`metadata.herdr.spend`](CONTRACT.md#run-spend-metadataherdrspend), summed over the todo's runs; `get` shows them. The figures are an estimate from the child's transcript, not a bill.
|
|
49
50
|
Use a name with `/boss send` only if it matches the name Straw Boss shows; a launch named `API worker` may appear there as `api-worker`.
|
|
50
51
|
You can still set `owner` by hand.
|
|
51
52
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-todo-ledger",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/index.ts
CHANGED
|
@@ -34,9 +34,10 @@ import {
|
|
|
34
34
|
READY_EVENT,
|
|
35
35
|
toChangedEvent,
|
|
36
36
|
} from "./ledger/contract.ts";
|
|
37
|
-
import { makeFinishCall } from "./ledger/finish-call.ts";
|
|
37
|
+
import { makeCommitNow, makeFinishCall } from "./ledger/finish-call.ts";
|
|
38
38
|
import { GuardRegistry } from "./ledger/guards.ts";
|
|
39
39
|
import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
|
|
40
|
+
import { registerHerdrSpend } from "./ledger/herdr-spend.ts";
|
|
40
41
|
import { NamespaceRegistry } from "./ledger/namespaces.ts";
|
|
41
42
|
import { I18N_NAMESPACE } from "./state/i18n-bridge.ts";
|
|
42
43
|
import { replayFromBranch } from "./state/replay.ts";
|
|
@@ -212,6 +213,7 @@ export default function (
|
|
|
212
213
|
const finish = makeFinishCall(pi, namespaces, guards);
|
|
213
214
|
registerTodoTool(pi, finish);
|
|
214
215
|
registerHerdrOwner(pi, finish);
|
|
216
|
+
registerHerdrSpend(pi, makeCommitNow(pi, namespaces));
|
|
215
217
|
registerTodosCommand(pi);
|
|
216
218
|
pi.events.emit(READY_EVENT, { v: CONTRACT_VERSION });
|
|
217
219
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { changesState, type ApplyResult } from "../state/state-reducer.ts";
|
|
2
|
+
import { applyTaskMutation, changesState, type ApplyResult } from "../state/state-reducer.ts";
|
|
3
3
|
import type { TaskState } from "../state/state.ts";
|
|
4
4
|
import { commitState, replaceState } from "../state/store.ts";
|
|
5
5
|
import { buildToolResult } from "../tool/response-envelope.ts";
|
|
@@ -44,3 +44,24 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export type FinishCall = ReturnType<typeof makeFinishCall>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The ledger's own bookkeeping of something that already happened (a run's spend, herdr-spend.ts), committed in the same tick its caller read `before` from the
|
|
50
|
+
* session's live branch: an `update` judged by the namespace validators, appended to the branch, then published. Change guards are not asked: they are awaited, and
|
|
51
|
+
* a write that awaits can land on a branch the session switched to meanwhile (pi moves the leaf before its `session_tree` handlers run). Returns the refusal, if any.
|
|
52
|
+
*/
|
|
53
|
+
export function makeCommitNow(pi: ExtensionAPI, namespaces: NamespaceRegistry) {
|
|
54
|
+
return (sessionId: string, input: TaskMutationParams, before: TaskState): string | undefined => {
|
|
55
|
+
const result = applyTaskMutation(before, "update", input);
|
|
56
|
+
if (result.op.kind === "error") return result.op.message;
|
|
57
|
+
if (!changesState(result.op)) return undefined;
|
|
58
|
+
const refusal = namespaces.check(changedTasks(result.op, input, result.state, before));
|
|
59
|
+
if (refusal) return refusal;
|
|
60
|
+
pi.appendEntry(SNAPSHOT_ENTRY_TYPE, toSnapshot(result.state, sessionId));
|
|
61
|
+
commitState(sessionId, result.state);
|
|
62
|
+
pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
|
|
63
|
+
return undefined;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type CommitNow = ReturnType<typeof makeCommitNow>;
|
|
@@ -6,7 +6,7 @@ import { sanitizeTerminalText } from "../tool/sanitize.ts";
|
|
|
6
6
|
import type { FinishCall } from "./finish-call.ts";
|
|
7
7
|
import { runningGuard } from "./guards.ts";
|
|
8
8
|
|
|
9
|
-
import { bindRun, history } from "./herdr-runs.ts";
|
|
9
|
+
import { bindRun, history, runOfPath } from "./herdr-runs.ts";
|
|
10
10
|
|
|
11
11
|
const uid = /^t_[a-z2-7]{10}$/;
|
|
12
12
|
const local = /^([a-f0-9]{8})#([1-9]\d*)$/i;
|
|
@@ -63,7 +63,7 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
|
|
|
63
63
|
return await withSessionLock(session, async () => {
|
|
64
64
|
const before = getState(session);
|
|
65
65
|
if (pinned && !pinned.uid && listGeneration(session) !== pinned.generation) return;
|
|
66
|
-
const matches = resume ? before.tasks.filter(t => t.status !== 'deleted' && history(t.metadata?.herdr).runs.some(r => r
|
|
66
|
+
const matches = resume ? before.tasks.filter(t => t.status !== 'deleted' && history(t.metadata?.herdr).runs.some(r => runOfPath(r, path as string))) : [];
|
|
67
67
|
if (resume && matches.length !== 1) return;
|
|
68
68
|
const task = resume ? matches[0] : pinned && !pinned.uid
|
|
69
69
|
? before.tasks.find(t => t.id === pinned.id && !t.uid)
|
package/src/ledger/herdr-runs.ts
CHANGED
|
@@ -4,6 +4,24 @@ export interface BoundRun {
|
|
|
4
4
|
pane?: string;
|
|
5
5
|
session?: string;
|
|
6
6
|
agent?: string;
|
|
7
|
+
/** Session files the run went on to (a fallback's final attempt), from an end tied to it by its run id: a resume of one of them is this binding's. */
|
|
8
|
+
also?: string[];
|
|
9
|
+
}
|
|
10
|
+
/** Whether a bound run is the one of session file `path`: its own, or one its ends named. */
|
|
11
|
+
export const runOfPath = (r: BoundRun, path: string) => r.session === path || (Array.isArray(r.also) && r.also.includes(path));
|
|
12
|
+
/** Run records kept for `also`, newest last. */
|
|
13
|
+
const ALSO = 4;
|
|
14
|
+
/** `herdr` with session file `path` recorded on its run `id` (`also`), when that run is bound and the path is not its own yet; else `herdr` as it is. */
|
|
15
|
+
export function aliasRun(herdr: Record<string, unknown>, id: string, path: string): Record<string, unknown> {
|
|
16
|
+
if (!Array.isArray(herdr.runs)) return herdr;
|
|
17
|
+
let changed = false;
|
|
18
|
+
const runs = herdr.runs.map((r: unknown) => {
|
|
19
|
+
const run = r as BoundRun;
|
|
20
|
+
if (!run || typeof run !== "object" || run.id !== id || runOfPath(run, path)) return r;
|
|
21
|
+
changed = true;
|
|
22
|
+
return { ...run, also: [...(Array.isArray(run.also) ? run.also.filter((p) => typeof p === "string") : []), path].slice(-ALSO) };
|
|
23
|
+
});
|
|
24
|
+
return changed ? { ...herdr, runs } : herdr;
|
|
7
25
|
}
|
|
8
26
|
export function history(value: unknown): { runs: BoundRun[]; older: number } {
|
|
9
27
|
if (!value || typeof value !== "object") return { runs: [], older: 0 };
|
|
@@ -40,5 +58,7 @@ export function bindRun(previous: unknown, newest: BoundRun) {
|
|
|
40
58
|
...(newest.pane ? { pane: newest.pane } : {}),
|
|
41
59
|
runs: next.slice(-6),
|
|
42
60
|
...(dropped ? { older: dropped } : {}),
|
|
61
|
+
// What the todo's runs spent (herdr-spend.ts) outlives a new binding.
|
|
62
|
+
...(previous && typeof previous === "object" && "spend" in previous ? { spend: (previous as { spend: unknown }).spend } : {}),
|
|
43
63
|
};
|
|
44
64
|
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { listOnBranch } from "../state/replay.ts";
|
|
3
|
+
import { sessionBusy, withSessionLock } from "../state/session-lock.ts";
|
|
4
|
+
import { listGeneration, sid } from "../state/store.ts";
|
|
5
|
+
import { sanitizeTerminalText } from "../tool/sanitize.ts";
|
|
6
|
+
import type { Task } from "../tool/types.ts";
|
|
7
|
+
import type { BoundRun } from "./herdr-runs.ts";
|
|
8
|
+
import type { CommitNow } from "./finish-call.ts";
|
|
9
|
+
import { runningGuard } from "./guards.ts";
|
|
10
|
+
import { aliasRun, history, runOfPath } from "./herdr-runs.ts";
|
|
11
|
+
import { addRun, fileSpend, nonblank, PROC, record, SETTLED, spendOf } from "./spend.ts";
|
|
12
|
+
|
|
13
|
+
// A run's spend on its todo (CONTRACT.md "Run spend"). A run's end comes two ways: the host's `subagent:run-end` event, sent as the host delivers the end whether or not the model
|
|
14
|
+
// ever reads it, and the `subagent_result` or `subagent_ping` message the launching session's model receives. Both name the run's id, by which it counts once, and its session files:
|
|
15
|
+
// one per spawned attempt (`attempts`, a fallback's failed ones included), else the end's `sessionFile`. The ledger reads those files, sums the usage of the child's own assistant
|
|
16
|
+
// turns, and records it on the todo in `metadata.herdr.spend`. A resume continues the same file, so a session's figures are replaced by its newest total (never added twice); wall time
|
|
17
|
+
// adds each attempt's `elapsed`. The figures are what pi wrote in the child's transcript: bookkeeping, not a bill.
|
|
18
|
+
//
|
|
19
|
+
// The write is synchronous: it reads the list from the branch pi is on at that moment (pi's leaf, not the live slot, which a pending `session_tree` replay may still hold from the
|
|
20
|
+
// branch before), reads the files, and appends in the same tick, so no branch switch, replay or shutdown can come between the read and the append. A `todo` call of the session that
|
|
21
|
+
// is running or queued holds the list while its guards run: the write then waits its turn in the session's queue and does the same there.
|
|
22
|
+
|
|
23
|
+
export const RUN_END_EVENT = "subagent:run-end";
|
|
24
|
+
const ENDS = new Set(["subagent_result", "subagent_ping"]);
|
|
25
|
+
const uid = /^t_[a-z2-7]{10}$/;
|
|
26
|
+
const seconds = (x: unknown): x is number => typeof x === "number" && Number.isFinite(x) && x >= 0;
|
|
27
|
+
|
|
28
|
+
/** One spawned attempt of a run: its session file, when it has one, and its wall time. */
|
|
29
|
+
interface Attempt { file?: string; elapsed?: number }
|
|
30
|
+
/** One ended run, from the host's event or its message's details. */
|
|
31
|
+
interface End { run?: string; item?: unknown; file?: string; elapsed?: number; attempts?: Attempt[] }
|
|
32
|
+
const endOf = (d: Record<string, unknown>): End => {
|
|
33
|
+
const attempts = Array.isArray(d.attempts)
|
|
34
|
+
? d.attempts.flatMap((a): Attempt[] => (record(a) ? [{ ...(nonblank(a.sessionFile) ? { file: a.sessionFile } : {}), ...(seconds(a.elapsed) ? { elapsed: a.elapsed } : {}) }] : []))
|
|
35
|
+
: [];
|
|
36
|
+
return {
|
|
37
|
+
...(nonblank(d.id) ? { run: d.id } : {}),
|
|
38
|
+
item: d.item,
|
|
39
|
+
...(nonblank(d.sessionFile) ? { file: d.sessionFile } : {}),
|
|
40
|
+
...(seconds(d.elapsed) ? { elapsed: d.elapsed } : {}),
|
|
41
|
+
...(attempts.length ? { attempts } : {}),
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
/** The session files an end names: each attempt's, else the end's own. */
|
|
45
|
+
const filesOf = (end: End): string[] => [...new Set(end.attempts ? end.attempts.flatMap((a) => (a.file ? [a.file] : [])) : end.file ? [end.file] : [])];
|
|
46
|
+
/** An end's wall time: its attempts' sum (a fallback's failed attempts ran too), else its own. */
|
|
47
|
+
const timeOf = (end: End): number | undefined => (end.attempts?.some((a) => a.elapsed !== undefined) ? end.attempts.reduce((sum, a) => sum + (a.elapsed ?? 0), 0) : end.elapsed);
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The open todo an ended run is for, as its launch bound it: the one whose bound runs hold its run id, else one of its session files, else the todo its `item` names by uid. A bare
|
|
51
|
+
* `<session8>#<id>` is never looked up as the todo of that number now: after a clear or a branch switch it names another todo (the launch's binding is what proves the identity).
|
|
52
|
+
*/
|
|
53
|
+
function taskOf(tasks: readonly Task[], end: End): Task | undefined {
|
|
54
|
+
const open = tasks.filter((t) => t.status !== "deleted"), files = new Set([...(end.file ? [end.file] : []), ...filesOf(end)]);
|
|
55
|
+
for (const match of [end.run && ((r: { id: string }) => r.id === end.run), files.size > 0 && ((r: BoundRun) => [...files].some((f) => runOfPath(r, f)))]) {
|
|
56
|
+
if (!match) continue;
|
|
57
|
+
const bound = open.filter((t) => history(t.metadata?.herdr).runs.some(match));
|
|
58
|
+
if (bound.length === 1) return bound[0];
|
|
59
|
+
if (bound.length > 1) return undefined;
|
|
60
|
+
}
|
|
61
|
+
return typeof end.item === "string" && uid.test(end.item) ? open.find((t) => t.uid === end.item) : undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The ids of the launcher's own entries: a forked child's file holds copies of them. */
|
|
65
|
+
function parentIds(ctx: ExtensionContext): Set<string> {
|
|
66
|
+
const sm = ctx.sessionManager as { getEntries?(): readonly unknown[]; getBranch(): readonly unknown[] };
|
|
67
|
+
const entries = typeof sm.getEntries === "function" ? sm.getEntries() : sm.getBranch();
|
|
68
|
+
return new Set(entries.flatMap((e) => (record(e) && typeof e.id === "string" ? [e.id] : [])));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Per-load observer of ended runs. */
|
|
72
|
+
export function registerHerdrSpend(pi: ExtensionAPI, commit: CommitNow) {
|
|
73
|
+
/** The session the host's event belongs to: this process's current one, as its last event showed it. */
|
|
74
|
+
let current: ExtensionContext | undefined;
|
|
75
|
+
const seen = (_event: unknown, ctx: ExtensionContext) => void (current = ctx);
|
|
76
|
+
pi.on("session_start", seen); pi.on("session_tree", seen); pi.on("agent_start", seen);
|
|
77
|
+
/** Shutdowns per session: a write queued before one is dropped, even when a call that finished after it rebuilt the list. */
|
|
78
|
+
const shutdowns = new Map<string, number>();
|
|
79
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
80
|
+
try { const s = sid(ctx); shutdowns.set(s, (shutdowns.get(s) ?? 0) + 1); } catch { /* a stale context: its session is gone with it */ }
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
/** Records one end in this tick, by one half of it (`by`); a reason when it could not, undefined when it did or when the end is not this list's. */
|
|
84
|
+
const book = (ctx: ExtensionContext, end: End, by: "event" | "message"): string | undefined => {
|
|
85
|
+
const session = sid(ctx);
|
|
86
|
+
if (listGeneration(session) === undefined) return undefined; // shut down: its list is gone, and no write may rebuild it
|
|
87
|
+
const before = listOnBranch(ctx), task = taskOf(before.tasks, end);
|
|
88
|
+
if (!task) return undefined;
|
|
89
|
+
const herdr = record(task.metadata?.herdr) ? task.metadata.herdr : {};
|
|
90
|
+
// The other half of a run already counted: it counts nothing, and the proof goes at the todo's next write.
|
|
91
|
+
const proof = end.run ? spendOf(herdr.spend).ended?.find((p) => p.id === end.run) : undefined;
|
|
92
|
+
if (proof) { if (proof.by !== by) SETTLED.add(proof.id); return undefined; }
|
|
93
|
+
const parent = parentIds(ctx), files = filesOf(end).map((session) => ({ session, spend: fileSpend(session, parent) }));
|
|
94
|
+
const spend = addRun(herdr.spend, files, timeOf(end), end.run ? { id: end.run, by, proc: PROC } : undefined);
|
|
95
|
+
// A fallback ends on another file than its launch's: record it on the run its id names, so a resume of that file is this todo's (review F012).
|
|
96
|
+
const last = end.attempts?.findLast((a) => a.file)?.file ?? end.file;
|
|
97
|
+
const bound = end.run && last ? aliasRun(herdr, end.run, last) : herdr;
|
|
98
|
+
return commit(session, { action: "update", id: task.id, metadata: { herdr: { ...bound, spend } } }, before);
|
|
99
|
+
};
|
|
100
|
+
/** `book` now, or, behind a running or queued call of the session, when its turn comes. */
|
|
101
|
+
const recordEnd = (ctx: ExtensionContext, end: End, by: "event" | "message"): string | undefined | Promise<string | undefined> => {
|
|
102
|
+
const session = sid(ctx);
|
|
103
|
+
if (runningGuard(session)) return "cannot update the list from its own change guard";
|
|
104
|
+
if (!sessionBusy(session)) return book(ctx, end, by);
|
|
105
|
+
const epoch = shutdowns.get(session) ?? 0;
|
|
106
|
+
return withSessionLock(session, async () => ((shutdowns.get(session) ?? 0) === epoch ? book(ctx, end, by) : undefined));
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// The host's event: an end the model may never read (a steer cleared before its turn) is still spent. A refusal here is said again by the message, when it comes.
|
|
110
|
+
pi.events.on(RUN_END_EVENT, (raw) => {
|
|
111
|
+
const ctx = current;
|
|
112
|
+
if (!ctx || !record(raw) || raw.v !== 1 || !nonblank(raw.id) || (raw.kind !== "result" && raw.kind !== "ping")) return;
|
|
113
|
+
try {
|
|
114
|
+
void Promise.resolve(recordEnd(ctx, endOf(raw), "event")).catch(() => undefined); // a stale context (the session was replaced): its next session replays its own list
|
|
115
|
+
} catch { /* the same, thrown in this tick */ }
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
pi.on("message_end", async (event, ctx) => {
|
|
119
|
+
const message = event.message as { role?: string; customType?: string; content?: unknown; details?: unknown };
|
|
120
|
+
if (message.role !== "custom" || !ENDS.has(message.customType ?? "") || !record(message.details)) return;
|
|
121
|
+
const say = (why: string) => {
|
|
122
|
+
const note = `Todo spend: ${sanitizeTerminalText(why)}`;
|
|
123
|
+
const content = typeof message.content === "string" ? `${message.content}\n\n${note}` : Array.isArray(message.content) ? [...message.content, { type: "text", text: note }] : note;
|
|
124
|
+
return { message: { ...message, content } as typeof event.message };
|
|
125
|
+
};
|
|
126
|
+
try {
|
|
127
|
+
const why = await recordEnd(ctx, endOf(message.details), "message");
|
|
128
|
+
return why ? say(why) : undefined;
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return say(error instanceof Error ? error.message : String(error));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { sanitizeTerminalText } from "../tool/sanitize.ts";
|
|
4
|
+
|
|
5
|
+
// A run's spend as `metadata.herdr.spend` keeps it (CONTRACT.md "Run spend"): pure parts, so `todo get` formats it without the observer (herdr-spend.ts).
|
|
6
|
+
|
|
7
|
+
export const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
|
|
8
|
+
export const nonblank = (x: unknown): x is string => typeof x === "string" && x.trim().length > 0;
|
|
9
|
+
/** Sessions kept for the replace-not-add rule, newest last; an older one folds into the totals and is no longer told apart. Models kept, first seen first. */
|
|
10
|
+
export const SPEND_SESSIONS = 12, SPEND_MODELS = 8;
|
|
11
|
+
const COUNTS = ["input", "output", "cacheRead", "cacheWrite", "tokens", "cost"] as const;
|
|
12
|
+
type Counts = Record<(typeof COUNTS)[number], number>;
|
|
13
|
+
export interface SessionSpend extends Counts { session: string; models: string[] }
|
|
14
|
+
/**
|
|
15
|
+
* One run counted by one half of its end (the host's `event` or its `message`) while the other half may still come: both name the run id, and it counts once. Both halves
|
|
16
|
+
* belong to one pi process (the host emits the event as it sends the message, and a queued message dies with its process), so `proc` names the process that counted it.
|
|
17
|
+
*/
|
|
18
|
+
export interface EndProof { id: string; by: "event" | "message"; proc: string }
|
|
19
|
+
export interface Spend extends Counts { ms: number; runs: number; models: string[]; sessions: SessionSpend[]; /** Runs counted whose other half may still come, oldest first. */ ended?: EndProof[] }
|
|
20
|
+
|
|
21
|
+
/** This pi process: one id for every load of the extension in it (a `/reload` keeps the queued messages, so it keeps the id). */
|
|
22
|
+
export const PROC: string = ((globalThis as Record<symbol, string | undefined>)[Symbol.for("pi-todo-ledger/process")] ??= randomUUID());
|
|
23
|
+
/** Run ids whose both halves came in this process: their proof is dropped at the todo's next write. Process-wide, so a `/reload` keeps it. */
|
|
24
|
+
export const SETTLED: Set<string> = ((globalThis as Record<symbol, Set<string> | undefined>)[Symbol.for("pi-todo-ledger/settled-ends")] ??= new Set());
|
|
25
|
+
/** The proofs that can still meet their other half: this process's, not yet settled. */
|
|
26
|
+
const live = (proofs: readonly EndProof[]) => proofs.filter((p) => p.proc === PROC && !SETTLED.has(p.id));
|
|
27
|
+
|
|
28
|
+
const count = (x: unknown) => (typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : 0);
|
|
29
|
+
const zero = (): Counts => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, tokens: 0, cost: 0 });
|
|
30
|
+
const names = (x: unknown) => (Array.isArray(x) ? x.filter(nonblank) : []);
|
|
31
|
+
|
|
32
|
+
/** A stored spend read back defensively: a hand-edited or partial one counts from what it holds. */
|
|
33
|
+
export function spendOf(value: unknown): Spend {
|
|
34
|
+
const v = record(value) ? value : {};
|
|
35
|
+
const sessions = (Array.isArray(v.sessions) ? v.sessions : []).flatMap((s): SessionSpend[] => (record(s) && nonblank(s.session) ? [{ session: s.session, ...Object.fromEntries(COUNTS.map((k) => [k, count(s[k])])) as Counts, models: names(s.models) }] : []));
|
|
36
|
+
const ended = (Array.isArray(v.ended) ? v.ended : []).flatMap((p): EndProof[] => (record(p) && nonblank(p.id) && (p.by === "event" || p.by === "message") && nonblank(p.proc) ? [{ id: p.id, by: p.by, proc: p.proc }] : []));
|
|
37
|
+
return { ...Object.fromEntries(COUNTS.map((k) => [k, count(v[k])])) as Counts, ms: count(v.ms), runs: count(v.runs), models: names(v.models), sessions, ...(ended.length ? { ended } : {}) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The usage pi recorded on the assistant turns of a child's session file, every branch of it (all of it was spent), and the models they ran on; undefined when the file cannot be read.
|
|
42
|
+
* A forked child starts with a copy of its launcher's branch, entry ids and times kept: a turn older than the file's header (written when the child was seeded) or one whose id the
|
|
43
|
+
* launcher's own session holds (`parent`) is the launcher's spend, not the child's.
|
|
44
|
+
*/
|
|
45
|
+
export function fileSpend(file: string, parent: ReadonlySet<string> = new Set()): FileSpend | undefined {
|
|
46
|
+
let raw: string;
|
|
47
|
+
try { raw = readFileSync(file, "utf8"); } catch { return undefined; }
|
|
48
|
+
const counts = zero(), models: string[] = [];
|
|
49
|
+
let seeded: number | undefined;
|
|
50
|
+
for (const line of raw.split("\n")) {
|
|
51
|
+
if (seeded === undefined && line.includes('"type":"session"')) {
|
|
52
|
+
try { const h = JSON.parse(line) as { type?: unknown; timestamp?: unknown }; if (h.type === "session" && typeof h.timestamp === "string") seeded = Date.parse(h.timestamp); } catch { /* no header time */ }
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!line.includes('"assistant"') || !line.includes('"usage"')) continue;
|
|
56
|
+
let entry: unknown;
|
|
57
|
+
try { entry = JSON.parse(line); } catch { continue; } // a torn last line
|
|
58
|
+
const m = record(entry) && record(entry.message) ? entry.message : undefined, u = m && m.role === "assistant" && record(m.usage) ? m.usage : undefined;
|
|
59
|
+
if (!m || !u) continue;
|
|
60
|
+
const e = entry as { id?: unknown; timestamp?: unknown }, at = typeof e.timestamp === "string" ? Date.parse(e.timestamp) : Number.NaN;
|
|
61
|
+
if ((typeof e.id === "string" && parent.has(e.id)) || (seeded !== undefined && Number.isFinite(seeded) && Number.isFinite(at) && at < seeded)) continue;
|
|
62
|
+
counts.input += count(u.input), counts.output += count(u.output), counts.cacheRead += count(u.cacheRead), counts.cacheWrite += count(u.cacheWrite);
|
|
63
|
+
counts.tokens += count(u.totalTokens) || count(u.input) + count(u.output) + count(u.cacheRead) + count(u.cacheWrite);
|
|
64
|
+
counts.cost += record(u.cost) ? count(u.cost.total) : 0;
|
|
65
|
+
const model = nonblank(m.model) ? (nonblank(m.provider) ? `${m.provider}/${m.model}` : m.model) : undefined;
|
|
66
|
+
if (model && !models.includes(model)) models.push(model);
|
|
67
|
+
}
|
|
68
|
+
return { counts, models };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** What one session file holds: the usage counts and the models of its own assistant turns. */
|
|
72
|
+
export interface FileSpend { counts: Counts; models: string[] }
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* `previous` with one ended run added: each of its session files' figures replaced by that file's total (a fallback run has a file per attempt, a resume continues
|
|
76
|
+
* one), `seconds` of wall time added, and its run id (`run`), when the host names one, kept. A file that could not be read (`undefined`) adds no tokens.
|
|
77
|
+
*/
|
|
78
|
+
export function addRun(previous: unknown, files: ReadonlyArray<{ session: string; spend: FileSpend | undefined }>, seconds: number | undefined, proof?: EndProof): Spend {
|
|
79
|
+
const s = spendOf(previous), out: Spend = { ...s, ms: s.ms + (seconds === undefined ? 0 : Math.round(seconds * 1000)), runs: s.runs + 1, models: [...s.models], sessions: [...s.sessions] };
|
|
80
|
+
const ended = [...live(s.ended ?? []).filter((p) => p.id !== proof?.id), ...(proof ? [proof] : [])];
|
|
81
|
+
if (ended.length) out.ended = ended;
|
|
82
|
+
else delete out.ended;
|
|
83
|
+
for (const { session, spend: file } of files) {
|
|
84
|
+
if (!file) continue;
|
|
85
|
+
const at = out.sessions.findIndex((x) => x.session === session), before = at < 0 ? zero() : out.sessions[at]!;
|
|
86
|
+
for (const k of COUNTS) out[k] = Math.max(0, out[k] + file.counts[k] - before[k]);
|
|
87
|
+
if (at >= 0) out.sessions.splice(at, 1);
|
|
88
|
+
out.sessions.push({ session, ...file.counts, models: file.models });
|
|
89
|
+
for (const m of file.models) if (!out.models.includes(m)) out.models.push(m);
|
|
90
|
+
}
|
|
91
|
+
out.sessions = out.sessions.slice(-SPEND_SESSIONS);
|
|
92
|
+
out.models = out.models.slice(0, SPEND_MODELS);
|
|
93
|
+
out.cost = Math.round(out.cost * 1e6) / 1e6;
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A spend in one line, for `todo get`: tokens, cost, wall time, runs, models. */
|
|
98
|
+
export function spendLine(value: unknown): string | undefined {
|
|
99
|
+
const s = spendOf(value);
|
|
100
|
+
if (!s.runs) return undefined;
|
|
101
|
+
const seconds = Math.round(s.ms / 1000), time = seconds < 60 ? `${seconds}s` : seconds < 3600 ? `${Math.floor(seconds / 60)}m ${seconds % 60}s` : `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
|
|
102
|
+
return [`${s.tokens.toLocaleString("en-US")} tokens`, `$${s.cost < 10 ? s.cost.toFixed(2) : s.cost.toFixed(1)}`, time, `${s.runs} run${s.runs === 1 ? "" : "s"}`, ...s.models.map(sanitizeTerminalText)].join(" · ");
|
|
103
|
+
}
|
package/src/state/replay.ts
CHANGED
|
@@ -90,3 +90,17 @@ export function replayFromBranch(ctx: { sessionManager: { getBranch(): Iterable<
|
|
|
90
90
|
fromV1 ?? fromLegacyEntries ?? fromToolResults ?? { tasks: [...EMPTY_STATE.tasks], nextId: EMPTY_STATE.nextId }
|
|
91
91
|
);
|
|
92
92
|
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The list the session's live branch holds now, as `replayFromBranch` reads it, from its newest valid `todo/v1` snapshot when there is one (a walk back from the
|
|
96
|
+
* leaf, which validates that one snapshot only). A writer that must commit onto the branch pi is on at this moment reads this, not the live slot: pi moves the leaf
|
|
97
|
+
* before its `session_tree` handlers replay the slot.
|
|
98
|
+
*/
|
|
99
|
+
export function listOnBranch(ctx: { sessionManager: { getBranch(): Iterable<unknown> } }): TaskState {
|
|
100
|
+
const branch = Array.from(ctx.sessionManager.getBranch());
|
|
101
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
102
|
+
const e = branch[i] as { type?: string; customType?: string; data?: unknown };
|
|
103
|
+
if (e?.type === "custom" && e.customType === SNAPSHOT_ENTRY_TYPE && isSnapshotV1(e.data)) return stateOf(e.data);
|
|
104
|
+
}
|
|
105
|
+
return replayFromBranch({ sessionManager: { getBranch: () => branch } });
|
|
106
|
+
}
|
|
@@ -21,3 +21,8 @@ export function withSessionLock<T>(sessionId: string, fn: () => Promise<T>): Pro
|
|
|
21
21
|
});
|
|
22
22
|
return run;
|
|
23
23
|
}
|
|
24
|
+
|
|
25
|
+
/** Whether a call of the session is running or queued: a synchronous writer must queue behind it, else the call commits a list read before the write. */
|
|
26
|
+
export function sessionBusy(sessionId: string): boolean {
|
|
27
|
+
return tails.has(sessionId);
|
|
28
|
+
}
|
|
@@ -2,6 +2,7 @@ import type { TaskState } from "../state/state.ts";
|
|
|
2
2
|
import type { Op } from "../state/state-reducer.ts";
|
|
3
3
|
import { deriveBlocks } from "../state/task-graph.ts";
|
|
4
4
|
import { isOpen, resultSuffix } from "../view/task-labels.ts";
|
|
5
|
+
import { spendLine } from "../ledger/spend.ts";
|
|
5
6
|
import { sanitizeTerminalText } from "./sanitize.ts";
|
|
6
7
|
import type { Task, TaskAction, TaskDetails, TaskMutationParams } from "./types.ts";
|
|
7
8
|
|
|
@@ -60,6 +61,8 @@ function formatGetLines(task: Task, state: TaskState): string {
|
|
|
60
61
|
if (task.points !== undefined) lines.push(` points: ${task.points}`);
|
|
61
62
|
if (task.anchor) lines.push(` anchor: ${sanitizeTerminalText(task.anchor)}`);
|
|
62
63
|
if (task.graph) lines.push(` graph: ${task.graph}`);
|
|
64
|
+
const spend = spendLine((task.metadata?.herdr as { spend?: unknown } | undefined)?.spend);
|
|
65
|
+
if (spend) lines.push(` spend: ${spend}`);
|
|
63
66
|
for (const e of task.evidence ?? []) {
|
|
64
67
|
const sha = e.sha ? ` @${sanitizeTerminalText(e.sha)}` : "";
|
|
65
68
|
lines.push(` evidence: ${e.result} ${sanitizeTerminalText(e.command)}${sha} (${sanitizeTerminalText(e.at)})`);
|