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
@@ -0,0 +1,274 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
+ import { createServer } from "node:net";
4
+ import { canonicalizeJson } from "./work-contract.js";
5
+ import { WINDOWS_VERIFICATION_SUPERVISOR } from "./local-verification-job.js";
6
+ import { VERIFICATION_COMMAND_TIMEOUT_MS, VERIFICATION_STOP_TIMEOUT_MS } from "./verification-limits.js";
7
+ export { VERIFICATION_COMMAND_TIMEOUT_MS, VERIFICATION_TOTAL_TIMEOUT_MS, VERIFICATION_STOP_TIMEOUT_MS, VERIFICATION_RPC_TIMEOUT_MS, } from "./verification-limits.js";
8
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
9
+ const PREVIEW_BYTES = 16 * 1024;
10
+ export class VerificationStopUnconfirmedError extends Error {
11
+ stopUnconfirmed = true;
12
+ constructor(cause) {
13
+ super("Verification process tree stop unconfirmed; workspace retained", { cause });
14
+ }
15
+ }
16
+ export function validateLocalVerificationPlan(value) {
17
+ const plan = value;
18
+ if (!plan ||
19
+ !Array.isArray(plan.commands) ||
20
+ plan.commands.length < 1 ||
21
+ plan.commands.length > 8 ||
22
+ plan.commands.some((command) => typeof command !== "string" || !command.trim() || command.length > 4096) ||
23
+ typeof plan.authorizedByAccountId !== "string" ||
24
+ !plan.authorizedByAccountId.trim() ||
25
+ !Number.isSafeInteger(plan.authorizedAt) ||
26
+ plan.authorizedAt <= 0 ||
27
+ plan.digest !==
28
+ createHash("sha256")
29
+ .update(canonicalizeJson({ commands: plan.commands }))
30
+ .digest("hex"))
31
+ throw new Error("Owner-authorized frozen verification plan required");
32
+ return structuredClone(plan);
33
+ }
34
+ /** Owner-trusted foreground/non-daemon commands. Digest covers all output bytes in observed stream order. */
35
+ export async function runVerificationCommand(command, options) {
36
+ options.signal?.throwIfAborted();
37
+ const windows = process.platform === "win32";
38
+ let windowsReceipt;
39
+ let resolveReceipt;
40
+ let rejectReceipt;
41
+ const receipt = new Promise((resolve, reject) => {
42
+ resolveReceipt = resolve;
43
+ rejectReceipt = reject;
44
+ });
45
+ void receipt.catch(() => { });
46
+ const sockets = new Set();
47
+ const pipeName = `pi-verification-${randomUUID()}`;
48
+ const receiptSecret = randomBytes(32).toString("hex");
49
+ const control = windows
50
+ ? createServer((socket) => {
51
+ sockets.add(socket);
52
+ let bytes = "";
53
+ let accepted = false;
54
+ socket.on("error", (error) => rejectReceipt(new VerificationStopUnconfirmedError(error)));
55
+ socket.once("end", () => {
56
+ if (!accepted)
57
+ rejectReceipt(new VerificationStopUnconfirmedError());
58
+ });
59
+ socket.on("data", (chunk) => {
60
+ bytes += chunk.toString("utf8");
61
+ if (bytes.length > 96) {
62
+ rejectReceipt(new VerificationStopUnconfirmedError());
63
+ socket.destroy();
64
+ return;
65
+ }
66
+ const match = /^([a-f0-9]{64}):(-?\d+)\r?\n$/.exec(bytes);
67
+ const code = match && Number(match[2]);
68
+ if (windowsReceipt === undefined &&
69
+ match?.[1] === receiptSecret &&
70
+ typeof code === "number" &&
71
+ Number.isInteger(code) &&
72
+ code >= -2147483648 &&
73
+ code <= 2147483647) {
74
+ accepted = true;
75
+ windowsReceipt = code;
76
+ resolveReceipt();
77
+ socket.end();
78
+ }
79
+ });
80
+ socket.once("close", () => {
81
+ sockets.delete(socket);
82
+ if (!accepted)
83
+ rejectReceipt(new VerificationStopUnconfirmedError());
84
+ });
85
+ })
86
+ : undefined;
87
+ if (control)
88
+ await new Promise((resolve, reject) => {
89
+ control.once("error", reject);
90
+ control.listen(`\\\\.\\pipe\\${pipeName}`, resolve);
91
+ });
92
+ const env = windows
93
+ ? { ...options.env, PI_LOCAL_VERIFICATION_COMMAND: command, PI_LOCAL_VERIFICATION_PIPE: pipeName }
94
+ : options.env;
95
+ let child;
96
+ try {
97
+ child = windows
98
+ ? spawn("powershell.exe", [
99
+ "-NoProfile",
100
+ "-NonInteractive",
101
+ "-OutputFormat",
102
+ "Text",
103
+ "-EncodedCommand",
104
+ Buffer.from(WINDOWS_VERIFICATION_SUPERVISOR, "utf16le").toString("base64"),
105
+ ], {
106
+ cwd: options.cwd,
107
+ env,
108
+ windowsHide: true,
109
+ stdio: ["pipe", "pipe", "pipe"],
110
+ })
111
+ : spawn(command, { cwd: options.cwd, env, shell: true, detached: true, stdio: ["ignore", "pipe", "pipe"] });
112
+ }
113
+ catch (error) {
114
+ control?.close();
115
+ throw error;
116
+ }
117
+ let closed = false;
118
+ let closeCode = null;
119
+ let spawnError;
120
+ let resolveClosed;
121
+ const done = new Promise((resolve) => {
122
+ resolveClosed = resolve;
123
+ });
124
+ child.once("error", (error) => {
125
+ spawnError = error;
126
+ });
127
+ child.once("close", (code) => {
128
+ closed = true;
129
+ closeCode = code;
130
+ resolveClosed();
131
+ });
132
+ child.stdin?.on("error", () => { });
133
+ if (windows)
134
+ child.stdin?.write(`${receiptSecret}\n`);
135
+ const stopMs = options.stopTimeoutMs ?? VERIFICATION_STOP_TIMEOUT_MS;
136
+ const bounded = async (operation) => {
137
+ let timer;
138
+ try {
139
+ await Promise.race([
140
+ operation,
141
+ new Promise((_, reject) => {
142
+ timer = setTimeout(() => reject(new VerificationStopUnconfirmedError()), stopMs);
143
+ }),
144
+ ]);
145
+ }
146
+ catch (error) {
147
+ throw error instanceof VerificationStopUnconfirmedError ? error : new VerificationStopUnconfirmedError(error);
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ }
152
+ };
153
+ const groupAlive = () => {
154
+ if (!child.pid)
155
+ return false;
156
+ try {
157
+ process.kill(-child.pid, 0);
158
+ return true;
159
+ }
160
+ catch (error) {
161
+ if (error.code === "ESRCH")
162
+ return false;
163
+ throw new VerificationStopUnconfirmedError(error);
164
+ }
165
+ };
166
+ const stopPosixGroup = async () => {
167
+ if (!child.pid) {
168
+ await done;
169
+ return;
170
+ }
171
+ try {
172
+ process.kill(-child.pid, "SIGKILL");
173
+ }
174
+ catch (error) {
175
+ if (error.code !== "ESRCH")
176
+ throw error;
177
+ }
178
+ await done;
179
+ const deadline = Date.now() + stopMs;
180
+ while (groupAlive()) {
181
+ if (Date.now() >= deadline)
182
+ throw new VerificationStopUnconfirmedError();
183
+ await new Promise((resolve) => setTimeout(resolve, 10));
184
+ }
185
+ };
186
+ let stopReason;
187
+ let stopping;
188
+ let notifyStop;
189
+ const stopStarted = new Promise((resolve, reject) => {
190
+ notifyStop = (operation) => {
191
+ void operation.then(resolve, reject);
192
+ };
193
+ });
194
+ void stopStarted.catch(() => { });
195
+ const stop = (reason) => {
196
+ if (stopping)
197
+ return;
198
+ stopReason = reason;
199
+ stopping = bounded((async () => {
200
+ if (windows) {
201
+ if (!closed)
202
+ child.stdin?.end("stop\n");
203
+ await done;
204
+ if (!spawnError)
205
+ await receipt;
206
+ }
207
+ else
208
+ await stopPosixGroup();
209
+ })());
210
+ notifyStop(stopping);
211
+ void stopping.catch(() => { });
212
+ };
213
+ const hash = createHash("sha256");
214
+ const preview = [];
215
+ let previewSize = 0, outputSize = 0;
216
+ const collect = (chunk) => {
217
+ hash.update(chunk);
218
+ outputSize += chunk.length;
219
+ if (previewSize < PREVIEW_BYTES) {
220
+ const part = chunk.subarray(0, PREVIEW_BYTES - previewSize);
221
+ preview.push(part);
222
+ previewSize += part.length;
223
+ }
224
+ if (outputSize > MAX_OUTPUT_BYTES)
225
+ stop("output limit exceeded");
226
+ };
227
+ child.stdout?.on("data", collect);
228
+ child.stderr?.on("data", collect);
229
+ const abort = () => stop("cancelled");
230
+ options.signal?.addEventListener("abort", abort, { once: true });
231
+ if (options.signal?.aborted)
232
+ abort();
233
+ const timer = setTimeout(() => stop("timed out"), options.timeoutMs ?? VERIFICATION_COMMAND_TIMEOUT_MS);
234
+ try {
235
+ await Promise.race([done, stopStarted]);
236
+ if (stopping)
237
+ await stopping;
238
+ if (windows && !spawnError) {
239
+ await bounded(receipt);
240
+ const signedExit = closeCode !== null && Number.isInteger(closeCode) && closeCode >= -2147483648 && closeCode <= 4294967295
241
+ ? closeCode | 0
242
+ : undefined;
243
+ if (signedExit === undefined || windowsReceipt !== signedExit)
244
+ throw new VerificationStopUnconfirmedError();
245
+ }
246
+ if (!windows && groupAlive()) {
247
+ stop("surviving foreground descendants");
248
+ await stopping;
249
+ }
250
+ if (options.signal?.aborted)
251
+ throw options.signal.reason ?? new Error("Verification cancelled");
252
+ const exitCode = windows && windowsReceipt !== undefined ? windowsReceipt : closeCode;
253
+ const passed = !stopReason && !spawnError && exitCode === 0;
254
+ return {
255
+ command,
256
+ status: passed ? "passed" : "failed",
257
+ exitCode: passed ? 0 : exitCode || 1,
258
+ outputDigest: hash.digest("hex"),
259
+ outputPreview: Buffer.concat(preview).toString("utf8"),
260
+ };
261
+ }
262
+ catch (error) {
263
+ if (windows && error instanceof VerificationStopUnconfirmedError && !closed)
264
+ child.kill();
265
+ throw error;
266
+ }
267
+ finally {
268
+ clearTimeout(timer);
269
+ options.signal?.removeEventListener("abort", abort);
270
+ for (const socket of sockets)
271
+ socket.destroy();
272
+ control?.close();
273
+ }
274
+ }
@@ -10,6 +10,8 @@ import { createLocalDeviceHub } from "./local-hub.js";
10
10
  import { createLocalBotRegistry } from "./bots.js";
