pi-daddy 0.59.1 → 0.61.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 (129) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +126 -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 +20 -0
  46. package/dist/kernel/env-names.d.ts.map +1 -1
  47. package/dist/kernel/env-names.js +27 -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 +10 -1
  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 +28 -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-screen.js +1 -1
  69. package/dist/products/dashboard-screen.js.map +1 -1
  70. package/dist/products/dashboard-session-client.d.ts +9 -0
  71. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  72. package/dist/products/dashboard-session-client.js +3 -1
  73. package/dist/products/dashboard-session-client.js.map +1 -1
  74. package/dist/products/dashboard-settings.d.ts +12 -2
  75. package/dist/products/dashboard-settings.d.ts.map +1 -1
  76. package/dist/products/dashboard-settings.js +19 -2
  77. package/dist/products/dashboard-settings.js.map +1 -1
  78. package/dist/products/episode-report.d.ts +2 -0
  79. package/dist/products/episode-report.d.ts.map +1 -1
  80. package/dist/products/episode-report.js +5 -1
  81. package/dist/products/episode-report.js.map +1 -1
  82. package/extensions/chain-plan.ts +6 -1
  83. package/extensions/child-usage-report.ts +77 -0
  84. package/extensions/dashboard-session-server.ts +22 -1
  85. package/extensions/dashboard-settings.ts +10 -0
  86. package/extensions/dashboard-telemetry.ts +237 -0
  87. package/extensions/definition-describe.ts +74 -16
  88. package/extensions/delegate-chain.ts +37 -10
  89. package/extensions/delegation-artifacts.ts +43 -1
  90. package/extensions/delegation-operations.ts +71 -33
  91. package/extensions/delegation.ts +86 -15
  92. package/extensions/execute-child.ts +62 -6
  93. package/extensions/execution-evidence.ts +139 -4
  94. package/extensions/fanout-outcome.ts +4 -1
  95. package/extensions/grants-command.ts +12 -1
  96. package/extensions/grants.ts +19 -2
  97. package/extensions/init-command.ts +1 -1
  98. package/extensions/parent-tool-host.ts +228 -0
  99. package/extensions/parent-tool-proxy.ts +44 -0
  100. package/extensions/public-evidence.ts +8 -2
  101. package/extensions/reload-environment.ts +6 -0
  102. package/extensions/replay-retry.ts +119 -0
  103. package/extensions/run-delegation.ts +77 -12
  104. package/extensions/runtime-snapshot.ts +16 -1
  105. package/extensions/session-report.ts +16 -0
  106. package/extensions/session.ts +9 -0
  107. package/extensions/spawn-summary.ts +31 -0
  108. package/package.json +2 -2
  109. package/src/executors/activity-session.ts +28 -0
  110. package/src/executors/child-final.ts +11 -1
  111. package/src/executors/child-usage.ts +280 -0
  112. package/src/governance/auto-mode-policy.ts +19 -2
  113. package/src/governance/operation-artifacts.ts +21 -1
  114. package/src/governance/operation-replay.ts +70 -0
  115. package/src/governance/parent-tool-calls.ts +191 -0
  116. package/src/kernel/child-tools.ts +39 -9
  117. package/src/kernel/delegate-types.ts +26 -0
  118. package/src/kernel/delegate.ts +17 -1
  119. package/src/kernel/dispatch-operation.ts +11 -0
  120. package/src/kernel/env-names.ts +27 -0
  121. package/src/kernel/parent-tools.ts +342 -0
  122. package/src/kernel/propagation.ts +12 -0
  123. package/src/kernel/replay-safe.ts +182 -0
  124. package/src/products/dashboard-cli.ts +27 -1
  125. package/src/products/dashboard-render.ts +25 -0
  126. package/src/products/dashboard-screen.ts +1 -1
  127. package/src/products/dashboard-session-client.ts +6 -1
  128. package/src/products/dashboard-settings.ts +31 -3
  129. package/src/products/episode-report.ts +8 -1
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The one automatic retry of a replay-safe child (owner decision of 2026-11-17, "Read-only work, once").
3
+ *
4
+ * The decision is the kernel's (`src/kernel/replay-safe.ts`); this module gathers its facts and, when it says yes,
5
+ * runs the same request again through the ordinary delegation path. The retry is a fresh execution: a new
6
+ * execution identity, a new child process and session, its own capacity reservation and capability decision,
7
+ * linked to the first in the retained result details. It is planned with nobody asked, so it can only be admitted if a
8
+ * fresh unprompted delegation would be, and it inherits the first attempt's wall-clock deadline. There is never a
9
+ * third attempt: the retry's own outcome is returned, not judged again.
10
+ */
11
+ import { childExecutionLimits } from "./dashboard-settings.ts";
12
+ import { isCriticalAssuranceBlock, type DelegationOutcome } from "./execute-child.ts";
13
+ import type { ExecutionOccurrenceIds } from "./execution-occurrence.ts";
14
+ import type { GrantsSession } from "./session.ts";
15
+ import { reconcileDelegationCapacity, reserveDelegationCapacity } from "./session-capacity.ts";
16
+ import type { CapacityReservation } from "../src/kernel/capacity.ts";
17
+ import { ENV_REPLAY_RETRY } from "../src/kernel/env-names.ts";
18
+ import { newExecutionId } from "../src/kernel/execution-id.ts";
19
+ import { GovernanceRefusal } from "../src/kernel/refusals.ts";
20
+ import { replayRetryDecision, replayRetrySwitch } from "../src/kernel/replay-safe.ts";
21
+ import { attemptsUsage, observedUsageOf, withObservedUsage } from "../src/executors/child-usage.ts";
22
+
23
+ /** What the first attempt's own path observed: approvals it spent and the deadline it recorded. */
24
+ export interface AttemptObservation {
25
+ runtime?: import("./definition-runtime.ts").ResolvedDefinitionRuntime;
26
+ approvalSpent?: boolean;
27
+ deadlineAt?: number;
28
+ }
29
+
30
+ /** Run the retry with a fresh identity and reservation; resolves to its outcome, or rejects as a delegation does. */
31
+ export type ReplayRun = (
32
+ ids: ExecutionOccurrenceIds,
33
+ reservation: CapacityReservation,
34
+ observe: { onExecutorEntry: () => void },
35
+ ) => Promise<DelegationOutcome>;
36
+
37
+ function noted(outcome: DelegationOutcome, note: string): DelegationOutcome {
38
+ return { ...outcome, reason: [outcome.reason, `automatic retry not started: ${note}`].filter(Boolean).join("; ") };
39
+ }
40
+
41
+ /**
42
+ * Return `first` unchanged unless every guard holds; otherwise the retry's outcome carrying `first`. A retry that
43
+ * could not start leaves `first` standing with a note. One whose child started and then threw rejects with the
44
+ * first attempt named, as an ordinary delegation's executor failure rejects. Under a stable operation an attempt
45
+ * that passes every other guard is not retried but returned marked `replayable` (owner decision of 2026-11-17,
46
+ * "Principal retries once"): the operation's owner retries it under a new operation.
47
+ */
48
+ export async function replayIfSafe(
49
+ first: DelegationOutcome,
50
+ input: {
51
+ session: GrantsSession;
52
+ ids: ExecutionOccurrenceIds;
53
+ budget: number | undefined;
54
+ signal: AbortSignal | undefined;
55
+ operation: boolean;
56
+ attempt: AttemptObservation;
57
+ },
58
+ run: ReplayRun,
59
+ ): Promise<DelegationOutcome> {
60
+ const { session, attempt } = input;
61
+ const decision = replayRetryDecision({
62
+ enabled: replayRetrySwitch(process.env[ENV_REPLAY_RETRY]).enabled,
63
+ capabilities: first.granted,
64
+ attempt: first,
65
+ operation: input.operation,
66
+ executor: session.executor.kind,
67
+ parentAborted: Boolean(input.signal?.aborted),
68
+ criticalAssuranceBlock: isCriticalAssuranceBlock(first),
69
+ approvalSpent: attempt.approvalSpent !== false,
70
+ remainingMs: attempt.deadlineAt === undefined ? Number.NaN : attempt.deadlineAt - Date.now(),
71
+ idleMs: childExecutionLimits(session).idleMs,
72
+ });
73
+ if (!decision.retry) return "replayable" in decision ? { ...first, replayable: true } : first;
74
+
75
+ const ids = { ...input.ids, executionId: newExecutionId() };
76
+ let reservation: CapacityReservation;
77
+ try {
78
+ await reconcileDelegationCapacity(session);
79
+ reservation = reserveDelegationCapacity(session, ids.executionId, input.budget);
80
+ } catch (error) {
81
+ // No room in the fan-out bound, or capacity could not be read: nothing started, so the first attempt stands.
82
+ return noted(first, String(error instanceof Error ? error.message : error));
83
+ }
84
+ // The parent may have been cancelled while capacity was reconciled: start nothing, and free what was reserved.
85
+ if (input.signal?.aborted) {
86
+ reservation.finalize({ state: "not-started", reason: "parent tool call cancelled before the automatic retry" });
87
+ return noted(first, "the parent tool call was cancelled");
88
+ }
89
+ let entered = false;
90
+ let second: DelegationOutcome;
91
+ try {
92
+ second = await run(ids, reservation, { onExecutorEntry: () => (entered = true) });
93
+ } catch (error) {
94
+ if (!entered) return noted(first, String(error instanceof Error ? error.message : error));
95
+ const note = `after an automatic retry of a replay-safe child whose first attempt failed (${decision.cause})`;
96
+ // Both attempts ran: the error the caller reports carries both observations, as an outcome would.
97
+ const usage = attemptsUsage(first.observedUsage, observedUsageOf(error));
98
+ const carried = <T>(replacement: T): T => (usage ? withObservedUsage(replacement, usage) : replacement);
99
+ if (error instanceof GovernanceRefusal)
100
+ throw carried(
101
+ new GovernanceRefusal({
102
+ code: error.code,
103
+ message: `${error.message}; ${note}`,
104
+ ...(error.details ? { details: error.details } : {}),
105
+ }),
106
+ );
107
+ throw carried(new Error(`${String(error instanceof Error ? error.message : error)}; ${note}`, { cause: error }));
108
+ }
109
+ // A refusal at the retry's own planning started nothing: the first attempt is still the answer.
110
+ if (!second.work && !second.final && !second.cleanup) return noted(first, second.reason ?? "refused");
111
+ // Child usage (2026-11-17): the delegation reports both attempts' usage; `retry.first` keeps the first's own.
112
+ const observedUsage = attemptsUsage(first.observedUsage, second.observedUsage);
113
+ return {
114
+ ...second,
115
+ ...(observedUsage ? { observedUsage } : {}),
116
+ ...(second.ok ? {} : { reason: [second.reason, `first attempt: ${first.reason}`].filter(Boolean).join("; ") }),
117
+ retry: { attempts: 2, firstFailure: decision.cause, executionId: ids.executionId, first },
118
+ };
119
+ }
@@ -8,6 +8,7 @@ import type { OperationClaim } from "../src/kernel/dispatch-operation.ts";
8
8
  import { reconcileDelegationCapacity, reserveDelegationCapacity } from "./session-capacity.ts";
