pi-web-ui 0.115.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 (161) hide show
  1. package/CHANGELOG.md +65 -2
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +159 -71
  4. package/dist/server/agent-service-daemon.js +136 -8
  5. package/dist/server/agent-service.js +594 -159
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +52 -8
  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 +77 -2
  11. package/dist/server/device-center/collab-service.js +61 -12
  12. package/dist/server/device-center/collab-tool.js +482 -21
  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 +17 -7
  18. package/dist/server/device-center/execution-instructions.js +2 -1
  19. package/dist/server/device-center/execution-settings.js +138 -25
  20. package/dist/server/device-center/executor.js +51 -6
  21. package/dist/server/device-center/file-sync.js +14 -13
  22. package/dist/server/device-center/group-context-message.js +3 -1
  23. package/dist/server/device-center/group-context.js +73 -3
  24. package/dist/server/device-center/hub-conversations.js +71 -6
  25. package/dist/server/device-center/hub-deliveries.js +120 -15
  26. package/dist/server/device-center/hub-integration.js +655 -334
  27. package/dist/server/device-center/hub-locks.js +320 -0
  28. package/dist/server/device-center/hub-page.js +16 -35
  29. package/dist/server/device-center/hub-setup.js +23 -1
  30. package/dist/server/device-center/hub-transaction-log.js +197 -0
  31. package/dist/server/device-center/hub-webhooks.js +165 -0
  32. package/dist/server/device-center/hub.js +1531 -305
  33. package/dist/server/device-center/integration-verification.js +113 -0
  34. package/dist/server/device-center/local-hub.js +8 -3
  35. package/dist/server/device-center/local-publication.js +423 -0
  36. package/dist/server/device-center/local-verification-job.js +97 -0
  37. package/dist/server/device-center/local-verification.js +274 -0
  38. package/dist/server/device-center/local.js +181 -13
  39. package/dist/server/device-center/main.js +4 -1
  40. package/dist/server/device-center/partition-log.js +330 -0
  41. package/dist/server/device-center/publication-journal.js +312 -0
  42. package/dist/server/device-center/publish-intent.js +379 -0
  43. package/dist/server/device-center/relay.js +134 -24
  44. package/dist/server/device-center/runtime.js +475 -42
  45. package/dist/server/device-center/store.js +366 -89
  46. package/dist/server/device-center/task-outcome.js +81 -0
  47. package/dist/server/device-center/task-recovery.js +603 -178
  48. package/dist/server/device-center/task-scheduler.js +48 -3
  49. package/dist/server/device-center/task-settlement.js +353 -0
  50. package/dist/server/device-center/task-workspace.js +443 -0
  51. package/dist/server/device-center/transfers.js +41 -15
  52. package/dist/server/device-center/verification-limits.js +10 -0
  53. package/dist/server/device-center/work-contract.js +995 -0
  54. package/dist/server/dispatch-domain-handlers.js +29 -3
  55. package/dist/server/dsh/dsh-agent-service.js +9 -2
  56. package/dist/server/engine-probe.js +112 -1
  57. package/dist/server/global-loader.js +119 -19
  58. package/dist/server/index.js +159 -17
  59. package/dist/server/managed.js +2 -0
  60. package/dist/server/model-admin.js +48 -6
  61. package/dist/server/model-enrich.js +10 -1
  62. package/dist/server/patch-node-pty.js +3 -2
  63. package/dist/server/patch-remote-catalog.js +3 -2
  64. package/dist/server/plugins.js +64 -7
  65. package/dist/server/preset-fields.js +17 -1
  66. package/dist/server/preset-share.js +1 -0
  67. package/dist/server/prompt-composer.js +39 -0
  68. package/dist/server/protocol-version.js +1 -1
  69. package/dist/server/quick-ask-settings.js +28 -0
  70. package/dist/server/quick-ask.js +164 -0
  71. package/dist/server/reasoning-registry.js +207 -0
  72. package/dist/server/resolve-global-sdk.js +61 -11
  73. package/dist/server/scheduler-tasks.js +35 -8
  74. package/dist/server/session-list-scan.js +223 -0
  75. package/dist/server/session-open.js +93 -0
  76. package/dist/server/session-parser.js +4 -0
  77. package/dist/server/session-scan.js +90 -38
  78. package/dist/server/settings-service.js +9 -1
  79. package/dist/server/soft-cap.js +5 -0
  80. package/dist/server/startup-banner.js +35 -0
  81. package/dist/server/subagents.js +2 -1
  82. package/dist/server/tool-manager.js +17 -9
  83. package/dist/server/transcript-prepare.js +73 -0
  84. package/dist/server/unauthorized-page.js +319 -0
  85. package/dist/server/universal/drivers/claude-code.js +98 -34
  86. package/dist/server/universal/universal-session.js +4 -0
  87. package/dist/server/workspace-handle.js +428 -0
  88. package/docs/architecture-plugins.md +959 -0
  89. package/docs/device-center.md +34 -20
  90. package/package.json +4 -4
  91. package/plugin-sdk/README.md +16 -8
  92. package/plugin-sdk/client.d.ts +27 -0
  93. package/plugin-sdk/client.mjs +82 -0
  94. package/plugin-sdk/index.d.ts +10 -0
  95. package/plugin-sdk/index.mjs +4 -683
  96. package/plugin-sdk/package.json +15 -4
  97. package/plugin-sdk/testing.d.ts +10 -0
  98. package/plugin-sdk/testing.mjs +566 -0
  99. package/themes/flow-cristallo.css +168 -0
  100. package/themes/flow-ink.css +169 -0
  101. package/themes/flow-obsidian.css +169 -0
  102. package/themes/flow-zurich.css +169 -0
  103. package/web/dist/.build-assets.json +1 -1
  104. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
  105. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
  106. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  107. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
  108. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  109. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  110. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
  111. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  112. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  113. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
  114. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  115. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  116. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  117. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  118. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  119. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  120. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
  121. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  122. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  123. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
  124. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  125. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  126. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  127. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  128. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  129. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
  130. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
  131. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  132. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  133. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  134. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
  135. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
  136. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  137. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  138. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  139. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
  140. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  141. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
  142. package/web/dist/index.html +11 -11
  143. package/web/dist/sw.js +1 -1
  144. package/dist/server/patch-turn-end-boundary.js +0 -77
  145. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  146. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  147. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  148. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  149. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  150. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  151. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  152. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  153. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  154. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  155. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  156. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  157. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  158. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  159. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  160. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  161. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -1,18 +1,25 @@
