@mozhi0012/pi-terminal-worker 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -0
  3. package/dist/controller.d.ts +457 -0
  4. package/dist/controller.d.ts.map +1 -0
  5. package/dist/controller.js +2164 -0
  6. package/dist/controller.js.map +1 -0
  7. package/dist/extension.d.ts +31 -0
  8. package/dist/extension.d.ts.map +1 -0
  9. package/dist/extension.js +89 -0
  10. package/dist/extension.js.map +1 -0
  11. package/dist/launcher.d.ts +131 -0
  12. package/dist/launcher.d.ts.map +1 -0
  13. package/dist/launcher.js +374 -0
  14. package/dist/launcher.js.map +1 -0
  15. package/dist/lifecycle.d.ts +103 -0
  16. package/dist/lifecycle.d.ts.map +1 -0
  17. package/dist/lifecycle.js +206 -0
  18. package/dist/lifecycle.js.map +1 -0
  19. package/dist/multi-worker.d.ts +324 -0
  20. package/dist/multi-worker.d.ts.map +1 -0
  21. package/dist/multi-worker.js +833 -0
  22. package/dist/multi-worker.js.map +1 -0
  23. package/dist/protocol.d.ts +249 -0
  24. package/dist/protocol.d.ts.map +1 -0
  25. package/dist/protocol.js +430 -0
  26. package/dist/protocol.js.map +1 -0
  27. package/dist/transport.d.ts +135 -0
  28. package/dist/transport.d.ts.map +1 -0
  29. package/dist/transport.js +459 -0
  30. package/dist/transport.js.map +1 -0
  31. package/dist/ui.d.ts +63 -0
  32. package/dist/ui.d.ts.map +1 -0
  33. package/dist/ui.js +100 -0
  34. package/dist/ui.js.map +1 -0
  35. package/dist/worker.d.ts +94 -0
  36. package/dist/worker.d.ts.map +1 -0
  37. package/dist/worker.js +842 -0
  38. package/dist/worker.js.map +1 -0
  39. package/package.json +72 -0
  40. package/runtime/bootstrap.mjs +286 -0
  41. package/src/controller.ts +2715 -0
  42. package/src/extension.ts +107 -0
  43. package/src/launcher.ts +510 -0
  44. package/src/lifecycle.ts +281 -0
  45. package/src/multi-worker.ts +1096 -0
  46. package/src/protocol.ts +739 -0
  47. package/src/transport.ts +561 -0
  48. package/src/ui.ts +131 -0
  49. package/src/worker.ts +996 -0