9
9
  import type { CapacityReservation } from "../src/kernel/capacity.ts";
10
10
  import { assertDefinitionIdentity } from "./definition-describe.ts";
11
+ import { replayIfSafe, type AttemptObservation } from "./replay-retry.ts";
11
12
  /**
12
13
  * Plan, gate, audit and run ONE governed child — the whole of a delegation except its tool surface.
13
14
  *
@@ -38,6 +39,7 @@ import type { CorrelationMetadata } from "../src/kernel/correlation.ts";
38
39
  import { preflightModel, runtimePairUnavailable, type ModelCatalogue } from "../src/kernel/model-preflight.ts";
39
40
  import { GovernanceRefusal, refusal as structuredRefusal } from "../src/kernel/refusals.ts";
40
41
  import { executePlannedChild, type DelegationOutcome } from "./execute-child.ts";
42
+ import type { ParentToolHost } from "./parent-tool-host.ts";
41
43
  import { recordDelegationDecision, type ApprovalLedgerFacts } from "./delegation-ledger.ts";
42
44
  import type { ExecutionOccurrenceIds } from "./execution-occurrence.ts";
43
45
  import { resolveDefinitionRuntime } from "./definition-runtime.ts";
@@ -73,7 +75,7 @@ export interface ChildSpec {
73
75
  * bridged the gap, which is the same "a value that was whatever happened to be in scope" shape the module
74
76
  * header lists four defects for.
75
77
  */
