@daex-dev/sdk 0.0.0-stage → 0.7.1
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/LICENSE +21 -0
- package/README.md +417 -3
- package/dist/client-C0KQKP8O.d.cts +2621 -0
- package/dist/client-C0KQKP8O.d.ts +2621 -0
- package/dist/electron/global.cjs +18 -0
- package/dist/electron/global.d.cts +35 -0
- package/dist/electron/global.d.ts +35 -0
- package/dist/electron/global.js +0 -0
- package/dist/electron/index.cjs +1133 -0
- package/dist/electron/index.d.cts +510 -0
- package/dist/electron/index.d.ts +510 -0
- package/dist/electron/index.js +1073 -0
- package/dist/electron/preload-auto.cjs +38 -0
- package/dist/electron/preload.cjs +66 -0
- package/dist/electron/preload.d.cts +46 -0
- package/dist/electron/preload.d.ts +46 -0
- package/dist/electron/preload.js +43 -0
- package/dist/electron/protocol-DXRtliy3.d.cts +904 -0
- package/dist/electron/protocol-DXRtliy3.d.ts +904 -0
- package/dist/electron/renderer.cjs +631 -0
- package/dist/electron/renderer.d.cts +508 -0
- package/dist/electron/renderer.d.ts +508 -0
- package/dist/electron/renderer.global.js +634 -0
- package/dist/electron/renderer.js +608 -0
- package/dist/index.cjs +6681 -0
- package/dist/index.d.cts +313 -0
- package/dist/index.d.ts +313 -0
- package/dist/index.js +6611 -0
- package/dist/server.cjs +1019 -0
- package/dist/server.d.cts +118 -0
- package/dist/server.d.ts +118 -0
- package/dist/server.js +989 -0
- package/dist/testing.cjs +815 -0
- package/dist/testing.d.cts +29 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +787 -0
- package/package.json +93 -6
package/dist/server.js
ADDED
|
@@ -0,0 +1,989 @@
|
|
|
1
|
+
// src/clientEvents.ts
|
|
2
|
+
var DAEX_CLIENT_EVENTS = ["exit", "transport", "restart", "threadLifecycle", "usageLimit"];
|
|
3
|
+
|
|
4
|
+
// src/errors.ts
|
|
5
|
+
var ADE_ERROR_CODES = [
|
|
6
|
+
"binary_not_found",
|
|
7
|
+
"download_failed",
|
|
8
|
+
"checksum_mismatch",
|
|
9
|
+
"spawn_failed",
|
|
10
|
+
"connect_failed",
|
|
11
|
+
"handshake_failed",
|
|
12
|
+
"rpc_error",
|
|
13
|
+
"rpc_timeout",
|
|
14
|
+
"transport_closed",
|
|
15
|
+
"protocol_error",
|
|
16
|
+
"thread_not_found",
|
|
17
|
+
"invalid_option",
|
|
18
|
+
"runtime_unavailable",
|
|
19
|
+
"approval_not_found",
|
|
20
|
+
"unauthorized",
|
|
21
|
+
"disposed",
|
|
22
|
+
"runtime_incompatible",
|
|
23
|
+
"turn_in_flight",
|
|
24
|
+
"unsupported",
|
|
25
|
+
"invalid_output",
|
|
26
|
+
"sign_in_failed"
|
|
27
|
+
];
|
|
28
|
+
var CODE_SET = new Set(ADE_ERROR_CODES);
|
|
29
|
+
function readAdeErrorCode(value) {
|
|
30
|
+
return typeof value === "string" && CODE_SET.has(value) ? value : null;
|
|
31
|
+
}
|
|
32
|
+
var DaexError = class extends Error {
|
|
33
|
+
code;
|
|
34
|
+
cause;
|
|
35
|
+
constructor(code, message, options) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "AdeError";
|
|
38
|
+
this.code = code;
|
|
39
|
+
if (options && "cause" in options) this.cause = options.cause;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// src/signInRegistry.ts
|
|
44
|
+
var TERMINAL_STATES = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired"]);
|
|
45
|
+
function createSignInRegistry(serializeError) {
|
|
46
|
+
const entries = /* @__PURE__ */ new Map();
|
|
47
|
+
const forget = (loginId, entry) => {
|
|
48
|
+
entries.delete(loginId);
|
|
49
|
+
entry.stop();
|
|
50
|
+
};
|
|
51
|
+
const owned = (loginId, owner) => {
|
|
52
|
+
const entry = entries.get(loginId);
|
|
53
|
+
return entry && entry.owner === owner ? entry : null;
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
/** Track a sign-in the client just started; answers what `signIn` returns across the bridge. */
|
|
57
|
+
async start(owner, handle) {
|
|
58
|
+
let status = {};
|
|
59
|
+
const stop = handle.on("update", (next) => {
|
|
60
|
+
status = next;
|
|
61
|
+
});
|
|
62
|
+
if (!status.loginId) {
|
|
63
|
+
stop();
|
|
64
|
+
await handle.cancel().catch(() => {
|
|
65
|
+
});
|
|
66
|
+
throw new DaexError("protocol_error", "The sign-in did not provide its initial status.");
|
|
67
|
+
}
|
|
68
|
+
entries.set(status.loginId, {
|
|
69
|
+
owner,
|
|
70
|
+
handle,
|
|
71
|
+
get status() {
|
|
72
|
+
return status;
|
|
73
|
+
},
|
|
74
|
+
stop,
|
|
75
|
+
result: handle.done.then((account) => ({ account }), (error) => ({ error: serializeError(error) }))
|
|
76
|
+
});
|
|
77
|
+
return { loginId: status.loginId, status };
|
|
78
|
+
},
|
|
79
|
+
/** The latest status; once it is terminal, also the outcome, and the entry is released. */
|
|
80
|
+
async status(owner, loginId) {
|
|
81
|
+
const entry = owned(loginId, owner);
|
|
82
|
+
if (!entry) throw new DaexError("invalid_option", `Sign-in "${loginId}" was not found.`);
|
|
83
|
+
if (!TERMINAL_STATES.has(entry.status.state)) return { status: entry.status };
|
|
84
|
+
const result = await entry.result;
|
|
85
|
+
forget(loginId, entry);
|
|
86
|
+
return { status: entry.status, ...result };
|
|
87
|
+
},
|
|
88
|
+
async submitCode(owner, loginId, code) {
|
|
89
|
+
const entry = owned(loginId, owner);
|
|
90
|
+
if (!entry) throw new DaexError("invalid_option", "This sign-in is no longer active.");
|
|
91
|
+
await entry.handle.submitCode(code);
|
|
92
|
+
},
|
|
93
|
+
/** Cancelling a sign-in that is already gone is not an error. */
|
|
94
|
+
async cancel(owner, loginId) {
|
|
95
|
+
const entry = owned(loginId, owner);
|
|
96
|
+
if (!entry) return;
|
|
97
|
+
forget(loginId, entry);
|
|
98
|
+
await entry.handle.cancel();
|
|
99
|
+
},
|
|
100
|
+
/** Cancel every sign-in an owner started: it went away and can no longer finish them. */
|
|
101
|
+
releaseOwner(owner) {
|
|
102
|
+
for (const [loginId, entry] of entries) {
|
|
103
|
+
if (entry.owner !== owner) continue;
|
|
104
|
+
forget(loginId, entry);
|
|
105
|
+
void entry.handle.cancel().catch(() => {
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/electron/protocol.ts
|
|
113
|
+
function serializeAdeError(error) {
|
|
114
|
+
const candidate = error && typeof error === "object" ? error : null;
|
|
115
|
+
return {
|
|
116
|
+
__adeError: true,
|
|
117
|
+
name: "AdeError",
|
|
118
|
+
code: candidate?.name === "AdeError" && typeof candidate.code === "string" ? candidate.code : "rpc_error",
|
|
119
|
+
message: typeof candidate?.message === "string" ? candidate.message : String(error)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function envelopeDedupeKey(envelope, occurrence = 0) {
|
|
123
|
+
const sequence = typeof envelope.sequence === "number" ? String(envelope.sequence) : "?";
|
|
124
|
+
const type = typeof envelope.event?.type === "string" ? envelope.event.type : "?";
|
|
125
|
+
const base = `${envelope.sessionId}:${sequence}:${envelope.timestamp}:${type}`;
|
|
126
|
+
return occurrence > 0 ? `${base}#${occurrence}` : base;
|
|
127
|
+
}
|
|
128
|
+
function keyEnvelopes(envelopes) {
|
|
129
|
+
const counts = /* @__PURE__ */ new Map();
|
|
130
|
+
return envelopes.map((envelope) => {
|
|
131
|
+
const base = envelopeDedupeKey(envelope);
|
|
132
|
+
const occurrence = counts.get(base) ?? 0;
|
|
133
|
+
counts.set(base, occurrence + 1);
|
|
134
|
+
return envelopeDedupeKey(envelope, occurrence);
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
function compareEnvelopes(a, b) {
|
|
138
|
+
const aSeq = typeof a.sequence === "number" ? a.sequence : null;
|
|
139
|
+
const bSeq = typeof b.sequence === "number" ? b.sequence : null;
|
|
140
|
+
if (aSeq !== null && bSeq === null) return -1;
|
|
141
|
+
if (aSeq === null && bSeq !== null) return 1;
|
|
142
|
+
if (aSeq !== null && bSeq !== null) {
|
|
143
|
+
if (aSeq !== bSeq) return aSeq - bSeq;
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
if (a.timestamp !== b.timestamp) return a.timestamp < b.timestamp ? -1 : 1;
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
function mergeHistoryWithBuffer(history, buffered) {
|
|
150
|
+
const seen = /* @__PURE__ */ new Set();
|
|
151
|
+
const merged = [];
|
|
152
|
+
const keys = [...keyEnvelopes(history), ...keyEnvelopes(buffered)];
|
|
153
|
+
[...history, ...buffered].forEach((envelope, index) => {
|
|
154
|
+
const key = keys[index];
|
|
155
|
+
if (seen.has(key)) return;
|
|
156
|
+
seen.add(key);
|
|
157
|
+
merged.push(envelope);
|
|
158
|
+
});
|
|
159
|
+
return merged.sort(compareEnvelopes);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/usage.ts
|
|
163
|
+
function validateThreadBudget(value) {
|
|
164
|
+
if (value === void 0) return void 0;
|
|
165
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
166
|
+
throw new DaexError("invalid_option", "budget must be an object with maxCostUsd and/or maxTokens.");
|
|
167
|
+
}
|
|
168
|
+
const entries = Object.entries(value);
|
|
169
|
+
if (!entries.length) {
|
|
170
|
+
throw new DaexError("invalid_option", "budget must set maxCostUsd, maxTokens, or both.");
|
|
171
|
+
}
|
|
172
|
+
for (const [key, limit] of entries) {
|
|
173
|
+
if (key !== "maxCostUsd" && key !== "maxTokens") {
|
|
174
|
+
throw new DaexError("invalid_option", `budget.${key} is not supported.`);
|
|
175
|
+
}
|
|
176
|
+
if (typeof limit !== "number" || !Number.isFinite(limit) || limit < 0) {
|
|
177
|
+
throw new DaexError("invalid_option", `budget.${key} must be a finite, non-negative number.`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { ...value };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/polledSignIn.ts
|
|
184
|
+
var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "expired"]);
|
|
185
|
+
function createPolledSignIn(started, ops) {
|
|
186
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
187
|
+
let current = started.status;
|
|
188
|
+
let timer = null;
|
|
189
|
+
let finished = false;
|
|
190
|
+
let delay = 500;
|
|
191
|
+
let resolveDone;
|
|
192
|
+
let rejectDone;
|
|
193
|
+
const done = new Promise((resolve, reject) => {
|
|
194
|
+
resolveDone = resolve;
|
|
195
|
+
rejectDone = reject;
|
|
196
|
+
});
|
|
197
|
+
done.catch(() => {
|
|
198
|
+
});
|
|
199
|
+
const publish = (status) => {
|
|
200
|
+
current = status;
|
|
201
|
+
for (const listener of [...listeners]) {
|
|
202
|
+
try {
|
|
203
|
+
listener(status);
|
|
204
|
+
} catch {
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
const finish = (result) => {
|
|
209
|
+
if (finished) return;
|
|
210
|
+
finished = true;
|
|
211
|
+
if (timer) clearTimeout(timer);
|
|
212
|
+
timer = null;
|
|
213
|
+
publish(result.status);
|
|
214
|
+
if (result.account) resolveDone(result.account);
|
|
215
|
+
else if (result.error !== void 0) rejectDone(ops.toError(result.error));
|
|
216
|
+
else rejectDone(new DaexError("sign_in_failed", result.status.message ?? `Sign-in ${result.status.state}.`));
|
|
217
|
+
};
|
|
218
|
+
const poll = async () => {
|
|
219
|
+
if (finished) return;
|
|
220
|
+
try {
|
|
221
|
+
const result = await ops.status(started.loginId);
|
|
222
|
+
if (JSON.stringify(result.status) !== JSON.stringify(current)) publish(result.status);
|
|
223
|
+
if (TERMINAL.has(result.status.state)) {
|
|
224
|
+
finish(result);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
delay = Math.min(5e3, delay * 1.5);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (finished) return;
|
|
230
|
+
finish({ status: { ...current, state: "failed", message: error instanceof Error ? error.message : String(error) } });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
timer = setTimeout(() => {
|
|
234
|
+
void poll();
|
|
235
|
+
}, delay);
|
|
236
|
+
};
|
|
237
|
+
if (TERMINAL.has(current.state)) void poll();
|
|
238
|
+
else timer = setTimeout(() => {
|
|
239
|
+
void poll();
|
|
240
|
+
}, delay);
|
|
241
|
+
return {
|
|
242
|
+
on: (_event, listener) => {
|
|
243
|
+
listeners.add(listener);
|
|
244
|
+
listener(current);
|
|
245
|
+
return () => listeners.delete(listener);
|
|
246
|
+
},
|
|
247
|
+
submitCode: async (code) => {
|
|
248
|
+
await ops.submitCode(started.loginId, code);
|
|
249
|
+
},
|
|
250
|
+
cancel: async () => {
|
|
251
|
+
if (finished) return;
|
|
252
|
+
await ops.cancel(started.loginId);
|
|
253
|
+
finish({ status: { ...current, state: "cancelled", endedAt: (/* @__PURE__ */ new Date()).toISOString() } });
|
|
254
|
+
},
|
|
255
|
+
done
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/types.ts
|
|
260
|
+
var USAGE_EVENT_TYPES = [
|
|
261
|
+
"tokens",
|
|
262
|
+
"context_usage",
|
|
263
|
+
"codex_token_usage"
|
|
264
|
+
];
|
|
265
|
+
var STATUS_EVENT_TYPES = [
|
|
266
|
+
"status",
|
|
267
|
+
"done",
|
|
268
|
+
"error",
|
|
269
|
+
"turn_health",
|
|
270
|
+
"session_meta_updated",
|
|
271
|
+
"interrupt_receipt",
|
|
272
|
+
"capabilities_changed",
|
|
273
|
+
"budget_exceeded"
|
|
274
|
+
];
|
|
275
|
+
|
|
276
|
+
// src/remoteClient.ts
|
|
277
|
+
var USAGE = new Set(USAGE_EVENT_TYPES);
|
|
278
|
+
var STATUS = new Set(STATUS_EVENT_TYPES);
|
|
279
|
+
function parseIncoming(raw) {
|
|
280
|
+
let value = raw;
|
|
281
|
+
if (value && typeof value === "object" && "data" in value) value = value.data;
|
|
282
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
283
|
+
if (value instanceof Uint8Array) return JSON.parse(new TextDecoder().decode(value));
|
|
284
|
+
return JSON.parse(String(value));
|
|
285
|
+
}
|
|
286
|
+
function bind(transport, event, listener) {
|
|
287
|
+
if (typeof transport.addEventListener === "function") {
|
|
288
|
+
transport.addEventListener(event, listener);
|
|
289
|
+
return () => transport.removeEventListener?.(event, listener);
|
|
290
|
+
}
|
|
291
|
+
if (typeof transport.on === "function") {
|
|
292
|
+
transport.on(event, listener);
|
|
293
|
+
return () => {
|
|
294
|
+
if (typeof transport.off === "function") transport.off(event, listener);
|
|
295
|
+
else transport.removeListener?.(event, listener);
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
throw new DaexError("invalid_option", "The remote transport must support message and close listeners.");
|
|
299
|
+
}
|
|
300
|
+
function remoteError(payload) {
|
|
301
|
+
const value = payload && typeof payload === "object" ? payload : {};
|
|
302
|
+
const code = readAdeErrorCode(value.code) ?? "rpc_error";
|
|
303
|
+
return new DaexError(code, typeof value.message === "string" ? value.message : "The DAEX server returned an error.");
|
|
304
|
+
}
|
|
305
|
+
function createDaexRemoteClient(transportOrUrl, options = {}) {
|
|
306
|
+
let transport;
|
|
307
|
+
if (typeof transportOrUrl === "string") {
|
|
308
|
+
const globalWebSocket = globalThis.WebSocket;
|
|
309
|
+
const WebSocketConstructor = options.WebSocket ?? globalWebSocket;
|
|
310
|
+
if (!WebSocketConstructor) {
|
|
311
|
+
throw new DaexError("invalid_option", "createDaexRemoteClient(url) needs a global WebSocket or the WebSocket option.");
|
|
312
|
+
}
|
|
313
|
+
transport = new WebSocketConstructor(transportOrUrl);
|
|
314
|
+
} else {
|
|
315
|
+
transport = transportOrUrl;
|
|
316
|
+
}
|
|
317
|
+
if (!transport || typeof transport.send !== "function") {
|
|
318
|
+
throw new DaexError("invalid_option", "createDaexRemoteClient needs a WebSocket-compatible transport.");
|
|
319
|
+
}
|
|
320
|
+
let nextId = 1;
|
|
321
|
+
let closed = false;
|
|
322
|
+
let disposed = false;
|
|
323
|
+
const pending = /* @__PURE__ */ new Map();
|
|
324
|
+
const queued = [];
|
|
325
|
+
const threads = /* @__PURE__ */ new Map();
|
|
326
|
+
const preOpenEvents = /* @__PURE__ */ new Map();
|
|
327
|
+
const providerListeners = /* @__PURE__ */ new Set();
|
|
328
|
+
const clientListeners = /* @__PURE__ */ new Map();
|
|
329
|
+
const isOpen = () => transport.readyState === void 0 || transport.readyState === (transport.OPEN ?? 1);
|
|
330
|
+
const sendRaw = (payload) => {
|
|
331
|
+
if (closed || disposed) throw new DaexError("transport_closed", "The DAEX server connection is closed.");
|
|
332
|
+
if (!isOpen()) {
|
|
333
|
+
queued.push(payload);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
transport.send(payload);
|
|
337
|
+
};
|
|
338
|
+
const flush = () => {
|
|
339
|
+
if (!isOpen() || closed || disposed) return;
|
|
340
|
+
for (const payload of queued.splice(0)) transport.send(payload);
|
|
341
|
+
};
|
|
342
|
+
const rejectPending = (error) => {
|
|
343
|
+
for (const call2 of pending.values()) {
|
|
344
|
+
clearTimeout(call2.timer);
|
|
345
|
+
call2.reject(error);
|
|
346
|
+
}
|
|
347
|
+
pending.clear();
|
|
348
|
+
};
|
|
349
|
+
const call = (method, params = {}) => {
|
|
350
|
+
if (closed || disposed) return Promise.reject(new DaexError("transport_closed", "The DAEX server connection is closed."));
|
|
351
|
+
const id = nextId++;
|
|
352
|
+
return new Promise((resolve, reject) => {
|
|
353
|
+
const timer = setTimeout(() => {
|
|
354
|
+
pending.delete(id);
|
|
355
|
+
reject(new DaexError("rpc_timeout", "The DAEX server did not answer " + method + " before the request timed out."));
|
|
356
|
+
}, 3e4);
|
|
357
|
+
pending.set(id, { resolve, reject, timer });
|
|
358
|
+
try {
|
|
359
|
+
sendRaw(JSON.stringify({ id, method, params }));
|
|
360
|
+
} catch (error) {
|
|
361
|
+
clearTimeout(timer);
|
|
362
|
+
pending.delete(id);
|
|
363
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
};
|
|
367
|
+
const dispatchThreadEvent = (state, envelope) => {
|
|
368
|
+
if (typeof envelope.sequence === "number") {
|
|
369
|
+
const key = envelopeDedupeKey(envelope);
|
|
370
|
+
if (state.seenSequences.has(key)) return;
|
|
371
|
+
state.seenSequences.add(key);
|
|
372
|
+
if (state.seenSequences.size > 2e4) state.seenSequences.delete(state.seenSequences.values().next().value);
|
|
373
|
+
}
|
|
374
|
+
const type = envelope.event?.type;
|
|
375
|
+
let deliveredToTranscript = false;
|
|
376
|
+
for (const [channel, listeners] of state.listeners) {
|
|
377
|
+
if (channel === "usage" && !USAGE.has(type)) continue;
|
|
378
|
+
if (channel === "status" && !STATUS.has(type)) continue;
|
|
379
|
+
if (channel === "event" && listeners.size) deliveredToTranscript = true;
|
|
380
|
+
for (const listener of [...listeners]) listener(envelope);
|
|
381
|
+
}
|
|
382
|
+
for (const buffer of state.buffers) buffer.push({ envelope, deliveredToTranscript });
|
|
383
|
+
};
|
|
384
|
+
const handleIncoming = (raw) => {
|
|
385
|
+
let message;
|
|
386
|
+
try {
|
|
387
|
+
message = parseIncoming(raw);
|
|
388
|
+
} catch {
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (!message || typeof message !== "object") return;
|
|
392
|
+
if (message.push === "event" && typeof message.key === "string" && message.envelope) {
|
|
393
|
+
const state = threads.get(message.key);
|
|
394
|
+
if (state) dispatchThreadEvent(state, message.envelope);
|
|
395
|
+
else {
|
|
396
|
+
const buffer = preOpenEvents.get(message.key) ?? [];
|
|
397
|
+
buffer.push(message.envelope);
|
|
398
|
+
if (buffer.length > 5e3) buffer.shift();
|
|
399
|
+
preOpenEvents.set(message.key, buffer);
|
|
400
|
+
}
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (message.push === "providers" && message.statuses && typeof message.statuses === "object") {
|
|
404
|
+
for (const listener of [...providerListeners]) listener(message.statuses);
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
if (message.push === "client" && typeof message.event === "string") {
|
|
408
|
+
for (const listener of [...clientListeners.get(message.event) ?? []]) listener(message.payload);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const entry = pending.get(message.id);
|
|
412
|
+
if (!entry) return;
|
|
413
|
+
pending.delete(message.id);
|
|
414
|
+
clearTimeout(entry.timer);
|
|
415
|
+
if (message.ok === true) entry.resolve(message.result);
|
|
416
|
+
else entry.reject(remoteError(message.error));
|
|
417
|
+
};
|
|
418
|
+
const detach = [
|
|
419
|
+
bind(transport, "message", (...args) => handleIncoming(args[0])),
|
|
420
|
+
bind(transport, "close", () => {
|
|
421
|
+
closed = true;
|
|
422
|
+
rejectPending(new DaexError("transport_closed", "The DAEX server closed the WebSocket connection."));
|
|
423
|
+
})
|
|
424
|
+
];
|
|
425
|
+
if (transport.addEventListener || transport.on) {
|
|
426
|
+
try {
|
|
427
|
+
detach.push(bind(transport, "open", flush));
|
|
428
|
+
} catch {
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
flush();
|
|
432
|
+
const openThread = async (key, options2) => {
|
|
433
|
+
const existing = threads.get(key);
|
|
434
|
+
if (existing) return makeThread(existing);
|
|
435
|
+
const snapshot = await call("threads.open", { key, options: options2 ?? {} });
|
|
436
|
+
const state = {
|
|
437
|
+
...snapshot,
|
|
438
|
+
key,
|
|
439
|
+
listeners: /* @__PURE__ */ new Map(),
|
|
440
|
+
buffers: /* @__PURE__ */ new Set(),
|
|
441
|
+
seenSequences: /* @__PURE__ */ new Set()
|
|
442
|
+
};
|
|
443
|
+
threads.set(key, state);
|
|
444
|
+
for (const envelope of preOpenEvents.get(key) ?? []) dispatchThreadEvent(state, envelope);
|
|
445
|
+
preOpenEvents.delete(key);
|
|
446
|
+
return makeThread(state);
|
|
447
|
+
};
|
|
448
|
+
function makeThread(state) {
|
|
449
|
+
const addListener = (channel, listener) => {
|
|
450
|
+
let listeners = state.listeners.get(channel);
|
|
451
|
+
if (!listeners) state.listeners.set(channel, listeners = /* @__PURE__ */ new Set());
|
|
452
|
+
listeners.add(listener);
|
|
453
|
+
return () => listeners?.delete(listener);
|
|
454
|
+
};
|
|
455
|
+
const readHistory = async (opts) => {
|
|
456
|
+
const buffer = [];
|
|
457
|
+
state.buffers.add(buffer);
|
|
458
|
+
try {
|
|
459
|
+
const history = await call("thread.history", { key: state.key, options: opts ?? {} });
|
|
460
|
+
const missed = buffer.filter((entry) => !entry.deliveredToTranscript).map((entry) => entry.envelope);
|
|
461
|
+
return mergeHistoryWithBuffer(Array.isArray(history) ? history : [], missed);
|
|
462
|
+
} finally {
|
|
463
|
+
state.buffers.delete(buffer);
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
const readHistoryPage = async (opts) => {
|
|
467
|
+
const buffer = [];
|
|
468
|
+
state.buffers.add(buffer);
|
|
469
|
+
try {
|
|
470
|
+
const page = await call("thread.historyPage", { key: state.key, options: opts ?? {} });
|
|
471
|
+
const missed = buffer.filter((entry) => !entry.deliveredToTranscript).map((entry) => entry.envelope);
|
|
472
|
+
return { ...page, events: mergeHistoryWithBuffer(Array.isArray(page?.events) ? page.events : [], missed) };
|
|
473
|
+
} finally {
|
|
474
|
+
state.buffers.delete(buffer);
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
return {
|
|
478
|
+
id: state.id,
|
|
479
|
+
key: state.key,
|
|
480
|
+
title: state.title,
|
|
481
|
+
model: state.model,
|
|
482
|
+
mcpCapability: state.mcpCapability,
|
|
483
|
+
instructionsCapability: state.instructionsCapability,
|
|
484
|
+
settingSourcesCapability: state.settingSourcesCapability,
|
|
485
|
+
permissionCapability: state.permissionCapability,
|
|
486
|
+
send: async (text, options2) => {
|
|
487
|
+
await call("thread.send", { key: state.key, text, options: options2 ?? {} });
|
|
488
|
+
},
|
|
489
|
+
steer: async (text, options2) => {
|
|
490
|
+
await call("thread.steer", { key: state.key, text, options: options2 ?? {} });
|
|
491
|
+
},
|
|
492
|
+
interrupt: async (options2) => {
|
|
493
|
+
await call("thread.interrupt", { key: state.key, options: options2 ?? {} });
|
|
494
|
+
},
|
|
495
|
+
respond: async (requestId, response) => {
|
|
496
|
+
await call("thread.respond", { key: state.key, requestId, response });
|
|
497
|
+
},
|
|
498
|
+
queue: {
|
|
499
|
+
list: () => call("thread.queue.list", { key: state.key }),
|
|
500
|
+
cancel: async (id) => {
|
|
501
|
+
await call("thread.queue.cancel", { key: state.key, id });
|
|
502
|
+
},
|
|
503
|
+
edit: async (id, text) => {
|
|
504
|
+
await call("thread.queue.edit", { key: state.key, id, text });
|
|
505
|
+
},
|
|
506
|
+
move: async (id, index) => {
|
|
507
|
+
await call("thread.queue.move", { key: state.key, id, index });
|
|
508
|
+
},
|
|
509
|
+
dispatch: async (id) => {
|
|
510
|
+
await call("thread.queue.dispatch", { key: state.key, id });
|
|
511
|
+
},
|
|
512
|
+
cancelDispatched: async (id) => {
|
|
513
|
+
await call("thread.queue.cancelDispatched", { key: state.key, id });
|
|
514
|
+
},
|
|
515
|
+
restore: async () => {
|
|
516
|
+
await call("thread.queue.restore", { key: state.key });
|
|
517
|
+
}
|
|
518
|
+
},
|
|
519
|
+
stopTask: async (taskId) => {
|
|
520
|
+
await call("thread.stopTask", { key: state.key, taskId });
|
|
521
|
+
},
|
|
522
|
+
slashCommands: () => call("thread.slashCommands", { key: state.key }),
|
|
523
|
+
recover: (options2) => call("thread.recover", { key: state.key, options: options2 ?? {} }),
|
|
524
|
+
resolveUnprocessed: (args) => call("thread.resolveUnprocessed", { key: state.key, args }),
|
|
525
|
+
usageLimit: {
|
|
526
|
+
resumeNow: () => call("thread.usageLimit.resumeNow", { key: state.key }),
|
|
527
|
+
continueOnAlternate: () => call("thread.usageLimit.continueOnAlternate", { key: state.key })
|
|
528
|
+
},
|
|
529
|
+
switchAccount: (instanceId) => call("thread.switchAccount", { key: state.key, instanceId }),
|
|
530
|
+
setModel: async (modelId, options2) => {
|
|
531
|
+
const result = await call("thread.setModel", { key: state.key, modelId, options: options2 ?? {} });
|
|
532
|
+
state.model = result;
|
|
533
|
+
return result;
|
|
534
|
+
},
|
|
535
|
+
update: async (patch, options2) => await call("thread.update", { key: state.key, patch, options: options2 ?? {} }),
|
|
536
|
+
retry: async () => await call("thread.retry", { key: state.key }),
|
|
537
|
+
editLast: async (text, options2) => await call("thread.editLast", { key: state.key, text, options: options2 ?? {} }),
|
|
538
|
+
history: readHistory,
|
|
539
|
+
historyPage: readHistoryPage,
|
|
540
|
+
approve: async (itemId, decision, responseText) => await call("thread.approve", { key: state.key, itemId, decision, responseText }),
|
|
541
|
+
pendingApprovals: async () => await call("thread.pendingApprovals", { key: state.key }),
|
|
542
|
+
usage: () => call("thread.usage", { key: state.key }),
|
|
543
|
+
updateMcpServers: async (servers) => await call("thread.updateMcpServers", { key: state.key, servers }),
|
|
544
|
+
refreshMcpHeaders: async () => await call("thread.refreshMcpHeaders", { key: state.key }),
|
|
545
|
+
on: addListener
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
return {
|
|
549
|
+
call,
|
|
550
|
+
providers: {
|
|
551
|
+
status: () => call("providers.status"),
|
|
552
|
+
refresh: () => call("providers.refresh"),
|
|
553
|
+
onChange: (listener) => {
|
|
554
|
+
providerListeners.add(listener);
|
|
555
|
+
return () => providerListeners.delete(listener);
|
|
556
|
+
},
|
|
557
|
+
capabilities: (provider) => call("providers.capabilities", { provider })
|
|
558
|
+
},
|
|
559
|
+
accounts: {
|
|
560
|
+
list: (provider) => call("accounts.list", { provider }),
|
|
561
|
+
add: (provider, options2) => call("accounts.add", { provider, options: options2 ?? {} }),
|
|
562
|
+
remove: (id) => call("accounts.remove", { id }),
|
|
563
|
+
rename: (id, label) => call("accounts.rename", { id, label }),
|
|
564
|
+
setDefault: (id) => call("accounts.setDefault", { id }),
|
|
565
|
+
signOut: (id) => call("accounts.signOut", { id }),
|
|
566
|
+
refresh: () => call("accounts.refresh"),
|
|
567
|
+
signIn: async (id, options2) => {
|
|
568
|
+
const started = await call("accounts.signIn", { id, options: options2 ?? {} });
|
|
569
|
+
return createPolledSignIn(started, {
|
|
570
|
+
status: (loginId) => call("accounts.signInStatus", { loginId }),
|
|
571
|
+
submitCode: async (loginId, code) => {
|
|
572
|
+
await call("accounts.signInSubmitCode", { loginId, code });
|
|
573
|
+
},
|
|
574
|
+
cancel: async (loginId) => {
|
|
575
|
+
await call("accounts.signInCancel", { loginId });
|
|
576
|
+
},
|
|
577
|
+
toError: remoteError
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
},
|
|
581
|
+
credentials: {
|
|
582
|
+
list: (provider) => call("credentials.list", { provider }),
|
|
583
|
+
add: (input) => call("credentials.add", { credential: input }),
|
|
584
|
+
remove: (id, provider) => call("credentials.remove", { id, provider }),
|
|
585
|
+
verify: (provider) => call("credentials.verify", { provider })
|
|
586
|
+
},
|
|
587
|
+
presets: {
|
|
588
|
+
list: () => call("presets.list"),
|
|
589
|
+
add: (input) => call("presets.add", { preset: input }),
|
|
590
|
+
update: (id, patch) => call("presets.update", { id, patch }),
|
|
591
|
+
remove: (id) => call("presets.remove", { id })
|
|
592
|
+
},
|
|
593
|
+
models: { list: () => call("models.list") },
|
|
594
|
+
threads: {
|
|
595
|
+
open: openThread,
|
|
596
|
+
list: () => call("threads.list"),
|
|
597
|
+
get: (key) => call("threads.get", { key }),
|
|
598
|
+
delete: async (key) => {
|
|
599
|
+
await call("threads.delete", { key });
|
|
600
|
+
threads.delete(key);
|
|
601
|
+
preOpenEvents.delete(key);
|
|
602
|
+
},
|
|
603
|
+
archive: async (key) => {
|
|
604
|
+
await call("threads.archive", { key });
|
|
605
|
+
},
|
|
606
|
+
unarchive: async (key) => {
|
|
607
|
+
await call("threads.unarchive", { key });
|
|
608
|
+
}
|
|
609
|
+
},
|
|
610
|
+
doctor: () => call("doctor"),
|
|
611
|
+
exportThread: (key) => call("thread.export", { key }),
|
|
612
|
+
on: (event, listener) => {
|
|
613
|
+
let listeners = clientListeners.get(event);
|
|
614
|
+
if (!listeners) clientListeners.set(event, listeners = /* @__PURE__ */ new Set());
|
|
615
|
+
const callback = listener;
|
|
616
|
+
listeners.add(callback);
|
|
617
|
+
return () => listeners?.delete(callback);
|
|
618
|
+
},
|
|
619
|
+
dispose: () => {
|
|
620
|
+
if (disposed) return;
|
|
621
|
+
disposed = true;
|
|
622
|
+
rejectPending(new DaexError("disposed", "The remote DAEX client was disposed."));
|
|
623
|
+
for (const remove of detach) remove();
|
|
624
|
+
providerListeners.clear();
|
|
625
|
+
clientListeners.clear();
|
|
626
|
+
threads.clear();
|
|
627
|
+
preOpenEvents.clear();
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
var createAdeRemoteClient = createDaexRemoteClient;
|
|
632
|
+
|
|
633
|
+
// src/server.ts
|
|
634
|
+
var KEYED_METHODS = /* @__PURE__ */ new Set([
|
|
635
|
+
"threads.open",
|
|
636
|
+
"threads.get",
|
|
637
|
+
"threads.delete",
|
|
638
|
+
"threads.archive",
|
|
639
|
+
"threads.unarchive",
|
|
640
|
+
"thread.export",
|
|
641
|
+
"thread.update",
|
|
642
|
+
"thread.retry",
|
|
643
|
+
"thread.editLast",
|
|
644
|
+
"thread.history",
|
|
645
|
+
"thread.historyPage",
|
|
646
|
+
"thread.send",
|
|
647
|
+
"thread.steer",
|
|
648
|
+
"thread.interrupt",
|
|
649
|
+
"thread.setModel",
|
|
650
|
+
"thread.approve",
|
|
651
|
+
"thread.pendingApprovals",
|
|
652
|
+
"thread.usage",
|
|
653
|
+
"thread.updateMcpServers",
|
|
654
|
+
"thread.refreshMcpHeaders",
|
|
655
|
+
"thread.respond",
|
|
656
|
+
"thread.queue.list",
|
|
657
|
+
"thread.queue.cancel",
|
|
658
|
+
"thread.queue.edit",
|
|
659
|
+
"thread.queue.move",
|
|
660
|
+
"thread.queue.dispatch",
|
|
661
|
+
"thread.queue.cancelDispatched",
|
|
662
|
+
"thread.queue.restore",
|
|
663
|
+
"thread.stopTask",
|
|
664
|
+
"thread.slashCommands",
|
|
665
|
+
"thread.recover",
|
|
666
|
+
"thread.resolveUnprocessed",
|
|
667
|
+
"thread.usageLimit.resumeNow",
|
|
668
|
+
"thread.usageLimit.continueOnAlternate",
|
|
669
|
+
"thread.switchAccount"
|
|
670
|
+
]);
|
|
671
|
+
function isAccountMethod(method) {
|
|
672
|
+
return method.startsWith("accounts.") || method.startsWith("credentials.") || method.startsWith("presets.");
|
|
673
|
+
}
|
|
674
|
+
function requireText(value, label) {
|
|
675
|
+
if (typeof value !== "string" || !value.trim()) throw new DaexError("invalid_option", label + " must be a non-empty string.");
|
|
676
|
+
return value;
|
|
677
|
+
}
|
|
678
|
+
function asParams(value) {
|
|
679
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
680
|
+
}
|
|
681
|
+
function stringify(value) {
|
|
682
|
+
try {
|
|
683
|
+
return JSON.stringify(value);
|
|
684
|
+
} catch {
|
|
685
|
+
return "null";
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
function safeSend(socket, value) {
|
|
689
|
+
try {
|
|
690
|
+
socket.send(stringify(value));
|
|
691
|
+
} catch {
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
function listen(socket, event, listener) {
|
|
695
|
+
if (typeof socket.addEventListener === "function") {
|
|
696
|
+
socket.addEventListener(event, listener);
|
|
697
|
+
return () => socket.removeEventListener?.(event, listener);
|
|
698
|
+
}
|
|
699
|
+
if (typeof socket.on === "function") {
|
|
700
|
+
socket.on(event, listener);
|
|
701
|
+
return () => {
|
|
702
|
+
if (typeof socket.off === "function") socket.off(event, listener);
|
|
703
|
+
else socket.removeListener?.(event, listener);
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
throw new DaexError("invalid_option", "createDaexServer needs a WebSocket-compatible socket.");
|
|
707
|
+
}
|
|
708
|
+
function parseMessage(raw) {
|
|
709
|
+
let value = raw;
|
|
710
|
+
if (value && typeof value === "object" && "data" in value) value = value.data;
|
|
711
|
+
return JSON.parse(typeof value === "string" ? value : String(value));
|
|
712
|
+
}
|
|
713
|
+
function rendererOpenOptions(options, exists) {
|
|
714
|
+
if (exists) return {};
|
|
715
|
+
const input = options ?? {};
|
|
716
|
+
return {
|
|
717
|
+
...typeof input.provider === "string" ? { provider: input.provider } : {},
|
|
718
|
+
...typeof input.model === "string" ? { model: input.model } : {},
|
|
719
|
+
...typeof input.title === "string" ? { title: input.title } : {},
|
|
720
|
+
...typeof input.reasoningEffort === "string" ? { reasoningEffort: input.reasoningEffort } : {},
|
|
721
|
+
...input.budget !== void 0 ? { budget: validateThreadBudget(input.budget) } : {}
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
function createDaexServer(options) {
|
|
725
|
+
const { client } = options;
|
|
726
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
727
|
+
const cleanups = /* @__PURE__ */ new Map();
|
|
728
|
+
let closed = false;
|
|
729
|
+
const attach = (socket) => {
|
|
730
|
+
if (closed) throw new DaexError("disposed", "This DAEX server bridge has been closed.");
|
|
731
|
+
const threads = /* @__PURE__ */ new Map();
|
|
732
|
+
const opening = /* @__PURE__ */ new Map();
|
|
733
|
+
const requestIds = /* @__PURE__ */ new Set();
|
|
734
|
+
const signIns = createSignInRegistry(serializeAdeError);
|
|
735
|
+
let disconnected = false;
|
|
736
|
+
const send = (message) => {
|
|
737
|
+
if (!disconnected) safeSend(socket, message);
|
|
738
|
+
};
|
|
739
|
+
const cleanup = () => {
|
|
740
|
+
if (disconnected) return;
|
|
741
|
+
disconnected = true;
|
|
742
|
+
sockets.delete(socket);
|
|
743
|
+
cleanups.delete(socket);
|
|
744
|
+
stopProvider();
|
|
745
|
+
for (const stop of stopClientEvents) stop();
|
|
746
|
+
for (const entry of threads.values()) entry.stop();
|
|
747
|
+
signIns.releaseOwner(socket);
|
|
748
|
+
threads.clear();
|
|
749
|
+
opening.clear();
|
|
750
|
+
detachMessage();
|
|
751
|
+
detachClose();
|
|
752
|
+
};
|
|
753
|
+
const stopProvider = client.providers.onChange((statuses) => send({ push: "providers", statuses }));
|
|
754
|
+
const stopClientEvents = DAEX_CLIENT_EVENTS.map(
|
|
755
|
+
(event) => client.on(event, (payload) => send({ push: "client", event, payload }))
|
|
756
|
+
);
|
|
757
|
+
const ensureThread = async (key, rendererOptions) => {
|
|
758
|
+
const existing = threads.get(key)?.thread;
|
|
759
|
+
if (existing) return existing;
|
|
760
|
+
const pending = opening.get(key);
|
|
761
|
+
if (pending) return pending;
|
|
762
|
+
const started = (async () => {
|
|
763
|
+
const summary = await client.threads.get(key);
|
|
764
|
+
const context = { exists: Boolean(summary), summary };
|
|
765
|
+
const resolvedOptions = options.openOptions ? await options.openOptions(key, rendererOptions, context) : rendererOpenOptions(rendererOptions, context.exists);
|
|
766
|
+
const thread = await client.threads.open(key, resolvedOptions);
|
|
767
|
+
const stop = thread.on("event", (envelope) => send({ push: "event", key, envelope }));
|
|
768
|
+
threads.set(key, { thread, stop });
|
|
769
|
+
return thread;
|
|
770
|
+
})().finally(() => opening.delete(key));
|
|
771
|
+
opening.set(key, started);
|
|
772
|
+
return started;
|
|
773
|
+
};
|
|
774
|
+
const requireThread = (key) => {
|
|
775
|
+
if (typeof key !== "string" || !threads.has(key)) {
|
|
776
|
+
throw new DaexError("thread_not_found", "Open the thread through this connection before calling it.");
|
|
777
|
+
}
|
|
778
|
+
return threads.get(key).thread;
|
|
779
|
+
};
|
|
780
|
+
const handlers = {
|
|
781
|
+
"providers.status": () => client.providers.status(),
|
|
782
|
+
"providers.refresh": () => client.providers.refresh(),
|
|
783
|
+
"models.list": () => client.models.list(),
|
|
784
|
+
"doctor": () => client.doctor(),
|
|
785
|
+
"threads.open": async ({ key, options: rendererOptions }) => {
|
|
786
|
+
if (typeof key !== "string" || !key.trim()) throw new DaexError("invalid_option", "threads.open needs a non-empty key.");
|
|
787
|
+
const thread = await ensureThread(key, asParams(rendererOptions));
|
|
788
|
+
return {
|
|
789
|
+
id: thread.id,
|
|
790
|
+
key: thread.key,
|
|
791
|
+
title: thread.title,
|
|
792
|
+
model: thread.model,
|
|
793
|
+
mcpCapability: thread.mcpCapability,
|
|
794
|
+
instructionsCapability: thread.instructionsCapability,
|
|
795
|
+
settingSourcesCapability: thread.settingSourcesCapability,
|
|
796
|
+
permissionCapability: thread.permissionCapability
|
|
797
|
+
};
|
|
798
|
+
},
|
|
799
|
+
"threads.list": async () => {
|
|
800
|
+
const rows = await client.threads.list();
|
|
801
|
+
if (!options.allowThreadKey) return rows;
|
|
802
|
+
const allowed = await Promise.all(rows.map(
|
|
803
|
+
async (row) => row.key && await options.allowThreadKey(row.key, "threads.list", { key: row.key }, socket)
|
|
804
|
+
));
|
|
805
|
+
return rows.filter((_row, index) => allowed[index]);
|
|
806
|
+
},
|
|
807
|
+
"threads.get": async ({ key }) => await client.threads.get(String(key ?? "")),
|
|
808
|
+
"threads.delete": async ({ key }) => {
|
|
809
|
+
await client.threads.delete(String(key ?? ""));
|
|
810
|
+
threads.get(String(key))?.stop();
|
|
811
|
+
threads.delete(String(key));
|
|
812
|
+
return null;
|
|
813
|
+
},
|
|
814
|
+
"threads.archive": async ({ key }) => {
|
|
815
|
+
await client.threads.archive(String(key ?? ""));
|
|
816
|
+
return null;
|
|
817
|
+
},
|
|
818
|
+
"threads.unarchive": async ({ key }) => {
|
|
819
|
+
await client.threads.unarchive(String(key ?? ""));
|
|
820
|
+
return null;
|
|
821
|
+
},
|
|
822
|
+
"thread.export": ({ key }) => client.exportThread(String(key ?? "")),
|
|
823
|
+
"thread.send": async ({ key, text, options: sendOptions }) => {
|
|
824
|
+
await requireThread(key).send(String(text ?? ""), asParams(sendOptions));
|
|
825
|
+
return null;
|
|
826
|
+
},
|
|
827
|
+
"thread.steer": async ({ key, text, options: steerOptions }) => {
|
|
828
|
+
await requireThread(key).steer(String(text ?? ""), asParams(steerOptions));
|
|
829
|
+
return null;
|
|
830
|
+
},
|
|
831
|
+
"thread.interrupt": async ({ key, options: interruptOptions }) => {
|
|
832
|
+
const raw = asParams(interruptOptions);
|
|
833
|
+
await requireThread(key).interrupt({
|
|
834
|
+
...raw.queue === "keep" || raw.queue === "drop" ? { queue: raw.queue } : {},
|
|
835
|
+
...typeof raw.mode === "string" ? { mode: raw.mode } : {}
|
|
836
|
+
});
|
|
837
|
+
return null;
|
|
838
|
+
},
|
|
839
|
+
"thread.setModel": async ({ key, modelId, options: modelOptions }) => await requireThread(key).setModel(String(modelId ?? ""), asParams(modelOptions)),
|
|
840
|
+
"thread.update": async ({ key, patch, options: updateOptions }) => await requireThread(key).update(asParams(patch), asParams(updateOptions)),
|
|
841
|
+
"thread.retry": async ({ key }) => await requireThread(key).retry(),
|
|
842
|
+
"thread.editLast": async ({ key, text, options: editOptions }) => await requireThread(key).editLast(String(text ?? ""), asParams(editOptions)),
|
|
843
|
+
"thread.history": async ({ key, options: historyOptions }) => await requireThread(key).history(asParams(historyOptions)),
|
|
844
|
+
"thread.historyPage": async ({ key, options: historyOptions }) => await requireThread(key).historyPage(asParams(historyOptions)),
|
|
845
|
+
"thread.approve": async ({ key, itemId, decision, responseText }) => await requireThread(key).approve(String(itemId ?? ""), decision, typeof responseText === "string" ? responseText : void 0),
|
|
846
|
+
"thread.pendingApprovals": async ({ key }) => await requireThread(key).pendingApprovals(),
|
|
847
|
+
"thread.usage": ({ key }) => requireThread(key).usage(),
|
|
848
|
+
"thread.updateMcpServers": async ({ key, servers }) => await requireThread(key).updateMcpServers(asParams(servers)),
|
|
849
|
+
"thread.refreshMcpHeaders": async ({ key }) => await requireThread(key).refreshMcpHeaders(),
|
|
850
|
+
"thread.respond": async ({ key, requestId, response }) => {
|
|
851
|
+
await requireThread(key).respond(requireText(requestId, "requestId"), asParams(response));
|
|
852
|
+
return null;
|
|
853
|
+
},
|
|
854
|
+
"thread.queue.list": async ({ key }) => await requireThread(key).queue.list(),
|
|
855
|
+
"thread.queue.cancel": async ({ key, id }) => {
|
|
856
|
+
await requireThread(key).queue.cancel(requireText(id, "id"));
|
|
857
|
+
return null;
|
|
858
|
+
},
|
|
859
|
+
"thread.queue.edit": async ({ key, id, text }) => {
|
|
860
|
+
await requireThread(key).queue.edit(requireText(id, "id"), String(text ?? ""));
|
|
861
|
+
return null;
|
|
862
|
+
},
|
|
863
|
+
"thread.queue.move": async ({ key, id, index }) => {
|
|
864
|
+
if (typeof index !== "number" || !Number.isInteger(index)) throw new DaexError("invalid_option", "index must be an integer.");
|
|
865
|
+
await requireThread(key).queue.move(requireText(id, "id"), index);
|
|
866
|
+
return null;
|
|
867
|
+
},
|
|
868
|
+
"thread.queue.dispatch": async ({ key, id }) => {
|
|
869
|
+
await requireThread(key).queue.dispatch(requireText(id, "id"));
|
|
870
|
+
return null;
|
|
871
|
+
},
|
|
872
|
+
"thread.queue.cancelDispatched": async ({ key, id }) => {
|
|
873
|
+
await requireThread(key).queue.cancelDispatched(requireText(id, "id"));
|
|
874
|
+
return null;
|
|
875
|
+
},
|
|
876
|
+
"thread.queue.restore": async ({ key }) => {
|
|
877
|
+
await requireThread(key).queue.restore();
|
|
878
|
+
return null;
|
|
879
|
+
},
|
|
880
|
+
"thread.stopTask": async ({ key, taskId }) => {
|
|
881
|
+
await requireThread(key).stopTask(requireText(taskId, "taskId"));
|
|
882
|
+
return null;
|
|
883
|
+
},
|
|
884
|
+
"thread.slashCommands": async ({ key }) => await requireThread(key).slashCommands(),
|
|
885
|
+
"thread.recover": async ({ key, options: recoverOptions }) => await requireThread(key).recover(asParams(recoverOptions)),
|
|
886
|
+
"thread.resolveUnprocessed": async ({ key, args }) => await requireThread(key).resolveUnprocessed(asParams(args)),
|
|
887
|
+
"thread.usageLimit.resumeNow": async ({ key }) => await requireThread(key).usageLimit.resumeNow(),
|
|
888
|
+
"thread.usageLimit.continueOnAlternate": async ({ key }) => await requireThread(key).usageLimit.continueOnAlternate(),
|
|
889
|
+
"thread.switchAccount": async ({ key, instanceId }) => await requireThread(key).switchAccount(requireText(instanceId, "instanceId")),
|
|
890
|
+
"providers.capabilities": async ({ provider }) => await client.providers.capabilities(requireText(provider, "provider")),
|
|
891
|
+
"accounts.list": async ({ provider }) => await client.accounts.list(typeof provider === "string" ? provider : void 0),
|
|
892
|
+
"accounts.add": async ({ provider, options: addOptions }) => await client.accounts.add(requireText(provider, "provider"), asParams(addOptions)),
|
|
893
|
+
"accounts.remove": async ({ id }) => await client.accounts.remove(requireText(id, "id")),
|
|
894
|
+
"accounts.rename": async ({ id, label }) => await client.accounts.rename(requireText(id, "id"), requireText(label, "label")),
|
|
895
|
+
"accounts.setDefault": async ({ id }) => await client.accounts.setDefault(requireText(id, "id")),
|
|
896
|
+
"accounts.signOut": async ({ id }) => await client.accounts.signOut(requireText(id, "id")),
|
|
897
|
+
"accounts.refresh": async () => await client.accounts.refresh(),
|
|
898
|
+
"accounts.signIn": async ({ id, options: signInOptions }) => {
|
|
899
|
+
const handle = await client.accounts.signIn(requireText(id, "id"), asParams(signInOptions));
|
|
900
|
+
return await signIns.start(socket, handle);
|
|
901
|
+
},
|
|
902
|
+
"accounts.signInStatus": async ({ loginId }) => await signIns.status(socket, requireText(loginId, "loginId")),
|
|
903
|
+
"accounts.signInSubmitCode": async ({ loginId, code }) => {
|
|
904
|
+
await signIns.submitCode(socket, requireText(loginId, "loginId"), requireText(code, "code"));
|
|
905
|
+
return null;
|
|
906
|
+
},
|
|
907
|
+
"accounts.signInCancel": async ({ loginId }) => {
|
|
908
|
+
await signIns.cancel(socket, requireText(loginId, "loginId"));
|
|
909
|
+
return null;
|
|
910
|
+
},
|
|
911
|
+
"credentials.list": async ({ provider }) => await client.credentials.list(typeof provider === "string" ? provider : void 0),
|
|
912
|
+
"credentials.add": async ({ credential }) => await client.credentials.add(asParams(credential)),
|
|
913
|
+
"credentials.remove": async ({ id, provider }) => await client.credentials.remove(requireText(id, "id"), typeof provider === "string" ? provider : void 0),
|
|
914
|
+
"credentials.verify": async ({ provider }) => await client.credentials.verify(requireText(provider, "provider")),
|
|
915
|
+
"presets.list": async () => await client.presets.list(),
|
|
916
|
+
"presets.add": async ({ preset }) => await client.presets.add(asParams(preset)),
|
|
917
|
+
"presets.update": async ({ id, patch }) => await client.presets.update(requireText(id, "id"), asParams(patch)),
|
|
918
|
+
"presets.remove": async ({ id }) => await client.presets.remove(requireText(id, "id"))
|
|
919
|
+
};
|
|
920
|
+
const dispatch = async (raw) => {
|
|
921
|
+
let request;
|
|
922
|
+
try {
|
|
923
|
+
request = parseMessage(raw);
|
|
924
|
+
} catch {
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
if (!request || typeof request.id !== "string" && typeof request.id !== "number" || typeof request.method !== "string") return;
|
|
928
|
+
const id = request.id;
|
|
929
|
+
if (requestIds.has(id)) {
|
|
930
|
+
send({ id, ok: false, error: serializeAdeError(new DaexError("protocol_error", "Duplicate request id.")) });
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
requestIds.add(id);
|
|
934
|
+
const params = asParams(request.params);
|
|
935
|
+
try {
|
|
936
|
+
if (options.authorize && !await options.authorize(socket, request.method, params)) {
|
|
937
|
+
throw new DaexError("unauthorized", "The host refused " + request.method + ".");
|
|
938
|
+
}
|
|
939
|
+
if (isAccountMethod(request.method)) {
|
|
940
|
+
const gate = options.allowAccountManagement;
|
|
941
|
+
const allowed = typeof gate === "function" ? await gate(socket, request.method, params) : gate === true;
|
|
942
|
+
if (!allowed) throw new DaexError("unauthorized", "The host has not enabled account management over this bridge.");
|
|
943
|
+
}
|
|
944
|
+
if (KEYED_METHODS.has(request.method)) {
|
|
945
|
+
const key = params.key;
|
|
946
|
+
if (typeof key !== "string") throw new DaexError("invalid_option", request.method + " needs a thread key.");
|
|
947
|
+
if (options.allowThreadKey && !await options.allowThreadKey(key, request.method, params, socket)) {
|
|
948
|
+
throw new DaexError("unauthorized", "The host refused thread key " + key + ".");
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
const customHandler = options.methods?.[request.method];
|
|
952
|
+
const handler = handlers[request.method] ?? (customHandler ? (value) => customHandler(value, { socket }) : void 0);
|
|
953
|
+
if (!handler) throw new DaexError("unsupported", "The DAEX server does not expose " + request.method + ".");
|
|
954
|
+
const result = await handler(params);
|
|
955
|
+
send({ id, ok: true, result: result === void 0 ? null : result });
|
|
956
|
+
} catch (error) {
|
|
957
|
+
options.logger?.("ade sdk server: " + request.method + " failed: " + (error instanceof Error ? error.message : String(error)));
|
|
958
|
+
send({ id, ok: false, error: serializeAdeError(error) });
|
|
959
|
+
} finally {
|
|
960
|
+
requestIds.delete(id);
|
|
961
|
+
}
|
|
962
|
+
};
|
|
963
|
+
const detachMessage = listen(socket, "message", (raw) => {
|
|
964
|
+
void dispatch(raw);
|
|
965
|
+
});
|
|
966
|
+
const detachClose = listen(socket, "close", cleanup);
|
|
967
|
+
sockets.add(socket);
|
|
968
|
+
const remove = () => cleanup();
|
|
969
|
+
cleanups.set(socket, remove);
|
|
970
|
+
return remove;
|
|
971
|
+
};
|
|
972
|
+
return {
|
|
973
|
+
handleConnection: attach,
|
|
974
|
+
close: () => {
|
|
975
|
+
if (closed) return;
|
|
976
|
+
closed = true;
|
|
977
|
+
for (const cleanup of [...cleanups.values()]) cleanup();
|
|
978
|
+
sockets.clear();
|
|
979
|
+
cleanups.clear();
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
var createAdeServer = createDaexServer;
|
|
984
|
+
export {
|
|
985
|
+
createAdeRemoteClient,
|
|
986
|
+
createAdeServer,
|
|
987
|
+
createDaexRemoteClient,
|
|
988
|
+
createDaexServer
|
|
989
|
+
};
|