pi-web-ui 0.119.0 → 0.120.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 (136) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +803 -106
  6. package/dist/server/atomic-file.js +130 -5
  7. package/dist/server/bash-timeout.js +15 -0
  8. package/dist/server/bash-tool.js +68 -4
  9. package/dist/server/bg-servers.js +19 -13
  10. package/dist/server/canvas/canvas-dispatch.js +12 -1
  11. package/dist/server/client-state.js +56 -14
  12. package/dist/server/conversation-tool.js +3 -2
  13. package/dist/server/delegate-task.js +8 -8
  14. package/dist/server/device-center/group-router-runtime.js +2 -0
  15. package/dist/server/device-center/hub-upgrade.js +5 -10
  16. package/dist/server/dispatch-domain-handlers.js +96 -22
  17. package/dist/server/dispatch-plugin-handlers.js +10 -0
  18. package/dist/server/dsh/dsh-agent-service.js +9 -9
  19. package/dist/server/durable/durable-agent-service.js +1 -1
  20. package/dist/server/files-service.js +41 -19
  21. package/dist/server/fs-copy.js +93 -0
  22. package/dist/server/goal-review-gate.js +2 -2
  23. package/dist/server/index.js +15 -0
  24. package/dist/server/job-runner.js +345 -0
  25. package/dist/server/marker-service.js +42 -26
  26. package/dist/server/model-session.js +16 -0
  27. package/dist/server/phone-tool.js +167 -0
  28. package/dist/server/plan-mode.js +2 -2
  29. package/dist/server/plugin-api-catalog.js +1 -1
  30. package/dist/server/plugin-bundled.js +35 -28
  31. package/dist/server/plugin-installer.js +15 -0
  32. package/dist/server/plugin-manifest-validate.js +10 -0
  33. package/dist/server/plugin-materialize.js +161 -0
  34. package/dist/server/plugin-paths.js +60 -0
  35. package/dist/server/plugin-removal.js +16 -3
  36. package/dist/server/plugin-schedule.js +8 -7
  37. package/dist/server/plugin-secrets.js +7 -3
  38. package/dist/server/plugin-updater.js +2 -4
  39. package/dist/server/plugins.js +74 -38
  40. package/dist/server/preset-fields.js +9 -9
  41. package/dist/server/process-utils.js +11 -0
  42. package/dist/server/project-scripts.js +38 -0
  43. package/dist/server/prompt-composer.js +40 -21
  44. package/dist/server/protocol-version.js +1 -1
  45. package/dist/server/quick-ask.js +3 -0
  46. package/dist/server/remote-ssh-service.js +39 -0
  47. package/dist/server/scm-commitmsg.js +2 -1
  48. package/dist/server/serialize.js +8 -0
  49. package/dist/server/session-list-index.js +246 -0
  50. package/dist/server/session-list-scan.js +5 -0
  51. package/dist/server/session-parser.js +16 -0
  52. package/dist/server/settings-service.js +39 -6
  53. package/dist/server/subagent-budget.js +68 -0
  54. package/dist/server/subagent-evidence.js +297 -0
  55. package/dist/server/subagent-helpers.js +12 -0
  56. package/dist/server/subagent-ledger.js +401 -0
  57. package/dist/server/subagent-notify.js +6 -2
  58. package/dist/server/subagent-security-gate.js +2 -2
  59. package/dist/server/subagent-settle.js +71 -0
  60. package/dist/server/subagents.js +497 -79
  61. package/dist/server/tabs.js +8 -1
  62. package/dist/server/terminals.js +0 -1
  63. package/dist/server/tool-manager.js +90 -16
  64. package/dist/server/tool-prompts.js +5 -1
  65. package/dist/server/universal/universal-service.js +1 -1
  66. package/dist/server/universal/universal-session.js +45 -7
  67. package/dist/server/vision-bridge.js +2 -0
  68. package/dist/server/workspace-handle.js +119 -17
  69. package/dist/server/workspace-queue.js +37 -0
  70. package/docs/README.md +25 -23
  71. package/docs/architecture-plugins.md +23 -3
  72. package/docs/device-center.md +1 -1
  73. package/package.json +15 -3
  74. package/plugins/catalog.json +13 -2
  75. package/themes/bases/flow-base.css +7 -16
  76. package/web/dist/.build-assets.json +1 -1
  77. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  78. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  79. package/web/dist/assets/{CanvasStudio-2ydYbnpW.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  80. package/web/dist/assets/{CanvasStudio-DizWvRjn.js → CanvasStudio-DU6O3N4u.js} +3 -3
  81. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  82. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  83. package/web/dist/assets/{DeviceExecutionSettings-B7R9ONaq.js → DeviceExecutionSettings-qJzbI0Cf.js} +1 -1
  84. package/web/dist/assets/{DeviceGroups-DFU4cv5b.js → DeviceGroups-DPrQxW6B.js} +1 -1
  85. package/web/dist/assets/{DeviceGroups-DoaQcxKj.js → DeviceGroups-DoucyUjI.js} +1 -1
  86. package/web/dist/assets/{Dropdown-Btjt6Dzh.js → Dropdown-kj_NIj6e.js} +1 -1
  87. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  88. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  89. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  90. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  91. package/web/dist/assets/{GroupConversation-DwZZrMuE.js → GroupConversation-1-lsPO1f.js} +3 -3
  92. package/web/dist/assets/{GroupConversation-KOi8sa5b.js → GroupConversation-HeiyW_O_.js} +3 -3
  93. package/web/dist/assets/{GroupWorkItems-FqAL74bC.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  94. package/web/dist/assets/{HintTip-BOwPzBGR.js → HintTip-DFhoclDw.js} +1 -1
  95. package/web/dist/assets/{ModelConfigModal-DLIfWKdB.js → ModelConfigModal-D2Ro-jUZ.js} +2 -2
  96. package/web/dist/assets/{ModelConfigModal-B140kWrs.js → ModelConfigModal-DPc9R1pq.js} +2 -2
  97. package/web/dist/assets/{NativeCliPanel-BwiLazSq.js → NativeCliPanel-B108d697.js} +3 -3
  98. package/web/dist/assets/{NativeCliPanel-U0F_EfAU.js → NativeCliPanel-DupvGwQM.js} +3 -3
  99. package/web/dist/assets/{PiSetupModal-Dc7EQ4L3.js → PiSetupModal-D0HitBfd.js} +1 -1
  100. package/web/dist/assets/{ProviderOAuthControls-C3opmPhu.js → ProviderOAuthControls-BLKUEDde.js} +1 -1
  101. package/web/dist/assets/{SCMPanel-BBxQfmq9.js → SCMPanel-DDbWrUHR.js} +1 -1
  102. package/web/dist/assets/{SCMPanel-D2t97Vvr.js → SCMPanel-DluNcd2-.js} +1 -1
  103. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  104. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  105. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  106. package/web/dist/assets/{TermXterm-B6nCtO2b.js → TermXterm-SYc-MUk2.js} +1 -1
  107. package/web/dist/assets/{TerminalPanel-BWB3iSeN.js → TerminalPanel-CgA_lhVT.js} +1 -1
  108. package/web/dist/assets/{TerminalPanel-CAV2SosY.js → TerminalPanel-vdSIOPjD.js} +1 -1
  109. package/web/dist/assets/{TuiOverlayModal-B0jBPOMc.js → TuiOverlayModal-Cy1jYYIw.js} +1 -1
  110. package/web/dist/assets/{TuiOverlayModal-DGd6fzU6.js → TuiOverlayModal-kXY_4hV8.js} +1 -1
  111. package/web/dist/assets/{app-globals-CR8Ls9nE.js → app-globals-CBEscsYP.js} +9 -9
  112. package/web/dist/assets/{canvas-client-B0lkqTtF.js → canvas-client-Clsypfs6.js} +1 -1
  113. package/web/dist/assets/{desktop-BME3DkyE.js → desktop-C6D9a8HZ.js} +1 -1
  114. package/web/dist/assets/index-BD29OL9L.js +404 -0
  115. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  116. package/web/dist/assets/index-DB55rbKC.css +1 -0
  117. package/web/dist/assets/{plugin-host-CVgcdBOk.js → plugin-host-VWBcq-LQ.js} +1 -1
  118. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  119. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  120. package/web/dist/index.html +10 -10
  121. package/web/dist/sw.js +1 -1
  122. package/web/dist/assets/BgTasksModal-CVHW1lRA.js +0 -1
  123. package/web/dist/assets/BgTasksModal-t5hxW1H6.js +0 -1
  124. package/web/dist/assets/DeviceCenter-CPaZNBJE.js +0 -3
  125. package/web/dist/assets/DeviceCenter-DsVakAYR.js +0 -3
  126. package/web/dist/assets/FilePreview-QGQfD2lV.js +0 -2
  127. package/web/dist/assets/FilePreview-qez9walH.js +0 -2
  128. package/web/dist/assets/GlobalSearchModal-B-cnTDJ5.js +0 -1
  129. package/web/dist/assets/GlobalSearchModal-BvbafjdU.js +0 -1
  130. package/web/dist/assets/SettingsModal-BqPQNUwF.js +0 -34
  131. package/web/dist/assets/SettingsModal-l7eeV-Rq.js +0 -34
  132. package/web/dist/assets/index-BBAQNi6v.js +0 -404
  133. package/web/dist/assets/index-BYW9d61A.js +0 -404
  134. package/web/dist/assets/index-BYWs88H2.css +0 -1
  135. package/web/dist/assets/remote-ssh-client-DEpvwgqG.js +0 -1
  136. package/web/dist/assets/theme-DVa7Z5Zu.js +0 -1
@@ -0,0 +1,345 @@
1
+ /**
2
+ * 进程内后台任务注册表:`bash({ background: true })` 的落点。
3
+ *
4
+ * 为什么不直接调 `scripts/safe-exec.mjs`:发布包(npm / 桌面)不带 `scripts/`,而且那个脚本的
5
+ * `.pid/.state.json/.cursor` 三件套 + detach 守护进程,本质是补偿「调用方不常驻」。pi-web-ui 的
6
+ * server 本身就常驻,所以这里只保留真正有用的机件:
7
+ * - 跨平台启动目标(Windows 优先 Git Bash,回退 cmd.exe;POSIX 用 bash/sh)
8
+ * - 子进程 stdin 接空设备(交互确认 / pager / REPL 一律读到 EOF,永不阻塞)
9
+ * - 原始输出先落盘,只按需回显尾部(不淹没上下文)
10
+ * - 总时长硬超时 + 空闲看门狗(0 = 关闭)
11
+ * - 进程树终止复用 `server/process-utils.ts` 的 killPidTree(单源)
12
+ *
13
+ * 不做的:日志游标文件、守护进程巡检、孤儿 jobfile 状态机 —— 进程挂在 server 上,正常退出时由
14
+ * dispose() 杀整棵进程树收场;server 被强杀留下的子进程目前只能靠面板 / `killPidTree` 手动清,
15
+ * 没有启动扫描(刻意不做:宁可漏报也不能拿存盘 pid 去杀陌生进程)。
16
+ *
17
+ * 与 `scripts/safe-exec.mjs` 的分工:那个脚本吃 argv、带 `--shell-bin` / `.cmd` 垫片解析 /
18
+ * detach 守护进程,服务的对象是「调用方不常驻」的 CI 与人工终端;这里吃整行命令字符串,服务的
19
+ * 对象是常驻 server 内的 bash 工具。两者共用 `killPidTree` 单源,其余各自演进,不强行合体。
20
+ */
21
+ import { spawn } from "node:child_process";
22
+ import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, readSync, statSync } from "node:fs";
23
+ import { join, resolve } from "node:path";
24
+ import { killPidTree, pidAlive } from "./process-utils.js";
25
+ import { MAX_BACKGROUND_TIMEOUT_SEC } from "./bash-timeout.js";
26
+ const BASH_LIKE_SHELL = /(?:^|[\\/])(?:bash|sh|zsh|dash)(?:\.exe)?$/i;
27
+ const READ_WINDOW = 256 * 1024;
28
+ const TAIL_DEFAULT = 40;
29
+ const FIRST_OUTPUT_WAIT_MS = 600;
30
+ /** 面板行 taskId 前缀:`list()` 生成与 `killBackgroundServer()` 解析必须同源(别各写一份 "job:")。 */
31
+ export const JOB_TASK_PREFIX = "job:";
32
+ /** Windows 下优先真 Git Bash:模型写的 `&&` / POSIX 路径 / 管道才不会被 cmd.exe 认错。 */
33
+ export function pickJobShell() {
34
+ if (process.platform !== "win32")
35
+ return existsSync("/bin/bash") ? "/bin/bash" : "sh";
36
+ const candidates = [
37
+ process.env.PI_WEB_SHELL,
38
+ process.env.EXEPATH && join(process.env.EXEPATH, "usr", "bin", "bash.exe"),
39
+ "C:\\Program Files\\Git\\bin\\bash.exe",
40
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
41
+ ];
42
+ for (const candidate of candidates) {
43
+ if (candidate && BASH_LIKE_SHELL.test(candidate) && existsSync(candidate))
44
+ return candidate;
45
+ }
46
+ return process.env.ComSpec ?? "cmd.exe";
47
+ }
48
+ /** 整行命令 → spawn 目标。bash 类 shell 用 `-c`;cmd.exe 用 `/d /s /c`(不经 Node 的 shell:true,引号可预期)。 */
49
+ export function bootCommand(command, shell = pickJobShell()) {
50
+ if (process.platform !== "win32" || BASH_LIKE_SHELL.test(shell))
51
+ return { file: shell, args: ["-c", command] };
52
+ return { file: shell, args: ["/d", "/s", "/c", command] };
53
+ }
54
+ function slug(text) {
55
+ const cleaned = text.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
56
+ return (cleaned || "job").slice(0, 48);
57
+ }
58
+ function readTail(path, lines) {
59
+ if (lines <= 0 || !existsSync(path))
60
+ return "";
61
+ const size = statSync(path).size;
62
+ if (size === 0)
63
+ return "";
64
+ const window = Math.min(size, READ_WINDOW);
65
+ const fd = openSync(path, "r");
66
+ try {
67
+ const buffer = Buffer.allocUnsafe(window);
68
+ readSync(fd, buffer, 0, window, size - window);
69
+ const text = buffer.toString("utf8");
70
+ const all = text.split(/\r?\n/);
71
+ return all.slice(-lines).join("\n").trimEnd();
72
+ }
73
+ finally {
74
+ closeSync(fd);
75
+ }
76
+ }
77
+ function readFrom(path, offset) {
78
+ if (!existsSync(path))
79
+ return { text: "", next: offset };
80
+ const size = statSync(path).size;
81
+ if (size <= offset)
82
+ return { text: "", next: offset };
83
+ const start = Math.max(offset, size - READ_WINDOW);
84
+ const fd = openSync(path, "r");
85
+ try {
86
+ const buffer = Buffer.allocUnsafe(size - start);
87
+ readSync(fd, buffer, 0, size - start, start);
88
+ return { text: buffer.toString("utf8"), next: size };
89
+ }
90
+ finally {
91
+ closeSync(fd);
92
+ }
93
+ }
94
+ export class JobRegistry {
95
+ jobs = new Map();
96
+ seq = 0;
97
+ disposed = false;
98
+ logDir;
99
+ opts;
100
+ constructor(opts = {}) {
101
+ this.opts = opts;
102
+ this.logDir = opts.logDir ?? (() => join(process.cwd(), ".safe-exec", "jobs"));
103
+ }
104
+ get size() {
105
+ return this.jobs.size;
106
+ }
107
+ /** 起一个后台任务:立即返回快照,不等命令结束。 */
108
+ start(spec) {
109
+ if (this.disposed)
110
+ throw new Error("Background job registry is disposed");
111
+ const command = String(spec.command ?? "").trim();
112
+ if (!command)
113
+ throw new Error("background job requires a non-empty command");
114
+ const dir = resolve(this.logDir());
115
+ mkdirSync(dir, { recursive: true });
116
+ const id = `${Date.now().toString(36)}${(++this.seq).toString(36).padStart(2, "0")}`;
117
+ const label = (spec.label ?? command).replace(/\s+/g, " ").slice(0, 120);
118
+ const logPath = join(dir, `${id}-${slug(label)}.log`);
119
+ const stream = createWriteStream(logPath, { flags: "a" });
120
+ const target = bootCommand(command);
121
+ const child = spawn(target.file, target.args, {
122
+ cwd: resolve(spec.cwd),
123
+ stdio: ["ignore", "pipe", "pipe"],
124
+ windowsHide: true,
125
+ // POSIX 下建新进程组:kill(-pid) 能带走整棵树,避免漏杀子进程变孤儿;
126
+ // Windows 不用 detached(taskkill /T 负责整棵树,且 detached 会留下独立控制台窗口)。
127
+ ...(process.platform === "win32" ? {} : { detached: true }),
128
+ env: { ...process.env, PAGER: "cat", GIT_PAGER: "cat", CI: process.env.CI ?? "true" },
129
+ });
130
+ const now = Date.now();
131
+ const record = {
132
+ id,
133
+ child,
134
+ pid: child.pid ?? 0,
135
+ command,
136
+ label,
137
+ cwd: resolve(spec.cwd),
138
+ ...(spec.origin ? { origin: spec.origin } : {}),
139
+ since: now,
140
+ logPath,
141
+ stream,
142
+ timeoutSec: Math.min(Math.max(0, Math.floor(spec.timeoutSec ?? 0)), MAX_BACKGROUND_TIMEOUT_SEC),
143
+ idleTimeoutSec: Math.max(0, Math.floor(spec.idleTimeoutSec ?? 0)),
144
+ lastOutputAt: now,
145
+ timer: null,
146
+ state: "running",
147
+ exitCode: null,
148
+ killing: false,
149
+ readCursor: 0,
150
+ };
151
+ this.jobs.set(id, record);
152
+ stream.write(`[job] ${new Date(now).toISOString()} cwd=${record.cwd} timeout=${record.timeoutSec}s idle=${record.idleTimeoutSec}s\n$ ${command}\n`);
153
+ const onData = (chunk) => {
154
+ const text = String(chunk);
155
+ record.lastOutputAt = Date.now();
156
+ stream.write(text);
157
+ };
158
+ child.stdout?.on("data", onData);
159
+ child.stderr?.on("data", onData);
160
+ child.once("error", (error) => {
161
+ stream.write(`\n[job] SPAWN_ERROR ${error.message}\n`);
162
+ this.finish(record, null, "spawn-error");
163
+ });
164
+ child.once("close", (code) => {
165
+ const tailText = readTail(record.logPath, 40);
166
+ if (tailText)
167
+ stream.write(`${tailText.endsWith("\n") ? "" : "\n"}`);
168
+ this.finish(record, code, record.reason ?? "exit");
169
+ });
170
+ if (record.timeoutSec > 0 || record.idleTimeoutSec > 0) {
171
+ record.timer = setInterval(() => this.check(record), 1000);
172
+ record.timer.unref?.();
173
+ }
174
+ this.opts.onChange?.();
175
+ return this.snapshot(record);
176
+ }
177
+ check(record) {
178
+ if (record.state !== "running" || record.killing)
179
+ return;
180
+ const now = Date.now();
181
+ if (record.timeoutSec > 0 && now - record.since >= record.timeoutSec * 1000) {
182
+ record.reason = "timeout";
183
+ this.kill(record.id);
184
+ return;
185
+ }
186
+ if (record.idleTimeoutSec > 0 && now - record.lastOutputAt >= record.idleTimeoutSec * 1000) {
187
+ record.reason = "idle";
188
+ this.kill(record.id);
189
+ }
190
+ }
191
+ snapshot(record) {
192
+ return {
193
+ id: record.id,
194
+ pid: record.pid,
195
+ command: record.command,
196
+ label: record.label,
197
+ cwd: record.cwd,
198
+ ...(record.origin ? { origin: record.origin } : {}),
199
+ since: record.since,
200
+ logPath: record.logPath,
201
+ state: record.state,
202
+ exitCode: record.exitCode,
203
+ ...(record.reason ? { reason: record.reason } : {}),
204
+ };
205
+ }
206
+ finish(record, exitCode, reason) {
207
+ if (record.state === "exited")
208
+ return;
209
+ if (record.timer) {
210
+ clearInterval(record.timer);
211
+ record.timer = null;
212
+ }
213
+ record.state = "exited";
214
+ record.exitCode = exitCode;
215
+ record.reason = reason;
216
+ record.stream.write(`\n[job] ${reason} exit=${exitCode === null ? "null" : exitCode}\n`);
217
+ record.stream.end();
218
+ const snap = { ...this.snapshot(record), tail: readTail(record.logPath, 20) };
219
+ this.jobs.delete(record.id);
220
+ this.opts.onChange?.();
221
+ try {
222
+ this.opts.onExit?.(snap);
223
+ }
224
+ catch { }
225
+ }
226
+ list() {
227
+ return [...this.jobs.values()].filter((j) => j.state === "running").map((j) => this.snapshot(j));
228
+ }
229
+ get(id) {
230
+ const record = this.jobs.get(id);
231
+ return record ? this.snapshot(record) : undefined;
232
+ }
233
+ /** 非破坏性读尾部(只回尾部,避免上下文被日志淹没)。 */
234
+ tail(id, lines = TAIL_DEFAULT) {
235
+ const record = this.jobs.get(id);
236
+ if (!record)
237
+ return "";
238
+ return readTail(record.logPath, lines);
239
+ }
240
+ /** 增量读:默认推进游标,下一次只回新输出。 */
241
+ readNew(id, opts = {}) {
242
+ const record = this.jobs.get(id);
243
+ if (!record)
244
+ return "";
245
+ const { text, next } = readFrom(record.logPath, record.readCursor);
246
+ if (opts.advance !== false)
247
+ record.readCursor = next;
248
+ return text.trimEnd();
249
+ }
250
+ /** 起任务后等首屏输出:服务类命令通常几百毫秒内会打印 listening 行。 */
251
+ async awaitFirstOutput(id, ms = FIRST_OUTPUT_WAIT_MS) {
252
+ const record = this.jobs.get(id);
253
+ if (!record)
254
+ return "";
255
+ const deadline = Date.now() + Math.max(0, ms);
256
+ while (Date.now() < deadline) {
257
+ const text = readTail(record.logPath, TAIL_DEFAULT);
258
+ if (text)
259
+ return text;
260
+ if (record.state === "exited")
261
+ break;
262
+ await new Promise((r) => setTimeout(r, 100));
263
+ }
264
+ return readTail(record.logPath, TAIL_DEFAULT);
265
+ }
266
+ kill(id) {
267
+ const record = this.jobs.get(id);
268
+ if (!record)
269
+ return false;
270
+ if (record.state !== "running")
271
+ return false;
272
+ record.killing = true;
273
+ record.reason ??= "killed";
274
+ if (record.pid > 1) {
275
+ void killPidTree(record.pid)
276
+ .catch(() => { })
277
+ .finally(() => {
278
+ // taskkill 是异步的:close 事件到了 finish 会自然收场;
279
+ // 若子进程迟迟不退出(Windows 上偶发),兜底强制收场,避免面板上“关不了”。
280
+ setTimeout(() => {
281
+ const cur = this.jobs.get(id);
282
+ if (cur && cur.state === "running" && cur.killing) {
283
+ if (cur.pid > 1)
284
+ void killPidTree(cur.pid).catch(() => { });
285
+ setTimeout(() => {
286
+ const again = this.jobs.get(id);
287
+ if (again && again.state === "running")
288
+ this.finish(again, null, "killed");
289
+ }, 3000);
290
+ }
291
+ }, 4000)?.unref?.();
292
+ });
293
+ }
294
+ else
295
+ this.finish(record, null, "killed");
296
+ return true;
297
+ }
298
+ /** 同步语义的杀:发 kill 后轮询确认进程真死了才返回(给面板停止按钮用,有明确成功/失败)。 */
299
+ async killAndWait(id, timeoutMs = 8000) {
300
+ const record = this.jobs.get(id);
301
+ if (!record)
302
+ return { ok: false, exited: true, timedOut: false };
303
+ if (record.state !== "running")
304
+ return { ok: false, exited: true, timedOut: false };
305
+ this.kill(id);
306
+ const deadline = Date.now() + Math.max(1000, timeoutMs);
307
+ while (Date.now() < deadline) {
308
+ const cur = this.jobs.get(id);
309
+ if (!cur || cur.state !== "running")
310
+ return { ok: true, exited: true, timedOut: false };
311
+ if (cur.pid > 1 && !pidAlive(cur.pid)) {
312
+ const grace = Date.now() + 1500;
313
+ while (Date.now() < grace) {
314
+ const again = this.jobs.get(id);
315
+ if (!again || again.state !== "running")
316
+ return { ok: true, exited: true, timedOut: false };
317
+ await new Promise((r) => setTimeout(r, 200));
318
+ }
319
+ const still = this.jobs.get(id);
320
+ if (still && still.state === "running")
321
+ this.finish(still, null, "killed");
322
+ return { ok: true, exited: true, timedOut: false };
323
+ }
324
+ await new Promise((r) => setTimeout(r, 250));
325
+ }
326
+ return { ok: true, exited: false, timedOut: true };
327
+ }
328
+ killAll() {
329
+ const ids = [...this.jobs.keys()];
330
+ for (const id of ids)
331
+ this.kill(id);
332
+ return ids;
333
+ }
334
+ /** 服务器退出前收场:杀整棵进程树,别留孤儿。 */
335
+ dispose() {
336
+ this.disposed = true;
337
+ for (const record of this.jobs.values()) {
338
+ if (record.timer)
339
+ clearInterval(record.timer);
340
+ if (record.pid > 1)
341
+ void killPidTree(record.pid).catch(() => { });
342
+ }
343
+ this.jobs.clear();
344
+ }
345
+ }
@@ -10,29 +10,52 @@ export class MarkerService {
10
10
  overlayCache = new Map();
11
11
  constructor(host) {
12
12
  this.host = host;
13
- this.settings = this.host.stateStore.getMarkerSettings(this.host.clientId);
13
+ const loaded = this.host.stateStore.getMarkerSettings(this.host.clientId);
14
+ this.settings = { disabledMarkers: [...loaded.disabledMarkers] };
15
+ // 旧版有独立的「启用标记工具(全局)」开关:曾经全局关闭的用户迁移成「所有标记关闭」,
16
+ // 否则升级后标记会默默复活。写回后旧字段随 markers 整块覆盖消失。
17
+ if (this.host.stateStore.getLegacyMarkersGlobalOff?.() === true) {
18
+ this.setDisabledMarkers(this.visibleMarkerNames());
19
+ }
14
20
  }
15
21
  get current() {
16
- return { ...this.settings, disabledMarkers: [...this.settings.disabledMarkers] };
22
+ return { disabledMarkers: [...this.settings.disabledMarkers] };
17
23
  }
18
24
  get allMarkerNames() {
19
25
  return listMarkerNames();
20
26
  }
21
- isGlobalEnabled() {
22
- return this.settings.markersEnabled;
27
+ /** UI 可见(非别名)的标记名:全局开关只看这一组,别名跟随主标记。 */
28
+ visibleMarkerNames() {
29
+ const names = [];
30
+ for (const m of allMarkers()) {
31
+ if (m.isAlias || m.name === "suggest")
32
+ continue;
33
+ if (names.includes(m.name))
34
+ continue;
35
+ names.push(m.name);
36
+ }
37
+ return names;
23
38
  }
24
- isMarkerEnabled(name) {
25
- if (!this.settings.markersEnabled)
39
+ isNameEnabled(name) {
40
+ const disabled = this.settings.disabledMarkers;
41
+ if (disabled.includes(name))
26
42
  return false;
27
- if (name === "suggest" && this.settings.disabledMarkers.includes("action"))
43
+ if (name === "suggest" && disabled.includes("action"))
28
44
  return false;
29
- return !this.settings.disabledMarkers.includes(name);
45
+ return true;
46
+ }
47
+ /** 全局是否启用:没有独立开关,只要还剩任意一个标记开着就是启用;全关 = 全局关闭。 */
48
+ isGlobalEnabled() {
49
+ return this.visibleMarkerNames().some((name) => this.isNameEnabled(name));
50
+ }
51
+ isMarkerEnabled(name) {
52
+ return this.isNameEnabled(name) && this.isGlobalEnabled();
30
53
  }
31
54
  lang() {
32
55
  return this.host.lang?.() ?? "en";
33
56
  }
34
57
  buildGuidance() {
35
- if (!this.settings.markersEnabled)
58
+ if (!this.isGlobalEnabled())
36
59
  return "";
37
60
  const disabled = new Set(this.settings.disabledMarkers);
38
61
  const lines = collectGuidance(disabled, "en");
@@ -44,10 +67,14 @@ export class MarkerService {
44
67
  linesText +
45
68
  "\n──────────\n");
46
69
  }
47
- setEnabled(enabled) {
48
- this.settings.markersEnabled = !!enabled;
70
+ persist() {
49
71
  this.host.stateStore.saveMarkerSettings(this.host.clientId, this.settings);
50
72
  }
73
+ /** per-marker 开关的唯一写入口;全局状态由它派生,不再接受「全局开关」字段。 */
74
+ setDisabledMarkers(names) {
75
+ this.settings = { disabledMarkers: [...new Set(names)] };
76
+ this.persist();
77
+ }
51
78
  toggleMarker(name, enabled) {
52
79
  const set = new Set(this.settings.disabledMarkers);
53
80
  if (enabled) {
@@ -60,20 +87,7 @@ export class MarkerService {
60
87
  if (name === "action")
61
88
  set.add("suggest");
62
89
  }
63
- this.settings.disabledMarkers = [...set];
64
- this.host.stateStore.saveMarkerSettings(this.host.clientId, this.settings);
65
- }
66
- setAll(settings) {
67
- if (settings.markersEnabled !== undefined)
68
- this.settings.markersEnabled = !!settings.markersEnabled;
69
- if (settings.disabledMarkers !== undefined) {
70
- this.settings.disabledMarkers = [...new Set(settings.disabledMarkers)];
71
- }
72
- else {
73
- this.host.stateStore.saveMarkerSettings(this.host.clientId, this.settings);
74
- return;
75
- }
76
- this.host.stateStore.saveMarkerSettings(this.host.clientId, this.settings);
90
+ this.setDisabledMarkers([...set]);
77
91
  }
78
92
  memFor(convId, ns) {
79
93
  return this.memStore.get(convId)?.get(ns);
@@ -129,7 +143,7 @@ export class MarkerService {
129
143
  this.chains.delete(conversationId);
130
144
  }
131
145
  async processAssistantText(conversationId, text) {
132
- if (!text || !this.settings.markersEnabled)
146
+ if (!text || !this.isGlobalEnabled())
133
147
  return;
134
148
  const tokens = parseMarkers(text);
135
149
  if (tokens.length === 0)
@@ -215,6 +229,8 @@ export class MarkerService {
215
229
  }
216
230
  overlayLines(conversationId) {
217
231
  const lines = [];
232
+ if (!this.isGlobalEnabled())
233
+ return lines;
218
234
  for (const m of allMarkers()) {
219
235
  if (m.isAlias || m.name === "suggest")
220
236
  continue;
@@ -0,0 +1,16 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ /**
3
+ * Provider session id for calls that bypass `AgentSession`.
4
+ *
5
+ * The SDK only fills `options.sessionId` inside the agent loop; direct `ModelRuntime` callers
6
+ * must supply it themselves. Relay gateways (opencode / opencode-go) reject requests without the
7
+ * derived `x-opencode-session` routing header with `400 MissingSessionID`.
8
+ *
9
+ * Pass a stable seed for multi-turn conversations so follow-ups keep the same route and prompt
10
+ * cache; omit it for one-shot calls.
11
+ */
12
+ export function modelSessionId(seed) {
13
+ if (!seed)
14
+ return `pi-web-${randomUUID()}`;
15
+ return `pi-web-${createHash("sha256").update(seed).digest("hex").slice(0, 32)}`;
16
+ }
@@ -0,0 +1,167 @@
1
+ import { Type } from "typebox";
2
+ import { PHONE_TOOL_NAME } from "./tool-manager.js";
3
+ const PHONE_CALL_DEFAULT_TIMEOUT_MS = 20_000;
4
+ const PHONE_CALL_MIN_TIMEOUT_MS = 1_000;
5
+ const PHONE_CALL_MAX_TIMEOUT_MS = 60_000;
6
+ /** `op` 的枚举:schema 显式列出,运行时仍接受任意非空字符串(旧客户端兼容)。 */
7
+ export const PHONE_OPS = [
8
+ "status",
9
+ "dump",
10
+ "tap",
11
+ "long_press",
12
+ "swipe",
13
+ "input",
14
+ "key",
15
+ "launch",
16
+ "screenshot",
17
+ ];
18
+ export const PHONE_KEYS = ["back", "home", "recents", "notifications", "quickSettings"];
19
+ /** 每 op 的签名是参数文档的唯一归属地,字段本身不再写说明。 */
20
+ export const PHONE_OP_SIGNATURE = "status | dump(maxNodes?,maxDepth?) | tap(x,y) | long_press(x,y,durationMs?) | " +
21
+ "swipe(x1,y1,x2,y2,durationMs?) | input(text) | key(back|home|recents|notifications|quickSettings) | " +
22
+ "launch(packageName) | screenshot(maxWidth?)";
23
+ const PHONE_ARG_KEYS = [
24
+ "x",
25
+ "y",
26
+ "x1",
27
+ "y1",
28
+ "x2",
29
+ "y2",
30
+ "durationMs",
31
+ "text",
32
+ "packageName",
33
+ "maxWidth",
34
+ "maxNodes",
35
+ "maxDepth",
36
+ ];
37
+ export function collectPhoneArgs(params) {
38
+ const args = {};
39
+ for (const key of PHONE_ARG_KEYS) {
40
+ if (params[key] !== undefined)
41
+ args[key] = params[key];
42
+ }
43
+ return args;
44
+ }
45
+ export function normalizePhoneCallTimeoutMs(value) {
46
+ const n = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : PHONE_CALL_DEFAULT_TIMEOUT_MS;
47
+ return Math.min(PHONE_CALL_MAX_TIMEOUT_MS, Math.max(PHONE_CALL_MIN_TIMEOUT_MS, n));
48
+ }
49
+ export function formatPhoneCallResult(result) {
50
+ if (typeof result === "string")
51
+ return result.length > 0 ? result : "(empty)";
52
+ if (result === undefined || result === null)
53
+ return "(no result)";
54
+ try {
55
+ return JSON.stringify(result, null, 2) ?? String(result);
56
+ }
57
+ catch {
58
+ return String(result);
59
+ }
60
+ }
61
+ export function formatPhoneError(op, error) {
62
+ return [
63
+ `phone "${op}" failed: ${error}`,
64
+ `phone "${op}" 失败:${error}`,
65
+ 'Next: op:"status" tells you whether the phone has the accessibility service on. If it is off, ask the user to enable it in system settings instead of retrying.',
66
+ '下一步:op:"status" 能看出手机有没有开启无障碍服务;没开就请用户在系统设置里开启,不要反复重试。',
67
+ ].join("\n");
68
+ }
69
+ /** 客户端回来的截图统一成长这样(宿主桥把 base64 拼成 dataUrl)。 */
70
+ export function extractPhoneShot(result) {
71
+ if (!result || typeof result !== "object")
72
+ return undefined;
73
+ const image = result.image;
74
+ if (!image || typeof image !== "object")
75
+ return undefined;
76
+ const src = image;
77
+ if (typeof src.dataUrl !== "string")
78
+ return undefined;
79
+ const match = /^data:([^;,]+);base64,(.+)$/s.exec(src.dataUrl);
80
+ if (!match)
81
+ return undefined;
82
+ return {
83
+ data: match[2],
84
+ mimeType: match[1],
85
+ width: typeof src.width === "number" ? src.width : undefined,
86
+ height: typeof src.height === "number" ? src.height : undefined,
87
+ };
88
+ }
89
+ export function makePhoneTool(clientSession, ownerId) {
90
+ return {
91
+ name: PHONE_TOOL_NAME,
92
+ label: "Phone",
93
+ description: "Read the phone screen and drive it through the accessibility service.",
94
+ promptSnippet: "read and drive this Android phone: UI tree, tap, swipe, type, keys, shots",
95
+ promptGuidelines: [
96
+ "Use phone only when the user asked you to operate their phone; never tap, type or navigate their apps on your own initiative",
97
+ 'Start with op:"dump" and act on the returned nodes: bounds are screen pixels already, so tap the centre of a node instead of guessing coordinates. Take a screenshot when the tree is not enough.',
98
+ "Typing text goes to the focused input only. If the user must enter a password, payment or system setting, stop and ask them to do it themselves.",
99
+ "After each action, dump again to confirm the screen changed instead of firing several actions blindly.",
100
+ ],
101
+ parameters: Type.Object({
102
+ op: Type.Unsafe({
103
+ type: "string",
104
+ enum: [...PHONE_OPS],
105
+ description: PHONE_OP_SIGNATURE,
106
+ }),
107
+ x: Type.Optional(Type.Number()),
108
+ y: Type.Optional(Type.Number()),
109
+ x1: Type.Optional(Type.Number()),
110
+ y1: Type.Optional(Type.Number()),
111
+ x2: Type.Optional(Type.Number()),
112
+ y2: Type.Optional(Type.Number()),
113
+ durationMs: Type.Optional(Type.Number()),
114
+ text: Type.Optional(Type.String()),
115
+ packageName: Type.Optional(Type.String()),
116
+ maxWidth: Type.Optional(Type.Number()),
117
+ maxNodes: Type.Optional(Type.Number()),
118
+ maxDepth: Type.Optional(Type.Number()),
119
+ key: Type.Optional(Type.Unsafe({ type: "string", enum: [...PHONE_KEYS] })),
120
+ timeoutMs: Type.Optional(Type.Number()),
121
+ }),
122
+ execute: async (_id, params, signal) => {
123
+ const p = (params ?? {});
124
+ const op = typeof p.op === "string" ? p.op.trim() : "";
125
+ if (!op) {
126
+ throw new Error('phone requires a non-empty `op` (e.g. "dump", "tap").\nphone 需要非空的 op(如 dump/tap)。');
127
+ }
128
+ const args = collectPhoneArgs(p);
129
+ // key 是枚举,但放在 args 里过桥,保持一个入口。
130
+ if (typeof p.key === "string" && p.key.length > 0)
131
+ args.name = p.key;
132
+ const resolved = await clientSession.phoneCall({ op, args, timeoutMs: normalizePhoneCallTimeoutMs(p.timeoutMs) }, { aborted: signal?.aborted }, ownerId);
133
+ if (!resolved.ok)
134
+ throw new Error(formatPhoneError(op, resolved.error));
135
+ const shot = extractPhoneShot(resolved.result);
136
+ const details = {
137
+ op,
138
+ args,
139
+ result: shot ? { ...resolved.result, image: "[image]" } : resolved.result,
140
+ };
141
+ if (!shot) {
142
+ return { content: [{ type: "text", text: formatPhoneCallResult(resolved.result) }], details };
143
+ }
144
+ const caption = [
145
+ `Phone screenshot — ${shot.width ?? "?"}×${shot.height ?? "?"} px.`,
146
+ `手机截图 — ${shot.width ?? "?"}×${shot.height ?? "?"} px。`,
147
+ ].join("\n");
148
+ if (clientSession.canSeeImages?.() === true) {
149
+ return {
150
+ content: [
151
+ { type: "text", text: caption },
152
+ { type: "image", data: shot.data, mimeType: shot.mimeType },
153
+ ],
154
+ details,
155
+ };
156
+ }
157
+ const bridged = await clientSession.transcribeToolImage?.(shot, signal);
158
+ const note = bridged?.text
159
+ ? `\n\n<vision-bridge>\n${bridged.text}\n</vision-bridge>`
160
+ : [
161
+ `\n\n(当前模型看不到图片:${bridged?.reason ?? "视觉桥不可用"} —— 可改用 op:"dump" 走控件树,或换支持识图的模型)`,
162
+ `(The current model cannot see images: ${bridged?.reason ?? "vision bridge unavailable"} — use op:"dump" instead)`,
163
+ ].join("\n");
164
+ return { content: [{ type: "text", text: caption + note }], details };
165
+ },
166
+ };
167
+ }
@@ -443,8 +443,8 @@ export function planModeDenial(toolName, params) {
443
443
  if (!isReadOnlyConversationAction(act)) {
444
444
  return {
445
445
  kind: "bypass-tool",
446
- reason: `计划模式:不能调用 subagent(action="${act || "spawn"}")(它会在别的会话里执行,绕过本会话的只读约束)。请在本对话内用只读工具完成调研。`,
447
- reasonEn: `Plan mode: subagent(action="${act || "spawn"}") is unavailable (it runs outside this conversation and would bypass the read-only constraint). Research with read-only tools here.`,
446
+ reason: `计划模式:不能调用 conversation(action="${act || "spawn"}")(它会在别的会话里执行,绕过本会话的只读约束)。请在本对话内用只读工具完成调研。`,
447
+ reasonEn: `Plan mode: conversation(action="${act || "spawn"}") is unavailable (it runs outside this conversation and would bypass the read-only constraint). Research with read-only tools here.`,
448
448
  };
449
449
  }
450
450
  }
@@ -231,7 +231,7 @@ export const HOST_METHODS = [
231
231
  {
232
232
  name: "storage",
233
233
  needs: "-",
234
- summary: "插件私有 KV(storage.json,原子写,卸载即删)",
234
+ summary: "插件私有 KV(plugin-data/<id>/storage.json,原子写,卸载即删)",
235
235
  example: `host.storage.get("k")`,
236
236
  },
237
237
  { name: "secrets", needs: "-", summary: "加密 secrets(明文永不落盘/下发)", example: `host.secrets.get("token")` },