@x-otto/subagent 0.0.0-stage → 0.4.0-beta.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/dist/index.js ADDED
@@ -0,0 +1,3098 @@
1
+ import { SLOTS, SUBAGENT_MAX_FAN_OUT_FIELD_SPEC, SUBAGENT_MODELS_FIELD_SPEC, THINKING_LEVELS, TIMINGS, TOOL_DEADLINE_ABORT_REASON, TOOL_NAMES, WORKER_SLOT_QUEUEING_FIELD_SPEC, admitChildModel, checkPlanItemIds, defineTool, describeSubagentRecovery, effectsOf, inStreamRetryOf, isPartialReason, parseThinkingLevel, resubmitRetryOf, textToolContent, toModelRef } from "@x-otto/kernel";
2
+ import { safeEmit } from "@x-otto/hooks";
3
+ import { createMemo, defineComponent } from "@x-otto/universal";
4
+ import { SlotQueue } from "@x-otto/jobs";
5
+ import { isPathWithin, settleWithin } from "@x-otto/shared";
6
+ import { createHash } from "node:crypto";
7
+ import { mkdir, readFile, readdir, rename, rm, stat } from "node:fs/promises";
8
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
9
+ import { objectSchema } from "@x-otto/tool-schema";
10
+ import { execFile } from "node:child_process";
11
+ import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
12
+ import { promisify } from "node:util";
13
+ import { PROCESS_START_TOLERANCE_MS, ensurePrivateDir, isReliableBootId, nodeBootId, ownProcessStartedAt, probeProcessStartedAt, readJsonFile, writeFileAtomic, writeJsonAtomic } from "@x-otto/atomic-fs";
14
+
15
+ //#region src/governor.ts
16
+ const DEFAULT_MAX_DELEGATION_DEPTH = 1;
17
+ const DEFAULT_MAX_FAN_OUT_PER_PARENT = 5;
18
+ function fanOutLimitOf(limits) {
19
+ return typeof limits.maxFanOutPerParent === "function" ? limits.maxFanOutPerParent() : limits.maxFanOutPerParent;
20
+ }
21
+ function resolveGovernorLimits(input) {
22
+ return {
23
+ maxDelegationDepth: input.maxDelegationDepth ?? 1,
24
+ maxFanOutPerParent: input.maxFanOutPerParent ?? 5
25
+ };
26
+ }
27
+ var Governor = class {
28
+ limits;
29
+ constructor(limits) {
30
+ this.limits = Object.freeze({ ...limits });
31
+ }
32
+ checkDepth(depth) {
33
+ return (depth ?? 0) + 1 > this.limits.maxDelegationDepth;
34
+ }
35
+ checkFanOut(activeRuns) {
36
+ return activeRuns <= fanOutLimitOf(this.limits);
37
+ }
38
+ };
39
+ function depthMessage(limit) {
40
+ return `Delegation depth limit (${limit}) reached — complete this subtask yourself instead of delegating further.`;
41
+ }
42
+ function fanOutMessage(parentSessionId, limit) {
43
+ return `Fan-out limit (${limit}) reached for session "${parentSessionId}" — wait for in-flight subagents to finish before delegating more.`;
44
+ }
45
+ function unknownProviderMessage(name, available) {
46
+ return `No subagent provider registered under "${name}" (available: ${available.length > 0 ? available.join(", ") : "none"})`;
47
+ }
48
+
49
+ //#endregion
50
+ //#region src/errors.ts
51
+ var SubagentDelegationError = class extends Error {
52
+ code;
53
+ constructor(message, code) {
54
+ super(message);
55
+ this.name = "SubagentDelegationError";
56
+ this.code = code;
57
+ }
58
+ };
59
+
60
+ //#endregion
61
+ //#region src/control-projection.ts
62
+ function artifactsFieldOf(result) {
63
+ return {
64
+ ...result.artifacts === void 0 ? {} : { artifacts: result.artifacts },
65
+ ...result.isolation === void 0 ? {} : { isolation: result.isolation }
66
+ };
67
+ }
68
+ function toOutcome(result) {
69
+ switch (result.status) {
70
+ case "completed": return {
71
+ status: "completed",
72
+ output: result.text,
73
+ ...artifactsFieldOf(result)
74
+ };
75
+ case "partial": return {
76
+ status: "partial",
77
+ output: result.text,
78
+ reason: result.reason,
79
+ ...artifactsFieldOf(result)
80
+ };
81
+ case "cancelled": return {
82
+ status: "cancelled",
83
+ cause: result.cause,
84
+ forced: false,
85
+ ...artifactsFieldOf(result)
86
+ };
87
+ case "failed": return {
88
+ status: "failed",
89
+ error: result.error,
90
+ ...artifactsFieldOf(result)
91
+ };
92
+ }
93
+ }
94
+ function messageOf(error) {
95
+ return error instanceof Error ? error.message : String(error);
96
+ }
97
+ const TITLE_MAX_CHARS = 80;
98
+ function collapseWhitespace(text) {
99
+ return text.replace(/\s+/g, " ").trim();
100
+ }
101
+ function titleOfRequest(request) {
102
+ const label = collapseWhitespace(request.label ?? "");
103
+ const collapsed = label === "" ? collapseWhitespace(request.prompt) : label;
104
+ if (collapsed === "") return;
105
+ if (collapsed.length <= TITLE_MAX_CHARS) return collapsed;
106
+ return `${collapsed.slice(0, TITLE_MAX_CHARS)}…`;
107
+ }
108
+ const WAKE_JOB_KEY_PREFIX = "wake:";
109
+ function isWakeJobKey(jobKey) {
110
+ return jobKey !== void 0 && jobKey.startsWith("wake:");
111
+ }
112
+ function isActiveDelegationRun(snapshot) {
113
+ if (snapshot.kind !== "subagent" || isWakeJobKey(snapshot.jobKey)) return false;
114
+ if (snapshot.owner === void 0) return false;
115
+ if (snapshot.status === "running") return true;
116
+ return snapshot.release.phase !== "confirmed" && snapshot.release.phase !== "abandoned";
117
+ }
118
+
119
+ //#endregion
120
+ //#region src/control-followup.ts
121
+ function lastAssistantTextOf(messages) {
122
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
123
+ const message = messages[index];
124
+ if (message?.role !== "assistant") continue;
125
+ const content = message.content;
126
+ if (typeof content === "string") return content;
127
+ const texts = (Array.isArray(content) ? content : []).map((part) => part !== null && typeof part === "object" && "text" in part ? String(part.text) : "").filter((text) => text !== "");
128
+ if (texts.length > 0) return texts.join("\n");
129
+ }
130
+ return "";
131
+ }
132
+ var SubagentFollowup = class {
133
+ constructor(options) {
134
+ this.options = options;
135
+ }
136
+ async followup(id, text, caller, expectedJobKey) {
137
+ return (await this.followupReceipt({ jobId: id }, text, caller, expectedJobKey)).outcome;
138
+ }
139
+ async followupReceipt(address, text, caller, expectedJobKey) {
140
+ const callerId = caller.sessionId;
141
+ const id = address.jobId;
142
+ const snapshot = id === void 0 ? void 0 : this.options.tasks().forOwner(callerId).get(id);
143
+ const key = expectedJobKey === void 0 ? void 0 : expectedJobKey.trim();
144
+ if (key !== void 0 && key !== "" && snapshot?.jobKey !== key) return { outcome: "failed" };
145
+ const fromJob = snapshot?.subjectId;
146
+ const fromChild = address.childSessionId;
147
+ if (fromJob !== void 0 && fromChild !== void 0 && fromJob !== fromChild) return { outcome: "failed" };
148
+ const childSessionId = fromChild ?? fromJob;
149
+ if (childSessionId === void 0 || !this.options.isOwnedBy(childSessionId, callerId)) return { outcome: "failed" };
150
+ const handle = this.options.sessions().get(childSessionId);
151
+ if (handle === void 0) return { outcome: "failed" };
152
+ const delivery = handle.deliver({
153
+ role: "user",
154
+ content: text,
155
+ timestamp: this.options.clock.now()
156
+ }, "steer");
157
+ if (delivery.outcome !== "delivered" || delivery.inputId === void 0) return {
158
+ outcome: delivery.outcome,
159
+ ...delivery.reason === void 0 ? {} : { reason: delivery.reason }
160
+ };
161
+ const jobId = await this.registerWakeJob({
162
+ callerId,
163
+ childSessionId,
164
+ inputId: delivery.inputId,
165
+ handle,
166
+ ...snapshot?.label === void 0 ? {} : { label: snapshot.label }
167
+ });
168
+ return {
169
+ outcome: delivery.outcome,
170
+ ...jobId === void 0 ? {} : { jobId },
171
+ jobKey: `${WAKE_JOB_KEY_PREFIX}${delivery.inputId}`,
172
+ wakeJob: jobId !== void 0
173
+ };
174
+ }
175
+ async registerWakeJob(input) {
176
+ const outputOf = () => lastAssistantTextOf(input.handle.messages);
177
+ let settleWake;
178
+ const done = new Promise((resolve) => {
179
+ settleWake = resolve;
180
+ });
181
+ let finished = false;
182
+ let jobId;
183
+ let unsubscribe;
184
+ const finish = (outcome) => {
185
+ if (finished) return;
186
+ finished = true;
187
+ unsubscribe?.();
188
+ unsubscribe = void 0;
189
+ settleWake(jobId === void 0 ? outcome : {
190
+ ...outcome,
191
+ jobId
192
+ });
193
+ };
194
+ const observe = this.options.observe;
195
+ if (observe !== void 0) unsubscribe = observe(`subagent::wake-observer::${input.inputId}`, TIMINGS.turnEnd, (payload) => {
196
+ if ((payload?.inputIds)?.includes(input.inputId) === true) finish({
197
+ status: "completed",
198
+ output: outputOf()
199
+ });
200
+ });
201
+ const starting = this.options.tasks().start({
202
+ kind: "subagent",
203
+ label: input.label === void 0 ? "wake" : `wake ${input.label}`,
204
+ owner: input.callerId,
205
+ attachment: "detached",
206
+ subjectId: input.childSessionId,
207
+ jobKey: `${WAKE_JOB_KEY_PREFIX}${input.inputId}`,
208
+ run: () => ({
209
+ done,
210
+ cancel: (cause) => {
211
+ input.handle.withdrawLastIfDangling();
212
+ finish({
213
+ status: "cancelled",
214
+ cause,
215
+ forced: false
216
+ });
217
+ },
218
+ release: async () => {
219
+ unsubscribe?.();
220
+ unsubscribe = void 0;
221
+ },
222
+ readOutput: outputOf
223
+ })
224
+ });
225
+ try {
226
+ jobId = (await starting).id;
227
+ } catch {
228
+ unsubscribe?.();
229
+ unsubscribe = void 0;
230
+ }
231
+ return jobId;
232
+ }
233
+ };
234
+
235
+ //#endregion
236
+ //#region src/release.ts
237
+ const RELEASE_REPORT_TIMEOUT_MS = 5e3;
238
+ async function releaseFailure(pending) {
239
+ if (pending === void 0) return void 0;
240
+ let timer;
241
+ try {
242
+ return await Promise.race([pending.then(() => void 0, (error) => error instanceof Error ? error.message : String(error)), new Promise((resolve) => {
243
+ timer = setTimeout(() => resolve("resource release remains pending"), RELEASE_REPORT_TIMEOUT_MS);
244
+ })]);
245
+ } finally {
246
+ if (timer !== void 0) clearTimeout(timer);
247
+ }
248
+ }
249
+
250
+ //#endregion
251
+ //#region src/control-state.ts
252
+ var SubagentControlState = class {
253
+ starting = /* @__PURE__ */ new Set();
254
+ reservations = /* @__PURE__ */ new Set();
255
+ admitting = /* @__PURE__ */ new Map();
256
+ retiring = /* @__PURE__ */ new Map();
257
+ spawnedBy = /* @__PURE__ */ new Map();
258
+ disposed = false;
259
+ disposal;
260
+ subagentRevision = 0;
261
+ bumpSubagentRevision() {
262
+ this.subagentRevision += 1;
263
+ }
264
+ };
265
+ function isSubagentControlState(value) {
266
+ if (value === null || typeof value !== "object") return false;
267
+ const state = value;
268
+ return state.starting instanceof Set && state.reservations instanceof Set && state.admitting instanceof Map && state.retiring instanceof Map && state.spawnedBy instanceof Map && typeof state.disposed === "boolean" && (state.disposal === void 0 || state.disposal !== null && typeof state.disposal.then === "function") && typeof state.subagentRevision === "number";
269
+ }
270
+ function disposeSubagentControlState(state, options) {
271
+ if (state.disposal !== void 0) return state.disposal;
272
+ state.disposed = true;
273
+ const tickets = [...state.starting];
274
+ for (const ticket of tickets) cancelStarting(ticket, "disposed");
275
+ const settleTickets = Promise.allSettled(tickets.map((ticket) => releaseTicketResources(state, ticket)));
276
+ const settleRuns = options.cancelActiveRuns("disposed").catch((error) => {
277
+ options.onCancelError?.(error);
278
+ throw error;
279
+ });
280
+ state.disposal = releaseFailure(Promise.allSettled([settleTickets, settleRuns]).then(([ticketSettled, runSettled]) => {
281
+ state.starting.clear();
282
+ const failures = ticketSettled.status === "fulfilled" ? ticketSettled.value.filter((entry) => entry.status === "rejected").map((entry) => entry.reason) : [ticketSettled.reason];
283
+ if (runSettled.status === "rejected") failures.push(runSettled.reason);
284
+ if (failures.length > 0) throw new SubagentDelegationError(`Subagent resources did not confirm release on dispose: ${failures.map(messageOf).join("; ")}`);
285
+ })).then((failure) => {
286
+ if (failure !== void 0) {
287
+ state.disposal = void 0;
288
+ throw new SubagentDelegationError(failure);
289
+ }
290
+ });
291
+ return state.disposal;
292
+ }
293
+ function releaseReservationIn(state, ticket) {
294
+ const reservation = ticket.phase.reservation;
295
+ if (reservation.kind !== "held") return;
296
+ state.reservations.delete(reservation.sessionId);
297
+ ticket.phase = withReservation(ticket.phase, { kind: "none" });
298
+ }
299
+ function detachTicketIn(state, ticket) {
300
+ releaseReservationIn(state, ticket);
301
+ state.starting.delete(ticket);
302
+ ticket.settle();
303
+ }
304
+ function closeTicketIn(state, ticket) {
305
+ detachTicketIn(state, ticket);
306
+ }
307
+ async function releaseTicketResources(state, ticket) {
308
+ await ticket.settlement;
309
+ const late = lateRunOf(ticket.phase);
310
+ if (late === void 0) return;
311
+ await late.release();
312
+ await whenReleased(late);
313
+ closeTicketIn(state, ticket);
314
+ }
315
+ function whenReleased(run) {
316
+ const release = () => run.release();
317
+ return run.done.then(release, release);
318
+ }
319
+ function cancelOnce(record, cause) {
320
+ if (record.cancelled) return;
321
+ record.cancelled = true;
322
+ record.run.cancel(cause);
323
+ }
324
+ function cancelStarting(ticket, cause) {
325
+ const next = withCancellation(ticket.phase, cause);
326
+ if (next === void 0) return;
327
+ ticket.phase = next;
328
+ if (!ticket.controller.signal.aborted) ticket.controller.abort();
329
+ }
330
+ function causeOf(phase) {
331
+ switch (phase.kind) {
332
+ case "pending":
333
+ case "handed-off": return;
334
+ case "cancelled":
335
+ case "handed-off-cancelled":
336
+ case "abandoned":
337
+ case "retiring": return phase.cause;
338
+ }
339
+ }
340
+ function lateRunOf(phase) {
341
+ return phase.kind === "retiring" ? phase.run : void 0;
342
+ }
343
+ function withReservation(phase, reservation) {
344
+ switch (phase.kind) {
345
+ case "pending": return {
346
+ kind: "pending",
347
+ reservation
348
+ };
349
+ case "cancelled": return {
350
+ kind: "cancelled",
351
+ cause: phase.cause,
352
+ reservation
353
+ };
354
+ case "handed-off": return {
355
+ kind: "handed-off",
356
+ reservation
357
+ };
358
+ case "handed-off-cancelled": return {
359
+ kind: "handed-off-cancelled",
360
+ cause: phase.cause,
361
+ reservation
362
+ };
363
+ case "abandoned": return {
364
+ kind: "abandoned",
365
+ cause: phase.cause,
366
+ reservation
367
+ };
368
+ case "retiring": return {
369
+ kind: "retiring",
370
+ cause: phase.cause,
371
+ reservation,
372
+ run: phase.run
373
+ };
374
+ }
375
+ }
376
+ function withCancellation(phase, cause) {
377
+ switch (phase.kind) {
378
+ case "pending": return {
379
+ kind: "cancelled",
380
+ cause,
381
+ reservation: phase.reservation
382
+ };
383
+ case "handed-off": return {
384
+ kind: "handed-off-cancelled",
385
+ cause,
386
+ reservation: phase.reservation
387
+ };
388
+ case "cancelled":
389
+ case "handed-off-cancelled":
390
+ case "abandoned":
391
+ case "retiring": return;
392
+ }
393
+ }
394
+ function ticketDisposition(phase) {
395
+ switch (phase.kind) {
396
+ case "pending":
397
+ case "cancelled": return "close";
398
+ case "handed-off":
399
+ case "handed-off-cancelled": return "detach";
400
+ case "abandoned":
401
+ case "retiring": return "keep-open";
402
+ }
403
+ }
404
+
405
+ //#endregion
406
+ //#region src/control-release.ts
407
+ const RELEASE_CONFIRM_POLL_MS = 20;
408
+ const SUBTREE_RELEASE_BUDGET_MS = 5e3;
409
+ const delayOf = (ms) => new Promise((resolve) => {
410
+ setTimeout(resolve, ms);
411
+ });
412
+ const OWNER_ID_PREFIX = "subagent:";
413
+ function ownerIdOf(childSessionId, jobId) {
414
+ return `${OWNER_ID_PREFIX}${childSessionId}:${jobId}`;
415
+ }
416
+ async function releaseConfirmedOf(registry, snapshots, remainingMs) {
417
+ const pending = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot.owner ?? ""]));
418
+ const failures = [];
419
+ while (pending.size > 0) {
420
+ if (remainingMs() <= 0) {
421
+ failures.push(`release for ${pending.size} job(s) did not confirm within ${SUBTREE_RELEASE_BUDGET_MS}ms`);
422
+ break;
423
+ }
424
+ await delayOf(RELEASE_CONFIRM_POLL_MS);
425
+ for (const [id, owner] of [...pending]) {
426
+ const snapshot = registry.forOwner(owner).get(id);
427
+ if (snapshot === void 0 || snapshot.release.phase !== "pending") {
428
+ pending.delete(id);
429
+ if (snapshot?.release.phase === "failed") failures.push(`release for job "${id}" failed: ${snapshot.release.error}`);
430
+ }
431
+ }
432
+ }
433
+ if (failures.length > 0) throw new Error(failures.join("; "));
434
+ }
435
+ async function retryFailedReleases(registry, owner, targets) {
436
+ const failures = [];
437
+ for (const snapshot of targets) {
438
+ if (snapshot.release.phase !== "failed") continue;
439
+ const view = registry.forOwner(owner);
440
+ const retry = view.retryRelease;
441
+ if (retry === void 0) continue;
442
+ const failure = await retry.call(view, snapshot.id).then(() => void 0, (error) => error);
443
+ if (failure !== void 0) failures.push(failure);
444
+ }
445
+ return failures;
446
+ }
447
+ async function cancelDelegationRuns(registry, cause) {
448
+ if (registry === void 0) return;
449
+ const snapshots = registry.admin().live().filter((snapshot) => isActiveDelegationRun(snapshot));
450
+ const failure = (await Promise.allSettled(snapshots.map((snapshot) => registry.forOwner(snapshot.owner ?? "").kill(snapshot.id, cause)))).find((entry) => entry.status === "rejected");
451
+ if (failure !== void 0) throw failure.reason;
452
+ const startedAt = Date.now();
453
+ await releaseConfirmedOf(registry, snapshots, () => startedAt + SUBTREE_RELEASE_BUDGET_MS - Date.now());
454
+ }
455
+ var SubagentRelease = class {
456
+ constructor(options, state) {
457
+ this.options = options;
458
+ this.state = state;
459
+ }
460
+ releaseParent = (parentSessionId) => {
461
+ const inFlight = this.state.retiring.get(parentSessionId);
462
+ if (inFlight !== void 0) return inFlight;
463
+ const releasing = this.releaseParentAttempt(parentSessionId).then(() => {
464
+ this.state.retiring.delete(parentSessionId);
465
+ }, (error) => {
466
+ this.state.retiring.delete(parentSessionId);
467
+ throw new SubagentDelegationError(`Subagent resources for session "${parentSessionId}" did not confirm release: ${messageOf(error)}`);
468
+ });
469
+ this.state.retiring.set(parentSessionId, releasing);
470
+ releasing.catch(() => void 0);
471
+ return releasing;
472
+ };
473
+ dispose = async () => {
474
+ this.options.disposeQueue();
475
+ this.detachProcessOwners();
476
+ await disposeSubagentControlState(this.state, {
477
+ cancelActiveRuns: (cause) => this.options.cancelActiveRuns(cause),
478
+ onCancelError: (error) => this.options.diagnose("SUBAGENT_CANCEL_FAILED", error)
479
+ });
480
+ };
481
+ async releaseParentAttempt(parentSessionId) {
482
+ const startedAt = this.options.clock.now();
483
+ const remainingMs = () => startedAt + SUBTREE_RELEASE_BUDGET_MS - this.options.clock.now();
484
+ const tickets = [...this.state.starting].filter((ticket) => ticket.parentSessionId === parentSessionId);
485
+ for (const ticket of tickets) cancelStarting(ticket, "owner");
486
+ const registry = this.options.tasks();
487
+ const targets = registry === void 0 ? [] : this.options.delegationJobsOf(parentSessionId);
488
+ const retried = registry === void 0 ? void 0 : retryFailedReleases(registry, parentSessionId, targets);
489
+ const failures = (await Promise.allSettled([...tickets.map((ticket) => releaseTicketResources(this.state, ticket)), ...registry === void 0 ? [] : targets.map((snapshot) => registry.forOwner(parentSessionId).kill(snapshot.id, "owner"))])).filter((entry) => entry.status === "rejected").map((entry) => entry.reason);
490
+ if (retried !== void 0) failures.push(...await retried);
491
+ if (registry !== void 0) {
492
+ const confirmed = await releaseConfirmedOf(registry, targets, remainingMs).then(() => void 0, (error) => error);
493
+ if (confirmed !== void 0) failures.push(confirmed);
494
+ }
495
+ if (failures.length > 0) {
496
+ const failure = failures.length === 1 ? failures[0] : /* @__PURE__ */ new Error(`${failures.length} subagent resources did not confirm release: ${failures.map((entry) => messageOf(entry)).join("; ")}`);
497
+ this.options.diagnose("SUBAGENT_RELEASE_FAILED", failure);
498
+ throw failure;
499
+ }
500
+ }
501
+ detachProcessOwners() {
502
+ try {
503
+ const owners = this.options.processOwners();
504
+ if (owners === void 0) return;
505
+ for (const snapshot of this.options.delegationJobsOf()) {
506
+ if (snapshot.subjectId === void 0) continue;
507
+ owners.unregister(ownerIdOf(snapshot.subjectId, snapshot.id));
508
+ }
509
+ } catch (error) {
510
+ this.options.diagnose("SUBAGENT_RELEASE_FAILED", error);
511
+ }
512
+ }
513
+ };
514
+
515
+ //#endregion
516
+ //#region src/control.ts
517
+ const SPAWNED_BY_LIMIT = 1024;
518
+ const MAX_ANCESTRY_DEPTH = 8;
519
+ const NO_SLOT_MESSAGE = "no free worker slot: the subagent was not started. Close a session (or wait for one to free its slot) and retry.";
520
+ var SubagentControlImpl = class {
521
+ providerTable = /* @__PURE__ */ new Map();
522
+ governor;
523
+ options;
524
+ state;
525
+ queue;
526
+ followupOps;
527
+ releaseOps;
528
+ fanOutLimit = () => fanOutLimitOf(this.governor.limits);
529
+ constructor(options, state = new SubagentControlState()) {
530
+ this.state = state;
531
+ this.queue = new SlotQueue(options.slotWait);
532
+ this.options = Object.freeze({
533
+ ...options,
534
+ limits: Object.freeze({ ...options.limits })
535
+ });
536
+ const resolved = resolveGovernorLimits(this.options.limits ?? {});
537
+ const baseFanOut = fanOutLimitOf(resolved);
538
+ const dynamic = this.options.fanOutLimit;
539
+ this.governor = new Governor(dynamic === void 0 ? resolved : {
540
+ ...resolved,
541
+ maxFanOutPerParent: () => dynamic() ?? baseFanOut
542
+ });
543
+ this.followupOps = new SubagentFollowup({
544
+ tasks: () => this.options.tasks(),
545
+ sessions: () => this.options.sessions(),
546
+ clock: this.options.clock,
547
+ isOwnedBy: (childSessionId, callerId) => this.isOwnedBy(childSessionId, callerId, void 0),
548
+ ...this.options.observe === void 0 ? {} : { observe: this.options.observe }
549
+ });
550
+ this.releaseOps = new SubagentRelease({
551
+ clock: this.options.clock,
552
+ tasks: () => this.options.tasks(),
553
+ processOwners: () => this.options.processOwners?.(),
554
+ disposeQueue: () => this.queue.dispose(),
555
+ delegationJobsOf: (owner) => this.delegationJobsOf(owner),
556
+ cancelActiveRuns: (cause) => cancelDelegationRuns(this.options.tasks(), cause),
557
+ diagnose: (code, error) => this.diagnose(code, error)
558
+ }, this.state);
559
+ }
560
+ queueDepth = () => this.queue.depth();
561
+ retireQueue = () => this.queue.dispose();
562
+ drainQueued = (limit) => this.queue.drain(limit);
563
+ registerProvider = (provider) => {
564
+ const previous = this.providerTable.get(provider.name);
565
+ this.providerTable.set(provider.name, provider);
566
+ return () => {
567
+ if (this.providerTable.get(provider.name) !== provider) return;
568
+ if (previous === void 0) this.providerTable.delete(provider.name);
569
+ else this.providerTable.set(provider.name, previous);
570
+ };
571
+ };
572
+ providers = () => [...this.providerTable.keys()];
573
+ delegationDepthLimit = () => this.governor.limits.maxDelegationDepth;
574
+ start = async (request, mode, provider) => {
575
+ if (this.state.disposed) throw new SubagentDelegationError("Subagent controller is disposed and cannot start new runs");
576
+ if (this.state.retiring.has(request.parent.sessionId)) throw new SubagentDelegationError("Subagent parent owner is closing and cannot start new runs");
577
+ const selected = this.selectProvider(provider);
578
+ this.assertCapabilities(selected, request);
579
+ const ticket = this.openTicket(request.parent.sessionId);
580
+ this.state.starting.add(ticket);
581
+ const unbind = this.forwardSignal(request.signal, ticket);
582
+ try {
583
+ this.assertStartLive(ticket);
584
+ await this.assertResumeOwnership(request, ticket);
585
+ this.assertStartLive(ticket);
586
+ if (this.governor.checkDepth(request.parent.depth)) throw new SubagentDelegationError(depthMessage(this.governor.limits.maxDelegationDepth));
587
+ const taskRegistry = this.options.tasks();
588
+ if (taskRegistry === void 0) throw new SubagentDelegationError("subagent delegation requires the job registry (@x-otto/jobs) to be installed");
589
+ this.assertStartLive(ticket);
590
+ let settleOutcome;
591
+ const jobOutcome = new Promise((resolve) => {
592
+ settleOutcome = resolve;
593
+ });
594
+ let startedRun;
595
+ let recordRef;
596
+ let applyUpdate;
597
+ let admitted = false;
598
+ const admit = () => {
599
+ if (!admitted) {
600
+ admitted = true;
601
+ this.noteAdmitting(parentSessionId, -1);
602
+ }
603
+ };
604
+ let admissionGate;
605
+ let currentTicket = ticket;
606
+ let queuedJobId;
607
+ const producer = {
608
+ done: jobOutcome,
609
+ cancel: (cause) => {
610
+ if (recordRef !== void 0) {
611
+ cancelOnce(recordRef, cause);
612
+ return;
613
+ }
614
+ if (startedRun !== void 0) {
615
+ startedRun.cancel(cause);
616
+ return;
617
+ }
618
+ if (queuedJobId !== void 0 && this.queue.remove(queuedJobId)) {
619
+ settleOutcome({
620
+ status: "cancelled",
621
+ cause,
622
+ forced: false
623
+ });
624
+ return;
625
+ }
626
+ cancelStarting(currentTicket, cause);
627
+ },
628
+ release: async () => {
629
+ if (startedRun !== void 0) {
630
+ await startedRun.release();
631
+ return;
632
+ }
633
+ await releaseTicketResources(this.state, currentTicket);
634
+ },
635
+ readOutput: () => startedRun?.readOutput?.() ?? "",
636
+ readProgress: () => startedRun?.readProgress?.() ?? 0
637
+ };
638
+ const subagentSpec = {
639
+ kind: "subagent",
640
+ label: request.label ?? request.prompt.slice(0, 80),
641
+ owner: request.parent.sessionId,
642
+ attachment: mode === "sync" ? "attached" : "detached",
643
+ ...request.resultPolicy !== void 0 ? { resultPolicy: request.resultPolicy } : {},
644
+ ...request.itemIds !== void 0 ? { itemIds: request.itemIds } : {},
645
+ ...request.originTurn !== void 0 ? { originTurn: request.originTurn } : {},
646
+ ...request.stageAttemptId === void 0 ? {} : { stageAttemptId: request.stageAttemptId },
647
+ run: (update, admission) => {
648
+ admit();
649
+ applyUpdate = update;
650
+ admissionGate = admission;
651
+ return producer;
652
+ }
653
+ };
654
+ const parentSessionId = request.parent.sessionId;
655
+ if (!this.governor.checkFanOut(this.occupiedRunsOf(parentSessionId) + 1)) throw new SubagentDelegationError(fanOutMessage(parentSessionId, this.fanOutLimit()));
656
+ this.noteAdmitting(parentSessionId, 1);
657
+ let snapshot;
658
+ try {
659
+ snapshot = await taskRegistry.start(subagentSpec);
660
+ } finally {
661
+ admit();
662
+ }
663
+ if (!this.governor.checkFanOut(this.occupiedRunsOf(parentSessionId))) {
664
+ settleOutcome({
665
+ status: "cancelled",
666
+ cause: "owner",
667
+ forced: false
668
+ });
669
+ throw new SubagentDelegationError(fanOutMessage(request.parent.sessionId, this.fanOutLimit()));
670
+ }
671
+ const queueOrRefuse = () => {
672
+ if (mode === "sync" || !this.queue.isEnabled()) {
673
+ settleOutcome({
674
+ status: "failed",
675
+ error: NO_SLOT_MESSAGE,
676
+ reportedInline: true
677
+ });
678
+ throw new SubagentDelegationError(NO_SLOT_MESSAGE);
679
+ }
680
+ };
681
+ const launchFrom = async (ticket, unbind, resumed) => {
682
+ const reserve = this.options.admission?.reserve;
683
+ const reservation = mode === "sync" || reserve === void 0 ? void 0 : await this.reserveThrough(reserve, request.parent.sessionId);
684
+ if (reservation === "queue") return queueOrRefuse();
685
+ if (admissionGate !== void 0 && (!resumed || reserve === void 0) && admissionGate() !== true) {
686
+ await reservation?.release().catch(() => void 0);
687
+ return queueOrRefuse();
688
+ }
689
+ let run;
690
+ let rejectAbort;
691
+ const aborted = new Promise((_, reject) => {
692
+ rejectAbort = () => reject(this.startCancelled(causeOf(ticket.phase) ?? "user"));
693
+ });
694
+ ticket.controller.signal.addEventListener("abort", rejectAbort, { once: true });
695
+ let providerStart;
696
+ try {
697
+ const launch = () => selected.start({
698
+ ...request,
699
+ signal: ticket.controller.signal
700
+ });
701
+ providerStart = reservation === void 0 ? launch() : reservation.within(launch);
702
+ run = await Promise.race([providerStart, aborted]);
703
+ } catch (error) {
704
+ await reservation?.release().catch(() => void 0);
705
+ const cause = causeOf(ticket.phase);
706
+ settleOutcome(cause !== void 0 ? {
707
+ status: "cancelled",
708
+ cause,
709
+ forced: false
710
+ } : {
711
+ status: "failed",
712
+ error: messageOf(error),
713
+ reportedInline: true
714
+ });
715
+ if (cause !== void 0 && providerStart) {
716
+ ticket.phase = {
717
+ kind: "abandoned",
718
+ cause,
719
+ reservation: ticket.phase.reservation
720
+ };
721
+ providerStart.then((late) => {
722
+ this.discardLateRun(late, cause);
723
+ this.retireLateTicket(ticket, cause, late);
724
+ }, () => this.closeTicket(ticket));
725
+ }
726
+ throw error;
727
+ } finally {
728
+ ticket.controller.signal.removeEventListener("abort", rejectAbort);
729
+ unbind();
730
+ }
731
+ const lateCause = causeOf(ticket.phase);
732
+ if (lateCause !== void 0) {
733
+ startedRun = run;
734
+ this.discardLateRun(run, lateCause);
735
+ this.retireLateTicket(ticket, lateCause, run);
736
+ settleOutcome({
737
+ status: "cancelled",
738
+ cause: lateCause,
739
+ forced: false
740
+ });
741
+ throw this.startCancelled(lateCause);
742
+ }
743
+ startedRun = run;
744
+ const model = run.modelId ?? request.model;
745
+ applyUpdate?.({
746
+ ...queuedJobId === void 0 ? {} : { queuePhase: "running" },
747
+ subjectId: run.childSessionId,
748
+ provider: selected.name,
749
+ ...run.effort !== void 0 ? { effort: run.effort } : {},
750
+ ...model !== void 0 ? { model } : {}
751
+ });
752
+ run.done.then((result) => settleOutcome(toOutcome(result)), (error) => settleOutcome({
753
+ status: "failed",
754
+ error: messageOf(error)
755
+ }));
756
+ const record = {
757
+ runId: snapshot.id,
758
+ run,
759
+ cancelled: false,
760
+ parentSessionId: request.parent.sessionId,
761
+ provider: selected.name,
762
+ label: request.label,
763
+ title: titleOfRequest(request),
764
+ detachOwner: void 0,
765
+ originTurn: request.originTurn,
766
+ ancestry: []
767
+ };
768
+ record.ancestry = this.ancestryOf(record.parentSessionId, record.originTurn);
769
+ recordRef = record;
770
+ this.noteSpawnedBy(run.childSessionId, record.parentSessionId, record.originTurn);
771
+ this.state.bumpSubagentRevision();
772
+ ticket.phase = {
773
+ kind: "handed-off",
774
+ reservation: ticket.phase.reservation
775
+ };
776
+ this.attachOwner(record);
777
+ this.observeRun(record);
778
+ this.emitSafely(TIMINGS.subagentStart, {
779
+ parentSessionId: request.parent.sessionId,
780
+ childSessionId: run.childSessionId,
781
+ provider: selected.name,
782
+ mode
783
+ });
784
+ this.assertStartLive(ticket);
785
+ const resolved = {
786
+ provider: selected.name,
787
+ modelId: run.modelId ?? request.model ?? "",
788
+ ...run.effort !== void 0 ? { effort: run.effort } : {}
789
+ };
790
+ if (mode === "sync") return {
791
+ kind: "run",
792
+ runId: record.runId,
793
+ run,
794
+ snapshot,
795
+ resolved
796
+ };
797
+ return {
798
+ kind: "job",
799
+ snapshot,
800
+ childSessionId: run.childSessionId,
801
+ resolved
802
+ };
803
+ };
804
+ const resumeQueued = async () => {
805
+ if (this.state.disposed || this.state.retiring.has(request.parent.sessionId)) {
806
+ settleOutcome({
807
+ status: "cancelled",
808
+ cause: "owner",
809
+ forced: false
810
+ });
811
+ return "failed";
812
+ }
813
+ const next = this.openTicket(request.parent.sessionId);
814
+ this.state.starting.add(next);
815
+ currentTicket = next;
816
+ try {
817
+ this.assertStartLive(next);
818
+ return await launchFrom(next, () => void 0, true) === void 0 ? "queued" : "started";
819
+ } catch (error) {
820
+ settleOutcome({
821
+ status: "failed",
822
+ error: messageOf(error),
823
+ reportedInline: true
824
+ });
825
+ return "failed";
826
+ } finally {
827
+ this.settleTicket(next);
828
+ }
829
+ };
830
+ const launched = await launchFrom(ticket, unbind, false);
831
+ if (launched !== void 0) return launched;
832
+ queuedJobId = snapshot.id;
833
+ applyUpdate?.({ queuePhase: "queued" });
834
+ this.queue.enqueue({
835
+ jobId: snapshot.id,
836
+ parentSessionId: request.parent.sessionId,
837
+ resume: resumeQueued,
838
+ abandon: (cause) => settleOutcome({
839
+ status: "cancelled",
840
+ cause,
841
+ forced: false
842
+ })
843
+ });
844
+ return {
845
+ kind: "queued",
846
+ snapshot,
847
+ reason: "pool-full"
848
+ };
849
+ } finally {
850
+ unbind();
851
+ this.settleTicket(ticket);
852
+ }
853
+ };
854
+ settleTicket(ticket) {
855
+ const disposition = ticketDisposition(ticket.phase);
856
+ if (disposition === "close") this.closeTicket(ticket);
857
+ if (disposition === "detach") this.detachTicket(ticket);
858
+ }
859
+ detachRun = (runId, options) => {
860
+ const registry = this.options.tasks();
861
+ if (registry === void 0) return false;
862
+ const owner = this.delegationJobOwnerOf(runId);
863
+ if (owner === void 0) return false;
864
+ return registry.forOwner(owner).detach(runId, options) !== void 0;
865
+ };
866
+ cancelRun = (runId, cause) => {
867
+ const registry = this.options.tasks();
868
+ if (registry === void 0) return false;
869
+ const owner = this.delegationJobOwnerOf(runId);
870
+ if (owner === void 0) return false;
871
+ registry.forOwner(owner).kill(runId, cause).catch((error) => this.diagnose("SUBAGENT_CANCEL_FAILED", error));
872
+ return true;
873
+ };
874
+ followup = (id, text, caller, expectedJobKey) => this.followupOps.followup(id, text, caller, expectedJobKey);
875
+ followupReceipt = (address, text, caller, expectedJobKey) => this.followupOps.followupReceipt(address, text, caller, expectedJobKey);
876
+ capabilityOf = (sessionId) => ({
877
+ sessionId,
878
+ isOwnedBy: (childSessionId) => this.isOwnedBy(childSessionId, sessionId, void 0)
879
+ });
880
+ revision = () => this.state.subagentRevision;
881
+ list = (caller) => {
882
+ const registry = this.options.tasks();
883
+ if (this.state.disposed || registry === void 0) return [];
884
+ const result = [];
885
+ for (const snapshot of registry.forOwner(caller).list()) {
886
+ if (!isActiveDelegationRun(snapshot) || snapshot.subjectId === void 0) continue;
887
+ const childSessionId = snapshot.subjectId;
888
+ const handle = this.options.sessions().get(childSessionId);
889
+ const phase = handle === void 0 ? { phase: "closed" } : handle.phase.kind === "idle" ? {
890
+ phase: "idle",
891
+ ...handle.lastReason?.kind !== void 0 ? { lastReason: handle.lastReason.kind } : {}
892
+ } : { phase: "running" };
893
+ result.push({
894
+ childSessionId,
895
+ parentSessionId: snapshot.owner ?? caller,
896
+ provider: snapshot.provider ?? "",
897
+ phase,
898
+ ...snapshot.label !== void 0 ? { label: snapshot.label } : {},
899
+ jobId: snapshot.id
900
+ });
901
+ }
902
+ return result;
903
+ };
904
+ delegationJobOwnerOf(runId) {
905
+ const registry = this.options.tasks();
906
+ if (registry === void 0) return;
907
+ return registry.admin().live().find((entry) => entry.id === runId && isActiveDelegationRun(entry))?.owner;
908
+ }
909
+ delegationJobsOf(owner) {
910
+ const registry = this.options.tasks();
911
+ if (registry === void 0) return [];
912
+ return (owner === void 0 ? registry.admin().live() : registry.forOwner(owner).list()).filter((snapshot) => isActiveDelegationRun(snapshot));
913
+ }
914
+ ownedRunsOf(childSessionId, caller) {
915
+ return this.delegationJobsOf(caller).filter((snapshot) => snapshot.subjectId === childSessionId);
916
+ }
917
+ activeRunsOf(owner) {
918
+ return this.delegationJobsOf(owner).length;
919
+ }
920
+ occupiedRunsOf(owner) {
921
+ return this.activeRunsOf(owner) + (this.state.admitting.get(owner) ?? 0);
922
+ }
923
+ noteAdmitting(owner, delta) {
924
+ const next = (this.state.admitting.get(owner) ?? 0) + delta;
925
+ if (next <= 0) {
926
+ this.state.admitting.delete(owner);
927
+ return;
928
+ }
929
+ this.state.admitting.set(owner, next);
930
+ }
931
+ releaseParent = (parentSessionId) => this.releaseOps.releaseParent(parentSessionId);
932
+ dispose() {
933
+ return this.releaseOps.dispose();
934
+ }
935
+ openTicket(parentSessionId) {
936
+ let settle;
937
+ const settlement = new Promise((resolve) => {
938
+ settle = resolve;
939
+ });
940
+ return {
941
+ parentSessionId,
942
+ phase: {
943
+ kind: "pending",
944
+ reservation: { kind: "none" }
945
+ },
946
+ controller: new AbortController(),
947
+ settlement,
948
+ settle
949
+ };
950
+ }
951
+ closeTicket(ticket) {
952
+ closeTicketIn(this.state, ticket);
953
+ }
954
+ detachTicket(ticket) {
955
+ detachTicketIn(this.state, ticket);
956
+ }
957
+ forwardSignal(signal, ticket) {
958
+ if (signal === void 0) return () => {};
959
+ const onAbort = () => {
960
+ cancelStarting(ticket, "user");
961
+ };
962
+ if (signal.aborted) {
963
+ onAbort();
964
+ return () => {};
965
+ }
966
+ signal.addEventListener("abort", onAbort, { once: true });
967
+ return () => signal.removeEventListener("abort", onAbort);
968
+ }
969
+ retireLateTicket(ticket, cause, run) {
970
+ ticket.phase = {
971
+ kind: "retiring",
972
+ cause,
973
+ reservation: ticket.phase.reservation,
974
+ run
975
+ };
976
+ whenReleased(run).then(() => {
977
+ this.closeTicket(ticket);
978
+ }, (error) => {
979
+ ticket.settle();
980
+ this.diagnose("SUBAGENT_RELEASE_FAILED", error);
981
+ });
982
+ }
983
+ selectProvider(name) {
984
+ if (name !== void 0) {
985
+ const found = this.providerTable.get(name);
986
+ if (!found) throw new SubagentDelegationError(unknownProviderMessage(name, this.providers()));
987
+ return found;
988
+ }
989
+ const first = this.providerTable.values().next();
990
+ if (first.done === true) throw new SubagentDelegationError("No subagent provider registered");
991
+ return first.value;
992
+ }
993
+ async reserveThrough(reserve, parentSessionId) {
994
+ let reserved;
995
+ try {
996
+ reserved = await reserve?.call(this.options.admission, parentSessionId);
997
+ } catch {
998
+ return;
999
+ }
1000
+ return reserved;
1001
+ }
1002
+ async assertResumeOwnership(request, ticket) {
1003
+ if (request.start.target !== "resume") return;
1004
+ const target = request.start.sessionId;
1005
+ if (target.length === 0) return;
1006
+ const caller = request.parent.sessionId;
1007
+ if (target === caller) throw new SubagentDelegationError("resume cannot target the calling session itself");
1008
+ const wait = this.options.meta?.(target);
1009
+ let onAbort;
1010
+ const aborted = new Promise((_, reject) => {
1011
+ onAbort = () => reject(this.startCancelled(causeOf(ticket.phase) ?? "user"));
1012
+ });
1013
+ ticket.controller.signal.addEventListener("abort", onAbort, { once: true });
1014
+ let meta;
1015
+ try {
1016
+ this.assertStartLive(ticket);
1017
+ meta = await Promise.race([wait, aborted]);
1018
+ } finally {
1019
+ ticket.controller.signal.removeEventListener("abort", onAbort);
1020
+ }
1021
+ this.assertStartLive(ticket);
1022
+ const persisted = meta?.config?.lineage?.parentSessionId;
1023
+ if (!this.isOwnedBy(target, caller, persisted)) throw new SubagentDelegationError(`Session "${target}" is not a child of "${caller}" and cannot be resumed`);
1024
+ if (this.state.reservations.has(target)) throw new SubagentDelegationError(`Session "${target}" is already being resumed`);
1025
+ const live = this.options.sessions().get(target);
1026
+ if (this.ownedRunsOf(target, caller).length > 0 || live?.phase.kind === "running") throw new SubagentDelegationError(`Session "${target}" already has a run in flight and cannot be resumed`);
1027
+ this.state.reservations.add(target);
1028
+ ticket.phase = withReservation(ticket.phase, {
1029
+ kind: "held",
1030
+ sessionId: target
1031
+ });
1032
+ }
1033
+ isOwnedBy(target, caller, persisted) {
1034
+ if (this.ownedRunsOf(target, caller).length > 0) return true;
1035
+ if (this.delegationJobsOf().some((snapshot) => snapshot.subjectId === target)) return false;
1036
+ if (this.options.sessions().isChildOf(target, caller)) return true;
1037
+ return persisted === caller;
1038
+ }
1039
+ cancelSafely(record, cause) {
1040
+ try {
1041
+ cancelOnce(record, cause);
1042
+ } catch (error) {
1043
+ this.diagnose("SUBAGENT_CANCEL_FAILED", error);
1044
+ }
1045
+ }
1046
+ assertStartLive(ticket) {
1047
+ const cause = causeOf(ticket.phase);
1048
+ if (cause !== void 0) throw this.startCancelled(cause);
1049
+ }
1050
+ startCancelled(cause) {
1051
+ return new SubagentDelegationError(`Subagent start cancelled before the provider returned (cause: ${cause})`);
1052
+ }
1053
+ discardLateRun(run, cause) {
1054
+ try {
1055
+ run.cancel(cause);
1056
+ } catch (error) {
1057
+ this.diagnose("SUBAGENT_CANCEL_FAILED", error);
1058
+ }
1059
+ run.done.catch(() => void 0);
1060
+ }
1061
+ noteSpawnedBy(childSessionId, parentSessionId, originTurn) {
1062
+ this.state.spawnedBy.set(childSessionId, {
1063
+ parentSessionId,
1064
+ originTurn
1065
+ });
1066
+ while (this.state.spawnedBy.size > SPAWNED_BY_LIMIT) {
1067
+ const oldest = this.state.spawnedBy.keys().next().value;
1068
+ if (oldest === void 0) break;
1069
+ this.state.spawnedBy.delete(oldest);
1070
+ }
1071
+ }
1072
+ ancestryOf(parentSessionId, originTurn) {
1073
+ const chain = [{
1074
+ sessionId: parentSessionId,
1075
+ ...originTurn === void 0 ? {} : { originTurn }
1076
+ }];
1077
+ let current = parentSessionId;
1078
+ for (let depth = 0; depth < MAX_ANCESTRY_DEPTH; depth += 1) {
1079
+ const spawn = this.state.spawnedBy.get(current);
1080
+ const next = this.options.sessions().get(current)?.lineage?.parentSessionId ?? spawn?.parentSessionId;
1081
+ if (next === void 0) break;
1082
+ chain.push({
1083
+ sessionId: next,
1084
+ ...spawn?.originTurn === void 0 ? {} : { originTurn: spawn.originTurn }
1085
+ });
1086
+ current = next;
1087
+ }
1088
+ return chain;
1089
+ }
1090
+ attachOwner(record) {
1091
+ const registry = this.options.processOwners?.();
1092
+ if (registry === void 0) return;
1093
+ const childSessionId = record.run.childSessionId;
1094
+ const ownerId = ownerIdOf(childSessionId, record.runId);
1095
+ record.detachOwner = registry.register({
1096
+ ownerId,
1097
+ domain: "tokens",
1098
+ kind: "session",
1099
+ label: record.label ?? childSessionId,
1100
+ release: async (reason) => {
1101
+ this.cancelSafely(record, "owner");
1102
+ return {
1103
+ ownerId,
1104
+ domain: "tokens",
1105
+ released: true,
1106
+ reason
1107
+ };
1108
+ }
1109
+ });
1110
+ }
1111
+ observeRun(record) {
1112
+ record.run.done.then((result) => {
1113
+ this.emitSafely(TIMINGS.subagentEnd, {
1114
+ parentSessionId: record.parentSessionId,
1115
+ childSessionId: record.run.childSessionId,
1116
+ runId: record.runId,
1117
+ ...record.title === void 0 ? {} : { title: record.title },
1118
+ ...record.originTurn === void 0 ? {} : { originTurn: record.originTurn },
1119
+ ancestry: record.ancestry,
1120
+ result
1121
+ });
1122
+ }, (error) => {
1123
+ this.diagnose("SUBAGENT_RUN_REJECTED", error);
1124
+ });
1125
+ whenReleased(record.run).then(() => {
1126
+ record.detachOwner?.();
1127
+ record.detachOwner = void 0;
1128
+ this.state.bumpSubagentRevision();
1129
+ }, (error) => {
1130
+ this.diagnose("SUBAGENT_RELEASE_FAILED", error);
1131
+ });
1132
+ }
1133
+ emitSafely(timing, payload) {
1134
+ try {
1135
+ this.options.emit(timing, payload);
1136
+ } catch (error) {
1137
+ this.diagnose("SUBAGENT_EMIT_FAILED", error);
1138
+ }
1139
+ }
1140
+ diagnose(code, error) {
1141
+ try {
1142
+ this.options.emit(TIMINGS.runtimeDiagnostic, {
1143
+ source: "provider",
1144
+ severity: "error",
1145
+ code,
1146
+ message: error instanceof Error ? error.message : String(error)
1147
+ });
1148
+ } catch {
1149
+ return;
1150
+ }
1151
+ }
1152
+ assertCapabilities(provider, request) {
1153
+ if (request.start.target === "fork" && !provider.capabilities.fork) throw new SubagentDelegationError(`Provider "${provider.name}" does not support fork`);
1154
+ if (request.start.target === "resume" && !provider.capabilities.resume) throw new SubagentDelegationError(`Provider "${provider.name}" does not support resume`);
1155
+ }
1156
+ };
1157
+
1158
+ //#endregion
1159
+ //#region src/persona.ts
1160
+ function compilePersona(ref, declaration) {
1161
+ const allow = nonEmpty(declaration.tools);
1162
+ const deny = nonEmpty(declaration.excludeTools);
1163
+ return {
1164
+ ref,
1165
+ toolView: {
1166
+ ...allow === void 0 ? {} : { allow },
1167
+ ...deny === void 0 ? {} : { deny }
1168
+ },
1169
+ ...declaration.cwd === void 0 ? {} : { cwd: declaration.cwd }
1170
+ };
1171
+ }
1172
+ async function resolvePersona(resolver, ref) {
1173
+ const declaration = await resolver.resolve(ref);
1174
+ if (declaration === void 0) return {
1175
+ ok: false,
1176
+ reason: `persona "${ref.pluginId}:${ref.personaId}" was not found in ${ref.scope}; omit the persona field to spawn without a persona`
1177
+ };
1178
+ if (declaration.instructions.trim() === "") return {
1179
+ ok: false,
1180
+ reason: `persona "${ref.pluginId}:${ref.personaId}" declares empty instructions`
1181
+ };
1182
+ return {
1183
+ ok: true,
1184
+ compilation: compilePersona(ref, declaration)
1185
+ };
1186
+ }
1187
+ function nonEmpty(values) {
1188
+ if (values === void 0) return;
1189
+ const filtered = values.filter((value) => value !== "");
1190
+ return filtered.length === 0 ? void 0 : filtered;
1191
+ }
1192
+ function personaCwdRefusal(parentCwd, compilation) {
1193
+ const declared = compilation.cwd;
1194
+ if (declared === void 0 || isPathWithin(parentCwd, declared)) return;
1195
+ return `persona "${compilation.ref.pluginId}:${compilation.ref.personaId}" declares cwd "${declared}" outside the parent working root "${parentCwd}"`;
1196
+ }
1197
+
1198
+ //#endregion
1199
+ //#region src/in-process.ts
1200
+ function subagentRunStatsOf(messages, fromIndex) {
1201
+ let tools = 0;
1202
+ let tokens = 0;
1203
+ let subagents = 0;
1204
+ for (const message of messages.slice(Math.max(0, fromIndex))) {
1205
+ if (message.role === "tool_result") {
1206
+ tools += 1;
1207
+ if (message.toolName === TOOL_NAMES.agentSpawn) subagents += 1;
1208
+ continue;
1209
+ }
1210
+ if (message.role === "assistant") tokens += message.usage.inputTokens + message.usage.outputTokens;
1211
+ }
1212
+ return {
1213
+ tools,
1214
+ tokens,
1215
+ subagents
1216
+ };
1217
+ }
1218
+ const IN_PROCESS_PROVIDER_NAME = "in-process";
1219
+ function configFor(persona, request, isolatedRoot) {
1220
+ const config = {
1221
+ ...persona === void 0 ? {} : { toolView: persona.toolView },
1222
+ ...persona === void 0 || request.persona === void 0 ? {} : { persona: request.persona },
1223
+ ...isolatedRoot === void 0 ? {} : { isolatedRoot }
1224
+ };
1225
+ return Object.keys(config).length === 0 ? void 0 : config;
1226
+ }
1227
+ async function resolveRequestPersona(deps, request) {
1228
+ const ref = request.persona;
1229
+ if (ref === void 0) return;
1230
+ if (ref.pluginId.trim() === "" || ref.personaId.trim() === "") throw new SubagentDelegationError("persona requires a non-empty pluginId and personaId; omit persona to spawn without one");
1231
+ if (deps.personas === void 0) throw new SubagentDelegationError(`a persona was requested ("${ref.pluginId}:${ref.personaId}") but no persona resolver is wired`);
1232
+ const resolution = await resolvePersona(deps.personas, ref);
1233
+ if (!resolution.ok) throw new SubagentDelegationError(resolution.reason);
1234
+ const cwdRefusal = personaCwdRefusal(request.parent.cwd, resolution.compilation);
1235
+ if (cwdRefusal !== void 0) throw new SubagentDelegationError(cwdRefusal);
1236
+ return resolution.compilation;
1237
+ }
1238
+ function requestedIsolationOf(request) {
1239
+ return request.isolation ?? "auto";
1240
+ }
1241
+ function refusesResumeIsolation(request) {
1242
+ const requested = request.isolation;
1243
+ if (request.start.target !== "resume" || requested === void 0 || requested === "auto") return;
1244
+ throw new SubagentDelegationError(`isolation=${requested} cannot be applied to a resumed session: a child keeps the workspace it was created with; start a fresh or forked subagent instead`);
1245
+ }
1246
+ function wantsWorktreeIsolation(request) {
1247
+ if (request.start.target === "resume") return false;
1248
+ const requested = requestedIsolationOf(request);
1249
+ const isReadonly = request.permissionCap?.readonly === true;
1250
+ if (requested === "in-place" && !isReadonly) throw new SubagentDelegationError("isolation=in-place requires a read-only child: a subagent that may write must run in its own workspace; omit isolation (auto) or use isolation=worktree");
1251
+ if (requested === "worktree") return true;
1252
+ return !isReadonly;
1253
+ }
1254
+ function toCancelCause(cause) {
1255
+ return cause === "disposed" ? "disposed" : "parent";
1256
+ }
1257
+ function errorOf(error) {
1258
+ return error instanceof Error ? error.message : String(error);
1259
+ }
1260
+ function failureTextOf(reason, promptError, retried) {
1261
+ if (reason?.kind === "error") return reason.message;
1262
+ if (retried || promptError === void 0) return "turn ended with error";
1263
+ return errorOf(promptError);
1264
+ }
1265
+ function suggestedActionOf(retryable, errorKind) {
1266
+ if (!retryable) return "none";
1267
+ if (errorKind === "auth" || errorKind === "rate-limit-exhausted") return "switch-provider";
1268
+ return "resume-child";
1269
+ }
1270
+ function recoverySummaryOf(reason, snapshot) {
1271
+ if (reason?.kind !== "error" || reason.errorKind === void 0) return;
1272
+ const errorKind = reason.errorKind;
1273
+ const retryable = inStreamRetryOf(errorKind) !== void 0 || resubmitRetryOf(errorKind) !== void 0;
1274
+ return {
1275
+ retryable,
1276
+ errorKind,
1277
+ attempts: snapshot?.attempt ?? 1,
1278
+ exhausted: snapshot?.phase === "manual",
1279
+ suggestedAction: suggestedActionOf(retryable, errorKind)
1280
+ };
1281
+ }
1282
+ function childModelIdOf(child) {
1283
+ try {
1284
+ return child.model.model;
1285
+ } catch {
1286
+ return;
1287
+ }
1288
+ }
1289
+ function assertResumedModelAllowed(child, allowedModels, catalogue) {
1290
+ const effective = childModelIdOf(child);
1291
+ const allowed = new Set(allowedModels);
1292
+ for (const id of allowedModels) {
1293
+ const model = catalogue.get(id);
1294
+ if (model !== void 0) allowed.add(model.wireId ?? model.id);
1295
+ }
1296
+ if (effective !== void 0 && allowed.has(effective)) return;
1297
+ throw new SubagentDelegationError(`the resumed session runs model "${effective ?? "unknown"}", which agent.subagent.models does not allow; pass an allowed model explicitly or clear the setting`);
1298
+ }
1299
+ function childEffortOf(child) {
1300
+ try {
1301
+ return child.meta.config?.effort;
1302
+ } catch {
1303
+ return;
1304
+ }
1305
+ }
1306
+ function textOf(message) {
1307
+ return message.content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
1308
+ }
1309
+ const RECOVERY_POLL_MS = 100;
1310
+ const RECOVERY_RESUME_START_POLLS = 50;
1311
+ function lastAssistantMessageOf(messages) {
1312
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
1313
+ const message = messages[i];
1314
+ if (message !== void 0 && message.role === "assistant") return message;
1315
+ }
1316
+ }
1317
+ function lastAssistantText(messages) {
1318
+ const message = lastAssistantMessageOf(messages);
1319
+ return message === void 0 ? "" : textOf(message);
1320
+ }
1321
+ function assertStartLive(signal, stage) {
1322
+ if (signal?.aborted) throw new SubagentDelegationError(`Subagent start aborted before ${stage}`);
1323
+ }
1324
+ function cancelledStart(registry, childSessionId) {
1325
+ return {
1326
+ childSessionId,
1327
+ done: Promise.resolve({
1328
+ status: "cancelled",
1329
+ text: "",
1330
+ childSessionId,
1331
+ cause: "user"
1332
+ }),
1333
+ release: async () => {
1334
+ await registry.detach(childSessionId);
1335
+ },
1336
+ cancel: () => {},
1337
+ readOutput: () => ""
1338
+ };
1339
+ }
1340
+ function resolveEffort(effort) {
1341
+ if (effort === void 0 || effort.length === 0) return;
1342
+ const parsed = parseThinkingLevel(effort);
1343
+ if (parsed === void 0) throw new SubagentDelegationError(`unknown effort "${effort}"; expected one of ${[...THINKING_LEVELS].join(" | ")}`);
1344
+ return parsed;
1345
+ }
1346
+ function sessionClaimOf(outcome) {
1347
+ if (typeof outcome === "boolean") return { ok: outcome };
1348
+ return outcome;
1349
+ }
1350
+ function claimRefusalMessage(childSessionId, origin, claim) {
1351
+ const subject = `session "${childSessionId}" could not be claimed for writing by this process: ${claim.message === void 0 ? "the host gave no reason" : claim.message}`;
1352
+ if (claim.contended === true) return `${subject}; another process holds its lease — wait for it to release, or start a fresh subagent`;
1353
+ if (origin === "created") return `${subject}; the new child session was removed — retry agent_spawn, and report this if it repeats`;
1354
+ return `${subject}; resume it later, or start a fresh subagent`;
1355
+ }
1356
+ function createInProcessProvider(deps) {
1357
+ return {
1358
+ name: IN_PROCESS_PROVIDER_NAME,
1359
+ capabilities: {
1360
+ fork: true,
1361
+ resume: true
1362
+ },
1363
+ async start(request) {
1364
+ const registry = deps.sessions();
1365
+ const signal = request.signal;
1366
+ assertStartLive(signal, "the child session was created");
1367
+ refusesResumeIsolation(request);
1368
+ const wantsWorktree = wantsWorktreeIsolation(request);
1369
+ const persona = await resolveRequestPersona(deps, request);
1370
+ const providedRoot = request.workspaceRoot;
1371
+ const allocatesRoot = wantsWorktree && providedRoot === void 0;
1372
+ const reservedSessionId = allocatesRoot && request.start.target === "fresh" ? deps.ids?.() : void 0;
1373
+ let isolatedRoot = providedRoot;
1374
+ let allocationFailure;
1375
+ if (allocatesRoot) try {
1376
+ isolatedRoot = await deps.workspaceRoots?.allocate({
1377
+ parentCwd: request.parent.cwd,
1378
+ ...reservedSessionId === void 0 ? {} : { ownerSessionId: reservedSessionId }
1379
+ });
1380
+ } catch (error) {
1381
+ allocationFailure = errorOf(error);
1382
+ }
1383
+ if (allocatesRoot && isolatedRoot === void 0) throw new SubagentDelegationError((deps.workspaceRoots?.allocate === void 0 ? "this host wires no workspace root allocator" : "this subagent may write, so it needs its own workspace root, but none could be allocated") + (allocationFailure === void 0 ? "" : ` (${allocationFailure})`) + "; a writable child never runs in the parent workspace. Start it read-only, or fix the workspace root allocation");
1384
+ const ownsIsolatedRoot = allocatesRoot && isolatedRoot !== void 0;
1385
+ const canSealRoot = deps.workspaceRoots?.seal !== void 0;
1386
+ const discardIsolatedRoot = async () => {
1387
+ if (ownsIsolatedRoot && isolatedRoot !== void 0) await deps.workspaceRoots?.release?.(isolatedRoot);
1388
+ };
1389
+ let handle;
1390
+ let origin = { kind: "created" };
1391
+ try {
1392
+ const allowedModels = deps.allowedModels?.() ?? [];
1393
+ const resumesWithoutModel = request.start.target === "resume" && request.model === void 0;
1394
+ const admitted = resumesWithoutModel ? { model: void 0 } : admitChildModel({
1395
+ catalog: deps.models(),
1396
+ availability: deps.availability
1397
+ }, allowedModels, request.model);
1398
+ if ("reason" in admitted) throw new SubagentDelegationError(admitted.message);
1399
+ const resolvedModel = admitted.model;
1400
+ const model = resolvedModel ? toModelRef(resolvedModel) : void 0;
1401
+ const lineage = {
1402
+ depth: request.parent.depth + 1,
1403
+ parentSessionId: request.parent.sessionId
1404
+ };
1405
+ const cap = request.permissionCap !== void 0 ? { permissionCap: request.permissionCap } : {};
1406
+ if (request.start.target === "resume" && request.permissionCap !== void 0) throw new SubagentDelegationError("a permission cap cannot be applied to a resumed session: the cap is part of the session creation contract; start a fresh or forked subagent instead");
1407
+ const effort = resolveEffort(request.effort);
1408
+ if (request.start.target === "resume") {
1409
+ const sessionId = request.start.sessionId;
1410
+ const existing = registry.get(sessionId);
1411
+ handle = existing ?? await registry.restore(sessionId, {
1412
+ model,
1413
+ lineage
1414
+ }) ?? void 0;
1415
+ if (signal?.aborted && !existing && handle) return cancelledStart(registry, handle.meta.id);
1416
+ assertStartLive(signal, `the resumed session "${sessionId}" was verified`);
1417
+ if (!handle) throw new SubagentDelegationError(`cannot resume session "${sessionId}": it does not exist or cannot be restored`);
1418
+ if (handle.phase.kind === "running") throw new SubagentDelegationError(`cannot resume session "${sessionId}": it is already running`);
1419
+ origin = { kind: "reused" };
1420
+ } else if (request.start.target === "fork") {
1421
+ const parentCwd = request.start.parent.cwd;
1422
+ handle = await registry.fork(request.start.parent.sessionId, {
1423
+ model,
1424
+ lineage,
1425
+ cwd: isolatedRoot ?? parentCwd,
1426
+ visibility: "internal",
1427
+ via: "delegation",
1428
+ ...cap,
1429
+ ...effort !== void 0 ? { effort } : {},
1430
+ ...isolatedRoot === void 0 ? {} : { isolatedRoot }
1431
+ });
1432
+ if (isolatedRoot !== void 0) await deps.workspaceRoots?.rebindOwner?.(isolatedRoot, handle.meta.id);
1433
+ }
1434
+ if (!handle) handle = await registry.create({
1435
+ ...reservedSessionId === void 0 ? {} : { id: reservedSessionId },
1436
+ model,
1437
+ lineage,
1438
+ cwd: isolatedRoot ?? request.cwd ?? persona?.cwd ?? request.parent.cwd,
1439
+ visibility: "internal",
1440
+ via: "delegation",
1441
+ ...configFor(persona, request, isolatedRoot) === void 0 ? {} : { config: configFor(persona, request, isolatedRoot) },
1442
+ ...cap,
1443
+ ...effort !== void 0 ? { effort } : {}
1444
+ });
1445
+ if (resumesWithoutModel && allowedModels.length > 0) assertResumedModelAllowed(handle, allowedModels, deps.models());
1446
+ } catch (error) {
1447
+ await discardIsolatedRoot();
1448
+ throw error;
1449
+ }
1450
+ const child = handle;
1451
+ const childSessionId = child.meta.id;
1452
+ if (deps.claimSession !== void 0 && origin.kind === "reused") {
1453
+ const claim = sessionClaimOf(await deps.claimSession(childSessionId));
1454
+ if (!claim.ok) {
1455
+ await discardIsolatedRoot();
1456
+ throw new SubagentDelegationError(claimRefusalMessage(childSessionId, origin.kind, claim));
1457
+ }
1458
+ }
1459
+ const isolation = isolatedRoot === void 0 ? "in-place" : "isolated";
1460
+ const statsBaseline = child.messages.length;
1461
+ const statsOf = () => subagentRunStatsOf(child.messages, statsBaseline);
1462
+ let cancelled;
1463
+ if (signal?.aborted) {
1464
+ if (origin.kind === "created") {
1465
+ await discardIsolatedRoot();
1466
+ return cancelledStart(registry, childSessionId);
1467
+ }
1468
+ throw new SubagentDelegationError("Subagent start aborted before the child prompt was dispatched");
1469
+ }
1470
+ let sealed;
1471
+ let sealFailed = false;
1472
+ const sealArtifacts = async () => {
1473
+ if (sealed !== void 0 || sealFailed || !ownsIsolatedRoot || isolatedRoot === void 0 || deps.workspaceRoots?.seal === void 0) return sealed;
1474
+ try {
1475
+ sealed = await deps.workspaceRoots.seal(isolatedRoot);
1476
+ return sealed;
1477
+ } catch (error) {
1478
+ sealFailed = true;
1479
+ deps.diagnose?.("SUBAGENT_SEAL_FAILED", `artifact seal failed for ${isolatedRoot}: ${error instanceof Error ? error.message : String(error)}`);
1480
+ return;
1481
+ }
1482
+ };
1483
+ const artifactsField = (artifacts) => artifacts === void 0 ? {} : { artifacts };
1484
+ const recoveryController = new AbortController();
1485
+ const waitRecoveryPoll = async () => {
1486
+ await settleWithin(child.whenIdle(), RECOVERY_POLL_MS);
1487
+ await new Promise((resolve) => {
1488
+ const timer = setTimeout(resolve, RECOVERY_POLL_MS);
1489
+ timer.unref?.();
1490
+ recoveryController.signal.addEventListener("abort", () => {
1491
+ clearTimeout(timer);
1492
+ resolve();
1493
+ }, { once: true });
1494
+ });
1495
+ };
1496
+ const waitForResumedTurn = async (failure) => {
1497
+ let observedRunning = false;
1498
+ let startPolls = 0;
1499
+ for (;;) {
1500
+ if (recoveryController.signal.aborted) return;
1501
+ if (child.lastReason !== failure) return;
1502
+ if (child.phase.kind === "running") observedRunning = true;
1503
+ else if (observedRunning) return;
1504
+ else if (startPolls >= RECOVERY_RESUME_START_POLLS) return;
1505
+ else startPolls += 1;
1506
+ await waitRecoveryPoll();
1507
+ }
1508
+ };
1509
+ const waitForRecoverySettled = async (failure) => {
1510
+ let handledRevision = deps.recoveryOf?.(childSessionId)?.revision ?? -1;
1511
+ for (;;) {
1512
+ const snapshot = deps.recoveryOf?.(childSessionId);
1513
+ if (snapshot?.phase === "waiting" || snapshot?.phase === "starting") {
1514
+ await waitRecoveryPoll();
1515
+ continue;
1516
+ }
1517
+ if (snapshot?.phase === "none" && snapshot.reason === "resumed" && snapshot !== void 0 && snapshot.revision > handledRevision) {
1518
+ handledRevision = snapshot.revision;
1519
+ await waitForResumedTurn(failure);
1520
+ continue;
1521
+ }
1522
+ return;
1523
+ }
1524
+ };
1525
+ const done = (async () => {
1526
+ let promptError;
1527
+ let promptMessage;
1528
+ try {
1529
+ promptMessage = await child.prompt(request.prompt, recoveryController.signal);
1530
+ } catch (error) {
1531
+ promptError = error;
1532
+ }
1533
+ const failureReason = child.lastReason;
1534
+ await waitForRecoverySettled(failureReason);
1535
+ const artifacts = await sealArtifacts();
1536
+ if (cancelled !== void 0) return {
1537
+ status: "cancelled",
1538
+ text: lastAssistantText(child.messages),
1539
+ childSessionId,
1540
+ cause: cancelled ?? "user",
1541
+ isolation,
1542
+ ...artifactsField(artifacts),
1543
+ stats: statsOf()
1544
+ };
1545
+ const kind = child.lastReason?.kind;
1546
+ const retried = child.lastReason !== failureReason;
1547
+ if (kind === "aborted" && recoveryController.signal.aborted) return {
1548
+ status: "cancelled",
1549
+ text: lastAssistantText(child.messages),
1550
+ childSessionId,
1551
+ cause: "user",
1552
+ isolation,
1553
+ ...artifactsField(artifacts),
1554
+ stats: statsOf()
1555
+ };
1556
+ if (kind === "error" || promptError !== void 0 && kind !== "completed" && !retried) {
1557
+ const recovery = recoverySummaryOf(child.lastReason, deps.recoveryOf?.(childSessionId));
1558
+ return {
1559
+ status: "failed",
1560
+ text: lastAssistantText(child.messages),
1561
+ childSessionId,
1562
+ error: failureTextOf(child.lastReason, promptError, retried),
1563
+ ...recovery === void 0 ? {} : { recovery },
1564
+ isolation,
1565
+ ...artifactsField(artifacts),
1566
+ stats: statsOf()
1567
+ };
1568
+ }
1569
+ if (isPartialReason(kind) && kind !== void 0 && kind !== "aborted") return {
1570
+ status: "partial",
1571
+ text: promptMessage === void 0 ? lastAssistantText(child.messages) : textOf(promptMessage),
1572
+ childSessionId,
1573
+ reason: kind,
1574
+ isolation,
1575
+ ...artifactsField(artifacts),
1576
+ stats: statsOf()
1577
+ };
1578
+ const message = promptMessage ?? lastAssistantMessageOf(child.messages);
1579
+ return {
1580
+ status: "completed",
1581
+ text: message === void 0 ? lastAssistantText(child.messages) : textOf(message),
1582
+ childSessionId,
1583
+ isolation,
1584
+ ...artifactsField(artifacts),
1585
+ stats: statsOf()
1586
+ };
1587
+ })();
1588
+ let detachAttempt;
1589
+ const attemptDetach = () => {
1590
+ if (detachAttempt === void 0) {
1591
+ const attempt = registry.detach(childSessionId);
1592
+ detachAttempt = attempt;
1593
+ attempt.catch(() => {
1594
+ if (detachAttempt === attempt) detachAttempt = void 0;
1595
+ });
1596
+ }
1597
+ return detachAttempt;
1598
+ };
1599
+ const runRelease = async () => {
1600
+ const settle = () => void 0;
1601
+ await done.then(settle, settle);
1602
+ if (origin.kind === "reused") return;
1603
+ const failures = [];
1604
+ try {
1605
+ await attemptDetach();
1606
+ } catch (error) {
1607
+ failures.push(error);
1608
+ }
1609
+ if (ownsIsolatedRoot && isolatedRoot !== void 0) {
1610
+ const artifacts = canSealRoot ? await sealArtifacts() : void 0;
1611
+ if (canSealRoot && artifacts === void 0) {
1612
+ sealFailed = false;
1613
+ failures.push(/* @__PURE__ */ new Error(`artifact seal failed for ${isolatedRoot}; the workspace root is kept so the work is not lost`));
1614
+ } else try {
1615
+ await deps.workspaceRoots?.release?.(isolatedRoot);
1616
+ } catch (error) {
1617
+ failures.push(error);
1618
+ }
1619
+ }
1620
+ if (failures.length === 1) throw failures[0];
1621
+ if (failures.length > 1) throw new AggregateError(failures, failures.map(errorOf).join("; "));
1622
+ };
1623
+ let releaseAttempt;
1624
+ const release = () => {
1625
+ if (releaseAttempt === void 0) {
1626
+ const attempt = runRelease();
1627
+ releaseAttempt = attempt;
1628
+ attempt.catch(() => {
1629
+ if (releaseAttempt === attempt) releaseAttempt = void 0;
1630
+ });
1631
+ }
1632
+ return releaseAttempt;
1633
+ };
1634
+ done.then(() => origin.kind === "reused" ? void 0 : attemptDetach()).catch(() => void 0);
1635
+ const modelId = childModelIdOf(child);
1636
+ const effectiveEffort = childEffortOf(child);
1637
+ return {
1638
+ childSessionId,
1639
+ ...modelId !== void 0 ? { modelId } : {},
1640
+ ...effectiveEffort !== void 0 ? { effort: effectiveEffort } : {},
1641
+ isolation,
1642
+ artifacts: () => sealed,
1643
+ done,
1644
+ release,
1645
+ cancel(cause) {
1646
+ cancelled = cause;
1647
+ recoveryController.abort();
1648
+ child.abort(toCancelCause(cause));
1649
+ },
1650
+ readOutput() {
1651
+ return lastAssistantText(child.messages);
1652
+ },
1653
+ readProgress() {
1654
+ return child.messages.length;
1655
+ }
1656
+ };
1657
+ }
1658
+ };
1659
+ }
1660
+
1661
+ //#endregion
1662
+ //#region src/isolation/apply.ts
1663
+ const MAX_PATCH_BYTES = 8 * 1024 * 1024;
1664
+ const DIGEST_PREFIX_MIN_CHARS = 12;
1665
+ async function gitThrough(backend, cwd, argumentList) {
1666
+ try {
1667
+ const process = backend.spawn("git", [...argumentList], { cwd });
1668
+ const exit = await process.done;
1669
+ const stdout = process.readOutput();
1670
+ const stderr = process.readError();
1671
+ return exit.exitCode === 0 ? {
1672
+ ok: true,
1673
+ stdout,
1674
+ stderr
1675
+ } : {
1676
+ ok: false,
1677
+ stdout,
1678
+ stderr: stderr.trim() === "" ? "git command failed" : stderr
1679
+ };
1680
+ } catch (error) {
1681
+ return {
1682
+ ok: false,
1683
+ stdout: "",
1684
+ stderr: error instanceof Error ? error.message : "git command failed"
1685
+ };
1686
+ }
1687
+ }
1688
+ function receiptIdOf(patchRef) {
1689
+ return basename(dirname(patchRef));
1690
+ }
1691
+ function targetPathsOf(numstatOutput) {
1692
+ return numstatOutput.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => {
1693
+ const parts = line.split(" ");
1694
+ return parts.length >= 3 ? parts[2] : void 0;
1695
+ }).filter((path) => path !== void 0 && path.length > 0);
1696
+ }
1697
+ function outsideOf(root, targets) {
1698
+ const base = resolve(root);
1699
+ return targets.filter((target) => {
1700
+ const absolute = resolve(target);
1701
+ return absolute !== base && !absolute.startsWith(base.endsWith("/") ? base : `${base}/`);
1702
+ });
1703
+ }
1704
+ async function readPatch(patchRef) {
1705
+ try {
1706
+ const bytes = await readFile(patchRef);
1707
+ if (bytes.byteLength > MAX_PATCH_BYTES) return {
1708
+ ok: false,
1709
+ error: `patch ${patchRef} is ${bytes.byteLength} bytes; the ${MAX_PATCH_BYTES}-byte limit is exceeded`
1710
+ };
1711
+ return {
1712
+ ok: true,
1713
+ bytes
1714
+ };
1715
+ } catch (error) {
1716
+ return {
1717
+ ok: false,
1718
+ error: error instanceof Error ? error.message : String(error)
1719
+ };
1720
+ }
1721
+ }
1722
+ function createIsolationApplyTool(artifactStore, backend) {
1723
+ return {
1724
+ name: TOOL_NAMES.isolationApply,
1725
+ exposure: "deferred",
1726
+ description: `Apply an isolated subagent artifact to the current repository. Both patch_ref and digest come from the artifacts line of agent_spawn or job_output. The digest may be the full sha256 or the truncated prefix shown there (at least ${DIGEST_PREFIX_MIN_CHARS} characters). Digest is verified before anything is written, target paths are declared for permission review, and the whole patch is applied atomically (git apply), so a failed apply leaves the tree untouched.`,
1727
+ schema: objectSchema({
1728
+ patch_ref: { type: "string" },
1729
+ digest: { type: "string" }
1730
+ }, { rejectUnknownFields: true }),
1731
+ effects: effectsOf({
1732
+ reads: [],
1733
+ writes: [],
1734
+ completeness: "incomplete"
1735
+ }),
1736
+ prepare: async (input, ctx) => {
1737
+ const execution = backend();
1738
+ const patchRef = isAbsolute(input.patch_ref) ? input.patch_ref : resolve(ctx.cwd, input.patch_ref);
1739
+ const read = await readPatch(patchRef);
1740
+ if (!read.ok) return {
1741
+ effects: effectsOf({
1742
+ reads: [patchRef],
1743
+ writes: [],
1744
+ completeness: "complete"
1745
+ }),
1746
+ execute: async () => ({
1747
+ content: textToolContent(read.error),
1748
+ isError: true,
1749
+ errorKind: "not_found"
1750
+ })
1751
+ };
1752
+ const digest = createHash("sha256").update(read.bytes).digest("hex");
1753
+ const declared = input.digest.trim().toLowerCase();
1754
+ const digestMatches = declared.length >= DIGEST_PREFIX_MIN_CHARS && digest.startsWith(declared);
1755
+ const numstat = digestMatches ? await gitThrough(execution, ctx.cwd, [
1756
+ "apply",
1757
+ "--numstat",
1758
+ patchRef
1759
+ ]) : void 0;
1760
+ const check = digestMatches ? await gitThrough(execution, ctx.cwd, [
1761
+ "apply",
1762
+ "--check",
1763
+ patchRef
1764
+ ]) : void 0;
1765
+ const targets = numstat !== void 0 && numstat.ok ? targetPathsOf(numstat.stdout).map((path) => resolve(ctx.cwd, path)) : [];
1766
+ const escaping = outsideOf(ctx.cwd, targets);
1767
+ const declaredEffectPaths = digestMatches && check?.ok === true && escaping.length === 0 ? targets : [];
1768
+ return {
1769
+ effects: effectsOf({
1770
+ reads: [patchRef],
1771
+ writes: declaredEffectPaths,
1772
+ completeness: digestMatches && check?.ok === true ? "complete" : "incomplete"
1773
+ }),
1774
+ execute: async () => {
1775
+ if (!digestMatches) return {
1776
+ content: textToolContent(`patch digest mismatch: declared ${declared} but computed ${digest}; refusing to apply ${patchRef}` + (declared.length < DIGEST_PREFIX_MIN_CHARS ? ` (at least ${DIGEST_PREFIX_MIN_CHARS} characters are required)` : "")),
1777
+ isError: true,
1778
+ errorKind: "validation"
1779
+ };
1780
+ if (escaping.length > 0) return {
1781
+ content: textToolContent(`patch targets paths outside ${ctx.cwd}: ${escaping.join(", ")}; refusing to apply ${patchRef}`),
1782
+ isError: true,
1783
+ errorKind: "path_escape"
1784
+ };
1785
+ if (check === void 0 || !check.ok) return {
1786
+ content: textToolContent(`patch does not apply cleanly to ${ctx.cwd}: ${(check?.stderr ?? "").trim() || "git apply --check failed"}`),
1787
+ isError: true,
1788
+ errorKind: "io"
1789
+ };
1790
+ const applied = await gitThrough(execution, ctx.cwd, ["apply", patchRef]);
1791
+ if (!applied.ok) return {
1792
+ content: textToolContent(`git apply failed: ${applied.stderr.trim()}`),
1793
+ isError: true,
1794
+ errorKind: "io"
1795
+ };
1796
+ const store = artifactStore?.();
1797
+ if (store !== void 0) try {
1798
+ await store.markArtifactConsumed({ receiptId: receiptIdOf(patchRef) });
1799
+ } catch {
1800
+ const appliedList = targetPathsOf(numstat?.stdout ?? "");
1801
+ return {
1802
+ content: textToolContent(appliedList.length === 0 ? `applied ${patchRef} (no file changes) but could not mark the artifact consumed` : `applied ${appliedList.length} file(s) from ${patchRef}: ${appliedList.join(", ")} (but could not mark the artifact consumed)`),
1803
+ details: {
1804
+ patchRef,
1805
+ digest,
1806
+ files: appliedList
1807
+ }
1808
+ };
1809
+ }
1810
+ const list = targetPathsOf(numstat?.stdout ?? "");
1811
+ return {
1812
+ content: textToolContent(list.length === 0 ? `applied ${patchRef} (no file changes)` : `applied ${list.length} file(s) from ${patchRef}: ${list.join(", ")}`),
1813
+ details: {
1814
+ patchRef,
1815
+ digest,
1816
+ files: list
1817
+ }
1818
+ };
1819
+ }
1820
+ };
1821
+ },
1822
+ execute: async () => ({
1823
+ content: textToolContent("isolation_apply requires a prepared call"),
1824
+ isError: true,
1825
+ errorKind: "validation"
1826
+ })
1827
+ };
1828
+ }
1829
+
1830
+ //#endregion
1831
+ //#region src/isolation/pending.ts
1832
+ function createIsolationPendingTool(artifacts) {
1833
+ return {
1834
+ name: TOOL_NAMES.isolationPending,
1835
+ exposure: "deferred",
1836
+ description: "List pending isolated subagent artifacts that have not been consumed yet. Each entry shows the lease, owner session, digest, byte size, and file list of a durable artifact produced by an isolated subagent; use isolation_apply with its patch reference to consume one.",
1837
+ schema: objectSchema({}, { rejectUnknownFields: true }),
1838
+ effects: effectsOf({
1839
+ reads: ["artifact-store"],
1840
+ completeness: "incomplete"
1841
+ }),
1842
+ execute: async () => {
1843
+ const port = artifacts();
1844
+ if (port === void 0) return {
1845
+ content: textToolContent("artifact store is not available in this host"),
1846
+ isError: true,
1847
+ errorKind: "not_found"
1848
+ };
1849
+ const entries = await port.listPendingArtifacts();
1850
+ return { content: textToolContent(entries.length === 0 ? "no pending artifacts" : entries.map((entry) => `- ${entry}`).join("\n")) };
1851
+ }
1852
+ };
1853
+ }
1854
+
1855
+ //#endregion
1856
+ //#region src/tools.ts
1857
+ const SUBAGENT_GUIDELINE = "A background child is driven through the job tools: read it with job_output, steer it with agent_send(job_id), stop it with job_abort; job_list shows children.";
1858
+ const SUBAGENT_SCHEMA_SHAPE = {
1859
+ prompt: { type: "string" },
1860
+ mode: {
1861
+ type: "string",
1862
+ optional: true,
1863
+ enum: ["sync", "background"]
1864
+ },
1865
+ start_target: {
1866
+ type: "string",
1867
+ optional: true,
1868
+ enum: [
1869
+ "fresh",
1870
+ "fork",
1871
+ "resume"
1872
+ ]
1873
+ },
1874
+ resume_session_id: {
1875
+ type: "string",
1876
+ optional: true
1877
+ },
1878
+ readonly: {
1879
+ type: "boolean",
1880
+ optional: true
1881
+ },
1882
+ isolation: {
1883
+ type: "string",
1884
+ optional: true,
1885
+ enum: [
1886
+ "auto",
1887
+ "in-place",
1888
+ "worktree"
1889
+ ]
1890
+ },
1891
+ model: {
1892
+ type: "string",
1893
+ optional: true
1894
+ },
1895
+ label: {
1896
+ type: "string",
1897
+ optional: true
1898
+ },
1899
+ provider: {
1900
+ type: "string",
1901
+ optional: true
1902
+ },
1903
+ effort: {
1904
+ type: "string",
1905
+ optional: true,
1906
+ enum: [...THINKING_LEVELS]
1907
+ },
1908
+ tasks: {
1909
+ type: "array",
1910
+ items: { type: "string" },
1911
+ optional: true
1912
+ },
1913
+ persona: {
1914
+ type: "object",
1915
+ optional: true,
1916
+ properties: {
1917
+ plugin_id: { type: "string" },
1918
+ persona_id: { type: "string" },
1919
+ scope: {
1920
+ type: "string",
1921
+ optional: true,
1922
+ enum: ["global"]
1923
+ }
1924
+ }
1925
+ }
1926
+ };
1927
+ const SUBAGENT_SCHEMA = objectSchema(SUBAGENT_SCHEMA_SHAPE, { rejectUnknownFields: true });
1928
+ const SUBAGENT_SCHEMA_WITHOUT_PERSONA = objectSchema(Object.fromEntries(Object.entries(SUBAGENT_SCHEMA_SHAPE).filter(([key]) => key !== "persona")), { rejectUnknownFields: true });
1929
+ const PERSONA_LISTING_LIMIT = 20;
1930
+ function spawnSchemaFor(personas) {
1931
+ if (personas.length > 0) return SUBAGENT_SCHEMA;
1932
+ return {
1933
+ parse: (data) => SUBAGENT_SCHEMA.parse(data),
1934
+ safeParse: (data) => SUBAGENT_SCHEMA.safeParse(data),
1935
+ toJSONSchema: () => SUBAGENT_SCHEMA_WITHOUT_PERSONA.toJSONSchema?.()
1936
+ };
1937
+ }
1938
+ function personaGuidanceOf(personas) {
1939
+ if (personas.length === 0) return "";
1940
+ return ` persona: optional; only one of the installed personas (plugin_id/persona_id): ${personas.slice(0, PERSONA_LISTING_LIMIT).map((ref) => `${ref.pluginId}/${ref.personaId}`).join(", ")}${personas.length > PERSONA_LISTING_LIMIT ? ` (+${personas.length - PERSONA_LISTING_LIMIT} more)` : ""}. Omit the field otherwise, never send empty ids.`;
1941
+ }
1942
+ const SEND_MESSAGE_SCHEMA = objectSchema({
1943
+ job_id: {
1944
+ type: "string",
1945
+ optional: true
1946
+ },
1947
+ child_session_id: {
1948
+ type: "string",
1949
+ optional: true
1950
+ },
1951
+ job_key: {
1952
+ type: "string",
1953
+ optional: true
1954
+ },
1955
+ text: { type: "string" }
1956
+ }, {
1957
+ rejectUnknownFields: true,
1958
+ refine: (value) => {
1959
+ const jobId = typeof value["job_id"] === "string" ? value["job_id"].trim() : "";
1960
+ const childSessionId = typeof value["child_session_id"] === "string" ? value["child_session_id"].trim() : "";
1961
+ if (jobId === "" && childSessionId === "") return ["pass job_id (from job_list) or child_session_id (from agent_spawn or job_list)"];
1962
+ }
1963
+ });
1964
+ const PERSONA_PARTIAL_MESSAGE = "persona needs both plugin_id and persona_id; omit the persona field entirely to spawn without a persona";
1965
+ function personaRefOf(persona) {
1966
+ if (persona === void 0) return;
1967
+ const pluginId = persona.plugin_id.trim();
1968
+ const personaId = persona.persona_id.trim();
1969
+ if (pluginId === "" && personaId === "") return;
1970
+ if (pluginId === "" || personaId === "") return "partial";
1971
+ return {
1972
+ scope: persona.scope ?? "global",
1973
+ pluginId,
1974
+ personaId
1975
+ };
1976
+ }
1977
+ function runtimeError(text) {
1978
+ return {
1979
+ content: textToolContent(text),
1980
+ isError: true,
1981
+ errorKind: "runtime"
1982
+ };
1983
+ }
1984
+ function failureDetails(fallbackProvider) {
1985
+ return fallbackProvider !== void 0 && fallbackProvider.length > 0 ? { provider: fallbackProvider } : {};
1986
+ }
1987
+ function artifactsNote(receipt) {
1988
+ if (receipt === void 0) return "";
1989
+ if (receipt.files.length === 0 && receipt.patchBytes === 0) return "";
1990
+ const digest = receipt.patchDigest.slice(0, 12);
1991
+ return `\n\n[artifacts: ${receipt.files.length} file(s) · ${receipt.patchBytes} bytes · digest ${digest} · patch ${receipt.patchRef} · apply with isolation_apply]`;
1992
+ }
1993
+ function artifactsDetails(receipt) {
1994
+ return receipt === void 0 ? {} : { artifacts: receipt };
1995
+ }
1996
+ function isolationDetails(isolation) {
1997
+ return isolation === void 0 ? {} : { isolation };
1998
+ }
1999
+ function isolationNote(isolation) {
2000
+ return isolation === "in-place" ? "\n\nisolation=in-place" : "";
2001
+ }
2002
+ function releaseFailureOf(run, jobs, owner, childSessionId) {
2003
+ if (jobs === void 0) return releaseFailure(run.release());
2004
+ const snapshot = jobs.forOwner(owner).list().find((job) => job.subjectId === childSessionId);
2005
+ if (snapshot === void 0) return Promise.resolve(void 0);
2006
+ return Promise.resolve(releaseFailureOfPhase(snapshot.release));
2007
+ }
2008
+ function releaseFailureOfPhase(release) {
2009
+ if (release.phase === "failed") return release.error;
2010
+ if (release.phase === "abandoned") return release.error;
2011
+ if (release.phase === "pending") return "the runtime resources have not confirmed release yet";
2012
+ }
2013
+ function releaseNote(failure) {
2014
+ if (failure === void 0) return "";
2015
+ return `
2016
+
2017
+ <subagent_resource_release_unconfirmed>
2018
+ The subagent result above is final, but its runtime resources did not confirm release: ${failure}\n</subagent_resource_release_unconfirmed>`;
2019
+ }
2020
+ function releaseDetails(failure) {
2021
+ if (failure === void 0) return {};
2022
+ return {
2023
+ resourceReleaseUnconfirmed: true,
2024
+ resourceReleaseError: failure
2025
+ };
2026
+ }
2027
+ const SETTLE_RELEASE_WAIT_MS = 2e3;
2028
+ function createSubagentTool(control, sessions = () => void 0, personas = [], jobs = () => void 0, waitReportOf = () => void 0) {
2029
+ return defineTool({
2030
+ name: TOOL_NAMES.agentSpawn,
2031
+ description: "Delegate a subtask to a child agent (a separate agent with its own context and tools) — this is not a shell command: use it when the work needs its own reasoning, not when a single command would do. mode=sync (default) runs inline and returns the answer only after the child finishes; it is exclusive — it blocks the whole turn, and several sync spawns in one message run one after another. mode=background returns a job_id immediately and wakes you when it settles, which is the right shape for long work. The host caps how many subagents may be in flight per session; when the cap is hit the refusal says so, so delegate in background rather than retrying in a loop. start_target=fork copies the conversation; start_target=resume with resume_session_id continues an idle child. model: id from list_models. provider: subagent execution backend, not the model vendor (rarely needed). tasks: plan item ids from task_write. readonly caps a fresh or forked child at read-only permissions (it can read and run read-only commands, but write/edit and mutating shell commands are denied); it cannot be applied to a resumed session (that cap belongs to the session creation contract), so omit readonly when start_target=resume. isolation: auto (default) runs a read-only child in the parent workspace and gives a child that may write its own git worktree; in-place shares the parent workspace and is refused unless the child is read-only; worktree always allocates one. A resumed child keeps the workspace it was created with, so omit isolation when start_target=resume." + personaGuidanceOf(personas),
2032
+ schema: spawnSchemaFor(personas),
2033
+ effects: effectsOf({ spawns: "agent" }),
2034
+ concurrency: (input) => input.mode === "background",
2035
+ async execute(input, ctx) {
2036
+ const a = input;
2037
+ const mode = a.mode ?? "sync";
2038
+ const parent = {
2039
+ sessionId: ctx.sessionId,
2040
+ depth: ctx.depth ?? 0,
2041
+ cwd: ctx.cwd
2042
+ };
2043
+ const start = a.start_target === "fork" ? {
2044
+ target: "fork",
2045
+ parent
2046
+ } : a.start_target === "resume" ? {
2047
+ target: "resume",
2048
+ sessionId: a.resume_session_id ?? ""
2049
+ } : { target: "fresh" };
2050
+ if (start.target === "resume" && start.sessionId.length === 0) return runtimeError("resume_session_id is required when start_target=resume");
2051
+ if (start.target === "resume" && a.readonly === true) return {
2052
+ content: textToolContent("readonly cannot be applied to a resumed session: the permission cap belongs to the session creation contract; start a fresh or forked subagent instead"),
2053
+ isError: true,
2054
+ errorKind: "validation"
2055
+ };
2056
+ const planCheck = checkPlanItemIds(sessions(), ctx.sessionId, a.tasks ?? []);
2057
+ if (!planCheck.ok) return planCheck.kind === "unknown" ? {
2058
+ content: textToolContent(`tasks references unknown plan item ids: ${planCheck.ids.join("; ")}`),
2059
+ isError: true,
2060
+ errorKind: "validation"
2061
+ } : {
2062
+ content: textToolContent(planCheck.message),
2063
+ isError: true,
2064
+ errorKind: "io"
2065
+ };
2066
+ const persona = personaRefOf(a.persona);
2067
+ if (persona === "partial") return {
2068
+ content: textToolContent(PERSONA_PARTIAL_MESSAGE),
2069
+ isError: true,
2070
+ errorKind: "validation"
2071
+ };
2072
+ const request = {
2073
+ prompt: a.prompt,
2074
+ parent,
2075
+ start,
2076
+ signal: ctx.signal,
2077
+ ...a.model !== void 0 ? { model: a.model } : {},
2078
+ ...a.label !== void 0 ? { label: a.label } : {},
2079
+ ...a.effort !== void 0 ? { effort: a.effort } : {},
2080
+ ...a.tasks !== void 0 ? { itemIds: a.tasks } : {},
2081
+ ...ctx.turn !== void 0 ? { originTurn: ctx.turn } : {},
2082
+ ...ctx.stageAttemptId === void 0 ? {} : { stageAttemptId: ctx.stageAttemptId },
2083
+ ...a.readonly === true ? { permissionCap: { readonly: true } } : {},
2084
+ ...a.isolation === void 0 ? {} : { isolation: a.isolation },
2085
+ ...persona === void 0 ? {} : { persona }
2086
+ };
2087
+ let started;
2088
+ let executionControl;
2089
+ try {
2090
+ executionControl = control();
2091
+ started = await executionControl.start(request, mode, a.provider);
2092
+ } catch (error) {
2093
+ const message = error instanceof Error ? error.message : String(error);
2094
+ return {
2095
+ ...runtimeError(`${message}${start.target === "resume" && message.includes("execution directory") ? " The isolated worktree of the earlier run was released, so that child can no longer be resumed; start a fresh subagent instead." : ""}`),
2096
+ details: failureDetails(a.provider)
2097
+ };
2098
+ }
2099
+ if (started.kind === "queued") return {
2100
+ content: textToolContent(`Subagent accepted and queued: every worker slot is busy, so it will start by itself as soon as one frees up. job_id: ${started.snapshot.id} — it is already a normal job: use job_output to read it, job_abort to cancel it. Do not start it again.`),
2101
+ details: {
2102
+ mode,
2103
+ jobId: started.snapshot.id,
2104
+ queued: true
2105
+ }
2106
+ };
2107
+ if (started.kind === "job") return {
2108
+ content: textToolContent(`Subagent started in background. job_id: ${started.snapshot.id} · child_session_id: ${started.childSessionId} — use job_output to read it, job_abort to stop it, agent_send(job_id:'${started.snapshot.id}') to steer it.`),
2109
+ details: {
2110
+ mode,
2111
+ jobId: started.snapshot.id,
2112
+ childSessionId: started.childSessionId,
2113
+ provider: started.resolved.provider,
2114
+ modelId: started.resolved.modelId,
2115
+ ...started.resolved.effort !== void 0 ? { effort: started.resolved.effort } : {}
2116
+ }
2117
+ };
2118
+ const { runId, run, resolved } = started;
2119
+ const jobId = started.snapshot?.id;
2120
+ const resolvedDetails = {
2121
+ provider: resolved.provider,
2122
+ modelId: resolved.modelId,
2123
+ ...resolved.effort !== void 0 ? { effort: resolved.effort } : {}
2124
+ };
2125
+ const cancelCause = () => {
2126
+ const reason = ctx.signal.reason;
2127
+ if (reason === TOOL_DEADLINE_ABORT_REASON) return "deadline";
2128
+ if (reason === "stall") return "stalled";
2129
+ if (reason === "disposed") return "disposed";
2130
+ if (reason === "parent") return "owner";
2131
+ return "user";
2132
+ };
2133
+ const forward = () => {
2134
+ const cause = cancelCause();
2135
+ if (cause === "deadline" || cause === "stalled") {
2136
+ if (executionControl.detachRun?.(runId, { deliverIfSettled: true }) === true) return;
2137
+ }
2138
+ executionControl.cancelRun(runId, cause);
2139
+ };
2140
+ ctx.signal.addEventListener("abort", forward, { once: true });
2141
+ if (ctx.signal.aborted) forward();
2142
+ const waitReport = waitReportOf();
2143
+ const waitTarget = run.childSessionId;
2144
+ if (waitReport !== void 0) {
2145
+ const decision = await waitReport.begin({
2146
+ waiter: ctx.sessionId,
2147
+ target: waitTarget
2148
+ });
2149
+ if (!decision.ok) {
2150
+ ctx.signal.removeEventListener("abort", forward);
2151
+ await waitReport.end({
2152
+ waiter: ctx.sessionId,
2153
+ target: waitTarget
2154
+ }).catch(() => void 0);
2155
+ return {
2156
+ content: textToolContent(`subagent ${waitTarget} refused the wait (${decision.code}); returned without blocking`),
2157
+ isError: true,
2158
+ errorKind: "validation"
2159
+ };
2160
+ }
2161
+ }
2162
+ try {
2163
+ const result = await run.done;
2164
+ await settledBeforeRelease(jobs(), ctx.sessionId, result, ctx.signal);
2165
+ const releaseFailure = await releaseFailureOf(run, jobs(), ctx.sessionId, result.childSessionId);
2166
+ const note = releaseNote(releaseFailure);
2167
+ if (result.status === "partial") {
2168
+ const incomplete = `\n\n<subagent_incomplete reason="${result.reason ?? "unknown"}">\nThe subagent did not finish cleanly; the output above may be truncated or incomplete.\n</subagent_incomplete>`;
2169
+ return {
2170
+ content: textToolContent((result.text.length > 0 ? result.text : `(no output — subagent session ${result.childSessionId})`) + incomplete + note + artifactsNote(result.artifacts) + isolationNote(result.isolation)),
2171
+ details: {
2172
+ mode,
2173
+ sessionId: result.childSessionId,
2174
+ ...jobId !== void 0 ? { jobId } : {},
2175
+ ...resolvedDetails,
2176
+ incomplete: true,
2177
+ reason: result.reason,
2178
+ ...isolationDetails(result.isolation),
2179
+ ...artifactsDetails(result.artifacts),
2180
+ ...releaseDetails(releaseFailure)
2181
+ }
2182
+ };
2183
+ }
2184
+ if (result.status !== "completed") {
2185
+ const recovery = result.status === "failed" ? describeSubagentRecovery(result.recovery) : "";
2186
+ const baseDetail = result.status === "failed" ? result.error : result.status === "cancelled" ? result.cause : "";
2187
+ const detail = recovery === "" ? baseDetail : `${baseDetail}\n${recovery}`;
2188
+ return {
2189
+ ...runtimeError(`Subagent ${result.status}: ${detail || result.text || "no output"}${note}${artifactsNote(result.artifacts)}${isolationNote(result.isolation)}`),
2190
+ details: {
2191
+ mode,
2192
+ sessionId: result.childSessionId,
2193
+ ...jobId !== void 0 ? { jobId } : {},
2194
+ ...resolvedDetails,
2195
+ ...isolationDetails(result.isolation),
2196
+ ...artifactsDetails(result.artifacts),
2197
+ ...releaseDetails(releaseFailure)
2198
+ }
2199
+ };
2200
+ }
2201
+ return {
2202
+ content: textToolContent((result.text.length > 0 ? result.text : "(no output)") + note + artifactsNote(result.artifacts) + isolationNote(result.isolation)),
2203
+ details: {
2204
+ mode,
2205
+ sessionId: result.childSessionId,
2206
+ ...jobId !== void 0 ? { jobId } : {},
2207
+ ...resolvedDetails,
2208
+ ...isolationDetails(result.isolation),
2209
+ ...artifactsDetails(result.artifacts),
2210
+ ...releaseDetails(releaseFailure)
2211
+ }
2212
+ };
2213
+ } finally {
2214
+ if (waitReport !== void 0) await waitReport.end({
2215
+ waiter: ctx.sessionId,
2216
+ target: waitTarget
2217
+ }).catch(() => void 0);
2218
+ ctx.signal.removeEventListener("abort", forward);
2219
+ }
2220
+ }
2221
+ });
2222
+ }
2223
+ function jobIdOf(outcome) {
2224
+ if (typeof outcome !== "object" || outcome === null) return;
2225
+ const value = outcome.jobId;
2226
+ return typeof value === "string" && value !== "" ? value : void 0;
2227
+ }
2228
+ async function settledBeforeRelease(jobs, owner, outcome, signal) {
2229
+ const jobId = jobIdOf(outcome);
2230
+ if (jobs === void 0 || jobId === void 0 || signal?.aborted === true) return;
2231
+ await jobs.forOwner(owner).wait(jobId, SETTLE_RELEASE_WAIT_MS, signal).catch(() => void 0);
2232
+ }
2233
+ function createSendMessage(control) {
2234
+ return defineTool({
2235
+ name: TOOL_NAMES.agentSend,
2236
+ description: "Send text to a running or retained idle subagent: a running one receives it before its next step, a retained idle one is woken as a new turn. Address it with job_id (from job_list) or child_session_id (from agent_spawn or job_list); when the job row is gone but the child session still exists, child_session_id is the way back. job_key (from the settled notice) refuses steering a run that reused the id. Fresh subagents release their handle after completion; continue one with agent_spawn start_target=resume.",
2237
+ schema: SEND_MESSAGE_SCHEMA,
2238
+ effects: effectsOf({ spawns: "agent" }),
2239
+ concurrency: () => true,
2240
+ async execute(input, ctx) {
2241
+ const a = input;
2242
+ const receiptOf = control();
2243
+ const caller = receiptOf.capabilityOf(ctx.sessionId);
2244
+ const followupReceipt = receiptOf.followupReceipt;
2245
+ const address = {
2246
+ ...a.job_id === void 0 ? {} : { jobId: a.job_id },
2247
+ ...a.child_session_id === void 0 ? {} : { childSessionId: a.child_session_id }
2248
+ };
2249
+ const receipt = followupReceipt === void 0 ? { outcome: await receiptOf.followup(a.job_id ?? "", a.text, caller, a.job_key) } : await followupReceipt.call(receiptOf, address, a.text, caller, a.job_key);
2250
+ const target = a.job_id ?? a.child_session_id ?? "";
2251
+ const outcome = receipt.outcome;
2252
+ if (outcome === "failed") return runtimeError(`No target "${a.job_id ?? a.child_session_id}" for this session` + (a.job_key === void 0 ? "" : " (or job_key does not match the current run)") + " — call job_list for job ids and child_session_ids (pass child_session_id when the job row is gone), or continue a finished child with agent_spawn start_target=resume");
2253
+ if (outcome === "held") return { content: textToolContent(`queued for ${target} without waking (it runs after the child's next wake)`) };
2254
+ if (receipt.jobId !== void 0) return { content: textToolContent(`delivered to ${target}; woke it as new job ${receipt.jobId}${receipt.jobKey === void 0 ? "" : ` [job_key ${receipt.jobKey}]`} — read it with job_output ${receipt.jobId}`) };
2255
+ if (receipt.wakeJob === false) return {
2256
+ content: textToolContent(`delivered to ${target}, but no wake job could be registered: if the child is idle it will not pick this up until something wakes it — send again, or continue it with agent_spawn start_target=resume.`),
2257
+ isError: true,
2258
+ errorKind: "runtime",
2259
+ details: {
2260
+ delivered: true,
2261
+ wakeJob: false
2262
+ }
2263
+ };
2264
+ return { content: textToolContent(`delivered to ${target}`) };
2265
+ }
2266
+ });
2267
+ }
2268
+
2269
+ //#endregion
2270
+ //#region src/component.ts
2271
+ const Subagent = defineComponent("Subagent", (ctx, options) => {
2272
+ const hooks = ctx.consume(SLOTS.hooks);
2273
+ const agentSessions = ctx.consume(SLOTS.agentSessionRegistry);
2274
+ const tasks = ctx.consume(SLOTS.jobs);
2275
+ const processOwners = ctx.maybe(SLOTS.processOwners);
2276
+ const models = ctx.consume(SLOTS.models);
2277
+ const settings = ctx.maybe(SLOTS.settings);
2278
+ const sessionStore = ctx.maybe(SLOTS.sessions);
2279
+ const availability = ctx.maybe(SLOTS.modelAvailability);
2280
+ const artifactStore = ctx.maybe(SLOTS.artifactStore);
2281
+ const executionBackend = ctx.maybe(SLOTS.executionBackend);
2282
+ const recoveryController = ctx.maybe(SLOTS.recoveryController);
2283
+ const jobAdmission = ctx.maybe(SLOTS.jobAdmission);
2284
+ const providerDiagnose = (code, message) => {
2285
+ safeEmit(hooks, TIMINGS.runtimeDiagnostic, {
2286
+ source: "provider",
2287
+ severity: "warning",
2288
+ code,
2289
+ message
2290
+ }, {
2291
+ timing: TIMINGS.runtimeDiagnostic,
2292
+ code: "HOOK_EMIT_FAILED"
2293
+ });
2294
+ };
2295
+ const spawnableDepth = resolveGovernorLimits(options.limits ?? {}).maxDelegationDepth - 1;
2296
+ let subagentModelsField;
2297
+ const readAllowedModels = () => {
2298
+ const manager = settings();
2299
+ if (manager === void 0) return [];
2300
+ try {
2301
+ subagentModelsField ??= manager.registerField(SUBAGENT_MODELS_FIELD_SPEC, "subagent");
2302
+ return subagentModelsField.get() ?? [];
2303
+ } catch (error) {
2304
+ providerDiagnose("SUBAGENT_MODELS_UNAVAILABLE", `subagent model allowlist is unavailable; every usable model is allowed: ${error instanceof Error ? error.message : String(error)}`);
2305
+ return [];
2306
+ }
2307
+ };
2308
+ let slotQueueingField;
2309
+ const isSlotQueueingEnabled = () => {
2310
+ const manager = settings();
2311
+ if (manager === void 0) return true;
2312
+ try {
2313
+ slotQueueingField ??= manager.registerField(WORKER_SLOT_QUEUEING_FIELD_SPEC, "subagent");
2314
+ return slotQueueingField.get() !== false;
2315
+ } catch {
2316
+ return true;
2317
+ }
2318
+ };
2319
+ let fanOutLimitField;
2320
+ const readFanOutLimit = () => {
2321
+ const manager = settings();
2322
+ if (manager === void 0) return;
2323
+ try {
2324
+ fanOutLimitField ??= manager.registerField(SUBAGENT_MAX_FAN_OUT_FIELD_SPEC, "subagent");
2325
+ return fanOutLimitField.get();
2326
+ } catch (error) {
2327
+ providerDiagnose("SUBAGENT_FAN_OUT_LIMIT_UNAVAILABLE", `subagent fan-out limit setting is unavailable; falling back to the configured limit: ${error instanceof Error ? error.message : String(error)}`);
2328
+ return;
2329
+ }
2330
+ };
2331
+ const state = ctx.resource("subagent-state", () => new SubagentControlState(), (kept) => disposeSubagentControlState(kept, {
2332
+ cancelActiveRuns: (cause) => cancelDelegationRuns(tasks(), cause),
2333
+ onCancelError: (error) => providerDiagnose("SUBAGENT_CANCEL_FAILED", error instanceof Error ? error.message : String(error))
2334
+ }), {
2335
+ hmr: "preserve",
2336
+ validate: isSubagentControlState
2337
+ });
2338
+ const control = new SubagentControlImpl({
2339
+ tasks: () => tasks(),
2340
+ processOwners: () => processOwners(),
2341
+ sessions: () => agentSessions(),
2342
+ clock: options.ports.clock,
2343
+ meta: (sessionId) => sessionStore()?.get(sessionId) ?? Promise.resolve(null),
2344
+ emit: (timing, payload) => safeEmit(hooks, timing, payload, {
2345
+ timing: TIMINGS.runtimeDiagnostic,
2346
+ code: "HOOK_EMIT_FAILED"
2347
+ }),
2348
+ observe: (name, timing, handler) => {
2349
+ const registered = hooks().register({
2350
+ name,
2351
+ timing,
2352
+ kind: "observer",
2353
+ handle: (input) => handler(input)
2354
+ });
2355
+ return () => registered.dispose();
2356
+ },
2357
+ ...options.limits !== void 0 ? { limits: options.limits } : {},
2358
+ ...options.limits?.maxFanOutPerParent === void 0 ? { fanOutLimit: readFanOutLimit } : {},
2359
+ admission: { reserve: async (parentSessionId) => await jobAdmission()?.reserve?.(parentSessionId) },
2360
+ slotWait: { isEnabled: isSlotQueueingEnabled }
2361
+ }, state);
2362
+ ctx.effect(() => () => control.retireQueue());
2363
+ ctx.provide(SLOTS.subagents, () => control);
2364
+ if (options.workspaceRoots !== void 0) {
2365
+ const workspaceRoots = options.workspaceRoots;
2366
+ ctx.provide(SLOTS.subagentWorkspaces, () => workspaceRoots);
2367
+ }
2368
+ ctx.contribute(SLOTS.sessionResources, "subagent", {
2369
+ phase: "cancel",
2370
+ dispose: (sessionId) => control.releaseParent(sessionId)
2371
+ });
2372
+ ctx.effect(() => control.registerProvider(createInProcessProvider({
2373
+ ids: () => options.ports.id.generate(),
2374
+ random: () => options.ports.random.next(),
2375
+ sessions: () => agentSessions(),
2376
+ models: () => models(),
2377
+ availability: () => availability(),
2378
+ allowedModels: readAllowedModels,
2379
+ recoveryOf: (sessionId) => recoveryController()?.snapshot(sessionId),
2380
+ clock: () => options.ports.clock.now(),
2381
+ diagnose: providerDiagnose,
2382
+ ...options.workspaceRoots === void 0 ? {} : { workspaceRoots: options.workspaceRoots },
2383
+ ...options.personas === void 0 ? {} : { personas: options.personas },
2384
+ ...options.claimSession === void 0 ? {} : { claimSession: options.claimSession }
2385
+ })));
2386
+ const availablePersonas = createMemo(() => options.personas?.available?.() ?? [], [], { equals: samePersonaRefs });
2387
+ ctx.effect(() => {
2388
+ const waitReportPort = ctx.maybe(SLOTS.jobWaitReport);
2389
+ const spawnTool = createSubagentTool(() => control, sessionStore, availablePersonas(), () => tasks(), waitReportPort);
2390
+ const tools = [spawnTool, createSendMessage(() => control)];
2391
+ const controlPlaneMetadata = {
2392
+ preset: "standard",
2393
+ category: "subagent",
2394
+ guideline: SUBAGENT_GUIDELINE,
2395
+ controlPlane: true
2396
+ };
2397
+ for (const tool of tools) {
2398
+ const metadata = tool === spawnTool ? {
2399
+ ...controlPlaneMetadata,
2400
+ maxDepth: spawnableDepth
2401
+ } : controlPlaneMetadata;
2402
+ ctx.contribute(SLOTS.tools, tool.name, {
2403
+ tool,
2404
+ metadata
2405
+ });
2406
+ }
2407
+ const requireBackend = () => {
2408
+ const backend = executionBackend();
2409
+ if (backend === void 0) throw new Error("execution backend is unavailable in this host");
2410
+ return backend;
2411
+ };
2412
+ for (const tool of [createIsolationApplyTool(() => artifactStore(), requireBackend), createIsolationPendingTool(() => artifactStore())]) ctx.contribute(SLOTS.tools, tool.name, {
2413
+ tool,
2414
+ metadata: {
2415
+ preset: "standard",
2416
+ category: "isolation"
2417
+ }
2418
+ });
2419
+ });
2420
+ });
2421
+ function samePersonaRefs(left, right) {
2422
+ if (left.length !== right.length) return false;
2423
+ return left.every((ref, index) => {
2424
+ const other = right[index];
2425
+ return other !== void 0 && ref.scope === other.scope && ref.pluginId === other.pluginId && ref.personaId === other.personaId;
2426
+ });
2427
+ }
2428
+
2429
+ //#endregion
2430
+ //#region src/persona-source.ts
2431
+ const PERSONA_CONTRIBUTION_KEY = "personas";
2432
+ function recordOf(value) {
2433
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2434
+ }
2435
+ function stringField(source, key) {
2436
+ const value = source[key];
2437
+ return typeof value === "string" && value !== "" ? value : void 0;
2438
+ }
2439
+ function stringListField(source, key) {
2440
+ const value = source[key];
2441
+ if (!Array.isArray(value)) return;
2442
+ const entries = value.filter((entry) => typeof entry === "string");
2443
+ return entries.length === 0 ? void 0 : entries;
2444
+ }
2445
+ function personaDeclarationOf(record) {
2446
+ const instructions = stringField(record, "instructions");
2447
+ if (instructions === void 0) return;
2448
+ const preset = stringField(record, "preset");
2449
+ const tools = stringListField(record, "tools");
2450
+ const excludeTools = stringListField(record, "excludeTools");
2451
+ const model = stringField(record, "model");
2452
+ const effort = stringField(record, "effort");
2453
+ const cwd = stringField(record, "cwd");
2454
+ return {
2455
+ instructions,
2456
+ ...preset === void 0 ? {} : { preset },
2457
+ ...tools === void 0 ? {} : { tools },
2458
+ ...excludeTools === void 0 ? {} : { excludeTools },
2459
+ ...model === void 0 ? {} : { model },
2460
+ ...effort === void 0 ? {} : { effort },
2461
+ ...cwd === void 0 ? {} : { cwd }
2462
+ };
2463
+ }
2464
+ function personasOfManifest(manifest) {
2465
+ const list = manifest.contributes?.[PERSONA_CONTRIBUTION_KEY];
2466
+ if (!Array.isArray(list)) return [];
2467
+ return list.map((entry) => recordOf(entry)).filter((entry) => entry !== void 0);
2468
+ }
2469
+ function personaDeclarationOfManifest(manifest, personaId) {
2470
+ for (const record of personasOfManifest(manifest)) {
2471
+ if (record["id"] !== personaId) continue;
2472
+ return personaDeclarationOf(record);
2473
+ }
2474
+ }
2475
+ function personaRefsOfManifest(manifest) {
2476
+ const refs = [];
2477
+ for (const record of personasOfManifest(manifest)) {
2478
+ const personaId = record["id"];
2479
+ if (typeof personaId !== "string" || personaId.trim() === "") continue;
2480
+ if (personaDeclarationOf(record) === void 0) continue;
2481
+ refs.push({
2482
+ scope: "global",
2483
+ pluginId: manifest.id,
2484
+ personaId
2485
+ });
2486
+ }
2487
+ return refs;
2488
+ }
2489
+ function createManifestPersonaResolver(lookup, globalManifests) {
2490
+ return {
2491
+ ...globalManifests === void 0 ? {} : { available: () => globalManifests().flatMap((manifest) => personaRefsOfManifest(manifest)) },
2492
+ async resolve(ref) {
2493
+ const manifest = await lookup(ref);
2494
+ if (manifest === void 0) return;
2495
+ return personaDeclarationOfManifest(manifest, ref.personaId);
2496
+ }
2497
+ };
2498
+ }
2499
+
2500
+ //#endregion
2501
+ //#region src/workspaces/artifact-store.ts
2502
+ const FENCING_CONSUMED_BY_STALE_LEASE = "artifact fencing check failed";
2503
+ const PATCH_FILENAME = "changes.patch";
2504
+ const RECEIPT_FILENAME = "receipt.json";
2505
+ const RECEIPT_FINAL_FILENAME = "receipt.final.json";
2506
+ const ARTIFACT_PENDING_DIRNAME = "pending";
2507
+ function createArtifactStore(options) {
2508
+ const directoryOf = (receiptId) => join(options.root(), receiptId);
2509
+ const finalPathOf = (receiptId) => join(options.root(), receiptId, RECEIPT_FINAL_FILENAME);
2510
+ const isPending = async (receiptId) => {
2511
+ try {
2512
+ await stat(finalPathOf(receiptId));
2513
+ return false;
2514
+ } catch {
2515
+ return true;
2516
+ }
2517
+ };
2518
+ return {
2519
+ async listPending() {
2520
+ let entries;
2521
+ try {
2522
+ entries = await readdir(options.root());
2523
+ } catch {
2524
+ return {
2525
+ receipts: [],
2526
+ unreadable: 0
2527
+ };
2528
+ }
2529
+ const receipts = [];
2530
+ let unreadable = 0;
2531
+ for (const receiptId of entries) {
2532
+ if (receiptId === "pending") continue;
2533
+ const stored = await readJsonFile(join(directoryOf(receiptId), RECEIPT_FILENAME), void 0);
2534
+ if (stored === void 0 || !await isPending(receiptId)) {
2535
+ if (stored === void 0) unreadable += 1;
2536
+ continue;
2537
+ }
2538
+ receipts.push(stored);
2539
+ }
2540
+ receipts.sort((left, right) => left.createdAt - right.createdAt);
2541
+ return {
2542
+ receipts,
2543
+ unreadable
2544
+ };
2545
+ },
2546
+ async markConsumed(receiptId) {
2547
+ const source = join(directoryOf(receiptId), RECEIPT_FILENAME);
2548
+ const stored = await readJsonFile(source, void 0);
2549
+ if (stored === void 0 || stored.receiptId !== receiptId) throw new Error(`artifact receipt ${receiptId} does not exist`);
2550
+ const fencingRecord = options.fencing?.leaseOf(stored);
2551
+ if (fencingRecord !== void 0 && fencingRecord.generation > stored.generation) throw new Error(`${FENCING_CONSUMED_BY_STALE_LEASE}: lease ${stored.leaseId} is at generation ${fencingRecord.generation} but the receipt was sealed at ${stored.generation}`);
2552
+ if (createHash("sha256").update(await readFile(stored.patchRef, "utf8"), "utf8").digest("hex") !== stored.patchDigest) throw new Error(`artifact digest mismatch for ${receiptId}; refusing to mark consumed`);
2553
+ await rename(source, finalPathOf(receiptId));
2554
+ },
2555
+ async persistComplete(input) {
2556
+ const receiptId = `art-${options.now()}-${options.id.generate().slice(0, 8)}`;
2557
+ const directory = directoryOf(receiptId);
2558
+ await ensurePrivateDir(directory);
2559
+ const patchRef = join(directory, PATCH_FILENAME);
2560
+ await writeFileAtomic(patchRef, input.patch, {
2561
+ durable: true,
2562
+ syncDirectory: true
2563
+ });
2564
+ const receipt = {
2565
+ version: 1,
2566
+ receiptId,
2567
+ createdAt: options.now(),
2568
+ leaseId: input.leaseId,
2569
+ generation: input.generation,
2570
+ ...input.ownerSessionId === void 0 ? {} : { ownerSessionId: input.ownerSessionId },
2571
+ ...input.baseRevision === void 0 ? {} : { baseRevision: input.baseRevision },
2572
+ files: [...input.files],
2573
+ patchRef,
2574
+ patchBytes: Buffer.byteLength(input.patch, "utf8"),
2575
+ patchDigest: createHash("sha256").update(input.patch, "utf8").digest("hex")
2576
+ };
2577
+ await writeJsonAtomic(join(directory, RECEIPT_FILENAME), receipt, {
2578
+ durable: true,
2579
+ syncDirectory: true
2580
+ });
2581
+ return receipt;
2582
+ },
2583
+ async prune(input) {
2584
+ const now = input.now?.() ?? options.now();
2585
+ let entries;
2586
+ try {
2587
+ entries = await readdir(options.root());
2588
+ } catch {
2589
+ return {
2590
+ removed: [],
2591
+ kept: 0
2592
+ };
2593
+ }
2594
+ const candidates = [];
2595
+ for (const receiptId of entries) {
2596
+ if (receiptId === "pending") continue;
2597
+ const stored = await readJsonFile(join(directoryOf(receiptId), RECEIPT_FILENAME), void 0) ?? await readJsonFile(finalPathOf(receiptId), void 0) ?? void 0;
2598
+ candidates.push({
2599
+ receiptId,
2600
+ createdAt: stored?.createdAt ?? (await stat(join(options.root(), receiptId)).catch(() => void 0))?.mtimeMs ?? now,
2601
+ pending: await isPending(receiptId)
2602
+ });
2603
+ }
2604
+ candidates.sort((left, right) => right.createdAt - left.createdAt);
2605
+ const removable = candidates.filter((candidate) => !candidate.pending);
2606
+ const kept0 = candidates.length - removable.length;
2607
+ const removed = [];
2608
+ for (const [index, candidate] of removable.entries()) {
2609
+ if (index < Math.max(0, input.keepCount)) continue;
2610
+ if (now - candidate.createdAt < input.maxAgeMs) continue;
2611
+ await rm(join(options.root(), candidate.receiptId), {
2612
+ recursive: true,
2613
+ force: true
2614
+ });
2615
+ removed.push(candidate.receiptId);
2616
+ }
2617
+ return {
2618
+ removed,
2619
+ kept: kept0 + (removable.length - removed.length)
2620
+ };
2621
+ },
2622
+ toPort() {
2623
+ return {
2624
+ listPendingArtifacts: async () => {
2625
+ return (await this.listPending()).receipts.map((receipt) => `lease ${receipt.leaseId} · digest ${receipt.patchDigest.slice(0, 12)} · ${receipt.patchBytes} bytes · ${receipt.files.length} file(s) · patch ${receipt.patchRef}`);
2626
+ },
2627
+ markArtifactConsumed: (input) => this.markConsumed(input.receiptId)
2628
+ };
2629
+ },
2630
+ async verify(receipt) {
2631
+ const stored = await readJsonFile(join(directoryOf(receipt.receiptId), RECEIPT_FILENAME), void 0);
2632
+ if (stored === void 0) return false;
2633
+ try {
2634
+ const patch = await readFile(stored.patchRef, "utf8");
2635
+ return createHash("sha256").update(patch, "utf8").digest("hex") === stored.patchDigest;
2636
+ } catch {
2637
+ return false;
2638
+ }
2639
+ }
2640
+ };
2641
+ }
2642
+
2643
+ //#endregion
2644
+ //#region src/workspaces/subagent-workspaces.ts
2645
+ const run = promisify(execFile);
2646
+ const SUBAGENT_WORKTREES_DIRNAME = "subagent-worktrees";
2647
+ const EXECUTION_ROOT_RECORDS_DIRNAME = "subagent-execution-roots";
2648
+ const SUBAGENT_ARTIFACTS_DIRNAME = "subagent-artifacts";
2649
+ const ARTIFACT_KEEP_COUNT = 50;
2650
+ const ARTIFACT_MAX_AGE_MS = 10080 * 60 * 1e3;
2651
+ const HEARTBEAT_INTERVAL_MS = 60 * 1e3;
2652
+ const ROOT_ALLOCATION_ATTEMPTS = 32;
2653
+ const ORPHAN_WORKTREE_MAX_AGE_MS = 10080 * 60 * 1e3;
2654
+ async function gitOutput(cwd, args) {
2655
+ try {
2656
+ const { stdout } = await run("git", args, { cwd });
2657
+ return stdout.trim();
2658
+ } catch {
2659
+ return;
2660
+ }
2661
+ }
2662
+ async function gitRawOutput(cwd, args) {
2663
+ try {
2664
+ const { stdout } = await run("git", args, {
2665
+ cwd,
2666
+ maxBuffer: 64 * 1024 * 1024
2667
+ });
2668
+ return stdout;
2669
+ } catch {
2670
+ return;
2671
+ }
2672
+ }
2673
+ async function gitRun(cwd, args) {
2674
+ try {
2675
+ await run("git", args, { cwd });
2676
+ return { ok: true };
2677
+ } catch (error) {
2678
+ return {
2679
+ ok: false,
2680
+ error: error instanceof Error ? error.message : String(error)
2681
+ };
2682
+ }
2683
+ }
2684
+ async function resolveBaseRevision(toplevel, baseRevision) {
2685
+ if (baseRevision.startsWith("-")) throw new Error(`invalid base revision for the subagent workspace: ${baseRevision}`);
2686
+ const commit = await gitOutput(toplevel, [
2687
+ "rev-parse",
2688
+ "--verify",
2689
+ `${baseRevision}^{commit}`
2690
+ ]);
2691
+ if (commit === void 0 || commit === "") throw new Error(`invalid base revision for the subagent workspace: ${baseRevision}`);
2692
+ return commit;
2693
+ }
2694
+ async function resolveStartPoint(toplevel, baseRevision) {
2695
+ return baseRevision === void 0 ? "HEAD" : resolveBaseRevision(toplevel, baseRevision);
2696
+ }
2697
+ function executionRootLiveness(record, options = {}) {
2698
+ const pid = record.pid;
2699
+ if (pid === void 0 || !Number.isInteger(pid) || pid <= 0) return "unverifiable";
2700
+ const bootId = (options.bootId ?? nodeBootId)();
2701
+ if (record.bootId !== void 0 && isReliableBootId(record.bootId) && isReliableBootId(bootId) && record.bootId !== bootId) return "dead";
2702
+ const platform = options.platform ?? process.platform;
2703
+ if (pid === process.pid) {
2704
+ const own = (options.ownStartedAt ?? ownProcessStartedAt)();
2705
+ if (record.processStartedAt === void 0 || own === void 0) return "alive";
2706
+ return Math.abs(record.processStartedAt - own) <= PROCESS_START_TOLERANCE_MS ? "alive" : "dead";
2707
+ }
2708
+ const probed = (options.probeStartedAt ?? probeProcessStartedAt)(pid);
2709
+ if (probed === void 0) return platform === "darwin" || platform === "linux" ? "dead" : "unverifiable";
2710
+ if (record.processStartedAt !== void 0 && Math.abs(record.processStartedAt - probed) > PROCESS_START_TOLERANCE_MS) return "dead";
2711
+ return "alive";
2712
+ }
2713
+ function executionRootRecordPath(baseDir, root) {
2714
+ return join(baseDir, EXECUTION_ROOT_RECORDS_DIRNAME, `${basename(root)}.json`);
2715
+ }
2716
+ function parseExecutionRootRecord(baseDir, fileName, raw) {
2717
+ let parsed;
2718
+ try {
2719
+ parsed = JSON.parse(raw);
2720
+ } catch {
2721
+ return;
2722
+ }
2723
+ if (typeof parsed !== "object" || parsed === null) return;
2724
+ const { root, leaseId, generation, ownerSessionId, baseRevision, pid, bootId, processStartedAt, heartbeatAt } = parsed;
2725
+ if (typeof root !== "string" || typeof leaseId !== "string" || typeof generation !== "number" || typeof ownerSessionId !== "string" || ownerSessionId === "") return;
2726
+ if (dirname(root) !== join(baseDir, "subagent-worktrees") || `${basename(root)}.json` !== fileName) return;
2727
+ return {
2728
+ root,
2729
+ leaseId,
2730
+ generation,
2731
+ ownerSessionId,
2732
+ ...typeof baseRevision === "string" ? { baseRevision } : {},
2733
+ ...typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? { pid } : {},
2734
+ ...typeof bootId === "string" && bootId !== "" ? { bootId } : {},
2735
+ ...typeof processStartedAt === "number" && Number.isFinite(processStartedAt) ? { processStartedAt } : {},
2736
+ ...typeof heartbeatAt === "number" && Number.isFinite(heartbeatAt) ? { heartbeatAt } : {}
2737
+ };
2738
+ }
2739
+ function readExecutionRootRecords(baseDir) {
2740
+ const directory = join(baseDir, EXECUTION_ROOT_RECORDS_DIRNAME);
2741
+ const records = /* @__PURE__ */ new Map();
2742
+ let fileNames;
2743
+ try {
2744
+ fileNames = readdirSync(directory);
2745
+ } catch {
2746
+ return records;
2747
+ }
2748
+ for (const fileName of fileNames) {
2749
+ if (!fileName.endsWith(".json")) continue;
2750
+ const path = join(directory, fileName);
2751
+ let raw;
2752
+ try {
2753
+ raw = readFileSync(path, "utf8");
2754
+ } catch {
2755
+ continue;
2756
+ }
2757
+ const record = parseExecutionRootRecord(baseDir, fileName, raw);
2758
+ if (record === void 0) continue;
2759
+ if (!existsSync(record.root)) {
2760
+ rmSync(path, { force: true });
2761
+ continue;
2762
+ }
2763
+ records.set(record.root, record);
2764
+ }
2765
+ return records;
2766
+ }
2767
+ function recordOfLease(live, restored, leaseId) {
2768
+ for (const record of live.values()) if (record.leaseId === leaseId) return record;
2769
+ for (const record of restored.values()) if (record.leaseId === leaseId) return record;
2770
+ }
2771
+ function createSubagentWorkspaceRoots(options) {
2772
+ let counter = 0;
2773
+ const owned = /* @__PURE__ */ new Set();
2774
+ const live = /* @__PURE__ */ new Map();
2775
+ const restored = /* @__PURE__ */ new Map();
2776
+ const liveness = /* @__PURE__ */ new Map();
2777
+ const persistRecord = async (record) => {
2778
+ const baseDir = options.baseDir();
2779
+ try {
2780
+ await ensurePrivateDir(join(baseDir, EXECUTION_ROOT_RECORDS_DIRNAME));
2781
+ await writeJsonAtomic(executionRootRecordPath(baseDir, record.root), record);
2782
+ } catch (error) {
2783
+ const reason = error instanceof Error ? error.message : String(error);
2784
+ options.report?.(`subagent workspace record for ${record.root} was not saved; the session cannot reopen after a restart: ${reason}`);
2785
+ }
2786
+ };
2787
+ const heartbeat = () => {
2788
+ const at = options.clock.now();
2789
+ for (const [root, record] of live) {
2790
+ if (!owned.has(root) || at - (record.heartbeatAt ?? 0) < HEARTBEAT_INTERVAL_MS) continue;
2791
+ const next = {
2792
+ ...record,
2793
+ heartbeatAt: at
2794
+ };
2795
+ live.set(root, next);
2796
+ persistRecord(next);
2797
+ }
2798
+ };
2799
+ const refresh = () => {
2800
+ const records = readExecutionRootRecords(options.baseDir());
2801
+ for (const root of [...live.keys()]) if (!owned.has(root) && !records.has(root)) live.delete(root);
2802
+ for (const root of [...restored.keys()]) if (!records.has(root)) {
2803
+ restored.delete(root);
2804
+ liveness.delete(root);
2805
+ }
2806
+ for (const [root, record] of records) {
2807
+ if (owned.has(root)) continue;
2808
+ const verdict = executionRootLiveness(record);
2809
+ if (verdict === "alive" && record.pid === process.pid) {
2810
+ live.set(root, record);
2811
+ restored.delete(root);
2812
+ liveness.delete(root);
2813
+ continue;
2814
+ }
2815
+ live.delete(root);
2816
+ restored.set(root, record);
2817
+ liveness.set(root, verdict);
2818
+ }
2819
+ heartbeat();
2820
+ };
2821
+ const store = createArtifactStore({
2822
+ now: () => options.clock.now(),
2823
+ id: options.id,
2824
+ fencing: { leaseOf: (receipt) => {
2825
+ refresh();
2826
+ const record = recordOfLease(live, restored, receipt.leaseId);
2827
+ return record === void 0 ? void 0 : {
2828
+ leaseId: record.leaseId,
2829
+ generation: record.generation,
2830
+ ...record.ownerSessionId === void 0 ? {} : { ownerSessionId: record.ownerSessionId },
2831
+ ...record.root === void 0 ? {} : { root: record.root }
2832
+ };
2833
+ } },
2834
+ root: () => join(options.baseDir(), SUBAGENT_ARTIFACTS_DIRNAME)
2835
+ });
2836
+ const recordFor = (root) => live.get(root) ?? restored.get(root);
2837
+ const claim = (record) => {
2838
+ owned.add(record.root);
2839
+ live.set(record.root, record);
2840
+ restored.delete(record.root);
2841
+ liveness.delete(record.root);
2842
+ };
2843
+ return {
2844
+ async allocate(input) {
2845
+ const toplevel = await gitOutput(input.parentCwd, ["rev-parse", "--show-toplevel"]);
2846
+ if (toplevel === void 0 || toplevel === "") {
2847
+ options.report?.(`subagent workspace isolation is unavailable under ${input.parentCwd}: not a git work tree; the child shares the parent working directory`);
2848
+ return;
2849
+ }
2850
+ const startPoint = await resolveStartPoint(toplevel, input.baseRevision);
2851
+ await mkdir(join(options.baseDir(), SUBAGENT_WORKTREES_DIRNAME), { recursive: true });
2852
+ let root;
2853
+ for (let attempt = 0; attempt < ROOT_ALLOCATION_ATTEMPTS && root === void 0; attempt += 1) {
2854
+ counter += 1;
2855
+ const candidate = join(options.baseDir(), SUBAGENT_WORKTREES_DIRNAME, `${options.clock.now()}-${counter}`);
2856
+ if (!existsSync(candidate)) root = candidate;
2857
+ }
2858
+ if (root === void 0) {
2859
+ options.report?.(`subagent workspace isolation failed: no free worktree directory under ${options.baseDir()}; the child shares the parent working directory`);
2860
+ return;
2861
+ }
2862
+ const branch = input.branch;
2863
+ if ((branch === void 0 ? await gitOutput(toplevel, [
2864
+ "worktree",
2865
+ "add",
2866
+ "--detach",
2867
+ root,
2868
+ startPoint
2869
+ ]) : await gitOutput(toplevel, [
2870
+ "worktree",
2871
+ "add",
2872
+ "-b",
2873
+ branch,
2874
+ root,
2875
+ startPoint
2876
+ ])) === void 0) {
2877
+ options.report?.(`subagent workspace isolation failed: could not create a worktree at ${root}; the child shares the parent working directory`);
2878
+ return;
2879
+ }
2880
+ refresh();
2881
+ const baseRevision = await gitOutput(root, ["rev-parse", "HEAD"]);
2882
+ const bootId = nodeBootId();
2883
+ const startedAt = ownProcessStartedAt();
2884
+ const record = {
2885
+ root,
2886
+ leaseId: `lease-${options.clock.now()}-${counter}`,
2887
+ generation: (recordFor(root)?.generation ?? 0) + 1,
2888
+ ...input.ownerSessionId === void 0 ? {} : { ownerSessionId: input.ownerSessionId },
2889
+ ...baseRevision === void 0 ? {} : { baseRevision },
2890
+ pid: process.pid,
2891
+ ...bootId === "" ? {} : { bootId },
2892
+ ...startedAt === void 0 ? {} : { processStartedAt: startedAt },
2893
+ heartbeatAt: options.clock.now()
2894
+ };
2895
+ claim(record);
2896
+ await persistRecord(record);
2897
+ return root;
2898
+ },
2899
+ issuedRoots() {
2900
+ refresh();
2901
+ return [...live.keys()];
2902
+ },
2903
+ restoredRoots() {
2904
+ refresh();
2905
+ return [...restored.values()].map((record) => ({
2906
+ ...record,
2907
+ liveness: liveness.get(record.root) ?? "unverifiable"
2908
+ }));
2909
+ },
2910
+ executionLeases() {
2911
+ refresh();
2912
+ return [...live.values(), ...restored.values()];
2913
+ },
2914
+ baseRevisionOf(root) {
2915
+ refresh();
2916
+ return recordFor(root)?.baseRevision;
2917
+ },
2918
+ artifactStore() {
2919
+ return store;
2920
+ },
2921
+ pruneArtifacts() {
2922
+ return store.prune({
2923
+ keepCount: ARTIFACT_KEEP_COUNT,
2924
+ maxAgeMs: ARTIFACT_MAX_AGE_MS
2925
+ });
2926
+ },
2927
+ sweepOrphanWorktrees() {
2928
+ refresh();
2929
+ const baseDir = options.baseDir();
2930
+ const cutoff = options.clock.now() - ORPHAN_WORKTREE_MAX_AGE_MS;
2931
+ const active = new Set(owned);
2932
+ for (const root of [...live.keys(), ...restored.keys()]) {
2933
+ if (owned.has(root)) continue;
2934
+ let recordModifiedAt = 0;
2935
+ try {
2936
+ recordModifiedAt = statSync(executionRootRecordPath(baseDir, root)).mtimeMs;
2937
+ } catch {
2938
+ recordModifiedAt = 0;
2939
+ }
2940
+ if (recordModifiedAt > cutoff) active.add(root);
2941
+ }
2942
+ return sweepOrphanWorktrees(baseDir, active).then((report) => {
2943
+ refresh();
2944
+ return report;
2945
+ });
2946
+ },
2947
+ async rebindOwner(root, ownerSessionId) {
2948
+ refresh();
2949
+ const record = recordFor(root);
2950
+ if (record === void 0) throw new Error(`execution root is not issued: ${root}`);
2951
+ if (record.ownerSessionId === ownerSessionId) return;
2952
+ const bootId = nodeBootId();
2953
+ const startedAt = ownProcessStartedAt();
2954
+ const rebound = {
2955
+ ...record,
2956
+ ownerSessionId,
2957
+ generation: record.generation + 1,
2958
+ pid: process.pid,
2959
+ ...bootId === "" ? {} : { bootId },
2960
+ ...startedAt === void 0 ? {} : { processStartedAt: startedAt },
2961
+ heartbeatAt: options.clock.now()
2962
+ };
2963
+ claim(rebound);
2964
+ await persistRecord(rebound);
2965
+ },
2966
+ async seal(root) {
2967
+ refresh();
2968
+ const record = recordFor(root);
2969
+ if (record === void 0) return;
2970
+ const baseRevision = record.baseRevision ?? await gitOutput(root, ["rev-parse", "HEAD"]);
2971
+ if (baseRevision === void 0) return;
2972
+ const collected = await collectIsolatedArtifacts(root, baseRevision);
2973
+ return store.persistComplete({
2974
+ leaseId: record.leaseId,
2975
+ generation: record.generation,
2976
+ ...record.ownerSessionId === void 0 ? {} : { ownerSessionId: record.ownerSessionId },
2977
+ baseRevision,
2978
+ files: collected.files,
2979
+ patch: collected.patch
2980
+ });
2981
+ },
2982
+ async release(root) {
2983
+ const commonDir = await gitCommonDir(root);
2984
+ owned.delete(root);
2985
+ live.delete(root);
2986
+ restored.delete(root);
2987
+ liveness.delete(root);
2988
+ await rm(root, {
2989
+ recursive: true,
2990
+ force: true
2991
+ });
2992
+ await rm(executionRootRecordPath(options.baseDir(), root), { force: true });
2993
+ if (commonDir !== void 0 && commonDir !== "") {
2994
+ const repositoryRoot = dirname(commonDir);
2995
+ const pruned = await gitRun(repositoryRoot, ["worktree", "prune"]);
2996
+ if (!pruned.ok) options.report?.(`subagent workspace cleanup: could not prune worktree records at ${repositoryRoot}: ${pruned.error}`);
2997
+ }
2998
+ }
2999
+ };
3000
+ }
3001
+ async function sweepOrphanWorktrees(baseDir, active, options = {}) {
3002
+ const directory = join(baseDir, SUBAGENT_WORKTREES_DIRNAME);
3003
+ const cutoff = (options.now ?? Date.now)() - (options.maxAgeMs ?? 6048e5);
3004
+ let scanned = 0;
3005
+ let removed = 0;
3006
+ let keptRecent = 0;
3007
+ let skippedActive = 0;
3008
+ const repositories = /* @__PURE__ */ new Set();
3009
+ let entries;
3010
+ try {
3011
+ entries = await readdir(directory, { withFileTypes: true });
3012
+ } catch {
3013
+ return {
3014
+ scanned,
3015
+ removed,
3016
+ keptRecent,
3017
+ skippedActive
3018
+ };
3019
+ }
3020
+ for (const entry of entries) {
3021
+ if (!entry.isDirectory()) continue;
3022
+ scanned += 1;
3023
+ const root = join(directory, entry.name);
3024
+ if (active.has(root)) {
3025
+ skippedActive += 1;
3026
+ continue;
3027
+ }
3028
+ let info;
3029
+ try {
3030
+ info = await stat(root);
3031
+ } catch {
3032
+ continue;
3033
+ }
3034
+ if (info.mtimeMs > cutoff) {
3035
+ keptRecent += 1;
3036
+ continue;
3037
+ }
3038
+ let gitFile;
3039
+ try {
3040
+ gitFile = await readFile(join(root, ".git"), "utf8");
3041
+ } catch {
3042
+ continue;
3043
+ }
3044
+ const matched = /^gitdir:\s*(.+)$/m.exec(gitFile);
3045
+ if (matched?.[1] !== void 0) {
3046
+ const gitdir = resolve(root, matched[1].trim());
3047
+ repositories.add(dirname(dirname(dirname(gitdir))));
3048
+ }
3049
+ try {
3050
+ await rm(root, {
3051
+ recursive: true,
3052
+ force: true
3053
+ });
3054
+ removed += 1;
3055
+ } catch {}
3056
+ }
3057
+ for (const repositoryRoot of repositories) await gitRun(repositoryRoot, ["worktree", "prune"]);
3058
+ return {
3059
+ scanned,
3060
+ removed,
3061
+ keptRecent,
3062
+ skippedActive
3063
+ };
3064
+ }
3065
+ async function gitCommonDir(root) {
3066
+ const absolute = await gitOutput(root, [
3067
+ "rev-parse",
3068
+ "--path-format=absolute",
3069
+ "--git-common-dir"
3070
+ ]);
3071
+ if (absolute !== void 0 && absolute !== "") return absolute;
3072
+ const relative = await gitOutput(root, ["rev-parse", "--git-common-dir"]);
3073
+ return relative === void 0 || relative === "" ? void 0 : resolve(root, relative);
3074
+ }
3075
+ async function collectIsolatedArtifacts(root, baseRevision) {
3076
+ const added = await gitOutput(root, ["add", "-A"]);
3077
+ const names = await gitOutput(root, [
3078
+ "diff",
3079
+ "--cached",
3080
+ "--name-only",
3081
+ baseRevision
3082
+ ]);
3083
+ const patch = await gitRawOutput(root, [
3084
+ "diff",
3085
+ "--cached",
3086
+ "--binary",
3087
+ baseRevision
3088
+ ]);
3089
+ if (added === void 0 || names === void 0 || patch === void 0) throw new Error(`could not collect isolated artifacts from ${root}: git diff against ${baseRevision} failed`);
3090
+ return {
3091
+ root,
3092
+ files: names === "" ? [] : names.split("\n"),
3093
+ patch
3094
+ };
3095
+ }
3096
+
3097
+ //#endregion
3098
+ export { EXECUTION_ROOT_RECORDS_DIRNAME, ORPHAN_WORKTREE_MAX_AGE_MS, PERSONA_CONTRIBUTION_KEY, SUBAGENT_ARTIFACTS_DIRNAME, SUBAGENT_WORKTREES_DIRNAME, Subagent, SubagentControlImpl, SubagentDelegationError, collectIsolatedArtifacts, compilePersona, createArtifactStore, createInProcessProvider, createManifestPersonaResolver, createSubagentTool, createSubagentWorkspaceRoots, executionRootLiveness, personaDeclarationOf, personaDeclarationOfManifest, personaRefsOfManifest, personasOfManifest, resolvePersona, sweepOrphanWorktrees };