@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.
@@ -0,0 +1,815 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/testing.ts
21
+ var testing_exports = {};
22
+ __export(testing_exports, {
23
+ createMockAdeChat: () => createMockAdeChat,
24
+ createMockDaexChat: () => createMockDaexChat
25
+ });
26
+ module.exports = __toCommonJS(testing_exports);
27
+
28
+ // src/errors.ts
29
+ var ADE_ERROR_CODES = [
30
+ "binary_not_found",
31
+ "download_failed",
32
+ "checksum_mismatch",
33
+ "spawn_failed",
34
+ "connect_failed",
35
+ "handshake_failed",
36
+ "rpc_error",
37
+ "rpc_timeout",
38
+ "transport_closed",
39
+ "protocol_error",
40
+ "thread_not_found",
41
+ "invalid_option",
42
+ "runtime_unavailable",
43
+ "approval_not_found",
44
+ "unauthorized",
45
+ "disposed",
46
+ "runtime_incompatible",
47
+ "turn_in_flight",
48
+ "unsupported",
49
+ "invalid_output",
50
+ "sign_in_failed"
51
+ ];
52
+ var CODE_SET = new Set(ADE_ERROR_CODES);
53
+ var DaexError = class extends Error {
54
+ code;
55
+ cause;
56
+ constructor(code, message, options) {
57
+ super(message);
58
+ this.name = "AdeError";
59
+ this.code = code;
60
+ if (options && "cause" in options) this.cause = options.cause;
61
+ }
62
+ };
63
+
64
+ // src/usage.ts
65
+ function validateThreadBudget(value) {
66
+ if (value === void 0) return void 0;
67
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
68
+ throw new DaexError("invalid_option", "budget must be an object with maxCostUsd and/or maxTokens.");
69
+ }
70
+ const entries = Object.entries(value);
71
+ if (!entries.length) {
72
+ throw new DaexError("invalid_option", "budget must set maxCostUsd, maxTokens, or both.");
73
+ }
74
+ for (const [key, limit] of entries) {
75
+ if (key !== "maxCostUsd" && key !== "maxTokens") {
76
+ throw new DaexError("invalid_option", `budget.${key} is not supported.`);
77
+ }
78
+ if (typeof limit !== "number" || !Number.isFinite(limit) || limit < 0) {
79
+ throw new DaexError("invalid_option", `budget.${key} must be a finite, non-negative number.`);
80
+ }
81
+ }
82
+ return { ...value };
83
+ }
84
+ function finite(value) {
85
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
86
+ }
87
+ function record(value) {
88
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
89
+ }
90
+ var ThreadUsageAccumulator = class {
91
+ seen = /* @__PURE__ */ new Set();
92
+ byTurn = /* @__PURE__ */ new Map();
93
+ completed = { inputTokens: 0, outputTokens: 0, costUsd: 0, hasProviderCost: false };
94
+ codexTotal = null;
95
+ contextWindow;
96
+ observe(envelope) {
97
+ const event = envelope.event;
98
+ const type = typeof event.type === "string" ? event.type : "";
99
+ if (type !== "tokens" && type !== "context_usage" && type !== "codex_token_usage" && type !== "done") return;
100
+ const identity = typeof envelope.sequence === "number" ? `${envelope.sessionId}:${envelope.sequence}` : `${envelope.sessionId}:${envelope.timestamp}:${JSON.stringify(event)}`;
101
+ if (this.seen.has(identity)) return;
102
+ this.seen.add(identity);
103
+ if (this.seen.size > 2e4) this.seen.delete(this.seen.values().next().value);
104
+ const turnId = typeof event.turnId === "string" && event.turnId ? event.turnId : "unscoped";
105
+ if (type === "tokens") {
106
+ const current2 = this.byTurn.get(turnId) ?? { inputTokens: 0, outputTokens: 0 };
107
+ current2.inputTokens = finite(event.inputTokens ?? event.input);
108
+ current2.outputTokens = finite(event.outputTokens ?? event.output);
109
+ this.byTurn.set(turnId, current2);
110
+ const contextWindow2 = finite(event.contextWindow);
111
+ if (contextWindow2) this.contextWindow = Math.max(this.contextWindow ?? 0, contextWindow2);
112
+ return;
113
+ }
114
+ if (type === "context_usage") {
115
+ const usage2 = record(event.usage);
116
+ const contextWindow2 = finite(usage2?.maxTokens);
117
+ if (contextWindow2) this.contextWindow = Math.max(this.contextWindow ?? 0, contextWindow2);
118
+ return;
119
+ }
120
+ if (type === "codex_token_usage") {
121
+ const usage2 = record(event.usage);
122
+ const total = record(usage2?.total);
123
+ if (!total) return;
124
+ this.codexTotal = {
125
+ inputTokens: Math.max(this.codexTotal?.inputTokens ?? 0, finite(total.inputTokens)),
126
+ outputTokens: Math.max(this.codexTotal?.outputTokens ?? 0, finite(total.outputTokens))
127
+ };
128
+ const contextWindow2 = finite(usage2?.modelContextWindow);
129
+ if (contextWindow2) this.contextWindow = Math.max(this.contextWindow ?? 0, contextWindow2);
130
+ return;
131
+ }
132
+ const current = this.byTurn.get(turnId) ?? { inputTokens: 0, outputTokens: 0 };
133
+ const usage = record(event.usage);
134
+ if (usage?.inputTokens !== void 0 && usage.inputTokens !== null) current.inputTokens = finite(usage.inputTokens);
135
+ if (usage?.outputTokens !== void 0 && usage.outputTokens !== null) current.outputTokens = finite(usage.outputTokens);
136
+ if (event.costSource === "provider") {
137
+ const costUsd = typeof event.costUsd === "number" && Number.isFinite(event.costUsd) && event.costUsd >= 0 ? event.costUsd : void 0;
138
+ if (costUsd !== void 0) current.costUsd = costUsd;
139
+ }
140
+ const contextWindow = finite(usage?.contextWindow);
141
+ if (contextWindow) this.contextWindow = Math.max(this.contextWindow ?? 0, contextWindow);
142
+ this.byTurn.set(turnId, current);
143
+ if (event.type === "done") {
144
+ this.completed.inputTokens += current.inputTokens;
145
+ this.completed.outputTokens += current.outputTokens;
146
+ if (current.costUsd !== void 0) {
147
+ this.completed.costUsd += current.costUsd;
148
+ this.completed.hasProviderCost = true;
149
+ }
150
+ this.byTurn.delete(turnId);
151
+ }
152
+ }
153
+ seed(envelopes) {
154
+ for (const envelope of envelopes) this.observe(envelope);
155
+ }
156
+ snapshot() {
157
+ let inputTokens = this.completed.inputTokens;
158
+ let outputTokens = this.completed.outputTokens;
159
+ let costUsd = this.completed.costUsd;
160
+ let hasProviderCost = this.completed.hasProviderCost;
161
+ for (const turn of this.byTurn.values()) {
162
+ inputTokens += turn.inputTokens;
163
+ outputTokens += turn.outputTokens;
164
+ if (turn.costUsd !== void 0) {
165
+ costUsd += turn.costUsd;
166
+ hasProviderCost = true;
167
+ }
168
+ }
169
+ if (this.codexTotal) {
170
+ inputTokens = Math.max(inputTokens, this.codexTotal.inputTokens);
171
+ outputTokens = Math.max(outputTokens, this.codexTotal.outputTokens);
172
+ }
173
+ return {
174
+ inputTokens,
175
+ outputTokens,
176
+ totalTokens: inputTokens + outputTokens,
177
+ ...this.contextWindow !== void 0 ? { contextWindow: this.contextWindow } : {},
178
+ ...hasProviderCost ? { costUsd } : {}
179
+ };
180
+ }
181
+ };
182
+ function budgetExceeded(budget, usage) {
183
+ return Boolean(
184
+ budget && (budget.maxTokens !== void 0 && usage.totalTokens >= budget.maxTokens || budget.maxCostUsd !== void 0 && usage.costUsd !== void 0 && usage.costUsd >= budget.maxCostUsd)
185
+ );
186
+ }
187
+
188
+ // src/run.ts
189
+ var import_node_crypto = require("crypto");
190
+ var DEFAULT_RUN_TIMEOUT_MS = 10 * 6e4;
191
+ var WAITS_FOR_AN_ANSWER = /* @__PURE__ */ new Set(["approval_request", "structured_question"]);
192
+ var InvalidOutputError = class extends DaexError {
193
+ rawText;
194
+ constructor(rawText, reason) {
195
+ super("invalid_output", `The model returned output that did not match the requested schema: ${reason}`);
196
+ this.rawText = rawText;
197
+ }
198
+ };
199
+ var SUPPORTED_SCHEMA_KEYS = /* @__PURE__ */ new Set([
200
+ "type",
201
+ "properties",
202
+ "required",
203
+ "items",
204
+ "enum",
205
+ "additionalProperties",
206
+ "title",
207
+ "description",
208
+ "$schema",
209
+ "$id",
210
+ "default",
211
+ "examples"
212
+ ]);
213
+ function isRecord(value) {
214
+ return value !== null && typeof value === "object" && !Array.isArray(value);
215
+ }
216
+ function canonicalJson(value) {
217
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
218
+ if (isRecord(value)) {
219
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
220
+ }
221
+ return JSON.stringify(value);
222
+ }
223
+ function validateSchemaShape(schema, path = "$schema") {
224
+ if (!isRecord(schema)) throw new DaexError("invalid_option", `${path} must be an object.`);
225
+ for (const key of Object.keys(schema)) {
226
+ if (!SUPPORTED_SCHEMA_KEYS.has(key)) {
227
+ throw new DaexError("invalid_option", `${path}.${key} is outside the SDK's supported JSON Schema subset.`);
228
+ }
229
+ }
230
+ if (schema.type !== void 0 && !["object", "array", "string", "number", "integer", "boolean", "null"].includes(schema.type)) {
231
+ throw new DaexError("invalid_option", `${path}.type is not supported.`);
232
+ }
233
+ if (schema.properties !== void 0) {
234
+ if (!isRecord(schema.properties)) throw new DaexError("invalid_option", `${path}.properties must be an object.`);
235
+ for (const [key, child] of Object.entries(schema.properties)) validateSchemaShape(child, `${path}.properties.${key}`);
236
+ }
237
+ if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) {
238
+ throw new DaexError("invalid_option", `${path}.required must be an array of property names.`);
239
+ }
240
+ if (schema.items !== void 0) validateSchemaShape(schema.items, `${path}.items`);
241
+ if (schema.enum !== void 0 && !Array.isArray(schema.enum)) {
242
+ throw new DaexError("invalid_option", `${path}.enum must be an array.`);
243
+ }
244
+ if (schema.additionalProperties !== void 0 && typeof schema.additionalProperties !== "boolean") {
245
+ validateSchemaShape(schema.additionalProperties, `${path}.additionalProperties`);
246
+ }
247
+ }
248
+ function matchesType(value, type) {
249
+ switch (type) {
250
+ case "object":
251
+ return isRecord(value);
252
+ case "array":
253
+ return Array.isArray(value);
254
+ case "string":
255
+ return typeof value === "string";
256
+ case "number":
257
+ return typeof value === "number" && Number.isFinite(value);
258
+ case "integer":
259
+ return typeof value === "number" && Number.isInteger(value);
260
+ case "boolean":
261
+ return typeof value === "boolean";
262
+ case "null":
263
+ return value === null;
264
+ }
265
+ }
266
+ function validateJsonSchema(value, schema, path = "$", errors = []) {
267
+ if (schema.type && !matchesType(value, schema.type)) errors.push(`${path} must be ${schema.type}`);
268
+ if (schema.enum && !schema.enum.some((entry) => canonicalJson(entry) === canonicalJson(value))) {
269
+ errors.push(`${path} must match one of the enum values`);
270
+ }
271
+ if (Array.isArray(value) && schema.items) {
272
+ value.forEach((entry, index) => validateJsonSchema(entry, schema.items, `${path}[${index}]`, errors));
273
+ }
274
+ if (isRecord(value)) {
275
+ for (const key of schema.required ?? []) {
276
+ if (!(key in value)) errors.push(`${path}.${key} is required`);
277
+ }
278
+ for (const [key, entry] of Object.entries(value)) {
279
+ const propertySchema = schema.properties?.[key];
280
+ if (propertySchema) validateJsonSchema(entry, propertySchema, `${path}.${key}`, errors);
281
+ else if (schema.additionalProperties === false) errors.push(`${path}.${key} is not allowed`);
282
+ else if (isRecord(schema.additionalProperties)) {
283
+ validateJsonSchema(entry, schema.additionalProperties, `${path}.${key}`, errors);
284
+ }
285
+ }
286
+ }
287
+ return errors;
288
+ }
289
+ function appendSchemaInstructions(options) {
290
+ const { schema, provider, model, budget, timeoutMs: _timeoutMs, ...openOptions } = options;
291
+ if (!schema) return { ...openOptions, provider, model, ...budget ? { budget } : {} };
292
+ const existing = openOptions.instructions;
293
+ const existingText = typeof existing === "string" ? existing : existing?.text;
294
+ const mode = typeof existing === "object" && existing !== null ? existing.mode : "append";
295
+ const instruction = [
296
+ existingText,
297
+ "Return only a JSON value that validates against this JSON Schema. Do not use a Markdown code block.",
298
+ JSON.stringify(schema)
299
+ ].filter(Boolean).join("\n\n");
300
+ return {
301
+ ...openOptions,
302
+ instructions: { mode, text: instruction },
303
+ provider,
304
+ model,
305
+ ...budget ? { budget } : {}
306
+ };
307
+ }
308
+ async function runTurn(thread, prompt, timeoutMs) {
309
+ return await new Promise((resolve, reject) => {
310
+ let output = "";
311
+ let errorMessage = null;
312
+ let settled = false;
313
+ let stop;
314
+ const abandon = (error) => {
315
+ finish(error);
316
+ void thread.interrupt().catch(() => {
317
+ });
318
+ };
319
+ const timer = setTimeout(() => {
320
+ abandon(new DaexError("rpc_timeout", `client.run() gave up after ${timeoutMs} ms; pass a larger timeoutMs for long tasks.`));
321
+ }, timeoutMs);
322
+ const finish = (error) => {
323
+ if (settled) return;
324
+ settled = true;
325
+ clearTimeout(timer);
326
+ stop?.();
327
+ if (error) reject(error);
328
+ else resolve(output);
329
+ };
330
+ stop = thread.on("event", (envelope) => {
331
+ const event = envelope.event;
332
+ if (WAITS_FOR_AN_ANSWER.has(event.type)) {
333
+ abandon(new DaexError(
334
+ "unsupported",
335
+ 'client.run() cannot answer approvals or questions. Give it permissions that need none (for example permissions: "always-allow" with a sandboxed cwd), or use a thread.'
336
+ ));
337
+ return;
338
+ }
339
+ if (event.type === "text" && typeof event.text === "string") output += event.text;
340
+ if (event.type === "error" && typeof event.message === "string") errorMessage = event.message;
341
+ if (event.type === "done") {
342
+ if (errorMessage) finish(new DaexError("rpc_error", errorMessage));
343
+ else finish();
344
+ } else if (event.type === "status" && event.synthetic === true && event.turnStatus === "failed") {
345
+ finish(new DaexError("runtime_unavailable", typeof event.message === "string" ? event.message : "The runtime stopped during client.run()."));
346
+ }
347
+ });
348
+ void thread.send(prompt).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
349
+ });
350
+ }
351
+ async function runOnce(client, prompt, options) {
352
+ if (typeof prompt !== "string" || !prompt.trim()) throw new DaexError("invalid_option", "client.run() needs a non-empty prompt.");
353
+ if (typeof options.model !== "string" || !options.model.trim()) throw new DaexError("invalid_option", "client.run() needs a model id.");
354
+ if (options.schema) validateSchemaShape(options.schema);
355
+ const timeoutMs = options.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;
356
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
357
+ throw new DaexError("invalid_option", "client.run() timeoutMs must be a positive number of milliseconds.");
358
+ }
359
+ const key = `__ade_run_${(0, import_node_crypto.randomUUID)()}`;
360
+ const thread = await client.threads.open(key, appendSchemaInstructions(options));
361
+ try {
362
+ let rawText = await runTurn(thread, prompt, timeoutMs);
363
+ if (!options.schema) return rawText;
364
+ for (let attempt = 0; attempt < 2; attempt += 1) {
365
+ try {
366
+ const parsed = JSON.parse(withoutCodeFence(rawText));
367
+ const errors = validateJsonSchema(parsed, options.schema);
368
+ if (!errors.length) return parsed;
369
+ if (attempt === 1) throw new InvalidOutputError(rawText, errors.join("; "));
370
+ rawText = await runTurn(
371
+ thread,
372
+ `Your previous response did not match the requested JSON Schema: ${errors.join("; ")}. Try once more and return only the corrected JSON value.`,
373
+ timeoutMs
374
+ );
375
+ } catch (error) {
376
+ if (error instanceof InvalidOutputError) throw error;
377
+ if (error instanceof SyntaxError) {
378
+ if (attempt === 1) throw new InvalidOutputError(rawText, "the output was not valid JSON");
379
+ rawText = await runTurn(thread, "Your previous response was not valid JSON. Try once more and return only a corrected JSON value.", timeoutMs);
380
+ continue;
381
+ }
382
+ throw error;
383
+ }
384
+ }
385
+ throw new InvalidOutputError(rawText, "the output could not be validated");
386
+ } finally {
387
+ await client.threads.delete(key).catch(() => {
388
+ });
389
+ }
390
+ }
391
+ function withoutCodeFence(text) {
392
+ const trimmed = text.trim();
393
+ const fenced = /^```[a-zA-Z0-9_-]*\s*\n([\s\S]*?)\n?```$/.exec(trimmed);
394
+ return fenced ? fenced[1].trim() : trimmed;
395
+ }
396
+
397
+ // src/testing.ts
398
+ var USAGE = /* @__PURE__ */ new Set(["tokens", "context_usage", "codex_token_usage"]);
399
+ var STATUS = /* @__PURE__ */ new Set(["status", "done", "error", "turn_health", "session_meta_updated", "interrupt_receipt", "capabilities_changed", "budget_exceeded"]);
400
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
401
+ function createMockDaexChat() {
402
+ const responses = [];
403
+ const usageQueue = [];
404
+ const threads = /* @__PURE__ */ new Map();
405
+ const providerListeners = /* @__PURE__ */ new Set();
406
+ const modelListeners = /* @__PURE__ */ new Set();
407
+ const clientListeners = /* @__PURE__ */ new Map();
408
+ let nextSession = 1;
409
+ let accounts = [];
410
+ let slashCommands = [];
411
+ const capabilities = /* @__PURE__ */ new Map();
412
+ let disposed = false;
413
+ const assertUsable = () => {
414
+ if (disposed) throw new DaexError("disposed", "This mock DAEX chat client was disposed.");
415
+ };
416
+ const emitClient = (event, payload) => {
417
+ for (const listener of [...clientListeners.get(event) ?? []]) listener(payload);
418
+ };
419
+ class MockThread {
420
+ constructor(key, options = {}) {
421
+ this.key = key;
422
+ this.provider = options.provider ?? "claude";
423
+ this.currentTitle = typeof options.title === "string" ? options.title : null;
424
+ this.currentModel = typeof options.model === "string" ? { modelId: options.model, displayName: options.model, provider: this.provider, model: options.model } : null;
425
+ this.budget = validateThreadBudget(options.budget);
426
+ }
427
+ key;
428
+ id = "mock-session-" + nextSession++;
429
+ currentTitle;
430
+ currentModel;
431
+ mcpCapability = null;
432
+ instructionsCapability = null;
433
+ settingSourcesCapability = null;
434
+ permissionCapability = null;
435
+ listeners = /* @__PURE__ */ new Map();
436
+ envelopes = [];
437
+ pending = /* @__PURE__ */ new Map();
438
+ queued = [];
439
+ nextQueued = 1;
440
+ usageTotals = new ThreadUsageAccumulator();
441
+ sequence = 0;
442
+ turn = 0;
443
+ active = false;
444
+ budgetStopped = false;
445
+ archived = false;
446
+ budget;
447
+ provider;
448
+ get title() {
449
+ return this.currentTitle;
450
+ }
451
+ get model() {
452
+ return this.currentModel;
453
+ }
454
+ makeEnvelope(event) {
455
+ return { sessionId: this.id, timestamp: now(), sequence: ++this.sequence, event };
456
+ }
457
+ emit(event, recorded) {
458
+ const envelope = recorded ?? this.makeEnvelope(event);
459
+ this.envelopes.push(envelope);
460
+ this.usageTotals.observe(envelope);
461
+ for (const [channel, listeners] of this.listeners) {
462
+ const type = envelope.event.type;
463
+ if (channel === "usage" && !USAGE.has(type)) continue;
464
+ if (channel === "status" && !STATUS.has(type)) continue;
465
+ for (const listener of [...listeners]) listener(envelope);
466
+ }
467
+ if (!this.budgetStopped && budgetExceeded(this.budget, this.usageTotals.snapshot())) {
468
+ this.budgetStopped = true;
469
+ this.emit({
470
+ type: "budget_exceeded",
471
+ budget: this.budget,
472
+ usage: { ...this.usageTotals.snapshot(), complete: true },
473
+ turnId: "mock-turn-" + this.turn
474
+ });
475
+ this.finish("interrupted");
476
+ }
477
+ }
478
+ finish(status) {
479
+ if (!this.active) return;
480
+ this.active = false;
481
+ this.emit({ type: "status", turnStatus: status, turnId: "mock-turn-" + this.turn });
482
+ this.emit({ type: "done", status, turnId: "mock-turn-" + this.turn });
483
+ }
484
+ async dispatch(text, _options = {}) {
485
+ assertUsable();
486
+ if (this.budgetStopped) throw new DaexError("invalid_option", "The mock thread exceeded its usage budget.");
487
+ this.turn += 1;
488
+ this.active = true;
489
+ this.emit({ type: "user_message", text, turnId: "mock-turn-" + this.turn });
490
+ this.emit({ type: "status", turnStatus: "started", turnId: "mock-turn-" + this.turn });
491
+ for (const event of usageQueue.splice(0)) {
492
+ this.emit({ ...event, turnId: event.turnId ?? "mock-turn-" + this.turn });
493
+ if (this.budgetStopped) return;
494
+ }
495
+ const response = responses.shift() ?? { kind: "reply", text: "Mock reply" };
496
+ switch (response.kind) {
497
+ case "reply":
498
+ this.emit({ type: "text", text: response.text, turnId: "mock-turn-" + this.turn });
499
+ this.finish("completed");
500
+ return;
501
+ case "tool_call": {
502
+ const itemId = "mock-tool-" + this.turn;
503
+ this.emit({ type: "tool_call", tool: response.tool, args: response.args, itemId, turnId: "mock-turn-" + this.turn });
504
+ this.emit({ type: "tool_result", tool: response.tool, result: response.result, itemId, status: "completed", turnId: "mock-turn-" + this.turn });
505
+ this.finish("completed");
506
+ return;
507
+ }
508
+ case "approval": {
509
+ const itemId = response.request.itemId ?? "mock-approval-" + this.turn;
510
+ const request = {
511
+ ...response.request,
512
+ itemId,
513
+ kind: response.request.kind ?? "command",
514
+ description: response.request.description ?? "Mock approval request",
515
+ provider: response.request.provider ?? this.provider
516
+ };
517
+ this.pending.set(itemId, request);
518
+ this.emit({ type: "approval_request", itemId, kind: request.kind, description: request.description, requestKind: request.requestKind, turnId: "mock-turn-" + this.turn });
519
+ return;
520
+ }
521
+ case "error":
522
+ this.emit({ type: "error", message: response.message, turnId: "mock-turn-" + this.turn });
523
+ this.finish("failed");
524
+ }
525
+ }
526
+ async send(text, options) {
527
+ await this.dispatch(text, options);
528
+ }
529
+ async steer(text, options) {
530
+ if (this.active) {
531
+ this.queued.push({ id: "mock-steer-" + this.nextQueued++, text, ...options?.attachments ? { attachments: options.attachments } : {} });
532
+ return;
533
+ }
534
+ await this.dispatch(text, options);
535
+ }
536
+ async interrupt(options) {
537
+ if (options?.queue === "drop") this.queued.length = 0;
538
+ this.finish("interrupted");
539
+ }
540
+ async respond(requestId, response) {
541
+ if (!this.pending.has(requestId)) throw new DaexError("approval_not_found", "No pending mock request " + requestId + ".");
542
+ this.pending.delete(requestId);
543
+ const declined = response.decision === "decline" || response.decision === "cancel";
544
+ this.emit({ type: "pending_input_resolved", itemId: requestId, resolution: declined ? "declined" : "accepted", turnId: "mock-turn-" + this.turn });
545
+ this.finish("completed");
546
+ }
547
+ queuedIndex(id) {
548
+ const index = this.queued.findIndex((item) => item.id === id);
549
+ if (index < 0) throw new DaexError("invalid_option", "No queued mock message " + id + ".");
550
+ return index;
551
+ }
552
+ queue = {
553
+ list: async () => this.queued.map((item) => ({ ...item })),
554
+ cancel: async (id) => {
555
+ this.queued.splice(this.queuedIndex(id), 1);
556
+ },
557
+ edit: async (id, text) => {
558
+ this.queued[this.queuedIndex(id)].text = text;
559
+ },
560
+ move: async (id, index) => {
561
+ const [item] = this.queued.splice(this.queuedIndex(id), 1);
562
+ this.queued.splice(Math.max(0, Math.min(index, this.queued.length)), 0, item);
563
+ },
564
+ dispatch: async (id) => {
565
+ const [item] = this.queued.splice(this.queuedIndex(id), 1);
566
+ this.finish("interrupted");
567
+ await this.dispatch(item.text);
568
+ },
569
+ cancelDispatched: async (_id) => {
570
+ },
571
+ restore: async () => {
572
+ }
573
+ };
574
+ async stopTask(_taskId) {
575
+ }
576
+ async slashCommands() {
577
+ return slashCommands.map((command) => ({ ...command }));
578
+ }
579
+ async recover(options = {}) {
580
+ return { action: options.action ?? "wait", turnId: options.turnId ?? "mock-turn-" + this.turn, status: "waiting" };
581
+ }
582
+ async resolveUnprocessed(args) {
583
+ return { steerId: args.steerId, action: args.action, status: "completed" };
584
+ }
585
+ usageLimit = {
586
+ resumeNow: async () => ({ ok: true, turnId: null }),
587
+ continueOnAlternate: async () => ({ ok: false, reason: "no_alternate", message: "The mock client has no alternate account." })
588
+ };
589
+ async switchAccount(instanceId) {
590
+ if (!accounts.some((account) => account.id === instanceId)) {
591
+ return { ok: false, reason: "signed_out", message: "No mock account " + instanceId + "." };
592
+ }
593
+ return { ok: true, instanceId };
594
+ }
595
+ async update(patch, _options) {
596
+ if (Object.hasOwn(patch, "title")) this.currentTitle = patch.title ?? null;
597
+ return { title: this.currentTitle, model: this.currentModel };
598
+ }
599
+ async updateMcpServers(_servers) {
600
+ return null;
601
+ }
602
+ async refreshMcpHeaders() {
603
+ return null;
604
+ }
605
+ async setModel(modelId) {
606
+ this.currentModel = { modelId, provider: this.provider, model: modelId, displayName: modelId };
607
+ return {
608
+ ...this.currentModel,
609
+ capabilities: {
610
+ mcpCapability: null,
611
+ permissionCapability: null,
612
+ instructionsCapability: null,
613
+ settingSourcesCapability: null
614
+ }
615
+ };
616
+ }
617
+ async retry() {
618
+ await this.dispatch("Mock retry");
619
+ return { retractedFromSequence: this.sequence, historyGeneration: 1, conversationRollback: "not_delivered" };
620
+ }
621
+ async editLast(text, _options) {
622
+ await this.dispatch(text);
623
+ return { retractedFromSequence: this.sequence, historyGeneration: 1, conversationRollback: "not_delivered" };
624
+ }
625
+ async history(options = {}) {
626
+ return options.limit ? this.envelopes.slice(-options.limit) : [...this.envelopes];
627
+ }
628
+ async historyPage(options = {}) {
629
+ const before = options.beforeSequence ?? Number.POSITIVE_INFINITY;
630
+ const older = this.envelopes.filter((envelope) => (envelope.sequence ?? 0) < before);
631
+ const limit = options.limit ?? 100;
632
+ const events = older.slice(-limit);
633
+ return { events, hasMore: older.length > events.length, nextBeforeSequence: events[0]?.sequence ?? null };
634
+ }
635
+ async approve(itemId, _decision) {
636
+ if (!this.pending.has(itemId)) throw new DaexError("approval_not_found", "No pending mock approval " + itemId + ".");
637
+ this.pending.delete(itemId);
638
+ this.emit({ type: "pending_input_resolved", itemId, resolution: "accepted", turnId: "mock-turn-" + this.turn });
639
+ this.finish("completed");
640
+ }
641
+ async pendingApprovals() {
642
+ return [...this.pending.values()];
643
+ }
644
+ on(channel, listener) {
645
+ let listeners = this.listeners.get(channel);
646
+ if (!listeners) this.listeners.set(channel, listeners = /* @__PURE__ */ new Set());
647
+ listeners.add(listener);
648
+ return () => listeners?.delete(listener);
649
+ }
650
+ usage() {
651
+ return { ...this.usageTotals.snapshot(), complete: true };
652
+ }
653
+ seed(envelopes) {
654
+ for (const envelope of envelopes) {
655
+ this.envelopes.push(envelope);
656
+ this.usageTotals.observe(envelope);
657
+ for (const listeners of this.listeners.values()) for (const listener of [...listeners]) listener(envelope);
658
+ }
659
+ if (budgetExceeded(this.budget, this.usageTotals.snapshot())) this.budgetStopped = true;
660
+ }
661
+ setArchived(archived) {
662
+ this.archived = archived;
663
+ }
664
+ get summary() {
665
+ const timestamp = this.envelopes.at(-1)?.timestamp ?? now();
666
+ return {
667
+ key: this.key,
668
+ sessionId: this.id,
669
+ provider: this.currentModel?.provider ?? this.provider,
670
+ model: this.currentModel?.modelId ?? "mock-model",
671
+ title: this.title,
672
+ status: this.active ? "active" : "idle",
673
+ startedAt: this.envelopes[0]?.timestamp ?? timestamp,
674
+ lastActivityAt: timestamp,
675
+ updatedAt: timestamp,
676
+ archived: this.archived,
677
+ modelSelection: this.currentModel
678
+ };
679
+ }
680
+ }
681
+ const unsupported = (what) => async () => {
682
+ throw new DaexError("unsupported", "The mock client does not " + what + ".");
683
+ };
684
+ const client = {
685
+ providers: {
686
+ status: async () => ({}),
687
+ refresh: async () => ({}),
688
+ onChange: (listener) => {
689
+ providerListeners.add(listener);
690
+ return () => providerListeners.delete(listener);
691
+ },
692
+ capabilities: async (provider) => {
693
+ const value = capabilities.get(provider);
694
+ if (!value) throw new DaexError("unsupported", "No mock capability record for provider " + provider + "; set one with setCapabilities().");
695
+ return value;
696
+ }
697
+ },
698
+ accounts: {
699
+ list: async (provider) => accounts.filter((account) => !provider || account.provider === provider).map((account) => ({ ...account })),
700
+ add: unsupported("add accounts; seed them with setAccounts()"),
701
+ remove: unsupported("remove accounts"),
702
+ rename: unsupported("rename accounts"),
703
+ setDefault: unsupported("change the default account"),
704
+ signOut: unsupported("sign accounts out"),
705
+ refresh: async () => accounts.map((account) => ({ ...account })),
706
+ signIn: unsupported("run provider sign-ins")
707
+ },
708
+ credentials: {
709
+ list: async () => [],
710
+ add: unsupported("store credentials"),
711
+ remove: unsupported("remove credentials"),
712
+ verify: unsupported("verify credentials")
713
+ },
714
+ presets: {
715
+ list: async () => [],
716
+ add: unsupported("add presets"),
717
+ update: unsupported("update presets"),
718
+ remove: unsupported("remove presets")
719
+ },
720
+ models: {
721
+ list: async () => [],
722
+ onChange: (listener) => {
723
+ modelListeners.add(listener);
724
+ return () => modelListeners.delete(listener);
725
+ },
726
+ defaultModel: async () => null
727
+ },
728
+ threads: {
729
+ open: async (key, options = {}) => {
730
+ assertUsable();
731
+ const existing = threads.get(key);
732
+ if (existing) return existing;
733
+ const thread = new MockThread(key, options);
734
+ threads.set(key, thread);
735
+ return thread;
736
+ },
737
+ list: async () => [...threads.values()].map((thread) => thread.summary),
738
+ get: async (key) => threads.get(key)?.summary ?? null,
739
+ delete: async (key) => {
740
+ if (!threads.delete(key)) throw new DaexError("thread_not_found", "No mock thread is registered under " + key + ".");
741
+ emitClient("threadLifecycle", { key, change: "deleted" });
742
+ },
743
+ archive: async (key) => {
744
+ const thread = threads.get(key);
745
+ if (!thread) throw new DaexError("thread_not_found", "No mock thread is registered under " + key + ".");
746
+ thread.setArchived(true);
747
+ emitClient("threadLifecycle", { key, change: "archived" });
748
+ },
749
+ unarchive: async (key) => {
750
+ const thread = threads.get(key);
751
+ if (!thread) throw new DaexError("thread_not_found", "No mock thread is registered under " + key + ".");
752
+ thread.setArchived(false);
753
+ emitClient("threadLifecycle", { key, change: "unarchived" });
754
+ }
755
+ },
756
+ on: (event, listener) => {
757
+ const key = String(event);
758
+ let listeners = clientListeners.get(key);
759
+ if (!listeners) clientListeners.set(key, listeners = /* @__PURE__ */ new Set());
760
+ const callback = listener;
761
+ listeners.add(callback);
762
+ return () => listeners?.delete(callback);
763
+ },
764
+ doctor: async () => ({ ok: true }),
765
+ exportThread: async (key) => (await threads.get(key)?.history() ?? []).map((event) => JSON.stringify(event)).join("\n"),
766
+ dispose: async () => {
767
+ disposed = true;
768
+ threads.clear();
769
+ providerListeners.clear();
770
+ modelListeners.clear();
771
+ },
772
+ run: (prompt, options) => runOnce({
773
+ threads: {
774
+ open: (key, openOptions) => client.threads.open(key, openOptions),
775
+ delete: (key) => client.threads.delete(key)
776
+ }
777
+ }, prompt, options),
778
+ setAccounts: (next) => {
779
+ accounts = next.map((account) => ({ ...account }));
780
+ },
781
+ setCapabilities: (provider, value) => {
782
+ capabilities.set(provider, value);
783
+ },
784
+ setSlashCommands: (next) => {
785
+ slashCommands = next.map((command) => ({ ...command }));
786
+ },
787
+ queueReply: (text) => {
788
+ responses.push({ kind: "reply", text });
789
+ },
790
+ queueToolCall: (call) => {
791
+ responses.push({ kind: "tool_call", tool: call.tool, args: call.args, result: call.result ?? null });
792
+ },
793
+ queueApproval: (request = {}) => {
794
+ responses.push({ kind: "approval", request });
795
+ },
796
+ queueError: (error) => {
797
+ responses.push({ kind: "error", message: error instanceof Error ? error.message : error });
798
+ },
799
+ queueUsage: (event) => {
800
+ usageQueue.push(event);
801
+ },
802
+ replay: async (envelopes, key = "replay") => {
803
+ const thread = await client.threads.open(key, { provider: "claude", model: "mock-model" });
804
+ threads.get(key).seed(envelopes);
805
+ return thread;
806
+ }
807
+ };
808
+ return client;
809
+ }
810
+ var createMockAdeChat = createMockDaexChat;
811
+ // Annotate the CommonJS export names for ESM import in node:
812
+ 0 && (module.exports = {
813
+ createMockAdeChat,
814
+ createMockDaexChat
815
+ });