76
- export interface DelegationToolContext extends ApprovalUIContext {
78
+ export interface DelegationToolContext extends ApprovalUIContext, ParentToolHost {
77
79
  cwd: string;
78
80
  model?: { provider: string; id: string };
79
81
  modelRegistry: ModelCatalogue;
@@ -297,6 +299,13 @@ async function runOneDelegationImplementation(
297
299
  }) => void;
298
300
  /** Approvals already obtained by the caller — see `planWithApprovals`. `delegate_chain` uses it. */
299
301
  preApproved?: InheritableApproval[];
302
+ /**
303
+ * The definitionId `spec` carries and where it came from (2026-11-17). Trusted: bound by the calling tool from
304
+ * its own arguments and this session's describe memory, never read from model input. Returned in the outcome's
305
+ * details and used for the refusal wording, not decisive: the identity check compares `spec.definitionId` with the
306
+ * current selection either way.
307
+ */
308
+ definitionBinding?: import("./definition-describe.ts").DefinitionBinding;
300
309
  /**
301
310
  * The child whose output composed this child's task (ADR-0033).
302
311
  *
@@ -317,6 +326,12 @@ async function runOneDelegationImplementation(
317
326
  * not even show up as a gap, and ADR-0010's compensating control was blind to every chain step.
318
327
  */
319
328
  approvalFacts?: ApprovalLedgerFacts;
329
+ /** A replay-safe retry (2026-11-17): plan with nobody asked, so it runs only if an unprompted call would. */
330
+ askNobody?: boolean;
331
+ /** Epoch ms the child's wall-clock deadline may not pass: the first attempt's, for a retry. */
332
+ deadlineAt?: number;
333
+ /** Composition-only observation of what this attempt spent and recorded; see `replay-retry.ts`. */
334
+ onAttempt?: (facts: AttemptObservation) => void;
320
335
  } = {},
