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
@@ -1,7 +1,12 @@
1
1
  import type { DashboardChoiceDetail } from "../src/kernel/dashboard-choice.ts";
2
2
  import { isJevEditAction } from "../src/products/dashboard-settings.ts";
3
3
  import { dashboardObservation } from "./dashboard-observation.ts";
4
- import { dashboardSettingsSnapshot, dashboardJev, setDashboardLimit } from "./dashboard-settings.ts";
4
+ import {
5
+ dashboardSettingsSnapshot,
6
+ dashboardJev,
7
+ setDashboardLimit,
8
+ setDashboardTelemetry,
9
+ } from "./dashboard-settings.ts";
5
10
  import { randomBytes } from "node:crypto";
6
11
  import { chmod, rm } from "node:fs/promises";
7
12
  import { createServer, type Server } from "node:net";
@@ -10,6 +15,7 @@ import { join } from "node:path";
10
15
  import type { GrantsSession } from "./session.ts";
11
16
  import { getDashboardControlState, setAutoApproval } from "./session-auto-mode.ts";
12
17
  import { saveSessionModelEdits, sessionModelRows } from "./session-model-prompt.ts";
18
+ import { childUsageInSession } from "../src/executors/child-usage.ts";
13
19
 
14
20
  export interface DashboardSessionEndpoint {
15
21
  socketPath: string;
@@ -130,6 +136,7 @@ async function respond(
130
136
  if (
131
137
  choiceAction ||
132
138
  request.action === "edit-jev" ||
139
+ request.action === "set-telemetry" ||
133
140
  (request.action !== "get" && request.expectedOwner !== undefined)
134
141
  ) {
135
142
  const observed = session.dashboardObservations?.(),
@@ -183,6 +190,9 @@ async function respond(
183
190
  } else if (request.action === "set-jev") {
184
191
  if (typeof request.enabled !== "boolean") return { ok: false, error: "JEV requires an explicit boolean" };
185
192
  jev = await dashboardJev(session, request.enabled ? "enable" : "disable");
193
+ } else if (request.action === "set-telemetry") {
194
+ if (typeof request.enabled !== "boolean") return { ok: false, error: "Telemetry requires an explicit boolean" };
195
+ await setDashboardTelemetry(session, request.enabled);
186
196
  } else if (request.action === "set-auto") {
187
197
  if (typeof request.enabled !== "boolean") return { ok: false, error: "Auto mode requires an explicit boolean" };
188
198
  await setAutoApproval(session, request.enabled, "dashboard");
@@ -226,9 +236,20 @@ async function respond(
226
236
  versions: versionSnapshot(session),
227
237
  settings,
228
238
  cost: null, // Live complete episode cost is unavailable; retained usage remains in the episode report.
239
+ ...childUsageSnapshot(session),
229
240
  };
230
241
  }
231
242
 
243
+ /** Child usage this Pi session's own record shows its delegation results reported (2026-11-17). Display only. */
244
+ function childUsageSnapshot(session: GrantsSession) {
245
+ try {
246
+ const childUsage = childUsageInSession(session.parentSession?.getEntries() ?? []);
247
+ return childUsage ? { childUsage } : {};
248
+ } catch {
249
+ return {};
250
+ }
251
+ }
252
+
232
253
  function versionSnapshot(session: GrantsSession) {
233
254
  try {
234
255
  const cached = versions.get(session),
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import type { GrantsSession } from "./session.ts";
5
5
  import type { DashboardJevState, DashboardSettingsSnapshot } from "../src/products/dashboard-settings.ts";
6
+ import { telemetrySnapshot, setTelemetryEnabled, closeTelemetry } from "./dashboard-telemetry.ts";
6
7
  import { isJevEditAction, type JevEditAction } from "../src/products/dashboard-settings.ts";
7
8
  import { MAX_CHILDREN_PER_CALL } from "../src/kernel/fanout.ts";
8
9
  import {
@@ -176,5 +177,14 @@ export async function dashboardSettingsSnapshot(
176
177
  maxDepth: session.maxDepth ?? 0,
177
178
  perCall: MAX_CHILDREN_PER_CALL,
178
179
  jev: jev ?? (await dashboardJev(session, "status")),
180
+ telemetry: telemetrySnapshot(session),
179
181
  };
180
182
  }
183
+ export async function setDashboardTelemetry(session: GrantsSession, enabled: boolean): Promise<void> {
184
+ owner(session, true);
185
+ if (enabled) setTelemetryEnabled(session, true);
186
+ else await closeTelemetry(session);
187
+ }
188
+ export function closeDashboardTelemetry(session: GrantsSession): Promise<void> {
189
+ return closeTelemetry(session);
190
+ }
@@ -0,0 +1,237 @@
1
+ import { execFile, type ExecFileOptionsWithStringEncoding } from "node:child_process";
2
+ import type { GrantsSession } from "./session.ts";
3
+
4
+ const TARGET = /^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9][A-Za-z0-9.-]*$/;
5
+ const SERVICE = /^[A-Za-z0-9][A-Za-z0-9_.@:-]{0,127}\.service$/;
6
+ type Execute = (
7
+ file: string,
8
+ args: string[],
9
+ options: ExecFileOptionsWithStringEncoding,
10
+ ) => Promise<{ stdout: string; stderr: string }>;
11
+ export type TelemetryReading = {
12
+ enabled: boolean;
13
+ status: "disabled" | "missing-dependency" | "stopped" | "disconnected" | "stale" | "connected";
14
+ sampledAt?: number;
15
+ gpuPercent?: number;
16
+ temperatureC?: number;
17
+ ramUsedBytes?: number;
18
+ ramTotalBytes?: number;
19
+ note?: string;
20
+ };
21
+
22
+ // execFile's abort callback can precede process close. Keep the owned sample busy
23
+ // until close so disable/re-enable and reload cannot overlap the old SSH process.
24
+ export const executeTelemetry: Execute = (file, args, options) =>
25
+ new Promise((resolve, reject) => {
26
+ const { signal, ...commandOptions } = options;
27
+ signal?.throwIfAborted();
28
+ let aborted = false;
29
+ let closed = false;
30
+ let result: { error: Error | null; stdout: string; stderr: string } | undefined;
31
+ const finish = () => {
32
+ if (!closed || !result) return;
33
+ if (result.error) reject(result.error);
34
+ else resolve({ stdout: result.stdout, stderr: result.stderr });
35
+ };
36
+ const child = execFile(file, args, { ...commandOptions, killSignal: "SIGKILL" }, (error, stdout, stderr) => {
37
+ result = { error: aborted ? new DOMException("Telemetry probe cancelled", "AbortError") : error, stdout, stderr };
38
+ finish();
39
+ });
40
+ const abort = () => {
41
+ aborted = true;
42
+ child.kill("SIGKILL");
43
+ };
44
+ signal?.addEventListener("abort", abort, { once: true });
45
+ if (signal?.aborted) abort();
46
+ child.once("close", () => {
47
+ signal?.removeEventListener("abort", abort);
48
+ closed = true;
49
+ finish();
50
+ });
51
+ });
52
+
53
+ function safeNumber(value: unknown, min: number, max: number): number | undefined {
54
+ return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max ? value : undefined;
55
+ }
56
+ export function parseGpuJson(text: string): Pick<TelemetryReading, "gpuPercent" | "temperatureC"> {
57
+ const root = JSON.parse(text) as {
58
+ devices?: Array<{
59
+ gpu_activity?: Record<string, { value?: unknown }>;
60
+ Sensors?: Record<string, { value?: unknown }>;
61
+ }>;
62
+ };
63
+ const device = root.devices?.[0];
64
+ if (!device) throw new Error("amdgpu_top response contains no device");
65
+ const gpuPercent = safeNumber(device.gpu_activity?.GFX?.value, 0, 100);
66
+ const temperatureC = safeNumber(device.Sensors?.["Edge Temperature"]?.value, -50, 200);
67
+ return {
68
+ ...(gpuPercent === undefined ? {} : { gpuPercent }),
69
+ ...(temperatureC === undefined ? {} : { temperatureC }),
70
+ };
71
+ }
72
+ export function parseSystemMemory(text: string): Pick<TelemetryReading, "ramUsedBytes" | "ramTotalBytes"> {
73
+ const value = (name: string) => {
74
+ const match = new RegExp(`^${name}:\\s+(\\d+)\\s+kB\\s*$`, "m").exec(text);
75
+ const bytes = match ? Number(match[1]) * 1024 : NaN;
76
+ return Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : undefined;
77
+ };
78
+ const total = value("MemTotal"),
79
+ available = value("MemAvailable");
80
+ if (total === undefined || total === 0) return {};
81
+ return {
82
+ ramTotalBytes: total,
83
+ ...(available === undefined || available > total ? {} : { ramUsedBytes: total - available }),
84
+ };
85
+ }
86
+ export async function sampleTelemetry(
87
+ env: NodeJS.ProcessEnv = process.env,
88
+ execute: Execute = executeTelemetry,
89
+ signal?: AbortSignal,
90
+ ): Promise<TelemetryReading> {
91
+ signal?.throwIfAborted();
92
+ const target = env.PI_DADDY_LLM_TELEMETRY_SSH_TARGET;
93
+ const identity = env.PI_DADDY_LLM_TELEMETRY_SSH_IDENTITY;
94
+ const service = env.PI_DADDY_LLM_TELEMETRY_SERVICE;
95
+ if (!target || !identity || !service || !TARGET.test(target) || !identity.startsWith("/") || !SERVICE.test(service))
96
+ return {
97
+ enabled: true,
98
+ status: "missing-dependency",
99
+ note: "Set SSH target, absolute identity path, and systemd service in Pi environment.",
100
+ };
101
+ try {
102
+ const ssh = ["-i", identity, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "ConnectTimeout=2", target];
103
+ let running = false;
104
+ try {
105
+ await execute("ssh", [...ssh, `systemctl is-active --quiet ${service}`], {
106
+ encoding: "utf8",
107
+ signal,
108
+ timeout: 3000,
109
+ maxBuffer: 1024,
110
+ });
111
+ running = true;
112
+ } catch (error) {
113
+ signal?.throwIfAborted();
114
+ const exitCode = (error as { code?: unknown }).code;
115
+ if (exitCode !== 3 && exitCode !== "3") throw error;
116
+ }
117
+ signal?.throwIfAborted();
118
+ const { stdout } = await execute(
119
+ "ssh",
120
+ [...ssh, "~/.local/bin/amdgpu_top --apu --single --no-pc --json -n 1 -s 1000"],
121
+ { encoding: "utf8", signal, timeout: 4000, maxBuffer: 64 * 1024 },
122
+ );
123
+ signal?.throwIfAborted();
124
+ const parsed = parseGpuJson(stdout);
125
+ const { stdout: memory } = await execute("ssh", [...ssh, "cat /proc/meminfo"], {
126
+ encoding: "utf8",
127
+ signal,
128
+ timeout: 3000,
129
+ maxBuffer: 8192,
130
+ });
131
+ signal?.throwIfAborted();
132
+ return {
133
+ enabled: true,
134
+ status: running ? "connected" : "stopped",
135
+ sampledAt: Date.now(),
136
+ ...parsed,
137
+ ...parseSystemMemory(memory),
138
+ note: "System RAM is the shared APU pool; GPU-only allocation and live prompt/generation speed are unavailable.",
139
+ };
140
+ } catch (error) {
141
+ signal?.throwIfAborted();
142
+ if ((error as NodeJS.ErrnoException).code === "ENOENT")
143
+ return { enabled: true, status: "missing-dependency", note: "OpenSSH client is not installed or not on PATH." };
144
+ return {
145
+ enabled: true,
146
+ status: "disconnected",
147
+ note: "SSH telemetry probe failed; check configured SSH access and amdgpu_top.",
148
+ };
149
+ }
150
+ }
151
+
152
+ export class TelemetryMonitor {
153
+ private enabled = false;
154
+ private reading: TelemetryReading = { enabled: false, status: "disabled" };
155
+ private timer?: NodeJS.Timeout;
156
+ private generation = 0;
157
+ private controller?: AbortController;
158
+ private pending?: Promise<void>;
159
+ private sample: (signal: AbortSignal) => Promise<TelemetryReading>;
160
+ constructor(sample = (signal: AbortSignal) => sampleTelemetry(process.env, executeTelemetry, signal)) {
161
+ this.sample = sample;
162
+ }
163
+ snapshot(): TelemetryReading {
164
+ if (!this.enabled) return { enabled: false, status: "disabled" };
165
+ const reading = this.reading.enabled
166
+ ? this.reading
167
+ : {
168
+ enabled: true,
169
+ status: "missing-dependency" as const,
170
+ note: "Checking configured SSH telemetry prerequisites.",
171
+ };
172
+ return reading.sampledAt !== undefined && Date.now() - reading.sampledAt > 6000
173
+ ? { ...reading, status: "stale" }
174
+ : reading;
175
+ }
176
+ setEnabled(enabled: boolean): void {
177
+ if (!enabled) {
178
+ this.generation++;
179
+ if (this.timer) clearTimeout(this.timer);
180
+ this.timer = undefined;
181
+ this.enabled = false;
182
+ this.reading = { enabled: false, status: "disabled" };
183
+ this.controller?.abort();
184
+ return;
185
+ }
186
+ if (this.enabled) return;
187
+ this.enabled = true;
188
+ const generation = ++this.generation;
189
+ const later = () => {
190
+ this.timer = setTimeout(poll, 2000);
191
+ this.timer.unref();
192
+ };
193
+ const poll = () => {
194
+ if (!this.enabled || this.generation !== generation) return;
195
+ if (this.pending) {
196
+ later();
197
+ return;
198
+ }
199
+ const controller = new AbortController();
200
+ this.controller = controller;
201
+ this.pending = Promise.resolve()
202
+ .then(() => this.sample(controller.signal))
203
+ .then((reading) => {
204
+ if (this.enabled && this.generation === generation) this.reading = reading;
205
+ })
206
+ .catch(() => {
207
+ if (this.enabled && this.generation === generation)
208
+ this.reading = { enabled: true, status: "disconnected", note: "Telemetry probe failed." };
209
+ })
210
+ .finally(() => {
211
+ this.controller = undefined;
212
+ this.pending = undefined;
213
+ if (this.enabled && this.generation === generation) later();
214
+ });
215
+ };
216
+ poll();
217
+ }
218
+ async close(): Promise<void> {
219
+ this.setEnabled(false);
220
+ await this.pending;
221
+ }
222
+ }
223
+ const states = new WeakMap<GrantsSession, TelemetryMonitor>();
224
+ export function telemetrySnapshot(session: GrantsSession): TelemetryReading {
225
+ return states.get(session)?.snapshot() ?? { enabled: false, status: "disabled" };
226
+ }
227
+ export function setTelemetryEnabled(session: GrantsSession, enabled: boolean): void {
228
+ let state = states.get(session);
229
+ if (!state) {
230
+ state = new TelemetryMonitor();
231
+ states.set(session, state);
232
+ }
233
+ state.setEnabled(enabled);
234
+ }
235
+ export async function closeTelemetry(session: GrantsSession): Promise<void> {
236
+ await states.get(session)?.close();
237
+ }
@@ -2,44 +2,90 @@
2
2
  import { publicEvidenceCall } from "./public-evidence.ts";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { Type } from "typebox";
5
- import { digestDefinition } from "../src/kernel/definitions.ts";
5
+ import { ceilingForDefinition, digestDefinition } from "../src/kernel/definitions.ts";
6
6
  import { maySpawnDefinition } from "../src/kernel/delegate.ts";
7
+ import { replaySafeCeiling } from "../src/kernel/replay-safe.ts";
8
+ import { hostModel, liveParentTools } from "./parent-tool-host.ts";
7
9
  import type { GrantsSession } from "./session.ts";
10
+ import type { ReloadLifecycle } from "./reload-environment.ts";
8
11
  import { assertDelegationAuthority } from "./delegation-authority.ts";
9
12
 
10
13
  export const definitionIdDescription =
11
- "Exact definitionId from delegate_describe.delegationArguments. Copy its agent together with this ID; " +
12
- "the ID alone does not select an agent. Required for Principal phases.";
14
+ "Optional; omit it after delegate_describe, which binds the agent's current definitionId for this session " +
15
+ "(required for Principal phases).";
13
16
 
14
17
  class DefinitionInputError extends Error {}
15
18
 
19
+ /** Where a delegation's definitionId came from: its own arguments, or this session's last describe of the agent. */
20
+ export type DefinitionIdSource = "supplied" | "remembered";
21
+ /**
22
+ * The definitionId a delegation was checked against, and its source. Returned in tool result details only: the
23
+ * ledger schema stays compatible with independently released readers; richer evidence needs an optional contract.
24
+ */
25
+ export interface DefinitionBinding {
26
+ definitionId: string;
27
+ source: DefinitionIdSource;
28
+ }
29
+
30
+ /**
31
+ * Owner decision 2026-11-17: the harness carries the IDs. Each omitted definitionId is filled from this Pi
32
+ * session's last successful describe of the same agent (kept on the reload lifecycle, see `ReloadLifecycle`).
33
+ * A supplied ID wins and never enters that memory. Call once per tool call, before any check, so every
34
+ * entry of one call is bound from one reading. The identity check that follows is the same either way.
35
+ */
36
+ export function bindDescribedDefinitions<T extends { agent?: string; definitionId?: string }>(
37
+ session: GrantsSession,
38
+ specs: readonly T[],
39
+ ): { specs: T[]; bindings: Array<DefinitionBinding | undefined> } {
40
+ const described = session.reloadLifecycle?.describedDefinitions;
41
+ const bindings = specs.map((spec): DefinitionBinding | undefined => {
42
+ if (spec.definitionId !== undefined) return { definitionId: spec.definitionId, source: "supplied" };
43
+ const remembered = spec.agent === undefined ? undefined : described?.get(spec.agent);
44
+ return remembered === undefined ? undefined : { definitionId: remembered, source: "remembered" };
45
+ });
46
+ return {
47
+ specs: specs.map((spec, index) => {
48
+ const binding = bindings[index];
49
+ return binding?.source === "remembered" ? { ...spec, definitionId: binding.definitionId } : spec;
50
+ }),
51
+ bindings,
52
+ };
53
+ }
54
+
55
+ /** A new, resumed or forked session, or a move in the session tree, has not seen this session's describes. */
56
+ export function forgetDescribedDefinitions(lifecycle: ReloadLifecycle): void {
57
+ delete lifecycle.describedDefinitions;
58
+ }
59
+
16
60
  export function assertDefinitionIdentity(
17
61
  session: GrantsSession,
18
62
  spec: { agent?: string; definitionId?: string },
63
+ source: DefinitionIdSource = "supplied",
19
64
  ): void {
20
65
  const definition = spec.agent ? session.definitions.get(spec.agent) : undefined;
21
66
  if (spec.definitionId !== undefined) {
22
67
  if (!spec.agent)
23
68
  throw new DefinitionInputError(
24
- "Missing delegation agent: definitionId does not select an agent. Copy BOTH agent and definitionId " +
25
- "from delegate_describe.delegationArguments, then add the task. No definition was selected.",
69
+ "Missing delegation agent: definitionId does not select an agent. Name the agent. No definition was selected.",
26
70
  );
27
- if (!definition)
71
+ if (!definition && source === "supplied")
28
72
  throw new DefinitionInputError(
29
73
  `Delegation agent ${JSON.stringify(spec.agent)} is not in the current selected definitions. ` +
30
74
  "Use the exact agent name returned by delegate_describe; refreshing an ID cannot correct a wrong agent name.",
31
75
  );
32
- if (definition.definitionId !== spec.definitionId)
76
+ if (definition?.definitionId !== spec.definitionId)
33
77
  throw new DefinitionInputError(
34
78
  `Definition snapshot changed or is unavailable for agent ${JSON.stringify(spec.agent)}: ` +
35
- "the supplied definitionId does not match its current selection. " +
36
- "Call delegate_describe for that agent and copy BOTH fields from delegationArguments; do not shorten or invent the ID.",
79
+ (source === "remembered"
80
+ ? "it changed since this session described it. Describe it again with delegate_describe."
81
+ : "the supplied definitionId does not match its current selection. " +
82
+ "Describe it again with delegate_describe and omit the ID."),
37
83
  );
38
84
  }
39
85
  if (definition?.binding && !spec.definitionId)
40
86
  throw new DefinitionInputError(
41
- `Principal delegation for agent ${JSON.stringify(spec.agent)} is missing definitionId. ` +
42
- "Call delegate_describe for that agent and copy BOTH fields from delegationArguments.",
87
+ `Principal delegation for agent ${JSON.stringify(spec.agent)} has no described definition. ` +
88
+ "Describe it first with delegate_describe.",
43
89
  );
44
90
  }
45
91
 
@@ -47,9 +93,10 @@ export function assertDefinitionIdentity(
47
93
  export function assertDefinitionInputsBeforeAdmission(
48
94
  session: GrantsSession,
49
95
  specs: readonly { agent?: string; definitionId?: string }[],
96
+ bindings: readonly (DefinitionBinding | undefined)[] = [],
50
97
  ): void {
51
98
  try {
52
- for (const spec of specs) assertDefinitionIdentity(session, spec);
99
+ for (const [index, spec] of specs.entries()) assertDefinitionIdentity(session, spec, bindings[index]?.source);
53
100
  } catch (error) {
54
101
  if (!(error instanceof DefinitionInputError)) throw error;
55
102
  error.message +=
@@ -65,10 +112,10 @@ export function registerDefinitionDescribe(pi: ExtensionAPI, session: GrantsSess
65
112
  label: "Describe a governed definition",
66
113
  description:
67
114
  "Read the exact selected definition identity and Principal binding before delegation. " +
68
- "Copy delegationArguments (agent and definitionId) into delegate or a batch/chain entry, then add its task. " +
69
- "Starts no child and grants nothing.",
115
+ "Binds its definitionId to this agent's later delegations in this session. Starts no child and grants nothing.",
70
116
  parameters: Type.Object({ agent: Type.String() }),
71
- async execute(_id, params) {
117
+ async execute(_id, params, _signal, _onUpdate, ctx) {
118
+ const lifecycle = session.reloadLifecycle;
72
119
  assertDelegationAuthority(session);
73
120
  await session.ensureDefinitions?.();
74
121
  if (!maySpawnDefinition(session.ownGrant, params.agent))
@@ -85,10 +132,21 @@ export function registerDefinitionDescribe(pi: ExtensionAPI, session: GrantsSess
85
132
  definitionId: definition.definitionId,
86
133
  delegationArguments: { agent: params.agent, definitionId: definition.definitionId },
87
134
  selectedResources: definition.selectedResources ?? null,
135
+ // Declared tools this session would run for the child itself, through its own tool pipeline (2026-11-17),
136
+ // for a child on this session's own provider and model, which is the only kind it runs them for. Like the
137
+ // rest of this answer, an observation: it grants nothing and admission still decides.
138
+ parentRunTools: liveParentTools(session, ceilingForDefinition(definition).capabilities, ctx, hostModel(ctx)),
139
+ // 2026-11-17: its declared tools only read, so a failure without an answer may be run once more (see
140
+ // `replay-safe.ts` for when). Every admitted plan's tools are exactly these (context modes only read), so the
141
+ // ceiling answers for the plan.
142
+ replaySafe: replaySafeCeiling(ceilingForDefinition(definition)),
88
143
  };
89
144
  const capture = publicEvidenceCall(session.publicEvidence, _id, "delegate_describe", [{ agent: params.agent }]);
90
145
  capture.selected(0, definition);
91
- return capture.finish({ content: [{ type: "text" as const, text: JSON.stringify(details) }], details });
146
+ const result = capture.finish({ content: [{ type: "text" as const, text: JSON.stringify(details) }], details });
147
+ // Only an answer actually returned binds; the lifecycle read at entry, so a replaced owner never receives it.
148
+ if (lifecycle) (lifecycle.describedDefinitions ??= new Map()).set(params.agent, definition.definitionId);
149
+ return result;
92
150
  },
93
151
  });
94
152
  }
@@ -2,7 +2,13 @@ import { dashboardSummaryDescription } from "../src/products/activity-summary.ts
2
2
  import { operationIdShape, claimDelegationOperation, existingOperationOutcome } from "./delegation-operations.ts";
3
3
  import { publicEvidenceCall } from "./public-evidence.ts";
4
4
  import { executionEvidenceContent } from "./execution-evidence.ts";
5
- import { assertDefinitionInputsBeforeAdmission, definitionIdDescription } from "./definition-describe.ts";
5
+ import { delegationUsage } from "../src/executors/child-usage.ts";
6
+ import { childUsageReport } from "./child-usage-report.ts";
7
+ import {
8
+ assertDefinitionInputsBeforeAdmission,
9
+ bindDescribedDefinitions,
10
+ definitionIdDescription,
11
+ } from "./definition-describe.ts";
6
12
  /**
7
13
  * `delegate_chain` — a governed sequential pipeline, planned and gated as one unit (ADR-0033).
8
14
  *
@@ -92,9 +98,7 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
92
98
  `that output is appended instead. The first step never receives one.`,
93
99
  }),
94
100
  agent: Type.Optional(
95
- Type.String({
96
- description: "Definition for this step; copy with definitionId from delegate_describe.delegationArguments.",
97
- }),
101
+ Type.String({ description: "Definition for this step. delegate_describe binds its definitionId." }),
98
102
  ),
99
103
  tools: Type.Optional(Type.Array(Type.String(), { description: "Capabilities, when no 'agent' fits." })),
100
104
  model: Type.Optional(Type.String({ description: "Model as provider/id. Defaults to this session's." })),
@@ -135,10 +139,15 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
135
139
  parameters: params,
136
140
  prepareArguments: withoutRetiredDelegationArguments,
137
141
  async execute(_toolCallId, args, signal, onUpdate, ctx) {
142
+ // A step that throws stops the chain; the steps that ran are reported through Pi's tool_result hook.
143
+ const usageReport = childUsageReport(session, _toolCallId);
138
144
  assertDelegationAuthority(session);
139
- const steps = args.steps ?? [];
145
+ const requested = args.steps ?? [];
140
146
  await session.ensureDefinitions?.();
141
- assertDefinitionInputsBeforeAdmission(session, steps);
147
+ // Bound once for the whole chain, before planning: every step uses this call's reading of the memory.
148
+ const bound = bindDescribedDefinitions(session, requested);
149
+ const steps = bound.specs;
150
+ assertDefinitionInputsBeforeAdmission(session, steps, bound.bindings);
142
151
 
143
152
  // **Every cheap refusal happens before any human is asked.** Yesterday's lesson on the `delegate` path: with
144
153
  // `PI_DADDY_HERDR=1` and herdr down, the gate ran first, an operator approved `bash`, a 30-day entry was
@@ -166,16 +175,18 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
166
175
  },
167
176
  ctx,
168
177
  signal,
178
+ bound.bindings[0],
169
179
  );
170
180
  const capture = publicEvidenceCall(
171
181
  session.publicEvidence,
172
182
  _toolCallId,
173
183
  "delegate_chain",
174
- steps,
184
+ requested,
175
185
  executionIds.map((id, index) => (index === 0 ? (firstClaim?.operation.executionId ?? id) : id)),
176
186
  );
177
187
  if (firstClaim?.reused) {
178
188
  const outcome = existingOperationOutcome(firstClaim, session.depth + 1);
189
+ if (bound.bindings[0]) outcome.definitionBinding = { ...bound.bindings[0] };
179
190
  return capture.finish(
180
191
  {
181
192
  isError: false,
@@ -183,7 +194,13 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
183
194
  { type: "text", text: outcome.text },
184
195
  executionEvidenceContent("delegate_chain", [outcome], steps.length),
185
196
  ],
186
- details: { outcomes: [outcome], steps: steps.length, completed: 0, aborted: true },
197
+ details: {
198
+ outcomes: [outcome],
199
+ steps: steps.length,
200
+ completed: 0,
201
+ aborted: true,
202
+ childUsage: delegationUsage([outcome]).childUsage,
203
+ },
187
204
  },
188
205
  [outcome],
189
206
  );
@@ -222,6 +239,7 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
222
239
  runtimeChoices.set(step, selected);
223
240
  return selected.model;
224
241
  },
242
+ ctx,
225
243
  );
226
244
  if (chainPlan.doomed) {
227
245
  const message =
@@ -349,6 +367,8 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
349
367
 
350
368
  const outcomes: Array<import("./execute-child.ts").DelegationOutcome & { step: number; agent?: string }> = [];
351
369
  let previous: string | undefined;
370
+ // The occurrence that wrote `previous`: the step's own, or its automatic retry's (2026-11-17).
371
+ let previousExecutionId: string | undefined;
352
372
  let aborted = false;
353
373
  let blockedReason: "full-final-too-large-for-handoff" | undefined;
354
374
  /**
@@ -373,7 +393,7 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
373
393
  chainPlan.uses.get(index)?.has(key) && (approval.scope !== "once" || approvalStep.get(key) === index)
374
394
  );
375
395
  });
376
- const outcome = await runOneDelegation(
396
+ const running = runOneDelegation(
377
397
  session,
378
398
  chainStepSpec(step, previous),
379
399
  {
@@ -387,6 +407,7 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
387
407
  signal,
388
408
  {
389
409
  ...(index === 0 ? { capacityReservation: firstReservation, operationClaim: firstClaim } : {}),
410
+ definitionBinding: bound.bindings[index],
390
411
  resolvedRuntime: runtimeChoices.get(step),
391
412
  onDefinition: (definition) => capture.selected(index, definition),
392
413
  preApproved: availableForStep,
@@ -406,9 +427,10 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
406
427
  },
407
428
  // Provenance: which child's output composed THIS step's task (ADR-0033). Absent for step 1.
408
429
  taskFrom: index === 0 ? undefined : childSpawnId(session.ownSpawnId, index - 1),
409
- taskFromExecutionId: index === 0 ? undefined : executionIds[index - 1],
430
+ taskFromExecutionId: index === 0 ? undefined : previousExecutionId,
410
431
  },
411
432
  );
433
+ const outcome = await usageReport.settle(running);
412
434
 
413
435
  children[index].state = outcome.ok ? "completed" : "failed";
414
436
  children[index].settledAt = Date.now();
@@ -439,6 +461,7 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
439
461
  break;
440
462
  }
441
463
  previous = outcome.text;
464
+ previousExecutionId = outcome.retry?.executionId ?? executionIds[index];
442
465
  }
443
466
  paint.flush();
444
467
 
@@ -471,8 +494,11 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
471
494
  if (outcomes[0].refusal) throw new GovernanceRefusal({ ...outcomes[0].refusal, message });
472
495
  throw new Error(message);
473
496
  }
497
+ // Every step that ran, including the one that stopped the chain (2026-11-17).
498
+ const { usage, childUsage } = delegationUsage(outcomes);
474
499
  return capture.finish(
475
500
  {
501
+ ...(usage ? { usage } : {}),
476
502
  isError: (aborted && !outcomes.at(-1)?.operation?.reused) || outcomes.some((o) => o.control === "failed"),
477
503
  content: [
478
504
  { type: "text", text: `${report}${tail}` },
@@ -486,6 +512,7 @@ export function registerChainTool(pi: ExtensionAPI, session: GrantsSession): voi
486
512
  budgetPerStep: firstReservation.childAllowance,
487
513
  ...(blockedReason ? { blockedReason } : {}),
488
514
  refusals: outcomes.map((outcome) => outcome.refusal ?? null),
515
+ childUsage,
489
516
  },
490
517
  },
491
518
  outcomes,