@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
@@ -0,0 +1,561 @@
1
+ /**
2
+ * 传输层实现:Windows 命名管道、流式 UTF-8 JSONL 解析、背压、认证与去重
3
+ */
4
+
5
+ import * as net from "node:net";
6
+ import * as crypto from "node:crypto";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { StringDecoder } from "node:string_decoder";
10
+ import { EventEmitter } from "node:events";
11
+ import {
12
+ type Envelope,
13
+ type AckPayload,
14
+ type ErrorPayload,
15
+ MAX_FRAME_SIZE,
16
+ MAX_DEDUP_CACHE_SIZE,
17
+ MAX_CONTROL_DEDUP_SIZE,
18
+ MAX_SEND_BUFFER_BYTES,
19
+ MAX_ERROR_MESSAGE_SIZE,
20
+ MAX_ID_LENGTH,
21
+ DEFAULT_ACK_TIMEOUT_MS,
22
+ ProtocolErrorCode,
23
+ ProtocolValidationError,
24
+ validateEnvelope,
25
+ validatePayload,
26
+ } from "./protocol.js";
27
+
28
+ /**
29
+ * 生成平台相关的管道地址
30
+ */
31
+ export function getPipePath(id: string): string {
32
+ if (process.platform === "win32") {
33
+ return `\\\\.\\pipe\\pi-terminal-worker-${id}`;
34
+ }
35
+ return path.join(os.tmpdir(), `pi-worker-${id}.sock`);
36
+ }
37
+
38
+ /**
39
+ * 常数时间比较两个 Token (防时序侧信道反推)
40
+ */
41
+ export function timingSafeCompare(tokenA: string, tokenB: string): boolean {
42
+ if (typeof tokenA !== "string" || typeof tokenB !== "string") {
43
+ return false;
44
+ }
45
+ const bufA = Buffer.from(tokenA, "utf8");
46
+ const bufB = Buffer.from(tokenB, "utf8");
47
+ if (bufA.length !== bufB.length) {
48
+ return false;
49
+ }
50
+ return crypto.timingSafeEqual(bufA, bufB);
51
+ }
52
+
53
+ /**
54
+ * 快速计算载荷哈希,用于检测同一 ID 是否包含不同载荷
55
+ */
56
+ function hashPayload(payload: unknown): string {
57
+ return crypto
58
+ .createHash("sha256")
59
+ .update(JSON.stringify(payload ?? null))
60
+ .digest("hex");
61
+ }
62
+
63
+ interface PendingRequest {
64
+ resolve: (ack: AckPayload) => void;
65
+ reject: (err: Error) => void;
66
+ timer: NodeJS.Timeout;
67
+ }
68
+
69
+ interface CachedResponse {
70
+ payloadHash: string;
71
+ ack: AckPayload;
72
+ isControl: boolean;
73
+ }
74
+
75
+ /**
76
+ * 发送队列字节超限:并发写排队总字节超过 MAX_SEND_BUFFER_BYTES
77
+ */
78
+ export class SendBufferFullError extends Error {
79
+ public readonly code: ProtocolErrorCode = ProtocolErrorCode.QUEUE_BYTES_EXCEEDED;
80
+
81
+ constructor(
82
+ public readonly queuedBytes: number,
83
+ public readonly limitBytes: number,
84
+ ) {
85
+ super(
86
+ `发送队列字节超限: 已排队 ${queuedBytes} 字节,本次写入后超过上限 ${limitBytes} 字节: ${ProtocolErrorCode.QUEUE_BYTES_EXCEEDED}`,
87
+ );
88
+ this.name = "SendBufferFullError";
89
+ }
90
+ }
91
+
92
+ /**
93
+ * ACK 等待超时:投递结果未知 (不自动重发)
94
+ */
95
+ export class AckTimeoutError extends Error {
96
+ public readonly code: ProtocolErrorCode = ProtocolErrorCode.TIMEOUT;
97
+ public readonly deliveryUnknown = true;
98
+
99
+ constructor(
100
+ public readonly requestId: string,
101
+ timeoutMs: number,
102
+ ) {
103
+ super(`请求超时 (${timeoutMs}ms): ${ProtocolErrorCode.TIMEOUT} (req: ${requestId})`);
104
+ this.name = "AckTimeoutError";
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 相同 ID 的重复请求包含不同内容
110
+ */
111
+ export class DuplicateRequestMismatchError extends Error {
112
+ public readonly code: ProtocolErrorCode = ProtocolErrorCode.DUPLICATE_REQUEST_MISMATCH;
113
+
114
+ constructor(requestId: string) {
115
+ super(`相同 ID 的重复请求包含不同内容: ${ProtocolErrorCode.DUPLICATE_REQUEST_MISMATCH} (req: ${requestId})`);
116
+ this.name = "DuplicateRequestMismatchError";
117
+ }
118
+ }
119
+
120
+ /**
121
+ * 普通去重缓存已满 (控制类请求不受此限)
122
+ */
123
+ export class DedupFullError extends Error {
124
+ public readonly code: ProtocolErrorCode = ProtocolErrorCode.DEDUP_FULL;
125
+
126
+ constructor(requestId: string) {
127
+ super(`普通去重缓存已满 (${MAX_DEDUP_CACHE_SIZE} 条): ${ProtocolErrorCode.DEDUP_FULL} (req: ${requestId})`);
128
+ this.name = "DedupFullError";
129
+ }
130
+ }
131
+
132
+ /**
133
+ * JsonlConnection 包装单个 Socket,负责分帧、发送背压、去重与 ACK 匹配
134
+ */
135
+ export class JsonlConnection extends EventEmitter {
136
+ private decoder = new StringDecoder("utf8");
137
+ private buffer = "";
138
+ private pendingRequests = new Map<string, PendingRequest>();
139
+ /** 普通请求去重缓存 (容量 MAX_DEDUP_CACHE_SIZE,满则丢弃新缓存) */
140
+ private dedupCache = new Map<string, CachedResponse>();
141
+ /** 控制类请求 (abort/close/terminate 等) 独立去重额度 (容量 MAX_CONTROL_DEDUP_SIZE,FIFO 淘汰) */
142
+ private controlDedupCache = new Map<string, CachedResponse>();
143
+ private isDestroyed = false;
144
+ /** 协议校验失败后置位:立即停止处理后续数据帧 */
145
+ private protocolFailed = false;
146
+ private seqCounter = 0;
147
+ /** 最近收到的入站序号;生产连接启用后拒绝重复/倒退序号 */
148
+ private lastReceivedSeq = 0;
149
+ /** 串行化写链:保证 socket.write 按序执行 */
150
+ private writeChain: Promise<void> = Promise.resolve();
151
+ /** 当前排队中的发送字节数 (入队记账,写完成 finally 扣减) */
152
+ private queuedWriteBytes = 0;
153
+
154
+ constructor(
155
+ public readonly socket: net.Socket,
156
+ public readonly role: "controller" | "supervisor" | "worker",
157
+ private readonly enforceInboundSequence = false,
158
+ ) {
159
+ super();
160
+
161
+ this.socket.on("data", (chunk: Buffer) => this.handleData(chunk));
162
+ this.socket.on("error", (err: Error) => {
163
+ this.emitError(err);
164
+ });
165
+ this.socket.on("close", (hadError: boolean) => {
166
+ this.handleClose(hadError);
167
+ });
168
+ this.socket.on("end", () => {
169
+ this.emit("end");
170
+ });
171
+ }
172
+
173
+ /**
174
+ * emit error 的安全包装:EventEmitter 对未监听的 'error' 事件会直接抛出,
175
+ * 在无监听方时降级为 warn,避免协议违规/对端错误击穿主进程 (uncaughtException)。
176
+ * 有监听方时行为与直接 emit 完全一致。
177
+ */
178
+ private emitError(err: Error): void {
179
+ if (this.listenerCount("error") > 0) {
180
+ this.emit("error", err);
181
+ } else {
182
+ console.warn(`[Transport] 未处理的连接错误 (无 error 监听): ${err.message}`);
183
+ }
184
+ }
185
+
186
+ public get nextSeq(): number {
187
+ return ++this.seqCounter;
188
+ }
189
+
190
+ private handleData(chunk: Buffer): void {
191
+ if (this.isDestroyed || this.protocolFailed) return;
192
+
193
+ this.buffer += this.decoder.write(chunk);
194
+
195
+ // 检查缓冲区未分帧时累计长度是否超过单帧上限
196
+ if (this.buffer.length > MAX_FRAME_SIZE * 2) {
197
+ this.failProtocol(
198
+ new Error(`接收缓冲未分帧长度超过上限: ${ProtocolErrorCode.PAYLOAD_TOO_LARGE}`),
199
+ undefined,
200
+ );
201
+ return;
202
+ }
203
+
204
+ let lineEndIndex: number;
205
+ while ((lineEndIndex = this.buffer.indexOf("\n")) !== -1) {
206
+ if (this.protocolFailed) return;
207
+
208
+ let line = this.buffer.slice(0, lineEndIndex);
209
+ this.buffer = this.buffer.slice(lineEndIndex + 1);
210
+
211
+ if (line.endsWith("\r")) {
212
+ line = line.slice(0, -1);
213
+ }
214
+
215
+ if (line.trim().length === 0) {
216
+ continue;
217
+ }
218
+
219
+ if (Buffer.byteLength(line, "utf8") > MAX_FRAME_SIZE) {
220
+ this.failProtocol(
221
+ new Error(`帧字节数超过 1 MiB 限制: ${ProtocolErrorCode.PAYLOAD_TOO_LARGE}`),
222
+ undefined,
223
+ );
224
+ return;
225
+ }
226
+
227
+ // 先尽力从原始行提取 id/controllerId/workerId,校验失败时用于回送 error envelope
228
+ let parsedId: string | undefined;
229
+ let remoteControllerId = "unknown";
230
+ let remoteWorkerId = "unknown";
231
+ try {
232
+ const rawObj = JSON.parse(line);
233
+ if (rawObj && typeof rawObj === "object") {
234
+ const ro = rawObj as Record<string, unknown>;
235
+ if (typeof ro.id === "string" && ro.id.length > 0) parsedId = ro.id.slice(0, MAX_ID_LENGTH);
236
+ if (typeof ro.controllerId === "string" && ro.controllerId.length > 0) {
237
+ remoteControllerId = ro.controllerId.slice(0, MAX_ID_LENGTH);
238
+ }
239
+ if (typeof ro.workerId === "string" && ro.workerId.length > 0) {
240
+ remoteWorkerId = ro.workerId.slice(0, MAX_ID_LENGTH);
241
+ }
242
+ }
243
+ } catch {
244
+ // 解析失败由下方统一处理
245
+ }
246
+
247
+ try {
248
+ const rawObj = JSON.parse(line);
249
+ const envelope = validateEnvelope(rawObj);
250
+ if (this.enforceInboundSequence) {
251
+ if (envelope.seq <= this.lastReceivedSeq) {
252
+ throw new ProtocolValidationError(
253
+ ProtocolErrorCode.PROTOCOL_ERROR,
254
+ `入站 seq 必须严格递增: 当前 ${envelope.seq},上一条 ${this.lastReceivedSeq}: ${ProtocolErrorCode.PROTOCOL_ERROR}`,
255
+ );
256
+ }
257
+ this.lastReceivedSeq = envelope.seq;
258
+ }
259
+ envelope.payload = validatePayload(envelope.type, envelope.payload);
260
+ this.handleEnvelope(envelope);
261
+ } catch (err: unknown) {
262
+ const error =
263
+ err instanceof ProtocolValidationError
264
+ ? err
265
+ : new Error(
266
+ `协议解码错误: ${err instanceof Error ? err.message : String(err)}: ${ProtocolErrorCode.PROTOCOL_ERROR}`,
267
+ );
268
+ this.failProtocol(error, parsedId, remoteControllerId, remoteWorkerId);
269
+ return;
270
+ }
271
+ }
272
+ }
273
+
274
+ /**
275
+ * 协议失败统一出口:尽力向对端回送 error envelope,随后销毁连接并 emit error。
276
+ * 后续数据帧不再处理 (protocolFailed 立即置位)。
277
+ */
278
+ private failProtocol(
279
+ err: Error,
280
+ replyTo?: string,
281
+ remoteControllerId = "unknown",
282
+ remoteWorkerId = "unknown",
283
+ ): void {
284
+ if (this.protocolFailed) return;
285
+ this.protocolFailed = true;
286
+
287
+ const code: string =
288
+ err instanceof ProtocolValidationError ? err.code : ProtocolErrorCode.PROTOCOL_ERROR;
289
+ console.warn(`[Transport] 协议校验失败,连接将被销毁 (${code}): ${err.message}`);
290
+
291
+ const sendPromise: Promise<void> = replyTo
292
+ ? this.sendEnvelope({
293
+ version: 1,
294
+ controllerId: remoteControllerId,
295
+ workerId: remoteWorkerId,
296
+ id: crypto.randomUUID(),
297
+ replyTo: replyTo.slice(0, MAX_ID_LENGTH),
298
+ seq: this.nextSeq,
299
+ type: "error",
300
+ payload: {
301
+ code,
302
+ message: err.message.slice(0, MAX_ERROR_MESSAGE_SIZE),
303
+ },
304
+ } as Envelope).catch(() => {})
305
+ : Promise.resolve();
306
+
307
+ void sendPromise.finally(() => {
308
+ try {
309
+ this.socket.destroy();
310
+ } catch {
311
+ // 忽略关闭时的错误
312
+ }
313
+ });
314
+
315
+ this.emitError(err);
316
+ }
317
+
318
+ private handleEnvelope(envelope: Envelope): void {
319
+ // 如果是 ACK 响应,核对正在等待的 PendingRequest
320
+ if (envelope.type === "ack" && envelope.replyTo) {
321
+ const pending = this.pendingRequests.get(envelope.replyTo);
322
+ if (pending) {
323
+ clearTimeout(pending.timer);
324
+ this.pendingRequests.delete(envelope.replyTo);
325
+ pending.resolve(envelope.payload as AckPayload);
326
+ return;
327
+ }
328
+ }
329
+
330
+ // 如果是对端回复的 Error
331
+ if (envelope.type === "error" && envelope.replyTo) {
332
+ const pending = this.pendingRequests.get(envelope.replyTo);
333
+ if (pending) {
334
+ clearTimeout(pending.timer);
335
+ this.pendingRequests.delete(envelope.replyTo);
336
+ const errPayload = envelope.payload as ErrorPayload;
337
+ pending.reject(
338
+ new Error(`[${errPayload.code}] ${errPayload.message}`),
339
+ );
340
+ return;
341
+ }
342
+ }
343
+
344
+ // 触发普通消息事件
345
+ this.emit("message", envelope);
346
+ }
347
+
348
+ private handleClose(hadError: boolean): void {
349
+ this.isDestroyed = true;
350
+ for (const [id, pending] of this.pendingRequests.entries()) {
351
+ clearTimeout(pending.timer);
352
+ pending.reject(
353
+ new Error(
354
+ `连接已断开: ${ProtocolErrorCode.PEER_DISCONNECTED} (req: ${id})`,
355
+ ),
356
+ );
357
+ }
358
+ this.pendingRequests.clear();
359
+ this.emit("close", hadError);
360
+ }
361
+
362
+ /**
363
+ * 发送原始字符串,带背压保护:
364
+ * - 排队字节超过 MAX_SEND_BUFFER_BYTES 时抛 SendBufferFullError
365
+ * - 写串行化到 writeChain,settle-once,对端关闭时以 PEER_DISCONNECTED reject
366
+ */
367
+ public async writeRaw(data: string): Promise<void> {
368
+ if (this.isDestroyed || this.socket.destroyed) {
369
+ throw new Error(`无法发送数据: 连接已关闭 (${ProtocolErrorCode.PEER_DISCONNECTED})`);
370
+ }
371
+
372
+ const bytes = Buffer.byteLength(data, "utf8");
373
+ if (this.queuedWriteBytes + bytes > MAX_SEND_BUFFER_BYTES) {
374
+ throw new SendBufferFullError(this.queuedWriteBytes, MAX_SEND_BUFFER_BYTES);
375
+ }
376
+
377
+ this.queuedWriteBytes += bytes;
378
+ const task = this.writeChain.then(() => this.doWrite(data));
379
+ // 链本身吞掉错误,保证后续写不被前一个失败阻塞
380
+ this.writeChain = task.catch(() => {});
381
+ try {
382
+ await task;
383
+ } finally {
384
+ this.queuedWriteBytes -= bytes;
385
+ }
386
+ }
387
+
388
+ /**
389
+ * 单次实际写:settle-once,等待 drain 期间若 socket close/error 则以 PEER_DISCONNECTED reject,
390
+ * 并移除自己注册的监听,绝不永久挂起、不泄漏 listener
391
+ */
392
+ private doWrite(data: string): Promise<void> {
393
+ const socket = this.socket;
394
+ return new Promise<void>((resolve, reject) => {
395
+ let settled = false;
396
+ const cleanup = (): void => {
397
+ socket.off("drain", onDrain);
398
+ socket.off("close", onClose);
399
+ socket.off("error", onError);
400
+ };
401
+ const onDrain = (): void => {
402
+ if (settled) return;
403
+ settled = true;
404
+ cleanup();
405
+ resolve();
406
+ };
407
+ const onClose = (): void => {
408
+ if (settled) return;
409
+ settled = true;
410
+ cleanup();
411
+ reject(new Error(`对端连接已关闭: ${ProtocolErrorCode.PEER_DISCONNECTED}`));
412
+ };
413
+ const onError = (err: Error): void => {
414
+ if (settled) return;
415
+ settled = true;
416
+ cleanup();
417
+ reject(err);
418
+ };
419
+ const flushed = socket.write(data, "utf8", (err) => {
420
+ if (settled) return;
421
+ if (err) {
422
+ settled = true;
423
+ cleanup();
424
+ reject(err);
425
+ } else if (flushed) {
426
+ settled = true;
427
+ cleanup();
428
+ resolve();
429
+ }
430
+ });
431
+ if (!flushed) {
432
+ socket.on("drain", onDrain);
433
+ socket.on("close", onClose);
434
+ socket.on("error", onError);
435
+ }
436
+ });
437
+ }
438
+
439
+ /**
440
+ * 发送 Envelope 消息 (带换行符)
441
+ */
442
+ public async sendEnvelope(envelope: Envelope): Promise<void> {
443
+ const json = JSON.stringify(envelope);
444
+ if (Buffer.byteLength(json, "utf8") > MAX_FRAME_SIZE) {
445
+ throw new Error(`发送帧超过 1 MiB 限制: ${ProtocolErrorCode.PAYLOAD_TOO_LARGE}`);
446
+ }
447
+ await this.writeRaw(json + "\n");
448
+ }
449
+
450
+ /**
451
+ * 发送单向请求并等待 ACK
452
+ */
453
+ public async sendRequest(
454
+ envelope: Envelope,
455
+ timeoutMs: number = DEFAULT_ACK_TIMEOUT_MS,
456
+ ): Promise<AckPayload> {
457
+ if (this.isDestroyed) {
458
+ throw new Error(`连接已断开: ${ProtocolErrorCode.PEER_DISCONNECTED}`);
459
+ }
460
+
461
+ return new Promise<AckPayload>((resolve, reject) => {
462
+ const timer = setTimeout(() => {
463
+ this.pendingRequests.delete(envelope.id);
464
+ reject(new AckTimeoutError(envelope.id, timeoutMs));
465
+ }, timeoutMs);
466
+
467
+ this.pendingRequests.set(envelope.id, { resolve, reject, timer });
468
+
469
+ this.sendEnvelope(envelope).catch((err) => {
470
+ clearTimeout(timer);
471
+ this.pendingRequests.delete(envelope.id);
472
+ reject(err);
473
+ });
474
+ });
475
+ }
476
+
477
+ /**
478
+ * 检查请求去重:查表顺序普通表 → 控制表。
479
+ * 命中且正文哈希一致则返回缓存;不一致抛 DuplicateRequestMismatchError;
480
+ * 未命中且普通表已满时抛 DedupFullError (控制请求永不因容量被拒绝)。
481
+ */
482
+ public checkDedup(
483
+ requestId: string,
484
+ payload: unknown,
485
+ isControl: boolean = false,
486
+ ): CachedResponse | null {
487
+ const currentHash = hashPayload(payload);
488
+ const existing = this.dedupCache.get(requestId) ?? this.controlDedupCache.get(requestId);
489
+ if (existing) {
490
+ if (existing.payloadHash !== currentHash) {
491
+ throw new DuplicateRequestMismatchError(requestId);
492
+ }
493
+ return existing;
494
+ }
495
+
496
+ if (!isControl && this.dedupCache.size >= MAX_DEDUP_CACHE_SIZE) {
497
+ throw new DedupFullError(requestId);
498
+ }
499
+
500
+ return null;
501
+ }
502
+
503
+ /**
504
+ * 缓存处理完成的 ACK 结果。
505
+ * 控制请求写入独立控制表 (FIFO 淘汰最旧控制条目,保证 abort/close/terminate 永远有额度);
506
+ * 普通请求写普通表,满则丢弃缓存并 warn。
507
+ */
508
+ public recordDedup(
509
+ requestId: string,
510
+ payload: unknown,
511
+ ack: AckPayload,
512
+ isControl: boolean = false,
513
+ ): void {
514
+ const entry: CachedResponse = {
515
+ payloadHash: hashPayload(payload),
516
+ ack,
517
+ isControl,
518
+ };
519
+
520
+ if (isControl) {
521
+ if (this.controlDedupCache.size >= MAX_CONTROL_DEDUP_SIZE && !this.controlDedupCache.has(requestId)) {
522
+ const oldest = this.controlDedupCache.keys().next().value;
523
+ if (oldest !== undefined) {
524
+ this.controlDedupCache.delete(oldest);
525
+ }
526
+ }
527
+ this.controlDedupCache.set(requestId, entry);
528
+ return;
529
+ }
530
+
531
+ if (this.dedupCache.size >= MAX_DEDUP_CACHE_SIZE && !this.dedupCache.has(requestId)) {
532
+ console.warn(
533
+ `[Transport] 普通去重缓存已满 (${MAX_DEDUP_CACHE_SIZE} 条),丢弃新缓存: ${requestId}`,
534
+ );
535
+ return;
536
+ }
537
+ this.dedupCache.set(requestId, entry);
538
+ }
539
+
540
+ /**
541
+ * 去重容量统计 (便于测试与诊断)
542
+ */
543
+ public getDedupStats(): { normal: number; control: number; maxNormal: number; maxControl: number } {
544
+ return {
545
+ normal: this.dedupCache.size,
546
+ control: this.controlDedupCache.size,
547
+ maxNormal: MAX_DEDUP_CACHE_SIZE,
548
+ maxControl: MAX_CONTROL_DEDUP_SIZE,
549
+ };
550
+ }
551
+
552
+ public destroy(): void {
553
+ if (this.isDestroyed) return;
554
+ this.isDestroyed = true;
555
+ try {
556
+ this.socket.destroy();
557
+ } catch {
558
+ // 忽略关闭时的错误
559
+ }
560
+ }
561
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * 原生 UI 集成:状态栏、小部件与通知
3
+ */
4
+
5
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
6
+ import type { WorkerInstanceMetadata } from "./lifecycle.js";
7
+
8
+ /**
9
+ * 多 Worker 状态栏汇总计数。
10
+ * running/review/issue 三分类之和应等于 total(见 MultiWorkerCoordinator.getSummary)。
11
+ */
12
+ export interface WorkerSummaryCounts {
13
+ total: number;
14
+ running: number;
15
+ review: number;
16
+ issue: number;
17
+ }
18
+
19
+ /**
20
+ * 刷新状态栏中的单实例 Worker 状态(保留旧语义,供底层控制器/历史调用使用)
21
+ */
22
+ export function updateWorkerUiStatus(
23
+ ui: ExtensionUIContext | undefined,
24
+ instance: WorkerInstanceMetadata | null,
25
+ ): void {
26
+ if (!ui) return;
27
+
28
+ if (!instance || instance.lifecycleState === "none" || instance.lifecycleState === "closed") {
29
+ ui.setStatus("worker", undefined);
30
+ return;
31
+ }
32
+
33
+ const modelShort = instance.modelId ? ` (${instance.modelId})` : "";
34
+ const statusStr = `[Worker: ${instance.taskState} | rev ${instance.revision}${modelShort}]`;
35
+ ui.setStatus("worker", statusStr);
36
+ }
37
+
38
+ /**
39
+ * 刷新状态栏中的多 Worker 汇总(只展示计数,不展示单实例明细)。
40
+ *
41
+ * - 无实例时清除状态栏,避免残留过期文本。
42
+ * - 非交互模式(ctx.ui 缺失或 setStatus 不可用)安全降级为 no-op。
43
+ */
44
+ export function updateMultiWorkerUiStatus(
45
+ ui: ExtensionUIContext | undefined,
46
+ summary: WorkerSummaryCounts | null,
47
+ ): void {
48
+ if (!ui || typeof ui.setStatus !== "function") return;
49
+
50
+ if (!summary || summary.total <= 0) {
51
+ ui.setStatus("worker", undefined);
52
+ return;
53
+ }
54
+
55
+ ui.setStatus(
56
+ "worker",
57
+ `Workers ${summary.total} | running ${summary.running} | review ${summary.review} | issue ${summary.issue}`,
58
+ );
59
+ }
60
+
61
+ /**
62
+ * 空闲状态栏轮询默认间隔。
63
+ *
64
+ * 异步 socket 事件(report_committed、断连、退出)推进实例状态时,主 Pi 可能完全空闲,
65
+ * 既没有工具调用也没有 turn/agent 事件;仅靠事件刷新会让状态栏停留在旧值。
66
+ * 用短周期轮询覆盖这段空窗,只在会话活跃期间持有 ctx。
67
+ */
68
+ export const WORKER_STATUS_POLL_INTERVAL_MS = 1000;
69
+
70
+ /**
71
+ * 会话级状态栏轮询器。
72
+ *
73
+ * 生命周期由扩展入口显式管理:
74
+ * - `start(ui)` 在 `session_start` 调用,立即刷新一次并启动短周期定时器;
75
+ * - `stop()` 在 `session_shutdown` 调用,清除定时器并释放 ctx 引用;
76
+ * - 定时器 `unref()`,不阻止进程正常退出;
77
+ * - 非交互模式(ui 缺失或 setStatus 不可用)不启动定时器,安全降级为 no-op。
78
+ */
79
+ export class WorkerStatusBarPoller {
80
+ private timer: ReturnType<typeof setInterval> | null = null;
81
+ private ui: ExtensionUIContext | undefined;
82
+
83
+ constructor(
84
+ private readonly readSummary: () => WorkerSummaryCounts,
85
+ private readonly intervalMs: number = WORKER_STATUS_POLL_INTERVAL_MS,
86
+ ) {}
87
+
88
+ /** 会话是否仍在轮询状态栏(诊断/测试用) */
89
+ public get isRunning(): boolean {
90
+ return this.timer !== null;
91
+ }
92
+
93
+ /** 会话开始:持有 ctx 并在整个会话期间短周期刷新 */
94
+ public start(ui: ExtensionUIContext | undefined): void {
95
+ this.stop();
96
+ if (!ui || typeof ui.setStatus !== "function") return;
97
+ this.ui = ui;
98
+ this.refresh();
99
+ this.timer = setInterval(() => this.refresh(), this.intervalMs);
100
+ const timer = this.timer as unknown as { unref?: () => void };
101
+ if (typeof timer.unref === "function") timer.unref();
102
+ }
103
+
104
+ /** 立即刷新;传入事件 ctx.ui 时更新持有的 UI 引用(同一会话内 ctx 可能变化) */
105
+ public refresh(ui?: ExtensionUIContext): void {
106
+ if (ui) this.ui = ui;
107
+ if (!this.ui) return;
108
+ updateMultiWorkerUiStatus(this.ui, this.readSummary());
109
+ }
110
+
111
+ /** 会话结束 / 卸载:清除定时器,释放 ctx 并停止轮询 */
112
+ public stop(): void {
113
+ if (this.timer) {
114
+ clearInterval(this.timer);
115
+ this.timer = null;
116
+ }
117
+ this.ui = undefined;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 显示工作者相关的通知
123
+ */
124
+ export function notifyWorker(
125
+ ui: ExtensionUIContext | undefined,
126
+ message: string,
127
+ type: "info" | "warning" | "error" = "info",
128
+ ): void {
129
+ if (!ui) return;
130
+ ui.notify(message, type);
131
+ }