pi-web-ui 0.113.1 → 0.114.1

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 (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -27,7 +27,7 @@ export class DurableAgentService {
27
27
  this.cwd = opts.cwd;
28
28
  this.dataDir = opts.dataDir;
29
29
  this.agentDir = opts.agentDir;
30
- this.store = new UniversalSessionStore(opts.dataDir);
30
+ this.store = new UniversalSessionStore(opts.dataDir, "durable");
31
31
  this.stateStore = opts.stateStore;
32
32
  }
33
33
  async attach(clientId, send) {
@@ -5,6 +5,7 @@ import { VERSION } from "@earendil-works/pi-coding-agent";
5
5
  import { runtimeBaseCandidates } from "./dsh/preset-clones.js";
6
6
  import { killPidTree } from "./process-utils.js";
7
7
  import { probeClaudeCode } from "./universal/drivers/claude-code.js";
8
+ import { probeCodex } from "./universal/drivers/codex.js";
8
9
  import { compareVersions, defaultFetcher, fetchLatest, NPM_DEFAULT_REGISTRY, } from "./update-check.js";
9
10
  import { probeGlobalPackage } from "./global-loader.js";
10
11
  export const ENGINE_PACKAGES = {
@@ -23,6 +24,11 @@ export const ENGINE_PACKAGES = {
23
24
  packageName: "@anthropic-ai/claude-code",
24
25
  installCommand: "npm i -g @anthropic-ai/claude-code",
25
26
  },
27
+ codex: {
28
+ id: "codex",
29
+ packageName: "@openai/codex",
30
+ installCommand: "npm i -g @openai/codex",
31
+ },
26
32
  durable: {
27
33
  id: "durable",
28
34
  packageName: "@earendil-works/pi-durable",
@@ -60,6 +66,14 @@ const engineRegistry = new Map([
60
66
  updating: false,
61
67
  },
62
68
  ],
69
+ [
70
+ "codex",
71
+ {
72
+ status: { id: "codex", installed: false, packageName: ENGINE_PACKAGES.codex.packageName },
73
+ probedAt: 0,
74
+ updating: false,
75
+ },
76
+ ],
63
77
  [
64
78
  "durable",
65
79
  {
@@ -128,11 +142,11 @@ export function probePi() {
128
142
  * 1. 优先检查常见全局 node_modules / 候选路径中的 @deepseek-ai/dsh package.json 与 dsh-base;
129
143
  * 2. 回退通过命令行探针执行 `dsh --version`。
130
144
  */
131
- export async function probeDsh() {
145
+ export async function probeDsh(force = false) {
132
146
  const pkgName = ENGINE_PACKAGES.dsh.packageName;
133
147
  // 0. 通用全局包探测器(覆盖 fnm / nvm / pnpm / 全局 prefix 等)
134
148
  try {
135
- const globalProbe = probeGlobalPackage(pkgName);
149
+ const globalProbe = probeGlobalPackage(pkgName, { refresh: force });
136
150
  if (globalProbe.installed) {
137
151
  return { id: "dsh", installed: true, packageName: pkgName, version: globalProbe.version };
138
152
  }
@@ -274,11 +288,20 @@ export async function probeEngine(id, force = false) {
274
288
  }
275
289
  let result;
276
290
  if (id === "dsh") {
277
- result = await probeDsh();
291
+ result = await probeDsh(force);
278
292
  }
279
293
  else if (id === "claude") {
280
294
  result = await probeClaude(force);
281
295
  }
296
+ else if (id === "codex") {
297
+ const probe = await probeCodex();
298
+ result = {
299
+ id: "codex",
300
+ installed: probe.available,
301
+ version: probe.version,
302
+ packageName: ENGINE_PACKAGES.codex.packageName,
303
+ };
304
+ }
282
305
  else if (id === "durable") {
283
306
  result = await probeDurable(force);
284
307
  }
@@ -304,20 +327,27 @@ export async function probeAllEngines(force = false) {
304
327
  if (!force && allFresh && entries.length > 0) {
305
328
  return entries.map(toPublicStatus);
306
329
  }
307
- const [pi, dsh, claude, durable] = await Promise.all([
330
+ const [pi, dsh, claude, durable, codex] = await Promise.all([
308
331
  probePi(),
309
- probeDsh(),
332
+ probeDsh(force),
310
333
  probeClaude(force),
311
334
  probeDurable(force),
335
+ probeCodex().then((probe) => ({
336
+ id: "codex",
337
+ installed: probe.available,
338
+ version: probe.version,
339
+ packageName: ENGINE_PACKAGES.codex.packageName,
340
+ })),
312
341
  ]);
313
342
  await Promise.all([
314
343
  enrichWithUpdateInfo(pi, force),
315
344
  enrichWithUpdateInfo(dsh, force),
316
345
  enrichWithUpdateInfo(claude, force),
317
346
  enrichWithUpdateInfo(durable, force),
347
+ enrichWithUpdateInfo(codex, force),
318
348
  ]);
319
349
  const timestamp = Date.now();
320
- const results = [pi, dsh, claude, durable];
350
+ const results = [pi, dsh, claude, durable, codex];
321
351
  for (const res of results) {
322
352
  const existing = engineRegistry.get(res.id);
323
353
  engineRegistry.set(res.id, {
@@ -67,142 +67,142 @@ function resolvePythonCmd() {
67
67
  }
68
68
  return null;
69
69
  }
70
- const PYTHON_DRIVER_SCRIPT = `
71
- import sys, io, ast, json, traceback, os
72
-
73
- # 跨平台编码对齐:Windows 默认代码页(如 CP936/GBK)读取 UTF-8 管道会导致多字节截断、
74
- # 反斜杠被吞噬破坏 JSON 结构(报 Expecting ',' delimiter)或触发 UnicodeDecodeError。
75
- # 强制标准流一律按 UTF-8 重配并附带容错替换策略,避免解码死锁。
76
- if hasattr(sys.stdin, "reconfigure"):
77
- sys.stdin.reconfigure(encoding="utf-8", errors="replace")
78
- if hasattr(sys.stdout, "reconfigure"):
79
- sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
80
- if hasattr(sys.stderr, "reconfigure"):
81
- sys.stderr.reconfigure(encoding="utf-8", errors="backslashreplace")
82
-
83
- WORKDIR = os.environ.get('PI_EVAL_WORKDIR', '')
84
- PROJECT_DIR = os.environ.get('PI_EVAL_PROJECT_DIR', '')
85
-
86
- _scope = {'__name__': '__main__', 'WORKDIR': WORKDIR, 'PROJECT_DIR': PROJECT_DIR}
87
-
88
- def run_cell(code):
89
- out = io.StringIO()
90
- err = io.StringIO()
91
- old_out, old_err = sys.stdout, sys.stderr
92
- sys.stdout, sys.stderr = out, err
93
- res = None
94
- exc = None
95
- try:
96
- parsed = ast.parse(code)
97
- if parsed.body and isinstance(parsed.body[-1], ast.Expr):
98
- last = parsed.body.pop()
99
- if parsed.body:
100
- exec(compile(parsed, '<eval>', 'exec'), _scope)
101
- res = eval(compile(ast.Expression(last.value), '<eval>', 'eval'), _scope)
102
- else:
103
- exec(compile(code, '<eval>', 'exec'), _scope)
104
- except Exception:
105
- exc = traceback.format_exc()
106
- finally:
107
- sys.stdout, sys.stderr = old_out, old_err
108
- return {
109
- 'stdout': out.getvalue(),
110
- 'stderr': err.getvalue(),
111
- 'result': repr(res) if res is not None else None,
112
- 'error': exc
113
- }
114
-
115
- for line in sys.stdin:
116
- if not line.strip():
117
- continue
118
- try:
119
- req = json.loads(line)
120
- if req.get('action') == 'reset':
121
- _scope.clear()
122
- _scope['__name__'] = '__main__'
123
- _scope['WORKDIR'] = WORKDIR
124
- _scope['PROJECT_DIR'] = PROJECT_DIR
125
- resp = {'ok': True, 'stdout': '', 'stderr': '', 'result': None, 'error': None}
126
- else:
127
- resp = run_cell(req.get('code', ''))
128
- resp['ok'] = resp['error'] is None
129
- except Exception as e:
130
- resp = {'ok': False, 'stdout': '', 'stderr': '', 'result': None, 'error': traceback.format_exc()}
131
-
132
- sys.stdout.write('__PI_EVAL_RES__' + json.dumps(resp, ensure_ascii=True) + '\\n')
133
- sys.stdout.flush()
70
+ const PYTHON_DRIVER_SCRIPT = `
71
+ import sys, io, ast, json, traceback, os
72
+
73
+ # 跨平台编码对齐:Windows 默认代码页(如 CP936/GBK)读取 UTF-8 管道会导致多字节截断、
74
+ # 反斜杠被吞噬破坏 JSON 结构(报 Expecting ',' delimiter)或触发 UnicodeDecodeError。
75
+ # 强制标准流一律按 UTF-8 重配并附带容错替换策略,避免解码死锁。
76
+ if hasattr(sys.stdin, "reconfigure"):
77
+ sys.stdin.reconfigure(encoding="utf-8", errors="replace")
78
+ if hasattr(sys.stdout, "reconfigure"):
79
+ sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
80
+ if hasattr(sys.stderr, "reconfigure"):
81
+ sys.stderr.reconfigure(encoding="utf-8", errors="backslashreplace")
82
+
83
+ WORKDIR = os.environ.get('PI_EVAL_WORKDIR', '')
84
+ PROJECT_DIR = os.environ.get('PI_EVAL_PROJECT_DIR', '')
85
+
86
+ _scope = {'__name__': '__main__', 'WORKDIR': WORKDIR, 'PROJECT_DIR': PROJECT_DIR}
87
+
88
+ def run_cell(code):
89
+ out = io.StringIO()
90
+ err = io.StringIO()
91
+ old_out, old_err = sys.stdout, sys.stderr
92
+ sys.stdout, sys.stderr = out, err
93
+ res = None
94
+ exc = None
95
+ try:
96
+ parsed = ast.parse(code)
97
+ if parsed.body and isinstance(parsed.body[-1], ast.Expr):
98
+ last = parsed.body.pop()
99
+ if parsed.body:
100
+ exec(compile(parsed, '<eval>', 'exec'), _scope)
101
+ res = eval(compile(ast.Expression(last.value), '<eval>', 'eval'), _scope)
102
+ else:
103
+ exec(compile(code, '<eval>', 'exec'), _scope)
104
+ except Exception:
105
+ exc = traceback.format_exc()
106
+ finally:
107
+ sys.stdout, sys.stderr = old_out, old_err
108
+ return {
109
+ 'stdout': out.getvalue(),
110
+ 'stderr': err.getvalue(),
111
+ 'result': repr(res) if res is not None else None,
112
+ 'error': exc
113
+ }
114
+
115
+ for line in sys.stdin:
116
+ if not line.strip():
117
+ continue
118
+ try:
119
+ req = json.loads(line)
120
+ if req.get('action') == 'reset':
121
+ _scope.clear()
122
+ _scope['__name__'] = '__main__'
123
+ _scope['WORKDIR'] = WORKDIR
124
+ _scope['PROJECT_DIR'] = PROJECT_DIR
125
+ resp = {'ok': True, 'stdout': '', 'stderr': '', 'result': None, 'error': None}
126
+ else:
127
+ resp = run_cell(req.get('code', ''))
128
+ resp['ok'] = resp['error'] is None
129
+ except Exception as e:
130
+ resp = {'ok': False, 'stdout': '', 'stderr': '', 'result': None, 'error': traceback.format_exc()}
131
+
132
+ sys.stdout.write('__PI_EVAL_RES__' + json.dumps(resp, ensure_ascii=True) + '\\n')
133
+ sys.stdout.flush()
134
134
  `;
135
- const NODE_DRIVER_SCRIPT = `
136
- import repl from "node:repl";
137
- import { PassThrough } from "node:stream";
138
- import readline from "node:readline";
139
-
140
- let server;
141
- function createRepl() {
142
- const inStream = new PassThrough();
143
- const outStream = new PassThrough();
144
- server = repl.start({
145
- input: inStream,
146
- output: outStream,
147
- terminal: false,
148
- useColors: false,
149
- preview: false
150
- });
151
- server.context.console = console;
152
- server.context.setTimeout = setTimeout;
153
- server.context.clearTimeout = clearTimeout;
154
- server.context.setInterval = setInterval;
155
- server.context.clearInterval = clearInterval;
156
- server.context.Buffer = Buffer;
157
- server.context.URL = URL;
158
- server.context.WORKDIR = process.env.PI_EVAL_WORKDIR || "";
159
- server.context.PROJECT_DIR = process.env.PI_EVAL_PROJECT_DIR || "";
160
- }
161
- createRepl();
162
-
163
- const rl = readline.createInterface({ input: process.stdin });
164
- rl.on("line", (line) => {
165
- if (!line.trim()) return;
166
- try {
167
- const req = JSON.parse(line);
168
- if (req.action === "reset") {
169
- createRepl();
170
- process.stdout.write("__PI_EVAL_RES__" + JSON.stringify({ ok: true, stdout: "", stderr: "", result: null, error: null }) + "\\n");
171
- return;
172
- }
173
- let capturedOut = "";
174
- let capturedErr = "";
175
- const origLog = server.context.console.log;
176
- const origErr = server.context.console.error;
177
- const origWarn = server.context.console.warn;
178
- server.context.console.log = (...args) => {
179
- capturedOut += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
180
- };
181
- server.context.console.error = (...args) => {
182
- capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
183
- };
184
- server.context.console.warn = (...args) => {
185
- capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
186
- };
187
-
188
- server.eval(req.code, server.context, "eval", (err, result) => {
189
- server.context.console.log = origLog;
190
- server.context.console.error = origErr;
191
- server.context.console.warn = origWarn;
192
- const resp = {
193
- ok: !err,
194
- stdout: capturedOut,
195
- stderr: capturedErr,
196
- result: result !== undefined ? (typeof result === "string" ? result : JSON.stringify(result, null, 2)) : null,
197
- error: err ? (err.stack || String(err)) : null
198
- };
199
- process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
200
- });
201
- } catch (e) {
202
- const resp = { ok: false, stdout: "", stderr: "", result: null, error: e.stack || String(e) };
203
- process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
204
- }
205
- });
135
+ const NODE_DRIVER_SCRIPT = `
136
+ import repl from "node:repl";
137
+ import { PassThrough } from "node:stream";
138
+ import readline from "node:readline";
139
+
140
+ let server;
141
+ function createRepl() {
142
+ const inStream = new PassThrough();
143
+ const outStream = new PassThrough();
144
+ server = repl.start({
145
+ input: inStream,
146
+ output: outStream,
147
+ terminal: false,
148
+ useColors: false,
149
+ preview: false
150
+ });
151
+ server.context.console = console;
152
+ server.context.setTimeout = setTimeout;
153
+ server.context.clearTimeout = clearTimeout;
154
+ server.context.setInterval = setInterval;
155
+ server.context.clearInterval = clearInterval;
156
+ server.context.Buffer = Buffer;
157
+ server.context.URL = URL;
158
+ server.context.WORKDIR = process.env.PI_EVAL_WORKDIR || "";
159
+ server.context.PROJECT_DIR = process.env.PI_EVAL_PROJECT_DIR || "";
160
+ }
161
+ createRepl();
162
+
163
+ const rl = readline.createInterface({ input: process.stdin });
164
+ rl.on("line", (line) => {
165
+ if (!line.trim()) return;
166
+ try {
167
+ const req = JSON.parse(line);
168
+ if (req.action === "reset") {
169
+ createRepl();
170
+ process.stdout.write("__PI_EVAL_RES__" + JSON.stringify({ ok: true, stdout: "", stderr: "", result: null, error: null }) + "\\n");
171
+ return;
172
+ }
173
+ let capturedOut = "";
174
+ let capturedErr = "";
175
+ const origLog = server.context.console.log;
176
+ const origErr = server.context.console.error;
177
+ const origWarn = server.context.console.warn;
178
+ server.context.console.log = (...args) => {
179
+ capturedOut += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
180
+ };
181
+ server.context.console.error = (...args) => {
182
+ capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
183
+ };
184
+ server.context.console.warn = (...args) => {
185
+ capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
186
+ };
187
+
188
+ server.eval(req.code, server.context, "eval", (err, result) => {
189
+ server.context.console.log = origLog;
190
+ server.context.console.error = origErr;
191
+ server.context.console.warn = origWarn;
192
+ const resp = {
193
+ ok: !err,
194
+ stdout: capturedOut,
195
+ stderr: capturedErr,
196
+ result: result !== undefined ? (typeof result === "string" ? result : JSON.stringify(result, null, 2)) : null,
197
+ error: err ? (err.stack || String(err)) : null
198
+ };
199
+ process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
200
+ });
201
+ } catch (e) {
202
+ const resp = { ok: false, stdout: "", stderr: "", result: null, error: e.stack || String(e) };
203
+ process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
204
+ }
205
+ });
206
206
  `;
207
207
  /**
208
208
  * 净化 Eval 子进程环境变量:仅保留操作系统基础变量,剥离所有包含 key/token/secret/auth/cred 等敏感环境变量,
@@ -0,0 +1,49 @@
1
+ import { join } from "node:path";
2
+ const installed = new WeakMap();
3
+ const PREFIX = "context-evidence:";
4
+ /** Resolve evidence before SDK permission hooks; leave all file access to the reader. */
5
+ export function installEvidenceToolHooks(session) {
6
+ if (!session || typeof session !== "object")
7
+ return false;
8
+ const target = session;
9
+ const original = target._beforeToolCall;
10
+ if (typeof original !== "function" || original.length !== 2)
11
+ return false;
12
+ if (installed.get(target) === original)
13
+ return true;
14
+ if (typeof target.sessionManager?.getSessionFile !== "function")
15
+ return false;
16
+ const wrapper = function (context, parentId) {
17
+ if (context.toolCall.name === "read" && context.args && typeof context.args === "object") {
18
+ const args = context.args;
19
+ const values = [args.path, args.file_path];
20
+ const references = values.filter((value) => typeof value === "string" && value.startsWith(PREFIX));
21
+ if (references.length) {
22
+ context.signal?.throwIfAborted();
23
+ const reference = references[0];
24
+ const match = /^context-evidence:([a-f0-9]{64})$/.exec(reference);
25
+ const isIndex = reference === `${PREFIX}index`;
26
+ if ((!isIndex && (!match || reference.length !== PREFIX.length + 64)) ||
27
+ values.some((value) => value !== undefined && value !== reference)) {
28
+ throw new Error("Invalid or conflicting evidence reference");
29
+ }
30
+ const sessionFile = target.sessionManager.getSessionFile();
31
+ if (!sessionFile)
32
+ throw new Error("Evidence requires a persisted session");
33
+ // SDK validated args must be detached from the immutable transcript block.
34
+ if (args === context.toolCall.arguments) {
35
+ throw new Error("Evidence arguments must not alias tool call history");
36
+ }
37
+ context.signal?.throwIfAborted();
38
+ const directory = `${sessionFile}.evidence`;
39
+ const path = isIndex ? directory : join(directory, `${match[1]}.txt`);
40
+ args.path = path;
41
+ args.file_path = path;
42
+ }
43
+ }
44
+ return original.call(this, context, parentId);
45
+ };
46
+ target._beforeToolCall = wrapper;
47
+ installed.set(target, wrapper);
48
+ return true;
49
+ }
@@ -0,0 +1,95 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access, mkdtemp, open, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ const run = promisify(execFile);
7
+ const timeout = 30_000;
8
+ const attributes = "--preserve=mode,ownership,timestamps,xattr";
9
+ /** Save an existing regular file without truncating it or silently discarding
10
+ * platform metadata. All preparation happens on the target volume. Native
11
+ * metadata/replace failures are fatal; there is no direct-write fallback.
12
+ * This provides atomic visibility, not a guarantee against power loss.
13
+ */
14
+ export async function saveFilePreservingMetadata(path, text) {
15
+ const target = await realpath(path); // Keep symlinks, replace their actual target.
16
+ const before = await stat(target);
17
+ if (!before.isFile())
18
+ throw new Error("Save target is not a regular file");
19
+ if (before.nlink > 1)
20
+ throw new Error("Cannot atomically save a file with multiple hard links");
21
+ await access(target, constants.W_OK);
22
+ if (!["win32", "linux", "darwin", "freebsd"].includes(process.platform))
23
+ throw new Error(`Metadata-preserving saves are unsupported on ${process.platform}`);
24
+ const stageDir = await mkdtemp(join(dirname(target), ".pi-save-"));
25
+ const staged = join(stageDir, "content");
26
+ const backup = join(stageDir, "original");
27
+ let committed = false;
28
+ try {
29
+ if (process.platform !== "win32") {
30
+ await run("cp", process.platform === "linux" ? [attributes, "--", target, staged] : ["-p", target, staged], {
31
+ timeout,
32
+ });
33
+ }
34
+ const handle = await open(staged, process.platform === "win32" ? "wx" : "r+", 0o600);
35
+ try {
36
+ await handle.writeFile(text, "utf8");
37
+ await handle.truncate(Buffer.byteLength(text, "utf8"));
38
+ await handle.sync();
39
+ }
40
+ finally {
41
+ await handle.close();
42
+ }
43
+ if (process.platform === "linux") {
44
+ // Writing can clear security xattrs/set-id bits. Reapply explicitly:
45
+ // unlike --preserve=all, failure to preserve a named attribute is fatal.
46
+ await run("cp", ["--attributes-only", attributes, "--", target, staged], { timeout });
47
+ const metadataHandle = await open(staged, "r");
48
+ try {
49
+ await metadataHandle.sync();
50
+ }
51
+ finally {
52
+ await metadataHandle.close();
53
+ }
54
+ }
55
+ const current = await stat(target);
56
+ if (current.dev !== before.dev ||
57
+ current.ino !== before.ino ||
58
+ current.nlink > 1 ||
59
+ current.size !== before.size ||
60
+ current.mtimeMs !== before.mtimeMs ||
61
+ current.ctimeMs !== before.ctimeMs)
62
+ throw new Error("Save target changed while preparing replacement; retry saving");
63
+ if (process.platform === "win32") {
64
+ // Constant script + environment paths: filenames never become PowerShell
65
+ // code. Start one process per explicit save, without a shell/profile.
66
+ const script = "$ErrorActionPreference='Stop'; try { [IO.File]::Replace($env:PI_SAVE_SOURCE,$env:PI_SAVE_TARGET,$env:PI_SAVE_BACKUP,$false) } catch { [Console]::Error.WriteLine($_.Exception.ToString()); exit 1 }";
67
+ await run("powershell.exe", [
68
+ "-NoLogo",
69
+ "-NoProfile",
70
+ "-NonInteractive",
71
+ "-EncodedCommand",
72
+ Buffer.from(script, "utf16le").toString("base64"),
73
+ ], {
74
+ timeout,
75
+ windowsHide: true,
76
+ env: { ...process.env, PI_SAVE_SOURCE: staged, PI_SAVE_TARGET: target, PI_SAVE_BACKUP: backup },
77
+ });
78
+ }
79
+ else
80
+ await rename(staged, target);
81
+ committed = true;
82
+ }
83
+ catch (error) {
84
+ // ReplaceFile can fail part-way through a metadata merge. Never delete
85
+ // its recovery backup on error; expose its stable path to the caller.
86
+ if (await stat(backup).then(() => true, () => false))
87
+ throw new Error(`Save failed; recovery file retained at ${backup}`, { cause: error });
88
+ throw error;
89
+ }
90
+ finally {
91
+ const hasBackup = await stat(backup).then(() => true, () => false);
92
+ if (committed || !hasBackup)
93
+ await rm(stageDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
94
+ }
95
+ }