@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/process.ts
CHANGED
|
@@ -4,11 +4,7 @@ import * as path from "node:path";
|
|
|
4
4
|
import { StringDecoder } from "node:string_decoder";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { getPackageDir } from "@earendil-works/pi-coding-agent";
|
|
7
|
-
import {
|
|
8
|
-
BROKER_CREDENTIAL_FD,
|
|
9
|
-
brokerCredentialEnvironment,
|
|
10
|
-
serializeBrokerCredentials,
|
|
11
|
-
} from "./broker-credentials.js";
|
|
7
|
+
import { BROKER_CREDENTIAL_FD, brokerCredentialEnvironment, serializeBrokerCredentials } from "./broker-credentials.js";
|
|
12
8
|
import { CHILD_COMMUNICATION_TOOL_NAMES } from "./child-communication-tools.js";
|
|
13
9
|
import type { ChildControl, ChildRequest, ChildResult } from "./types.js";
|
|
14
10
|
|
|
@@ -22,667 +18,650 @@ const RPC_RESPONSE_TIMEOUT_MS = 30_000;
|
|
|
22
18
|
const KILL_GRACE_MS = 1_000;
|
|
23
19
|
|
|
24
20
|
interface ProcessSettlement {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
21
|
+
code: number;
|
|
22
|
+
cancelled: boolean;
|
|
23
|
+
timedOut: boolean;
|
|
24
|
+
completed: boolean;
|
|
25
|
+
launchError?: string;
|
|
30
26
|
}
|
|
31
27
|
|
|
32
28
|
interface AssistantEvent {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
29
|
+
type?: string;
|
|
30
|
+
id?: string;
|
|
31
|
+
success?: boolean;
|
|
32
|
+
error?: string;
|
|
33
|
+
message?: {
|
|
34
|
+
role?: string;
|
|
35
|
+
content?: Array<{ type?: string; text?: string }>;
|
|
36
|
+
stopReason?: string;
|
|
37
|
+
errorMessage?: string;
|
|
38
|
+
};
|
|
43
39
|
}
|
|
44
40
|
|
|
45
41
|
interface PendingRpcCommand {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
42
|
+
command: string;
|
|
43
|
+
resolve: () => void;
|
|
44
|
+
reject: (error: Error) => void;
|
|
45
|
+
timer: NodeJS.Timeout;
|
|
46
|
+
onAccepted?: () => void;
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
onAbort?: () => void;
|
|
53
49
|
}
|
|
54
50
|
|
|
55
51
|
export function resolveTimeoutMs(timeout: number | undefined): number | undefined {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
52
|
+
if (timeout === undefined) return undefined;
|
|
53
|
+
if (!Number.isFinite(timeout) || timeout <= 0) {
|
|
54
|
+
throw new Error("Invalid timeout: must be a finite number of seconds");
|
|
55
|
+
}
|
|
56
|
+
const timeoutMs = timeout * 1000;
|
|
57
|
+
if (timeoutMs > MAX_TIMEOUT_MS) {
|
|
58
|
+
throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);
|
|
59
|
+
}
|
|
60
|
+
return timeoutMs;
|
|
65
61
|
}
|
|
66
62
|
|
|
67
63
|
export async function runChild(request: ChildRequest): Promise<ChildResult> {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
64
|
+
if (request.signal.aborted) return cancelledResult();
|
|
65
|
+
try {
|
|
66
|
+
const invocation = resolvePiInvocation(buildPiArgs(request));
|
|
67
|
+
return await executeProcess(invocation, request);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (request.signal.aborted) return cancelledResult();
|
|
70
|
+
return {
|
|
71
|
+
state: "failed",
|
|
72
|
+
error: truncateText(error instanceof Error ? error.message : String(error), MAX_ERROR_BYTES).text,
|
|
73
|
+
limitations: [],
|
|
74
|
+
truncated: false,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
82
77
|
}
|
|
83
78
|
|
|
84
79
|
export function buildPiArgs(request: ChildRequest): string[] {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
80
|
+
const args = [
|
|
81
|
+
"--mode",
|
|
82
|
+
"rpc",
|
|
83
|
+
"--no-session",
|
|
84
|
+
"--no-extensions",
|
|
85
|
+
"--no-skills",
|
|
86
|
+
"--no-prompt-templates",
|
|
87
|
+
"-e",
|
|
88
|
+
childCommunicationBridgePath(),
|
|
89
|
+
"--model",
|
|
90
|
+
request.model,
|
|
91
|
+
"--thinking",
|
|
92
|
+
request.thinkingLevel,
|
|
93
|
+
request.projectTrusted ? "--approve" : "--no-approve",
|
|
94
|
+
];
|
|
95
|
+
const tools = [...new Set([...request.tools, ...CHILD_COMMUNICATION_TOOL_NAMES])];
|
|
96
|
+
args.push("--tools", tools.join(","));
|
|
97
|
+
return args;
|
|
103
98
|
}
|
|
104
99
|
|
|
105
100
|
export function childCommunicationBridgePath(): string {
|
|
106
|
-
|
|
101
|
+
return fileURLToPath(new URL("./child-communication-bridge.ts", import.meta.url));
|
|
107
102
|
}
|
|
108
103
|
|
|
109
104
|
async function executeProcess(
|
|
110
|
-
|
|
111
|
-
|
|
105
|
+
invocation: { command: string; args: string[] },
|
|
106
|
+
request: ChildRequest,
|
|
112
107
|
): Promise<ChildResult> {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
-
|
|
211
|
-
|
|
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
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
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
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
result: output,
|
|
476
|
-
error: failure,
|
|
477
|
-
limitations,
|
|
478
|
-
truncated,
|
|
479
|
-
};
|
|
480
|
-
}
|
|
481
|
-
return {
|
|
482
|
-
state: "failed",
|
|
483
|
-
error: failure,
|
|
484
|
-
limitations,
|
|
485
|
-
truncated,
|
|
486
|
-
};
|
|
108
|
+
const timeoutMs = resolveTimeoutMs(request.timeout);
|
|
109
|
+
let latestOutput = "";
|
|
110
|
+
let terminalOutput: string | undefined;
|
|
111
|
+
let terminalStopReason: "stop" | "length" | undefined;
|
|
112
|
+
let errorMessage = "";
|
|
113
|
+
let assistantFailed = false;
|
|
114
|
+
let stderr = "";
|
|
115
|
+
let truncated = false;
|
|
116
|
+
let malformedEvents = 0;
|
|
117
|
+
let rpcCounter = 0;
|
|
118
|
+
const pendingCommands = new Map<string, PendingRpcCommand>();
|
|
119
|
+
let rpcInputError: Error | undefined;
|
|
120
|
+
let sendCommand: (
|
|
121
|
+
command: { type: "prompt" | "steer"; message: string },
|
|
122
|
+
onAccepted?: () => void,
|
|
123
|
+
signal?: AbortSignal,
|
|
124
|
+
) => Promise<void> = () => Promise.reject(new Error("Subagent RPC process is unavailable."));
|
|
125
|
+
let onAgentSettled: () => void = () => undefined;
|
|
126
|
+
|
|
127
|
+
const takePendingCommand = (id: string): PendingRpcCommand | undefined => {
|
|
128
|
+
const pending = pendingCommands.get(id);
|
|
129
|
+
if (!pending) return undefined;
|
|
130
|
+
pendingCommands.delete(id);
|
|
131
|
+
clearTimeout(pending.timer);
|
|
132
|
+
if (pending.signal && pending.onAbort) {
|
|
133
|
+
pending.signal.removeEventListener("abort", pending.onAbort);
|
|
134
|
+
}
|
|
135
|
+
return pending;
|
|
136
|
+
};
|
|
137
|
+
const rejectPendingCommand = (id: string, error: Error) => {
|
|
138
|
+
takePendingCommand(id)?.reject(error);
|
|
139
|
+
};
|
|
140
|
+
const rejectPendingCommands = (error: Error) => {
|
|
141
|
+
for (const id of [...pendingCommands.keys()]) rejectPendingCommand(id, error);
|
|
142
|
+
};
|
|
143
|
+
const resolvePendingCommand = (id: string) => {
|
|
144
|
+
const pending = takePendingCommand(id);
|
|
145
|
+
if (!pending) return;
|
|
146
|
+
try {
|
|
147
|
+
pending.onAccepted?.();
|
|
148
|
+
pending.resolve();
|
|
149
|
+
} catch (error) {
|
|
150
|
+
pending.reject(error instanceof Error ? error : new Error(String(error)));
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
const failRpcInput = (error: Error) => {
|
|
154
|
+
rpcInputError ??= error;
|
|
155
|
+
rejectPendingCommands(rpcInputError);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const decoder = new JsonLineDecoder(
|
|
159
|
+
(value) => {
|
|
160
|
+
const event = value as AssistantEvent;
|
|
161
|
+
if (event.type === "response" && typeof event.id === "string") {
|
|
162
|
+
const pending = pendingCommands.get(event.id);
|
|
163
|
+
if (!pending) return;
|
|
164
|
+
if (event.success === true) {
|
|
165
|
+
resolvePendingCommand(event.id);
|
|
166
|
+
} else {
|
|
167
|
+
rejectPendingCommand(
|
|
168
|
+
event.id,
|
|
169
|
+
new Error(
|
|
170
|
+
typeof event.error === "string" ? event.error : `Subagent RPC ${pending.command} command failed.`,
|
|
171
|
+
),
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (event.type === "agent_settled") {
|
|
177
|
+
onAgentSettled();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (event.type === "message_end" && event.message?.role === "assistant") {
|
|
181
|
+
const text = (event.message.content ?? [])
|
|
182
|
+
.filter((part) => part.type === "text" && typeof part.text === "string")
|
|
183
|
+
.map((part) => part.text)
|
|
184
|
+
.join("\n")
|
|
185
|
+
.trim();
|
|
186
|
+
if (text) {
|
|
187
|
+
const limited = truncateText(text, MAX_OUTPUT_BYTES);
|
|
188
|
+
latestOutput = limited.text;
|
|
189
|
+
truncated ||= limited.truncated;
|
|
190
|
+
if (event.message.stopReason === "stop" || event.message.stopReason === "length") {
|
|
191
|
+
terminalOutput = limited.text;
|
|
192
|
+
terminalStopReason = event.message.stopReason;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (event.message.stopReason === "error" || event.message.stopReason === "aborted") {
|
|
196
|
+
assistantFailed = true;
|
|
197
|
+
}
|
|
198
|
+
if (event.message.errorMessage) {
|
|
199
|
+
const limited = truncateText(event.message.errorMessage, MAX_ERROR_BYTES);
|
|
200
|
+
errorMessage = limited.text;
|
|
201
|
+
truncated ||= limited.truncated;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
() => {
|
|
206
|
+
malformedEvents++;
|
|
207
|
+
},
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
const settlement = await new Promise<ProcessSettlement>((resolve) => {
|
|
211
|
+
let process: ChildProcess;
|
|
212
|
+
let settled = false;
|
|
213
|
+
let finishRequested = false;
|
|
214
|
+
let spawned = false;
|
|
215
|
+
let terminating = false;
|
|
216
|
+
let cancelled = false;
|
|
217
|
+
let timedOut = false;
|
|
218
|
+
let completed = false;
|
|
219
|
+
let ready = false;
|
|
220
|
+
let deadline: NodeJS.Timeout | undefined;
|
|
221
|
+
let forceClose: NodeJS.Timeout | undefined;
|
|
222
|
+
let escalation: NodeJS.Timeout | undefined;
|
|
223
|
+
let termination: Promise<void> | undefined;
|
|
224
|
+
|
|
225
|
+
const finish = (code: number, launchError?: string) => {
|
|
226
|
+
if (settled || finishRequested) return;
|
|
227
|
+
finishRequested = true;
|
|
228
|
+
const complete = () => {
|
|
229
|
+
if (settled) return;
|
|
230
|
+
settled = true;
|
|
231
|
+
if (deadline) clearTimeout(deadline);
|
|
232
|
+
if (forceClose) clearTimeout(forceClose);
|
|
233
|
+
if (escalation) clearTimeout(escalation);
|
|
234
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
235
|
+
rejectPendingCommands(new Error("Subagent RPC process closed."));
|
|
236
|
+
resolve({ code, cancelled, timedOut, completed, launchError });
|
|
237
|
+
};
|
|
238
|
+
if (termination) void termination.then(complete, complete);
|
|
239
|
+
else complete();
|
|
240
|
+
};
|
|
241
|
+
const terminate = (code: number) => {
|
|
242
|
+
if (settled || terminating) return;
|
|
243
|
+
terminating = true;
|
|
244
|
+
if (deadline) {
|
|
245
|
+
clearTimeout(deadline);
|
|
246
|
+
deadline = undefined;
|
|
247
|
+
}
|
|
248
|
+
if (globalThis.process.platform === "win32") {
|
|
249
|
+
termination = terminateWindowsProcessTree(process);
|
|
250
|
+
} else {
|
|
251
|
+
signalPosixProcess(process, "SIGTERM");
|
|
252
|
+
escalation = setTimeout(() => signalPosixProcess(process, "SIGKILL"), KILL_GRACE_MS);
|
|
253
|
+
escalation.unref();
|
|
254
|
+
}
|
|
255
|
+
forceClose = setTimeout(() => {
|
|
256
|
+
decoder.finish();
|
|
257
|
+
process.stdin?.destroy();
|
|
258
|
+
process.stdout?.destroy();
|
|
259
|
+
process.stderr?.destroy();
|
|
260
|
+
finish(code);
|
|
261
|
+
}, KILL_GRACE_MS * 2);
|
|
262
|
+
forceClose.unref();
|
|
263
|
+
};
|
|
264
|
+
const onAbort = () => {
|
|
265
|
+
if (settled) return;
|
|
266
|
+
cancelled = true;
|
|
267
|
+
terminate(130);
|
|
268
|
+
};
|
|
269
|
+
const completeNormally = () => {
|
|
270
|
+
if (settled || terminating || !ready) return;
|
|
271
|
+
completed = true;
|
|
272
|
+
terminate(0);
|
|
273
|
+
};
|
|
274
|
+
onAgentSettled = completeNormally;
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
process = spawn(invocation.command, invocation.args, {
|
|
278
|
+
cwd: request.cwd,
|
|
279
|
+
detached: globalThis.process.platform !== "win32",
|
|
280
|
+
shell: false,
|
|
281
|
+
stdio: ["pipe", "pipe", "pipe", "pipe"],
|
|
282
|
+
env: {
|
|
283
|
+
...globalThis.process.env,
|
|
284
|
+
...brokerCredentialEnvironment(),
|
|
285
|
+
PI_SUBAGENT_DEPTH: String((Number.parseInt(globalThis.process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1),
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
} catch (error) {
|
|
289
|
+
finish(1, error instanceof Error ? error.message : String(error));
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
process.stdin?.on("error", failRpcInput);
|
|
294
|
+
sendCommand = (command, onAccepted, signal) => {
|
|
295
|
+
if (settled || terminating || process.exitCode !== null) {
|
|
296
|
+
return Promise.reject(new Error("Subagent RPC process is no longer active."));
|
|
297
|
+
}
|
|
298
|
+
if (signal?.aborted) {
|
|
299
|
+
return Promise.reject(abortError("Subagent RPC command was cancelled."));
|
|
300
|
+
}
|
|
301
|
+
if (rpcInputError) return Promise.reject(rpcInputError);
|
|
302
|
+
const stdin = process.stdin;
|
|
303
|
+
if (!stdin || stdin.destroyed || !stdin.writable) {
|
|
304
|
+
return Promise.reject(new Error("Subagent RPC stdin is unavailable."));
|
|
305
|
+
}
|
|
306
|
+
const id = `rpc_${++rpcCounter}`;
|
|
307
|
+
return new Promise<void>((resolveCommand, rejectCommand) => {
|
|
308
|
+
const timer = setTimeout(
|
|
309
|
+
() => rejectPendingCommand(id, new Error(`Subagent RPC ${command.type} response timed out.`)),
|
|
310
|
+
RPC_RESPONSE_TIMEOUT_MS,
|
|
311
|
+
);
|
|
312
|
+
timer.unref();
|
|
313
|
+
const pending: PendingRpcCommand = {
|
|
314
|
+
command: command.type,
|
|
315
|
+
resolve: resolveCommand,
|
|
316
|
+
reject: rejectCommand,
|
|
317
|
+
timer,
|
|
318
|
+
onAccepted,
|
|
319
|
+
signal,
|
|
320
|
+
};
|
|
321
|
+
if (signal) {
|
|
322
|
+
pending.onAbort = () => rejectPendingCommand(id, abortError("Subagent RPC command was cancelled."));
|
|
323
|
+
}
|
|
324
|
+
pendingCommands.set(id, pending);
|
|
325
|
+
if (signal && pending.onAbort) {
|
|
326
|
+
signal.addEventListener("abort", pending.onAbort, { once: true });
|
|
327
|
+
if (signal.aborted) {
|
|
328
|
+
pending.onAbort();
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
try {
|
|
333
|
+
stdin.write(`${JSON.stringify({ id, ...command })}\n`, (error) => {
|
|
334
|
+
if (error) failRpcInput(error);
|
|
335
|
+
});
|
|
336
|
+
} catch (error) {
|
|
337
|
+
failRpcInput(error instanceof Error ? error : new Error(String(error)));
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
343
|
+
if (request.signal.aborted) onAbort();
|
|
344
|
+
process.once("spawn", () => {
|
|
345
|
+
spawned = true;
|
|
346
|
+
if (settled || cancelled) return;
|
|
347
|
+
void sendCommand(
|
|
348
|
+
{ type: "prompt", message: `Task: ${request.task}` },
|
|
349
|
+
() => {
|
|
350
|
+
if (settled || terminating || request.signal.aborted) {
|
|
351
|
+
throw new Error("Subagent RPC prompt was superseded.");
|
|
352
|
+
}
|
|
353
|
+
ready = true;
|
|
354
|
+
if (timeoutMs !== undefined) {
|
|
355
|
+
deadline = setTimeout(() => {
|
|
356
|
+
timedOut = true;
|
|
357
|
+
terminate(124);
|
|
358
|
+
}, timeoutMs);
|
|
359
|
+
deadline.unref();
|
|
360
|
+
}
|
|
361
|
+
const control: ChildControl = {
|
|
362
|
+
send: async (message, signal) => {
|
|
363
|
+
if (!ready || completed || terminating) {
|
|
364
|
+
throw new Error("Subagent job is no longer accepting messages.");
|
|
365
|
+
}
|
|
366
|
+
await sendCommand({ type: "steer", message }, undefined, signal);
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
request.onControl?.(control);
|
|
370
|
+
},
|
|
371
|
+
request.signal,
|
|
372
|
+
).catch((error) => {
|
|
373
|
+
if (settled || terminating) return;
|
|
374
|
+
errorMessage = truncateText(error instanceof Error ? error.message : String(error), MAX_ERROR_BYTES).text;
|
|
375
|
+
terminate(1);
|
|
376
|
+
});
|
|
377
|
+
});
|
|
378
|
+
process.stdout?.on("data", (chunk) => decoder.push(chunk));
|
|
379
|
+
process.stderr?.on("data", (chunk) => {
|
|
380
|
+
const limited = truncateTail(`${stderr}${chunk.toString()}`, MAX_ERROR_BYTES);
|
|
381
|
+
stderr = limited.text;
|
|
382
|
+
truncated ||= limited.truncated;
|
|
383
|
+
});
|
|
384
|
+
process.once("close", (code) => {
|
|
385
|
+
decoder.finish();
|
|
386
|
+
finish(cancelled ? 130 : timedOut ? 124 : completed ? 0 : (code ?? 1));
|
|
387
|
+
});
|
|
388
|
+
process.once("error", (error) => {
|
|
389
|
+
const limited = truncateText(error.message, MAX_ERROR_BYTES);
|
|
390
|
+
errorMessage = limited.text;
|
|
391
|
+
truncated ||= limited.truncated;
|
|
392
|
+
if (spawned) terminate(1);
|
|
393
|
+
else finish(1, error.message);
|
|
394
|
+
});
|
|
395
|
+
const credentialPipe = process.stdio[BROKER_CREDENTIAL_FD];
|
|
396
|
+
if (!credentialPipe || !("end" in credentialPipe)) {
|
|
397
|
+
errorMessage = "Subagent broker credential pipe is unavailable.";
|
|
398
|
+
terminate(1);
|
|
399
|
+
} else {
|
|
400
|
+
const onCredentialError = () => {
|
|
401
|
+
if (settled || finishRequested) return;
|
|
402
|
+
errorMessage = "Subagent broker credential transfer failed.";
|
|
403
|
+
terminate(1);
|
|
404
|
+
};
|
|
405
|
+
const removeCredentialListeners = () => {
|
|
406
|
+
credentialPipe.removeListener("error", onCredentialError);
|
|
407
|
+
credentialPipe.removeListener("close", removeCredentialListeners);
|
|
408
|
+
};
|
|
409
|
+
credentialPipe.on("error", onCredentialError);
|
|
410
|
+
credentialPipe.once("close", removeCredentialListeners);
|
|
411
|
+
try {
|
|
412
|
+
credentialPipe.end(serializeBrokerCredentials(request.communication));
|
|
413
|
+
} catch {
|
|
414
|
+
onCredentialError();
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
const output = terminalOutput ?? latestOutput;
|
|
420
|
+
const limitations = malformedEvents > 0 ? [`Ignored ${malformedEvents} malformed or oversized child event(s).`] : [];
|
|
421
|
+
if (truncated) limitations.push("Child output was truncated to runtime limits.");
|
|
422
|
+
if (terminalStopReason === "length") {
|
|
423
|
+
limitations.push("Child output ended at the model output limit and may be incomplete.");
|
|
424
|
+
}
|
|
425
|
+
if (settlement.cancelled) return cancelledResult(output, limitations, truncated);
|
|
426
|
+
if (settlement.timedOut) {
|
|
427
|
+
return {
|
|
428
|
+
state: "timed_out",
|
|
429
|
+
...(output ? { result: output } : {}),
|
|
430
|
+
error: "Subagent execution timed out.",
|
|
431
|
+
limitations,
|
|
432
|
+
truncated,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
const error = settlement.launchError || errorMessage || stderr.trim();
|
|
436
|
+
if (settlement.completed && terminalStopReason === "stop" && !assistantFailed && !errorMessage) {
|
|
437
|
+
return {
|
|
438
|
+
state: "completed",
|
|
439
|
+
result: terminalOutput,
|
|
440
|
+
limitations,
|
|
441
|
+
truncated,
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
const failure =
|
|
445
|
+
error ||
|
|
446
|
+
(terminalStopReason === "length"
|
|
447
|
+
? "Subagent output reached the model limit."
|
|
448
|
+
: assistantFailed
|
|
449
|
+
? "Subagent model turn failed."
|
|
450
|
+
: settlement.completed
|
|
451
|
+
? "Subagent settled without a terminal assistant result."
|
|
452
|
+
: settlement.code === 0
|
|
453
|
+
? "Subagent exited without settling."
|
|
454
|
+
: `Subagent exited with code ${settlement.code}.`);
|
|
455
|
+
if (output) {
|
|
456
|
+
return {
|
|
457
|
+
state: "partial",
|
|
458
|
+
result: output,
|
|
459
|
+
error: failure,
|
|
460
|
+
limitations,
|
|
461
|
+
truncated,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
return {
|
|
465
|
+
state: "failed",
|
|
466
|
+
error: failure,
|
|
467
|
+
limitations,
|
|
468
|
+
truncated,
|
|
469
|
+
};
|
|
487
470
|
}
|
|
488
471
|
|
|
489
472
|
function resolvePiInvocation(args: string[]): { command: string; args: string[] } {
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
473
|
+
const packageDirectory = fs.realpathSync(getPackageDir());
|
|
474
|
+
const manifestPath = path.join(packageDirectory, "package.json");
|
|
475
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
|
|
476
|
+
name?: string;
|
|
477
|
+
bin?: { pi?: string };
|
|
478
|
+
};
|
|
479
|
+
if (manifest.name !== CORE_PACKAGE_NAME || typeof manifest.bin?.pi !== "string") {
|
|
480
|
+
throw new Error("Loaded Pi core package does not declare a valid bin.pi entry.");
|
|
481
|
+
}
|
|
482
|
+
const declared = manifest.bin.pi;
|
|
483
|
+
if (path.isAbsolute(declared)) throw new Error("Pi core bin.pi must be package-relative.");
|
|
484
|
+
if (
|
|
485
|
+
globalThis.process.versions.bun &&
|
|
486
|
+
/^pi(?:\.exe)?$/iu.test(path.basename(globalThis.process.execPath)) &&
|
|
487
|
+
path.dirname(fs.realpathSync(globalThis.process.execPath)) === packageDirectory
|
|
488
|
+
) {
|
|
489
|
+
return { command: globalThis.process.execPath, args };
|
|
490
|
+
}
|
|
491
|
+
const cliPath = fs.realpathSync(path.resolve(packageDirectory, declared));
|
|
492
|
+
const relative = path.relative(packageDirectory, cliPath);
|
|
493
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
494
|
+
throw new Error("Pi core bin.pi escapes its package directory.");
|
|
495
|
+
}
|
|
496
|
+
if (!fs.statSync(cliPath).isFile()) throw new Error("Pi core bin.pi is not a file.");
|
|
497
|
+
return { command: globalThis.process.execPath, args: [cliPath, ...args] };
|
|
515
498
|
}
|
|
516
499
|
|
|
517
500
|
function signalPosixProcess(process: ChildProcess, signal: NodeJS.Signals): void {
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
501
|
+
if (process.pid) {
|
|
502
|
+
try {
|
|
503
|
+
globalThis.process.kill(-process.pid, signal);
|
|
504
|
+
return;
|
|
505
|
+
} catch {
|
|
506
|
+
// Fall back to the immediate child.
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
try {
|
|
510
|
+
process.kill(signal);
|
|
511
|
+
} catch {
|
|
512
|
+
// The process may already be terminal.
|
|
513
|
+
}
|
|
531
514
|
}
|
|
532
515
|
|
|
533
516
|
export function terminateWindowsProcessTree(
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
517
|
+
process: ChildProcess,
|
|
518
|
+
spawnProcess: typeof spawn = spawn,
|
|
519
|
+
taskkillPath = resolveTaskkillPath(),
|
|
520
|
+
helperTimeoutMs = KILL_GRACE_MS,
|
|
538
521
|
): Promise<void> {
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
522
|
+
if (!process.pid || !taskkillPath) {
|
|
523
|
+
killImmediateChild(process);
|
|
524
|
+
return Promise.resolve();
|
|
525
|
+
}
|
|
526
|
+
return new Promise((resolve) => {
|
|
527
|
+
let settled = false;
|
|
528
|
+
let treeKiller: ChildProcess;
|
|
529
|
+
let deadline: NodeJS.Timeout | undefined;
|
|
530
|
+
const onError = () => finish(true, false);
|
|
531
|
+
const onClose = (code: number | null) => finish(code !== 0, false);
|
|
532
|
+
const finish = (fallback: boolean, terminateHelper: boolean) => {
|
|
533
|
+
if (settled) return;
|
|
534
|
+
settled = true;
|
|
535
|
+
if (deadline) clearTimeout(deadline);
|
|
536
|
+
treeKiller.removeListener("error", onError);
|
|
537
|
+
treeKiller.removeListener("close", onClose);
|
|
538
|
+
if (terminateHelper) killImmediateChild(treeKiller);
|
|
539
|
+
if (fallback) killImmediateChild(process);
|
|
540
|
+
resolve();
|
|
541
|
+
};
|
|
542
|
+
try {
|
|
543
|
+
treeKiller = spawnProcess(taskkillPath, ["/PID", String(process.pid), "/T", "/F"], {
|
|
544
|
+
stdio: "ignore",
|
|
545
|
+
windowsHide: true,
|
|
546
|
+
});
|
|
547
|
+
} catch {
|
|
548
|
+
killImmediateChild(process);
|
|
549
|
+
resolve();
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
treeKiller.once("error", onError);
|
|
553
|
+
treeKiller.once("close", onClose);
|
|
554
|
+
deadline = setTimeout(() => finish(true, true), helperTimeoutMs);
|
|
555
|
+
deadline.unref();
|
|
556
|
+
});
|
|
574
557
|
}
|
|
575
558
|
|
|
576
559
|
function resolveTaskkillPath(): string | undefined {
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
560
|
+
const systemRoot = globalThis.process.env.SystemRoot ?? globalThis.process.env.WINDIR;
|
|
561
|
+
if (!systemRoot || !path.win32.isAbsolute(systemRoot)) return undefined;
|
|
562
|
+
return path.win32.join(systemRoot, "System32", "taskkill.exe");
|
|
580
563
|
}
|
|
581
564
|
|
|
582
565
|
function killImmediateChild(process: ChildProcess): void {
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
566
|
+
try {
|
|
567
|
+
process.kill("SIGKILL");
|
|
568
|
+
} catch {
|
|
569
|
+
// The process may already be terminal.
|
|
570
|
+
}
|
|
588
571
|
}
|
|
589
572
|
|
|
590
573
|
function abortError(message: string): Error {
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
574
|
+
const error = new Error(message);
|
|
575
|
+
error.name = "AbortError";
|
|
576
|
+
return error;
|
|
594
577
|
}
|
|
595
578
|
|
|
596
|
-
function cancelledResult(
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
error: "Subagent execution was cancelled.",
|
|
605
|
-
limitations,
|
|
606
|
-
truncated,
|
|
607
|
-
};
|
|
579
|
+
function cancelledResult(result?: string, limitations: string[] = [], truncated = false): ChildResult {
|
|
580
|
+
return {
|
|
581
|
+
state: "cancelled",
|
|
582
|
+
...(result ? { result } : {}),
|
|
583
|
+
error: "Subagent execution was cancelled.",
|
|
584
|
+
limitations,
|
|
585
|
+
truncated,
|
|
586
|
+
};
|
|
608
587
|
}
|
|
609
588
|
|
|
610
589
|
function truncateText(text: string, maxBytes: number): { text: string; truncated: boolean } {
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
590
|
+
const bytes = Buffer.from(text, "utf8");
|
|
591
|
+
if (bytes.length <= maxBytes) return { text, truncated: false };
|
|
592
|
+
return {
|
|
593
|
+
text: `${bytes
|
|
594
|
+
.subarray(0, Math.max(0, maxBytes - 18))
|
|
595
|
+
.toString("utf8")
|
|
596
|
+
.replace(/�+$/gu, "")}\n… [truncated]`,
|
|
597
|
+
truncated: true,
|
|
598
|
+
};
|
|
620
599
|
}
|
|
621
600
|
|
|
622
601
|
function truncateTail(text: string, maxBytes: number): { text: string; truncated: boolean } {
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
602
|
+
const bytes = Buffer.from(text, "utf8");
|
|
603
|
+
if (bytes.length <= maxBytes) return { text, truncated: false };
|
|
604
|
+
return {
|
|
605
|
+
text: `… [truncated]\n${bytes
|
|
606
|
+
.subarray(bytes.length - Math.max(0, maxBytes - 18))
|
|
607
|
+
.toString("utf8")
|
|
608
|
+
.replace(/^�+/gu, "")}`,
|
|
609
|
+
truncated: true,
|
|
610
|
+
};
|
|
632
611
|
}
|
|
633
612
|
|
|
634
613
|
class JsonLineDecoder {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
614
|
+
private buffer = "";
|
|
615
|
+
private dropping = false;
|
|
616
|
+
private readonly decoder = new StringDecoder("utf8");
|
|
617
|
+
|
|
618
|
+
constructor(
|
|
619
|
+
private readonly onValue: (value: unknown) => void,
|
|
620
|
+
private readonly onMalformed: () => void,
|
|
621
|
+
) {}
|
|
622
|
+
|
|
623
|
+
push(chunk: Buffer | string): void {
|
|
624
|
+
this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
|
|
625
|
+
this.drain(false);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
finish(): void {
|
|
629
|
+
this.buffer += this.decoder.end();
|
|
630
|
+
this.drain(true);
|
|
631
|
+
this.buffer = "";
|
|
632
|
+
this.dropping = false;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
private drain(flush: boolean): void {
|
|
636
|
+
while (true) {
|
|
637
|
+
const newline = this.buffer.indexOf("\n");
|
|
638
|
+
if (newline < 0) break;
|
|
639
|
+
const line = this.buffer.slice(0, newline).replace(/\r$/u, "");
|
|
640
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
641
|
+
if (this.dropping) {
|
|
642
|
+
this.dropping = false;
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
this.parse(line);
|
|
646
|
+
}
|
|
647
|
+
if (!flush && Buffer.byteLength(this.buffer, "utf8") > MAX_EVENT_LINE_BYTES) {
|
|
648
|
+
this.onMalformed();
|
|
649
|
+
this.buffer = "";
|
|
650
|
+
this.dropping = true;
|
|
651
|
+
}
|
|
652
|
+
if (flush && this.buffer && !this.dropping) this.parse(this.buffer.replace(/\r$/u, ""));
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
private parse(line: string): void {
|
|
656
|
+
if (!line.trim()) return;
|
|
657
|
+
if (Buffer.byteLength(line, "utf8") > MAX_EVENT_LINE_BYTES) {
|
|
658
|
+
this.onMalformed();
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
try {
|
|
662
|
+
this.onValue(JSON.parse(line));
|
|
663
|
+
} catch {
|
|
664
|
+
this.onMalformed();
|
|
665
|
+
}
|
|
666
|
+
}
|
|
688
667
|
}
|