11
11
  import { loadExecutionSettings, saveExecutionSettings } from "./execution-settings.js";
12
12
  import { hostWithoutPort, isLoopbackHost } from "../host-guard.js";
13
+ import { MAX_CONTRACT_REQUEST_BYTES } from "./work-contract.js";
14
+ import { INTEGRATION_HTTP_TIMEOUT_MS, VERIFICATION_HTTP_TIMEOUT_MS } from "./verification-limits.js";
13
15
  /** Hub enrollment accepts HTTP(S) origins, including public IP addresses. */
14
16
  export function normalizeHubUrl(input) {
15
17
  if (typeof input !== "string" || input.length > 2048)
@@ -88,6 +90,15 @@ export async function installLocalDeviceCenter(options) {
88
90
  let localHub;
89
91
  let localStarting;
90
92
  const activeConfig = () => config ?? localHub?.config;
93
+ function forAgent(captured) {
94
+ const { uiCredential: _uiCredential, ...agentConfig } = captured;
95
+ return {
96
+ ...agentConfig,
97
+ get accountId() {
98
+ return captured.accountId;
99
+ },
100
+ };
101
+ }
91
102
  async function ensureLocalHub() {
92
103
  if (config || localHub || closed)
93
104
  return;
@@ -95,9 +106,8 @@ export async function installLocalDeviceCenter(options) {
95
106
  localStarting = (async () => {
96
107
  const hub = await createLocalDeviceHub(options.dataDir, () => loadExecutionSettings(options.dataDir));
97
108
  try {
98
- const { uiCredential: _uiCredential, ...agentConfig } = hub.config;
99
109
  localHub = hub;
100
- connection = await options.connect(agentConfig, syncBots);
110
+ connection = await options.connect(forAgent(hub.config), syncBots);
101
111
  await syncBots();
102
112
  }
103
113
  catch (error) {
@@ -141,8 +151,7 @@ export async function installLocalDeviceCenter(options) {
141
151
  localHub = undefined;
142
152
  await bots.setScope(config ? JSON.stringify([config.hubUrl, config.deviceId]) : "unpaired");
143
153
  if (config && !closed) {
144
- const { uiCredential: _uiCredential, ...agentConfig } = config;
145
- connection = await options.connect(agentConfig, syncBots);
154
+ connection = await options.connect(forAgent(config), syncBots);
146
155
  }
147
156
  }
148
157
  async function syncBots() {
@@ -169,11 +178,22 @@ export async function installLocalDeviceCenter(options) {
169
178
  })),
170
179
  }),
171
180
  });
172
- await response.body?.cancel();
173
- if (!response.ok)
181
+ if (!response.ok) {
182
+ await response.body?.cancel();
174
183
  throw new Error("Bot configuration saved locally, but Hub synchronization failed; retry after reconnecting");
184
+ }
185
+ // Only the authenticated Hub supplies the owner, never a publication command's wire scope.
186
+ const result = await response.json();
187
+ const accountId = result && typeof result === "object" && "accountId" in result ? result.accountId : undefined;
175
188
  if (activeConfig() !== captured || closed)
176
189
  throw new Error("Device binding changed during Bot synchronization");
190
+ if (typeof accountId === "string" && accountId) {
191
+ if (captured.accountId && captured.accountId !== accountId)
192
+ throw new Error("Device account binding changed");
193
+ // Legacy bindings are refreshed each connection; do not race pairing's serialized config writes.
194
+ if (!captured.accountId)
195
+ captured.accountId = accountId;
196
+ }
177
197
  }
178
198
  async function hubRequest(hubUrl, path, body) {
179
199
  const response = await fetch(`${hubUrl}${path}`, {
@@ -216,7 +236,8 @@ export async function installLocalDeviceCenter(options) {
216
236
  typeof value.name !== "string" ||
217
237
  (value.remark !== undefined && typeof value.remark !== "string") ||
218
238
  typeof value.allowExecution !== "boolean" ||
219
- (value.uiCredential !== undefined && typeof value.uiCredential !== "string"))
239
+ (value.uiCredential !== undefined && typeof value.uiCredential !== "string") ||
240
+ (value.accountId !== undefined && (typeof value.accountId !== "string" || !value.accountId)))
220
241
  throw new Error("Invalid saved device configuration");
221
242
  config = { ...value, hubUrl: normalizeHubUrl(value.hubUrl) };
222
243
  await reconnect();
@@ -272,6 +293,50 @@ export async function installLocalDeviceCenter(options) {
272
293
  connected: connection?.isConnected?.() ?? false,
273
294
  });
274
295
  });
