@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Arul Sharma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,479 @@
1
- # Temporary Holding Version
1
+ # @daex-dev/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed Node / Electron-main client that spawns a slim DAEX runtime as a sidecar
4
+ and exposes chat as durable named threads.
5
+
6
+ Formerly `@ade-dev/sdk`. To move, change your imports to `@daex-dev/sdk`; the
7
+ `Ade*` names (`createAdeChat`, `AdeError`, ...) still work as deprecated aliases
8
+ of the `DAEX*` names.
9
+
10
+ **Docs:** [DAEX SDK](https://ade-app.dev/docs/sdk/overview) — install, threads, MCP honesty table, chat UI, runtime, and API reference.
11
+
12
+ | Page | What it covers |
13
+ |---|---|
14
+ | [Threads](https://ade-app.dev/docs/sdk/threads) | Lifecycle, attachments, paged history, configuration and model switching |
15
+ | [Accounts](https://ade-app.dev/docs/sdk/accounts) | Isolated sign-in, provider accounts, credentials, endpoint presets and usage limits |
16
+ | [Bring your own AI plan](https://ade-app.dev/docs/sdk/connect) | Sign in with ChatGPT or Cursor; AI calls on the user's own plan |
17
+ | [MCP servers](https://ade-app.dev/docs/sdk/mcp) | Injected tools, credentials that change, resource links, and the strict-mode honesty table |
18
+ | [Permissions](https://ade-app.dev/docs/sdk/permissions) | The policy object, per-provider enforcement, answering approvals |
19
+ | [Accounts](https://ade-app.dev/docs/sdk/accounts) | Isolated sign-in, provider accounts, stored credentials, presets and usage limits |
20
+ | [Chat UI](https://ade-app.dev/docs/sdk/chat-ui) | `@daex-dev/chat-ui`, theming, approval cards, provider cards |
21
+ | [Electron](https://ade-app.dev/docs/sdk/electron) | The main / preload / renderer bridge under `sandbox: true` |
22
+ | [WebSocket server](https://ade-app.dev/docs/sdk/server) | Authorized server bridge and browser remote client |
23
+ | [Testing](https://ade-app.dev/docs/sdk/testing) | Mock clients and transcript replay without a runtime or provider tokens |
24
+ | [Bundling](https://ade-app.dev/docs/sdk/bundling) | Platform packages, `codesign`, entitlements, electron-builder |
25
+ | [Runtime](https://ade-app.dev/docs/sdk/runtime) | The sidecar, exit events and `autoRestart`, version compatibility, and `doctor().runtime` provenance |
26
+ | [Reference](https://ade-app.dev/docs/sdk/reference) | Every option, shape, and error code |
27
+ | [License](https://ade-app.dev/docs/sdk/license) | What each artifact is licensed under |
28
+
29
+ ```bash
30
+ npm install @daex-dev/sdk
31
+ ```
32
+
33
+ Requires Node 22.13 or newer. The sidecar is a guest: isolated `home`, sync off, no
34
+ machine-brain authority. It dies with your process.
35
+
36
+ SDK 0.7 supports runtime `>=1.2.82 <2.0.0` (`SUPPORTED_RUNTIME_RANGE`). The
37
+ lower bound did not move in 0.5 or 0.6, so a host on runtime 1.2.82 keeps
38
+ working. On an older runtime, MCP tool filters are refused before they are
39
+ sent (they need `capabilities.personalChats.mcpToolFilters`), and a mid-turn
40
+ `updateMcpServers` is refused with `turn_in_flight` instead of queued; the
41
+ header refresh needs nothing new. An older or newer runtime still
42
+ connects, logs one warning, and degrades feature by feature. Pass
43
+ `requireCompatibleRuntime: true` to refuse it with
44
+ `runtime_incompatible`. `doctor().runtime.compatibility` reports the verdict.
45
+
46
+ ## Quickstart
47
+
48
+ ```ts
49
+ import { createDaexChat } from "@daex-dev/sdk";
50
+
51
+ const daex = await createDaexChat({ home: "./.ade-embed" });
52
+ const thread = await daex.threads.open("support", {
53
+ provider: "claude",
54
+ model: "claude-sonnet-4-5",
55
+ });
56
+ thread.on("event", (envelope) => console.log(envelope.event.type));
57
+ await thread.send("Summarise today's incidents");
58
+ console.log(thread.usage());
59
+ ```
60
+
61
+ `thread.usage()` reports cumulative token totals and provider-reported cost.
62
+ Pass `budget: { maxTokens, maxCostUsd }` when creating a thread to interrupt it
63
+ when a reported limit is reached. Budgets persist with the thread key.
64
+
65
+ Use `daex.run(prompt, { provider, model, schema })` for a temporary one-shot
66
+ thread. A schema response is parsed and checked locally, retried once when it
67
+ does not match, then rejected with `InvalidOutputError` carrying `rawText`.
68
+
69
+ Reopening `"support"` after a restart resumes the same conversation. Call
70
+ `daex.dispose()` when the host shuts down.
71
+
72
+ ## Provider auth
73
+
74
+ The sidecar reuses the provider CLIs and logins already on the machine
75
+ (`claude`, `codex`, `cursor`, …). DAEX state under `home` is isolated; Claude /
76
+ Codex / Cursor credentials still live in those tools' own config homes
77
+ (`~/.claude`, `~/.codex`, `~/.cursor`). If the host user can already run that
78
+ provider in a terminal, the sidecar can too. SDK 0.7 defaults to isolated
79
+ provider logins. **BREAKING from SDK 0.6:** pass
80
+ `useMachineLogin: true` to keep relying on the host machine's Claude or Codex
81
+ login, or sign the user in through `daex.accounts.signIn()` (see
82
+ [Accounts](https://ade-app.dev/docs/sdk/accounts)).
83
+
84
+ `daex.providers.status()` reports, per provider, whether a binary was found, at
85
+ which path and version, and whether credentials are present. Read `source`
86
+ first: `"probed"` means the runtime looked at the filesystem, `"derived"` means
87
+ it is an older runtime inferring from the model catalog. `daex.providers.refresh()`
88
+ bypasses the runtime's 60-second probe cache.
89
+
90
+ `daex.doctor()` is the structured health check: binary path and provenance,
91
+ socket, event transport, providers, and known threads.
92
+
93
+ ```ts
94
+ const report = await daex.doctor();
95
+ if (!report.ok) console.error(report);
96
+ ```
97
+
98
+ Pin a specific DAEX build with `binaryPath`, or let the client download a
99
+ release. Downloads are fail-closed against that release's `SHA256SUMS`.
100
+
101
+ ## Threads
102
+
103
+ ```ts
104
+ const thread = await daex.threads.open("support", {
105
+ provider: "claude",
106
+ model: "claude-sonnet-4-5",
107
+ permissions: "always-allow",
108
+ });
109
+
110
+ await thread.send("What changed?");
111
+ await thread.steer("Focus on the outage"); // mid-turn follow-up
112
+ await thread.steer("", { attachments: [{ path: "/abs/path/log.txt" }] });
113
+ await thread.interrupt();
114
+ await thread.setModel("claude-opus-4"); // see setModel below
115
+ await thread.update({ title: "Outage review" });
116
+
117
+ const page = await thread.historyPage({ limit: 200 }); // newest page
118
+ const rows = await daex.threads.list(); // title, archived, updatedAt, modelSelection
119
+ await daex.threads.archive("support"); // or unarchive / delete
120
+ ```
121
+
122
+ `threads.open(key)` is open-or-resume by key stored under `home`. Keys survive
123
+ host restarts. `exportThread(key)` returns the transcript as one JSON envelope
124
+ per line. `thread.title` and `thread.model` (with `displayName`) are on the
125
+ handle.
126
+
127
+ `threads.delete(key)` removes the runtime session, the transcript and the key.
128
+ `archive` keeps both. Each interrupts a running turn first.
129
+
130
+ `thread.update({ title, reasoningEffort, fastMode }, { force })` renames at any
131
+ time. The other two fields are refused mid-turn unless `{ force: true }`.
132
+
133
+ Attachments are `{ path, name?, mimeType?, type?, hydrate? }` refs. `type`
134
+ (`"file"` or `"image"`) is inferred from the MIME type or extension when
135
+ absent, so an image reaches the model as an image. `hydrate: false` sends the
136
+ path only and the runtime never reads the bytes. An absolute path must be
137
+ inside the chat's `cwd`, `<home>/personal-chats/state`, or a directory in the
138
+ thread's `attachmentRoots` (0.4, runtime 1.2.82). See
139
+ [Attachments](https://ade-app.dev/docs/sdk/threads#attachments) for the
140
+ size limits.
141
+
142
+ One refused `attachmentRoots` entry fails the whole open, and a host normally
143
+ sends the same roots every time. Test a candidate with `checkAttachmentRoot`,
144
+ or prepare the whole list with `filterAttachmentRoots`, which drops a bad entry
145
+ and reports why (both 0.5). A list identical to the one already in use is not
146
+ sent again, so a repeated list costs no update call.
147
+
148
+ `thread.retry()` and `thread.editLast(text)` (0.4, runtime 1.2.82) roll the
149
+ provider back and run the last user message again, and the transcript shows it
150
+ once. Claude and Codex only; another provider throws `unsupported`, and a
151
+ running turn throws `turn_in_flight`. The rollback covers the conversation, not
152
+ the disk: files the old turn wrote stay, and the result does not report them.
153
+ If you allow writes, inspect the events at or after `retractedFromSequence` in
154
+ your own history copy and warn the user.
155
+
156
+ `models.defaultModel({ prefer })` (0.5) takes your own ranking inside one
157
+ provider's models. Return a number above zero to prefer a model — the highest
158
+ score wins — so a host that wants the newest Sonnet, not the provider's
159
+ default, states it here instead of keeping its own copy of the rule. A model
160
+ nobody scores falls back to `isDefault`, then to catalog order.
161
+
162
+ Host configuration applies on **create only**. A resume re-applies what the key
163
+ was created with and ignores the `cwd`, `instructions`, `settingSources`,
164
+ `permissions`, `mcpServers` and `loadUserMcpServers` passed to that call,
165
+ logging one line per option it ignored. Open a different key to run under
166
+ different configuration — do not assume a tighter policy took effect because you
167
+ passed one. The one exception is `refresh.mcpServers` (see below).
168
+
169
+ When the runtime lost a key's session, the SDK **recreates** it from the stored
170
+ record. The record wins for `provider`, `model`, `cwd`, `instructions`,
171
+ `settingSources`, `permissions`, `mcpServers` and `loadUserMcpServers`; the
172
+ call's options only fill a field the record lacks. Before 0.3 the call's
173
+ options won. A recreate changes `thread.id`, so key your state on `key`.
174
+
175
+ `setModel` returns the resolved model with `displayName` and the four
176
+ capability reports on the new provider, and emits `capabilities_changed` on the
177
+ `status` channel.
178
+
179
+ `setModel` refuses while a turn is in flight — call `interrupt()` first, or
180
+ pass `{ force: true }` to accept losing the turn. `dispose()` is not guarded
181
+ that way: a shutdown that can refuse is worse than a truncated reply. The
182
+ transcript is durable either way.
183
+
184
+ ## MCP servers and strict mode
185
+
186
+ ```ts
187
+ const thread = await daex.threads.open("ops", {
188
+ provider: "claude",
189
+ model: "claude-sonnet-4-5",
190
+ mcpServers: {
191
+ docs: { type: "http", url: "https://mcp.example/mcp" },
192
+ },
193
+ // default: withhold the user's own MCP config
194
+ // loadUserMcpServers: true // opt back in
195
+ });
196
+
197
+ if (thread.mcpCapability?.strictRequested && thread.mcpCapability.level !== "enforced") {
198
+ console.warn(thread.mcpCapability.residual);
199
+ }
200
+ ```
201
+
202
+ Supplying `mcpServers` turns on strict mode unless you set
203
+ `loadUserMcpServers: true`. **False is not a uniform guarantee.** Only Claude
204
+ can enforce it. Everywhere else DAEX applies the strongest mechanism that
205
+ provider exposes, and Pi has no MCP surface at all (injected servers are
206
+ refused rather than opening a tool-less thread):
207
+
208
+ | Provider | Strict mode | What still loads under strict |
209
+ |---|---|---|
210
+ | claude | enforced | nothing MCP-wise (user rules/commands/output styles still load — they are not MCP) |
211
+ | codex | best-effort | servers contributed by a Codex *plugin* |
212
+ | cursor | best-effort | user-layer servers (`~/.cursor`; DAEX's own preToolUse hook lives there) |
213
+ | droid | best-effort | tools that appear only after the first disable pass |
214
+ | opencode | best-effort | the global OpenCode config directory (for auth) |
215
+ | pi | unsupported | n/a — create refuses injected servers |
216
+
217
+ The server shape is checked against the selected provider before launch. Codex
218
+ does not support `sse`, so a Codex request containing an SSE entry is rejected.
219
+ Server names `computer_use` and `daex-cto` are reserved (so is `ade-cto`, its
220
+ name before the DAEX rename), and a request may contain at most 32 servers.
221
+
222
+ Read `thread.mcpCapability` after open. `strictRequested` first, then `level`.
223
+ `"enforced"` is the only value that means "nothing but the servers I supplied".
224
+ Do not tell your users "only your tools are loaded" without checking that.
225
+
226
+ ### Credentials that change
227
+
228
+ The SDK never writes MCP header values to disk. The thread store keeps header
229
+ names only, and a pre-0.3 store is migrated on first read. The runtime does the
230
+ same. So supply current values in one of three ways:
231
+
232
+ ```ts
233
+ const daex = await createDaexChat({
234
+ home,
235
+ mcpHeaders: (key, server) => (server === "app" ? { Authorization: `Bearer ${token()}` } : undefined),
236
+ });
237
+ await daex.threads.open("support", { refresh: { mcpServers: { app: { type: "http", url, headers } } } });
238
+ await thread.updateMcpServers({ app: { type: "http", url: newUrl, headers: newHeaders } });
239
+ ```
240
+
241
+ `refresh.mcpServers` replaces the servers on a resume or a recreate.
242
+ `thread.updateMcpServers()` replaces them on a live thread, for the next turn;
243
+ mid-turn the runtime queues them for the end of the turn, and a runtime before
244
+ 1.2.81 refuses. Without any of the three, a server connects without its
245
+ headers and the SDK logs a line.
246
+
247
+ `mcpHeaders` may be async, and it runs before every `send`, `retry` and
248
+ `editLast` of a thread with remote servers: a token that changed (an OAuth
249
+ access token that expired) is pushed before the turn, and the provider resumes
250
+ the same conversation with it. `thread.refreshMcpHeaders()` does the same on
251
+ demand, right after you rotate a token.
252
+
253
+ Each server can also carry `allowedTools` / `disallowedTools` (bare tool
254
+ names). Codex enforces both; Claude enforces `disallowedTools` only; other
255
+ providers refuse both rather than ignore them. URL query
256
+ strings and stdio `env` values are still stored; do not put secrets there.
257
+
258
+ Tool results carry MCP `resource_link` items as `event.resourceLinks` on Codex
259
+ and on Claude (MCP tools only). Other providers do not pass them.
260
+
261
+ ## Shaping the session
262
+
263
+ `threads.open` takes four options beyond the provider and model. Each one is
264
+ optional, each persists on the thread record, and omitting all four reproduces
265
+ 0.1.x behavior exactly.
266
+
267
+ ```ts
268
+ const thread = await daex.threads.open("assistant", {
269
+ provider: "claude",
270
+ model: "claude-sonnet-4-5",
271
+ instructions: { mode: "replace", text: "You are Ada, MyApp's assistant." },
272
+ cwd: "/Users/me/Library/Application Support/MyApp/work",
273
+ settingSources: "project",
274
+ permissions: {
275
+ allowedTools: ["mcp:catalog:*", "Read"],
276
+ deniedTools: ["Bash"],
277
+ fallback: "deny",
278
+ },
279
+ });
280
+ ```
281
+
282
+ - **`instructions`** — your own system instructions, never a hidden first
283
+ message. A bare string means append. See [Threads](https://ade-app.dev/docs/sdk/threads).
284
+ - **`cwd`** — the absolute directory the provider runs in. Defaults to a scratch
285
+ workspace under `home`. Relative paths and `~` are refused.
286
+ - **`settingSources`** — which on-disk config the provider loads. `"none"` is the
287
+ default and is what every 0.1.x thread got.
288
+ - **`permissions`** — a policy object is the third form, alongside `"default"`
289
+ and `"always-allow"`. `fallback` is required. See
290
+ [Permissions](https://ade-app.dev/docs/sdk/permissions).
291
+
292
+ Each one reports back what the provider actually did, the same way
293
+ `mcpCapability` does. Read `thread.instructionsCapability`,
294
+ `thread.settingSourcesCapability` and `thread.permissionCapability`, and branch
295
+ on `level` — the presence of a report is never itself a guarantee.
296
+
297
+ An approval blocks the turn until it is answered. Handle `approval_request` with
298
+ `thread.approve(itemId, decision)`, restore cards after a reload with
299
+ `thread.pendingApprovals()`, or pass `fallback: "deny"` so nothing ever asks.
300
+ `approvalTimeoutMs` on the policy (opt-in, enforced by the SDK) declines an
301
+ approval-shaped request that this client saw and nobody answered in time.
302
+
303
+ On Codex, every MCP tool call raises an approval, and the policy judges it as
304
+ `mcp:<server>:<tool>`: `deniedTools`, then `allowedTools` /
305
+ `autoApproveMcpServers`, then `fallback`. `accept_always` remembers the answer
306
+ for the session only. On Codex, `sandboxRoot` still decides command and file
307
+ escapes, and the tool fields do not.
308
+
309
+ The CTO's own tool server is `daex-cto`. `ade-cto`, its name before the DAEX
310
+ rename, is a deprecated alias: `mcp:ade-cto:*` (or `ade-cto` in
311
+ `autoApproveMcpServers`) still matches the server, in allow and deny rules
312
+ alike. Write `daex-cto` in new policies.
313
+
314
+ On Claude (Agent SDK 0.3.280), `canUseTool` fires for MCP tools and for
315
+ commands that change things, not for commands Claude Code classifies as
316
+ read-only. `fallback: "ask"` stays `best-effort` for that reason.
317
+
318
+ On Claude a deny fallback does more than skip the prompt. It removes every
319
+ mutating built-in the policy does not name from the model's catalog, and scopes
320
+ MCP to the servers the policy names — including servers you injected yourself,
321
+ so name those in the policy too. `sandboxRoot` is not applied in that mode: an
322
+ unnamed tool is refused outright rather than contained. Read
323
+ `thread.permissionCapability.residual`, and see
324
+ [Permissions](https://ade-app.dev/docs/sdk/permissions).
325
+
326
+ ## Bring your own AI plan (`@daex-dev/sdk/connect`)
327
+
328
+ Let your app's users power its AI features with a plan they already pay for,
329
+ so your app pays for no AI. They press **Sign in with ChatGPT** or **Sign in
330
+ with Cursor** once; your server keeps the sign-in sealed and renewed and makes
331
+ AI calls with it. This entry point does not start a DAEX runtime.
332
+
333
+ ```ts
334
+ import { createConnectHandler, createConnectVault, provideCursorSdk } from "@daex-dev/sdk/connect";
335
+
336
+ provideCursorSdk(() => import("@cursor/sdk")); // only if you offer Cursor
337
+
338
+ const vault = createConnectVault({ storage: yourKeyValueStore, secret: process.env.CONNECT_SECRET! });
339
+ const handler = createConnectHandler({
340
+ vault,
341
+ appName: "My App",
342
+ hostId: process.env.CONNECT_HOST_ID!, // newCodexHostId(), generated once
343
+ getUserId: (request) => yourSession(request)?.userId ?? null,
344
+ });
345
+ // Fetch API (Next.js route handlers need a Response, never null):
346
+ const route = (request: Request) => handler(request).then((response) => response ?? new Response("Not found", { status: 404 }));
347
+ export { route as GET, route as POST };
348
+ // Node/Express: app.use(toNodeListener(handler))
349
+ ```
350
+
351
+ On the page:
352
+
353
+ ```ts
354
+ import { createConnectClient } from "@daex-dev/sdk/connect/browser";
355
+
356
+ const connect = createConnectClient({ baseUrl: "/connect" });
357
+ await connect.signIn("cursor");
358
+ await connect.signIn("codex", { askForRedirectUrl: () => askUserToPaste() });
359
+ for await (const event of connect.respond({ provider: "codex", prompt: "Summarize my notes" })) {
360
+ if (event.type === "text") append(event.delta);
361
+ }
362
+ ```
363
+
364
+ On the server, `createConnectAI({ vault }).respond(userId, { provider, prompt })`
365
+ does the same without HTTP. Every request can set `model`, `effort`,
366
+ `responseFormat` (JSON schema), `rawEvents`, raw OpenAI Responses fields
367
+ (`codex: { tools, reasoning, text, … }`) and Cursor model parameters and agent
368
+ options (`cursor: { params, agent, send }`); yours win over the defaults. A
369
+ browser may set model, instructions, effort, format and Cursor `params`;
370
+ `prepareRequest` decides everything else (raw `codex` fields and Cursor agent
371
+ options run with your server's authority, so they never come from a page
372
+ unless you pass them on). `ConnectError.code` says what to show:
373
+ `not_signed_in`, `sign_in_required`, `usage_limit` (with `manageUrl`),
374
+ `plan_usage_disabled`, `provider_unavailable` and more.
375
+
376
+ - **ChatGPT** (Plus or Pro): OpenAI returns the browser to
377
+ `http://127.0.0.1:…`. A desktop app catches it with
378
+ `signInWithCodexOnThisDevice`; a web page asks the user to paste the address
379
+ the tab ended on. Tokens renew themselves; one server holds each sign-in.
380
+ - **Cursor**: `npm install @cursor/sdk`. The user opens a link and your server
381
+ waits; Cursor mints a 90-day key on the user's plan. Replies run as a Cursor
382
+ agent on an in-memory file tree.
383
+ - Storage is any key-value store (`get`/`set`/`delete`, optional `lock` for
384
+ several server instances). Rows are AES-256-GCM sealed and keyed by a hash of
385
+ the user ID. Runnable example: `examples/connect`.
386
+
387
+ ## Electron
388
+
389
+ Run this from the main process, not the renderer. Spawn owns a child process
390
+ and a socket / named pipe.
391
+
392
+ ```ts
393
+ const daex = await createDaexChat({
394
+ home: path.join(app.getPath("userData"), "ade"),
395
+ });
396
+ ```
397
+
398
+ Do not write the bridge yourself. `@daex-dev/sdk/electron`,
399
+ `@daex-dev/sdk/electron/preload` and `@daex-dev/sdk/electron/renderer` ship one
400
+ function per process, with listener teardown on reload and the history-and-live
401
+ ordering rule already in code. None of the three depends on `electron`.
402
+ `@daex-dev/sdk/electron/global` types `window.ade`. For a `sandbox: true`
403
+ preload, point `webPreferences.preload` at
404
+ `require.resolve("@daex-dev/sdk/electron/preload-auto")` (default key and
405
+ prefix), copy the ten-line preload from the docs, or bundle `exposeDaexBridge`
406
+ into one file. `@daex-dev/sdk/electron/preload` alone only exports the function
407
+ and exposes nothing. See
408
+ [Electron](https://ade-app.dev/docs/sdk/electron).
409
+
410
+ The renderer does not configure threads. Pass `openOptions: (key, rendererOptions) => ThreadOpenOptions`
411
+ to `registerDaexIpc` and main decides; without it, only `provider`, `model`,
412
+ `title` and `reasoningEffort` cross (breaking in 0.3). `allowModel` gates model
413
+ choice. `registerDaexIpc` also accepts `() => client`, for a host that replaces
414
+ its client per account.
415
+
416
+ `onThreadRemoved(key, kind)` (0.5) fires for every delete and archive the served
417
+ client reports, whether the renderer or your own main-process code made it, so
418
+ your chat list stays exact. It follows a client swapped per account as soon as
419
+ the bridge serves a call. Refuse `threads.delete` or `threads.archive` in
420
+ `authorize` to stop the renderer from making them at all — there is no separate
421
+ deny list.
422
+
423
+ To ship the runtime inside a signed app instead of downloading it, install
424
+ `@daex-dev/runtime`, copy it into your resources, and pass
425
+ `...resolvePackagedRuntime(process.resourcesPath)` with `allowDownload: false`.
426
+ `doctor().runtime.source` then reports `"packaged"`. See
427
+ [Bundling](https://ade-app.dev/docs/sdk/bundling).
428
+
429
+ ## Runtime exits
430
+
431
+ ```ts
432
+ const daex = await createDaexChat({ home, autoRestart: true });
433
+ daex.on("exit", ({ code, signal, error }) => {});
434
+ daex.on("transport", ({ state }) => {}); // "closed" | "reconnected"
435
+ daex.on("restart", ({ attempt, ok }) => {});
436
+ ```
437
+
438
+ When the runtime exits, each live thread gets a synthetic
439
+ `{ type: "status", turnStatus: "failed", message, synthetic: true }` envelope.
440
+ `autoRestart` (off by default; `true` = 5 attempts, 1 s doubling backoff)
441
+ respawns the runtime and re-opens every live thread. The client object stays
442
+ the same. A turn in flight is not resumed. See
443
+ [Runtime](https://ade-app.dev/docs/sdk/runtime#when-the-runtime-exits).
444
+
445
+ ## The live seam test
446
+
447
+ `npm test` runs against an in-process fake runtime, so it can only prove the SDK
448
+ agrees with itself. `test/live.integration.test.ts` boots a real DAEX runtime and
449
+ checks that both sides agree on the wire. It is opt-in and skips itself when the
450
+ binary is not named.
451
+
452
+ Build the runtime first, then point the test at it:
453
+
454
+ ```sh
455
+ cd apps/ade-cli && npm run build
456
+ cd packages/sdk
457
+ ADE_SDK_LIVE_BINARY=../../apps/ade-cli/dist/cli.cjs npm run test:live
458
+ ```
459
+
460
+ That run spends no provider tokens. It covers the advertised capabilities, the
461
+ `providers.status` probe, the host configuration on the raw session summary,
462
+ the cwd refusals on both sides, `pendingApprovals()`, and a cold resume.
463
+
464
+ Add `ADE_SDK_LIVE_SPEND=1` to also run the cases that need a model turn. They
465
+ need a provider that is installed and logged in, and they cost a few cents on
466
+ the cheapest model in the catalog:
467
+
468
+ ```sh
469
+ ADE_SDK_LIVE_BINARY=../../apps/ade-cli/dist/cli.cjs ADE_SDK_LIVE_SPEND=1 npm run test:live
470
+ ```
471
+
472
+ Read the header of `test/live.integration.test.ts` before you trust a green
473
+ spending run. Claude's own permission default can accept every tool without
474
+ asking, and on a machine configured that way the approval cases record that
475
+ fact instead of proving the round trip.
476
+
477
+ ## License
478
+
479
+ MIT. See [LICENSE](./LICENSE). DAEX (formerly ADE) itself remains AGPL-3.0-only; see the [DAEX Runtime Embedding Exception](https://github.com/arul28/DAEX/blob/main/RUNTIME-EMBEDDING-EXCEPTION.md) for shipping the runtime binary in your app.