@blade-hq/agent-client 2612.0.0-beta.8 → 2612.0.0-beta.80
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.
- package/README.md +405 -34
- package/dist/application-client.d.ts +19 -0
- package/dist/blade-client.d.ts +28 -9
- package/dist/{chunk-ZTHGY4OX.js → chunk-RI7ZYTYK.js} +1889 -391
- package/dist/chunk-RI7ZYTYK.js.map +1 -0
- package/dist/index.d.ts +24 -6
- package/dist/index.js +23 -1
- package/dist/internal.d.ts +13 -4
- package/dist/internal.js +39 -3
- package/dist/internal.js.map +1 -1
- package/dist/pack-page-bridge.d.ts +11 -0
- package/dist/resources/auth.d.ts +25 -1
- package/dist/resources/computers.d.ts +2 -7
- package/dist/resources/connectors.d.ts +385 -0
- package/dist/resources/headless.d.ts +1 -1
- package/dist/resources/llm.d.ts +64 -0
- package/dist/resources/models.d.ts +6 -1
- package/dist/resources/pack-records.d.ts +26 -0
- package/dist/resources/phones.d.ts +106 -0
- package/dist/resources/plugins.d.ts +22 -0
- package/dist/resources/profile.d.ts +100 -0
- package/dist/resources/sandbox.d.ts +22 -0
- package/dist/resources/sessions.d.ts +126 -11
- package/dist/schemas/ask-user-question.d.ts +21 -0
- package/dist/schemas/context-attachments.d.ts +20 -0
- package/dist/schemas/message-utils.d.ts +3 -9
- package/dist/schemas/message.d.ts +16 -2
- package/dist/schemas/plugin-refs.d.ts +7 -0
- package/dist/schemas/projection.d.ts +14 -1
- package/dist/schemas/session.d.ts +3 -48
- package/dist/server-clock.d.ts +2 -0
- package/dist/session/agent-session.d.ts +45 -95
- package/dist/session/definition.d.ts +4 -0
- package/dist/session/events.d.ts +0 -1
- package/dist/session/hub.d.ts +0 -24
- package/dist/session/queue.d.ts +2 -0
- package/dist/session/state.d.ts +8 -1
- package/dist/session/workflow.d.ts +10 -3
- package/dist/shared/pack-events.d.ts +4 -0
- package/dist/shared/projection/builder.d.ts +0 -2
- package/dist/shared/projection/index.d.ts +1 -0
- package/dist/shared/projection/workflow.d.ts +24 -0
- package/dist/tool-provider.d.ts +60 -0
- package/dist/types/sdk-profile.d.ts +1 -0
- package/dist/types/socket-events.d.ts +191 -11
- package/dist/version.d.ts +0 -1
- package/node_modules/engine.io-client/build/cjs/globals.node.d.ts +2 -3
- package/node_modules/engine.io-client/build/cjs/index.d.ts +3 -3
- package/node_modules/engine.io-client/build/cjs/index.js +1 -4
- package/node_modules/engine.io-client/build/cjs/socket.d.ts +39 -82
- package/node_modules/engine.io-client/build/cjs/socket.js +151 -218
- package/node_modules/engine.io-client/build/cjs/transport.d.ts +1 -1
- package/node_modules/engine.io-client/build/cjs/transports/polling-xhr.d.ts +4 -4
- package/node_modules/engine.io-client/build/cjs/transports/polling-xhr.js +2 -2
- package/node_modules/engine.io-client/build/cjs/transports/polling-xhr.node.js +17 -7
- package/node_modules/engine.io-client/build/cjs/transports/websocket.node.js +17 -7
- package/node_modules/engine.io-client/build/esm/globals.node.d.ts +2 -3
- package/node_modules/engine.io-client/build/esm/index.d.ts +3 -3
- package/node_modules/engine.io-client/build/esm/index.js +1 -2
- package/node_modules/engine.io-client/build/esm/socket.d.ts +39 -82
- package/node_modules/engine.io-client/build/esm/socket.js +141 -206
- package/node_modules/engine.io-client/build/esm/transport.d.ts +1 -1
- package/node_modules/engine.io-client/build/esm/transports/polling-xhr.d.ts +4 -4
- package/node_modules/engine.io-client/build/esm/transports/polling-xhr.js +2 -2
- package/node_modules/engine.io-client/build/esm-debug/globals.node.d.ts +2 -3
- package/node_modules/engine.io-client/build/esm-debug/index.d.ts +3 -3
- package/node_modules/engine.io-client/build/esm-debug/index.js +1 -2
- package/node_modules/engine.io-client/build/esm-debug/socket.d.ts +39 -82
- package/node_modules/engine.io-client/build/esm-debug/socket.js +150 -215
- package/node_modules/engine.io-client/build/esm-debug/transport.d.ts +1 -1
- package/node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.d.ts +4 -4
- package/node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.js +2 -2
- package/node_modules/engine.io-client/dist/engine.io.esm.min.js +3 -3
- package/node_modules/engine.io-client/dist/engine.io.esm.min.js.map +1 -1
- package/node_modules/engine.io-client/dist/engine.io.js +164 -239
- package/node_modules/engine.io-client/dist/engine.io.js.map +1 -1
- package/node_modules/engine.io-client/dist/engine.io.min.js +3 -3
- package/node_modules/engine.io-client/dist/engine.io.min.js.map +1 -1
- package/node_modules/engine.io-client/package.json +2 -2
- package/node_modules/socket.io-parser/build/cjs/binary.js +4 -1
- package/node_modules/socket.io-parser/build/cjs/index.d.ts +14 -4
- package/node_modules/socket.io-parser/build/cjs/index.js +18 -11
- package/node_modules/socket.io-parser/build/esm/binary.js +4 -1
- package/node_modules/socket.io-parser/build/esm/index.d.ts +14 -4
- package/node_modules/socket.io-parser/build/esm/index.js +14 -10
- package/node_modules/socket.io-parser/build/esm-debug/binary.js +4 -1
- package/node_modules/socket.io-parser/build/esm-debug/index.d.ts +14 -4
- package/node_modules/socket.io-parser/build/esm-debug/index.js +14 -10
- package/node_modules/socket.io-parser/package.json +1 -1
- package/node_modules/ws/index.js +15 -6
- package/node_modules/ws/lib/constants.js +1 -0
- package/node_modules/ws/lib/permessage-deflate.js +9 -7
- package/node_modules/ws/lib/receiver.js +37 -0
- package/node_modules/ws/lib/sender.js +6 -1
- package/node_modules/ws/lib/websocket-server.js +18 -6
- package/node_modules/ws/lib/websocket.js +50 -17
- package/node_modules/ws/package.json +8 -3
- package/node_modules/ws/wrapper.mjs +14 -1
- package/package.json +4 -4
- package/public-api.md +851 -36
- package/dist/chunk-ZTHGY4OX.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.
|
|
230
|
+
var SDK_VERSION = true ? "2612.0.0-beta.80" : "1.1.1";
|
|
4
231
|
|
|
5
232
|
// src/auth-login.ts
|
|
6
233
|
function isAuthCallbackMessage(value) {
|
|
@@ -128,53 +355,118 @@ async function loginWithPopup(client, options = {}) {
|
|
|
128
355
|
});
|
|
129
356
|
}
|
|
130
357
|
|
|
131
|
-
// src/
|
|
132
|
-
var
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
this.
|
|
358
|
+
// src/resources/pack-records.ts
|
|
359
|
+
var PackRecordsResource = class {
|
|
360
|
+
constructor(client) {
|
|
361
|
+
this.client = client;
|
|
362
|
+
}
|
|
363
|
+
client;
|
|
364
|
+
list(pack, collection, query = {}, init) {
|
|
365
|
+
const params = new URLSearchParams();
|
|
366
|
+
if (query.filter) params.set("filter", JSON.stringify(query.filter));
|
|
367
|
+
if (query.limit !== void 0) params.set("limit", String(query.limit));
|
|
368
|
+
if (query.offset !== void 0) params.set("offset", String(query.offset));
|
|
369
|
+
return this.client.jsonFromInit(`${this.path(pack, collection)}?${params}`, init);
|
|
370
|
+
}
|
|
371
|
+
upsert(pack, collection, data, id) {
|
|
372
|
+
return this.client.json("POST", this.path(pack, collection), { id, data });
|
|
373
|
+
}
|
|
374
|
+
delete(pack, collection, id) {
|
|
375
|
+
return this.client.json("DELETE", `${this.path(pack, collection)}/${encodeURIComponent(id)}`);
|
|
376
|
+
}
|
|
377
|
+
/** Events are invalidations. Refresh the list on reconnect as well. */
|
|
378
|
+
onChanged(pack, collection, listener) {
|
|
379
|
+
let socket = this.client.socket();
|
|
380
|
+
const changed = (value) => {
|
|
381
|
+
if (value.pack === pack && value.collection === collection) listener();
|
|
382
|
+
};
|
|
383
|
+
const bind = () => {
|
|
384
|
+
socket.on("pack:records_changed", changed);
|
|
385
|
+
socket.on("connect", listener);
|
|
386
|
+
};
|
|
387
|
+
const unbind = () => {
|
|
388
|
+
socket.off("pack:records_changed", changed);
|
|
389
|
+
socket.off("connect", listener);
|
|
390
|
+
};
|
|
391
|
+
bind();
|
|
392
|
+
const off = this.client.onSocketReplaced(() => {
|
|
393
|
+
unbind();
|
|
394
|
+
socket = this.client.socket();
|
|
395
|
+
bind();
|
|
396
|
+
listener();
|
|
397
|
+
});
|
|
398
|
+
return () => {
|
|
399
|
+
off();
|
|
400
|
+
unbind();
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
path(pack, collection) {
|
|
404
|
+
return `/api/packs/${encodeURIComponent(pack)}/records/${encodeURIComponent(collection)}`;
|
|
143
405
|
}
|
|
144
406
|
};
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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 {
|
|
407
|
+
|
|
408
|
+
// src/resources/profile.ts
|
|
409
|
+
var ProfileResource = class {
|
|
410
|
+
constructor(client) {
|
|
411
|
+
this.client = client;
|
|
162
412
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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`;
|
|
413
|
+
client;
|
|
414
|
+
get(init) {
|
|
415
|
+
return this.client.jsonFromInit("/api/profile", init);
|
|
171
416
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
417
|
+
/** Also refresh after reconnect, since changes may have happened offline. */
|
|
418
|
+
onChanged(listener) {
|
|
419
|
+
let socket = this.client.socket();
|
|
420
|
+
const bind = () => {
|
|
421
|
+
socket.on("profile:changed", listener);
|
|
422
|
+
socket.on("connect", listener);
|
|
423
|
+
};
|
|
424
|
+
const unbind = () => {
|
|
425
|
+
socket.off("profile:changed", listener);
|
|
426
|
+
socket.off("connect", listener);
|
|
427
|
+
};
|
|
428
|
+
bind();
|
|
429
|
+
const off = this.client.onSocketReplaced(() => {
|
|
430
|
+
unbind();
|
|
431
|
+
socket = this.client.socket();
|
|
432
|
+
bind();
|
|
433
|
+
listener();
|
|
434
|
+
});
|
|
435
|
+
return () => {
|
|
436
|
+
off();
|
|
437
|
+
unbind();
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
var PacksResource = class {
|
|
442
|
+
constructor(client) {
|
|
443
|
+
this.client = client;
|
|
444
|
+
this.records = new PackRecordsResource(client);
|
|
445
|
+
}
|
|
446
|
+
client;
|
|
447
|
+
records;
|
|
448
|
+
sessionByTag(name, tag, init) {
|
|
449
|
+
return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/sessions/by-tag?${new URLSearchParams({ tag })}`, init);
|
|
450
|
+
}
|
|
451
|
+
list() {
|
|
452
|
+
return this.client.json("GET", "/api/packs");
|
|
453
|
+
}
|
|
454
|
+
save(manifest, files = {}) {
|
|
455
|
+
return this.client.json("POST", "/api/packs", { manifest, files });
|
|
456
|
+
}
|
|
457
|
+
enable(name) {
|
|
458
|
+
return this.client.json("POST", `/api/packs/${encodeURIComponent(name)}/enable`);
|
|
459
|
+
}
|
|
460
|
+
disable(name) {
|
|
461
|
+
return this.client.json("POST", `/api/packs/${encodeURIComponent(name)}/disable`);
|
|
462
|
+
}
|
|
463
|
+
reset() {
|
|
464
|
+
return this.client.json("POST", "/api/packs/reset");
|
|
465
|
+
}
|
|
466
|
+
file(name, path, init) {
|
|
467
|
+
return this.client.textFromInit(`/api/packs/${encodeURIComponent(name)}/files/${path.split("/").map(encodeURIComponent).join("/")}`, init);
|
|
468
|
+
}
|
|
469
|
+
};
|
|
178
470
|
|
|
179
471
|
// src/resources/auth.ts
|
|
180
472
|
var AuthResource = class {
|
|
@@ -182,6 +474,16 @@ var AuthResource = class {
|
|
|
182
474
|
this.client = client;
|
|
183
475
|
}
|
|
184
476
|
client;
|
|
477
|
+
subaccounts() {
|
|
478
|
+
return this.client.json("GET", "/api/auth/subaccounts");
|
|
479
|
+
}
|
|
480
|
+
createSubaccount(name, requestId) {
|
|
481
|
+
return this.client.json("POST", "/api/auth/subaccounts", { name, request_id: requestId });
|
|
482
|
+
}
|
|
483
|
+
/** Server-side only: keep the returned execution credential out of the UI. */
|
|
484
|
+
subaccountCredential(id) {
|
|
485
|
+
return this.client.json("POST", `/api/auth/subaccounts/${encodeURIComponent(id)}/credential`, {});
|
|
486
|
+
}
|
|
185
487
|
/**
|
|
186
488
|
* 弹窗授权登录(浏览器专用):弹出后端授权页,用户点击"许可授权"后
|
|
187
489
|
* 自动取得 PAT 并热挂载到当前 client。等价于 client.login()。
|
|
@@ -202,6 +504,7 @@ var AuthResource = class {
|
|
|
202
504
|
headers: { Origin: params.clientOrigin },
|
|
203
505
|
body: JSON.stringify({
|
|
204
506
|
code: params.code,
|
|
507
|
+
...params.codeVerifier ? { code_verifier: params.codeVerifier, android_app: params.androidApp, desktop_app: params.desktopApp, callback_uri: params.callbackUri } : {},
|
|
205
508
|
state: params.state,
|
|
206
509
|
client_origin: params.clientOrigin
|
|
207
510
|
})
|
|
@@ -214,8 +517,8 @@ var AuthResource = class {
|
|
|
214
517
|
getProviders() {
|
|
215
518
|
return this.client.json("GET", "/api/auth/providers");
|
|
216
519
|
}
|
|
217
|
-
getMe() {
|
|
218
|
-
return this.client.
|
|
520
|
+
getMe(options = {}) {
|
|
521
|
+
return this.client.jsonFromInit("/api/auth/me", { signal: options.signal });
|
|
219
522
|
}
|
|
220
523
|
logout() {
|
|
221
524
|
return this.client.json("POST", "/api/auth/logout");
|
|
@@ -280,6 +583,52 @@ var LogCursor = class {
|
|
|
280
583
|
}
|
|
281
584
|
};
|
|
282
585
|
|
|
586
|
+
// src/schemas/context-attachments.ts
|
|
587
|
+
function snapshotContextAttachments(value) {
|
|
588
|
+
const snapshot2 = JSON.parse(JSON.stringify(value));
|
|
589
|
+
if (!Array.isArray(snapshot2) || snapshot2.length > 20) throw new Error("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u63D0\u4F9B 20 \u4EFD\u8D44\u6599");
|
|
590
|
+
const ids = /* @__PURE__ */ new Set();
|
|
591
|
+
const validText = (text, limit) => typeof text === "string" && [...text].length > 0 && [...text].length <= limit;
|
|
592
|
+
for (const item of snapshot2) {
|
|
593
|
+
if (!item || !validText(item.id, 128) || !validText(item.label, 512) || item.action !== "remove" && !validText(item.content, 64e3) || ids.has(item.id)) throw new Error("\u9644\u52A0\u8D44\u6599\u683C\u5F0F\u9519\u8BEF\u6216 ID \u91CD\u590D");
|
|
594
|
+
if (item.action != null && item.action !== "remove" && item.action !== "restore") throw new Error("\u8D44\u6599\u64CD\u4F5C\u65E0\u6548");
|
|
595
|
+
if (item.action === "restore" && item.update_format === void 0) throw new Error("\u6062\u590D\u4F1A\u8BDD\u8D44\u6599\u9700\u8981\u63D0\u4F9B\u5B8C\u6574\u5FEB\u7167\u7684\u66F4\u65B0\u683C\u5F0F");
|
|
596
|
+
if (item.action === "remove" && (item.content !== "" || item.data != null || (item.files?.length ?? 0) > 0 || item.update_format !== void 0)) throw new Error("\u64A4\u9500\u8D44\u6599\u4E0D\u80FD\u540C\u65F6\u63D0\u4F9B\u6B63\u6587\u3001\u6570\u636E\u3001\u6587\u4EF6\u6216\u66F4\u65B0\u683C\u5F0F");
|
|
597
|
+
ids.add(item.id);
|
|
598
|
+
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");
|
|
599
|
+
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");
|
|
600
|
+
if (item.files != null && (!Array.isArray(item.files) || item.files.length > 20)) throw new Error("\u8D44\u6599\u6587\u4EF6\u683C\u5F0F\u9519\u8BEF");
|
|
601
|
+
for (const file of item.files ?? []) {
|
|
602
|
+
if (!validText(file.name, 512)) throw new Error("\u8D44\u6599\u6587\u4EF6\u540D\u683C\u5F0F\u9519\u8BEF");
|
|
603
|
+
if (file.session_id == null && file.path == null) continue;
|
|
604
|
+
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");
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
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");
|
|
608
|
+
return snapshot2;
|
|
609
|
+
}
|
|
610
|
+
function normalizeContextAttachments(value) {
|
|
611
|
+
return Array.isArray(value) ? value : [];
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// src/shared/pack-events.ts
|
|
615
|
+
function packEventNotification(source) {
|
|
616
|
+
if (!isRecord(source) || typeof source.pack !== "string" || !source.pack || typeof source.event_id !== "string" || !source.event_id || typeof source.title !== "string") return null;
|
|
617
|
+
return { type: "system_notification", content: {
|
|
618
|
+
notification_type: "pack:event",
|
|
619
|
+
status: "received",
|
|
620
|
+
title: `\u6765\u81EA\u300E${source.title}\u300F\u7684\u4E8B\u4EF6`,
|
|
621
|
+
detail: null,
|
|
622
|
+
metadata: source
|
|
623
|
+
} };
|
|
624
|
+
}
|
|
625
|
+
function packEventTitle(message) {
|
|
626
|
+
for (const block of message.blocks ?? []) {
|
|
627
|
+
if (block.type === "system_notification" && isRecord(block.content) && block.content.notification_type === "pack:event" && typeof block.content.title === "string") return block.content.title;
|
|
628
|
+
}
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
|
|
283
632
|
// src/schemas/plugin-refs.ts
|
|
284
633
|
function normalizePluginRefs(value) {
|
|
285
634
|
if (!Array.isArray(value)) return [];
|
|
@@ -292,6 +641,19 @@ function normalizePluginRefs(value) {
|
|
|
292
641
|
return [{ provider: "plugin", plugin: item.plugin, server: item.server, id: item.id, label: item.label }];
|
|
293
642
|
});
|
|
294
643
|
}
|
|
644
|
+
function normalizeMessageRefs(value) {
|
|
645
|
+
if (!Array.isArray(value)) return [];
|
|
646
|
+
const seen = /* @__PURE__ */ new Set();
|
|
647
|
+
return value.flatMap((item) => {
|
|
648
|
+
if (!item || typeof item !== "object") return [];
|
|
649
|
+
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];
|
|
650
|
+
if (!ref) return [];
|
|
651
|
+
const key = ref.provider === "skill" ? JSON.stringify([ref.provider, ref.id]) : JSON.stringify([ref.provider, ref.plugin, ref.server, ref.id]);
|
|
652
|
+
if (seen.has(key)) return [];
|
|
653
|
+
seen.add(key);
|
|
654
|
+
return [ref];
|
|
655
|
+
});
|
|
656
|
+
}
|
|
295
657
|
|
|
296
658
|
// src/schemas/topic-assets.ts
|
|
297
659
|
function normalizeTopicAssetRefs(value) {
|
|
@@ -667,14 +1029,14 @@ function applyAskUserPauseToTurn(turn, pauseToolData, toolCallId, childLoopName,
|
|
|
667
1029
|
}
|
|
668
1030
|
function spacedJson(value) {
|
|
669
1031
|
try {
|
|
670
|
-
const
|
|
671
|
-
if (Array.isArray(item)) return `[${item.map(
|
|
1032
|
+
const encode2 = (item) => {
|
|
1033
|
+
if (Array.isArray(item)) return `[${item.map(encode2).join(", ")}]`;
|
|
672
1034
|
if (item && typeof item === "object") {
|
|
673
|
-
return `{${Object.entries(item).map(([key, part]) => `${JSON.stringify(key)}: ${
|
|
1035
|
+
return `{${Object.entries(item).map(([key, part]) => `${JSON.stringify(key)}: ${encode2(part)}`).join(", ")}}`;
|
|
674
1036
|
}
|
|
675
1037
|
return JSON.stringify(item) ?? "null";
|
|
676
1038
|
};
|
|
677
|
-
return
|
|
1039
|
+
return encode2(JSON.parse(value));
|
|
678
1040
|
} catch {
|
|
679
1041
|
return value;
|
|
680
1042
|
}
|
|
@@ -843,23 +1205,12 @@ function normalizeChildPause(pausePayload) {
|
|
|
843
1205
|
}
|
|
844
1206
|
function attachToolEvidence(call, evidence) {
|
|
845
1207
|
if (!call) return;
|
|
846
|
-
call.evidence = call.status === "done" && Array.isArray(evidence) ? evidence : void 0;
|
|
1208
|
+
call.evidence = (call.status === "done" || call.status === "error") && Array.isArray(evidence) ? evidence : void 0;
|
|
847
1209
|
}
|
|
848
1210
|
|
|
849
1211
|
// src/schemas/message.ts
|
|
850
1212
|
function inferToolStatus(resultStr) {
|
|
851
1213
|
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
1214
|
return "done";
|
|
864
1215
|
}
|
|
865
1216
|
|
|
@@ -903,8 +1254,8 @@ function snapshot(state, sequence, status) {
|
|
|
903
1254
|
first_token_ms: state.firstTokenMs,
|
|
904
1255
|
stream_duration_ms: state.streamDurationMs,
|
|
905
1256
|
first_token_delivery_ms: state.firstTokenDeliveryMs,
|
|
906
|
-
started_at: state.modelStartedAt
|
|
907
|
-
//
|
|
1257
|
+
started_at: state.modelStartedAt,
|
|
1258
|
+
// 未上报时不伪造服务器起点;浏览器时钟不能与服务器时钟混用。
|
|
908
1259
|
has_reported_timing: state.modelStartedAtReported,
|
|
909
1260
|
context_window: state.contextWindow,
|
|
910
1261
|
memory_refs: state.memoryRefs,
|
|
@@ -1130,10 +1481,8 @@ var ClientProjectionBuilder = class {
|
|
|
1130
1481
|
latestTurns = /* @__PURE__ */ new Map();
|
|
1131
1482
|
turnsById = /* @__PURE__ */ new Map();
|
|
1132
1483
|
loopDescriptions = /* @__PURE__ */ new Map();
|
|
1133
|
-
/** loop_name → 正在运行的子智能体起点,agent:end 结算并挂到父工具调用上。 */
|
|
1134
1484
|
activeSubagentRuns = /* @__PURE__ */ new Map();
|
|
1135
1485
|
pendingChildPauses = /* @__PURE__ */ new Map();
|
|
1136
|
-
/** 作答后子回路续跑,最终回复就是随后落盘的父 Agent 工具结果。 */
|
|
1137
1486
|
answeredChildParents = /* @__PURE__ */ new Map();
|
|
1138
1487
|
pendingMemoryRefs = /* @__PURE__ */ new Map();
|
|
1139
1488
|
activeCompactions = /* @__PURE__ */ new Map();
|
|
@@ -1289,6 +1638,11 @@ var ClientProjectionBuilder = class {
|
|
|
1289
1638
|
/** A durable snapshot supersedes only this turn's temporary overlay. */
|
|
1290
1639
|
acceptDurableTurn(turn) {
|
|
1291
1640
|
this.seedSequence(turn.sequence);
|
|
1641
|
+
if (turn.kind === "compaction") {
|
|
1642
|
+
this.turnsById.set(turn.turn_id, turn);
|
|
1643
|
+
if (turn.status !== "streaming") this.activeCompactions.delete(turn.compaction_id ?? "");
|
|
1644
|
+
return;
|
|
1645
|
+
}
|
|
1292
1646
|
if (!isConversationTurn(turn)) return;
|
|
1293
1647
|
const active = this.activeTurns.get(turn.loop_id);
|
|
1294
1648
|
if (active?.turnId === turn.turn_id) this.activeTurns.delete(turn.loop_id);
|
|
@@ -1309,6 +1663,7 @@ var ClientProjectionBuilder = class {
|
|
|
1309
1663
|
const turnsById = /* @__PURE__ */ new Map();
|
|
1310
1664
|
for (const turn of turns) {
|
|
1311
1665
|
this.seedSequence(turn.sequence);
|
|
1666
|
+
if (turn.kind === "compaction") turnsById.set(turn.turn_id, turn);
|
|
1312
1667
|
if (!isConversationTurn(turn)) continue;
|
|
1313
1668
|
turnsById.set(turn.turn_id, turn);
|
|
1314
1669
|
const current = latestTurns.get(turn.loop_id);
|
|
@@ -1319,7 +1674,6 @@ var ClientProjectionBuilder = class {
|
|
|
1319
1674
|
this.latestTurns = latestTurns;
|
|
1320
1675
|
this.turnsById = turnsById;
|
|
1321
1676
|
}
|
|
1322
|
-
// --- Event handlers ---
|
|
1323
1677
|
onMemoryInject(loopId, payload) {
|
|
1324
1678
|
const refs = payload.memory_refs;
|
|
1325
1679
|
const turnId = String(payload.turn_id ?? "");
|
|
@@ -1545,7 +1899,7 @@ var ClientProjectionBuilder = class {
|
|
|
1545
1899
|
onUserMessage(_loopId, payload) {
|
|
1546
1900
|
const entryId = String(payload.entry_id ?? this.nextTurnId("user"));
|
|
1547
1901
|
const displayContent = payload.display_content ?? payload.content ?? "";
|
|
1548
|
-
const refs =
|
|
1902
|
+
const refs = normalizeMessageRefs(payload.refs);
|
|
1549
1903
|
const turn = {
|
|
1550
1904
|
id: entryId,
|
|
1551
1905
|
sequence: this.nextSeq(),
|
|
@@ -1556,6 +1910,7 @@ var ClientProjectionBuilder = class {
|
|
|
1556
1910
|
status: "completed",
|
|
1557
1911
|
blocks: [{ type: "text", content: displayContent }],
|
|
1558
1912
|
...refs.length ? { refs } : {},
|
|
1913
|
+
context_attachments: normalizeContextAttachments(payload.context_attachments),
|
|
1559
1914
|
topic_asset_refs: normalizeTopicAssetRefs(payload.topic_asset_refs),
|
|
1560
1915
|
tool_calls: [],
|
|
1561
1916
|
model: null,
|
|
@@ -1566,6 +1921,8 @@ var ClientProjectionBuilder = class {
|
|
|
1566
1921
|
if (payload.start_reason === "background-completion") {
|
|
1567
1922
|
turn.blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
|
|
1568
1923
|
}
|
|
1924
|
+
const packEvent = packEventNotification(payload.pack_event);
|
|
1925
|
+
if (packEvent) turn.blocks.push(packEvent);
|
|
1569
1926
|
this.latestTurns.set("root", turn);
|
|
1570
1927
|
return [{ kind: "upsert", turn }];
|
|
1571
1928
|
}
|
|
@@ -1584,7 +1941,6 @@ var ClientProjectionBuilder = class {
|
|
|
1584
1941
|
this.latestTurns.set("root", turn);
|
|
1585
1942
|
return [{ kind: "upsert", turn }];
|
|
1586
1943
|
}
|
|
1587
|
-
// --- Delta / streaming events ---
|
|
1588
1944
|
onDelta(state, blockType, _toolCallId, content) {
|
|
1589
1945
|
if (!content) return null;
|
|
1590
1946
|
appendTextBlock(state, blockType, content);
|
|
@@ -1636,10 +1992,7 @@ var ClientProjectionBuilder = class {
|
|
|
1636
1992
|
if (!applyResponseBlockOrder(state, payload.response_blocks) && "content" in payload) {
|
|
1637
1993
|
replaceTextContent(state, completedResponseText(payload.content));
|
|
1638
1994
|
}
|
|
1639
|
-
|
|
1640
|
-
if (state.toolCalls.length === 0 || isNativeProviderResponse && state.toolCalls.every(
|
|
1641
|
-
(toolCall) => toolCall.status !== "pending" && toolCall.status !== "awaiting_answer"
|
|
1642
|
-
)) {
|
|
1995
|
+
if (state.toolCalls.length === 0) {
|
|
1643
1996
|
const childParent = this.answeredChildParents.get(loopId);
|
|
1644
1997
|
if (childParent) {
|
|
1645
1998
|
this.answeredChildParents.delete(loopId);
|
|
@@ -1656,6 +2009,7 @@ var ClientProjectionBuilder = class {
|
|
|
1656
2009
|
return this.syncPatch(state);
|
|
1657
2010
|
}
|
|
1658
2011
|
applyFirstTokenDelivery(state, payload) {
|
|
2012
|
+
this.applyStreamTiming(state, payload);
|
|
1659
2013
|
const firstTokenMs = payload.first_token_ms;
|
|
1660
2014
|
if (state.firstTokenMs === null && typeof firstTokenMs === "number" && firstTokenMs >= 0) {
|
|
1661
2015
|
state.firstTokenMs = Math.round(firstTokenMs);
|
|
@@ -1684,7 +2038,7 @@ var ClientProjectionBuilder = class {
|
|
|
1684
2038
|
const toolCallId = String(payload.tool_call_id ?? "");
|
|
1685
2039
|
const streamedResult = state.toolCalls.find((toolCall) => toolCall.id === toolCallId)?.result;
|
|
1686
2040
|
const content = payload.content_from_deltas === true ? streamedResult ?? "" : payload.content ?? "";
|
|
1687
|
-
const status = payload.is_error === true ? "error" : toolStatusFromResult(content);
|
|
2041
|
+
const status = payload.is_error === true ? "error" : payload._tool_pending === true ? "pending" : toolStatusFromResult(content);
|
|
1688
2042
|
const rawDuration = payload.duration_ms;
|
|
1689
2043
|
const durationMs = typeof rawDuration === "number" && rawDuration >= 0 ? Math.round(rawDuration) : null;
|
|
1690
2044
|
const ranInParallel = typeof payload.ran_in_parallel === "boolean" ? payload.ran_in_parallel : null;
|
|
@@ -1705,8 +2059,7 @@ var ClientProjectionBuilder = class {
|
|
|
1705
2059
|
this.displayNameResolver
|
|
1706
2060
|
);
|
|
1707
2061
|
}
|
|
1708
|
-
|
|
1709
|
-
if (!isNativeProviderResult && this.shouldFinalizeAfterToolResults(state)) {
|
|
2062
|
+
if (this.shouldFinalizeAfterToolResults(state)) {
|
|
1710
2063
|
return this.finalize(loopId, "completed");
|
|
1711
2064
|
}
|
|
1712
2065
|
return this.syncPatch(state);
|
|
@@ -1928,6 +2281,8 @@ var ClientProjectionBuilder = class {
|
|
|
1928
2281
|
onCompaction(eventType, loopId, payload) {
|
|
1929
2282
|
const compactionId = String(payload.compaction_id ?? "");
|
|
1930
2283
|
if (!compactionId) return null;
|
|
2284
|
+
const previous = this.turnsById.get(`compaction:${compactionId}`);
|
|
2285
|
+
if (eventType === "compaction:start" && previous && previous.status !== "streaming") return null;
|
|
1931
2286
|
let current = {
|
|
1932
2287
|
...this.activeCompactions.get(compactionId) ?? {},
|
|
1933
2288
|
...payload,
|
|
@@ -1965,7 +2320,6 @@ var ClientProjectionBuilder = class {
|
|
|
1965
2320
|
const turn = buildCompactionTurn(this.nextSeq(), compactionId, loopId, status, current);
|
|
1966
2321
|
return [{ kind: "upsert", turn }];
|
|
1967
2322
|
}
|
|
1968
|
-
// --- Internal helpers ---
|
|
1969
2323
|
syncPatch(state) {
|
|
1970
2324
|
const turn = snapshot(state, this.nextSeq(), "streaming");
|
|
1971
2325
|
this.latestTurns.set(state.loopId, turn);
|
|
@@ -2145,7 +2499,6 @@ function projectHistory(entries) {
|
|
|
2145
2499
|
const pendingChildPauses = /* @__PURE__ */ new Map();
|
|
2146
2500
|
const childPauseEntries = [];
|
|
2147
2501
|
const answeredToolCallIds = /* @__PURE__ */ new Set();
|
|
2148
|
-
const nativeToolTurns = /* @__PURE__ */ new Set();
|
|
2149
2502
|
const turnEntryAliases = /* @__PURE__ */ new Map();
|
|
2150
2503
|
let latestRootMessage = null;
|
|
2151
2504
|
let latestRootAssistant = null;
|
|
@@ -2211,7 +2564,7 @@ function projectHistory(entries) {
|
|
|
2211
2564
|
const owner = toolOwners.get(toolCallId);
|
|
2212
2565
|
const toolCall = owner?.tool_calls.find((item) => item.id === toolCallId);
|
|
2213
2566
|
if (owner && toolCall) {
|
|
2214
|
-
toolCall.status = message._error ? "error" : inferToolStatus(String(message.content ?? ""));
|
|
2567
|
+
toolCall.status = message._error ? "error" : message._tool_pending === true ? "pending" : inferToolStatus(String(message.content ?? ""));
|
|
2215
2568
|
toolCall.result = message.content ?? "";
|
|
2216
2569
|
attachToolEvidence(toolCall, message._evidence);
|
|
2217
2570
|
const duration = numberOrNull(message._duration_ms);
|
|
@@ -2220,11 +2573,9 @@ function projectHistory(entries) {
|
|
|
2220
2573
|
toolCall.started_at = message._started_at;
|
|
2221
2574
|
}
|
|
2222
2575
|
if (message._ran_in_parallel === true) toolCall.ran_in_parallel = true;
|
|
2223
|
-
owner.blocks.
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
tool_call_id: toolCallId
|
|
2227
|
-
});
|
|
2576
|
+
const existing = owner.blocks.find((block) => block.type === "tool_result" && block.tool_call_id === toolCallId);
|
|
2577
|
+
if (existing) existing.content = message.content ?? "";
|
|
2578
|
+
else owner.blocks.push({ type: "tool_result", content: message.content ?? "", tool_call_id: toolCallId });
|
|
2228
2579
|
}
|
|
2229
2580
|
continue;
|
|
2230
2581
|
}
|
|
@@ -2234,6 +2585,8 @@ function projectHistory(entries) {
|
|
|
2234
2585
|
if (role === "user" && message._start_reason === "background-completion") {
|
|
2235
2586
|
blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
|
|
2236
2587
|
}
|
|
2588
|
+
const packEvent = role === "user" ? packEventNotification(message._pack_event) : null;
|
|
2589
|
+
if (packEvent) blocks.push(packEvent);
|
|
2237
2590
|
const turn = {
|
|
2238
2591
|
id,
|
|
2239
2592
|
sequence: ++sequence,
|
|
@@ -2241,56 +2594,29 @@ function projectHistory(entries) {
|
|
|
2241
2594
|
loop_id: loopId,
|
|
2242
2595
|
kind: "message",
|
|
2243
2596
|
role,
|
|
2597
|
+
client_request_id: stringOrNull(entry.client_request_id),
|
|
2244
2598
|
status: message._error ? "failed" : message._interrupted ? "interrupted" : "completed",
|
|
2245
2599
|
blocks,
|
|
2246
2600
|
tool_calls: toolCalls,
|
|
2247
2601
|
model: stringOrNull(message.model),
|
|
2248
2602
|
usage: isRecord(message._usage) ? { ...message._usage } : null,
|
|
2249
|
-
// 模型请求区间来自持久化字段;旧会话缺失时为 null,不用落盘时刻冒充(#2581 A1)。
|
|
2250
2603
|
duration_ms: numberOrNull(message._duration_ms),
|
|
2251
2604
|
first_token_ms: numberOrNull(message._first_token_ms),
|
|
2252
2605
|
stream_duration_ms: numberOrNull(message._stream_duration_ms),
|
|
2253
2606
|
started_at: typeof message._started_at === "string" ? message._started_at : typeof entry.timestamp === "string" ? entry.timestamp : void 0,
|
|
2254
2607
|
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
2608
|
parent_fork_tool_call_id: stringOrNull(message._parent_fork_tool_call_id)
|
|
2259
2609
|
};
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
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;
|
|
2610
|
+
if (role === "user") {
|
|
2611
|
+
const refs = normalizeMessageRefs(message.refs);
|
|
2612
|
+
if (refs.length) turn.refs = refs;
|
|
2613
|
+
turn.context_attachments = normalizeContextAttachments(message.context_attachments);
|
|
2287
2614
|
}
|
|
2288
2615
|
if (loopId === "root" && (role === "user" || role === "assistant")) {
|
|
2289
2616
|
latestRootMessage = turn;
|
|
2290
2617
|
}
|
|
2291
2618
|
turns.push(turn);
|
|
2292
2619
|
turnEntryAliases.set(id, turn);
|
|
2293
|
-
if (isNativeToolEntry) nativeToolTurns.add(turn);
|
|
2294
2620
|
if (role === "assistant") latestAssistantByLoop.set(loopId, turn);
|
|
2295
2621
|
if (loopId === "root") {
|
|
2296
2622
|
if (role === "assistant") latestRootAssistant = turn;
|
|
@@ -2306,7 +2632,7 @@ function projectHistory(entries) {
|
|
|
2306
2632
|
if (owner && toolCallId) {
|
|
2307
2633
|
const rawContent = data.content;
|
|
2308
2634
|
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));
|
|
2635
|
+
const status = data.is_error === true ? "error" : data._tool_pending === true ? "pending" : inferToolStatus(typeof content === "string" ? content : JSON.stringify(content));
|
|
2310
2636
|
setToolCallStatus(owner, toolCallId, status, content, null);
|
|
2311
2637
|
if (!owner.blocks.some((block) => block.type === "tool_result" && block.tool_call_id === toolCallId)) {
|
|
2312
2638
|
owner.blocks.push({ type: "tool_result", content, tool_call_id: toolCallId });
|
|
@@ -2314,6 +2640,33 @@ function projectHistory(entries) {
|
|
|
2314
2640
|
}
|
|
2315
2641
|
continue;
|
|
2316
2642
|
}
|
|
2643
|
+
if (kind === "workflow_step") {
|
|
2644
|
+
const data = entry.data ?? {};
|
|
2645
|
+
const toolCallId = String(data.tool_call_id ?? "");
|
|
2646
|
+
const owner = toolOwners.get(toolCallId) ?? findLatestAssistant(turns, loopId);
|
|
2647
|
+
if (owner && toolCallId) {
|
|
2648
|
+
const index = owner.tool_calls.findIndex((call) => call.id === toolCallId);
|
|
2649
|
+
if (index >= 0) {
|
|
2650
|
+
const call = owner.tool_calls[index];
|
|
2651
|
+
owner.tool_calls[index] = {
|
|
2652
|
+
...call,
|
|
2653
|
+
workflow_steps: [
|
|
2654
|
+
...call.workflow_steps ?? [],
|
|
2655
|
+
{
|
|
2656
|
+
step_id: String(data.step_id ?? ""),
|
|
2657
|
+
desc: String(data.desc ?? ""),
|
|
2658
|
+
step_kind: String(data.step_kind ?? "step"),
|
|
2659
|
+
status: String(data.status ?? "done"),
|
|
2660
|
+
output: String(data.output ?? ""),
|
|
2661
|
+
...typeof data.seq === "number" ? { seq: data.seq } : {},
|
|
2662
|
+
...typeof data.log_seq === "number" ? { log_seq: data.log_seq } : {}
|
|
2663
|
+
}
|
|
2664
|
+
]
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
continue;
|
|
2669
|
+
}
|
|
2317
2670
|
if (kind === "mode_change") {
|
|
2318
2671
|
turns.push(markerTurn(id, ++sequence, loopId, "mode_change", entry.data ?? {}));
|
|
2319
2672
|
} else if (kind === "workspace_change") {
|
|
@@ -2364,7 +2717,7 @@ function projectHistory(entries) {
|
|
|
2364
2717
|
let content = isRecord(entry.message) ? entry.message.content : void 0;
|
|
2365
2718
|
if (kind === "tool_result_archive") {
|
|
2366
2719
|
const archivedCount = Array.isArray(data.archived_files) ? data.archived_files.length : 0;
|
|
2367
|
-
content = `<compaction-summary>
|
|
2720
|
+
content = typeof data.summary === "string" && data.summary ? data.summary : `<compaction-summary>
|
|
2368
2721
|
\u5DF2\u5F52\u6863 ${archivedCount} \u4E2A\u5927\u578B\u5DE5\u5177\u7ED3\u679C\u3002
|
|
2369
2722
|
</compaction-summary>`;
|
|
2370
2723
|
}
|
|
@@ -2588,6 +2941,35 @@ function findLatestAssistant(turns, loopId) {
|
|
|
2588
2941
|
return void 0;
|
|
2589
2942
|
}
|
|
2590
2943
|
|
|
2944
|
+
// src/shared/projection/workflow.ts
|
|
2945
|
+
var STEP_KINDS = /* @__PURE__ */ new Set(["agent", "step", "parallel", "choice", "end"]);
|
|
2946
|
+
function workflowEntriesFromSteps(steps) {
|
|
2947
|
+
const items = [];
|
|
2948
|
+
const ordered = steps.every((step) => typeof step.seq === "number");
|
|
2949
|
+
steps.forEach((step, index) => {
|
|
2950
|
+
const base = ordered ? step.seq : index * 2;
|
|
2951
|
+
const stepKind = step.step_kind && STEP_KINDS.has(step.step_kind) ? step.step_kind : "step";
|
|
2952
|
+
items.push({
|
|
2953
|
+
key: base,
|
|
2954
|
+
entry: { kind: "step", stepId: step.step_id, desc: step.desc ?? "", stepKind, status: step.status }
|
|
2955
|
+
});
|
|
2956
|
+
const logKey = ordered && typeof step.log_seq === "number" ? step.log_seq : base + 0.5;
|
|
2957
|
+
const output = step.output ?? "";
|
|
2958
|
+
if (step.status === "done" && stepKind === "step") {
|
|
2959
|
+
const chars = Array.from(output);
|
|
2960
|
+
const shown = chars.length <= 300 ? output : `${chars.slice(0, 300).join("")}\u2026(\u5171${chars.length}\u5B57)`;
|
|
2961
|
+
items.push({ key: logKey, entry: { kind: "log", text: ` \u2514 \u8F93\u51FA: ${shown || "(\u7A7A)"}`, stepId: step.step_id } });
|
|
2962
|
+
}
|
|
2963
|
+
if (step.status === "error" && output) {
|
|
2964
|
+
items.push({ key: logKey, entry: { kind: "log", text: `\u5931\u8D25: ${output}`, stepId: step.step_id } });
|
|
2965
|
+
}
|
|
2966
|
+
});
|
|
2967
|
+
return items.sort((a, b) => a.key - b.key).map((item) => item.entry);
|
|
2968
|
+
}
|
|
2969
|
+
function workflowRunCancelled(steps) {
|
|
2970
|
+
return steps.some((step) => step.status === "cancelled") && !steps.some((step) => step.status === "error");
|
|
2971
|
+
}
|
|
2972
|
+
|
|
2591
2973
|
// src/resources/headless.ts
|
|
2592
2974
|
var HeadlessError = class extends Error {
|
|
2593
2975
|
constructor(message, detail) {
|
|
@@ -2623,7 +3005,7 @@ var HeadlessResource = class {
|
|
|
2623
3005
|
return this.runTracked(session_id, prompt, options, true);
|
|
2624
3006
|
}
|
|
2625
3007
|
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\
|
|
3008
|
+
if ((options.refs?.length ?? 0) > 20) throw new HeadlessError("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u9009\u62E9 20 \u4E2A\u5F15\u7528");
|
|
2627
3009
|
if ((options.topicAssetRefs?.length ?? 0) > 20) throw new HeadlessError("\u6BCF\u6761\u6D88\u606F\u6700\u591A\u5F15\u7528 20 \u4E2A\u4E3B\u9898\u8D44\u4EA7");
|
|
2628
3010
|
const timeoutMs = options.timeoutMs ?? 3e5;
|
|
2629
3011
|
const session_id = sessionId;
|
|
@@ -2656,7 +3038,7 @@ var HeadlessResource = class {
|
|
|
2656
3038
|
});
|
|
2657
3039
|
if (stopped.status !== "received") return { ...stopped, phase: "stop_ack", chat_run_id: runId };
|
|
2658
3040
|
const ack = stopped.ack;
|
|
2659
|
-
const confirmed = isRecord(ack) && ack.ok !== false &&
|
|
3041
|
+
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
3042
|
return {
|
|
2661
3043
|
status: confirmed ? "confirmed" : "unconfirmed",
|
|
2662
3044
|
phase: "stop_ack",
|
|
@@ -2957,7 +3339,6 @@ function waitForCleanupAck(socket, deadline, request) {
|
|
|
2957
3339
|
|
|
2958
3340
|
// src/resources/computers.ts
|
|
2959
3341
|
function computerState(computer) {
|
|
2960
|
-
if (computer.is_primary) return "primary";
|
|
2961
3342
|
if (computer.enabled) return "enabled";
|
|
2962
3343
|
return computer.online ? "idle" : "offline";
|
|
2963
3344
|
}
|
|
@@ -2977,9 +3358,6 @@ function computerPlatformLabel(computer) {
|
|
|
2977
3358
|
function computerDaemonVersion(computer) {
|
|
2978
3359
|
return (computer.daemon_version ?? "").trim();
|
|
2979
3360
|
}
|
|
2980
|
-
function canToggleComputer(computer) {
|
|
2981
|
-
return !computer.is_primary;
|
|
2982
|
-
}
|
|
2983
3361
|
function sortComputers(computers) {
|
|
2984
3362
|
return [...computers].sort((a, b) => {
|
|
2985
3363
|
const byCreated = (a.created_at ?? "").localeCompare(b.created_at ?? "");
|
|
@@ -3030,14 +3408,263 @@ var ComputersResource = class {
|
|
|
3030
3408
|
}
|
|
3031
3409
|
};
|
|
3032
3410
|
|
|
3033
|
-
// src/resources/
|
|
3034
|
-
|
|
3411
|
+
// src/resources/phones.ts
|
|
3412
|
+
function phoneState(phone) {
|
|
3413
|
+
if (phone.enabled) return "enabled";
|
|
3414
|
+
return phone.online ? "idle" : "offline";
|
|
3415
|
+
}
|
|
3416
|
+
function sortPhones(phones) {
|
|
3417
|
+
return [...phones].sort((a, b) => {
|
|
3418
|
+
const byCreated = (a.created_at ?? "").localeCompare(b.created_at ?? "");
|
|
3419
|
+
if (byCreated !== 0) return byCreated;
|
|
3420
|
+
return a.label.localeCompare(b.label);
|
|
3421
|
+
});
|
|
3422
|
+
}
|
|
3423
|
+
function phoneSerialLabel(phone) {
|
|
3424
|
+
return (phone.serial ?? phone.machine_id ?? phone.id ?? "").trim();
|
|
3425
|
+
}
|
|
3426
|
+
var PhonesResource = class {
|
|
3035
3427
|
constructor(client) {
|
|
3036
3428
|
this.client = client;
|
|
3037
3429
|
}
|
|
3038
3430
|
client;
|
|
3039
|
-
|
|
3040
|
-
|
|
3431
|
+
/** 账号下的全部手机(不含"本次会话是否可用")。 */
|
|
3432
|
+
async listAccount() {
|
|
3433
|
+
return this.client.json("GET", "/api/phone/devices");
|
|
3434
|
+
}
|
|
3435
|
+
/**
|
|
3436
|
+
* 当前接入密钥;没有就补一个。
|
|
3437
|
+
*
|
|
3438
|
+
* **取的时候不轮换**:每次打开设置页都换钥匙会让已配好的手机集体掉线。
|
|
3439
|
+
*/
|
|
3440
|
+
getKey() {
|
|
3441
|
+
return this.client.json("GET", "/api/phone/key");
|
|
3442
|
+
}
|
|
3443
|
+
/** 换一把新密钥(旧的立即失效)。 */
|
|
3444
|
+
resetKey() {
|
|
3445
|
+
return this.client.json("POST", "/api/phone/key/reset");
|
|
3446
|
+
}
|
|
3447
|
+
/** 作废密钥;设备记录保留,用户下次取密钥会得到一把新的。 */
|
|
3448
|
+
async revokeKey() {
|
|
3449
|
+
await this.client.fetch("DELETE", "/api/phone/key");
|
|
3450
|
+
}
|
|
3451
|
+
async remove(phoneId) {
|
|
3452
|
+
await this.client.fetch("DELETE", `/api/phone/devices/${encodeURIComponent(phoneId)}`);
|
|
3453
|
+
}
|
|
3454
|
+
/** 本次会话能用的手机 + 账号下的其他手机。 */
|
|
3455
|
+
listForSession(sessionId) {
|
|
3456
|
+
return this.client.json(
|
|
3457
|
+
"GET",
|
|
3458
|
+
`/api/sessions/${encodeURIComponent(sessionId)}/phones`
|
|
3459
|
+
);
|
|
3460
|
+
}
|
|
3461
|
+
setEnabled(sessionId, phoneId, enabled) {
|
|
3462
|
+
return this.client.json(
|
|
3463
|
+
"PUT",
|
|
3464
|
+
`/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/enabled`,
|
|
3465
|
+
{ enabled }
|
|
3466
|
+
);
|
|
3467
|
+
}
|
|
3468
|
+
health(sessionId, phoneId) {
|
|
3469
|
+
return this.client.json(
|
|
3470
|
+
"GET",
|
|
3471
|
+
`/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/health`
|
|
3472
|
+
);
|
|
3473
|
+
}
|
|
3474
|
+
/**
|
|
3475
|
+
* WHEP 信令:POST 一个 SDP offer,拿到 answer。
|
|
3476
|
+
*
|
|
3477
|
+
* 走 `textFromInit` 而不是 `json()`:SDP 是纯文本,`json()` 会强制序列化成
|
|
3478
|
+
* JSON;也不能用裸 `fetch`,那会丢掉 bearer token。
|
|
3479
|
+
*/
|
|
3480
|
+
async whep(sessionId, phoneId, offerSdp) {
|
|
3481
|
+
return this.client.textFromInit(
|
|
3482
|
+
`/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/whep`,
|
|
3483
|
+
{
|
|
3484
|
+
method: "POST",
|
|
3485
|
+
body: offerSdp,
|
|
3486
|
+
headers: { "content-type": "application/sdp" }
|
|
3487
|
+
}
|
|
3488
|
+
);
|
|
3489
|
+
}
|
|
3490
|
+
/** 用户点「刷新画面」:让后台重新确认隧道服务并忘掉记住的 token。 */
|
|
3491
|
+
async wake(sessionId, phoneId) {
|
|
3492
|
+
await this.client.json(
|
|
3493
|
+
"POST",
|
|
3494
|
+
`/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/wake`
|
|
3495
|
+
);
|
|
3496
|
+
}
|
|
3497
|
+
};
|
|
3498
|
+
|
|
3499
|
+
// src/resources/llm.ts
|
|
3500
|
+
var LlmResource = class {
|
|
3501
|
+
constructor(client) {
|
|
3502
|
+
this.client = client;
|
|
3503
|
+
}
|
|
3504
|
+
client;
|
|
3505
|
+
chat = { completions: { create: (body, options = {}) => this.client.jsonFromInit("/api/llm/chat/completions", { method: "POST", body: JSON.stringify(body), signal: options.signal }) } };
|
|
3506
|
+
};
|
|
3507
|
+
|
|
3508
|
+
// src/resources/models.ts
|
|
3509
|
+
var ModelsResource = class {
|
|
3510
|
+
constructor(client) {
|
|
3511
|
+
this.client = client;
|
|
3512
|
+
}
|
|
3513
|
+
client;
|
|
3514
|
+
list(options = {}) {
|
|
3515
|
+
return this.client.jsonFromInit("/api/config/models", { signal: options.signal });
|
|
3516
|
+
}
|
|
3517
|
+
};
|
|
3518
|
+
|
|
3519
|
+
// src/resources/connectors.ts
|
|
3520
|
+
function isLocalConnectorName(name) {
|
|
3521
|
+
return name.startsWith("connector.personal.") || name.startsWith("connector.builtin.");
|
|
3522
|
+
}
|
|
3523
|
+
var ConnectorsResource = class {
|
|
3524
|
+
constructor(client) {
|
|
3525
|
+
this.client = client;
|
|
3526
|
+
}
|
|
3527
|
+
client;
|
|
3528
|
+
rules(name) {
|
|
3529
|
+
return this.client.json("GET", `/api/connectors/${encodeURIComponent(name)}/rules`);
|
|
3530
|
+
}
|
|
3531
|
+
updateRules(name, set) {
|
|
3532
|
+
return this.client.json("PUT", `/api/connectors/${encodeURIComponent(name)}/rules`, { set });
|
|
3533
|
+
}
|
|
3534
|
+
guide(name, section, init) {
|
|
3535
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/guide${section ? `?section=${encodeURIComponent(section)}` : ""}`, init);
|
|
3536
|
+
}
|
|
3537
|
+
/** Stage an explicit attachment in the current user's SW connection. Reuse requestId on retry. */
|
|
3538
|
+
async uploadFile(name, file, fileName, requestId) {
|
|
3539
|
+
const form = new FormData();
|
|
3540
|
+
form.append("file", file, fileName);
|
|
3541
|
+
form.append("request_id", requestId);
|
|
3542
|
+
const response = await this.client.formData("POST", `/api/connectors/${encodeURIComponent(name)}/files`, form);
|
|
3543
|
+
return response.json();
|
|
3544
|
+
}
|
|
3545
|
+
/** Fetch a private artifact through BA authentication; no SW PAT or public URL is exposed. */
|
|
3546
|
+
downloadFile(name, artifactId) {
|
|
3547
|
+
return this.client.blob("GET", `/api/connectors/${encodeURIComponent(name)}/files/${encodeURIComponent(artifactId)}`);
|
|
3548
|
+
}
|
|
3549
|
+
pushSettings(name, init) {
|
|
3550
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/push-settings`, { ...init, method: "GET" });
|
|
3551
|
+
}
|
|
3552
|
+
setPushSettings(name, changes, init) {
|
|
3553
|
+
const query = init?.expectedConnectionId ? `?expected_connection_id=${encodeURIComponent(init.expectedConnectionId)}` : "";
|
|
3554
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/push-settings${query}`, {
|
|
3555
|
+
...init,
|
|
3556
|
+
method: "PUT",
|
|
3557
|
+
body: JSON.stringify(changes)
|
|
3558
|
+
});
|
|
3559
|
+
}
|
|
3560
|
+
authorization(name, init) {
|
|
3561
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/authorization`, init);
|
|
3562
|
+
}
|
|
3563
|
+
authorize(name, action, pushUrl, options) {
|
|
3564
|
+
return this.client.json("POST", `/api/connectors/${encodeURIComponent(name)}/authorization`, {
|
|
3565
|
+
action,
|
|
3566
|
+
...options,
|
|
3567
|
+
...pushUrl ? { push_url: pushUrl } : {}
|
|
3568
|
+
});
|
|
3569
|
+
}
|
|
3570
|
+
authorizationPlan(name, capabilities) {
|
|
3571
|
+
return this.client.json("POST", `/api/connectors/${encodeURIComponent(name)}/authorization`, { action: "plan", capabilities });
|
|
3572
|
+
}
|
|
3573
|
+
diagnostics(name, init) {
|
|
3574
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/diagnostics`, init);
|
|
3575
|
+
}
|
|
3576
|
+
create(draft) {
|
|
3577
|
+
return this.client.json("POST", "/api/connectors", draft);
|
|
3578
|
+
}
|
|
3579
|
+
update(name, draft) {
|
|
3580
|
+
return this.client.json("PATCH", `/api/connectors/${encodeURIComponent(name)}`, draft);
|
|
3581
|
+
}
|
|
3582
|
+
delete(name) {
|
|
3583
|
+
return this.client.json("DELETE", `/api/connectors/${encodeURIComponent(name)}`);
|
|
3584
|
+
}
|
|
3585
|
+
/** Create a generation conversation and send its visible Skill request.
|
|
3586
|
+
* Hosts use onCreated only to register caches and navigate before sending. */
|
|
3587
|
+
async startGeneration({ connector, onCreated, initiator = "sdk" } = {}) {
|
|
3588
|
+
const intent = connector ? "\u4FEE\u6539\u8FDE\u63A5\u5668" : "\u521B\u5EFA\u8FDE\u63A5\u5668";
|
|
3589
|
+
const request = connector ? "\u4FEE\u6539\u9009\u5B9A\u7684\u8FDE\u63A5\u5668" : "\u521B\u5EFA\u8FDE\u63A5\u5668";
|
|
3590
|
+
const { session_id } = await this.client.sessions.createSessionWithRequest({ intent, solution_id: "connector_generate", initiator });
|
|
3591
|
+
await onCreated?.({ session_id, intent });
|
|
3592
|
+
const session = await this.client.sessions.connect(session_id);
|
|
3593
|
+
try {
|
|
3594
|
+
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`, {
|
|
3595
|
+
mode: "executing",
|
|
3596
|
+
refs: [{ provider: "skill", id: "generate-connector", label: "\u8FDE\u63A5\u5668\u751F\u6210\u5668" }],
|
|
3597
|
+
...connector ? { contextAttachments: [{
|
|
3598
|
+
id: "connector-generation-target",
|
|
3599
|
+
label: "\u9009\u5B9A\u7684\u8FDE\u63A5\u5668",
|
|
3600
|
+
content: JSON.stringify({ name: connector.name, display_name: connector.display_name }),
|
|
3601
|
+
update_format: "snapshot"
|
|
3602
|
+
}] } : {}
|
|
3603
|
+
});
|
|
3604
|
+
return { session_id, sent };
|
|
3605
|
+
} finally {
|
|
3606
|
+
session.dispose();
|
|
3607
|
+
}
|
|
3608
|
+
}
|
|
3609
|
+
list(init) {
|
|
3610
|
+
return this.client.jsonFromInit("/api/connectors", init);
|
|
3611
|
+
}
|
|
3612
|
+
listForSession(sessionId, init) {
|
|
3613
|
+
return this.client.jsonFromInit(`/api/connectors?session_id=${encodeURIComponent(sessionId)}`, init);
|
|
3614
|
+
}
|
|
3615
|
+
read(name, init) {
|
|
3616
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/connection`, init);
|
|
3617
|
+
}
|
|
3618
|
+
connect(name, update, init) {
|
|
3619
|
+
return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/connection`, {
|
|
3620
|
+
method: "PUT",
|
|
3621
|
+
body: JSON.stringify(update),
|
|
3622
|
+
...init
|
|
3623
|
+
});
|
|
3624
|
+
}
|
|
3625
|
+
browserAuthorizationUrl(name) {
|
|
3626
|
+
return new URL(`connector-auth/${encodeURIComponent(name)}`, `${this.client.options.baseUrl.replace(/\/$/, "")}/`).toString();
|
|
3627
|
+
}
|
|
3628
|
+
/** One-use, one-minute identity handoff to this client's trusted Blade origin.
|
|
3629
|
+
* Tokens travel only through a source/origin-bound message, never a URL/storage. */
|
|
3630
|
+
bindBrowserAuthorizationFrame(frame, name) {
|
|
3631
|
+
const nonce = Array.from(crypto.getRandomValues(new Uint8Array(32)), (value) => value.toString(16).padStart(2, "0")).join("");
|
|
3632
|
+
const url = new URL(this.browserAuthorizationUrl(name), window.location.href);
|
|
3633
|
+
url.searchParams.set("embedded", "1");
|
|
3634
|
+
url.searchParams.set("handoff", nonce);
|
|
3635
|
+
url.searchParams.set("parent_origin", window.location.origin);
|
|
3636
|
+
const receive = (event) => {
|
|
3637
|
+
if (event.origin !== url.origin || event.source !== frame.contentWindow || event.data?.type !== "blade:connector-auth-ready" || event.data?.nonce !== nonce) return;
|
|
3638
|
+
cleanup();
|
|
3639
|
+
frame.contentWindow?.postMessage({ type: "blade:connector-auth-identity", nonce, token: this.client.token }, url.origin);
|
|
3640
|
+
};
|
|
3641
|
+
const timeout = window.setTimeout(() => cleanup(), 6e4);
|
|
3642
|
+
const cleanup = () => {
|
|
3643
|
+
window.clearTimeout(timeout);
|
|
3644
|
+
window.removeEventListener("message", receive);
|
|
3645
|
+
};
|
|
3646
|
+
window.addEventListener("message", receive);
|
|
3647
|
+
frame.src = url.toString();
|
|
3648
|
+
return cleanup;
|
|
3649
|
+
}
|
|
3650
|
+
async startBrowserAuthorization(name, sessionId) {
|
|
3651
|
+
const view = await this.read(name);
|
|
3652
|
+
if (view.authorization?.type !== "browser") throw new Error("\u8BE5\u8FDE\u63A5\u5668\u6CA1\u6709\u7F51\u9875\u767B\u5F55\u5165\u53E3");
|
|
3653
|
+
const id = sessionId ?? (await this.client.sessions.createSessionWithRequest({
|
|
3654
|
+
intent: `\u8FDE\u63A5 ${view.display_name || "\u4E1A\u52A1\u7CFB\u7EDF"}`,
|
|
3655
|
+
memory_enabled: false
|
|
3656
|
+
})).session_id;
|
|
3657
|
+
await this.client.json("POST", `/api/sessions/${encodeURIComponent(id)}/browser/wake`, {});
|
|
3658
|
+
const tabs = await this.client.json("GET", `/api/sessions/${encodeURIComponent(id)}/browser/tabs`);
|
|
3659
|
+
const hasBusinessTab = tabs.data?.some(({ url }) => url && url !== "about:blank" && !/^http:\/\/(?:127\.0\.0\.1|localhost):9223\/home(?:[/?#]|$)/.test(url));
|
|
3660
|
+
if (!sessionId || !hasBusinessTab) await this.client.json("POST", `/api/sessions/${encodeURIComponent(id)}/browser/tabs`, { url: view.authorization.url });
|
|
3661
|
+
return { session_id: id, view };
|
|
3662
|
+
}
|
|
3663
|
+
verify(name) {
|
|
3664
|
+
return this.client.json("POST", `/api/connectors/${encodeURIComponent(name)}/connection:verify`);
|
|
3665
|
+
}
|
|
3666
|
+
disconnect(name) {
|
|
3667
|
+
return this.client.json("DELETE", `/api/connectors/${encodeURIComponent(name)}/connection`);
|
|
3041
3668
|
}
|
|
3042
3669
|
};
|
|
3043
3670
|
|
|
@@ -3054,12 +3681,13 @@ var SessionInfo = type({
|
|
|
3054
3681
|
created_at: "string",
|
|
3055
3682
|
updated_at: "string",
|
|
3056
3683
|
"shared?": "boolean",
|
|
3684
|
+
"anonymous?": "boolean",
|
|
3057
3685
|
"memory_enabled?": "boolean",
|
|
3058
3686
|
"is_persistent?": "boolean",
|
|
3059
3687
|
"initiator?": "'ui' | 'sdk' | 'unknown' | null",
|
|
3060
3688
|
"is_headless?": "boolean",
|
|
3689
|
+
"scheduled_task_id?": "string",
|
|
3061
3690
|
"viewer_role?": "'owner' | 'viewer'",
|
|
3062
|
-
"template_id?": "string | null",
|
|
3063
3691
|
"model?": "string | null",
|
|
3064
3692
|
"enable_thinking?": "boolean | null",
|
|
3065
3693
|
"solution_id?": "string | null",
|
|
@@ -3067,19 +3695,12 @@ var SessionInfo = type({
|
|
|
3067
3695
|
"biz_role_id?": "string | null",
|
|
3068
3696
|
"solution?": "unknown",
|
|
3069
3697
|
"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
3698
|
"replay_state?": "unknown",
|
|
3075
3699
|
"is_pinned?": "boolean",
|
|
3076
3700
|
"pinned_at?": "string | null",
|
|
3077
3701
|
"is_example?": "boolean",
|
|
3078
3702
|
"ports?": "unknown",
|
|
3079
3703
|
"disable_tools?": "string[]",
|
|
3080
|
-
"runtime_type?": "string | null",
|
|
3081
|
-
"daemon_id?": "string | null",
|
|
3082
|
-
"agent_runtime_id?": "string | null",
|
|
3083
3704
|
"workspace_path?": "string | null",
|
|
3084
3705
|
"ba_version?": "string | null",
|
|
3085
3706
|
"sandbox_version?": "string | null",
|
|
@@ -3110,24 +3731,23 @@ function toCreateSessionPayload(request) {
|
|
|
3110
3731
|
const solutionRef = request.solution_ref ?? externalSolutionRef(request.solution_id);
|
|
3111
3732
|
return {
|
|
3112
3733
|
intent: request.intent ?? "",
|
|
3113
|
-
|
|
3734
|
+
// The server defaults to sdk; older APIs reject even this redundant field.
|
|
3735
|
+
initiator: request.initiator === "sdk" ? void 0 : request.initiator,
|
|
3736
|
+
anonymous: request.anonymous,
|
|
3114
3737
|
solution_id: solutionRef ? void 0 : request.solution_id,
|
|
3115
3738
|
solution_ref: solutionRef,
|
|
3116
3739
|
biz_role_id: request.biz_role_id ?? null,
|
|
3117
3740
|
model: request.model ?? null,
|
|
3118
3741
|
enable_thinking: request.enable_thinking ?? null,
|
|
3119
3742
|
memory_enabled: request.memory_enabled ?? null,
|
|
3120
|
-
primary_skill_id: request.primary_skill_id ?? null,
|
|
3121
3743
|
env: request.env,
|
|
3122
3744
|
disable_tools: request.disable_tools ?? null,
|
|
3123
3745
|
mcp_sources: request.mcp_sources,
|
|
3124
3746
|
skip_confirmations: request.skip_confirmations,
|
|
3125
3747
|
session_solution_asset_id: request.session_solution_asset_id ?? null,
|
|
3748
|
+
session_solution_files: request.session_solution_files,
|
|
3126
3749
|
solution_snapshot_session_id: request.solution_snapshot_session_id ?? null,
|
|
3127
3750
|
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
3751
|
...request.chat_group_id ? { chat_group_id: request.chat_group_id } : {}
|
|
3132
3752
|
};
|
|
3133
3753
|
}
|
|
@@ -3135,6 +3755,7 @@ var builtinSolutionIds = /* @__PURE__ */ new Set([
|
|
|
3135
3755
|
"app-dev",
|
|
3136
3756
|
"general_chat",
|
|
3137
3757
|
"night_build",
|
|
3758
|
+
"scheduled_tasks",
|
|
3138
3759
|
"skill_editor",
|
|
3139
3760
|
"smart_bid",
|
|
3140
3761
|
"solution_generate"
|
|
@@ -3174,6 +3795,20 @@ var SessionsResource = class {
|
|
|
3174
3795
|
this.pendingImages.set(identity, pending);
|
|
3175
3796
|
return pending;
|
|
3176
3797
|
}
|
|
3798
|
+
openFileOpener(sessionId, body, init) {
|
|
3799
|
+
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/file-openers:open`, {
|
|
3800
|
+
...init,
|
|
3801
|
+
method: "POST",
|
|
3802
|
+
body: JSON.stringify(body)
|
|
3803
|
+
});
|
|
3804
|
+
}
|
|
3805
|
+
callFileOpener(sessionId, body, init) {
|
|
3806
|
+
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/file-openers:call`, {
|
|
3807
|
+
...init,
|
|
3808
|
+
method: "POST",
|
|
3809
|
+
body: JSON.stringify(body)
|
|
3810
|
+
});
|
|
3811
|
+
}
|
|
3177
3812
|
getMcpApp(sessionId, sourceId, init) {
|
|
3178
3813
|
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/mcp-apps/${encodeURIComponent(sourceId)}`, init);
|
|
3179
3814
|
}
|
|
@@ -3215,7 +3850,8 @@ var SessionsResource = class {
|
|
|
3215
3850
|
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/plugins`, init);
|
|
3216
3851
|
}
|
|
3217
3852
|
setSessionPluginActivation(sessionId, name, active, init) {
|
|
3218
|
-
|
|
3853
|
+
const kind = isLocalConnectorName(name) ? "connectors" : "plugins";
|
|
3854
|
+
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/${kind}/${encodeURIComponent(name)}:activation`, { method: "POST", body: JSON.stringify({ active }), ...init });
|
|
3219
3855
|
}
|
|
3220
3856
|
/**
|
|
3221
3857
|
* Fetch a plugin's package-local icon as bytes.
|
|
@@ -3270,7 +3906,7 @@ var SessionsResource = class {
|
|
|
3270
3906
|
return this.createDeclared(request);
|
|
3271
3907
|
}
|
|
3272
3908
|
const { session_id } = await this.createSessionWithRequest(request);
|
|
3273
|
-
return this.connect(session_id);
|
|
3909
|
+
return request.anonymous ? this.client.forAnonymousSession(session_id).sessions.connect(session_id) : this.connect(session_id);
|
|
3274
3910
|
}
|
|
3275
3911
|
async createDeclared(definition) {
|
|
3276
3912
|
const { intent, solution, skills = [], config } = definition;
|
|
@@ -3291,7 +3927,8 @@ var SessionsResource = class {
|
|
|
3291
3927
|
memory_enabled: config?.memoryEnabled,
|
|
3292
3928
|
compaction_ratio: config?.compactionRatio,
|
|
3293
3929
|
env: config?.env,
|
|
3294
|
-
disable_tools: config?.disableTools
|
|
3930
|
+
disable_tools: config?.disableTools,
|
|
3931
|
+
mcp_sources: config?.mcpSources
|
|
3295
3932
|
});
|
|
3296
3933
|
session_id = created.session_id;
|
|
3297
3934
|
} catch (error) {
|
|
@@ -3357,7 +3994,6 @@ var SessionsResource = class {
|
|
|
3357
3994
|
fetchSessionsPage({
|
|
3358
3995
|
limit,
|
|
3359
3996
|
offset,
|
|
3360
|
-
template_id_prefix,
|
|
3361
3997
|
solution_id,
|
|
3362
3998
|
solution_registry_id,
|
|
3363
3999
|
q,
|
|
@@ -3366,7 +4002,6 @@ var SessionsResource = class {
|
|
|
3366
4002
|
const searchParams = new URLSearchParams();
|
|
3367
4003
|
searchParams.set("limit", String(limit));
|
|
3368
4004
|
searchParams.set("offset", String(offset));
|
|
3369
|
-
if (template_id_prefix) searchParams.set("template_id_prefix", template_id_prefix);
|
|
3370
4005
|
if (solution_registry_id) {
|
|
3371
4006
|
searchParams.set("solution_registry_id", solution_registry_id);
|
|
3372
4007
|
} else if (solution_id) {
|
|
@@ -3377,12 +4012,12 @@ var SessionsResource = class {
|
|
|
3377
4012
|
if (chat_group_id) searchParams.set("chat_group_id", chat_group_id);
|
|
3378
4013
|
return this.client.json("GET", `/api/sessions?${searchParams.toString()}`);
|
|
3379
4014
|
}
|
|
3380
|
-
async listSessions(
|
|
4015
|
+
async listSessions(solution_id) {
|
|
3381
4016
|
const pageSize = 100;
|
|
3382
4017
|
const sessions = [];
|
|
3383
4018
|
let offset = 0;
|
|
3384
4019
|
while (true) {
|
|
3385
|
-
const page = await this.fetchSessionsPage({ limit: pageSize, offset,
|
|
4020
|
+
const page = await this.fetchSessionsPage({ limit: pageSize, offset, solution_id });
|
|
3386
4021
|
sessions.push(...page.items);
|
|
3387
4022
|
if (sessions.length >= page.total || page.items.length === 0) return sessions;
|
|
3388
4023
|
offset += page.items.length;
|
|
@@ -3399,8 +4034,8 @@ var SessionsResource = class {
|
|
|
3399
4034
|
if (params.limit !== void 0) searchParams.set("limit", String(params.limit));
|
|
3400
4035
|
return this.client.json("GET", `/api/search?${searchParams.toString()}`);
|
|
3401
4036
|
}
|
|
3402
|
-
createSession(intent
|
|
3403
|
-
return this.createSessionWithRequest({ intent
|
|
4037
|
+
createSession(intent) {
|
|
4038
|
+
return this.createSessionWithRequest({ intent });
|
|
3404
4039
|
}
|
|
3405
4040
|
createSessionWithRequest(request) {
|
|
3406
4041
|
return this.client.json("POST", "/api/sessions", toCreateSessionPayload(request));
|
|
@@ -3418,6 +4053,13 @@ var SessionsResource = class {
|
|
|
3418
4053
|
updateSession(sessionId, payload) {
|
|
3419
4054
|
return this.client.json("PATCH", `/api/sessions/${sessionId}`, payload);
|
|
3420
4055
|
}
|
|
4056
|
+
getSessionConfiguration(sessionId, init) {
|
|
4057
|
+
return this.client.jsonFromInit(`/api/sessions/${encodeURIComponent(sessionId)}/configuration`, init);
|
|
4058
|
+
}
|
|
4059
|
+
/** Updates atomically between turns. A running/handoff session returns HTTP 409. */
|
|
4060
|
+
updateSessionConfiguration(sessionId, request) {
|
|
4061
|
+
return this.client.json("PATCH", `/api/sessions/${encodeURIComponent(sessionId)}/configuration`, request);
|
|
4062
|
+
}
|
|
3421
4063
|
setSessionEnv(sessionId, env) {
|
|
3422
4064
|
return this.client.json("PUT", `/api/sessions/${sessionId}/env`, { env });
|
|
3423
4065
|
}
|
|
@@ -3458,6 +4100,10 @@ var SessionsResource = class {
|
|
|
3458
4100
|
getSessionTasks(sessionId) {
|
|
3459
4101
|
return this.client.json("GET", `/api/sessions/${sessionId}/tasks`);
|
|
3460
4102
|
}
|
|
4103
|
+
/** Durable result for this execution; null until its run_end is committed. Owner only. */
|
|
4104
|
+
getRunResult(sessionId, runId) {
|
|
4105
|
+
return this.client.json("GET", `/api/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}`);
|
|
4106
|
+
}
|
|
3461
4107
|
async getSessionTurns(sessionId) {
|
|
3462
4108
|
const entries = await this.client.json(
|
|
3463
4109
|
"GET",
|
|
@@ -3491,7 +4137,19 @@ var SessionsResource = class {
|
|
|
3491
4137
|
items: index.items.map((item) => ({
|
|
3492
4138
|
entryId: item.entry_id,
|
|
3493
4139
|
preview: item.preview,
|
|
3494
|
-
|
|
4140
|
+
recaption: item.recaption,
|
|
4141
|
+
artifacts: item.artifacts?.map((artifact) => ({
|
|
4142
|
+
kind: artifact.kind === "link" ? "link" : "file",
|
|
4143
|
+
target: artifact.target,
|
|
4144
|
+
label: artifact.label
|
|
4145
|
+
})),
|
|
4146
|
+
createdAt: item.created_at,
|
|
4147
|
+
entries: item.entries?.map((entry) => ({
|
|
4148
|
+
entryId: entry.entry_id,
|
|
4149
|
+
preview: entry.preview,
|
|
4150
|
+
createdAt: entry.created_at,
|
|
4151
|
+
answer: entry.answer
|
|
4152
|
+
}))
|
|
3495
4153
|
}))
|
|
3496
4154
|
};
|
|
3497
4155
|
}
|
|
@@ -3568,6 +4226,12 @@ var SessionsResource = class {
|
|
|
3568
4226
|
checkpoint_id: checkpointId
|
|
3569
4227
|
});
|
|
3570
4228
|
}
|
|
4229
|
+
listAnonymousSessions() {
|
|
4230
|
+
return this.client.json("GET", "/api/anonymous-sessions");
|
|
4231
|
+
}
|
|
4232
|
+
deleteAnonymousSession(sessionId) {
|
|
4233
|
+
return this.client.json("DELETE", `/api/anonymous-sessions/${encodeURIComponent(sessionId)}`);
|
|
4234
|
+
}
|
|
3571
4235
|
deleteSession(sessionId, options) {
|
|
3572
4236
|
const query = options?.deleteWorkspace ? "?delete_workspace=true" : "";
|
|
3573
4237
|
return this.client.json("DELETE", `/api/sessions/${sessionId}${query}`);
|
|
@@ -3790,6 +4454,19 @@ var PluginsResource = class {
|
|
|
3790
4454
|
this.client = client;
|
|
3791
4455
|
}
|
|
3792
4456
|
client;
|
|
4457
|
+
catalogSnapshot;
|
|
4458
|
+
pendingCatalog;
|
|
4459
|
+
catalogListeners = /* @__PURE__ */ new Set();
|
|
4460
|
+
/** Observe the directory loaded by existing plugin surfaces without starting a request. */
|
|
4461
|
+
getCatalogSnapshot() {
|
|
4462
|
+
return this.catalogSnapshot?.token === this.client.token ? this.catalogSnapshot?.entries : void 0;
|
|
4463
|
+
}
|
|
4464
|
+
subscribeCatalog(listener) {
|
|
4465
|
+
this.catalogListeners.add(listener);
|
|
4466
|
+
return () => {
|
|
4467
|
+
this.catalogListeners.delete(listener);
|
|
4468
|
+
};
|
|
4469
|
+
}
|
|
3793
4470
|
/**
|
|
3794
4471
|
* 列出当前用户安装的插件及其展示信息。
|
|
3795
4472
|
*
|
|
@@ -3797,7 +4474,24 @@ var PluginsResource = class {
|
|
|
3797
4474
|
* 单个插件的展示信息读不出来只会降级成占位,不会让整份目录失败。
|
|
3798
4475
|
*/
|
|
3799
4476
|
catalog(init) {
|
|
3800
|
-
|
|
4477
|
+
const token = this.client.token;
|
|
4478
|
+
if (!init && this.pendingCatalog && this.pendingCatalog.token === token) return this.pendingCatalog.request;
|
|
4479
|
+
const request = this.client.jsonFromInit("/api/plugins/catalog", init).then((result) => {
|
|
4480
|
+
if (token === this.client.token) {
|
|
4481
|
+
this.catalogSnapshot = { token, entries: result.plugins };
|
|
4482
|
+
for (const listener of this.catalogListeners) listener();
|
|
4483
|
+
}
|
|
4484
|
+
return result;
|
|
4485
|
+
}).finally(() => {
|
|
4486
|
+
if (this.pendingCatalog?.request === request) this.pendingCatalog = void 0;
|
|
4487
|
+
});
|
|
4488
|
+
if (!init) this.pendingCatalog = { token, request };
|
|
4489
|
+
return request;
|
|
4490
|
+
}
|
|
4491
|
+
/** Load once on demand; share both the snapshot and any request already in flight. */
|
|
4492
|
+
ensureCatalog() {
|
|
4493
|
+
const plugins = this.getCatalogSnapshot();
|
|
4494
|
+
return plugins ? Promise.resolve({ plugins }) : this.catalog();
|
|
3801
4495
|
}
|
|
3802
4496
|
/** 取一个插件的包内图标字节(用户级,不需要会话)。 */
|
|
3803
4497
|
fetchIcon(name) {
|
|
@@ -3969,7 +4663,6 @@ var SiteVisitsResource = class {
|
|
|
3969
4663
|
try {
|
|
3970
4664
|
const response = await (this.client.options.fetchImpl ?? fetch)(url.toString(), {
|
|
3971
4665
|
method,
|
|
3972
|
-
// 访客 Cookie 是唯一的去重依据,必须随请求往返。
|
|
3973
4666
|
credentials: "include",
|
|
3974
4667
|
signal: controller.signal
|
|
3975
4668
|
});
|
|
@@ -3983,6 +4676,20 @@ var SiteVisitsResource = class {
|
|
|
3983
4676
|
}
|
|
3984
4677
|
};
|
|
3985
4678
|
|
|
4679
|
+
// src/server-clock.ts
|
|
4680
|
+
var clocks = /* @__PURE__ */ new WeakMap();
|
|
4681
|
+
function syncServerTime(client, timestamp, receivedAt = performance.now()) {
|
|
4682
|
+
if (typeof timestamp !== "string") return;
|
|
4683
|
+
const serverTime = Date.parse(timestamp);
|
|
4684
|
+
if (!Number.isFinite(serverTime)) return;
|
|
4685
|
+
const current = getServerTime(client, receivedAt);
|
|
4686
|
+
clocks.set(client, { serverTime: Math.max(serverTime, current ?? serverTime), receivedAt });
|
|
4687
|
+
}
|
|
4688
|
+
function getServerTime(client, now = performance.now()) {
|
|
4689
|
+
const clock = client ? clocks.get(client) : void 0;
|
|
4690
|
+
return clock ? clock.serverTime + Math.max(0, now - clock.receivedAt) : null;
|
|
4691
|
+
}
|
|
4692
|
+
|
|
3986
4693
|
// src/session/background.ts
|
|
3987
4694
|
var BACKGROUND_STATUSES = [
|
|
3988
4695
|
"starting",
|
|
@@ -4222,6 +4929,7 @@ function toQueuedMessage(value) {
|
|
|
4222
4929
|
updated_at: value.updated_at
|
|
4223
4930
|
};
|
|
4224
4931
|
if (typeof value.target_run_id === "string") item.target_run_id = value.target_run_id;
|
|
4932
|
+
if (typeof value.next_turn_only === "boolean") item.next_turn_only = value.next_turn_only;
|
|
4225
4933
|
if (typeof value.error === "string") item.error = value.error;
|
|
4226
4934
|
return item;
|
|
4227
4935
|
}
|
|
@@ -4303,7 +5011,7 @@ function canCancelQueuedMessage(item) {
|
|
|
4303
5011
|
return item.status === "pending";
|
|
4304
5012
|
}
|
|
4305
5013
|
function canDeliverQueuedMessage(item) {
|
|
4306
|
-
return item.status === "pending";
|
|
5014
|
+
return item.status === "pending" && !item.next_turn_only;
|
|
4307
5015
|
}
|
|
4308
5016
|
var QUEUED_MESSAGE_STATUS_LABELS = {
|
|
4309
5017
|
pending: "\u5F85\u6267\u884C",
|
|
@@ -4427,15 +5135,8 @@ function contentPreview(content, maxLen = 80) {
|
|
|
4427
5135
|
const text = getTextContent(content).trim();
|
|
4428
5136
|
return text.length > maxLen ? `${text.slice(0, maxLen)}\u2026` : text;
|
|
4429
5137
|
}
|
|
4430
|
-
function transformSlashCommand(skillName, rawInput,
|
|
4431
|
-
|
|
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`;
|
|
5138
|
+
function transformSlashCommand(skillName, rawInput, _availability = {}) {
|
|
5139
|
+
return rawInput.replace(`<skill>${skillName}</skill>`, `@${skillName}`).trim();
|
|
4439
5140
|
}
|
|
4440
5141
|
var ATTACHMENT_TAG_RE = /\[附件:\s*([^\]]+)\](?:[ \t]*已上传到工作区路径:[ \t]*([^\r\n]+))?/g;
|
|
4441
5142
|
var CONTEXT_PART_RE = /^\[上下文:\s*([^\]]+)\]\n([\s\S]*)$/;
|
|
@@ -4563,7 +5264,13 @@ function workflowEntriesFromOutput(output) {
|
|
|
4563
5264
|
}
|
|
4564
5265
|
function workflowNameFromArguments(argumentsJson) {
|
|
4565
5266
|
try {
|
|
4566
|
-
const
|
|
5267
|
+
const args = JSON.parse(argumentsJson);
|
|
5268
|
+
const skillId = typeof args?.skill_id === "string" ? args.skill_id.trim() : "";
|
|
5269
|
+
if (skillId) {
|
|
5270
|
+
const flow = typeof args?.flow === "string" ? args.flow.trim() : "";
|
|
5271
|
+
return `\u6280\u80FD\u300C${skillId}\u300D${flow && flow !== "main" ? ` \xB7 \u6D41\u7A0B ${flow}` : ""}`;
|
|
5272
|
+
}
|
|
5273
|
+
const name = args?.name;
|
|
4567
5274
|
return typeof name === "string" ? name : "";
|
|
4568
5275
|
} catch {
|
|
4569
5276
|
return "";
|
|
@@ -4587,6 +5294,15 @@ function applyWorkflowEvent(current, toolCallId, type2, payload) {
|
|
|
4587
5294
|
}
|
|
4588
5295
|
const base = current ?? { toolCallId, name: "", status: "running", entries: [] };
|
|
4589
5296
|
if (type2 === "workflow:step") {
|
|
5297
|
+
const settled = asText(payload.status);
|
|
5298
|
+
const stepId = asText(payload.step_id);
|
|
5299
|
+
if (stepId && isFinished(settled)) {
|
|
5300
|
+
const index = base.entries.findIndex((entry) => entry.kind === "step" && entry.stepId === stepId);
|
|
5301
|
+
if (index === -1) return null;
|
|
5302
|
+
const entries = [...base.entries];
|
|
5303
|
+
entries[index] = { ...entries[index], status: settled };
|
|
5304
|
+
return { ...base, entries };
|
|
5305
|
+
}
|
|
4590
5306
|
return {
|
|
4591
5307
|
...base,
|
|
4592
5308
|
entries: [
|
|
@@ -4601,7 +5317,9 @@ function applyWorkflowEvent(current, toolCallId, type2, payload) {
|
|
|
4601
5317
|
};
|
|
4602
5318
|
}
|
|
4603
5319
|
if (type2 === "workflow:log") {
|
|
4604
|
-
|
|
5320
|
+
const stepId = asText(payload.step_id);
|
|
5321
|
+
const entry = stepId ? { kind: "log", text: asText(payload.text), stepId } : { kind: "log", text: asText(payload.text) };
|
|
5322
|
+
return { ...base, entries: [...base.entries, entry] };
|
|
4605
5323
|
}
|
|
4606
5324
|
if (type2 === "workflow:run:end") {
|
|
4607
5325
|
const status = asText(payload.status);
|
|
@@ -4623,10 +5341,10 @@ function rebuildWorkflowRuns(turns, previous) {
|
|
|
4623
5341
|
const name = workflowNameFromArguments(toolCall.arguments);
|
|
4624
5342
|
const prior = previous[toolCall.id];
|
|
4625
5343
|
if (isFinished(toolCall.status)) {
|
|
4626
|
-
const
|
|
4627
|
-
|
|
4628
|
-
);
|
|
4629
|
-
runs[toolCall.id] = prior && prior.status ===
|
|
5344
|
+
const steps = toolCall.workflow_steps ?? [];
|
|
5345
|
+
const entries = steps.length > 0 ? workflowEntriesFromSteps(steps) : workflowEntriesFromOutput(typeof toolCall.result === "string" ? toolCall.result.trim() : "");
|
|
5346
|
+
const status = toolCall.status === "error" && workflowRunCancelled(steps) ? "cancelled" : toolCall.status;
|
|
5347
|
+
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
5348
|
continue;
|
|
4631
5349
|
}
|
|
4632
5350
|
runs[toolCall.id] = prior && prior.name === name ? prior : { toolCallId: toolCall.id, name, status: prior?.status ?? "running", entries: prior?.entries ?? [] };
|
|
@@ -4662,6 +5380,7 @@ function createInitialSessionState(sessionId) {
|
|
|
4662
5380
|
mode: null,
|
|
4663
5381
|
connection: "disconnected",
|
|
4664
5382
|
errorMessage: null,
|
|
5383
|
+
lastRun: null,
|
|
4665
5384
|
askAnswers: {},
|
|
4666
5385
|
agentLoops: {},
|
|
4667
5386
|
activeCompaction: null,
|
|
@@ -4756,14 +5475,12 @@ function parentForkToolCallIdFromTurn(turn) {
|
|
|
4756
5475
|
}
|
|
4757
5476
|
return null;
|
|
4758
5477
|
}
|
|
4759
|
-
function
|
|
4760
|
-
const
|
|
4761
|
-
if (
|
|
4762
|
-
if (
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
return JSON.stringify(block.content);
|
|
4766
|
-
}).join("");
|
|
5478
|
+
function messageContentFromTurn(turn) {
|
|
5479
|
+
const contents = turn.blocks.filter((block) => block.type === "text").map((block) => normalizeMessageContent(block.content));
|
|
5480
|
+
if (contents.length === 0) return "";
|
|
5481
|
+
if (contents.length === 1) return contents[0];
|
|
5482
|
+
if (contents.every((content) => typeof content === "string")) return contents.join("");
|
|
5483
|
+
return contents.flatMap((content) => typeof content === "string" ? [{ type: "text", text: content }] : content);
|
|
4767
5484
|
}
|
|
4768
5485
|
function workspaceNotificationContent(turn) {
|
|
4769
5486
|
const block = turn.blocks.find(
|
|
@@ -4869,7 +5586,7 @@ function projectionToMessage(turn) {
|
|
|
4869
5586
|
...turn.started_at ? { timestamp: turn.started_at } : {}
|
|
4870
5587
|
};
|
|
4871
5588
|
}
|
|
4872
|
-
const content =
|
|
5589
|
+
const content = messageContentFromTurn(turn) || workspaceNotificationContent(turn);
|
|
4873
5590
|
const reasoning = buildReasoning(turn);
|
|
4874
5591
|
const toolCalls = turn.tool_calls.length > 0 ? turn.tool_calls.map((toolCall) => ({
|
|
4875
5592
|
id: toolCall.id,
|
|
@@ -4879,6 +5596,7 @@ function projectionToMessage(turn) {
|
|
|
4879
5596
|
result: toolCall.result ?? void 0,
|
|
4880
5597
|
...toolCall.evidence ? { evidence: toolCall.evidence } : {},
|
|
4881
5598
|
pending_question_ref: toolCall.pending_question_ref ?? void 0,
|
|
5599
|
+
workflow_steps: toolCall.workflow_steps ?? void 0,
|
|
4882
5600
|
status: toolCall.status === "pending" || toolCall.status === "awaiting_answer" || toolCall.status === "done" || toolCall.status === "error" || toolCall.status === "cancelled" ? toolCall.status : "pending",
|
|
4883
5601
|
...typeof toolCall.duration_ms === "number" ? { duration_ms: toolCall.duration_ms } : {}
|
|
4884
5602
|
})) : void 0;
|
|
@@ -4893,11 +5611,13 @@ function projectionToMessage(turn) {
|
|
|
4893
5611
|
...toolCalls ? { tool_calls: toolCalls } : {},
|
|
4894
5612
|
loop_name: turn.loop_id,
|
|
4895
5613
|
entry_id: turn.turn_id,
|
|
5614
|
+
...turn.client_request_id ? { client_request_id: turn.client_request_id } : {},
|
|
4896
5615
|
status: turn.status,
|
|
4897
5616
|
...typeof turn.duration_ms === "number" ? { duration_ms: turn.duration_ms } : {},
|
|
4898
5617
|
...turn.started_at ? { timestamp: turn.started_at } : {},
|
|
4899
5618
|
...turn.memory_refs?.length ? { memory_refs: turn.memory_refs } : {},
|
|
4900
5619
|
...turn.refs?.length ? { refs: turn.refs } : {},
|
|
5620
|
+
...turn.context_attachments?.length ? { context_attachments: turn.context_attachments } : {},
|
|
4901
5621
|
...turn.topic_asset_refs?.length ? { topic_asset_refs: turn.topic_asset_refs } : {}
|
|
4902
5622
|
};
|
|
4903
5623
|
}
|
|
@@ -5125,8 +5845,6 @@ function withTurns(state, turns) {
|
|
|
5125
5845
|
activeCompaction,
|
|
5126
5846
|
askAnswers,
|
|
5127
5847
|
mode: latestMode ?? state.mode,
|
|
5128
|
-
// 历史恢复时 chat:end(paused) 可能已不在 socket replay 缓存中;
|
|
5129
|
-
// awaiting_answer 是投影里的持久权威状态,必须据此恢复问答交互。
|
|
5130
5848
|
status: isWaitingForInput ? "waiting_for_input" : state.status
|
|
5131
5849
|
};
|
|
5132
5850
|
}
|
|
@@ -5135,18 +5853,16 @@ function withQueue(state, snapshot2) {
|
|
|
5135
5853
|
return { ...state, queue: snapshot2 };
|
|
5136
5854
|
}
|
|
5137
5855
|
var localTurnCounter = 0;
|
|
5138
|
-
function addUserMessage(state, content, clientRequestId, topicAssetRefs, refs) {
|
|
5856
|
+
function addUserMessage(state, content, clientRequestId, topicAssetRefs, refs, contextAttachments) {
|
|
5139
5857
|
localTurnCounter += 1;
|
|
5140
5858
|
const turnId = `local-user-${clientRequestId ?? `${Date.now()}-${localTurnCounter}`}`;
|
|
5141
5859
|
const optimisticTurn = {
|
|
5142
5860
|
id: turnId,
|
|
5143
5861
|
sequence: Math.max(0, ...state.turns.map((turn) => turn.sequence)) + 1,
|
|
5144
5862
|
turn_id: turnId,
|
|
5145
|
-
// 乐观态就自赋,跟服务端确认后 reconcileUserTurns 补上的
|
|
5146
|
-
// client_render_id(= 乐观 turn 自己的 turn_id)保持同一个值,
|
|
5147
|
-
// 消费方才能拿它当"确认前后不变"的稳定标识使用。
|
|
5148
5863
|
client_render_id: turnId,
|
|
5149
5864
|
...refs ? { refs } : {},
|
|
5865
|
+
...contextAttachments?.length ? { context_attachments: contextAttachments } : {},
|
|
5150
5866
|
...topicAssetRefs?.length ? { topic_asset_refs: topicAssetRefs } : {},
|
|
5151
5867
|
loop_id: "root",
|
|
5152
5868
|
role: "user",
|
|
@@ -5347,9 +6063,7 @@ var AgentSession = class _AgentSession {
|
|
|
5347
6063
|
logCursor = new LogCursor();
|
|
5348
6064
|
sessionId;
|
|
5349
6065
|
state;
|
|
5350
|
-
/** status 每变化一次加一(单调递增)。异步读取会话详情时据此判断请求期间状态是否变过,避免 running→终态→running 这类来回被误认为「没变」。 */
|
|
5351
6066
|
statusRevision = 0;
|
|
5352
|
-
/** 实时事件写入 status 时调用:值不变也要记一次,才能识别请求期间收到过更新的状态。 */
|
|
5353
6067
|
noteLiveStatus() {
|
|
5354
6068
|
this.statusRevision += 1;
|
|
5355
6069
|
}
|
|
@@ -5364,15 +6078,10 @@ var AgentSession = class _AgentSession {
|
|
|
5364
6078
|
patchFlushCancel = null;
|
|
5365
6079
|
joined = false;
|
|
5366
6080
|
joinPending = null;
|
|
5367
|
-
// bootstrap 与每次 reconnect 共用一条订阅生命周期队列。它们都会重置 join
|
|
5368
|
-
// 状态并临时设置 replay source,禁止并发,否则较早操作的 finally 会清掉
|
|
5369
|
-
// 较晚操作仍在使用的来源上下文。
|
|
5370
6081
|
subscriptionQueue = Promise.resolve();
|
|
5371
6082
|
replaceQueue = Promise.resolve();
|
|
5372
6083
|
timelineEpoch = 0;
|
|
5373
|
-
/** 定位请求的流水号:被后一次选择取代的那次定位不再提交窗口(见 locateEntry)。 */
|
|
5374
6084
|
locateToken = 0;
|
|
5375
|
-
/** 在途那次定位的请求句柄。**只**服务定位:权威刷新不共用它(见 cancelPendingLocate)。 */
|
|
5376
6085
|
locateAbort = null;
|
|
5377
6086
|
pagingGeneration = 0;
|
|
5378
6087
|
liveRevision = 0;
|
|
@@ -5381,14 +6090,7 @@ var AgentSession = class _AgentSession {
|
|
|
5381
6090
|
pendingOptimisticTurnIds = /* @__PURE__ */ new Set();
|
|
5382
6091
|
olderPending = null;
|
|
5383
6092
|
replaceInFlight = 0;
|
|
5384
|
-
// 回放控制请求排成一条队列。连着点"5x"再点"退出回放"时,并发发出去的两个
|
|
5385
|
-
// 请求响应可能乱序回来,晚到的旧值会把已经退出的会话又显示成回放中;用
|
|
5386
|
-
// 序号丢弃过期响应又会在失败时留下中间态。串行执行就没有这些情况:每个
|
|
5387
|
-
// 响应都是当时最新的,失败也只影响自己。
|
|
5388
6093
|
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
6094
|
commandRestoreQueue = Promise.resolve();
|
|
5393
6095
|
commandRecoveryGeneration = 0;
|
|
5394
6096
|
commandRestoreRetryAttempt = 0;
|
|
@@ -5396,33 +6098,22 @@ var AgentSession = class _AgentSession {
|
|
|
5396
6098
|
bufferedCommandDeliveries = null;
|
|
5397
6099
|
pendingReplayMessage = null;
|
|
5398
6100
|
pendingReplayMode;
|
|
6101
|
+
pendingReplayRequestId;
|
|
6102
|
+
pendingReplayAttachments;
|
|
5399
6103
|
pendingReplayRefs;
|
|
5400
6104
|
pendingReplayTopicAssetRefs;
|
|
5401
6105
|
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
6106
|
lastDeliveredSystemError = null;
|
|
5414
|
-
/** 每次投递 `system:error` 递增,用于判定某条失败是否属于本次等待。 */
|
|
5415
6107
|
systemErrorGeneration = 0;
|
|
5416
6108
|
subscriptionReplaySource = null;
|
|
6109
|
+
lifetimeAbort = new AbortController();
|
|
5417
6110
|
disposed = false;
|
|
5418
6111
|
getAppContext = null;
|
|
5419
6112
|
sendPending = false;
|
|
5420
6113
|
manualCompactionRequest = null;
|
|
5421
|
-
/** Reload requests from retracts/epoch changes; done only when a reload started after the latest one succeeds. */
|
|
5422
6114
|
epochReloadRequested = 0;
|
|
5423
6115
|
epochReloadDone = 0;
|
|
5424
6116
|
epochReloadRunning = false;
|
|
5425
|
-
/** 手动整理的在途标记,同时写进状态(界面据此保持「正在整理」,见 SessionState.compactionPending)。 */
|
|
5426
6117
|
setManualCompactionRequest(request) {
|
|
5427
6118
|
this.manualCompactionRequest = request;
|
|
5428
6119
|
const pending = request !== null;
|
|
@@ -5435,16 +6126,8 @@ var AgentSession = class _AgentSession {
|
|
|
5435
6126
|
if (request.runId === null) request.finishedBeforeAck.add(runId);
|
|
5436
6127
|
else if (request.runId === runId) this.setManualCompactionRequest(null);
|
|
5437
6128
|
}
|
|
5438
|
-
/** 最近一次还在等服务端结果的发送请求 id;排队中断的 chat:end 据此判断回滚是否过期。 */
|
|
5439
6129
|
pendingChatRequestId = null;
|
|
5440
|
-
/** 会话详情给出的运行时类型;"native" 时启用原生智能体的投影规则(见 _handleTurnEvents / _handleChatEnd)。 */
|
|
5441
|
-
runtimeType = null;
|
|
5442
|
-
/** workflow_run_id → 触发它的 workflow:run 工具调用 id(只有 run:start 事件带工具调用 id)。 */
|
|
5443
6130
|
workflowRunToolCalls = /* @__PURE__ */ new Map();
|
|
5444
|
-
/**
|
|
5445
|
-
* 第一方 Web 的精简模式传输优化:订阅时是否要 token 级事件。null 表示宿主没设置,订阅时不带这个字段。
|
|
5446
|
-
* `desiredStreamTokens` 是宿主最新的选择;运行中不切换,等这一轮结束再重订阅。
|
|
5447
|
-
*/
|
|
5448
6131
|
desiredStreamTokens = null;
|
|
5449
6132
|
joinedStreamTokens = null;
|
|
5450
6133
|
deliveredCommandKeys = /* @__PURE__ */ new Set();
|
|
@@ -5482,11 +6165,8 @@ var AgentSession = class _AgentSession {
|
|
|
5482
6165
|
emitWithAck: async () => readonlyError(),
|
|
5483
6166
|
ensureConnected: readonlyError,
|
|
5484
6167
|
fetchTurnsPage: async () => ({ turns, nextBefore: null, currentMode: "executing" }),
|
|
5485
|
-
// 静态会话(分享页)没有会话目录接口,宿主用已加载的历史兜底条目。
|
|
5486
6168
|
fetchTurnIndex: async () => ({ sessionId, items: [] }),
|
|
5487
6169
|
fetchCommands: async () => [],
|
|
5488
|
-
// 静态历史没有回放身份可言,给个空详情即可,不要抛错——_bootstrap
|
|
5489
|
-
// 不会跑到这里,但保持只读语义一致。
|
|
5490
6170
|
fetchSessionInfo: async () => ({ replay_state: null }),
|
|
5491
6171
|
updateReplay: async () => readonlyError(),
|
|
5492
6172
|
listDir: async () => readonlyError(),
|
|
@@ -5505,7 +6185,6 @@ var AgentSession = class _AgentSession {
|
|
|
5505
6185
|
};
|
|
5506
6186
|
return session;
|
|
5507
6187
|
}
|
|
5508
|
-
// ---------------------------------------------------------------- 状态订阅
|
|
5509
6188
|
/** 返回当前会话快照。引用稳定:状态未变化时返回同一对象。 */
|
|
5510
6189
|
getState() {
|
|
5511
6190
|
return this.state;
|
|
@@ -5627,11 +6306,6 @@ var AgentSession = class _AgentSession {
|
|
|
5627
6306
|
if (this.disposed || !response || response.ok === false || typeof response.is_running !== "boolean") return;
|
|
5628
6307
|
this._applyRunningState(response.is_running, liveRevision);
|
|
5629
6308
|
}
|
|
5630
|
-
/**
|
|
5631
|
-
* timeline 被整体改写(rewind / checkout / 释放):推进纪元,并把在途定位请求一并中止
|
|
5632
|
-
* ——它已经属于旧 timeline,却还占着替换队列,会让改写后的权威窗口排在后面等它跑完。
|
|
5633
|
-
* 作废号仍然保留:中止只是让它更早结束。
|
|
5634
|
-
*/
|
|
5635
6309
|
invalidateTimeline() {
|
|
5636
6310
|
this.timelineEpoch += 1;
|
|
5637
6311
|
this.locateAbort?.abort();
|
|
@@ -5669,7 +6343,6 @@ var AgentSession = class _AgentSession {
|
|
|
5669
6343
|
update(fn) {
|
|
5670
6344
|
this.setState(fn(this.state));
|
|
5671
6345
|
}
|
|
5672
|
-
// ---------------------------------------------------------------- 语义事件
|
|
5673
6346
|
/** 监听语义事件(底层逃生舱,见 events.ts)。返回取消函数。 */
|
|
5674
6347
|
on(name, handler) {
|
|
5675
6348
|
return this.emitter.on(name, handler);
|
|
@@ -5686,7 +6359,6 @@ var AgentSession = class _AgentSession {
|
|
|
5686
6359
|
onCommand(action, handler) {
|
|
5687
6360
|
return this.commands.onCommand(action, handler);
|
|
5688
6361
|
}
|
|
5689
|
-
// ---------------------------------------------------------------- 动作
|
|
5690
6362
|
/**
|
|
5691
6363
|
* 声明当前应用提供的页面上下文和业务 CLI。
|
|
5692
6364
|
*
|
|
@@ -5697,10 +6369,94 @@ var AgentSession = class _AgentSession {
|
|
|
5697
6369
|
this.getAppContext = options.getContext;
|
|
5698
6370
|
return attachment;
|
|
5699
6371
|
}
|
|
6372
|
+
/** 立即为整个会话切换模型,并接续因模型故障停下的任务。 */
|
|
6373
|
+
async selectModel(model) {
|
|
6374
|
+
try {
|
|
6375
|
+
await this.ensureJoined();
|
|
6376
|
+
const response = await this.runtime.emitWithAck("chat:model", { session_id: this.sessionId, model }, 3e4);
|
|
6377
|
+
if (response?.status !== "ok") throw new Error(typeof response?.message === "string" ? response.message : "\u6A21\u578B\u5207\u6362\u5931\u8D25");
|
|
6378
|
+
return true;
|
|
6379
|
+
} catch (error) {
|
|
6380
|
+
const failure = describeSessionError(error, "\u6A21\u578B\u5207\u6362\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
|
|
6381
|
+
this.update((state) => addErrorMessage(state, failure.message));
|
|
6382
|
+
this.emitter.emit("error", { message: failure.message });
|
|
6383
|
+
return false;
|
|
6384
|
+
}
|
|
6385
|
+
}
|
|
6386
|
+
/** Prepare a durable text input without sending any network request. */
|
|
6387
|
+
prepareSend(content, options = {}) {
|
|
6388
|
+
if (!content.trim()) throw new Error("\u6D88\u606F\u4E0D\u80FD\u4E3A\u7A7A");
|
|
6389
|
+
if (Object.keys(options).some((key) => !["mode", "model", "thinkingOverride", "reasoningLevel", "contextAttachments", "queueWhenRunning", "headless"].includes(key))) {
|
|
6390
|
+
throw new Error("\u53EF\u9760\u6587\u672C\u53D1\u9001\u4E0D\u652F\u6301\u8FD9\u4E9B\u53C2\u6570\uFF0C\u8BF7\u4F7F\u7528 send()");
|
|
6391
|
+
}
|
|
6392
|
+
const snapshot2 = JSON.parse(JSON.stringify(options));
|
|
6393
|
+
if (snapshot2.contextAttachments) snapshot2.contextAttachments = snapshotContextAttachments(snapshot2.contextAttachments);
|
|
6394
|
+
return { sessionId: this.sessionId, requestId: createClientRequestId(), content, options: snapshot2 };
|
|
6395
|
+
}
|
|
6396
|
+
/** Durably send a text input with its saved delivery intent. Retries must reuse the saved request. */
|
|
6397
|
+
async sendPrepared(request) {
|
|
6398
|
+
if (request.sessionId !== this.sessionId) throw new Error("\u53D1\u9001\u8BF7\u6C42\u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD");
|
|
6399
|
+
try {
|
|
6400
|
+
this.runtime.ensureConnected();
|
|
6401
|
+
const response = await this.runtime.emitWithAck("chat:append", {
|
|
6402
|
+
session_id: this.sessionId,
|
|
6403
|
+
client_request_id: request.requestId,
|
|
6404
|
+
message: request.content,
|
|
6405
|
+
prepared_options: {
|
|
6406
|
+
mode: request.options.mode,
|
|
6407
|
+
model: request.options.model,
|
|
6408
|
+
...request.options.headless !== void 0 ? { headless: request.options.headless } : {},
|
|
6409
|
+
...request.options.queueWhenRunning !== void 0 ? { queue_when_running: request.options.queueWhenRunning } : {},
|
|
6410
|
+
thinking_override: request.options.thinkingOverride,
|
|
6411
|
+
reasoning_level: request.options.reasoningLevel,
|
|
6412
|
+
...request.options.contextAttachments ? { context_attachments: request.options.contextAttachments } : {}
|
|
6413
|
+
}
|
|
6414
|
+
}, QUEUE_ACK_TIMEOUT_MS);
|
|
6415
|
+
const result = parseQueueAck(response, this.sessionId);
|
|
6416
|
+
if (result.snapshot) this.update((state) => withQueue(state, result.snapshot));
|
|
6417
|
+
if (!result.ok) return {
|
|
6418
|
+
requestId: request.requestId,
|
|
6419
|
+
status: response?.status === "conflict" ? "rejected" : "unknown",
|
|
6420
|
+
message: result.message ?? void 0
|
|
6421
|
+
};
|
|
6422
|
+
const delivery = response?.delivery;
|
|
6423
|
+
if (!isRecord(delivery) || delivery.status !== "accepted") return { requestId: request.requestId, status: "unknown" };
|
|
6424
|
+
return {
|
|
6425
|
+
requestId: request.requestId,
|
|
6426
|
+
status: "accepted",
|
|
6427
|
+
itemId: typeof delivery.item_id === "string" ? delivery.item_id : void 0,
|
|
6428
|
+
queueStatus: typeof delivery.queue_status === "string" ? delivery.queue_status : void 0,
|
|
6429
|
+
executionId: typeof delivery.execution_id === "string" ? delivery.execution_id : null
|
|
6430
|
+
};
|
|
6431
|
+
} catch {
|
|
6432
|
+
return { requestId: request.requestId, status: "unknown" };
|
|
6433
|
+
}
|
|
6434
|
+
}
|
|
6435
|
+
/** Owner-authorized lookup; receipts remain until the session is deleted. */
|
|
6436
|
+
async getDelivery(requestId) {
|
|
6437
|
+
try {
|
|
6438
|
+
this.runtime.ensureConnected();
|
|
6439
|
+
const response = await this.runtime.emitWithAck("chat:queue:request", {
|
|
6440
|
+
session_id: this.sessionId,
|
|
6441
|
+
client_request_id: requestId
|
|
6442
|
+
}, QUEUE_ACK_TIMEOUT_MS);
|
|
6443
|
+
if (response?.status === "accepted") return {
|
|
6444
|
+
requestId,
|
|
6445
|
+
status: "accepted",
|
|
6446
|
+
itemId: typeof response.item_id === "string" ? response.item_id : void 0,
|
|
6447
|
+
queueStatus: typeof response.queue_status === "string" ? response.queue_status : void 0,
|
|
6448
|
+
executionId: typeof response.execution_id === "string" ? response.execution_id : null
|
|
6449
|
+
};
|
|
6450
|
+
if (response?.status === "not_found") return { requestId, status: "not_found" };
|
|
6451
|
+
return { requestId, status: "unknown", message: typeof response?.message === "string" ? response.message : void 0 };
|
|
6452
|
+
} catch {
|
|
6453
|
+
return { requestId, status: "unknown" };
|
|
6454
|
+
}
|
|
6455
|
+
}
|
|
5700
6456
|
/** 发送一条消息。字符串或多模态内容均可。 */
|
|
5701
6457
|
async send(content, options = {}) {
|
|
5702
6458
|
this.runtime.ensureConnected();
|
|
5703
|
-
if (this.state.
|
|
6459
|
+
if (this.state.activeCompaction || this.sendPending || this.manualCompactionRequest) {
|
|
5704
6460
|
this.update(
|
|
5705
6461
|
(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
6462
|
);
|
|
@@ -5809,10 +6565,6 @@ var AgentSession = class _AgentSession {
|
|
|
5809
6565
|
async refreshQueue() {
|
|
5810
6566
|
return this.runQueueCommand("chat:queue:list", { session_id: this.sessionId });
|
|
5811
6567
|
}
|
|
5812
|
-
/**
|
|
5813
|
-
* 发出一条队列命令并安装 ack 里的快照。
|
|
5814
|
-
* 传输层失败(超时 / 断线)会 reject,由调用方决定是否重试。
|
|
5815
|
-
*/
|
|
5816
6568
|
async requestQueueAck(event, payload) {
|
|
5817
6569
|
this.runtime.ensureConnected();
|
|
5818
6570
|
const response = await this.runtime.emitWithAck(event, payload, QUEUE_ACK_TIMEOUT_MS);
|
|
@@ -5821,7 +6573,6 @@ var AgentSession = class _AgentSession {
|
|
|
5821
6573
|
if (snapshot2) this.update((state) => withQueue(state, snapshot2));
|
|
5822
6574
|
return result;
|
|
5823
6575
|
}
|
|
5824
|
-
/** 队列命令的对外入口:传输失败只体现为失败结果,不向调用方抛异常。 */
|
|
5825
6576
|
async runQueueCommand(event, payload) {
|
|
5826
6577
|
try {
|
|
5827
6578
|
return await this.requestQueueAck(event, payload);
|
|
@@ -5830,15 +6581,16 @@ var AgentSession = class _AgentSession {
|
|
|
5830
6581
|
}
|
|
5831
6582
|
}
|
|
5832
6583
|
async sendUnlocked(content, options) {
|
|
6584
|
+
const contextAttachments = options.contextAttachments ? snapshotContextAttachments(options.contextAttachments) : void 0;
|
|
5833
6585
|
await this.ensureIdleBeforeSend();
|
|
5834
|
-
if (this.state.
|
|
6586
|
+
if (this.state.activeCompaction || this.manualCompactionRequest) {
|
|
5835
6587
|
this.update(
|
|
5836
6588
|
(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
6589
|
);
|
|
5838
6590
|
return false;
|
|
5839
6591
|
}
|
|
5840
6592
|
let appContext;
|
|
5841
|
-
if (this.getAppContext) {
|
|
6593
|
+
if (this.getAppContext && !this.state.isStreaming) {
|
|
5842
6594
|
try {
|
|
5843
6595
|
const rawContext = await this.getAppContext();
|
|
5844
6596
|
if (!isRecord(rawContext)) {
|
|
@@ -5866,7 +6618,7 @@ var AgentSession = class _AgentSession {
|
|
|
5866
6618
|
let optimisticAskAnswer;
|
|
5867
6619
|
let previousAskAnswer;
|
|
5868
6620
|
this.update((state) => {
|
|
5869
|
-
const next = addUserMessage(state, content, clientRequestId, options.topicAssetRefs, options.refs);
|
|
6621
|
+
const next = addUserMessage(state, content, clientRequestId, options.topicAssetRefs, options.refs, contextAttachments);
|
|
5870
6622
|
optimisticTurnId = next.turns.at(-1)?.turn_id ?? null;
|
|
5871
6623
|
return next;
|
|
5872
6624
|
});
|
|
@@ -5884,6 +6636,8 @@ var AgentSession = class _AgentSession {
|
|
|
5884
6636
|
if (!options.replayDecision) {
|
|
5885
6637
|
this.pendingReplayMessage = content;
|
|
5886
6638
|
this.pendingReplayMode = options.mode;
|
|
6639
|
+
this.pendingReplayRequestId = clientRequestId;
|
|
6640
|
+
this.pendingReplayAttachments = contextAttachments;
|
|
5887
6641
|
this.pendingReplayRefs = options.refs;
|
|
5888
6642
|
this.pendingReplayTopicAssetRefs = options.topicAssetRefs;
|
|
5889
6643
|
}
|
|
@@ -5900,9 +6654,9 @@ var AgentSession = class _AgentSession {
|
|
|
5900
6654
|
whatif: options.whatif,
|
|
5901
6655
|
replay_decision: options.replayDecision,
|
|
5902
6656
|
app_context: appContext,
|
|
6657
|
+
context_attachments: contextAttachments,
|
|
5903
6658
|
refs: options.refs,
|
|
5904
6659
|
topic_asset_refs: options.topicAssetRefs,
|
|
5905
|
-
// 运行中提交不必由客户端挑命令:服务端按会话运行状态决定直接执行还是入队。
|
|
5906
6660
|
queue_when_running: options.queueWhenRunning === true
|
|
5907
6661
|
};
|
|
5908
6662
|
try {
|
|
@@ -5944,6 +6698,14 @@ var AgentSession = class _AgentSession {
|
|
|
5944
6698
|
typeof response?.code === "string" ? response.code : void 0
|
|
5945
6699
|
);
|
|
5946
6700
|
}
|
|
6701
|
+
if (optimisticTurnId) {
|
|
6702
|
+
this.update((state) => {
|
|
6703
|
+
const next = withTurns(state, state.turns.map(
|
|
6704
|
+
(turn) => turn.turn_id === optimisticTurnId ? { ...turn, status: "completed" } : turn
|
|
6705
|
+
));
|
|
6706
|
+
return { ...next, askAnswers: state.askAnswers };
|
|
6707
|
+
});
|
|
6708
|
+
}
|
|
5947
6709
|
return true;
|
|
5948
6710
|
} catch (error) {
|
|
5949
6711
|
const failure = describeSessionError(error, "\u6D88\u606F\u53D1\u9001\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5");
|
|
@@ -5978,13 +6740,14 @@ var AgentSession = class _AgentSession {
|
|
|
5978
6740
|
}
|
|
5979
6741
|
this.emitter.emit("error", { message, ...code ? { code } : {} });
|
|
5980
6742
|
}
|
|
5981
|
-
/** 撤回一次乐观提交:移除乐观消息、恢复提问作答、清掉回放草稿。 */
|
|
5982
6743
|
discardOptimisticSend(optimisticTurnId, askUserAnswer, optimisticAskAnswer, previousAskAnswer) {
|
|
5983
6744
|
if (optimisticTurnId && this.pendingChatRequestId && optimisticTurnId === `local-user-${this.pendingChatRequestId}`) {
|
|
5984
6745
|
this.pendingChatRequestId = null;
|
|
5985
6746
|
}
|
|
5986
6747
|
this.pendingReplayMessage = null;
|
|
5987
6748
|
this.pendingReplayMode = void 0;
|
|
6749
|
+
this.pendingReplayRequestId = void 0;
|
|
6750
|
+
this.pendingReplayAttachments = void 0;
|
|
5988
6751
|
this.pendingReplayRefs = void 0;
|
|
5989
6752
|
this.pendingReplayTopicAssetRefs = void 0;
|
|
5990
6753
|
this.update((current) => {
|
|
@@ -6008,9 +6771,9 @@ var AgentSession = class _AgentSession {
|
|
|
6008
6771
|
}
|
|
6009
6772
|
}
|
|
6010
6773
|
/** 停止当前回复。 */
|
|
6011
|
-
async stop() {
|
|
6774
|
+
async stop(executionId) {
|
|
6012
6775
|
const request = this.manualCompactionRequest;
|
|
6013
|
-
if (request) {
|
|
6776
|
+
if (request && !executionId) {
|
|
6014
6777
|
const ack = await request.ack;
|
|
6015
6778
|
if (ack.status !== "accepted") return ack;
|
|
6016
6779
|
if (this.manualCompactionRequest !== request) return { status: "idle" };
|
|
@@ -6019,7 +6782,7 @@ var AgentSession = class _AgentSession {
|
|
|
6019
6782
|
chat_run_id: request.runId
|
|
6020
6783
|
}, 35e3) ?? {};
|
|
6021
6784
|
}
|
|
6022
|
-
const response = await this.runtime.emitWithAck("chat:stop", { session_id: this.sessionId }, 35e3) ?? {};
|
|
6785
|
+
const response = await this.runtime.emitWithAck("chat:stop", { session_id: this.sessionId, ...executionId ? { chat_run_id: executionId } : {} }, 35e3) ?? {};
|
|
6023
6786
|
const cancelled = response.cancelled_client_request_ids;
|
|
6024
6787
|
if (response.status === "stopped" && Array.isArray(cancelled) && this.pendingChatRequestId !== null && cancelled.includes(this.pendingChatRequestId)) {
|
|
6025
6788
|
this.pendingChatRequestId = null;
|
|
@@ -6108,6 +6871,7 @@ var AgentSession = class _AgentSession {
|
|
|
6108
6871
|
if (this.disposed) return;
|
|
6109
6872
|
if (!this.runtime.onDispose(this)) return;
|
|
6110
6873
|
this.disposed = true;
|
|
6874
|
+
this.lifetimeAbort.abort();
|
|
6111
6875
|
this.invalidateTimeline();
|
|
6112
6876
|
this.invalidateOlderPaging();
|
|
6113
6877
|
this.state = { ...this.state, nextBefore: null, loadingOlder: false };
|
|
@@ -6126,22 +6890,15 @@ var AgentSession = class _AgentSession {
|
|
|
6126
6890
|
get isDisposed() {
|
|
6127
6891
|
return this.disposed;
|
|
6128
6892
|
}
|
|
6129
|
-
// ------------------------------------------------------- Hub 回调(内部)
|
|
6130
|
-
/** @internal 连接状态变化(同 client 下所有会话共享一条连接)。 */
|
|
6131
6893
|
_setConnection(connection) {
|
|
6132
6894
|
if (this.state.connection === connection) return;
|
|
6133
6895
|
this.update((s) => ({ ...s, connection }));
|
|
6134
6896
|
}
|
|
6135
|
-
/**
|
|
6136
|
-
* @internal 服务端广播的权威队列快照。
|
|
6137
|
-
* 结构不合法或 revision 不新的一律丢弃,绝不用旧快照覆盖新状态。
|
|
6138
|
-
*/
|
|
6139
6897
|
_handleQueueUpdated(payload) {
|
|
6140
6898
|
if (!isSessionQueueSnapshot(payload)) return;
|
|
6141
6899
|
const snapshot2 = payload;
|
|
6142
6900
|
this.update((state) => withQueue(state, snapshot2));
|
|
6143
6901
|
}
|
|
6144
|
-
/** @internal socket 重连后由 Hub 调用:重新加入房间并补数。 */
|
|
6145
6902
|
_rejoinAfterReconnect() {
|
|
6146
6903
|
this.invalidateOlderPaging();
|
|
6147
6904
|
this.update((state) => ({ ...state, nextBefore: null, loadingOlder: false }));
|
|
@@ -6170,7 +6927,6 @@ var AgentSession = class _AgentSession {
|
|
|
6170
6927
|
}
|
|
6171
6928
|
});
|
|
6172
6929
|
}
|
|
6173
|
-
/** @internal 首次连接:加载历史 + 加入房间。 */
|
|
6174
6930
|
_bootstrap() {
|
|
6175
6931
|
const commandRecoveryGeneration = this.beginCommandRecovery();
|
|
6176
6932
|
return this.enqueueSubscription(async () => {
|
|
@@ -6181,7 +6937,6 @@ var AgentSession = class _AgentSession {
|
|
|
6181
6937
|
Promise.resolve().then(fetchDetail).catch(() => fetchDetail()).catch(() => null)
|
|
6182
6938
|
]);
|
|
6183
6939
|
if (this.disposed) return;
|
|
6184
|
-
if (detail) this.runtimeType = detail.runtime_type ?? null;
|
|
6185
6940
|
this.subscriptionReplaySource = "bootstrap_replay";
|
|
6186
6941
|
try {
|
|
6187
6942
|
await this.ensureJoined();
|
|
@@ -6195,17 +6950,14 @@ var AgentSession = class _AgentSession {
|
|
|
6195
6950
|
]);
|
|
6196
6951
|
});
|
|
6197
6952
|
}
|
|
6198
|
-
/** 订阅生命周期串行执行;一次失败只由自己的调用方观察,不截断后续重连。 */
|
|
6199
6953
|
enqueueSubscription(operation) {
|
|
6200
6954
|
const run = this.subscriptionQueue.then(operation);
|
|
6201
6955
|
this.subscriptionQueue = run.catch(() => void 0);
|
|
6202
6956
|
return run;
|
|
6203
6957
|
}
|
|
6204
|
-
/** 改回放是 owner 专属(服务端 PATCH 走 _get_owned_session)。 */
|
|
6205
6958
|
get canControlReplay() {
|
|
6206
6959
|
return this.state.viewerRole !== "viewer";
|
|
6207
6960
|
}
|
|
6208
|
-
/** 拉一次会话详情,填会话状态、回放状态、只读身份和运行时类型;失败不挡启动。 */
|
|
6209
6961
|
async syncSessionFromDetail(options) {
|
|
6210
6962
|
const statusRevisionAtRequest = this.statusRevision;
|
|
6211
6963
|
try {
|
|
@@ -6214,18 +6966,14 @@ var AgentSession = class _AgentSession {
|
|
|
6214
6966
|
} catch {
|
|
6215
6967
|
}
|
|
6216
6968
|
}
|
|
6217
|
-
/** 安装一份会话详情;`statusRevisionAtRequest` 是发出请求时的状态修订号。 */
|
|
6218
6969
|
applySessionDetail(info, statusRevisionAtRequest) {
|
|
6219
6970
|
if (this.disposed) return;
|
|
6220
|
-
this.runtimeType = info.runtime_type ?? null;
|
|
6221
6971
|
const replay = toReplaySnapshot(info.replay_state);
|
|
6222
6972
|
const viewerRole = info.viewer_role ?? null;
|
|
6223
6973
|
this.update((s) => ({
|
|
6224
6974
|
...s,
|
|
6225
6975
|
replay,
|
|
6226
6976
|
viewerRole,
|
|
6227
|
-
// 请求期间 status 变过(哪怕又变回原值)就说明实时事件比这份详情更新,不覆盖。
|
|
6228
|
-
// child_pause 已让提问进入等待态,而稍旧的详情仍可能写着 running。
|
|
6229
6977
|
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
6978
|
}));
|
|
6231
6979
|
}
|
|
@@ -6239,7 +6987,6 @@ var AgentSession = class _AgentSession {
|
|
|
6239
6987
|
if (!this.state.replay?.isReplay || !this.canControlReplay) return;
|
|
6240
6988
|
await this.applyReplayControl({ status: "autonomous" });
|
|
6241
6989
|
}
|
|
6242
|
-
/** 把一次回放控制请求排进队列;前一个完成后才发出,响应直接安装。 */
|
|
6243
6990
|
applyReplayControl(payload) {
|
|
6244
6991
|
const run = this.replayQueue.then(async () => {
|
|
6245
6992
|
const result = await this.runtime.updateReplay(this.sessionId, payload);
|
|
@@ -6248,12 +6995,10 @@ var AgentSession = class _AgentSession {
|
|
|
6248
6995
|
this.replayQueue = run.catch(() => void 0);
|
|
6249
6996
|
return run;
|
|
6250
6997
|
}
|
|
6251
|
-
/** @internal */
|
|
6252
6998
|
_handleTurnStart(turn) {
|
|
6253
6999
|
this.markRunningIfIdle();
|
|
6254
7000
|
this.applyTurn(turn);
|
|
6255
7001
|
}
|
|
6256
|
-
/** @internal */
|
|
6257
7002
|
_handleTurnPatch(patch) {
|
|
6258
7003
|
this.markRunningIfIdle();
|
|
6259
7004
|
if (patch.data.workspace_changed) {
|
|
@@ -6269,7 +7014,6 @@ var AgentSession = class _AgentSession {
|
|
|
6269
7014
|
}
|
|
6270
7015
|
this.schedulePatchFlush();
|
|
6271
7016
|
}
|
|
6272
|
-
/** @internal */
|
|
6273
7017
|
_handleTurnEnd(turn) {
|
|
6274
7018
|
this.applyTurn(turn);
|
|
6275
7019
|
}
|
|
@@ -6284,18 +7028,19 @@ var AgentSession = class _AgentSession {
|
|
|
6284
7028
|
if (this.epochReloadRequested > target) this.runEpochReload();
|
|
6285
7029
|
});
|
|
6286
7030
|
}
|
|
6287
|
-
/** @internal 历史回放通道(event_format: raw)。 */
|
|
6288
7031
|
_handleTurnEvents(incoming, replayed = false) {
|
|
6289
7032
|
const delivery = this.logCursor.consume(incoming);
|
|
6290
7033
|
let events = delivery.events;
|
|
6291
7034
|
if (delivery.reload) {
|
|
6292
7035
|
this.activeReplayPlaybackId = null;
|
|
6293
7036
|
this.projectionBuilder.reset();
|
|
7037
|
+
this.update((state) => ({ ...state, lastRun: null }));
|
|
6294
7038
|
this.pendingTurnPatches.clear();
|
|
6295
7039
|
this.epochReloadRequested += 1;
|
|
6296
7040
|
}
|
|
6297
7041
|
this.runEpochReload();
|
|
6298
7042
|
for (const event of events) {
|
|
7043
|
+
if (event.type === "chat:end") this.recordRunResult(event.payload);
|
|
6299
7044
|
const playbackId = typeof event.payload.playback_id === "string" ? event.payload.playback_id : null;
|
|
6300
7045
|
if (event.type === "chat:start") this.activeReplayPlaybackId = null;
|
|
6301
7046
|
if (event.type === "replay:start" && playbackId) {
|
|
@@ -6364,7 +7109,6 @@ var AgentSession = class _AgentSession {
|
|
|
6364
7109
|
const updates = this.projectionBuilder.processBatch(events);
|
|
6365
7110
|
for (const update of updates) {
|
|
6366
7111
|
if (update.kind === "upsert") {
|
|
6367
|
-
if (this.isNativeBootstrapTurn(update.turn)) continue;
|
|
6368
7112
|
this.applyTurn(
|
|
6369
7113
|
update.turn,
|
|
6370
7114
|
replayed ? this.subscriptionReplaySource ?? "bootstrap_replay" : "live"
|
|
@@ -6387,7 +7131,6 @@ var AgentSession = class _AgentSession {
|
|
|
6387
7131
|
this.completeChat(terminalChatEndStatus ?? "completed");
|
|
6388
7132
|
}
|
|
6389
7133
|
}
|
|
6390
|
-
/** @internal */
|
|
6391
7134
|
_handleChatStart() {
|
|
6392
7135
|
this.noteLiveStatus();
|
|
6393
7136
|
this.update((s) => ({
|
|
@@ -6397,10 +7140,14 @@ var AgentSession = class _AgentSession {
|
|
|
6397
7140
|
isStreaming: true
|
|
6398
7141
|
}));
|
|
6399
7142
|
}
|
|
6400
|
-
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
7143
|
+
recordRunResult(payload) {
|
|
7144
|
+
const runId = payload.chat_run_id;
|
|
7145
|
+
if (payload.queued || typeof runId !== "string" || !runId) return;
|
|
7146
|
+
this.update((state) => ({
|
|
7147
|
+
...state,
|
|
7148
|
+
lastRun: { runId, status: payload.status ?? "completed", result: payload.result }
|
|
7149
|
+
}));
|
|
7150
|
+
}
|
|
6404
7151
|
_handleChatEnd(payload = {}) {
|
|
6405
7152
|
const status = payload.status ?? "completed";
|
|
6406
7153
|
if (payload.queued === true) {
|
|
@@ -6410,6 +7157,7 @@ var AgentSession = class _AgentSession {
|
|
|
6410
7157
|
return false;
|
|
6411
7158
|
}
|
|
6412
7159
|
}
|
|
7160
|
+
this.recordRunResult(payload);
|
|
6413
7161
|
this.pendingChatRequestId = null;
|
|
6414
7162
|
this.noteLiveStatus();
|
|
6415
7163
|
this.flushPatches();
|
|
@@ -6419,29 +7167,9 @@ var AgentSession = class _AgentSession {
|
|
|
6419
7167
|
this.emitter.emit("chatEnd", { status });
|
|
6420
7168
|
return true;
|
|
6421
7169
|
}
|
|
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
7170
|
this.completeChat(status);
|
|
6442
7171
|
return true;
|
|
6443
7172
|
}
|
|
6444
|
-
/** @internal */
|
|
6445
7173
|
_handleSystemError(message, code) {
|
|
6446
7174
|
this.pendingChatRequestId = null;
|
|
6447
7175
|
this.noteLiveStatus();
|
|
@@ -6471,15 +7199,12 @@ var AgentSession = class _AgentSession {
|
|
|
6471
7199
|
...code ? { code } : {}
|
|
6472
7200
|
});
|
|
6473
7201
|
}
|
|
6474
|
-
/** @internal */
|
|
6475
7202
|
_handleTaskUpdated(tasks) {
|
|
6476
7203
|
this.emitter.emit("taskListUpdated", { tasks });
|
|
6477
7204
|
}
|
|
6478
|
-
/** @internal */
|
|
6479
7205
|
_handleWorkspaceFilesChanged(filePath, paths) {
|
|
6480
7206
|
this.emitter.emit("workspaceChanged", paths?.length ? { filePath, paths } : { filePath });
|
|
6481
7207
|
}
|
|
6482
|
-
/** @internal */
|
|
6483
7208
|
_handleSessionUpdated(data) {
|
|
6484
7209
|
if (data.status) {
|
|
6485
7210
|
this.noteLiveStatus();
|
|
@@ -6495,11 +7220,9 @@ var AgentSession = class _AgentSession {
|
|
|
6495
7220
|
intent: data.intent,
|
|
6496
7221
|
status: data.status,
|
|
6497
7222
|
model: data.model,
|
|
6498
|
-
boundSkillId: data.bound_skill_id,
|
|
6499
7223
|
replayState: data.replay_state
|
|
6500
7224
|
});
|
|
6501
7225
|
}
|
|
6502
|
-
/** @internal */
|
|
6503
7226
|
_handleRewind(checkpointId) {
|
|
6504
7227
|
this.invalidateTimeline();
|
|
6505
7228
|
this.invalidateOlderPaging();
|
|
@@ -6514,14 +7237,17 @@ var AgentSession = class _AgentSession {
|
|
|
6514
7237
|
void this.replaceFromHistory();
|
|
6515
7238
|
this.emitter.emit("rewind", { checkpointId });
|
|
6516
7239
|
}
|
|
6517
|
-
/** @internal */
|
|
6518
7240
|
_handleReplayMismatch(data) {
|
|
6519
7241
|
const message = this.pendingReplayMessage ?? data.actual_message ?? "";
|
|
6520
7242
|
const mode = this.pendingReplayMode;
|
|
7243
|
+
const requestId = this.pendingReplayRequestId ?? createClientRequestId();
|
|
7244
|
+
const contextAttachments = this.pendingReplayAttachments;
|
|
6521
7245
|
const refs = this.pendingReplayRefs;
|
|
6522
7246
|
const topicAssetRefs = this.pendingReplayTopicAssetRefs;
|
|
6523
7247
|
this.pendingReplayMessage = null;
|
|
6524
7248
|
this.pendingReplayMode = void 0;
|
|
7249
|
+
this.pendingReplayRequestId = void 0;
|
|
7250
|
+
this.pendingReplayAttachments = void 0;
|
|
6525
7251
|
this.pendingReplayRefs = void 0;
|
|
6526
7252
|
this.pendingReplayTopicAssetRefs = void 0;
|
|
6527
7253
|
const respond = (decision) => {
|
|
@@ -6532,8 +7258,10 @@ var AgentSession = class _AgentSession {
|
|
|
6532
7258
|
message,
|
|
6533
7259
|
mode,
|
|
6534
7260
|
replay_decision: decision,
|
|
7261
|
+
client_request_id: requestId,
|
|
6535
7262
|
refs,
|
|
6536
|
-
topic_asset_refs: topicAssetRefs
|
|
7263
|
+
topic_asset_refs: topicAssetRefs,
|
|
7264
|
+
context_attachments: contextAttachments
|
|
6537
7265
|
},
|
|
6538
7266
|
3e4
|
|
6539
7267
|
).then((response) => {
|
|
@@ -6562,7 +7290,6 @@ var AgentSession = class _AgentSession {
|
|
|
6562
7290
|
respond("continue_replay");
|
|
6563
7291
|
}
|
|
6564
7292
|
}
|
|
6565
|
-
/** @internal */
|
|
6566
7293
|
_handleSystemNotification(loopId, notification) {
|
|
6567
7294
|
const notificationType = typeof notification.notification_type === "string" ? notification.notification_type : "system_notification";
|
|
6568
7295
|
const title = typeof notification.title === "string" ? notification.title : notificationType;
|
|
@@ -6589,11 +7316,9 @@ var AgentSession = class _AgentSession {
|
|
|
6589
7316
|
}
|
|
6590
7317
|
}
|
|
6591
7318
|
}
|
|
6592
|
-
/** @internal */
|
|
6593
7319
|
_handleBackgroundTask(task) {
|
|
6594
7320
|
this.emitter.emit("backgroundTask", task);
|
|
6595
7321
|
}
|
|
6596
|
-
/** @internal */
|
|
6597
7322
|
_handleArtifact(data, kind, replayed = false) {
|
|
6598
7323
|
const filePath = typeof data.file_path === "string" ? data.file_path : "";
|
|
6599
7324
|
if (!filePath) return;
|
|
@@ -6609,7 +7334,6 @@ var AgentSession = class _AgentSession {
|
|
|
6609
7334
|
kind
|
|
6610
7335
|
});
|
|
6611
7336
|
}
|
|
6612
|
-
/** @internal 加入房间的应答里带 is_running,据此校准流式状态。 */
|
|
6613
7337
|
_applyRunningState(isRunning, liveRevisionAtJoin = this.liveRevision) {
|
|
6614
7338
|
const hasPendingQuestion = this.state.turns.some(
|
|
6615
7339
|
(turn) => turn.tool_calls.some((call) => call.status === "awaiting_answer")
|
|
@@ -6622,7 +7346,6 @@ var AgentSession = class _AgentSession {
|
|
|
6622
7346
|
void this.refreshAuthoritativeHistory({ liveRevisionAtStart: liveRevisionAtJoin });
|
|
6623
7347
|
}
|
|
6624
7348
|
}
|
|
6625
|
-
// ---------------------------------------------------------------- 内部实现
|
|
6626
7349
|
markRunningIfIdle() {
|
|
6627
7350
|
if (!this.state.isStreaming) {
|
|
6628
7351
|
this.noteLiveStatus();
|
|
@@ -6639,15 +7362,6 @@ var AgentSession = class _AgentSession {
|
|
|
6639
7362
|
});
|
|
6640
7363
|
this.applyDesiredStreamTokens();
|
|
6641
7364
|
}
|
|
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
7365
|
applyWorkflowEvents(events) {
|
|
6652
7366
|
for (const event of events) {
|
|
6653
7367
|
if (!isWorkflowEvent(event.type)) continue;
|
|
@@ -6662,10 +7376,6 @@ var AgentSession = class _AgentSession {
|
|
|
6662
7376
|
this.update((state) => withWorkflowEvent(state, toolCallId, event.type, payload));
|
|
6663
7377
|
}
|
|
6664
7378
|
}
|
|
6665
|
-
/**
|
|
6666
|
-
* @internal 宿主改了 token 订阅偏好(精简模式)。空闲时立即重订阅;运行中等这一轮结束再换,
|
|
6667
|
-
* 避免在输出中途丢掉 token 流。
|
|
6668
|
-
*/
|
|
6669
7379
|
_setStreamTokens(enabled) {
|
|
6670
7380
|
this.desiredStreamTokens = enabled;
|
|
6671
7381
|
if (!this.state.isStreaming) this.applyDesiredStreamTokens();
|
|
@@ -6683,7 +7393,7 @@ var AgentSession = class _AgentSession {
|
|
|
6683
7393
|
completeChat(status) {
|
|
6684
7394
|
this.finishStreaming(status);
|
|
6685
7395
|
this.recentChatEndAt = Date.now();
|
|
6686
|
-
|
|
7396
|
+
void this.refreshAuthoritativeHistory();
|
|
6687
7397
|
this.emitter.emit("chatEnd", { status });
|
|
6688
7398
|
}
|
|
6689
7399
|
markTurnFresh(turnId) {
|
|
@@ -6761,7 +7471,6 @@ var AgentSession = class _AgentSession {
|
|
|
6761
7471
|
this.patchFlushCancel = null;
|
|
6762
7472
|
}
|
|
6763
7473
|
}
|
|
6764
|
-
/** turn 数据落地后统一派生语义事件(指令 / 工具调用 / 消息 / 模式 / 预览 / OOM)。 */
|
|
6765
7474
|
emitTurnDerivedEvents(previous, turn, source = "live") {
|
|
6766
7475
|
this.emitter.emit("turnUpdated", { turn, source });
|
|
6767
7476
|
const mode = extractModeFromBlocks(turn.blocks);
|
|
@@ -6874,20 +7583,11 @@ var AgentSession = class _AgentSession {
|
|
|
6874
7583
|
this.update((s) => addErrorMessage(s, OOM_MESSAGE));
|
|
6875
7584
|
this.emitter.emit("sandboxOom", { toolCallId: key });
|
|
6876
7585
|
}
|
|
6877
|
-
/**
|
|
6878
|
-
* 权威刷新(运行结束 / 重连补数):**按当前窗口第一条发言取窗口**,不再另记"用户想看哪段"。
|
|
6879
|
-
*
|
|
6880
|
-
* 窗口本身就是"用户在看哪段":首屏就是最新一页,向上翻页 / 定位之后首条就是用户滚到的位置。
|
|
6881
|
-
* 直接拿 `from_entry_id = 当前窗口第一条 turn_id` 去取,运行结束、重连补数、翻页之后的对账
|
|
6882
|
-
* 是同一条规则,不需要意图、锚点、已落地锚点这些状态;窗口首条已经不在分支上(404 / 409)时
|
|
6883
|
-
* 回落到最新一页。
|
|
6884
|
-
*/
|
|
6885
7586
|
refreshAuthoritativeHistory(options = {}) {
|
|
6886
7587
|
let entryGone = false;
|
|
6887
7588
|
const locateTokenAtStart = this.locateToken;
|
|
6888
7589
|
return this.replaceFromHistory({
|
|
6889
7590
|
...options,
|
|
6890
|
-
// 锚点在**这次操作真正开始**时采样:排队期间用户可能刚定位过,那时窗口首条才是他要的。
|
|
6891
7591
|
fromEntryId: () => {
|
|
6892
7592
|
const anchor = this.state.turns[0]?.turn_id;
|
|
6893
7593
|
return anchor?.startsWith("local-user-") ? void 0 : anchor;
|
|
@@ -7055,7 +7755,6 @@ var AgentSession = class _AgentSession {
|
|
|
7055
7755
|
this.bufferedCommandDeliveries = null;
|
|
7056
7756
|
}
|
|
7057
7757
|
}
|
|
7058
|
-
/** 首次订阅前的 REST 历史建立语义事件基线,随后同一工具的订阅回放不再投递。 */
|
|
7059
7758
|
seedToolCallDeliveryBaseline(turns) {
|
|
7060
7759
|
for (const turn of turns) {
|
|
7061
7760
|
for (const toolCall of turn.tool_calls) {
|
|
@@ -7097,7 +7796,41 @@ var AgentSession = class _AgentSession {
|
|
|
7097
7796
|
return join;
|
|
7098
7797
|
}
|
|
7099
7798
|
async ensureIdleBeforeSend() {
|
|
7100
|
-
if (this.
|
|
7799
|
+
if (this.disposed) throw new AgentSessionError("\u4F1A\u8BDD\u5DF2\u5173\u95ED\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\u3002", "session_disposed");
|
|
7800
|
+
if (this.state.status === "waiting_for_input" && this.state.isStreaming) {
|
|
7801
|
+
await new Promise((resolve, reject) => {
|
|
7802
|
+
const signal = this.lifetimeAbort.signal;
|
|
7803
|
+
const finish = (error) => {
|
|
7804
|
+
globalThis.clearTimeout(timeout);
|
|
7805
|
+
unsubscribe();
|
|
7806
|
+
offEnd();
|
|
7807
|
+
offError();
|
|
7808
|
+
signal.removeEventListener("abort", onDispose);
|
|
7809
|
+
if (error) reject(error);
|
|
7810
|
+
else resolve();
|
|
7811
|
+
};
|
|
7812
|
+
const onDispose = () => finish(new AgentSessionError("\u4F1A\u8BDD\u5DF2\u5173\u95ED\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\u3002", "session_disposed"));
|
|
7813
|
+
const timeout = globalThis.setTimeout(() => {
|
|
7814
|
+
finish(new AgentSessionError("\u95EE\u9898\u8FD8\u5728\u51C6\u5907\u4E2D\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002", "question_not_ready"));
|
|
7815
|
+
}, 3e4);
|
|
7816
|
+
const unsubscribe = this.subscribe(() => {
|
|
7817
|
+
if (this.state.connection !== "connected") {
|
|
7818
|
+
finish(new AgentSessionError("\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\uFF0C\u8BF7\u91CD\u8FDE\u540E\u91CD\u8BD5\u3002", "connection_lost"));
|
|
7819
|
+
} else if (this.state.status !== "waiting_for_input") {
|
|
7820
|
+
finish(new AgentSessionError("\u95EE\u9898\u72B6\u6001\u5DF2\u6539\u53D8\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\uFF0C\u8BF7\u67E5\u770B\u5F53\u524D\u5BF9\u8BDD\u3002", "question_not_ready"));
|
|
7821
|
+
}
|
|
7822
|
+
});
|
|
7823
|
+
const offEnd = this.on("chatEnd", ({ status }) => {
|
|
7824
|
+
if (status === "paused") finish();
|
|
7825
|
+
else finish(new AgentSessionError("\u95EE\u9898\u5DF2\u7ED3\u675F\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\uFF0C\u8BF7\u67E5\u770B\u5F53\u524D\u5BF9\u8BDD\u3002", "question_not_ready"));
|
|
7826
|
+
});
|
|
7827
|
+
const offError = this.on("error", () => {
|
|
7828
|
+
finish(new AgentSessionError("\u95EE\u9898\u6267\u884C\u5931\u8D25\uFF0C\u56DE\u7B54\u672A\u53D1\u9001\uFF0C\u8BF7\u67E5\u770B\u5F53\u524D\u5BF9\u8BDD\u3002", "question_not_ready"));
|
|
7829
|
+
});
|
|
7830
|
+
signal.addEventListener("abort", onDispose, { once: true });
|
|
7831
|
+
});
|
|
7832
|
+
}
|
|
7833
|
+
if (this.state.isStreaming || this.state.status === "waiting_for_input") return;
|
|
7101
7834
|
if (Date.now() - this.recentChatEndAt > 3e3) return;
|
|
7102
7835
|
const deadline = Date.now() + 3e3;
|
|
7103
7836
|
while (Date.now() < deadline) {
|
|
@@ -7114,7 +7847,6 @@ var SessionHub = class {
|
|
|
7114
7847
|
client;
|
|
7115
7848
|
sessions = /* @__PURE__ */ new Map();
|
|
7116
7849
|
bootstrapPending = /* @__PURE__ */ new Map();
|
|
7117
|
-
/** 每个会话当前有多少方持有(connect 一次 +1,dispose 一次 -1)。 */
|
|
7118
7850
|
holdCounts = /* @__PURE__ */ new Map();
|
|
7119
7851
|
connection = "disconnected";
|
|
7120
7852
|
connectionListeners = /* @__PURE__ */ new Set();
|
|
@@ -7123,19 +7855,12 @@ var SessionHub = class {
|
|
|
7123
7855
|
authBusyReconnect = new AuthBusyReconnect();
|
|
7124
7856
|
hubEmitter = new Emitter();
|
|
7125
7857
|
options = { restoreHistoricalCommands: true };
|
|
7126
|
-
/** token 订阅偏好(第一方 Web 精简模式);null 表示不设置,订阅时不带字段。 */
|
|
7127
7858
|
streamTokens = null;
|
|
7128
|
-
/** 状态订阅(mode: "status")的持有计数。 */
|
|
7129
7859
|
statusWatchCounts = /* @__PURE__ */ new Map();
|
|
7130
7860
|
statusLogCursors = /* @__PURE__ */ new Map();
|
|
7131
7861
|
replayPlaybackIds = /* @__PURE__ */ new Map();
|
|
7132
|
-
/** 启动连接门控:扣住期间只登记「需要连接」,放开后连一次。 */
|
|
7133
7862
|
connectionHeld = false;
|
|
7134
7863
|
connectDeferred = false;
|
|
7135
|
-
/**
|
|
7136
|
-
* 宿主显式要过连接(ensureConnected / reconnect,例如只收产品事件的页面)。有会话、状态订阅或这个需求时,
|
|
7137
|
-
* 鉴权忙碌的临时拒绝都要按服务端建议重试,否则连接会一直停在断开,直到别的动作碰巧重连。
|
|
7138
|
-
*/
|
|
7139
7864
|
connectionDemanded = false;
|
|
7140
7865
|
constructor(client) {
|
|
7141
7866
|
this.client = client;
|
|
@@ -7148,10 +7873,6 @@ var SessionHub = class {
|
|
|
7148
7873
|
on(name, handler) {
|
|
7149
7874
|
return this.hubEmitter.on(name, handler);
|
|
7150
7875
|
}
|
|
7151
|
-
/**
|
|
7152
|
-
* @internal 第一方 Web 的精简模式传输优化:订阅时是否要 token 级事件。
|
|
7153
|
-
* 空闲会话立即重订阅,运行中的会话等这一轮结束。
|
|
7154
|
-
*/
|
|
7155
7876
|
setStreamTokens(enabled) {
|
|
7156
7877
|
if (this.streamTokens === enabled) return;
|
|
7157
7878
|
this.streamTokens = enabled;
|
|
@@ -7312,11 +8033,6 @@ var SessionHub = class {
|
|
|
7312
8033
|
this.forceRelease(session);
|
|
7313
8034
|
}
|
|
7314
8035
|
}
|
|
7315
|
-
/**
|
|
7316
|
-
* @internal 底层 socket 被换掉时由 BladeClient 调用(如 setBaseUrl)。
|
|
7317
|
-
* 事件监听器绑在旧 socket 实例上,换新实例后必须重绑,否则所有
|
|
7318
|
-
* turn:* / chat:* 事件都会静默丢弃。
|
|
7319
|
-
*/
|
|
7320
8036
|
_handleSocketReplaced() {
|
|
7321
8037
|
this.authBusyReconnect.cancel();
|
|
7322
8038
|
this.bound = false;
|
|
@@ -7345,14 +8061,9 @@ var SessionHub = class {
|
|
|
7345
8061
|
onDispose: (session) => this.release(session)
|
|
7346
8062
|
};
|
|
7347
8063
|
}
|
|
7348
|
-
/** 记一份持有。 */
|
|
7349
8064
|
hold(sessionId) {
|
|
7350
8065
|
this.holdCounts.set(sessionId, (this.holdCounts.get(sessionId) ?? 0) + 1);
|
|
7351
8066
|
}
|
|
7352
|
-
/**
|
|
7353
|
-
* 归还一份持有;还剩别的持有者时返回 false,让 AgentSession 保持可用。
|
|
7354
|
-
* 归零才退订房间并从路由表移除。
|
|
7355
|
-
*/
|
|
7356
8067
|
release(session) {
|
|
7357
8068
|
const remaining = (this.holdCounts.get(session.sessionId) ?? 0) - 1;
|
|
7358
8069
|
if (remaining > 0) {
|
|
@@ -7370,6 +8081,7 @@ var SessionHub = class {
|
|
|
7370
8081
|
this.client.socket().emit("session:unsubscribe", { session_id: session.sessionId });
|
|
7371
8082
|
if (this.statusWatchCounts.has(session.sessionId)) this.emitStatusSubscribe([session.sessionId]);
|
|
7372
8083
|
else this.statusLogCursors.delete(session.sessionId);
|
|
8084
|
+
if (this.client.options.anonymousSessionId && !this.needsConnection()) this.disconnect();
|
|
7373
8085
|
return true;
|
|
7374
8086
|
}
|
|
7375
8087
|
statusCursor(sessionId) {
|
|
@@ -7396,7 +8108,6 @@ var SessionHub = class {
|
|
|
7396
8108
|
sessions: sessionIds.map(payload)
|
|
7397
8109
|
});
|
|
7398
8110
|
}
|
|
7399
|
-
/** 不管还有几方持有都立即释放(启动失败、切换身份)。 */
|
|
7400
8111
|
forceRelease(session) {
|
|
7401
8112
|
this.holdCounts.delete(session.sessionId);
|
|
7402
8113
|
session.dispose();
|
|
@@ -7421,7 +8132,6 @@ var SessionHub = class {
|
|
|
7421
8132
|
}
|
|
7422
8133
|
}
|
|
7423
8134
|
}
|
|
7424
|
-
/** 事件带 session_id 时精确路由;缺省时按当前唯一活跃会话兜底。 */
|
|
7425
8135
|
route(sessionId) {
|
|
7426
8136
|
if (sessionId) {
|
|
7427
8137
|
const session = this.sessions.get(sessionId);
|
|
@@ -7490,6 +8200,7 @@ var SessionHub = class {
|
|
|
7490
8200
|
socket.on(
|
|
7491
8201
|
"turn:events",
|
|
7492
8202
|
(data, acknowledge) => {
|
|
8203
|
+
syncServerTime(this.client, data.server_time);
|
|
7493
8204
|
acknowledgeTurnEvents(acknowledge);
|
|
7494
8205
|
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
8206
|
const delivery = this.statusCursor(data.session_id).consume(data.events ?? []);
|
|
@@ -7691,20 +8402,29 @@ function createSocket(options) {
|
|
|
7691
8402
|
|
|
7692
8403
|
// src/blade-client.ts
|
|
7693
8404
|
var REFRESH_PATH = "/api/auth/refresh";
|
|
7694
|
-
var BladeClient = class {
|
|
8405
|
+
var BladeClient = class _BladeClient {
|
|
8406
|
+
anonymousClients = /* @__PURE__ */ new Map();
|
|
8407
|
+
toolProviders = /* @__PURE__ */ new Set();
|
|
7695
8408
|
refreshPromise = null;
|
|
8409
|
+
cookieLogoutPending = 0;
|
|
7696
8410
|
socketInstance = null;
|
|
7697
8411
|
socketReplacementListeners = /* @__PURE__ */ new Set();
|
|
7698
|
-
|
|
7699
|
-
runtimeToken = null;
|
|
8412
|
+
runtimeToken = void 0;
|
|
7700
8413
|
options;
|
|
8414
|
+
profile;
|
|
8415
|
+
packs;
|
|
8416
|
+
sandbox;
|
|
7701
8417
|
auth;
|
|
7702
8418
|
headless;
|
|
7703
8419
|
computers;
|
|
8420
|
+
/** 用户接进来的手机:账号级清单、会话启用、画面信令。 */
|
|
8421
|
+
phones;
|
|
8422
|
+
llm;
|
|
7704
8423
|
models;
|
|
7705
8424
|
sessions;
|
|
7706
8425
|
/** 按用户读取的插件目录与图标;没有会话时也能用。 */
|
|
7707
8426
|
plugins;
|
|
8427
|
+
connectors;
|
|
7708
8428
|
chatGroups;
|
|
7709
8429
|
/**
|
|
7710
8430
|
* 全站访问统计:匿名读写,不带 bearer 也不触发登录刷新。
|
|
@@ -7714,23 +8434,38 @@ var BladeClient = class {
|
|
|
7714
8434
|
/** 实时会话中枢:client.sessions.connect() 内部使用,一般不直接访问。 */
|
|
7715
8435
|
hub;
|
|
7716
8436
|
constructor(options) {
|
|
8437
|
+
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)) {
|
|
8438
|
+
throw new Error("\u533F\u540D\u4F1A\u8BDD ID \u5FC5\u987B\u662F UUID v4");
|
|
8439
|
+
}
|
|
7717
8440
|
this.options = {
|
|
7718
8441
|
...options,
|
|
7719
8442
|
baseUrl: normalizeBaseUrl(options.baseUrl)
|
|
7720
8443
|
};
|
|
8444
|
+
this.profile = new ProfileResource(this);
|
|
8445
|
+
this.packs = new PacksResource(this);
|
|
8446
|
+
this.sandbox = new SandboxResource(this);
|
|
7721
8447
|
this.auth = new AuthResource(this);
|
|
7722
8448
|
this.headless = new HeadlessResource(this);
|
|
7723
8449
|
this.computers = new ComputersResource(this);
|
|
8450
|
+
this.phones = new PhonesResource(this);
|
|
8451
|
+
this.llm = new LlmResource(this);
|
|
7724
8452
|
this.models = new ModelsResource(this);
|
|
7725
8453
|
this.sessions = new SessionsResource(this);
|
|
7726
8454
|
this.plugins = new PluginsResource(this);
|
|
8455
|
+
this.connectors = new ConnectorsResource(this);
|
|
7727
8456
|
this.chatGroups = new ChatGroupsResource(this);
|
|
7728
8457
|
this.siteVisits = new SiteVisitsResource(this);
|
|
7729
8458
|
this.hub = new SessionHub(this);
|
|
7730
|
-
if (this.options.token === void 0) {
|
|
7731
|
-
this.runtimeToken = readStoredToken(this.options.baseUrl);
|
|
8459
|
+
if (this.options.token === void 0 && !this.options.anonymousSessionId) {
|
|
8460
|
+
this.runtimeToken = readStoredToken(this.options.baseUrl) ?? void 0;
|
|
7732
8461
|
}
|
|
7733
8462
|
}
|
|
8463
|
+
/** Backend application tools, callable over an outbound WebSocket. */
|
|
8464
|
+
connectToolProvider(options) {
|
|
8465
|
+
const provider = new ToolProvider(this, options, () => this.toolProviders.delete(provider));
|
|
8466
|
+
this.toolProviders.add(provider);
|
|
8467
|
+
return provider;
|
|
8468
|
+
}
|
|
7734
8469
|
/**
|
|
7735
8470
|
* 弹窗授权登录:用户在弹出的授权页点击"许可授权"后自动取得 PAT,
|
|
7736
8471
|
* REST 与 Socket.IO 立即生效。只在浏览器可用。
|
|
@@ -7750,7 +8485,13 @@ var BladeClient = class {
|
|
|
7750
8485
|
const previousToken = this.resolveToken();
|
|
7751
8486
|
this.runtimeToken = token;
|
|
7752
8487
|
const nextToken = this.resolveToken();
|
|
8488
|
+
if (token === null) for (const provider of this.toolProviders) provider.dispose();
|
|
7753
8489
|
if (previousToken !== nextToken) {
|
|
8490
|
+
this.options.applicationTransport?.invalidate();
|
|
8491
|
+
for (const provider of this.toolProviders) {
|
|
8492
|
+
if (nextToken) provider.reconnect();
|
|
8493
|
+
else provider.dispose();
|
|
8494
|
+
}
|
|
7754
8495
|
this.hub.disposeAll();
|
|
7755
8496
|
}
|
|
7756
8497
|
writeStoredToken(this.options.baseUrl, token, this.options.tokenStorage ?? "local");
|
|
@@ -7783,12 +8524,27 @@ var BladeClient = class {
|
|
|
7783
8524
|
get token() {
|
|
7784
8525
|
return this.resolveRestToken();
|
|
7785
8526
|
}
|
|
8527
|
+
/** 获取只访问指定匿名会话的客户端;创建仍由已认证的原客户端完成。 */
|
|
8528
|
+
forAnonymousSession(sessionId) {
|
|
8529
|
+
let client = this.anonymousClients.get(sessionId);
|
|
8530
|
+
if (!client) {
|
|
8531
|
+
client = new _BladeClient({ baseUrl: this.options.baseUrl, anonymousSessionId: sessionId, fetchImpl: this.options.fetchImpl, commandTransport: this.options.commandTransport });
|
|
8532
|
+
this.anonymousClients.set(sessionId, client);
|
|
8533
|
+
}
|
|
8534
|
+
return client;
|
|
8535
|
+
}
|
|
7786
8536
|
setBaseUrl(baseUrl) {
|
|
7787
8537
|
const nextBaseUrl = normalizeBaseUrl(baseUrl);
|
|
7788
8538
|
if (nextBaseUrl === this.options.baseUrl) {
|
|
7789
8539
|
return;
|
|
7790
8540
|
}
|
|
8541
|
+
for (const provider of this.toolProviders) provider.dispose();
|
|
7791
8542
|
this.hub.disposeAll();
|
|
8543
|
+
for (const client of this.anonymousClients.values()) {
|
|
8544
|
+
client.hub.disposeAll();
|
|
8545
|
+
client.hub.disconnect();
|
|
8546
|
+
}
|
|
8547
|
+
this.anonymousClients.clear();
|
|
7792
8548
|
this.options.baseUrl = nextBaseUrl;
|
|
7793
8549
|
if (this.socketInstance) {
|
|
7794
8550
|
this.socketInstance.removeAllListeners();
|
|
@@ -7813,7 +8569,7 @@ var BladeClient = class {
|
|
|
7813
8569
|
}
|
|
7814
8570
|
socket() {
|
|
7815
8571
|
if (!this.socketInstance) {
|
|
7816
|
-
this.socketInstance = createSocket({
|
|
8572
|
+
this.socketInstance = this.options.applicationTransport?.socket() ?? createSocket({
|
|
7817
8573
|
baseUrl: this.options.baseUrl,
|
|
7818
8574
|
token: () => this.resolveSocketToken()
|
|
7819
8575
|
});
|
|
@@ -7828,7 +8584,10 @@ var BladeClient = class {
|
|
|
7828
8584
|
else resolve(ack ?? {});
|
|
7829
8585
|
});
|
|
7830
8586
|
});
|
|
7831
|
-
|
|
8587
|
+
const transport = this.options.commandTransport;
|
|
8588
|
+
if (!transport) return send();
|
|
8589
|
+
const handled = this.options.anonymousSessionId ? transport(event, payload, send, { anonymousSessionId: this.options.anonymousSessionId }) : transport(event, payload, send);
|
|
8590
|
+
return handled ?? send();
|
|
7832
8591
|
}
|
|
7833
8592
|
async json(method, path, body) {
|
|
7834
8593
|
const response = await this.fetch(method, path, {
|
|
@@ -7886,24 +8645,31 @@ var BladeClient = class {
|
|
|
7886
8645
|
}
|
|
7887
8646
|
async fetch(method, path, init = {}, isRetry = false) {
|
|
7888
8647
|
const url = this.buildUrl(path);
|
|
7889
|
-
const
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
7893
|
-
|
|
7894
|
-
|
|
7895
|
-
|
|
7896
|
-
|
|
7897
|
-
|
|
7898
|
-
|
|
7899
|
-
|
|
8648
|
+
const isLogout = method === "POST" && url.pathname === this.buildUrl("/api/auth/logout").pathname && this.isSameBackendUrl(url);
|
|
8649
|
+
if (isLogout) this.cookieLogoutPending += 1;
|
|
8650
|
+
try {
|
|
8651
|
+
if (isLogout) await this.refreshPromise;
|
|
8652
|
+
const response = await (this.options.fetchImpl ?? fetch)(url.toString(), {
|
|
8653
|
+
method,
|
|
8654
|
+
body: init.body,
|
|
8655
|
+
credentials: init.credentials ?? "include",
|
|
8656
|
+
headers: this.buildHeaders(url, init.headers),
|
|
8657
|
+
signal: init.signal
|
|
8658
|
+
});
|
|
8659
|
+
if (response.status === 401 && !isRetry && this.shouldRefreshFor401(url)) {
|
|
8660
|
+
const refreshed = await this.tryRefreshUnlessAborted(init.signal);
|
|
8661
|
+
if (refreshed) {
|
|
8662
|
+
return this.fetch(method, path, init, true);
|
|
8663
|
+
}
|
|
7900
8664
|
}
|
|
8665
|
+
if (init.expectOk !== false && !response.ok) {
|
|
8666
|
+
const detail = await extractErrorDetail(response);
|
|
8667
|
+
throw decorateAuthError(new BladeApiError(response, detail));
|
|
8668
|
+
}
|
|
8669
|
+
return response;
|
|
8670
|
+
} finally {
|
|
8671
|
+
if (isLogout) this.cookieLogoutPending -= 1;
|
|
7901
8672
|
}
|
|
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
8673
|
}
|
|
7908
8674
|
buildAuthedUrl(path) {
|
|
7909
8675
|
const url = buildBackendUrl(this.options.baseUrl, path);
|
|
@@ -7949,13 +8715,6 @@ var BladeClient = class {
|
|
|
7949
8715
|
hasExplicitBearerToken() {
|
|
7950
8716
|
return Boolean(this.resolveRestToken());
|
|
7951
8717
|
}
|
|
7952
|
-
/**
|
|
7953
|
-
* 等一次令牌刷新,但调用方中止请求时不再等下去。
|
|
7954
|
-
*
|
|
7955
|
-
* 刷新本身是共享的(`refreshPromise`,别的请求也在等它),这里只是让这次已被取消的
|
|
7956
|
-
* 请求尽早结束——否则它会一直挂在调用方(定位)的串行队列里,用户改选的新目标要等到
|
|
7957
|
-
* 刷新结束才轮得到。
|
|
7958
|
-
*/
|
|
7959
8718
|
async tryRefreshUnlessAborted(signal) {
|
|
7960
8719
|
if (!signal) return this.tryRefresh();
|
|
7961
8720
|
if (signal.aborted) throw new DOMException("The operation was aborted.", "AbortError");
|
|
@@ -7971,6 +8730,7 @@ var BladeClient = class {
|
|
|
7971
8730
|
}
|
|
7972
8731
|
}
|
|
7973
8732
|
async tryRefresh() {
|
|
8733
|
+
if (this.options.anonymousSessionId || this.cookieLogoutPending > 0) return false;
|
|
7974
8734
|
if (this.refreshPromise) {
|
|
7975
8735
|
return this.refreshPromise;
|
|
7976
8736
|
}
|
|
@@ -7981,7 +8741,6 @@ var BladeClient = class {
|
|
|
7981
8741
|
{
|
|
7982
8742
|
method: "POST",
|
|
7983
8743
|
credentials: "include",
|
|
7984
|
-
// Refresh remains cookie-only; do not attach the REST bearer.
|
|
7985
8744
|
headers: { "X-Blade-Client": `${SDK_NAME}/${SDK_VERSION}` }
|
|
7986
8745
|
}
|
|
7987
8746
|
);
|
|
@@ -8005,14 +8764,16 @@ var BladeClient = class {
|
|
|
8005
8764
|
return this.resolveRestToken();
|
|
8006
8765
|
}
|
|
8007
8766
|
resolveRestToken() {
|
|
8767
|
+
if (this.options.anonymousSessionId) return `ba-anonymous-${this.options.anonymousSessionId}`;
|
|
8008
8768
|
return this.resolveToken();
|
|
8009
8769
|
}
|
|
8010
8770
|
resolveSocketToken() {
|
|
8011
|
-
if (this.
|
|
8771
|
+
if (this.options.anonymousSessionId) return `ba-anonymous-${this.options.anonymousSessionId}`;
|
|
8772
|
+
if (this.runtimeToken !== void 0) return this.runtimeToken;
|
|
8012
8773
|
return resolveTokenOption(this.options.socketToken ?? this.options.token);
|
|
8013
8774
|
}
|
|
8014
8775
|
resolveToken() {
|
|
8015
|
-
if (this.runtimeToken) return this.runtimeToken;
|
|
8776
|
+
if (this.runtimeToken !== void 0) return this.runtimeToken;
|
|
8016
8777
|
return resolveTokenOption(this.options.token);
|
|
8017
8778
|
}
|
|
8018
8779
|
formDataWithUploadProgress(method, path, form, options, isRetry = false) {
|
|
@@ -8109,12 +8870,738 @@ function parseXhrHeaders(rawHeaders) {
|
|
|
8109
8870
|
return headers;
|
|
8110
8871
|
}
|
|
8111
8872
|
|
|
8873
|
+
// src/application-client.ts
|
|
8874
|
+
var Events = class {
|
|
8875
|
+
listeners = /* @__PURE__ */ new Map();
|
|
8876
|
+
on(name, listener) {
|
|
8877
|
+
let set = this.listeners.get(name);
|
|
8878
|
+
if (!set) {
|
|
8879
|
+
set = /* @__PURE__ */ new Set();
|
|
8880
|
+
this.listeners.set(name, set);
|
|
8881
|
+
}
|
|
8882
|
+
set.add(listener);
|
|
8883
|
+
return this;
|
|
8884
|
+
}
|
|
8885
|
+
off(name, listener) {
|
|
8886
|
+
if (listener) this.listeners.get(name)?.delete(listener);
|
|
8887
|
+
else this.listeners.delete(name);
|
|
8888
|
+
return this;
|
|
8889
|
+
}
|
|
8890
|
+
once(name, listener) {
|
|
8891
|
+
const wrapped = (...args) => {
|
|
8892
|
+
this.off(name, wrapped);
|
|
8893
|
+
listener(...args);
|
|
8894
|
+
};
|
|
8895
|
+
return this.on(name, wrapped);
|
|
8896
|
+
}
|
|
8897
|
+
fire(name, ...args) {
|
|
8898
|
+
for (const listener of [...this.listeners.get(name) ?? []]) {
|
|
8899
|
+
try {
|
|
8900
|
+
listener(...args);
|
|
8901
|
+
} catch (error) {
|
|
8902
|
+
console.warn(
|
|
8903
|
+
`[agent-client] "${name}" application handler failed:`,
|
|
8904
|
+
error
|
|
8905
|
+
);
|
|
8906
|
+
}
|
|
8907
|
+
}
|
|
8908
|
+
}
|
|
8909
|
+
removeAllListeners() {
|
|
8910
|
+
this.listeners.clear();
|
|
8911
|
+
return this;
|
|
8912
|
+
}
|
|
8913
|
+
};
|
|
8914
|
+
function encode(input) {
|
|
8915
|
+
const attachments = [];
|
|
8916
|
+
const walk = (value) => {
|
|
8917
|
+
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
8918
|
+
const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
8919
|
+
let text = "";
|
|
8920
|
+
for (let offset = 0; offset < bytes.length; offset += 8192)
|
|
8921
|
+
text += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
|
8922
|
+
attachments.push(btoa(text));
|
|
8923
|
+
return ["bytes", attachments.length - 1];
|
|
8924
|
+
}
|
|
8925
|
+
if (Array.isArray(value)) return ["list", value.map(walk)];
|
|
8926
|
+
if (value && typeof value === "object")
|
|
8927
|
+
return [
|
|
8928
|
+
"dict",
|
|
8929
|
+
Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => [key, walk(item)])
|
|
8930
|
+
];
|
|
8931
|
+
return ["value", value ?? null];
|
|
8932
|
+
};
|
|
8933
|
+
return { value: walk(input), attachments };
|
|
8934
|
+
}
|
|
8935
|
+
function decode(wire) {
|
|
8936
|
+
const walk = (node) => {
|
|
8937
|
+
if (!Array.isArray(node) || node.length !== 2)
|
|
8938
|
+
throw new Error("Invalid application value");
|
|
8939
|
+
if (node[0] === "value") return node[1];
|
|
8940
|
+
if (node[0] === "bytes")
|
|
8941
|
+
return Uint8Array.from(
|
|
8942
|
+
atob(wire.attachments[node[1]]),
|
|
8943
|
+
(c) => c.charCodeAt(0)
|
|
8944
|
+
);
|
|
8945
|
+
if (node[0] === "list") return node[1].map(walk);
|
|
8946
|
+
if (node[0] === "dict")
|
|
8947
|
+
return Object.fromEntries(
|
|
8948
|
+
node[1].map(([key, value2]) => [key, walk(value2)])
|
|
8949
|
+
);
|
|
8950
|
+
throw new Error("Invalid application value");
|
|
8951
|
+
};
|
|
8952
|
+
const value = walk(wire.value);
|
|
8953
|
+
if (!Array.isArray(value)) throw new Error("Invalid application event");
|
|
8954
|
+
return value;
|
|
8955
|
+
}
|
|
8956
|
+
var BladeApplicationClient = class {
|
|
8957
|
+
constructor(options) {
|
|
8958
|
+
this.options = options;
|
|
8959
|
+
this.channels = [
|
|
8960
|
+
new ApplicationChannel(this.options.baseUrl, this.applicationId),
|
|
8961
|
+
new ApplicationChannel(this.options.baseUrl, this.applicationId)
|
|
8962
|
+
];
|
|
8963
|
+
}
|
|
8964
|
+
options;
|
|
8965
|
+
channels;
|
|
8966
|
+
clients = /* @__PURE__ */ new Map();
|
|
8967
|
+
applicationId = crypto.randomUUID();
|
|
8968
|
+
forUser(userId, options) {
|
|
8969
|
+
const saved = this.clients.get(userId);
|
|
8970
|
+
if (saved) return saved;
|
|
8971
|
+
let hash = 0;
|
|
8972
|
+
for (const character of userId)
|
|
8973
|
+
hash = hash * 31 + character.charCodeAt(0) | 0;
|
|
8974
|
+
const channel = this.channels[(hash >>> 0) % this.channels.length];
|
|
8975
|
+
const user = new ApplicationUser(channel, userId, () => client);
|
|
8976
|
+
const client = new BladeClient({
|
|
8977
|
+
...this.options,
|
|
8978
|
+
...options,
|
|
8979
|
+
tokenStorage: options.tokenStorage ?? "memory",
|
|
8980
|
+
applicationTransport: user
|
|
8981
|
+
});
|
|
8982
|
+
this.clients.set(userId, client);
|
|
8983
|
+
return client;
|
|
8984
|
+
}
|
|
8985
|
+
get connectionCount() {
|
|
8986
|
+
return this.channels.filter((channel) => channel.isConnected).length;
|
|
8987
|
+
}
|
|
8988
|
+
dispose() {
|
|
8989
|
+
for (const client of this.clients.values()) {
|
|
8990
|
+
client.hub.disposeAll();
|
|
8991
|
+
client.logoutToken();
|
|
8992
|
+
}
|
|
8993
|
+
for (const channel of this.channels) channel.dispose();
|
|
8994
|
+
this.clients.clear();
|
|
8995
|
+
}
|
|
8996
|
+
};
|
|
8997
|
+
var ApplicationChannel = class {
|
|
8998
|
+
constructor(baseUrl, applicationId) {
|
|
8999
|
+
this.baseUrl = baseUrl;
|
|
9000
|
+
this.applicationId = applicationId;
|
|
9001
|
+
}
|
|
9002
|
+
baseUrl;
|
|
9003
|
+
applicationId;
|
|
9004
|
+
socket;
|
|
9005
|
+
opening;
|
|
9006
|
+
timer;
|
|
9007
|
+
stopped = false;
|
|
9008
|
+
attempts = 0;
|
|
9009
|
+
controlCount = 0;
|
|
9010
|
+
controlWaiters = [];
|
|
9011
|
+
async controlSlot() {
|
|
9012
|
+
if (this.controlCount >= 16)
|
|
9013
|
+
await new Promise((resolve) => this.controlWaiters.push(resolve));
|
|
9014
|
+
else this.controlCount++;
|
|
9015
|
+
return () => {
|
|
9016
|
+
const next = this.controlWaiters.shift();
|
|
9017
|
+
if (next) next();
|
|
9018
|
+
else this.controlCount--;
|
|
9019
|
+
};
|
|
9020
|
+
}
|
|
9021
|
+
pending = /* @__PURE__ */ new Map();
|
|
9022
|
+
users = /* @__PURE__ */ new Map();
|
|
9023
|
+
get isConnected() {
|
|
9024
|
+
return this.socket?.readyState === WebSocket.OPEN;
|
|
9025
|
+
}
|
|
9026
|
+
ensure() {
|
|
9027
|
+
if (this.stopped)
|
|
9028
|
+
return Promise.reject(new Error("Application client disposed"));
|
|
9029
|
+
if (this.isConnected) return Promise.resolve();
|
|
9030
|
+
if (!this.opening) {
|
|
9031
|
+
const work = this.open();
|
|
9032
|
+
this.opening = work;
|
|
9033
|
+
void work.finally(() => {
|
|
9034
|
+
if (this.opening === work) this.opening = void 0;
|
|
9035
|
+
}).catch(() => {
|
|
9036
|
+
});
|
|
9037
|
+
}
|
|
9038
|
+
return this.opening;
|
|
9039
|
+
}
|
|
9040
|
+
async open() {
|
|
9041
|
+
clearTimeout(this.timer);
|
|
9042
|
+
this.timer = void 0;
|
|
9043
|
+
const candidates = [...this.users.values()].filter(
|
|
9044
|
+
(user2) => user2.demanded && user2.client().token
|
|
9045
|
+
);
|
|
9046
|
+
const user = candidates[this.attempts % candidates.length];
|
|
9047
|
+
let ticket;
|
|
9048
|
+
try {
|
|
9049
|
+
if (!user)
|
|
9050
|
+
throw new Error(
|
|
9051
|
+
"Application channel requires a demanded user credential"
|
|
9052
|
+
);
|
|
9053
|
+
ticket = await user.client().jsonFromInit("/api/app-channels", {
|
|
9054
|
+
method: "POST",
|
|
9055
|
+
body: JSON.stringify({ application_id: this.applicationId }),
|
|
9056
|
+
signal: AbortSignal.timeout(1e4)
|
|
9057
|
+
});
|
|
9058
|
+
} catch (error) {
|
|
9059
|
+
this.schedule();
|
|
9060
|
+
throw error;
|
|
9061
|
+
}
|
|
9062
|
+
if (this.stopped) throw new Error("Application client disposed");
|
|
9063
|
+
const endpoint = buildBackendUrl(this.baseUrl, "/api/app-channels/connect");
|
|
9064
|
+
endpoint.protocol = endpoint.protocol === "https:" ? "wss:" : "ws:";
|
|
9065
|
+
const socket = new WebSocket(endpoint, [
|
|
9066
|
+
"blade-application",
|
|
9067
|
+
`blade-channel.${ticket.token}`
|
|
9068
|
+
]);
|
|
9069
|
+
this.socket = socket;
|
|
9070
|
+
await new Promise((resolve, reject) => {
|
|
9071
|
+
const timeout = setTimeout(() => {
|
|
9072
|
+
reject(new Error("Application connection timed out"));
|
|
9073
|
+
socket.close();
|
|
9074
|
+
}, 15e3);
|
|
9075
|
+
socket.addEventListener("open", () => {
|
|
9076
|
+
if (this.socket !== socket || this.stopped) return;
|
|
9077
|
+
clearTimeout(timeout);
|
|
9078
|
+
this.attempts = 0;
|
|
9079
|
+
resolve();
|
|
9080
|
+
for (const user2 of this.users.values()) user2.restore();
|
|
9081
|
+
});
|
|
9082
|
+
socket.addEventListener("message", (event) => {
|
|
9083
|
+
if (this.socket !== socket || typeof event.data !== "string") return;
|
|
9084
|
+
try {
|
|
9085
|
+
this.receive(JSON.parse(event.data));
|
|
9086
|
+
} catch {
|
|
9087
|
+
socket.close();
|
|
9088
|
+
}
|
|
9089
|
+
});
|
|
9090
|
+
socket.addEventListener("error", () => {
|
|
9091
|
+
clearTimeout(timeout);
|
|
9092
|
+
reject(new Error("Application connection failed"));
|
|
9093
|
+
});
|
|
9094
|
+
socket.addEventListener("close", () => {
|
|
9095
|
+
clearTimeout(timeout);
|
|
9096
|
+
reject(new Error("Application connection closed"));
|
|
9097
|
+
if (this.socket !== socket) return;
|
|
9098
|
+
this.socket = void 0;
|
|
9099
|
+
for (const request of this.pending.values()) {
|
|
9100
|
+
clearTimeout(request.timer);
|
|
9101
|
+
request.reject(new Error("Application connection closed"));
|
|
9102
|
+
}
|
|
9103
|
+
this.pending.clear();
|
|
9104
|
+
for (const user2 of this.users.values()) user2.lost();
|
|
9105
|
+
this.schedule();
|
|
9106
|
+
});
|
|
9107
|
+
});
|
|
9108
|
+
}
|
|
9109
|
+
schedule() {
|
|
9110
|
+
if (this.stopped || this.timer || ![...this.users.values()].some((user) => user.demanded))
|
|
9111
|
+
return;
|
|
9112
|
+
this.timer = setTimeout(
|
|
9113
|
+
() => {
|
|
9114
|
+
this.timer = void 0;
|
|
9115
|
+
void this.ensure().catch(() => this.schedule());
|
|
9116
|
+
},
|
|
9117
|
+
Math.min(1e4, 500 * 2 ** Math.min(this.attempts++, 5))
|
|
9118
|
+
);
|
|
9119
|
+
}
|
|
9120
|
+
receive(frame) {
|
|
9121
|
+
if (frame.id) {
|
|
9122
|
+
const request = this.pending.get(frame.id);
|
|
9123
|
+
if (!request || request.user !== frame.user) return;
|
|
9124
|
+
this.pending.delete(frame.id);
|
|
9125
|
+
clearTimeout(request.timer);
|
|
9126
|
+
if (frame.error)
|
|
9127
|
+
request.reject(
|
|
9128
|
+
Object.assign(new Error(frame.error.message), {
|
|
9129
|
+
code: frame.error.code,
|
|
9130
|
+
data: {
|
|
9131
|
+
code: frame.error.code,
|
|
9132
|
+
status: frame.error.code === "auth_busy" ? 429 : 401,
|
|
9133
|
+
retry_after: 1
|
|
9134
|
+
}
|
|
9135
|
+
})
|
|
9136
|
+
);
|
|
9137
|
+
else request.resolve(frame.result);
|
|
9138
|
+
return;
|
|
9139
|
+
}
|
|
9140
|
+
const user = frame.user && this.users.get(frame.user);
|
|
9141
|
+
if (user) user.receive(frame);
|
|
9142
|
+
}
|
|
9143
|
+
async request(user, method, params, timeoutMs = 3e4) {
|
|
9144
|
+
const release = method === "socket/event" ? () => {
|
|
9145
|
+
} : await this.controlSlot();
|
|
9146
|
+
try {
|
|
9147
|
+
return await new Promise((resolve, reject) => {
|
|
9148
|
+
const id = crypto.randomUUID();
|
|
9149
|
+
const timer = setTimeout(() => {
|
|
9150
|
+
this.pending.delete(id);
|
|
9151
|
+
reject(new Error("Application request timed out"));
|
|
9152
|
+
}, timeoutMs);
|
|
9153
|
+
this.pending.set(id, { user, resolve, reject, timer });
|
|
9154
|
+
try {
|
|
9155
|
+
this.send({ id, user, method, params });
|
|
9156
|
+
} catch (error) {
|
|
9157
|
+
clearTimeout(timer);
|
|
9158
|
+
this.pending.delete(id);
|
|
9159
|
+
reject(error);
|
|
9160
|
+
}
|
|
9161
|
+
});
|
|
9162
|
+
} finally {
|
|
9163
|
+
release();
|
|
9164
|
+
}
|
|
9165
|
+
}
|
|
9166
|
+
send(frame) {
|
|
9167
|
+
if (!this.isConnected || !this.socket)
|
|
9168
|
+
throw new Error("Application connection unavailable");
|
|
9169
|
+
this.socket.send(JSON.stringify(frame));
|
|
9170
|
+
}
|
|
9171
|
+
dispose() {
|
|
9172
|
+
this.stopped = true;
|
|
9173
|
+
clearTimeout(this.timer);
|
|
9174
|
+
this.timer = void 0;
|
|
9175
|
+
for (const user of this.users.values()) user.lost();
|
|
9176
|
+
this.socket?.close();
|
|
9177
|
+
for (const request of this.pending.values()) {
|
|
9178
|
+
clearTimeout(request.timer);
|
|
9179
|
+
request.reject(new Error("Application client disposed"));
|
|
9180
|
+
}
|
|
9181
|
+
this.pending.clear();
|
|
9182
|
+
this.users.clear();
|
|
9183
|
+
}
|
|
9184
|
+
};
|
|
9185
|
+
var ApplicationUser = class {
|
|
9186
|
+
constructor(channel, userId, client) {
|
|
9187
|
+
this.channel = channel;
|
|
9188
|
+
this.userId = userId;
|
|
9189
|
+
this.client = client;
|
|
9190
|
+
this.events = new ApplicationSocket(this);
|
|
9191
|
+
channel.users.set(this.key, this);
|
|
9192
|
+
}
|
|
9193
|
+
channel;
|
|
9194
|
+
userId;
|
|
9195
|
+
client;
|
|
9196
|
+
key = crypto.randomUUID();
|
|
9197
|
+
events;
|
|
9198
|
+
providers = /* @__PURE__ */ new Map();
|
|
9199
|
+
binding;
|
|
9200
|
+
bindingToken;
|
|
9201
|
+
get demanded() {
|
|
9202
|
+
return this.events.active || this.providers.size > 0;
|
|
9203
|
+
}
|
|
9204
|
+
async bind() {
|
|
9205
|
+
await this.channel.ensure();
|
|
9206
|
+
if (!this.demanded) throw new Error("Application user no longer needed");
|
|
9207
|
+
const token = this.client().token;
|
|
9208
|
+
if (!token) throw new Error("Application user requires a token");
|
|
9209
|
+
if (!this.binding || this.bindingToken !== token) {
|
|
9210
|
+
this.bindingToken = token;
|
|
9211
|
+
const work = this.channel.request(this.key, "user/bind", { user_id: this.userId, token }).then((result) => {
|
|
9212
|
+
if (result.user_id !== this.userId)
|
|
9213
|
+
throw new Error("Application user identity mismatch");
|
|
9214
|
+
if (!this.demanded) {
|
|
9215
|
+
this.binding = void 0;
|
|
9216
|
+
this.bindingToken = void 0;
|
|
9217
|
+
void this.channel.request(this.key, "user/unbind", {}).catch(() => {
|
|
9218
|
+
});
|
|
9219
|
+
throw new Error("Application user no longer needed");
|
|
9220
|
+
}
|
|
9221
|
+
});
|
|
9222
|
+
this.binding = work;
|
|
9223
|
+
void work.catch(() => {
|
|
9224
|
+
if (this.binding === work) this.binding = void 0;
|
|
9225
|
+
});
|
|
9226
|
+
}
|
|
9227
|
+
return this.binding;
|
|
9228
|
+
}
|
|
9229
|
+
socket() {
|
|
9230
|
+
return this.events;
|
|
9231
|
+
}
|
|
9232
|
+
provider() {
|
|
9233
|
+
const provider = new ApplicationProviderSocket(this);
|
|
9234
|
+
this.providers.set(provider.handle, provider);
|
|
9235
|
+
provider.open();
|
|
9236
|
+
return provider;
|
|
9237
|
+
}
|
|
9238
|
+
invalidate() {
|
|
9239
|
+
this.binding = void 0;
|
|
9240
|
+
this.bindingToken = void 0;
|
|
9241
|
+
if (!this.client().token && this.channel.isConnected)
|
|
9242
|
+
void this.channel.request(this.key, "user/unbind", {}).catch(() => {
|
|
9243
|
+
});
|
|
9244
|
+
}
|
|
9245
|
+
restore() {
|
|
9246
|
+
if (this.events.active) this.events.connect();
|
|
9247
|
+
}
|
|
9248
|
+
lost() {
|
|
9249
|
+
this.invalidate();
|
|
9250
|
+
this.events.lost();
|
|
9251
|
+
for (const provider of [...this.providers.values()]) provider.closeLocal();
|
|
9252
|
+
}
|
|
9253
|
+
receive(frame) {
|
|
9254
|
+
if (frame.method === "socket/closed") {
|
|
9255
|
+
this.events.lost();
|
|
9256
|
+
if (this.events.active) this.events.connect();
|
|
9257
|
+
return;
|
|
9258
|
+
}
|
|
9259
|
+
if (frame.method === "tool/closed") {
|
|
9260
|
+
this.providers.get(frame.handle ?? "")?.closeLocal();
|
|
9261
|
+
return;
|
|
9262
|
+
}
|
|
9263
|
+
if (frame.method === "tool/message") {
|
|
9264
|
+
this.providers.get(frame.handle ?? "")?.message(frame.message);
|
|
9265
|
+
return;
|
|
9266
|
+
}
|
|
9267
|
+
if (frame.event && frame.args) {
|
|
9268
|
+
const args = decode(frame.args);
|
|
9269
|
+
if (frame.ack_id)
|
|
9270
|
+
args.push(
|
|
9271
|
+
(...values) => this.channel.send({
|
|
9272
|
+
method: "event/ack",
|
|
9273
|
+
user: this.key,
|
|
9274
|
+
ack_id: frame.ack_id,
|
|
9275
|
+
params: encode(values)
|
|
9276
|
+
})
|
|
9277
|
+
);
|
|
9278
|
+
this.events.fire(frame.event, ...args);
|
|
9279
|
+
}
|
|
9280
|
+
}
|
|
9281
|
+
};
|
|
9282
|
+
var ApplicationSocket = class extends Events {
|
|
9283
|
+
constructor(user) {
|
|
9284
|
+
super();
|
|
9285
|
+
this.user = user;
|
|
9286
|
+
}
|
|
9287
|
+
user;
|
|
9288
|
+
connected = false;
|
|
9289
|
+
active = false;
|
|
9290
|
+
io = new Events();
|
|
9291
|
+
connecting;
|
|
9292
|
+
generation = 0;
|
|
9293
|
+
connect() {
|
|
9294
|
+
this.active = true;
|
|
9295
|
+
if (this.connected || this.connecting) return this;
|
|
9296
|
+
const generation = ++this.generation;
|
|
9297
|
+
const work = this.user.bind().then(() => {
|
|
9298
|
+
if (generation !== this.generation || !this.active) return;
|
|
9299
|
+
return this.user.channel.request(this.user.key, "socket/connect", {});
|
|
9300
|
+
}).then(() => {
|
|
9301
|
+
if (generation !== this.generation || !this.active) return;
|
|
9302
|
+
this.connected = true;
|
|
9303
|
+
this.fire("connect");
|
|
9304
|
+
}).catch((error) => {
|
|
9305
|
+
if (generation === this.generation && this.active) {
|
|
9306
|
+
if (error?.code === "auth_busy" || error?.code === "unauthorized")
|
|
9307
|
+
this.active = false;
|
|
9308
|
+
this.fire("connect_error", error);
|
|
9309
|
+
}
|
|
9310
|
+
}).finally(() => {
|
|
9311
|
+
if (this.connecting === work) this.connecting = void 0;
|
|
9312
|
+
});
|
|
9313
|
+
this.connecting = work;
|
|
9314
|
+
return this;
|
|
9315
|
+
}
|
|
9316
|
+
disconnect() {
|
|
9317
|
+
this.active = false;
|
|
9318
|
+
this.lost();
|
|
9319
|
+
if (this.user.channel.isConnected)
|
|
9320
|
+
void this.user.channel.request(this.user.key, "socket/disconnect", {}).catch(() => {
|
|
9321
|
+
});
|
|
9322
|
+
return this;
|
|
9323
|
+
}
|
|
9324
|
+
lost() {
|
|
9325
|
+
const wasConnected = this.connected;
|
|
9326
|
+
this.connected = false;
|
|
9327
|
+
this.connecting = void 0;
|
|
9328
|
+
this.generation++;
|
|
9329
|
+
if (wasConnected) this.fire("disconnect", "transport close");
|
|
9330
|
+
}
|
|
9331
|
+
emit(event, ...args) {
|
|
9332
|
+
this.send(event, args);
|
|
9333
|
+
return this;
|
|
9334
|
+
}
|
|
9335
|
+
timeout(timeoutMs) {
|
|
9336
|
+
return {
|
|
9337
|
+
emit: (event, ...args) => {
|
|
9338
|
+
this.send(event, args, timeoutMs);
|
|
9339
|
+
return this;
|
|
9340
|
+
}
|
|
9341
|
+
};
|
|
9342
|
+
}
|
|
9343
|
+
send(event, values, timeoutMs) {
|
|
9344
|
+
const args = [...values];
|
|
9345
|
+
const callback = typeof args.at(-1) === "function" ? args.pop() : void 0;
|
|
9346
|
+
const generation = this.generation;
|
|
9347
|
+
const deadline = Date.now() + (timeoutMs ?? 3e4);
|
|
9348
|
+
const work = (async () => {
|
|
9349
|
+
if (!this.active) throw new Error("Application user disconnected");
|
|
9350
|
+
if (!this.connected) await this.connecting;
|
|
9351
|
+
if (!this.connected || this.generation !== generation)
|
|
9352
|
+
throw new Error("Application user disconnected");
|
|
9353
|
+
const remaining = deadline - Date.now();
|
|
9354
|
+
if (remaining <= 0) throw new Error("Application request timed out");
|
|
9355
|
+
const params = { event, args: encode(args) };
|
|
9356
|
+
if (!callback) {
|
|
9357
|
+
this.user.channel.send({
|
|
9358
|
+
user: this.user.key,
|
|
9359
|
+
method: "socket/event",
|
|
9360
|
+
params
|
|
9361
|
+
});
|
|
9362
|
+
return;
|
|
9363
|
+
}
|
|
9364
|
+
return this.user.channel.request(
|
|
9365
|
+
this.user.key,
|
|
9366
|
+
"socket/event",
|
|
9367
|
+
params,
|
|
9368
|
+
remaining
|
|
9369
|
+
);
|
|
9370
|
+
})();
|
|
9371
|
+
void work.then(
|
|
9372
|
+
(result) => {
|
|
9373
|
+
if (!callback) return;
|
|
9374
|
+
const values2 = decode(result);
|
|
9375
|
+
if (timeoutMs !== void 0) callback?.(null, ...values2);
|
|
9376
|
+
else callback?.(...values2);
|
|
9377
|
+
},
|
|
9378
|
+
(error) => {
|
|
9379
|
+
if (timeoutMs !== void 0) callback?.(error);
|
|
9380
|
+
else if (callback) callback(error);
|
|
9381
|
+
}
|
|
9382
|
+
);
|
|
9383
|
+
}
|
|
9384
|
+
};
|
|
9385
|
+
var ApplicationProviderSocket = class extends Events {
|
|
9386
|
+
constructor(user) {
|
|
9387
|
+
super();
|
|
9388
|
+
this.user = user;
|
|
9389
|
+
}
|
|
9390
|
+
user;
|
|
9391
|
+
handle = crypto.randomUUID();
|
|
9392
|
+
readyState = WebSocket.CONNECTING;
|
|
9393
|
+
addEventListener(name, listener) {
|
|
9394
|
+
this.on(name, listener);
|
|
9395
|
+
}
|
|
9396
|
+
open() {
|
|
9397
|
+
void this.user.bind().then(
|
|
9398
|
+
() => {
|
|
9399
|
+
if (this.readyState !== WebSocket.CONNECTING) return;
|
|
9400
|
+
this.readyState = WebSocket.OPEN;
|
|
9401
|
+
this.fire("open", new Event("open"));
|
|
9402
|
+
},
|
|
9403
|
+
() => {
|
|
9404
|
+
if (this.readyState !== WebSocket.CLOSED) {
|
|
9405
|
+
this.fire("error", new Event("error"));
|
|
9406
|
+
this.closeLocal();
|
|
9407
|
+
}
|
|
9408
|
+
}
|
|
9409
|
+
);
|
|
9410
|
+
}
|
|
9411
|
+
send(text) {
|
|
9412
|
+
if (this.readyState !== WebSocket.OPEN)
|
|
9413
|
+
throw new Error("Application provider closed");
|
|
9414
|
+
const message = JSON.parse(text);
|
|
9415
|
+
if (message.method === "provider/register") {
|
|
9416
|
+
void this.user.channel.request(this.user.key, "tool/register", {
|
|
9417
|
+
...message.params,
|
|
9418
|
+
handle: this.handle
|
|
9419
|
+
}).then(
|
|
9420
|
+
(result) => this.message({ jsonrpc: "2.0", id: message.id, result }),
|
|
9421
|
+
(error) => this.message({
|
|
9422
|
+
jsonrpc: "2.0",
|
|
9423
|
+
id: message.id,
|
|
9424
|
+
error: { code: -32001, message: error.message }
|
|
9425
|
+
})
|
|
9426
|
+
);
|
|
9427
|
+
} else
|
|
9428
|
+
this.user.channel.send({
|
|
9429
|
+
method: "tool/result",
|
|
9430
|
+
user: this.user.key,
|
|
9431
|
+
handle: this.handle,
|
|
9432
|
+
message
|
|
9433
|
+
});
|
|
9434
|
+
}
|
|
9435
|
+
message(message) {
|
|
9436
|
+
if (this.readyState === WebSocket.OPEN)
|
|
9437
|
+
this.fire(
|
|
9438
|
+
"message",
|
|
9439
|
+
new MessageEvent("message", { data: JSON.stringify(message) })
|
|
9440
|
+
);
|
|
9441
|
+
}
|
|
9442
|
+
close() {
|
|
9443
|
+
if (this.readyState === WebSocket.CLOSED) return;
|
|
9444
|
+
if (this.user.channel.isConnected)
|
|
9445
|
+
void this.user.channel.request(this.user.key, "tool/unregister", { handle: this.handle }).catch(() => {
|
|
9446
|
+
});
|
|
9447
|
+
this.closeLocal();
|
|
9448
|
+
}
|
|
9449
|
+
closeLocal() {
|
|
9450
|
+
if (this.readyState === WebSocket.CLOSED) return;
|
|
9451
|
+
this.readyState = WebSocket.CLOSED;
|
|
9452
|
+
this.user.providers.delete(this.handle);
|
|
9453
|
+
this.fire("close", new Event("close"));
|
|
9454
|
+
this.removeAllListeners();
|
|
9455
|
+
}
|
|
9456
|
+
};
|
|
9457
|
+
|
|
9458
|
+
// src/schemas/ask-user-question.ts
|
|
9459
|
+
function parseAskUserQuestion(toolResult) {
|
|
9460
|
+
if (!toolResult) return null;
|
|
9461
|
+
try {
|
|
9462
|
+
const parsed = JSON.parse(toolResult);
|
|
9463
|
+
let questions = parsed?.questions;
|
|
9464
|
+
if (typeof questions === "string") {
|
|
9465
|
+
try {
|
|
9466
|
+
questions = JSON.parse(questions);
|
|
9467
|
+
} catch {
|
|
9468
|
+
return null;
|
|
9469
|
+
}
|
|
9470
|
+
}
|
|
9471
|
+
if (Array.isArray(questions) && questions.length > 0) {
|
|
9472
|
+
const normalized = questions.map(normalizeQuestionItem);
|
|
9473
|
+
if (normalized.every((question) => question !== null)) {
|
|
9474
|
+
return { ...parsed, questions: normalized };
|
|
9475
|
+
}
|
|
9476
|
+
}
|
|
9477
|
+
} catch {
|
|
9478
|
+
}
|
|
9479
|
+
return null;
|
|
9480
|
+
}
|
|
9481
|
+
function formatAskUserAnswer(data, answer) {
|
|
9482
|
+
const parts = data.questions.map((question, index) => {
|
|
9483
|
+
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(", ");
|
|
9484
|
+
return `- ${question.question} -> ${indentAnswerContinuationLines(text)}`;
|
|
9485
|
+
});
|
|
9486
|
+
const note = answer.note?.trim() ?? "";
|
|
9487
|
+
return [
|
|
9488
|
+
`\u5173\u4E8E\u9700\u8981\u786E\u8BA4\u7684\u95EE\u9898\uFF0C\u7528\u6237\u7684\u56DE\u7B54\u5982\u4E0B\uFF1A
|
|
9489
|
+
${parts.join("\n")}`,
|
|
9490
|
+
note ? `\u8865\u5145\u8BF4\u660E\uFF1A${indentAnswerContinuationLines(note)}` : ""
|
|
9491
|
+
].filter(Boolean).join("\n");
|
|
9492
|
+
}
|
|
9493
|
+
function indentAnswerContinuationLines(answer) {
|
|
9494
|
+
return answer.replaceAll("\n", "\n ");
|
|
9495
|
+
}
|
|
9496
|
+
function normalizeQuestionItem(value) {
|
|
9497
|
+
if (!value || typeof value !== "object") return null;
|
|
9498
|
+
const item = value;
|
|
9499
|
+
if (typeof item.question !== "string" || !Array.isArray(item.options)) return null;
|
|
9500
|
+
const options = item.options.map(normalizeOptionItem);
|
|
9501
|
+
if (!options.every((option) => option !== null)) return null;
|
|
9502
|
+
return {
|
|
9503
|
+
question: item.question,
|
|
9504
|
+
options,
|
|
9505
|
+
multiSelect: item.multiSelect === true || item.multi_select === true
|
|
9506
|
+
};
|
|
9507
|
+
}
|
|
9508
|
+
function normalizeOptionItem(value) {
|
|
9509
|
+
if (typeof value === "string") return { label: value, description: "" };
|
|
9510
|
+
if (!value || typeof value !== "object") return null;
|
|
9511
|
+
const option = value;
|
|
9512
|
+
if (typeof option.label !== "string") return null;
|
|
9513
|
+
return {
|
|
9514
|
+
label: option.label,
|
|
9515
|
+
description: typeof option.description === "string" ? option.description : ""
|
|
9516
|
+
};
|
|
9517
|
+
}
|
|
9518
|
+
|
|
9519
|
+
// src/pack-page-bridge.ts
|
|
9520
|
+
function attachPackPageBridge(options) {
|
|
9521
|
+
const { client, frame, pack, collections, openSession } = options;
|
|
9522
|
+
const host = options.host ?? window;
|
|
9523
|
+
const controller = new AbortController();
|
|
9524
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
9525
|
+
const send = (value) => {
|
|
9526
|
+
if (!controller.signal.aborted) frame.postMessage(value, "*");
|
|
9527
|
+
};
|
|
9528
|
+
const changed = (collection) => send({ type: "blade:pack:records_changed", collection });
|
|
9529
|
+
const receive = async (event) => {
|
|
9530
|
+
if (event.source !== frame || controller.signal.aborted) return;
|
|
9531
|
+
const request = event.data;
|
|
9532
|
+
if (!request || typeof request !== "object") return;
|
|
9533
|
+
const { type: type2, id, method, params } = request;
|
|
9534
|
+
if (type2 !== "blade:pack:request" || typeof id !== "string" || !id || id.length > 128) return;
|
|
9535
|
+
const reply = (result) => send({ type: "blade:pack:response", id, result });
|
|
9536
|
+
try {
|
|
9537
|
+
if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548");
|
|
9538
|
+
const input = params;
|
|
9539
|
+
if (method === "session.openByTag") {
|
|
9540
|
+
if (typeof input.tag !== "string" || !input.tag || input.tag.length > 256) throw new Error("\u6848\u4EF6\u6807\u8BB0\u65E0\u6548");
|
|
9541
|
+
const result = await client.packs.sessionByTag(pack, input.tag, { signal: controller.signal });
|
|
9542
|
+
if (controller.signal.aborted) return;
|
|
9543
|
+
reply(result);
|
|
9544
|
+
openSession(result.session_id);
|
|
9545
|
+
return;
|
|
9546
|
+
}
|
|
9547
|
+
if (typeof input.collection !== "string" || !collections.includes(input.collection)) throw new Error("\u6B64\u9875\u9762\u65E0\u6CD5\u8BBF\u95EE\u8BE5\u6570\u636E\u8868");
|
|
9548
|
+
const collection = input.collection;
|
|
9549
|
+
switch (method) {
|
|
9550
|
+
case "records.list": {
|
|
9551
|
+
const query = {};
|
|
9552
|
+
if (input.filter !== void 0) {
|
|
9553
|
+
if (!input.filter || typeof input.filter !== "object" || Array.isArray(input.filter) || Object.values(input.filter).some((v) => !["string", "number", "boolean"].includes(typeof v))) throw new Error("\u7B5B\u9009\u6761\u4EF6\u65E0\u6548");
|
|
9554
|
+
query.filter = input.filter;
|
|
9555
|
+
}
|
|
9556
|
+
for (const key of ["limit", "offset"]) {
|
|
9557
|
+
if (input[key] !== void 0) {
|
|
9558
|
+
if (typeof input[key] !== "number" || !Number.isInteger(input[key])) throw new Error("\u67E5\u8BE2\u8303\u56F4\u65E0\u6548");
|
|
9559
|
+
query[key] = input[key];
|
|
9560
|
+
}
|
|
9561
|
+
}
|
|
9562
|
+
reply(await client.packs.records.list(pack, collection, query, { signal: controller.signal }));
|
|
9563
|
+
return;
|
|
9564
|
+
}
|
|
9565
|
+
case "records.subscribe":
|
|
9566
|
+
if (!subscriptions.has(collection)) subscriptions.set(collection, client.packs.records.onChanged(pack, collection, () => changed(collection)));
|
|
9567
|
+
reply({ subscribed: true });
|
|
9568
|
+
changed(collection);
|
|
9569
|
+
return;
|
|
9570
|
+
case "records.unsubscribe":
|
|
9571
|
+
subscriptions.get(collection)?.();
|
|
9572
|
+
subscriptions.delete(collection);
|
|
9573
|
+
reply({ subscribed: false });
|
|
9574
|
+
return;
|
|
9575
|
+
default:
|
|
9576
|
+
throw new Error("\u6B64\u9875\u9762\u4E0D\u652F\u6301\u8BE5\u64CD\u4F5C");
|
|
9577
|
+
}
|
|
9578
|
+
} catch (error) {
|
|
9579
|
+
send({ type: "blade:pack:response", id, error: error instanceof Error ? error.message : "\u64CD\u4F5C\u6682\u65F6\u65E0\u6CD5\u5B8C\u6210" });
|
|
9580
|
+
}
|
|
9581
|
+
};
|
|
9582
|
+
host.addEventListener("message", receive);
|
|
9583
|
+
send({ type: "blade:pack:ready" });
|
|
9584
|
+
return () => {
|
|
9585
|
+
controller.abort();
|
|
9586
|
+
host.removeEventListener("message", receive);
|
|
9587
|
+
for (const off of subscriptions.values()) off();
|
|
9588
|
+
subscriptions.clear();
|
|
9589
|
+
};
|
|
9590
|
+
}
|
|
9591
|
+
|
|
8112
9592
|
export {
|
|
9593
|
+
SandboxResource,
|
|
9594
|
+
BladeApiError,
|
|
9595
|
+
ToolProvider,
|
|
8113
9596
|
SDK_NAME,
|
|
8114
9597
|
SDK_VERSION,
|
|
8115
|
-
|
|
9598
|
+
PackRecordsResource,
|
|
9599
|
+
ProfileResource,
|
|
9600
|
+
PacksResource,
|
|
8116
9601
|
isRecord,
|
|
9602
|
+
packEventTitle,
|
|
8117
9603
|
normalizePluginRefs,
|
|
9604
|
+
normalizeMessageRefs,
|
|
8118
9605
|
normalizeTopicAssetRefs,
|
|
8119
9606
|
inferToolStatus,
|
|
8120
9607
|
contextProjectionData,
|
|
@@ -8137,10 +9624,14 @@ export {
|
|
|
8137
9624
|
computerOS,
|
|
8138
9625
|
computerPlatformLabel,
|
|
8139
9626
|
computerDaemonVersion,
|
|
8140
|
-
canToggleComputer,
|
|
8141
9627
|
sortComputers,
|
|
8142
9628
|
ComputersResource,
|
|
9629
|
+
phoneState,
|
|
9630
|
+
sortPhones,
|
|
9631
|
+
phoneSerialLabel,
|
|
8143
9632
|
ModelsResource,
|
|
9633
|
+
isLocalConnectorName,
|
|
9634
|
+
ConnectorsResource,
|
|
8144
9635
|
SessionStatus,
|
|
8145
9636
|
DEFAULT_REPLAY_SPEED,
|
|
8146
9637
|
SessionInfo,
|
|
@@ -8148,6 +9639,8 @@ export {
|
|
|
8148
9639
|
isEntryGoneError,
|
|
8149
9640
|
PluginsResource,
|
|
8150
9641
|
ChatGroupsResource,
|
|
9642
|
+
syncServerTime,
|
|
9643
|
+
getServerTime,
|
|
8151
9644
|
authBusyRetryDelayMs,
|
|
8152
9645
|
AuthBusyReconnect,
|
|
8153
9646
|
prependOlder,
|
|
@@ -8182,6 +9675,7 @@ export {
|
|
|
8182
9675
|
toReplaySnapshot,
|
|
8183
9676
|
createInitialSessionState,
|
|
8184
9677
|
parentForkToolCallIdFromTurn,
|
|
9678
|
+
messageContentFromTurn,
|
|
8185
9679
|
reconcileOptimisticUserTurns,
|
|
8186
9680
|
reconcileHistoricalUserTurns,
|
|
8187
9681
|
withTurns,
|
|
@@ -8192,6 +9686,10 @@ export {
|
|
|
8192
9686
|
AgentSession,
|
|
8193
9687
|
SessionHub,
|
|
8194
9688
|
createSocket,
|
|
8195
|
-
BladeClient
|
|
9689
|
+
BladeClient,
|
|
9690
|
+
BladeApplicationClient,
|
|
9691
|
+
parseAskUserQuestion,
|
|
9692
|
+
formatAskUserAnswer,
|
|
9693
|
+
attachPackPageBridge
|
|
8196
9694
|
};
|
|
8197
|
-
//# sourceMappingURL=chunk-
|
|
9695
|
+
//# sourceMappingURL=chunk-RI7ZYTYK.js.map
|