1
- import { isAbsolute, join, resolve } from "node:path";
2
- import { createHash } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
3
2
  import { readFileSync, statSync } from "node:fs";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
4
  import { writeJsonAtomicSync } from "../atomic-file.js";
5
+ import { VerificationStopUnconfirmedError } from "./local-verification.js";
6
+ import { canonicalPath, computeCanonicalRepositoryId, git, verifyRepoRoot } from "../workspace-handle.js";
5
7
  import { createDeviceCollabService } from "./collab-service.js";
8
+ import { deviceCancelIntegration, deviceConfirmIntegration, devicePublicationStatus, deviceCancelPublication, devicePrepareIntegration, deviceVerifyIntegration, loadPersistentSessions, } from "./device-integration.js";
9
+ import { executionRoot, executionRootsOverlap } from "./execution-workspace.js";
6
10
  import { createDeviceTaskExecutor } from "./executor.js";
11
+ import { loadExecutionSettings, saveExecutionSettings } from "./execution-settings.js";
7
12
  import { createDeviceFileSync } from "./file-sync.js";
13
+ import { reportUploadMetadata } from "./report-metadata.js";
8
14
  import { DeviceTaskError } from "./task-error.js";
9
15
  import { TaskRecoveryManager } from "./task-recovery.js";
10
16
  import { createTaskReportOutbox } from "./task-report-outbox.js";
11
- import { reportUploadMetadata } from "./report-metadata.js";
12
17
  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";
18
+ import { cleanupTaskWorkspace, captureTaskArtifact, prepareTaskWorkspace, resolveTrustedTaskWorkspace, getTaskWorkspaceCapability, } from "./task-workspace.js";
19
+ import { canonicalizeJson, validateContextManifest, validateWorkContract } from "./work-contract.js";
20
+ import { assertPublishIntentScope, validatePublishIntent } from "./publish-intent.js";
21
+ import { readPublicationJournal, loadPublicationJournals } from "./publication-journal.js";
22
+ import { PublicationStopUnconfirmedError } from "./local-publication.js";
16
23
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
24
  function samePath(a, b) {
18
25
  if (!a || !b)
@@ -44,8 +51,47 @@ export function createDeviceRuntime(options) {
44
51
  hubUrl: config.hubUrl,
45
52
  });
46
53
  const reportOutbox = createTaskReportOutbox(options.dataDir, config.deviceId, config.hubUrl);
54
+ const schedulerFile = options.dataDir ? join(options.dataDir, "task-scheduler-state.json") : undefined;
55
+ let schedulerSaveTimer;
56
+ let schedulerStatePending = false;
57
+ function loadSchedulerState() {
58
+ if (!schedulerFile)
59
+ return undefined;
60
+ try {
61
+ return JSON.parse(readFileSync(schedulerFile, "utf8"));
62
+ }
63
+ catch {
64
+ // Corrupt or missing fairness state only means a restart starts with neutral fairness.
65
+ return undefined;
66
+ }
67
+ }
68
+ function flushSchedulerState() {
69
+ if (!schedulerFile || !schedulerStatePending)
70
+ return;
71
+ schedulerStatePending = false;
72
+ try {
73
+ writeJsonAtomicSync(schedulerFile, scheduler.snapshotState());
74
+ }
75
+ catch {
76
+ /* fairness state is best-effort; never fail dispatch on persistence */
77
+ }
78
+ }
79
+ function scheduleSchedulerStateSave() {
80
+ if (!schedulerFile)
81
+ return;
82
+ schedulerStatePending = true;
83
+ if (schedulerSaveTimer)
84
+ return;
85
+ schedulerSaveTimer = setTimeout(() => {
86
+ schedulerSaveTimer = undefined;
87
+ flushSchedulerState();
88
+ }, 250);
89
+ schedulerSaveTimer.unref?.();
90
+ }
47
91
  const scheduler = new DeviceTaskScheduler({
48
92
  initialSettings: loadExecutionSettings(options.dataDir),
93
+ persistedState: loadSchedulerState(),
94
+ onChange: scheduleSchedulerStateSave,
49
95
  });
50
96
  const conflicts = (a, b) => a.botId === b.botId || executionRootsOverlap(a.root, b.root);
51
97
  function drain() {
@@ -99,12 +145,46 @@ export function createDeviceRuntime(options) {
99
145
  await entry.files.close();
100
146
  }
101
147
  }
