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