pi-web-ui 0.116.0 → 0.117.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 (155) hide show
  1. package/CHANGELOG.md +38 -4
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +138 -70
  4. package/dist/server/agent-service-daemon.js +52 -6
  5. package/dist/server/agent-service.js +495 -141
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +35 -6
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +48 -1
  11. package/dist/server/device-center/collab-service.js +26 -8
  12. package/dist/server/device-center/collab-tool.js +394 -18
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +15 -5
  18. package/dist/server/device-center/executor.js +47 -5
  19. package/dist/server/device-center/hub-conversations.js +14 -4
  20. package/dist/server/device-center/hub-deliveries.js +120 -15
  21. package/dist/server/device-center/hub-integration.js +655 -334
  22. package/dist/server/device-center/hub-page.js +5 -4
  23. package/dist/server/device-center/hub-setup.js +23 -1
  24. package/dist/server/device-center/hub-transaction-log.js +197 -0
  25. package/dist/server/device-center/hub.js +772 -354
  26. package/dist/server/device-center/integration-verification.js +113 -0
  27. package/dist/server/device-center/local-hub.js +6 -2
  28. package/dist/server/device-center/local-publication.js +423 -0
  29. package/dist/server/device-center/local-verification-job.js +97 -0
  30. package/dist/server/device-center/local-verification.js +274 -0
  31. package/dist/server/device-center/local.js +107 -12
  32. package/dist/server/device-center/main.js +4 -1
  33. package/dist/server/device-center/partition-log.js +62 -25
  34. package/dist/server/device-center/publication-journal.js +312 -0
  35. package/dist/server/device-center/publish-intent.js +379 -0
  36. package/dist/server/device-center/relay.js +134 -24
  37. package/dist/server/device-center/runtime.js +426 -42
  38. package/dist/server/device-center/store.js +225 -47
  39. package/dist/server/device-center/task-outcome.js +81 -0
  40. package/dist/server/device-center/task-recovery.js +603 -178
  41. package/dist/server/device-center/task-settlement.js +353 -0
  42. package/dist/server/device-center/task-workspace.js +443 -0
  43. package/dist/server/device-center/verification-limits.js +10 -0
  44. package/dist/server/device-center/work-contract.js +995 -0
  45. package/dist/server/dispatch-domain-handlers.js +15 -0
  46. package/dist/server/dsh/dsh-agent-service.js +9 -2
  47. package/dist/server/index.js +26 -1
  48. package/dist/server/patch-node-pty.js +3 -2
  49. package/dist/server/patch-remote-catalog.js +3 -2
  50. package/dist/server/preset-fields.js +17 -1
  51. package/dist/server/preset-share.js +1 -0
  52. package/dist/server/protocol-version.js +1 -1
  53. package/dist/server/quick-ask-settings.js +28 -0
  54. package/dist/server/quick-ask.js +164 -0
  55. package/dist/server/resolve-global-sdk.js +61 -11
  56. package/dist/server/scheduler-tasks.js +35 -8
  57. package/dist/server/session-list-scan.js +223 -0
  58. package/dist/server/session-open.js +93 -0
  59. package/dist/server/session-parser.js +4 -0
  60. package/dist/server/session-scan.js +90 -38
  61. package/dist/server/settings-service.js +9 -1
  62. package/dist/server/soft-cap.js +5 -0
  63. package/dist/server/transcript-prepare.js +73 -0
  64. package/dist/server/universal/drivers/claude-code.js +98 -34
  65. package/dist/server/universal/universal-session.js +4 -0
  66. package/dist/server/workspace-handle.js +428 -0
  67. package/docs/architecture-plugins.md +18 -5
  68. package/docs/device-center.md +30 -22
  69. package/package.json +3 -4
  70. package/plugin-sdk/README.md +16 -8
  71. package/plugin-sdk/client.d.ts +27 -0
  72. package/plugin-sdk/client.mjs +82 -0
  73. package/plugin-sdk/index.d.ts +10 -0
  74. package/plugin-sdk/index.mjs +4 -683
  75. package/plugin-sdk/package.json +15 -4
  76. package/plugin-sdk/testing.d.ts +10 -0
  77. package/plugin-sdk/testing.mjs +566 -0
  78. package/themes/flow-cristallo.css +168 -0
  79. package/themes/flow-ink.css +169 -0
  80. package/themes/flow-obsidian.css +169 -0
  81. package/themes/flow-zurich.css +169 -0
  82. package/web/dist/.build-assets.json +1 -1
  83. package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
  84. package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
  85. package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  86. package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
  87. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  88. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  89. package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
  90. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  91. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  92. package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
  93. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  94. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  95. package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  96. package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  97. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  98. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  99. package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
  100. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  101. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  102. package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
  103. package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  104. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  105. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  106. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  107. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  108. package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
  109. package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
  110. package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  111. package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  112. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  113. package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
  114. package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
  115. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  116. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  117. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  118. package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
  119. package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  120. package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
  121. package/web/dist/index.html +11 -11
  122. package/web/dist/sw.js +1 -1
  123. package/dist/gh-comment-781.md +0 -5
  124. package/dist/server/device-center/local-page.js +0 -17
  125. package/dist/server/device-center/smoke-preview.js +0 -3
  126. package/dist/server/durable/durable-capabilities.js +0 -11
  127. package/dist/server/markers/builtins/services.js +0 -123
  128. package/dist/server/markers/builtins/todo.js +0 -189
  129. package/dist/server/markers-list-tool.js +0 -34
  130. package/dist/server/orchestrator.js +0 -109
  131. package/dist/server/patch-turn-end-boundary.js +0 -77
  132. package/dist/server/system-prompt-soul.js +0 -41
  133. package/dist/server/univer-service.js +0 -448
  134. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  135. package/dist/test-artifact.md +0 -9
  136. package/dist/test-preview-modal.md +0 -11
  137. package/dist/test-report.html +0 -20
  138. package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
  139. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
  140. package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
  141. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
  142. package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
  143. package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
  144. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
  145. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
  146. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
  147. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
  148. package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
  149. package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
  150. package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
  151. package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
  152. package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
  153. package/web/dist/assets/index-C6DwztqE.css +0 -1
  154. package/web/dist/assets/index-CuN802Sj.js +0 -93
  155. package/web/dist/assets/index-EH5Fw9fa.js +0 -93
