pi-daddy 0.59.1 → 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 +12 -0
  2. package/README.md +101 -19
  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 +17 -1
  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 +16 -0
  97. package/extensions/session.ts +9 -0
  98. package/extensions/spawn-summary.ts +31 -0
  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
@@ -1,5 +1,5 @@
1
1
  /** Non-authorizing dispatch election. The elected caller still runs the ordinary governance path. */
2
- import { claimWithArtifact, retainOperationArtifact } from "./delegation-artifacts.ts";
2
+ import { claimWithArtifact, retainOperationArtifact, retainOperationRetryEligibility } from "./delegation-artifacts.ts";
3
3
  import { openOperationArtifacts, type OperationArtifactStore } from "../src/governance/operation-artifacts.ts";
4
4
  import type { OperationArtifactRef } from "../src/kernel/operation-artifact.ts";
5
5
  import type { DashboardResultDescription } from "../src/kernel/dashboard-observation.ts";
@@ -13,7 +13,7 @@ import { planDelegation } from "../src/kernel/delegate.ts";
13
13
  import type { OperationClaim, OperationReference } from "../src/kernel/dispatch-operation.ts";
14
14
  import { validOperationId } from "../src/kernel/dispatch-operation.ts";
15
15
  import { GovernanceRefusal } from "../src/kernel/refusals.ts";
16
- import { assertDefinitionIdentity } from "./definition-describe.ts";
16
+ import { assertDefinitionIdentity, type DefinitionBinding } from "./definition-describe.ts";
17
17
  import { assertDelegationAuthority } from "./delegation-authority.ts";
18
18
  import { recordDelegationDecision } from "./delegation-ledger.ts";
19
19
  import type { GrantsSession } from "./session.ts";