102
- async function acquire(botId, signal) {
148
+ async function assertPublicationWorkspaceIdle(botId, root) {
149
+ if (!options.dataDir)
150
+ return;
151
+ try {
152
+ const journals = await loadPublicationJournals(options.dataDir);
153
+ if (journals.some((journal) => journal.casStarted &&
154
+ !journal.processStopped &&
155
+ !journal.stop?.stopConfirmed &&
156
+ (journal.intent.targetBotId === botId ||
157
+ (!!journal.repository &&
158
+ executionRootsOverlap(executionRoot(journal.repository.repoRoot), executionRoot(root))))))
159
+ throw new Error("Publication process stop unconfirmed; original workspace blocked");
160
+ }
161
+ catch (error) {
162
+ throw new DeviceTaskStopUnconfirmedError(error);
163
+ }
164
+ }
165
+ async function acquire(botId, signal, cancellationId) {
103
166
  enabled(signal);
104
167
  await sweep();
105
168
  const lease = await bots.acquire(botId);
106
169
  try {
107
170
  enabled(signal);
171
+ await assertPublicationWorkspaceIdle(botId, lease.root);
172
+ if (options.dataDir) {
173
+ const pending = await loadPersistentSessions(options.dataDir);
174
+ for (const session of pending.values()) {
175
+ const legacyStopUnknown = session.verificationStopConfirmed !== true && !session.localVerification;
176
+ if (!session.verificationInFlight && !session.stopUnconfirmed && !legacyStopUnknown)
177
+ continue;
178
+ if (session.targetBotId !== botId &&
179
+ !executionRootsOverlap(executionRoot(session.repoRoot), executionRoot(lease.root)))
180
+ continue;
181
+ const canCancel = cancellationId === session.integrationId &&
182
+ ((!session.verificationInFlight && !session.stopUnconfirmed && legacyStopUnknown) ||
183
+ [...active].some((owner) => !owner.blocked && owner.taskId === `integration:${cancellationId}` && owner.botId === botId));
184
+ if (!canCancel)
185
+ throw new DeviceTaskStopUnconfirmedError(new Error("Integration process stop unconfirmed; workspace blocked"));
186
+ }
187
+ }
108
188
  if ([...active].some((owner) => owner.blocked && conflicts(owner, { botId, root: executionRoot(lease.root) })))
109
189
  throw new DeviceTaskError("Task stop unconfirmed; workspace blocked until service restart");
110
190
  return lease;
@@ -126,6 +206,7 @@ export function createDeviceRuntime(options) {
126
206
  .digest("hex")
127
207
  .slice(0, 32);
128
208
  const scopedDataDir = join(options.dataDir, "scoped-transfers", scopeToken);
209
+ const currentSettings = scheduler.getSettings();
129
210
  entry = {
130
211
  roomId,
131
212
  botId,
@@ -134,6 +215,11 @@ export function createDeviceRuntime(options) {
134
215
  root: lease.root,
135
216
  dataDir: scopedDataDir,
136
217
  allowReceive: config.allowExecution,
218
+ limits: {
219
+ bytes: currentSettings.fileSyncMaxBytes,
220
+ files: currentSettings.fileSyncMaxFiles,
221
+ stagedBytes: currentSettings.fileSyncStagedBytes,
222
+ },
137
223
  }),
138
224
  };
139
225
  files.set(key, entry);
@@ -181,6 +267,11 @@ export function createDeviceRuntime(options) {
181
267
  function onTask(task, signal, callbacks) {
182
268
  try {
183
269
  enabled(signal);
270
+ if (task.deviceId !== config.deviceId ||
271
+ ![task.id, task.attemptId, task.botId, task.roomId].every((value) => typeof value === "string" && value.length > 0 && value.length <= 128) ||
272
+ !Number.isSafeInteger(task.botRevision) ||
273
+ task.botRevision < 1)
274
+ throw new DeviceTaskError("Invalid task route or execution identity");
184
275
  }
185
276
  catch (error) {
186
277
  return Promise.reject(error);
@@ -236,6 +327,8 @@ export function createDeviceRuntime(options) {
236
327
  catch (error) {
237
328
  return Promise.reject(error);
238
329
  }
330
+ // Detach all task data before the first await; wire objects must never remain mutable inputs.
331
+ task = structuredClone(task);
239
332
  if (typeof task.leaseToken !== "string" || !task.leaseToken) {
240
333
  return Promise.reject(new DeviceTaskError("Hub task lease grant required"));
241
334
  }
@@ -243,6 +336,70 @@ export function createDeviceRuntime(options) {
243
336
  if (!capacityCheck.available) {
244
337
  return Promise.reject(new DeviceTaskError(capacityCheck.reason ?? "Recovery outbox capacity reached"));
245
338
  }
339
+ const isCode = task.executionMode === "code" || task.contract?.executionMode === "code";
340
+ let contract = task.contract;
341
+ let contextManifest = task.contextManifest;
342
+ if (contract) {
343
+ const cCheck = validateWorkContract(contract);
344
+ if (!cCheck.valid) {
345
+ return Promise.reject(new DeviceTaskError(`Invalid work contract: ${cCheck.reason}`));
346
+ }
347
+ contract = cCheck.contract;
348
+ }
349
+ if (contextManifest) {
350
+ const mCheck = validateContextManifest(contextManifest, contract);
351
+ if (!mCheck.valid) {
352
+ return Promise.reject(new DeviceTaskError(`Invalid context manifest: ${mCheck.reason}`));
353
+ }
354
+ contextManifest = mCheck.manifest;
355
+ }
356
+ if (contextManifest?.executionPolicy) {
357
+ const policy = contextManifest.executionPolicy;
358
+ if (policy.deviceId !== config.deviceId ||
359
+ policy.botId !== task.botId ||
360
+ policy.botRevision !== task.botRevision) {
361
+ return Promise.reject(new DeviceTaskError(`Context manifest execution policy mismatch: expected device=${config.deviceId}, bot=${task.botId}@${task.botRevision}; manifest specifies device=${policy.deviceId}, bot=${policy.botId}@${policy.botRevision}`));
362
+ }
363
+ }
364
+ let effectiveContext = task.context;
365
+ let effectiveTaskState = task.taskState;
366
+ if (contextManifest) {
367
+ if (contextManifest.context !== null && contextManifest.context !== undefined) {
368
+ if (task.context !== undefined &&
369
+ canonicalizeJson(task.context) !== canonicalizeJson(contextManifest.context)) {
370
+ return Promise.reject(new DeviceTaskError("Task wire context does not match sealed contextManifest"));
371
+ }
372
+ effectiveContext = contextManifest.context;
373
+ }
374
+ else {
375
+ if (task.context !== undefined && task.context !== null)
376
+ return Promise.reject(new DeviceTaskError("Task wire context does not match sealed contextManifest"));
377
+ effectiveContext = undefined;
378
+ }
379
+ if (contextManifest.taskState !== null && contextManifest.taskState !== undefined) {
380
+ if (task.taskState !== undefined &&
381
+ canonicalizeJson(task.taskState) !== canonicalizeJson(contextManifest.taskState)) {
382
+ return Promise.reject(new DeviceTaskError("Task wire taskState does not match sealed contextManifest"));
383
+ }
384
+ effectiveTaskState = contextManifest.taskState;
385
+ }
386
+ else {
387
+ if (task.taskState !== undefined && task.taskState !== null)
388
+ return Promise.reject(new DeviceTaskError("Task wire taskState does not match sealed contextManifest"));
389
+ effectiveTaskState = undefined;
390
+ }
391
+ }
392
+ if (isCode) {
393
+ if (task.resume) {
394
+ return Promise.reject(new DeviceTaskError("Code execution mode refuses resuming old sessions in first slice"));
395
+ }
396
+ if (!contract || contract.executionMode !== "code") {
397
+ return Promise.reject(new DeviceTaskError("Code task requires a valid code work contract"));
398
+ }
399
+ if (!contextManifest) {
400
+ return Promise.reject(new DeviceTaskError("Code task requires sealed contextManifest"));
401
+ }
402
+ }
246
403
  const owner = {
247
404
  controller: new AbortController(),
248
405
  botId: task.botId,
@@ -264,6 +421,9 @@ export function createDeviceRuntime(options) {
264
421
  leaseToken: task.leaseToken,
265
422
  leaseGeneration: task.leaseGeneration ?? 1,
266
423
  conversationId: task.conversationId,
424
+ contractDigest: contract?.digest,
425
+ manifestDigest: contextManifest?.digest,
426
+ executionMode: isCode ? "code" : "chat",
267
427
  });
268
428
  leaseRecorded = true;
269
429
  activeItem = scheduler.registerActive({
@@ -285,7 +445,26 @@ export function createDeviceRuntime(options) {
285
445
  callbacks?.onStarted?.();
286
446
  const taskSignal = AbortSignal.any([owner.controller.signal, ...(signal ? [signal] : [])]);
287
447
  const operation = (async () => {
448
+ let publishingOutcome = false;
449
+ const outcomeTask = {
450
+ id: task.id,
451
+ attemptId: task.attemptId,
452
+ botId: task.botId,
453
+ deviceId: config.deviceId,
454
+ roomId: task.roomId,
455
+ leaseToken: task.leaseToken,
456
+ leaseGeneration: task.leaseGeneration ?? 1,
457
+ contractDigest: contract?.digest,
458
+ manifestDigest: contextManifest?.digest,
459
+ };
288
460
  let lease;
461
+ let workspaceHandle;
462
+ let workspaceCapability;
463
+ let workspaceBinding;
464
+ let executionCwd = root;
465
+ let executionCompleted = false;
466
+ let artifactProduced = false;
467
+ let capturedArtifact;
289
468
  let stopping;
290
469
  const stop = () => {
291
470
  if (!stopping)
@@ -313,12 +492,61 @@ export function createDeviceRuntime(options) {
313
492
  lease = await acquire(task.botId, taskSignal);
314
493
  if (task.botRevision !== lease.bot.revision || executionRoot(lease.root) !== root)
315
494
  throw new Error("Task Bot revision or workspace mismatch");
495
+ const policy = contextManifest?.executionPolicy;
496
+ if (policy &&
497
+ (policy.deviceId !== config.deviceId ||
498
+ policy.botId !== lease.bot.id ||
499
+ policy.botRevision !== lease.bot.revision))
500
+ throw new Error("Context manifest execution policy mismatch with acquired lease");
316
501
  }
317
502
  catch (error) {
318
503
  if (taskSignal.aborted)
319
504
  throw error;
320
505
  throw new DeviceTaskError("目标 Bot 不可用、配置已变更或正在忙碌。 / Target Bot unavailable or busy.");
321
506
  }
507
+ executionCwd = lease.root;
508
+ if (isCode) {
509
+ if (contract?.baseline) {
510
+ const canonicalRepoId = await computeCanonicalRepositoryId(lease.root, taskSignal);
511
+ const expectedRepoId = contract.baseline.repositoryId.trim();
512
+ if (expectedRepoId !== canonicalRepoId && expectedRepoId !== "default" && expectedRepoId !== "local") {
513
+ let matchesRoot = false;
514
+ try {
515
+ const roots = (await git(lease.root, ["rev-list", "--max-parents=0", "HEAD"], taskSignal))
516
+ .trim()
517
+ .split("\n")
518
+ .map((c) => c.trim().toLowerCase());
519
+ matchesRoot = roots.includes(expectedRepoId.toLowerCase());
520
+ }
521
+ catch { }
522
+ if (!matchesRoot) {
523
+ throw new DeviceTaskError(`Repository identity mismatch: baseline specifies '${expectedRepoId}', local repository is '${canonicalRepoId}'`);
524
+ }
525
+ }
526
+ }
527
+ workspaceBinding = {
528
+ deviceId: config.deviceId,
529
+ botId: task.botId,
530
+ botRevision: lease.bot.revision,
531
+ taskId: task.id,
532
+ attemptId: task.attemptId,
533
+ };
534
+ workspaceHandle = await prepareTaskWorkspace({
535
+ dataDir: options.dataDir ?? process.cwd(),
536
+ deviceId: config.deviceId,
537
+ botId: task.botId,
538
+ botRevision: lease.bot.revision,
539
+ taskId: task.id,
540
+ attemptId: task.attemptId,
541
+ repoRoot: lease.root,
542
+ contract: contract,
543
+ contextManifest: contextManifest,
544
+ signal: taskSignal,
545
+ });
546
+ workspaceCapability = getTaskWorkspaceCapability(workspaceHandle, workspaceBinding);
547
+ const resolved = await resolveTrustedTaskWorkspace(workspaceCapability, workspaceBinding);
548
+ executionCwd = resolved.cwd;
549
+ }
322
550
  let binding;
323
551
  let resumePath;
324
552
  let transcriptPath;
@@ -327,7 +555,8 @@ export function createDeviceRuntime(options) {
327
555
  throw new DeviceTaskError("Invalid resume flag");
328
556
  if (task.resume && !task.conversationId)
329
557
  throw new DeviceTaskError("Resume conversation address required");
330
- if (task.conversationId !== undefined) {
558
+ // Code turns always use fresh sessions and never read or overwrite chat resume ownership.
559
+ if (!isCode && task.conversationId !== undefined) {
331
560
  if (!UUID.test(task.conversationId) || !transcriptFile || transcriptLoadError)
332
561
  throw new DeviceTaskError("Persistent conversation storage unavailable or invalid address");
333
562
  binding = createHash("sha256")
@@ -395,6 +624,10 @@ export function createDeviceRuntime(options) {
395
624
  localOrigin: options.localOrigin,
396
625
  localAuthToken: options.localAuthToken,
397
626
  cwd: lease.root,
627
+ executionCwd,
628
+ executionMode: isCode ? "code" : "chat",
629
+ workspaceHandleId: workspaceHandle?.handleId,
630
+ workspaceCapability,
398
631
  bot: lease.bot,
399
632
  allowExecution: config.allowExecution,
400
633
  resumePath,
@@ -406,7 +639,7 @@ export function createDeviceRuntime(options) {
406
639
  !isAbsolute(path) ||
407
640
  (resumePath && !samePath(path, resumePath)))
408
641
  throw new Error("Transcript ownership mismatch");
409
- if (task.conversationId) {
642
+ if (!isCode && task.conversationId) {
410
643
  const currentBot = bots.get(task.botId);
411
644
  if (!binding ||
412
645
  !currentBot?.enabled ||
@@ -439,9 +672,9 @@ export function createDeviceRuntime(options) {
439
672
  if (sessionId && !taskSignal.aborted)
440
673
  sessions.set(sessionId, {
441
674
  taskId,
442
- ...(task.taskState ? { taskState: structuredClone(task.taskState) } : {}),
675
+ ...(effectiveTaskState ? { taskState: structuredClone(effectiveTaskState) } : {}),
443
676
  roomId: task.roomId,
444
- root: lease.root,
677
+ root: executionCwd,
445
678
  botId: task.botId,
446
679
  conversationId: task.conversationId,
447
680
  sourceConversationId: task.sourceConversationId,
@@ -452,10 +685,34 @@ export function createDeviceRuntime(options) {
452
685
  });
453
686
  taskSignal.addEventListener("abort", stop, { once: true });
454
687
  taskSignal.throwIfAborted();
455
- const result = await owner.executor.run(task);
688
+ const result = await owner.executor.run({
689
+ ...task,
690
+ context: effectiveContext,
691
+ taskState: effectiveTaskState,
692
+ executionMode: isCode ? "code" : "chat",
693
+ contract,
694
+ contextManifest,
695
+ workspaceHandleId: workspaceHandle?.handleId,
696
+ executionCwd,
697
+ });
456
698
  await confirmStop();
457
699
  taskSignal.throwIfAborted();
458
- if (task.conversationId) {
700
+ executionCompleted = true;
701
+ if (isCode && workspaceHandle && workspaceBinding) {
702
+ try {
703
+ capturedArtifact = await captureTaskArtifact(workspaceHandle, workspaceBinding, taskSignal);
704
+ artifactProduced = true;
705
+ }
706
+ catch (captureErr) {
707
+ // capture 失败不报 completed!
708
+ // 执行完成与 artifactProduced 是独立 facts(executionCompleted 可以 true artifact 不存在导致终态 failed)
709
+ const msg = captureErr instanceof Error
710
+ ? `Task artifact capture failed: ${captureErr.message}`
711
+ : "Task artifact capture failed";
712
+ throw new DeviceTaskError(msg, msg);
713
+ }
714
+ }
715
+ if (!isCode && task.conversationId) {
459
716
  const currentBot = bots.get(task.botId);
460
717
  if (!transcriptPath ||
461
718
  !binding ||
@@ -471,39 +728,42 @@ export function createDeviceRuntime(options) {
471
728
  throw new DeviceTaskError("Conversation transcript unavailable after execution");
472
729
  }
473
730
  }
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
- }, {
731
+ // A failed durable commit must retain the lease, never manufacture a second outcome.
732
+ publishingOutcome = true;
733
+ recovery.recordTaskFinish(outcomeTask, {
482
734
  status: "completed",
483
735
  report: result,
484
736
  reportMetadata: reportUploadMetadata(reportOutbox.get(task) ?? reportOutbox.markMissing(task)),
737
+ artifact: capturedArtifact,
738
+ executionCompleted,
739
+ artifactProduced,
485
740
  });
486
741
  return result;
487
742
  }
488
743
  catch (error) {
489
- const isUnconfirmed = !!owner.blocked ||
490
- error instanceof DeviceTaskStopUnconfirmedError ||
491
- (error && typeof error === "object" && error.stopUnconfirmed === true);
744
+ if (publishingOutcome)
745
+ throw error;
746
+ let failure = error;
492
747
  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
- });
748
+ await confirmStop();
504
749
  }
505
- catch { }
506
- throw error;
750
+ catch (stopError) {
751
+ failure = stopError;
752
+ }
753
+ // 若无法确认任务已停止,必须保留 active lease 和 blocked owner,绝不能持久化终态,破坏确认停止不变量
754
+ if (owner.blocked || failure instanceof DeviceTaskStopUnconfirmedError) {
755
+ throw failure;
756
+ }
757
+ const interrupted = taskSignal.aborted;
758
+ recovery.recordTaskFinish(outcomeTask, {
759
+ status: interrupted ? "interrupted" : "failed",
760
+ error: failure,
761
+ reportMetadata: reportUploadMetadata(reportOutbox.get(task) ?? reportOutbox.markMissing(task)),
762
+ artifact: capturedArtifact,
763
+ executionCompleted,
764
+ artifactProduced,
765
+ });
766
+ throw failure;
507
767
  }
508
768
  finally {
509
769
  taskSignal.removeEventListener("abort", stop);
@@ -516,6 +776,14 @@ export function createDeviceRuntime(options) {
516
776
  for (const [id, bound] of sessions)
517
777
  if (bound.taskId === task.id && bound.roomId === task.roomId)
518
778
  sessions.delete(id);
779
+ // 只能在 stoppedCleanly && !owner.blocked 时保守清理(无 force,dirty/额外commit会被保留)
780
+ // 若 stop 未确认,绝不能清理工作区,保留现场!
781
+ if (stoppedCleanly && !owner.blocked && workspaceHandle && workspaceBinding) {
782
+ try {
783
+ await cleanupTaskWorkspace(workspaceHandle, workspaceBinding, { force: false });
784
+ }
785
+ catch { }
786
+ }
519
787
  if (!owner.blocked && stoppedCleanly) {
520
788
  lease?.release();
521
789
  if (activeItem)
@@ -527,8 +795,88 @@ export function createDeviceRuntime(options) {
527
795
  owner.done = operation;
528
796
  return track(operation);
529
797
  }
798
+ async function originalPublicationCommand(command, historical) {
799
+ const intent = validatePublishIntent(command.publishIntent);
800
+ assertPublishIntentScope(intent, {
801
+ accountId: config.accountId ?? intent.accountId,
802
+ targetDeviceId: config.deviceId,
803
+ });
804
+ if (command.accountId !== intent.accountId ||
805
+ command.roomId !== intent.roomId ||
806
+ command.conversationId !== intent.conversationId ||
807
+ command.integrationId !== intent.integrationId ||
808
+ command.targetBotId !== intent.targetBotId ||
809
+ command.targetBotRevision !== intent.targetBotRevision)
810
+ throw new Error("Publication command original scope mismatch");
811
+ const original = await readPublicationJournal(options.dataDir ?? process.cwd(), intent);
812
+ if (!config.accountId) {
813
+ if (!historical || !original)
814
+ throw new Error("Authenticated publication account context required");
815
+ }
816
+ return intent;
817
+ }
818
+ async function ownerCleanup(command, signal) {
819
+ if (!options.dataDir || typeof command.integrationId !== "string")
820
+ throw new Error("Original integration session required for owner cleanup");
821
+ const session = (await loadPersistentSessions(options.dataDir)).get(command.integrationId);
822
+ if (!session ||
823
+ session.targetBotId !== command.targetBotId ||
824
+ session.targetBotRevision !== command.targetBotRevision)
825
+ throw new Error("Original integration cleanup identity mismatch");
826
+ await assertPublicationWorkspaceIdle(session.targetBotId, session.repoRoot);
827
+ const identity = { botId: session.targetBotId, root: executionRoot(session.repoRoot) };
828
+ const existing = [...active].find((owner) => owner.taskId === `integration:${session.integrationId}` && owner.botId === session.targetBotId);
829
+ if ([...active].some((owner) => conflicts(owner, identity) && owner !== existing))
830
+ throw new Error("Target Bot or workspace is busy");
831
+ let owner;
832
+ let item;
833
+ if (!existing) {
834
+ owner = {
835
+ ...identity,
836
+ controller: new AbortController(),
837
+ taskId: `integration:${session.integrationId}`,
838
+ attemptId: randomUUID(),
839
+ };
840
+ item = scheduler.registerActive({
841
+ id: owner.taskId,
842
+ attemptId: owner.attemptId,
843
+ roomId: "integration",
844
+ botId: owner.botId,
845
+ botRevision: String(session.targetBotRevision),
846
+ root: owner.root,
847
+ }, owner.controller);
848
+ active.add(owner);
849
+ }
850
+ try {
851
+ return await deviceCancelIntegration({
852
+ integrationId: session.integrationId,
853
+ targetBotId: session.targetBotId,
854
+ targetBotRevision: session.targetBotRevision,
855
+ repoRoot: session.repoRoot,
856
+ dataDir: options.dataDir,
857
+ priorStatus: command.priorStatus,
858
+ verificationMayBeRunning: command.verificationMayBeRunning === true,
859
+ }, { signal });
860
+ }
861
+ catch (error) {
862
+ if (error instanceof VerificationStopUnconfirmedError && owner) {
863
+ owner.blocked = error;
864
+ scheduler.markBlocked(owner.taskId, owner.attemptId, error);
865
+ }
866
+ throw error;
867
+ }
868
+ finally {
869
+ if (owner && !owner.blocked) {
870
+ if (item)
871
+ scheduler.releaseActive(item);
872
+ active.delete(owner);
873
+ drain();
874
+ }
875
+ }
876
+ }
530
877
  function onCommand(action, payload, signal) {
531
- const commandSignal = AbortSignal.any([signal, generation.signal]);
878
+ const integrationController = new AbortController();
879
+ const commandSignal = AbortSignal.any([signal, generation.signal, integrationController.signal]);
532
880
  if (action === "transfer_fence") {
533
881
  return track((async () => {
534
882
  enabled(commandSignal);
@@ -537,20 +885,62 @@ export function createDeviceRuntime(options) {
537
885
  })());
538
886
  }
539
887
  const operation = (async () => {
540
- enabled(commandSignal);
541
888
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
542
889
  throw new Error("Invalid transfer command");
543
890
  const command = payload;
891
+ if (action === "integration_publication_status" || (action === "integration_cancel" && command.publishIntent)) {
892
+ const intent = await originalPublicationCommand(command, true);
893
+ const historical = { dataDir: options.dataDir ?? process.cwd(), publishIntent: intent };
894
+ return action === "integration_publication_status"
895
+ ? devicePublicationStatus(historical)
896
+ : deviceCancelPublication(historical);
897
+ }
898
+ enabled(commandSignal);
899
+ if (action === "integration_confirm")
900
+ await originalPublicationCommand(command, false);
544
901
  if (typeof command.roomId !== "string" && !action.startsWith("integration_"))
545
902
  throw new Error("Room required");
546
903
  if (typeof command.targetBotId !== "string" || !command.targetBotId)
547
904
  throw new Error("Target Bot required");
548
- const lease = await acquire(command.targetBotId, commandSignal);
905
+ if (action === "integration_cancel" && command.ownerCleanup === true)
906
+ return ownerCleanup(command, commandSignal);
907
+ const lease = await acquire(command.targetBotId, commandSignal, action === "integration_cancel" ? String(command.integrationId) : undefined);
908
+ let integrationOwner;
909
+ let integrationItem;
549
910
  try {
550
911
  if (!action.startsWith("integration_")
551
912
  ? command.targetBotRevision !== lease.bot.revision
552
913
  : command.targetBotRevision !== undefined && command.targetBotRevision !== lease.bot.revision)
553
914
  throw new Error("Transfer Bot revision mismatch");
915
+ if (action.startsWith("integration_")) {
916
+ const repo = await verifyRepoRoot(lease.root, commandSignal);
917
+ if (repo.repoRoot !== (await canonicalPath(lease.root)))
918
+ throw new Error("Integration Bot workspace must be the canonical repository root");
919
+ }
920
+ if (action === "integration_cancel" &&
921
+ [...active].some((owner) => conflicts(owner, { botId: lease.bot.id, root: executionRoot(lease.root) }) &&
922
+ owner.taskId !== `integration:${String(command.integrationId)}`))
923
+ throw new Error("Target Bot or workspace is busy");
924
+ if (action.startsWith("integration_") &&
925
+ !(action === "integration_cancel" &&
926
+ [...active].some((owner) => owner.taskId === `integration:${String(command.integrationId)}` && owner.botId === lease.bot.id))) {
927
+ integrationOwner = {
928
+ controller: integrationController,
929
+ botId: lease.bot.id,
930
+ root: executionRoot(lease.root),
931
+ taskId: `integration:${String(command.integrationId)}`,
932
+ attemptId: randomUUID(),
933
+ };
934
+ integrationItem = scheduler.registerActive({
935
+ id: integrationOwner.taskId,
936
+ attemptId: integrationOwner.attemptId,
937
+ roomId: typeof command.roomId === "string" ? command.roomId : "integration",
938
+ botId: lease.bot.id,
939
+ botRevision: String(lease.bot.revision),
940
+ root: integrationOwner.root,
941
+ }, integrationController);
942
+ active.add(integrationOwner);
943
+ }
554
944
  if (action === "integration_prepare") {
555
945
  return await devicePrepareIntegration({
556
946
  integrationId: command.integrationId,
@@ -560,16 +950,28 @@ export function createDeviceRuntime(options) {
560
950
  dataDir: options.dataDir ?? process.cwd(),
561
951
  targetBranch: command.targetBranch,
562
952
  commit: command.commit,
953
+ artifactRef: command.artifactRef,
954
+ artifact: command.artifact,
955
+ accountId: config.accountId,
956
+ roomId: command.roomId,
957
+ conversationId: command.conversationId,
958
+ targetDeviceId: config.deviceId,
563
959
  }, { signal: commandSignal });
564
960
  }
565
961
  if (action === "integration_verify") {
962
+ if (!lease.bot.tools.includes("bash"))
963
+ throw new Error("Target Bot bash command permission required");
566
964
  return await deviceVerifyIntegration({
567
965
  integrationId: command.integrationId,
568
966
  targetBotId: lease.bot.id,
569
967
  targetBotRevision: lease.bot.revision,
570
968
  repoRoot: lease.root,
571
969
  dataDir: options.dataDir ?? process.cwd(),
572
- commands: command.commands,
970
+ verificationPlan: command.verificationPlan,
971
+ artifactRef: command.artifactRef,
972
+ materializedCommit: command.materializedCommit,
973
+ preparedTree: command.preparedTree,
974
+ expectedTargetSha: command.expectedTargetSha,
573
975
  }, { signal: commandSignal });
574
976
  }
575
977
  if (action === "integration_confirm") {
@@ -581,7 +983,10 @@ export function createDeviceRuntime(options) {
581
983
  dataDir: options.dataDir ?? process.cwd(),
582
984
  deliveryId: command.deliveryId,
583
985
  commit: command.commit,
986
+ materializedCommit: command.materializedCommit,
584
987
  expectedTargetSha: command.expectedTargetSha,
988
+ publishIntent: validatePublishIntent(command.publishIntent),
989
+ mode: command.mode === "resume" ? "resume" : "first",
585
990
  }, { signal: commandSignal });
586
991
  }
587
992
  if (action === "integration_cancel") {
@@ -591,6 +996,8 @@ export function createDeviceRuntime(options) {
591
996
  targetBotRevision: lease.bot.revision,
592
997
  repoRoot: lease.root,
593
998
  dataDir: options.dataDir ?? process.cwd(),
999
+ priorStatus: command.priorStatus,
1000
+ verificationMayBeRunning: command.verificationMayBeRunning === true,
594
1001
  }, { signal: commandSignal });
595
1002
  }
596
1003
  if (action === "transfer_fence") {
@@ -702,8 +1109,23 @@ export function createDeviceRuntime(options) {
702
1109
  }
703
1110
  throw new Error("Unsupported device command");
704
1111
  }
1112
+ catch (error) {
1113
+ if ((error instanceof VerificationStopUnconfirmedError || error instanceof PublicationStopUnconfirmedError) &&
1114
+ integrationOwner) {
1115
+ integrationOwner.blocked = error;
1116
+ scheduler.markBlocked(integrationOwner.taskId, integrationOwner.attemptId, error);
1117
+ }
1118
+ throw error;
1119
+ }
705
1120
  finally {
706
- lease.release();
1121
+ if (!integrationOwner?.blocked) {
1122
+ lease.release();
1123
+ if (integrationItem)
1124
+ scheduler.releaseActive(integrationItem);
1125
+ if (integrationOwner)
1126
+ active.delete(integrationOwner);
1127
+ drain();
1128
+ }
707
1129
  }
708
1130
  })();
709
1131
  if (action.startsWith("transfer_") && action !== "transfer_fence") {
@@ -743,6 +1165,13 @@ export function createDeviceRuntime(options) {
743
1165
  cancelScheduledTask(taskId, attemptId) {
744
1166
  return scheduler.cancelTask(taskId, attemptId);
745
1167
  },
1168
+ async steerTask(taskId, text) {
1169
+ const owner = [...active].find((item) => item.taskId === taskId);
1170
+ if (!owner || owner.controller.signal.aborted || owner.blocked || !owner.executor?.steer) {
1171
+ return false;
1172
+ }
1173
+ return owner.executor.steer(text);
1174
+ },
746
1175
  answerTaskInteraction(taskId, attemptId, answer) {
747
1176
  const owner = [...active].find((item) => item.taskId === taskId && item.attemptId === attemptId);
748
1177
  return !!owner && !owner.controller.signal.aborted && !owner.blocked && !!owner.answer?.(answer);
@@ -752,6 +1181,10 @@ export function createDeviceRuntime(options) {
752
1181
  onDisconnect,
753
1182
  async close() {
754
1183
  closed = true;
1184
+ if (schedulerSaveTimer)
1185
+ clearTimeout(schedulerSaveTimer);
1186
+ schedulerSaveTimer = undefined;
1187
+ flushSchedulerState();
755
1188
  await onDisconnect({ abortTasks: true });
756
1189
  await Promise.allSettled([...files.values()].map((entry) => entry.files.close()));
757
1190
  files.clear();