pi-web-ui 0.118.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 (195) hide show
  1. package/CHANGELOG.md +143 -1
  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 +930 -166
  6. package/dist/server/approval-default-rules.js +4 -4
  7. package/dist/server/ask-user-question-tool.js +3 -40
  8. package/dist/server/atomic-file.js +130 -5
  9. package/dist/server/background-executors.js +235 -0
  10. package/dist/server/bash-timeout.js +47 -0
  11. package/dist/server/bash-tool.js +72 -5
  12. package/dist/server/bg-servers.js +19 -13
  13. package/dist/server/browser-page-tool.js +38 -29
  14. package/dist/server/browser-script-tool.js +119 -0
  15. package/dist/server/canvas/canvas-agent-tool.js +46 -35
  16. package/dist/server/canvas/canvas-dispatch.js +12 -1
  17. package/dist/server/claim-files-tool.js +6 -7
  18. package/dist/server/client-state.js +457 -41
  19. package/dist/server/communicate-tool.js +59 -77
  20. package/dist/server/compact-context-tool.js +4 -13
  21. package/dist/server/conversation-communication.js +23 -1
  22. package/dist/server/conversation-read-tool.js +14 -23
  23. package/dist/server/conversation-rows.js +17 -0
  24. package/dist/server/conversation-tool-names.js +2 -2
  25. package/dist/server/conversation-tool.js +23 -15
  26. package/dist/server/conversation-touches.js +1 -1
  27. package/dist/server/delegate-mode.js +0 -1
  28. package/dist/server/delegate-task.js +18 -39
  29. package/dist/server/device-center/approval-summary.js +0 -1
  30. package/dist/server/device-center/bot-execution.js +0 -1
  31. package/dist/server/device-center/group-router-runtime.js +2 -0
  32. package/dist/server/device-center/hub-upgrade.js +5 -10
  33. package/dist/server/device-center/task-progress.js +2 -2
  34. package/dist/server/dispatch-domain-handlers.js +97 -24
  35. package/dist/server/dispatch-plugin-handlers.js +10 -0
  36. package/dist/server/dsh/dsh-agent-service.js +21 -19
  37. package/dist/server/durable/durable-agent-service.js +1 -1
  38. package/dist/server/edit-tool.js +293 -0
  39. package/dist/server/engine-catalog.js +8 -2
  40. package/dist/server/engine-cli.js +29 -7
  41. package/dist/server/engine-probe.js +11 -6
  42. package/dist/server/eval-tool.js +5 -19
  43. package/dist/server/files-service.js +41 -19
  44. package/dist/server/fs-copy.js +93 -0
  45. package/dist/server/goal-review-gate.js +2 -3
  46. package/dist/server/index.js +92 -3
  47. package/dist/server/job-runner.js +345 -0
  48. package/dist/server/lsp-tool.js +10 -28
  49. package/dist/server/marker-service.js +42 -30
  50. package/dist/server/mcp-agent-tool.js +22 -47
  51. package/dist/server/model-session.js +16 -0
  52. package/dist/server/native-cli-session-hooks.js +3 -2
  53. package/dist/server/native-cli-session.js +27 -2
  54. package/dist/server/patch-tool.js +2 -8
  55. package/dist/server/phone-tool.js +167 -0
  56. package/dist/server/plan-mode.js +7 -4
  57. package/dist/server/plan-update-tool.js +5 -8
  58. package/dist/server/plugin-api-catalog.js +13 -1
  59. package/dist/server/plugin-bundled.js +35 -28
  60. package/dist/server/plugin-catalog.js +6 -0
  61. package/dist/server/plugin-delivery.js +358 -0
  62. package/dist/server/plugin-inbox.js +152 -0
  63. package/dist/server/plugin-installer.js +15 -0
  64. package/dist/server/plugin-ledger.js +183 -0
  65. package/dist/server/plugin-manifest-validate.js +19 -0
  66. package/dist/server/plugin-materialize.js +161 -0
  67. package/dist/server/plugin-paths.js +60 -0
  68. package/dist/server/plugin-removal.js +16 -3
  69. package/dist/server/plugin-schedule.js +8 -7
  70. package/dist/server/plugin-secrets.js +7 -3
  71. package/dist/server/plugin-updater.js +2 -4
  72. package/dist/server/plugins.js +205 -48
  73. package/dist/server/present-files-tool.js +7 -13
  74. package/dist/server/preset-fields.js +23 -12
  75. package/dist/server/preset-share.js +1 -1
  76. package/dist/server/process-utils.js +11 -0
  77. package/dist/server/project-scripts.js +38 -0
  78. package/dist/server/prompt-composer.js +40 -21
  79. package/dist/server/protocol-version.js +1 -1
  80. package/dist/server/question-params.js +98 -0
  81. package/dist/server/quick-ask-settings.js +0 -1
  82. package/dist/server/quick-ask.js +3 -0
  83. package/dist/server/read-tool.js +10 -17
  84. package/dist/server/remote-ssh-service.js +40 -1
  85. package/dist/server/sandbox-runtime-gate.js +1 -1
  86. package/dist/server/sandbox-service.js +0 -1
  87. package/dist/server/sandbox-tool.js +25 -34
  88. package/dist/server/schedule-agent-tool.js +9 -19
  89. package/dist/server/scm-commitmsg.js +2 -1
  90. package/dist/server/serialize.js +8 -0
  91. package/dist/server/session-list-index.js +246 -0
  92. package/dist/server/session-list-scan.js +5 -0
  93. package/dist/server/session-parser.js +16 -0
  94. package/dist/server/settings-service.js +49 -19
  95. package/dist/server/skill-tool.js +4 -6
  96. package/dist/server/subagent-budget.js +68 -0
  97. package/dist/server/subagent-evidence.js +297 -0
  98. package/dist/server/subagent-helpers.js +12 -0
  99. package/dist/server/subagent-ledger.js +401 -0
  100. package/dist/server/subagent-notify.js +6 -2
  101. package/dist/server/subagent-security-gate.js +2 -3
  102. package/dist/server/subagent-settle.js +71 -0
  103. package/dist/server/subagents.js +566 -211
  104. package/dist/server/tabs.js +8 -1
  105. package/dist/server/terminals.js +34 -28
  106. package/dist/server/tool-approval.js +15 -1
  107. package/dist/server/tool-guards.js +0 -91
  108. package/dist/server/tool-manager.js +127 -47
  109. package/dist/server/tool-overrides.js +8 -1
  110. package/dist/server/tool-prompt-overrides.js +3 -6
  111. package/dist/server/tool-prompts.js +60 -17
  112. package/dist/server/universal/driver-base.js +2 -0
  113. package/dist/server/universal/drivers/claude-code.js +210 -211
  114. package/dist/server/universal/drivers/codex.js +29 -24
  115. package/dist/server/universal/engine-mcp.js +107 -0
  116. package/dist/server/universal/universal-attachments.js +77 -1
  117. package/dist/server/universal/universal-service.js +1 -1
  118. package/dist/server/universal/universal-session.js +106 -69
  119. package/dist/server/vision-bridge.js +2 -0
  120. package/dist/server/workspace-handle.js +119 -17
  121. package/dist/server/workspace-queue.js +37 -0
  122. package/dist/server/worktree-tool.js +13 -20
  123. package/docs/README.md +40 -36
  124. package/docs/architecture-plugins.md +64 -35
  125. package/docs/device-center.md +1 -1
  126. package/package.json +16 -4
  127. package/plugin-sdk/index.d.ts +102 -0
  128. package/plugins/catalog.json +23 -51
  129. package/themes/bases/flow-base.css +8 -17
  130. package/themes/dark-teal.css +0 -3
  131. package/web/dist/.build-assets.json +1 -1
  132. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  133. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  134. package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  135. package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
  136. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  137. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  138. package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
  139. package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
  140. package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
  141. package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
  142. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  143. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  144. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  145. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  146. package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
  147. package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
  148. package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  149. package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
  150. package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
  151. package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
  152. package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
  153. package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
  154. package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
  155. package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
  156. package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
  157. package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
  158. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  159. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  160. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  161. package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
  162. package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
  163. package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
  164. package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
  165. package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
  166. package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
  167. package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
  168. package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
  169. package/web/dist/assets/index-BD29OL9L.js +404 -0
  170. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  171. package/web/dist/assets/index-DB55rbKC.css +1 -0
  172. package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
  173. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  174. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  175. package/web/dist/index.html +10 -10
  176. package/web/dist/sw.js +1 -1
  177. package/dist/server/edit-soft-tool.js +0 -297
  178. package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
  179. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
  180. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
  181. package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
  182. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
  183. package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
  184. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
  185. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
  186. package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
  187. package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
  188. package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
  189. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
  190. package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
  191. package/web/dist/assets/index-CQc3VrWa.css +0 -1
  192. package/web/dist/assets/index-D_AGu4Zv.js +0 -404
  193. package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
  194. package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
  195. package/web/dist/assets/theme-DGL7hLUs.js +0 -1