@@ -1,79 +1,10 @@
1
- import { execFile } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
- import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
4
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
- function checkSignal(signal) {
6
- signal?.throwIfAborted();
7
- }
8
- function safeId(value) {
9
- if (!/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{0,127}$/.test(value) || value === "." || value === "..") {
10
- throw new Error(`Invalid canvas workspace identifier: ${value}`);
11
- }
12
- return value;
13
- }
14
- function inside(root, path) {
15
- const rel = relative(root, path);
16
- return !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
17
- }
18
- async function canonicalPath(path) {
19
- try {
20
- return await realpath(path);
21
- }
22
- catch (error) {
23
- if (error.code !== "ENOENT")
24
- throw error;
25
- const parent = resolve(path, "..");
26
- if (parent === path)
27
- throw error;
28
- return join(await canonicalPath(parent), relative(parent, path));
29
- }
30
- }
31
- async function git(cwd, args, signal, index, input) {
32
- checkSignal(signal);
33
- // Never let an inherited Git context redirect commands to the user's other repository/index.
34
- const env = { ...process.env };
35
- for (const key of Object.keys(env)) {
36
- if (/^GIT_/i.test(key))
37
- delete env[key];
38
- }
39
- if (index)
40
- env.GIT_INDEX_FILE = index;
41
- const stdout = await new Promise((done, reject) => {
42
- const child = execFile("git", ["-c", "core.hooksPath=", ...args], {
43
- cwd,
44
- signal,
45
- windowsHide: true,
46
- timeout: 60_000,
47
- maxBuffer: 64 * 1024 * 1024,
48
- env,
49
- }, (error, stdout) => (error ? reject(error) : done(stdout)));
50
- // Apply the bytes we validated, rather than reopening an attacker-replaceable path.
51
- child.stdin?.on("error", () => {
52
- /* execFile reports process failure. */
53
- });
54
- child.stdin?.end(input);
55
- });
56
- checkSignal(signal);
57
- return stdout;
58
- }
2
+ import { mkdir, readFile, realpath, writeFile } from "node:fs/promises";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { canonicalPath, checkSignal, createDetachedWorktree, git, inside, safeId, snapshotTree, verifyWorktreeIdentity, } from "../workspace-handle.js";
59
5
  function workspaceDir(workspace, kind) {
60
6
  return join(resolve(workspace.dataDir), "canvas", kind, safeId(workspace.graphId), safeId(workspace.runId), safeId(workspace.nodeId));
61
7
  }
