@daex-dev/sdk 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +478 -2
  3. package/dist/client-DVZHOtg6.d.cts +2635 -0
  4. package/dist/client-DVZHOtg6.d.ts +2635 -0
  5. package/dist/connect/browser.cjs +209 -0
  6. package/dist/connect/browser.d.cts +81 -0
  7. package/dist/connect/browser.d.ts +81 -0
  8. package/dist/connect/browser.js +183 -0
  9. package/dist/connect/index.cjs +1954 -0
  10. package/dist/connect/index.d.cts +433 -0
  11. package/dist/connect/index.d.ts +433 -0
  12. package/dist/connect/index.js +1888 -0
  13. package/dist/electron/global.cjs +18 -0
  14. package/dist/electron/global.d.cts +35 -0
  15. package/dist/electron/global.d.ts +35 -0
  16. package/dist/electron/global.js +0 -0
  17. package/dist/electron/index.cjs +1133 -0
  18. package/dist/electron/index.d.cts +510 -0
  19. package/dist/electron/index.d.ts +510 -0
  20. package/dist/electron/index.js +1073 -0
  21. package/dist/electron/preload-auto.cjs +38 -0
  22. package/dist/electron/preload.cjs +66 -0
  23. package/dist/electron/preload.d.cts +46 -0
  24. package/dist/electron/preload.d.ts +46 -0
  25. package/dist/electron/preload.js +43 -0
  26. package/dist/electron/protocol-DXRtliy3.d.cts +904 -0
  27. package/dist/electron/protocol-DXRtliy3.d.ts +904 -0
  28. package/dist/electron/renderer.cjs +631 -0
  29. package/dist/electron/renderer.d.cts +508 -0
  30. package/dist/electron/renderer.d.ts +508 -0
  31. package/dist/electron/renderer.global.js +634 -0
  32. package/dist/electron/renderer.js +608 -0
  33. package/dist/index.cjs +6731 -0
  34. package/dist/index.d.cts +316 -0
  35. package/dist/index.d.ts +316 -0
  36. package/dist/index.js +6661 -0
  37. package/dist/server.cjs +1019 -0
  38. package/dist/server.d.cts +118 -0
  39. package/dist/server.d.ts +118 -0
  40. package/dist/server.js +989 -0
  41. package/dist/testing.cjs +815 -0
  42. package/dist/testing.d.cts +29 -0
  43. package/dist/testing.d.ts +29 -0
  44. package/dist/testing.js +787 -0
  45. package/dist/types-DUGv-9QF.d.cts +166 -0
  46. package/dist/types-DUGv-9QF.d.ts +166 -0
  47. package/package.json +109 -4
