@blade-hq/agent-client 2612.0.0-beta.7 → 2612.0.0-beta.71

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 (95) hide show
  1. package/README.md +352 -34
  2. package/dist/application-client.d.ts +19 -0
  3. package/dist/blade-client.d.ts +25 -9
  4. package/dist/{chunk-E7J2JBML.js → chunk-DMVWOTJB.js} +1588 -391
  5. package/dist/chunk-DMVWOTJB.js.map +1 -0
  6. package/dist/index.d.ts +18 -5
  7. package/dist/index.js +15 -1
  8. package/dist/internal.d.ts +12 -4
  9. package/dist/internal.js +29 -3
  10. package/dist/internal.js.map +1 -1
  11. package/dist/resources/auth.d.ts +9 -1
  12. package/dist/resources/computers.d.ts +2 -7
  13. package/dist/resources/connectors.d.ts +323 -0
  14. package/dist/resources/headless.d.ts +1 -1
  15. package/dist/resources/llm.d.ts +64 -0
  16. package/dist/resources/models.d.ts +6 -1
  17. package/dist/resources/phones.d.ts +109 -0
  18. package/dist/resources/plugins.d.ts +22 -0
  19. package/dist/resources/sandbox.d.ts +22 -0
  20. package/dist/resources/sessions.d.ts +105 -10
  21. package/dist/schemas/ask-user-question.d.ts +21 -0
  22. package/dist/schemas/context-attachments.d.ts +18 -0
  23. package/dist/schemas/message-utils.d.ts +3 -9
  24. package/dist/schemas/message.d.ts +16 -2
  25. package/dist/schemas/plugin-refs.d.ts +7 -0
  26. package/dist/schemas/projection.d.ts +14 -1
  27. package/dist/schemas/session.d.ts +2 -48
  28. package/dist/server-clock.d.ts +2 -0
  29. package/dist/session/agent-session.d.ts +44 -95
  30. package/dist/session/definition.d.ts +3 -0
  31. package/dist/session/events.d.ts +0 -1
  32. package/dist/session/hub.d.ts +0 -24
  33. package/dist/session/state.d.ts +8 -1
  34. package/dist/session/workflow.d.ts +10 -3
  35. package/dist/shared/projection/builder.d.ts +0 -2
  36. package/dist/shared/projection/index.d.ts +1 -0
  37. package/dist/shared/projection/workflow.d.ts +24 -0
  38. package/dist/tool-provider.d.ts +60 -0
  39. package/dist/types/socket-events.d.ts +167 -11
  40. package/dist/version.d.ts +0 -1
  41. package/node_modules/engine.io-client/build/cjs/globals.node.d.ts +2 -3
  42. package/node_modules/engine.io-client/build/cjs/index.d.ts +3 -3
  43. package/node_modules/engine.io-client/build/cjs/index.js +1 -4
  44. package/node_modules/engine.io-client/build/cjs/socket.d.ts +39 -82
  45. package/node_modules/engine.io-client/build/cjs/socket.js +151 -218
  46. package/node_modules/engine.io-client/build/cjs/transport.d.ts +1 -1
  47. package/node_modules/engine.io-client/build/cjs/transports/polling-xhr.d.ts +4 -4
  48. package/node_modules/engine.io-client/build/cjs/transports/polling-xhr.js +2 -2
  49. package/node_modules/engine.io-client/build/cjs/transports/polling-xhr.node.js +17 -7
  50. package/node_modules/engine.io-client/build/cjs/transports/websocket.node.js +17 -7
  51. package/node_modules/engine.io-client/build/esm/globals.node.d.ts +2 -3
  52. package/node_modules/engine.io-client/build/esm/index.d.ts +3 -3
  53. package/node_modules/engine.io-client/build/esm/index.js +1 -2
  54. package/node_modules/engine.io-client/build/esm/socket.d.ts +39 -82
  55. package/node_modules/engine.io-client/build/esm/socket.js +141 -206
  56. package/node_modules/engine.io-client/build/esm/transport.d.ts +1 -1
  57. package/node_modules/engine.io-client/build/esm/transports/polling-xhr.d.ts +4 -4
  58. package/node_modules/engine.io-client/build/esm/transports/polling-xhr.js +2 -2
  59. package/node_modules/engine.io-client/build/esm-debug/globals.node.d.ts +2 -3
  60. package/node_modules/engine.io-client/build/esm-debug/index.d.ts +3 -3
  61. package/node_modules/engine.io-client/build/esm-debug/index.js +1 -2
  62. package/node_modules/engine.io-client/build/esm-debug/socket.d.ts +39 -82
  63. package/node_modules/engine.io-client/build/esm-debug/socket.js +150 -215
  64. package/node_modules/engine.io-client/build/esm-debug/transport.d.ts +1 -1
  65. package/node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.d.ts +4 -4
  66. package/node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.js +2 -2
  67. package/node_modules/engine.io-client/dist/engine.io.esm.min.js +3 -3
  68. package/node_modules/engine.io-client/dist/engine.io.esm.min.js.map +1 -1
  69. package/node_modules/engine.io-client/dist/engine.io.js +164 -239
  70. package/node_modules/engine.io-client/dist/engine.io.js.map +1 -1
  71. package/node_modules/engine.io-client/dist/engine.io.min.js +3 -3
  72. package/node_modules/engine.io-client/dist/engine.io.min.js.map +1 -1
  73. package/node_modules/engine.io-client/package.json +2 -2
  74. package/node_modules/socket.io-parser/build/cjs/binary.js +4 -1
  75. package/node_modules/socket.io-parser/build/cjs/index.d.ts +14 -4
  76. package/node_modules/socket.io-parser/build/cjs/index.js +18 -11
  77. package/node_modules/socket.io-parser/build/esm/binary.js +4 -1
  78. package/node_modules/socket.io-parser/build/esm/index.d.ts +14 -4
  79. package/node_modules/socket.io-parser/build/esm/index.js +14 -10
  80. package/node_modules/socket.io-parser/build/esm-debug/binary.js +4 -1
  81. package/node_modules/socket.io-parser/build/esm-debug/index.d.ts +14 -4
  82. package/node_modules/socket.io-parser/build/esm-debug/index.js +14 -10
  83. package/node_modules/socket.io-parser/package.json +1 -1
  84. package/node_modules/ws/index.js +15 -6
  85. package/node_modules/ws/lib/constants.js +1 -0
  86. package/node_modules/ws/lib/permessage-deflate.js +9 -7
  87. package/node_modules/ws/lib/receiver.js +37 -0
  88. package/node_modules/ws/lib/sender.js +6 -1
  89. package/node_modules/ws/lib/websocket-server.js +18 -6
  90. package/node_modules/ws/lib/websocket.js +50 -17
  91. package/node_modules/ws/package.json +8 -3
  92. package/node_modules/ws/wrapper.mjs +14 -1
  93. package/package.json +4 -4
  94. package/public-api.md +662 -36
  95. package/dist/chunk-E7J2JBML.js.map +0 -1
@@ -1,6 +1,233 @@
1
+ // src/resources/sandbox.ts
2
+ var SandboxResource = class {
3
+ constructor(client) {
4
+ this.client = client;
5
+ }
6
+ client;
7
+ execute(input) {
8
+ return this.client.json("POST", "/api/sandbox/execute", input);
9
+ }
10
+ };
11
+
12
+ // src/rest.ts
13
+ var DOCS_URL = "https://blade-hq.github.io/public-skills/";
14
+ var BladeApiError = class extends Error {
15
+ response;
16
+ status;
17
+ statusText;
18
+ constructor(response, message) {
19
+ super(message ?? `\u8BF7\u6C42\u5931\u8D25\uFF08${response.status} ${response.statusText}\uFF09`);
20
+ this.name = "BladeApiError";
21
+ this.response = response;
22
+ this.status = response.status;
23
+ this.statusText = response.statusText;
24
+ }
25
+ };
26
+ async function extractErrorDetail(response) {
27
+ try {
28
+ const cloned = response.clone();
29
+ const contentType = cloned.headers.get("content-type") ?? "";
30
+ if (contentType.includes("application/json")) {
31
+ const data = await cloned.json();
32
+ const detail = data?.detail;
33
+ if (typeof detail === "string" && detail.trim()) return detail;
34
+ if (Array.isArray(detail) && detail.length > 0) {
35
+ const first = detail[0];
36
+ if (first && typeof first.msg === "string") return first.msg;
37
+ }
38
+ } else {
39
+ const text = (await cloned.text()).trim();
40
+ if (text) return text;
41
+ }
42
+ } catch {
43
+ }
44
+ return void 0;
45
+ }
46
+ function decorateAuthError(error) {
47
+ if (!(error instanceof BladeApiError)) return error;
48
+ if (error.status === 401) {
49
+ error.message = `${error.message}\uFF08\u672A\u767B\u5F55\u6216\u51ED\u8BC1\u5DF2\u5931\u6548\u3002\u6D4F\u89C8\u5668\u573A\u666F\u8C03\u7528 client.auth.login() \u5F39\u7A97\u767B\u5F55\uFF0C\u81EA\u52A8\u5316\u573A\u666F\u5728 new BladeClient({ token }) \u4F20\u5165 PAT\u3002\u63A5\u5165\u6307\u5357\uFF1A${DOCS_URL}\uFF09`;
50
+ } else if (error.status === 403) {
51
+ error.message = `${error.message}\uFF08\u5F53\u524D\u8D26\u53F7\u65E0\u6743\u8BBF\u95EE\u8BE5\u8D44\u6E90\u3002\u63A5\u5165\u6307\u5357\uFF1A${DOCS_URL}\uFF09`;
52
+ }
53
+ return error;
54
+ }
55
+ function buildBackendUrl(baseUrl, path) {
56
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
57
+ return new URL(path.startsWith("/") ? path.slice(1) : path, base);
58
+ }
59
+
60
+ // src/tool-provider.ts
61
+ var ToolProvider = class {
62
+ constructor(client, options, onDispose) {
63
+ this.client = client;
64
+ this.options = options;
65
+ this.onDispose = onDispose;
66
+ if (!/^[a-zA-Z0-9_-]{1,128}$/.test(options.providerId) || options.capability.length < 16 || options.capability.length > 4096) throw new Error("Invalid tool provider identity");
67
+ if (new Set(options.tools.map((t) => t.name)).size !== options.tools.length || options.tools.length > 256) throw new Error("Duplicate or excessive provider tools");
68
+ this.url = `blade-rpc://${options.providerId}`;
69
+ this.open();
70
+ }
71
+ client;
72
+ options;
73
+ onDispose;
74
+ url;
75
+ socket;
76
+ timer;
77
+ registrationTimer;
78
+ disposed = false;
79
+ registered = false;
80
+ attempts = 0;
81
+ calls = /* @__PURE__ */ new Map();
82
+ waiters = /* @__PURE__ */ new Set();
83
+ /** Resolves only after BA has authenticated and registered this connection. */
84
+ ready() {
85
+ if (this.disposed) return Promise.reject(new Error("Tool provider disposed"));
86
+ if (this.registered) return Promise.resolve();
87
+ return new Promise((resolve, reject) => {
88
+ const timer = setTimeout(() => {
89
+ this.waiters.delete(waiter);
90
+ reject(new Error("Tool provider registration timed out"));
91
+ }, 25e3);
92
+ const waiter = { resolve: () => {
93
+ clearTimeout(timer);
94
+ resolve();
95
+ }, reject: (e) => {
96
+ clearTimeout(timer);
97
+ reject(e);
98
+ } };
99
+ this.waiters.add(waiter);
100
+ });
101
+ }
102
+ reconnect() {
103
+ if (this.disposed) return;
104
+ clearTimeout(this.timer);
105
+ this.reset();
106
+ this.open();
107
+ }
108
+ reset() {
109
+ clearTimeout(this.registrationTimer);
110
+ this.registered = false;
111
+ const socket = this.socket;
112
+ this.socket = void 0;
113
+ socket?.close();
114
+ for (const controller of this.calls.values()) controller.abort();
115
+ this.calls.clear();
116
+ }
117
+ fail(error) {
118
+ for (const waiter of this.waiters) waiter.reject(error);
119
+ this.waiters.clear();
120
+ try {
121
+ this.options.onError?.(error);
122
+ } catch {
123
+ }
124
+ }
125
+ open() {
126
+ if (this.disposed) return;
127
+ const endpoint = buildBackendUrl(this.client.options.baseUrl, "/api/app-tools/connect");
128
+ endpoint.protocol = endpoint.protocol === "https:" ? "wss:" : "ws:";
129
+ let socket;
130
+ try {
131
+ const token = this.client.token;
132
+ if (!token) throw new Error("Tool provider requires a token");
133
+ const encoded = btoa(Array.from(new TextEncoder().encode(token), (byte) => String.fromCharCode(byte)).join("")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
134
+ socket = this.client.options.applicationTransport?.provider() ?? new WebSocket(endpoint, ["blade-rpc", `blade-bearer.${encoded}`]);
135
+ } catch {
136
+ this.fail(new Error("Tool provider WebSocket unavailable"));
137
+ this.schedule();
138
+ return;
139
+ }
140
+ this.socket = socket;
141
+ this.registrationTimer = setTimeout(() => {
142
+ if (this.socket === socket) {
143
+ this.fail(new Error("Tool provider registration timed out"));
144
+ socket.close();
145
+ }
146
+ }, 15e3);
147
+ socket.addEventListener("open", () => {
148
+ if (this.socket !== socket) return;
149
+ socket.send(JSON.stringify({ jsonrpc: "2.0", id: "register", method: "provider/register", params: { providerId: this.options.providerId, capability: this.options.capability, tools: this.definitions() } }));
150
+ });
151
+ socket.addEventListener("message", (event) => {
152
+ if (this.socket !== socket || typeof event.data !== "string") return;
153
+ void this.receive(socket, event.data).catch(() => {
154
+ this.fail(new Error("Invalid application tool RPC message"));
155
+ socket.close();
156
+ });
157
+ });
158
+ socket.addEventListener("error", () => {
159
+ if (this.socket === socket) this.fail(new Error("Application tool connection failed"));
160
+ });
161
+ socket.addEventListener("close", () => {
162
+ if (this.socket !== socket) return;
163
+ this.reset();
164
+ this.fail(new Error("Application tool connection closed; unfinished calls will not be replayed"));
165
+ this.schedule();
166
+ });
167
+ }
168
+ schedule() {
169
+ if (this.disposed) return;
170
+ this.timer = setTimeout(() => this.open(), Math.min(1e4, 500 * 2 ** Math.min(this.attempts++, 5)));
171
+ }
172
+ definitions() {
173
+ return this.options.tools.map(({ name, description, inputSchema, outputSchema, annotations }) => ({ name, description, inputSchema, ...outputSchema ? { outputSchema } : {}, ...annotations ? { annotations } : {} }));
174
+ }
175
+ async receive(socket, text) {
176
+ const message = JSON.parse(text);
177
+ if (message.jsonrpc !== "2.0") throw new Error("Invalid JSON-RPC envelope");
178
+ if (message.id === "register" && !message.method) {
179
+ clearTimeout(this.registrationTimer);
180
+ if (message.error || !message.result?.registered) {
181
+ this.fail(new Error(message.error?.message ?? "Tool provider registration rejected"));
182
+ socket.close();
183
+ return;
184
+ }
185
+ this.registered = true;
186
+ this.attempts = 0;
187
+ for (const waiter of this.waiters) waiter.resolve();
188
+ this.waiters.clear();
189
+ return;
190
+ }
191
+ if (!this.registered) throw new Error("Provider not registered");
192
+ if (message.method === "notifications/cancelled") {
193
+ this.calls.get(String(message.params?.requestId))?.abort();
194
+ return;
195
+ }
196
+ if (!message.id || typeof message.id !== "string" || this.calls.has(message.id)) throw new Error("Invalid RPC request ID");
197
+ const controller = new AbortController();
198
+ this.calls.set(message.id, controller);
199
+ let response = { jsonrpc: "2.0", id: message.id };
200
+ try {
201
+ if (message.method === "tools/list") {
202
+ response.result = { tools: this.definitions() };
203
+ } else if (message.method === "tools/call") {
204
+ const params = message.params;
205
+ const tool = this.options.tools.find((t) => t.name === params?.name);
206
+ if (!tool || typeof params?.sessionId !== "string" || !params.sessionId || !params.arguments || typeof params.arguments !== "object" || Array.isArray(params.arguments)) throw new Error("Invalid or unauthorized tool call");
207
+ response.result = await tool.handler(params.arguments, { sessionId: params.sessionId, signal: controller.signal, ...Object.fromEntries(["executionId", "requestId", "toolCallId"].flatMap((key) => typeof params[key] === "string" && params[key] ? [[key, params[key]]] : [])) });
208
+ } else {
209
+ response.error = { code: -32601, message: "Method not found" };
210
+ }
211
+ } catch {
212
+ response = { jsonrpc: "2.0", id: message.id, error: { code: -32e3, message: "Application tool execution failed" } };
213
+ } finally {
214
+ this.calls.delete(message.id);
215
+ }
216
+ if (this.socket === socket && socket.readyState === WebSocket.OPEN && !controller.signal.aborted) socket.send(JSON.stringify(response));
217
+ }
218
+ dispose() {
219
+ if (this.disposed) return;
220
+ this.disposed = true;
221
+ clearTimeout(this.timer);
222
+ this.reset();
223
+ this.fail(new Error("Tool provider disposed"));
224
+ this.onDispose();
225
+ }
226
+ };
227
+
1
228
  // src/version.ts
2
229
  var SDK_NAME = "agent-client";
3
- var SDK_VERSION = true ? "2612.0.0-beta.7" : "1.1.1";
230
+ var SDK_VERSION = true ? "2612.0.0-beta.71" : "1.1.1";
4
231
 
5
232
  // src/auth-login.ts
6
233
  function isAuthCallbackMessage(value) {
@@ -128,54 +355,6 @@ async function loginWithPopup(client, options = {}) {
128
355
  });
129
356
  }
130
357
 
131
- // src/rest.ts
132
- var DOCS_URL = "https://blade-hq.github.io/public-skills/";
133
- var BladeApiError = class extends Error {
134
- response;
135
- status;
136
- statusText;
137
- constructor(response, message) {
138
- super(message ?? `\u8BF7\u6C42\u5931\u8D25\uFF08${response.status} ${response.statusText}\uFF09`);
139
- this.name = "BladeApiError";
140
- this.response = response;
141
- this.status = response.status;
142
- this.statusText = response.statusText;
143
- }
144
- };
145
- async function extractErrorDetail(response) {
146
- try {
147
- const cloned = response.clone();
148
- const contentType = cloned.headers.get("content-type") ?? "";
149
- if (contentType.includes("application/json")) {
150
- const data = await cloned.json();
151
- const detail = data?.detail;
152
- if (typeof detail === "string" && detail.trim()) return detail;
153
- if (Array.isArray(detail) && detail.length > 0) {
154
- const first = detail[0];
155
- if (first && typeof first.msg === "string") return first.msg;
156
- }
157
- } else {
158
- const text = (await cloned.text()).trim();
159
- if (text) return text;
160
- }
161
- } catch {
162
- }
163
- return void 0;
164
- }
165
- function decorateAuthError(error) {
166
- if (!(error instanceof BladeApiError)) return error;
167
- if (error.status === 401) {
168
- error.message = `${error.message}\uFF08\u672A\u767B\u5F55\u6216\u51ED\u8BC1\u5DF2\u5931\u6548\u3002\u6D4F\u89C8\u5668\u573A\u666F\u8C03\u7528 client.auth.login() \u5F39\u7A97\u767B\u5F55\uFF0C\u81EA\u52A8\u5316\u573A\u666F\u5728 new BladeClient({ token }) \u4F20\u5165 PAT\u3002\u63A5\u5165\u6307\u5357\uFF1A${DOCS_URL}\uFF09`;
169
- } else if (error.status === 403) {
170
- error.message = `${error.message}\uFF08\u5F53\u524D\u8D26\u53F7\u65E0\u6743\u8BBF\u95EE\u8BE5\u8D44\u6E90\u3002\u63A5\u5165\u6307\u5357\uFF1A${DOCS_URL}\uFF09`;
171
- }
172
- return error;
173
- }
174
- function buildBackendUrl(baseUrl, path) {
175
- const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
176
- return new URL(path.startsWith("/") ? path.slice(1) : path, base);
177
- }
178
-
179
358
  // src/resources/auth.ts
