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
@@ -1,6 +1,22 @@
1
- import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { mkdir, open, readFile, rename, rm } from "node:fs/promises";
2
3
  import { dirname } from "node:path";
3
4
  import { randomUUID } from "node:crypto";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ /**
7
+ * Windows 上杀毒 / 搜索索引器会在文件刚写完的几毫秒里短暂持有句柄,此时 rename(MoveFileEx 覆盖)报
8
+ * EPERM / EACCES / EBUSY。这类错误是瞬时的,重试即可;其余错误(EIO / ENOSPC / EXDEV …)重试无用。
9
+ * 退避必须真等,连续空转的「立刻重试三次」在毫秒级占用面前等于没重试。
10
+ */
11
+ export const TRANSIENT_FS_CODES = ["EPERM", "EACCES", "EBUSY"];
12
+ /** 每次失败后等多久再试;数组长度即最大重试次数。总等待 ≈ 630ms,覆盖杀毒扫描窗口。 */
13
+ export const ATOMIC_RETRY_DELAY_MS = [20, 60, 150, 400];
14
+ export function isTransientFsCode(code) {
15
+ return typeof code === "string" && TRANSIENT_FS_CODES.includes(code);
16
+ }
17
+ function sleepSync(ms) {
18
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
19
+ }
4
20
  export function writeAtomicSync(file, data, options = {}) {
5
21
  const dir = dirname(file);
6
22
  mkdirSync(dir, { recursive: true });
@@ -37,9 +53,10 @@ export function writeAtomicSync(file, data, options = {}) {
37
53
  break;
38
54
  }
39
55
  catch (error) {
40
- const code = error.code;
41
- if (attempt >= 2 || !["EPERM", "EACCES", "EBUSY"].includes(code ?? ""))
56
+ const attemptDelay = ATOMIC_RETRY_DELAY_MS[attempt];
57
+ if (attemptDelay === undefined || !isTransientFsCode(error.code))
42
58
  throw error;
59
+ sleepSync(attemptDelay);
43
60
  }
44
61
  }
45
62
  }
@@ -50,14 +67,93 @@ export function writeAtomicSync(file, data, options = {}) {
50
67
  catch { }
51
68
  }
52
69
  }
