@aiti-ai/ext-shared 0.0.0-stage → 0.1.11

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 (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/agent-accounts.test.mjs +227 -0
  4. package/agent-accounts.ts +324 -0
  5. package/agent-capability-contract.test.mjs +129 -0
  6. package/agent-interaction.test.mjs +194 -0
  7. package/agent-interaction.ts +340 -0
  8. package/agent-launch.test.mjs +262 -0
  9. package/agent-spawn-env.test.mjs +169 -0
  10. package/agent-spawn-env.ts +548 -0
  11. package/aiti-editor-inject.mjs +49 -0
  12. package/backend-queue.test.mjs +336 -0
  13. package/backend-queue.ts +469 -0
  14. package/blob-save-route.ts +128 -0
  15. package/cbc-model-catalog.ts +86 -0
  16. package/check-client.mjs +273 -0
  17. package/check-ext-globals.mjs +144 -0
  18. package/controlled-login-dialog.mjs +270 -0
  19. package/controlled-login.mjs +398 -0
  20. package/controlled-login.test.mjs +466 -0
  21. package/convert-saveas.test.mjs +39 -0
  22. package/convert-saveas.ts +170 -0
  23. package/copy-client-bundle.mjs +39 -0
  24. package/cursor-cli-store.ts +377 -0
  25. package/dedupe-fetch.test.mjs +71 -0
  26. package/dedupe-fetch.ts +58 -0
  27. package/deploy-commit.mjs +52 -0
  28. package/dev-pack.mjs +246 -0
  29. package/dock-icons.ts +127 -0
  30. package/esbuild-bin.test.mjs +53 -0
  31. package/esbuild-bin.ts +66 -0
  32. package/exec-async.test.mjs +86 -0
  33. package/exec-async.ts +179 -0
  34. package/ext-display-names.ts +91 -0
  35. package/ext-entry-contracts.test.mjs +131 -0
  36. package/ext-float-dock-core.test.mjs +348 -0
  37. package/ext-float-dock-core.ts +783 -0
  38. package/ext-float-dock-lite.ts +52 -0
  39. package/ext-float-dock.test.mjs +286 -0
  40. package/ext-float-dock.ts +740 -0
  41. package/ext-icons-deploy.mjs +24 -0
  42. package/ext-lazy.test.mjs +186 -0
  43. package/ext-lazy.tsx +183 -0
  44. package/ext-model-state.test.mjs +272 -0
  45. package/ext-model-state.ts +324 -0
  46. package/ext-protocol.mjs +113 -0
  47. package/ext-protocol.test.mjs +88 -0
  48. package/ext-session-usage.test.mjs +219 -0
  49. package/ext-session-usage.ts +507 -0
  50. package/external-cli-governance.ts +153 -0
  51. package/git-ops-client/api.mjs +56 -0
  52. package/git-ops-client/branch-panel.tsx +987 -0
  53. package/git-ops-client/i18n.mjs +328 -0
  54. package/host-tools-allow.test.mjs +46 -0
  55. package/host-tools-allow.ts +84 -0
  56. package/icons/alert.svg +1 -0
  57. package/icons/bookmark.svg +1 -0
  58. package/icons/bot.svg +1 -0
  59. package/icons/chart-column.svg +1 -0
  60. package/icons/check-circle.svg +1 -0
  61. package/icons/clipboard-list.svg +1 -0
  62. package/icons/clock.svg +1 -0
  63. package/icons/coffee.svg +1 -0
  64. package/icons/edit.svg +1 -0
  65. package/icons/eye.svg +1 -0
  66. package/icons/git-branch.svg +1 -0
  67. package/icons/git-commit-horizontal.svg +1 -0
  68. package/icons/globe.svg +1 -0
  69. package/icons/history.svg +1 -0
  70. package/icons/import.svg +1 -0
  71. package/icons/inbox.svg +1 -0
  72. package/icons/key-round.svg +1 -0
  73. package/icons/layout-grid.svg +1 -0
  74. package/icons/mail.svg +1 -0
  75. package/icons/message-circle.svg +1 -0
  76. package/icons/message-square.svg +1 -0
  77. package/icons/meter-vertical.svg +1 -0
  78. package/icons/mic.svg +1 -0
  79. package/icons/monitor.svg +1 -0
  80. package/icons/pen-line.svg +1 -0
  81. package/icons/plug.svg +1 -0
  82. package/icons/radio-dot.svg +1 -0
  83. package/icons/radio.svg +1 -0
  84. package/icons/refresh.svg +1 -0
  85. package/icons/rocket.svg +1 -0
  86. package/icons/search.svg +1 -0
  87. package/icons/shield.svg +1 -0
  88. package/icons/sparkles.svg +1 -0
  89. package/icons/square-kanban.svg +1 -0
  90. package/icons/terminal.svg +1 -0
  91. package/icons/users.svg +1 -0
  92. package/icons/volume-2.svg +1 -0
  93. package/icons/wand.svg +1 -0
  94. package/icons/wrench.svg +1 -0
  95. package/icons/x-circle.svg +1 -0
  96. package/icons/x.svg +1 -0
  97. package/ignore-semantics.ts +76 -0
  98. package/lazy-loading-metrics.mjs +61 -0
  99. package/new-session-cwd.test.mjs +389 -0
  100. package/new-session-cwd.ts +253 -0
  101. package/open-viewer-window.ts +65 -0
  102. package/overlay-back-client.test.mjs +123 -0
  103. package/overlay-back-client.ts +87 -0
  104. package/package.json +65 -4
  105. package/pi-fork-rpc/README.md +12 -0
  106. package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
  107. package/pi-fork-rpc/cli-resolve.ts +79 -0
  108. package/pi-fork-rpc/remote-queue.test.mjs +100 -0
  109. package/pi-fork-rpc/remote-queue.ts +140 -0
  110. package/pi-fork-rpc/spec.ts +106 -0
  111. package/pi-fork-rpc/wire.test.mjs +260 -0
  112. package/pi-fork-rpc/wire.ts +367 -0
  113. package/popup-anchor.ts +45 -0
  114. package/provider-priority-contract.test.mjs +55 -0
  115. package/reconcile-deps.mjs +41 -0
  116. package/reload-instances.mjs +60 -0
  117. package/seed-tool.test.mjs +95 -0
  118. package/seed-tool.ts +88 -0
  119. package/session-recycle.ts +109 -0
  120. package/shared-copy-sync.test.mjs +115 -0
  121. package/soffice-locate.ts +171 -0
  122. package/soffice-panel.ts +239 -0
  123. package/sync-dir.mjs +91 -0
  124. package/sync-dir.test.mjs +101 -0
  125. package/sync-gate.test.mjs +93 -0
  126. package/sync-mirror.test.mjs +85 -0
  127. package/task-list.test.mjs +91 -0
  128. package/task-list.ts +118 -0
  129. package/test-rm-rf.mjs +33 -0
  130. package/ui-dialogs.test.mjs +198 -0
  131. package/ui-dialogs.ts +310 -0
@@ -0,0 +1,260 @@
1
+ /**
2
+ * wire.test — pi-fork-rpc 共享层线协议宿主 / extension_ui 桥接纯函数测试。
3
+ * 拆分自旧 aiti-pi-agent/pi-rpc-spawn.test.mjs 的公共部分(不依赖任何 fork 语义)。
4
+ */
5
+
6
+ import assert from "node:assert/strict";
7
+ import test from "node:test";
8
+ import { PassThrough } from "node:stream";
9
+ import { spawn } from "node:child_process";
10
+ import { RpcChildHost, lineReader, shutdownChild, toInteractionRequest, toExtensionUIResponse } from "./wire.ts";
11
+
12
+ function fakeChild() {
13
+ const stdout = new PassThrough();
14
+ const stderr = new PassThrough();
15
+ const writes = [];
16
+ const stdin = new PassThrough();
17
+ stdin.on("data", (c) => writes.push(Buffer.from(c).toString("utf8")));
18
+ const listeners = new Map();
19
+ return {
20
+ stdout,
21
+ stderr,
22
+ stdin,
23
+ writes,
24
+ frames: () => writes.join("").split("\n").filter(Boolean).map((l) => JSON.parse(l)),
25
+ exitCode: null,
26
+ kill: () => true,
27
+ once: (ev, fn) => {
28
+ if (!listeners.has(ev)) listeners.set(ev, []);
29
+ listeners.get(ev).push(fn);
30
+ return this;
31
+ },
32
+ emit: (ev, ...args) => {
33
+ for (const fn of listeners.get(ev) ?? []) fn(...args);
34
+ },
35
+ _listeners: listeners,
36
+ };
37
+ }
38
+
39
+ function feed(host, obj) {
40
+ host.child.stdout.write(JSON.stringify(obj) + "\n");
41
+ }
42
+
43
+ async function later(ms = 20) {
44
+ await new Promise((r) => setTimeout(r, ms));
45
+ }
46
+
47
+ test("wire:request/response id 关联 + 错误帧 reject", async () => {
48
+ const child = fakeChild();
49
+ const h = new RpcChildHost(child);
50
+ const p = h.request({ type: "get_state" });
51
+ await later();
52
+ assert.equal(child.frames()[0].type, "get_state");
53
+ feed(h, { id: "r1", type: "response", command: "?", success: true, data: { ok: 1 } });
54
+ assert.deepEqual(await p, { ok: 1 });
55
+
56
+ const p2 = h.request({ type: "get_state" });
57
+ await later();
58
+ feed(h, { id: "r2", type: "response", command: "get_state", success: false, error: "boom" });
59
+ await assert.rejects(p2, /boom/);
60
+ });
61
+
62
+ test("wire:非 response 帧默认原样透传 emit", async () => {
63
+ const child = fakeChild();
64
+ const h = new RpcChildHost(child);
65
+ const events = [];
66
+ h.subscribe((e) => events.push(e));
67
+ feed(h, { type: "agent_start" });
68
+ feed(h, { type: "message_end", message: { role: "assistant", content: [] } });
69
+ await later();
70
+ assert.equal(events[0].type, "agent_start");
71
+ assert.equal(events[1].type, "message_end");
72
+ });
73
+
74
+ test("wire:进程 exit → pending reject + session_backend_dead 事件", async () => {
75
+ const child = fakeChild();
76
+ const h = new RpcChildHost(child);
77
+ const events = [];
78
+ h.subscribe((e) => events.push(e));
79
+ const p = h.request({ type: "abort" });
80
+ await later();
81
+ child.emit("exit", 137);
82
+ await assert.rejects(p, /dead/);
83
+ assert.equal(events.find((e) => e.type === "session_backend_dead")?.reason, "process exited (137)");
84
+ });
85
+
86
+ // ---- 加固回归(审查 docs/pi-fork-rpc-review-findings.md 实证项)---------------------
87
+
88
+ test("wire:跨 chunk 的多字节字符整行解码不损坏(审查 P0-1 回归)", async () => {
89
+ const pt = new PassThrough();
90
+ const lines = [];
91
+ lineReader(pt, (l) => lines.push(l));
92
+ // 「标」= E6 A0 87、「题」= E9 A2 98:在「标」的 3 字节中间切开
93
+ pt.write('{"title":"');
94
+ pt.write(Buffer.from([0xe6, 0xa0]));
95
+ pt.write(Buffer.from([0x87, 0xe9, 0xa2, 0x98]));
96
+ pt.write('"}\n');
97
+ await later();
98
+ assert.ok(lines[0]?.includes("标题"), `跨块解码应完整,got=${JSON.stringify(lines[0])}`);
99
+ });
100
+
101
+ test("lineReader:超长行触发 onOverflow 并停止处理(审查 P1-6 回归)", async () => {
102
+ const pt = new PassThrough();
103
+ const lines = [];
104
+ let overflowSize = 0;
105
+ lineReader(pt, (l) => lines.push(l), { maxLineBytes: 64, onOverflow: (n) => (overflowSize = n) });
106
+ pt.write(Buffer.from("a".repeat(100))); // 无换行超限
107
+ await later();
108
+ pt.write('{"x":1}\n'); // 超限后不再处理
109
+ await later();
110
+ assert.ok(overflowSize >= 64, "应触发 onOverflow");
111
+ assert.equal(lines.length, 0, "超限后不再分发");
112
+ });
113
+
114
+ test("wire:行超限 → markDead(RpcChildHost 接线)", async () => {
115
+ const child = fakeChild();
116
+ const h = new RpcChildHost(child, { maxLineBytes: 64 });
117
+ const events = [];
118
+ h.subscribe((e) => events.push(e));
119
+ child.stdout.write(Buffer.from("a".repeat(100)));
120
+ await later();
121
+ assert.equal(events.find((e) => e.type === "session_backend_dead")?.reason.includes("overflow"), true);
122
+ assert.equal(h.aliveFlag, false);
123
+ });
124
+
125
+ test("wire:单个 listener 抛错不漏帧、不裸抛(审查 P0-3 回归)", async () => {
126
+ const child = fakeChild();
127
+ const h = new RpcChildHost(child);
128
+ const got = [];
129
+ let boom = null;
130
+ h.subscribe(() => { throw new Error("listener boom"); });
131
+ h.subscribe((e) => got.push(e));
132
+ child.stdout.write(JSON.stringify({ type: "agent_start" }) + "\n");
133
+ await later();
134
+ assert.equal(got.length, 1, "第二个 listener 应照常收到帧");
135
+ assert.equal(got[0].type, "agent_start");
136
+ });
137
+
138
+ test("wire:stdout 流 error → markDead(审查 P0-2 回归)", async () => {
139
+ const child = fakeChild();
140
+ const h = new RpcChildHost(child);
141
+ const events = [];
142
+ h.subscribe((e) => events.push(e));
143
+ child.stdout.emit("error", Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }));
144
+ await later();
145
+ assert.equal(events.find((e) => e.type === "session_backend_dead")?.reason.includes("stdout error"), true);
146
+ assert.equal(h.aliveFlag, false);
147
+ });
148
+
149
+ test("wire:request 超时 reject + 响应/死亡清定时器(审查 P1-4 回归)", async () => {
150
+ const child = fakeChild();
151
+ const h = new RpcChildHost(child);
152
+ await assert.rejects(
153
+ h.request({ type: "get_state" }, { timeoutMs: 20 }),
154
+ /\[rpc-child\] timeout: get_state after 20ms/,
155
+ );
156
+ // 正常响应路径不受超时影响
157
+ const p = h.request({ type: "get_state" }, { timeoutMs: 5_000 });
158
+ await later();
159
+ feed(h, { id: "r2", type: "response", command: "get_state", success: true, data: { ok: 1 } });
160
+ assert.deepEqual(await p, { ok: 1 });
161
+ });
162
+
163
+ test("wire:死亡时挂起超时定时器一并清理(无泄漏)", async () => {
164
+ const child = fakeChild();
165
+ const h = new RpcChildHost(child);
166
+ const p = h.request({ type: "get_state" }, { timeoutMs: 60_000 });
167
+ await later();
168
+ child.emit("exit", 0);
169
+ await assert.rejects(p, /dead/);
170
+ // 若定时器未清,60s 后会多一次 reject(pending 已清,无副作用)——此处仅回归 reject 路径
171
+ });
172
+
173
+ test("shutdownChild:SIGTERM → destroy 三流(真实子进程冒烟)", async () => {
174
+ const child = spawn("node", ["-e", "setInterval(()=>{},1000)"]);
175
+ await later(80);
176
+ const t0 = Date.now();
177
+ await shutdownChild(child, 120);
178
+ assert.ok(child.signalCode !== null || child.exitCode !== null, "子进程应已退出");
179
+ assert.ok(Date.now() - t0 < 900, "grace 后应快速收尾");
180
+ assert.equal(child.stdout.destroyed, true);
181
+ assert.equal(child.stdin.destroyed, true);
182
+ });
183
+
184
+ // ---- extension_ui ⇄ interaction_request 桥接纯函数 --------------------------------
185
+
186
+ test("toInteractionRequest:open_url 真实帧形状(instructions 字段)→ prompt 投影", () => {
187
+ const ir = toInteractionRequest({
188
+ type: "extension_ui_request", id: "ui-8", method: "open_url",
189
+ url: "https://auth.x/oa2/authorize", launchUrl: "http://127.0.0.1:1/l", instructions: "在浏览器完成授权",
190
+ });
191
+ assert.equal(ir.kind, "open_url");
192
+ assert.equal(ir.toolName, "extension_ui.open_url");
193
+ assert.equal(ir.prompt, "在浏览器完成授权");
194
+ assert.equal(ir.url, "https://auth.x/oa2/authorize");
195
+ assert.equal(ir.launchUrl, "http://127.0.0.1:1/l");
196
+ });
197
+
198
+ test("toInteractionRequest:select(含 optionDetails description)→ ask_user 事件", () => {
199
+ const ir = toInteractionRequest({
200
+ type: "extension_ui_request", id: "b", method: "select", title: "t", options: ["x", "y"],
201
+ optionDetails: [{}, { description: "便宜" }],
202
+ });
203
+ assert.equal(ir.kind, "ask_user");
204
+ assert.equal(ir.questions[0].options[1].description, "便宜");
205
+ });
206
+
207
+ test("toExtensionUIResponse:select 无答案(decline)→ cancelled;纯函数直测", () => {
208
+ assert.deepEqual(
209
+ toExtensionUIResponse({ type: "extension_ui_request", id: "a", method: "select", title: "t", options: ["x"] }, { action: "decline" }),
210
+ { type: "extension_ui_response", id: "a", cancelled: true },
211
+ );
212
+ const ir = toInteractionRequest({ type: "extension_ui_request", id: "b", method: "select", title: "t", options: ["x"] });
213
+ assert.equal(ir.kind, "ask_user");
214
+ });
215
+
216
+ test("toExtensionUIResponse:select accept 带答案 → value 帧;confirm 三态;input/editor", () => {
217
+ const sel = toExtensionUIResponse(
218
+ { type: "extension_ui_request", id: "s", method: "select", title: "t", options: ["x"] },
219
+ { action: "accept", answers: { t: "x" } },
220
+ );
221
+ assert.deepEqual(sel, { type: "extension_ui_response", id: "s", value: "x" });
222
+ // confirm:accept(无答案=批准按钮路径)→ confirmed true;answers 选「取消」→ false;decline → cancelled
223
+ assert.deepEqual(
224
+ toExtensionUIResponse({ type: "extension_ui_request", id: "c1", method: "confirm", title: "删除?", message: "不可撤销" }, { action: "accept" }),
225
+ { type: "extension_ui_response", id: "c1", confirmed: true },
226
+ );
227
+ assert.deepEqual(
228
+ toExtensionUIResponse({ type: "extension_ui_request", id: "c2", method: "confirm", title: "删除?", message: "不可撤销" }, { action: "accept", answers: { "删除?\n不可撤销": "取消" } }),
229
+ { type: "extension_ui_response", id: "c2", confirmed: false },
230
+ );
231
+ assert.deepEqual(
232
+ toExtensionUIResponse({ type: "extension_ui_request", id: "c3", method: "confirm", title: "t", message: "m" }, { action: "decline", message: "不要" }),
233
+ { type: "extension_ui_response", id: "c3", cancelled: true },
234
+ );
235
+ // confirm 防御(fail-closed):answers 非空但未命中问题 key → 不再默认 confirmed true
236
+ assert.deepEqual(
237
+ toExtensionUIResponse({ type: "extension_ui_request", id: "c4", method: "confirm", title: "删除?", message: "不可撤销" }, { action: "accept", answers: { "别的问题": "确认" } }),
238
+ { type: "extension_ui_response", id: "c4", confirmed: false },
239
+ );
240
+ // input/editor:answers 文本 → value;decline → cancelled
241
+ assert.deepEqual(
242
+ toExtensionUIResponse({ type: "extension_ui_request", id: "i1", method: "input", title: "会话名" }, { action: "accept", answers: { "会话名": "my session" } }),
243
+ { type: "extension_ui_response", id: "i1", value: "my session" },
244
+ );
245
+ assert.deepEqual(
246
+ toExtensionUIResponse({ type: "extension_ui_request", id: "e1", method: "editor", title: "" }, { action: "decline" }),
247
+ { type: "extension_ui_response", id: "e1", cancelled: true },
248
+ );
249
+ });
250
+
251
+ test("toExtensionUIResponse:notify/setWidget 等单向方法 → null(无需响应)", () => {
252
+ assert.equal(
253
+ toExtensionUIResponse({ type: "extension_ui_request", id: "n", method: "notify", message: "hello" }, { action: "accept" }),
254
+ null,
255
+ );
256
+ assert.equal(
257
+ toExtensionUIResponse({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "autoresearch" }, { action: "accept" }),
258
+ null,
259
+ );
260
+ });
@@ -0,0 +1,367 @@
1
+ /**
2
+ * wire.ts — JSONL RPC 线协议宿主(载体无关)。
3
+ *
4
+ * 拆自 aiti-pi-agent 的 pi-rpc-spawn.ts:子进程管理 / request-response id 关联 /
5
+ * 事件扇出 / 死亡上报 + extension_ui_request ⇄ interaction_request 帧桥接。
6
+ * 本层**不含任何 fork 语义**(命令映射 / 能力面 / 生命周期收口由各扩展 handle 负责)。
7
+ */
8
+
9
+ import type { ChildProcess } from "node:child_process";
10
+ import { StringDecoder } from "node:string_decoder";
11
+
12
+ /** 缺省单行字节上限(MCP stdio transport 同款 10MB):无换行的超长行视为子进程失控。 */
13
+ export const DEFAULT_MAX_LINE_BYTES = 10 * 1024 * 1024;
14
+
15
+ /** 控制面命令缺省超时(get_state/set_model/… 等快命令;prompt/compact/bash 等长轮次命令不设)。 */
16
+ export const RPC_CTRL_TIMEOUT_MS = 30_000;
17
+
18
+ export interface LineReaderOptions {
19
+ /** 单行字节上限(换行前累积量),超出触发 onOverflow 并停止处理后续数据。缺省 10MB。 */
20
+ maxLineBytes?: number;
21
+ /** 行超限回调(宿主侧应 markDead——协议流已不可信)。 */
22
+ onOverflow?: (size: number) => void;
23
+ }
24
+
25
+ /**
26
+ * 逐行读取 stdout 流(JSONL);返回取消函数。
27
+ * 字节累积、按 `\n` 切 Buffer 后整行 utf8 解码(MCP ReadBuffer 同款)——
28
+ * 逐 chunk `Buffer.toString` 会把跨 chunk 的多字节字符解码成 U+FFFD(中文必踩)。
29
+ */
30
+ export function lineReader(
31
+ stream: NodeJS.ReadableStream,
32
+ onLine: (line: string) => void,
33
+ opts?: LineReaderOptions,
34
+ ): () => void {
35
+ const maxLineBytes = opts?.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES;
36
+ const onOverflow = opts?.onOverflow;
37
+ let buf: Buffer = Buffer.alloc(0);
38
+ let overflowed = false;
39
+ const onData = (c: Buffer | string) => {
40
+ if (overflowed) return;
41
+ const chunk = typeof c === "string" ? Buffer.from(c, "utf8") : c;
42
+ buf = buf.length === 0 ? chunk : Buffer.concat([buf, chunk]);
43
+ let idx: number;
44
+ while ((idx = buf.indexOf(0x0a)) >= 0) {
45
+ const line = buf.subarray(0, idx).toString("utf8").trim();
46
+ buf = buf.subarray(idx + 1);
47
+ if (line) onLine(line);
48
+ }
49
+ if (buf.length > maxLineBytes) {
50
+ overflowed = true;
51
+ onOverflow?.(buf.length);
52
+ }
53
+ };
54
+ stream.on("data", onData);
55
+ return () => {
56
+ stream.off("data", onData);
57
+ };
58
+ }
59
+
60
+ export type HostEventListener = (event: Record<string, unknown>) => void;
61
+
62
+ interface PendingRequest {
63
+ resolve(v: unknown): void;
64
+ reject(e: Error): void;
65
+ timer?: NodeJS.Timeout;
66
+ }
67
+
68
+ /**
69
+ * 载体无关的 RPC 子进程宿主:
70
+ * - 进程管理(stdin 写帧 / stdout 逐行读 / stderr 日志 / exit·error 杀尾)
71
+ * - request id 关联(command 附带 `id`,`response` 帧按 id 回拨;控制面命令可带超时)
72
+ * - 事件扇出(非 response 帧 → onFrame 分发给子类 → emit 给监听者;逐监听器异常隔离)
73
+ * - 死亡上报(session_backend_dead)
74
+ *
75
+ * 子类通过覆写 onFrame 注入语义(extension_ui / host_tool / ready 握手 / 状态帧…),
76
+ * 通过 protected request / writeRaw 发命令。
77
+ */
78
+ export class RpcChildHost {
79
+ protected child: ChildProcess;
80
+ protected pending = new Map<string, PendingRequest>();
81
+ protected seq = 0;
82
+ protected aliveFlag = true;
83
+ private listeners = new Set<HostEventListener>();
84
+ private detachReader: (() => void) | null = null;
85
+
86
+ constructor(child: ChildProcess, opts?: { maxLineBytes?: number }) {
87
+ this.child = child;
88
+ this.detachReader = lineReader(child.stdout!, (line) => this.dispatchLine(line), {
89
+ ...(opts?.maxLineBytes ? { maxLineBytes: opts.maxLineBytes } : {}),
90
+ onOverflow: (size) => this.markDead(`stdout line overflow (${size} bytes > ${opts?.maxLineBytes ?? DEFAULT_MAX_LINE_BYTES})`),
91
+ });
92
+ const stderrDecoder = new StringDecoder("utf8");
93
+ child.stderr?.on("data", (c: Buffer | string) => {
94
+ const text = (typeof c === "string" ? c : stderrDecoder.write(c)).trim();
95
+ if (text) console.log(`[rpc-child] ${text.slice(0, 500)}`);
96
+ });
97
+ // 三个流都必须挂 error 监听:子进程被杀/管道断裂时流上抛 ECONNRESET/EPIPE,
98
+ // 没有监听器 = unhandled 'error' event = 宿主进程崩溃(MCP stdio transport 同款防御)。
99
+ child.stdout?.on("error", (err: Error) => this.markDead(`stdout error: ${err.message}`));
100
+ child.stderr?.on("error", (err: Error) => console.log(`[rpc-child] stderr error: ${err.message}`));
101
+ child.stdin?.on("error", (err: Error) => console.log(`[rpc-child] stdin error: ${err.message}`));
102
+ child.once("exit", (code) => this.markDead(`process exited (${code ?? "signal"})`));
103
+ child.once("error", (err) => this.markDead(`process error: ${err.message}`));
104
+ }
105
+
106
+ emit(event: Record<string, unknown>): void {
107
+ for (const l of this.listeners) {
108
+ try {
109
+ l(event);
110
+ } catch (e) {
111
+ // 逐监听器隔离:一个订阅者抛错不得漏帧给其余订阅者,更不得沿流 data 回调裸抛崩进程
112
+ console.error(`[rpc-child] listener error: ${e instanceof Error ? e.message : String(e)}`);
113
+ }
114
+ }
115
+ }
116
+
117
+ subscribe(listener: HostEventListener): () => void {
118
+ this.listeners.add(listener);
119
+ return () => {
120
+ this.listeners.delete(listener);
121
+ };
122
+ }
123
+
124
+ /** 发命令并挂 id 关联(写 stdin;帧的 id 由本方法追加,勿重复传)。
125
+ * opts.timeoutMs:可选超时(控制面快命令用;prompt/compact/bash 等长轮次命令不设——
126
+ * 超时仅解除 pending 并 reject,不影响子进程继续跑)。 */
127
+ protected request<T = unknown>(command: Record<string, unknown>, opts?: { timeoutMs?: number }): Promise<T> {
128
+ if (!this.aliveFlag || !this.child.stdin?.writable) {
129
+ return Promise.reject(new Error("[rpc-child] not running"));
130
+ }
131
+ const id = `r${++this.seq}`;
132
+ return new Promise<T>((resolve, reject) => {
133
+ const pending: PendingRequest = { resolve: resolve as (v: unknown) => void, reject };
134
+ const timeoutMs = opts?.timeoutMs;
135
+ if (timeoutMs && timeoutMs > 0) {
136
+ const timer = setTimeout(() => {
137
+ this.pending.delete(id);
138
+ reject(new Error(`[rpc-child] timeout: ${String(command.type ?? "?")} after ${timeoutMs}ms`));
139
+ }, timeoutMs);
140
+ timer.unref?.();
141
+ pending.timer = timer;
142
+ }
143
+ this.pending.set(id, pending);
144
+ try {
145
+ this.child.stdin!.write(JSON.stringify({ ...command, id }) + "\n");
146
+ } catch (e) {
147
+ this.pending.delete(id);
148
+ if (pending.timer) clearTimeout(pending.timer);
149
+ reject(new Error(`[rpc-child] write failed: ${e instanceof Error ? e.message : String(e)}`));
150
+ }
151
+ });
152
+ }
153
+
154
+ /** 原样写帧(不回显追加 request id)——host_tool_result 等须回显请求帧的 id。 */
155
+ protected writeRaw(frame: Record<string, unknown>): void {
156
+ if (!this.aliveFlag || !this.child.stdin?.writable) return;
157
+ try {
158
+ this.child.stdin.write(JSON.stringify(frame) + "\n");
159
+ } catch {
160
+ // 写失败(子进程刚死):exit 事件会收尸 markDead
161
+ }
162
+ }
163
+
164
+ /** 行分发:response 按 id 回拨;其余交给子类 onFrame。 */
165
+ protected dispatchLine(line: string): void {
166
+ let msg: Record<string, unknown>;
167
+ try {
168
+ msg = JSON.parse(line) as Record<string, unknown>;
169
+ } catch {
170
+ return;
171
+ }
172
+ if (msg.type === "response" && typeof msg.id === "string") {
173
+ const p = this.pending.get(msg.id);
174
+ if (!p) return;
175
+ this.pending.delete(msg.id);
176
+ if (p.timer) clearTimeout(p.timer);
177
+ if (msg.success === true) p.resolve(msg.data);
178
+ else p.reject(new Error(String(msg.error ?? "request failed")));
179
+ return;
180
+ }
181
+ try {
182
+ this.onFrame(msg);
183
+ } catch (e) {
184
+ // 子类 onFrame 异常同样不得沿流 data 回调裸抛(emit 已隔离,此处兜子类自身逻辑)
185
+ console.error(`[rpc-child] onFrame error: ${e instanceof Error ? e.message : String(e)}`);
186
+ }
187
+ }
188
+
189
+ /** 子类覆写:非 response 帧的语义分发(默认原样透传 emit)。 */
190
+ protected onFrame(_msg: Record<string, unknown>): void {
191
+ this.emit(_msg);
192
+ }
193
+
194
+ protected markDead(reason: string): void {
195
+ if (!this.aliveFlag) return;
196
+ this.aliveFlag = false;
197
+ this.detachReader?.();
198
+ this.detachReader = null;
199
+ for (const p of this.pending.values()) {
200
+ if (p.timer) clearTimeout(p.timer);
201
+ p.reject(new Error(`[rpc-child] dead: ${reason}`));
202
+ }
203
+ this.pending.clear();
204
+ this.emit({ type: "session_backend_dead", reason });
205
+ }
206
+ }
207
+
208
+ // ============================================================================
209
+ // 子进程收尾(dispose 共用)
210
+ // ============================================================================
211
+
212
+ /** 子进程收尾:SIGTERM → graceMs(缺省 1s)→ SIGKILL → destroy 三流(释放句柄/事件循环;
213
+ * MCP stdio transport 同款阶梯 + 清理)。已死进程直接跳过信号、仅清流。幂等可重入。 */
214
+ export async function shutdownChild(child: ChildProcess, graceMs = 1_000): Promise<void> {
215
+ if (child.exitCode === null && child.signalCode === null) {
216
+ try { child.kill("SIGTERM"); } catch { /* 已死容错 */ }
217
+ await new Promise<void>((resolve) => {
218
+ const t = setTimeout(() => {
219
+ try { child.kill("SIGKILL"); } catch { /* 已死容错 */ }
220
+ resolve();
221
+ }, graceMs);
222
+ child.once("exit", () => {
223
+ clearTimeout(t);
224
+ resolve();
225
+ });
226
+ });
227
+ }
228
+ child.stdout?.destroy();
229
+ child.stderr?.destroy();
230
+ child.stdin?.destroy();
231
+ }
232
+
233
+ // ============================================================================
234
+ // extension_ui_request ⇄ interaction_request 桥接(通用帧转换,无 fork 语义)
235
+ // ============================================================================
236
+
237
+ /** fork 子进程 extension_ui_request 帧(select/confirm/input/editor/notify/...)。 */
238
+ export interface ExtensionUIRequest extends Record<string, unknown> {
239
+ type: "extension_ui_request";
240
+ id: string;
241
+ method: string;
242
+ }
243
+
244
+ /** 需要用户作答、要挂 pending 等响应的 UI 方法(其余为单向通知,透传即可)。 */
245
+ export const UI_METHODS_NEEDING_ANSWER = new Set(["select", "confirm", "input", "editor"]);
246
+
247
+ /**
248
+ * 把 extension_ui_request 投影为 pi-web 统一 interaction_request 事件
249
+ * (lib/session/types.ts InteractionRequestEvent)。
250
+ * select/confirm/input → kind "ask_user"(标准问题卡渲染);
251
+ * open_url → kind "open_url"(OAuth 登录专用卡:url/launchUrl 字段,单向无需作答);
252
+ * 其余(editor/notify/setStatus/...)→ kind "generic"(原始帧进 input)。
253
+ */
254
+ export function toInteractionRequest(req: ExtensionUIRequest): Record<string, unknown> {
255
+ const method = req.method;
256
+ if (method === "open_url") {
257
+ // fork 真实帧:{url, launchUrl, instructions}(instructions = 给用户的操作说明)
258
+ const promptText = [req.title, req.instructions].find((s) => typeof s === "string");
259
+ return {
260
+ type: "interaction_request",
261
+ requestId: req.id,
262
+ kind: "open_url",
263
+ toolName: "extension_ui.open_url",
264
+ ...(promptText ? { prompt: promptText } : {}),
265
+ ...(typeof req.url === "string" ? { url: req.url } : {}),
266
+ ...(typeof req.launchUrl === "string" ? { launchUrl: req.launchUrl } : {}),
267
+ input: req,
268
+ };
269
+ }
270
+ if (method === "select") {
271
+ const options = Array.isArray(req.options) ? req.options : [];
272
+ const details = Array.isArray(req.optionDetails) ? req.optionDetails : [];
273
+ return {
274
+ type: "interaction_request",
275
+ requestId: req.id,
276
+ kind: "ask_user",
277
+ toolName: "extension_ui.select",
278
+ prompt: typeof req.title === "string" ? req.title : undefined,
279
+ questions: [
280
+ {
281
+ question: typeof req.title === "string" ? req.title : "Select an option",
282
+ options: options.map((o, i) => ({
283
+ label: String(o),
284
+ ...(typeof (details[i] as { description?: unknown })?.description === "string"
285
+ ? { description: (details[i] as { description: string }).description }
286
+ : {}),
287
+ })),
288
+ },
289
+ ],
290
+ input: req,
291
+ };
292
+ }
293
+ if (method === "confirm") {
294
+ return {
295
+ type: "interaction_request",
296
+ requestId: req.id,
297
+ kind: "ask_user",
298
+ toolName: "extension_ui.confirm",
299
+ prompt: typeof req.title === "string" ? req.title : undefined,
300
+ questions: [
301
+ {
302
+ question: [req.title, req.message].filter((s) => typeof s === "string").join("\n") || "Confirm?",
303
+ options: [{ label: "确认" }, { label: "取消" }],
304
+ },
305
+ ],
306
+ input: req,
307
+ };
308
+ }
309
+ if (method === "input") {
310
+ return {
311
+ type: "interaction_request",
312
+ requestId: req.id,
313
+ kind: "ask_user",
314
+ toolName: "extension_ui.input",
315
+ prompt: typeof req.title === "string" ? req.title : undefined,
316
+ questions: [{ question: typeof req.title === "string" ? req.title : "Input" }],
317
+ input: req,
318
+ };
319
+ }
320
+ return {
321
+ type: "interaction_request",
322
+ requestId: req.id,
323
+ kind: "generic",
324
+ toolName: `extension_ui.${method}`,
325
+ input: req,
326
+ };
327
+ }
328
+
329
+ /**
330
+ * 把用户作答(InteractionAnswer)编回 extension_ui_response 帧
331
+ * (omp RpcExtensionUIResponse:{value} | {confirmed} | {cancelled:true})。
332
+ * 返回 null 表示该请求无需作答(单向通知类)。
333
+ */
334
+ export function toExtensionUIResponse(
335
+ req: ExtensionUIRequest,
336
+ answer: { action: "accept" | "decline"; answers?: Record<string, string | string[]>; message?: string },
337
+ ): Record<string, unknown> | null {
338
+ const method = req.method;
339
+ if (method === "select") {
340
+ if (answer.action === "decline") return { type: "extension_ui_response", id: req.id, cancelled: true };
341
+ const q = typeof req.title === "string" ? req.title : "Select an option";
342
+ const v = answer.answers?.[q];
343
+ return v === undefined
344
+ ? { type: "extension_ui_response", id: req.id, cancelled: true }
345
+ : { type: "extension_ui_response", id: req.id, value: Array.isArray(v) ? v[0] : v };
346
+ }
347
+ if (method === "input" || method === "editor") {
348
+ if (answer.action === "decline") return { type: "extension_ui_response", id: req.id, cancelled: true };
349
+ const q = typeof req.title === "string" ? req.title : method === "input" ? "Input" : "";
350
+ const v = answer.answers?.[q];
351
+ const value = (Array.isArray(v) ? v[0] : v) ?? answer.message ?? "";
352
+ return { type: "extension_ui_response", id: req.id, value };
353
+ }
354
+ if (method === "confirm") {
355
+ if (answer.action === "decline") return { type: "extension_ui_response", id: req.id, cancelled: true };
356
+ // select 卡渲染的确认/取消:按所选 label 判断;accept + 未选「取消」= confirmed
357
+ const q = [req.title, req.message].filter((s) => typeof s === "string").join("\n") || "Confirm?";
358
+ const v = answer.answers?.[q];
359
+ const picked = Array.isArray(v) ? v[0] : v;
360
+ // 防御(fail-closed):answers 非空但未命中问题 key(title 渲染漂移等)→ 视为未确认;
361
+ // 完全无 answers(前端批准按钮路径)保持 confirmed:true,不破坏既有契约。
362
+ const hasAnswers = !!answer.answers && Object.keys(answer.answers).length > 0;
363
+ const confirmed = picked !== undefined ? picked !== "取消" : !hasAnswers;
364
+ return { type: "extension_ui_response", id: req.id, confirmed };
365
+ }
366
+ return null; // notify/setStatus/setWidget/setTitle/open_url/... 单向,无需响应
367
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * _shared/popup-anchor.ts — 弹层固定定位公共小工具(零 react,构建期内联进各扩展 bundle)。
3
+ *
4
+ * 背景:左栏 sidebar-container(桌面端宽度动画 overflow:hidden)→ StackCell → DockBody
5
+ * 全链 overflow:hidden,absolute 锚定的弹层(下拉/菜单)在矮格/折叠格/栈底格一律被
6
+ * 祖先裁剪(弹层自身 getBoundingClientRect 仍在视口内 → 视口钳位兜底探测不到)。
7
+ * 出路 = 弹层一律 position:fixed 锚定触发器矩形——fixed 逃逸 overflow 裁剪;唯
8
+ * transform/filter 等祖先会成为 fixed 的 containing block,此时坐标须按其原点校正
9
+ * (fixedOrigin)。
10
+ */
11
+
12
+ /** 祖先是否构成 fixed containing block(CSS 常用子集:transform/perspective/filter、
13
+ * will-change 声明同类属性、contain 布局系取值)。 */
14
+ function isFixedContainingBlock(cs: CSSStyleDeclaration): boolean {
15
+ if (cs.transform !== "none" || cs.perspective !== "none" || cs.filter !== "none") return true;
16
+ if (/transform|perspective|filter/.test(cs.willChange || "")) return true;
17
+ const c = cs.contain;
18
+ return c === "strict" || c === "content" || c === "layout" || c === "paint";
19
+ }
20
+
21
+ /** el 最近 fixed-containing-block 祖先的原点(视口坐标;无 = {x:0,y:0})。
22
+ * fixed 弹层坐标 = 期望视口坐标 − 本值(无 transformed 祖先时即视口坐标)。 */
23
+ export function fixedOrigin(el: Element): { x: number; y: number } {
24
+ let n = el.parentElement;
25
+ while (n && n !== document.documentElement) {
26
+ try {
27
+ if (isFixedContainingBlock(getComputedStyle(n))) {
28
+ const r = n.getBoundingClientRect();
29
+ return { x: r.left, y: r.top };
30
+ }
31
+ } catch { /* ignore */ }
32
+ n = n.parentElement;
33
+ }
34
+ return { x: 0, y: 0 };
35
+ }
36
+
37
+ /** 视口内钳制(pad 内边距;宽/高超视口时贴 pad 对齐)。入参/返回均为视口坐标。 */
38
+ export function clampToViewport(left: number, top: number, width: number, height: number, pad = 8): { left: number; top: number } {
39
+ const vw = window.innerWidth;
40
+ const vh = window.innerHeight;
41
+ return {
42
+ left: Math.max(pad, Math.min(left, vw - pad - width)),
43
+ top: Math.max(pad, Math.min(top, Math.max(pad, vh - pad - height))),
44
+ };
45
+ }