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,5 +1,10 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { sealPublishIntent, validatePublishIntent, validatePublicationResult } from "./publish-intent.js";
2
3
  import { getAcceptedDeliveryForIntegration } from "./hub-deliveries.js";
4
+ import { assertDeliveryAuthority, assertNoApplyingIntegration, hasOpenPublication, isLegacyPublicationUnknown, } from "./delivery-authority.js";
5
+ import { artifactRefsMatch, deliveryReviewMatches } from "./delivery-subject.js";
6
+ import { computeVerificationDigest, freezeVerificationPlan, hasVerifiedIntegration, validateVerificationFacts, } from "./integration-verification.js";
7
+ import { canonicalizeJson } from "./work-contract.js";
3
8
  function fail(status, message) {
4
9
  throw Object.assign(new Error(message), { status });
5
10
  }
@@ -7,16 +12,15 @@ function text(value, max, name) {
7
12
  if (typeof value !== "string" ||
8
13
  !value.trim() ||
9
14
  value.length > max ||
10
- /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value)) {
15
+ /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))
11
16
  fail(400, `Invalid ${name}`);
12
- }
13
17
  return value.trim();
14
18
  }
15
19
  function sha(value) {
16
20
  const result = text(value, 64, "commit");
17
- if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(result))
18
- fail(400, "Full commit SHA required");
19
- return result.toLowerCase();
21
+ if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/.test(result))
22
+ fail(502, "Full commit SHA required");
23
+ return result;
20
24
  }
21
25
  function safeBranch(value) {
22
26
  const result = text(value, 256, "branch");
@@ -25,16 +29,12 @@ function safeBranch(value) {
25
29
  result.includes("..") ||
26
30
  result.startsWith("/") ||
27
31
  result.endsWith("/") ||
28
- result.endsWith(".lock")) {
32
+ result.endsWith(".lock"))
29
33
  fail(400, "Invalid branch name");
30
- }
31
34
  return result;
32
35
  }