53
- export function writeAtomicPortableSync(fs, file, data, nonce, mode = 0o600) {
70
+ /** Same contract as `writeAtomicSync`, for async callers (rename retries await, they do not block the loop). */
71
+ export async function writeAtomic(file, data, options = {}) {
72
+ await mkdir(dirname(file), { recursive: true });
73
+ const tmp = `${file}.${process.pid}.${Date.now()}.${randomUUID().slice(0, 8)}.tmp`;
74
+ try {
75
+ const handle = await open(tmp, "wx", options.mode ?? 0o666);
76
+ try {
77
+ await handle.writeFile(data);
78
+ if (options.fsync)
79
+ await handle.sync();
80
+ }
81
+ finally {
82
+ await handle.close();
83
+ }
84
+ for (let attempt = 0;; attempt++) {
85
+ try {
86
+ await rename(tmp, file);
87
+ break;
88
+ }
89
+ catch (error) {
90
+ const attemptDelay = ATOMIC_RETRY_DELAY_MS[attempt];
91
+ if (attemptDelay === undefined || !isTransientFsCode(error.code))
92
+ throw error;
93
+ await delay(attemptDelay);
94
+ }
95
+ }
96
+ }
97
+ finally {
98
+ await rm(tmp, { force: true }).catch(() => { });
99
+ }
100
+ }
101
+ /**
102
+ * 读侧同样会被瞬时占用咬到(写方正在 rename,读方 handleExisting 失败)。ENOENT 是正常结果,交回调用方。
103
+ */
104
+ export function readFileSyncRetry(file, encoding = "utf8") {
105
+ for (let attempt = 0;; attempt++) {
106
+ try {
107
+ return readFileSync(file, encoding);
108
+ }
109
+ catch (error) {
110
+ const code = error.code;
111
+ const attemptDelay = ATOMIC_RETRY_DELAY_MS[attempt];
112
+ if (code === "ENOENT" || attemptDelay === undefined || !isTransientFsCode(code))
113
+ throw error;
114
+ sleepSync(attemptDelay);
115
+ }
116
+ }
117
+ }
118
+ export async function readFileRetry(file, encoding = "utf8") {
119
+ for (let attempt = 0;; attempt++) {
120
+ try {
121
+ return await readFile(file, encoding);
122
+ }
123
+ catch (error) {
124
+ const code = error.code;
125
+ const attemptDelay = ATOMIC_RETRY_DELAY_MS[attempt];
126
+ if (code === "ENOENT" || attemptDelay === undefined || !isTransientFsCode(code))
127
+ throw error;
128
+ await delay(attemptDelay);
129
+ }
130
+ }
131
+ }
132
+ /**
133
+ * 注入式原子写:`fs` 由调用方给,函数自包含,可 `toString()` 后在无 server 依赖的进程里跑
134
+ * (见 `portableAtomicWriteSyncSource`)。非 Node 宿主不必带 `fsync`。
135
+ */
136
+ export function writeAtomicPortableSync(fs, file, data, nonce, mode = 0o600, fsync = false) {
54
137
  if (!nonce || nonce.length > 128 || !/^[A-Za-z0-9_.-]+$/.test(nonce))
55
138
  throw new Error("Invalid atomic-write nonce");
139
+ const sleep = (ms) => {
140
+ try {
141
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
142
+ }
143
+ catch { }
144
+ };
145
+ const retryDelays = [20, 60, 150, 400];
146
+ const transient = ["EPERM", "EACCES", "EBUSY"];
147
+ const sep = Math.max(file.lastIndexOf("/"), file.lastIndexOf("\\"));
148
+ if (sep > 0)
149
+ fs.mkdirSync(file.slice(0, sep), { recursive: true });
56
150
  const temporary = `${file}.${nonce}.tmp`;
57
151
  try {
58
152
  const descriptor = fs.openSync(temporary, "wx", mode);
59
153
  try {
60
154
  fs.writeFileSync(descriptor, data, "utf8");
155
+ if (fsync)
156
+ fs.fsyncSync(descriptor);
61
157
  }
62
158
  finally {
63
159
  fs.closeSync(descriptor);
@@ -68,8 +164,11 @@ export function writeAtomicPortableSync(fs, file, data, nonce, mode = 0o600) {
68
164
  break;
69
165
  }
70
166
  catch (error) {
71
- if (attempt >= 2 || !["EPERM", "EACCES", "EBUSY"].includes(error.code ?? ""))
167
+ const code = error.code;
168
+ const attemptDelay = retryDelays[attempt];
169
+ if (attemptDelay === undefined || !transient.includes(code ?? ""))
72
170
  throw error;
171
+ sleep(attemptDelay);
73
172
  }
74
173
  }
75
174
  }
@@ -80,9 +179,35 @@ export function writeAtomicPortableSync(fs, file, data, nonce, mode = 0o600) {
80
179
  catch { }
81
180
  }
82
181
  }
182
+ /** 注入式容错读:与 `readFileSyncRetry` 同一套退避,可 `toString()` 后独立运行。 */
183
+ export function readFileSyncRetryPortableSync(fs, file, encoding = "utf8") {
184
+ const sleep = (ms) => {
185
+ try {
186
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
187
+ }
188
+ catch { }
189
+ };
190
+ const retryDelays = [20, 60, 150, 400];
191
+ const transient = ["EPERM", "EACCES", "EBUSY"];
192
+ for (let attempt = 0;; attempt++) {
193
+ try {
194
+ return fs.readFileSync(file, encoding);
195
+ }
196
+ catch (error) {
197
+ const code = error.code;
198
+ const attemptDelay = retryDelays[attempt];
199
+ if (code === "ENOENT" || attemptDelay === undefined || !transient.includes(code ?? ""))
200
+ throw error;
201
+ sleep(attemptDelay);
202
+ }
203
+ }
204
+ }
83
205
  export function portableAtomicWriteSyncSource() {
84
206
  return `const writeAtomicPortable = (${writeAtomicPortableSync.toString()});`;
85
207
  }
208
+ export function portableAtomicReadSyncSource() {
209
+ return `const readFileSyncRetryPortable = (${readFileSyncRetryPortableSync.toString()});`;
210
+ }
86
211
  export function writeJsonAtomicSync(file, data, indent = 2) {
87
212
  const text = JSON.stringify(data, null, indent) + "\n";
88
213
  writeAtomicSync(file, text);
@@ -30,3 +30,18 @@ export function withDefaultBashTimeout(params) {
30
30
  const timeout = resolveBashTimeoutSec(requested);
31
31
  return (timeout === requested ? params : { ...params, timeout });
32
32
  }
33
+ /**
34
+ * 后台任务(`bash({ background: true })`)的总时长上限(秒)。
35
+ * 只防手滑传天文数字把定时器算坏,不承担"防挂死"职责:长驻服务本来就该一直活着。
36
+ */
37
+ export const MAX_BACKGROUND_TIMEOUT_SEC = 7 * 24 * 3600;
38
+ /**
39
+ * 后台任务的 timeout 语义与前台**故意不同**(前台:默认 120 / 上限 3600):
40
+ * 缺省、0、非法值一律 = 不限;显式给正数才计时,并夹到一个防手滑的极大值。
41
+ * 别把这里换成 `resolveBashTimeoutSec`:那会把 "0 = 不限" 翻成 120 秒,服务两分钟后被杀。
42
+ */
43
+ export function resolveBackgroundTimeoutSec(requested) {
44
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0)
45
+ return 0;
46
+ return Math.min(Math.ceil(requested), MAX_BACKGROUND_TIMEOUT_SEC);
47
+ }
@@ -1,10 +1,26 @@
1
- import { createBashToolDefinition, createLocalBashOperations, } from "@earendil-works/pi-coding-agent";
1
+ import { createBashToolDefinition, createLocalBashOperations, getAgentDir, SettingsManager, } from "@earendil-works/pi-coding-agent";
2
+ import { pick } from "./i18n.js";
2
3
  import { applyHeadTail } from "./terminals.js";
3
4
  import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
4
- import { withDefaultBashTimeout } from "./bash-timeout.js";
5
+ import { resolveBackgroundTimeoutSec, withDefaultBashTimeout } from "./bash-timeout.js";
5
6
  import { getGlobalRemoteSshService, isRemoteWorkspaceUri, restoreWorkspaceUriFromSessionDir, } from "./remote-ssh-service.js";
6
- export function makeKillableBashTool(cwd, kills, lang = () => "en") {
7
- const base = createLocalBashOperations();
7
+ /**
8
+ * pi CLI 的 bash 工具按 settings.json 的 `shellPath` 选解释器;这里以前直接
9
+ * `createLocalBashOperations()`,等于把这步丢了 —— Windows 上 Git 装在非默认路径的用户只有
10
+ * shellPath 这一条路,落地表现就是每次 bash 都 "No bash shell found"(issue #866)。
11
+ * 按 CLI 同一来源解析:全局 settings.json + 项目 .pi/settings.json;读不出来就交回 SDK 默认探测。
12
+ */
13
+ function resolveShellPath(cwd) {
14
+ try {
15
+ return SettingsManager.create(cwd, getAgentDir()).getShellPath();
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ export function makeKillableBashTool(cwd, kills, lang = () => "en", jobs, origin) {
22
+ // shellPath 必须透传:不传时 SDK 只认 %ProgramFiles%\Git 和 PATH,配置被静默吞掉。
23
+ const base = createLocalBashOperations({ shellPath: resolveShellPath(cwd) });
8
24
  const tool = createBashToolDefinition(cwd, {
9
25
  operations: {
10
26
  exec: async (command, c, opts) => {
@@ -50,6 +66,51 @@ export function makeKillableBashTool(cwd, kills, lang = () => "en") {
50
66
  prepareArguments: tool.prepareArguments,
51
67
  executionMode: tool.executionMode,
52
68
  execute: async (toolCallId, params, signal, onUpdate, ctx) => {
69
+ const raw = params;
70
+ // 后台任务走进程内 job registry(不经过 PTY、不阻塞本次调用)。
71
+ if (raw?.background === true) {
72
+ if (!jobs) {
73
+ throw new Error("background=true is unavailable: the in-process job runner is not wired on this server. Run the command in the foreground or start it in the terminal panel.");
74
+ }
75
+ const command = String(raw.command ?? "").trim();
76
+ if (!command)
77
+ throw new Error("background=true requires a non-empty command");
78
+ const effCwd = restoreWorkspaceUriFromSessionDir(cwd);
79
+ if (isRemoteWorkspaceUri(effCwd)) {
80
+ throw new Error("background=true is not supported on remote SSH workspaces: the job would run on the local machine. Run it in the foreground instead.");
81
+ }
82
+ const timeoutSec = resolveBackgroundTimeoutSec(raw.timeout);
83
+ const job = jobs.start({
84
+ command,
85
+ cwd: effCwd,
86
+ label: command,
87
+ timeoutSec,
88
+ ...(origin?.() ? { origin: origin() } : {}),
89
+ });
90
+ const head = await jobs.awaitFirstOutput(job.id);
91
+ const l = lang();
92
+ const timeoutText = timeoutSec > 0
93
+ ? pick(l, `硬超时 ${timeoutSec}s`, `hard timeout ${timeoutSec}s`, "bash.bgTimeout", { n: timeoutSec })
94
+ : pick(l, "不限时", "no time limit", "bash.bgNoTimeout");
95
+ const text = pick(l, `已在后台启动:job ${job.id},pid ${job.pid}(${timeoutText})。本次调用立即返回,命令继续运行。\n` +
96
+ `日志文件:${job.logPath}(要看后续输出就用 read 读它的尾部)。\n` +
97
+ `停止:顶栏「后台任务」→ 停止,或任何一次 bash 里 kill -TERM ${job.pid}。\n` +
98
+ (head ? `已捕获的输出:\n${head}\n` : "(暂无输出)\n"), `Started in the background: job ${job.id}, pid ${job.pid} (${timeoutText}). This call returned immediately; the command keeps running.\n` +
99
+ `Log file: ${job.logPath} (read its tail to follow up).\n` +
100
+ `Stop: top-bar Background tasks → Stop, or kill -TERM ${job.pid} in a later bash call.\n` +
101
+ (head ? `Captured output:\n${head}\n` : "(no output yet)\n"), "bash.bgStarted", { id: job.id, pid: job.pid, timeout: timeoutSec });
102
+ return {
103
+ content: [{ type: "text", text }],
104
+ details: {
105
+ background: true,
106
+ jobId: job.id,
107
+ pid: job.pid,
108
+ logPath: job.logPath,
109
+ timeoutSec,
110
+ tail: head.slice(0, 4000),
111
+ },
112
+ };
113
+ }
53
114
  // 模型漏传 timeout 时不给"无时限":默认 120s,由 server/bash-timeout.ts 单源归一。
54
115
  const effective = withDefaultBashTimeout(params);
55
116
  const result = (await tool.execute(toolCallId, effective, signal, onUpdate, ctx));
@@ -66,6 +127,9 @@ export function makeAdaptiveBashTool(killable, terminalBacked, useTerminal) {
66
127
  ...killable,
67
128
  execute: (id, params, signal, onUpdate, ctx) => {
68
129
  const p = params;
130
+ // background 永远走 job registry:PTY 后端没有后台契约(scrollback 无日志、分不清退出原因)。
131
+ if (p?.background === true)
132
+ return killable.execute(id, params, signal, onUpdate, ctx);
69
133
  const shouldUseTerminal = useTerminal() && (process.platform !== "win32" || p?.persist === true);
70
134
  return (shouldUseTerminal ? terminalBacked : killable).execute(id, params, signal, onUpdate, ctx);
71
135
  },
@@ -266,13 +266,17 @@ export class BgServerTracker {
266
266
  port,
267
267
  pid: v.pid,
268
268
  since: v.since,
269
+ kind: "port",
269
270
  ...(v.name ? { name: v.name } : {}),
270
271
  ...(v.command ? { command: v.command } : {}),
271
272
  ...(v.keep ? { keep: true } : {}),
272
273
  }))
273
274
  .sort((a, b) => a.since - b.since);
274
275
  for (const t of this.opts.pluginTasks?.() ?? [])
275
- out.push(t);
276
+ out.push({ kind: "plugin", ...t });
277
+ // bash background 的 job 行:不靠端口 diff,而是 JobRegistry 显式登记(不监听端口的任务也能看见)。
278
+ for (const j of this.opts.jobs?.() ?? [])
279
+ out.push({ kind: "job", ...j });
276
280
  return out;
277
281
  }
278
282
  push() {
@@ -396,19 +400,21 @@ export class BgServerTracker {
396
400
  return killed;
397
401
  }
398
402
  async killAll() {
399
- if (this.servers.size === 0)
400
- return [];
401
- await this.verifyBeforeKill();
402
- if (this.servers.size === 0)
403
- return [];
404
- const killed = [];
405
- // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
406
- for (const [port, { pid }] of [...this.servers]) {
407
- killPidTree(pid);
408
- killed.push(String(port));
403
+ // 「全部关闭」的语义是「把后台都停了」:端口行 + bash background 的 job 行一起收。
404
+ // 插件常驻任务不在内(它们由插件自己的 stop 回调负责,面板上也单独走 kill_background_server{taskId})。
405
+ const killedJobs = this.opts.killAllJobs?.() ?? [];
406
+ const killed = killedJobs.map((id) => `job:${id}`);
407
+ if (this.servers.size > 0) {
408
+ await this.verifyBeforeKill();
409
+ // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: killPidTree 的异步回调可能改 map
410
+ for (const [port, { pid }] of [...this.servers]) {
411
+ killPidTree(pid);
412
+ killed.push(String(port));
413
+ }
414
+ this.servers.clear();
409
415
  }
410
- this.servers.clear();
411
- this.push();
416
+ if (killed.length > 0)
417
+ this.push();
412
418
  return killed;
413
419
  }
414
420
  }
@@ -50,8 +50,19 @@ export function handleCanvasMessage(msg, dataDir, orchestrator, send, opts) {
50
50
  return true;
51
51
  }
52
52
  case "canvas_save": {
53
- if (!isSafeGraphId(msg.graph?.id))
53
+ if (!isSafeGraphId(msg.graph?.id)) {
54
+ send({
55
+ type: "canvas_error",
56
+ code: "invalid_graph",
57
+ message: `Invalid canvas graph id: ${String(msg.graph?.id)}`,
58
+ messageI18n: canvasRuntimeMessage("error.invalidGraphId", {
59
+ id: String(msg.graph?.id),
60
+ }),
61
+ graphId: typeof msg.graph?.id === "string" ? msg.graph.id : undefined,
62
+ requestId: msg.requestId,
63
+ });
54
64
  return true;
65
+ }
55
66
  try {
56
67
  assertCanvasGraph(msg.graph);
57
68
  }
@@ -449,7 +449,7 @@ export const DEFAULT_DARK_MINIMAL_SETTINGS = Object.freeze({
449
449
  promptOverrides: {
450
450
  append: "使用gh fnm uv\npr和issue处理完要回复 并且关闭, 分支合并之后就删除\n处理问题时 跳出“修补表象、头痛医头”的打地鼠视角 寻找根本的解决办法",
451
451
  },
452
- promptDisabled: ["persona", "plugin_dev"],
452
+ promptDisabled: ["plugin_dev"],
453
453
  _promptPluginDevConfigured: false,
454
454
  toolPromptOverrides: {},
455
455
  disabledSkills: [],
@@ -499,10 +499,14 @@ export const DEFAULT_DARK_MINIMAL_SETTINGS = Object.freeze({
499
499
  "db_tables",
500
500
  "image_services",
501
501
  "image_generate",
502
+ "browser_use",
503
+ "live2d",
502
504
  "live_preview",
503
505
  "matrix",
506
+ "music_control",
504
507
  "pm2",
505
508
  "qq",
509
+ "quota_status",
506
510
  "session_migrate_import",
507
511
  "session_migrate_scan",
508
512
  "slack",
@@ -518,11 +522,17 @@ export const DEFAULT_DARK_MINIMAL_SETTINGS = Object.freeze({
518
522
  "imessage",
519
523
  "legado_source_probe",
520
524
  "legado_run_rule",
525
+ "bili_ask",
521
526
  "bili_comments",
527
+ "bili_deepen",
528
+ "bili_delivery",
529
+ "bili_dm_messages",
530
+ "bili_dm_sessions",
522
531
  "bili_duty_run",
523
532
  "bili_fav_add",
524
533
  "bili_fav_folders",
525
534
  "bili_hot_videos",
535
+ "bili_index",
526
536
  "bili_login_poll",
527
537
  "bili_login_start",
528
538
  "bili_rank",
@@ -533,20 +543,25 @@ export const DEFAULT_DARK_MINIMAL_SETTINGS = Object.freeze({
533
543
  "bili_send_message",
534
544
  "bili_status",
535
545
  "bili_subtitle",
546
+ "bili_taste",
536
547
  "bili_up_videos",
548
+ "bili_video_content",
537
549
  "bili_video_info",
538
550
  "bili_whoami",
539
551
  "tts",
540
552
  "office",
541
553
  "desktop_click",
554
+ "desktop_drag",
542
555
  "desktop_elements",
543
556
  "desktop_key",
544
557
  "desktop_screenshot",
558
+ "desktop_scroll",
545
559
  "desktop_type",
546
560
  "desktop_window",
547
561
  "wechat_send",
548
562
  "remote_term",
549
563
  "notes",
564
+ "frp",
550
565
  ],
551
566
  nativeCliInheritModel: {},
552
567
  terminalToolsEnabled: false,
@@ -735,7 +750,9 @@ export function normalizePathKey(p) {
735
750
  }
736
751
  if (/^[a-zA-Z]:[\\/]/.test(p)) {
737
752
  const drive = p.slice(0, 2).toLowerCase();
738
- const rest = p.slice(2).replace(/\\/g, "/").replace(/\/+/g, "/");
753
+ // 尾部斜杠也要归一:win32 走 resolve() 已经去掉了,这条非 win32 分支是自己拼的,
754
+ // 留着会让 "e:/work/p" 与 "E:\\work\\p\\" 被当成两个目录(cwd 比对 / 缓存键 / 去重全分叉)。
755
+ const rest = p.slice(2).replace(/\\/g, "/").replace(/\/+/g, "/").replace(/\/+$/, "");
739
756
  return (drive + rest).toLowerCase();
740
757
  }
741
758
  return resolve(p);
@@ -892,23 +909,41 @@ export class ClientStateStore {
892
909
  get(clientId) {
893
910
  return this.load()[clientId] ?? { projects: [] };
894
911
  }
895
- remember(clientId, cwd) {
912
+ /**
913
+ * 记录一个项目。
914
+ * - `promote`(默认)= 真实对话活动,把 `lastUsed` 顶到当前时间;项目排序只认这个。
915
+ * - `promote: false` = 浏览/切换/恢复,只记 `lastCwd`、清 tombstone、缺省登记(`lastUsed: 0`),
916
+ * 不刷新时间,所以只是点开看看不会把项目顶到最新。
917
+ */
918
+ remember(clientId, cwd, opts) {
896
919
  const all = this.load();
897
920
  const state = (all[clientId] ??= { projects: [] });
898
921
  this.touchClient(all, clientId);
899
922
  state.lastCwd = cwd;
900
923
  const now = Date.now();
901
924
  const targetKey = normalizePathKey(cwd);
902
- state.projects = [
903
- { path: cwd, lastUsed: now },
904
- ...state.projects.filter((p) => normalizePathKey(p.path) !== targetKey),
905
- ].slice(0, RECENT_PROJECTS_MAX);
925
+ const promote = opts?.promote !== false;
906
926
  // Also persist in global settings so new tabs and sessions inherit it immediately
907
927
  const globalState = (all[ClientStateStore.GLOBAL_SETTINGS_KEY] ??= { projects: [] });
908
- globalState.projects = [
909
- { path: cwd, lastUsed: now },
910
- ...(globalState.projects ?? []).filter((p) => normalizePathKey(p.path) !== targetKey),
911
- ].slice(0, RECENT_PROJECTS_MAX);
928
+ if (promote) {
929
+ state.projects = [
930
+ { path: cwd, lastUsed: now },
931
+ ...state.projects.filter((p) => normalizePathKey(p.path) !== targetKey),
932
+ ].slice(0, RECENT_PROJECTS_MAX);
933
+ globalState.projects = [
934
+ { path: cwd, lastUsed: now },
935
+ ...(globalState.projects ?? []).filter((p) => normalizePathKey(p.path) !== targetKey),
936
+ ].slice(0, RECENT_PROJECTS_MAX);
937
+ }
938
+ else {
939
+ // 浏览不算「最近对话」:已登记的不动时间,没登记的补一条 lastUsed: 0 留着位置
940
+ if (!state.projects.some((p) => normalizePathKey(p.path) === targetKey)) {
941
+ state.projects = [{ path: cwd, lastUsed: 0 }, ...state.projects].slice(0, RECENT_PROJECTS_MAX);
942
+ }
943
+ if (!(globalState.projects ?? []).some((p) => normalizePathKey(p.path) === targetKey)) {
944
+ globalState.projects = [{ path: cwd, lastUsed: 0 }, ...(globalState.projects ?? [])].slice(0, RECENT_PROJECTS_MAX);
945
+ }
946
+ }
912
947
  // Opening the workspace again clears its removal tombstone across all clients and global settings.
913
948
  for (const cState of Object.values(all)) {
914
949
  if (cState.removedProjects?.length) {
@@ -1720,16 +1755,23 @@ export class ClientStateStore {
1720
1755
  getMarkerSettings(_clientId) {
1721
1756
  const s = this.load()[ClientStateStore.GLOBAL_SETTINGS_KEY]?.markers;
1722
1757
  return {
1723
- markersEnabled: s?.markersEnabled ?? true,
1724
1758
  disabledMarkers: s?.disabledMarkers ?? [...DEFAULT_DISABLED_MARKERS],
1725
1759
  };
1726
1760
  }
1761
+ /**
1762
+ * 【一次性迁移】旧版独立的「启用标记工具(全局)」开关是否被关掉。
1763
+ * `undefined` = 旧数据里没有这个字段。新语义「全关即全局关闭」由 MarkerService 从 disabledMarkers 派生。
1764
+ */
1765
+ getLegacyMarkersGlobalOff() {
1766
+ const markers = this.load()[ClientStateStore.GLOBAL_SETTINGS_KEY]?.markers;
1767
+ return typeof markers?.markersEnabled === "boolean" ? !markers.markersEnabled : undefined;
1768
+ }
1727
1769
  saveMarkerSettings(_clientId, settings) {
1728
1770
  const all = this.load();
1729
1771
  const state = (all[ClientStateStore.GLOBAL_SETTINGS_KEY] ??= { projects: [] });
1730
- const cur = state.markers ?? { markersEnabled: true, disabledMarkers: [...DEFAULT_DISABLED_MARKERS] };
1772
+ const cur = state.markers ?? { disabledMarkers: [...DEFAULT_DISABLED_MARKERS] };
1773
+ // 只落盘 per-marker 黑名单:整块覆盖会顺带清掉旧数据里已下线的 markersEnabled 字段
1731
1774
  state.markers = {
1732
- markersEnabled: settings.markersEnabled ?? cur.markersEnabled ?? true,
1733
1775
  disabledMarkers: settings.disabledMarkers ?? cur.disabledMarkers ?? [...DEFAULT_DISABLED_MARKERS],
1734
1776
  };
1735
1777
  this.save();
@@ -1,8 +1,9 @@
1
1
  import { Type } from "typebox";
2
2
  /** Compact action signature for the merged tool: the only place documenting parameters,
3
3
  * so every field schema stays flat and prose-free. */
4
- export const CONVERSATION_ACTION_SIGNATURE = "spawn(prompt,type?) | steer/answer(runId,message,requestId?) | complete(summary) | consult(message) | " +
5
- "escalate(runId,requestId) | get_result/stop/status(runId) | wait_all/dismiss(runIds?) | handoff(toRunId,payload) | " +
4
+ export const CONVERSATION_ACTION_SIGNATURE = "spawn(prompt,type?,key? | tasks[{key,prompt,type?,template?,model?,thinking?,isolation?,persist?,notifyOnDone?}]) | " +
5
+ "steer/answer(runId,message,requestId?) | complete(summary,evidence{files[],commands[],none?,blocked?}) | consult(message) | " +
6
+ "escalate(runId,requestId) | get_result/stop/status/resume(runId,message?) | wait_all/dismiss(runIds? keys accepted) | handoff(toRunId,payload) | " +
6
7
  "list(kind?,query?) | read/files(id|path,query?,last?)";
7
8
  export function mergeConversationTools(tools) {
8
9
  const reader = tools.find((tool) => tool.name === "conversation_read");
@@ -28,7 +28,7 @@ export function normalizeDelegation(params) {
28
28
  export function validateDelegation(input, usableNames, lang = "en") {
29
29
  if (!input.agent || !usableNames.includes(input.agent)) {
30
30
  const shown = usableNames.slice(0, 12).join(" · ") + (usableNames.length > 12 ? " · …" : "");
31
- return pick(lang, `派单被驳回:模板 "${input.agent || "(空)"}" 不可用(不存在或已停用)。可用模板:${shown || "(无)"}。用 subagent(action="templates") 查简介再选;不要编造模板名。`, `Delegation rejected: template "${input.agent || "(empty)"}" is unavailable (missing or disabled). Available templates: ${shown || "(none)"}. Use subagent(action="templates") for descriptions; do not invent template names.`, "delegate.validate.agent", { agent: input.agent, available: shown });
31
+ return pick(lang, `派单被驳回:模板 "${input.agent || "(空)"}" 不可用(不存在或已停用)。可用模板:${shown || "(无)"}。用 conversation(action="templates") 查简介再选;不要编造模板名。`, `Delegation rejected: template "${input.agent || "(empty)"}" is unavailable (missing or disabled). Available templates: ${shown || "(none)"}. Use conversation(action="templates") for descriptions; do not invent template names.`, "delegate.validate.agent", { agent: input.agent, available: shown });
32
32
  }
33
33
  const checks = [
34
34
  { section: "TASK", text: input.task, min: MIN_TASK },
@@ -40,7 +40,7 @@ export function validateDelegation(input, usableNames, lang = "en") {
40
40
  ];
41
41
  for (const c of checks) {
42
42
  if (c.text.trim().length < c.min) {
43
- return pick(lang, `派单被驳回:${c.section} 段太短(至少 ${c.min} 字,当前 ${c.text.trim().length} 字)。六段缺一不可、含糊不得:补全后重试,不要改用 subagent(action="spawn") 绕过校验。`, `Delegation rejected: section ${c.section} is too short (minimum ${c.min} chars, got ${c.text.trim().length}). All six sections are mandatory and vague prompts fail: complete it and retry; do not bypass validation via subagent(action="spawn").`, "delegate.validate.short", { section: c.section, min: c.min });
43
+ return pick(lang, `派单被驳回:${c.section} 段太短(至少 ${c.min} 字,当前 ${c.text.trim().length} 字)。六段缺一不可、含糊不得:补全后重试,不要改用 conversation(action="spawn") 绕过校验。`, `Delegation rejected: section ${c.section} is too short (minimum ${c.min} chars, got ${c.text.trim().length}). All six sections are mandatory and vague prompts fail: complete it and retry; do not bypass validation via conversation(action="spawn").`, "delegate.validate.short", { section: c.section, min: c.min });
44
44
  }
45
45
  }
46
46
  return null;
@@ -76,7 +76,7 @@ export function buildDelegationPrompt(input, lang = "en") {
76
76
  ].join("\n");
77
77
  }
78
78
  const delegateSchema = Type.Object({
79
- agent: Type.String({ description: "Template name from subagent(action='templates')" }),
79
+ agent: Type.String({ description: "Template name from conversation(action='templates')" }),
80
80
  task: Type.String(),
81
81
  expected_outcome: Type.String(),
82
82
  required_tools: Type.String({ description: "Free text; 'read-only' switches the subagent to a readonly whitelist" }),
@@ -99,7 +99,7 @@ export function makeDelegateTaskTool(host, lang) {
99
99
  promptSnippet: "hand a well-scoped task to a specialist template",
100
100
  promptGuidelines: [
101
101
  "Fill every section concretely: one action, deliverables plus done criteria, explicit tool whitelist, exhaustive must_do/must_not_do, file paths and constraints",
102
- "Prefer delegate_task over subagent(action='spawn'): it spawns a real subagent conversation and can be followed up in that SAME session instead of delegating again",
102
+ "Prefer delegate_task over conversation(action='spawn'): it spawns a real subagent conversation and can be followed up in that SAME session instead of delegating again",
103
103
  "Before delegating, declare which template you chose and WHY its description matches the task",
104
104
  "After delegation ALWAYS verify the result: " +
105
105
  "does it work, does it follow codebase patterns, did it respect MUST DO / MUST NOT DO",
@@ -141,10 +141,10 @@ export function makeDelegateTaskTool(host, lang) {
141
141
  const securityLineZh = securityMode !== "normal" ? `\n安全模式:${securityMode === "readonly" ? "严格只读" : "审查验证"}` : "";
142
142
  const securityLineEn = securityMode !== "normal" ? `\nSecurity mode: ${securityMode}` : "";
143
143
  return text(pick(getLang(), `已派单:${convId}\n模板:${input.agent} · 标题:${title}${modelLineZh}${toolsLineZh}${securityLineZh}` +
144
- `\n子代理已在左栏运行列表中。用 subagent(action="wait_all") 一次等全部完成(不用轮询)、subagent(action="get_result") 取单个结果;` +
145
- `追问请在同一子代理会话里继续(subagent(action="steer")),不要重复派单。拿到结果后必须验证再汇报。`, `Delegated: ${convId}\nTemplate: ${input.agent} · Title: ${title}${modelLineEn}${toolsLineEn}${securityLineEn}` +
146
- `\nThe subagent is in the left running list. Use subagent(action="wait_all") to wait for all at once (no polling), ` +
147
- `subagent(action="get_result") for a single result; continue follow-ups in the SAME subagent session (subagent(action="steer")), ` +
144
+ `\n子代理已在左栏运行列表中。用 conversation(action="wait_all") 一次等全部完成(不用轮询)、conversation(action="get_result") 取单个结果;` +
145
+ `追问请在同一子代理会话里继续(conversation(action="steer")),不要重复派单。拿到结果后必须验证再汇报。`, `Delegated: ${convId}\nTemplate: ${input.agent} · Title: ${title}${modelLineEn}${toolsLineEn}${securityLineEn}` +
146
+ `\nThe subagent is in the left running list. Use conversation(action="wait_all") to wait for all at once (no polling), ` +
147
+ `conversation(action="get_result") for a single result; continue follow-ups in the SAME subagent session (conversation(action="steer")), ` +
148
148
  `do not delegate again. Verify the result before reporting.`, "delegate.started", {
149
149
  convId: convId,
150
150
  agent: input.agent,
@@ -1,5 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { Check } from "typebox/value";
3
+ import { modelSessionId } from "../model-session.js";
3
4
  const MAX_ACTIONS = 16;
4
5
  const MAX_ACTION_BYTES = 65_536;
5
6
  const MAX_CONTEXT_BYTES = 262_144;
@@ -117,6 +118,7 @@ export function createGroupRouterRuntime(options) {
117
118
  const requestOptions = {
118
119
  signal,
119
120
  maxTokens: 4_096,
121
+ sessionId: modelSessionId(),
120
122
  ...(thinking === "off" ? {} : { reasoning: thinking }),
121
123
  };
122
124
  for (let round = 0; round < MAX_ROUNDS; round++) {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { spawn } from "node:child_process";
3
- import { readFile, writeFile, rename, rm, mkdir } from "node:fs/promises";
3
+ import { readFile, mkdir } from "node:fs/promises";
4
+ import { readFileRetry, writeAtomic } from "../atomic-file.js";
4
5
  import { pathToFileURL } from "node:url";
5
6
  import { dirname, join, resolve } from "node:path";
6
7
  const PUBLIC_JOB_FIELDS = [
@@ -34,20 +35,14 @@ const MAX_AGE = 30 * 60_000;
34
35
  export function createHubUpgradeManager(options) {
35
36
  const path = join(options.dataDir, "hub-upgrade.json");
36
37
  let submitting = false;
38
+ // Windows 杀毒 / 索引器会短暂占用刚写完的文件,rename 因此报 EPERM/EBUSY —— 统一由 atomic-file 退避重试。
37
39
  async function write(job) {
38
- const temp = `${path}.${randomUUID()}.tmp`;
39
- try {
40
- await writeFile(temp, `${JSON.stringify(job, null, 2)}\n`, { flag: "wx", mode: 0o600 });
41
- await rename(temp, path);
42
- }
43
- finally {
44
- await rm(temp, { force: true });
45
- }
40
+ await writeAtomic(path, `${JSON.stringify(job, null, 2)}\n`, { mode: 0o600, fsync: true });
46
41
  }
47
42
  async function status(id) {
48
43
  let job;
49
44
  try {
50
- job = JSON.parse(await readFile(path, "utf8"));
45
+ job = JSON.parse(await readFileRetry(path));
51
46
  }
52
47
  catch (error) {
53
48
  if (error.code === "ENOENT")