pi-daddy 0.59.0 → 0.60.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +105 -21
  3. package/contracts/ledger-record/v1/README.md +6 -0
  4. package/dist/executors/activity-session.d.ts +4 -0
  5. package/dist/executors/activity-session.d.ts.map +1 -1
  6. package/dist/executors/activity-session.js +19 -0
  7. package/dist/executors/activity-session.js.map +1 -1
  8. package/dist/executors/child-final.d.ts +2 -0
  9. package/dist/executors/child-final.d.ts.map +1 -1
  10. package/dist/executors/child-final.js +4 -0
  11. package/dist/executors/child-final.js.map +1 -1
  12. package/dist/executors/child-usage.d.ts +129 -0
  13. package/dist/executors/child-usage.d.ts.map +1 -0
  14. package/dist/executors/child-usage.js +202 -0
  15. package/dist/executors/child-usage.js.map +1 -0
  16. package/dist/governance/auto-mode-policy.d.ts +3 -0
  17. package/dist/governance/auto-mode-policy.d.ts.map +1 -1
  18. package/dist/governance/auto-mode-policy.js +18 -2
  19. package/dist/governance/auto-mode-policy.js.map +1 -1
  20. package/dist/governance/operation-artifacts.d.ts +2 -0
  21. package/dist/governance/operation-artifacts.d.ts.map +1 -1
  22. package/dist/governance/operation-artifacts.js +20 -1
  23. package/dist/governance/operation-artifacts.js.map +1 -1
  24. package/dist/governance/operation-replay.d.ts +7 -0
  25. package/dist/governance/operation-replay.d.ts.map +1 -0
  26. package/dist/governance/operation-replay.js +47 -0
  27. package/dist/governance/operation-replay.js.map +1 -0
  28. package/dist/governance/parent-tool-calls.d.ts +31 -0
  29. package/dist/governance/parent-tool-calls.d.ts.map +1 -0
  30. package/dist/governance/parent-tool-calls.js +156 -0
  31. package/dist/governance/parent-tool-calls.js.map +1 -0
  32. package/dist/kernel/child-tools.d.ts +9 -1
  33. package/dist/kernel/child-tools.d.ts.map +1 -1
  34. package/dist/kernel/child-tools.js +25 -5
  35. package/dist/kernel/child-tools.js.map +1 -1
  36. package/dist/kernel/delegate-types.d.ts +26 -0
  37. package/dist/kernel/delegate-types.d.ts.map +1 -1
  38. package/dist/kernel/delegate-types.js.map +1 -1
  39. package/dist/kernel/delegate.d.ts.map +1 -1
  40. package/dist/kernel/delegate.js +19 -1
  41. package/dist/kernel/delegate.js.map +1 -1
  42. package/dist/kernel/dispatch-operation.d.ts +14 -0
  43. package/dist/kernel/dispatch-operation.d.ts.map +1 -1
  44. package/dist/kernel/dispatch-operation.js.map +1 -1
  45. package/dist/kernel/env-names.d.ts +16 -0
  46. package/dist/kernel/env-names.d.ts.map +1 -1
  47. package/dist/kernel/env-names.js +20 -0
  48. package/dist/kernel/env-names.js.map +1 -1
  49. package/dist/kernel/parent-tools.d.ts +174 -0
  50. package/dist/kernel/parent-tools.d.ts.map +1 -0
  51. package/dist/kernel/parent-tools.js +268 -0
  52. package/dist/kernel/parent-tools.js.map +1 -0
  53. package/dist/kernel/propagation.d.ts +1 -1
  54. package/dist/kernel/propagation.d.ts.map +1 -1
  55. package/dist/kernel/propagation.js +5 -0
  56. package/dist/kernel/propagation.js.map +1 -1
  57. package/dist/kernel/replay-safe.d.ts +110 -0
  58. package/dist/kernel/replay-safe.d.ts.map +1 -0
  59. package/dist/kernel/replay-safe.js +121 -0
  60. package/dist/kernel/replay-safe.js.map +1 -0
  61. package/dist/products/dashboard-cli.d.ts.map +1 -1
  62. package/dist/products/dashboard-cli.js +1 -0
  63. package/dist/products/dashboard-cli.js.map +1 -1
  64. package/dist/products/dashboard-render.d.ts +5 -0
  65. package/dist/products/dashboard-render.d.ts.map +1 -1
  66. package/dist/products/dashboard-render.js +25 -0
  67. package/dist/products/dashboard-render.js.map +1 -1
  68. package/dist/products/dashboard-session-client.d.ts +6 -0
  69. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  70. package/dist/products/dashboard-session-client.js.map +1 -1
  71. package/dist/products/episode-report.d.ts +2 -0
  72. package/dist/products/episode-report.d.ts.map +1 -1
  73. package/dist/products/episode-report.js +5 -1
  74. package/dist/products/episode-report.js.map +1 -1
  75. package/extensions/chain-plan.ts +6 -1
  76. package/extensions/child-usage-report.ts +77 -0
  77. package/extensions/dashboard-session-server.ts +12 -0
  78. package/extensions/definition-describe.ts +74 -16
  79. package/extensions/delegate-chain.ts +37 -10
  80. package/extensions/delegation-artifacts.ts +43 -1
  81. package/extensions/delegation-operations.ts +71 -33
  82. package/extensions/delegation.ts +86 -15
  83. package/extensions/execute-child.ts +62 -6
  84. package/extensions/execution-evidence.ts +139 -4
  85. package/extensions/fanout-outcome.ts +4 -1
  86. package/extensions/grants-command.ts +12 -1
  87. package/extensions/grants.ts +23 -4
  88. package/extensions/init-command.ts +1 -1
  89. package/extensions/parent-tool-host.ts +228 -0
  90. package/extensions/parent-tool-proxy.ts +44 -0
  91. package/extensions/public-evidence.ts +8 -2
  92. package/extensions/reload-environment.ts +6 -0
  93. package/extensions/replay-retry.ts +119 -0
  94. package/extensions/run-delegation.ts +77 -12
  95. package/extensions/runtime-snapshot.ts +16 -1
  96. package/extensions/session-report.ts +25 -1
  97. package/extensions/session.ts +9 -0
  98. package/extensions/spawn-summary.ts +72 -3
  99. package/package.json +2 -2
  100. package/src/executors/activity-session.ts +28 -0
  101. package/src/executors/child-final.ts +11 -1
  102. package/src/executors/child-usage.ts +280 -0
  103. package/src/governance/auto-mode-policy.ts +19 -2
  104. package/src/governance/operation-artifacts.ts +21 -1
  105. package/src/governance/operation-replay.ts +70 -0
  106. package/src/governance/parent-tool-calls.ts +191 -0
  107. package/src/kernel/child-tools.ts +39 -9
  108. package/src/kernel/delegate-types.ts +26 -0
  109. package/src/kernel/delegate.ts +17 -1
  110. package/src/kernel/dispatch-operation.ts +11 -0
  111. package/src/kernel/env-names.ts +20 -0
  112. package/src/kernel/parent-tools.ts +342 -0
  113. package/src/kernel/propagation.ts +5 -0
  114. package/src/kernel/replay-safe.ts +182 -0
  115. package/src/products/dashboard-cli.ts +1 -0
  116. package/src/products/dashboard-render.ts +25 -0
  117. package/src/products/dashboard-session-client.ts +2 -0
  118. package/src/products/episode-report.ts +8 -1