@@ -107,7 +107,7 @@ export const DEFAULT_APPROVAL_RULES = [
107
107
  {
108
108
  id: "builtin.file.sensitive.env",
109
109
  enabled: true,
110
- tools: ["write", "edit", "edit_soft", "patch"],
110
+ tools: ["write", "edit", "patch"],
111
111
  field: "path",
112
112
  match: "regex",
113
113
  value: "(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$",
@@ -122,7 +122,7 @@ export const DEFAULT_APPROVAL_RULES = [
122
122
  {
123
123
  id: "builtin.file.sensitive.ssh",
124
124
  enabled: true,
125
- tools: ["write", "edit", "edit_soft", "patch"],
125
+ tools: ["write", "edit", "patch"],
126
126
  field: "path",
127
127
  match: "regex",
128
128
  value: "(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$",
@@ -137,7 +137,7 @@ export const DEFAULT_APPROVAL_RULES = [
137
137
  {
138
138
  id: "builtin.file.sensitive.shell",
139
139
  enabled: true,
140
- tools: ["write", "edit", "edit_soft", "patch"],
140
+ tools: ["write", "edit", "patch"],
141
141
  field: "path",
142
142
  match: "regex",
143
143
  value: "(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$",
@@ -152,7 +152,7 @@ export const DEFAULT_APPROVAL_RULES = [
152
152
  {
153
153
  id: "builtin.file.outside-workspace",
154
154
  enabled: true,
155
- tools: ["write", "edit", "edit_soft", "patch"],
155
+ tools: ["write", "edit", "patch"],
156
156
  field: "path",
157
157
  match: "outside_workspace",
158
158
  value: "",
@@ -1,54 +1,17 @@
1
1
  import { Type } from "typebox";
2
+ import { askQuestionsSchema } from "./question-params.js";
2
3
  export function makeAskUserQuestionTool(clientSession, ownerId) {
3
- const QuestionOptionSchema = Type.Object({
4
- label: Type.String({ description: "Display label (1-5 words)" }),
5
- description: Type.Optional(Type.String({
6
- description: "Short explanation of impact/tradeoff",
7
- })),
8
- preview: Type.Optional(Type.String({
9
- description: "Optional preview (markdown/HTML/code)",
10
- })),
11
- recommended: Type.Optional(Type.Boolean({
12
- description: "Highlight as recommended option",
13
- })),
14
- });
15
- const QuestionSchema = Type.Object({
16
- id: Type.String({ description: "Unique identifier (snake_case)" }),
17
- question: Type.String({ description: "Question text (markdown/HTML ok)" }),
18
- detail: Type.Optional(Type.String({ description: "Optional context under question" })),
19
- header: Type.Optional(Type.String({ description: "Optional short header" })),
20
- options: Type.Optional(Type.Array(QuestionOptionSchema, {
21
- description: "2-4 choices (recommended option first)",
22
- minItems: 2,
23
- maxItems: 4,
24
- })),
25
- multiSelect: Type.Optional(Type.Boolean({ description: "Allow multiple choices (default: false)" })),
26
- dependsOn: Type.Optional(Type.Object({
27
- questionId: Type.String({ description: "Prior question ID" }),
28
- value: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], {
29
- description: "Show when prior answer matches",
30
- })),
31
- })),
32
- optionsMap: Type.Optional(Type.Record(Type.String(), Type.Array(QuestionOptionSchema), {
33
- description: "Dynamic options keyed by prior answer",
34
- })),
35
- });
36
4
  return {
37
5
  name: "ask_user_question",
38
6
  label: "Ask the user",
39
- description: "Ask the user 1-3 focused questions to clarify requirements, confirm decisions, or choose options. " +
40
- "Renders a rich browser dialog; resumes on submit or cancel.",
7
+ description: "Ask the user 1-3 questions via interactive dialog.",
41
8
  promptSnippet: "clarify ambiguous requirements or confirm a decision with the user",
42
9
  promptGuidelines: [
43
10
  "When requirements are ambiguous, clarify with ask_user_question: 1 to 3 focused questions (prefer 1), 2-4 choices with the recommended option first, each with a concise impact/tradeoff",
44
11
  "A cancelled question comes back as a tool error — respect it without immediately re-asking",
45
12
  ],
46
13
  parameters: Type.Object({
47
- questions: Type.Array(QuestionSchema, {
48
- description: "Questions to ask (prefer 1).",
49
- minItems: 1,
50
- maxItems: 3,
51
- }),
14
+ questions: askQuestionsSchema(),
52
15
  }),
53
16
  execute: async (_id, params, signal) => {
54
17
  const qs = params.questions;
@@ -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);
@@ -0,0 +1,235 @@
1
+ /**
2
+ * 后台执行者注册表(Background Executor Registry)
3
+ *
4
+ * 解决的问题:宿主里有四类「无客户端连接也应该活着」的执行者 —— 内置定时任务、常驻插件
5
+ * (QQ/微信/Telegram 等渠道的长连接)、Canvas worker、device-task executor。在此之前
6
+ * 它们各有一套启动时机:定时任务在 `listen` 前直接 `start()`,插件却只能寄生在第一个
7
+ * WebSocket attach 上(`server/index.ts` 的 `ensureLoaded` 调用点),于是「没人打开网页 =
8
+ * QQ 机器人没上线」。
9
+ *
10
+ * 契约:每个执行者声明 `kind: "boot"` 表示进程起来就该跑;`kind: "on-demand"` 只登记不启动。
11
+ * 注册表负责 **启动顺序、失败隔离(一个坏执行者不拖垮其它/不阻断 listen)、健康快照、
12
+ * 按策略的退避重启**。新增后台执行者只需 `register()`,不会再犯「忘记在启动时拉起」的错误。
13
+ *
14
+ * 红线相关:
15
+ * - 探针间隔 60s(远小于 6h 的 `armDelay` 分片门槛),定时器一律 `unref()`。
16
+ * - 重启策略默认 `never`:无人值守时宁可「如实报告 unhealthy」也不要反复拉起抖动的外部连接。
17
+ */
18
+ import { randomUUID } from "node:crypto";
19
+ const DEFAULT_PROBE_MS = 60_000;
20
+ const DEFAULT_RESTART_COOLDOWN_MS = 5 * 60_000;
21
+ const DEFAULT_MAX_RESTARTS = 3;
22
+ export class BackgroundExecutorRegistry {
23
+ entries = new Map();
24
+ now;
25
+ log;
26
+ restartCooldownMs;
27
+ maxRestarts;
28
+ timer = null;
29
+ booted = false;
30
+ constructor(opts = {}) {
31
+ this.now = opts.now ?? Date.now;
32
+ this.log = opts.log ?? (() => { });
33
+ this.restartCooldownMs = opts.restartCooldownMs ?? DEFAULT_RESTART_COOLDOWN_MS;
34
+ this.maxRestarts = opts.maxRestarts ?? DEFAULT_MAX_RESTARTS;
35
+ }
36
+ register(executor) {
37
+ if (!executor.id)
38
+ throw new Error("background executor requires an id");
39
+ if (this.entries.has(executor.id)) {
40
+ throw new Error(`duplicate background executor id: ${executor.id}`);
41
+ }
42
+ this.entries.set(executor.id, {
43
+ executor,
44
+ state: "pending",
45
+ runId: "",
46
+ restarts: 0,
47
+ });
48
+ }
49
+ /** 是否已跑过 boot 阶段(幂等 guard,供 main 流程断言)。 */
50
+ isBooted() {
51
+ return this.booted;
52
+ }
53
+ /**
54
+ * 启动所有 `kind: "boot"` 执行者。**永不抛错** —— 调用方可以安全地在 `listen` 回调里 `void` 它。
55
+ * 返回本次失败的执行者 id,便于日志/单测断言。
56
+ */
57
+ async startAll() {
58
+ if (this.booted)
59
+ return { started: [], failed: [] };
60
+ this.booted = true;
61
+ const started = [];
62
+ const failed = [];
63
+ for (const entry of this.entries.values()) {
64
+ if (entry.executor.kind !== "boot")
65
+ continue;
66
+ const ok = await this.runStart(entry, "boot");
67
+ if (ok)
68
+ started.push(entry.executor.id);
69
+ else
70
+ failed.push(entry.executor.id);
71
+ }
72
+ if (failed.length > 0) {
73
+ this.log("warning", `background executors failed to start: ${failed.join(", ")}`);
74
+ }
75
+ return { started, failed };
76
+ }
77
+ /** 逐个刷新健康快照,并按 `restart: "on-failure"` + 冷却/上限执行重启。永不抛错。 */
78
+ async probe() {
79
+ const at = this.now();
80
+ for (const entry of this.entries.values()) {
81
+ if (entry.state === "stopped")
82
+ continue;
83
+ const health = this.readHealth(entry);
84
+ entry.health = health;
85
+ entry.healthCheckedAt = at;
86
+ if (entry.executor.restart !== "on-failure")
87
+ continue;
88
+ const unhealthy = health ? !health.ok : entry.state === "failed";
89
+ if (!unhealthy)
90
+ continue;
91
+ if (entry.restarts >= this.maxRestarts)
92
+ continue;
93
+ // 冷却以「上次成功启动的时间」为基准:刚拉起的执行者不因首次探针抖动被立刻重启。
94
+ const since = entry.startedAt ?? at;
95
+ if (at - since < this.restartCooldownMs)
96
+ continue;
97
+ entry.restarts += 1;
98
+ this.log("warning", `background executor "${entry.executor.id}" unhealthy, restarting`);
99
+ await this.runStart(entry, "restart");
100
+ }
101
+ }
102
+ /** 启动周期性探针(默认 60s,`unref` 不阻止进程退出)。重复调用无副作用。 */
103
+ startProbing(intervalMs = DEFAULT_PROBE_MS) {
104
+ if (this.timer)
105
+ return;
106
+ const ms = Math.max(1_000, Math.min(intervalMs, 60 * 60_000));
107
+ this.timer = setInterval(() => void this.probe().catch(() => { }), ms);
108
+ this.timer.unref?.();
109
+ }
110
+ stopProbing() {
111
+ if (!this.timer)
112
+ return;
113
+ clearInterval(this.timer);
114
+ this.timer = null;
115
+ }
116
+ async stopAll() {
117
+ this.stopProbing();
118
+ for (const entry of this.entries.values()) {
119
+ if (entry.state === "pending")
120
+ continue;
121
+ entry.state = "stopped";
122
+ const stop = entry.executor.stop;
123
+ if (!stop)
124
+ continue;
125
+ try {
126
+ await stop.call(entry.executor);
127
+ }
128
+ catch (err) {
129
+ this.log("warning", `background executor "${entry.executor.id}" stop failed: ${errText(err)}`);
130
+ }
131
+ }
132
+ }
133
+ /**
134
+ * 实时刷新所有执行者的 health(不触发重启策略)。
135
+ * `/api/health` 必须用这个而不是 `snapshot()` —— 快照里的是上一次探针的值,
136
+ * 运维看到「积压 N 条 / 死信 M 条」时想要的显然是现在。
137
+ */
138
+ refreshHealth() {
139
+ const at = this.now();
140
+ for (const entry of this.entries.values()) {
141
+ if (!entry.executor.health)
142
+ continue;
143
+ entry.health = this.readHealth(entry);
144
+ entry.healthCheckedAt = at;
145
+ }
146
+ }
147
+ /** 刷新后取快照(`/api/health` 专用)。 */
148
+ snapshotLive() {
149
+ this.refreshHealth();
150
+ return this.snapshot();
151
+ }
152
+ snapshot() {
153
+ const out = [];
154
+ for (const entry of this.entries.values()) {
155
+ out.push({
156
+ id: entry.executor.id,
157
+ kind: entry.executor.kind,
158
+ state: entry.state,
159
+ ...(entry.startedAt !== undefined ? { startedAt: entry.startedAt } : {}),
160
+ ...(entry.lastError ? { lastError: entry.lastError } : {}),
161
+ restarts: entry.restarts,
162
+ ...(entry.health ? { health: entry.health } : {}),
163
+ ...(entry.healthCheckedAt !== undefined ? { healthCheckedAt: entry.healthCheckedAt } : {}),
164
+ });
165
+ }
166
+ return out;
167
+ }
168
+ /** `/api/health` 用的紧凑视图:只有不 healthy 的才算问题。 */
169
+ unhealthy() {
170
+ const out = [];
171
+ for (const entry of this.entries.values()) {
172
+ if (entry.executor.kind !== "boot")
173
+ continue;
174
+ if (entry.state === "pending") {
175
+ out.push({ id: entry.executor.id, state: entry.state, detail: "not started yet" });
176
+ continue;
177
+ }
178
+ if (entry.state === "failed") {
179
+ out.push({ id: entry.executor.id, state: entry.state, detail: entry.lastError ?? "start failed" });
180
+ continue;
181
+ }
182
+ if (entry.health && !entry.health.ok) {
183
+ out.push({ id: entry.executor.id, state: entry.state, detail: entry.health.detail ?? "unhealthy" });
184
+ }
185
+ }
186
+ return out;
187
+ }
188
+ readHealth(entry) {
189
+ const fn = entry.executor.health;
190
+ if (!fn)
191
+ return undefined;
192
+ try {
193
+ const h = fn.call(entry.executor);
194
+ if (!h || typeof h !== "object")
195
+ return { ok: true };
196
+ return h;
197
+ }
198
+ catch (err) {
199
+ return { ok: false, detail: `health() threw: ${errText(err)}` };
200
+ }
201
+ }
202
+ /** 单次启动;失败只记录,不抛。 */
203
+ async runStart(entry, reason) {
204
+ const id = entry.executor.id;
205
+ entry.runId = randomUUID();
206
+ const runId = entry.runId;
207
+ entry.state = "running";
208
+ entry.startedAt = this.now();
209
+ entry.lastError = undefined;
210
+ entry.health = undefined;
211
+ entry.healthCheckedAt = undefined;
212
+ try {
213
+ await entry.executor.start();
214
+ // start() 期间被 stop/dispose 抢占:不要把它标成健康。
215
+ if (entry.runId !== runId)
216
+ return false;
217
+ if (reason === "restart")
218
+ this.log("info", `background executor "${id}" restarted`);
219
+ return true;
220
+ }
221
+ catch (err) {
222
+ if (entry.runId !== runId)
223
+ return false;
224
+ entry.state = "failed";
225
+ entry.lastError = errText(err);
226
+ this.log("error", `background executor "${id}" ${reason} failed: ${entry.lastError}`);
227
+ return false;
228
+ }
229
+ }
230
+ }
231
+ function errText(err) {
232
+ if (err instanceof Error)
233
+ return err.message;
234
+ return String(err);
235
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * bash 工具的默认硬超时(秒)。
3
+ * 模型漏传 `timeout` 时兜底:否则该次调用毫无时限,只能等会话级工具看门狗(默认 20 分钟)收尸,
4
+ * 期间工具卡片一直转、用户看到的是"卡死"。默认值可用 `PI_WEB_BASH_TIMEOUT_SEC` 覆盖。
5
+ */
6
+ export const DEFAULT_BASH_TIMEOUT_SEC = 120;
7
+ /**
8
+ * 上限(秒)。SDK 自己的 MAX 是 2^31 ms(≈24 天),等于没有护栏:
9
+ * 真跑得久请用 `--detach` 后台托管或持久终端,而不是把单次调用挂成"不死鸟"。
10
+ */
11
+ export const MAX_BASH_TIMEOUT_SEC = 3600;
12
+ export function defaultBashTimeoutSec() {
13
+ const raw = Number(process.env.PI_WEB_BASH_TIMEOUT_SEC);
14
+ if (!Number.isFinite(raw) || raw <= 0)
15
+ return DEFAULT_BASH_TIMEOUT_SEC;
16
+ return Math.min(Math.ceil(raw), MAX_BASH_TIMEOUT_SEC);
17
+ }
18
+ /**
19
+ * 归一化模型给的 timeout:缺失 / 0 / 负数 / 非有限值一律回落到默认值
20
+ * (SDK 对 0 与负数直接抛 `Invalid timeout`,让它抛错不如按默认值跑),过大的值夹到上限。
21
+ */
22
+ export function resolveBashTimeoutSec(requested) {
23
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0)
24
+ return defaultBashTimeoutSec();
25
+ return Math.min(Math.ceil(requested), MAX_BASH_TIMEOUT_SEC);
26
+ }
27
+ /** 给任何 bash 参数对象补上生效的 timeout;值未变时原样返回,免得多造对象。 */
28
+ export function withDefaultBashTimeout(params) {
29
+ const requested = params?.timeout;
30
+ const timeout = resolveBashTimeoutSec(requested);
31
+ return (timeout === requested ? params : { ...params, timeout });
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,9 +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";
5
+ import { resolveBackgroundTimeoutSec, withDefaultBashTimeout } from "./bash-timeout.js";
4
6
  import { getGlobalRemoteSshService, isRemoteWorkspaceUri, restoreWorkspaceUriFromSessionDir, } from "./remote-ssh-service.js";
5
- export function makeKillableBashTool(cwd, kills, lang = () => "en") {
6
- 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) });
7
24
  const tool = createBashToolDefinition(cwd, {
8
25
  operations: {
9
26
  exec: async (command, c, opts) => {
@@ -49,8 +66,55 @@ export function makeKillableBashTool(cwd, kills, lang = () => "en") {
49
66
  prepareArguments: tool.prepareArguments,
50
67
  executionMode: tool.executionMode,
51
68
  execute: async (toolCallId, params, signal, onUpdate, ctx) => {
52
- const result = (await tool.execute(toolCallId, params, signal, onUpdate, ctx));
53
- const p = params;
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
+ }
114
+ // 模型漏传 timeout 时不给"无时限":默认 120s,由 server/bash-timeout.ts 单源归一。
115
+ const effective = withDefaultBashTimeout(params);
116
+ const result = (await tool.execute(toolCallId, effective, signal, onUpdate, ctx));
117
+ const p = effective;
54
118
  if ((p?.head || p?.tail) && result?.content?.[0]?.text != null) {
55
119
  result.content[0].text = applyHeadTail(result.content[0].text, p.head, p.tail, lang());
56
120
  }
@@ -63,6 +127,9 @@ export function makeAdaptiveBashTool(killable, terminalBacked, useTerminal) {
63
127
  ...killable,
64
128
  execute: (id, params, signal, onUpdate, ctx) => {
65
129
  const p = params;
130
+ // background 永远走 job registry:PTY 后端没有后台契约(scrollback 无日志、分不清退出原因)。
131
+ if (p?.background === true)
132
+ return killable.execute(id, params, signal, onUpdate, ctx);
66
133
  const shouldUseTerminal = useTerminal() && (process.platform !== "win32" || p?.persist === true);
67
134
  return (shouldUseTerminal ? terminalBacked : killable).execute(id, params, signal, onUpdate, ctx);
68
135
  },