pi-web-ui 0.114.2 → 0.115.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 +55 -1
  2. package/bin/pi-web-ui.mjs +69 -7
  3. package/dist/server/agent-service-daemon.js +440 -32
  4. package/dist/server/agent-service.js +878 -383
  5. package/dist/server/canvas/canvas-dispatch.js +13 -1
  6. package/dist/server/client-state.js +25 -0
  7. package/dist/server/communicate-tool.js +2 -0
  8. package/dist/server/context-usage.js +105 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +72 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +328 -10
  16. package/dist/server/device-center/collab-tool.js +738 -12
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +19 -0
  22. package/dist/server/device-center/execution-settings.js +100 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +389 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +180 -91
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +208 -0
  30. package/dist/server/device-center/group-context.js +109 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +178 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub.js +1544 -80
  37. package/dist/server/device-center/human-interaction.js +232 -0
  38. package/dist/server/device-center/integration-errors.js +25 -0
  39. package/dist/server/device-center/local-hub.js +18 -0
  40. package/dist/server/device-center/local.js +356 -40
  41. package/dist/server/device-center/main.js +11 -1
  42. package/dist/server/device-center/path-portal.js +11 -3
  43. package/dist/server/device-center/relay.js +364 -35
  44. package/dist/server/device-center/report-metadata.js +66 -0
  45. package/dist/server/device-center/report-upload.js +63 -0
  46. package/dist/server/device-center/runtime.js +549 -41
  47. package/dist/server/device-center/store.js +66 -3
  48. package/dist/server/device-center/task-context-budget.js +161 -0
  49. package/dist/server/device-center/task-journal.js +385 -0
  50. package/dist/server/device-center/task-plan.js +33 -0
  51. package/dist/server/device-center/task-progress.js +141 -0
  52. package/dist/server/device-center/task-recovery.js +452 -0
  53. package/dist/server/device-center/task-report-outbox.js +216 -0
  54. package/dist/server/device-center/task-report.js +384 -0
  55. package/dist/server/device-center/task-scheduler.js +400 -0
  56. package/dist/server/device-center/task-state.js +333 -0
  57. package/dist/server/device-center/transfer-stream.js +1006 -0
  58. package/dist/server/device-center/transfers.js +815 -8
  59. package/dist/server/dispatch-domain-handlers.js +21 -3
  60. package/dist/server/dsh/dsh-agent-service.js +6 -0
  61. package/dist/server/goal-service.js +10 -5
  62. package/dist/server/index.js +89 -13
  63. package/dist/server/message-deletion.js +40 -0
  64. package/dist/server/message-window.js +9 -0
  65. package/dist/server/patch-executable-lookup.js +396 -0
  66. package/dist/server/payload-limits.js +2 -0
  67. package/dist/server/plugin-llm.js +100 -9
  68. package/dist/server/plugins.js +1 -0
  69. package/dist/server/preset-fields.js +24 -0
  70. package/dist/server/preset-share.js +2 -0
  71. package/dist/server/prompt-base-store.js +85 -0
  72. package/dist/server/prompt-composer.js +5 -2
  73. package/dist/server/protocol-version.js +1 -1
  74. package/dist/server/protocol.js +2 -2
  75. package/dist/server/remote-ssh-service.js +22 -9
  76. package/dist/server/resolve-global-sdk.js +2 -0
  77. package/dist/server/session-search.js +1 -1
  78. package/dist/server/settings-service.js +90 -39
  79. package/dist/server/skill-content-filler.js +29 -8
  80. package/dist/server/skill-tool.js +12 -3
  81. package/dist/server/subagent-helpers.js +4 -1
  82. package/dist/server/subagents.js +50 -36
  83. package/dist/server/tool-host-factories.js +1 -0
  84. package/dist/server/universal/universal-session.js +5 -0
  85. package/dist/server/webui-context.js +25 -5
  86. package/docs/README.md +94 -0
  87. package/docs/device-center.md +100 -12
  88. package/docs/dsh-engine.md +10 -10
  89. package/extensions/webui.ts +43 -1
  90. package/package.json +1 -1
  91. package/themes/aetheris.css +5 -0
  92. package/themes/ayu-light.css +6 -0
  93. package/themes/bases/flow-base.css +68 -68
  94. package/themes/catppuccin-latte.css +6 -0
  95. package/themes/catppuccin.css +6 -0
  96. package/themes/claude-code-dark.css +5 -0
  97. package/themes/codex.css +6 -0
  98. package/themes/cyberpunk.css +6 -0
  99. package/themes/dark-teal.css +6 -1
  100. package/themes/dazzle.css +6 -0
  101. package/themes/everforest-light.css +6 -0
  102. package/themes/flow-light.css +8 -1
  103. package/themes/flow.css +6 -1
  104. package/themes/geist.css +6 -0
  105. package/themes/gruvbox-light.css +6 -0
  106. package/themes/kanagawa-lotus.css +6 -0
  107. package/themes/md-preview.css +6 -0
  108. package/themes/mist.css +6 -0
  109. package/themes/nord.css +6 -0
  110. package/themes/one-dark.css +6 -0
  111. package/themes/paper.css +6 -0
  112. package/themes/rose-pine-dawn.css +6 -0
  113. package/themes/sakura.css +6 -0
  114. package/themes/solarized-light.css +6 -0
  115. package/themes/tokyo-night.css +6 -0
  116. package/themes/translucent.css +6 -0
  117. package/themes/transparent.css +6 -0
  118. package/themes/vs-code-dark.css +5 -0
  119. package/themes/wallpaper-flow.css +5 -1
  120. package/themes/wallpaper-obsidian.css +6 -0
  121. package/themes/white.css +6 -0
  122. package/themes/zhujian-dark.css +6 -1
  123. package/themes/zhujian.css +6 -1
  124. package/themes/zhupi-dark.css +6 -1
  125. package/themes/zhupi.css +6 -1
  126. package/web/dist/.build-assets.json +1 -1
  127. package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
  128. package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
  129. package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
  130. package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
  131. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
  132. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
  133. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
  134. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
  135. package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
  136. package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
  137. package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
  138. package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
  139. package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
  140. package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
  141. package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
  142. package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
  143. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
  144. package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
  145. package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
  146. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
  147. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
  148. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
  149. package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
  150. package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
  151. package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
  152. package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
  153. package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
  154. package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
  155. package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
  156. package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
  157. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  158. package/web/dist/assets/index-CsFs_HMb.css +1 -0
  159. package/web/dist/assets/index-DHeeHS_l.js +85 -0
  160. package/web/dist/assets/index-DTZch8uz.js +85 -0
  161. package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
  162. package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
  163. package/web/dist/assets/theme-BXGpyTMh.js +1 -0
  164. package/web/dist/index.html +10 -9
  165. package/web/dist/sw.js +1 -1
  166. package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
  167. package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
  168. package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
  169. package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
  170. package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
  171. package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
  172. package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
  173. package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
  174. package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
  175. package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
  176. package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
  177. package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
  178. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
  179. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
  180. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
  181. package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
  182. package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
  183. package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
  184. package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
  185. package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
  186. package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
  187. package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
  188. package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
  189. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  190. package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
  191. package/web/dist/assets/index-Cdh3sibd.js +0 -85
  192. package/web/dist/assets/index-DDZMv6LO.css +0 -1
  193. package/web/dist/assets/index-DWw_SxRq.js +0 -85
  194. package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
  195. package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