package/src/worker.ts ADDED
@@ -0,0 +1,996 @@
1
+ /**
2
+ * 执行端 (Worker) 核心实现:
3
+ * 环境变量激活、命名管道双向通信、worker_report 工具、候选/正式回执流转、本地人工输入干预与消息排队
4
+ */
5
+
6
+ import * as net from "node:net";
7
+ import * as crypto from "node:crypto";
8
+ import type {
9
+ ExtensionAPI,
10
+ ExtensionContext,
11
+ ExtensionCommandContext,
12
+ InputEvent,
13
+ ToolExecutionStartEvent,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import { Type } from "typebox";
16
+ import {
17
+ PROTOCOL_VERSION,
18
+ MAX_FOLLOWUP_QUEUE_SIZE,
19
+ MAX_FOLLOWUP_QUEUE_BYTES,
20
+ MAX_REPORT_SIZE,
21
+ MAX_ERROR_MESSAGE_SIZE,
22
+ jsonByteLength,
23
+ ProtocolErrorCode,
24
+ ProtocolValidationError,
25
+ validateWorkerReport,
26
+ type Envelope,
27
+ type AckPayload,
28
+ type TaskPayload,
29
+ type FollowupPayload,
30
+ type AbortPayload,
31
+ type ClosePayload,
32
+ type WorkerReportPayload,
33
+ type WorkerReadyPayload,
34
+ type ModelChangedPayload,
35
+ } from "./protocol.js";
36
+ import { JsonlConnection } from "./transport.js";
37
+ import { SessionGenerationManager } from "./lifecycle.js";
38
+
39
+ const FORBIDDEN_WORKER_TOOLS = new Set([
40
+ "subagent",
41
+ "subagent_stop",
42
+ "subagent_wait",
43
+ ]);
44
+
45
+ /** followup 队列条目:sessionGeneration 绑定入队时的会话代际,绝不跨会话派发 */
46
+ interface FollowupQueueItem {
47
+ taskId: string;
48
+ revision: number;
49
+ runId: number;
50
+ message: string;
51
+ sessionGeneration: number;
52
+ }
53
+
54
+ export class WorkerManager {
55
+ private conn: JsonlConnection | null = null;
56
+ private isDetached = false;
57
+ private currentContext: ExtensionContext | null = null;
58
+
59
+ /** 会话代际追踪:session_start / session_shutdown 时推进,使旧异步回调立即失效 */
60
+ private readonly sessionGen = new SessionGenerationManager();
61
+ /** 当前活动代际,初值与 sessionGen.generation (0) 一致 */
62
+ private activeGeneration = 0;
63
+ /** 被 generation 校验拦截的失效回调计数 (仅用于诊断) */
64
+ private staleCallbacksIgnored = 0;
65
+
66
+ /** worker_ready 双条件门控:hello_ok 认证确认 + currentContext 就绪,两者谁先到均在齐备后发送且只发一次 */
67
+ private helloOkReceived = false;
68
+ private workerReadySent = false;
69
+
70
+ private controllerId: string;
71
+ private workerId: string;
72
+ private pipePath: string;
73
+ private token: string;
74
+
75
+ private currentTaskId: string | null = null;
76
+ private currentRevision = 1;
77
+ private currentRunId = 1;
78
+
79
+ private currentCandidate: WorkerReportPayload | null = null;
80
+ private candidateInvalidated = false;
81
+ private taskHasReported = false;
82
+
83
+ private followupQueue: FollowupQueueItem[] = [];
84
+ /** followup 队列总字节数 (与 8 条上限共同生效) */
85
+ private followupQueueBytes = 0;
86
+
87
+ private readonly strictProtocol: boolean;
88
+
89
+ constructor(private pi: ExtensionAPI, strictProtocol = false) {
90
+ this.strictProtocol = strictProtocol;
91
+ this.controllerId = process.env.PI_TERMINAL_WORKER_CONTROLLER_ID || "";
92
+ this.workerId = process.env.PI_TERMINAL_WORKER_WORKER_ID || "";
93
+ this.pipePath = process.env.PI_TERMINAL_WORKER_PIPE_PATH || "";
94
+ this.token = process.env.PI_TERMINAL_WORKER_TOKEN || "";
95
+ }
96
+
97
+ public async init(): Promise<void> {
98
+ if (!this.pipePath || !this.token) {
99
+ console.warn("[Worker] 缺少管道配置或 Token,跳过 Worker 初始化");
100
+ return;
101
+ }
102
+
103
+ this.registerWorkerReportTool();
104
+ this.registerWorkerCommands();
105
+ this.setupPiEventListeners();
106
+
107
+ // 建立与主控的连接
108
+ await this.connectToController();
109
+ }
110
+
111
+ private async connectToController(): Promise<void> {
112
+ const socket = net.createConnection(this.pipePath);
113
+ this.conn = new JsonlConnection(socket, "worker", this.strictProtocol);
114
+ const connAtConnect = this.conn;
115
+
116
+ socket.on("connect", () => {
117
+ // session_shutdown / detach 可能已销毁并置空连接:晚到的 connect 不得再用旧连接发 hello
118
+ if (this.conn !== connAtConnect) {
119
+ return;
120
+ }
121
+ // 发送 hello 认证
122
+ connAtConnect.sendEnvelope({
123
+ version: PROTOCOL_VERSION,
124
+ controllerId: this.controllerId,
125
+ workerId: this.workerId,
126
+ id: crypto.randomUUID(),
127
+ seq: connAtConnect.nextSeq,
128
+ type: "hello",
129
+ payload: {
130
+ role: "worker",
131
+ token: this.token,
132
+ controllerId: this.controllerId,
133
+ workerId: this.workerId,
134
+ },
135
+ }).catch((err) => {
136
+ console.error("[Worker] 发送 hello 失败:", err);
137
+ });
138
+ });
139
+
140
+ this.conn.on("message", (env: Envelope) => {
141
+ this.handleControllerEnvelope(env);
142
+ });
143
+
144
+ this.conn.on("close", () => {
145
+ if (!this.isDetached) {
146
+ console.warn("[Worker] 与 Controller 管道断开,继续保持本地 TUI 会话运行");
147
+ }
148
+ this.conn = null;
149
+ });
150
+
151
+ this.conn.on("error", (err: Error) => {
152
+ console.error("[Worker] 管道通信异常:", err.message);
153
+ });
154
+ }
155
+
156
+ /**
157
+ * 校验 Controller 发来的任务迁移,避免延迟/重放消息重绑当前任务。
158
+ * 首个 task 可建立绑定;之后只能接收同一 task 的更高 revision/runId followup。
159
+ */
160
+ private validateTaskTransition(
161
+ type: "task" | "followup",
162
+ payload: TaskPayload | FollowupPayload,
163
+ ): void {
164
+ if (!this.currentTaskId) {
165
+ if (type === "followup") {
166
+ throw new ProtocolValidationError(
167
+ ProtocolErrorCode.INVALID_STATE,
168
+ `没有当前任务,不能接收 followup: ${ProtocolErrorCode.INVALID_STATE}`,
169
+ );
170
+ }
171
+ return;
172
+ }
173
+ if (payload.taskId !== this.currentTaskId) {
174
+ throw new ProtocolValidationError(
175
+ ProtocolErrorCode.IDENTITY_MISMATCH,
176
+ `任务 ID 与当前 Worker 任务不匹配 (${payload.taskId} !== ${this.currentTaskId}): ${ProtocolErrorCode.IDENTITY_MISMATCH}`,
177
+ );
178
+ }
179
+ if (type === "task") {
180
+ throw new ProtocolValidationError(
181
+ ProtocolErrorCode.INVALID_STATE,
182
+ `当前任务已绑定,不能再次接收初始 task: ${ProtocolErrorCode.INVALID_STATE}`,
183
+ );
184
+ }
185
+ if (
186
+ payload.revision < this.currentRevision ||
187
+ (payload.revision === this.currentRevision && payload.runId <= this.currentRunId)
188
+ ) {
189
+ throw new ProtocolValidationError(
190
+ ProtocolErrorCode.INVALID_STATE,
191
+ `过时的任务迁移 (revision=${payload.revision}, runId=${payload.runId}; 当前 revision=${this.currentRevision}, runId=${this.currentRunId}): ${ProtocolErrorCode.INVALID_STATE}`,
192
+ );
193
+ }
194
+ }
195
+ private handleControllerEnvelope(env: Envelope): void {
196
+ // 连接或会话已失效 (session_shutdown / detach / socket close) 后晚到的消息:
197
+ // 不得再改状态、不得回 ACK,直接忽略并计数
198
+ const entryGen = this.activeGeneration;
199
+ if (!this.isCurrentGeneration(entryGen) || !this.conn) {
200
+ this.staleCallbacksIgnored++;
201
+ return;
202
+ }
203
+
204
+ const { id, type, payload } = env;
205
+
206
+ // 身份校验:controllerId/workerId 与自身环境变量不一致的消息一律丢弃,
207
+ // 不改状态、不派发、不回 ACK,仅回发一条 error
208
+ if (env.controllerId !== this.controllerId || env.workerId !== this.workerId) {
209
+ console.warn(
210
+ `[Worker] 身份不匹配的消息已丢弃: type=${type} id=${id} ` +
211
+ `(期望 controllerId=${this.controllerId} workerId=${this.workerId},实际 ${env.controllerId}/${env.workerId})`,
212
+ );
213
+ this.sendPeerError(
214
+ id,
215
+ ProtocolErrorCode.PROTOCOL_ERROR,
216
+ `身份不匹配: workerId 应为 ${this.workerId},请求 ${id} 已被忽略`,
217
+ );
218
+ return;
219
+ }
220
+
221
+ if (type === "hello_ok") {
222
+ this.helloOkReceived = true;
223
+ // session_start 可能早于认证完成;齐备后补发 worker_ready
224
+ this.trySendWorkerReady();
225
+ return;
226
+ }
227
+
228
+ if (type === "ping") {
229
+ this.conn?.sendEnvelope({
230
+ version: PROTOCOL_VERSION,
231
+ controllerId: this.controllerId,
232
+ workerId: this.workerId,
233
+ id: crypto.randomUUID(),
234
+ replyTo: id,
235
+ seq: this.conn.nextSeq,
236
+ type: "pong",
237
+ payload: { timestamp: Date.now(), replyTimestamp: (payload as any).timestamp },
238
+ });
239
+ return;
240
+ }
241
+
242
+ if (type === "task") {
243
+ const hit = this.dedupGate(id, payload, false);
244
+ if (hit) return; // 重复请求:已回发缓存 ACK,不重复派发
245
+ try {
246
+ const p = payload as TaskPayload;
247
+ this.validateTaskTransition("task", p);
248
+ this.currentTaskId = p.taskId;
249
+ this.currentRevision = p.revision;
250
+ this.currentRunId = p.runId;
251
+ this.currentCandidate = null;
252
+ this.candidateInvalidated = false;
253
+ this.taskHasReported = false;
254
+
255
+ const formattedPrompt = this.buildTaskPrompt(p);
256
+
257
+ // 先排队或直接派发,成功后才发送 ACK;队列满/超字节时由 catch 回发失败 ACK
258
+ // 显式传入入口处捕获并校验过的 ctx 与 generation,不隐式读取可能已过期的状态
259
+ this.enqueueOrDispatchMessage(
260
+ {
261
+ taskId: p.taskId,
262
+ revision: p.revision,
263
+ runId: p.runId,
264
+ message: formattedPrompt,
265
+ },
266
+ this.currentContext,
267
+ entryGen,
268
+ );
269
+
270
+ // 发送 ACK,并把完全相同的 payload 对象记入去重缓存
271
+ const ackPayload = this.sendAck(id, true);
272
+ this.conn?.recordDedup(id, payload, ackPayload, false);
273
+ } catch (err: unknown) {
274
+ const message = err instanceof Error ? err.message : String(err);
275
+ const code = err instanceof ProtocolValidationError ? err.code : undefined;
276
+ const ackPayload = this.sendAck(id, false, message, code);
277
+ this.conn?.recordDedup(id, payload, ackPayload, false);
278
+ }
279
+ return;
280
+ }
281
+
282
+ if (type === "followup") {
283
+ const hit = this.dedupGate(id, payload, false);
284
+ if (hit) return; // 重复请求:已回发缓存 ACK,不重复入队/派发
285
+ try {
286
+ const p = payload as FollowupPayload;
287
+ this.validateTaskTransition("followup", p);
288
+ this.currentRevision = p.revision;
289
+ this.currentRunId = p.runId;
290
+ this.currentCandidate = null;
291
+ this.candidateInvalidated = false;
292
+ this.taskHasReported = false;
293
+
294
+ const formattedPrompt = `【来自主控端的 ${p.kind === "revision" ? "返修任务" : "补充说明"} (Revision ${p.revision})】\n${p.message}\n\n请在实施完毕或遇到问题时,通过 worker_report 工具提交新的回执。`;
295
+
296
+ // 先排队或直接派发,成功后才发送 ACK;队列满/超字节时由 catch 回发失败 ACK
297
+ this.enqueueOrDispatchMessage(
298
+ {
299
+ taskId: p.taskId,
300
+ revision: p.revision,
301
+ runId: p.runId,
302
+ message: formattedPrompt,
303
+ },
304
+ this.currentContext,
305
+ entryGen,
306
+ );
307
+
308
+ const ackPayload = this.sendAck(id, true);
309
+ this.conn?.recordDedup(id, payload, ackPayload, false);
310
+ } catch (err: unknown) {
311
+ const message = err instanceof Error ? err.message : String(err);
312
+ const code = err instanceof ProtocolValidationError ? err.code : undefined;
313
+ const ackPayload = this.sendAck(id, false, message, code);
314
+ this.conn?.recordDedup(id, payload, ackPayload, false);
315
+ }
316
+ return;
317
+ }
318
+
319
+ if (type === "abort") {
320
+ const hit = this.dedupGate(id, payload, true);
321
+ if (hit) return; // 重复 abort:幂等,走缓存 ACK
322
+ this.clearQueue();
323
+ this.currentCandidate = null;
324
+ if (this.currentContext) {
325
+ this.currentContext.abort();
326
+ }
327
+ const ackPayload = this.sendAck(id, true);
328
+ this.conn?.recordDedup(id, payload, ackPayload, true);
329
+ return;
330
+ }
331
+
332
+ if (type === "close") {
333
+ const hit = this.dedupGate(id, payload, true);
334
+ if (hit) return; // 重复 close:幂等,走缓存 ACK
335
+ const ackPayload = this.sendAck(id, true);
336
+ this.conn?.recordDedup(id, payload, ackPayload, true);
337
+ // 延迟 shutdown 跨越定时器:回调内重新校验代际与当前上下文;
338
+ // 不比较 ctx 身份 (Pi 每个事件新建 ctx,跨事件身份比较恒为真)
339
+ const closeGen = this.activeGeneration;
340
+ setTimeout(() => {
341
+ if (!this.isCurrentGeneration(closeGen) || !this.currentContext) {
342
+ this.staleCallbacksIgnored++;
343
+ return;
344
+ }
345
+ this.currentContext.shutdown();
346
+ }, 200);
347
+ return;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * 去重网关:命中缓存则回发缓存 ACK 并返回它;
353
+ * DUPLICATE_REQUEST_MISMATCH / DEDUP_FULL 则回发失败 ACK 并返回;正常返回 null。
354
+ */
355
+ private dedupGate(id: string, payload: unknown, isControl: boolean): AckPayload | null {
356
+ const conn = this.conn;
357
+ if (!conn) return null;
358
+ try {
359
+ const cached = conn.checkDedup(id, payload, isControl);
360
+ if (cached) {
361
+ this.emitAck(cached.ack);
362
+ return cached.ack;
363
+ }
364
+ } catch (err: unknown) {
365
+ const e = err as { code?: string; message?: string };
366
+ if (
367
+ e?.code === ProtocolErrorCode.DUPLICATE_REQUEST_MISMATCH ||
368
+ e?.code === ProtocolErrorCode.DEDUP_FULL
369
+ ) {
370
+ const ackPayload = this.sendAck(id, false, e.message ?? String(err), e.code);
371
+ // 注意:这两个分支不 recordDedup ——
372
+ // MISMATCH:原有缓存条目 (同 ID 同正文 → 缓存 ACK) 必须保留,
373
+ // 若用冲突正文覆盖,之后重发原始正文会再也查不回缓存 ACK (设计文档 5.4 节语义);
374
+ // DEDUP_FULL:普通表已满,recordDedup 只会丢弃并 warn,无意义。
375
+ return ackPayload;
376
+ }
377
+ throw err;
378
+ }
379
+ return null;
380
+ }
381
+
382
+ private sendAck(replyTo: string, ok: boolean, error?: string, code?: string): AckPayload {
383
+ const ackPayload: AckPayload = { id: replyTo, ok };
384
+ if (error !== undefined) {
385
+ ackPayload.error = error.slice(0, MAX_ERROR_MESSAGE_SIZE);
386
+ }
387
+ if (code !== undefined) {
388
+ ackPayload.code = code;
389
+ }
390
+ this.emitAck(ackPayload);
391
+ return ackPayload;
392
+ }
393
+
394
+ /**
395
+ * 回发 ACK envelope;payload 对象与传入引用完全一致 (去重缓存一致性)
396
+ */
397
+ private emitAck(ackPayload: AckPayload): void {
398
+ if (!this.conn || this.conn.socket.destroyed) return;
399
+ this.conn.sendEnvelope({
400
+ version: PROTOCOL_VERSION,
401
+ controllerId: this.controllerId,
402
+ workerId: this.workerId,
403
+ id: crypto.randomUUID(),
404
+ replyTo: ackPayload.id,
405
+ seq: this.conn.nextSeq,
406
+ type: "ack",
407
+ payload: ackPayload,
408
+ }).catch(() => {});
409
+ }
410
+
411
+ /**
412
+ * 尽力向主控回发一条 error envelope
413
+ */
414
+ private sendPeerError(replyTo: string, code: string, message: string): void {
415
+ if (!this.conn || this.conn.socket.destroyed) return;
416
+ this.conn.sendEnvelope({
417
+ version: PROTOCOL_VERSION,
418
+ controllerId: this.controllerId,
419
+ workerId: this.workerId,
420
+ id: crypto.randomUUID(),
421
+ replyTo,
422
+ seq: this.conn.nextSeq,
423
+ type: "error",
424
+ payload: { code, message: message.slice(0, MAX_ERROR_MESSAGE_SIZE) },
425
+ }).catch(() => {});
426
+ }
427
+
428
+ /**
429
+ * 发送 worker_ready:必须等 hello_ok 认证确认且 currentContext 存在后发送,
430
+ * 两者无论谁先到均保证发送一次 (认证前发送会被主控丢弃,造成永久等待)
431
+ */
432
+ private trySendWorkerReady(): void {
433
+ if (this.workerReadySent) return;
434
+ if (!this.helloOkReceived) return;
435
+ const gen = this.activeGeneration;
436
+ const ctx = this.currentContext;
437
+ if (!ctx || !this.isCurrentGeneration(gen)) return;
438
+ if (!this.conn || this.conn.socket.destroyed) return;
439
+
440
+ this.workerReadySent = true;
441
+ const readyPayload: WorkerReadyPayload = {
442
+ cwd: ctx.cwd,
443
+ tools: this.pi.getActiveTools().filter((name) => !FORBIDDEN_WORKER_TOOLS.has(name)),
444
+ version: PROTOCOL_VERSION.toString(),
445
+ ...this.collectModelInfo(ctx),
446
+ };
447
+ this.conn.sendEnvelope({
448
+ version: PROTOCOL_VERSION,
449
+ controllerId: this.controllerId,
450
+ workerId: this.workerId,
451
+ id: crypto.randomUUID(),
452
+ seq: this.conn.nextSeq,
453
+ type: "worker_ready",
454
+ payload: readyPayload,
455
+ }).catch(() => {});
456
+ }
457
+
458
+ /**
459
+ * 采集 Worker 会话实际的模型信息 (不猜测、不硬编码)
460
+ */
461
+ private collectModelInfo(ctx: ExtensionContext): { provider?: string; modelId?: string; thinkingLevel?: string } {
462
+ const info: { provider?: string; modelId?: string; thinkingLevel?: string } = {};
463
+ const model = (ctx as { model?: { provider?: string; id?: string } }).model;
464
+ if (model?.provider) info.provider = model.provider;
465
+ if (model?.id) info.modelId = model.id;
466
+ try {
467
+ const level = (this.pi as ExtensionAPI).getThinkingLevel?.();
468
+ if (level) info.thinkingLevel = level;
469
+ } catch {
470
+ // 获取 thinking 级别失败不影响主流程
471
+ }
472
+ return info;
473
+ }
474
+
475
+ /**
476
+ * 会话中模型/思考级别变化后向主控刷新上报
477
+ */
478
+ private sendModelChanged(): void {
479
+ const gen = this.activeGeneration;
480
+ const ctx = this.currentContext;
481
+ if (!ctx || !this.isCurrentGeneration(gen)) return;
482
+ if (!this.conn || this.conn.socket.destroyed) return;
483
+ this.conn.sendEnvelope({
484
+ version: PROTOCOL_VERSION,
485
+ controllerId: this.controllerId,
486
+ workerId: this.workerId,
487
+ id: crypto.randomUUID(),
488
+ seq: this.conn.nextSeq,
489
+ type: "model_changed",
490
+ payload: this.collectModelInfo(ctx) as ModelChangedPayload,
491
+ }).catch(() => {});
492
+ }
493
+
494
+ private buildTaskPrompt(p: TaskPayload): string {
495
+ const parts: string[] = [
496
+ `【来自主控端的指派任务 - Task ID: ${p.taskId} (Revision ${p.revision})】`,
497
+ `目标需求:\n${p.task}`,
498
+ ];
499
+
500
+ if (p.context) {
501
+ parts.push(`背景上下文:\n${p.context}`);
502
+ }
503
+
504
+ if (p.allowedPaths && p.allowedPaths.length > 0) {
505
+ parts.push(`允许修改的路径范围契约:\n${p.allowedPaths.map((x) => `- ${x}`).join("\n")}`);
506
+ }
507
+
508
+ if (p.acceptanceCriteria && p.acceptanceCriteria.length > 0) {
509
+ parts.push(`验收指标与测试要求:\n${p.acceptanceCriteria.map((x) => `- ${x}`).join("\n")}`);
510
+ }
511
+
512
+ parts.push(
513
+ `执行与回执要求:`,
514
+ `1. 按照方案在指定工作目录内修改代码并进行本地验证。`,
515
+ `2. 不得再派发子代理或启动新终端;超出允许范围或需要改变设计时,调用 worker_report(kind="blocked") 说明原因。`,
516
+ `3. 任务完成、遇到提问或出现阻碍时,必须调用 worker_report 工具提交回执。`,
517
+ );
518
+
519
+ return parts.join("\n\n");
520
+ }
521
+
522
+ private isCurrentGeneration(gen: number): boolean {
523
+ return this.sessionGen.isValid(gen);
524
+ }
525
+
526
+ /**
527
+ * 入队或立即派发。sessionGeneration 写入入队当时的 generation;
528
+ * ctx/gen 可显式传入(跨 await/tick 的调用点必须传当时捕获的值)。
529
+ */
530
+ private enqueueOrDispatchMessage(
531
+ item: {
532
+ taskId: string;
533
+ revision: number;
534
+ runId: number;
535
+ message: string;
536
+ sessionGeneration?: number;
537
+ },
538
+ ctx: ExtensionContext | null = this.currentContext,
539
+ gen: number = this.activeGeneration,
540
+ ): void {
541
+ item.sessionGeneration = gen;
542
+ const queueItem = item as FollowupQueueItem;
543
+
544
+ if (ctx && ctx.isIdle() && !ctx.hasPendingMessages()) {
545
+ // 立即派发分支同样校验代际:绝不把消息交给已失效的会话
546
+ if (!this.isCurrentGeneration(queueItem.sessionGeneration)) {
547
+ this.staleCallbacksIgnored++;
548
+ return;
549
+ }
550
+ this.dispatchUserMessage(queueItem.message, ctx, queueItem.sessionGeneration);
551
+ return;
552
+ }
553
+
554
+ const itemBytes = jsonByteLength(queueItem);
555
+ if (this.followupQueue.length >= MAX_FOLLOWUP_QUEUE_SIZE) {
556
+ throw new Error(
557
+ `Worker 内部消息队列已满 (${MAX_FOLLOWUP_QUEUE_SIZE} 条): ${ProtocolErrorCode.QUEUE_FULL}`,
558
+ );
559
+ }
560
+ if (this.followupQueueBytes + itemBytes > MAX_FOLLOWUP_QUEUE_BYTES) {
561
+ throw new Error(
562
+ `Worker 内部消息队列总字节超限 (上限 1 MiB=${MAX_FOLLOWUP_QUEUE_BYTES} 字节,` +
563
+ `当前 ${this.followupQueueBytes} 字节,新增 ${itemBytes} 字节): ${ProtocolErrorCode.QUEUE_BYTES_EXCEEDED}`,
564
+ );
565
+ }
566
+ this.followupQueue.push(queueItem);
567
+ this.followupQueueBytes += itemBytes;
568
+ }
569
+
570
+ /**
571
+ * 出队并扣减字节;丢弃所有 sessionGeneration 与目标 gen 不符的旧条目
572
+ * (逐条计入 staleCallbacksIgnored),绝不派发到新会话。队列为空时返回 undefined。
573
+ */
574
+ private shiftQueueItem(gen: number = this.activeGeneration): FollowupQueueItem | undefined {
575
+ while (this.followupQueue.length > 0) {
576
+ const item = this.followupQueue.shift()!;
577
+ this.followupQueueBytes -= jsonByteLength(item);
578
+ if (item.sessionGeneration === gen && this.isCurrentGeneration(gen)) {
579
+ return item;
580
+ }
581
+ this.staleCallbacksIgnored++;
582
+ }
583
+ return undefined;
584
+ }
585
+
586
+ /** 清空队列并归零字节计数 */
587
+ private clearQueue(): void {
588
+ this.followupQueue = [];
589
+ this.followupQueueBytes = 0;
590
+ }
591
+
592
+ /**
593
+ * 派发用户消息。必须显式传入捕获的 ctx 与 gen;
594
+ * ctx 非空、代际有效且当前存在会话上下文时才调用 Pi API;
595
+ * 绝不比较 ctx 身份 (Pi 每个事件新建 ctx,跨事件身份比较恒为真)。
596
+ */
597
+ private dispatchUserMessage(text: string, ctx: ExtensionContext | null, gen: number): boolean {
598
+ if (!ctx || !this.isCurrentGeneration(gen) || !this.currentContext) {
599
+ this.staleCallbacksIgnored++;
600
+ return false;
601
+ }
602
+ this.pi.sendUserMessage(text, {
603
+ expandPromptTemplates: false,
604
+ });
605
+ return true;
606
+ }
607
+
608
+ private setupPiEventListeners(): void {
609
+ // 监听 session_start
610
+ this.pi.on("session_start", async (_event: any, ctx: ExtensionContext) => {
611
+ const previousContext = this.currentContext;
612
+ // 每次 session_start 都推进代际:旧会话的异步回调随即失效
613
+ this.activeGeneration = this.sessionGen.nextGeneration();
614
+ this.currentContext = ctx;
615
+
616
+ if (previousContext === null) {
617
+ // 启动竞态:首个 session_start 之前入队的早到任务仍属于本次会话,
618
+ // 把它们的 generation 改写为新代际(adopt),随后可正常补派发
619
+ for (const item of this.followupQueue) {
620
+ item.sessionGeneration = this.activeGeneration;
621
+ }
622
+ } else {
623
+ // 真实会话切换(用户切换/重开 session):绝不把旧会话消息注入新 session。
624
+ // 旧队列、旧候选与旧任务绑定一律作废:
625
+ // currentTaskId 置空后,旧会话晚到的 agent_settled 既无候选也无任务,
626
+ // 不会向新会话发出 report_missing。
627
+ this.clearQueue();
628
+ this.currentCandidate = null;
629
+ this.candidateInvalidated = true;
630
+ this.taskHasReported = false;
631
+ this.currentTaskId = null;
632
+ }
633
+
634
+ this.pi.setActiveTools(
635
+ this.pi.getActiveTools().filter((name) => !FORBIDDEN_WORKER_TOOLS.has(name)),
636
+ );
637
+ // hello_ok 可能尚未到达或已到达;两种时序下均由双条件门控发送 worker_ready
638
+ this.trySendWorkerReady();
639
+
640
+ // 启动竞态修复:会话就绪后立即补派发队列首条,避免队列永久卡住
641
+ if (
642
+ this.followupQueue.length > 0 &&
643
+ ctx.isIdle() &&
644
+ !ctx.hasPendingMessages()
645
+ ) {
646
+ const next = this.shiftQueueItem(this.activeGeneration);
647
+ if (next) {
648
+ this.dispatchUserMessage(next.message, ctx, this.activeGeneration);
649
+ }
650
+ }
651
+ });
652
+
653
+ // 监听 session_shutdown
654
+ this.pi.on("session_shutdown", async () => {
655
+ // 幂等:重复触发不得再次 destroy / 抛错;先推进代际使所有旧回调立即失效,
656
+ // 之后旧回调不得再调用 sendUserMessage / abort / shutdown / setActiveTools
657
+ this.sessionGen.nextGeneration();
658
+ this.activeGeneration = this.sessionGen.generation;
659
+ this.currentContext = null;
660
+ this.clearQueue();
661
+ this.currentCandidate = null;
662
+ this.candidateInvalidated = true;
663
+
664
+ const conn = this.conn;
665
+ if (conn) {
666
+ this.conn = null;
667
+ conn.destroy();
668
+ }
669
+ });
670
+
671
+ // 监听 input 事件:识别本地用户在终端窗口键盘输入干预
672
+ this.pi.on("input", async (event: InputEvent) => {
673
+ const gen = this.activeGeneration;
674
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
675
+ // 会话已切换/已关闭:不得再改状态、不得发 local_input
676
+ this.staleCallbacksIgnored++;
677
+ return { action: "continue" };
678
+ }
679
+ if (event.source === "interactive") {
680
+ // 用户敲键盘干预!
681
+ this.candidateInvalidated = true;
682
+ this.currentCandidate = null;
683
+ this.clearQueue(); // 暂停自动派发旧队列
684
+
685
+ if (this.conn && !this.conn.socket.destroyed) {
686
+ this.conn.sendEnvelope({
687
+ version: PROTOCOL_VERSION,
688
+ controllerId: this.controllerId,
689
+ workerId: this.workerId,
690
+ id: crypto.randomUUID(),
691
+ seq: this.conn.nextSeq,
692
+ type: "local_input",
693
+ payload: {
694
+ taskId: this.currentTaskId ?? undefined,
695
+ textSummary: event.text.slice(0, 100),
696
+ },
697
+ }).catch(() => {});
698
+ }
699
+ }
700
+ return { action: "continue" };
701
+ });
702
+
703
+ // 监听 model_select / thinking_level_select:会话内切换模型/思考级别后刷新主控状态
704
+ this.pi.on("model_select", async () => {
705
+ this.sendModelChanged();
706
+ });
707
+
708
+ this.pi.on("thinking_level_select", async () => {
709
+ this.sendModelChanged();
710
+ });
711
+
712
+ this.pi.on("tool_call", async (event) => {
713
+ const gen = this.activeGeneration;
714
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
715
+ this.staleCallbacksIgnored++;
716
+ return undefined;
717
+ }
718
+ if (FORBIDDEN_WORKER_TOOLS.has(event.toolName)) {
719
+ return { block: true, reason: "Worker 不允许递归派发子代理" };
720
+ }
721
+ return undefined;
722
+ });
723
+
724
+ // 监听 tool_execution_start
725
+ this.pi.on("tool_execution_start", async (event: ToolExecutionStartEvent) => {
726
+ const gen = this.activeGeneration;
727
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
728
+ this.staleCallbacksIgnored++;
729
+ return;
730
+ }
731
+ // 如果此前记录了 candidate,但模型又调用了其他工具,则候选失效
732
+ if (event.toolName !== "worker_report" && this.currentCandidate) {
733
+ this.candidateInvalidated = true;
734
+ this.currentCandidate = null;
735
+ }
736
+
737
+ // 上报活动状态
738
+ if (this.conn && !this.conn.socket.destroyed) {
739
+ this.conn.sendEnvelope({
740
+ version: PROTOCOL_VERSION,
741
+ controllerId: this.controllerId,
742
+ workerId: this.workerId,
743
+ id: crypto.randomUUID(),
744
+ seq: this.conn.nextSeq,
745
+ type: "activity",
746
+ payload: {
747
+ state: "busy",
748
+ toolName: String(event.toolName).slice(0, 256),
749
+ },
750
+ }).catch(() => {});
751
+ }
752
+ });
753
+
754
+ // 监听 agent_settled:回执最终确认与后续消息触发
755
+ this.pi.on("agent_settled", async (_event: any, ctx: ExtensionContext) => {
756
+ const gen = this.activeGeneration;
757
+ // 旧会话晚到的 settled:代际失效或不存在当前上下文 → 直接忽略。
758
+ // 绝不比较 ctx 身份:Pi 每个事件都新建 ctx 对象,跨事件身份比较恒为真,
759
+ // 若用身份比较会把真实回执静默丢弃。
760
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
761
+ this.staleCallbacksIgnored++;
762
+ return;
763
+ }
764
+ // 本事件的 ctx 就是当前会话上下文:记录下来,供后续路径继续使用
765
+ this.currentContext = ctx;
766
+
767
+ // 1. 确认候选回执
768
+ if (this.currentCandidate && !this.candidateInvalidated) {
769
+ this.taskHasReported = true;
770
+ if (this.conn && !this.conn.socket.destroyed) {
771
+ this.conn.sendEnvelope({
772
+ version: PROTOCOL_VERSION,
773
+ controllerId: this.controllerId,
774
+ workerId: this.workerId,
775
+ taskId: this.currentTaskId ?? undefined,
776
+ revision: this.currentRevision,
777
+ id: crypto.randomUUID(),
778
+ seq: this.conn.nextSeq,
779
+ type: "report_committed",
780
+ payload: {
781
+ taskId: this.currentTaskId ?? "",
782
+ revision: this.currentRevision,
783
+ runId: this.currentRunId,
784
+ report: this.currentCandidate,
785
+ },
786
+ }).catch(() => {});
787
+ }
788
+ this.currentCandidate = null;
789
+ } else if (!this.taskHasReported && this.currentTaskId) {
790
+ // 模型结束了但没有提交过回执
791
+ if (this.conn && !this.conn.socket.destroyed) {
792
+ this.conn.sendEnvelope({
793
+ version: PROTOCOL_VERSION,
794
+ controllerId: this.controllerId,
795
+ workerId: this.workerId,
796
+ taskId: this.currentTaskId,
797
+ revision: this.currentRevision,
798
+ id: crypto.randomUUID(),
799
+ seq: this.conn.nextSeq,
800
+ type: "report_missing",
801
+ payload: {
802
+ taskId: this.currentTaskId,
803
+ revision: this.currentRevision,
804
+ runId: this.currentRunId,
805
+ },
806
+ }).catch(() => {});
807
+ }
808
+ }
809
+
810
+ // 2. 检查是否有排队消息在独立 tick 派发
811
+ setImmediate(() => {
812
+ // 续段跨越 tick:重新校验代际与当前上下文是否存在,
813
+ // 绝不比较 ctx 身份,也绝不把旧会话消息注入新会话
814
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
815
+ this.staleCallbacksIgnored++;
816
+ return;
817
+ }
818
+ if (
819
+ this.followupQueue.length > 0 &&
820
+ this.currentContext &&
821
+ this.currentContext.isIdle() &&
822
+ !this.currentContext.hasPendingMessages()
823
+ ) {
824
+ const next = this.shiftQueueItem(gen);
825
+ if (next) {
826
+ this.dispatchUserMessage(next.message, ctx, gen);
827
+ }
828
+ } else if (
829
+ this.followupQueue.length === 0 &&
830
+ this.currentContext?.isIdle() &&
831
+ !this.currentContext.hasPendingMessages() &&
832
+ this.conn && !this.conn.socket.destroyed
833
+ ) {
834
+ this.conn.sendEnvelope({
835
+ version: PROTOCOL_VERSION,
836
+ controllerId: this.controllerId,
837
+ workerId: this.workerId,
838
+ taskId: this.currentTaskId ?? undefined,
839
+ revision: this.currentRevision,
840
+ id: crypto.randomUUID(),
841
+ seq: this.conn.nextSeq,
842
+ type: "activity",
843
+ payload: { state: "idle" },
844
+ }).catch(() => {});
845
+ }
846
+ });
847
+ });
848
+ }
849
+
850
+ private registerWorkerReportTool(): void {
851
+ this.pi.registerTool({
852
+ name: "worker_report",
853
+ label: "Worker Report",
854
+ description: "向主控端提交进度进展、提问、阻碍问题或最终交付报告。当完成任务时调用此工具。",
855
+ executionMode: "sequential",
856
+ parameters: Type.Object({
857
+ kind: Type.Union([
858
+ Type.Literal("progress"),
859
+ Type.Literal("question"),
860
+ Type.Literal("blocked"),
861
+ Type.Literal("result"),
862
+ Type.Literal("failed"),
863
+ ], { description: "回执种类:progress(进展), question(向主控提问), blocked(遇到阻碍无法继续), result(任务完成交付), failed(执行失败)" }),
864
+ summary: Type.String({ description: "简短明了的任务进展、结论或原因摘要" }),
865
+ changedFiles: Type.Optional(Type.Array(Type.String(), { description: "本次任务修改或创建的文件列表" })),
866
+ validation: Type.Optional(Type.Array(Type.Object({
867
+ command: Type.String({ description: "执行的验证命令" }),
868
+ outcome: Type.Union([Type.Literal("passed"), Type.Literal("failed"), Type.Literal("not_run")]),
869
+ note: Type.Optional(Type.String()),
870
+ }), { description: "运行过的测试与验证记录" })),
871
+ unresolved: Type.Optional(Type.Array(Type.String(), { description: "尚未解决的遗留问题" })),
872
+ question: Type.Optional(Type.String({ description: "如果向主控提问,写明具体问题" })),
873
+ }),
874
+ execute: async (_toolCallId: string, params: any) => {
875
+ const gen = this.activeGeneration;
876
+ // 会话已切换/已关闭:不得写候选、不得向连接发送任何信封
877
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
878
+ this.staleCallbacksIgnored++;
879
+ return {
880
+ content: [{ type: "text", text: "会话已切换,回执已作废" }],
881
+ details: params,
882
+ };
883
+ }
884
+ if (jsonByteLength(params) > MAX_REPORT_SIZE) {
885
+ throw new Error(`回执超过 64 KiB 限制: ${ProtocolErrorCode.PAYLOAD_TOO_LARGE}`);
886
+ }
887
+ let report: WorkerReportPayload;
888
+ try {
889
+ report = validateWorkerReport(params);
890
+ } catch (err: unknown) {
891
+ if (
892
+ err instanceof ProtocolValidationError &&
893
+ err.code === ProtocolErrorCode.PAYLOAD_TOO_LARGE
894
+ ) {
895
+ throw new Error(`回执超过 64 KiB 限制: ${ProtocolErrorCode.PAYLOAD_TOO_LARGE}`);
896
+ }
897
+ throw err;
898
+ }
899
+
900
+ if (report.kind === "progress") {
901
+ if (this.conn && !this.conn.socket.destroyed) {
902
+ this.conn.sendEnvelope({
903
+ version: PROTOCOL_VERSION,
904
+ controllerId: this.controllerId,
905
+ workerId: this.workerId,
906
+ taskId: this.currentTaskId ?? undefined,
907
+ revision: this.currentRevision,
908
+ id: crypto.randomUUID(),
909
+ seq: this.conn.nextSeq,
910
+ type: "activity",
911
+ payload: {
912
+ state: "busy",
913
+ toolName: `worker_report [progress: ${report.summary}]`.slice(0, 256),
914
+ },
915
+ }).catch(() => {});
916
+ }
917
+ return {
918
+ content: [{ type: "text", text: `已记录阶段进展: ${report.summary}` }],
919
+ details: report,
920
+ };
921
+ }
922
+
923
+ // 终结类报告:提交候选前再次校验代际;失效则绝不写 currentCandidate、绝不发信封
924
+ if (!this.isCurrentGeneration(gen) || !this.currentContext) {
925
+ this.staleCallbacksIgnored++;
926
+ return {
927
+ content: [{ type: "text", text: "会话已切换,回执已作废" }],
928
+ details: params,
929
+ };
930
+ }
931
+ this.currentCandidate = report;
932
+ this.candidateInvalidated = false;
933
+
934
+ if (this.conn && !this.conn.socket.destroyed) {
935
+ this.conn.sendEnvelope({
936
+ version: PROTOCOL_VERSION,
937
+ controllerId: this.controllerId,
938
+ workerId: this.workerId,
939
+ taskId: this.currentTaskId ?? undefined,
940
+ revision: this.currentRevision,
941
+ id: crypto.randomUUID(),
942
+ seq: this.conn.nextSeq,
943
+ type: "report_candidate",
944
+ payload: {
945
+ taskId: this.currentTaskId ?? "",
946
+ revision: this.currentRevision,
947
+ runId: this.currentRunId,
948
+ report,
949
+ },
950
+ }).catch(() => {});
951
+ }
952
+
953
+ return {
954
+ content: [
955
+ {
956
+ type: "text",
957
+ text: `回执候选 (${report.kind}) 已记录。本轮不要继续调用其他工具,等待主控端审核。`,
958
+ },
959
+ ],
960
+ details: report,
961
+ };
962
+ },
963
+ });
964
+ }
965
+
966
+ private registerWorkerCommands(): void {
967
+ this.pi.registerCommand("worker-status", {
968
+ description: "查看当前 Worker 受控状态",
969
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
970
+ const status = this.conn ? "已连接到 Controller" : "未连接 / 已脱钩";
971
+ ctx.ui.notify(
972
+ `Worker ID: ${this.workerId} | 任务: ${this.currentTaskId || "无"} | 管道: ${status}`,
973
+ "info",
974
+ );
975
+ },
976
+ });
977
+
978
+ this.pi.registerCommand("worker-detach", {
979
+ description: "脱离主控端管理,转为本地独立执行",
980
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
981
+ const confirmed = await ctx.ui.confirm(
982
+ "脱钩确认",
983
+ "脱离主控后,主控将无法再自动派发或验收,当前窗口转为完全独立运行。是否确认?",
984
+ );
985
+ if (confirmed) {
986
+ this.isDetached = true;
987
+ if (this.conn) {
988
+ this.conn.destroy();
989
+ this.conn = null;
990
+ }
991
+ ctx.ui.notify("已脱钩主控,当前终端为独立会话", "warning");
992
+ }
993
+ },
994
+ });
995
+ }
996
+ }