33
36
  function sanitizePublicError(error) {
34
- if (!error)
35
- return "Integration operation failed";
36
- const raw = error instanceof Error ? error.message : String(error);
37
- return raw
37
+ return (error instanceof Error ? error.message : String(error))
38
38
  .replace(/\/\/[^@\s]+@/g, "//***@")
39
39
  .split("\n")[0]
40
40
  .trim()
@@ -42,410 +42,731 @@ function sanitizePublicError(error) {
42
42
  }
43
43
  function wrapRpcError(error) {
44
44
  const err = error instanceof Error ? error : new Error(String(error));
45
- const msg = err.message.toLowerCase();
46
- if (!err.status) {
47
- if (msg.includes("checked out") ||
48
- msg.includes("moved from") ||
49
- msg.includes("uncommitted") ||
50
- msg.includes("dirty") ||
51
- msg.includes("custom") ||
52
- msg.includes("mismatch") ||
53
- msg.includes("offline") ||
54
- msg.includes("cannot") ||
55
- msg.includes("rejected") ||
56
- msg.includes("conflict")) {
57
- Object.assign(err, { status: 409 });
58
- }
59
- else {
60
- Object.assign(err, { status: 502 });
61
- }
62
- }
45
+ if (!err.status)
46
+ Object.assign(err, {
47
+ status: /checked out|moved from|uncommitted|dirty|custom|mismatch|offline|cannot|rejected|conflict/i.test(err.message)
48
+ ? 409
49
+ : 502,
50
+ });
63
51
  return err;
64
52
  }
65
- /** 白名单验证并投影设备端准备集成返回的结果 */
66
- function validateDevicePrepareResult(raw) {
67
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
68
- fail(502, "Invalid device response");
69
- }
70
- const obj = raw;
71
- if (obj.status !== "prepared" && obj.status !== "conflict") {
72
- fail(502, "Invalid integration status from device");
73
- }
74
- const expectedTargetSha = sha(obj.expectedTargetSha);
75
- let conflicts;
76
- if (obj.conflicts !== undefined) {
77
- if (!Array.isArray(obj.conflicts) || obj.conflicts.some((c) => typeof c !== "string" || !c.trim())) {
78
- fail(502, "Invalid conflicts list from device");
53
+ function actorTask(state, roomId, actor) {
54
+ const room = state.rooms.find((r) => r.id === roomId && r.accountId === actor.accountId);
55
+ if (!room)
56
+ fail(404, "Room missing");
57
+ if (actor.originalBot)
58
+ fail(403, "Historical actor is read-only");
59
+ if (!actor.bot)
60
+ return undefined;
61
+ const bot = state.bots.find((b) => b.id === actor.bot.id &&
62
+ b.accountId === actor.accountId &&
63
+ b.enabled &&
64
+ b.revision === actor.bot.revision &&
65
+ b.deviceId === actor.bot.deviceId);
66
+ if (!bot ||
67
+ !room.botIds.includes(bot.id) ||
68
+ !state.devices.some((d) => d.id === bot.deviceId && d.accountId === actor.accountId))
69
+ fail(403, "Actor Bot membership or revision changed");
70
+ const task = state.tasks.find((t) => t.accountId === actor.accountId &&
71
+ t.roomId === roomId &&
72
+ t.botId === bot.id &&
73
+ t.deviceId === bot.deviceId &&
74
+ t.botRevision === bot.revision &&
75
+ t.status === "running" &&
76
+ !t.cancelRequested &&
77
+ state.conversations.some((c) => c.id === t.conversationId &&
78
+ c.latestTaskId === t.id &&
79
+ !c.closed &&
80
+ c.botId === bot.id &&
81
+ c.botRevision === bot.revision &&
82
+ c.deviceId === bot.deviceId));
83
+ if (!task)
84
+ fail(403, "Current running Bot task required");
85
+ return task.id;
86
+ }
87
+ function recordFor(state, roomId, conversationId, id, actor) {
88
+ const record = state.integrations.find((i) => i.id === id && i.accountId === actor.accountId && i.roomId === roomId && i.conversationId === conversationId);
89
+ if (!record)
90
+ fail(404, "Integration task not found");
91
+ return record;
92
+ }
93
+ function latestDelivery(state, roomId, conversationId, accountId, deliveryId) {
94
+ if (!state.conversations.some((c) => c.id === conversationId && c.roomId === roomId && c.accountId === accountId && !c.closed))
95
+ fail(404, "Conversation missing or closed");
96
+ const delivery = state.deliveries
97
+ .filter((d) => d.accountId === accountId && d.roomId === roomId && d.conversationId === conversationId)
98
+ .at(-1);
99
+ if (!delivery || delivery.id !== deliveryId)
100
+ fail(409, "Only the latest delivery can be integrated");
101
+ assertDeliveryAuthority(state, delivery);
102
+ return delivery;
103
+ }
104
+ function targetBot(state, record, allowLegacyCancellation = false) {
105
+ const room = state.rooms.find((r) => r.id === record.roomId && r.accountId === record.accountId);
106
+ const bot = state.bots.find((b) => b.id === record.targetBotId &&
107
+ b.accountId === record.accountId &&
108
+ b.enabled &&
109
+ b.revision === record.targetBotRevision &&
110
+ (b.deviceId === record.targetDeviceId || (allowLegacyCancellation && record.targetDeviceId === undefined)));
111
+ if (!bot ||
112
+ !room?.botIds.includes(bot.id) ||
113
+ !state.devices.some((d) => d.id === bot.deviceId && d.accountId === record.accountId))
114
+ fail(409, "Target Bot membership, revision or device changed");
115
+ return bot;
116
+ }
117
+ function authority(state, record, accepted = false) {
118
+ const delivery = latestDelivery(state, record.roomId, record.conversationId, record.accountId, record.deliveryId);
119
+ if (delivery.artifactRef
120
+ ? !artifactRefsMatch(delivery.artifactRef, record.artifactRef)
121
+ : !!record.artifactRef || !delivery.commit || delivery.commit !== record.commit)
122
+ fail(409, "Delivery subject changed");
123
+ let review;
124
+ if (accepted || !delivery.artifactRef) {
125
+ review = getAcceptedDeliveryForIntegration(state, record.conversationId, delivery.id).review;
126
+ if (delivery.artifactRef) {
127
+ const task = assertDeliveryAuthority(state, delivery);
128
+ const criteria = task.contract.acceptanceCriteria ?? [];
129
+ if (!deliveryReviewMatches(delivery, review) ||
130
+ review.integrationId !== record.id ||
131
+ review.verificationDigest !== record.verification?.digest ||
132
+ !review.criteriaResults ||
133
+ review.criteriaResults.length !== criteria.length ||
134
+ new Set(review.criteriaResults.map((c) => c.criterionIndex)).size !== criteria.length ||
135
+ review.criteriaResults.some((c) => c.verdict !== "met" ||
136
+ !Number.isInteger(c.criterionIndex) ||
137
+ c.criterionIndex < 0 ||
138
+ c.criterionIndex >= criteria.length ||
139
+ !c.evidence.trim()))
140
+ fail(409, "Artifact accepted review must match verification and every sealed criterion");
79
141
  }
80
- conflicts = obj.conflicts.map((c) => text(c, 1024, "conflict path"));
142
+ if (record.reviewId && record.reviewId !== review.id)
143
+ fail(409, "Accepted review invalidated");
81
144
  }
82
- let diff;
83
- if (obj.diff !== undefined) {
84
- diff = text(obj.diff, 64 * 1024, "diff");
85
- }
86
- return {
87
- status: obj.status,
88
- expectedTargetSha,
89
- conflicts,
90
- diff,
91
- };
145
+ return { delivery, review, bot: targetBot(state, record) };
92
146
  }
93
- /** 白名单验证并投影设备端验证命令返回的结果 */
94
- function validateDeviceVerifyResult(raw) {
95
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
96
- fail(502, "Invalid device response");
97
- }
98
- const obj = raw;
99
- if (obj.status !== "verified" && obj.status !== "failed") {
100
- fail(502, "Invalid verification status from device");
147
+ function cancellationDevice(state, record, actor) {
148
+ if (!actor.bot && record.targetDeviceId) {
149
+ if (!state.devices.some((d) => d.id === record.targetDeviceId && d.accountId === actor.accountId))
150
+ fail(409, "Cleanup device is no longer owned by this account");
151
+ return record.targetDeviceId;
101
152
  }
102
- if (!Array.isArray(obj.validationCommands)) {
103
- fail(502, "Invalid validationCommands from device");
104
- }
105
- const validationCommands = obj.validationCommands.map((v) => {
106
- if (!v || typeof v !== "object")
107
- fail(502, "Invalid validation command item");
108
- const item = v;
109
- const status = item.status === "passed" || item.status === "failed" ? item.status : "failed";
110
- return {
111
- command: text(item.command, 1024, "command"),
112
- status,
113
- exitCode: typeof item.exitCode === "number" ? item.exitCode : undefined,
114
- output: typeof item.output === "string" ? item.output.slice(0, 16 * 1024) : undefined,
115
- };
153
+ return targetBot(state, record, true).deviceId;
154
+ }
155
+ function stableSubject(record) {
156
+ return canonicalizeJson({
157
+ id: record.id,
158
+ accountId: record.accountId,
159
+ roomId: record.roomId,
160
+ conversationId: record.conversationId,
161
+ deliveryId: record.deliveryId,
162
+ commit: record.commit ?? null,
163
+ artifactRef: record.artifactRef ?? null,
164
+ reviewId: record.reviewId ?? null,
165
+ targetBotId: record.targetBotId,
166
+ targetBotRevision: record.targetBotRevision,
167
+ targetDeviceId: record.targetDeviceId ?? null,
168
+ targetBranch: record.targetBranch,
169
+ expectedTargetSha: record.expectedTargetSha,
170
+ materializedCommit: record.materializedCommit ?? null,
171
+ preparedTree: record.preparedTree ?? null,
172
+ verificationPlan: record.verificationPlan ?? null,
173
+ verification: record.verification ?? null,
174
+ verificationMayBeRunning: record.verificationMayBeRunning ?? false,
116
175
  });
117
- return {
118
- status: obj.status,
119
- validationCommands,
120
- };
121
176
  }
122
- /** 白名单验证并投影设备端确认写入返回的结果 */
123
- function validateDeviceConfirmResult(raw) {
124
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
125
- fail(502, "Invalid device response");
126
- }
127
- const obj = raw;
128
- if (obj.status !== "applied") {
129
- fail(502, "Device failed to apply integration");
130
- }
131
- return {
132
- status: "applied",
133
- newCommitSha: sha(obj.newCommitSha),
134
- cleanupPending: !!obj.cleanupPending,
135
- };
177
+ function recheck(state, before, roomId, conversationId, actor, taskId, status, accepted = false) {
178
+ const record = recordFor(state, roomId, conversationId, before.id, actor);
179
+ if (record.status !== status ||
180
+ record.currentOpId !== before.currentOpId ||
181
+ stableSubject(record) !== stableSubject(before))
182
+ fail(409, "Integration operation generation or subject changed");
183
+ if (actorTask(state, roomId, actor) !== taskId)
184
+ fail(403, "Integration actor task changed");
185
+ authority(state, record, accepted);
186
+ return record;
136
187
  }
137
- /**
138
- * Hub 端准备集成:
139
- * 1. 同步 reservation:校验授权与 accepted delivery,添加 preparing 状态记录并持久化
140
- * 2. 事务外异步副作用:强制通过设备端 RPC 执行隔离工作树预合并(严禁本地 fallback!)
141
- * 3. 同步 commit:再次全量校验 Bot 版本、成员归属与 delivery 状态,持久化白名单投影结果
142
- */
143
- export async function hubPrepareIntegration(store, roomId, conversationId, actor, input, driver) {
144
- if (!driver?.callDeviceCommand) {
188
+ async function failed(store, before, status, error) {
189
+ await store.transact((draft) => {
190
+ const record = draft.integrations.find((i) => i.id === before.id);
191
+ if (record?.publishReceipt)
192
+ return;
193
+ if (record?.publishIntent && before.publishIntent?.digest === record.publishIntent.digest) {
194
+ // An RPC/Hub failure says nothing about whether the reserved CAS happened.
195
+ record.error = `Publication outcome unknown: ${sanitizePublicError(error)}`.slice(0, 300);
196
+ record.updatedAt = Date.now();
197
+ return;
198
+ }
199
+ if (record?.status === status && record.currentOpId === before.currentOpId) {
200
+ record.status = "failed";
201
+ record.error = sanitizePublicError(error);
202
+ if (error?.stopUnconfirmed) {
203
+ record.cleanupPending = true;
204
+ record.verificationMayBeRunning = true;
205
+ }
206
+ if (status === "applying") {
207
+ record.cleanupPending = true;
208
+ record.error = `Apply failed; check target outcome: ${record.error}`.slice(0, 300);
209
+ }
210
+ record.updatedAt = Date.now();
211
+ }
212
+ });
213
+ throw wrapRpcError(error);
214
+ }
215
+ function driverRequired(driver) {
216
+ if (!driver?.callDeviceCommand)
145
217
  fail(409, "Target device offline or command unavailable; Hub local execution is forbidden");
146
- }
218
+ return driver;
219
+ }
220
+ export async function hubPrepareIntegration(store, roomId, conversationId, actor, input, driver) {
221
+ const rpc = driverRequired(driver);
147
222
  const deliveryId = text(input.deliveryId, 128, "deliveryId");
148
223
  const targetBotId = text(input.targetBotId, 128, "targetBotId");
149
- const targetBranch = safeBranch(input.targetBranch || "main");
150
- const integrationId = randomUUID();
151
- // Step 1: 同步 reservation
152
- const { delivery, targetBot } = await store.transact((draft) => {
153
- const room = draft.rooms.find((r) => r.id === roomId && r.accountId === actor.accountId);
154
- if (!room)
155
- fail(404, "Room missing");
156
- if (!room.botIds.includes(targetBotId))
157
- fail(403, "Target Bot is not a room member");
224
+ const targetBranch = safeBranch(input.targetBranch ?? "main");
225
+ const { before, taskId, artifact } = await store.transact((draft) => {
226
+ const taskId = actorTask(draft, roomId, actor);
227
+ assertNoApplyingIntegration(draft, actor.accountId, roomId, conversationId);
228
+ const delivery = latestDelivery(draft, roomId, conversationId, actor.accountId, deliveryId);
229
+ const review = delivery.artifactRef
230
+ ? undefined
231
+ : getAcceptedDeliveryForIntegration(draft, conversationId, deliveryId).review;
158
232
  const bot = draft.bots.find((b) => b.id === targetBotId && b.accountId === actor.accountId && b.enabled);
159
233
  if (!bot)
160
234
  fail(404, "Target Bot not found or disabled");
161
- const { delivery: del, review } = getAcceptedDeliveryForIntegration(draft, conversationId, deliveryId);
162
- const initialRecord = {
163
- id: integrationId,
235
+ const record = {
236
+ id: randomUUID(),
164
237
  accountId: actor.accountId,
165
238
  roomId,
166
239
  conversationId,
167
240
  deliveryId,
168
- commit: del.commit,
169
- reviewId: review.id,
241
+ commit: delivery.commit,
242
+ reviewId: review?.id,
243
+ artifactRef: delivery.artifactRef,
170
244
  targetBotId,
171
245
  targetBotRevision: bot.revision,
246
+ targetDeviceId: bot.deviceId,
172
247
  targetBranch,
173
248
  expectedTargetSha: "",
174
249
  status: "preparing",
250
+ currentOpId: randomUUID(),
175
251
  validationCommands: [],
176
252
  createdAt: Date.now(),
177
253
  updatedAt: Date.now(),
178
254
  };
179
- draft.integrations.push(initialRecord);
180
- return { delivery: del, targetBot: { ...bot } };
255
+ targetBot(draft, record);
256
+ draft.integrations.push(record);
257
+ return { before: structuredClone(record), taskId, artifact: assertDeliveryAuthority(draft, delivery)?.artifact };
181
258
  });
182
- // Step 2: 事务外异步调用设备 RPC
183
259
  try {
184
- const payload = {
185
- integrationId,
260
+ const raw = await rpc.callDeviceCommand(before.targetDeviceId, "integration_prepare", {
261
+ integrationId: before.id,
262
+ accountId: before.accountId,
263
+ conversationId,
264
+ targetDeviceId: before.targetDeviceId,
186
265
  roomId,
187
266
  targetBotId,
188
- targetBotRevision: targetBot.revision,
267
+ targetBotRevision: before.targetBotRevision,
189
268
  targetBranch,
190
- commit: delivery.commit,
191
- };
192
- const rawResult = await driver.callDeviceCommand(targetBot.deviceId, "integration_prepare", payload);
193
- const deviceResult = validateDevicePrepareResult(rawResult);
194
- // Step 3: 同步 commit,并严密重新核验版本、归属与当前 delivery 状态
269
+ commit: before.commit,
270
+ artifactRef: before.artifactRef,
271
+ artifact,
272
+ });
273
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
274
+ fail(502, "Invalid device prepare response");
275
+ const obj = raw;
276
+ if (obj.status !== "prepared" && obj.status !== "conflict")
277
+ fail(502, "Invalid integration status from device");
278
+ if (obj.objectFormat !== "sha1" && obj.objectFormat !== "sha256")
279
+ fail(502, "Missing repository object format");
280
+ if (before.artifactRef && obj.objectFormat !== "sha1")
281
+ fail(409, "SHA-256 artifact baselines are unsupported");
282
+ const repositoryId = text(obj.repositoryId, 1024, "repositoryId");
283
+ if (before.artifactRef && repositoryId !== before.artifactRef.repositoryId)
284
+ fail(502, "Repository identity mismatch");
285
+ const expectedTargetSha = sha(obj.expectedTargetSha);
286
+ if (expectedTargetSha.length !== (obj.objectFormat === "sha1" ? 40 : 64))
287
+ fail(502, "Object format mismatch");
288
+ if (before.artifactRef && expectedTargetSha !== before.artifactRef.baselineCommit)
289
+ fail(409, "Artifact target must equal sealed baseline commit");
290
+ const materializedCommit = obj.status === "prepared" ? sha(obj.materializedCommit) : undefined;
291
+ const preparedTree = obj.status === "prepared" ? sha(obj.preparedTree) : undefined;
292
+ if ([materializedCommit, preparedTree].some((value) => value && value.length !== expectedTargetSha.length))
293
+ fail(502, "Prepared object format mismatch");
294
+ if (before.artifactRef && obj.status === "prepared" && preparedTree !== before.artifactRef.outputTree)
295
+ fail(502, "Prepared artifact tree mismatch");
296
+ if (obj.conflicts !== undefined && (!Array.isArray(obj.conflicts) || obj.conflicts.length > 256))
297
+ fail(502, "Invalid conflicts");
298
+ const conflicts = obj.conflicts?.map((c) => text(c, 1024, "conflict"));
299
+ const diff = obj.diff === undefined || obj.diff === "" ? undefined : text(obj.diff, 64 * 1024, "diff");
195
300
  return await store.transact((draft) => {
196
- const room = draft.rooms.find((r) => r.id === roomId && r.accountId === actor.accountId);
197
- if (!room || !room.botIds.includes(targetBotId))
198
- fail(403, "Target Bot membership changed during integration");
199
- const currentBot = draft.bots.find((b) => b.id === targetBotId && b.accountId === actor.accountId && b.enabled);
200
- if (!currentBot || currentBot.revision !== targetBot.revision || currentBot.deviceId !== targetBot.deviceId) {
201
- fail(409, "Target Bot revision or hosting device changed during integration");
202
- }
203
- const { delivery: currentDelivery, review: currentReview } = getAcceptedDeliveryForIntegration(draft, conversationId, deliveryId);
204
- if (currentDelivery.commit !== delivery.commit || currentReview.verdict !== "accepted") {
205
- fail(409, "Delivery or review state changed during preparation");
206
- }
207
- const record = draft.integrations.find((it) => it.id === integrationId);
208
- if (!record)
209
- fail(404, "Integration record missing");
210
- if (record.status !== "preparing") {
211
- fail(409, `Integration generation collision; expected 'preparing' but found '${record.status}'`);
212
- }
213
- record.status = deviceResult.status;
214
- record.expectedTargetSha = deviceResult.expectedTargetSha;
215
- record.conflicts = deviceResult.conflicts;
216
- record.diff = deviceResult.diff;
217
- record.updatedAt = Date.now();
218
- return { ...record };
301
+ const record = recheck(draft, before, roomId, conversationId, actor, taskId, "preparing");
302
+ Object.assign(record, {
303
+ status: obj.status,
304
+ expectedTargetSha,
305
+ materializedCommit,
306
+ preparedTree,
307
+ objectFormat: obj.objectFormat,
308
+ repositoryId,
309
+ conflicts,
310
+ diff,
311
+ updatedAt: Date.now(),
312
+ });
313
+ return structuredClone(record);
219
314
  });
220
315
  }
221
316
  catch (error) {
222
- const errMsg = sanitizePublicError(error);
223
- await store.transact((draft) => {
224
- const record = draft.integrations.find((it) => it.id === integrationId);
225
- if (record && record.status === "preparing") {
226
- record.status = "failed";
227
- record.error = errMsg;
228
- record.updatedAt = Date.now();
229
- }
230
- });
231
- throw wrapRpcError(error);
317
+ return failed(store, before, "preparing", error);
232
318
  }
233
319
  }
234
- /**
235
- * Hub 端运行显式验证命令
236
- */
237
320
  export async function hubVerifyIntegration(store, roomId, conversationId, integrationId, actor, input, driver) {
238
- if (!driver?.callDeviceCommand) {
239
- fail(409, "Target device offline or command unavailable");
240
- }
241
- const rawCommands = input.commands;
242
- if (!Array.isArray(rawCommands) || rawCommands.length === 0) {
243
- fail(400, "Explicit commands array required");
244
- }
245
- const commands = rawCommands.map((c) => text(c, 1024, "command"));
246
- const opId = randomUUID();
247
- // Step 1: 同步 reservation
248
- const { targetBot } = await store.transact((draft) => {
249
- const record = draft.integrations.find((it) => it.id === integrationId &&
250
- it.roomId === roomId &&
251
- it.conversationId === conversationId &&
252
- it.accountId === actor.accountId);
253
- if (!record)
254
- fail(404, "Integration task not found");
255
- if (record.status !== "prepared" && record.status !== "verified") {
321
+ const rpc = driverRequired(driver);
322
+ const { before, taskId } = await store.transact((draft) => {
323
+ const taskId = actorTask(draft, roomId, actor);
324
+ const record = recordFor(draft, roomId, conversationId, integrationId, actor);
325
+ if (record.publishIntent || isLegacyPublicationUnknown(record))
326
+ fail(409, "Publication outcome is unresolved; manual recovery or read-only reconcile required");
327
+ if (record.verification)
328
+ fail(409, "Successful verification is immutable; prepare a new integration to verify again");
329
+ if (record.status !== "prepared" && record.status !== "failed")
256
330
  fail(409, `Cannot verify integration in status '${record.status}'`);
331
+ authority(draft, record);
332
+ if (!record.preparedTree || !record.materializedCommit)
333
+ fail(409, "Missing prepared tree and materialized commit proof");
334
+ if (actor.bot) {
335
+ if (!record.verificationPlan || record.verificationPlan.authorizedByAccountId !== actor.accountId)
336
+ fail(403, "Only the account owner may authorize verification commands");
337
+ if (input.commands !== undefined &&
338
+ canonicalizeJson(input.commands) !== canonicalizeJson(record.verificationPlan.commands))
339
+ fail(403, "Bot cannot change owner-authorized verification commands");
257
340
  }
258
- // 重新校验交付与 accepted 审查绑定
259
- const { delivery, review } = getAcceptedDeliveryForIntegration(draft, conversationId, record.deliveryId);
260
- if (delivery.commit !== record.commit || review.id !== record.reviewId || review.verdict !== "accepted") {
261
- fail(409, "Delivery or accepted review invalidated; verification rejected");
262
- }
263
- const bot = draft.bots.find((b) => b.id === record.targetBotId && b.accountId === actor.accountId && b.enabled);
264
- if (!bot || bot.revision !== record.targetBotRevision) {
265
- fail(409, "Target Bot revision mismatch or disabled");
341
+ else if (record.verificationPlan) {
342
+ if (input.commands !== undefined &&
343
+ canonicalizeJson(input.commands) !== canonicalizeJson(record.verificationPlan.commands))
344
+ fail(409, "Verification plan is frozen; prepare a new integration to change commands");
266
345
  }
346
+ else
347
+ record.verificationPlan = freezeVerificationPlan(input.commands, actor.accountId);
267
348
  record.status = "verifying";
268
- record.currentOpId = opId;
349
+ record.verificationMayBeRunning = true;
350
+ record.currentOpId = randomUUID();
351
+ record.error = undefined;
269
352
  record.updatedAt = Date.now();
270
- return { targetBot: { ...bot } };
353
+ return { before: structuredClone(record), taskId };
271
354
  });
272
- // Step 2: 事务外调用设备 RPC
273
355
  try {
274
- const payload = {
356
+ const raw = await rpc.callDeviceCommand(before.targetDeviceId, "integration_verify", {
275
357
  integrationId,
276
358
  roomId,
277
- targetBotId: targetBot.id,
278
- targetBotRevision: targetBot.revision,
279
- commands,
280
- };
281
- const rawResult = await driver.callDeviceCommand(targetBot.deviceId, "integration_verify", payload);
282
- const deviceResult = validateDeviceVerifyResult(rawResult);
283
- // Step 3: 同步 commit
359
+ targetBotId: before.targetBotId,
360
+ targetBotRevision: before.targetBotRevision,
361
+ verificationPlan: before.verificationPlan,
362
+ artifactRef: before.artifactRef,
363
+ materializedCommit: before.materializedCommit,
364
+ preparedTree: before.preparedTree,
365
+ expectedTargetSha: before.expectedTargetSha,
366
+ });
367
+ const { status, facts } = validateVerificationFacts(raw, before);
284
368
  return await store.transact((draft) => {
285
- const record = draft.integrations.find((it) => it.id === integrationId);
286
- if (!record)
287
- fail(404, "Integration record missing");
288
- if (record.status !== "verifying" || record.currentOpId !== opId) {
289
- fail(409, "Verification generation mismatch");
290
- }
291
- record.status = deviceResult.status;
292
- record.validationCommands = deviceResult.validationCommands;
369
+ const record = recheck(draft, before, roomId, conversationId, actor, taskId, "verifying");
370
+ record.status = status;
371
+ record.verificationMayBeRunning = false;
372
+ record.validationCommands = facts.results.map((r) => ({
373
+ command: r.command,
374
+ status: r.status,
375
+ exitCode: r.exitCode,
376
+ output: r.outputPreview,
377
+ }));
378
+ if (status === "verified")
379
+ record.verification = { ...facts, digest: computeVerificationDigest(record, facts), verifiedAt: Date.now() };
293
380
  record.updatedAt = Date.now();
294
- return { ...record };
381
+ return structuredClone(record);
295
382
  });
296
383
  }
297
384
  catch (error) {
298
- const errMsg = sanitizePublicError(error);
299
- await store.transact((draft) => {
300
- const record = draft.integrations.find((it) => it.id === integrationId);
301
- if (record && record.status === "verifying" && record.currentOpId === opId) {
302
- record.status = "failed";
303
- record.error = errMsg;
304
- record.updatedAt = Date.now();
305
- }
306
- });
307
- throw wrapRpcError(error);
385
+ return failed(store, before, "verifying", error);
308
386
  }
309
387
  }
310
- /**
311
- * Hub 端确认写入目标分支
312
- */
313
388
  export async function hubConfirmIntegration(store, roomId, conversationId, integrationId, actor, input, driver) {
314
- if (!driver?.callDeviceCommand) {
315
- fail(409, "Target device offline or command unavailable");
316
- }
317
- const opId = randomUUID();
318
- // Step 1: 同步 reservation
319
- const { integration, targetBot, expectedTargetSha } = await store.transact((draft) => {
320
- const record = draft.integrations.find((it) => it.id === integrationId &&
321
- it.roomId === roomId &&
322
- it.conversationId === conversationId &&
323
- it.accountId === actor.accountId);
324
- if (!record)
325
- fail(404, "Integration task not found");
326
- if (record.status !== "prepared" && record.status !== "verified" && record.status !== "failed") {
327
- fail(409, `Integration in status '${record.status}' cannot be applied`);
328
- }
329
- const { delivery, review } = getAcceptedDeliveryForIntegration(draft, conversationId, record.deliveryId);
330
- if (delivery.commit !== record.commit) {
331
- fail(409, "Delivery commit changed; integration rejected");
332
- }
333
- if (review.id !== record.reviewId || review.verdict !== "accepted") {
334
- fail(409, "Delivery accepted review invalidated; integration rejected");
335
- }
336
- const expSha = text(input.expectedTargetSha || record.expectedTargetSha, 64, "expectedTargetSha");
337
- if (expSha !== record.expectedTargetSha) {
389
+ // The synchronous WAL callback seals data only, before the first possible RPC.
390
+ const { before, dispatch } = await store.transact((draft) => {
391
+ const record = recordFor(draft, roomId, conversationId, integrationId, actor);
392
+ if (actor.originalBot)
393
+ fail(403, "Historical actor is read-only");
394
+ if (record.publishIntent || record.status === "applied")
395
+ return { before: structuredClone(record), dispatch: false };
396
+ driverRequired(driver);
397
+ const taskId = actorTask(draft, roomId, actor);
398
+ if (record.status !== "verified" || !hasVerifiedIntegration(record))
399
+ fail(409, "Apply requires successful real verification proof");
400
+ const { delivery, review } = authority(draft, record, true);
401
+ const expected = text(input.expectedTargetSha ?? record.expectedTargetSha, 64, "expectedTargetSha");
402
+ if (expected !== record.expectedTargetSha)
338
403
  fail(409, "Expected target SHA mismatch");
404
+ if (!record.repositoryId || !record.objectFormat)
405
+ fail(409, "Prepare must capture repository identity and object format");
406
+ const createdAt = Date.now();
407
+ record.publishIntent = sealPublishIntent({
408
+ version: 1,
409
+ id: randomUUID(),
410
+ accountId: record.accountId,
411
+ roomId,
412
+ conversationId,
413
+ integrationId,
414
+ targetDeviceId: record.targetDeviceId,
415
+ targetBotId: record.targetBotId,
416
+ targetBotRevision: record.targetBotRevision,
417
+ actor: {
418
+ accountId: actor.accountId,
419
+ ...(actor.bot
420
+ ? { botId: actor.bot.id, botRevision: actor.bot.revision, botDeviceId: actor.bot.deviceId, taskId }
421
+ : {}),
422
+ },
423
+ repositoryId: record.repositoryId,
424
+ objectFormat: record.objectFormat,
425
+ targetRef: record.targetBranch.startsWith("refs/heads/")
426
+ ? record.targetBranch
427
+ : `refs/heads/${record.targetBranch}`,
428
+ expectedOld: record.expectedTargetSha,
429
+ preparedTree: record.preparedTree,
430
+ materializedCommit: record.materializedCommit,
431
+ createdAt,
432
+ delivery: {
433
+ id: delivery.id,
434
+ ...(delivery.commit ? { commit: delivery.commit } : {}),
435
+ ...(delivery.artifactRef ? { artifactRef: structuredClone(delivery.artifactRef) } : {}),
436
+ },
437
+ review: structuredClone(review),
438
+ verificationPlan: structuredClone(record.verificationPlan),
439
+ verification: structuredClone(record.verification),
440
+ });
441
+ record.reviewId = review.id;
442
+ record.status = "applying";
443
+ record.currentOpId = randomUUID();
444
+ record.updatedAt = createdAt;
445
+ return { before: structuredClone(record), dispatch: true };
446
+ });
447
+ if (!dispatch)
448
+ return before;
449
+ return dispatchPublication(store, before, driverRequired(driver), "first");
450
+ }
451
+ export async function hubCancelIntegration(store, roomId, conversationId, integrationId, actor, driver) {
452
+ const existing = recordFor(store.snapshot(), roomId, conversationId, integrationId, actor);
453
+ if (existing.publishIntent) {
454
+ if (actor.originalBot)
455
+ fail(403, "Historical actor is read-only");
456
+ if (actor.bot)
457
+ actorTask(store.snapshot(), roomId, actor);
458
+ if (existing.publishReceipt && !hasOpenPublication(existing))
459
+ return existing;
460
+ const rpc = driverRequired(driver);
461
+ const before = await store.transact((draft) => {
462
+ const record = recordFor(draft, roomId, conversationId, integrationId, actor);
463
+ if (record.publishIntent?.digest !== existing.publishIntent.digest)
464
+ fail(409, "Publication intent changed");
465
+ if (!record.publishReceipt && hasOpenPublication(record))
466
+ record.status = "cancelling";
467
+ if (record.publishObservation)
468
+ record.publishObservation.retryable = false;
469
+ return structuredClone(record);
470
+ });
471
+ if (!hasOpenPublication(before))
472
+ return before;
473
+ try {
474
+ const raw = await rpc.callDeviceCommand(before.publishIntent.targetDeviceId, "integration_cancel", {
475
+ ...publicationPayload(before),
476
+ ownerCleanup: !actor.bot,
477
+ });
478
+ return await mergePublicationResult(store, before, raw);
339
479
  }
340
- const bot = draft.bots.find((b) => b.id === record.targetBotId && b.accountId === actor.accountId && b.enabled);
341
- if (!bot || bot.revision !== record.targetBotRevision) {
342
- fail(409, "Target Bot revision mismatch or disabled");
480
+ catch (error) {
481
+ return failed(store, before, "cancelling", error);
343
482
  }
344
- record.status = "applying";
345
- record.currentOpId = opId;
346
- record.updatedAt = Date.now();
347
- return { integration: { ...record }, targetBot: { ...bot }, expectedTargetSha: expSha };
483
+ }
484
+ const { before, taskId, priorStatus } = await store.transact((draft) => {
485
+ const record = recordFor(draft, roomId, conversationId, integrationId, actor);
486
+ if (record.status === "applied")
487
+ fail(409, "Already applied integration cannot be cancelled");
488
+ if (isLegacyPublicationUnknown(record))
489
+ fail(409, "Legacy publication outcome unknown; manual investigation required");
490
+ const taskId = actor.bot ? actorTask(draft, roomId, actor) : undefined;
491
+ driverRequired(driver);
492
+ const priorStatus = record.status;
493
+ if (["verifying", "failed", "verified"].includes(record.status) && !hasVerifiedIntegration(record))
494
+ record.verificationMayBeRunning = true;
495
+ const deviceId = cancellationDevice(draft, record, actor);
496
+ // Legacy jobs may be cleaned on their still-bound Bot/device without inventing verification proof.
497
+ record.targetDeviceId ??= deviceId;
498
+ if (record.status !== "cancelled") {
499
+ record.status = "cancelling";
500
+ record.currentOpId = randomUUID();
501
+ record.updatedAt = Date.now();
502
+ }
503
+ return { before: structuredClone(record), taskId, priorStatus };
348
504
  });
349
- // Step 2: 事务外调用设备 RPC
505
+ if (before.status === "cancelled")
506
+ return before;
350
507
  try {
351
- const payload = {
508
+ const raw = await driverRequired(driver).callDeviceCommand(before.targetDeviceId, "integration_cancel", {
352
509
  integrationId,
353
510
  roomId,
354
- targetBotId: targetBot.id,
355
- targetBotRevision: targetBot.revision,
356
- deliveryId: integration.deliveryId,
357
- commit: integration.commit,
358
- expectedTargetSha,
359
- };
360
- const rawResult = await driver.callDeviceCommand(targetBot.deviceId, "integration_confirm", payload);
361
- const deviceResult = validateDeviceConfirmResult(rawResult);
362
- // Step 3: 同步 commit
511
+ targetBotId: before.targetBotId,
512
+ targetBotRevision: before.targetBotRevision,
513
+ priorStatus,
514
+ verificationMayBeRunning: before.verificationMayBeRunning === true,
515
+ ownerCleanup: !actor.bot,
516
+ });
517
+ if (!raw || typeof raw !== "object" || raw.status !== "cancelled")
518
+ fail(502, "Device has not confirmed integration stop and cleanup");
363
519
  return await store.transact((draft) => {
364
- const record = draft.integrations.find((it) => it.id === integrationId);
365
- if (!record)
366
- fail(404, "Integration record missing");
367
- if (record.status !== "applying" || record.currentOpId !== opId) {
368
- fail(409, "Integration application generation mismatch");
369
- }
370
- record.status = "applied";
371
- record.newCommitSha = deviceResult.newCommitSha;
372
- if (deviceResult.cleanupPending) {
373
- record.cleanupPending = true;
374
- }
520
+ const record = recordFor(draft, roomId, conversationId, integrationId, actor);
521
+ if (record.status !== "cancelling" ||
522
+ record.currentOpId !== before.currentOpId ||
523
+ stableSubject(record) !== stableSubject(before))
524
+ fail(409, "Cancellation generation changed");
525
+ if (actor.bot && actorTask(draft, roomId, actor) !== taskId)
526
+ fail(403, "Integration actor task changed");
527
+ if (cancellationDevice(draft, record, actor) !== before.targetDeviceId)
528
+ fail(409, "Cleanup device changed");
529
+ record.status = "cancelled";
530
+ record.verificationMayBeRunning = false;
531
+ record.cleanupPending = false;
375
532
  record.updatedAt = Date.now();
376
- return { ...record };
533
+ return structuredClone(record);
377
534
  });
378
535
  }
379
536
  catch (error) {
380
- const errMsg = sanitizePublicError(error);
381
- await store.transact((draft) => {
382
- const record = draft.integrations.find((it) => it.id === integrationId);
383
- if (record && record.status === "applying" && record.currentOpId === opId) {
384
- record.status = "failed";
385
- record.error = errMsg;
386
- record.updatedAt = Date.now();
387
- }
388
- });
389
- throw wrapRpcError(error);
537
+ return failed(store, before, "cancelling", error);
390
538
  }
391
539
  }
392
- /**
393
- * Hub 端取消集成
394
- */
395
- export async function hubCancelIntegration(store, roomId, conversationId, integrationId, actor, driver) {
396
- // Step 1: 同步 reservation
397
- const { targetBot } = await store.transact((draft) => {
398
- const record = draft.integrations.find((it) => it.id === integrationId &&
399
- it.roomId === roomId &&
400
- it.conversationId === conversationId &&
401
- it.accountId === actor.accountId);
402
- if (!record)
403
- fail(404, "Integration task not found");
404
- if (record.status === "applied") {
405
- fail(409, "Already applied integration cannot be cancelled");
540
+ function publicationPayload(record) {
541
+ const intent = validatePublishIntent(record.publishIntent);
542
+ return {
543
+ integrationId: intent.integrationId,
544
+ accountId: intent.accountId,
545
+ roomId: intent.roomId,
546
+ conversationId: intent.conversationId,
547
+ targetBotId: intent.targetBotId,
548
+ targetBotRevision: intent.targetBotRevision,
549
+ publishIntent: intent,
550
+ };
551
+ }
552
+ async function mergePublicationResult(store, before, raw) {
553
+ const intent = validatePublishIntent(before.publishIntent);
554
+ const result = validatePublicationResult(raw, intent);
555
+ return store.transact((draft) => {
556
+ const record = draft.integrations.find((i) => i.id === intent.integrationId &&
557
+ i.accountId === intent.accountId &&
558
+ i.roomId === intent.roomId &&
559
+ i.conversationId === intent.conversationId);
560
+ if (!record || record.publishIntent?.digest !== intent.digest || record.publishIntent.id !== intent.id)
561
+ fail(409, "Publication intent changed");
562
+ validatePublishIntent(record.publishIntent);
563
+ // Match only the sealed operation. Current membership/review/task may have been revoked after CAS.
564
+ if (result.publishReceipt && !record.publishReceipt)
565
+ record.publishReceipt = result.publishReceipt;
566
+ if (result.publishObservation &&
567
+ (!record.publishObservation || result.publishObservation.observedAt >= record.publishObservation.observedAt))
568
+ record.publishObservation = result.publishObservation;
569
+ if (result.publishStop) {
570
+ const previous = record.publishStop;
571
+ if (!previous)
572
+ record.publishStop = result.publishStop;
573
+ else if (!previous.stopConfirmed && result.publishStop.stopConfirmed)
574
+ record.publishStop = {
575
+ ...result.publishStop,
576
+ closed: previous.closed || result.publishStop.closed,
577
+ fencedAt: Math.min(previous.fencedAt, result.publishStop.fencedAt),
578
+ };
579
+ else if (!previous.closed && result.publishStop.closed)
580
+ record.publishStop = {
581
+ ...previous,
582
+ closed: true,
583
+ fencedAt: Math.min(previous.fencedAt, result.publishStop.fencedAt),
584
+ };
406
585
  }
407
- if (record.status === "applying") {
408
- fail(409, "Integration is currently being applied and cannot be cancelled");
586
+ if (record.publishReceipt) {
587
+ record.status = "applied";
588
+ record.newCommitSha = intent.candidateSha;
589
+ if (record.publishStop)
590
+ record.publishStop.pastEffect = "applied";
591
+ if (record.publishObservation)
592
+ record.publishObservation.retryable = false;
593
+ record.error = undefined;
594
+ }
595
+ else if (record.publishStop?.closed && record.publishStop.stopConfirmed) {
596
+ record.status = record.publishStop.pastEffect === "not_applied" ? "cancelled" : "cancelling";
597
+ if (record.publishObservation)
598
+ record.publishObservation.retryable = false;
599
+ record.error =
600
+ record.publishStop.pastEffect === "unknown"
601
+ ? "Publication closed for future writes; historical outcome remains unknown"
602
+ : undefined;
409
603
  }
410
- if (record.status === "cancelled") {
411
- return { targetBot: undefined };
604
+ else {
605
+ record.status = record.status === "cancelling" ? "cancelling" : "applying";
606
+ if (record.status === "cancelling" && record.publishObservation)
607
+ record.publishObservation.retryable = false;
608
+ record.error = result.publishObservation?.error;
412
609
  }
413
- record.status = "cancelling";
610
+ if (result.cleanupPending !== undefined)
611
+ record.cleanupPending = result.cleanupPending;
414
612
  record.updatedAt = Date.now();
415
- const bot = draft.bots.find((b) => b.id === record.targetBotId && b.accountId === actor.accountId);
416
- return { targetBot: bot ? { ...bot } : undefined };
613
+ return structuredClone(record);
417
614
  });
418
- // Step 2: 事务外异步调用设备 RPC
419
- let rpcError;
615
+ }
616
+ async function dispatchPublication(store, before, driver, mode) {
420
617
  try {
421
- if (targetBot && driver?.callDeviceCommand) {
422
- const payload = { integrationId, roomId, targetBotId: targetBot.id };
423
- await driver.callDeviceCommand(targetBot.deviceId, "integration_cancel", payload);
424
- }
618
+ const raw = await driver.callDeviceCommand(before.publishIntent.targetDeviceId, "integration_confirm", {
619
+ ...publicationPayload(before),
620
+ mode,
621
+ deliveryId: before.deliveryId,
622
+ commit: before.commit,
623
+ expectedTargetSha: before.expectedTargetSha,
624
+ artifactRef: before.artifactRef,
625
+ materializedCommit: before.materializedCommit,
626
+ verificationDigest: before.verification.digest,
627
+ });
628
+ return await mergePublicationResult(store, before, raw);
425
629
  }
426
630
  catch (error) {
427
- rpcError = error;
631
+ return failed(store, before, "applying", error);
428
632
  }
429
- // Step 3: 严格终态 CAS,防止覆盖并发已 applied 终态
430
- const result = await store.transact((draft) => {
431
- const rec = draft.integrations.find((it) => it.id === integrationId);
432
- if (!rec)
433
- fail(404, "Integration record missing");
434
- if (rec.status === "applied") {
435
- return { ...rec };
436
- }
437
- rec.status = "cancelled";
438
- if (rpcError) {
439
- rec.error = sanitizePublicError(rpcError);
440
- }
441
- rec.updatedAt = Date.now();
442
- return { ...rec };
633
+ }
634
+ function historicalActor(record, actor) {
635
+ const bot = actor.originalBot ?? actor.bot;
636
+ if (!bot)
637
+ return;
638
+ const intent = record.publishIntent;
639
+ if (!intent ||
640
+ bot.accountId !== intent.accountId ||
641
+ !((bot.id === intent.targetBotId && bot.deviceId === intent.targetDeviceId) ||
642
+ (bot.id === intent.actor.botId && bot.deviceId === intent.actor.botDeviceId)))
643
+ fail(403, "Historical publication actor scope mismatch");
644
+ }
645
+ export async function hubReconcileIntegration(store, roomId, conversationId, actor, id, driver) {
646
+ const before = recordFor(store.snapshot(), roomId, conversationId, id, actor);
647
+ historicalActor(before, actor);
648
+ // Legacy records carry no journal identity. Never synthesize a receipt or retry them.
649
+ if (!before.publishIntent)
650
+ return structuredClone(before);
651
+ try {
652
+ const raw = await driverRequired(driver).callDeviceCommand(before.publishIntent.targetDeviceId, "integration_publication_status", publicationPayload(before));
653
+ return await mergePublicationResult(store, before, raw);
654
+ }
655
+ catch (error) {
656
+ return failed(store, before, before.status, error);
657
+ }
658
+ }
659
+ export async function hubResumeIntegration(store, roomId, conversationId, actor, id, input, driver) {
660
+ if (actor.bot || actor.originalBot)
661
+ fail(403, "Only the human account owner may resume publication");
662
+ const before = await store.transact((draft) => {
663
+ actorTask(draft, roomId, actor);
664
+ const record = recordFor(draft, roomId, conversationId, id, actor);
665
+ const intent = validatePublishIntent(record.publishIntent);
666
+ if (!input ||
667
+ input.intentId !== intent.id ||
668
+ input.intentDigest !== intent.digest ||
669
+ input.candidateSha !== intent.candidateSha)
670
+ fail(409, "Resume must bind exact publication intent");
671
+ if (record.publishReceipt)
672
+ return structuredClone(record);
673
+ if (record.publishStop?.closed)
674
+ fail(409, "Publication is closed for future writes");
675
+ if (record.status === "cancelling")
676
+ fail(409, "Publication cancellation is in progress");
677
+ if (!record.publishObservation?.retryable ||
678
+ !["prepared", "cas_rejected"].includes(record.publishObservation.phase))
679
+ fail(409, "Publication is not proven safe to resume; reconcile first");
680
+ validatePublicationResult({ status: "pending", publishObservation: record.publishObservation }, intent);
681
+ const { review } = authority(draft, record, true);
682
+ if (review?.id !== intent.review.id ||
683
+ !hasVerifiedIntegration(record) ||
684
+ record.verification?.digest !== intent.verification.digest ||
685
+ record.repositoryId !== intent.repositoryId ||
686
+ record.objectFormat !== intent.objectFormat ||
687
+ record.expectedTargetSha !== intent.expectedOld ||
688
+ record.preparedTree !== intent.preparedTree ||
689
+ record.materializedCommit !== intent.materializedCommit ||
690
+ record.targetDeviceId !== intent.targetDeviceId ||
691
+ record.targetBotId !== intent.targetBotId ||
692
+ record.targetBotRevision !== intent.targetBotRevision ||
693
+ (record.targetBranch.startsWith("refs/heads/") ? record.targetBranch : `refs/heads/${record.targetBranch}`) !==
694
+ intent.targetRef)
695
+ fail(409, "Current publication authority or verification changed");
696
+ driverRequired(driver);
697
+ record.status = "applying";
698
+ record.currentOpId = randomUUID();
699
+ // Consume the Hub's retry capability before dispatch. Device independently checks the durable journal.
700
+ record.publishObservation.retryable = false;
701
+ record.updatedAt = Date.now();
702
+ return structuredClone(record);
443
703
  });
444
- if (rpcError)
445
- throw rpcError;
446
- return result;
704
+ if (before.publishReceipt)
705
+ return before;
706
+ return dispatchPublication(store, before, driverRequired(driver), "resume");
707
+ }
708
+ const pendingRecovery = new WeakMap();
709
+ const recoveryBatches = new WeakMap();
710
+ const recoveryCursors = new WeakMap();
711
+ /** Startup/ready recovery only issues status queries. No implicit publication retry. */
712
+ export async function reconcilePendingIntegrations(store, driver, options = {}) {
713
+ const active = recoveryBatches.get(store);
714
+ if (active)
715
+ return active;
716
+ const batch = runPendingRecovery(store, driver, options);
717
+ recoveryBatches.set(store, batch);
718
+ try {
719
+ return await batch;
720
+ }
721
+ finally {
722
+ if (recoveryBatches.get(store) === batch)
723
+ recoveryBatches.delete(store);
724
+ }
725
+ }
726
+ async function runPendingRecovery(store, driver, options) {
727
+ const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(64, Math.floor(options.limit))) : 16;
728
+ const all = store
729
+ .snapshot()
730
+ .integrations.filter((i) => hasOpenPublication(i) && (!options.deviceId || i.publishIntent.targetDeviceId === options.deviceId));
731
+ let cursors = recoveryCursors.get(store);
732
+ if (!cursors) {
733
+ cursors = new Map();
734
+ recoveryCursors.set(store, cursors);
735
+ }
736
+ const scope = options.deviceId ?? "";
737
+ const start = (cursors.get(scope) ?? 0) % Math.max(1, all.length);
738
+ const pending = [...all.slice(start), ...all.slice(0, start)].slice(0, limit);
739
+ cursors.set(scope, (start + pending.length) % Math.max(1, all.length));
740
+ let running = pendingRecovery.get(store);
741
+ if (!running) {
742
+ running = new Map();
743
+ pendingRecovery.set(store, running);
744
+ }
745
+ const results = [];
746
+ let cursor = 0;
747
+ await Promise.all(Array.from({ length: Math.min(4, pending.length) }, async () => {
748
+ while (cursor < pending.length) {
749
+ const record = pending[cursor++];
750
+ const key = record.publishIntent.id;
751
+ let operation = running.get(key);
752
+ if (!operation) {
753
+ operation = hubReconcileIntegration(store, record.roomId, record.conversationId, { accountId: record.accountId }, record.id, driver);
754
+ running.set(key, operation);
755
+ }
756
+ try {
757
+ results.push(await operation);
758
+ }
759
+ catch {
760
+ /* Keep unresolved evidence for the next read-only probe. */
761
+ }
762
+ finally {
763
+ if (running.get(key) === operation)
764
+ running.delete(key);
765
+ }
766
+ }
767
+ }));
768
+ return results;
447
769
  }
448
- /** 查询会话的集成历史记录 */
449
770
  export function listIntegrations(state, conversationId) {
450
- return state.integrations.filter((it) => it.conversationId === conversationId);
771
+ return state.integrations.filter((i) => i.conversationId === conversationId);
451
772
  }