296
+ options.app.post("/api/device-center/upgrade-hub", async (_req, res) => {
297
+ const captured = activeConfig();
298
+ if (!captured)
299
+ return res.status(400).json({ error: "Device hub not paired" });
300
+ try {
301
+ const hubUrl = captured.hubUrl;
302
+ const forwardUrl = `${hubUrl}/api/system/upgrade`;
303
+ const response = await fetch(forwardUrl, {
304
+ method: "POST",
305
+ headers: {
306
+ "Content-Type": "application/json",
307
+ "x-device-id": captured.deviceId,
308
+ authorization: `Bearer ${captured.credential}`,
309
+ },
310
+ signal: AbortSignal.timeout(15_000),
311
+ });
312
+ if (!response.ok) {
313
+ const errData = (await response.json().catch(() => ({})));
314
+ throw new Error(errData.error || `Hub returned HTTP ${response.status}`);
315
+ }
316
+ const deadline = Date.now() + 60_000;
317
+ let healthy = false;
318
+ await new Promise((r) => setTimeout(r, 1500));
319
+ while (Date.now() < deadline) {
320
+ try {
321
+ const probe = await fetch(`${hubUrl}/health`, { signal: AbortSignal.timeout(2000) });
322
+ if (probe.ok) {
323
+ const data = (await probe.json().catch(() => ({})));
324
+ if (data && data.status === "ok") {
325
+ healthy = true;
326
+ break;
327
+ }
328
+ }
329
+ }
330
+ catch { }
331
+ await new Promise((r) => setTimeout(r, 1500));
332
+ }
333
+ await reconnect().catch(() => { });
334
+ res.json({ ok: true, healthy, message: healthy ? "Hub updated successfully" : "Hub update triggered" });
335
+ }
336
+ catch (error) {
337
+ res.status(500).json({ error: error?.message || "Failed to upgrade hub" });
338
+ }
339
+ });
275
340
  options.app.get("/api/device-center/execution-settings", (_req, res) => {
276
341
  try {
277
342
  const settings = loadExecutionSettings(options.dataDir);
@@ -390,6 +455,7 @@ export async function installLocalDeviceCenter(options) {
390
455
  }
391
456
  });
392
457
  function userRoute(method, path, fields) {
458
+ const supportsContract = method === "post" && fields.includes("contract");
393
459
  options.app[method](`/api/device-center/${path}`, async (req, res) => {
394
460
  try {
395
461
  await serialize(ensureLocalHub);
@@ -413,7 +479,8 @@ export async function installLocalDeviceCenter(options) {
413
479
  typeof body !== "object" ||
414
480
  Array.isArray(body) ||
415
481
  Object.keys(body).some((key) => !fields.includes(key)) ||
416
- Buffer.byteLength(JSON.stringify(body)) > 32768))
482
+ Buffer.byteLength(JSON.stringify(body)) >
483
+ (supportsContract && body.contract !== undefined ? MAX_CONTRACT_REQUEST_BYTES : 32768)))
417
484
  return res.status(400).json({ code: "INVALID_BODY", error: "Invalid group request" });
418
485
  const controller = new AbortController();
419
486
  activeRequests.add(controller);
@@ -428,10 +495,15 @@ export async function installLocalDeviceCenter(options) {
428
495
  const suffix = path.replace(/:([A-Za-z]+)/g, (_match, key) => encodeURIComponent(String(req.params[key])));
429
496
  const queryIndex = req.url.indexOf("?");
430
497
  const queryStr = queryIndex >= 0 ? req.url.slice(queryIndex) : "";
498
+ const timeoutMs = method === "post" && path.includes("/integrations")
499
+ ? path.endsWith("/verify")
500
+ ? VERIFICATION_HTTP_TIMEOUT_MS
501
+ : INTEGRATION_HTTP_TIMEOUT_MS
502
+ : 15000;
431
503
  const response = await fetch(`${captured.hubUrl}/api/device-user/${suffix}${queryStr}`, {
432
504
  method: method.toUpperCase(),
433
505
  redirect: "error",
434
- signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]),
506
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]),
435
507
  headers: {
436
508
  "Content-Type": "application/json",
437
509
  "X-Device-Id": captured.deviceId,
@@ -692,7 +764,15 @@ export async function installLocalDeviceCenter(options) {
692
764
  ]);
693
765
  userRoute("get", "rooms/:id/conversations", []);
694
766
  userRoute("get", "rooms/:id/conversations/:conversationId", []);
695
- userRoute("post", "rooms/:id/conversations", ["name", "targetBotId", "text", "idempotencyKey", "planOnly"]);
767
+ userRoute("post", "rooms/:id/conversations", [
768
+ "name",
769
+ "targetBotId",
770
+ "text",
771
+ "idempotencyKey",
772
+ "planOnly",
773
+ "executionMode",
774
+ "contract",
775
+ ]);
696
776
  userRoute("post", "rooms/:id/conversations/:conversationId/messages", [
697
777
  "text",
698
778
  "kind",
@@ -700,8 +780,11 @@ export async function installLocalDeviceCenter(options) {
700
780
  "attentionId",
701
781
  "idempotencyKey",
702
782
  "planOnly",
783
+ "executionMode",
784
+ "contract",
703
785
  ]);
704
786
  userRoute("post", "rooms/:id/conversations/:conversationId/deliveries", [
787
+ "artifactTaskId",
705
788
  "repository",
706
789
  "baseCommit",
707
790
  "commit",
@@ -714,6 +797,10 @@ export async function installLocalDeviceCenter(options) {
714
797
  userRoute("post", "rooms/:id/conversations/:conversationId/reviews", [
715
798
  "deliveryId",
716
799
  "commit",
800
+ "artifactDigest",
801
+ "integrationId",
802
+ "verificationDigest",
803
+ "criteriaResults",
717
804
  "verdict",
718
805
  "summary",
719
806
  "idempotencyKey",
@@ -728,6 +815,12 @@ export async function installLocalDeviceCenter(options) {
728
815
  userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", ["commands"]);
729
816
  userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", ["expectedTargetSha"]);
730
817
  userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", []);
818
+ userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/reconcile", []);
819
+ userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/resume", [
820
+ "intentId",
821
+ "intentDigest",
822
+ "candidateSha",
823
+ ]);
731
824
  userRoute("get", "rooms/:id/transfers", []);
732
825
  userRoute("post", "rooms/:id/transfers/start", [
733
826
  "sourceBotId",
@@ -757,6 +850,8 @@ export async function installLocalDeviceCenter(options) {
757
850
  "handoff",
758
851
  "parentTaskId",
759
852
  "planOnly",
853
+ "executionMode",
854
+ "contract",
760
855
  ]);
761
856
  userRoute("get", "rooms/:id/webhooks", []);
762
857
  userRoute("post", "rooms/:id/webhooks", [
@@ -827,6 +922,7 @@ export async function installLocalDeviceCenter(options) {
827
922
  hubUrl: pair.hubUrl,
828
923
  name: pair.name,
829
924
  deviceId: result.deviceId,
925
+ ...(typeof result.accountId === "string" && result.accountId ? { accountId: result.accountId } : {}),
830
926
  credential: result.credential,
831
927
  uiCredential: result.uiCredential,
832
928
  allowExecution: false,
@@ -898,8 +994,7 @@ export async function installLocalDeviceCenter(options) {
898
994
  const current = activeConfig();
899
995
  if (!current)
900
996
  return undefined;
901
- const { uiCredential: _uiCredential, ...agentConfig } = current;
902
- return agentConfig;
997
+ return forAgent(current);
903
998
  },
904
999
  async close() {
905
1000
  closed = true;
@@ -50,7 +50,10 @@ export async function startDeviceHub(env = process.env) {
50
50
  getAccount: (req) => hub.getRelayAccount(req),
51
51
  ownsDevice: (accountId, id) => hub.store.getDeviceOwner(id) === accountId,
52
52
  getDeviceName: (id) => hub.store.getDevice(id)?.name,
53
- onTaskEvent: (id, event) => hub.acceptTaskEvent(id, event).then(() => undefined),
53
+ onTaskEvent: (id, event) => hub.acceptTaskEvent(id, event),
54
+ onDeviceConnect: async (id) => {
55
+ await Promise.all([hub.resumeQueuedTasks(id), hub.reconcilePendingPublications(id)]);
56
+ },
54
57
  onTaskInteractions: (id, event) => hub.acceptInteractions(id, event),
55
58
  onTaskProgress: (id, event) => hub.acceptTaskProgress(id, event),
56
59
  onTaskToolLifecycle: (id, frame) => hub.acceptTaskToolLifecycle(id, frame),