@@ -1,8 +1,33 @@
1
- import { resolve } from "node:path";
1
+ import { isAbsolute, join, resolve } from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { writeJsonAtomicSync } from "../atomic-file.js";
2
5
  import { createDeviceCollabService } from "./collab-service.js";
3
6
  import { createDeviceTaskExecutor } from "./executor.js";
4
7
  import { createDeviceFileSync } from "./file-sync.js";
5
8
  import { DeviceTaskError } from "./task-error.js";
9
+ import { TaskRecoveryManager } from "./task-recovery.js";
10
+ import { createTaskReportOutbox } from "./task-report-outbox.js";
11
+ import { reportUploadMetadata } from "./report-metadata.js";
12
+ import { DeviceTaskScheduler } from "./task-scheduler.js";
13
+ import { loadExecutionSettings, saveExecutionSettings } from "./execution-settings.js";
14
+ import { executionRoot, executionRootsOverlap } from "./execution-workspace.js";
15
+ import { devicePrepareIntegration, deviceVerifyIntegration, deviceConfirmIntegration, deviceCancelIntegration, } from "./device-integration.js";
16
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+ function samePath(a, b) {
18
+ if (!a || !b)
19
+ return false;
20
+ const fold = (p) => (process.platform === "win32" ? resolve(p).toLowerCase() : resolve(p));
21
+ return fold(a) === fold(b);
22
+ }
23
+ /** The task settled, but its executor has not confirmed that execution stopped. */
24
+ export class DeviceTaskStopUnconfirmedError extends Error {
25
+ stopUnconfirmed = true;
26
+ constructor(cause) {
27
+ super(cause instanceof Error ? cause.message : "Task executor stop unconfirmed", { cause });
28
+ this.name = "DeviceTaskStopUnconfirmedError";
29
+ }
30
+ }
6
31
  export function createDeviceRuntime(options) {
7
32
  const { config, bots } = options;
8
33
  const sessions = new Map();
@@ -10,21 +35,56 @@ export function createDeviceRuntime(options) {
10
35
  const receipts = new Map();
11
36
  const operations = new Set();
12
37
  let closed = false;
13
- let blocked;
14
38
  let generation = new AbortController();
15
- let active;
39
+ const active = new Set();
40
+ const transferOperations = new Set();
41
+ const recovery = new TaskRecoveryManager({
42
+ dataDir: options.dataDir,
43
+ deviceId: config.deviceId,
44
+ hubUrl: config.hubUrl,
45
+ });
46
+ const reportOutbox = createTaskReportOutbox(options.dataDir, config.deviceId, config.hubUrl);
47
+ const scheduler = new DeviceTaskScheduler({
48
+ initialSettings: loadExecutionSettings(options.dataDir),
49
+ });
50
+ const conflicts = (a, b) => a.botId === b.botId || executionRootsOverlap(a.root, b.root);
51
+ function drain() {
52
+ scheduler.drain();
53
+ }
54
+ const transcriptFile = options.dataDir ? join(options.dataDir, "bot-execution-conversations.json") : undefined;
55
+ let transcripts = Object.create(null);
56
+ let transcriptLoadError;
57
+ if (transcriptFile) {
58
+ try {
59
+ const stored = JSON.parse(readFileSync(transcriptFile, "utf8"));
60
+ if (!stored || typeof stored !== "object" || Array.isArray(stored))
61
+ throw new Error("Invalid transcript registry");
62
+ for (const [id, entry] of Object.entries(stored)) {
63
+ const value = entry;
64
+ if (!UUID.test(id) ||
65
+ !value ||
66
+ typeof value.binding !== "string" ||
67
+ typeof value.path !== "string" ||
68
+ !isAbsolute(value.path))
69
+ throw new Error("Invalid transcript registry");
70
+ }
71
+ transcripts = Object.assign(Object.create(null), stored);
72
+ }
73
+ catch (error) {
74
+ if (error.code !== "ENOENT")
75
+ transcriptLoadError = error;
76
+ }
77
+ }
16
78
  function enabled(signal) {
17
79
  signal?.throwIfAborted();
18
80
  if (closed)
19
81
  throw new Error("Device runtime closed");
20
- if (blocked)
21
- throw new DeviceTaskError("群任务停止状态不确定,项目已隔离。请在本机确认后重启服务。 / Task stop unconfirmed; workspace blocked until service restart.");
22
82
  if (!config.allowExecution)
23
83
  throw new DeviceTaskError("目标设备未开启群任务执行权限。 / Local task execution is disabled.");
24
84
  }
25
85
  function track(operation) {
26
86
  operations.add(operation);
27
- void operation.finally(() => operations.delete(operation)).catch(() => { });
87
+ void operation.catch(() => { }).finally(() => operations.delete(operation));
28
88
  return operation;
29
89
  }
30
90
  async function sweep() {
@@ -45,6 +105,8 @@ export function createDeviceRuntime(options) {
45
105
  const lease = await bots.acquire(botId);
46
106
  try {
47
107
  enabled(signal);
108
+ if ([...active].some((owner) => owner.blocked && conflicts(owner, { botId, root: executionRoot(lease.root) })))
109
+ throw new DeviceTaskError("Task stop unconfirmed; workspace blocked until service restart");
48
110
  return lease;
49
111
  }
50
112
  catch (error) {
@@ -56,13 +118,21 @@ export function createDeviceRuntime(options) {
56
118
  const key = JSON.stringify([roomId, botId, lease.revision]);
57
119
  let entry = files.get(key);
58
120
  if (!entry) {
121
+ if (!options.dataDir)
122
+ throw new Error("File synchronization storage unavailable");
123
+ const canonicalRoot = resolve(lease.root);
124
+ const scopeToken = createHash("sha256")
125
+ .update(JSON.stringify([config.hubUrl, config.deviceId, roomId, botId, lease.revision, canonicalRoot]))
126
+ .digest("hex")
127
+ .slice(0, 32);
128
+ const scopedDataDir = join(options.dataDir, "scoped-transfers", scopeToken);
59
129
  entry = {
60
130
  roomId,
61
131
  botId,
62
132
  revision: lease.revision,
63
133
  files: createDeviceFileSync({
64
134
  root: lease.root,
65
- dataDir: options.dataDir,
135
+ dataDir: scopedDataDir,
66
136
  allowReceive: config.allowExecution,
67
137
  }),
68
138
  };
@@ -72,6 +142,10 @@ export function createDeviceRuntime(options) {
72
142
  }
73
143
  const service = createDeviceCollabService({
74
144
  getConfig: () => (closed ? undefined : config),
145
+ getExecutionContext: (context) => {
146
+ const owner = context?.sessionId ? sessions.get(context.sessionId) : undefined;
147
+ return owner && samePath(context?.cwd, owner.root) ? owner : undefined;
148
+ },
75
149
  getParentTask: (context) => (context?.sessionId ? sessions.get(context.sessionId)?.taskId : undefined),
76
150
  getSourceBot: (context) => (context?.sessionId ? sessions.get(context.sessionId)?.botId : undefined),
77
151
  async workspaceResolver({ roomId, sourceBotId, context, signal }) {
@@ -95,24 +169,121 @@ export function createDeviceRuntime(options) {
95
169
  });
96
170
  const collabService = {
97
171
  execute(action, args, signal, context) {
98
- if (action === "send_task" && (!context?.sessionId || sessions.get(context.sessionId)?.roomId !== args.roomId))
99
- return Promise.reject(new Error("Task session is not bound to this room"));
172
+ if (action === "send_task") {
173
+ const owner = context?.sessionId ? sessions.get(context.sessionId) : undefined;
174
+ if (!owner || (args.roomId !== undefined && owner.roomId !== args.roomId))
175
+ return Promise.reject(new Error("Task session is not bound to this room"));
176
+ }
100
177
  const commandSignal = AbortSignal.any([generation.signal, ...(signal ? [signal] : [])]);
101
178
  return track(service.execute(action, args, commandSignal, context));
102
179
  },
103
180
  };
104
- function onTask(task, signal) {
181
+ function onTask(task, signal, callbacks) {
105
182
  try {
106
183
  enabled(signal);
107
184
  }
108
185
  catch (error) {
109
186
  return Promise.reject(error);
110
187
  }
111
- if (active)
112
- return Promise.reject(new DeviceTaskError("目标设备正在执行另一个群任务,请稍后再试。 / Local task executor busy."));
113
- const owner = { controller: new AbortController() };
114
- active = owner;
115
- const taskSignal = AbortSignal.any([owner.controller.signal, generation.signal, ...(signal ? [signal] : [])]);
188
+ const taskSignal = signal ?? new AbortController().signal;
189
+ const root = executionRoot(bots.get(task.botId)?.cwd ?? options.dataDir ?? process.cwd());
190
+ return track(new Promise((resolve, reject) => {
191
+ let queued = null;
192
+ const onAbort = () => {
193
+ if (queued)
194
+ scheduler.removeWaiting(queued);
195
+ taskSignal.removeEventListener("abort", onAbort);
196
+ reject(taskSignal.reason ?? new DeviceTaskError("Task cancelled"));
197
+ scheduler.drain();
198
+ };
199
+ try {
200
+ queued = scheduler.enqueue({
201
+ id: task.id,
202
+ attemptId: task.attemptId,
203
+ roomId: task.roomId,
204
+ botId: task.botId,
205
+ botRevision: String(task.botRevision),
206
+ root,
207
+ }, {
208
+ start() {
209
+ taskSignal.removeEventListener("abort", onAbort);
210
+ void runTask(task, root, taskSignal, callbacks).then(resolve, reject).finally(drain);
211
+ },
212
+ reject(error) {
213
+ taskSignal.removeEventListener("abort", onAbort);
214
+ reject(error);
215
+ },
216
+ cancel() {
217
+ taskSignal.removeEventListener("abort", onAbort);
218
+ reject(taskSignal.reason ?? new DeviceTaskError("Task cancelled"));
219
+ scheduler.drain();
220
+ },
221
+ }, taskSignal);
222
+ }
223
+ catch (err) {
224
+ reject(err);
225
+ return;
226
+ }
227
+ taskSignal.addEventListener("abort", onAbort, { once: true });
228
+ if (taskSignal.aborted)
229
+ onAbort();
230
+ }));
231
+ }
232
+ function runTask(task, root, signal, callbacks) {
233
+ try {
234
+ enabled(signal);
235
+ }
236
+ catch (error) {
237
+ return Promise.reject(error);
238
+ }
239
+ if (typeof task.leaseToken !== "string" || !task.leaseToken) {
240
+ return Promise.reject(new DeviceTaskError("Hub task lease grant required"));
241
+ }
242
+ const capacityCheck = recovery.hasOutboxCapacity();
243
+ if (!capacityCheck.available) {
244
+ return Promise.reject(new DeviceTaskError(capacityCheck.reason ?? "Recovery outbox capacity reached"));
245
+ }
246
+ const owner = {
247
+ controller: new AbortController(),
248
+ botId: task.botId,
249
+ root,
250
+ taskId: task.id,
251
+ attemptId: task.attemptId,
252
+ };
253
+ // Transactional Admission: reverse cleanup on any failure before execution starts
254
+ let leaseRecorded = false;
255
+ let activeItem;
256
+ try {
257
+ active.add(owner);
258
+ recovery.recordTaskStart({
259
+ taskId: task.id,
260
+ attemptId: task.attemptId,
261
+ botId: task.botId,
262
+ deviceId: config.deviceId,
263
+ roomId: task.roomId,
264
+ leaseToken: task.leaseToken,
265
+ leaseGeneration: task.leaseGeneration ?? 1,
266
+ conversationId: task.conversationId,
267
+ });
268
+ leaseRecorded = true;
269
+ activeItem = scheduler.registerActive({
270
+ id: task.id,
271
+ attemptId: task.attemptId,
272
+ roomId: task.roomId,
273
+ botId: task.botId,
274
+ botRevision: String(task.botRevision),
275
+ root,
276
+ }, owner.controller);
277
+ }
278
+ catch (admissionError) {
279
+ if (leaseRecorded) {
280
+ recovery.removeActiveLease(task.id, task.attemptId);
281
+ }
282
+ active.delete(owner);
283
+ return Promise.reject(admissionError);
284
+ }
285
+ callbacks?.onStarted?.();
286
+ const taskSignal = AbortSignal.any([owner.controller.signal, ...(signal ? [signal] : [])]);
116
287
  const operation = (async () => {
117
288
  let lease;
118
289
  let stopping;
@@ -127,8 +298,10 @@ export function createDeviceRuntime(options) {
127
298
  await stopping;
128
299
  }
129
300
  catch (error) {
130
- blocked = error;
131
- throw error;
301
+ const failure = error instanceof DeviceTaskStopUnconfirmedError ? error : new DeviceTaskStopUnconfirmedError(error);
302
+ owner.blocked = failure;
303
+ scheduler.markBlocked(task.id, task.attemptId, failure);
304
+ throw failure;
132
305
  }
133
306
  };
134
307
  try {
@@ -138,43 +311,217 @@ export function createDeviceRuntime(options) {
138
311
  if (task.deviceId !== config.deviceId || !task.botId)
139
312
  throw new Error("Task Bot route mismatch");
140
313
  lease = await acquire(task.botId, taskSignal);
141
- if (task.botRevision !== lease.bot.revision)
142
- throw new Error("Task Bot revision mismatch");
314
+ if (task.botRevision !== lease.bot.revision || executionRoot(lease.root) !== root)
315
+ throw new Error("Task Bot revision or workspace mismatch");
143
316
  }
144
317
  catch (error) {
145
318
  if (taskSignal.aborted)
146
319
  throw error;
147
320
  throw new DeviceTaskError("目标 Bot 不可用、配置已变更或正在忙碌。 / Target Bot unavailable or busy.");
148
321
  }
322
+ let binding;
323
+ let resumePath;
324
+ let transcriptPath;
325
+ let boundSession;
326
+ if (task.resume !== undefined && typeof task.resume !== "boolean")
327
+ throw new DeviceTaskError("Invalid resume flag");
328
+ if (task.resume && !task.conversationId)
329
+ throw new DeviceTaskError("Resume conversation address required");
330
+ if (task.conversationId !== undefined) {
331
+ if (!UUID.test(task.conversationId) || !transcriptFile || transcriptLoadError)
332
+ throw new DeviceTaskError("Persistent conversation storage unavailable or invalid address");
333
+ binding = createHash("sha256")
334
+ .update(JSON.stringify([
335
+ config.hubUrl,
336
+ config.deviceId,
337
+ task.roomId,
338
+ lease.bot.id,
339
+ lease.bot.revision,
340
+ resolve(lease.root),
341
+ ]))
342
+ .digest("hex");
343
+ const stored = transcripts[task.conversationId];
344
+ if (task.resume) {
345
+ if (!stored || stored.binding !== binding)
346
+ throw new DeviceTaskError("Conversation unavailable or configuration changed");
347
+ try {
348
+ if (!statSync(stored.path).isFile())
349
+ throw new Error();
350
+ }
351
+ catch {
352
+ throw new DeviceTaskError("Conversation transcript unavailable");
353
+ }
354
+ resumePath = stored.path;
355
+ }
356
+ else if (stored)
357
+ throw new DeviceTaskError("Conversation already exists; explicit resume required");
358
+ }
149
359
  owner.executor = (options.executorFactory ?? createDeviceTaskExecutor)({
360
+ ...callbacks,
361
+ onActivity() {
362
+ recovery.recordActivity(task.id, task.attemptId);
363
+ callbacks?.onActivity?.();
364
+ },
365
+ onProgress(progress) {
366
+ recovery.recordActivity(task.id, task.attemptId);
367
+ callbacks?.onProgress?.(progress);
368
+ },
369
+ onInteractions(items) {
370
+ recovery.recordActivity(task.id, task.attemptId);
371
+ callbacks?.onInteractions?.(items);
372
+ },
373
+ onFullReport(taskId, attemptId, fullReport) {
374
+ recovery.recordActivity(taskId, attemptId);
375
+ if (taskId !== task.id || attemptId !== task.attemptId)
376
+ throw new Error("Report task binding mismatch");
377
+ // Persist the original before notifying transport or settling the task.
378
+ reportOutbox.capture(task, fullReport);
379
+ return callbacks?.onFullReport?.(taskId, attemptId, fullReport);
380
+ },
381
+ onPlanReady(taskId, plan) {
382
+ taskSignal.throwIfAborted();
383
+ if (taskId !== task.id)
384
+ return Promise.resolve(false);
385
+ recovery.recordActivity(taskId, task.attemptId);
386
+ return callbacks?.onPlanReady?.(taskId, plan) ?? Promise.resolve(false);
387
+ },
388
+ onToolLifecycle(lifecycle) {
389
+ recovery.recordActivity(task.id, task.attemptId);
390
+ callbacks?.onToolLifecycle?.(lifecycle);
391
+ },
392
+ registerInteractionAnswer(answer) {
393
+ owner.answer = answer;
394
+ },
150
395
  localOrigin: options.localOrigin,
151
396
  localAuthToken: options.localAuthToken,
152
397
  cwd: lease.root,
153
398
  bot: lease.bot,
154
399
  allowExecution: config.allowExecution,
400
+ resumePath,
401
+ onSessionPath(taskId, path) {
402
+ taskSignal.throwIfAborted();
403
+ if (taskId !== task.id ||
404
+ !boundSession ||
405
+ sessions.get(boundSession)?.taskId !== task.id ||
406
+ !isAbsolute(path) ||
407
+ (resumePath && !samePath(path, resumePath)))
408
+ throw new Error("Transcript ownership mismatch");
409
+ if (task.conversationId) {
410
+ const currentBot = bots.get(task.botId);
411
+ if (!binding ||
412
+ !currentBot?.enabled ||
413
+ currentBot.revision !== lease.bot.revision ||
414
+ resolve(currentBot.cwd) !== resolve(lease.root))
415
+ throw new DeviceTaskError("Conversation transcript ownership changed");
416
+ try {
417
+ // Fresh SDK sessions allocate a path before the first message creates
418
+ // the file. Bind it now so failed first turns remain recoverable.
419
+ // Existing resume paths must still refer to a real transcript.
420
+ if (resumePath && !statSync(path).isFile())
421
+ throw new Error();
422
+ const next = { ...transcripts, [task.conversationId]: { binding, path } };
423
+ writeJsonAtomicSync(transcriptFile, next);
424
+ transcripts = next;
425
+ }
426
+ catch {
427
+ throw new DeviceTaskError("Conversation transcript persistence failed");
428
+ }
429
+ }
430
+ transcriptPath = path;
431
+ },
155
432
  onSession(taskId, sessionId) {
433
+ if (taskId !== task.id)
434
+ throw new Error("Task session ownership mismatch");
435
+ boundSession = sessionId;
156
436
  for (const [id, bound] of sessions)
157
437
  if (bound.taskId === taskId && bound.roomId === task.roomId)
158
438
  sessions.delete(id);
159
439
  if (sessionId && !taskSignal.aborted)
160
- sessions.set(sessionId, { taskId, roomId: task.roomId, root: lease.root, botId: task.botId });
440
+ sessions.set(sessionId, {
441
+ taskId,
442
+ ...(task.taskState ? { taskState: structuredClone(task.taskState) } : {}),
443
+ roomId: task.roomId,
444
+ root: lease.root,
445
+ botId: task.botId,
446
+ conversationId: task.conversationId,
447
+ sourceConversationId: task.sourceConversationId,
448
+ requestId: task.requestId,
449
+ kind: task.kind,
450
+ });
161
451
  },
162
452
  });
163
453
  taskSignal.addEventListener("abort", stop, { once: true });
164
454
  taskSignal.throwIfAborted();
165
455
  const result = await owner.executor.run(task);
456
+ await confirmStop();
166
457
  taskSignal.throwIfAborted();
458
+ if (task.conversationId) {
459
+ const currentBot = bots.get(task.botId);
460
+ if (!transcriptPath ||
461
+ !binding ||
462
+ !currentBot?.enabled ||
463
+ currentBot.revision !== lease.bot.revision ||
464
+ resolve(currentBot.cwd) !== resolve(lease.root))
465
+ throw new DeviceTaskError("Conversation transcript capture failed");
466
+ try {
467
+ if (!statSync(transcriptPath).isFile())
468
+ throw new Error();
469
+ }
470
+ catch {
471
+ throw new DeviceTaskError("Conversation transcript unavailable after execution");
472
+ }
473
+ }
474
+ // Commit to durable outbox ONLY after all outcomes and transcripts are verified
475
+ recovery.recordTaskFinish({
476
+ id: task.id,
477
+ attemptId: task.attemptId,
478
+ botId: task.botId,
479
+ deviceId: config.deviceId,
480
+ roomId: task.roomId,
481
+ }, {
482
+ status: "completed",
483
+ report: result,
484
+ reportMetadata: reportUploadMetadata(reportOutbox.get(task) ?? reportOutbox.markMissing(task)),
485
+ });
167
486
  return result;
168
487
  }
488
+ catch (error) {
489
+ const isUnconfirmed = !!owner.blocked ||
490
+ error instanceof DeviceTaskStopUnconfirmedError ||
491
+ (error && typeof error === "object" && error.stopUnconfirmed === true);
492
+ try {
493
+ recovery.recordTaskFinish({
494
+ id: task.id,
495
+ attemptId: task.attemptId,
496
+ botId: task.botId,
497
+ deviceId: config.deviceId,
498
+ roomId: task.roomId,
499
+ }, {
500
+ status: isUnconfirmed ? "interrupted" : "failed",
501
+ error,
502
+ reportMetadata: reportUploadMetadata(reportOutbox.get(task) ?? reportOutbox.markMissing(task)),
503
+ });
504
+ }
505
+ catch { }
506
+ throw error;
507
+ }
169
508
  finally {
170
509
  taskSignal.removeEventListener("abort", stop);
171
- await confirmStop();
510
+ let stoppedCleanly = false;
511
+ try {
512
+ await confirmStop();
513
+ stoppedCleanly = true;
514
+ }
515
+ catch { }
172
516
  for (const [id, bound] of sessions)
173
517
  if (bound.taskId === task.id && bound.roomId === task.roomId)
174
518
  sessions.delete(id);
175
- lease?.release();
176
- if (active === owner)
177
- active = undefined;
519
+ if (!owner.blocked && stoppedCleanly) {
520
+ lease?.release();
521
+ if (activeItem)
522
+ scheduler.releaseActive(activeItem);
523
+ active.delete(owner);
524
+ }
178
525
  }
179
526
  })();
180
527
  owner.done = operation;
@@ -182,19 +529,76 @@ export function createDeviceRuntime(options) {
182
529
  }
183
530
  function onCommand(action, payload, signal) {
184
531
  const commandSignal = AbortSignal.any([signal, generation.signal]);
185
- return track((async () => {
532
+ if (action === "transfer_fence") {
533
+ return track((async () => {
534
+ enabled(commandSignal);
535
+ await Promise.allSettled(Array.from(operations));
536
+ return { ok: true, settled: true, remaining: 0 };
537
+ })());
538
+ }
539
+ const operation = (async () => {
186
540
  enabled(commandSignal);
187
541
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
188
542
  throw new Error("Invalid transfer command");
189
543
  const command = payload;
190
- if (typeof command.roomId !== "string" || !command.roomId)
544
+ if (typeof command.roomId !== "string" && !action.startsWith("integration_"))
191
545
  throw new Error("Room required");
192
546
  if (typeof command.targetBotId !== "string" || !command.targetBotId)
193
547
  throw new Error("Target Bot required");
194
548
  const lease = await acquire(command.targetBotId, commandSignal);
195
549
  try {
196
- if (command.targetBotRevision !== lease.bot.revision)
550
+ if (!action.startsWith("integration_")
551
+ ? command.targetBotRevision !== lease.bot.revision
552
+ : command.targetBotRevision !== undefined && command.targetBotRevision !== lease.bot.revision)
197
553
  throw new Error("Transfer Bot revision mismatch");
554
+ if (action === "integration_prepare") {
555
+ return await devicePrepareIntegration({
556
+ integrationId: command.integrationId,
557
+ targetBotId: lease.bot.id,
558
+ targetBotRevision: lease.bot.revision,
559
+ repoRoot: lease.root,
560
+ dataDir: options.dataDir ?? process.cwd(),
561
+ targetBranch: command.targetBranch,
562
+ commit: command.commit,
563
+ }, { signal: commandSignal });
564
+ }
565
+ if (action === "integration_verify") {
566
+ return await deviceVerifyIntegration({
567
+ integrationId: command.integrationId,
568
+ targetBotId: lease.bot.id,
569
+ targetBotRevision: lease.bot.revision,
570
+ repoRoot: lease.root,
571
+ dataDir: options.dataDir ?? process.cwd(),
572
+ commands: command.commands,
573
+ }, { signal: commandSignal });
574
+ }
575
+ if (action === "integration_confirm") {
576
+ return await deviceConfirmIntegration({
577
+ integrationId: command.integrationId,
578
+ targetBotId: lease.bot.id,
579
+ targetBotRevision: lease.bot.revision,
580
+ repoRoot: lease.root,
581
+ dataDir: options.dataDir ?? process.cwd(),
582
+ deliveryId: command.deliveryId,
583
+ commit: command.commit,
584
+ expectedTargetSha: command.expectedTargetSha,
585
+ }, { signal: commandSignal });
586
+ }
587
+ if (action === "integration_cancel") {
588
+ return await deviceCancelIntegration({
589
+ integrationId: command.integrationId,
590
+ targetBotId: lease.bot.id,
591
+ targetBotRevision: lease.bot.revision,
592
+ repoRoot: lease.root,
593
+ dataDir: options.dataDir ?? process.cwd(),
594
+ }, { signal: commandSignal });
595
+ }
596
+ if (action === "transfer_fence") {
597
+ const snapshot = Array.from(transferOperations);
598
+ await Promise.allSettled(snapshot);
599
+ commandSignal.throwIfAborted();
600
+ return { ok: true };
601
+ }
198
602
  if (action === "transfer_stage") {
199
603
  const entry = roomFiles(command.roomId, command.targetBotId, lease);
200
604
  const preview = await entry.files.stage(command.bundle, { signal: commandSignal });
@@ -202,49 +606,153 @@ export function createDeviceRuntime(options) {
202
606
  receipts.set(preview.id, entry);
203
607
  return preview;
204
608
  }
609
+ if (action === "transfer_init") {
610
+ const entry = roomFiles(command.roomId, command.targetBotId, lease);
611
+ const res = await entry.files.initChunkedTransfer(command.manifest, { signal: commandSignal });
612
+ commandSignal.throwIfAborted();
613
+ receipts.set(res.transferId, entry);
614
+ return res;
615
+ }
616
+ if (action === "transfer_prepare_export") {
617
+ const entry = roomFiles(command.roomId, command.targetBotId, lease);
618
+ return await entry.files.prepareChunked({
619
+ paths: command.paths,
620
+ recursive: command.recursive === true,
621
+ transferId: command.transferId,
622
+ signal: commandSignal,
623
+ });
624
+ }
625
+ if (action === "transfer_read_chunk") {
626
+ const entry = roomFiles(command.roomId, command.targetBotId, lease);
627
+ const res = await entry.files.readChunk({
628
+ path: command.path,
629
+ offset: command.offset,
630
+ size: command.size,
631
+ expectedFileSize: typeof command.expectedFileSize === "number"
632
+ ? command.expectedFileSize
633
+ : typeof command.expectedSize === "number"
634
+ ? command.expectedSize
635
+ : undefined,
636
+ expectedChunkSha256: typeof command.expectedChunkSha256 === "string"
637
+ ? command.expectedChunkSha256
638
+ : typeof command.expectedSha256 === "string"
639
+ ? command.expectedSha256
640
+ : undefined,
641
+ signal: commandSignal,
642
+ });
643
+ return { data: res.buffer.toString("base64"), sha256: res.sha256 };
644
+ }
205
645
  const receipt = typeof command.transferId === "string" ? receipts.get(command.transferId) : undefined;
646
+ if (action === "transfer_abort") {
647
+ if (receipt) {
648
+ if (receipt.roomId !== command.roomId ||
649
+ receipt.botId !== command.targetBotId ||
650
+ receipt.revision !== lease.revision) {
651
+ throw new Error("Transfer workspace changed or transfer unavailable");
652
+ }
653
+ receipts.delete(command.transferId);
654
+ const res = await receipt.files.abortChunkedTransfer(command.transferId);
655
+ return { ...res, status: "cancelled" };
656
+ }
657
+ if (typeof command.transferId === "string") {
658
+ const entry = roomFiles(command.roomId, command.targetBotId, lease);
659
+ const res = await entry.files.abortChunkedTransfer(command.transferId);
660
+ return { ...res, status: "cancelled" };
661
+ }
662
+ return { ok: true, status: "cancelled" };
663
+ }
206
664
  if (!receipt ||
207
665
  receipt.roomId !== command.roomId ||
208
666
  receipt.botId !== command.targetBotId ||
209
667
  receipt.revision !== lease.revision)
210
668
  throw new Error("Transfer workspace changed or transfer unavailable");
211
- if (action === "transfer_preview")
212
- return await receipt.files.preview(command.transferId, { signal: commandSignal });
669
+ if (action === "transfer_chunk")
670
+ return await receipt.files.writeTransferChunk(command.chunk, { signal: commandSignal });
671
+ if (action === "transfer_status")
672
+ return await receipt.files.getTransferStatus(command.transferId);
673
+ if (action === "transfer_preview") {
674
+ try {
675
+ return await receipt.files.previewChunked(command.transferId, { signal: commandSignal });
676
+ }
677
+ catch {
678
+ return await receipt.files.preview(command.transferId, { signal: commandSignal });
679
+ }
680
+ }
213
681
  if (action === "transfer_apply" &&
214
682
  typeof command.revision === "string" &&
215
683
  Array.isArray(command.overwritePaths) &&
216
- command.overwritePaths.every((path) => typeof path === "string"))
217
- return await receipt.files.apply({
218
- id: command.transferId,
219
- revision: command.revision,
220
- decisions: Object.fromEntries(command.overwritePaths.map((path) => [path, "overwrite"])),
221
- signal: commandSignal,
222
- });
684
+ command.overwritePaths.every((path) => typeof path === "string")) {
685
+ const decisions = Object.fromEntries(command.overwritePaths.map((path) => [path, "overwrite"]));
686
+ try {
687
+ return await receipt.files.applyChunked({
688
+ transferId: command.transferId,
689
+ revision: command.revision,
690
+ decisions,
691
+ signal: commandSignal,
692
+ });
693
+ }
694
+ catch {
695
+ return await receipt.files.apply({
696
+ id: command.transferId,
697
+ revision: command.revision,
698
+ decisions,
699
+ signal: commandSignal,
700
+ });
701
+ }
702
+ }
223
703
  throw new Error("Unsupported device command");
224
704
  }
225
705
  finally {
226
706
  lease.release();
227
707
  }
228
- })());
708
+ })();
709
+ if (action.startsWith("transfer_") && action !== "transfer_fence") {
710
+ transferOperations.add(operation);
711
+ void operation.then(() => transferOperations.delete(operation), () => transferOperations.delete(operation));
712
+ }
713
+ return track(operation);
229
714
  }
230
- async function onDisconnect() {
715
+ async function onDisconnect(optionsDisconnect) {
231
716
  const previous = generation;
232
717
  generation = new AbortController();
233
- previous.abort();
234
- active?.controller.abort();
718
+ if (optionsDisconnect?.abortTasks === true) {
719
+ previous.abort();
720
+ for (const owner of active)
721
+ owner.controller.abort();
722
+ }
235
723
  await Promise.allSettled(operations);
236
724
  await sweep();
725
+ const blocked = [...active].find((owner) => owner.blocked)?.blocked;
237
726
  if (blocked)
238
727
  throw blocked;
239
728
  }
240
729
  return {
241
730
  onTask,
731
+ recovery,
732
+ reportOutbox,
733
+ getSchedulerSnapshot() {
734
+ return scheduler.getSnapshot();
735
+ },
736
+ updateExecutionSettings(next) {
737
+ if (options.dataDir) {
738
+ const saved = saveExecutionSettings(options.dataDir, next);
739
+ return scheduler.updateSettings(saved);
740
+ }
741
+ return scheduler.updateSettings(next);
742
+ },
743
+ cancelScheduledTask(taskId, attemptId) {
744
+ return scheduler.cancelTask(taskId, attemptId);
745
+ },
746
+ answerTaskInteraction(taskId, attemptId, answer) {
747
+ const owner = [...active].find((item) => item.taskId === taskId && item.attemptId === attemptId);
748
+ return !!owner && !owner.controller.signal.aborted && !owner.blocked && !!owner.answer?.(answer);
749
+ },
242
750
  onCommand,
243
751
  collabService,
244
752
  onDisconnect,
245
753
  async close() {
246
754
  closed = true;
247
- await onDisconnect();
755
+ await onDisconnect({ abortTasks: true });
248
756
  await Promise.allSettled([...files.values()].map((entry) => entry.files.close()));
249
757
  files.clear();
250
758
  receipts.clear();