62
- /** Build a tree without touching the user's index, branch, or commit history. Ignored files are excluded. */
63
- async function snapshotTree(cwd, dataDir, signal) {
64
- const scratch = join(resolve(dataDir), "canvas", "indexes");
65
- await mkdir(scratch, { recursive: true });
66
- const index = join(scratch, randomUUID());
67
- try {
68
- await git(cwd, ["read-tree", "HEAD"], signal, index);
69
- await git(cwd, ["add", "-A", "--", "."], signal, index);
70
- return (await git(cwd, ["write-tree"], signal, index)).trim();
71
- }
72
- finally {
73
- await rm(index, { force: true });
74
- await rm(`${index}.lock`, { force: true });
75
- }
76
- }
77
8
  function layersOf(artifacts) {
78
9
  const layers = new Map();
79
10
  for (const artifact of artifacts) {
@@ -102,6 +33,7 @@ async function trustedArtifactPath(workspace, path, nodeId) {
102
33
  }
103
34
  return resolved;
104
35
  }
36
+ const workspaceIdentities = new WeakMap();
105
37
  async function assertWorkspaceIdentity(workspace, signal) {
106
38
  const expected = workspaceDir(workspace, "workspaces");
107
39
  if (!workspace.worktreePath ||
@@ -110,18 +42,14 @@ async function assertWorkspaceIdentity(workspace, signal) {
110
42
  (await realpath(expected)) !== expected) {
111
43
  throw new Error("Canvas worktree identity mismatch: canonical path changed");
112
44
  }
113
- const top = (await git(expected, ["rev-parse", "--show-toplevel"], signal)).trim();
114
- const common = (await git(expected, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
115
- const sourceCommon = (await git(workspace.repoRoot, ["rev-parse", "--path-format=absolute", "--git-common-dir"], signal)).trim();
116
- const gitDir = (await git(expected, ["rev-parse", "--absolute-git-dir"], signal)).trim();
117
- const canonicalGitDir = await realpath(gitDir);
118
- const canonicalCommon = await realpath(common);
119
- if (resolve(top) !== expected ||
120
- canonicalCommon !== (await realpath(sourceCommon)) ||
121
- canonicalGitDir === canonicalCommon ||
122
- !inside(join(canonicalCommon, "worktrees"), canonicalGitDir) ||
123
- resolve((await readFile(join(canonicalGitDir, "gitdir"), "utf8")).trim()) !== join(expected, ".git")) {
124
- throw new Error("Canvas worktree identity mismatch: Git repository changed");
45
+ try {
46
+ const identity = workspaceIdentities.get(workspace);
47
+ if (!identity)
48
+ throw new Error("Unregistered canvas workspace");
49
+ await verifyWorktreeIdentity(expected, workspace.repoRoot, signal, identity.gitDir, identity.commonDir);
50
+ }
51
+ catch (error) {
52
+ throw new Error("Canvas worktree identity mismatch: Git repository changed", { cause: error });
125
53
  }
126
54
  }
127
55
  /** No fallback: an isolation request either returns a detached worktree or throws. */
@@ -199,7 +127,7 @@ export async function prepareCanvasWorkspace(options) {
199
127
  await mkdir(resolve(worktreePath, ".."), { recursive: true });
200
128
  if ((await canonicalPath(worktreePath)) !== worktreePath)
201
129
  throw new Error("Canvas worktree path is redirected");
202
- await git(repoRoot, ["worktree", "add", "--detach", worktreePath, baseCommit], options.signal);
130
+ await createDetachedWorktree(repoRoot, worktreePath, baseCommit, options.signal);
203
131
  // Once created, failures deliberately retain the workspace for inspection. Never remove dirty outputs.
204
132
  for (const { layer, bytes } of patches) {
205
133
  checkSignal(options.signal);
@@ -220,7 +148,7 @@ export async function prepareCanvasWorkspace(options) {
220
148
  if (!inside(worktreePath, await canonicalPath(preparedCwd)))
221
149
  throw new Error("Canvas integrated cwd escapes its worktree");
222
150
  checkSignal(options.signal);
223
- return {
151
+ const prepared = {
224
152
  ...workspace,
225
153
  cwd: preparedCwd,
226
154
  repoRoot,
@@ -228,6 +156,9 @@ export async function prepareCanvasWorkspace(options) {
228
156
  baseCommit,
229
157
  inputTree: await snapshotTree(worktreePath, workspace.dataDir, options.signal),
230
158
  };
159
+ const identity = await verifyWorktreeIdentity(worktreePath, repoRoot, options.signal);
160
+ workspaceIdentities.set(prepared, { gitDir: identity.gitDir, commonDir: identity.commonDir });
161
+ return prepared;
231
162
  }
232
163
  /** Includes tracked changes, deletions, and non-ignored untracked files, including binary additions. */
233
164
  export async function captureCanvasWorkspaceArtifact(workspace, options = {}) {
@@ -281,4 +212,5 @@ export async function cleanupCanvasWorkspace(workspace, options = {}) {
281
212
  throw new Error("Canvas workspace has pending artifacts or commits; retained for explicit adoption");
282
213
  }
283
214
  await git(workspace.repoRoot, ["worktree", "remove", workspace.worktreePath], options.signal);
215
+ workspaceIdentities.delete(workspace);
284
216
  }
@@ -11,11 +11,12 @@ import { normalizeUploadMaxMb } from "./payload-limits.js";
11
11
  import * as fsPromises from "node:fs/promises";
12
12
  import { dirname, isAbsolute, resolve } from "node:path";
13
13
  import { writeJsonAtomicSync } from "./atomic-file.js";
14
- import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
+ import { normalizeAutoCompactionInstructions, normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
15
15
  import { deriveLegacy, legacyToDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
16
16
  import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
17
17
  import { UI_SLOTS } from "./plugin-ui-slots.js";
18
18
  import { DEFAULT_PROMPT_DISABLED } from "./prompt-composer.js";
19
+ import { mergeQuickAskSettings, normalizeQuickAskSettings } from "./quick-ask-settings.js";
19
20
  /** Persisted queue modes fall back to processing all queued messages. */
20
21
  export function normalizeQueueMode(value) {
21
22
  return value === "one-at-a-time" ? value : "all";
@@ -475,6 +476,9 @@ export const CLIENT_STATE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
475
476
  * 淘汰最旧的。兜底上限:完全无时间戳可推断的存量键不按年龄淘汰,靠它保证
476
477
  * client-state.json 不随时间无界膨胀。 */
477
478
  export const MAX_TRACKED_CLIENTS = 50;
479
+ /** 最近项目上限(记录、合并读取、推送给左栏共用)。原为 30:项目多的用户有一部分永远出现不了。
480
+ * 读取时每个候选做一次异步 fs.access 探测(并发),100 次探测的开销可忽略。 */
481
+ export const RECENT_PROJECTS_MAX = 100;
478
482
  /** 死键清理扫描的最小间隔:load() 是所有读写的高频入口,扫描按 1 小时节流,
479
483
  * 首次加载必扫。 */
480
484
  export const CLIENT_STATE_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
@@ -552,8 +556,27 @@ export class ClientStateStore {
552
556
  }
553
557
  }
554
558
  }
555
- // 死键清理(issue #441):在墓碑迁移之后做——各 client 的墓碑已先并入全局键,
556
- // 淘汰死 client 不会丢墓碑;合并一次 save 落盘(迁移和淘汰只发生一次时也只写一遍)。
559
+ // 老版本的最近项目可能仅存在临时 clientId 下。先按全部墓碑过滤并迁移到全局,
560
+ // 再淘汰死 client,避免持久化列表丢失历史项目;只在首次加载时合并,不扫描磁盘历史。
561
+ const projectsByKey = new Map();
562
+ for (const state of Object.values(this.cache)) {
563
+ for (const project of state.projects ?? []) {
564
+ const key = normalizePathKey(project.path);
565
+ if (globalSet.has(key))
566
+ continue;
567
+ const existing = projectsByKey.get(key);
568
+ if (!existing || project.lastUsed > existing.lastUsed)
569
+ projectsByKey.set(key, project);
570
+ }
571
+ }
572
+ const projects = [...projectsByKey.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, RECENT_PROJECTS_MAX);
573
+ const previousProjects = globalState.projects ?? [];
574
+ if (projects.length !== previousProjects.length ||
575
+ projects.some((p, i) => p.path !== previousProjects[i].path || p.lastUsed !== previousProjects[i].lastUsed)) {
576
+ globalState.projects = projects;
577
+ migrated = true;
578
+ }
579
+ // 死键清理(issue #441):墓碑和最近项目均迁移完毕后再淘汰,合并一次 save 落盘。
557
580
  this.lastSweepAt = Date.now();
558
581
  const evicted = this.sweepDeadClients();
559
582
  if (migrated || evicted > 0) {
@@ -652,13 +675,13 @@ export class ClientStateStore {
652
675
  state.projects = [
653
676
  { path: cwd, lastUsed: now },
654
677
  ...state.projects.filter((p) => normalizePathKey(p.path) !== targetKey),
655
- ].slice(0, 30);
678
+ ].slice(0, RECENT_PROJECTS_MAX);
656
679
  // Also persist in global settings so new tabs and sessions inherit it immediately
657
680
  const globalState = (all[ClientStateStore.GLOBAL_SETTINGS_KEY] ??= { projects: [] });
658
681
  globalState.projects = [
659
682
  { path: cwd, lastUsed: now },
660
683
  ...(globalState.projects ?? []).filter((p) => normalizePathKey(p.path) !== targetKey),
661
- ].slice(0, 50);
684
+ ].slice(0, RECENT_PROJECTS_MAX);
662
685
  // Opening the workspace again clears its removal tombstone across all clients and global settings.
663
686
  for (const cState of Object.values(all)) {
664
687
  if (cState.removedProjects?.length) {
@@ -755,7 +778,7 @@ export class ClientStateStore {
755
778
  }
756
779
  }
757
780
  // 先截断后探测:探测次数 ≤ 30,且并发执行(Promise.allSettled 吸收单点失败)。
758
- const candidates = [...map.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, 30);
781
+ const candidates = [...map.values()].sort((a, b) => b.lastUsed - a.lastUsed).slice(0, RECENT_PROJECTS_MAX);
759
782
  const probes = await Promise.allSettled(candidates.map((p) => this.pathExists(p.path)));
760
783
  return candidates.filter((_, i) => {
761
784
  const probe = probes[i];
@@ -977,6 +1000,7 @@ export class ClientStateStore {
977
1000
  visionBridgePrompt: stored?.visionBridgePrompt ?? "",
978
1001
  scmCommitMsgPromptMode: stored?.scmCommitMsgPromptMode === "replace" ? "replace" : "append",
979
1002
  scmCommitMsgPrompt: stored?.scmCommitMsgPrompt ?? "",
1003
+ ...normalizeQuickAskSettings(stored ?? {}),
980
1004
  planModePromptMode: stored?.planModePromptMode === "replace" ? "replace" : "append",
981
1005
  planModePrompt: stored?.planModePrompt ?? "",
982
1006
  subagentDefaultModel: stored?.subagentDefaultModel ?? null,
@@ -987,6 +1011,7 @@ export class ClientStateStore {
987
1011
  retryMaxAttempts: normalizeRetryMaxAttempts(stored?.retryMaxAttempts),
988
1012
  softCapTokens: normalizeSoftCapTokens(stored?.softCapTokens),
989
1013
  softCapByModel: normalizeSoftCapByModel(stored?.softCapByModel),
1014
+ autoCompactionInstructions: normalizeAutoCompactionInstructions(stored?.autoCompactionInstructions),
990
1015
  quickPhrases: stored?.quickPhrases ?? [],
991
1016
  quickPhrasesEnabled: stored?.quickPhrasesEnabled ?? true,
992
1017
  minimalNewChat: stored?.minimalNewChat ?? false,
@@ -1077,10 +1102,12 @@ export class ClientStateStore {
1077
1102
  retryMaxAttempts: normalizeRetryMaxAttempts(settings.retryMaxAttempts ?? cur.retryMaxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS),
1078
1103
  softCapTokens: normalizeSoftCapTokens(settings.softCapTokens ?? cur.softCapTokens ?? 0),
1079
1104
  softCapByModel: normalizeSoftCapByModel(settings.softCapByModel ?? cur.softCapByModel ?? {}),
1105
+ autoCompactionInstructions: normalizeAutoCompactionInstructions(settings.autoCompactionInstructions ?? cur.autoCompactionInstructions ?? ""),
1080
1106
  visionBridgePromptMode: settings.visionBridgePromptMode ?? cur.visionBridgePromptMode ?? "append",
1081
1107
  visionBridgePrompt: settings.visionBridgePrompt ?? cur.visionBridgePrompt ?? "",
1082
1108
  scmCommitMsgPromptMode: settings.scmCommitMsgPromptMode ?? cur.scmCommitMsgPromptMode ?? "append",
1083
1109
  scmCommitMsgPrompt: settings.scmCommitMsgPrompt ?? cur.scmCommitMsgPrompt ?? "",
1110
+ ...mergeQuickAskSettings(cur, settings),
1084
1111
  planModePromptMode: settings.planModePromptMode ?? cur.planModePromptMode ?? "append",
1085
1112
  planModePrompt: settings.planModePrompt ?? cur.planModePrompt ?? "",
1086
1113
  reviewPrompt: settings.reviewPrompt ?? cur.reviewPrompt ?? "",
@@ -1140,6 +1167,8 @@ export class ClientStateStore {
1140
1167
  }
1141
1168
  if (Object.hasOwn(p, "softCapByModel"))
1142
1169
  preset.softCapByModel = normalizeSoftCapByModel(p.softCapByModel);
1170
+ if (Object.hasOwn(p, "autoCompactionInstructions"))
1171
+ preset.autoCompactionInstructions = normalizeAutoCompactionInstructions(p.autoCompactionInstructions);
1143
1172
  return preset;
1144
1173
  });
1145
1174
  }
@@ -361,20 +361,23 @@ const HEALTHY_TRANSCRIPT_CACHE_MAX = 512;
361
361
  function rememberHealthyTranscript(filePath) {
362
362
  try {
363
363
  const st = statSync(filePath);
364
- const sig = `${st.mtimeMs}:${st.size}`;
365
- healthyTranscriptCache.delete(filePath);
366
- healthyTranscriptCache.set(filePath, sig);
367
- while (healthyTranscriptCache.size > HEALTHY_TRANSCRIPT_CACHE_MAX) {
368
- const oldest = healthyTranscriptCache.keys().next();
369
- if (oldest.done)
370
- break;
371
- healthyTranscriptCache.delete(oldest.value);
372
- }
364
+ rememberHealthyTranscriptSig(filePath, `${st.mtimeMs}:${st.size}`);
373
365
  }
374
366
  catch {
375
367
  /* best effort */
376
368
  }
377
369
  }
370
+ /** 以给定指纹记住健康文件(调用方已 stat;用于打开流程在悬空调用修复追加后统一刷新指纹)。 */
371
+ export function rememberHealthyTranscriptSig(filePath, sig) {
372
+ healthyTranscriptCache.delete(filePath);
373
+ healthyTranscriptCache.set(filePath, sig);
374
+ while (healthyTranscriptCache.size > HEALTHY_TRANSCRIPT_CACHE_MAX) {
375
+ const oldest = healthyTranscriptCache.keys().next();
376
+ if (oldest.done)
377
+ break;
378
+ healthyTranscriptCache.delete(oldest.value);
379
+ }
380
+ }
378
381
  /**
379
382
  * 落盘版修复:健康文件只读不写;坏文件先写 <原名>.bak(已存在则保留最早那份,
380
383
  * 不覆盖),再写回修复文本。读失败/写失败返回 null(调用方按原错误继续抛)。
@@ -383,21 +386,8 @@ export function repairSessionFile(filePath) {
383
386
  try {
384
387
  const st = statSync(filePath);
385
388
  const sig = `${st.mtimeMs}:${st.size}`;
386
- if (healthyTranscriptCache.get(filePath) === sig) {
387
- healthyTranscriptCache.delete(filePath);
388
- healthyTranscriptCache.set(filePath, sig);
389
- return {
390
- text: "",
391
- changed: false,
392
- removedPending: 0,
393
- renamedIds: 0,
394
- rewiredParents: 0,
395
- cyclesBroken: 0,
396
- interrupted: false,
397
- file: filePath,
398
- backup: null,
399
- };
400
- }
389
+ if (isTranscriptHealthyCached(filePath, sig))
390
+ return healthyRepairResult(filePath);
401
391
  }
402
392
  catch {
403
393
  return null;
@@ -409,6 +399,35 @@ export function repairSessionFile(filePath) {
409
399
  catch {
410
400
  return null;
411
401
  }
402
+ return repairSessionFileFromText(filePath, raw);
403
+ }
404
+ /** 健康指纹命中即续期(LRU)。sig = `${mtimeMs}:${size}`。 */
405
+ export function isTranscriptHealthyCached(filePath, sig) {
406
+ if (healthyTranscriptCache.get(filePath) !== sig)
407
+ return false;
408
+ healthyTranscriptCache.delete(filePath);
409
+ healthyTranscriptCache.set(filePath, sig);
410
+ return true;
411
+ }
412
+ /** 无需修复时的统一返回值(text 为空:调用方不读它)。 */
413
+ export function healthyRepairResult(filePath) {
414
+ return {
415
+ text: "",
416
+ changed: false,
417
+ removedPending: 0,
418
+ renamedIds: 0,
419
+ rewiredParents: 0,
420
+ cyclesBroken: 0,
421
+ interrupted: false,
422
+ file: filePath,
423
+ backup: null,
424
+ };
425
+ }
426
+ /**
427
+ * 与 repairSessionFile 相同,但使用调用方已读入的文本(打开会话时与悬空调用检查共用一次读盘)。
428
+ * 健康:记住指纹并返回 changed=false;有坏:写 .bak 与修复文本(同步写,仅坏文件才发生)。
429
+ */
430
+ export function repairSessionFileFromText(filePath, raw) {
412
431
  const r = repairSessionTranscript(raw);
413
432
  if (!r.changed) {
414
433
  rememberHealthyTranscript(filePath);
@@ -23,7 +23,7 @@
23
23
  * - healDanglingToolCallFile:落盘版,仅针对当前分支尾部生效的悬空调用追加合成 toolResult;
24
24
  * - 合成结果文案:danglingToolResultText(cause)(按成因归因,中英各一,toolResult content 只带一条文本)。
25
25
  */
26
- import { appendFileSync, existsSync, readFileSync } from "node:fs";
26
+ import { appendFileSync, existsSync, readFileSync, statSync } from "node:fs";
27
27
  import { randomUUID } from "node:crypto";
28
28
  const DANGLING_TEXT = {
29
29
  generic: {
@@ -178,6 +178,18 @@ export function tailAssistantToolCallIds(entries, lastId) {
178
178
  * 返回追加条数(0 = 健康,无需处理;-1 = 文件不可读/不可写)。
179
179
  */
180
180
  export function healDanglingToolCallFile(filePath, cause = "generic") {
181
+ // 健康指纹命中:文件自上次判定"无悬空调用"后 mtime/size 未变,结果必然仍为 0,
182
+ // 跳过整文件同步读取(打开大转录时这是阻塞事件循环的主要来源之一)。
183
+ let sig = null;
184
+ try {
185
+ const st = statSync(filePath);
186
+ sig = `${st.mtimeMs}:${st.size}`;
187
+ if (isDanglingHealthyCached(filePath, sig))
188
+ return 0;
189
+ }
190
+ catch {
191
+ return -1;
192
+ }
181
193
  let raw;
182
194
  try {
183
195
  raw = readFileSync(filePath, "utf8");
@@ -185,29 +197,173 @@ export function healDanglingToolCallFile(filePath, cause = "generic") {
185
197
  catch {
186
198
  return -1;
187
199
  }
200
+ const result = healDanglingToolCallsInText(filePath, raw, cause);
201
+ if (result === 0 && sig)
202
+ rememberHealthyDangling(filePath, sig);
203
+ else
204
+ healthyDanglingCache.delete(filePath);
205
+ return result;
206
+ }
207
+ /** 已判定无悬空调用的文件指纹(filePath -> `${mtimeMs}:${size}`,LRU)。 */
208
+ const healthyDanglingCache = new Map();
209
+ const HEALTHY_DANGLING_CACHE_MAX = 512;
210
+ /** 指纹命中即续期(LRU)。 */
211
+ export function isDanglingHealthyCached(filePath, sig) {
212
+ if (healthyDanglingCache.get(filePath) !== sig)
213
+ return false;
214
+ healthyDanglingCache.delete(filePath);
215
+ healthyDanglingCache.set(filePath, sig);
216
+ return true;
217
+ }
218
+ export function rememberHealthyDangling(filePath, sig) {
219
+ healthyDanglingCache.delete(filePath);
220
+ healthyDanglingCache.set(filePath, sig);
221
+ while (healthyDanglingCache.size > HEALTHY_DANGLING_CACHE_MAX) {
222
+ const oldest = healthyDanglingCache.keys().next();
223
+ if (oldest.done)
224
+ break;
225
+ healthyDanglingCache.delete(oldest.value);
226
+ }
227
+ }
228
+ export function forgetHealthyDangling(filePath) {
229
+ healthyDanglingCache.delete(filePath);
230
+ }
231
+ /** 测试用:清空健康指纹缓存。 */
232
+ export function resetHealthyDanglingCacheForTest() {
233
+ healthyDanglingCache.clear();
234
+ }
235
+ /** 长行只取开头的这段做头字段提取(type/id/parentId 在 SDK 落盘格式里总是最前面几个键)。 */
236
+ const HEADER_SCAN_CHARS = 260;
237
+ /** 不超过此长度的行直接完整解析(成本可忽略)。 */
238
+ const FULL_PARSE_MAX_LINE = 512;
239
+ function parseLineFully(line) {
240
+ try {
241
+ const parsed = JSON.parse(line);
242
+ return typeof parsed === "object" && parsed !== null ? parsed : null;
243
+ }
244
+ catch {
245
+ return null;
246
+ }
247
+ }
248
+ /**
249
+ * 取一行的 id / parentId。长行(数十 KB~数 MB 的工具输出、图片)只扫开头一小段:
250
+ * 要求 id 与 parentId 都出现在第一个嵌套 `{` 之前,确保匹配的是顶层键;否则回退完整解析。
251
+ * 返回 null = 该行不是合法 JSON 对象(脏行,SDK 加载时同样跳过)。
252
+ */
253
+ function lineHeader(line) {
254
+ if (line.length > FULL_PARSE_MAX_LINE) {
255
+ const head = line.slice(0, HEADER_SCAN_CHARS);
256
+ const brace = head.indexOf("{", 1);
257
+ const topLevel = brace === -1 ? head : head.slice(0, brace);
258
+ if (topLevel.startsWith("{")) {
259
+ const idMatch = /"id"\s*:\s*"([^"\\]+)"/.exec(topLevel);
260
+ const parentStr = /"parentId"\s*:\s*"([^"\\]*)"/.exec(topLevel);
261
+ const parentNull = !parentStr && /"parentId"\s*:\s*null/.test(topLevel);
262
+ if (idMatch && (parentStr || parentNull)) {
263
+ return { id: idMatch[1], parentId: parentStr ? parentStr[1] : null, entry: null };
264
+ }
265
+ }
266
+ }
267
+ const entry = parseLineFully(line);
268
+ if (!entry)
269
+ return null;
270
+ return {
271
+ id: typeof entry.id === "string" ? entry.id : null,
272
+ parentId: typeof entry.parentId === "string" ? entry.parentId : null,
273
+ entry,
274
+ };
275
+ }
276
+ /**
277
+ * 在转录文本上检测并落盘修复当前分支尾部的悬空 toolCall(语义同原全量版本)。
278
+ *
279
+ * 按需解析:先只取每行的 id/parentId(长行只扫行首),再沿 parentId 从尾部回溯,
280
+ * 只完整解析回溯经过的行与尾部 assistant 之后的行。健康长转录(最常见:尾部是
281
+ * 没有工具调用的 assistant 或 user)因此只需完整解析末尾几行,而不是逐行 JSON.parse
282
+ * 整个文件。
283
+ *
284
+ * 与全量版本等价性:某个 toolCallId 悬空 ⇔ 存在一次出现之后没有对应结果。尾部
285
+ * assistant 之前的同名调用若缺后继结果,尾部那次必然也缺,所以只看尾部 assistant
286
+ * 及其之后的行即可得到相同集合。
287
+ *
288
+ * 返回追加条数(0 = 健康;-1 = 写入失败)。
289
+ */
290
+ export function healDanglingToolCallsInText(filePath, raw, cause = "generic") {
188
291
  const lines = raw.split("\n");
189
- const entries = [];
190
- let lastId = null;
191
- for (const line of lines) {
292
+ const headers = new Array(lines.length).fill(null);
293
+ const byId = new Map();
294
+ for (let i = 0; i < lines.length; i++) {
295
+ const line = lines[i];
192
296
  if (!line.trim())
193
297
  continue;
194
- try {
195
- const parsed = JSON.parse(line);
196
- entries.push(parsed);
197
- if (typeof parsed === "object" && parsed !== null && typeof parsed.id === "string") {
198
- lastId = parsed.id;
199
- }
298
+ const h = lineHeader(line);
299
+ headers[i] = h;
300
+ // 同名 id:后出现者覆盖(与全量版本 Map.set 语义一致)
301
+ if (h?.id)
302
+ byId.set(h.id, i);
303
+ }
304
+ const fullEntry = (i) => {
305
+ const h = headers[i];
306
+ if (!h)
307
+ return null;
308
+ if (!h.entry)
309
+ h.entry = parseLineFully(lines[i]);
310
+ return h.entry;
311
+ };
312
+ // lastId = 文件里最后一条「能解析且带字符串 id」的条目。头字段提取不验证整行 JSON,
313
+ // 崩溃残留的半截尾行可能被误认,所以这里从尾部往前逐行完整解析确认。
314
+ let lastId = null;
315
+ for (let i = lines.length - 1; i >= 0; i--) {
316
+ if (!headers[i])
317
+ continue;
318
+ const e = fullEntry(i);
319
+ if (!e) {
320
+ headers[i] = null;
321
+ continue;
200
322
  }
201
- catch {
202
- // 脏行:SDK 加载时同样跳过,这里忽略。
323
+ if (typeof e.id === "string") {
324
+ lastId = e.id;
325
+ break;
203
326
  }
204
327
  }
205
- if (entries.length === 0 || !lastId)
328
+ if (!lastId)
206
329
  return 0;
207
- const tailIds = tailAssistantToolCallIds(entries, lastId);
208
- if (tailIds.size === 0)
330
+ // 沿当前分支回溯,定位尾部生效 assistant(规则同 tailAssistantToolCallIds)。
331
+ let tailIndex = -1;
332
+ let tailIds = new Set();
333
+ const seen = new Set();
334
+ let cursor = lastId;
335
+ while (cursor && !seen.has(cursor)) {
336
+ seen.add(cursor);
337
+ const idx = byId.get(cursor);
338
+ if (idx === undefined)
339
+ break;
340
+ const entry = fullEntry(idx);
341
+ if (!entry)
342
+ break;
343
+ const msg = typeof entry.message === "object" && entry.message !== null ? entry.message : null;
344
+ if (msg && "role" in msg) {
345
+ const m = msg;
346
+ if (m.role === "user")
347
+ break;
348
+ if (m.role === "assistant") {
349
+ if (m.stopReason !== "error" && m.stopReason !== "aborted") {
350
+ tailIds = new Set(toolCallsOfMessage(m).map((c) => c.toolCallId));
351
+ tailIndex = idx;
352
+ }
353
+ break;
354
+ }
355
+ }
356
+ cursor = typeof entry.parentId === "string" ? entry.parentId : null;
357
+ }
358
+ if (tailIds.size === 0 || tailIndex < 0)
209
359
  return 0;
210
- const dangling = findDanglingToolCalls(entries).filter((d) => tailIds.has(d.toolCallId));
360
+ const after = [];
361
+ for (let i = tailIndex; i < lines.length; i++) {
362
+ const e = fullEntry(i);
363
+ if (e)
364
+ after.push(e);
365
+ }
366
+ const dangling = findDanglingToolCalls(after).filter((d) => tailIds.has(d.toolCallId));
211
367
  if (dangling.length === 0)
212
368
  return 0;
213
369
  try {
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { isTrustedTaskWorkspaceCapability, resolveTrustedTaskWorkspace, } from "./task-workspace.js";
2
3
  import { isAbsolute, resolve } from "node:path";
3
4
  import { getBotExecutionInstructions } from "./execution-instructions.js";
4
5
  import { checkGroupTaskPlanGuard, isGroupToolForbiddenInPlanCatalog } from "./group-plan-guard.js";
@@ -41,8 +42,35 @@ export function registerBotExecution(bot, authorizedResumePath, context) {
41
42
  }
42
43
  if (authorizedResumePath !== undefined && !isAbsolute(authorizedResumePath))
43
44
  throw new Error("Resume path must be absolute");
45
+ if (context?.executionMode === "code" && authorizedResumePath) {
46
+ throw new Error("Code execution mode refuses resuming old sessions in first slice");
47
+ }
48
+ if (context?.executionCwd !== undefined && !isAbsolute(context.executionCwd)) {
49
+ throw new Error("Execution cwd must be absolute");
50
+ }
44
51
  const snapshot = structuredClone(bot);
45
52
  snapshot.cwd = resolve(snapshot.cwd);
53
+ const executionCwd = context?.executionCwd ? resolve(context.executionCwd) : snapshot.cwd;
54
+ const code = context?.executionMode === "code";
55
+ const workspace = context?.workspaceCapability;
56
+ const workspaceBinding = Object.freeze({
57
+ deviceId: context?.deviceId ?? "",
58
+ botId: snapshot.id,
59
+ botRevision: snapshot.revision,
60
+ taskId: context?.taskId ?? "",
61
+ attemptId: context?.attemptId ?? "",
62
+ });
63
+ if (code) {
64
+ if (!isTrustedTaskWorkspaceCapability(workspace) ||
65
+ !workspaceBinding.deviceId ||
66
+ !workspaceBinding.taskId ||
67
+ !workspaceBinding.attemptId ||
68
+ workspace.handleId !== context?.workspaceHandleId)
69
+ throw new Error("Code execution requires a trusted task workspace capability");
70
+ }
71
+ else if (executionCwd !== snapshot.cwd || context?.workspaceHandleId || workspace) {
72
+ throw new Error("Chat execution cwd must match the Bot project");
73
+ }
46
74
  Object.freeze(snapshot.tools);
47
75
  Object.freeze(snapshot.skills);
48
76
  Object.freeze(snapshot.mcpServers);
@@ -92,9 +120,27 @@ export function registerBotExecution(bot, authorizedResumePath, context) {
92
120
  authorizedResumePath,
93
121
  planOnly: context?.planOnly === true,
94
122
  attenuatedTools: attenuatedList ? Object.freeze([...attenuatedList]) : undefined,
123
+ executionCwd,
124
+ executionMode: context?.executionMode ?? "chat",
125
+ workspaceHandleId: context?.workspaceHandleId,
126
+ taskId: context?.taskId,
127
+ attemptId: context?.attemptId,
95
128
  assertActive() {
96
129
  if (!active)
97
130
  throw new Error("Bot execution capability has been revoked");
131
+ if (code && !isTrustedTaskWorkspaceCapability(workspace))
132
+ throw new Error("Task workspace capability has expired");
133
+ },
134
+ async assertWorkspace(cwd = executionCwd) {
135
+ this.assertActive();
136
+ if (resolve(cwd) !== executionCwd)
137
+ throw new Error("Bot execution cwd mismatch");
138
+ if (code) {
139
+ const actual = await resolveTrustedTaskWorkspace(workspace, workspaceBinding);
140
+ this.assertActive();
141
+ if (resolve(actual.cwd) !== executionCwd || resolve(actual.repoRoot) !== snapshot.cwd)
142
+ throw new Error("Task workspace identity mismatch");
143
+ }
98
144
  },
99
145
  allowsToolRegistration(name) {
100
146
  if (attenuatedSet?.has(name))
@@ -188,7 +234,8 @@ export function botExecutionMessageAllowed(clientId, type, message) {
188
234
  return true;
189
235
  }
190
236
  if (type === "switch_session")
191
- return (!!capability.authorizedResumePath &&
237
+ return (capability.executionMode !== "code" &&
238
+ !!capability.authorizedResumePath &&
192
239
  !!message &&
193
240
  typeof message === "object" &&
194
241
  "path" in message &&