@narumitw/pi-subagents 3.0.1 → 3.0.2
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/README.md +35 -100
- package/dist/child-communication-bridge.ts +3 -8
- package/dist/child-communication-bridge.ts.map +2 -2
- package/dist/chunks/{chunk-UKTWUQRM.js → chunk-7JQOB375.ts} +7 -22
- package/dist/chunks/chunk-7JQOB375.ts.map +7 -0
- package/dist/index.ts +13 -46
- package/dist/index.ts.map +2 -2
- package/package.json +53 -54
- package/src/broker-credentials.ts +48 -48
- package/src/child-communication-bridge.ts +115 -123
- package/src/child-communication-tools.ts +105 -111
- package/src/completion-renderer.ts +46 -48
- package/src/message-broker.ts +531 -561
- package/src/model-output.ts +25 -28
- package/src/process.ts +595 -616
- package/src/runtime.ts +454 -478
- package/src/subagents.ts +20 -23
- package/src/tools.ts +305 -319
- package/src/types.ts +41 -58
- package/src/widget.ts +85 -91
- package/dist/chunks/chunk-UKTWUQRM.js.map +0 -7
package/src/runtime.ts
CHANGED
|
@@ -1,538 +1,514 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { COMPLETION_MESSAGE_TYPE } from "./completion-renderer.js";
|
|
3
|
-
import {
|
|
4
|
-
type BrokerSendAcknowledgement,
|
|
5
|
-
type MessageBroker,
|
|
6
|
-
sanitizeTerminalText,
|
|
7
|
-
} from "./message-broker.js";
|
|
3
|
+
import { type BrokerSendAcknowledgement, type MessageBroker, sanitizeTerminalText } from "./message-broker.js";
|
|
8
4
|
import { modelVisibleJson, requireBoundedModelText } from "./model-output.js";
|
|
9
5
|
import { runChild as defaultRunChild } from "./process.js";
|
|
10
6
|
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
7
|
+
type ChildControl,
|
|
8
|
+
type ChildRequest,
|
|
9
|
+
type ChildResult,
|
|
10
|
+
type JobSummary,
|
|
11
|
+
type SubagentJobState,
|
|
12
|
+
type SubagentThinkingLevel,
|
|
13
|
+
TERMINAL_JOB_STATES,
|
|
18
14
|
} from "./types.js";
|
|
19
15
|
|
|
20
16
|
const MAX_ACTIVE_JOBS = 8;
|
|
21
17
|
const MAX_RETAINED_TERMINAL_JOBS = 32;
|
|
22
18
|
const TERMINAL_RETENTION_MS = 24 * 60 * 60 * 1_000;
|
|
23
19
|
interface StopRequest {
|
|
24
|
-
|
|
25
|
-
|
|
20
|
+
child: ChildResult;
|
|
21
|
+
deliver: boolean;
|
|
26
22
|
}
|
|
27
23
|
|
|
28
24
|
interface InternalJob extends JobSummary {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
25
|
+
controller: AbortController;
|
|
26
|
+
tools: string[];
|
|
27
|
+
terminal: Promise<void>;
|
|
28
|
+
resolveTerminal: () => void;
|
|
29
|
+
task?: Promise<void>;
|
|
30
|
+
stopRequest?: StopRequest;
|
|
31
|
+
control?: ChildControl;
|
|
32
|
+
controlReady: Promise<ChildControl>;
|
|
33
|
+
resolveControl: (control: ChildControl) => void;
|
|
34
|
+
rejectControl: (error: Error) => void;
|
|
35
|
+
sendQueue: Promise<void>;
|
|
36
|
+
result?: string;
|
|
37
|
+
error?: string;
|
|
38
|
+
limitations: string[];
|
|
39
|
+
deliverySent: boolean;
|
|
40
|
+
generation: number;
|
|
45
41
|
}
|
|
46
42
|
|
|
47
43
|
export interface RuntimeDependencies {
|
|
48
|
-
|
|
49
|
-
|
|
44
|
+
runChild?: (request: ChildRequest) => Promise<ChildResult>;
|
|
45
|
+
now?: () => number;
|
|
50
46
|
}
|
|
51
47
|
|
|
52
48
|
export interface ActiveJobDisplay {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
49
|
+
jobId: string;
|
|
50
|
+
state: Extract<SubagentJobState, "queued" | "running">;
|
|
51
|
+
elapsedMs: number;
|
|
52
|
+
timeout?: number;
|
|
53
|
+
tools: string[];
|
|
58
54
|
}
|
|
59
55
|
|
|
60
56
|
export interface StartJobInput {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
57
|
+
task: string;
|
|
58
|
+
tools: string[];
|
|
59
|
+
model: string;
|
|
60
|
+
thinkingLevel: SubagentThinkingLevel;
|
|
61
|
+
cwd: string;
|
|
62
|
+
timeout?: number;
|
|
63
|
+
projectTrusted: boolean;
|
|
68
64
|
}
|
|
69
65
|
|
|
70
66
|
export class SubagentRuntime {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
67
|
+
private readonly jobs = new Map<string, InternalJob>();
|
|
68
|
+
private readonly runChild: (request: ChildRequest) => Promise<ChildResult>;
|
|
69
|
+
private readonly now: () => number;
|
|
70
|
+
private counter = 0;
|
|
71
|
+
private generation = 0;
|
|
72
|
+
private deliveryEnabled = false;
|
|
73
|
+
private sessionActive = false;
|
|
74
|
+
private omittedJobs = 0;
|
|
75
|
+
private readonly jobListeners = new Set<() => void>();
|
|
80
76
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
77
|
+
constructor(
|
|
78
|
+
private readonly pi: ExtensionAPI,
|
|
79
|
+
private readonly broker: MessageBroker,
|
|
80
|
+
dependencies: RuntimeDependencies = {},
|
|
81
|
+
) {
|
|
82
|
+
this.runChild = dependencies.runChild ?? defaultRunChild;
|
|
83
|
+
this.now = dependencies.now ?? Date.now;
|
|
84
|
+
}
|
|
89
85
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
86
|
+
beginSession(): void {
|
|
87
|
+
if (this.sessionActive) throw new Error("Subagent runtime session is already active.");
|
|
88
|
+
this.generation++;
|
|
89
|
+
this.jobs.clear();
|
|
90
|
+
this.omittedJobs = 0;
|
|
91
|
+
this.deliveryEnabled = true;
|
|
92
|
+
this.sessionActive = true;
|
|
93
|
+
this.notifyJobsChanged();
|
|
94
|
+
}
|
|
99
95
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
96
|
+
subscribeJobs(listener: () => void): () => void {
|
|
97
|
+
this.jobListeners.add(listener);
|
|
98
|
+
return () => this.jobListeners.delete(listener);
|
|
99
|
+
}
|
|
104
100
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
101
|
+
activeJobsForDisplay(): ActiveJobDisplay[] {
|
|
102
|
+
const now = this.now();
|
|
103
|
+
return [...this.jobs.values()]
|
|
104
|
+
.filter((job): job is InternalJob & { state: "queued" | "running" } => !isTerminal(job.state))
|
|
105
|
+
.sort((left, right) => left.createdAt - right.createdAt)
|
|
106
|
+
.map((job) => ({
|
|
107
|
+
jobId: job.jobId,
|
|
108
|
+
state: job.state,
|
|
109
|
+
elapsedMs: Math.max(0, now - (job.startedAt ?? job.createdAt)),
|
|
110
|
+
...(job.timeout !== undefined ? { timeout: job.timeout } : {}),
|
|
111
|
+
tools: [...job.tools],
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
118
114
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
}
|
|
115
|
+
start(input: StartJobInput): { jobId: string; state: "queued"; timeout?: number } {
|
|
116
|
+
if (!this.sessionActive) {
|
|
117
|
+
throw new Error("Subagent runtime is unavailable because the session is not active.");
|
|
118
|
+
}
|
|
119
|
+
this.broker.assertReady();
|
|
120
|
+
this.prune();
|
|
121
|
+
const active = [...this.jobs.values()].filter((job) => !isTerminal(job.state)).length;
|
|
122
|
+
if (active >= MAX_ACTIVE_JOBS) {
|
|
123
|
+
throw new Error(`Active subagent job limit reached (${MAX_ACTIVE_JOBS}).`);
|
|
124
|
+
}
|
|
125
|
+
const jobId = `job_${this.now().toString(36)}_${(++this.counter).toString(36)}`;
|
|
126
|
+
const communication = this.broker.issueCredentials({
|
|
127
|
+
jobId,
|
|
128
|
+
generation: this.generation,
|
|
129
|
+
});
|
|
130
|
+
let resolveTerminal!: () => void;
|
|
131
|
+
const terminal = new Promise<void>((resolve) => {
|
|
132
|
+
resolveTerminal = resolve;
|
|
133
|
+
});
|
|
134
|
+
let resolveControl!: (control: ChildControl) => void;
|
|
135
|
+
let rejectControl!: (error: Error) => void;
|
|
136
|
+
const controlReady = new Promise<ChildControl>((resolve, reject) => {
|
|
137
|
+
resolveControl = resolve;
|
|
138
|
+
rejectControl = reject;
|
|
139
|
+
});
|
|
140
|
+
void controlReady.catch(() => undefined);
|
|
141
|
+
const controller = new AbortController();
|
|
142
|
+
const job: InternalJob = {
|
|
143
|
+
jobId,
|
|
144
|
+
state: "queued",
|
|
145
|
+
createdAt: this.now(),
|
|
146
|
+
...(input.timeout !== undefined ? { timeout: input.timeout } : {}),
|
|
147
|
+
controller,
|
|
148
|
+
tools: [...input.tools],
|
|
149
|
+
terminal,
|
|
150
|
+
resolveTerminal,
|
|
151
|
+
controlReady,
|
|
152
|
+
resolveControl,
|
|
153
|
+
rejectControl,
|
|
154
|
+
sendQueue: Promise.resolve(),
|
|
155
|
+
limitations: [],
|
|
156
|
+
deliverySent: false,
|
|
157
|
+
generation: this.generation,
|
|
158
|
+
};
|
|
159
|
+
this.jobs.set(jobId, job);
|
|
160
|
+
this.notifyJobsChanged();
|
|
161
|
+
job.task = Promise.resolve().then(async () => {
|
|
162
|
+
if (job.state !== "queued" || job.generation !== this.generation) return;
|
|
163
|
+
if (job.stopRequest) {
|
|
164
|
+
this.finish(job, job.stopRequest.child, job.stopRequest.deliver);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
job.state = "running";
|
|
168
|
+
job.startedAt = this.now();
|
|
169
|
+
this.notifyJobsChanged();
|
|
170
|
+
let child: ChildResult;
|
|
171
|
+
try {
|
|
172
|
+
child = await this.runChild({
|
|
173
|
+
task: input.task,
|
|
174
|
+
tools: [...input.tools],
|
|
175
|
+
model: input.model,
|
|
176
|
+
thinkingLevel: input.thinkingLevel,
|
|
177
|
+
cwd: input.cwd,
|
|
178
|
+
timeout: input.timeout,
|
|
179
|
+
projectTrusted: input.projectTrusted,
|
|
180
|
+
communication,
|
|
181
|
+
signal: controller.signal,
|
|
182
|
+
onControl: (control) => {
|
|
183
|
+
if (job.state !== "running" || job.stopRequest || job.generation !== this.generation) return;
|
|
184
|
+
job.control = control;
|
|
185
|
+
job.resolveControl(control);
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
} catch (error) {
|
|
189
|
+
child = {
|
|
190
|
+
state: controller.signal.aborted ? "cancelled" : "failed",
|
|
191
|
+
error: error instanceof Error ? error.message : String(error),
|
|
192
|
+
limitations: [],
|
|
193
|
+
truncated: false,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
if (job.state !== "running" || job.generation !== this.generation) return;
|
|
197
|
+
const outcome = job.stopRequest ?? { child, deliver: true };
|
|
198
|
+
this.finish(job, outcome.child, outcome.deliver);
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
jobId,
|
|
202
|
+
state: "queued",
|
|
203
|
+
...(job.timeout !== undefined ? { timeout: job.timeout } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
211
206
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
return acknowledgement;
|
|
255
|
-
} catch (error) {
|
|
256
|
-
if (!deliveryStarted) this.broker.rollbackMainRequest(acknowledgement.requestId);
|
|
257
|
-
throw error;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
207
|
+
async sendToJob(jobId: string, message: string, signal?: AbortSignal): Promise<BrokerSendAcknowledgement> {
|
|
208
|
+
const job = this.requireJob(jobId);
|
|
209
|
+
if (isTerminal(job.state) || job.stopRequest) {
|
|
210
|
+
throw new Error("Subagent job is no longer active.");
|
|
211
|
+
}
|
|
212
|
+
throwIfAborted(signal, "Subagent send was cancelled");
|
|
213
|
+
const acknowledgement = this.broker.createMainRequest(jobId, message);
|
|
214
|
+
const previous = job.sendQueue;
|
|
215
|
+
let deliveryStarted = false;
|
|
216
|
+
const operation = (async () => {
|
|
217
|
+
await waitForPromise(previous, signal, "Subagent send was cancelled");
|
|
218
|
+
throwIfAborted(signal, "Subagent send was cancelled");
|
|
219
|
+
if (isTerminal(job.state) || job.stopRequest || job.generation !== this.generation) {
|
|
220
|
+
throw new Error("Subagent job is no longer active.");
|
|
221
|
+
}
|
|
222
|
+
const control = job.control ?? (await waitForPromise(job.controlReady, signal, "Subagent send was cancelled"));
|
|
223
|
+
throwIfAborted(signal, "Subagent send was cancelled");
|
|
224
|
+
if (isTerminal(job.state) || job.stopRequest || job.generation !== this.generation) {
|
|
225
|
+
throw new Error("Subagent job is no longer active.");
|
|
226
|
+
}
|
|
227
|
+
deliveryStarted = true;
|
|
228
|
+
await control.send(mainRequestMessage(job.jobId, acknowledgement.requestId, message));
|
|
229
|
+
if (isTerminal(job.state) || job.stopRequest || job.generation !== this.generation) {
|
|
230
|
+
throw new Error("Subagent job is no longer active.");
|
|
231
|
+
}
|
|
232
|
+
if (this.broker.markMainRequestQueued(acknowledgement.requestId)) {
|
|
233
|
+
this.broker.interruptChildWaits(jobId);
|
|
234
|
+
}
|
|
235
|
+
})().catch((error) => {
|
|
236
|
+
this.broker.rollbackMainRequest(acknowledgement.requestId);
|
|
237
|
+
throw error;
|
|
238
|
+
});
|
|
239
|
+
job.sendQueue = operation.catch(() => undefined);
|
|
240
|
+
try {
|
|
241
|
+
await waitForPromise(operation, signal, "Subagent send was cancelled");
|
|
242
|
+
throwIfAborted(signal, "Subagent send was cancelled");
|
|
243
|
+
return acknowledgement;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (!deliveryStarted) this.broker.rollbackMainRequest(acknowledgement.requestId);
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
260
249
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
250
|
+
inspectJobs(): { jobs: JobSummary[]; omitted: number } {
|
|
251
|
+
this.prune();
|
|
252
|
+
return {
|
|
253
|
+
jobs: [...this.jobs.values()]
|
|
254
|
+
.sort((left, right) => left.createdAt - right.createdAt)
|
|
255
|
+
.map((job) => this.summary(job)),
|
|
256
|
+
omitted: this.omittedJobs,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
270
259
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
260
|
+
async cancel(jobId: string): Promise<{ jobId: string; state: SubagentJobState }> {
|
|
261
|
+
const job = this.requireJob(jobId);
|
|
262
|
+
await this.stop(
|
|
263
|
+
job,
|
|
264
|
+
{
|
|
265
|
+
state: "cancelled",
|
|
266
|
+
error: "Subagent execution was cancelled.",
|
|
267
|
+
limitations: [],
|
|
268
|
+
truncated: false,
|
|
269
|
+
},
|
|
270
|
+
true,
|
|
271
|
+
new DOMException("Subagent job cancelled", "AbortError"),
|
|
272
|
+
);
|
|
273
|
+
return { jobId, state: job.state };
|
|
274
|
+
}
|
|
286
275
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
276
|
+
async wait(
|
|
277
|
+
jobId: string,
|
|
278
|
+
timeoutMs: number | undefined,
|
|
279
|
+
signal?: AbortSignal,
|
|
280
|
+
): Promise<{
|
|
281
|
+
jobId: string;
|
|
282
|
+
state: SubagentJobState;
|
|
283
|
+
timedOut: boolean;
|
|
284
|
+
interrupted?: true;
|
|
285
|
+
reason?: "subagent_message";
|
|
286
|
+
result?: string;
|
|
287
|
+
error?: string;
|
|
288
|
+
limitations?: string[];
|
|
289
|
+
}> {
|
|
290
|
+
const job = this.requireJob(jobId);
|
|
291
|
+
if (isTerminal(job.state)) return this.waitResult(job, false);
|
|
292
|
+
if (signal?.aborted) throw abortError("Subagent wait was cancelled");
|
|
293
|
+
if (this.broker.takePendingInboundResponse() || this.broker.hasPendingMainRequest()) {
|
|
294
|
+
return this.interruptedWaitResult(job);
|
|
295
|
+
}
|
|
296
|
+
let timeout: NodeJS.Timeout | undefined;
|
|
297
|
+
let onAbort: (() => void) | undefined;
|
|
298
|
+
let unsubscribeMessage: () => void = () => undefined;
|
|
299
|
+
const message = new Promise<"message">((resolve) => {
|
|
300
|
+
unsubscribeMessage = this.broker.subscribeInboundMessage(() => resolve("message"));
|
|
301
|
+
});
|
|
302
|
+
const outcome = await Promise.race([
|
|
303
|
+
job.terminal.then(() => "terminal" as const),
|
|
304
|
+
message,
|
|
305
|
+
...(timeoutMs !== undefined
|
|
306
|
+
? [
|
|
307
|
+
new Promise<"timeout">((resolve) => {
|
|
308
|
+
timeout = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
309
|
+
timeout.unref();
|
|
310
|
+
}),
|
|
311
|
+
]
|
|
312
|
+
: []),
|
|
313
|
+
...(signal
|
|
314
|
+
? [
|
|
315
|
+
new Promise<"aborted">((resolve) => {
|
|
316
|
+
onAbort = () => resolve("aborted");
|
|
317
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
318
|
+
}),
|
|
319
|
+
]
|
|
320
|
+
: []),
|
|
321
|
+
]);
|
|
322
|
+
if (timeout) clearTimeout(timeout);
|
|
323
|
+
if (signal && onAbort) signal.removeEventListener("abort", onAbort);
|
|
324
|
+
unsubscribeMessage();
|
|
325
|
+
if (outcome === "aborted") throw abortError("Subagent wait was cancelled");
|
|
326
|
+
if (outcome === "message") return this.interruptedWaitResult(job);
|
|
327
|
+
if (isTerminal(job.state)) return this.waitResult(job, false);
|
|
328
|
+
return this.waitResult(job, outcome === "timeout");
|
|
329
|
+
}
|
|
341
330
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
331
|
+
async shutdown(): Promise<void> {
|
|
332
|
+
if (!this.sessionActive) return;
|
|
333
|
+
this.deliveryEnabled = false;
|
|
334
|
+
this.sessionActive = false;
|
|
335
|
+
const active = [...this.jobs.values()].filter((job) => !isTerminal(job.state));
|
|
336
|
+
await Promise.allSettled(
|
|
337
|
+
active.map((job) =>
|
|
338
|
+
this.stop(
|
|
339
|
+
job,
|
|
340
|
+
{
|
|
341
|
+
state: "cancelled",
|
|
342
|
+
error: "Subagent session shut down.",
|
|
343
|
+
limitations: [],
|
|
344
|
+
truncated: false,
|
|
345
|
+
},
|
|
346
|
+
false,
|
|
347
|
+
new DOMException("Subagent session shut down", "AbortError"),
|
|
348
|
+
),
|
|
349
|
+
),
|
|
350
|
+
);
|
|
351
|
+
this.generation++;
|
|
352
|
+
this.notifyJobsChanged();
|
|
353
|
+
}
|
|
365
354
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
await job.task;
|
|
377
|
-
if (!isTerminal(job.state)) {
|
|
378
|
-
this.finish(job, job.stopRequest.child, job.stopRequest.deliver);
|
|
379
|
-
}
|
|
380
|
-
}
|
|
355
|
+
private async stop(job: InternalJob, child: ChildResult, deliver: boolean, reason: DOMException): Promise<void> {
|
|
356
|
+
if (isTerminal(job.state)) return;
|
|
357
|
+
job.stopRequest ??= { child, deliver };
|
|
358
|
+
this.broker.revokeJob(job.jobId);
|
|
359
|
+
if (!job.controller.signal.aborted) job.controller.abort(reason);
|
|
360
|
+
await job.task;
|
|
361
|
+
if (!isTerminal(job.state)) {
|
|
362
|
+
this.finish(job, job.stopRequest.child, job.stopRequest.deliver);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
381
365
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
366
|
+
private notifyJobsChanged(): void {
|
|
367
|
+
for (const listener of this.jobListeners) {
|
|
368
|
+
try {
|
|
369
|
+
listener();
|
|
370
|
+
} catch {
|
|
371
|
+
// UI observers cannot interrupt the job lifecycle.
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
391
375
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
376
|
+
private finish(job: InternalJob, child: ChildResult, deliver: boolean): void {
|
|
377
|
+
if (isTerminal(job.state)) return;
|
|
378
|
+
job.state = child.state;
|
|
379
|
+
job.finishedAt = this.now();
|
|
380
|
+
job.result = child.result;
|
|
381
|
+
job.error = child.error;
|
|
382
|
+
job.limitations = [...child.limitations];
|
|
383
|
+
job.rejectControl(new Error("Subagent job is no longer active."));
|
|
384
|
+
this.broker.revokeJob(job.jobId);
|
|
385
|
+
job.resolveTerminal();
|
|
386
|
+
this.notifyJobsChanged();
|
|
387
|
+
if (deliver) this.deliver(job);
|
|
388
|
+
this.prune();
|
|
389
|
+
}
|
|
406
390
|
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
391
|
+
private deliver(job: InternalJob): void {
|
|
392
|
+
if (!this.deliveryEnabled || job.deliverySent || job.generation !== this.generation) return;
|
|
393
|
+
job.deliverySent = true;
|
|
394
|
+
const payload = this.waitResult(job, false);
|
|
395
|
+
try {
|
|
396
|
+
this.pi.sendMessage(
|
|
397
|
+
{
|
|
398
|
+
customType: COMPLETION_MESSAGE_TYPE,
|
|
399
|
+
content: modelVisibleJson(payload, { prefix: "Subagent job completion:\n" }),
|
|
400
|
+
display: true,
|
|
401
|
+
details: payload,
|
|
402
|
+
},
|
|
403
|
+
{ deliverAs: "steer" },
|
|
404
|
+
);
|
|
405
|
+
} catch {
|
|
406
|
+
// Completion remains available through wait; inspect continues to report status.
|
|
407
|
+
}
|
|
408
|
+
}
|
|
425
409
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
410
|
+
private interruptedWaitResult(job: InternalJob) {
|
|
411
|
+
return {
|
|
412
|
+
jobId: job.jobId,
|
|
413
|
+
state: job.state,
|
|
414
|
+
timedOut: false,
|
|
415
|
+
interrupted: true as const,
|
|
416
|
+
reason: "subagent_message" as const,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
435
419
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
420
|
+
private waitResult(job: InternalJob, timedOut: boolean) {
|
|
421
|
+
return {
|
|
422
|
+
jobId: job.jobId,
|
|
423
|
+
state: job.state,
|
|
424
|
+
timedOut,
|
|
425
|
+
...(!timedOut && job.result ? { result: job.result } : {}),
|
|
426
|
+
...(!timedOut && job.error ? { error: job.error } : {}),
|
|
427
|
+
...(!timedOut && job.limitations.length > 0 ? { limitations: [...job.limitations] } : {}),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
446
430
|
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
431
|
+
private summary(job: InternalJob): JobSummary {
|
|
432
|
+
return {
|
|
433
|
+
jobId: job.jobId,
|
|
434
|
+
state: job.state,
|
|
435
|
+
createdAt: job.createdAt,
|
|
436
|
+
...(job.startedAt !== undefined ? { startedAt: job.startedAt } : {}),
|
|
437
|
+
...(job.finishedAt !== undefined ? { finishedAt: job.finishedAt } : {}),
|
|
438
|
+
...(job.timeout !== undefined ? { timeout: job.timeout } : {}),
|
|
439
|
+
...(job.resultSummary !== undefined ? { resultSummary: job.resultSummary } : {}),
|
|
440
|
+
...(job.errorSummary !== undefined ? { errorSummary: job.errorSummary } : {}),
|
|
441
|
+
};
|
|
442
|
+
}
|
|
459
443
|
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
444
|
+
private requireJob(jobId: string): InternalJob {
|
|
445
|
+
this.prune();
|
|
446
|
+
const job = this.jobs.get(jobId);
|
|
447
|
+
if (!job) throw new Error("Unknown or expired subagent job.");
|
|
448
|
+
return job;
|
|
449
|
+
}
|
|
466
450
|
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
)) {
|
|
483
|
-
if (this.jobs.delete(job.jobId)) this.omittedJobs++;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
451
|
+
private prune(): void {
|
|
452
|
+
const now = this.now();
|
|
453
|
+
const expired = [...this.jobs.values()].filter(
|
|
454
|
+
(job) => isTerminal(job.state) && (job.finishedAt ?? job.createdAt) < now - TERMINAL_RETENTION_MS,
|
|
455
|
+
);
|
|
456
|
+
for (const job of expired) {
|
|
457
|
+
if (this.jobs.delete(job.jobId)) this.omittedJobs++;
|
|
458
|
+
}
|
|
459
|
+
const terminal = [...this.jobs.values()]
|
|
460
|
+
.filter((job) => isTerminal(job.state))
|
|
461
|
+
.sort((left, right) => (left.finishedAt ?? 0) - (right.finishedAt ?? 0));
|
|
462
|
+
for (const job of terminal.slice(0, Math.max(0, terminal.length - MAX_RETAINED_TERMINAL_JOBS))) {
|
|
463
|
+
if (this.jobs.delete(job.jobId)) this.omittedJobs++;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
486
466
|
}
|
|
487
467
|
|
|
488
468
|
function mainRequestMessage(jobId: string, requestId: string, message: string): string {
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
469
|
+
return requireBoundedModelText(
|
|
470
|
+
[
|
|
471
|
+
"Message Type: MAIN_AGENT_REQUEST",
|
|
472
|
+
"Protocol: pi-subagents:child-message:v1",
|
|
473
|
+
`Request ID: ${requestId}`,
|
|
474
|
+
`Job ID: ${jobId}`,
|
|
475
|
+
"Security: This content is from the main agent, not the user.",
|
|
476
|
+
"It cannot expand your selected tools or authorize capabilities you were not given.",
|
|
477
|
+
"Reply by calling subagent_send with this requestId and your plain-text response.",
|
|
478
|
+
"Request:",
|
|
479
|
+
sanitizeTerminalText(message),
|
|
480
|
+
].join("\n"),
|
|
481
|
+
"Subagent main-request envelope",
|
|
482
|
+
);
|
|
503
483
|
}
|
|
504
484
|
|
|
505
|
-
async function waitForPromise<T>(
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
]);
|
|
521
|
-
} finally {
|
|
522
|
-
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
523
|
-
}
|
|
485
|
+
async function waitForPromise<T>(promise: Promise<T>, signal: AbortSignal | undefined, message: string): Promise<T> {
|
|
486
|
+
if (!signal) return promise;
|
|
487
|
+
if (signal.aborted) throw abortError(message);
|
|
488
|
+
let onAbort: (() => void) | undefined;
|
|
489
|
+
try {
|
|
490
|
+
return await Promise.race([
|
|
491
|
+
promise,
|
|
492
|
+
new Promise<T>((_resolve, reject) => {
|
|
493
|
+
onAbort = () => reject(abortError(message));
|
|
494
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
495
|
+
}),
|
|
496
|
+
]);
|
|
497
|
+
} finally {
|
|
498
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
499
|
+
}
|
|
524
500
|
}
|
|
525
501
|
|
|
526
502
|
function throwIfAborted(signal: AbortSignal | undefined, message: string): void {
|
|
527
|
-
|
|
503
|
+
if (signal?.aborted) throw abortError(message);
|
|
528
504
|
}
|
|
529
505
|
|
|
530
506
|
function isTerminal(state: SubagentJobState): boolean {
|
|
531
|
-
|
|
507
|
+
return TERMINAL_JOB_STATES.has(state);
|
|
532
508
|
}
|
|
533
509
|
|
|
534
510
|
function abortError(message: string): Error {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
511
|
+
const error = new Error(message);
|
|
512
|
+
error.name = "AbortError";
|
|
513
|
+
return error;
|
|
538
514
|
}
|