@@ -13,7 +13,13 @@ const object = (x: unknown): x is Record<string, any> => !!x && typeof x === "ob
13
13
  const hash = (s: string) => createHash("sha256").update(s, "utf8").digest("hex");
14
14
  export type ChildFinal =
15
15
  | { state: "complete"; text: string; sessionId: string; messageId: string; leafId: string; sha256: string }
16
- | { state: "unavailable"; reason: string; diagnosticText?: string };
16
+ | {
17
+ state: "unavailable";
18
+ reason: string;
19
+ diagnosticText?: string;
20
+ /** The settled run's terminal assistant message reports a failed model request (`stopReason: "error"`). */
21
+ providerError?: true;
22
+ };
17
23
  const capturedSessions = new WeakMap<ChildFinal, Readonly<CapturedSessionBranch>>();
18
24
  /** Only the original in-process final carries this observation; JSON/copies do not recreate it. */
19
25
  export function capturedFinalSession(final: ChildFinal): Readonly<CapturedSessionBranch> | undefined {
@@ -113,6 +119,10 @@ export class ChildFinalCapture {
113
119
  state: "unavailable",
114
120
  reason,
115
121
  ...(this.visible() ? { diagnosticText: this.visible().slice(0, 8192) } : {}),
122
+ // Pi's JSON mode exits 0 after a failed model request; the settled terminal message is the one record of it.
123
+ ...(this.settled && !this.active.size && this.final?.stopReason === "error"
124
+ ? { providerError: true as const }
125
+ : {}),
116
126
  });