@@ -130,6 +130,8 @@ export async function claimDelegationOperation(
130
130
  ids: ExecutionOccurrenceIds,
131
131
  ctx: DelegationToolContext,
132
132
  signal?: AbortSignal,
133
+ /** Trusted: bound by the calling tool from its own arguments and the session's describe memory; wording only. */
134
+ definitionBinding?: DefinitionBinding,
133
135
  ): Promise<OperationClaim | undefined> {
134
136
  const operationScope = session.reloadLifecycle?.operationFinals;
135
137
  const operationId = spec.operation_id;
@@ -138,8 +140,8 @@ export async function claimDelegationOperation(
138
140
  if (!validOperationId(operationId)) throw Error("Invalid operation_id");
139
141
  if (signal?.aborted) throw Error("Operation request aborted");
140
142
  await session.ensureDefinitions?.();
141
- assertDefinitionIdentity(session, spec);
142
- const context = await session.delegationContext();
143
+ assertDefinitionIdentity(session, spec, definitionBinding?.source);
144
+ const context = { ...(await session.delegationContext()), ...session.parentToolContext?.(ctx) };
143
145
  const model = spec.model ?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined);
144
146
  const preview = planDelegation(
145
147
  { ...spec, model, boundWorkspaceId: spec.workspace?.workspace_id },
@@ -158,29 +160,43 @@ export async function claimDelegationOperation(
158
160
  if (!operations) throw Error("Session operation admission is unavailable; no dispatch started");
159
161
  const cwd = await realpath(ctx.cwd);
160
162
  // A display-only caption may change when resuming the very same task.
161
- const { operation_id: _id, dashboardSummary: _caption, ...request } = spec;
162
- const requestDigest = createHash("sha256")
163
- .update(
164
- JSON.stringify(
165
- canonical({
166
- request,
167
- cwd,
168
- model,
169
- piThinking: session.currentThinking?.(),
170
- definitionDigest: preview.definitionDigest,
171
- grant: [...session.ownGrant].sort(),
172
- gated: [...session.gated].sort(),
173
- depth: session.depth,
174
- maxDepth: session.maxDepth,
175
- executor: session.executor.kind,
176
- definition: spec.agent ? session.definitions.get(spec.agent)?.body : null,
177
- runtimeSettings: session.definitionRuntimeSettings,
178
- runtimeOverrides: [...session.definitionRuntimeOverrides.entries()].sort(([a], [b]) => a.localeCompare(b)),
179
- workspaceRoot: spec.workspace ? session.workspacePin?.get(spec.workspace.workspace_id) : null,
180
- }),
181
- ),
182
- )
183
- .digest("hex");
163
+ const { operation_id: _id, dashboardSummary: _caption, ...asked } = spec;
164
+ // Digest the selected definition's ID, not how the call got one (supplied, filled from a describe, or omitted):
165
+ // the identity check above proved any ID present equals it. Describe memory then cannot turn an identical retry
166
+ // into a conflict, and a changed selected definition is a different request.
167
+ const request = {
168
+ ...asked,
169
+ definitionId: spec.agent ? session.definitions.get(spec.agent)?.definitionId : undefined,
170
+ };
171
+ const digest = (request: typeof asked) =>
172
+ createHash("sha256")
173
+ .update(
174
+ JSON.stringify(
175
+ canonical({
176
+ request,
177
+ cwd,
178
+ model,
179
+ piThinking: session.currentThinking?.(),
180
+ definitionDigest: preview.definitionDigest,
181
+ grant: [...session.ownGrant].sort(),
182
+ gated: [...session.gated].sort(),
183
+ depth: session.depth,
184
+ maxDepth: session.maxDepth,
185
+ executor: session.executor.kind,
186
+ definition: spec.agent ? session.definitions.get(spec.agent)?.body : null,
187
+ runtimeSettings: session.definitionRuntimeSettings,
188
+ runtimeOverrides: [...session.definitionRuntimeOverrides.entries()].sort(([a], [b]) =>
189
+ a.localeCompare(b),
190
+ ),
191
+ workspaceRoot: spec.workspace ? session.workspacePin?.get(spec.workspace.workspace_id) : null,
192
+ }),
193
+ ),
194
+ )
195
+ .digest("hex");
196
+ const requestDigest = digest(request);
197
+ const definition = spec.agent ? session.definitions.get(spec.agent) : undefined;
198
+ const { definitionId: _definitionId, ...legacyRequest } = asked;
199
+ const legacyRequestDigest = definition && !definition.binding ? digest(legacyRequest) : undefined;
184
200
  const identity = {
185
201
  operationId,
186
202
  requestDigest,
@@ -190,10 +206,14 @@ export async function claimDelegationOperation(
190
206
  };
191
207
  const agent = spec.agent && /^[a-z][a-z0-9_-]{0,48}$/i.test(spec.agent) ? spec.agent : undefined;
192
208
  const summary = dashboardContentEnabled(process.env) ? safeDashboardSummary(spec.dashboardSummary) : undefined;
193
- return claimWithArtifact(session, identity, () => operations.claim(identity, signal), operationScope, {
194
- agent,
195
- summary,
196
- });
209
+ return claimWithArtifact(
210
+ session,
211
+ identity,
212
+ () => operations.claim(identity, signal),
213
+ operationScope,
214
+ { agent, summary },
215
+ legacyRequestDigest,
216
+ );
197
217
  };
198
218
  if (!denied) return elect();
199
219
 
@@ -235,8 +255,16 @@ export function existingOperationOutcome(claim: OperationClaim, depth: number):
235
255
  `No new child started. Operation ${claim.operation.operationId} already exists (${claim.operation.state}), execution ${claim.operation.executionId}. ` +
236
256
  (active
237
257
  ? "Follow the original operation; this reference is not its final result."
238
- : "No mutation result was replayed. Inspect the original outcome before an intentional new attempt with a new operation_id."),
239
- reason: active ? "existing-operation" : "operation-already-ended",
258
+ : claim.legacyResult
259
+ ? "Historical completed result from before the definition-binding update. " +
260
+ "The old record did not capture the full definition identity; this is not new execution or current approval.\n\n" +
261
+ claim.legacyResult.text
262
+ : "No mutation result was replayed. Inspect the original outcome before an intentional new attempt with a new operation_id."),
263
+ reason: active
264
+ ? "existing-operation"
265
+ : claim.legacyResult
266
+ ? "legacy-completed-operation"
267
+ : "operation-already-ended",
240
268
  granted: [],
241
269
  depth,
242
270
  exitCode: null,
@@ -248,6 +276,7 @@ export async function finishDelegationOperation(
248
276
  result: DelegationOutcome,
249
277
  session: GrantsSession,
250
278
  finalScope: object | undefined,
279
+ boundDefinitionId?: string,
251
280
  ) {
252
281
  const cleanup = result.cleanup;
253
282
  const state: OperationReference["state"] =
@@ -305,6 +334,15 @@ export async function finishDelegationOperation(
305
334
  : {}),
306
335
  });
307
336
  await claim.finish!(state, runtime);
337
+ if (result.replayable && boundDefinitionId) {
338
+ retainOperationRetryEligibility(claim, {
339
+ version: 1,
340
+ eligible: true,
341
+ operationId: claim.operation.operationId,
342
+ executionId: claim.operation.executionId,
343
+ definitionId: boundDefinitionId,
344
+ });
345
+ }
308
346
  retainOperationFinal(session, claim, result, finalScope);
309
347
  result.operation = {
310
348
  ...claim.operation,
@@ -2,9 +2,12 @@ import { dashboardSummaryDescription } from "../src/products/activity-summary.ts
2
2
  import { operationIdShape, claimDelegationOperation } from "./delegation-operations.ts";
3
3
  import { publicEvidenceCall } from "./public-evidence.ts";
4
4
  import { executionEvidenceContent } from "./execution-evidence.ts";
5
+ import { delegationUsage } from "../src/executors/child-usage.ts";
6
+ import { childUsageReport } from "./child-usage-report.ts";
5
7
  import { reconcileDelegationCapacity, reserveDelegationCapacity } from "./session-capacity.ts";
6
8
  import {
7
9
  assertDefinitionInputsBeforeAdmission,
10
+ bindDescribedDefinitions,
8
11
  definitionIdDescription,
9
12
  registerDefinitionDescribe,
10
13
  } from "./definition-describe.ts";
@@ -22,6 +25,8 @@ import {
22
25
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
23
26
  import { Type } from "typebox";
24
27
  import { maySpawnDefinition } from "../src/kernel/delegate.ts";
28
+ import { ceilingForDefinition } from "../src/kernel/definitions.ts";
29
+ import { childToolDeliveryRefusal, type ChildToolSource } from "../src/kernel/child-tools.ts";
25
30
  import { MAX_CHILDREN_PER_CALL, splitBudget } from "../src/kernel/fanout.ts";
26
31
  import {
27
32
  PAINT_INTERVAL_MS,
@@ -134,7 +139,8 @@ export interface DelegationRegistration {
134
139
  *
135
140
  * Must be called once the session knows the answer — `session_start` loads the definitions, and the first
136
141
  * provider request tightens `ownGrant`. Both change the list, and neither has happened when the tools are
137
- * registered. See R-39: without this the answer is permanently `none`.
142
+ * registered. See R-39: without this the answer is permanently `none`. Each call also re-reads the child-tool
143
+ * inventory, which lacks Daddy's own tools until they are registered.
138
144
  */
139
145
  refreshSpawnable: () => void;
140
146
  }
@@ -148,14 +154,57 @@ export interface DelegationRegistration {
148
154
  */
149
155
  export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession): DelegationRegistration {
150
156
  /**
151
- * Definitions this session is actually authorised to spawn (ADR-0017), for the tool description.
157
+ * Definitions this session is actually authorised to spawn (ADR-0017) and whose declared tools a governed
158
+ * child can load, for the tool description.
152
159
  *
153
160
  * Listing all of them would tell the model it can spawn things every attempt at which is refused — the
154
161
  * R-28 shape again, a description disagreeing with the enforcer. Computed from the same
155
- * `maySpawnDefinition` the planner uses.
162
+ * `maySpawnDefinition` the planner uses, and from the same `childToolDeliveryRefusal` over the inputs
163
+ * `session.delegationContext` hands it: the tool inventory, the extension path, and the parent-run facts
164
+ * (depth, owner channel and the inventory preview of tools this root can run for a child). The planner's
165
+ * per-call `context:` handling adds and removes no tool name, so the declared ceiling alone decides delivery.
166
+ * One parent-run condition is per delegation: the child's model must be the root's own. The preview leaves
167
+ * it to dispatch (`rootModel: "preview"`), so a definition is listed when a delegation that keeps this
168
+ * session's model would be admitted, and a delegation on another model is refused with the reason.
169
+ *
170
+ * Both filters only remove names. This runs inside `session_start`, `ensureDefinitions` and the
171
+ * provider-request hook, so the delivery filter must not throw: Pi's `getAllTools` asserts a bound, live
172
+ * runtime, and an unreadable inventory falls back to the planner's own unobserved rule (native tools,
173
+ * nothing external). A ceiling that cannot be read is not offered. The planner re-reads the inventory at
174
+ * dispatch and remains the enforcer.
156
175
  */
157
- const spawnable = () =>
158
- [...session.definitions.keys()].filter((name) => maySpawnDefinition(session.ownGrant, name)).sort();
176
+ const spawnable = () => {
177
+ let childToolSources: readonly ChildToolSource[] | undefined;
178
+ try {
179
+ childToolSources = session.childToolSources?.();
180
+ } catch {
181
+ // Left unobserved, as for a caller that supplies no inventory.
182
+ }
183
+ let parentRun: ReturnType<NonNullable<GrantsSession["parentToolContext"]>> | undefined;
184
+ try {
185
+ parentRun = session.parentToolContext?.();
186
+ } catch {
187
+ // None offered: the planner's preview reads the same inventory and fails the same way.
188
+ }
189
+ const delivery = {
190
+ childToolSources,
191
+ extensionPath: session.extensionPath,
192
+ depth: session.depth,
193
+ autoModeRef: session.autoMode?.reference,
194
+ ...parentRun,
195
+ };
196
+ const deliverable = (definition: Parameters<typeof ceilingForDefinition>[0]) => {
197
+ try {
198
+ return !childToolDeliveryRefusal(ceilingForDefinition(definition).capabilities, delivery);
199
+ } catch {
200
+ return false; // An unreadable ceiling is not offered; dispatch fails on the same read.
201
+ }
202
+ };
203
+ return [...session.definitions]
204
+ .filter(([name, definition]) => maySpawnDefinition(session.ownGrant, name) && deliverable(definition))
205
+ .map(([name]) => name)
206
+ .sort();
207
+ };
159
208
 
160
209
  /**
161
210
  * **R-39.** This used to be computed once, right here, and it was always `[]`.
@@ -175,7 +224,7 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
175
224
  */
176
225
  const describeAgent = (names: string[]) =>
177
226
  `Name of a definition to spawn — its allowed-tools become the grant and its instructions ` +
178
- `become the sub-agent's system prompt. Copy this together with definitionId from delegate_describe.delegationArguments. ` +
227
+ `become the sub-agent's system prompt. delegate_describe binds its definitionId. ` +
179
228
  `Available: ${names.join(", ") || "none"}.`;
180
229
 
181
230
  const correlationShape = buildCorrelationShape();
@@ -257,14 +306,21 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
257
306
  parameters: delegateParams,
258
307
  prepareArguments: withoutRetiredDelegationArguments,
259
308
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
309
+ // Reported through Pi's tool_result hook if this call throws after its child ran (2026-11-17).
310
+ const usageReport = childUsageReport(session, _toolCallId);
260
311
  assertDelegationAuthority(session);
261
312
  await session.ensureDefinitions?.();
262
- assertDefinitionInputsBeforeAdmission(session, [params]);
313
+ // The call's own definitionId, else this session's last describe of the agent; checked the same way.
314
+ const bound = bindDescribedDefinitions(session, [params]);
315
+ const [spec] = bound.specs;
316
+ const [definitionBinding] = bound.bindings;
317
+ assertDefinitionInputsBeforeAdmission(session, bound.specs, bound.bindings);
263
318
  // ADR-0032: one child, same block. `_onUpdate` was discarded here, so a delegation showed the bare word
264
319
  // `delegate` for up to DEFAULT_TIMEOUT_MS — sixty minutes by default.
265
320
  const progress = progressReporter(session, [params.agent ?? "delegate"], onUpdate as never);
266
321
  const occurrence = newDelegationOccurrence(session, 0);
267
- const operationClaim = await claimDelegationOperation(session, params, occurrence, ctx, signal);
322
+ const operationClaim = await claimDelegationOperation(session, spec, occurrence, ctx, signal, definitionBinding);
323
+ // Public capture keeps the caller's own request; the bound ID is in details.
268
324
  const capture = publicEvidenceCall(
269
325
  session.publicEvidence,
270
326
  _toolCallId,
@@ -272,11 +328,11 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
272
328
  [params],
273
329
  [operationClaim?.operation.executionId ?? occurrence.executionId],
274
330
  );
275
- const outcome = await runOneDelegation(
331
+ const running = runOneDelegation(
276
332
  session,
277
333
  {
278
334
  operation_id: params.operation_id,
279
- definitionId: params.definitionId,
335
+ definitionId: spec.definitionId,
280
336
  task: params.task,
281
337
  dashboardSummary: params.dashboardSummary,
282
338
  agent: params.agent,
@@ -294,11 +350,13 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
294
350
  signal,
295
351
  {
296
352
  operationClaim,
353
+ definitionBinding,
297
354
  onProgress: progress.sink(0),
298
355
  toolCallId: _toolCallId,
299
356
  onDefinition: (definition) => capture.selected(0, definition),
300
357
  },
301
358
  );
359
+ const outcome = await usageReport.settle(running);
302
360
  progress.settle([outcome]);
303
361
 
304
362
  if (isCriticalAssuranceBlock(outcome)) throw new Error(outcome.text);
@@ -310,8 +368,11 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
310
368
  }
311
369
  // Pi 1.0.4 preserves returned isError. Keep every outcome dimension and useful output together.
312
370
  const failed = !outcome.operation?.reused && (!outcome.ok || outcome.control === "failed");
371
+ // Pi adds `usage` to this session's totals; `details.childUsage` says what it covers (2026-11-17).
372
+ const { usage, childUsage } = delegationUsage([outcome]);
313
373
  return capture.finish(
314
374
  {
375
+ ...(usage ? { usage } : {}),
315
376
  isError: failed,
316
377
  content: [
317
378
  {
@@ -322,7 +383,7 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
322
383
  },
323
384
  executionEvidenceContent("delegate", [outcome], 1),
324
385
  ],
325
- details: outcome,
386
+ details: { ...outcome, childUsage },
326
387
  },
327
388
  [outcome],
328
389
  );
@@ -357,18 +418,22 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
357
418
  parameters: delegateAllParams,
358
419
  prepareArguments: withoutRetiredDelegationArguments,
359
420
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
421
+ const usageReport = childUsageReport(session, _toolCallId);
360
422
  assertDelegationAuthority(session);
361
423
  const children = params.children ?? [];
362
424
  // Correctable definition inputs must not consume earlier siblings' operation IDs.
363
425
  await session.ensureDefinitions?.();
364
- assertDefinitionInputsBeforeAdmission(session, children);
426
+ const bound = bindDescribedDefinitions(session, children);
427
+ assertDefinitionInputsBeforeAdmission(session, bound.specs, bound.bindings);
365
428
  if (session.capacityRefusal) throw new GovernanceRefusal(session.capacityRefusal);
366
429
  await reconcileDelegationCapacity(session);
367
430
  const occurrences = children.map((_, index) => newDelegationOccurrence(session, index));
368
431
  const claims: Array<import("../src/kernel/dispatch-operation.ts").OperationClaim | undefined> = [];
369
432
  try {
370
- for (const [index, child] of children.entries())
371
- claims.push(await claimDelegationOperation(session, child, occurrences[index], ctx, signal));
433
+ for (const [index, child] of bound.specs.entries())
434
+ claims.push(
435
+ await claimDelegationOperation(session, child, occurrences[index], ctx, signal, bound.bindings[index]),
436
+ );
372
437
  } catch (error) {
373
438
  await Promise.all(claims.map((claim) => claim?.finish?.("not-started")));
374
439
  throw error;
@@ -405,7 +470,7 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
405
470
  children,
406
471
  occurrences.map((row, index) => claims[index]?.operation.executionId ?? row.executionId),
407
472
  );
408
- const pending = children.map(async (child, index): Promise<DelegationOutcome> => {
473
+ const pending = bound.specs.map(async (child, index): Promise<DelegationOutcome> => {
409
474
  let enteredDelegation = false;
410
475
  try {
411
476
  // Reserve each batch share synchronously here, before another dispatch can interleave.
@@ -415,6 +480,7 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
415
480
  enteredDelegation = true;
416
481
  return await runOneDelegation(session, child, occurrences[index], split.perChild, ctx, signal, {
417
482
  operationClaim: claims[index],
483
+ definitionBinding: bound.bindings[index],
418
484
  capacityReservation,
419
485
  onDefinition: (definition) => capture.selected(index, definition),
420
486
  onProgress: progress.sink(index),
@@ -428,6 +494,8 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
428
494
  }
429
495
  });
430
496
  const outcomes = await Promise.all(pending);
497
+ // Both throws below follow children that ran: a vetoed child's siblings, or every child failed after running.
498
+ usageReport.add(...outcomes);
431
499
  progress.settle(outcomes);
432
500
  // The upstream controller's verdict outranks our own infrastructure noise — it is the answer the
433
501
  // caller is waiting for, and ADR-0034 requires it to pass through unchanged. But an infrastructure
@@ -443,8 +511,10 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
443
511
  if (failed.length === children.length && outcomes.every((o) => !o.work && !o.final && !o.cleanup))
444
512
  throw totalFanoutFailure(failed, `fan-out failed: every child was refused or failed.\n\n${report}`);
445
513
 
514
+ const { usage, childUsage } = delegationUsage(outcomes);
446
515
  return capture.finish(
447
516
  {
517
+ ...(usage ? { usage } : {}),
448
518
  isError: outcomes.some((o) => !o.operation?.reused && (!o.ok || o.control === "failed")),
449
519
  content: [
450
520
  { type: "text", text: report },
@@ -458,6 +528,7 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
458
528
  granted: outcomes.map((o) => o.granted),
459
529
  refusals: outcomes.map((o) => o.refusal ?? null),
460
530
  retention: outcomes.map((o) => o.retention ?? null),
531
+ childUsage,
461
532
  },
462
533
  },
463
534
  outcomes,
@@ -28,6 +28,8 @@ import { CHILD_ATTRIBUTION_ENV_KEYS, ENV_EPISODE_ID } from "../src/kernel/env-na
28
28
  import { releaseDelegationWorkspace, type PreparedWorkspace } from "./workspace-runtime.ts";
29
29
  import { ActivityTimelineRecorder, ENV_ACTIVITY_PARENT_TASK } from "../src/products/activity-timeline.ts";
30
30
  import { resolvedModelOf, type ResolvedDefinitionRuntime } from "./definition-runtime.ts";
31
+ import { openParentTools, type ParentToolHost, type ParentToolSession } from "./parent-tool-host.ts";
32
+ import { observedChildUsage, withObservedUsage, type ObservedChildUsage } from "../src/executors/child-usage.ts";
31
33
  export interface DelegationOutcome {
32
34
  operation?: import("../src/kernel/dispatch-operation.ts").OperationReference & { reused: boolean };
33
35
  cwd?: string;
@@ -44,6 +46,8 @@ export interface DelegationOutcome {
44
46
  aborted?: boolean;
45
47
  truncated?: boolean;
46
48
  spawnFailed?: boolean;
49
+ /** The executor's own launch failure, kept so a transient one can be told from a configuration fault. */
50
+ spawnError?: string;
47
51
  retention?: RetentionStatus;
48
52
  /** A loud best-effort post-execution observation failure; execution ownership is still settled. */
49
53
  control?: "failed";
@@ -53,6 +57,29 @@ export interface DelegationOutcome {
53
57
  observation?: { state: "complete" | "incomplete"; reasons: string[] };
54
58
  diagnostics?: string;
55
59
  diagnosticsTruncated?: boolean;
60
+ /** The definitionId the identity check used and whether the call supplied it or Daddy remembered it. */
61
+ definitionBinding?: import("./definition-describe.ts").DefinitionBinding;
62
+ /**
63
+ * This child's model usage and its delegations', as observed at settlement; reported to the parent session. After
64
+ * an automatic retry it covers both attempts (`retry.first` keeps the first attempt's own).
65
+ */
66
+ observedUsage?: ObservedChildUsage;
67
+ /**
68
+ * The automatic retry of a replay-safe child (decision of 2026-11-17). Present only when the retry ran; this
69
+ * outcome is then the second attempt's, `executionId` names it and `first` keeps the first attempt complete.
70
+ */
71
+ retry?: {
72
+ attempts: 2;
73
+ firstFailure: import("../src/kernel/replay-safe.ts").ReplayFailure;
74
+ executionId: string;
75
+ first: DelegationOutcome;
76
+ };
77
+ /**
78
+ * A failed replay-safe attempt under a stable operation that passed every other retry guard (decision of
79
+ * 2026-11-17, "Principal retries once"). Daddy did not retry it; the operation's owner may, once, under a new
80
+ * operation. Never set on a success, a retry, a reused reference or when any guard refused.
81
+ */
82
+ replayable?: true;
56
83
  }
57
84
  /**
58
85
  * The upstream controller's token, honoured ONLY when the child otherwise exited cleanly non-zero.
@@ -133,20 +160,30 @@ export interface ChildExecutionInput {
133
160
  parentExecutionId: string | null;
134
161
  toolCallId?: string;
135
162
  cwd: string;
163
+ /** The waiting delegation's own tool context, which runs the plan's parent-run tools (2026-11-17). */
164
+ parentToolHost?: ParentToolHost;
136
165
  preparedWorkspace?: PreparedWorkspace;
137
166
  resolvedRuntime?: ResolvedDefinitionRuntime;
138
167
  signal?: AbortSignal;
139
168
  onProgress?: (update: ChildProgressUpdate) => void;
169
+ /** Epoch ms no deadline may pass: a retry inherits its first attempt's wall-clock deadline (2026-11-17). */
170
+ deadlineAt?: number;
171
+ /** Composition-only observation of the wall-clock deadline this execution recorded. */
172
+ onDeadline?: (deadlineAt: number) => void;
140
173
  }
141
174
  export async function executePlannedChild(input: ChildExecutionInput): Promise<DelegationOutcome> {
142
175
  let executorEntered = false;
143
176
  const runtime = input.session.reloadLifecycle?.runtimeSettlement;
144
177
  let registered = false;
178
+ let parentTools: ParentToolSession | undefined;
145
179
  try {
146
180
  const limits = childExecutionLimits(input.session);
147
181
  input = { ...input, cwd: await realpath(input.preparedWorkspace?.workspace.root ?? input.cwd) };
148
182
  runtime?.begin(input.executionId);
149
183
  registered = Boolean(runtime);
184
+ // Registered before the child exists and closed once it has settled, on every path: an unknown or finished
185
+ // child is refused, and a call still in flight when it settles is cancelled. A refusal here starts nothing.
186
+ parentTools = openParentTools(input.session, input.plan, input.executionId, input.parentToolHost);
150
187
  const result = await executePreparedChild(
151
188
  input,
152
189
  () => {
@@ -155,7 +192,8 @@ export async function executePlannedChild(input: ChildExecutionInput): Promise<D
155
192
  },
156
193
  runtime,
157
194
  limits,
158
- );
195
+ parentTools,
196
+ ).finally(() => parentTools?.close());
159
197
  try {
160
198
  await runtime?.finish(
161
199
  input.executionId,
@@ -220,6 +258,7 @@ async function executePreparedChild(
220
258
  onExecutorEntry: () => void,
221
259
  runtime: import("../src/governance/runtime-settlement.ts").RuntimeSettlement | undefined,
222
260
  limits: ReturnType<typeof childExecutionLimits>,
261
+ parentTools?: ParentToolSession,
223
262
  ): Promise<DelegationOutcome> {
224
263
  const { session, plan, childId, executionId, parentExecutionId, preparedWorkspace, signal, onProgress } = input;
225
264
  const ledgerPath = session.ledgerPath;
@@ -271,7 +310,11 @@ async function executePreparedChild(
271
310
  );
272
311
  activityStarted = true;
273
312
  } catch {}
274
- const configuredTimeoutMs = limits.wallMs;
313
+ // A retry gets only what remains of its first attempt's deadline; the recorded deadline below is clamped to it too.
314
+ const configuredTimeoutMs =
315
+ input.deadlineAt === undefined
316
+ ? limits.wallMs
317
+ : Math.max(1, Math.min(limits.wallMs, input.deadlineAt - Date.now()));
275
318
  // PR 3e: the working bound is inactivity; `deadlineAt` below is the runaway ceiling. Every child gets a pi session
276
319
  // file so the parent can see it working when its stdout is quiet (pi appends each message and tool result to it).
277
320
  const configuredIdleMs = limits.idleMs;
@@ -312,10 +355,17 @@ async function executePreparedChild(
312
355
  activitySession.probe(),
313
356
  childPid === undefined ? undefined : processTreeActivity(childPid),
314
357
  ]);
315
- return file === undefined && tree === undefined ? undefined : `${file ?? "-"}|${tree ?? "-"}`;
358
+ // A child waiting on its parent to run a tool is working, not idle. Its wall-clock bound still applies.
359
+ const waiting = parentTools ? `|${parentTools.activity()}` : "";
360
+ return file === undefined && tree === undefined && !waiting
361
+ ? undefined
362
+ : `${file ?? "-"}|${tree ?? "-"}${waiting}`;
316
363
  };
317
364
  const startedAt = new Date();
318
- const deadlineAt = new Date(startedAt.getTime() + configuredTimeoutMs).toISOString();
365
+ const deadlineAt = new Date(
366
+ Math.min(startedAt.getTime() + configuredTimeoutMs, input.deadlineAt ?? Number.POSITIVE_INFINITY),
367
+ ).toISOString();
368
+ input.onDeadline?.(Date.parse(deadlineAt));
319
369
  if (ledgerPath) {
320
370
  try {
321
371
  await appendLedgerEvent(
@@ -436,7 +486,7 @@ async function executePreparedChild(
436
486
  },
437
487
  command: "pi",
438
488
  args,
439
- env: mergeChildEnv(process.env, plan.env),
489
+ env: mergeChildEnv(process.env, parentTools ? { ...plan.env, ...parentTools.env } : plan.env),
440
490
  cwd,
441
491
  signal: executionSignal,
442
492
  // SIGTERM gets only grace that fits INSIDE the recorded deadline. The independent hard timer
@@ -607,6 +657,7 @@ async function executePreparedChild(
607
657
  : "CHILD_EXIT_NONZERO";
608
658
  const failed: DelegationOutcome = {
609
659
  ok: false,
660
+ observedUsage: observedChildUsage(usageObservation),
610
661
  work: workFailed ? "failed" : final?.state === "complete" ? "succeeded" : "unknown",
611
662
  ...(final ? { final } : {}),
612
663
  ...(cleanup ? { cleanup } : {}),
@@ -623,6 +674,7 @@ async function executePreparedChild(
623
674
  aborted: output.aborted,
624
675
  truncated: output.truncated,
625
676
  spawnFailed: Boolean(output.spawnError),
677
+ ...(output.spawnError ? { spawnError: output.spawnError } : {}),
626
678
  };
627
679
  await teardown();
628
680
  return withTeardownNotes(failed);
@@ -630,6 +682,7 @@ async function executePreparedChild(
630
682
 
631
683
  const succeeded: DelegationOutcome = {
632
684
  ok: true,
685
+ observedUsage: observedChildUsage(usageObservation),
633
686
  work: "succeeded",
634
687
  ...(final ? { final } : {}),
635
688
  ...(cleanup ? { cleanup } : {}),
@@ -718,7 +771,10 @@ async function executePreparedChild(
718
771
  // Attached, not dropped. `withTeardownNotes` was applied on both return paths and neither throw path,
719
772
  // so a failed lease-release record — the thing that makes the NEXT owner report a phantom crash — was
720
773
  // collected into an array nothing read.
721
- throw errorWithTeardownNotes(error, [...controlFailures, ...teardownFailures]);
774
+ throw withObservedUsage(
775
+ errorWithTeardownNotes(error, [...controlFailures, ...teardownFailures]),
776
+ observedChildUsage(usageObservation),
777
+ );
722
778
  }
723
779
  /**
724
780
  * Surfaces a teardown failure WITHOUT discarding the result. The child already ran; telling the