180
359
  var AuthResource = class {
181
360
  constructor(client) {
@@ -202,6 +381,7 @@ var AuthResource = class {
202
381
  headers: { Origin: params.clientOrigin },
203
382
  body: JSON.stringify({
204
383
  code: params.code,
384
+ ...params.codeVerifier ? { code_verifier: params.codeVerifier, android_app: params.androidApp, desktop_app: params.desktopApp, callback_uri: params.callbackUri } : {},
205
385
  state: params.state,
206
386
  client_origin: params.clientOrigin
207
387
  })
@@ -214,8 +394,8 @@ var AuthResource = class {
214
394
  getProviders() {
215
395
  return this.client.json("GET", "/api/auth/providers");
216
396
  }
217
- getMe() {
218
- return this.client.json("GET", "/api/auth/me");
397
+ getMe(options = {}) {
398
+ return this.client.jsonFromInit("/api/auth/me", { signal: options.signal });
219
399
  }
220
400
  logout() {
221
401
  return this.client.json("POST", "/api/auth/logout");
@@ -280,6 +460,31 @@ var LogCursor = class {
280
460
  }
281
461
  };
282
462
 
463
+ // src/schemas/context-attachments.ts
464
+ function snapshotContextAttachments(value) {
465
+ const snapshot2 = JSON.parse(JSON.stringify(value));
466
+ if (!Array.isArray(snapshot2) || snapshot2.length > 20) throw new Error("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u63D0\u4F9B 20 \u4EFD\u8D44\u6599");
467
+ const ids = /* @__PURE__ */ new Set();
468
+ const validText = (text, limit) => typeof text === "string" && [...text].length > 0 && [...text].length <= limit;
469
+ for (const item of snapshot2) {
470
+ if (!item || !validText(item.id, 128) || !validText(item.label, 512) || !validText(item.content, 64e3) || ids.has(item.id)) throw new Error("\u9644\u52A0\u8D44\u6599\u683C\u5F0F\u9519\u8BEF\u6216 ID \u91CD\u590D");
471
+ ids.add(item.id);
472
+ if (item.update_format !== void 0 && item.update_format !== "snapshot" && item.update_format !== "diff") throw new Error("\u8D44\u6599\u66F4\u65B0\u683C\u5F0F\u65E0\u6548");
473
+ if (item.data != null && (typeof item.data !== "object" || Array.isArray(item.data))) throw new Error("\u8D44\u6599\u6570\u636E\u5FC5\u987B\u662F JSON \u5BF9\u8C61");
474
+ if (item.files != null && (!Array.isArray(item.files) || item.files.length > 20)) throw new Error("\u8D44\u6599\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF");
475
+ for (const file of item.files ?? []) {
476
+ if (!validText(file.name, 512)) throw new Error("\u8D44\u6599\u6587\u4EF6\u540D\u683C\u5F0F\u9519\u8BEF");
477
+ if (file.session_id == null && file.path == null) continue;
478
+ if (!validText(file.session_id, 128) || !validText(file.path, 2048) || /[\\:]/.test(file.path) || file.path.replace(/^\//, "").split("/").some((part) => !part || part === "." || part === "..")) throw new Error("\u8D44\u6599\u6587\u4EF6\u5FC5\u987B\u4F7F\u7528\u6709\u6548\u7684\u4F1A\u8BDD\u6587\u4EF6\u8DEF\u5F84");
479
+ }
480
+ }
481
+ if (new TextEncoder().encode(JSON.stringify(snapshot2)).length > 256 * 1024) throw new Error("\u6D88\u606F\u9644\u52A0\u8D44\u6599\u4E0D\u80FD\u8D85\u8FC7 256 KiB");
482
+ return snapshot2;
483
+ }
484
+ function normalizeContextAttachments(value) {
485
+ return Array.isArray(value) ? value : [];
486
+ }
487
+
283
488
  // src/schemas/plugin-refs.ts
284
489
  function normalizePluginRefs(value) {
285
490
  if (!Array.isArray(value)) return [];
@@ -292,6 +497,19 @@ function normalizePluginRefs(value) {
292
497
  return [{ provider: "plugin", plugin: item.plugin, server: item.server, id: item.id, label: item.label }];
293
498
  });
294
499
  }
500
+ function normalizeMessageRefs(value) {
501
+ if (!Array.isArray(value)) return [];
502
+ const seen = /* @__PURE__ */ new Set();
503
+ return value.flatMap((item) => {
504
+ if (!item || typeof item !== "object") return [];
505
+ const ref = item.provider === "skill" && typeof item.id === "string" && item.id && typeof item.label === "string" && item.label ? { provider: "skill", id: item.id, label: item.label } : normalizePluginRefs([item])[0];
506
+ if (!ref) return [];
507
+ const key = ref.provider === "skill" ? JSON.stringify([ref.provider, ref.id]) : JSON.stringify([ref.provider, ref.plugin, ref.server, ref.id]);
508
+ if (seen.has(key)) return [];
509
+ seen.add(key);
510
+ return [ref];
511
+ });
512
+ }
295
513
 
296
514
  // src/schemas/topic-assets.ts
297
515
  function normalizeTopicAssetRefs(value) {
@@ -667,14 +885,14 @@ function applyAskUserPauseToTurn(turn, pauseToolData, toolCallId, childLoopName,
667
885
  }
668
886
  function spacedJson(value) {
669
887
  try {
670
- const encode = (item) => {
671
- if (Array.isArray(item)) return `[${item.map(encode).join(", ")}]`;
888
+ const encode2 = (item) => {
889
+ if (Array.isArray(item)) return `[${item.map(encode2).join(", ")}]`;
672
890
  if (item && typeof item === "object") {
673
- return `{${Object.entries(item).map(([key, part]) => `${JSON.stringify(key)}: ${encode(part)}`).join(", ")}}`;
891
+ return `{${Object.entries(item).map(([key, part]) => `${JSON.stringify(key)}: ${encode2(part)}`).join(", ")}}`;
674
892
  }
675
893
  return JSON.stringify(item) ?? "null";
676
894
  };
677
- return encode(JSON.parse(value));
895
+ return encode2(JSON.parse(value));
678
896
  } catch {
679
897
  return value;
680
898
  }
@@ -843,23 +1061,12 @@ function normalizeChildPause(pausePayload) {
843
1061
  }
844
1062
  function attachToolEvidence(call, evidence) {
845
1063
  if (!call) return;
846
- call.evidence = call.status === "done" && Array.isArray(evidence) ? evidence : void 0;
1064
+ call.evidence = (call.status === "done" || call.status === "error") && Array.isArray(evidence) ? evidence : void 0;
847
1065
  }
848
1066
 
849
1067
  // src/schemas/message.ts
850
1068
  function inferToolStatus(resultStr) {
851
1069
  if (resultStr.includes('"Cancelled by user"')) return "cancelled";
852
- try {
853
- const parsed = JSON.parse(resultStr);
854
- if (typeof parsed === "object" && parsed !== null) {
855
- if ("error" in parsed && parsed.error) return "error";
856
- const nested = parsed.result;
857
- if (typeof nested === "object" && nested !== null && "error" in nested && nested.error) {
858
- return "error";
859
- }
860
- }
861
- } catch {
862
- }
863
1070
  return "done";
864
1071
  }
865
1072
 
@@ -903,8 +1110,8 @@ function snapshot(state, sequence, status) {
903
1110
  first_token_ms: state.firstTokenMs,
904
1111
  stream_duration_ms: state.streamDurationMs,
905
1112
  first_token_delivery_ms: state.firstTokenDeliveryMs,
906
- started_at: state.modelStartedAt ?? new Date(state.startedAt).toISOString(),
907
- // 没有 payload 上报时用的是 loop:turn 的浏览器事件时间,标记出来供瀑布区分。
1113
+ started_at: state.modelStartedAt,
1114
+ // 未上报时不伪造服务器起点;浏览器时钟不能与服务器时钟混用。
908
1115
  has_reported_timing: state.modelStartedAtReported,
909
1116
  context_window: state.contextWindow,
910
1117
  memory_refs: state.memoryRefs,
@@ -1130,10 +1337,8 @@ var ClientProjectionBuilder = class {
1130
1337
  latestTurns = /* @__PURE__ */ new Map();
1131
1338
  turnsById = /* @__PURE__ */ new Map();
1132
1339
  loopDescriptions = /* @__PURE__ */ new Map();
1133
- /** loop_name → 正在运行的子智能体起点,agent:end 结算并挂到父工具调用上。 */
1134
1340
  activeSubagentRuns = /* @__PURE__ */ new Map();
1135
1341
  pendingChildPauses = /* @__PURE__ */ new Map();
1136
- /** 作答后子回路续跑,最终回复就是随后落盘的父 Agent 工具结果。 */
1137
1342
  answeredChildParents = /* @__PURE__ */ new Map();
1138
1343
  pendingMemoryRefs = /* @__PURE__ */ new Map();
1139
1344
  activeCompactions = /* @__PURE__ */ new Map();
@@ -1289,6 +1494,11 @@ var ClientProjectionBuilder = class {
1289
1494
  /** A durable snapshot supersedes only this turn's temporary overlay. */
1290
1495
  acceptDurableTurn(turn) {
1291
1496
  this.seedSequence(turn.sequence);
1497
+ if (turn.kind === "compaction") {
1498
+ this.turnsById.set(turn.turn_id, turn);
1499
+ if (turn.status !== "streaming") this.activeCompactions.delete(turn.compaction_id ?? "");
1500
+ return;
1501
+ }
1292
1502
  if (!isConversationTurn(turn)) return;
1293
1503
  const active = this.activeTurns.get(turn.loop_id);
1294
1504
  if (active?.turnId === turn.turn_id) this.activeTurns.delete(turn.loop_id);
@@ -1309,6 +1519,7 @@ var ClientProjectionBuilder = class {
1309
1519
  const turnsById = /* @__PURE__ */ new Map();
1310
1520
  for (const turn of turns) {
1311
1521
  this.seedSequence(turn.sequence);
1522
+ if (turn.kind === "compaction") turnsById.set(turn.turn_id, turn);
1312
1523
  if (!isConversationTurn(turn)) continue;
1313
1524
  turnsById.set(turn.turn_id, turn);
1314
1525
  const current = latestTurns.get(turn.loop_id);
@@ -1319,7 +1530,6 @@ var ClientProjectionBuilder = class {
1319
1530
  this.latestTurns = latestTurns;
1320
1531
  this.turnsById = turnsById;
1321
1532
  }
1322
- // --- Event handlers ---
1323
1533
  onMemoryInject(loopId, payload) {
1324
1534
  const refs = payload.memory_refs;
1325
1535
  const turnId = String(payload.turn_id ?? "");
@@ -1545,7 +1755,7 @@ var ClientProjectionBuilder = class {
1545
1755
  onUserMessage(_loopId, payload) {
1546
1756
  const entryId = String(payload.entry_id ?? this.nextTurnId("user"));
1547
1757
  const displayContent = payload.display_content ?? payload.content ?? "";
1548
- const refs = normalizePluginRefs(payload.refs);
1758
+ const refs = normalizeMessageRefs(payload.refs);
1549
1759
  const turn = {
1550
1760
  id: entryId,
1551
1761
  sequence: this.nextSeq(),
@@ -1556,6 +1766,7 @@ var ClientProjectionBuilder = class {
1556
1766
  status: "completed",
1557
1767
  blocks: [{ type: "text", content: displayContent }],
1558
1768
  ...refs.length ? { refs } : {},
1769
+ context_attachments: normalizeContextAttachments(payload.context_attachments),
1559
1770
  topic_asset_refs: normalizeTopicAssetRefs(payload.topic_asset_refs),
1560
1771
  tool_calls: [],
1561
1772
  model: null,
@@ -1584,7 +1795,6 @@ var ClientProjectionBuilder = class {
1584
1795
  this.latestTurns.set("root", turn);
1585
1796
  return [{ kind: "upsert", turn }];
1586
1797
  }
1587
- // --- Delta / streaming events ---
1588
1798
  onDelta(state, blockType, _toolCallId, content) {
1589
1799
  if (!content) return null;
1590
1800
  appendTextBlock(state, blockType, content);
@@ -1636,10 +1846,7 @@ var ClientProjectionBuilder = class {
1636
1846
  if (!applyResponseBlockOrder(state, payload.response_blocks) && "content" in payload) {
1637
1847
  replaceTextContent(state, completedResponseText(payload.content));
1638
1848
  }
1639
- const isNativeProviderResponse = typeof payload.provider === "string" && payload.provider !== "";
1640
- if (state.toolCalls.length === 0 || isNativeProviderResponse && state.toolCalls.every(
1641
- (toolCall) => toolCall.status !== "pending" && toolCall.status !== "awaiting_answer"
1642
- )) {
1849
+ if (state.toolCalls.length === 0) {
1643
1850
  const childParent = this.answeredChildParents.get(loopId);
1644
1851
  if (childParent) {
1645
1852
  this.answeredChildParents.delete(loopId);
@@ -1656,6 +1863,7 @@ var ClientProjectionBuilder = class {
1656
1863
  return this.syncPatch(state);
1657
1864
  }
1658
1865
  applyFirstTokenDelivery(state, payload) {
1866
+ this.applyStreamTiming(state, payload);
1659
1867
  const firstTokenMs = payload.first_token_ms;
1660
1868
  if (state.firstTokenMs === null && typeof firstTokenMs === "number" && firstTokenMs >= 0) {
1661
1869
  state.firstTokenMs = Math.round(firstTokenMs);
@@ -1684,7 +1892,7 @@ var ClientProjectionBuilder = class {
1684
1892
  const toolCallId = String(payload.tool_call_id ?? "");
1685
1893
  const streamedResult = state.toolCalls.find((toolCall) => toolCall.id === toolCallId)?.result;
1686
1894
  const content = payload.content_from_deltas === true ? streamedResult ?? "" : payload.content ?? "";
1687
- const status = payload.is_error === true ? "error" : toolStatusFromResult(content);
1895
+ const status = payload.is_error === true ? "error" : payload._tool_pending === true ? "pending" : toolStatusFromResult(content);
1688
1896
  const rawDuration = payload.duration_ms;
1689
1897
  const durationMs = typeof rawDuration === "number" && rawDuration >= 0 ? Math.round(rawDuration) : null;
1690
1898
  const ranInParallel = typeof payload.ran_in_parallel === "boolean" ? payload.ran_in_parallel : null;
@@ -1705,8 +1913,7 @@ var ClientProjectionBuilder = class {
1705
1913
  this.displayNameResolver
1706
1914
  );
1707
1915
  }
1708
- const isNativeProviderResult = typeof payload.provider === "string" && payload.provider !== "";
1709
- if (!isNativeProviderResult && this.shouldFinalizeAfterToolResults(state)) {
1916
+ if (this.shouldFinalizeAfterToolResults(state)) {
1710
1917
  return this.finalize(loopId, "completed");
1711
1918
  }
1712
1919
  return this.syncPatch(state);
@@ -1928,6 +2135,8 @@ var ClientProjectionBuilder = class {
1928
2135
  onCompaction(eventType, loopId, payload) {
1929
2136
  const compactionId = String(payload.compaction_id ?? "");
1930
2137
  if (!compactionId) return null;
2138
+ const previous = this.turnsById.get(`compaction:${compactionId}`);
2139
+ if (eventType === "compaction:start" && previous && previous.status !== "streaming") return null;
1931
2140
  let current = {
1932
2141
  ...this.activeCompactions.get(compactionId) ?? {},
1933
2142
  ...payload,
@@ -1965,7 +2174,6 @@ var ClientProjectionBuilder = class {
1965
2174
  const turn = buildCompactionTurn(this.nextSeq(), compactionId, loopId, status, current);
1966
2175
  return [{ kind: "upsert", turn }];
1967
2176
  }
1968
- // --- Internal helpers ---
1969
2177
  syncPatch(state) {
1970
2178
  const turn = snapshot(state, this.nextSeq(), "streaming");
1971
2179
  this.latestTurns.set(state.loopId, turn);
@@ -2145,7 +2353,6 @@ function projectHistory(entries) {
2145
2353
  const pendingChildPauses = /* @__PURE__ */ new Map();
2146
2354
  const childPauseEntries = [];
2147
2355
  const answeredToolCallIds = /* @__PURE__ */ new Set();
2148
- const nativeToolTurns = /* @__PURE__ */ new Set();
2149
2356
  const turnEntryAliases = /* @__PURE__ */ new Map();
2150
2357
  let latestRootMessage = null;
2151
2358
  let latestRootAssistant = null;
@@ -2211,7 +2418,7 @@ function projectHistory(entries) {
2211
2418
  const owner = toolOwners.get(toolCallId);
2212
2419
  const toolCall = owner?.tool_calls.find((item) => item.id === toolCallId);
2213
2420
  if (owner && toolCall) {
2214
- toolCall.status = message._error ? "error" : inferToolStatus(String(message.content ?? ""));
2421
+ toolCall.status = message._error ? "error" : message._tool_pending === true ? "pending" : inferToolStatus(String(message.content ?? ""));
2215
2422
  toolCall.result = message.content ?? "";
2216
2423
  attachToolEvidence(toolCall, message._evidence);
2217
2424
  const duration = numberOrNull(message._duration_ms);
@@ -2220,11 +2427,9 @@ function projectHistory(entries) {
2220
2427
  toolCall.started_at = message._started_at;
2221
2428
  }
2222
2429
  if (message._ran_in_parallel === true) toolCall.ran_in_parallel = true;
2223
- owner.blocks.push({
2224
- type: "tool_result",
2225
- content: message.content ?? "",
2226
- tool_call_id: toolCallId
2227
- });
2430
+ const existing = owner.blocks.find((block) => block.type === "tool_result" && block.tool_call_id === toolCallId);
2431
+ if (existing) existing.content = message.content ?? "";
2432
+ else owner.blocks.push({ type: "tool_result", content: message.content ?? "", tool_call_id: toolCallId });
2228
2433
  }
2229
2434
  continue;
2230
2435
  }
@@ -2241,56 +2446,29 @@ function projectHistory(entries) {
2241
2446
  loop_id: loopId,
2242
2447
  kind: "message",
2243
2448
  role,
2449
+ client_request_id: stringOrNull(entry.client_request_id),
2244
2450
  status: message._error ? "failed" : message._interrupted ? "interrupted" : "completed",
2245
2451
  blocks,
2246
2452
  tool_calls: toolCalls,
2247
2453
  model: stringOrNull(message.model),
2248
2454
  usage: isRecord(message._usage) ? { ...message._usage } : null,
2249
- // 模型请求区间来自持久化字段;旧会话缺失时为 null,不用落盘时刻冒充(#2581 A1)。
2250
2455
  duration_ms: numberOrNull(message._duration_ms),
2251
2456
  first_token_ms: numberOrNull(message._first_token_ms),
2252
2457
  stream_duration_ms: numberOrNull(message._stream_duration_ms),
2253
2458
  started_at: typeof message._started_at === "string" ? message._started_at : typeof entry.timestamp === "string" ? entry.timestamp : void 0,
2254
2459
  has_reported_timing: typeof message._started_at === "string",
2255
- // fork 子会话的父锚点:历史里落在消息级 _parent_fork_tool_call_id。丢掉它,
2256
- // 刷新后工作流步骤 fork 就配不回 workflow:run 工具调用(普通 Agent fork 有
2257
- // root Agent 工具调用兜底配对,工作流 fork 没有,子智能体卡会整体消失)。
2258
2460
  parent_fork_tool_call_id: stringOrNull(message._parent_fork_tool_call_id)
2259
2461
  };
2260
- const isNativeToolEntry = role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.some(
2261
- (toolCall) => isRecord(toolCall) && typeof toolCall.provider === "string"
2262
- );
2263
- const previousTurn = turns[turns.length - 1];
2264
- if (role === "assistant" && previousTurn?.role === "assistant" && previousTurn.loop_id === loopId && nativeToolTurns.has(previousTurn)) {
2265
- nativeToolTurns.delete(previousTurn);
2266
- previousTurn.blocks.push(...turn.blocks);
2267
- previousTurn.tool_calls.push(...turn.tool_calls);
2268
- previousTurn.status = turn.status;
2269
- previousTurn.model = turn.model ?? previousTurn.model;
2270
- previousTurn.usage = turn.usage ?? previousTurn.usage;
2271
- if (turn.duration_ms) previousTurn.duration_ms = turn.duration_ms;
2272
- previousTurn.first_token_ms = turn.first_token_ms ?? previousTurn.first_token_ms;
2273
- previousTurn.stream_duration_ms = turn.stream_duration_ms ?? previousTurn.stream_duration_ms;
2274
- if (turn.has_reported_timing) {
2275
- previousTurn.started_at = turn.started_at;
2276
- previousTurn.has_reported_timing = true;
2277
- } else if (!previousTurn.has_reported_timing) {
2278
- previousTurn.started_at = previousTurn.started_at ?? turn.started_at;
2279
- }
2280
- previousTurn.id = turn.id;
2281
- previousTurn.turn_id = turn.turn_id;
2282
- if (isNativeToolEntry) nativeToolTurns.add(previousTurn);
2283
- turnEntryAliases.set(id, previousTurn);
2284
- if (loopId === "root") latestRootMessage = previousTurn;
2285
- latestAssistantByLoop.set(loopId, previousTurn);
2286
- continue;
2462
+ if (role === "user") {
2463
+ const refs = normalizeMessageRefs(message.refs);
2464
+ if (refs.length) turn.refs = refs;
2465
+ turn.context_attachments = normalizeContextAttachments(message.context_attachments);
2287
2466
  }
2288
2467
  if (loopId === "root" && (role === "user" || role === "assistant")) {
2289
2468
  latestRootMessage = turn;
2290
2469
  }
2291
2470
  turns.push(turn);
2292
2471
  turnEntryAliases.set(id, turn);
2293
- if (isNativeToolEntry) nativeToolTurns.add(turn);
2294
2472
  if (role === "assistant") latestAssistantByLoop.set(loopId, turn);
2295
2473
  if (loopId === "root") {
2296
2474
  if (role === "assistant") latestRootAssistant = turn;
@@ -2306,7 +2484,7 @@ function projectHistory(entries) {
2306
2484
  if (owner && toolCallId) {
2307
2485
  const rawContent = data.content;
2308
2486
  const content = typeof rawContent === "string" ? rawContent : Array.isArray(rawContent) ? rawContent : String(rawContent ?? "");
2309
- const status = data.is_error === true ? "error" : inferToolStatus(typeof content === "string" ? content : JSON.stringify(content));
2487
+ const status = data.is_error === true ? "error" : data._tool_pending === true ? "pending" : inferToolStatus(typeof content === "string" ? content : JSON.stringify(content));
2310
2488
  setToolCallStatus(owner, toolCallId, status, content, null);
2311
2489
  if (!owner.blocks.some((block) => block.type === "tool_result" && block.tool_call_id === toolCallId)) {
2312
2490
  owner.blocks.push({ type: "tool_result", content, tool_call_id: toolCallId });
@@ -2314,6 +2492,33 @@ function projectHistory(entries) {
2314
2492
  }
2315
2493
  continue;
2316
2494
  }
2495
+ if (kind === "workflow_step") {
2496
+ const data = entry.data ?? {};
2497
+ const toolCallId = String(data.tool_call_id ?? "");
2498
+ const owner = toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
2499
+ if (owner && toolCallId) {
2500
+ const index = owner.tool_calls.findIndex((call) => call.id === toolCallId);
2501
+ if (index >= 0) {
2502
+ const call = owner.tool_calls[index];
2503
+ owner.tool_calls[index] = {
2504
+ ...call,
2505
+ workflow_steps: [
2506
+ ...call.workflow_steps ?? [],
2507
+ {
2508
+ step_id: String(data.step_id ?? ""),
2509
+ desc: String(data.desc ?? ""),
2510
+ step_kind: String(data.step_kind ?? "step"),
2511
+ status: String(data.status ?? "done"),
2512
+ output: String(data.output ?? ""),
2513
+ ...typeof data.seq === "number" ? { seq: data.seq } : {},
2514
+ ...typeof data.log_seq === "number" ? { log_seq: data.log_seq } : {}
2515
+ }
2516
+ ]
2517
+ };
2518
+ }
2519
+ }
2520
+ continue;
2521
+ }
2317
2522
  if (kind === "mode_change") {
2318
2523
  turns.push(markerTurn(id, ++sequence, loopId, "mode_change", entry.data ?? {}));
2319
2524
  } else if (kind === "workspace_change") {
@@ -2364,7 +2569,7 @@ function projectHistory(entries) {
2364
2569
  let content = isRecord(entry.message) ? entry.message.content : void 0;
2365
2570
  if (kind === "tool_result_archive") {
2366
2571
  const archivedCount = Array.isArray(data.archived_files) ? data.archived_files.length : 0;
2367
- content = `<compaction-summary>
2572
+ content = typeof data.summary === "string" && data.summary ? data.summary : `<compaction-summary>
2368
2573
  \u5DF2\u5F52\u6863 ${archivedCount} \u4E2A\u5927\u578B\u5DE5\u5177\u7ED3\u679C\u3002
2369
2574
  </compaction-summary>`;
2370
2575
  }
@@ -2588,6 +2793,35 @@ function findLatestAssistant(turns, loopId) {
2588
2793
  return void 0;
2589
2794
  }
2590
2795
 
2796
+ // src/shared/projection/workflow.ts
2797
+ var STEP_KINDS = /* @__PURE__ */ new Set(["agent", "step", "parallel", "choice", "end"]);
2798
+ function workflowEntriesFromSteps(steps) {
2799
+ const items = [];
2800
+ const ordered = steps.every((step) => typeof step.seq === "number");
2801
+ steps.forEach((step, index) => {
2802
+ const base = ordered ? step.seq : index * 2;
2803
+ const stepKind = step.step_kind && STEP_KINDS.has(step.step_kind) ? step.step_kind : "step";
2804
+ items.push({
2805
+ key: base,
2806
+ entry: { kind: "step", stepId: step.step_id, desc: step.desc ?? "", stepKind, status: step.status }
2807
+ });
2808
+ const logKey = ordered && typeof step.log_seq === "number" ? step.log_seq : base + 0.5;
2809
+ const output = step.output ?? "";
2810
+ if (step.status === "done" && stepKind === "step") {
2811
+ const chars = Array.from(output);
2812
+ const shown = chars.length <= 300 ? output : `${chars.slice(0, 300).join("")}\u2026(\u5171${chars.length}\u5B57)`;
2813
+ items.push({ key: logKey, entry: { kind: "log", text: ` \u2514 \u8F93\u51FA: ${shown || "(\u7A7A)"}`, stepId: step.step_id } });
2814
+ }
2815
+ if (step.status === "error" && output) {
2816
+ items.push({ key: logKey, entry: { kind: "log", text: `\u5931\u8D25: ${output}`, stepId: step.step_id } });
2817
+ }
2818
+ });
2819
+ return items.sort((a, b) => a.key - b.key).map((item) => item.entry);
2820
+ }
2821
+ function workflowRunCancelled(steps) {
2822
+ return steps.some((step) => step.status === "cancelled") && !steps.some((step) => step.status === "error");
2823
+ }
2824
+
2591
2825
  // src/resources/headless.ts
2592
2826
  var HeadlessError = class extends Error {
2593
2827
  constructor(message, detail) {
@@ -2623,7 +2857,7 @@ var HeadlessResource = class {
2623
2857
  return this.runTracked(session_id, prompt, options, true);
2624
2858
  }
2625
2859
  async runTracked(sessionId, prompt, options, returnEnvelope) {
2626
- if ((options.refs?.length ?? 0) > 20) throw new HeadlessError("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u9009\u62E9 20 \u4E2A\u63D2\u4EF6\u6761\u76EE");
2860
+ if ((options.refs?.length ?? 0) > 20) throw new HeadlessError("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u9009\u62E9 20 \u4E2A\u5F15\u7528");
2627
2861
  if ((options.topicAssetRefs?.length ?? 0) > 20) throw new HeadlessError("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u5F15\u7528 20 \u4E2A\u4E3B\u9898\u8D44\u4EA7");
2628
2862
  const timeoutMs = options.timeoutMs ?? 3e5;
2629
2863
  const session_id = sessionId;
@@ -2656,7 +2890,7 @@ var HeadlessResource = class {
2656
2890
  });
2657
2891
  if (stopped.status !== "received") return { ...stopped, phase: "stop_ack", chat_run_id: runId };
2658
2892
  const ack = stopped.ack;
2659
- const confirmed = isRecord(ack) && ack.ok !== false && (!Object.hasOwn(ack, "chat_run_id") || ack.chat_run_id === runId) && typeof ack.status === "string" && ["stopping", "stopped", "idle", "done", "interrupted"].includes(ack.status);
2893
+ const confirmed = isRecord(ack) && ack.ok !== false && ack.chat_run_id === runId && typeof ack.status === "string" && ["stopping", "stopped", "idle", "done", "interrupted"].includes(ack.status);
2660
2894
  return {
2661
2895
  status: confirmed ? "confirmed" : "unconfirmed",
2662
2896
  phase: "stop_ack",
@@ -2957,7 +3191,6 @@ function waitForCleanupAck(socket, deadline, request) {
2957
3191
 
2958
3192
  // src/resources/computers.ts
2959
3193
  function computerState(computer) {
2960
- if (computer.is_primary) return "primary";
2961
3194
  if (computer.enabled) return "enabled";
2962
3195
  return computer.online ? "idle" : "offline";
2963
3196
  }
@@ -2977,9 +3210,6 @@ function computerPlatformLabel(computer) {
2977
3210
  function computerDaemonVersion(computer) {
2978
3211
  return (computer.daemon_version ?? "").trim();
2979
3212
  }
2980
- function canToggleComputer(computer) {
2981
- return !computer.is_primary;
2982
- }
2983
3213
  function sortComputers(computers) {
2984
3214
  return [...computers].sort((a, b) => {
2985
3215
  const byCreated = (a.created_at ?? "").localeCompare(b.created_at ?? "");
@@ -3030,14 +3260,243 @@ var ComputersResource = class {
3030
3260
  }
3031
3261
  };
3032
3262
 
3263
+ // src/resources/phones.ts
3264
+ function phoneState(phone) {
3265
+ if (phone.enabled) return "enabled";
3266
+ return phone.online ? "idle" : "offline";
3267
+ }
3268
+ function sortPhones(phones) {
3269
+ return [...phones].sort((a, b) => {
3270
+ const byCreated = (a.created_at ?? "").localeCompare(b.created_at ?? "");
3271
+ if (byCreated !== 0) return byCreated;
3272
+ return a.label.localeCompare(b.label);
3273
+ });
3274
+ }
3275
+ function phoneSerialLabel(phone) {
3276
+ return phone.serial.trim();
3277
+ }
3278
+ var PhonesResource = class {
3279
+ constructor(client) {
3280
+ this.client = client;
3281
+ }
3282
+ client;
3283
+ /** 账号下的全部手机(不含"本次会话是否可用")。 */
3284
+ async listAccount() {
3285
+ return this.client.json("GET", "/api/phone/devices");
3286
+ }
3287
+ /**
3288
+ * 当前接入密钥;没有就补一个。
3289
+ *
3290
+ * **取的时候不轮换**:每次打开设置页都换钥匙会让已配好的手机集体掉线。
3291
+ */
3292
+ getKey() {
3293
+ return this.client.json("GET", "/api/phone/key");
3294
+ }
3295
+ /** 换一把新密钥(旧的立即失效)。 */
3296
+ resetKey() {
3297
+ return this.client.json("POST", "/api/phone/key/reset");
3298
+ }
3299
+ /** 作废密钥;设备记录保留,用户下次取密钥会得到一把新的。 */
3300
+ async revokeKey() {
3301
+ await this.client.fetch("DELETE", "/api/phone/key");
3302
+ }
3303
+ async remove(phoneId) {
3304
+ await this.client.fetch("DELETE", `/api/phone/devices/${encodeURIComponent(phoneId)}`);
3305
+ }
3306
+ /** 本次会话能用的手机 + 账号下的其他手机。 */
3307
+ listForSession(sessionId) {
3308
+ return this.client.json(
3309
+ "GET",
3310
+ `/api/sessions/${encodeURIComponent(sessionId)}/phones`
3311
+ );
3312
+ }
3313
+ setEnabled(sessionId, phoneId, enabled) {
3314
+ return this.client.json(
3315
+ "PUT",
3316
+ `/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/enabled`,
3317
+ { enabled }
3318
+ );
3319
+ }
3320
+ health(sessionId, phoneId) {
3321
+ return this.client.json(
3322
+ "GET",
3323
+ `/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/health`
3324
+ );
3325
+ }
3326
+ /**
3327
+ * WHEP 信令:POST 一个 SDP offer,拿到 answer。
3328
+ *
3329
+ * 走 `textFromInit` 而不是 `json()`:SDP 是纯文本,`json()` 会强制序列化成
3330
+ * JSON;也不能用裸 `fetch`,那会丢掉 bearer token。
3331
+ */
3332
+ async whep(sessionId, phoneId, offerSdp) {
3333
+ return this.client.textFromInit(
3334
+ `/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/whep`,
3335
+ {
3336
+ method: "POST",
3337
+ body: offerSdp,
3338
+ headers: { "content-type": "application/sdp" }
3339
+ }
3340
+ );
3341
+ }
3342
+ /** 用户点「刷新画面」:让后台重新确认隧道服务并忘掉记住的 token。 */
3343
+ async wake(sessionId, phoneId) {
3344
+ await this.client.json(
3345
+ "POST",
3346
+ `/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/wake`
3347
+ );
3348
+ }
3349
+ };
3350
+
3351
+ // src/resources/llm.ts
3352
+ var LlmResource = class {
3353
+ constructor(client) {
3354
+ this.client = client;
3355
+ }
3356
+ client;
3357
+ chat = { completions: { create: (body, options = {}) => this.client.jsonFromInit("/api/llm/chat/completions", { method: "POST", body: JSON.stringify(body), signal: options.signal }) } };
3358
+ };
3359
+
3033
3360
  // src/resources/models.ts
3034
3361
  var ModelsResource = class {
3035
3362
  constructor(client) {
3036
3363
  this.client = client;
3037
3364
  }
3038
3365
  client;
3039
- list() {
3040
- return this.client.json("GET", "/api/config/models");
3366
+ list(options = {}) {
3367
+ return this.client.jsonFromInit("/api/config/models", { signal: options.signal });
3368
+ }
3369
+ };
3370
+
3371
+ // src/resources/connectors.ts
3372
+ function isLocalConnectorName(name) {
3373
+ return name.startsWith("connector.personal.") || name.startsWith("connector.builtin.");
3374
+ }
3375
+ var ConnectorsResource = class {
3376
+ constructor(client) {
3377
+ this.client = client;
3378
+ }
3379
+ client;
3380
+ /** Stage an explicit attachment in the current user's SW connection. Reuse requestId on retry. */
3381
+ async uploadFile(name, file, fileName, requestId) {
3382
+ const form = new FormData();
3383
+ form.append("file", file, fileName);
3384
+ form.append("request_id", requestId);
3385
+ const response = await this.client.formData("POST", `/api/connectors/${encodeURIComponent(name)}/files`, form);
3386
+ return response.json();
3387
+ }
3388
+ /** Fetch a private artifact through BA authentication; no SW PAT or public URL is exposed. */
3389
+ downloadFile(name, artifactId) {
3390
+ return this.client.blob("GET", `/api/connectors/${encodeURIComponent(name)}/files/${encodeURIComponent(artifactId)}`);
3391
+ }
3392
+ authorization(name, init) {
3393
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/authorization`, init);
3394
+ }
3395
+ authorize(name, action, pushUrl, options) {
3396
+ return this.client.json("POST", `/api/connectors/${encodeURIComponent(name)}/authorization`, {
3397
+ action,
3398
+ ...options,
3399
+ ...pushUrl ? { push_url: pushUrl } : {}
3400
+ });
3401
+ }
3402
+ authorizationPlan(name, capabilities) {
3403
+ return this.client.json("POST", `/api/connectors/${encodeURIComponent(name)}/authorization`, { action: "plan", capabilities });
3404
+ }
3405
+ diagnostics(name, init) {
3406
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/diagnostics`, init);
3407
+ }
3408
+ create(draft) {
3409
+ return this.client.json("POST", "/api/connectors", draft);
3410
+ }
3411
+ update(name, draft) {
3412
+ return this.client.json("PATCH", `/api/connectors/${encodeURIComponent(name)}`, draft);
3413
+ }
3414
+ delete(name) {
3415
+ return this.client.json("DELETE", `/api/connectors/${encodeURIComponent(name)}`);
3416
+ }
3417
+ /** Create a generation conversation and send its visible Skill request.
3418
+ * Hosts use onCreated only to register caches and navigate before sending. */
3419
+ async startGeneration({ connector, onCreated, initiator = "sdk" } = {}) {
3420
+ const intent = connector ? "\u4FEE\u6539\u8FDE\u63A5\u5668" : "\u521B\u5EFA\u8FDE\u63A5\u5668";
3421
+ const request = connector ? "\u4FEE\u6539\u9009\u5B9A\u7684\u8FDE\u63A5\u5668" : "\u521B\u5EFA\u8FDE\u63A5\u5668";
3422
+ const { session_id } = await this.client.sessions.createSessionWithRequest({ intent, solution_id: "connector_generate", initiator });
3423
+ await onCreated?.({ session_id, intent });
3424
+ const session = await this.client.sessions.connect(session_id);
3425
+ try {
3426
+ const sent = await session.send(`\u8BF7\u4F7F\u7528\u8FDE\u63A5\u5668\u751F\u6210\u5668\uFF0C\u5E2E\u6211${request}\u3002\u5148\u786E\u8BA4\u6211\u5E0C\u671B\u8FDE\u63A5\u7684\u7CFB\u7EDF\u548C\u9700\u8981\u7684\u529F\u80FD\uFF0C\u518D\u6309\u6280\u80FD\u5F15\u5BFC\u6211\u5B8C\u6210\u3002`, {
3427
+ mode: "executing",
3428
+ refs: [{ provider: "skill", id: "generate-connector", label: "\u8FDE\u63A5\u5668\u751F\u6210\u5668" }],
3429
+ ...connector ? { contextAttachments: [{
3430
+ id: "connector-generation-target",
3431
+ label: "\u9009\u5B9A\u7684\u8FDE\u63A5\u5668",
3432
+ content: JSON.stringify({ name: connector.name, display_name: connector.display_name }),
3433
+ update_format: "snapshot"
3434
+ }] } : {}
3435
+ });
3436
+ return { session_id, sent };
3437
+ } finally {
3438
+ session.dispose();
3439
+ }
3440
+ }
3441
+ list(init) {
3442
+ return this.client.jsonFromInit("/api/connectors", init);
3443
+ }
3444
+ listForSession(sessionId, init) {
3445
+ return this.client.jsonFromInit(`/api/connectors?session_id=${encodeURIComponent(sessionId)}`, init);
3446
+ }
3447
+ read(name, init) {
3448
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/connection`, init);
3449
+ }
3450
+ connect(name, update, init) {
3451
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/connection`, {
3452
+ method: "PUT",
3453
+ body: JSON.stringify(update),
3454
+ ...init
3455
+ });
3456
+ }
3457
+ browserAuthorizationUrl(name) {
3458
+ return new URL(`connector-auth/${encodeURIComponent(name)}`, `${this.client.options.baseUrl.replace(/\/$/, "")}/`).toString();
3459
+ }
3460
+ /** One-use, one-minute identity handoff to this client's trusted Blade origin.
3461
+ * Tokens travel only through a source/origin-bound message, never a URL/storage. */
3462
+ bindBrowserAuthorizationFrame(frame, name) {
3463
+ const nonce = Array.from(crypto.getRandomValues(new Uint8Array(32)), (value) => value.toString(16).padStart(2, "0")).join("");
3464
+ const url = new URL(this.browserAuthorizationUrl(name), window.location.href);
3465
+ url.searchParams.set("embedded", "1");
3466
+ url.searchParams.set("handoff", nonce);
3467
+ url.searchParams.set("parent_origin", window.location.origin);
3468
+ const receive = (event) => {
3469
+ if (event.origin !== url.origin || event.source !== frame.contentWindow || event.data?.type !== "blade:connector-auth-ready" || event.data?.nonce !== nonce) return;
3470
+ cleanup();
3471
+ frame.contentWindow?.postMessage({ type: "blade:connector-auth-identity", nonce, token: this.client.token }, url.origin);
3472
+ };
3473
+ const timeout = window.setTimeout(() => cleanup(), 6e4);
3474
+ const cleanup = () => {
3475
+ window.clearTimeout(timeout);
3476
+ window.removeEventListener("message", receive);
3477
+ };
3478
+ window.addEventListener("message", receive);
3479
+ frame.src = url.toString();
3480
+ return cleanup;
3481
+ }
3482
+ async startBrowserAuthorization(name, sessionId) {
3483
+ const view = await this.read(name);
3484
+ if (view.authorization?.type !== "browser") throw new Error("\u8BE5\u8FDE\u63A5\u5668\u6CA1\u6709\u7F51\u9875\u767B\u5F55\u5165\u53E3");
3485
+ const id = sessionId ?? (await this.client.sessions.createSessionWithRequest({
3486
+ intent: `\u8FDE\u63A5 ${view.display_name || "\u4E1A\u52A1\u7CFB\u7EDF"}`,
3487
+ memory_enabled: false
3488
+ })).session_id;
3489
+ await this.client.json("POST", `/api/sessions/${encodeURIComponent(id)}/browser/wake`, {});
3490
+ const tabs = await this.client.json("GET", `/api/sessions/${encodeURIComponent(id)}/browser/tabs`);
3491
+ const hasBusinessTab = tabs.data?.some(({ url }) => url && url !== "about:blank" && !/^http:\/\/(?:127\.0\.0\.1|localhost):9223\/home(?:[/?#]|$)/.test(url));
3492
+ if (!sessionId || !hasBusinessTab) await this.client.json("POST", `/api/sessions/${encodeURIComponent(id)}/browser/tabs`, { url: view.authorization.url });
3493
+ return { session_id: id, view };
3494
+ }
3495
+ verify(name) {
3496
+ return this.client.json("POST", `/api/connectors/${encodeURIComponent(name)}/connection:verify`);
3497
+ }
3498
+ disconnect(name) {
3499
+ return this.client.json("DELETE", `/api/connectors/${encodeURIComponent(name)}/connection`);
3041
3500
  }
3042
3501
  };
3043
3502
 
@@ -3054,12 +3513,12 @@ var SessionInfo = type({
3054
3513
  created_at: "string",
3055
3514
  updated_at: "string",
3056
3515
  "shared?": "boolean",
3516
+ "anonymous?": "boolean",
3057
3517
  "memory_enabled?": "boolean",
3058
3518
  "is_persistent?": "boolean",
3059
3519
  "initiator?": "'ui' | 'sdk' | 'unknown' | null",
3060
3520
  "is_headless?": "boolean",
3061
3521
  "viewer_role?": "'owner' | 'viewer'",
3062
- "template_id?": "string | null",
3063
3522
  "model?": "string | null",
3064
3523
  "enable_thinking?": "boolean | null",
3065
3524
  "solution_id?": "string | null",
@@ -3067,19 +3526,12 @@ var SessionInfo = type({
3067
3526
  "biz_role_id?": "string | null",
3068
3527
  "solution?": "unknown",
3069
3528
  "plan_summary?": "string | null",
3070
- "primary_skill_id?": "string | null",
3071
- // ship-attack v2:后端 engine.set_bound_skill 写入的"绑定 skill id"。
3072
- // 未绑定 / 非 ship-attack session 为 null。
3073
- "bound_skill_id?": "string | null",
3074
3529
  "replay_state?": "unknown",
3075
3530
  "is_pinned?": "boolean",
3076
3531
  "pinned_at?": "string | null",
3077
3532
  "is_example?": "boolean",
3078
3533
  "ports?": "unknown",
3079
3534
  "disable_tools?": "string[]",
3080
- "runtime_type?": "string | null",
3081
- "daemon_id?": "string | null",
3082
- "agent_runtime_id?": "string | null",
3083
3535
  "workspace_path?": "string | null",
3084
3536
  "ba_version?": "string | null",
3085
3537
  "sandbox_version?": "string | null",
@@ -3110,24 +3562,23 @@ function toCreateSessionPayload(request) {
3110
3562
  const solutionRef = request.solution_ref ?? externalSolutionRef(request.solution_id);
3111
3563
  return {
3112
3564
  intent: request.intent ?? "",
3113
- template_id: request.template_id,
3565
+ // The server defaults to sdk; older APIs reject even this redundant field.
3566
+ initiator: request.initiator === "sdk" ? void 0 : request.initiator,
3567
+ anonymous: request.anonymous,
3114
3568
  solution_id: solutionRef ? void 0 : request.solution_id,
3115
3569
  solution_ref: solutionRef,
3116
3570
  biz_role_id: request.biz_role_id ?? null,
3117
3571
  model: request.model ?? null,
3118
3572
  enable_thinking: request.enable_thinking ?? null,
3119
3573
  memory_enabled: request.memory_enabled ?? null,
3120
- primary_skill_id: request.primary_skill_id ?? null,
3121
3574
  env: request.env,
3122
3575
  disable_tools: request.disable_tools ?? null,
3123
3576
  mcp_sources: request.mcp_sources,
3124
3577
  skip_confirmations: request.skip_confirmations,
3125
3578
  session_solution_asset_id: request.session_solution_asset_id ?? null,
3579
+ session_solution_files: request.session_solution_files,
3126
3580
  solution_snapshot_session_id: request.solution_snapshot_session_id ?? null,
3127
3581
  compaction_ratio: request.compaction_ratio ?? null,
3128
- ...request.runtime_type ? { runtime_type: request.runtime_type } : {},
3129
- ...request.daemon_id ? { daemon_id: request.daemon_id } : {},
3130
- ...request.agent_runtime_id ? { agent_runtime_id: request.agent_runtime_id } : {},
3131
3582
  ...request.chat_group_id ? { chat_group_id: request.chat_group_id } : {}
3132
3583
  };
3133
3584
  }
@@ -3174,6 +3625,20 @@ var SessionsResource = class {
3174
3625
  this.pendingImages.set(identity, pending);
3175
3626
  return pending;
3176
3627
  }
3628
+ openFileOpener(sessionId, body, init) {
3629
+ return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/file-openers:open`, {
3630
+ ...init,
3631
+ method: "POST",
3632
+ body: JSON.stringify(body)
3633
+ });
3634
+ }
3635
+ callFileOpener(sessionId, body, init) {
3636
+ return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/file-openers:call`, {
3637
+ ...init,
3638
+ method: "POST",
3639
+ body: JSON.stringify(body)
3640
+ });
3641
+ }
3177
3642
  getMcpApp(sessionId, sourceId, init) {
3178
3643
  return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/mcp-apps/${encodeURIComponent(sourceId)}`, init);
3179
3644
  }
@@ -3215,7 +3680,8 @@ var SessionsResource = class {
3215
3680
  return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/plugins`, init);
3216
3681
  }
3217
3682
  setSessionPluginActivation(sessionId, name, active, init) {
3218
- return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/plugins/${encodeURIComponent(name)}:activation`, { method: "POST", body: JSON.stringify({ active }), ...init });
3683
+ const kind = isLocalConnectorName(name) ? "connectors" : "plugins";
3684
+ return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/${kind}/${encodeURIComponent(name)}:activation`, { method: "POST", body: JSON.stringify({ active }), ...init });
3219
3685
  }
3220
3686
  /**
3221
3687
  * Fetch a plugin's package-local icon as bytes.
@@ -3270,7 +3736,7 @@ var SessionsResource = class {
3270
3736
  return this.createDeclared(request);
3271
3737
  }
3272
3738
  const { session_id } = await this.createSessionWithRequest(request);
3273
- return this.connect(session_id);
3739
+ return request.anonymous ? this.client.forAnonymousSession(session_id).sessions.connect(session_id) : this.connect(session_id);
3274
3740
  }
3275
3741
  async createDeclared(definition) {
3276
3742
  const { intent, solution, skills = [], config } = definition;
@@ -3291,7 +3757,8 @@ var SessionsResource = class {
3291
3757
  memory_enabled: config?.memoryEnabled,
3292
3758
  compaction_ratio: config?.compactionRatio,
3293
3759
  env: config?.env,
3294
- disable_tools: config?.disableTools
3760
+ disable_tools: config?.disableTools,
3761
+ mcp_sources: config?.mcpSources
3295
3762
  });
3296
3763
  session_id = created.session_id;
3297
3764
  } catch (error) {
@@ -3357,7 +3824,6 @@ var SessionsResource = class {
3357
3824
  fetchSessionsPage({
3358
3825
  limit,
3359
3826
  offset,
3360
- template_id_prefix,
3361
3827
  solution_id,
3362
3828
  solution_registry_id,
3363
3829
  q,
@@ -3366,7 +3832,6 @@ var SessionsResource = class {
3366
3832
  const searchParams = new URLSearchParams();
3367
3833
  searchParams.set("limit", String(limit));
3368
3834
  searchParams.set("offset", String(offset));
3369
- if (template_id_prefix) searchParams.set("template_id_prefix", template_id_prefix);
3370
3835
  if (solution_registry_id) {
3371
3836
  searchParams.set("solution_registry_id", solution_registry_id);
3372
3837
  } else if (solution_id) {
@@ -3377,12 +3842,12 @@ var SessionsResource = class {
3377
3842
  if (chat_group_id) searchParams.set("chat_group_id", chat_group_id);
3378
3843
  return this.client.json("GET", `/api/sessions?${searchParams.toString()}`);
3379
3844
  }
3380
- async listSessions(template_id_prefix, solution_id) {
3845
+ async listSessions(solution_id) {
3381
3846
  const pageSize = 100;
3382
3847
  const sessions = [];
3383
3848
  let offset = 0;
3384
3849
  while (true) {
3385
- const page = await this.fetchSessionsPage({ limit: pageSize, offset, template_id_prefix, solution_id });
3850
+ const page = await this.fetchSessionsPage({ limit: pageSize, offset, solution_id });
3386
3851
  sessions.push(...page.items);
3387
3852
  if (sessions.length >= page.total || page.items.length === 0) return sessions;
3388
3853
  offset += page.items.length;
@@ -3399,8 +3864,8 @@ var SessionsResource = class {
3399
3864
  if (params.limit !== void 0) searchParams.set("limit", String(params.limit));
3400
3865
  return this.client.json("GET", `/api/search?${searchParams.toString()}`);
3401
3866
  }
3402
- createSession(intent, template_id, primary_skill_id) {
3403
- return this.createSessionWithRequest({ intent, template_id, primary_skill_id });
3867
+ createSession(intent) {
3868
+ return this.createSessionWithRequest({ intent });
3404
3869
  }
3405
3870
  createSessionWithRequest(request) {
3406
3871
  return this.client.json("POST", "/api/sessions", toCreateSessionPayload(request));
@@ -3418,6 +3883,13 @@ var SessionsResource = class {
3418
3883
  updateSession(sessionId, payload) {
3419
3884
  return this.client.json("PATCH", `/api/sessions/${sessionId}`, payload);
3420
3885
  }
3886
+ getSessionConfiguration(sessionId, init) {
3887
+ return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/configuration`, init);
3888
+ }
3889
+ /** Updates atomically between turns. A running/handoff session returns HTTP 409. */
3890
+ updateSessionConfiguration(sessionId, request) {
3891
+ return this.client.json("PATCH", `/api/sessions/${encodeURIComponent(sessionId)}/configuration`, request);
3892
+ }
3421
3893
  setSessionEnv(sessionId, env) {
3422
3894
  return this.client.json("PUT", `/api/sessions/${sessionId}/env`, { env });
3423
3895
  }
@@ -3458,6 +3930,10 @@ var SessionsResource = class {
3458
3930
  getSessionTasks(sessionId) {
3459
3931
  return this.client.json("GET", `/api/sessions/${sessionId}/tasks`);
3460
3932
  }
3933
+ /** Durable result for this execution; null until its run_end is committed. Owner only. */
3934
+ getRunResult(sessionId, runId) {
3935
+ return this.client.json("GET", `/api/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`);
3936
+ }
3461
3937
  async getSessionTurns(sessionId) {
3462
3938
  const entries = await this.client.json(
3463
3939
  "GET",
@@ -3568,6 +4044,12 @@ var SessionsResource = class {
3568
4044
  checkpoint_id: checkpointId
3569
4045
  });
3570
4046
  }
4047
+ listAnonymousSessions() {
4048
+ return this.client.json("GET", "/api/anonymous-sessions");
4049
+ }
4050
+ deleteAnonymousSession(sessionId) {
4051
+ return this.client.json("DELETE", `/api/anonymous-sessions/${encodeURIComponent(sessionId)}`);
4052
+ }
3571
4053
  deleteSession(sessionId, options) {
3572
4054
  const query = options?.deleteWorkspace ? "?delete_workspace=true" : "";
3573
4055
  return this.client.json("DELETE", `/api/sessions/${sessionId}${query}`);
@@ -3790,6 +4272,19 @@ var PluginsResource = class {
3790
4272
  this.client = client;
3791
4273
  }
3792
4274
  client;
4275
+ catalogSnapshot;
4276
+ pendingCatalog;
4277
+ catalogListeners = /* @__PURE__ */ new Set();
4278
+ /** Observe the directory loaded by existing plugin surfaces without starting a request. */
4279
+ getCatalogSnapshot() {
4280
+ return this.catalogSnapshot?.token === this.client.token ? this.catalogSnapshot?.entries : void 0;
4281
+ }
4282
+ subscribeCatalog(listener) {
4283
+ this.catalogListeners.add(listener);
4284
+ return () => {
4285
+ this.catalogListeners.delete(listener);
4286
+ };
4287
+ }
3793
4288
  /**
3794
4289
  * 列出当前用户安装的插件及其展示信息。
3795
4290
  *
@@ -3797,7 +4292,24 @@ var PluginsResource = class {
3797
4292
  * 单个插件的展示信息读不出来只会降级成占位,不会让整份目录失败。
3798
4293
  */
3799
4294
  catalog(init) {
3800
- return this.client.jsonFromInit("/api/plugins/catalog", init);
4295
+ const token = this.client.token;
4296
+ if (!init && this.pendingCatalog && this.pendingCatalog.token === token) return this.pendingCatalog.request;
4297
+ const request = this.client.jsonFromInit("/api/plugins/catalog", init).then((result) => {
4298
+ if (token === this.client.token) {
4299
+ this.catalogSnapshot = { token, entries: result.plugins };
4300
+ for (const listener of this.catalogListeners) listener();
4301
+ }
4302
+ return result;
4303
+ }).finally(() => {
4304
+ if (this.pendingCatalog?.request === request) this.pendingCatalog = void 0;
4305
+ });
4306
+ if (!init) this.pendingCatalog = { token, request };
4307
+ return request;
4308
+ }
4309
+ /** Load once on demand; share both the snapshot and any request already in flight. */
4310
+ ensureCatalog() {
4311
+ const plugins = this.getCatalogSnapshot();
4312
+ return plugins ? Promise.resolve({ plugins }) : this.catalog();
3801
4313
  }
3802
4314
  /** 取一个插件的包内图标字节(用户级,不需要会话)。 */
3803
4315
  fetchIcon(name) {
@@ -3969,7 +4481,6 @@ var SiteVisitsResource = class {
3969
4481
  try {
3970
4482
  const response = await (this.client.options.fetchImpl ?? fetch)(url.toString(), {
3971
4483
  method,
3972
- // 访客 Cookie 是唯一的去重依据,必须随请求往返。
3973
4484
  credentials: "include",
3974
4485
  signal: controller.signal
3975
4486
  });
@@ -3983,6 +4494,20 @@ var SiteVisitsResource = class {
3983
4494
  }
3984
4495
  };
3985
4496
 
4497
+ // src/server-clock.ts
4498
+ var clocks = /* @__PURE__ */ new WeakMap();
4499
+ function syncServerTime(client, timestamp, receivedAt = performance.now()) {
4500
+ if (typeof timestamp !== "string") return;
4501
+ const serverTime = Date.parse(timestamp);
4502
+ if (!Number.isFinite(serverTime)) return;
4503
+ const current = getServerTime(client, receivedAt);
4504
+ clocks.set(client, { serverTime: Math.max(serverTime, current ?? serverTime), receivedAt });
4505
+ }
4506
+ function getServerTime(client, now = performance.now()) {
4507
+ const clock = client ? clocks.get(client) : void 0;
4508
+ return clock ? clock.serverTime + Math.max(0, now - clock.receivedAt) : null;
4509
+ }
4510
+
3986
4511
  // src/session/background.ts
3987
4512
  var BACKGROUND_STATUSES = [
3988
4513
  "starting",
@@ -4427,15 +4952,8 @@ function contentPreview(content, maxLen = 80) {
4427
4952
  const text = getTextContent(content).trim();
4428
4953
  return text.length > maxLen ? `${text.slice(0, maxLen)}\u2026` : text;
4429
4954
  }
4430
- function transformSlashCommand(skillName, rawInput, { local = true, installed = true } = {}) {
4431
- const prompt = rawInput.replace(`<skill>${skillName}</skill>`, "").trim();
4432
- if (local) {
4433
- return prompt ? `\u8BF7\u4F7F\u7528 ${skillName} skill \u5B8C\u6210\u4EFB\u52A1
4434
- ${prompt}` : `\u8BF7\u4F7F\u7528 ${skillName} skill \u5B8C\u6210\u4EFB\u52A1`;
4435
- }
4436
- const steps = installed ? `\u8BF7\u5148\u8FD0\u884C blade hub skill use ${skillName} \u52A0\u8F7D\u6280\u80FD` : `\u8BE5\u6280\u80FD\u5C1A\u672A\u5B89\u88C5\u3002\u8BF7\u5148\u8FD0\u884C blade hub skill install ${skillName} \u5B89\u88C5\uFF0C\u518D\u8FD0\u884C blade hub skill use ${skillName} \u52A0\u8F7D`;
4437
- return prompt ? `${steps}\uFF0C\u7136\u540E\u5B8C\u6210\u4EFB\u52A1\uFF1A
4438
- ${prompt}` : `${steps}\uFF0C\u7136\u540E\u4F7F\u7528\u5B83\u5B8C\u6210\u4EFB\u52A1`;
4955
+ function transformSlashCommand(skillName, rawInput, _availability = {}) {
4956
+ return rawInput.replace(`<skill>${skillName}</skill>`, `@${skillName}`).trim();
4439
4957
  }
4440
4958
  var ATTACHMENT_TAG_RE = /\[附件:\s*([^\]]+)\](?:[ \t]*已上传到工作区路径:[ \t]*([^\r\n]+))?/g;
4441
4959
  var CONTEXT_PART_RE = /^\[上下文:\s*([^\]]+)\]\n([\s\S]*)$/;
@@ -4563,7 +5081,13 @@ function workflowEntriesFromOutput(output) {
4563
5081
  }
4564
5082
  function workflowNameFromArguments(argumentsJson) {
4565
5083
  try {
4566
- const name = JSON.parse(argumentsJson)?.name;
5084
+ const args = JSON.parse(argumentsJson);
5085
+ const skillId = typeof args?.skill_id === "string" ? args.skill_id.trim() : "";
5086
+ if (skillId) {
5087
+ const flow = typeof args?.flow === "string" ? args.flow.trim() : "";
5088
+ return `\u6280\u80FD\u300C${skillId}\u300D${flow && flow !== "main" ? ` \xB7 \u6D41\u7A0B ${flow}` : ""}`;
5089
+ }
5090
+ const name = args?.name;
4567
5091
  return typeof name === "string" ? name : "";
4568
5092
  } catch {
4569
5093
  return "";
@@ -4587,6 +5111,15 @@ function applyWorkflowEvent(current, toolCallId, type2, payload) {
4587
5111
  }
4588
5112
  const base = current ?? { toolCallId, name: "", status: "running", entries: [] };
4589
5113
  if (type2 === "workflow:step") {
5114
+ const settled = asText(payload.status);
5115
+ const stepId = asText(payload.step_id);
5116
+ if (stepId && isFinished(settled)) {
5117
+ const index = base.entries.findIndex((entry) => entry.kind === "step" && entry.stepId === stepId);
5118
+ if (index === -1) return null;
5119
+ const entries = [...base.entries];
5120
+ entries[index] = { ...entries[index], status: settled };
5121
+ return { ...base, entries };
5122
+ }
4590
5123
  return {
4591
5124
  ...base,
4592
5125
  entries: [
@@ -4601,7 +5134,9 @@ function applyWorkflowEvent(current, toolCallId, type2, payload) {
4601
5134
  };
4602
5135
  }
4603
5136
  if (type2 === "workflow:log") {
4604
- return { ...base, entries: [...base.entries, { kind: "log", text: asText(payload.text) }] };
5137
+ const stepId = asText(payload.step_id);
5138
+ const entry = stepId ? { kind: "log", text: asText(payload.text), stepId } : { kind: "log", text: asText(payload.text) };
5139
+ return { ...base, entries: [...base.entries, entry] };
4605
5140
  }
4606
5141
  if (type2 === "workflow:run:end") {
4607
5142
  const status = asText(payload.status);
@@ -4623,10 +5158,10 @@ function rebuildWorkflowRuns(turns, previous) {
4623
5158
  const name = workflowNameFromArguments(toolCall.arguments);
4624
5159
  const prior = previous[toolCall.id];
4625
5160
  if (isFinished(toolCall.status)) {
4626
- const entries = workflowEntriesFromOutput(
4627
- typeof toolCall.result === "string" ? toolCall.result.trim() : ""
4628
- );
4629
- runs[toolCall.id] = prior && prior.status === toolCall.status && prior.name === name && JSON.stringify(prior.entries) === JSON.stringify(entries) ? prior : { toolCallId: toolCall.id, name, status: toolCall.status, entries };
5161
+ const steps = toolCall.workflow_steps ?? [];
5162
+ const entries = steps.length > 0 ? workflowEntriesFromSteps(steps) : workflowEntriesFromOutput(typeof toolCall.result === "string" ? toolCall.result.trim() : "");
5163
+ const status = toolCall.status === "error" && workflowRunCancelled(steps) ? "cancelled" : toolCall.status;
5164
+ runs[toolCall.id] = prior && prior.status === status && prior.name === name && JSON.stringify(prior.entries) === JSON.stringify(entries) ? prior : { toolCallId: toolCall.id, name, status, entries };
4630
5165
  continue;
4631
5166
  }
4632
5167
  runs[toolCall.id] = prior && prior.name === name ? prior : { toolCallId: toolCall.id, name, status: prior?.status ?? "running", entries: prior?.entries ?? [] };
@@ -4662,6 +5197,7 @@ function createInitialSessionState(sessionId) {
4662
5197
  mode: null,
4663
5198
  connection: "disconnected",
4664
5199
  errorMessage: null,
5200
+ lastRun: null,
4665
5201
  askAnswers: {},
4666
5202
  agentLoops: {},
4667
5203
  activeCompaction: null,
@@ -4756,14 +5292,12 @@ function parentForkToolCallIdFromTurn(turn) {
4756
5292
  }
4757
5293
  return null;
4758
5294
  }
4759
- function buildMessageContent2(turn) {
4760
- const textBlocks = turn.blocks.filter((block) => block.type === "text");
4761
- if (textBlocks.length === 0) return "";
4762
- if (textBlocks.length === 1) return normalizeMessageContent(textBlocks[0].content);
4763
- return textBlocks.map((block) => {
4764
- if (typeof block.content === "string") return block.content;
4765
- return JSON.stringify(block.content);
4766
- }).join("");
5295
+ function messageContentFromTurn(turn) {
5296
+ const contents = turn.blocks.filter((block) => block.type === "text").map((block) => normalizeMessageContent(block.content));
5297
+ if (contents.length === 0) return "";
5298
+ if (contents.length === 1) return contents[0];
5299
+ if (contents.every((content) => typeof content === "string")) return contents.join("");
5300
+ return contents.flatMap((content) => typeof content === "string" ? [{ type: "text", text: content }] : content);
4767
5301
  }
4768
5302
  function workspaceNotificationContent(turn) {
4769
5303
  const block = turn.blocks.find(
@@ -4869,7 +5403,7 @@ function projectionToMessage(turn) {
4869
5403
  ...turn.started_at ? { timestamp: turn.started_at } : {}
4870
5404
  };
4871
5405
  }
4872
- const content = buildMessageContent2(turn) || workspaceNotificationContent(turn);
5406
+ const content = messageContentFromTurn(turn) || workspaceNotificationContent(turn);
4873
5407
  const reasoning = buildReasoning(turn);
4874
5408
  const toolCalls = turn.tool_calls.length > 0 ? turn.tool_calls.map((toolCall) => ({
4875
5409
  id: toolCall.id,
@@ -4879,6 +5413,7 @@ function projectionToMessage(turn) {
4879
5413
  result: toolCall.result ?? void 0,
4880
5414
  ...toolCall.evidence ? { evidence: toolCall.evidence } : {},
4881
5415
  pending_question_ref: toolCall.pending_question_ref ?? void 0,
5416
+ workflow_steps: toolCall.workflow_steps ?? void 0,
4882
5417
  status: toolCall.status === "pending" || toolCall.status === "awaiting_answer" || toolCall.status === "done" || toolCall.status === "error" || toolCall.status === "cancelled" ? toolCall.status : "pending",
4883
5418
  ...typeof toolCall.duration_ms === "number" ? { duration_ms: toolCall.duration_ms } : {}
4884
5419
  })) : void 0;
@@ -4893,11 +5428,13 @@ function projectionToMessage(turn) {
4893
5428
  ...toolCalls ? { tool_calls: toolCalls } : {},
4894
5429
  loop_name: turn.loop_id,
4895
5430
  entry_id: turn.turn_id,
5431
+ ...turn.client_request_id ? { client_request_id: turn.client_request_id } : {},
4896
5432
  status: turn.status,
4897
5433
  ...typeof turn.duration_ms === "number" ? { duration_ms: turn.duration_ms } : {},
4898
5434
  ...turn.started_at ? { timestamp: turn.started_at } : {},
4899
5435
  ...turn.memory_refs?.length ? { memory_refs: turn.memory_refs } : {},
4900
5436
  ...turn.refs?.length ? { refs: turn.refs } : {},
5437
+ ...turn.context_attachments?.length ? { context_attachments: turn.context_attachments } : {},
4901
5438
  ...turn.topic_asset_refs?.length ? { topic_asset_refs: turn.topic_asset_refs } : {}
4902
5439
  };
4903
5440
  }
@@ -5125,8 +5662,6 @@ function withTurns(state, turns) {
5125
5662
  activeCompaction,
5126
5663
  askAnswers,
5127
5664
  mode: latestMode ?? state.mode,
5128
- // 历史恢复时 chat:end(paused) 可能已不在 socket replay 缓存中;
5129
- // awaiting_answer 是投影里的持久权威状态,必须据此恢复问答交互。
5130
5665
  status: isWaitingForInput ? "waiting_for_input" : state.status
5131
5666
  };
5132
5667
  }
@@ -5135,18 +5670,16 @@ function withQueue(state, snapshot2) {
5135
5670
  return { ...state, queue: snapshot2 };
5136
5671
  }
5137
5672
  var localTurnCounter = 0;
5138
- function addUserMessage(state, content, clientRequestId, topicAssetRefs, refs) {
5673
+ function addUserMessage(state, content, clientRequestId, topicAssetRefs, refs, contextAttachments) {
5139
5674
  localTurnCounter += 1;
5140
5675
  const turnId = `local-user-${clientRequestId ?? `${Date.now()}-${localTurnCounter}`}`;
5141
5676
  const optimisticTurn = {
5142
5677
  id: turnId,
5143
5678
  sequence: Math.max(0, ...state.turns.map((turn) => turn.sequence)) + 1,
5144
5679
  turn_id: turnId,
5145
- // 乐观态就自赋,跟服务端确认后 reconcileUserTurns 补上的
5146
- // client_render_id(= 乐观 turn 自己的 turn_id)保持同一个值,
5147
- // 消费方才能拿它当"确认前后不变"的稳定标识使用。
5148
5680
  client_render_id: turnId,
5149
5681
  ...refs ? { refs } : {},
5682
+ ...contextAttachments?.length ? { context_attachments: contextAttachments } : {},
5150
5683
  ...topicAssetRefs?.length ? { topic_asset_refs: topicAssetRefs } : {},
5151
5684
  loop_id: "root",
5152
5685
  role: "user",
@@ -5347,9 +5880,7 @@ var AgentSession = class _AgentSession {
5347
5880
  logCursor = new LogCursor();
5348
5881
  sessionId;
5349
5882
  state;
5350
- /** status 每变化一次加一(单调递增)。异步读取会话详情时据此判断请求期间状态是否变过,避免 running→终态→running 这类来回被误认为「没变」。 */
5351
5883
  statusRevision = 0;
5352
- /** 实时事件写入 status 时调用:值不变也要记一次,才能识别请求期间收到过更新的状态。 */
5353
5884
  noteLiveStatus() {
5354
5885
  this.statusRevision += 1;
5355
5886
  }
@@ -5364,15 +5895,10 @@ var AgentSession = class _AgentSession {
5364
5895
  patchFlushCancel = null;
5365
5896
  joined = false;
5366
5897
  joinPending = null;
5367
- // bootstrap 与每次 reconnect 共用一条订阅生命周期队列。它们都会重置 join
5368
- // 状态并临时设置 replay source,禁止并发,否则较早操作的 finally 会清掉
5369
- // 较晚操作仍在使用的来源上下文。
5370
5898
  subscriptionQueue = Promise.resolve();
5371
5899
  replaceQueue = Promise.resolve();
5372
5900
  timelineEpoch = 0;
5373
- /** 定位请求的流水号:被后一次选择取代的那次定位不再提交窗口(见 locateEntry)。 */
5374
5901
  locateToken = 0;
5375
- /** 在途那次定位的请求句柄。**只**服务定位:权威刷新不共用它(见 cancelPendingLocate)。 */
5376
5902
  locateAbort = null;
5377
5903
  pagingGeneration = 0;
5378
5904
  liveRevision = 0;
@@ -5381,14 +5907,7 @@ var AgentSession = class _AgentSession {
5381
5907
  pendingOptimisticTurnIds = /* @__PURE__ */ new Set();
5382
5908
  olderPending = null;
5383
5909
  replaceInFlight = 0;
5384
- // 回放控制请求排成一条队列。连着点"5x"再点"退出回放"时,并发发出去的两个
5385
- // 请求响应可能乱序回来,晚到的旧值会把已经退出的会话又显示成回放中;用
5386
- // 序号丢弃过期响应又会在失败时留下中间态。串行执行就没有这些情况:每个
5387
- // 响应都是当时最新的,失败也只影响自己。
5388
5910
  replayQueue = Promise.resolve();
5389
- // Historical snapshots and live commands share one delivery barrier. A
5390
- // repair closes the barrier before joining, snapshots the raw command log
5391
- // after the join, then releases buffered commands in socket arrival order.
5392
5911
  commandRestoreQueue = Promise.resolve();
5393
5912
  commandRecoveryGeneration = 0;
5394
5913
  commandRestoreRetryAttempt = 0;
@@ -5396,33 +5915,21 @@ var AgentSession = class _AgentSession {
5396
5915
  bufferedCommandDeliveries = null;
5397
5916
  pendingReplayMessage = null;
5398
5917
  pendingReplayMode;
5918
+ pendingReplayRequestId;
5919
+ pendingReplayAttachments;
5399
5920
  pendingReplayRefs;
5400
5921
  pendingReplayTopicAssetRefs;
5401
5922
  recentChatEndAt = 0;
5402
- /**
5403
- * 最近一次已经通过 `error` 事件投递过的服务端失败(`message` + `code`)。
5404
- *
5405
- * `chat:send` 被代理时服务端会先发 `system:error`、再用同一条失败回 ack,两条
5406
- * 通道都会到达这里:前者走 `_handleSystemError`,后者走发送失败的回滚。不去重
5407
- * 的话调用方会收到两次同一个 `error`(重复提示、重试逻辑跑两遍)。
5408
- *
5409
- * 带代际边界,只认「本次 `emitWithAck` 等待期间」投递的那一条:否则队列/停止
5410
- * 失败留下的标记会一直挂着,之后一次无关的订阅失败只是文案码相同就被当成
5411
- * 重复而静音。用单调递增的代际号而不是时间戳,同一毫秒内的两条也不会混淆。
5412
- */
5413
5923
  lastDeliveredSystemError = null;
5414
- /** 每次投递 `system:error` 递增,用于判定某条失败是否属于本次等待。 */
5415
5924
  systemErrorGeneration = 0;
5416
5925
  subscriptionReplaySource = null;
5417
5926
  disposed = false;
5418
5927
  getAppContext = null;
5419
5928
  sendPending = false;
5420
5929
  manualCompactionRequest = null;
5421
- /** Reload requests from retracts/epoch changes; done only when a reload started after the latest one succeeds. */
5422
5930
  epochReloadRequested = 0;
5423
5931
  epochReloadDone = 0;
5424
5932
  epochReloadRunning = false;
5425
- /** 手动整理的在途标记,同时写进状态(界面据此保持「正在整理」,见 SessionState.compactionPending)。 */
5426
5933
  setManualCompactionRequest(request) {
5427
5934
  this.manualCompactionRequest = request;
5428
5935
  const pending = request !== null;
@@ -5435,16 +5942,8 @@ var AgentSession = class _AgentSession {
5435
5942
  if (request.runId === null) request.finishedBeforeAck.add(runId);
5436
5943
  else if (request.runId === runId) this.setManualCompactionRequest(null);
5437
5944
  }
5438
- /** 最近一次还在等服务端结果的发送请求 id;排队中断的 chat:end 据此判断回滚是否过期。 */
5439
5945
  pendingChatRequestId = null;
5440
- /** 会话详情给出的运行时类型;"native" 时启用原生智能体的投影规则(见 _handleTurnEvents / _handleChatEnd)。 */
5441
- runtimeType = null;
5442
- /** workflow_run_id → 触发它的 workflow:run 工具调用 id(只有 run:start 事件带工具调用 id)。 */
5443
5946
  workflowRunToolCalls = /* @__PURE__ */ new Map();
5444
- /**
5445
- * 第一方 Web 的精简模式传输优化:订阅时是否要 token 级事件。null 表示宿主没设置,订阅时不带这个字段。
5446
- * `desiredStreamTokens` 是宿主最新的选择;运行中不切换,等这一轮结束再重订阅。
5447
- */
5448
5947
  desiredStreamTokens = null;
5449
5948
  joinedStreamTokens = null;
5450
5949
  deliveredCommandKeys = /* @__PURE__ */ new Set();
@@ -5482,11 +5981,8 @@ var AgentSession = class _AgentSession {
5482
5981
  emitWithAck: async () => readonlyError(),
5483
5982
  ensureConnected: readonlyError,
5484
5983
  fetchTurnsPage: async () => ({ turns, nextBefore: null, currentMode: "executing" }),
5485
- // 静态会话(分享页)没有会话目录接口,宿主用已加载的历史兜底条目。
5486
5984
  fetchTurnIndex: async () => ({ sessionId, items: [] }),
5487
5985
  fetchCommands: async () => [],
5488
- // 静态历史没有回放身份可言,给个空详情即可,不要抛错——_bootstrap
5489
- // 不会跑到这里,但保持只读语义一致。
5490
5986
  fetchSessionInfo: async () => ({ replay_state: null }),
5491
5987
  updateReplay: async () => readonlyError(),
5492
5988
  listDir: async () => readonlyError(),
@@ -5505,7 +6001,6 @@ var AgentSession = class _AgentSession {
5505
6001
  };
5506
6002
  return session;
5507
6003
  }
5508
- // ---------------------------------------------------------------- 状态订阅
5509
6004
  /** 返回当前会话快照。引用稳定:状态未变化时返回同一对象。 */
5510
6005
  getState() {
5511
6006
  return this.state;
@@ -5627,11 +6122,6 @@ var AgentSession = class _AgentSession {
5627
6122
  if (this.disposed || !response || response.ok === false || typeof response.is_running !== "boolean") return;
5628
6123
  this._applyRunningState(response.is_running, liveRevision);
5629
6124
  }
5630
- /**
5631
- * timeline 被整体改写(rewind / checkout / 释放):推进纪元,并把在途定位请求一并中止
5632
- * ——它已经属于旧 timeline,却还占着替换队列,会让改写后的权威窗口排在后面等它跑完。
5633
- * 作废号仍然保留:中止只是让它更早结束。
5634
- */
5635
6125
  invalidateTimeline() {
5636
6126
  this.timelineEpoch += 1;
5637
6127
  this.locateAbort?.abort();
@@ -5669,7 +6159,6 @@ var AgentSession = class _AgentSession {
5669
6159
  update(fn) {
5670
6160
  this.setState(fn(this.state));
5671
6161
  }
5672
- // ---------------------------------------------------------------- 语义事件
5673
6162
  /** 监听语义事件(底层逃生舱,见 events.ts)。返回取消函数。 */
5674
6163
  on(name, handler) {
5675
6164
  return this.emitter.on(name, handler);
@@ -5686,7 +6175,6 @@ var AgentSession = class _AgentSession {
5686
6175
  onCommand(action, handler) {
5687
6176
  return this.commands.onCommand(action, handler);
5688
6177
  }
5689
- // ---------------------------------------------------------------- 动作
5690
6178
  /**
5691
6179
  * 声明当前应用提供的页面上下文和业务 CLI。
5692
6180
  *
@@ -5697,10 +6185,94 @@ var AgentSession = class _AgentSession {
5697
6185
  this.getAppContext = options.getContext;
5698
6186
  return attachment;
5699
6187
  }
6188
+ /** 立即为整个会话切换模型,并接续因模型故障停下的任务。 */
6189
+ async selectModel(model) {
6190
+ try {
6191
+ await this.ensureJoined();
6192
+ const response = await this.runtime.emitWithAck("chat:model", { session_id: this.sessionId, model }, 3e4);
6193
+ if (response?.status !== "ok") throw new Error(typeof response?.message === "string" ? response.message : "\u6A21\u578B\u5207\u6362\u5931\u8D25");
6194
+ return true;
6195
+ } catch (error) {
6196
+ const failure = describeSessionError(error, "\u6A21\u578B\u5207\u6362\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
6197
+ this.update((state) => addErrorMessage(state, failure.message));
6198
+ this.emitter.emit("error", { message: failure.message });
6199
+ return false;
6200
+ }
6201
+ }
6202
+ /** Prepare a durable text input without sending any network request. */
6203
+ prepareSend(content, options = {}) {
6204
+ if (!content.trim()) throw new Error("\u6D88\u606F\u4E0D\u80FD\u4E3A\u7A7A");
6205
+ if (Object.keys(options).some((key) => !["mode", "model", "thinkingOverride", "reasoningLevel", "contextAttachments", "queueWhenRunning", "headless"].includes(key))) {
6206
+ throw new Error("\u53EF\u9760\u6587\u672C\u53D1\u9001\u4E0D\u652F\u6301\u8FD9\u4E9B\u53C2\u6570\uFF0C\u8BF7\u4F7F\u7528 send()");
6207
+ }
6208
+ const snapshot2 = JSON.parse(JSON.stringify(options));
6209
+ if (snapshot2.contextAttachments) snapshot2.contextAttachments = snapshotContextAttachments(snapshot2.contextAttachments);
6210
+ return { sessionId: this.sessionId, requestId: createClientRequestId(), content, options: snapshot2 };
6211
+ }
6212
+ /** Durably send a text input with its saved delivery intent. Retries must reuse the saved request. */
6213
+ async sendPrepared(request) {
6214
+ if (request.sessionId !== this.sessionId) throw new Error("\u53D1\u9001\u8BF7\u6C42\u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD");
6215
+ try {
6216
+ this.runtime.ensureConnected();
6217
+ const response = await this.runtime.emitWithAck("chat:append", {
6218
+ session_id: this.sessionId,
6219
+ client_request_id: request.requestId,
6220
+ message: request.content,
6221
+ prepared_options: {
6222
+ mode: request.options.mode,
6223
+ model: request.options.model,
6224
+ ...request.options.headless !== void 0 ? { headless: request.options.headless } : {},
6225
+ ...request.options.queueWhenRunning !== void 0 ? { queue_when_running: request.options.queueWhenRunning } : {},
6226
+ thinking_override: request.options.thinkingOverride,
6227
+ reasoning_level: request.options.reasoningLevel,
6228
+ ...request.options.contextAttachments ? { context_attachments: request.options.contextAttachments } : {}
6229
+ }
6230
+ }, QUEUE_ACK_TIMEOUT_MS);
6231
+ const result = parseQueueAck(response, this.sessionId);
6232
+ if (result.snapshot) this.update((state) => withQueue(state, result.snapshot));
6233
+ if (!result.ok) return {
6234
+ requestId: request.requestId,
6235
+ status: response?.status === "conflict" ? "rejected" : "unknown",
6236
+ message: result.message ?? void 0
6237
+ };
6238
+ const delivery = response?.delivery;
6239
+ if (!isRecord(delivery) || delivery.status !== "accepted") return { requestId: request.requestId, status: "unknown" };
6240
+ return {
6241
+ requestId: request.requestId,
6242
+ status: "accepted",
6243
+ itemId: typeof delivery.item_id === "string" ? delivery.item_id : void 0,
6244
+ queueStatus: typeof delivery.queue_status === "string" ? delivery.queue_status : void 0,
6245
+ executionId: typeof delivery.execution_id === "string" ? delivery.execution_id : null
6246
+ };
6247
+ } catch {
6248
+ return { requestId: request.requestId, status: "unknown" };
6249
+ }
6250
+ }
6251
+ /** Owner-authorized lookup; receipts remain until the session is deleted. */
6252
+ async getDelivery(requestId) {
6253
+ try {
6254
+ this.runtime.ensureConnected();
6255
+ const response = await this.runtime.emitWithAck("chat:queue:request", {
6256
+ session_id: this.sessionId,
6257
+ client_request_id: requestId
6258
+ }, QUEUE_ACK_TIMEOUT_MS);
6259
+ if (response?.status === "accepted") return {
6260
+ requestId,
6261
+ status: "accepted",
6262
+ itemId: typeof response.item_id === "string" ? response.item_id : void 0,
6263
+ queueStatus: typeof response.queue_status === "string" ? response.queue_status : void 0,
6264
+ executionId: typeof response.execution_id === "string" ? response.execution_id : null
6265
+ };
6266
+ if (response?.status === "not_found") return { requestId, status: "not_found" };
6267
+ return { requestId, status: "unknown", message: typeof response?.message === "string" ? response.message : void 0 };
6268
+ } catch {
6269
+ return { requestId, status: "unknown" };
6270
+ }
6271
+ }
5700
6272
  /** 发送一条消息。字符串或多模态内容均可。 */
5701
6273
  async send(content, options = {}) {
5702
6274
  this.runtime.ensureConnected();
5703
- if (this.state.isStreaming && options.queueWhenRunning !== true || this.state.activeCompaction || this.sendPending || this.manualCompactionRequest) {
6275
+ if (this.state.activeCompaction || this.sendPending || this.manualCompactionRequest) {
5704
6276
  this.update(
5705
6277
  (s) => addErrorMessage(s, "\u5F53\u524D\u56DE\u590D\u5C1A\u672A\u7ED3\u675F\u6216\u5BF9\u8BDD\u6B63\u5728\u6574\u7406\uFF0C\u8BF7\u7A0D\u540E\u518D\u53D1\u9001\u3002")
5706
6278
  );
@@ -5809,10 +6381,6 @@ var AgentSession = class _AgentSession {
5809
6381
  async refreshQueue() {
5810
6382
  return this.runQueueCommand("chat:queue:list", { session_id: this.sessionId });
5811
6383
  }
5812
- /**
5813
- * 发出一条队列命令并安装 ack 里的快照。
5814
- * 传输层失败(超时 / 断线)会 reject,由调用方决定是否重试。
5815
- */
5816
6384
  async requestQueueAck(event, payload) {
5817
6385
  this.runtime.ensureConnected();
5818
6386
  const response = await this.runtime.emitWithAck(event, payload, QUEUE_ACK_TIMEOUT_MS);
@@ -5821,7 +6389,6 @@ var AgentSession = class _AgentSession {
5821
6389
  if (snapshot2) this.update((state) => withQueue(state, snapshot2));
5822
6390
  return result;
5823
6391
  }
5824
- /** 队列命令的对外入口:传输失败只体现为失败结果,不向调用方抛异常。 */
5825
6392
  async runQueueCommand(event, payload) {
5826
6393
  try {
5827
6394
  return await this.requestQueueAck(event, payload);
@@ -5830,15 +6397,16 @@ var AgentSession = class _AgentSession {
5830
6397
  }
5831
6398
  }
5832
6399
  async sendUnlocked(content, options) {
6400
+ const contextAttachments = options.contextAttachments ? snapshotContextAttachments(options.contextAttachments) : void 0;
5833
6401
  await this.ensureIdleBeforeSend();
5834
- if (this.state.isStreaming && options.queueWhenRunning !== true || this.state.activeCompaction || this.manualCompactionRequest) {
6402
+ if (this.state.activeCompaction || this.manualCompactionRequest) {
5835
6403
  this.update(
5836
6404
  (s) => addErrorMessage(s, "\u5F53\u524D\u56DE\u590D\u5C1A\u672A\u7ED3\u675F\u6216\u5BF9\u8BDD\u6B63\u5728\u6574\u7406\uFF0C\u8BF7\u7A0D\u540E\u518D\u53D1\u9001\u3002")
5837
6405
  );
5838
6406
  return false;
5839
6407
  }
5840
6408
  let appContext;
5841
- if (this.getAppContext) {
6409
+ if (this.getAppContext && !this.state.isStreaming) {
5842
6410
  try {
5843
6411
  const rawContext = await this.getAppContext();
5844
6412
  if (!isRecord(rawContext)) {
@@ -5866,7 +6434,7 @@ var AgentSession = class _AgentSession {
5866
6434
  let optimisticAskAnswer;
5867
6435
  let previousAskAnswer;
5868
6436
  this.update((state) => {
5869
- const next = addUserMessage(state, content, clientRequestId, options.topicAssetRefs, options.refs);
6437
+ const next = addUserMessage(state, content, clientRequestId, options.topicAssetRefs, options.refs, contextAttachments);
5870
6438
  optimisticTurnId = next.turns.at(-1)?.turn_id ?? null;
5871
6439
  return next;
5872
6440
  });
@@ -5884,6 +6452,8 @@ var AgentSession = class _AgentSession {
5884
6452
  if (!options.replayDecision) {
5885
6453
  this.pendingReplayMessage = content;
5886
6454
  this.pendingReplayMode = options.mode;
6455
+ this.pendingReplayRequestId = clientRequestId;
6456
+ this.pendingReplayAttachments = contextAttachments;
5887
6457
  this.pendingReplayRefs = options.refs;
5888
6458
  this.pendingReplayTopicAssetRefs = options.topicAssetRefs;
5889
6459
  }
@@ -5900,9 +6470,9 @@ var AgentSession = class _AgentSession {
5900
6470
  whatif: options.whatif,
5901
6471
  replay_decision: options.replayDecision,
5902
6472
  app_context: appContext,
6473
+ context_attachments: contextAttachments,
5903
6474
  refs: options.refs,
5904
6475
  topic_asset_refs: options.topicAssetRefs,
5905
- // 运行中提交不必由客户端挑命令:服务端按会话运行状态决定直接执行还是入队。
5906
6476
  queue_when_running: options.queueWhenRunning === true
5907
6477
  };
5908
6478
  try {
@@ -5944,6 +6514,14 @@ var AgentSession = class _AgentSession {
5944
6514
  typeof response?.code === "string" ? response.code : void 0
5945
6515
  );
5946
6516
  }
6517
+ if (optimisticTurnId) {
6518
+ this.update((state) => {
6519
+ const next = withTurns(state, state.turns.map(
6520
+ (turn) => turn.turn_id === optimisticTurnId ? { ...turn, status: "completed" } : turn
6521
+ ));
6522
+ return { ...next, askAnswers: state.askAnswers };
6523
+ });
6524
+ }
5947
6525
  return true;
5948
6526
  } catch (error) {
5949
6527
  const failure = describeSessionError(error, "\u6D88\u606F\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
@@ -5978,13 +6556,14 @@ var AgentSession = class _AgentSession {
5978
6556
  }
5979
6557
  this.emitter.emit("error", { message, ...code ? { code } : {} });
5980
6558
  }
5981
- /** 撤回一次乐观提交:移除乐观消息、恢复提问作答、清掉回放草稿。 */
5982
6559
  discardOptimisticSend(optimisticTurnId, askUserAnswer, optimisticAskAnswer, previousAskAnswer) {
5983
6560
  if (optimisticTurnId && this.pendingChatRequestId && optimisticTurnId === `local-user-${this.pendingChatRequestId}`) {
5984
6561
  this.pendingChatRequestId = null;
5985
6562
  }
5986
6563
  this.pendingReplayMessage = null;
5987
6564
  this.pendingReplayMode = void 0;
6565
+ this.pendingReplayRequestId = void 0;
6566
+ this.pendingReplayAttachments = void 0;
5988
6567
  this.pendingReplayRefs = void 0;
5989
6568
  this.pendingReplayTopicAssetRefs = void 0;
5990
6569
  this.update((current) => {
@@ -6008,9 +6587,9 @@ var AgentSession = class _AgentSession {
6008
6587
  }
6009
6588
  }
6010
6589
  /** 停止当前回复。 */
6011
- async stop() {
6590
+ async stop(executionId) {
6012
6591
  const request = this.manualCompactionRequest;
6013
- if (request) {
6592
+ if (request && !executionId) {
6014
6593
  const ack = await request.ack;
6015
6594
  if (ack.status !== "accepted") return ack;
6016
6595
  if (this.manualCompactionRequest !== request) return { status: "idle" };
@@ -6019,7 +6598,7 @@ var AgentSession = class _AgentSession {
6019
6598
  chat_run_id: request.runId
6020
6599
  }, 35e3) ?? {};
6021
6600
  }
6022
- const response = await this.runtime.emitWithAck("chat:stop", { session_id: this.sessionId }, 35e3) ?? {};
6601
+ const response = await this.runtime.emitWithAck("chat:stop", { session_id: this.sessionId, ...executionId ? { chat_run_id: executionId } : {} }, 35e3) ?? {};
6023
6602
  const cancelled = response.cancelled_client_request_ids;
6024
6603
  if (response.status === "stopped" && Array.isArray(cancelled) && this.pendingChatRequestId !== null && cancelled.includes(this.pendingChatRequestId)) {
6025
6604
  this.pendingChatRequestId = null;
@@ -6126,22 +6705,15 @@ var AgentSession = class _AgentSession {
6126
6705
  get isDisposed() {
6127
6706
  return this.disposed;
6128
6707
  }
6129
- // ------------------------------------------------------- Hub 回调(内部)
6130
- /** @internal 连接状态变化(同 client 下所有会话共享一条连接)。 */
6131
6708
  _setConnection(connection) {
6132
6709
  if (this.state.connection === connection) return;
6133
6710
  this.update((s) => ({ ...s, connection }));
6134
6711
  }
6135
- /**
6136
- * @internal 服务端广播的权威队列快照。
6137
- * 结构不合法或 revision 不新的一律丢弃,绝不用旧快照覆盖新状态。
6138
- */
6139
6712
  _handleQueueUpdated(payload) {
6140
6713
  if (!isSessionQueueSnapshot(payload)) return;
6141
6714
  const snapshot2 = payload;
6142
6715
  this.update((state) => withQueue(state, snapshot2));
6143
6716
  }
6144
- /** @internal socket 重连后由 Hub 调用:重新加入房间并补数。 */
6145
6717
  _rejoinAfterReconnect() {
6146
6718
  this.invalidateOlderPaging();
6147
6719
  this.update((state) => ({ ...state, nextBefore: null, loadingOlder: false }));
@@ -6170,7 +6742,6 @@ var AgentSession = class _AgentSession {
6170
6742
  }
6171
6743
  });
6172
6744
  }
6173
- /** @internal 首次连接:加载历史 + 加入房间。 */
6174
6745
  _bootstrap() {
6175
6746
  const commandRecoveryGeneration = this.beginCommandRecovery();
6176
6747
  return this.enqueueSubscription(async () => {
@@ -6181,7 +6752,6 @@ var AgentSession = class _AgentSession {
6181
6752
  Promise.resolve().then(fetchDetail).catch(() => fetchDetail()).catch(() => null)
6182
6753
  ]);
6183
6754
  if (this.disposed) return;
6184
- if (detail) this.runtimeType = detail.runtime_type ?? null;
6185
6755
  this.subscriptionReplaySource = "bootstrap_replay";
6186
6756
  try {
6187
6757
  await this.ensureJoined();
@@ -6195,17 +6765,14 @@ var AgentSession = class _AgentSession {
6195
6765
  ]);
6196
6766
  });
6197
6767
  }
6198
- /** 订阅生命周期串行执行;一次失败只由自己的调用方观察,不截断后续重连。 */
6199
6768
  enqueueSubscription(operation) {
6200
6769
  const run = this.subscriptionQueue.then(operation);
6201
6770
  this.subscriptionQueue = run.catch(() => void 0);
6202
6771
  return run;
6203
6772
  }
6204
- /** 改回放是 owner 专属(服务端 PATCH 走 _get_owned_session)。 */
6205
6773
  get canControlReplay() {
6206
6774
  return this.state.viewerRole !== "viewer";
6207
6775
  }
6208
- /** 拉一次会话详情,填会话状态、回放状态、只读身份和运行时类型;失败不挡启动。 */
6209
6776
  async syncSessionFromDetail(options) {
6210
6777
  const statusRevisionAtRequest = this.statusRevision;
6211
6778
  try {
@@ -6214,18 +6781,14 @@ var AgentSession = class _AgentSession {
6214
6781
  } catch {
6215
6782
  }
6216
6783
  }
6217
- /** 安装一份会话详情;`statusRevisionAtRequest` 是发出请求时的状态修订号。 */
6218
6784
  applySessionDetail(info, statusRevisionAtRequest) {
6219
6785
  if (this.disposed) return;
6220
- this.runtimeType = info.runtime_type ?? null;
6221
6786
  const replay = toReplaySnapshot(info.replay_state);
6222
6787
  const viewerRole = info.viewer_role ?? null;
6223
6788
  this.update((s) => ({
6224
6789
  ...s,
6225
6790
  replay,
6226
6791
  viewerRole,
6227
- // 请求期间 status 变过(哪怕又变回原值)就说明实时事件比这份详情更新,不覆盖。
6228
- // child_pause 已让提问进入等待态,而稍旧的详情仍可能写着 running。
6229
6792
  status: this.statusRevision === statusRevisionAtRequest && !(s.status === "waiting_for_input" && info.status === "running" && s.turns.some((turn) => turn.tool_calls.some((call) => call.status === "awaiting_answer"))) ? info.status ?? s.status : s.status
6230
6793
  }));
6231
6794
  }
@@ -6239,7 +6802,6 @@ var AgentSession = class _AgentSession {
6239
6802
  if (!this.state.replay?.isReplay || !this.canControlReplay) return;
6240
6803
  await this.applyReplayControl({ status: "autonomous" });
6241
6804
  }
6242
- /** 把一次回放控制请求排进队列;前一个完成后才发出,响应直接安装。 */
6243
6805
  applyReplayControl(payload) {
6244
6806
  const run = this.replayQueue.then(async () => {
6245
6807
  const result = await this.runtime.updateReplay(this.sessionId, payload);
@@ -6248,12 +6810,10 @@ var AgentSession = class _AgentSession {
6248
6810
  this.replayQueue = run.catch(() => void 0);
6249
6811
  return run;
6250
6812
  }
6251
- /** @internal */
6252
6813
  _handleTurnStart(turn) {
6253
6814
  this.markRunningIfIdle();
6254
6815
  this.applyTurn(turn);
6255
6816
  }
6256
- /** @internal */
6257
6817
  _handleTurnPatch(patch) {
6258
6818
  this.markRunningIfIdle();
6259
6819
  if (patch.data.workspace_changed) {
@@ -6269,7 +6829,6 @@ var AgentSession = class _AgentSession {
6269
6829
  }
6270
6830
  this.schedulePatchFlush();
6271
6831
  }
6272
- /** @internal */
6273
6832
  _handleTurnEnd(turn) {
6274
6833
  this.applyTurn(turn);
6275
6834
  }
@@ -6284,18 +6843,19 @@ var AgentSession = class _AgentSession {
6284
6843
  if (this.epochReloadRequested > target) this.runEpochReload();
6285
6844
  });
6286
6845
  }
6287
- /** @internal 历史回放通道(event_format: raw)。 */
6288
6846
  _handleTurnEvents(incoming, replayed = false) {
6289
6847
  const delivery = this.logCursor.consume(incoming);
6290
6848
  let events = delivery.events;
6291
6849
  if (delivery.reload) {
6292
6850
  this.activeReplayPlaybackId = null;
6293
6851
  this.projectionBuilder.reset();
6852
+ this.update((state) => ({ ...state, lastRun: null }));
6294
6853
  this.pendingTurnPatches.clear();
6295
6854
  this.epochReloadRequested += 1;
6296
6855
  }
6297
6856
  this.runEpochReload();
6298
6857
  for (const event of events) {
6858
+ if (event.type === "chat:end") this.recordRunResult(event.payload);
6299
6859
  const playbackId = typeof event.payload.playback_id === "string" ? event.payload.playback_id : null;
6300
6860
  if (event.type === "chat:start") this.activeReplayPlaybackId = null;
6301
6861
  if (event.type === "replay:start" && playbackId) {
@@ -6364,7 +6924,6 @@ var AgentSession = class _AgentSession {
6364
6924
  const updates = this.projectionBuilder.processBatch(events);
6365
6925
  for (const update of updates) {
6366
6926
  if (update.kind === "upsert") {
6367
- if (this.isNativeBootstrapTurn(update.turn)) continue;
6368
6927
  this.applyTurn(
6369
6928
  update.turn,
6370
6929
  replayed ? this.subscriptionReplaySource ?? "bootstrap_replay" : "live"
@@ -6387,7 +6946,6 @@ var AgentSession = class _AgentSession {
6387
6946
  this.completeChat(terminalChatEndStatus ?? "completed");
6388
6947
  }
6389
6948
  }
6390
- /** @internal */
6391
6949
  _handleChatStart() {
6392
6950
  this.noteLiveStatus();
6393
6951
  this.update((s) => ({
@@ -6397,10 +6955,14 @@ var AgentSession = class _AgentSession {
6397
6955
  isStreaming: true
6398
6956
  }));
6399
6957
  }
6400
- /**
6401
- * @internal 返回 false 表示这是一条过期的排队回滚(被取消的是更早的请求,当前运行不受影响),
6402
- * Hub 据此不把它当成一次运行结束广播出去。
6403
- */
6958
+ recordRunResult(payload) {
6959
+ const runId = payload.chat_run_id;
6960
+ if (payload.queued || typeof runId !== "string" || !runId) return;
6961
+ this.update((state) => ({
6962
+ ...state,
6963
+ lastRun: { runId, status: payload.status ?? "completed", result: payload.result }
6964
+ }));
6965
+ }
6404
6966
  _handleChatEnd(payload = {}) {
6405
6967
  const status = payload.status ?? "completed";
6406
6968
  if (payload.queued === true) {
@@ -6410,6 +6972,7 @@ var AgentSession = class _AgentSession {
6410
6972
  return false;
6411
6973
  }
6412
6974
  }
6975
+ this.recordRunResult(payload);
6413
6976
  this.pendingChatRequestId = null;
6414
6977
  this.noteLiveStatus();
6415
6978
  this.flushPatches();
@@ -6419,29 +6982,9 @@ var AgentSession = class _AgentSession {
6419
6982
  this.emitter.emit("chatEnd", { status });
6420
6983
  return true;
6421
6984
  }
6422
- if (this.runtimeType === "native") {
6423
- const updates = this.projectionBuilder.processBatch([
6424
- {
6425
- type: "chat:end",
6426
- payload: {
6427
- loop_name: "root",
6428
- status,
6429
- ...payload.pause_tool_data ? { pause_tool_data: payload.pause_tool_data } : {}
6430
- }
6431
- }
6432
- ]);
6433
- for (const update of updates) {
6434
- if (update.kind === "upsert") this.applyTurn(update.turn);
6435
- }
6436
- this.finishStreaming(status);
6437
- this.recentChatEndAt = Date.now();
6438
- this.emitter.emit("chatEnd", { status });
6439
- return true;
6440
- }
6441
6985
  this.completeChat(status);
6442
6986
  return true;
6443
6987
  }
6444
- /** @internal */
6445
6988
  _handleSystemError(message, code) {
6446
6989
  this.pendingChatRequestId = null;
6447
6990
  this.noteLiveStatus();
@@ -6471,15 +7014,12 @@ var AgentSession = class _AgentSession {
6471
7014
  ...code ? { code } : {}
6472
7015
  });
6473
7016
  }
6474
- /** @internal */
6475
7017
  _handleTaskUpdated(tasks) {
6476
7018
  this.emitter.emit("taskListUpdated", { tasks });
6477
7019
  }
6478
- /** @internal */
6479
7020
  _handleWorkspaceFilesChanged(filePath, paths) {
6480
7021
  this.emitter.emit("workspaceChanged", paths?.length ? { filePath, paths } : { filePath });
6481
7022
  }
6482
- /** @internal */
6483
7023
  _handleSessionUpdated(data) {
6484
7024
  if (data.status) {
6485
7025
  this.noteLiveStatus();
@@ -6495,11 +7035,9 @@ var AgentSession = class _AgentSession {
6495
7035
  intent: data.intent,
6496
7036
  status: data.status,
6497
7037
  model: data.model,
6498
- boundSkillId: data.bound_skill_id,
6499
7038
  replayState: data.replay_state
6500
7039
  });
6501
7040
  }
6502
- /** @internal */
6503
7041
  _handleRewind(checkpointId) {
6504
7042
  this.invalidateTimeline();
6505
7043
  this.invalidateOlderPaging();
@@ -6514,14 +7052,17 @@ var AgentSession = class _AgentSession {
6514
7052
  void this.replaceFromHistory();
6515
7053
  this.emitter.emit("rewind", { checkpointId });
6516
7054
  }
6517
- /** @internal */
6518
7055
  _handleReplayMismatch(data) {
6519
7056
  const message = this.pendingReplayMessage ?? data.actual_message ?? "";
6520
7057
  const mode = this.pendingReplayMode;
7058
+ const requestId = this.pendingReplayRequestId ?? createClientRequestId();
7059
+ const contextAttachments = this.pendingReplayAttachments;
6521
7060
  const refs = this.pendingReplayRefs;
6522
7061
  const topicAssetRefs = this.pendingReplayTopicAssetRefs;
6523
7062
  this.pendingReplayMessage = null;
6524
7063
  this.pendingReplayMode = void 0;
7064
+ this.pendingReplayRequestId = void 0;
7065
+ this.pendingReplayAttachments = void 0;
6525
7066
  this.pendingReplayRefs = void 0;
6526
7067
  this.pendingReplayTopicAssetRefs = void 0;
6527
7068
  const respond = (decision) => {
@@ -6532,8 +7073,10 @@ var AgentSession = class _AgentSession {
6532
7073
  message,
6533
7074
  mode,
6534
7075
  replay_decision: decision,
7076
+ client_request_id: requestId,
6535
7077
  refs,
6536
- topic_asset_refs: topicAssetRefs
7078
+ topic_asset_refs: topicAssetRefs,
7079
+ context_attachments: contextAttachments
6537
7080
  },
6538
7081
  3e4
6539
7082
  ).then((response) => {
@@ -6562,7 +7105,6 @@ var AgentSession = class _AgentSession {
6562
7105
  respond("continue_replay");
6563
7106
  }
6564
7107
  }
6565
- /** @internal */
6566
7108
  _handleSystemNotification(loopId, notification) {
6567
7109
  const notificationType = typeof notification.notification_type === "string" ? notification.notification_type : "system_notification";
6568
7110
  const title = typeof notification.title === "string" ? notification.title : notificationType;
@@ -6589,11 +7131,9 @@ var AgentSession = class _AgentSession {
6589
7131
  }
6590
7132
  }
6591
7133
  }
6592
- /** @internal */
6593
7134
  _handleBackgroundTask(task) {
6594
7135
  this.emitter.emit("backgroundTask", task);
6595
7136
  }
6596
- /** @internal */
6597
7137
  _handleArtifact(data, kind, replayed = false) {
6598
7138
  const filePath = typeof data.file_path === "string" ? data.file_path : "";
6599
7139
  if (!filePath) return;
@@ -6609,7 +7149,6 @@ var AgentSession = class _AgentSession {
6609
7149
  kind
6610
7150
  });
6611
7151
  }
6612
- /** @internal 加入房间的应答里带 is_running,据此校准流式状态。 */
6613
7152
  _applyRunningState(isRunning, liveRevisionAtJoin = this.liveRevision) {
6614
7153
  const hasPendingQuestion = this.state.turns.some(
6615
7154
  (turn) => turn.tool_calls.some((call) => call.status === "awaiting_answer")
@@ -6622,7 +7161,6 @@ var AgentSession = class _AgentSession {
6622
7161
  void this.refreshAuthoritativeHistory({ liveRevisionAtStart: liveRevisionAtJoin });
6623
7162
  }
6624
7163
  }
6625
- // ---------------------------------------------------------------- 内部实现
6626
7164
  markRunningIfIdle() {
6627
7165
  if (!this.state.isStreaming) {
6628
7166
  this.noteLiveStatus();
@@ -6639,15 +7177,6 @@ var AgentSession = class _AgentSession {
6639
7177
  });
6640
7178
  this.applyDesiredStreamTokens();
6641
7179
  }
6642
- /**
6643
- * 原生智能体常在用户发言之前就宣告一个空的 assistant 回合(投影的起点),它的真实内容会随第一条
6644
- * 输出再发一次。消息列表在启动期间本来就显示一个「正在生成」占位,两者并存会出现两个占位,
6645
- * 所以只丢掉原生会话里这种空的流式回合。
6646
- */
6647
- isNativeBootstrapTurn(turn) {
6648
- return this.runtimeType === "native" && turn.role === "assistant" && turn.status === "streaming" && turn.blocks.length === 0 && turn.tool_calls.length === 0;
6649
- }
6650
- /** 实时 workflow:* 事件叠加到对应工具调用的时间线上(见 workflow.ts 的来源规则)。 */
6651
7180
  applyWorkflowEvents(events) {
6652
7181
  for (const event of events) {
6653
7182
  if (!isWorkflowEvent(event.type)) continue;
@@ -6662,10 +7191,6 @@ var AgentSession = class _AgentSession {
6662
7191
  this.update((state) => withWorkflowEvent(state, toolCallId, event.type, payload));
6663
7192
  }
6664
7193
  }
6665
- /**
6666
- * @internal 宿主改了 token 订阅偏好(精简模式)。空闲时立即重订阅;运行中等这一轮结束再换,
6667
- * 避免在输出中途丢掉 token 流。
6668
- */
6669
7194
  _setStreamTokens(enabled) {
6670
7195
  this.desiredStreamTokens = enabled;
6671
7196
  if (!this.state.isStreaming) this.applyDesiredStreamTokens();
@@ -6683,7 +7208,7 @@ var AgentSession = class _AgentSession {
6683
7208
  completeChat(status) {
6684
7209
  this.finishStreaming(status);
6685
7210
  this.recentChatEndAt = Date.now();
6686
- if (this.runtimeType !== "native") void this.refreshAuthoritativeHistory();
7211
+ void this.refreshAuthoritativeHistory();
6687
7212
  this.emitter.emit("chatEnd", { status });
6688
7213
  }
6689
7214
  markTurnFresh(turnId) {
@@ -6761,7 +7286,6 @@ var AgentSession = class _AgentSession {
6761
7286
  this.patchFlushCancel = null;
6762
7287
  }
6763
7288
  }
6764
- /** turn 数据落地后统一派生语义事件(指令 / 工具调用 / 消息 / 模式 / 预览 / OOM)。 */
6765
7289
  emitTurnDerivedEvents(previous, turn, source = "live") {
6766
7290
  this.emitter.emit("turnUpdated", { turn, source });
6767
7291
  const mode = extractModeFromBlocks(turn.blocks);
@@ -6874,20 +7398,11 @@ var AgentSession = class _AgentSession {
6874
7398
  this.update((s) => addErrorMessage(s, OOM_MESSAGE));
6875
7399
  this.emitter.emit("sandboxOom", { toolCallId: key });
6876
7400
  }
6877
- /**
6878
- * 权威刷新(运行结束 / 重连补数):**按当前窗口第一条发言取窗口**,不再另记"用户想看哪段"。
6879
- *
6880
- * 窗口本身就是"用户在看哪段":首屏就是最新一页,向上翻页 / 定位之后首条就是用户滚到的位置。
6881
- * 直接拿 `from_entry_id = 当前窗口第一条 turn_id` 去取,运行结束、重连补数、翻页之后的对账
6882
- * 是同一条规则,不需要意图、锚点、已落地锚点这些状态;窗口首条已经不在分支上(404 / 409)时
6883
- * 回落到最新一页。
6884
- */
6885
7401
  refreshAuthoritativeHistory(options = {}) {
6886
7402
  let entryGone = false;
6887
7403
  const locateTokenAtStart = this.locateToken;
6888
7404
  return this.replaceFromHistory({
6889
7405
  ...options,
6890
- // 锚点在**这次操作真正开始**时采样:排队期间用户可能刚定位过,那时窗口首条才是他要的。
6891
7406
  fromEntryId: () => {
6892
7407
  const anchor = this.state.turns[0]?.turn_id;
6893
7408
  return anchor?.startsWith("local-user-") ? void 0 : anchor;
@@ -7055,7 +7570,6 @@ var AgentSession = class _AgentSession {
7055
7570
  this.bufferedCommandDeliveries = null;
7056
7571
  }
7057
7572
  }
7058
- /** 首次订阅前的 REST 历史建立语义事件基线,随后同一工具的订阅回放不再投递。 */
7059
7573
  seedToolCallDeliveryBaseline(turns) {
7060
7574
  for (const turn of turns) {
7061
7575
  for (const toolCall of turn.tool_calls) {
@@ -7114,7 +7628,6 @@ var SessionHub = class {
7114
7628
  client;
7115
7629
  sessions = /* @__PURE__ */ new Map();
7116
7630
  bootstrapPending = /* @__PURE__ */ new Map();
7117
- /** 每个会话当前有多少方持有(connect 一次 +1,dispose 一次 -1)。 */
7118
7631
  holdCounts = /* @__PURE__ */ new Map();
7119
7632
  connection = "disconnected";
7120
7633
  connectionListeners = /* @__PURE__ */ new Set();
@@ -7123,19 +7636,12 @@ var SessionHub = class {
7123
7636
  authBusyReconnect = new AuthBusyReconnect();
7124
7637
  hubEmitter = new Emitter();
7125
7638
  options = { restoreHistoricalCommands: true };
7126
- /** token 订阅偏好(第一方 Web 精简模式);null 表示不设置,订阅时不带字段。 */
7127
7639
  streamTokens = null;
7128
- /** 状态订阅(mode: "status")的持有计数。 */
7129
7640
  statusWatchCounts = /* @__PURE__ */ new Map();
7130
7641
  statusLogCursors = /* @__PURE__ */ new Map();
7131
7642
  replayPlaybackIds = /* @__PURE__ */ new Map();
7132
- /** 启动连接门控:扣住期间只登记「需要连接」,放开后连一次。 */
7133
7643
  connectionHeld = false;
7134
7644
  connectDeferred = false;
7135
- /**
7136
- * 宿主显式要过连接(ensureConnected / reconnect,例如只收产品事件的页面)。有会话、状态订阅或这个需求时,
7137
- * 鉴权忙碌的临时拒绝都要按服务端建议重试,否则连接会一直停在断开,直到别的动作碰巧重连。
7138
- */
7139
7645
  connectionDemanded = false;
7140
7646
  constructor(client) {
7141
7647
  this.client = client;
@@ -7148,10 +7654,6 @@ var SessionHub = class {
7148
7654
  on(name, handler) {
7149
7655
  return this.hubEmitter.on(name, handler);
7150
7656
  }
7151
- /**
7152
- * @internal 第一方 Web 的精简模式传输优化:订阅时是否要 token 级事件。
7153
- * 空闲会话立即重订阅,运行中的会话等这一轮结束。
7154
- */
7155
7657
  setStreamTokens(enabled) {
7156
7658
  if (this.streamTokens === enabled) return;
7157
7659
  this.streamTokens = enabled;
@@ -7312,11 +7814,6 @@ var SessionHub = class {
7312
7814
  this.forceRelease(session);
7313
7815
  }
7314
7816
  }
7315
- /**
7316
- * @internal 底层 socket 被换掉时由 BladeClient 调用(如 setBaseUrl)。
7317
- * 事件监听器绑在旧 socket 实例上,换新实例后必须重绑,否则所有
7318
- * turn:* / chat:* 事件都会静默丢弃。
7319
- */
7320
7817
  _handleSocketReplaced() {
7321
7818
  this.authBusyReconnect.cancel();
7322
7819
  this.bound = false;
@@ -7345,14 +7842,9 @@ var SessionHub = class {
7345
7842
  onDispose: (session) => this.release(session)
7346
7843
  };
7347
7844
  }
7348
- /** 记一份持有。 */
7349
7845
  hold(sessionId) {
7350
7846
  this.holdCounts.set(sessionId, (this.holdCounts.get(sessionId) ?? 0) + 1);
7351
7847
  }
7352
- /**
7353
- * 归还一份持有;还剩别的持有者时返回 false,让 AgentSession 保持可用。
7354
- * 归零才退订房间并从路由表移除。
7355
- */
7356
7848
  release(session) {
7357
7849
  const remaining = (this.holdCounts.get(session.sessionId) ?? 0) - 1;
7358
7850
  if (remaining > 0) {
@@ -7370,6 +7862,7 @@ var SessionHub = class {
7370
7862
  this.client.socket().emit("session:unsubscribe", { session_id: session.sessionId });
7371
7863
  if (this.statusWatchCounts.has(session.sessionId)) this.emitStatusSubscribe([session.sessionId]);
7372
7864
  else this.statusLogCursors.delete(session.sessionId);
7865
+ if (this.client.options.anonymousSessionId && !this.needsConnection()) this.disconnect();
7373
7866
  return true;
7374
7867
  }
7375
7868
  statusCursor(sessionId) {
@@ -7396,7 +7889,6 @@ var SessionHub = class {
7396
7889
  sessions: sessionIds.map(payload)
7397
7890
  });
7398
7891
  }
7399
- /** 不管还有几方持有都立即释放(启动失败、切换身份)。 */
7400
7892
  forceRelease(session) {
7401
7893
  this.holdCounts.delete(session.sessionId);
7402
7894
  session.dispose();
@@ -7421,7 +7913,6 @@ var SessionHub = class {
7421
7913
  }
7422
7914
  }
7423
7915
  }
7424
- /** 事件带 session_id 时精确路由;缺省时按当前唯一活跃会话兜底。 */
7425
7916
  route(sessionId) {
7426
7917
  if (sessionId) {
7427
7918
  const session = this.sessions.get(sessionId);
@@ -7490,6 +7981,7 @@ var SessionHub = class {
7490
7981
  socket.on(
7491
7982
  "turn:events",
7492
7983
  (data, acknowledge) => {
7984
+ syncServerTime(this.client, data.server_time);
7493
7985
  acknowledgeTurnEvents(acknowledge);
7494
7986
  if (data.session_id && (this.statusWatchCounts.has(data.session_id) || this.sessions.has(data.session_id)) && data.events?.some((event) => event.type === "log:record")) {
7495
7987
  const delivery = this.statusCursor(data.session_id).consume(data.events ?? []);
@@ -7691,20 +8183,27 @@ function createSocket(options) {
7691
8183
 
7692
8184
  // src/blade-client.ts
7693
8185
  var REFRESH_PATH = "/api/auth/refresh";
7694
- var BladeClient = class {
8186
+ var BladeClient = class _BladeClient {
8187
+ anonymousClients = /* @__PURE__ */ new Map();
8188
+ toolProviders = /* @__PURE__ */ new Set();
7695
8189
  refreshPromise = null;
8190
+ cookieLogoutPending = 0;
7696
8191
  socketInstance = null;
7697
8192
  socketReplacementListeners = /* @__PURE__ */ new Set();
7698
- /** login() / setToken() 热挂载的令牌,优先级高于构造参数。 */
7699
- runtimeToken = null;
8193
+ runtimeToken = void 0;
7700
8194
  options;
8195
+ sandbox;
7701
8196
  auth;
7702
8197
  headless;
7703
8198
  computers;
8199
+ /** 用户接进来的手机:账号级清单、会话启用、画面信令。 */
8200
+ phones;
8201
+ llm;
7704
8202
  models;
7705
8203
  sessions;
7706
8204
  /** 按用户读取的插件目录与图标;没有会话时也能用。 */
7707
8205
  plugins;
8206
+ connectors;
7708
8207
  chatGroups;
7709
8208
  /**
7710
8209
  * 全站访问统计:匿名读写,不带 bearer 也不触发登录刷新。
@@ -7714,23 +8213,36 @@ var BladeClient = class {
7714
8213
  /** 实时会话中枢:client.sessions.connect() 内部使用,一般不直接访问。 */
7715
8214
  hub;
7716
8215
  constructor(options) {
8216
+ if (options.anonymousSessionId !== void 0 && !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(options.anonymousSessionId)) {
8217
+ throw new Error("\u533F\u540D\u4F1A\u8BDD ID \u5FC5\u987B\u662F UUID v4");
8218
+ }
7717
8219
  this.options = {
7718
8220
  ...options,
7719
8221
  baseUrl: normalizeBaseUrl(options.baseUrl)
7720
8222
  };
8223
+ this.sandbox = new SandboxResource(this);
7721
8224
  this.auth = new AuthResource(this);
7722
8225
  this.headless = new HeadlessResource(this);
7723
8226
  this.computers = new ComputersResource(this);
8227
+ this.phones = new PhonesResource(this);
8228
+ this.llm = new LlmResource(this);
7724
8229
  this.models = new ModelsResource(this);
7725
8230
  this.sessions = new SessionsResource(this);
7726
8231
  this.plugins = new PluginsResource(this);
8232
+ this.connectors = new ConnectorsResource(this);
7727
8233
  this.chatGroups = new ChatGroupsResource(this);
7728
8234
  this.siteVisits = new SiteVisitsResource(this);
7729
8235
  this.hub = new SessionHub(this);
7730
- if (this.options.token === void 0) {
7731
- this.runtimeToken = readStoredToken(this.options.baseUrl);
8236
+ if (this.options.token === void 0 && !this.options.anonymousSessionId) {
8237
+ this.runtimeToken = readStoredToken(this.options.baseUrl) ?? void 0;
7732
8238
  }
7733
8239
  }
8240
+ /** Backend application tools, callable over an outbound WebSocket. */
8241
+ connectToolProvider(options) {
8242
+ const provider = new ToolProvider(this, options, () => this.toolProviders.delete(provider));
8243
+ this.toolProviders.add(provider);
8244
+ return provider;
8245
+ }
7734
8246
  /**
7735
8247
  * 弹窗授权登录:用户在弹出的授权页点击"许可授权"后自动取得 PAT,
7736
8248
  * REST 与 Socket.IO 立即生效。只在浏览器可用。
@@ -7750,7 +8262,13 @@ var BladeClient = class {
7750
8262
  const previousToken = this.resolveToken();
7751
8263
  this.runtimeToken = token;
7752
8264
  const nextToken = this.resolveToken();
8265
+ if (token === null) for (const provider of this.toolProviders) provider.dispose();
7753
8266
  if (previousToken !== nextToken) {
8267
+ this.options.applicationTransport?.invalidate();
8268
+ for (const provider of this.toolProviders) {
8269
+ if (nextToken) provider.reconnect();
8270
+ else provider.dispose();
8271
+ }
7754
8272
  this.hub.disposeAll();
7755
8273
  }
7756
8274
  writeStoredToken(this.options.baseUrl, token, this.options.tokenStorage ?? "local");
@@ -7783,12 +8301,27 @@ var BladeClient = class {
7783
8301
  get token() {
7784
8302
  return this.resolveRestToken();
7785
8303
  }
8304
+ /** 获取只访问指定匿名会话的客户端;创建仍由已认证的原客户端完成。 */
8305
+ forAnonymousSession(sessionId) {
8306
+ let client = this.anonymousClients.get(sessionId);
8307
+ if (!client) {
8308
+ client = new _BladeClient({ baseUrl: this.options.baseUrl, anonymousSessionId: sessionId, fetchImpl: this.options.fetchImpl, commandTransport: this.options.commandTransport });
8309
+ this.anonymousClients.set(sessionId, client);
8310
+ }
8311
+ return client;
8312
+ }
7786
8313
  setBaseUrl(baseUrl) {
7787
8314
  const nextBaseUrl = normalizeBaseUrl(baseUrl);
7788
8315
  if (nextBaseUrl === this.options.baseUrl) {
7789
8316
  return;
7790
8317
  }
8318
+ for (const provider of this.toolProviders) provider.dispose();
7791
8319
  this.hub.disposeAll();
8320
+ for (const client of this.anonymousClients.values()) {
8321
+ client.hub.disposeAll();
8322
+ client.hub.disconnect();
8323
+ }
8324
+ this.anonymousClients.clear();
7792
8325
  this.options.baseUrl = nextBaseUrl;
7793
8326
  if (this.socketInstance) {
7794
8327
  this.socketInstance.removeAllListeners();
@@ -7813,7 +8346,7 @@ var BladeClient = class {
7813
8346
  }
7814
8347
  socket() {
7815
8348
  if (!this.socketInstance) {
7816
- this.socketInstance = createSocket({
8349
+ this.socketInstance = this.options.applicationTransport?.socket() ?? createSocket({
7817
8350
  baseUrl: this.options.baseUrl,
7818
8351
  token: () => this.resolveSocketToken()
7819
8352
  });
@@ -7828,7 +8361,10 @@ var BladeClient = class {
7828
8361
  else resolve(ack ?? {});
7829
8362
  });
7830
8363
  });
7831
- return this.options.commandTransport?.(event, payload, send) ?? send();
8364
+ const transport = this.options.commandTransport;
8365
+ if (!transport) return send();
8366
+ const handled = this.options.anonymousSessionId ? transport(event, payload, send, { anonymousSessionId: this.options.anonymousSessionId }) : transport(event, payload, send);
8367
+ return handled ?? send();
7832
8368
  }
7833
8369
  async json(method, path, body) {
7834
8370
  const response = await this.fetch(method, path, {
@@ -7886,24 +8422,31 @@ var BladeClient = class {
7886
8422
  }
7887
8423
  async fetch(method, path, init = {}, isRetry = false) {
7888
8424
  const url = this.buildUrl(path);
7889
- const response = await (this.options.fetchImpl ?? fetch)(url.toString(), {
7890
- method,
7891
- body: init.body,
7892
- credentials: init.credentials ?? "include",
7893
- headers: this.buildHeaders(url, init.headers),
7894
- signal: init.signal
7895
- });
7896
- if (response.status === 401 && !isRetry && this.shouldRefreshFor401(url)) {
7897
- const refreshed = await this.tryRefreshUnlessAborted(init.signal);
7898
- if (refreshed) {
7899
- return this.fetch(method, path, init, true);
8425
+ const isLogout = method === "POST" && url.pathname === this.buildUrl("/api/auth/logout").pathname && this.isSameBackendUrl(url);
8426
+ if (isLogout) this.cookieLogoutPending += 1;
8427
+ try {
8428
+ if (isLogout) await this.refreshPromise;
8429
+ const response = await (this.options.fetchImpl ?? fetch)(url.toString(), {
8430
+ method,
8431
+ body: init.body,
8432
+ credentials: init.credentials ?? "include",
8433
+ headers: this.buildHeaders(url, init.headers),
8434
+ signal: init.signal
8435
+ });
8436
+ if (response.status === 401 && !isRetry && this.shouldRefreshFor401(url)) {
8437
+ const refreshed = await this.tryRefreshUnlessAborted(init.signal);
8438
+ if (refreshed) {
8439
+ return this.fetch(method, path, init, true);
8440
+ }
7900
8441
  }
8442
+ if (init.expectOk !== false && !response.ok) {
8443
+ const detail = await extractErrorDetail(response);
8444
+ throw decorateAuthError(new BladeApiError(response, detail));
8445
+ }
8446
+ return response;
8447
+ } finally {
8448
+ if (isLogout) this.cookieLogoutPending -= 1;
7901
8449
  }
7902
- if (init.expectOk !== false && !response.ok) {
7903
- const detail = await extractErrorDetail(response);
7904
- throw decorateAuthError(new BladeApiError(response, detail));
7905
- }
7906
- return response;
7907
8450
  }
7908
8451
  buildAuthedUrl(path) {
7909
8452
  const url = buildBackendUrl(this.options.baseUrl, path);
@@ -7949,13 +8492,6 @@ var BladeClient = class {
7949
8492
  hasExplicitBearerToken() {
7950
8493
  return Boolean(this.resolveRestToken());
7951
8494
  }
7952
- /**
7953
- * 等一次令牌刷新,但调用方中止请求时不再等下去。
7954
- *
7955
- * 刷新本身是共享的(`refreshPromise`,别的请求也在等它),这里只是让这次已被取消的
7956
- * 请求尽早结束——否则它会一直挂在调用方(定位)的串行队列里,用户改选的新目标要等到
7957
- * 刷新结束才轮得到。
7958
- */
7959
8495
  async tryRefreshUnlessAborted(signal) {
7960
8496
  if (!signal) return this.tryRefresh();
7961
8497
  if (signal.aborted) throw new DOMException("The operation was aborted.", "AbortError");
@@ -7971,6 +8507,7 @@ var BladeClient = class {
7971
8507
  }
7972
8508
  }
7973
8509
  async tryRefresh() {
8510
+ if (this.options.anonymousSessionId || this.cookieLogoutPending > 0) return false;
7974
8511
  if (this.refreshPromise) {
7975
8512
  return this.refreshPromise;
7976
8513
  }
@@ -7981,7 +8518,6 @@ var BladeClient = class {
7981
8518
  {
7982
8519
  method: "POST",
7983
8520
  credentials: "include",
7984
- // Refresh remains cookie-only; do not attach the REST bearer.
7985
8521
  headers: { "X-Blade-Client": `${SDK_NAME}/${SDK_VERSION}` }
7986
8522
  }
7987
8523
  );
@@ -8005,14 +8541,16 @@ var BladeClient = class {
8005
8541
  return this.resolveRestToken();
8006
8542
  }
8007
8543
  resolveRestToken() {
8544
+ if (this.options.anonymousSessionId) return `ba-anonymous-${this.options.anonymousSessionId}`;
8008
8545
  return this.resolveToken();
8009
8546
  }
8010
8547
  resolveSocketToken() {
8011
- if (this.runtimeToken) return this.runtimeToken;
8548
+ if (this.options.anonymousSessionId) return `ba-anonymous-${this.options.anonymousSessionId}`;
8549
+ if (this.runtimeToken !== void 0) return this.runtimeToken;
8012
8550
  return resolveTokenOption(this.options.socketToken ?? this.options.token);
8013
8551
  }
8014
8552
  resolveToken() {
8015
- if (this.runtimeToken) return this.runtimeToken;
8553
+ if (this.runtimeToken !== void 0) return this.runtimeToken;
8016
8554
  return resolveTokenOption(this.options.token);
8017
8555
  }
8018
8556
  formDataWithUploadProgress(method, path, form, options, isRetry = false) {
@@ -8109,12 +8647,661 @@ function parseXhrHeaders(rawHeaders) {
8109
8647
  return headers;
8110
8648
  }
8111
8649
 
8650
+ // src/application-client.ts
8651
+ var Events = class {
8652
+ listeners = /* @__PURE__ */ new Map();
8653
+ on(name, listener) {
8654
+ let set = this.listeners.get(name);
8655
+ if (!set) {
8656
+ set = /* @__PURE__ */ new Set();
8657
+ this.listeners.set(name, set);
8658
+ }
8659
+ set.add(listener);
8660
+ return this;
8661
+ }
8662
+ off(name, listener) {
8663
+ if (listener) this.listeners.get(name)?.delete(listener);
8664
+ else this.listeners.delete(name);
8665
+ return this;
8666
+ }
8667
+ once(name, listener) {
8668
+ const wrapped = (...args) => {
8669
+ this.off(name, wrapped);
8670
+ listener(...args);
8671
+ };
8672
+ return this.on(name, wrapped);
8673
+ }
8674
+ fire(name, ...args) {
8675
+ for (const listener of [...this.listeners.get(name) ?? []]) {
8676
+ try {
8677
+ listener(...args);
8678
+ } catch (error) {
8679
+ console.warn(
8680
+ `[agent-client] "${name}" application handler failed:`,
8681
+ error
8682
+ );
8683
+ }
8684
+ }
8685
+ }
8686
+ removeAllListeners() {
8687
+ this.listeners.clear();
8688
+ return this;
8689
+ }
8690
+ };
8691
+ function encode(input) {
8692
+ const attachments = [];
8693
+ const walk = (value) => {
8694
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
8695
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
8696
+ let text = "";
8697
+ for (let offset = 0; offset < bytes.length; offset += 8192)
8698
+ text += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
8699
+ attachments.push(btoa(text));
8700
+ return ["bytes", attachments.length - 1];
8701
+ }
8702
+ if (Array.isArray(value)) return ["list", value.map(walk)];
8703
+ if (value && typeof value === "object")
8704
+ return [
8705
+ "dict",
8706
+ Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => [key, walk(item)])
8707
+ ];
8708
+ return ["value", value ?? null];
8709
+ };
8710
+ return { value: walk(input), attachments };
8711
+ }
8712
+ function decode(wire) {
8713
+ const walk = (node) => {
8714
+ if (!Array.isArray(node) || node.length !== 2)
8715
+ throw new Error("Invalid application value");
8716
+ if (node[0] === "value") return node[1];
8717
+ if (node[0] === "bytes")
8718
+ return Uint8Array.from(
8719
+ atob(wire.attachments[node[1]]),
8720
+ (c) => c.charCodeAt(0)
8721
+ );
8722
+ if (node[0] === "list") return node[1].map(walk);
8723
+ if (node[0] === "dict")
8724
+ return Object.fromEntries(
8725
+ node[1].map(([key, value2]) => [key, walk(value2)])
8726
+ );
8727
+ throw new Error("Invalid application value");
8728
+ };
8729
+ const value = walk(wire.value);
8730
+ if (!Array.isArray(value)) throw new Error("Invalid application event");
8731
+ return value;
8732
+ }
8733
+ var BladeApplicationClient = class {
8734
+ constructor(options) {
8735
+ this.options = options;
8736
+ this.channels = [
8737
+ new ApplicationChannel(this.options.baseUrl, this.applicationId),
8738
+ new ApplicationChannel(this.options.baseUrl, this.applicationId)
8739
+ ];
8740
+ }
8741
+ options;
8742
+ channels;
8743
+ clients = /* @__PURE__ */ new Map();
8744
+ applicationId = crypto.randomUUID();
8745
+ forUser(userId, options) {
8746
+ const saved = this.clients.get(userId);
8747
+ if (saved) return saved;
8748
+ let hash = 0;
8749
+ for (const character of userId)
8750
+ hash = hash * 31 + character.charCodeAt(0) | 0;
8751
+ const channel = this.channels[(hash >>> 0) % this.channels.length];
8752
+ const user = new ApplicationUser(channel, userId, () => client);
8753
+ const client = new BladeClient({
8754
+ ...this.options,
8755
+ ...options,
8756
+ tokenStorage: options.tokenStorage ?? "memory",
8757
+ applicationTransport: user
8758
+ });
8759
+ this.clients.set(userId, client);
8760
+ return client;
8761
+ }
8762
+ get connectionCount() {
8763
+ return this.channels.filter((channel) => channel.isConnected).length;
8764
+ }
8765
+ dispose() {
8766
+ for (const client of this.clients.values()) {
8767
+ client.hub.disposeAll();
8768
+ client.logoutToken();
8769
+ }
8770
+ for (const channel of this.channels) channel.dispose();
8771
+ this.clients.clear();
8772
+ }
8773
+ };
8774
+ var ApplicationChannel = class {
8775
+ constructor(baseUrl, applicationId) {
8776
+ this.baseUrl = baseUrl;
8777
+ this.applicationId = applicationId;
8778
+ }
8779
+ baseUrl;
8780
+ applicationId;
8781
+ socket;
8782
+ opening;
8783
+ timer;
8784
+ stopped = false;
8785
+ attempts = 0;
8786
+ controlCount = 0;
8787
+ controlWaiters = [];
8788
+ async controlSlot() {
8789
+ if (this.controlCount >= 16)
8790
+ await new Promise((resolve) => this.controlWaiters.push(resolve));
8791
+ else this.controlCount++;
8792
+ return () => {
8793
+ const next = this.controlWaiters.shift();
8794
+ if (next) next();
8795
+ else this.controlCount--;
8796
+ };
8797
+ }
8798
+ pending = /* @__PURE__ */ new Map();
8799
+ users = /* @__PURE__ */ new Map();
8800
+ get isConnected() {
8801
+ return this.socket?.readyState === WebSocket.OPEN;
8802
+ }
8803
+ ensure() {
8804
+ if (this.stopped)
8805
+ return Promise.reject(new Error("Application client disposed"));
8806
+ if (this.isConnected) return Promise.resolve();
8807
+ if (!this.opening) {
8808
+ const work = this.open();
8809
+ this.opening = work;
8810
+ void work.finally(() => {
8811
+ if (this.opening === work) this.opening = void 0;
8812
+ }).catch(() => {
8813
+ });
8814
+ }
8815
+ return this.opening;
8816
+ }
8817
+ async open() {
8818
+ clearTimeout(this.timer);
8819
+ this.timer = void 0;
8820
+ const candidates = [...this.users.values()].filter(
8821
+ (user2) => user2.demanded && user2.client().token
8822
+ );
8823
+ const user = candidates[this.attempts % candidates.length];
8824
+ let ticket;
8825
+ try {
8826
+ if (!user)
8827
+ throw new Error(
8828
+ "Application channel requires a demanded user credential"
8829
+ );
8830
+ ticket = await user.client().jsonFromInit("/api/app-channels", {
8831
+ method: "POST",
8832
+ body: JSON.stringify({ application_id: this.applicationId }),
8833
+ signal: AbortSignal.timeout(1e4)
8834
+ });
8835
+ } catch (error) {
8836
+ this.schedule();
8837
+ throw error;
8838
+ }
8839
+ if (this.stopped) throw new Error("Application client disposed");
8840
+ const endpoint = buildBackendUrl(this.baseUrl, "/api/app-channels/connect");
8841
+ endpoint.protocol = endpoint.protocol === "https:" ? "wss:" : "ws:";
8842
+ const socket = new WebSocket(endpoint, [
8843
+ "blade-application",
8844
+ `blade-channel.${ticket.token}`
8845
+ ]);
8846
+ this.socket = socket;
8847
+ await new Promise((resolve, reject) => {
8848
+ const timeout = setTimeout(() => {
8849
+ reject(new Error("Application connection timed out"));
8850
+ socket.close();
8851
+ }, 15e3);
8852
+ socket.addEventListener("open", () => {
8853
+ if (this.socket !== socket || this.stopped) return;
8854
+ clearTimeout(timeout);
8855
+ this.attempts = 0;
8856
+ resolve();
8857
+ for (const user2 of this.users.values()) user2.restore();
8858
+ });
8859
+ socket.addEventListener("message", (event) => {
8860
+ if (this.socket !== socket || typeof event.data !== "string") return;
8861
+ try {
8862
+ this.receive(JSON.parse(event.data));
8863
+ } catch {
8864
+ socket.close();
8865
+ }
8866
+ });
8867
+ socket.addEventListener("error", () => {
8868
+ clearTimeout(timeout);
8869
+ reject(new Error("Application connection failed"));
8870
+ });
8871
+ socket.addEventListener("close", () => {
8872
+ clearTimeout(timeout);
8873
+ reject(new Error("Application connection closed"));
8874
+ if (this.socket !== socket) return;
8875
+ this.socket = void 0;
8876
+ for (const request of this.pending.values()) {
8877
+ clearTimeout(request.timer);
8878
+ request.reject(new Error("Application connection closed"));
8879
+ }
8880
+ this.pending.clear();
8881
+ for (const user2 of this.users.values()) user2.lost();
8882
+ this.schedule();
8883
+ });
8884
+ });
8885
+ }
8886
+ schedule() {
8887
+ if (this.stopped || this.timer || ![...this.users.values()].some((user) => user.demanded))
8888
+ return;
8889
+ this.timer = setTimeout(
8890
+ () => {
8891
+ this.timer = void 0;
8892
+ void this.ensure().catch(() => this.schedule());
8893
+ },
8894
+ Math.min(1e4, 500 * 2 ** Math.min(this.attempts++, 5))
8895
+ );
8896
+ }
8897
+ receive(frame) {
8898
+ if (frame.id) {
8899
+ const request = this.pending.get(frame.id);
8900
+ if (!request || request.user !== frame.user) return;
8901
+ this.pending.delete(frame.id);
8902
+ clearTimeout(request.timer);
8903
+ if (frame.error)
8904
+ request.reject(
8905
+ Object.assign(new Error(frame.error.message), {
8906
+ code: frame.error.code,
8907
+ data: {
8908
+ code: frame.error.code,
8909
+ status: frame.error.code === "auth_busy" ? 429 : 401,
8910
+ retry_after: 1
8911
+ }
8912
+ })
8913
+ );
8914
+ else request.resolve(frame.result);
8915
+ return;
8916
+ }
8917
+ const user = frame.user && this.users.get(frame.user);
8918
+ if (user) user.receive(frame);
8919
+ }
8920
+ async request(user, method, params, timeoutMs = 3e4) {
8921
+ const release = method === "socket/event" ? () => {
8922
+ } : await this.controlSlot();
8923
+ try {
8924
+ return await new Promise((resolve, reject) => {
8925
+ const id = crypto.randomUUID();
8926
+ const timer = setTimeout(() => {
8927
+ this.pending.delete(id);
8928
+ reject(new Error("Application request timed out"));
8929
+ }, timeoutMs);
8930
+ this.pending.set(id, { user, resolve, reject, timer });
8931
+ try {
8932
+ this.send({ id, user, method, params });
8933
+ } catch (error) {
8934
+ clearTimeout(timer);
8935
+ this.pending.delete(id);
8936
+ reject(error);
8937
+ }
8938
+ });
8939
+ } finally {
8940
+ release();
8941
+ }
8942
+ }
8943
+ send(frame) {
8944
+ if (!this.isConnected || !this.socket)
8945
+ throw new Error("Application connection unavailable");
8946
+ this.socket.send(JSON.stringify(frame));
8947
+ }
8948
+ dispose() {
8949
+ this.stopped = true;
8950
+ clearTimeout(this.timer);
8951
+ this.timer = void 0;
8952
+ for (const user of this.users.values()) user.lost();
8953
+ this.socket?.close();
8954
+ for (const request of this.pending.values()) {
8955
+ clearTimeout(request.timer);
8956
+ request.reject(new Error("Application client disposed"));
8957
+ }
8958
+ this.pending.clear();
8959
+ this.users.clear();
8960
+ }
8961
+ };
8962
+ var ApplicationUser = class {
8963
+ constructor(channel, userId, client) {
8964
+ this.channel = channel;
8965
+ this.userId = userId;
8966
+ this.client = client;
8967
+ this.events = new ApplicationSocket(this);
8968
+ channel.users.set(this.key, this);
8969
+ }
8970
+ channel;
8971
+ userId;
8972
+ client;
8973
+ key = crypto.randomUUID();
8974
+ events;
8975
+ providers = /* @__PURE__ */ new Map();
8976
+ binding;
8977
+ bindingToken;
8978
+ get demanded() {
8979
+ return this.events.active || this.providers.size > 0;
8980
+ }
8981
+ async bind() {
8982
+ await this.channel.ensure();
8983
+ if (!this.demanded) throw new Error("Application user no longer needed");
8984
+ const token = this.client().token;
8985
+ if (!token) throw new Error("Application user requires a token");
8986
+ if (!this.binding || this.bindingToken !== token) {
8987
+ this.bindingToken = token;
8988
+ const work = this.channel.request(this.key, "user/bind", { user_id: this.userId, token }).then((result) => {
8989
+ if (result.user_id !== this.userId)
8990
+ throw new Error("Application user identity mismatch");
8991
+ if (!this.demanded) {
8992
+ this.binding = void 0;
8993
+ this.bindingToken = void 0;
8994
+ void this.channel.request(this.key, "user/unbind", {}).catch(() => {
8995
+ });
8996
+ throw new Error("Application user no longer needed");
8997
+ }
8998
+ });
8999
+ this.binding = work;
9000
+ void work.catch(() => {
9001
+ if (this.binding === work) this.binding = void 0;
9002
+ });
9003
+ }
9004
+ return this.binding;
9005
+ }
9006
+ socket() {
9007
+ return this.events;
9008
+ }
9009
+ provider() {
9010
+ const provider = new ApplicationProviderSocket(this);
9011
+ this.providers.set(provider.handle, provider);
9012
+ provider.open();
9013
+ return provider;
9014
+ }
9015
+ invalidate() {
9016
+ this.binding = void 0;
9017
+ this.bindingToken = void 0;
9018
+ if (!this.client().token && this.channel.isConnected)
9019
+ void this.channel.request(this.key, "user/unbind", {}).catch(() => {
9020
+ });
9021
+ }
9022
+ restore() {
9023
+ if (this.events.active) this.events.connect();
9024
+ }
9025
+ lost() {
9026
+ this.invalidate();
9027
+ this.events.lost();
9028
+ for (const provider of [...this.providers.values()]) provider.closeLocal();
9029
+ }
9030
+ receive(frame) {
9031
+ if (frame.method === "socket/closed") {
9032
+ this.events.lost();
9033
+ if (this.events.active) this.events.connect();
9034
+ return;
9035
+ }
9036
+ if (frame.method === "tool/closed") {
9037
+ this.providers.get(frame.handle ?? "")?.closeLocal();
9038
+ return;
9039
+ }
9040
+ if (frame.method === "tool/message") {
9041
+ this.providers.get(frame.handle ?? "")?.message(frame.message);
9042
+ return;
9043
+ }
9044
+ if (frame.event && frame.args) {
9045
+ const args = decode(frame.args);
9046
+ if (frame.ack_id)
9047
+ args.push(
9048
+ (...values) => this.channel.send({
9049
+ method: "event/ack",
9050
+ user: this.key,
9051
+ ack_id: frame.ack_id,
9052
+ params: encode(values)
9053
+ })
9054
+ );
9055
+ this.events.fire(frame.event, ...args);
9056
+ }
9057
+ }
9058
+ };
9059
+ var ApplicationSocket = class extends Events {
9060
+ constructor(user) {
9061
+ super();
9062
+ this.user = user;
9063
+ }
9064
+ user;
9065
+ connected = false;
9066
+ active = false;
9067
+ io = new Events();
9068
+ connecting;
9069
+ generation = 0;
9070
+ connect() {
9071
+ this.active = true;
9072
+ if (this.connected || this.connecting) return this;
9073
+ const generation = ++this.generation;
9074
+ const work = this.user.bind().then(() => {
9075
+ if (generation !== this.generation || !this.active) return;
9076
+ return this.user.channel.request(this.user.key, "socket/connect", {});
9077
+ }).then(() => {
9078
+ if (generation !== this.generation || !this.active) return;
9079
+ this.connected = true;
9080
+ this.fire("connect");
9081
+ }).catch((error) => {
9082
+ if (generation === this.generation && this.active) {
9083
+ if (error?.code === "auth_busy" || error?.code === "unauthorized")
9084
+ this.active = false;
9085
+ this.fire("connect_error", error);
9086
+ }
9087
+ }).finally(() => {
9088
+ if (this.connecting === work) this.connecting = void 0;
9089
+ });
9090
+ this.connecting = work;
9091
+ return this;
9092
+ }
9093
+ disconnect() {
9094
+ this.active = false;
9095
+ this.lost();
9096
+ if (this.user.channel.isConnected)
9097
+ void this.user.channel.request(this.user.key, "socket/disconnect", {}).catch(() => {
9098
+ });
9099
+ return this;
9100
+ }
9101
+ lost() {
9102
+ const wasConnected = this.connected;
9103
+ this.connected = false;
9104
+ this.connecting = void 0;
9105
+ this.generation++;
9106
+ if (wasConnected) this.fire("disconnect", "transport close");
9107
+ }
9108
+ emit(event, ...args) {
9109
+ this.send(event, args);
9110
+ return this;
9111
+ }
9112
+ timeout(timeoutMs) {
9113
+ return {
9114
+ emit: (event, ...args) => {
9115
+ this.send(event, args, timeoutMs);
9116
+ return this;
9117
+ }
9118
+ };
9119
+ }
9120
+ send(event, values, timeoutMs) {
9121
+ const args = [...values];
9122
+ const callback = typeof args.at(-1) === "function" ? args.pop() : void 0;
9123
+ const generation = this.generation;
9124
+ const deadline = Date.now() + (timeoutMs ?? 3e4);
9125
+ const work = (async () => {
9126
+ if (!this.active) throw new Error("Application user disconnected");
9127
+ if (!this.connected) await this.connecting;
9128
+ if (!this.connected || this.generation !== generation)
9129
+ throw new Error("Application user disconnected");
9130
+ const remaining = deadline - Date.now();
9131
+ if (remaining <= 0) throw new Error("Application request timed out");
9132
+ const params = { event, args: encode(args) };
9133
+ if (!callback) {
9134
+ this.user.channel.send({
9135
+ user: this.user.key,
9136
+ method: "socket/event",
9137
+ params
9138
+ });
9139
+ return;
9140
+ }
9141
+ return this.user.channel.request(
9142
+ this.user.key,
9143
+ "socket/event",
9144
+ params,
9145
+ remaining
9146
+ );
9147
+ })();
9148
+ void work.then(
9149
+ (result) => {
9150
+ if (!callback) return;
9151
+ const values2 = decode(result);
9152
+ if (timeoutMs !== void 0) callback?.(null, ...values2);
9153
+ else callback?.(...values2);
9154
+ },
9155
+ (error) => {
9156
+ if (timeoutMs !== void 0) callback?.(error);
9157
+ else if (callback) callback(error);
9158
+ }
9159
+ );
9160
+ }
9161
+ };
9162
+ var ApplicationProviderSocket = class extends Events {
9163
+ constructor(user) {
9164
+ super();
9165
+ this.user = user;
9166
+ }
9167
+ user;
9168
+ handle = crypto.randomUUID();
9169
+ readyState = WebSocket.CONNECTING;
9170
+ addEventListener(name, listener) {
9171
+ this.on(name, listener);
9172
+ }
9173
+ open() {
9174
+ void this.user.bind().then(
9175
+ () => {
9176
+ if (this.readyState !== WebSocket.CONNECTING) return;
9177
+ this.readyState = WebSocket.OPEN;
9178
+ this.fire("open", new Event("open"));
9179
+ },
9180
+ () => {
9181
+ if (this.readyState !== WebSocket.CLOSED) {
9182
+ this.fire("error", new Event("error"));
9183
+ this.closeLocal();
9184
+ }
9185
+ }
9186
+ );
9187
+ }
9188
+ send(text) {
9189
+ if (this.readyState !== WebSocket.OPEN)
9190
+ throw new Error("Application provider closed");
9191
+ const message = JSON.parse(text);
9192
+ if (message.method === "provider/register") {
9193
+ void this.user.channel.request(this.user.key, "tool/register", {
9194
+ ...message.params,
9195
+ handle: this.handle
9196
+ }).then(
9197
+ (result) => this.message({ jsonrpc: "2.0", id: message.id, result }),
9198
+ (error) => this.message({
9199
+ jsonrpc: "2.0",
9200
+ id: message.id,
9201
+ error: { code: -32001, message: error.message }
9202
+ })
9203
+ );
9204
+ } else
9205
+ this.user.channel.send({
9206
+ method: "tool/result",
9207
+ user: this.user.key,
9208
+ handle: this.handle,
9209
+ message
9210
+ });
9211
+ }
9212
+ message(message) {
9213
+ if (this.readyState === WebSocket.OPEN)
9214
+ this.fire(
9215
+ "message",
9216
+ new MessageEvent("message", { data: JSON.stringify(message) })
9217
+ );
9218
+ }
9219
+ close() {
9220
+ if (this.readyState === WebSocket.CLOSED) return;
9221
+ if (this.user.channel.isConnected)
9222
+ void this.user.channel.request(this.user.key, "tool/unregister", { handle: this.handle }).catch(() => {
9223
+ });
9224
+ this.closeLocal();
9225
+ }
9226
+ closeLocal() {
9227
+ if (this.readyState === WebSocket.CLOSED) return;
9228
+ this.readyState = WebSocket.CLOSED;
9229
+ this.user.providers.delete(this.handle);
9230
+ this.fire("close", new Event("close"));
9231
+ this.removeAllListeners();
9232
+ }
9233
+ };
9234
+
9235
+ // src/schemas/ask-user-question.ts
9236
+ function parseAskUserQuestion(toolResult) {
9237
+ if (!toolResult) return null;
9238
+ try {
9239
+ const parsed = JSON.parse(toolResult);
9240
+ let questions = parsed?.questions;
9241
+ if (typeof questions === "string") {
9242
+ try {
9243
+ questions = JSON.parse(questions);
9244
+ } catch {
9245
+ return null;
9246
+ }
9247
+ }
9248
+ if (Array.isArray(questions) && questions.length > 0) {
9249
+ const normalized = questions.map(normalizeQuestionItem);
9250
+ if (normalized.every((question) => question !== null)) {
9251
+ return { ...parsed, questions: normalized };
9252
+ }
9253
+ }
9254
+ } catch {
9255
+ }
9256
+ return null;
9257
+ }
9258
+ function formatAskUserAnswer(data, answer) {
9259
+ const parts = data.questions.map((question, index) => {
9260
+ const text = typeof answer.custom[index] === "string" ? answer.custom[index].trim() : [...answer.selections[index] ?? []].sort((a, b) => a - b).map((optionIndex) => question.options[optionIndex].label).join(", ");
9261
+ return `- ${question.question} -> ${indentAnswerContinuationLines(text)}`;
9262
+ });
9263
+ const note = answer.note?.trim() ?? "";
9264
+ return [
9265
+ `\u5173\u4E8E\u9700\u8981\u786E\u8BA4\u7684\u95EE\u9898\uFF0C\u7528\u6237\u7684\u56DE\u7B54\u5982\u4E0B\uFF1A
9266
+ ${parts.join("\n")}`,
9267
+ note ? `\u8865\u5145\u8BF4\u660E\uFF1A${indentAnswerContinuationLines(note)}` : ""
9268
+ ].filter(Boolean).join("\n");
9269
+ }
9270
+ function indentAnswerContinuationLines(answer) {
9271
+ return answer.replaceAll("\n", "\n ");
9272
+ }
9273
+ function normalizeQuestionItem(value) {
9274
+ if (!value || typeof value !== "object") return null;
9275
+ const item = value;
9276
+ if (typeof item.question !== "string" || !Array.isArray(item.options)) return null;
9277
+ const options = item.options.map(normalizeOptionItem);
9278
+ if (!options.every((option) => option !== null)) return null;
9279
+ return {
9280
+ question: item.question,
9281
+ options,
9282
+ multiSelect: item.multiSelect === true || item.multi_select === true
9283
+ };
9284
+ }
9285
+ function normalizeOptionItem(value) {
9286
+ if (typeof value === "string") return { label: value, description: "" };
9287
+ if (!value || typeof value !== "object") return null;
9288
+ const option = value;
9289
+ if (typeof option.label !== "string") return null;
9290
+ return {
9291
+ label: option.label,
9292
+ description: typeof option.description === "string" ? option.description : ""
9293
+ };
9294
+ }
9295
+
8112
9296
  export {
9297
+ SandboxResource,
9298
+ BladeApiError,
9299
+ ToolProvider,
8113
9300
  SDK_NAME,
8114
9301
  SDK_VERSION,
8115
- BladeApiError,
8116
9302
  isRecord,
8117
9303
  normalizePluginRefs,
9304
+ normalizeMessageRefs,
8118
9305
  normalizeTopicAssetRefs,
8119
9306
  inferToolStatus,
8120
9307
  contextProjectionData,
@@ -8137,10 +9324,14 @@ export {
8137
9324
  computerOS,
8138
9325
  computerPlatformLabel,
8139
9326
  computerDaemonVersion,
8140
- canToggleComputer,
8141
9327
  sortComputers,
8142
9328
  ComputersResource,
9329
+ phoneState,
9330
+ sortPhones,
9331
+ phoneSerialLabel,
8143
9332
  ModelsResource,
9333
+ isLocalConnectorName,
9334
+ ConnectorsResource,
8144
9335
  SessionStatus,
8145
9336
  DEFAULT_REPLAY_SPEED,
8146
9337
  SessionInfo,
@@ -8148,6 +9339,8 @@ export {
8148
9339
  isEntryGoneError,
8149
9340
  PluginsResource,
8150
9341
  ChatGroupsResource,
9342
+ syncServerTime,
9343
+ getServerTime,
8151
9344
  authBusyRetryDelayMs,
8152
9345
  AuthBusyReconnect,
8153
9346
  prependOlder,
@@ -8182,6 +9375,7 @@ export {
8182
9375
  toReplaySnapshot,
8183
9376
  createInitialSessionState,
8184
9377
  parentForkToolCallIdFromTurn,
9378
+ messageContentFromTurn,
8185
9379
  reconcileOptimisticUserTurns,
8186
9380
  reconcileHistoricalUserTurns,
8187
9381
  withTurns,
@@ -8192,6 +9386,9 @@ export {
8192
9386
  AgentSession,
8193
9387
  SessionHub,
8194
9388
  createSocket,
8195
- BladeClient
9389
+ BladeClient,
9390
+ BladeApplicationClient,
9391
+ parseAskUserQuestion,
9392
+ formatAskUserAnswer
8196
9393
  };
8197
- //# sourceMappingURL=chunk-E7J2JBML.js.map
9394
+ //# sourceMappingURL=chunk-DMVWOTJB.js.map