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,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)
@@ -138,12 +145,46 @@ export function createDeviceRuntime(options) {
138
145
  await entry.files.close();
139
146
  }
140
147
  }
141
- 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) {
142
166
  enabled(signal);
143
167
  await sweep();
144
168
  const lease = await bots.acquire(botId);
145
169
  try {
146
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
+ }
147
188
  if ([...active].some((owner) => owner.blocked && conflicts(owner, { botId, root: executionRoot(lease.root) })))
148
189
  throw new DeviceTaskError("Task stop unconfirmed; workspace blocked until service restart");
149
190
  return lease;
@@ -226,6 +267,11 @@ export function createDeviceRuntime(options) {
226
267
  function onTask(task, signal, callbacks) {
227
268
  try {
228
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");
229
275
  }
230
276
  catch (error) {
231
277
  return Promise.reject(error);
@@ -281,6 +327,8 @@ export function createDeviceRuntime(options) {
281
327
  catch (error) {
282
328
  return Promise.reject(error);
283
329
  }
330
+ // Detach all task data before the first await; wire objects must never remain mutable inputs.
331
+ task = structuredClone(task);
284
332
  if (typeof task.leaseToken !== "string" || !task.leaseToken) {
285
333
  return Promise.reject(new DeviceTaskError("Hub task lease grant required"));
286
334
  }
@@ -288,6 +336,70 @@ export function createDeviceRuntime(options) {
288
336
  if (!capacityCheck.available) {
289
337
  return Promise.reject(new DeviceTaskError(capacityCheck.reason ?? "Recovery outbox capacity reached"));
290
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
+ }
291
403
  const owner = {
292
404
  controller: new AbortController(),
293
405
  botId: task.botId,
@@ -309,6 +421,9 @@ export function createDeviceRuntime(options) {
309
421
  leaseToken: task.leaseToken,
310
422
  leaseGeneration: task.leaseGeneration ?? 1,
311
423
  conversationId: task.conversationId,
424
+ contractDigest: contract?.digest,
425
+ manifestDigest: contextManifest?.digest,
426
+ executionMode: isCode ? "code" : "chat",
312
427
  });
313
428
  leaseRecorded = true;
314
429
  activeItem = scheduler.registerActive({
@@ -330,7 +445,26 @@ export function createDeviceRuntime(options) {
330
445
  callbacks?.onStarted?.();
331
446
  const taskSignal = AbortSignal.any([owner.controller.signal, ...(signal ? [signal] : [])]);
332
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
+ };
333
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;
334
468
  let stopping;
335
469
  const stop = () => {
336
470
  if (!stopping)
@@ -358,12 +492,61 @@ export function createDeviceRuntime(options) {
358
492
  lease = await acquire(task.botId, taskSignal);
359
493
  if (task.botRevision !== lease.bot.revision || executionRoot(lease.root) !== root)
360
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");
361
501
  }
362
502
  catch (error) {
363
503
  if (taskSignal.aborted)
364
504
  throw error;
365
505
  throw new DeviceTaskError("目标 Bot 不可用、配置已变更或正在忙碌。 / Target Bot unavailable or busy.");
366
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
+ }
367
550
  let binding;
368
551
  let resumePath;
369
552
  let transcriptPath;
@@ -372,7 +555,8 @@ export function createDeviceRuntime(options) {
372
555
  throw new DeviceTaskError("Invalid resume flag");
373
556
  if (task.resume && !task.conversationId)
374
557
  throw new DeviceTaskError("Resume conversation address required");
375
- 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) {
376
560
  if (!UUID.test(task.conversationId) || !transcriptFile || transcriptLoadError)
377
561
  throw new DeviceTaskError("Persistent conversation storage unavailable or invalid address");
378
562
  binding = createHash("sha256")
@@ -440,6 +624,10 @@ export function createDeviceRuntime(options) {
440
624
  localOrigin: options.localOrigin,
441
625
  localAuthToken: options.localAuthToken,
442
626
  cwd: lease.root,
627
+ executionCwd,
628
+ executionMode: isCode ? "code" : "chat",
629
+ workspaceHandleId: workspaceHandle?.handleId,
630
+ workspaceCapability,
443
631
  bot: lease.bot,
444
632
  allowExecution: config.allowExecution,
445
633
  resumePath,
@@ -451,7 +639,7 @@ export function createDeviceRuntime(options) {
451
639
  !isAbsolute(path) ||
452
640
  (resumePath && !samePath(path, resumePath)))
453
641
  throw new Error("Transcript ownership mismatch");
454
- if (task.conversationId) {
642
+ if (!isCode && task.conversationId) {
455
643
  const currentBot = bots.get(task.botId);
456
644
  if (!binding ||
457
645
  !currentBot?.enabled ||
@@ -484,9 +672,9 @@ export function createDeviceRuntime(options) {
484
672
  if (sessionId && !taskSignal.aborted)
485
673
  sessions.set(sessionId, {
486
674
  taskId,
487
- ...(task.taskState ? { taskState: structuredClone(task.taskState) } : {}),
675
+ ...(effectiveTaskState ? { taskState: structuredClone(effectiveTaskState) } : {}),
488
676
  roomId: task.roomId,
489
- root: lease.root,
677
+ root: executionCwd,
490
678
  botId: task.botId,
491
679
  conversationId: task.conversationId,
492
680
  sourceConversationId: task.sourceConversationId,
@@ -497,10 +685,34 @@ export function createDeviceRuntime(options) {
497
685
  });
498
686
  taskSignal.addEventListener("abort", stop, { once: true });
499
687
  taskSignal.throwIfAborted();
500
- 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
+ });
501
698
  await confirmStop();
502
699
  taskSignal.throwIfAborted();
503
- 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) {
504
716
  const currentBot = bots.get(task.botId);
505
717
  if (!transcriptPath ||
506
718
  !binding ||
@@ -516,39 +728,42 @@ export function createDeviceRuntime(options) {
516
728
  throw new DeviceTaskError("Conversation transcript unavailable after execution");
517
729
  }
518
730
  }
519
- // Commit to durable outbox ONLY after all outcomes and transcripts are verified
520
- recovery.recordTaskFinish({
521
- id: task.id,
522
- attemptId: task.attemptId,
523
- botId: task.botId,
524
- deviceId: config.deviceId,
525
- roomId: task.roomId,
526
- }, {
731
+ // A failed durable commit must retain the lease, never manufacture a second outcome.
732
+ publishingOutcome = true;
733
+ recovery.recordTaskFinish(outcomeTask, {
527
734
  status: "completed",
528
735
  report: result,
529
736
  reportMetadata: reportUploadMetadata(reportOutbox.get(task) ?? reportOutbox.markMissing(task)),
737
+ artifact: capturedArtifact,
738
+ executionCompleted,
739
+ artifactProduced,
530
740
  });
531
741
  return result;
532
742
  }
533
743
  catch (error) {
534
- const isUnconfirmed = !!owner.blocked ||
535
- error instanceof DeviceTaskStopUnconfirmedError ||
536
- (error && typeof error === "object" && error.stopUnconfirmed === true);
744
+ if (publishingOutcome)
745
+ throw error;
746
+ let failure = error;
537
747
  try {
538
- recovery.recordTaskFinish({
539
- id: task.id,
540
- attemptId: task.attemptId,
541
- botId: task.botId,
542
- deviceId: config.deviceId,
543
- roomId: task.roomId,
544
- }, {
545
- status: isUnconfirmed ? "interrupted" : "failed",
546
- error,
547
- reportMetadata: reportUploadMetadata(reportOutbox.get(task) ?? reportOutbox.markMissing(task)),
548
- });
748
+ await confirmStop();
549
749
  }
550
- catch { }
551
- 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;
552
767
  }
553
768
  finally {
554
769
  taskSignal.removeEventListener("abort", stop);
@@ -561,6 +776,14 @@ export function createDeviceRuntime(options) {
561
776
  for (const [id, bound] of sessions)
562
777
  if (bound.taskId === task.id && bound.roomId === task.roomId)
563
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
+ }
564
787
  if (!owner.blocked && stoppedCleanly) {
565
788
  lease?.release();
566
789
  if (activeItem)
@@ -572,8 +795,88 @@ export function createDeviceRuntime(options) {
572
795
  owner.done = operation;
573
796
  return track(operation);
574
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
+ }
575
877
  function onCommand(action, payload, signal) {
576
- const commandSignal = AbortSignal.any([signal, generation.signal]);
878
+ const integrationController = new AbortController();
879
+ const commandSignal = AbortSignal.any([signal, generation.signal, integrationController.signal]);
577
880
  if (action === "transfer_fence") {
578
881
  return track((async () => {
579
882
  enabled(commandSignal);
@@ -582,20 +885,62 @@ export function createDeviceRuntime(options) {
582
885
  })());
583
886
  }
584
887
  const operation = (async () => {
585
- enabled(commandSignal);
586
888
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
587
889
  throw new Error("Invalid transfer command");
588
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);
589
901
  if (typeof command.roomId !== "string" && !action.startsWith("integration_"))
590
902
  throw new Error("Room required");
591
903
  if (typeof command.targetBotId !== "string" || !command.targetBotId)
592
904
  throw new Error("Target Bot required");
593
- 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;
594
910
  try {
595
911
  if (!action.startsWith("integration_")
596
912
  ? command.targetBotRevision !== lease.bot.revision
597
913
  : command.targetBotRevision !== undefined && command.targetBotRevision !== lease.bot.revision)
598
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
+ }
599
944
  if (action === "integration_prepare") {
600
945
  return await devicePrepareIntegration({
601
946
  integrationId: command.integrationId,
@@ -605,16 +950,28 @@ export function createDeviceRuntime(options) {
605
950
  dataDir: options.dataDir ?? process.cwd(),
606
951
  targetBranch: command.targetBranch,
607
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,
608
959
  }, { signal: commandSignal });
609
960
  }
610
961
  if (action === "integration_verify") {
962
+ if (!lease.bot.tools.includes("bash"))
963
+ throw new Error("Target Bot bash command permission required");
611
964
  return await deviceVerifyIntegration({
612
965
  integrationId: command.integrationId,
613
966
  targetBotId: lease.bot.id,
614
967
  targetBotRevision: lease.bot.revision,
615
968
  repoRoot: lease.root,
616
969
  dataDir: options.dataDir ?? process.cwd(),
617
- commands: command.commands,
970
+ verificationPlan: command.verificationPlan,
971
+ artifactRef: command.artifactRef,
972
+ materializedCommit: command.materializedCommit,
973
+ preparedTree: command.preparedTree,
974
+ expectedTargetSha: command.expectedTargetSha,
618
975
  }, { signal: commandSignal });
619
976
  }
620
977
  if (action === "integration_confirm") {
@@ -626,7 +983,10 @@ export function createDeviceRuntime(options) {
626
983
  dataDir: options.dataDir ?? process.cwd(),
627
984
  deliveryId: command.deliveryId,
628
985
  commit: command.commit,
986
+ materializedCommit: command.materializedCommit,
629
987
  expectedTargetSha: command.expectedTargetSha,
988
+ publishIntent: validatePublishIntent(command.publishIntent),
989
+ mode: command.mode === "resume" ? "resume" : "first",
630
990
  }, { signal: commandSignal });
631
991
  }
632
992
  if (action === "integration_cancel") {
@@ -636,6 +996,8 @@ export function createDeviceRuntime(options) {
636
996
  targetBotRevision: lease.bot.revision,
637
997
  repoRoot: lease.root,
638
998
  dataDir: options.dataDir ?? process.cwd(),
999
+ priorStatus: command.priorStatus,
1000
+ verificationMayBeRunning: command.verificationMayBeRunning === true,
639
1001
  }, { signal: commandSignal });
640
1002
  }
641
1003
  if (action === "transfer_fence") {
@@ -747,8 +1109,23 @@ export function createDeviceRuntime(options) {
747
1109
  }
748
1110
  throw new Error("Unsupported device command");
749
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
+ }
750
1120
  finally {
751
- 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
+ }
752
1129
  }
753
1130
  })();
754
1131
  if (action.startsWith("transfer_") && action !== "transfer_fence") {
@@ -788,6 +1165,13 @@ export function createDeviceRuntime(options) {
788
1165
  cancelScheduledTask(taskId, attemptId) {
789
1166
  return scheduler.cancelTask(taskId, attemptId);
790
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
+ },
791
1175
  answerTaskInteraction(taskId, attemptId, answer) {
792
1176
  const owner = [...active].find((item) => item.taskId === taskId && item.attemptId === attemptId);
793
1177
  return !!owner && !owner.controller.signal.aborted && !owner.blocked && !!owner.answer?.(answer);