321
336
  ): Promise<DelegationOutcome> {
322
337
  let capacity: CapacityReservation | undefined;
@@ -335,9 +350,9 @@ async function runOneDelegationImplementation(
335
350
  let executorEntered = false;
336
351
  try {
337
352
  await session.ensureDefinitions?.();
338
- assertDefinitionIdentity(session, spec);
353
+ assertDefinitionIdentity(session, spec, options.definitionBinding?.source);
339
354
 
340
- const { toolCallId, onProgress, preApproved, taskFrom, taskFromExecutionId, approvalFacts } = options;
355
+ const { toolCallId, onProgress, preApproved, taskFrom, taskFromExecutionId, approvalFacts, askNobody } = options;
341
356
  // pi resolves a BARE model id to an unauthenticated provider and the child dies at startup — the id
342
357
  // alone is not enough, it must be qualified with its provider (`Model<Api>` carries both).
343
358
  const defaultModel = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
@@ -407,7 +422,8 @@ async function runOneDelegationImplementation(
407
422
  );
408
423
  executorRefusal ||= nativeRefusal;
409
424
 
410
- const planContext = extra;
425
+ // Parent-run tools are decided by THIS delegation's live tool context: it is what will run them.
426
+ const planContext = { ...extra, ...session.parentToolContext?.(ctx) };
411
427
  let preparedWorkspace: PreparedWorkspace | undefined;
412
428
  let approvalOutcome: ApprovalOutcome | undefined;
413
429
  let plan: ReturnType<typeof planDelegation>;
@@ -433,7 +449,14 @@ async function runOneDelegationImplementation(
433
449
  ledgerPath: session.ledgerPath,
434
450
  });
435
451
  request.correlation = preparedWorkspace.correlation;
436
- const gated = await planWithApprovals(session, request, planContext, ctx, signal, preApproved);
452
+ const gated = await planWithApprovals(
453
+ session,
454
+ request,
455
+ planContext,
456
+ askNobody ? null : ctx,
457
+ signal,
458
+ preApproved,
459
+ );
437
460
  plan = gated.plan;
438
461
  options.onDefinition?.(gated.definition);
439
462
  approvalOutcome = gated.approval;
@@ -450,7 +473,7 @@ async function runOneDelegationImplementation(
450
473
  session,
451
474
  request,
452
475
  planContext,
453
- executorRefusal || modelRefusal || capacityRefusal ? null : ctx,
476
+ askNobody || executorRefusal || modelRefusal || capacityRefusal ? null : ctx,
454
477
  signal,
455
478
  preApproved,
456
479
  );
@@ -522,6 +545,12 @@ async function runOneDelegationImplementation(
522
545
  };
523
546
  }
524
547
 
548
+ // Any answer a gate gave for this attempt is spent on it: prompt, store or Auto here, a chain's upfront dialog
549
+ // through `preApproved` (whose ledger attribution, `approvalFacts`, is derived from the same list).
550
+ options.onAttempt?.({
551
+ runtime: resolvedRuntime,
552
+ approvalSpent: Boolean(approvalOutcome?.approved.length || preApproved?.length),
553
+ });
525
554
  executorEntered = true;
526
555
  return await executePlannedChild({
527
556
  capacityReservation: capacity,
@@ -536,10 +565,13 @@ async function runOneDelegationImplementation(
536
565
  parentExecutionId: ids.parentExecutionId,
537
566
  toolCallId: options.toolCallId,
538
567
  cwd: ctx.cwd,
568
+ parentToolHost: ctx,
539
569
  preparedWorkspace,
540
570
  resolvedRuntime,
541
571
  signal,
542
572
  onProgress,
573
+ deadlineAt: options.deadlineAt,
574
+ onDeadline: (deadlineAt) => options.onAttempt?.({ deadlineAt }),
543
575
  });
544
576
  } finally {
545
577
  capacity?.finalize(
@@ -554,16 +586,20 @@ async function runOneDelegationImplementation(
554
586
  export async function runOneDelegation(
555
587
  ...args: Parameters<typeof runOneDelegationImplementation>
556
588
  ): Promise<DelegationOutcome> {
557
- const [session, spec, ids, , ctx, signal] = args;
589
+ const [session, spec, ids, budget, ctx, signal] = args;
558
590
  const finalScope = operationFinalScope(session);
559
591
  const options = args[6] ?? {};
560
- const claim = options.operationClaim ?? (await claimDelegationOperation(session, spec, ids, ctx, signal));
592
+ const binding = options.definitionBinding;
593
+ const bindOutcome = (outcome: DelegationOutcome) =>
594
+ binding ? Object.assign(outcome, { definitionBinding: { ...binding } }) : outcome;
595
+ const claim = options.operationClaim ?? (await claimDelegationOperation(session, spec, ids, ctx, signal, binding));
561
596
  if (claim?.reused) {
562
597
  options.capacityReservation?.finalize({ state: "not-started", reason: "existing operation reused" });
563
- return existingOperationOutcome(claim, session.depth + 1);
598
+ return bindOutcome(existingOperationOutcome(claim, session.depth + 1));
564
599
  }
565
600
  let executorEntered = false;
566
601
  try {
602
+ const attempt: AttemptObservation = {};
567
603
  args[6] = {
568
604
  ...options,
569
605
  operationClaim: claim,
@@ -571,19 +607,48 @@ export async function runOneDelegation(
571
607
  executorEntered = true;
572
608
  options.onExecutorEntry?.();
573
609
  },
610
+ onAttempt: (facts) => Object.assign(attempt, facts),
574
611
  };
575
- const result = await runOneDelegationImplementation(...args);
612
+ let result = await runOneDelegationImplementation(...args);
613
+ // 2026-11-17: one automatic retry of a replay-safe child, never under a stable operation (its admission names
614
+ // exactly one execution; an eligible failure there is marked `replayable` for the operation's owner instead).
615
+ // The retry is a new occurrence planned through this same path, with nobody asked, the first attempt's
616
+ // runtime and deadline, and none of the approvals the first attempt spent.
617
+ const operation = Boolean(claim);
618
+ result = await replayIfSafe(
619
+ result,
620
+ { session, ids, budget, signal, operation, attempt },
621
+ (retryIds, reservation, observe) => {
622
+ const {
623
+ operationClaim: _claim,
624
+ capacityReservation: _first,
625
+ preApproved: _spent,
626
+ approvalFacts: _facts,
627
+ ...kept
628
+ } = options;
629
+ return runOneDelegationImplementation(session, spec, retryIds, budget, ctx, signal, {
630
+ ...kept,
631
+ capacityReservation: reservation,
632
+ resolvedRuntime: attempt.runtime,
633
+ askNobody: true,
634
+ deadlineAt: attempt.deadlineAt,
635
+ onExecutorEntry: observe.onExecutorEntry,
636
+ });
637
+ },
638
+ );
576
639
  if (claim) {
577
640
  try {
578
- await finishDelegationOperation(claim, result, session, finalScope);
641
+ await finishDelegationOperation(claim, result, session, finalScope, spec.definitionId);
579
642
  } catch (error) {
580
643
  // A post-execution observation failure must not erase the native final or settlement receipt.
581
644
  result.control = "failed";
582
645
  result.reason = [result.reason, `operation status update failed: ${String(error)}`].filter(Boolean).join("; ");
583
646
  result.operation = { ...claim.operation, state: "uncertain", reused: false };
647
+ // A failed control step refuses a retry, so it refuses the mark a retry would be taken on too.
648
+ delete result.replayable;
584
649
  }
585
650
  }
586
- return result;
651
+ return bindOutcome(result);
587
652
  } catch (error) {
588
653
  if (claim)
589
654
  await claim.finish!(
@@ -191,10 +191,25 @@ export function registerRuntimeSnapshot(
191
191
  )
192
192
  throw Error("operation owner changed during read");
193
193
  const artifact = operation ? operationArtifactReference(session, operation) : undefined;
194
+ const retained = operation ? operationHistory(session, operation.operationId, false) : undefined;
195
+ const proof =
196
+ retained?.operation.executionId === operation?.executionId
197
+ ? retained?.operation.runtime?.automaticRetryEligibility
198
+ : undefined;
194
199
  request.reply!({
195
200
  ...envelope,
196
201
  qualified: true,
197
- operation: operation ? { ...operation, ...(artifact ? { artifact } : {}) } : null,
202
+ operation: operation
203
+ ? {
204
+ ...operation,
205
+ ...(artifact ? { artifact } : {}),
206
+ ...(proof &&
207
+ ["settled", "not-started"].includes(operation.state) &&
208
+ operation.runtime?.control !== "failed"
209
+ ? { runtime: { ...operation.runtime, automaticRetryEligibility: proof } }
210
+ : {}),
211
+ }
212
+ : null,
198
213
  ...(!operation
199
214
  ? { reason: "operation record is absent; this does not prove the dispatch was not started" }
200
215
  : {}),
@@ -20,6 +20,9 @@ import { existsSync } from "node:fs";
20
20
  import { legacyApprovalsPath, sharedApprovalsPath } from "../src/governance/approval-store.ts";
21
21
  import { verifyLedger } from "../src/governance/ledger.ts";
22
22
  import { AGENT_WILDCARD } from "../src/kernel/resolve.ts";
23
+ import { ENV_PARENT_TOOLS, ENV_REPLAY_RETRY } from "../src/kernel/env-names.ts";
24
+ import { parentToolsSwitch } from "../src/kernel/parent-tools.ts";
25
+ import { replayRetrySwitch } from "../src/kernel/replay-safe.ts";
23
26
  import { planWithApprovals } from "./run-delegation.ts";
24
27
  import type { GrantsSession } from "./session.ts";
25
28
  import { renderSpawnableSummary, summariseSpawnable } from "./spawn-summary.ts";
@@ -68,6 +71,17 @@ export async function reportSessionStart(session: GrantsSession, ctx: SessionRep
68
71
  // the moment somebody tries to delegate to it.
69
72
  for (const reason of session.definitionSkips)
70
73
  ctx.ui.notify(`grants: a definition was not loaded — ${reason}`, "warning");
74
+ // The parent-run tool switch fails closed; a typo that silently changed it would not be a choice anyone made.
75
+ if (session.depth === 0 && parentToolsSwitch(process.env[ENV_PARENT_TOOLS]).malformed)
76
+ ctx.ui.notify(
77
+ `grants: ${ENV_PARENT_TOOLS} must be literal 1 or 0 — no tool is run for a child by this session (failing closed)`,
78
+ "warning",
79
+ );
80
+ if (session.depth === 0 && replayRetrySwitch(process.env[ENV_REPLAY_RETRY]).malformed)
81
+ ctx.ui.notify(
82
+ `grants: ${ENV_REPLAY_RETRY} must be literal 1 or 0 — no failed child is retried automatically (failing closed)`,
83
+ "warning",
84
+ );
71
85
  // A registered workspace that could not be pinned is not routable this session, and the routing refusal an
72
86
  // operator would otherwise meet names neither the directory nor the reason.
73
87
  // Trust on first use, announced rather than silent: a control that installs itself quietly is one nobody
@@ -329,6 +343,8 @@ function selectedDefinitionsSummary(session: GrantsSession): Promise<string | nu
329
343
  depth: session.depth,
330
344
  maxDepth: session.maxDepth,
331
345
  toolsObserved: session.observed,
346
+ replayRetry: replayRetrySwitch(process.env[ENV_REPLAY_RETRY]).enabled,
347
+ executor: session.executor.kind,
332
348
  },
333
349
  ).then((summary) => renderSpawnableSummary(summary, session.definitions.size));
334
350
  }
@@ -247,6 +247,13 @@ export interface GrantsSession extends NativeSessionHost {
247
247
  observedTools: string[] | null;
248
248
  /** Re-read public origins at admission; a parent's callable name does not prove child delivery. */
249
249
  childToolSources?: () => readonly import("../src/kernel/child-tools.ts").ChildToolSource[];
250
+ /**
251
+ * Parent-run tools this session can offer a child (2026-11-17). Without a host it previews Pi's inventory;
252
+ * dispatch passes the live tool context of the delegation that waits on the child. Bound by `grants.ts`.
253
+ */
254
+ parentToolContext?: (
255
+ host?: import("./parent-tool-host.ts").ParentToolHost,
256
+ ) => import("./parent-tool-host.ts").ParentToolContext;
250
257
  /** ADR-0016: `SKILL.md` definitions, keyed by name. The format this package spawns from now. */
251
258
  ensureDefinitions?: () => Promise<void>;
252
259
  definitions: Map<string, SkillDefinition>;
@@ -691,6 +698,8 @@ export function createGrantsSession(
691
698
  extensionPath: session.extensionPath,
692
699
  observerExtensionPath: session.observerExtensionPath,
693
700
  childToolSources: session.childToolSources?.(),
701
+ // A preview from the inventory; a dispatch overrides it with the live tool context's answer.
702
+ ...session.parentToolContext?.(),
694
703
  childEnv: activityChildEnv(session.activity),
695
704
  // ADR-0042: the pin this session holds, handed to the kernel so a delegated child inherits a narrowed
696
705
  // one through the same builder `publishChildEnv` uses. Read here rather than in the kernel so there is
@@ -25,6 +25,7 @@
25
25
  */
26
26
 
27
27
  import type { SkillDefinition } from "../src/kernel/definitions.ts";
28
+ import { replayRetryNotice, replaySafe } from "../src/kernel/replay-safe.ts";
28
29
  import type { GatedPlan } from "./run-delegation.ts";
29
30
 
30
31
  /** Why a definition is not spawnable right now; display never changes the planner's refusal. */
@@ -52,6 +53,10 @@ export interface SpawnableSummary {
52
53
  withheld: WithheldDefinition[];
53
54
  /** Extension capabilities have not been observed yet; this is not an installation failure. */
54
55
  awaitingTools?: string[];
56
+ /** Spawnable definitions whose allowlisted tools this session runs for the child (2026-11-17). */
57
+ parentRun?: { name: string; tools: string[] }[];
58
+ /** Spawnable definitions whose planned tools only read, and when this session does not retry them. */
59
+ replaySafe?: { names: string[]; notice: string };
55
60
  /**
56
61
  * Set when NOTHING can be spawned for a reason about the SESSION rather than about any definition — no
57
62
  * `tool:delegate`, or a depth bound that forbids spawning. Per-definition work is skipped entirely.
@@ -84,6 +89,10 @@ export interface SessionFacts {
84
89
  maxDepth: number;
85
90
  /** Omitted by callers with an already-settled planner; false only before native tool observation. */
86
91
  toolsObserved?: boolean;
92
+ /** The automatic retry of replay-safe children is on (`PI_DADDY_REPLAY_RETRY`); omitted means on. */
93
+ replayRetry?: boolean;
94
+ /** Where children run: Herdr panes are never retried (2026-11-17). Omitted means the process executor. */
95
+ executor?: "process" | "herdr";
87
96
  }
88
97
 
89
98
  /**
@@ -137,11 +146,15 @@ export async function summariseSpawnable(
137
146
  const spawnable: string[] = [];
138
147
  const withheld: WithheldDefinition[] = [];
139
148
  const awaitingTools: string[] = [];
149
+ const parentRun: { name: string; tools: string[] }[] = [];
150
+ const replay: string[] = [];
140
151
 
141
152
  for (const name of names.slice(0, PREVIEW_LIMIT)) {
142
153
  const { plan } = await preview(name);
143
154
  if (plan.ok) {
144
155
  spawnable.push(name);
156
+ if (plan.parentTools?.length) parentRun.push({ name, tools: plan.parentTools });
157
+ if (replaySafe(plan.effective)) replay.push(name);
145
158
  continue;
146
159
  }
147
160
  // The initial catalog contains built-ins before Pi exposes its callable extension tools. Preserve
@@ -182,6 +195,15 @@ export async function summariseSpawnable(
182
195
  spawnable,
183
196
  withheld,
184
197
  ...(awaitingTools.length ? { awaitingTools } : {}),
198
+ ...(parentRun.length ? { parentRun } : {}),
199
+ ...(replay.length
200
+ ? {
201
+ replaySafe: {
202
+ names: replay,
203
+ notice: replayRetryNotice(session.replayRetry !== false, session.executor ?? "process"),
204
+ },
205
+ }
206
+ : {}),
185
207
  notChecked: Math.max(0, names.length - PREVIEW_LIMIT),
186
208
  };
187
209
  }
@@ -241,6 +263,15 @@ export function renderSpawnableSummary(summary: SpawnableSummary, total: number)
241
263
  const extra = summary.withheld.length - shown.length;
242
264
  lines.push(` withheld: ${shown.join("; ")}${extra > 0 ? `; … and ${extra} more` : ""}`);
243
265
  }
266
+ // A new path for authority is named where the operator reads what is spawnable, not left to be discovered.
267
+ if (summary.parentRun?.length) {
268
+ const runs = summary.parentRun.map((run) => `${safeName(run.name)} (${list(run.tools.map(safeName))})`);
269
+ lines.push(` run by this session for the child: ${list(runs)}`);
270
+ }
271
+ // 2026-11-17: whose failures without an answer are retried once without asking, and when this session does not.
272
+ if (summary.replaySafe) {
273
+ lines.push(` replay-safe (${summary.replaySafe.notice}): ${list(summary.replaySafe.names.map(safeName))}`);
274
+ }
244
275
  if (summary.awaitingTools?.length) {
245
276
  lines.push(` checking available tools: ${list(summary.awaitingTools.map(safeName))} — updates when work starts`);
246
277
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-daddy",
3
- "version": "0.59.1",
3
+ "version": "0.61.0",
4
4
  "description": "Capability governance for pi sub-agents: spawn Agent Skills (SKILL.md) definitions whose allowed-tools becomes a grant that can only narrow going down a delegation tree, enforced by pi's own --tools allowlist, with an append-only ledger.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -53,7 +53,7 @@
53
53
  "typecheck": "tsc -p tsconfig.check.json",
54
54
  "test": "node scripts/unit-tests.ts",
55
55
  "test:integration": "node --test test-integration/*.it.ts",
56
- "test:integration:ci": "node --test test-integration/approval.it.ts test-integration/governance.it.ts test-integration/activity.it.ts test-integration/auto-chain.it.ts test-integration/pi-sdk/automatic-start.it.ts test-integration/pi-sdk/dashboard-prompts.it.ts test-integration/pi-sdk/owned-pattern-cleanup.it.ts test-integration/pi-sdk/child-tool-delivery.it.ts",
56
+ "test:integration:ci": "node --test test-integration/approval.it.ts test-integration/governance.it.ts test-integration/activity.it.ts test-integration/auto-chain.it.ts test-integration/pi-sdk/automatic-start.it.ts test-integration/pi-sdk/dashboard-prompts.it.ts test-integration/pi-sdk/owned-pattern-cleanup.it.ts test-integration/pi-sdk/child-tool-delivery.it.ts test-integration/pi-sdk/parent-run-tools.it.ts test-integration/pi-sdk/described-binding.it.ts test-integration/pi-sdk/child-usage-total.it.ts",
57
57
  "contracts:generate": "node scripts/generate-ledger-record-contract.ts",
58
58
  "prepack": "npm run build",
59
59
  "test:smoke": "node scripts/smoke-installed.mjs",
@@ -12,11 +12,21 @@ import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
12
12
  import { SessionManager, type FileEntry } from "@earendil-works/pi-coding-agent";
13
13
  import { BoundedReadCleanupError, readBoundedBytes } from "../kernel/bounded-read.ts";
14
14
  import type { ChildUsageTotals } from "../governance/ledger-events.ts";
15
+ import {
16
+ addDelegationResult,
17
+ addUnansweredCalls,
18
+ DELEGATION_RESULT_TOOLS,
19
+ delegationCallIds,
20
+ type ObservedChildUsage,
21
+ } from "./child-usage.ts";
15
22
  import { tmpdir } from "node:os";
16
23
  import { join } from "node:path";
17
24
 
18
25
  export interface ChildUsageObservation {
26
+ /** The child's own model calls: what the ledger records. Never what its delegation results reported. */
19
27
  usage?: ChildUsageTotals;
28
+ /** What the child's own delegation results reported: its descendants, already in its session total. */
29
+ delegated?: ObservedChildUsage;
20
30
  unavailable?: "session-missing" | "session-invalid" | "usage-missing";
21
31
  resolvedModel?: { provider: string; modelId: string };
22
32
  effectiveThinkingLevel?: string;
@@ -190,6 +200,9 @@ async function readChildUsage(path: string | Promise<string | undefined>): Promi
190
200
  let resolvedModel: ChildUsageObservation["resolvedModel"];
191
201
  let effectiveThinkingLevel: string | undefined;
192
202
  let compactionCount = 0;
203
+ let delegated: ObservedChildUsage | undefined;
204
+ // This turn's delegation calls still without a result, by id: a child stopped while it waited on its own child.
205
+ const unanswered = new Map<string, number>();
193
206
  try {
194
207
  const read = await readBoundedBytes(resolved, { maxBytes: MAX_USAGE_SESSION_BYTES, timeoutMs: 3000 });
195
208
  if (!read.ok)
@@ -218,6 +231,16 @@ async function readChildUsage(path: string | Promise<string | undefined>): Promi
218
231
  if (message.role !== "assistant" && message.role !== "toolResult") continue;
219
232
  if (message.role === "assistant" && typeof message.provider === "string" && typeof message.model === "string")
220
233
  resolvedModel = { provider: message.provider, modelId: message.model };
234
+ if (message.role === "assistant")
235
+ for (const id of delegationCallIds(message.content)) unanswered.set(id, (unanswered.get(id) ?? 0) + 1);
236
+ // Counted in this child's session total, but these are its descendants' calls, not its own (2026-11-17).
237
+ if (message.role === "toolResult" && DELEGATION_RESULT_TOOLS.has(String(message.toolName))) {
238
+ const waiting = unanswered.get(String(message.toolCallId)) ?? 0;
239
+ if (waiting > 0) unanswered.set(String(message.toolCallId), waiting - 1);
240
+ delegated = addDelegationResult(delegated, message);
241
+ if (!delegated) return { unavailable: "session-invalid" };
242
+ continue;
243
+ }
221
244
  usage = object(message.usage);
222
245
  if (message.role === "toolResult" && !usage) continue;
223
246
  } else if (["usage", "compaction", "branch_summary"].includes(entry.type)) {
@@ -250,10 +273,15 @@ async function readChildUsage(path: string | Promise<string | undefined>): Promi
250
273
  return { unavailable: "session-invalid" };
251
274
  found = true;
252
275
  }
276
+ delegated = addUnansweredCalls(
277
+ delegated,
278
+ [...unanswered.values()].reduce((sum, waiting) => sum + waiting, 0),
279
+ );
253
280
  const metadata = {
254
281
  ...(resolvedModel ? { resolvedModel } : {}),
255
282
  ...(effectiveThinkingLevel ? { effectiveThinkingLevel } : {}),
256
283
  compactionCount,
284
+ ...(delegated ? { delegated } : {}),
257
285
  };
258
286
  if (!found || incomplete) return { unavailable: "usage-missing", ...metadata };
259
287
  return {
@@ -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();