@@ -0,0 +1,2635 @@
1
+ type AccountUsage = {
2
+ state: "ok" | "stale" | "expired" | "signed_out" | "no_reading" | "error";
3
+ readAt: string | null;
4
+ note: string | null;
5
+ windows: Array<{
6
+ type: string;
7
+ label: string;
8
+ percentLeft: number;
9
+ resetsAt: string | null;
10
+ unlimited?: true;
11
+ countLeft?: number;
12
+ countTotal?: number;
13
+ }>;
14
+ };
15
+ type AccountInfo = {
16
+ id: string;
17
+ provider: string;
18
+ label: string;
19
+ email?: string;
20
+ plan?: string;
21
+ signedIn: boolean;
22
+ isDefault: boolean;
23
+ loginBroken?: boolean;
24
+ accentColor?: string;
25
+ createdAt?: string;
26
+ usage?: AccountUsage;
27
+ };
28
+ type ApiCredentialInfo = {
29
+ provider: string;
30
+ credentialId: string;
31
+ label: string;
32
+ envVar?: string;
33
+ baseUrl?: string;
34
+ protocol?: "openai-compatible" | "openai-responses" | "anthropic";
35
+ models?: string[];
36
+ source: "store" | "env" | "config";
37
+ createdAt: string;
38
+ updatedAt: string;
39
+ maskedTail?: string;
40
+ };
41
+ type SignInStatus = {
42
+ loginId: string;
43
+ instanceId: string;
44
+ provider: string;
45
+ state: "running" | "verifying" | "succeeded" | "failed" | "cancelled" | "expired";
46
+ url: string | null;
47
+ awaitingCode: boolean;
48
+ deviceCode?: string;
49
+ email?: string;
50
+ message?: string;
51
+ startedAt: string;
52
+ endedAt?: string;
53
+ };
54
+ type SignInHandle = {
55
+ on(event: "update", listener: (status: SignInStatus) => void): () => void;
56
+ submitCode(code: string): Promise<void>;
57
+ cancel(): Promise<void>;
58
+ done: Promise<AccountInfo>;
59
+ };
60
+ type AccountManagement = {
61
+ accounts: {
62
+ list(provider?: string): Promise<AccountInfo[]>;
63
+ add(provider: string, options?: {
64
+ label?: string;
65
+ }): Promise<AccountInfo>;
66
+ remove(id: string): Promise<unknown>;
67
+ rename(id: string, label: string): Promise<AccountInfo>;
68
+ setDefault(id: string): Promise<unknown>;
69
+ signOut(id: string): Promise<unknown>;
70
+ refresh(): Promise<AccountInfo[]>;
71
+ signIn(id: string, options?: {
72
+ deviceAuth?: boolean;
73
+ }): Promise<SignInHandle>;
74
+ };
75
+ credentials: {
76
+ list(provider?: string): Promise<ApiCredentialInfo[]>;
77
+ add(input: {
78
+ provider: string;
79
+ key: string;
80
+ label: string;
81
+ }): Promise<ApiCredentialInfo>;
82
+ remove(id: string, provider?: string): Promise<unknown>;
83
+ verify(provider: string): Promise<unknown>;
84
+ };
85
+ presets: {
86
+ list(): Promise<Record<string, unknown>[]>;
87
+ add(input: Record<string, unknown>): Promise<Record<string, unknown>>;
88
+ update(id: string, patch: Record<string, unknown>): Promise<Record<string, unknown>>;
89
+ remove(id: string): Promise<unknown>;
90
+ };
91
+ dispose(): Promise<void>;
92
+ };
93
+
94
+ /**
95
+ * Normalization and honesty reports for the three per-thread host-configuration
96
+ * options: `instructions`, `cwd`, and `settingSources`.
97
+ *
98
+ * All three are the same shape of problem as MCP strict mode — the caller asks
99
+ * for one thing and six providers do six different things with it — so all
100
+ * three report back the same way, through a capability object that is null when
101
+ * nothing was asked for.
102
+ */
103
+ /** Host instructions for a thread. A bare string means `{ mode: "append" }`. */
104
+ type ThreadInstructions = string | {
105
+ mode: "append" | "replace";
106
+ text: string;
107
+ };
108
+ /** Most roots one thread may name. Matches the runtime's own cap. */
109
+ declare const MAX_ATTACHMENT_ROOTS = 32;
110
+ /** What {@link checkAttachmentRoot} answers: the canonical root, or the refusal. */
111
+ type AttachmentRootCheck = {
112
+ ok: true;
113
+ root: string;
114
+ } | {
115
+ ok: false;
116
+ reason: string;
117
+ };
118
+ /**
119
+ * Check one candidate `attachmentRoots` entry without throwing (SDK 0.5).
120
+ *
121
+ * The runtime refuses some roots — the home folder itself, a filesystem root, a
122
+ * path inside the SDK home — and a refused root fails the whole `threads.open`.
123
+ * Because a host normally sends the same roots on every open, one bad entry
124
+ * locks every chat. Use this to test a candidate before you send it:
125
+ *
126
+ * const check = checkAttachmentRoot(downloadsDir, home);
127
+ * if (!check.ok) warn(check.reason); else roots.push(check.root);
128
+ *
129
+ * `root` is the canonical, validated spelling, so it is what
130
+ * `validateAttachmentRoots` and the runtime will accept. `sdkHome` is the same
131
+ * `home` you pass to `createDaexChat`.
132
+ */
133
+ declare function checkAttachmentRoot(value: unknown, sdkHome: string): AttachmentRootCheck;
134
+ /** The result of {@link filterAttachmentRoots}: the roots to send, and the ones dropped. */
135
+ type AttachmentRootFilterResult = {
136
+ /** Valid roots, canonicalized, de-duplicated, capped. Pass these to `threads.open`. */
137
+ roots: string[];
138
+ /** One entry per refused or over-the-limit input, with the reason it was refused. */
139
+ dropped: Array<{
140
+ root: string;
141
+ reason: string;
142
+ }>;
143
+ };
144
+ /**
145
+ * Prepare a root list for `threads.open` without ever failing the open (SDK 0.5).
146
+ *
147
+ * Keeps every valid entry in list order, canonicalized and de-duplicated, and
148
+ * reports each refused entry with its reason instead of throwing. `dropped`
149
+ * lists the refused entries first, then the entries past the 32-entry cap. The
150
+ * result is safe to pass straight to `threads.open` or
151
+ * `threads.open(..., { refresh: { attachmentRoots } })`.
152
+ *
153
+ * A non-array argument still throws: that is a programming error, not a root a
154
+ * caller meant to filter.
155
+ */
156
+ declare function filterAttachmentRoots(value: unknown, sdkHome: string): AttachmentRootFilterResult;
157
+ /**
158
+ * What the provider did with a host-configuration request.
159
+ *
160
+ * Null means one of two things, exactly as `mcpCapability` does: this thread
161
+ * asked for nothing, or it asked and an older runtime reported nothing. The
162
+ * SDK does not invent a level for the second case — an unverified guarantee is
163
+ * reported as unverified.
164
+ */
165
+ type HostConfigCapability = {
166
+ /**
167
+ * Always true on a non-null report: a report exists only for a request that
168
+ * was made. Retained because the field is part of the published shape and
169
+ * because a null report is ambiguous, so code that has a report in hand can
170
+ * still say plainly which of the two cases it is not in.
171
+ */
172
+ requested: boolean;
173
+ level: AgentChatHostConfigLevel;
174
+ /** How the provider implemented it, for logs and support threads. */
175
+ mechanism: string;
176
+ /** Why the level is not `"applied"`, or null when it is. */
177
+ detail: string | null;
178
+ } & Record<string, unknown>;
179
+ type InstructionsCapability = HostConfigCapability & {
180
+ mode: "append" | "replace";
181
+ };
182
+ type SettingSourcesCapability = HostConfigCapability & {
183
+ value: AgentChatSettingSources;
184
+ };
185
+ /**
186
+ * What the provider could actually enforce of a permission policy.
187
+ *
188
+ * `"enforced"` means the provider itself gates every tool call against the
189
+ * policy. `"best-effort"` means DAEX approximated it with the containment and
190
+ * approval knobs the provider does expose, and `residual` names what the policy
191
+ * therefore does not cover. `"unsupported"` means the provider has no gate at
192
+ * all and only the coarse preset applies.
193
+ */
194
+ type PermissionCapability = {
195
+ level: "enforced" | "best-effort" | "unsupported";
196
+ mechanism: string;
197
+ residual: string | null;
198
+ };
199
+
200
+ /**
201
+ * Wire types for the DAEX machine-scoped chat surface.
202
+ *
203
+ * PROVENANCE — every type in this file is a hand-copied subset of DAEX's own
204
+ * shared contracts. The package deliberately does NOT import across the repo
205
+ * boundary (`apps/desktop/src/shared/**`) so it builds and publishes on its
206
+ * own. When the engine contract moves, this file moves with it:
207
+ *
208
+ * - `AgentChatEventEnvelope`, `AgentChatEvent`, `AgentChatSessionSummary`,
209
+ * `AgentChatCreateArgs`, `AgentChatSendArgs`, `AgentChatSteerArgs`,
210
+ * `AgentChatModelCatalog*`, permission-mode unions
211
+ * <- apps/desktop/src/shared/types/chat.ts
212
+ * - the runtime's internal wire shapes (`BufferedEvent`, the
213
+ * `personalChats.call` envelope, `ade/initialize`) live in `wireTypes.ts`
214
+ *
215
+ * The event union in `chat.ts` has ~60 members and grows every release, so it
216
+ * is modelled here as an open record with a `type` discriminant plus narrowed
217
+ * shapes for the members an SDK consumer actually renders. Unknown members
218
+ * pass through untouched rather than being dropped or failing a parse.
219
+ */
220
+
221
+ /** Known provider ids for autocomplete; provider strings remain open for newer runtimes. */
222
+ type DaexProvider = "claude" | "codex" | "cursor" | "droid" | "opencode" | "pi" | "muse" | "qwen" | "kimi" | "grok" | "copilot" | "devin" | "antigravity" | (string & {});
223
+ type AgentChatSessionStatus = "active" | "idle" | "ended";
224
+ /** Collaboration mode accepted by the Codex app-server for an active turn/start. */
225
+ type AgentChatCodexCollaborationMode = "default" | "plan";
226
+ type AgentChatPermissionMode = "default" | "auto" | "plan" | "edit" | "full-auto" | "config-toml";
227
+ /**
228
+ * Which on-disk configuration layers a provider loads for a thread.
229
+ *
230
+ * `"none"` is the default for SDK threads and is what every 0.1.x thread got.
231
+ * The four values are sent verbatim; the engine decides what each one means per
232
+ * provider, and reports the answer on {@link AgentChatSessionSummary}.
233
+ */
234
+ type AgentChatSettingSources = "none" | "project" | "user" | "all";
235
+ /** Host instructions for one thread, in the normalized wire form. */
236
+ type AgentChatInstructions = {
237
+ mode: "append" | "replace";
238
+ text: string;
239
+ };
240
+ /**
241
+ * How completely a provider honoured a host configuration request.
242
+ *
243
+ * The same three-value vocabulary the MCP report uses, for the same reason:
244
+ * four of the six providers cannot do the thing exactly, and a report that said
245
+ * only "applied" would be a lie for most embedders.
246
+ *
247
+ * - `"applied"` — the provider received the value through a first-class
248
+ * channel of its own.
249
+ * - `"best-effort"` — DAEX reached the same outcome through a mechanism it
250
+ * already owns (a prompt prefix, a containment root), and `detail` names
251
+ * what that costs.
252
+ * - `"ignored"` — the provider has no switch for it and the value did not
253
+ * reach the model. `detail` says so.
254
+ */
255
+ type AgentChatHostConfigLevel = "applied" | "best-effort" | "ignored";
256
+ /**
257
+ * Which of one MCP server's tools reach the model. Bare tool names, as the
258
+ * server lists them (`"search"`, not `"mcp__docs__search"`). Names are not
259
+ * secrets: the thread store keeps them.
260
+ *
261
+ * Not every provider can enforce both, and a filter a provider cannot enforce
262
+ * is refused (`invalid_option`) at open, `updateMcpServers` and `setModel` —
263
+ * never dropped:
264
+ *
265
+ * | provider | `allowedTools` | `disallowedTools` |
266
+ * | --- | --- | --- |
267
+ * | codex | yes (`enabled_tools`) | yes (`disabled_tools`) |
268
+ * | claude | refused | yes (removed from the model's context) |
269
+ * | cursor, droid, opencode, muse, pi | refused | refused |
270
+ *
271
+ * Needs a runtime advertising `capabilities.personalChats.mcpToolFilters`;
272
+ * an older one would drop the fields, so the SDK refuses to send them there.
273
+ */
274
+ type McpToolFilter = {
275
+ /** Only these tools reach the model. Never empty. */
276
+ allowedTools?: string[];
277
+ /** These tools never reach the model. Applied after `allowedTools`. */
278
+ disallowedTools?: string[];
279
+ };
280
+ /**
281
+ * Per-thread MCP server definition. Mirrors `AgentChatMcpServerConfig` on the
282
+ * engine side (unit 1). Passing these sets `mcpServers` on the create call;
283
+ * `loadUserMcpServers: false` additionally sets `strictMcpConfig: true`.
284
+ */
285
+ type McpServerConfig = ({
286
+ type: "http" | "sse";
287
+ url: string;
288
+ headers?: Record<string, string>;
289
+ } & McpToolFilter) | ({
290
+ type: "stdio";
291
+ command: string;
292
+ args?: string[];
293
+ env?: Record<string, string>;
294
+ } & McpToolFilter);
295
+ /**
296
+ * What the provider could actually do with a caller's MCP request.
297
+ *
298
+ * Mirrors `AgentChatMcpCapability` in chat.ts. Only DAEX's Claude adapter can
299
+ * enforce strict mode outright; the rest are best-effort with a named residual,
300
+ * and Pi has no MCP surface at all (a thread that asks for `mcpServers` on Pi
301
+ * is refused by the runtime rather than silently opened without them).
302
+ *
303
+ * Read `strictRequested` FIRST, then `level`. `level` and `residual` describe
304
+ * strict mode, so they only make a claim when strict mode was requested; on a
305
+ * delivery-only thread (`loadUserMcpServers: true`) the user's own config loads
306
+ * by design and no level value means "only my tools are loaded".
307
+ *
308
+ * Given `strictRequested`, `level` is the field to branch on, and `"enforced"`
309
+ * is the ONLY value that means "nothing but the servers I supplied". Treating
310
+ * `"best-effort"` as a synonym is the mistake this type exists to prevent —
311
+ * four of the six providers report it, so an embedder that branches on
312
+ * truthiness rather than on the level will overpromise for most of its users.
313
+ *
314
+ * Surface `residual` when it is non-null: "your servers are loaded, and so is
315
+ * X" is a materially different guarantee from "only yours". The residual text
316
+ * comes from the provider adapter and names the specific leak, so it is safe
317
+ * to show verbatim.
318
+ */
319
+ type McpCapabilityReport = {
320
+ /**
321
+ * What strict mode achieved — meaningful ONLY when `strictRequested` is true.
322
+ * Read that field first.
323
+ */
324
+ level: "enforced" | "best-effort" | "unsupported";
325
+ /**
326
+ * How the provider implemented the request, for logs and support threads.
327
+ *
328
+ * Describes ENFORCEMENT when `strictRequested` is true, and DELIVERY (how the
329
+ * supplied servers were handed to the provider) when it is false.
330
+ */
331
+ mechanism: string;
332
+ /**
333
+ * What strict mode could NOT exclude, or null when nothing leaked through.
334
+ *
335
+ * Always null when `strictRequested` is false: nothing was asked to be
336
+ * excluded, so nothing leaked.
337
+ */
338
+ residual: string | null;
339
+ /**
340
+ * Whether this thread asked DAEX to withhold the user's and project's own MCP
341
+ * config — i.e. `loadUserMcpServers: false`, explicitly or by supplying
342
+ * `mcpServers` without opting back in.
343
+ *
344
+ * THE FIRST FIELD TO READ. When it is false the caller asked for delivery
345
+ * only: the user's own MCP config loads by design, and `level` makes no
346
+ * isolation claim at all — treating `level === "enforced"` as "only my tools
347
+ * are loaded" on a delivery-only thread would be exactly backwards.
348
+ *
349
+ * An older runtime that predates the field omits it, and the SDK reports
350
+ * false rather than guessing. That is the conservative direction: it
351
+ * understates isolation instead of promising one that was never verified.
352
+ */
353
+ strictRequested: boolean;
354
+ /**
355
+ * False when the provider has no MCP surface and supplied servers were
356
+ * dropped.
357
+ *
358
+ * PREFER `level`. On a current runtime this is effectively always true —
359
+ * `create` refuses the only case that would make it false — so branching on
360
+ * it tells you nothing that `level` does not tell you better. It is retained
361
+ * because it is part of the published shape, not because it is useful.
362
+ *
363
+ * Older runtimes additionally returned false for a strict-only request
364
+ * (strict mode with no servers) that had in fact been enforced, which made
365
+ * `!delivered` read a success as a failure. Anything keyed on this field
366
+ * against a pre-fix runtime is suspect; `level === "unsupported"` is the
367
+ * check that was always correct.
368
+ */
369
+ delivered: boolean;
370
+ };
371
+ /**
372
+ * File attachment reference accepted by `send` and `steer`.
373
+ *
374
+ * Only the path crosses the wire; bytes never do. The runtime reads the file
375
+ * itself, on the host machine, when the provider needs its contents.
376
+ *
377
+ * WHERE THE PATH MAY LIVE. The runtime resolves an attachment against the
378
+ * thread's working directory and refuses an absolute path it cannot place, so
379
+ * a send whose attachment names a file outside what the runtime accepts throws
380
+ * rather than dropping the file quietly. Pass paths the host obtained from its
381
+ * own file dialog or drop handler, not strings a model produced.
382
+ */
383
+ type AgentChatFileRef = {
384
+ path: string;
385
+ name?: string;
386
+ mimeType?: string;
387
+ bytes?: number;
388
+ /**
389
+ * How the provider receives the file.
390
+ *
391
+ * `"image"` sends the bytes as an image the model can see (Claude and Codex
392
+ * both take image input). `"file"` sends a path hint the model can open with
393
+ * its own tools. When absent, the SDK fills it in before sending with the
394
+ * runtime's own rule, exported as `inferAttachmentType(path, mimeType)`: any
395
+ * `image/*` `mimeType` is an image; otherwise the extension of `path`
396
+ * decides (`.bmp .gif .heic .heif .ico .jpeg .jpg .png .svg .tif .tiff
397
+ * .webp` are images), and everything else is `"file"`. Before 0.3 the field
398
+ * did not exist and every image arrived as a path hint.
399
+ */
400
+ type?: "file" | "image";
401
+ /**
402
+ * Whether the runtime may read the file's bytes. Defaults to true.
403
+ *
404
+ * `false` is REFERENCE-ONLY: the runtime never opens the file, never copies
405
+ * it to a staging directory, and hands the model the path alone — even for an
406
+ * image. Use it for files that must not be downloaded as a side effect, such
407
+ * as a macOS File Provider placeholder, where reading the bytes hydrates the
408
+ * whole file from the cloud.
409
+ *
410
+ * An older runtime ignores the field and reads the bytes as before; the SDK
411
+ * cannot detect that from here, so treat reference-only as a request until
412
+ * your runtime is at least the SDK's supported minimum
413
+ * (`SUPPORTED_RUNTIME_RANGE`).
414
+ */
415
+ hydrate?: boolean;
416
+ };
417
+ /**
418
+ * One transcript event. The `type` field is the discriminant; the remaining
419
+ * fields are provider- and type-specific and are preserved verbatim.
420
+ */
421
+ type AgentChatEvent = {
422
+ type: string;
423
+ [key: string]: unknown;
424
+ };
425
+ /**
426
+ * Which provider raised a pending input request.
427
+ *
428
+ * `"acp"` covers all four ACP dialects, because the permission round trip is
429
+ * one method there. `"ade"` is a request DAEX staged itself.
430
+ */
431
+ /**
432
+ * Who raised a pending input. The ACP harnesses (Qwen, Kimi, Grok, Copilot,
433
+ * Devin, Antigravity) all report `"acp"`, not their own name.
434
+ */
435
+ type PendingInputSource = "claude" | "codex" | "cursor" | "droid" | "opencode" | "pi" | "muse" | "acp" | "ade";
436
+ /**
437
+ * What the provider is asking for.
438
+ *
439
+ * `"approval"` and `"permissions"` are the two approval-shaped kinds — a
440
+ * yes/no on an action the model wants to take. The other four want prose or a
441
+ * choice, and `DaexThread.approve` cannot answer them: render them read-only.
442
+ */
443
+ declare const PENDING_INPUT_KINDS: readonly ["approval", "question", "structured_question", "permissions", "plan_approval", "model_selection"];
444
+ type PendingInputKind = (typeof PENDING_INPUT_KINDS)[number];
445
+ type PendingInputOption = {
446
+ label: string;
447
+ value: string;
448
+ description?: string;
449
+ recommended?: boolean;
450
+ preview?: string;
451
+ previewFormat?: "markdown" | "html";
452
+ };
453
+ type PendingInputQuestion = {
454
+ id: string;
455
+ header?: string;
456
+ question: string;
457
+ options?: PendingInputOption[] | null;
458
+ multiSelect?: boolean;
459
+ allowsFreeform?: boolean;
460
+ isSecret?: boolean;
461
+ defaultAssumption?: string | null;
462
+ impact?: string | null;
463
+ };
464
+ /**
465
+ * One unresolved request the provider is blocked on.
466
+ *
467
+ * Mirrors `PendingInputRequest` in chat.ts. Returned by the `pendingInputs`
468
+ * action and mapped to the SDK's {@link ApprovalRequest} shape before it
469
+ * reaches a caller.
470
+ */
471
+ type PendingInputRequest = {
472
+ requestId: string;
473
+ itemId?: string;
474
+ source: PendingInputSource;
475
+ kind: PendingInputKind;
476
+ title?: string | null;
477
+ description?: string | null;
478
+ questions: PendingInputQuestion[];
479
+ allowsFreeform: boolean;
480
+ blocking: boolean;
481
+ canProceedWithoutAnswer: boolean;
482
+ options?: PendingInputOption[];
483
+ providerMetadata?: Record<string, unknown>;
484
+ autoResolutionMs?: number | null;
485
+ turnId?: string | null;
486
+ };
487
+ /** The stop modes personal-chat callers can request. */
488
+ type AgentChatStopMode = "stop_only" | "stop_and_clear" | "stop_and_background" | "stop_and_clear_and_background" | "stop_and_clear_and_children" | "stop_everything_and_children";
489
+ type AgentChatRecoverTurnArgs = {
490
+ sessionId: string;
491
+ turnId: string;
492
+ action: "wait" | "nudge" | "retry_same_runtime" | "restart_resume";
493
+ };
494
+ type AgentChatResolveUnprocessedMessageArgs = {
495
+ sessionId: string;
496
+ steerId: string;
497
+ action: "run_next" | "dismiss";
498
+ };
499
+ type AgentChatRespondToInputArgs = {
500
+ sessionId: string;
501
+ itemId: string;
502
+ decision?: "accept" | "accept_for_session" | "decline" | "cancel";
503
+ answers?: Record<string, string | string[]>;
504
+ responseText?: string | null;
505
+ };
506
+ type AgentChatSlashCommand = {
507
+ name: string;
508
+ description: string;
509
+ argumentHint?: string;
510
+ source: "sdk" | "local";
511
+ kind?: "command" | "skill" | "mcp";
512
+ origin?: "project" | "user" | "plugin" | "provider";
513
+ server?: string;
514
+ };
515
+ type AgentChatRecoverTurnResult = {
516
+ action: AgentChatRecoverTurnArgs["action"];
517
+ turnId: string;
518
+ status: "waiting" | "nudged" | "retrying" | "resumed";
519
+ };
520
+ type AgentChatResolveUnprocessedMessageResult = {
521
+ steerId: string;
522
+ action: AgentChatResolveUnprocessedMessageArgs["action"];
523
+ status: "completed" | "already_completed";
524
+ replacementMessageId?: string;
525
+ };
526
+ type AgentChatSwitchAccountResult = {
527
+ ok: true;
528
+ instanceId: string;
529
+ } | {
530
+ ok: false;
531
+ reason: "busy" | "signed_out" | "failed";
532
+ message: string;
533
+ };
534
+ type AgentChatUsageLimitResult = {
535
+ ok: true;
536
+ turnId: string | null;
537
+ } | {
538
+ ok: true;
539
+ sessionId: string;
540
+ } | {
541
+ ok: false;
542
+ reason: string;
543
+ message: string;
544
+ };
545
+ /** Runtime-derived controls available for a provider. */
546
+ type ProviderCapabilities = {
547
+ permissionModes: AgentChatPermissionMode[];
548
+ reasoningEfforts: string[];
549
+ fastMode: boolean;
550
+ multipleAccounts: boolean;
551
+ signIn: "cli-login" | "device-code" | "api-key" | "none";
552
+ apiKeys: boolean;
553
+ presets: boolean;
554
+ mcp: "full" | "partial" | "none";
555
+ };
556
+ /**
557
+ * A thread's usage-limit state, as the runtime publishes it on
558
+ * `session_meta_updated.usageLimitResume` (a copy of
559
+ * `AgentChatUsageLimitResume`). The runtime republishes the whole value on
560
+ * every transition and sends null when the limit clears.
561
+ */
562
+ type UsageLimitResume = {
563
+ state: "armed" | "resuming" | "paused" | "opted_out" | "no_reset" | (string & {});
564
+ provider: DaexProvider;
565
+ /** When the resume prompt is sent (reset + buffer). Null when unknown. */
566
+ fireAt: string | null;
567
+ /** The reset the provider published. Null when unknown. */
568
+ resetAt: string | null;
569
+ /** Turn that hit the limit. */
570
+ turnId: string | null;
571
+ updatedAt: string;
572
+ /** Another signed-in account with room, chosen by the runtime. */
573
+ alternateAccount?: {
574
+ instanceId: string;
575
+ label: string;
576
+ } | null;
577
+ [key: string]: unknown;
578
+ };
579
+ /** The client `usageLimit` event: one thread's limit state changed. */
580
+ type UsageLimitEvent = {
581
+ /** Thread key; empty when the session is not one this client opened by key. */
582
+ key: string;
583
+ sessionId: string;
584
+ provider: DaexProvider;
585
+ /** The current state, or null when the limit cleared. */
586
+ status: UsageLimitResume | null;
587
+ };
588
+ /** The narrowed members most consumers actually branch on. */
589
+ type KnownAgentChatEvent = {
590
+ type: "user_message";
591
+ text: string;
592
+ displayText?: string;
593
+ messageId?: string;
594
+ turnId?: string;
595
+ steerId?: string;
596
+ deliveryState?: "queued" | "accepted" | "processed" | "unprocessed" | "delivered" | "inline" | "failed";
597
+ attachments?: AgentChatFileRef[];
598
+ } | {
599
+ type: "user_message_resolution";
600
+ steerId: string;
601
+ action: "run_next" | "dismiss";
602
+ state: "completed";
603
+ replacementMessageId?: string;
604
+ } | {
605
+ type: "queue_reordered";
606
+ steerIds: string[];
607
+ } | {
608
+ type: "queue_recovery";
609
+ recoveryId: string;
610
+ state: "available" | "restored" | "expired";
611
+ messageCount: number;
612
+ /** On `restored`: the messages put back in the queue. */
613
+ restoredSteers?: Array<{
614
+ steerId: string;
615
+ text: string;
616
+ attachments?: AgentChatFileRef[];
617
+ }>;
618
+ } | {
619
+ type: "text";
620
+ text: string;
621
+ messageId?: string;
622
+ turnId?: string;
623
+ } | {
624
+ type: "reasoning";
625
+ text?: string;
626
+ turnId?: string;
627
+ } | {
628
+ type: "tool_call";
629
+ tool: string;
630
+ args: unknown;
631
+ itemId: string;
632
+ turnId?: string;
633
+ } | {
634
+ type: "tool_result";
635
+ tool: string;
636
+ result: unknown;
637
+ itemId?: string;
638
+ turnId?: string;
639
+ } | {
640
+ type: "tokens";
641
+ [key: string]: unknown;
642
+ } | {
643
+ type: "context_usage";
644
+ [key: string]: unknown;
645
+ } | {
646
+ type: "codex_token_usage";
647
+ [key: string]: unknown;
648
+ } | {
649
+ /**
650
+ * The provider is blocked and wants a decision. Answer it with
651
+ * `thread.approve(itemId, …)`.
652
+ *
653
+ * AN UNANSWERED REQUEST BLOCKS THE TURN. There is no timeout anywhere in
654
+ * the runtime: the turn stays parked until `approve()` or `interrupt()`.
655
+ * A host that receives this event and renders nothing has a chat that
656
+ * looks frozen, so render a card for every one of them.
657
+ */
658
+ type: "approval_request";
659
+ itemId: string;
660
+ logicalItemId?: string;
661
+ kind: "command" | "file_change" | "tool_call";
662
+ description: string;
663
+ turnId?: string;
664
+ detail?: unknown;
665
+ /**
666
+ * The finer-grained kind. `"question"` and the other prose kinds ride
667
+ * this event because `kind` has no word for a question — they cannot be
668
+ * answered with approve/decline, so render them read-only.
669
+ */
670
+ requestKind?: PendingInputKind;
671
+ } | {
672
+ /** An `approval_request` with this `itemId` is settled. Upgrade the card. */
673
+ type: "pending_input_resolved";
674
+ itemId: string;
675
+ resolution: "accepted" | "declined" | "cancelled";
676
+ answers?: Record<string, string | string[]>;
677
+ turnId?: string;
678
+ } | {
679
+ type: "status";
680
+ [key: string]: unknown;
681
+ } | {
682
+ type: "error";
683
+ [key: string]: unknown;
684
+ } | {
685
+ type: "budget_exceeded";
686
+ budget: {
687
+ maxCostUsd?: number;
688
+ maxTokens?: number;
689
+ };
690
+ usage: {
691
+ inputTokens: number;
692
+ outputTokens: number;
693
+ totalTokens: number;
694
+ complete?: boolean;
695
+ contextWindow?: number;
696
+ costUsd?: number;
697
+ };
698
+ turnId?: string;
699
+ resumed?: boolean;
700
+ } | {
701
+ type: "done";
702
+ [key: string]: unknown;
703
+ };
704
+ /**
705
+ * The `status` envelope the SDK synthesizes when the runtime goes away.
706
+ *
707
+ * A runtime that exits mid-turn emits nothing — the process that would have
708
+ * sent `done` or `error` is gone — so without this every subscriber stayed
709
+ * "running" forever. Every live thread receives one of these, on the `status`
710
+ * and `event` channels, when the client sees the runtime exit or its socket
711
+ * drop. `synthetic: true` marks it as the SDK's own; the runtime never sends
712
+ * that key. It is not in the durable transcript, so `history()` never
713
+ * returns it.
714
+ */
715
+ type SyntheticRuntimeLostStatusEvent = {
716
+ type: "status";
717
+ /**
718
+ * `"failed"`, the runtime's own word for a turn that ended badly, so a
719
+ * subscriber that already maps `turnStatus` needs no new case. Tell it apart
720
+ * from a runtime-sent failure by `synthetic: true`.
721
+ */
722
+ turnStatus: "failed";
723
+ message: string;
724
+ synthetic: true;
725
+ };
726
+ /**
727
+ * Emitted on a thread's `status` channel after `setModel` replaced its
728
+ * capability reports.
729
+ *
730
+ * A switch across providers can move a policy from `"enforced"` to
731
+ * `"best-effort"`, and a host that read the reports once at open would keep
732
+ * showing the old guarantee. Synthesized by the SDK, never by the runtime.
733
+ */
734
+ type CapabilitiesChangedEvent = {
735
+ type: "capabilities_changed";
736
+ synthetic: true;
737
+ } & ThreadCapabilities;
738
+ /**
739
+ * The four capability reports a thread carries, as one object.
740
+ *
741
+ * Returned by `setModel` and carried by `capabilities_changed`. Each report
742
+ * keeps its own null rule — see the matching field on `DaexThread`.
743
+ */
744
+ type ThreadCapabilities = {
745
+ mcpCapability: McpCapabilityReport | null;
746
+ permissionCapability: PermissionCapability | null;
747
+ instructionsCapability: InstructionsCapability | null;
748
+ settingSourcesCapability: SettingSourcesCapability | null;
749
+ };
750
+ /**
751
+ * What a thread's model resolved to, as the runtime reports it.
752
+ *
753
+ * The runtime resolves aliases, CLI-wrapped ids, and ids a CLI update retired,
754
+ * so this can differ from the id the host passed. Render `displayName` rather
755
+ * than the raw id whenever it is non-null.
756
+ */
757
+ type ThreadModelSelection = {
758
+ /** Catalog model id now bound to the thread. */
759
+ modelId: string;
760
+ /** Provider group that id resolved into — authoritative, not inferred. */
761
+ provider: string;
762
+ /** Provider-native model token. */
763
+ model: string;
764
+ /**
765
+ * The catalog's display name for `modelId`, or null when the catalog does
766
+ * not list it (a retired model, or a catalog that has not loaded).
767
+ */
768
+ displayName: string | null;
769
+ };
770
+ /**
771
+ * One page of a thread's durable transcript, newest page first.
772
+ *
773
+ * Returned by `DaexThread.historyPage`. `events` are in transcript order
774
+ * (oldest first) within the page.
775
+ */
776
+ type ThreadHistoryPage = {
777
+ events: AgentChatEventEnvelope[];
778
+ /** True when older events exist before this page. */
779
+ hasMore: boolean;
780
+ /**
781
+ * Pass as `beforeSequence` to read the page before this one. Null when
782
+ * `hasMore` is false — including the case where the transcript's envelopes
783
+ * carry no `sequence`, which cannot be paged by sequence at all.
784
+ */
785
+ nextBeforeSequence: number | null;
786
+ };
787
+ type AgentChatEventEnvelope = {
788
+ sessionId: string;
789
+ timestamp: string;
790
+ event: AgentChatEvent;
791
+ sequence?: number;
792
+ /**
793
+ * Mirrors `AgentChatEventEnvelope["provenance"]` in DAEX's `shared/types/chat.ts`,
794
+ * NARROWED on purpose: only the keys an SDK consumer can act on are named.
795
+ *
796
+ * DAEX stamps more than this — orchestration routing (`targetKind`,
797
+ * `sourceSessionId`, `attemptId`, `stepKey`, `laneId`, `runId`), fork shape
798
+ * (`replayFork`), and other DAEX-only metadata. These describe surfaces this
799
+ * package does not have: a sidecar drives its own thread with the `agent`
800
+ * role, so it is never the orchestrator reading routing keys or DAEX metadata.
801
+ * Naming them here would advertise surfaces that do not exist.
802
+ *
803
+ * The index signature is what makes that narrowing safe rather than lossy:
804
+ * the runtime is downloaded and can be newer than the SDK, so every key DAEX
805
+ * stamps still arrives and still reads, typed `unknown`. Add a key to the
806
+ * named set only when this package grows a use for it.
807
+ */
808
+ provenance?: {
809
+ messageId?: string;
810
+ providerMessageId?: string;
811
+ threadId?: string | null;
812
+ role?: "user" | "orchestrator" | "worker" | "agent" | null;
813
+ [key: string]: unknown;
814
+ };
815
+ };
816
+ type AgentChatSessionSummary = {
817
+ sessionId: string;
818
+ laneId: string;
819
+ provider: string;
820
+ model: string;
821
+ title?: string | null;
822
+ reasoningEffort?: string | null;
823
+ permissionMode?: AgentChatPermissionMode;
824
+ /** Accepted Codex app-server collaboration mode, when a live runtime reports one. */
825
+ codexEffectiveCollaborationMode?: AgentChatCodexCollaborationMode;
826
+ /** True when a live Codex runtime confirms there is no accepted turn mode. */
827
+ codexEffectiveCollaborationModeWasCleared?: boolean;
828
+ status: AgentChatSessionStatus;
829
+ startedAt: string;
830
+ endedAt: string | null;
831
+ archivedAt?: string | null;
832
+ lastActivityAt: string;
833
+ lastOutputPreview: string | null;
834
+ summary: string | null;
835
+ awaitingInput?: boolean;
836
+ /**
837
+ * The working directory the runtime actually bound the session to, echoed
838
+ * back in its own spelling. Present only when one was requested.
839
+ *
840
+ * This is the canonical answer: the engine resolves the path before it
841
+ * stores it, so a symlinked or differently-cased spelling of one directory
842
+ * comes back as one string. A client that records the caller's spelling
843
+ * instead reports a resume mismatch on a `cwd` that never changed.
844
+ */
845
+ requestedCwd?: string | null;
846
+ /** Catalog model id the session is bound to, when the runtime reports one. */
847
+ modelId?: string;
848
+ /** Present only when the chat was created with an MCP request. */
849
+ mcpCapability?: McpCapabilityReport;
850
+ /**
851
+ * True while MCP servers sent mid-turn wait for that turn to end.
852
+ * `mcpCapability` still describes the servers the running turn has.
853
+ */
854
+ mcpServersPending?: boolean;
855
+ /**
856
+ * Present only when the chat was created with `instructions`. Absent means
857
+ * nothing was requested — NOT that the request was dropped.
858
+ */
859
+ instructionsCapability?: {
860
+ level: AgentChatHostConfigLevel;
861
+ mode: "append" | "replace";
862
+ mechanism: string;
863
+ detail: string | null;
864
+ } | null;
865
+ /** Present only when the chat was created with `settingSources`. */
866
+ settingSourcesCapability?: {
867
+ level: AgentChatHostConfigLevel;
868
+ value: AgentChatSettingSources;
869
+ mechanism: string;
870
+ detail: string | null;
871
+ } | null;
872
+ /** Present only when the chat was created with a permission policy. */
873
+ permissionCapability?: {
874
+ level: "enforced" | "best-effort" | "unsupported";
875
+ mechanism: string;
876
+ residual: string | null;
877
+ } | null;
878
+ [key: string]: unknown;
879
+ };
880
+ /** Flattened, SDK-facing model row. */
881
+ type ModelCatalogEntry = {
882
+ /** Canonical DAEX registry id — this is what `ThreadOpenOptions.model` takes. */
883
+ id: string;
884
+ displayName: string;
885
+ /**
886
+ * The provider group this model belongs to. One of the six
887
+ * {@link DaexProvider} values for every model this SDK can open a thread on;
888
+ * typed open because the runtime's catalog is downloaded and can list a
889
+ * provider group newer than this SDK.
890
+ *
891
+ * Because it is open, `ThreadOpenOptions.provider` (typed `DaexProvider`) will
892
+ * not take it without narrowing. Narrow it with `isSupportedProvider` — an
893
+ * SDK export since 0.4 — rather than a cast:
894
+ *
895
+ * if (!isSupportedProvider(entry.provider)) return;
896
+ * daex.threads.open(key, { provider: entry.provider, model: entry.id });
897
+ */
898
+ provider: DaexProvider | (string & {});
899
+ /** Provider-native model ref DAEX sends under the hood. */
900
+ runtimeModelId: string;
901
+ isDefault: boolean;
902
+ isAvailable: boolean;
903
+ connected: boolean;
904
+ requiresConfiguration: boolean;
905
+ reasoningEfforts: string[];
906
+ defaultReasoningEffort: string | null;
907
+ description: string | null;
908
+ };
909
+ /**
910
+ * Per-provider installation, authentication and availability roll-up.
911
+ *
912
+ * READ `source` FIRST. It is the field that says how much the rest of the
913
+ * record is worth:
914
+ *
915
+ * - `"probed"` — the runtime resolved the binary the provider would actually
916
+ * spawn, ran `--version`, and looked at the credential files the CLI itself
917
+ * uses. `installed`, `binaryPath`, `version` and `authenticated` are real
918
+ * measurements.
919
+ * - `"derived"` — the runtime is older than the `providers.status` RPC, so
920
+ * everything here comes from the model catalog. `installed` is
921
+ * `modelCount > 0`, the three probe fields are null, and a UI should say
922
+ * "not detected" rather than "not installed".
923
+ */
924
+ type ProviderStatus = {
925
+ provider: string;
926
+ displayName: string;
927
+ /**
928
+ * A usable binary or package was found.
929
+ *
930
+ * On a derived record this is `modelCount > 0`, which answers a different
931
+ * question — "does DAEX know models for this provider" — so do not present it
932
+ * as a filesystem fact unless `source` is `"probed"`.
933
+ */
934
+ installed: boolean;
935
+ /** Absolute path the runtime would spawn. Null when not found or derived. */
936
+ binaryPath: string | null;
937
+ /** Verbatim first line of `--version`. Null on a timeout, or when derived. */
938
+ version: string | null;
939
+ /**
940
+ * Credentials the CLI can use were found.
941
+ *
942
+ * On a probed record this is a credential-file check. On a derived one it
943
+ * means "the catalog resolved at least one connected model", which a stale
944
+ * catalog can report after the credential expired — `stale` carries that.
945
+ */
946
+ authenticated: boolean;
947
+ /** How, when the probe could tell: subscription, api-key, oauth, unknown. */
948
+ authMethod?: string | null;
949
+ /** Remediation DAEX supplies. Null on a derived record. */
950
+ installCommand: string | null;
951
+ loginCommand: string | null;
952
+ docsUrl: string | null;
953
+ /** True when at least one model is usable right now. */
954
+ available: boolean;
955
+ /** True when every usable path needs setup first. */
956
+ requiresConfiguration: boolean;
957
+ modelCount: number;
958
+ /**
959
+ * True when something behind this verdict was served from the cache rather
960
+ * than probed on this call: a cached model catalog, or a cached probe record.
961
+ * It does not mean the record is past the runtime's TTL — a record inside the
962
+ * TTL is served from the cache and is stale by this definition.
963
+ */
964
+ stale: boolean;
965
+ /** How this record was produced. Read this before trusting the rest. */
966
+ source: "probed" | "derived";
967
+ /** ISO timestamp of the probe, or of the derivation. */
968
+ checkedAt: string;
969
+ /** Human-readable note from the probe, when it had one. */
970
+ detail?: string | null;
971
+ /** Provider controls, present only when the runtime advertises them. */
972
+ capabilities?: ProviderCapabilities;
973
+ /** Config-home isolation used by this runtime, when it can report it. */
974
+ isolation?: "isolated" | "shared";
975
+ };
976
+ /**
977
+ * One provider record as the `providers.status` RPC sends it.
978
+ *
979
+ * NOT a `Partial<ProviderStatus>`. `ProviderStatus` is this SDK's OUTPUT type
980
+ * and carries four fields only the model catalog can answer — `available`,
981
+ * `requiresConfiguration`, `modelCount` and the `"derived"` half of `source` —
982
+ * which the probe never sends and `mergeProviderStatus` deliberately takes from
983
+ * the catalog instead. Declaring them here would admit members that never
984
+ * occur.
985
+ *
986
+ * Every field is optional and widely typed on purpose: this is untrusted wire
987
+ * data, and `mergeProviderStatus` re-reads each one through its own guard. The
988
+ * shape is the one documented in `docs/features/sdk/README.md`.
989
+ */
990
+ type ProviderStatusProbeRecord = {
991
+ provider?: string;
992
+ displayName?: string;
993
+ installed?: boolean;
994
+ binaryPath?: string | null;
995
+ version?: string | null;
996
+ authenticated?: boolean;
997
+ authMethod?: string | null;
998
+ installCommand?: string | null;
999
+ loginCommand?: string | null;
1000
+ docsUrl?: string | null;
1001
+ source?: "probed";
1002
+ stale?: boolean;
1003
+ checkedAt?: string;
1004
+ detail?: string | null;
1005
+ capabilities?: ProviderCapabilities;
1006
+ isolation?: "isolated" | "shared";
1007
+ };
1008
+ /** Result of the `providers.status` machine RPC. */
1009
+ type ProviderStatusRpcResult = {
1010
+ checkedAt: string;
1011
+ providers: Record<string, ProviderStatusProbeRecord>;
1012
+ };
1013
+ type ThreadSummary = {
1014
+ /** Stable caller-chosen key. Null for chats created outside the SDK. */
1015
+ key: string | null;
1016
+ sessionId: string;
1017
+ provider: string;
1018
+ model: string;
1019
+ title: string | null;
1020
+ status: AgentChatSessionStatus;
1021
+ startedAt: string;
1022
+ lastActivityAt: string;
1023
+ /** The same instant as `lastActivityAt`, under the name list UIs sort by. */
1024
+ updatedAt: string;
1025
+ archived: boolean;
1026
+ /**
1027
+ * What the thread's model resolved to, with the catalog's display name.
1028
+ * Null when the runtime reported no model at all.
1029
+ */
1030
+ modelSelection: ThreadModelSelection | null;
1031
+ };
1032
+ type DoctorReport = {
1033
+ ok: boolean;
1034
+ /**
1035
+ * Version of this SDK package. Reported alongside the runtime version
1036
+ * because a mismatched pair is the first thing to check when an embedder's
1037
+ * chat misbehaves: the two ship on separate cadences, and the SDK is the
1038
+ * half that lives inside the embedder's own build.
1039
+ */
1040
+ sdkVersion: string;
1041
+ binary: {
1042
+ path: string;
1043
+ /** Version string reported by `<binary> --version`, when it answered. */
1044
+ version: string | null;
1045
+ source: "option" | "path" | "download" | "cache";
1046
+ /**
1047
+ * Whether THIS client verified the binary against a published SHA256SUMS.
1048
+ *
1049
+ * False is not an accusation — a caller-supplied `binaryPath`, an `ade`
1050
+ * found on PATH, and a reuse of an earlier download are all unverified by
1051
+ * this client because it did not fetch them. It is only meaningful as
1052
+ * "provenance was checked here", which is what an operator wants to know
1053
+ * when auditing where the running binary came from.
1054
+ */
1055
+ checksumVerified: boolean;
1056
+ };
1057
+ /**
1058
+ * Runtime provenance: which of the five resolution steps produced the binary,
1059
+ * where its native modules came from, and whether the OS considers it signed.
1060
+ *
1061
+ * `binary` above is the 0.1.x view and keeps its four `source` values.
1062
+ * `source` and `signature` here are the two fields to put in a support
1063
+ * bundle: together they separate "the app is running the runtime we signed
1064
+ * and shipped" from "the app quietly downloaded one on this machine", which
1065
+ * is the difference an embedder cannot otherwise see.
1066
+ */
1067
+ runtime: {
1068
+ /**
1069
+ * `"packaged"` is an explicit runtime whose options came from
1070
+ * `resolvePackagedRuntime()` — the copy inside the host's own signed app
1071
+ * bundle. `"explicit"` is any other caller-pinned `binaryPath`.
1072
+ */
1073
+ source: "explicit" | "packaged" | "bundled-package" | "cached-download" | "path" | "downloaded" | "attached";
1074
+ binaryPath: string;
1075
+ version: string | null;
1076
+ /** `ADE_RUNTIME_ROOT` as spawned, or null when the install carries its own. */
1077
+ runtimeRoot: string | null;
1078
+ /** `ADE_RUNTIME_NODE_MODULES` as spawned. */
1079
+ nodeModulesPath: string | null;
1080
+ /**
1081
+ * macOS and Windows only. Null on Linux, in attach mode, and whenever the
1082
+ * check could not run — "not known", never "not signed".
1083
+ *
1084
+ * `accepted` on macOS is Gatekeeper's verdict on the outermost `.app` the
1085
+ * runtime is embedded in (a nested binary assessed alone is always
1086
+ * "rejected" as not an app), and null when it cannot be judged. Only
1087
+ * `accepted: false` means the OS refused it.
1088
+ */
1089
+ signature: {
1090
+ signed: boolean;
1091
+ authority?: string;
1092
+ accepted?: boolean | null;
1093
+ } | null;
1094
+ /** True only when THIS client downloaded a runtime during its lifetime. */
1095
+ downloadedThisSession: boolean;
1096
+ checksumVerified: boolean;
1097
+ /**
1098
+ * Whether the runtime's self-reported version is inside the range this SDK
1099
+ * supports (`SUPPORTED_RUNTIME_RANGE`).
1100
+ *
1101
+ * An unsupported runtime still connects: features it lacks are detected
1102
+ * and degrade with a logged line. Pass `requireCompatibleRuntime: true` to
1103
+ * `createDaexChat` to refuse it instead. A dev build (`0.0.0`, or no version
1104
+ * at all) counts as supported and says so in `note`.
1105
+ */
1106
+ compatibility: RuntimeCompatibility;
1107
+ };
1108
+ socket: {
1109
+ path: string;
1110
+ connected: boolean;
1111
+ /** Runtime info from the `ade/initialize` result, when the runtime sent it. */
1112
+ runtimeVersion: string | null;
1113
+ pid: number | null;
1114
+ };
1115
+ events: {
1116
+ mode: "push" | "drain" | "unavailable";
1117
+ /** Buffer epoch last observed; a change means the runtime restarted. */
1118
+ epoch: string | null;
1119
+ gapsRecovered: number;
1120
+ };
1121
+ providers: Record<string, ProviderStatus>;
1122
+ logins: {
1123
+ mode: "isolated" | "machine" | "attached";
1124
+ perProvider: Record<string, "isolated" | "shared" | "unknown">;
1125
+ };
1126
+ threads: {
1127
+ tracked: number;
1128
+ live: number;
1129
+ };
1130
+ /** Most recent errors the client recorded, newest last. Capped. */
1131
+ recentErrors: Array<{
1132
+ at: string;
1133
+ scope: string;
1134
+ message: string;
1135
+ }>;
1136
+ };
1137
+ /** The result of comparing a runtime's version with `SUPPORTED_RUNTIME_RANGE`. */
1138
+ type RuntimeCompatibility = {
1139
+ supported: boolean;
1140
+ /** The range this SDK build supports, e.g. `">=1.2.81 <2.0.0"`. */
1141
+ range: string;
1142
+ /** What the runtime reported on `ade/initialize`, or null when it sent none. */
1143
+ version: string | null;
1144
+ /** Why a version counted as supported without being checked, when it did. */
1145
+ note: string | null;
1146
+ };
1147
+ type Unsubscribe = () => void;
1148
+ /** @deprecated Use {@link DaexProvider}. */
1149
+ type AdeProvider = DaexProvider;
1150
+
1151
+ /**
1152
+ * The client-level lifecycle events, in one dependency-free module.
1153
+ *
1154
+ * Kept apart from `client.ts` so the Electron protocol (which the sandboxed
1155
+ * preload bundles) can key its payload type by this map without importing the
1156
+ * client, and so the event list exists exactly once: `DaexChatClient.on`
1157
+ * validates against it, the Electron bridge subscribes to every name in it,
1158
+ * and the IPC payload type is derived from it.
1159
+ */
1160
+ /**
1161
+ * Payloads of the client-level events, by name.
1162
+ *
1163
+ * These are about the RUNTIME, not about any one thread. A thread learns that
1164
+ * its runtime died from the synthetic `status` envelope on its own `status`
1165
+ * channel; a host learns it here, once.
1166
+ */
1167
+ type DaexClientEventMap = {
1168
+ /**
1169
+ * The runtime process this client spawned exited without `dispose()`.
1170
+ * `error` is the tail of its stderr, when it wrote any. Not emitted in attach
1171
+ * mode, where the client owns no process — watch `transport` there.
1172
+ */
1173
+ exit: {
1174
+ code: number | null;
1175
+ signal: string | null;
1176
+ error: string | null;
1177
+ };
1178
+ /**
1179
+ * The socket to the runtime closed unexpectedly (`"closed"`), or an
1180
+ * `autoRestart` brought it back (`"reconnected"`).
1181
+ */
1182
+ transport: {
1183
+ state: "closed" | "reconnected";
1184
+ error: string | null;
1185
+ };
1186
+ /**
1187
+ * One `autoRestart` attempt finished. `attempt` counts from 1 per outage.
1188
+ * `final` is true when no further attempt follows for this outage: the
1189
+ * attempt succeeded (`ok: true`), or it failed and was the last one
1190
+ * `maxAttempts` allows (the client gave up; the runtime stays down until the
1191
+ * host creates a new client). SDK >= 0.4.
1192
+ */
1193
+ restart: {
1194
+ attempt: number;
1195
+ ok: boolean;
1196
+ error: string | null;
1197
+ final: boolean;
1198
+ };
1199
+ /**
1200
+ * A thread left, or came back to, the host's active list through this
1201
+ * client: `threads.delete` (`"deleted"`), `threads.archive` (`"archived"`)
1202
+ * or `threads.unarchive` (`"unarchived"`). Emitted after the action
1203
+ * succeeds, whoever called it: host code in the main process, or a renderer
1204
+ * over the Electron bridge. A change made by another client of the same
1205
+ * runtime (DAEX desktop) is not reported. SDK >= 0.4.
1206
+ */
1207
+ threadLifecycle: {
1208
+ key: string;
1209
+ change: "deleted" | "archived" | "unarchived";
1210
+ };
1211
+ /** A provider turn stopped because its current account reached a usage limit. */
1212
+ usageLimit: UsageLimitEvent;
1213
+ };
1214
+ /** Every client-level event name, once. See {@link DaexClientEventMap}. */
1215
+ declare const DAEX_CLIENT_EVENTS: readonly ["exit", "transport", "restart", "threadLifecycle", "usageLimit"];
1216
+ /** The client-level event names. See {@link DaexClientEventMap}. */
1217
+ type DaexClientEvent = (typeof DAEX_CLIENT_EVENTS)[number];
1218
+ /** @deprecated Use {@link DAEX_CLIENT_EVENTS}. */
1219
+ declare const ADE_CLIENT_EVENTS: readonly ["exit", "transport", "restart", "threadLifecycle", "usageLimit"];
1220
+ /** @deprecated Use {@link DaexClientEvent}. */
1221
+ type AdeClientEvent = DaexClientEvent;
1222
+ /** @deprecated Use {@link DaexClientEventMap}. */
1223
+ type AdeClientEventMap = DaexClientEventMap;
1224
+
1225
+ /** Options for `pickDefaultModel` and `client.models.defaultModel`. */
1226
+ type DefaultModelOptions = {
1227
+ /**
1228
+ * Only models a thread can use now: `isAvailable` and `connected` (the
1229
+ * provider is signed in). Default true.
1230
+ */
1231
+ available?: boolean;
1232
+ /**
1233
+ * Only these providers, in order of preference: the first provider with a
1234
+ * qualifying model wins. Omit for every provider.
1235
+ */
1236
+ providers?: readonly string[];
1237
+ /**
1238
+ * Your own ranking inside one provider's qualifying models (SDK 0.5). Return
1239
+ * a number greater than zero to prefer a model — the highest score wins.
1240
+ * Return 0, a negative number, or a non-finite number for "no opinion": that
1241
+ * model is then ranked the way it is ranked without this option.
1242
+ *
1243
+ * Use it to state a cost or family preference instead of keeping your own
1244
+ * copy of the rule. For example, to start new chats on the newest Sonnet:
1245
+ *
1246
+ * prefer: (model) => (/sonnet/i.test(model.id) ? 1 : 0)
1247
+ *
1248
+ * A model that nobody scores falls back to `isDefault`, then to catalog
1249
+ * order, so passing this option never removes a model from the pool.
1250
+ *
1251
+ * A callback that throws propagates out of `pickDefaultModel` (and out of
1252
+ * `client.models.defaultModel`), like every other host callback that is part
1253
+ * of an operation. It is not swallowed: a ranking that fails silently would
1254
+ * pick a model you did not ask for.
1255
+ */
1256
+ prefer?: (model: ModelCatalogEntry) => number;
1257
+ };
1258
+ /**
1259
+ * The model a new thread should use, or null when none qualifies.
1260
+ *
1261
+ * Among the qualifying models (see `DefaultModelOptions`), per provider in the
1262
+ * order `providers` gives (or all at once without it): the model `prefer`
1263
+ * scores highest, else the catalog's `isDefault` model, else the first model
1264
+ * the catalog lists.
1265
+ */
1266
+ declare function pickDefaultModel(models: readonly ModelCatalogEntry[], opts?: DefaultModelOptions): ModelCatalogEntry | null;
1267
+
1268
+ /**
1269
+ * Every error this package throws carries a stable machine-readable code.
1270
+ *
1271
+ * Kept as its own union rather than derived from {@link ADE_ERROR_CODES} so
1272
+ * each member can carry its own doc comment; a test asserts the two agree.
1273
+ */
1274
+ type DaexErrorCode = "binary_not_found" | "download_failed" | "checksum_mismatch" | "spawn_failed" | "connect_failed" | "handshake_failed" | "rpc_error" | "rpc_timeout" | "transport_closed" | "protocol_error" | "thread_not_found" | "invalid_option"
1275
+ /**
1276
+ * No runtime could be resolved and `allowDownload: false` forbade fetching
1277
+ * one. A packaging mistake must fail here, loudly, rather than work on the
1278
+ * developer's machine through a silent download and fail on a locked-down
1279
+ * user's.
1280
+ */
1281
+ | "runtime_unavailable"
1282
+ /**
1283
+ * `approve()` named an item that is not pending. A stop, a teardown, or an
1284
+ * earlier call already settled it; the engine settles unknown items silently,
1285
+ * so the SDK checks first and says so rather than letting a no-op look like
1286
+ * a success.
1287
+ */
1288
+ | "approval_not_found"
1289
+ /**
1290
+ * A bridge refused the call before it reached the SDK — the host's
1291
+ * `authorize` hook said no. Used by `@daex-dev/sdk/electron`.
1292
+ */
1293
+ | "unauthorized" | "disposed"
1294
+ /**
1295
+ * The runtime's version is outside `SUPPORTED_RUNTIME_RANGE` and the host
1296
+ * asked `createDaexChat` to refuse it (`requireCompatibleRuntime: true`).
1297
+ * Without that option an unsupported runtime connects with a logged warning.
1298
+ */
1299
+ | "runtime_incompatible"
1300
+ /**
1301
+ * The call was refused only because a turn is running on the thread:
1302
+ * `setModel`, a reasoning `update`, `retry`, `editLast`, or a runtime action
1303
+ * that must wait for the turn to end. Nothing changed. Wait for the turn to
1304
+ * finish (or `interrupt()` it), then call again. `setModel` and `update`
1305
+ * also accept `{ force: true }`. Before SDK 0.4 these refusals used
1306
+ * `invalid_option`.
1307
+ */
1308
+ | "turn_in_flight"
1309
+ /**
1310
+ * The thread's provider, or the runtime, cannot do what was asked. Nothing
1311
+ * changed. `retry` and `editLast` throw it for a provider other than Claude
1312
+ * or Codex, and for a runtime older than the `rerunLastTurn` action.
1313
+ */
1314
+ | "unsupported" | "invalid_output"
1315
+ /**
1316
+ * A provider sign-in ended without signing in: it failed, was cancelled, or
1317
+ * expired. The handle's last status says which (`state`) and why (`message`).
1318
+ */
1319
+ | "sign_in_failed";
1320
+ declare class DaexError extends Error {
1321
+ readonly code: DaexErrorCode;
1322
+ readonly cause?: unknown;
1323
+ constructor(code: DaexErrorCode, message: string, options?: {
1324
+ cause?: unknown;
1325
+ });
1326
+ }
1327
+ /** @deprecated Use {@link DaexError}. */
1328
+ declare const AdeError: typeof DaexError;
1329
+ /** @deprecated Use {@link DaexError}. */
1330
+ type AdeError = DaexError;
1331
+ /** @deprecated Use {@link DaexErrorCode}. */
1332
+ type AdeErrorCode = DaexErrorCode;
1333
+
1334
+ /**
1335
+ * Supplies MCP header values for one server of one thread.
1336
+ *
1337
+ * Called at every create, resume and restart that needs them, and before each
1338
+ * turn of a thread with remote servers; the result is sent to the runtime and
1339
+ * never persisted by the SDK. May return a Promise, so a host can refresh an
1340
+ * OAuth token first. Return undefined for a server that needs no headers.
1341
+ */
1342
+ type McpHeadersResolver = (key: string, serverName: string) => Record<string, string> | undefined | Promise<Record<string, string> | undefined>;
1343
+
1344
+ type PermissionPreset = "always-allow" | "default";
1345
+ /**
1346
+ * A per-tool permission policy: the third form of `permissions`, alongside the
1347
+ * two presets.
1348
+ *
1349
+ * Tool names are provider-neutral. `mcp:<server>:<tool>` and `mcp:<server>:*`
1350
+ * name an MCP tool and the engine translates them to each provider's own
1351
+ * spelling (Claude writes `mcp__server__tool`). Any other string is matched
1352
+ * against the provider's own tool name, case-insensitively, with an optional
1353
+ * trailing `*` for a prefix match — and built-in tool names ARE
1354
+ * provider-specific, so `Bash` means something on Claude and nothing on Pi.
1355
+ *
1356
+ * Precedence on Claude, highest first:
1357
+ * 1. `deniedTools`
1358
+ * 2. `allowedTools` and `autoApproveMcpServers`
1359
+ * 3. `sandboxRoot` containment, for commands and file writes only
1360
+ * 4. `fallback`
1361
+ *
1362
+ * On Codex the three tool fields apply to MCP tool calls only: a call Codex
1363
+ * raises as an elicitation is judged by `deniedTools`, then `allowedTools` /
1364
+ * `autoApproveMcpServers` on `mcp:<server>:<tool>`, then `fallback`. Commands
1365
+ * and file writes reach only rungs 3 and 4 — `sandboxRoot` containment then
1366
+ * `fallback` — and the command text is never consulted. Read
1367
+ * `thread.permissionCapability.residual` rather than assuming a rung.
1368
+ *
1369
+ * `fallback` is required. A policy with no fallback has no obvious default, and
1370
+ * guessing "ask" would silently park the turn for a host that built no approval
1371
+ * UI — which is the failure this type exists to remove.
1372
+ */
1373
+ type ThreadPermissionPolicy = {
1374
+ /** Tools that run without asking. Exact names, or a trailing-`*` prefix. */
1375
+ allowedTools?: string[];
1376
+ /** Tools refused outright, never asked about. Wins over `allowedTools`. */
1377
+ deniedTools?: string[];
1378
+ /** Every tool of these servers is allowed. Same as `mcp:<server>:*`. */
1379
+ autoApproveMcpServers?: string[];
1380
+ /**
1381
+ * Absolute path. Commands and file writes inside it auto-approve; outside it
1382
+ * they follow `fallback`. This is containment, not a jail: see
1383
+ * `ThreadOpenOptions.cwd` for the plain working directory.
1384
+ */
1385
+ sandboxRoot?: string;
1386
+ /** What happens to anything the rules above did not match. */
1387
+ fallback: "ask" | "deny";
1388
+ /**
1389
+ * Decline an approval nobody answered within this many milliseconds.
1390
+ *
1391
+ * Opt-in and enforced by the SDK, not the runtime: the field is stripped
1392
+ * before the policy goes on the wire. When an approval-shaped
1393
+ * `approval_request` this client watched arrive is still pending after the
1394
+ * timeout, the SDK answers it `decline` and logs a line; the transcript then
1395
+ * records the refusal like any other. Questions and plan approvals are left
1396
+ * alone — a decline is not an answer to them.
1397
+ *
1398
+ * Only requests this client SAW are timed, from the moment it saw them. One
1399
+ * raised before the client connected, or while its runtime was down, is not.
1400
+ *
1401
+ * There is no default. Proceeding after N seconds is a security decision, and
1402
+ * refusing after N seconds breaks a long human review, so the host picks.
1403
+ */
1404
+ approvalTimeoutMs?: number;
1405
+ };
1406
+ declare const SUPPORTED_PROVIDERS: readonly DaexProvider[];
1407
+ /**
1408
+ * Narrow a provider string (for example `ModelCatalogEntry.provider`, typed
1409
+ * open for catalog groups newer than this SDK) to `DaexProvider` without a cast.
1410
+ * Exported from the package root since SDK 0.4.
1411
+ */
1412
+ declare function isSupportedProvider(value: string): value is DaexProvider;
1413
+
1414
+ /** Default GitHub repository that publishes the standalone runtime assets. */
1415
+ declare const DEFAULT_RELEASE_REPO = "arul28/DAEX";
1416
+ /**
1417
+ * Asset naming and URL scheme, mirrored from
1418
+ * `apps/ade-cli/scripts/install-runtime.sh` and `apps/web/api/install.ts`:
1419
+ *
1420
+ * https://github.com/<repo>/releases/latest/download/<asset>
1421
+ * https://github.com/<repo>/releases/download/<tag>/<asset>
1422
+ *
1423
+ * with `<asset>` one of `daex-<platform>-<arch>[.exe]`, the matching
1424
+ * `daex-<platform>-<arch>.native.tar.gz`, and `SHA256SUMS`. Releases before
1425
+ * the DAEX names published `ade-<platform>-<arch>…` instead; the download reads
1426
+ * which from the release's SHA256SUMS.
1427
+ *
1428
+ * The runtime binary alone is NOT runnable: it dlopens native modules out of
1429
+ * the archive's `node_modules`, which is why both assets are fetched and why
1430
+ * `spawnEnv` below exists.
1431
+ */
1432
+ type RuntimeTarget = {
1433
+ /** e.g. `darwin-arm64`, `linux-x64`, `win32-x64`. */
1434
+ target: string;
1435
+ /** e.g. `daex-darwin-arm64`. */
1436
+ binaryAsset: string;
1437
+ /** e.g. `daex-darwin-arm64.native.tar.gz`. */
1438
+ archiveAsset: string;
1439
+ /**
1440
+ * The same assets under the names releases used before DAEX
1441
+ * (`ade-darwin-arm64`, `ade-darwin-arm64.native.tar.gz`). Downloaded when a
1442
+ * release publishes only those.
1443
+ *
1444
+ * DAEX-OLD-RELEASES: keep these while downloads of releases from before the
1445
+ * rename (an explicit `channel` tag) are supported; not a window-end deletion.
1446
+ */
1447
+ legacyBinaryAsset?: string;
1448
+ legacyArchiveAsset?: string;
1449
+ };
1450
+ type DownloadRequest = {
1451
+ /** Directory that receives `bin/ade` and `runtime/<target>/node_modules`. */
1452
+ home: string;
1453
+ /** Release channel: `latest` (default) or an explicit tag such as `v1.2.69`. */
1454
+ channel: string;
1455
+ repo: string;
1456
+ target: RuntimeTarget;
1457
+ logger: (line: string) => void;
1458
+ signal?: AbortSignal;
1459
+ /**
1460
+ * Refuse to install a runtime whose checksum cannot be verified. Defaults to
1461
+ * true; set false only for a channel that genuinely publishes no SHA256SUMS.
1462
+ */
1463
+ requireChecksum?: boolean;
1464
+ };
1465
+ type DownloadResult = {
1466
+ /** Absolute path of the installed `ade` binary. */
1467
+ binaryPath: string;
1468
+ /** Absolute path of the extracted native runtime root. */
1469
+ runtimeRoot: string;
1470
+ /** True when a checksum from a published SHA256SUMS was verified. */
1471
+ checksumVerified: boolean;
1472
+ };
1473
+ /**
1474
+ * Injectable so tests never touch the network. `createDaexChat` accepts one via
1475
+ * the internal options bag; the default is `downloadRuntime`.
1476
+ */
1477
+ type RuntimeDownloader = (request: DownloadRequest) => Promise<DownloadResult>;
1478
+ declare function resolveRuntimeTarget(platform?: NodeJS.Platform, arch?: string): RuntimeTarget;
1479
+ declare function assetUrl(repo: string, channel: string, asset: string): string;
1480
+ /**
1481
+ * Parses a `SHA256SUMS` body into asset -> hex digest.
1482
+ *
1483
+ * Format is the coreutils one: `<hex> <name>` (two spaces, or ` *` for the
1484
+ * binary marker). Names may carry a directory prefix in some release layouts,
1485
+ * so only the basename is keyed — the same normalization the install script's
1486
+ * awk does.
1487
+ */
1488
+ declare function parseChecksums(body: string): Map<string, string>;
1489
+ /**
1490
+ * Environment a spawned DAEX runtime binary needs so it can load the native
1491
+ * modules that ship in the archive rather than whatever happens to be on the
1492
+ * host's NODE_PATH. Mirrors `set_runtime_env` in install-runtime.sh.
1493
+ *
1494
+ * `nodeModulesPath` defaults to `<runtimeRoot>/node_modules`, which is the
1495
+ * layout every DAEX installer produces. An embedder who relocated the two halves
1496
+ * inside their bundle passes it explicitly, and it is then used verbatim: the
1497
+ * binary resolves `ADE_RUNTIME_NODE_MODULES` on its own, so silently deriving
1498
+ * the path would point a signed app at a directory that is not there.
1499
+ */
1500
+ declare function runtimeSpawnEnv(runtimeRoot: string, base?: NodeJS.ProcessEnv, nodeModulesPath?: string): NodeJS.ProcessEnv;
1501
+
1502
+ /** A host-side limit for the usage observed on one thread. */
1503
+ type ThreadBudget = {
1504
+ maxCostUsd?: number;
1505
+ maxTokens?: number;
1506
+ };
1507
+ /** Usage totals observed or recovered from a thread's durable transcript. */
1508
+ type ThreadUsage = {
1509
+ inputTokens: number;
1510
+ outputTokens: number;
1511
+ totalTokens: number;
1512
+ /** False when the SDK could not load part of the durable transcript. */
1513
+ complete?: boolean;
1514
+ contextWindow?: number;
1515
+ /** Present only when the provider reports a dollar cost. */
1516
+ costUsd?: number;
1517
+ };
1518
+
1519
+ type CreateDaexChatOptions = {
1520
+ /** Isolated per-app DAEX state root. Created if missing. */
1521
+ home: string;
1522
+ /** Pin a specific `ade` build. Skips PATH discovery and the downloader. */
1523
+ binaryPath?: string;
1524
+ /**
1525
+ * Where the native modules the runtime dlopens live. Maps to
1526
+ * `ADE_RUNTIME_NODE_MODULES`. Required alongside `binaryPath` when the
1527
+ * modules are not beside the binary, which is the normal case for an app
1528
+ * bundle: the binary lands in `Contents/Resources/ade-runtime/bin` and the
1529
+ * modules in `Contents/Resources/ade-runtime/native/node_modules`.
1530
+ */
1531
+ runtimeNodeModules?: string;
1532
+ /** Maps to `ADE_RUNTIME_ROOT`. Defaults to the parent of `runtimeNodeModules`. */
1533
+ runtimeRoot?: string;
1534
+ /**
1535
+ * Never reach the network. Throws `runtime_unavailable` instead of
1536
+ * downloading. Defaults to true, which preserves 0.1.x behavior.
1537
+ *
1538
+ * A shipping app wants false: a packaging mistake then fails loudly in QA,
1539
+ * rather than working on the developer's machine through a silent download
1540
+ * and failing on a locked-down user's.
1541
+ */
1542
+ allowDownload?: boolean;
1543
+ /** Release channel for the downloader: `latest` (default) or a tag. */
1544
+ channel?: string;
1545
+ logger?: (line: string) => void;
1546
+ /**
1547
+ * Default instructions for every thread this client opens.
1548
+ *
1549
+ * A per-thread `instructions` wins outright — it is not merged with this one,
1550
+ * because two texts silently concatenated is nobody's intent. Use this for
1551
+ * the persona your whole app shares and the per-thread field for a narrower
1552
+ * one.
1553
+ */
1554
+ instructions?: ThreadInstructions;
1555
+ /**
1556
+ * Supplies MCP header values — usually a bearer token — per thread and
1557
+ * server, at the moment they are needed.
1558
+ *
1559
+ * The SDK never writes header values to disk: the thread store keeps header
1560
+ * NAMES only. So a resume, a recreate after the runtime lost a session, and
1561
+ * an `autoRestart` all need the values again, and this is where they come
1562
+ * from when the caller did not pass them (`refresh.mcpServers` on
1563
+ * `threads.open` wins over it; headers passed explicitly on a create win over
1564
+ * it too). May return a Promise, so the host can refresh an OAuth token
1565
+ * first; return undefined for a server that needs no headers.
1566
+ *
1567
+ * Also called before every `send`, `retry` and `editLast` of a thread with
1568
+ * remote servers, and by `thread.refreshMcpHeaders()`: when the values
1569
+ * changed (a token rotated), the SDK pushes them and the runtime restarts
1570
+ * the provider between turns on the same provider thread, so a long chat
1571
+ * never runs on an expired token. Unchanged values push nothing, so keep
1572
+ * the callback cheap — return a cached token until it nears expiry.
1573
+ *
1574
+ * On a resume the SDK pushes the resolved servers to the runtime with
1575
+ * `updateSession`, so a rotated token takes effect on the next turn. That
1576
+ * needs a runtime advertising `capabilities.personalChats.updateMcpServers`;
1577
+ * an older one keeps whatever it had and the SDK logs a warning. Two cases
1578
+ * push nothing: when this callback supplies no value for any server that
1579
+ * needs one (re-sending would replace the session's live credentials with
1580
+ * none; logged), and when the resolved servers, values included, are the
1581
+ * ones this client already sent for the thread.
1582
+ */
1583
+ mcpHeaders?: McpHeadersResolver;
1584
+ /**
1585
+ * Respawn the runtime when it exits unexpectedly. Off by default.
1586
+ *
1587
+ * `true` uses 5 attempts with a 1 s backoff that doubles per attempt;
1588
+ * the object form overrides either. Each attempt emits
1589
+ * `client.on("restart")`. On success the client re-handshakes, rebinds its
1590
+ * event stream, and re-opens every thread it had open from the stored
1591
+ * record — header values resolved again through `mcpHeaders` — so the
1592
+ * thread objects a host holds, and a bridge built on this client, keep
1593
+ * working. The client object itself never changes.
1594
+ *
1595
+ * A turn in flight when the runtime died is NOT resumed: each live thread
1596
+ * already received a synthetic `status` / `turnStatus: "failed"` envelope,
1597
+ * and the transcript keeps everything that was persisted.
1598
+ *
1599
+ * Not attempted after `dispose()`, and not in attach mode for a runtime the
1600
+ * SDK did not start — there the client only reconnects to the same socket.
1601
+ */
1602
+ autoRestart?: boolean | {
1603
+ maxAttempts?: number;
1604
+ backoffMs?: number;
1605
+ };
1606
+ /**
1607
+ * Refuse a runtime whose version is outside `SUPPORTED_RUNTIME_RANGE`,
1608
+ * throwing `DaexError("runtime_incompatible")` from `createDaexChat` (and
1609
+ * failing an `autoRestart` attempt the same way).
1610
+ *
1611
+ * Off by default: an unsupported runtime connects, logs one warning, and
1612
+ * degrades feature by feature. `doctor().runtime.compatibility` reports the
1613
+ * verdict either way. Dev builds (`0.0.0`, or no version) always pass.
1614
+ */
1615
+ requireCompatibleRuntime?: boolean;
1616
+ /**
1617
+ * Where `binaryPath` came from. Set by `resolvePackagedRuntime()`, which
1618
+ * returns `source: "packaged"` so that spreading its result into these
1619
+ * options makes `doctor().runtime.source` report `"packaged"` rather than
1620
+ * `"explicit"`. Ignored without `binaryPath`.
1621
+ */
1622
+ source?: "packaged";
1623
+ /**
1624
+ * Reuse the runtime host's provider logins. Defaults to false (isolated
1625
+ * per-app logins). SDK 0.7 changes the default from machine logins; pass
1626
+ * true to keep relying on the host machine's Claude/Codex login.
1627
+ */
1628
+ useMachineLogin?: boolean;
1629
+ /**
1630
+ * The environment the runtime starts with. Defaults to this process's
1631
+ * environment. `useMachineLogin: false` isolates the providers' sign-in
1632
+ * folders, not variables: an `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` or
1633
+ * `CURSOR_API_KEY` here is visible to the runtime, so leave them out when end
1634
+ * users must run only on their own logins and keys. The host's own `ADE_*`
1635
+ * variables are always removed.
1636
+ */
1637
+ env?: NodeJS.ProcessEnv;
1638
+ /**
1639
+ * Resolve a host-vault credential id to a secret for one thread session.
1640
+ * The value is pushed to the runtime for the live session and never saved
1641
+ * in the SDK thread record.
1642
+ */
1643
+ resolveSecret?: (provider: DaexProvider, credentialId: string) => string | undefined | Promise<string | undefined>;
1644
+ /** Usage-limit behavior for new threads. Defaults to `wait`. */
1645
+ onUsageLimit?: "failover" | "wait" | "ask";
1646
+ };
1647
+ /**
1648
+ * Credentials and endpoints to push onto a thread as it is opened.
1649
+ *
1650
+ * The one exception to "a resume re-applies the stored values": MCP servers
1651
+ * carry secrets that rotate (a bearer token after sign-out or an account
1652
+ * switch) and endpoints that move (a port that was busy), and a thread pinned
1653
+ * to the old ones fails MCP auth for good.
1654
+ */
1655
+ type ThreadRefreshOptions = {
1656
+ /**
1657
+ * Replaces the thread's caller MCP servers wholesale.
1658
+ *
1659
+ * On a resume the SDK sends these with `updateSession`, and the provider
1660
+ * picks them up on its next turn; that needs a runtime advertising
1661
+ * `capabilities.personalChats.updateMcpServers`, and an older one keeps its
1662
+ * old servers with a logged warning. On a recreate they are the servers the
1663
+ * new session is created with. On a create they are used when `mcpServers`
1664
+ * is absent. The stored record is updated either way — header names only.
1665
+ *
1666
+ * A map identical (header values included) to the one this client last sent
1667
+ * for the key is not sent again, so a renderer that reloads and repeats the
1668
+ * same `refresh` does not restart the provider.
1669
+ */
1670
+ mcpServers?: Record<string, McpServerConfig>;
1671
+ /**
1672
+ * Replaces the thread's `attachmentRoots` (see `ThreadOpenOptions`); `[]`
1673
+ * clears them. On a resume, and on a thread this client already holds open,
1674
+ * the SDK sends them with `updateSession` (runtime >= 1.2.82) before the MCP
1675
+ * refresh, and a refusal fails the `open` with the thread unchanged. On a
1676
+ * recreate or a create they are the roots the session starts with. The
1677
+ * stored record is updated either way. SDK >= 0.4.
1678
+ *
1679
+ * A list identical to the one the record holds is NOT sent again, the same
1680
+ * way an identical `refresh.mcpServers` map is skipped: a host that repeats
1681
+ * its four roots on every open costs no update call and does not restart the
1682
+ * provider. Compare and canonicalize a root with `checkAttachmentRoot`, and
1683
+ * prepare a whole list with `filterAttachmentRoots`, so one refused entry
1684
+ * cannot fail every open. SDK >= 0.5.
1685
+ */
1686
+ attachmentRoots?: string[];
1687
+ };
1688
+ /** Escape hatches for tests and embedders. Not part of the stable surface. */
1689
+ type InternalAdeChatOptions = CreateDaexChatOptions & {
1690
+ /** Override the endpoint (a mock server's temp socket, for instance). */
1691
+ socketPath?: string;
1692
+ /** Attach to an already-running runtime instead of spawning one. */
1693
+ attach?: boolean;
1694
+ download?: RuntimeDownloader;
1695
+ releaseRepo?: string;
1696
+ allowPathDiscovery?: boolean;
1697
+ /** Anchor for the `@daex-dev/runtime-*` lookup. Tests and vendored trees only. */
1698
+ resolveBundledFrom?: string;
1699
+ clientName?: string;
1700
+ /** Override the least-privilege role. Escape hatch; not for normal use. */
1701
+ adeDefaultRole?: string;
1702
+ startupTimeoutMs?: number;
1703
+ pollIntervalMs?: number;
1704
+ /** Interval for `providers.onChange` re-derivation while listeners exist. */
1705
+ providerPollIntervalMs?: number;
1706
+ };
1707
+ type ThreadOpenOptions = {
1708
+ /** A provider id present in this runtime's model catalog. */
1709
+ provider: DaexProvider | (string & {});
1710
+ model: string;
1711
+ /** Stop a turn when cumulative reported usage reaches either limit. */
1712
+ budget?: ThreadBudget;
1713
+ /** Direct harness permission mode; validated against provider capabilities when available. */
1714
+ permissionMode?: AgentChatPermissionMode;
1715
+ /** Reasoning tier, validated against provider capabilities when available. */
1716
+ reasoningEffort?: string;
1717
+ /** Fast mode, validated against provider capabilities when available. */
1718
+ fastMode?: boolean;
1719
+ /** Provider instance id. Create-only; persisted and reused when recreating this key. */
1720
+ account?: string;
1721
+ /** Runtime credential id. Create-only; persisted without its key value. */
1722
+ credential?: string;
1723
+ /** Harness preset id. Create-only; persisted and reused when recreating this key. */
1724
+ preset?: string;
1725
+ /**
1726
+ * MCP servers to attach to this thread.
1727
+ *
1728
+ * Refused outright by providers with no MCP surface (Pi), so a thread never
1729
+ * opens silently tool-less. Read {@link DaexThread.mcpCapability} afterwards
1730
+ * for what the provider actually delivered.
1731
+ *
1732
+ * Supplying servers also turns on strict mode unless you set
1733
+ * `loadUserMcpServers: true` — see that field.
1734
+ *
1735
+ * IGNORED ON RESUME: a key this home already knows re-applies the tool
1736
+ * surface it was created with, and the SDK logs one line when the map passed
1737
+ * here differs. See {@link ThreadResumeOptions}.
1738
+ */
1739
+ mcpServers?: Record<string, McpServerConfig>;
1740
+ /**
1741
+ * Whether to also load the user's and project's own MCP configuration.
1742
+ *
1743
+ * Applies when you supply `mcpServers` or set this flag explicitly: either
1744
+ * makes the SDK send `strictMcpConfig` — `true` to withhold the user's
1745
+ * config, and an explicit `false` (not an omission) when you set this flag
1746
+ * true, because omitting the key is not the same as asking for the user's
1747
+ * servers.
1748
+ *
1749
+ * A thread that does neither sends no MCP field at all and lets the runtime's
1750
+ * session profile decide. The profile SDK threads run is strict by default,
1751
+ * so "sent nothing" means the user's own MCP config is withheld — pass
1752
+ * `loadUserMcpServers: true` if you want it loaded.
1753
+ *
1754
+ * IMPORTANT — false is NOT a uniform guarantee. Only Claude can enforce it.
1755
+ * Every other provider is best-effort because the gap is in the provider's
1756
+ * own SDK, not in DAEX:
1757
+ *
1758
+ * | provider | strict mode | what still loads anyway |
1759
+ * |----------|-------------|------------------------------------------------|
1760
+ * | claude | enforced | nothing (MCP-wise) |
1761
+ * | codex | best-effort | servers contributed by a Codex *plugin* |
1762
+ * | cursor | best-effort | user-layer servers |
1763
+ * | droid | best-effort | tools appearing only after the first sweep |
1764
+ * | opencode | best-effort | the global OpenCode config dir (for auth) |
1765
+ * | pi | unsupported | n/a — no MCP surface at all |
1766
+ *
1767
+ * That table is a summary of DAEX's own `CALLER_MCP_SUPPORT` table in
1768
+ * `apps/desktop/src/shared/callerMcpServers.ts`, which is where each level,
1769
+ * mechanism and residual is decided; this doc comment restates it and must be
1770
+ * updated when a row there changes.
1771
+ *
1772
+ * Note that even for Claude, "enforced" scopes to MCP only: the user's
1773
+ * rules, commands, and output styles still load, because those are not MCP
1774
+ * and are not what strict mode excludes.
1775
+ *
1776
+ * Do not present this to your users as "only your tools are loaded" without
1777
+ * checking {@link DaexThread.mcpCapability}: it names the exact residual for
1778
+ * the thread you actually got, and it is authoritative where this table is
1779
+ * only a summary.
1780
+ *
1781
+ * The table above applies only when this is false. Setting it TRUE (or
1782
+ * supplying servers and opting back in) is a delivery-only request: the
1783
+ * user's own MCP config loads by design, the report comes back with
1784
+ * `strictRequested: false`, `residual` is null, and `mechanism` describes how
1785
+ * the servers were delivered rather than any enforcement. Nothing in that
1786
+ * report claims isolation, because none was asked for.
1787
+ *
1788
+ * IGNORED ON RESUME: a key this home already knows re-applies the value it
1789
+ * was created with, and the SDK logs one line when the value passed here
1790
+ * differs. See {@link ThreadResumeOptions}.
1791
+ */
1792
+ loadUserMcpServers?: boolean;
1793
+ /**
1794
+ * How tool use is gated on this thread. Three accepted forms.
1795
+ *
1796
+ * `"default"` leaves each provider's own behavior in place, and what that
1797
+ * means differs enough per provider to be worth stating: on Claude, DAEX
1798
+ * installs no gate at all and the Agent SDK decides non-interactively; on
1799
+ * Codex, an approval request PARKS THE TURN until something answers it.
1800
+ *
1801
+ * `"always-allow"` maps to each provider's full-auto create args —
1802
+ * `bypassPermissions` on Claude, `danger-full-access` on Codex.
1803
+ *
1804
+ * A {@link ThreadPermissionPolicy} object is the third form, and the only one
1805
+ * that is neither of those extremes: name the tools that may run, the tools
1806
+ * that may not, and what happens to everything else. `fallback: "deny"`
1807
+ * guarantees a turn never parks, which is what a host with no approval UI
1808
+ * wants. `fallback: "ask"` emits `approval_request` and needs
1809
+ * {@link DaexThread.approve} wired to a card.
1810
+ *
1811
+ * Read {@link DaexThread.permissionCapability} afterwards: only Claude gates
1812
+ * every tool call against the policy.
1813
+ *
1814
+ * IGNORED ON RESUME: a key this home already knows re-applies the value it
1815
+ * was created with, and the SDK logs one line when the value passed here
1816
+ * differs. See {@link ThreadResumeOptions}.
1817
+ */
1818
+ permissions?: PermissionPreset | ThreadPermissionPolicy;
1819
+ /**
1820
+ * Host instructions for this thread.
1821
+ *
1822
+ * A bare string is shorthand for `{ mode: "append", text }`, which keeps
1823
+ * DAEX's own personal-chat framing and adds yours after it. `"replace"` uses
1824
+ * your text alone — for a chat branded as your assistant, which must not
1825
+ * mention DAEX.
1826
+ *
1827
+ * This does NOT put the text in the transcript: `exportThread` returns no
1828
+ * user message carrying it, which is the whole difference from the
1829
+ * hidden-first-message workaround it replaces. Falls back to the client-level
1830
+ * `instructions` when omitted; check {@link DaexThread.instructionsCapability}
1831
+ * for what the provider did with it.
1832
+ *
1833
+ * IGNORED ON RESUME: a key this home already knows re-applies the value it
1834
+ * was created with, and the SDK logs one line when the value passed here
1835
+ * differs. See {@link ThreadResumeOptions}.
1836
+ */
1837
+ instructions?: ThreadInstructions;
1838
+ /**
1839
+ * Absolute directory the provider runs in.
1840
+ *
1841
+ * Created recursively (mode 0755) when missing. Defaults to the runtime's own
1842
+ * scratch workspace at `<home>/personal-chats/workspaces`, and omitting it
1843
+ * keeps exactly that behavior.
1844
+ *
1845
+ * Refused, with `invalid_option`: a relative path (it would resolve against
1846
+ * the runtime's working directory, not yours), a path starting with `~` (not
1847
+ * expanded), a filesystem root, the user's home directory itself, and
1848
+ * anything inside the SDK's own `home`.
1849
+ *
1850
+ * This is a working directory, NOT a sandbox. For containment use
1851
+ * `permissions.sandboxRoot`; the two are separate fields precisely so setting
1852
+ * one does not read as implying the other.
1853
+ *
1854
+ * IGNORED ON RESUME: a key this home already knows re-applies the value it
1855
+ * was created with, and the SDK logs one line when the value passed here
1856
+ * differs. See {@link ThreadResumeOptions}.
1857
+ */
1858
+ cwd?: string;
1859
+ /**
1860
+ * Extra directories an attachment's ABSOLUTE path may point into, beside
1861
+ * the chat's working directory and the runtime's state directory. SDK >= 0.4,
1862
+ * runtime >= 1.2.82 (an older runtime ignores the field, and an attachment
1863
+ * outside the default roots still throws on send).
1864
+ *
1865
+ * Use it for a folder the user drops files from (Downloads, a music
1866
+ * library), so the host can attach the file in place instead of copying it.
1867
+ * Combined with `hydrate: false`, a File Provider placeholder is attached
1868
+ * without being downloaded.
1869
+ *
1870
+ * Each entry follows the `cwd` rules (absolute, no `~`, not a filesystem
1871
+ * root, not the home directory itself, not inside the SDK home); at most 32.
1872
+ * These are READ roots for attachments only: they do not change where the
1873
+ * agent runs, and they are not a sandbox. A path is matched after the
1874
+ * runtime resolves symlinks on both sides (see the attachments guide).
1875
+ *
1876
+ * ONE REFUSED ENTRY FAILS THE WHOLE OPEN, because the runtime is sent the
1877
+ * whole list. Test a candidate first with `checkAttachmentRoot`, or prepare
1878
+ * the list with `filterAttachmentRoots`, which drops a bad entry and reports
1879
+ * why. Both are SDK >= 0.5.
1880
+ *
1881
+ * IGNORED ON RESUME, like `cwd`: a known key keeps the roots on record. Pass
1882
+ * `refresh.attachmentRoots` to replace them on a live thread.
1883
+ */
1884
+ attachmentRoots?: string[];
1885
+ /**
1886
+ * Which on-disk configuration layers the provider loads.
1887
+ *
1888
+ * Defaults to `"none"`, which is what every 0.1.x thread got: no filesystem
1889
+ * settings. `"project"` loads files in `cwd` (a `CLAUDE.md` your app ships);
1890
+ * `"user"` loads the machine user's own global config; `"all"` loads user,
1891
+ * project and local.
1892
+ *
1893
+ * `"project"` is usually the right choice for an embedder. Loading a user's
1894
+ * personal `~/.claude` into an app-branded assistant is a surprise, and it
1895
+ * should take an explicit `"user"` or `"all"` to get it. Only Claude has a
1896
+ * real switch — see {@link DaexThread.settingSourcesCapability}.
1897
+ *
1898
+ * IGNORED ON RESUME: a key this home already knows re-applies the value it
1899
+ * was created with, and the SDK logs one line when the value passed here
1900
+ * differs. See {@link ThreadResumeOptions}.
1901
+ */
1902
+ settingSources?: AgentChatSettingSources;
1903
+ title?: string;
1904
+ /** See {@link ThreadRefreshOptions}. */
1905
+ refresh?: ThreadRefreshOptions;
1906
+ };
1907
+ /**
1908
+ * Options for reopening a key this home already knows.
1909
+ *
1910
+ * `provider` and `model` become optional because a durable thread already
1911
+ * recorded them — but they are still used if the runtime lost the session and
1912
+ * the thread has to be recreated, so a caller that has them should pass them.
1913
+ *
1914
+ * A RESUME RE-APPLIES THE STORED VALUES. `cwd`, `instructions`,
1915
+ * `settingSources`, `permissions`, `mcpServers` and `loadUserMcpServers` are
1916
+ * read off the durable record, not off this object: one key is one
1917
+ * conversation, and moving a live agent to a new directory, a new policy or a
1918
+ * new tool surface on reopen is not what "reopen" means. Passing a value that
1919
+ * differs from the stored one is not an error and does not change the thread;
1920
+ * the SDK logs one line naming the option it ignored. To run under different
1921
+ * host configuration, open a different key.
1922
+ *
1923
+ * THE STORED RECORD ALSO WINS ON A RECREATE. When the runtime has lost the
1924
+ * session entirely (a wiped or migrated home, a corrupt state root), the key is
1925
+ * created afresh from the record: `provider`, `model`, `cwd`, `instructions`,
1926
+ * `settingSources`, `permissions`, `mcpServers` and `loadUserMcpServers` come
1927
+ * off the record, and a value passed here only fills a field the record lacks.
1928
+ * `permissions` means the stored policy or, for a key created on 0.3 or later
1929
+ * with a preset, the stored preset; a key written before 0.3 with a preset has
1930
+ * none on record, so the value passed here (or `"default"`) is used. Before
1931
+ * 0.3 the call's options won instead, which let any caller that could name a
1932
+ * key — a renderer, over the Electron bridge — rebuild a lost thread
1933
+ * with a looser policy, another provider, or no MCP servers at all.
1934
+ *
1935
+ * `refresh.mcpServers` is the one field that does replace the stored value, on
1936
+ * a resume and on a recreate alike — see {@link ThreadRefreshOptions}.
1937
+ */
1938
+ type ThreadResumeOptions = Partial<ThreadOpenOptions>;
1939
+ /** @deprecated Use {@link CreateDaexChatOptions}. */
1940
+ type CreateAdeChatOptions = CreateDaexChatOptions;
1941
+
1942
+ /**
1943
+ * The approval half of the pending-input surface.
1944
+ *
1945
+ * A provider that wants a decision emits `approval_request` and then BLOCKS.
1946
+ * There is no timeout in the runtime, so the turn stays parked until something
1947
+ * answers it. `thread.approve()` is the answer; `thread.interrupt()` is the
1948
+ * abort. A host that renders neither has a chat that looks frozen.
1949
+ */
1950
+ /** What a host can say about a pending approval. */
1951
+ type ApprovalDecision = "accept" | "accept_always" | "reject";
1952
+ declare const APPROVAL_DECISIONS: readonly ApprovalDecision[];
1953
+ /** One request a host has to answer before its turn can continue. */
1954
+ type ApprovalRequest = {
1955
+ /** The id to pass to `approve()`. */
1956
+ itemId: string;
1957
+ /** Groups retries of one logical action, when the provider reports one. */
1958
+ logicalItemId?: string;
1959
+ /** The shape of the thing being confirmed. */
1960
+ kind: "command" | "file_change" | "tool_call";
1961
+ /**
1962
+ * The finer-grained kind.
1963
+ *
1964
+ * `"approval"` and `"permissions"` are answerable with `approve()`. Use
1965
+ * `respond()` for `"question"` and `"structured_question"` requests, with
1966
+ * answers keyed by question id, and for `"plan_approval"` with an explicit
1967
+ * decision. A runtime may leave other request kinds read-only.
1968
+ */
1969
+ requestKind?: PendingInputKind;
1970
+ /** Human-readable and provider-supplied. Safe to render. */
1971
+ description: string;
1972
+ turnId?: string;
1973
+ /** Provider payload: the command string, the patch, the tool input. */
1974
+ detail?: unknown;
1975
+ /** Which provider raised it. */
1976
+ provider: DaexProvider;
1977
+ /** The original prompts for requests answered through `respond()`. */
1978
+ questions?: PendingInputRequest["questions"];
1979
+ /** False when the runtime cannot answer this request through the SDK. */
1980
+ answerable?: boolean;
1981
+ };
1982
+ /**
1983
+ * True for the two kinds `approve()` can actually settle.
1984
+ *
1985
+ * The canonical partition of `PendingInputKind`. `@daex-dev/chat-ui` states the
1986
+ * complement of this set in `transcript/ApprovalCard.tsx` because it takes this
1987
+ * package only as an OPTIONAL peer and cannot import the function; that copy
1988
+ * points back here.
1989
+ */
1990
+ declare function isApprovalShaped(kind: PendingInputKind | undefined): boolean;
1991
+
1992
+ /** One message waiting in a thread's queue. */
1993
+ type ThreadQueueItem = {
1994
+ id: string;
1995
+ text: string;
1996
+ attachments?: AgentChatFileRef[];
1997
+ };
1998
+
1999
+ /** Options for `historyPage`. */
2000
+ type HistoryPageOptions = {
2001
+ /**
2002
+ * Return events strictly older than this `sequence`. Omit for the newest
2003
+ * page. Pass the previous page's `nextBeforeSequence` to walk backwards.
2004
+ */
2005
+ beforeSequence?: number;
2006
+ /**
2007
+ * At most this many events. The runtime pages by bytes, so a page can hold
2008
+ * fewer; when it holds more, the SDK keeps the newest `limit` and moves the
2009
+ * cursor so nothing is skipped. Defaults to 200.
2010
+ */
2011
+ limit?: number;
2012
+ };
2013
+
2014
+ type ThreadEventChannel = "event" | "usage" | "status";
2015
+ type SetModelOptions = {
2016
+ /**
2017
+ * Switch even with a turn in flight, accepting that the turn ends with no
2018
+ * completion event. Only meaningful mid-turn; ignored on an idle thread.
2019
+ */
2020
+ force?: boolean;
2021
+ };
2022
+ /**
2023
+ * What `setModel` returns: the resolved model, plus the four capability
2024
+ * reports as they stand on the new provider.
2025
+ *
2026
+ * A switch across providers can quietly lower a guarantee — a policy Claude
2027
+ * enforced is best-effort on Codex — so the reports come back with the answer
2028
+ * rather than leaving the caller to re-read four fields and notice. The same
2029
+ * object is emitted as `capabilities_changed` on the thread's `status`
2030
+ * channel, for subscribers that did not make the call.
2031
+ */
2032
+ type SetModelResult = ThreadModelSelection & {
2033
+ capabilities: ThreadCapabilities;
2034
+ };
2035
+ type SendOptions = {
2036
+ /** Files to attach. `type` is inferred when absent; see `AgentChatFileRef`. */
2037
+ attachments?: AgentChatFileRef[];
2038
+ /** Text shown to the user when it differs from what the agent receives. */
2039
+ displayText?: string;
2040
+ reasoningEffort?: string | null;
2041
+ };
2042
+
2043
+ type ThreadInterruptOptions = {
2044
+ /** Keep queued messages, or remove them along with the active turn. */
2045
+ queue?: "keep" | "drop";
2046
+ /** Full DAEX stop semantics. When set, this takes precedence over `queue`. */
2047
+ mode?: AgentChatStopMode;
2048
+ };
2049
+ /** The response fields accepted by the runtime's `respondToInput` action. */
2050
+ type ThreadRespondOptions = Pick<AgentChatRespondToInputArgs, "answers" | "decision" | "responseText">;
2051
+ /** Options for `steer`. */
2052
+ type SteerOptions = {
2053
+ /**
2054
+ * Files to hand the running turn. Same shape and inference as
2055
+ * `SendOptions.attachments`. A steer with attachments may have empty text.
2056
+ */
2057
+ attachments?: AgentChatFileRef[];
2058
+ };
2059
+ /**
2060
+ * What `update` may change on a live thread.
2061
+ *
2062
+ * `title` is a rename and is safe at any time. `reasoningEffort` and
2063
+ * `fastMode` reconfigure the provider, which on some providers restarts it —
2064
+ * so they follow the same mid-turn rule `setModel` does.
2065
+ */
2066
+ type ThreadUpdate = {
2067
+ /**
2068
+ * New title. Persisted in the thread store as well. A host title marks the
2069
+ * chat as named: the runtime's automatic title never replaces it.
2070
+ *
2071
+ * `null` clears the host title. The chat then shows the provider's
2072
+ * placeholder title ("Claude Chat", "Codex Chat"), so `thread.title` reads
2073
+ * that string, not null, and the automatic title may name the chat again
2074
+ * after its next message (runtime >= 1.2.82; before, `null` set the
2075
+ * placeholder and still counted as named).
2076
+ */
2077
+ title?: string | null;
2078
+ /** Reasoning effort for later turns. `null` returns to the model default. */
2079
+ reasoningEffort?: string | null;
2080
+ /** Provider fast mode, where the provider has one. */
2081
+ fastMode?: boolean;
2082
+ };
2083
+ /** Options for `update`. */
2084
+ type ThreadUpdateOptions = {
2085
+ /**
2086
+ * Apply `reasoningEffort` / `fastMode` even with a turn in flight, accepting
2087
+ * that some providers end that turn without a completion event. Ignored for
2088
+ * a title-only update, which never needs it.
2089
+ */
2090
+ force?: boolean;
2091
+ };
2092
+ /** What `update` returns: the thread's title and model after the change. */
2093
+ type ThreadUpdateResult = {
2094
+ title: string | null;
2095
+ model: ThreadModelSelection | null;
2096
+ };
2097
+ /** Options for `editLast`. */
2098
+ type EditLastOptions = {
2099
+ /** Text shown to the user when it differs from what the agent receives. */
2100
+ displayText?: string;
2101
+ /**
2102
+ * Files for the edited message, replacing the original's. Omit to keep the
2103
+ * original message's attachments; pass `[]` to drop them.
2104
+ */
2105
+ attachments?: AgentChatFileRef[];
2106
+ };
2107
+ /**
2108
+ * What `retry` and `editLast` return, once the runtime has cut the old turn
2109
+ * out and dispatched the new one. The new turn's events follow on the stream.
2110
+ *
2111
+ * The rollback is the CONVERSATION only. Files the old turn wrote stay on
2112
+ * disk, and this result does not report them (see `retry`).
2113
+ */
2114
+ type ThreadRerunResult = {
2115
+ /**
2116
+ * The first history `sequence` removed. Every event at or after it is gone
2117
+ * from the runtime's history; drop the same events from any copy you keep —
2118
+ * and inspect them there if you want to warn about files the old turn wrote.
2119
+ */
2120
+ retractedFromSequence: number;
2121
+ /**
2122
+ * The thread's history generation after the cut. The runtime also emits a
2123
+ * `session_meta_updated` event with `historyInvalidated: true` and this
2124
+ * generation, before the new turn's first event.
2125
+ */
2126
+ historyGeneration: number;
2127
+ /**
2128
+ * How the provider conversation went back: `claude_fork` (the Claude session
2129
+ * was copied up to the entry before the turn), `claude_new_session` (the
2130
+ * turn was the first, so a new Claude session starts), `codex_thread` (the
2131
+ * Codex thread was reverted or forked before the turn), or `not_delivered`
2132
+ * (the turn never reached the provider, so only the history changed).
2133
+ */
2134
+ conversationRollback: "claude_fork" | "claude_new_session" | "codex_thread" | "not_delivered";
2135
+ };
2136
+ interface DaexThread {
2137
+ /**
2138
+ * The runtime session id. Stable for the life of the thread, EXCEPT across a
2139
+ * recreate: if an `autoRestart` finds the runtime lost the session, the key
2140
+ * is rebuilt on a new session and this id changes. Key your own state on
2141
+ * `key`, not on this.
2142
+ */
2143
+ readonly id: string;
2144
+ readonly key: string;
2145
+ /**
2146
+ * The thread's title, or null. Updated by `update({ title })`; the runtime
2147
+ * may also retitle a thread after its first turn, which this reflects at the
2148
+ * next open or `update`.
2149
+ */
2150
+ readonly title: string | null;
2151
+ /**
2152
+ * What the thread's model resolved to, with the catalog display name.
2153
+ *
2154
+ * Kept current by `setModel`. Null only when the runtime reported no model.
2155
+ * Show `displayName` rather than the id when it is non-null: after a CLI
2156
+ * update retires a model the runtime resolves the id forward, and the raw id
2157
+ * a host stored is then the wrong label.
2158
+ */
2159
+ readonly model: ThreadModelSelection | null;
2160
+ /**
2161
+ * What the provider did with this thread's `mcpServers` / strict-mode request.
2162
+ *
2163
+ * Only Claude enforces strict mode outright. Every other provider is
2164
+ * best-effort with a named `residual`, so an embedder that promised its users
2165
+ * an isolated tool surface must read this rather than assume the request
2166
+ * landed whole. Populated on create AND on resume — a reopened thread rebuilds
2167
+ * the same tool surface it started with, and reports the same caveat.
2168
+ *
2169
+ * Null means one of two things, and they are NOT equivalent:
2170
+ * - the thread asked for neither `mcpServers` nor strict mode; or
2171
+ * - the runtime did not report one. Older runtimes omit the field
2172
+ * entirely. The SDK logs a warning in that case rather than letting a
2173
+ * missing report read as "nothing was requested" — if you asked for
2174
+ * servers and got null here, treat the guarantee as unverified.
2175
+ */
2176
+ readonly mcpCapability: McpCapabilityReport | null;
2177
+ /**
2178
+ * What the provider did with this thread's `instructions`.
2179
+ *
2180
+ * Null when the thread asked for none, or when an older runtime reported
2181
+ * nothing — the same two-case ambiguity `mcpCapability` has, and for the same
2182
+ * reason: the SDK does not invent a verdict it did not receive.
2183
+ *
2184
+ * `level` is `"applied"` on Claude, Codex, OpenCode and Pi, which all take
2185
+ * instructions through a channel of their own; `"best-effort"` on Cursor and
2186
+ * Droid, where DAEX merges the text into a prompt it already prefixes.
2187
+ */
2188
+ readonly instructionsCapability: InstructionsCapability | null;
2189
+ /**
2190
+ * What the provider did with this thread's `settingSources`.
2191
+ *
2192
+ * Only Claude has a real switch. Codex reports `"best-effort"` for `project`
2193
+ * and `all` because it always reads its own user-level file too, and every
2194
+ * other provider reports `"ignored"` — the value did not reach it.
2195
+ */
2196
+ readonly settingSourcesCapability: SettingSourcesCapability | null;
2197
+ /**
2198
+ * What the provider could enforce of this thread's permission policy.
2199
+ *
2200
+ * Null when the thread opened with a preset rather than a policy. Read
2201
+ * `level` before telling a user their rules are in force: only Claude gates
2202
+ * every tool call against the policy, Codex approximates it with containment
2203
+ * and approval settings, and the rest cannot express it at all.
2204
+ */
2205
+ readonly permissionCapability: PermissionCapability | null;
2206
+ /**
2207
+ * Queue a message for the agent.
2208
+ *
2209
+ * DISPATCH-RESOLUTION ASYMMETRY: this resolves when the turn has been
2210
+ * DISPATCHED, not when the reply is complete. Nothing in the returned promise
2211
+ * tells you a turn is still streaming, so code that runs after an `await
2212
+ * send(...)` must not assume the thread is idle. Before any destructive
2213
+ * operation — `setModel`, `dispose` — either await the completion event on
2214
+ * `on("status")` or check the thread's status; `setModel` enforces this for
2215
+ * you and throws rather than silently ending the turn.
2216
+ *
2217
+ * With an `mcpHeaders` callback and remote MCP servers, the headers are
2218
+ * resolved again first (see `refreshMcpHeaders`), so a token that expired
2219
+ * since the last turn is replaced before this one. A refresh that fails is
2220
+ * logged and the message is still sent, on the headers the session has.
2221
+ */
2222
+ send(text: string, opts?: SendOptions): Promise<void>;
2223
+ /**
2224
+ * Add input to the turn in flight, without waiting for it to end.
2225
+ *
2226
+ * Needs text, attachments, or both. Attachments follow the same rules as
2227
+ * `send`. Resolves once the runtime accepted the steer, not once the agent
2228
+ * read it.
2229
+ */
2230
+ steer(text: string, opts?: SteerOptions): Promise<void>;
2231
+ interrupt(): Promise<void>;
2232
+ /**
2233
+ * Rename the thread, or change its reasoning effort or fast mode.
2234
+ *
2235
+ * A title-only update is allowed at any time. `reasoningEffort` and
2236
+ * `fastMode` are refused while a turn is in flight (`DaexError` code
2237
+ * `turn_in_flight`, SDK >= 0.4) unless `{ force: true }`:
2238
+ * on Codex a settings change the provider rejects tears the provider down,
2239
+ * which ends the turn without `error` or `done` — the silent truncation the
2240
+ * client's destructive-while-streaming rule forbids. Await the turn or
2241
+ * `interrupt()` first.
2242
+ *
2243
+ * Resolves with the title and model as the runtime reports them afterwards.
2244
+ */
2245
+ update(patch: ThreadUpdate, opts?: ThreadUpdateOptions): Promise<ThreadUpdateResult>;
2246
+ /**
2247
+ * Run the last user turn again, as if the first attempt never happened.
2248
+ *
2249
+ * The runtime rolls the provider conversation back to just before the last
2250
+ * user message, removes that message and everything after it from the
2251
+ * thread's history, and sends the same message (text and attachments) again.
2252
+ * The history then holds the message once. Files the old turn changed are
2253
+ * NOT restored: the rollback covers the conversation, not the disk.
2254
+ *
2255
+ * The result does not say whether the old turn wrote files, because the
2256
+ * runtime cannot tell which of YOUR tools write. A host that lets the agent
2257
+ * write can find them itself: the removed events are the ones at or after
2258
+ * `retractedFromSequence` in your own copy of the history, so inspect their
2259
+ * tool calls and warn the user if any of them was a write.
2260
+ *
2261
+ * What a subscriber sees, in order: `session_meta_updated` with
2262
+ * `historyInvalidated: true` and the new `historyGeneration` (drop your copy
2263
+ * of the events at or after `retractedFromSequence`, or re-read `history()`),
2264
+ * then the new turn's `user_message`, `status: started`, and the rest of the
2265
+ * turn. A `history()` or `historyPage()` read after the call returns only the
2266
+ * new attempt.
2267
+ *
2268
+ * Claude and Codex only. Throws `turn_in_flight` while a turn runs or waits
2269
+ * on an approval (nothing changed; await it or `interrupt()` first),
2270
+ * `unsupported` for another provider or a runtime without the action, and
2271
+ * `rpc_error` when the thread has no user message yet.
2272
+ *
2273
+ * Resolves once the new turn is dispatched, not once it ends.
2274
+ */
2275
+ retry(): Promise<ThreadRerunResult>;
2276
+ /**
2277
+ * Replace the last user message with `text` and run it again.
2278
+ *
2279
+ * Everything `retry` says applies: same rollback, same event sequence, same
2280
+ * errors, and the history shows only the edited message. `text` may be empty
2281
+ * only when `opts.attachments` is non-empty. Attachments default to the
2282
+ * original message's.
2283
+ */
2284
+ editLast(text: string, opts?: EditLastOptions): Promise<ThreadRerunResult>;
2285
+ /**
2286
+ * Replace this thread's caller MCP servers wholesale.
2287
+ *
2288
+ * For a credential or URL that changed: a rotated bearer token, a port that
2289
+ * moved. The provider picks the new servers up on the next turn. Header
2290
+ * values are sent to the runtime and never persisted by the SDK — the thread
2291
+ * store keeps header names only.
2292
+ *
2293
+ * A remote server passed without `headers` gets them from the client's
2294
+ * `mcpHeaders` callback, when there is one.
2295
+ *
2296
+ * Mid-turn, the runtime validates the servers at once (a bad map still
2297
+ * rejects) and queues them for the end of the running turn — completed,
2298
+ * interrupted or failed — and the call resolves. A later call replaces a
2299
+ * queued map. Until the swap the summary reports `mcpServersPending: true`,
2300
+ * and `mcpCapability` keeps describing the servers the running turn has. A
2301
+ * runtime without `capabilities.personalChats.deferredMcpUpdates` refuses
2302
+ * mid-turn instead (`turn_in_flight`).
2303
+ *
2304
+ * Refused by the SDK on a runtime that does not advertise
2305
+ * `capabilities.personalChats.updateMcpServers` (`invalid_option`) — an older
2306
+ * runtime would ignore the field and leave the old credentials in place,
2307
+ * which is worse than failing. The same goes for `allowedTools` /
2308
+ * `disallowedTools` on a runtime without `mcpToolFilters`, and for a filter
2309
+ * the thread's provider cannot enforce (see `McpToolFilter`).
2310
+ *
2311
+ * A map identical to the one this client last sent for the thread — header
2312
+ * values included — is not sent again: the call resolves with the current
2313
+ * `mcpCapability` and the provider is left alone. So a renderer that reloads
2314
+ * and repeats the same `refresh` does not restart anything.
2315
+ *
2316
+ * Resolves with the thread's new `mcpCapability`.
2317
+ */
2318
+ updateMcpServers(servers: Record<string, McpServerConfig>): Promise<McpCapabilityReport | null>;
2319
+ /**
2320
+ * Resolve this thread's MCP header values again through the client's
2321
+ * `mcpHeaders` callback and push them when they changed.
2322
+ *
2323
+ * `send`, `retry` and `editLast` already do this before every turn; call it
2324
+ * yourself right after rotating a token, so the swap does not wait for the
2325
+ * next message. The servers are the thread's own (the last map it was
2326
+ * opened or updated with); only the header values of its remote servers
2327
+ * that carry headers are re-resolved, and a thread with none is a no-op. Values
2328
+ * identical to the last ones sent push nothing. Mid-turn the push is queued
2329
+ * for the end of the turn, as `updateMcpServers` is.
2330
+ *
2331
+ * Throws `invalid_option` without an `mcpHeaders` callback, on a runtime
2332
+ * without `updateMcpServers`, and when the callback supplies nothing for a
2333
+ * server that needs headers: pushing would replace that server's live
2334
+ * credentials with none. A callback that throws rejects this call with its
2335
+ * error. Resolves with the thread's `mcpCapability`.
2336
+ */
2337
+ refreshMcpHeaders(): Promise<McpCapabilityReport | null>;
2338
+ /**
2339
+ * Switch this thread's model, including across providers — the runtime tears
2340
+ * the old one down and replays the transcript into the new one.
2341
+ *
2342
+ * Refused while a turn is in flight (code `turn_in_flight`, SDK >= 0.4)
2343
+ * unless `{ force: true }`: the switch would
2344
+ * end that turn without emitting `error` or `done`, so a caller who did not
2345
+ * know a turn was running would see the response simply stop. Await the turn
2346
+ * or `interrupt()` first.
2347
+ *
2348
+ * Returns what the model actually resolved to — the runtime resolves aliases
2349
+ * and CLI-wrapped ids, so it can differ from what you passed — together with
2350
+ * the four capability reports on the new provider. The same reports are
2351
+ * emitted as a `capabilities_changed` envelope on the `status` channel.
2352
+ */
2353
+ setModel(modelId: string, opts?: SetModelOptions): Promise<SetModelResult>;
2354
+ /**
2355
+ * The durable transcript, newest `limit` events (all of them when omitted,
2356
+ * up to the runtime's own cap of about 20,000 events / 2 MB). For a long
2357
+ * thread prefer `historyPage`, which reads one bounded page at a time.
2358
+ */
2359
+ history(opts?: {
2360
+ limit?: number;
2361
+ }): Promise<AgentChatEventEnvelope[]>;
2362
+ /** Token totals observed on this thread; cost is present only when reported by the provider. */
2363
+ usage(): ThreadUsage;
2364
+ /**
2365
+ * One page of the durable transcript, for "load older" on scroll.
2366
+ *
2367
+ * Without `beforeSequence` this is the newest page. Each page reports the
2368
+ * cursor for the one before it. Events are oldest-first within a page.
2369
+ *
2370
+ * On a runtime without the `getEventHistoryPage` action, only the newest page
2371
+ * is available: an older-page request returns an empty page with
2372
+ * `hasMore: false` and logs once.
2373
+ */
2374
+ historyPage(opts?: HistoryPageOptions): Promise<ThreadHistoryPage>;
2375
+ /**
2376
+ * Answer an approval this thread emitted.
2377
+ *
2378
+ * AN UNANSWERED APPROVAL BLOCKS THE TURN, with no timeout anywhere in the
2379
+ * runtime. This call and `interrupt()` are the only two ways out, and they
2380
+ * are not the same: this one answers the request and lets the turn continue,
2381
+ * while `interrupt()` aborts the turn without answering anything. A policy
2382
+ * with `approvalTimeoutMs` adds a third: the SDK declines the request itself
2383
+ * when the time runs out.
2384
+ *
2385
+ * Resolves once the runtime accepts the decision, NOT once the tool has run —
2386
+ * the same dispatch-resolution asymmetry `send()` has.
2387
+ *
2388
+ * Throws `approval_not_found` when the item is not pending: a stop, a
2389
+ * teardown, or an earlier call already settled it. The engine settles unknown
2390
+ * items silently, so without this check an answer to a dead card would look
2391
+ * like it worked.
2392
+ *
2393
+ * Use `respond()` for questions and plan approvals. This method accepts only
2394
+ * `"approval"` and `"permissions"` requests; an MCP elicitation that only
2395
+ * asks "may this tool run?" arrives as `"approval"` and is answerable here.
2396
+ *
2397
+ * `accept_always` settles this request and every later one the provider
2398
+ * considers the same, for the life of the session.
2399
+ */
2400
+ approve(itemId: string, decision: ApprovalDecision, responseText?: string): Promise<void>;
2401
+ /**
2402
+ * Every request this thread is currently blocked on.
2403
+ *
2404
+ * Call it after a reload to restore approval cards: the requests outlive the
2405
+ * client that saw the events. The `answerable` field identifies whether the
2406
+ * runtime supports a response for each request. Questions and plan approvals
2407
+ * use `respond()` when that action is available; tool approvals use
2408
+ * `approve()`.
2409
+ */
2410
+ pendingApprovals(): Promise<ApprovalRequest[]>;
2411
+ /**
2412
+ * Answer a question, structured question, or plan approval through the
2413
+ * runtime's `respondToInput` action. Question answers are keyed by question
2414
+ * id. Plan approval uses an explicit `decision` (`accept` or `decline`); the
2415
+ * SDK never infers it from option labels.
2416
+ */
2417
+ respond(requestId: string, response: ThreadRespondOptions): Promise<void>;
2418
+ /** Mutable queued sends belonging to this thread. */
2419
+ readonly queue: {
2420
+ list(): Promise<ThreadQueueItem[]>;
2421
+ cancel(id: string): Promise<void>;
2422
+ edit(id: string, text: string): Promise<void>;
2423
+ move(id: string, index: number): Promise<void>;
2424
+ dispatch(id: string): Promise<void>;
2425
+ cancelDispatched(id: string): Promise<void>;
2426
+ restore(): Promise<void>;
2427
+ };
2428
+ interrupt(options?: ThreadInterruptOptions): Promise<void>;
2429
+ stopTask(taskId: string): Promise<void>;
2430
+ slashCommands(): Promise<AgentChatSlashCommand[]>;
2431
+ recover(options?: {
2432
+ turnId?: string;
2433
+ action?: "wait" | "nudge" | "retry_same_runtime" | "restart_resume";
2434
+ }): Promise<AgentChatRecoverTurnResult>;
2435
+ resolveUnprocessed(args: {
2436
+ steerId: string;
2437
+ action: "run_next" | "dismiss";
2438
+ }): Promise<AgentChatResolveUnprocessedMessageResult>;
2439
+ readonly usageLimit: {
2440
+ resumeNow(): Promise<AgentChatUsageLimitResult>;
2441
+ continueOnAlternate(): Promise<AgentChatUsageLimitResult>;
2442
+ };
2443
+ switchAccount(instanceId: string): Promise<AgentChatSwitchAccountResult>;
2444
+ on(event: ThreadEventChannel, cb: (envelope: AgentChatEventEnvelope) => void): Unsubscribe;
2445
+ }
2446
+ /** @deprecated Use {@link DaexThread}. */
2447
+ type AdeThread = DaexThread;
2448
+
2449
+ type JsonSchema = {
2450
+ type?: "object" | "array" | "string" | "number" | "integer" | "boolean" | "null";
2451
+ properties?: Record<string, JsonSchema>;
2452
+ required?: string[];
2453
+ items?: JsonSchema;
2454
+ enum?: unknown[];
2455
+ additionalProperties?: boolean | JsonSchema;
2456
+ title?: string;
2457
+ description?: string;
2458
+ $schema?: string;
2459
+ $id?: string;
2460
+ default?: unknown;
2461
+ examples?: unknown[];
2462
+ };
2463
+ type RunOptions = Omit<ThreadOpenOptions, "provider" | "model"> & {
2464
+ provider: DaexProvider;
2465
+ model: string;
2466
+ schema?: JsonSchema;
2467
+ budget?: ThreadBudget;
2468
+ /**
2469
+ * Longest one turn may take, in ms (default 10 minutes). On expiry the turn
2470
+ * is interrupted and `run()` rejects with `rpc_timeout`.
2471
+ */
2472
+ timeoutMs?: number;
2473
+ };
2474
+ declare class InvalidOutputError extends DaexError {
2475
+ readonly rawText: string;
2476
+ constructor(rawText: string, reason: string);
2477
+ }
2478
+ declare function validateJsonSchema(value: unknown, schema: JsonSchema, path?: string, errors?: string[]): string[];
2479
+
2480
+ /**
2481
+ * RULE FOR ANYTHING ADDED TO THIS SURFACE — destructive while streaming.
2482
+ *
2483
+ * An SDK caller has no ambient signal that a turn is live. `send()` resolves as
2484
+ * soon as the turn is dispatched, not when it completes, so nothing in the API
2485
+ * tells a settings handler or a render effect that a reply is mid-flight. And
2486
+ * when a turn dies from a runtime teardown it emits neither `error` nor `done`
2487
+ * — subscribers just stop receiving. Silent truncation is therefore the default
2488
+ * failure mode of every destructive operation here, not an edge case.
2489
+ *
2490
+ * So any new operation that can end a running turn must pick one, explicitly:
2491
+ * - refuse mid-turn and name the way out (`setModel`, which throws and points
2492
+ * at `interrupt()` or `{ force: true }`); or
2493
+ * - proceed, and say plainly in its own docs that in-flight turns end without
2494
+ * a completion event (`dispose`, because a shutdown that can refuse is
2495
+ * worse than a lost reply).
2496
+ *
2497
+ * What is not acceptable is the third option: destroying the turn quietly and
2498
+ * letting the consumer discover it as a response that stopped mid-sentence.
2499
+ */
2500
+ interface DaexChatClient {
2501
+ accounts: AccountManagement["accounts"];
2502
+ credentials: AccountManagement["credentials"];
2503
+ presets: AccountManagement["presets"];
2504
+ providers: {
2505
+ /**
2506
+ * Per-provider install, auth and availability.
2507
+ *
2508
+ * Served from the runtime's probe cache when the runtime supports it, and
2509
+ * derived from the model catalog when it does not. Read `source` on each
2510
+ * record before presenting any of it as a fact about the machine.
2511
+ */
2512
+ status(): Promise<Record<string, ProviderStatus>>;
2513
+ /**
2514
+ * The same map, with the runtime's probe cache bypassed.
2515
+ *
2516
+ * This is the "I just installed it" button. It spawns `--version` for every
2517
+ * provider, so it is the slow path — `status()` and the `onChange` poll
2518
+ * never bypass the cache.
2519
+ */
2520
+ refresh(): Promise<Record<string, ProviderStatus>>;
2521
+ onChange(cb: (status: Record<string, ProviderStatus>) => void): Unsubscribe;
2522
+ /** Runtime-derived controls for a provider, or `unsupported` when absent. */
2523
+ capabilities(provider: string): Promise<ProviderCapabilities>;
2524
+ };
2525
+ models: {
2526
+ list(): Promise<ModelCatalogEntry[]>;
2527
+ /**
2528
+ * Called with the whole catalog when it changes: a provider signs in or
2529
+ * out, or the runtime's catalog gains or drops a model. Driven by the same
2530
+ * poll as `providers.onChange`, and called only when a model's id,
2531
+ * `isAvailable`, `connected` or `isDefault` changed. Not called with the
2532
+ * current list on subscribe; call `list()` for that. SDK >= 0.4.
2533
+ */
2534
+ onChange(cb: (models: ModelCatalogEntry[]) => void): Unsubscribe;
2535
+ /**
2536
+ * The model a new thread should use, or null when none qualifies. See
2537
+ * `pickDefaultModel` for the rule; this reads a fresh catalog first.
2538
+ * SDK >= 0.4.
2539
+ */
2540
+ defaultModel(opts?: DefaultModelOptions): Promise<ModelCatalogEntry | null>;
2541
+ };
2542
+ threads: {
2543
+ /** Open a thread, creating it when the key is new to this home. */
2544
+ open(key: string, opts: ThreadOpenOptions): Promise<DaexThread>;
2545
+ /**
2546
+ * Reopen a key this home already stores. The provider and model come from
2547
+ * the stored record, so an app that reopens `"support"` after a restart
2548
+ * does not have to remember how it was created.
2549
+ */
2550
+ open(key: string, opts?: ThreadResumeOptions): Promise<DaexThread>;
2551
+ /**
2552
+ * Every chat in this home, archived ones included, newest activity first
2553
+ * is NOT guaranteed — sort on `updatedAt` yourself.
2554
+ */
2555
+ list(): Promise<ThreadSummary[]>;
2556
+ /**
2557
+ * One thread's summary, by key, or null when the runtime has no session for
2558
+ * it: a key this home never opened, a deleted key, or a key whose session
2559
+ * the runtime lost (the next `open` recreates it). The same row `list()`
2560
+ * would return, without reading every chat. SDK >= 0.4.
2561
+ */
2562
+ get(key: string): Promise<ThreadSummary | null>;
2563
+ /**
2564
+ * Delete a thread: its runtime session, its transcript, and its key.
2565
+ *
2566
+ * A running turn is interrupted FIRST, so subscribers receive the turn's
2567
+ * `done` before the session goes away rather than a stream that simply
2568
+ * stops. Then the runtime deletes the session, the key is removed from the
2569
+ * thread store, and a live `DaexThread` for the key is released — it throws
2570
+ * `disposed`-style errors from the runtime afterwards, so drop it.
2571
+ *
2572
+ * A key whose session the runtime already lost is still removed. A key the
2573
+ * store does not know and no live thread holds throws `thread_not_found`.
2574
+ * Throws `invalid_option` on a runtime without the `delete` action.
2575
+ */
2576
+ delete(key: string): Promise<void>;
2577
+ /**
2578
+ * Archive a thread. The key and transcript are kept; `list()` reports it
2579
+ * with `archived: true`, and `unarchive` brings it back.
2580
+ *
2581
+ * Like `delete`, a running turn is interrupted first so it ends with a
2582
+ * `done` event rather than silently. Throws `thread_not_found` for a key
2583
+ * the store does not know, and `invalid_option` on a runtime without the
2584
+ * `archive` action.
2585
+ */
2586
+ archive(key: string): Promise<void>;
2587
+ /** Reverse `archive`. Same errors. */
2588
+ unarchive(key: string): Promise<void>;
2589
+ };
2590
+ doctor(): Promise<DoctorReport>;
2591
+ exportThread(key: string): Promise<string>;
2592
+ /** Run a temporary thread and delete it after the final answer is received. */
2593
+ run<T = unknown>(prompt: string, options: RunOptions): Promise<T | string>;
2594
+ /**
2595
+ * Listen for runtime lifecycle events: `"exit"`, `"transport"`, `"restart"`.
2596
+ * See {@link DaexClientEventMap} for the payloads. Returns the unsubscribe.
2597
+ *
2598
+ * Listeners survive an `autoRestart`, because the client object does.
2599
+ */
2600
+ on<E extends DaexClientEvent>(event: E, cb: (payload: DaexClientEventMap[E]) => void): Unsubscribe;
2601
+ /**
2602
+ * Stop the runtime and release this client. Idempotent.
2603
+ *
2604
+ * Ends any turn still in flight, and — like every teardown on this surface —
2605
+ * without an `error` or `done` event first: the child process goes away, so
2606
+ * subscribers simply stop receiving. Deliberately NOT guarded the way
2607
+ * `setModel` is, because dispose is the teardown path and a shutdown that can
2608
+ * refuse is worse than a truncated reply. If a caller needs the reply, it
2609
+ * must await the turn before disposing; the transcript is durable either way
2610
+ * and `exportThread` still returns everything that was persisted.
2611
+ */
2612
+ dispose(): Promise<void>;
2613
+ }
2614
+ /**
2615
+ * Boots an isolated DAEX runtime and returns a chat client that owns it.
2616
+ *
2617
+ * The returned client owns the child process: `dispose()` stops it, and the
2618
+ * process exit hooks stop it if the host dies first. Two clients on one `home`
2619
+ * would fight over the same socket and state root, so an app opens one per
2620
+ * isolated home.
2621
+ *
2622
+ * Before shipping, read the MCP caveat on
2623
+ * {@link ThreadOpenOptions.loadUserMcpServers}: withholding the user's own MCP
2624
+ * config is enforced only on Claude and best-effort on Codex, Cursor, Droid,
2625
+ * Muse and OpenCode. Check `thread.mcpCapability.strictRequested === true` AND
2626
+ * `.level === "enforced"` before telling your users that only their tools are
2627
+ * loaded — on a delivery-only thread the level says nothing about isolation.
2628
+ */
2629
+ declare function createDaexChat(options: CreateDaexChatOptions | InternalAdeChatOptions): Promise<DaexChatClient>;
2630
+ /** @deprecated Use {@link DaexChatClient}. */
2631
+ type AdeChatClient = DaexChatClient;
2632
+ /** @deprecated Use {@link createDaexChat}. */
2633
+ declare const createAdeChat: typeof createDaexChat;
2634
+
2635
+ export { type HostConfigCapability as $, type AgentChatEventEnvelope as A, type AgentChatSettingSources as B, type ApiCredentialInfo as C, type DaexClientEvent as D, type ApprovalDecision as E, type ApprovalRequest as F, type AttachmentRootCheck as G, type AttachmentRootFilterResult as H, type InstructionsCapability as I, type CapabilitiesChangedEvent as J, type CreateAdeChatOptions as K, type CreateDaexChatOptions as L, type McpCapabilityReport as M, DAEX_CLIENT_EVENTS as N, DEFAULT_RELEASE_REPO as O, type ProviderStatus as P, type DaexProvider as Q, type RuntimeCompatibility as R, type SettingSourcesCapability as S, type ThreadModelSelection as T, type DaexThread as U, type DefaultModelOptions as V, type DoctorReport as W, type DownloadRequest as X, type DownloadResult as Y, type EditLastOptions as Z, type HistoryPageOptions as _, type DaexClientEventMap as a, InvalidOutputError as a0, type JsonSchema as a1, type KnownAgentChatEvent as a2, MAX_ATTACHMENT_ROOTS as a3, type McpHeadersResolver as a4, type McpServerConfig as a5, type McpToolFilter as a6, type ModelCatalogEntry as a7, type PendingInputKind as a8, type PendingInputOption as a9, type ThreadRefreshOptions as aA, type ThreadRerunResult as aB, type ThreadRespondOptions as aC, type ThreadUpdate as aD, type ThreadUpdateOptions as aE, type ThreadUpdateResult as aF, type ThreadUsage as aG, type Unsubscribe as aH, type UsageLimitEvent as aI, type UsageLimitResume as aJ, assetUrl as aK, checkAttachmentRoot as aL, createAdeChat as aM, createDaexChat as aN, filterAttachmentRoots as aO, isApprovalShaped as aP, isSupportedProvider as aQ, parseChecksums as aR, pickDefaultModel as aS, resolveRuntimeTarget as aT, runtimeSpawnEnv as aU, validateJsonSchema as aV, type AccountManagement as aW, type AgentChatSlashCommand as aX, type PendingInputQuestion as aa, type PendingInputRequest as ab, type PendingInputSource as ac, type PermissionPreset as ad, type ProviderCapabilities as ae, type ProviderStatusProbeRecord as af, type ProviderStatusRpcResult as ag, type RunOptions as ah, type RuntimeDownloader as ai, type RuntimeTarget as aj, SUPPORTED_PROVIDERS as ak, type SendOptions as al, type SetModelOptions as am, type SetModelResult as an, type SignInHandle as ao, type SignInStatus as ap, type SteerOptions as aq, type SyntheticRuntimeLostStatusEvent as ar, type ThreadBudget as as, type ThreadCapabilities as at, type ThreadEventChannel as au, type ThreadHistoryPage as av, type ThreadInstructions as aw, type ThreadInterruptOptions as ax, type ThreadPermissionPolicy as ay, type ThreadQueueItem as az, type PermissionCapability as b, type DaexChatClient as c, type ThreadSummary as d, type ThreadOpenOptions as e, type ThreadResumeOptions as f, AdeError as g, type AdeErrorCode as h, DaexError as i, type DaexErrorCode as j, ADE_CLIENT_EVENTS as k, APPROVAL_DECISIONS as l, type AccountInfo as m, type AccountUsage as n, type AdeChatClient as o, type AdeClientEvent as p, type AdeClientEventMap as q, type AdeProvider as r, type AdeThread as s, type AgentChatCodexCollaborationMode as t, type AgentChatEvent as u, type AgentChatFileRef as v, type AgentChatHostConfigLevel as w, type AgentChatInstructions as x, type AgentChatSessionStatus as y, type AgentChatSessionSummary as z };