117
127
  try {
118
128
  this.buffer += this.decoder.decode();
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Governed children's model usage, as the delegating Pi session accounts it (owner decision 2026-11-17).
3
+ *
4
+ * Pi adds a tool result's `usage` to the session that ran the tool: the persisted tool result message, session
5
+ * statistics, the footer and cost (Pi 0.81.0 and later; read in 1.0.4 and 1.5.2). `delegate`, `delegate_all` and
6
+ * `delegate_chain` report there what their children were observed to spend, so a session that delegates its work
7
+ * does not look cheap. A call that throws reports through Pi's `tool_result` hook instead
8
+ * (`extensions/child-usage-report.ts`). A host without that accounting does not keep the field, and nothing else
9
+ * changes.
10
+ *
11
+ * **Each model call is counted once, at any depth.** A child's own session counts what its delegation results
12
+ * reported, so `activity-session.ts` keeps the two apart: the child's own calls are `usage`, which the ledger
13
+ * records, and what its delegation results reported is `delegated`. Its report to its parent is both, so the root
14
+ * session's total holds every call in the tree once, and summing the ledger over an episode still holds each once.
15
+ *
16
+ * **Coverage is counted, never filled in.** `measured` and `unmeasured` count governed executions in the subtree
17
+ * whose own usage was or was not observed. An unobserved child adds nothing to the total, so a total with
18
+ * `unmeasured > 0` is a lower bound. In a child's session, a delegation result without a record counts as one
19
+ * unmeasured child, because nothing says whether a child ran; so does a delegation call with no result at all (the
20
+ * child stopped while it waited); a record whose usage the host did not keep counts all its children as unmeasured.
21
+ *
22
+ * Every value read back comes from a child's session file: untrusted numbers. A value that is not a non-negative
23
+ * number makes the child's observation invalid. A number beyond `USAGE_CEILINGS`, or one whose addition would take a
24
+ * sum beyond them, is implausible and counts as unmeasured. Children are added one at a time, so only that child is
25
+ * unmeasured and every other one keeps its usage. They describe usage and nothing else; no grant, refusal or limit
26
+ * reads them.
27
+ */
28
+ import type { ChildUsageTotals } from "../governance/ledger-events.ts";
29
+
30
+ /** The tools whose results report children's usage. `delegate_describe` starts nothing. */
31
+ export const DELEGATION_RESULT_TOOLS: ReadonlySet<string> = new Set(["delegate", "delegate_all", "delegate_chain"]);
32
+
33
+ /**
34
+ * The largest value accepted for one usage figure: a child's report, a delegation result read back, or a sum
35
+ * (review of 2026-11-17). Under Daddy's defaults one delegation call's whole subtree runs at most 8 sessions at a time
36
+ * (the fan-out budget) for at most 48 hours (an 8-step chain of 6-hour ceilings): 384 session-hours. A session that
37
+ * re-read a 1M-token context every second, beyond any real agent loop, would use 1.4e12 tokens in that time, $6.9e7
38
+ * at $50 per million tokens; one governed execution a second would be 1.4e6 executions. The ceilings sit above all
39
+ * three. A larger value is a fault or a hostile child: it counts as unmeasured and never reaches Pi's totals, while
40
+ * the ledger still records each execution's own usage as read. An operator who raises those bounds far enough could
41
+ * pass a ceiling legitimately and is then told `unmeasured`, never a wrong total. Below the ceilings a token sum of
42
+ * hundreds of values stays an exact integer, so no sibling's usage is absorbed by another's.
43
+ */
44
+ export const USAGE_CEILINGS = { tokens: 1e13, cost: 1e8, executions: 1e7 } as const;
45
+
46
+ export interface UsageCoverage {
47
+ /** Governed executions in the subtree whose own model usage was observed. */
48
+ measured: number;
49
+ /** Governed executions in the subtree whose usage was not observed and is in no total. */
50
+ unmeasured: number;
51
+ }
52
+ /** A settled child's own calls plus what its own delegation results reported, as far as observed. */
53
+ export interface ObservedChildUsage extends UsageCoverage {
54
+ usage?: ChildUsageTotals;
55
+ }
56
+ /** What a delegation result says in `details.childUsage`, and what its parent reads back. */
57
+ export interface ChildUsageRecord extends UsageCoverage {
58
+ /** Whether the result set Pi's tool-result `usage`: exactly when some child's usage was observed. */
59
+ reported: boolean;
60
+ /**
61
+ * With `reported`: the cost total of the usage it reported, which is the children's alone. Pi adds the usage of
62
+ * the tools a call ran nested to the same persisted result, and a parent-run tool (`scout_research`, run by this
63
+ * session for its child) runs nested in the waiting delegation, so the persisted usage can also hold this session's
64
+ * own calls. The owning session reads its children's share here (integration of 2026-11-17); a parent never reads
65
+ * it back from a child.
66
+ */
67
+ cost?: number;
68
+ coverage: "complete" | "partial" | "unavailable";
69
+ }
70
+
71
+ const TOKEN_FIELDS = ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const;
72
+ const COST_FIELDS = ["input", "output", "cacheRead", "cacheWrite", "total"] as const;
73
+ const NONE: ObservedChildUsage = { measured: 0, unmeasured: 0 };
74
+ const object = (value: unknown): Record<string, unknown> | undefined =>
75
+ value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
76
+ /** NaN fails; Infinity passes here and fails the ceilings. */
77
+ const nonNegative = (value: unknown): value is number => typeof value === "number" && value >= 0;
78
+ const count = (value: unknown): value is number =>
79
+ Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= USAGE_CEILINGS.executions;
80
+
81
+ /** Pi's `Usage` fields this package reads, as a new object, when each is a non-negative number. */
82
+ function usageShape(value: unknown): ChildUsageTotals | undefined {
83
+ const usage = object(value),
84
+ cost = object(usage?.cost);
85
+ if (
86
+ !usage ||
87
+ !cost ||
88
+ !TOKEN_FIELDS.every((field) => nonNegative(usage[field])) ||
89
+ !COST_FIELDS.every((field) => nonNegative(cost[field]))
90
+ )
91
+ return undefined;
92
+ if (usage.reasoning !== undefined && !nonNegative(usage.reasoning)) return undefined;
93
+ return addUsage(undefined, usage as unknown as ChildUsageTotals);
94
+ }
95
+ /** Every field within `USAGE_CEILINGS`; Infinity and NaN are not. */
96
+ function plausible(usage: ChildUsageTotals): boolean {
97
+ return (
98
+ [...TOKEN_FIELDS.map((field) => usage[field]), usage.reasoning ?? 0].every((v) => v <= USAGE_CEILINGS.tokens) &&
99
+ COST_FIELDS.every((field) => usage.cost[field] <= USAGE_CEILINGS.cost)
100
+ );
101
+ }
102
+ /** Pi's `Usage` fields this package reads, validated and within the ceilings; anything else in the value is dropped. */
103
+ export function usageTotals(value: unknown): ChildUsageTotals | undefined {
104
+ const usage = usageShape(value);
105
+ return usage && plausible(usage) ? usage : undefined;
106
+ }
107
+
108
+ /** Field-wise sum; `reasoning` stays absent unless a side reported it. `addObserved` checks the sum is plausible. */
109
+ export function addUsage(left: ChildUsageTotals | undefined, right: ChildUsageTotals): ChildUsageTotals {
110
+ const sum = (a: number | undefined, b: number) => (a ?? 0) + b;
111
+ const reasoning =
112
+ left?.reasoning === undefined && right.reasoning === undefined
113
+ ? undefined
114
+ : sum(left?.reasoning, right.reasoning ?? 0);
115
+ return {
116
+ input: sum(left?.input, right.input),
117
+ output: sum(left?.output, right.output),
118
+ cacheRead: sum(left?.cacheRead, right.cacheRead),
119
+ cacheWrite: sum(left?.cacheWrite, right.cacheWrite),
120
+ ...(reasoning === undefined ? {} : { reasoning }),
121
+ totalTokens: sum(left?.totalTokens, right.totalTokens),
122
+ cost: {
123
+ input: sum(left?.cost.input, right.cost.input),
124
+ output: sum(left?.cost.output, right.cost.output),
125
+ cacheRead: sum(left?.cost.cacheRead, right.cost.cacheRead),
126
+ cacheWrite: sum(left?.cost.cacheWrite, right.cost.cacheWrite),
127
+ total: sum(left?.cost.total, right.cost.total),
128
+ },
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Adds one child to a running total. A child whose usage would take the sum past a ceiling (or make it non-finite)
134
+ * adds all its executions as unmeasured and no usage; the total so far keeps its measured children. Counts stay safe
135
+ * integers: each record is at most `USAGE_CEILINGS.executions` and one session file holds at most 64 MiB of them.
136
+ */
137
+ function addObserved(total: ObservedChildUsage, child: ObservedChildUsage): ObservedChildUsage {
138
+ const usage = child.usage ? addUsage(total.usage, child.usage) : total.usage;
139
+ if (usage && !plausible(usage)) return { ...total, unmeasured: total.unmeasured + child.measured + child.unmeasured };
140
+ return {
141
+ ...(usage ? { usage } : {}),
142
+ measured: total.measured + child.measured,
143
+ unmeasured: total.unmeasured + child.unmeasured,
144
+ };
145
+ }
146
+
147
+ /** A record read back from a child's session; `coverage` is recomputed, never trusted. */
148
+ export function childUsageRecord(value: unknown): Omit<ChildUsageRecord, "coverage"> | undefined {
149
+ const record = object(value);
150
+ if (!record || typeof record.reported !== "boolean" || !count(record.measured) || !count(record.unmeasured))
151
+ return undefined;
152
+ return { reported: record.reported, measured: record.measured, unmeasured: record.unmeasured };
153
+ }
154
+
155
+ /**
156
+ * Adds one of a child's own delegation results, as its session recorded it. Undefined when its usage is not usage
157
+ * at all, which makes the child's whole observation invalid rather than partly counted. Without a usable record the
158
+ * result is one unmeasured child; usage the host did not keep, or beyond the ceilings, leaves the record's children
159
+ * unmeasured; a record that says it reported nothing measured nothing.
160
+ */
161
+ export function addDelegationResult(
162
+ previous: ObservedChildUsage | undefined,
163
+ value: { usage?: unknown; details?: unknown },
164
+ ): ObservedChildUsage | undefined {
165
+ if (value.usage !== undefined && !usageShape(value.usage)) return undefined;
166
+ const usage = usageTotals(value.usage);
167
+ const record = childUsageRecord(object(value.details)?.childUsage);
168
+ const child: ObservedChildUsage = !record
169
+ ? { ...(usage ? { usage } : {}), measured: 0, unmeasured: 1 }
170
+ : record.reported && usage
171
+ ? { usage, measured: record.measured, unmeasured: record.unmeasured }
172
+ : { measured: 0, unmeasured: record.measured + record.unmeasured };
173
+ return addObserved(previous ?? NONE, child);
174
+ }
175
+
176
+ /** Ids of the delegation calls in an assistant message's content; a child's reader matches them to their results. */
177
+ export function delegationCallIds(content: unknown): string[] {
178
+ if (!Array.isArray(content)) return [];
179
+ return content.flatMap((block) => {
180
+ const call = object(block);
181
+ return call?.type === "toolCall" && DELEGATION_RESULT_TOOLS.has(String(call.name)) ? [String(call.id)] : [];
182
+ });
183
+ }
184
+
185
+ /** Delegation calls with no result: the child stopped while each waited, so each is one unmeasured child. */
186
+ export function addUnansweredCalls(
187
+ previous: ObservedChildUsage | undefined,
188
+ calls: number,
189
+ ): ObservedChildUsage | undefined {
190
+ return calls > 0 ? addObserved(previous ?? NONE, { measured: 0, unmeasured: calls }) : previous;
191
+ }
192
+
193
+ /** One settled child: its own calls when observed and plausible, plus what its delegation results reported. */
194
+ export function observedChildUsage(observation: {
195
+ usage?: ChildUsageTotals;
196
+ delegated?: ObservedChildUsage;
197
+ }): ObservedChildUsage {
198
+ const own = usageTotals(observation.usage);
199
+ const self: ObservedChildUsage = own ? { usage: own, measured: 1, unmeasured: 0 } : { measured: 0, unmeasured: 1 };
200
+ return observation.delegated ? addObserved(self, observation.delegated) : self;
201
+ }
202
+
203
+ /**
204
+ * The two tool-result fields: Pi's `usage` when any child's usage was observed, and `details.childUsage`.
205
+ * A reused operation started nothing in this call; the call that ran it already reported its usage.
206
+ */
207
+ export function delegationUsage(
208
+ outcomes: readonly { observedUsage?: ObservedChildUsage; operation?: { reused?: boolean } }[],
209
+ ): { usage?: ChildUsageTotals; childUsage: ChildUsageRecord } {
210
+ let total = NONE;
211
+ for (const { observedUsage, operation } of outcomes)
212
+ if (!operation?.reused && observedUsage) total = addObserved(total, observedUsage);
213
+ const { usage, measured, unmeasured } = total;
214
+ const coverage = unmeasured === 0 ? "complete" : measured > 0 ? "partial" : "unavailable";
215
+ return {
216
+ ...(usage ? { usage } : {}),
217
+ childUsage: {
218
+ reported: usage !== undefined,
219
+ ...(usage ? { cost: usage.cost.total } : {}),
220
+ measured,
221
+ unmeasured,
222
+ coverage,
223
+ },
224
+ };
225
+ }
226
+
227
+ /**
228
+ * One child's attempts together: a replay-safe child that failed is run once more in the same call, and both
229
+ * attempts used the model (integration with the automatic retry, 2026-11-17). Added as two children are, so each
230
+ * attempt counts as one execution; undefined when no attempt was observed at all.
231
+ */
232
+ export function attemptsUsage(...attempts: (ObservedChildUsage | undefined)[]): ObservedChildUsage | undefined {
233
+ const observed = attempts.filter((attempt): attempt is ObservedChildUsage => attempt !== undefined);
234
+ return observed.length === 0 ? undefined : observed.reduce(addObserved, NONE);
235
+ }
236
+
237
+ const thrown = new WeakMap<object, ObservedChildUsage>();
238
+ /** A child that ran and then threw keeps its observation on the error, so a fan-out that reports it can count it. */
239
+ export function withObservedUsage<T>(error: T, usage: ObservedChildUsage): T {
240
+ if (error !== null && typeof error === "object") thrown.set(error, usage);
241
+ return error;
242
+ }
243
+ export function observedUsageOf(error: unknown): ObservedChildUsage | undefined {
244
+ if (error === null || typeof error !== "object") return undefined;
245
+ const own = thrown.get(error);
246
+ if (own || !(error instanceof AggregateError)) return own;
247
+ for (const inner of error.errors) {
248
+ const found = observedUsageOf(inner);
249
+ if (found) return found;
250
+ }
251
+ return undefined;
252
+ }
253
+
254
+ /**
255
+ * The host-side check, read from this Pi session's own record: how many of its delegation results reported child
256
+ * usage, and how many of those the host kept on the persisted tool result, which is what its totals sum. The cost
257
+ * is the children's share of what was kept: the persisted usage also holds any tool the call ran nested, such as a
258
+ * parent-run `scout_research`, and that is this session's own usage, not child usage.
259
+ */
260
+ export function childUsageInSession(
261
+ entries: readonly unknown[],
262
+ ): { results: number; recorded: number; cost: number } | undefined {
263
+ let results = 0,
264
+ recorded = 0,
265
+ cost = 0;
266
+ for (const entry of entries) {
267
+ const message = object(object(entry)?.type === "message" ? object(entry)!.message : undefined);
268
+ if (message?.role !== "toolResult" || !DELEGATION_RESULT_TOOLS.has(String(message.toolName))) continue;
269
+ const record = object(object(message.details)?.childUsage);
270
+ if (!childUsageRecord(record)?.reported) continue;
271
+ results += 1;
272
+ const usage = usageTotals(message.usage);
273
+ if (!usage) continue;
274
+ recorded += 1;
275
+ // A record without its own cost (or one the kept usage cannot hold) leaves the kept usage as the bound.
276
+ const children = record?.cost;
277
+ cost += nonNegative(children) && children <= usage.cost.total ? children : usage.cost.total;
278
+ }
279
+ return results > 0 && Number.isFinite(cost) ? { results, recorded, cost } : undefined;
280
+ }
@@ -1,5 +1,7 @@
1
1
  import { createDispatchOperations } from "./dispatch-operations.ts";
2
2
  import { connectDispatchOperations } from "./dispatch-operation-client.ts";
3
+ import { createParentToolCalls, type ParentToolCalls } from "./parent-tool-calls.ts";
4
+ import { MAX_PARENT_TOOL_REQUEST_CHARS } from "../kernel/parent-tools.ts";
3
5
  /** Root-owned live Auto authority. Descendants receive read/admit access, never mutation access. */
4
6
  import { randomBytes, randomUUID } from "node:crypto";
5
7
  import { chmod, unlink } from "node:fs/promises";
@@ -25,6 +27,8 @@ const validPending = (value: unknown): value is PendingApproval => {
25
27
  export interface AutoModeAuthority extends AutoModeReader {
26
28
  snapshot(): AutoModeSnapshot;
27
29
  set(enabled: boolean, source: AutoModeSource): AutoModeSnapshot;
30
+ /** Running children that may ask this owner to run an allowlisted parent-only tool, and nothing else. */
31
+ readonly parentTools: ParentToolCalls;
28
32
  }
29
33
 
30
34
  export async function createAutoModeAuthority(initial: {
@@ -41,6 +45,7 @@ export async function createAutoModeAuthority(initial: {
41
45
  revision = 0,
42
46
  closed = false;
43
47
  const operations = createDispatchOperations();
48
+ const parentTools = createParentToolCalls();
44
49
  const pending = new Map<string, PendingApproval>();
45
50
  const waiters = new Set<() => void>();
46
51
  const sockets = new Set<Socket>();
@@ -113,14 +118,20 @@ export async function createAutoModeAuthority(initial: {
113
118
  return;
114
119
  }
115
120
  input += chunk;
116
- if (input.length > 4096) {
121
+ // One action carries bounded tool arguments; every other request keeps the 4096-character line.
122
+ if (input.length > MAX_PARENT_TOOL_REQUEST_CHARS) {
117
123
  socket.destroy();
118
124
  return;
119
125
  }
120
126
  if (!input.includes("\n")) return;
121
127
  handled = true;
122
128
  try {
123
- const request = JSON.parse(input.slice(0, input.indexOf("\n")));
129
+ const line = input.slice(0, input.indexOf("\n"));
130
+ const request = JSON.parse(line);
131
+ if (line.length > 4096 && request?.action !== "parent-tool") {
132
+ socket.destroy();
133
+ return;
134
+ }
124
135
  if (request.token !== reference.token || request.ownerId !== reference.ownerId)
125
136
  throw new Error("Unauthorized Auto policy request");
126
137
  assertOpen();
@@ -149,6 +160,10 @@ export async function createAutoModeAuthority(initial: {
149
160
  } else if (request.action === "operation-finish") {
150
161
  operations.finish(request.operationId, request.ticket, request.state, request.runtime);
151
162
  reply({ ok: true });
163
+ } else if (request.action === "parent-tool") {
164
+ // Held like `wait`: the socket closing is the child leaving, and that cancels the call it made.
165
+ socket.setTimeout(0);
166
+ void parentTools.handle(request.call, controller.signal).then((value) => reply({ ok: true, value }));
152
167
  } else throw new Error("Unknown Auto policy action");
153
168
  } catch (error) {
154
169
  reply({ ok: false, error: String(error) });
@@ -176,6 +191,7 @@ export async function createAutoModeAuthority(initial: {
176
191
  const operationAccess = connectDispatchOperations(reference);
177
192
  return {
178
193
  operations: operationAccess,
194
+ parentTools,
179
195
  reference,
180
196
  snapshot,
181
197
  read: async () => snapshot(),
@@ -198,6 +214,7 @@ export async function createAutoModeAuthority(initial: {
198
214
  if (closed) return;
199
215
  closed = true;
200
216
  operationAccess.close();
217
+ parentTools.close();
201
218
  enabled = false;
202
219
  for (const wake of [...waiters]) wake();
203
220
  for (const socket of sockets) socket.destroy();
@@ -4,6 +4,8 @@ import { join } from "node:path";
4
4
  import { readBoundedTextSync } from "../kernel/bounded-read-sync.ts";
5
5
  import { operationArtifactsDir } from "../kernel/project-paths.ts";
6
6
  import { validOperationId, type OperationRequest, type OperationReference } from "../kernel/dispatch-operation.ts";
7
+ import type { AutomaticRetryEligibility } from "../kernel/dispatch-operation.ts";
8
+ import { readAutomaticRetryEligibility, retainAutomaticRetryEligibility } from "./operation-replay.ts";
7
9
  import {
8
10
  MAX_OPERATION_ARTIFACT_BYTES,
9
11
  MAX_OPERATION_MANIFEST_BYTES,
@@ -259,8 +261,17 @@ export function readOperationHistory(
259
261
  bytes: Buffer.byteLength(text),
260
262
  });
261
263
  const content = includeFinal ? readOperationArtifact(artifact, { agentDirectory: directory }) : undefined;
264
+ const { automaticRetryEligibility: _unqualified, ...runtime } = manifest.operation.runtime ?? {};
265
+ const proof = readAutomaticRetryEligibility(path, owner, admission.request, manifest.operation);
266
+ const operation = {
267
+ ...manifest.operation,
268
+ ...(manifest.operation.runtime
269
+ ? { runtime: { ...runtime, ...(proof ? { automaticRetryEligibility: proof } : {}) } }
270
+ : {}),
271
+ artifact,
272
+ };
262
273
  return {
263
- operation: { ...manifest.operation, artifact },
274
+ operation,
264
275
  artifact,
265
276
  requestDigest: admission.request.requestDigest,
266
277
  ...(content?.final ? { final: content.final } : {}),
@@ -276,6 +287,15 @@ export function openOperationArtifacts(agentDirectory: string, owner: OperationA
276
287
  return {
277
288
  owner: Object.freeze({ ...owner }),
278
289
  history,
290
+ retainAutomaticRetry(request: OperationRequest, proof: AutomaticRetryEligibility) {
291
+ requestCheck(request);
292
+ const path = location(directory, owner, request.operationId);
293
+ const admission = admissionAt(path, owner, request.operationId);
294
+ const retained = history(request.operationId, false);
295
+ if (!admission || !sameRequest(admission.request, request) || !retained?.artifact)
296
+ throw Error("automatic retry evidence requires its exact retained owner");
297
+ retainAutomaticRetryEligibility(path, owner, request, retained.operation, proof);
298
+ },
279
299
  admit(request: OperationRequest) {
280
300
  requestCheck(request);
281
301
  request = cleanRequest(request);
@@ -0,0 +1,70 @@
1
+ /** Optional private owner evidence. Older runtimes and ledger readers need not know this file exists. */
2
+ import { join } from "node:path";
3
+ import { readBoundedTextSync } from "../kernel/bounded-read-sync.ts";
4
+ import type { AutomaticRetryEligibility, OperationReference, OperationRequest } from "../kernel/dispatch-operation.ts";
5
+ import type { OperationArtifactOwner } from "../kernel/operation-artifact.ts";
6
+ import { artifactJson, publishArtifact } from "./operation-artifact-io.ts";
7
+
8
+ function eligible(proof: AutomaticRetryEligibility, request: OperationRequest, operation: OperationReference): boolean {
9
+ const runtime = operation.runtime;
10
+ return (
11
+ !!proof &&
12
+ proof.version === 1 &&
13
+ proof.eligible === true &&
14
+ proof.operationId === request.operationId &&
15
+ proof.executionId === request.executionId &&
16
+ operation.operationId === request.operationId &&
17
+ operation.executionId === request.executionId &&
18
+ typeof proof.definitionId === "string" &&
19
+ /^[a-f0-9]{64}$/.test(proof.definitionId) &&
20
+ Object.keys(proof).sort().join(",") === "definitionId,eligible,executionId,operationId,version" &&
21
+ runtime?.work !== "succeeded" &&
22
+ runtime?.control !== "failed" &&
23
+ runtime?.final?.state !== "complete" &&
24
+ ((operation.state === "settled" &&
25
+ runtime?.cleanup?.state === "settled" &&
26
+ runtime.cleanup.executionId === operation.executionId) ||
27
+ (operation.state === "not-started" && runtime?.cleanup?.state === "not-started"))
28
+ );
29
+ }
30
+
31
+ /** Called only after the owner has successfully settled and retained this exact failed execution. */
32
+ export function retainAutomaticRetryEligibility(
33
+ path: string,
34
+ owner: OperationArtifactOwner,
35
+ request: OperationRequest,
36
+ operation: OperationReference,
37
+ proof: AutomaticRetryEligibility,
38
+ ): void {
39
+ if (!eligible(proof, request, operation)) throw Error("automatic retry evidence does not match its terminal owner");
40
+ publishArtifact(
41
+ path,
42
+ "automatic-retry.json",
43
+ artifactJson({ version: 1, owner, requestDigest: request.requestDigest, eligibility: proof }),
44
+ );
45
+ }
46
+
47
+ /** Missing or unusable optional evidence disables automatic replay, without hiding the original result. */
48
+ export function readAutomaticRetryEligibility(
49
+ path: string,
50
+ owner: OperationArtifactOwner,
51
+ request: OperationRequest,
52
+ operation: OperationReference,
53
+ ): AutomaticRetryEligibility | undefined {
54
+ try {
55
+ const record = JSON.parse(
56
+ readBoundedTextSync(join(path, "automatic-retry.json"), { maxBytes: 4096, confinedRoot: path }).text,
57
+ );
58
+ if (
59
+ record.version !== 1 ||
60
+ record.owner?.sessionId !== owner.sessionId ||
61
+ record.owner?.cwd !== owner.cwd ||
62
+ record.requestDigest !== request.requestDigest ||
63
+ !eligible(record.eligibility, request, operation)
64
+ )
65
+ return undefined;
66
+ return record.eligibility;
67
+ } catch {
68
+ return undefined;
69
+ }
70
+ }