@h1r-ai/croche 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +1184 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/dist/archive.d.ts +47 -0
  5. package/dist/archive.js +217 -0
  6. package/dist/atomic-replace.d.ts +18 -0
  7. package/dist/atomic-replace.js +39 -0
  8. package/dist/commands.d.ts +56 -0
  9. package/dist/commands.js +1 -0
  10. package/dist/control.d.ts +62 -0
  11. package/dist/control.js +269 -0
  12. package/dist/core-abi.d.ts +110 -0
  13. package/dist/core-abi.js +1 -0
  14. package/dist/core-bindgen.d.ts +413 -0
  15. package/dist/core-bindgen.js +1533 -0
  16. package/dist/core-runtime.d.ts +214 -0
  17. package/dist/core-runtime.js +837 -0
  18. package/dist/core-wasm-bytes.d.ts +4 -0
  19. package/dist/core-wasm-bytes.js +5 -0
  20. package/dist/core-wasm.d.ts +16 -0
  21. package/dist/core-wasm.js +63 -0
  22. package/dist/debug.d.ts +26 -0
  23. package/dist/debug.js +171 -0
  24. package/dist/file-lock.d.ts +46 -0
  25. package/dist/file-lock.js +300 -0
  26. package/dist/images.d.ts +53 -0
  27. package/dist/images.js +179 -0
  28. package/dist/index.d.ts +14 -0
  29. package/dist/index.js +9 -0
  30. package/dist/markers.d.ts +1 -0
  31. package/dist/markers.js +1 -0
  32. package/dist/node.d.ts +46 -0
  33. package/dist/node.js +281 -0
  34. package/dist/project-core.d.ts +79 -0
  35. package/dist/project-core.js +261 -0
  36. package/dist/project-session.d.ts +44 -0
  37. package/dist/project-session.js +143 -0
  38. package/dist/project-types.d.ts +97 -0
  39. package/dist/project-types.js +1 -0
  40. package/dist/project-wire.d.ts +19 -0
  41. package/dist/project-wire.js +39 -0
  42. package/dist/sse.d.ts +19 -0
  43. package/dist/sse.js +53 -0
  44. package/dist/storage.d.ts +24 -0
  45. package/dist/storage.js +32 -0
  46. package/dist/stream-branch.d.ts +47 -0
  47. package/dist/stream-branch.js +107 -0
  48. package/dist/stream-hub.d.ts +207 -0
  49. package/dist/stream-hub.js +210 -0
  50. package/dist/stream.d.ts +3 -0
  51. package/dist/stream.js +5 -0
  52. package/dist/types.d.ts +928 -0
  53. package/dist/types.js +8 -0
  54. package/dist/wiki.d.ts +15 -0
  55. package/dist/wiki.js +25 -0
  56. package/docs/CODING-AGENT.md +96 -0
  57. package/docs/DEBUGGER.md +230 -0
  58. package/docs/S2-IMPLEMENTATION.md +585 -0
  59. package/docs/SKILL.md +337 -0
  60. package/docs/skills/croche/agents/openai.yaml +4 -0
  61. package/docs/skills/croche/references/agents.md +78 -0
  62. package/docs/skills/croche/references/first-turn.md +74 -0
  63. package/docs/skills/croche/references/tools.md +43 -0
  64. package/docs/skills/croche-cli/SKILL.md +158 -0
  65. package/docs/skills/croche-cli/agents/openai.yaml +4 -0
  66. package/docs/skills/croche-cli/references/powershell.md +47 -0
  67. package/docs/skills/croche-config/SKILL.md +152 -0
  68. package/docs/skills/croche-config/agents/openai.yaml +4 -0
  69. package/docs/skills/croche-config/references/models.md +12 -0
  70. package/docs/skills/croche-platforms/SKILL.md +55 -0
  71. package/docs/skills/croche-platforms/agents/openai.yaml +4 -0
  72. package/docs/skills/croche-platforms/references/android.md +185 -0
  73. package/docs/skills/croche-platforms/references/ios.md +165 -0
  74. package/docs/skills/croche-platforms/references/react-native.md +50 -0
  75. package/docs/skills/croche-platforms/references/web-backend.md +58 -0
  76. package/docs/skills/croche-troubleshoot/SKILL.md +72 -0
  77. package/docs/skills/croche-troubleshoot/agents/openai.yaml +4 -0
  78. package/docs/skills/croche-troubleshoot/references/recovery.md +31 -0
  79. package/package.json +52 -4
  80. package/src/archive.ts +188 -0
  81. package/src/atomic-replace.ts +43 -0
  82. package/src/commands.ts +62 -0
  83. package/src/control.ts +179 -0
  84. package/src/core-abi.ts +52 -0
  85. package/src/core-bindgen.ts +1557 -0
  86. package/src/core-runtime.ts +750 -0
  87. package/src/core-wasm-bytes.ts +5 -0
  88. package/src/core-wasm.ts +57 -0
  89. package/src/debug.ts +160 -0
  90. package/src/file-lock.ts +269 -0
  91. package/src/images.ts +174 -0
  92. package/src/index.ts +15 -0
  93. package/src/markers.ts +1 -0
  94. package/src/node.ts +194 -0
  95. package/src/project-core.ts +231 -0
  96. package/src/project-session.ts +118 -0
  97. package/src/project-types.ts +77 -0
  98. package/src/project-wire.ts +39 -0
  99. package/src/sse.ts +57 -0
  100. package/src/storage.ts +30 -0
  101. package/src/stream-branch.ts +112 -0
  102. package/src/stream-hub.ts +249 -0
  103. package/src/stream.ts +7 -0
  104. package/src/types.ts +838 -0
  105. package/src/wiki.ts +25 -0
package/src/types.ts ADDED
@@ -0,0 +1,838 @@
1
+ import type { RuntimeTool } from './commands.js';
2
+ export type { RuntimeTool } from './commands.js';
3
+ export type JsonPrimitive = string | number | boolean | null;
4
+ export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
5
+ export type JsonSchema = Record<string, unknown>;
6
+
7
+ /** Writes must atomically replace a complete value; use one owner per namespace. */
8
+ export interface RuntimeStorage {
9
+ /** Wrappers over the same backing store can share an ownership identity. */
10
+ readonly ownershipIdentity?: object;
11
+ /**
12
+ * Optional: where the turn archive lives (F20.6). The SDK's `FileStorage`, `WebStorage` and
13
+ * `MemoryStorage` have one. A storage without it keeps no archive: everything else works, and
14
+ * what needs the archive answers `archive_unavailable`.
15
+ */
16
+ readonly archive?: ArchiveRuntimeStorage;
17
+ /** Optional host lock. The returned release runs after all durable writes settle. */
18
+ acquireLock?(key: string): Promise<() => void | Promise<void>>;
19
+ getItem(key: string): Promise<string | null>;
20
+ setItem(key: string, value: string): Promise<void>;
21
+ removeItem(key: string): Promise<void>;
22
+ }
23
+
24
+ /**
25
+ * Line storage beside a store, for the turn archive (F20.6): named entries (`[a-z0-9]+`) of one
26
+ * store `key`, each a list of lines. The SDK's archive rules (segments of 100 turns, the byte
27
+ * bound, the last record per turn wins) run over these five calls.
28
+ */
29
+ export interface ArchiveRuntimeStorage {
30
+ /** Appends one line (it holds no newline) to the entry, creating it. Durable when it resolves. */
31
+ appendLine(key: string, entry: string, line: string): Promise<void>;
32
+ /** The entry's complete lines in order; [] when it does not exist. A torn last line is not one. */
33
+ readLines(key: string, entry: string): Promise<string[]>;
34
+ /**
35
+ * Replaces the entry's lines with `lines`, atomically: after a crash the entry holds either
36
+ * every old line or every new one, never a mix and never none (a ranged clear rewrites a
37
+ * segment this way, F20.5.1a). `[]` deletes the entry.
38
+ */
39
+ replaceLines(key: string, entry: string, lines: string[]): Promise<void>;
40
+ /** Deletes the entry for real (the bytes leave the device). Absent is not an error. */
41
+ remove(key: string, entry: string): Promise<void>;
42
+ /** The store's entries whose names start with `prefix`, with their sizes in bytes. */
43
+ entries(key: string, prefix: string): Promise<Array<{ entry: string; bytes: number }>>;
44
+ }
45
+
46
+ export interface ToolContext {
47
+ callId: string;
48
+ messageId: string;
49
+ /** The opaque user id Croche issued; "" until Cloud has issued it. */
50
+ userId: string;
51
+ /** The character this Runtime is, or null when it was created without an agentId. */
52
+ agentId: string | null;
53
+ signal: AbortSignal;
54
+ }
55
+
56
+ /**
57
+ * What the app decides (the app snapshot, founder's split 2026-10-03): the persona, tools, documents,
58
+ * memory policy and budget limits. Project config is the single document format; Runtime
59
+ * does not create a separate app-snapshot export.
60
+ */
61
+ export interface AppOptions {
62
+ instructions: string;
63
+ /** App-authored guidance, verbatim at the start of run_tool's App tools section. */
64
+ toolGuide?: string;
65
+ /** Core-owned library tools: save/replace, recall and history are on when memory is on;
66
+ * wiki requires visible documents; schedule defaults off. */
67
+ crocheTools?: CrocheTools;
68
+ tools?: RuntimeTool[];
69
+ /**
70
+ * The app's knowledge documents, loaded at open (same as `runtime.wiki.set`). Held in memory,
71
+ * never stored: pass them on every open. Only a catalog of titles is put into the prompt; the
72
+ * agent searches and reads bodies with the built-in `wiki` command. Pass `{docs, include,
73
+ * exclude}` to also limit what this agent sees by path globs (`menu/**`, `staff/*.md`): a
74
+ * document exists for it only when the globs and the document's `agents` both allow it.
75
+ */
76
+ wiki?: WikiDocument[] | WikiOptions;
77
+ /** App-specific presentation markers; never executable actions. */
78
+ markerGuide?: string;
79
+ maxIterations?: number;
80
+ /** App output-token budget (64–1048576, default 2048); model-specific limits belong in Studio. */
81
+ maxOutputTokens?: number;
82
+ /**
83
+ * The context window, in estimated tokens (250-16777216, default 12000). Budgets are estimates
84
+ * from per-language coefficients, calibrated against what the model reports; your tools'
85
+ * declarations count in it. `maxContextCharacters` was renamed and is refused.
86
+ */
87
+ maxContextTokens?: number;
88
+ /**
89
+ * Long-term memory. On by default. When older conversation would leave the context
90
+ * window, the Core asks the model to rewrite one plain-text memory block from the
91
+ * existing memory plus the turns leaving, then renders that block on every turn.
92
+ * The call is paid like any other and reported with purpose "summary".
93
+ */
94
+ memory?: RuntimeMemoryOptions;
95
+ /**
96
+ * A regular check-in the app turns on: a turn every `everyMs` (15 minutes to 24 hours, both
97
+ * pending founder confirmation), delivered by `runtime.deliverDue()` like a due note and in
98
+ * the same turn as any. The next one is a period after the last delivery, so a long gap gives
99
+ * one turn, not one per missed period. Never in `schedule list`, never counted toward its 20,
100
+ * not cancellable by the agent. Off by default; removing it stops it.
101
+ */
102
+ heartbeat?: { everyMs: number };
103
+ }
104
+
105
+ /**
106
+ * How this Runtime runs on this host: Cloud identity, storage, transport, clock, upkeep and
107
+ * diagnostics. Never part of an app snapshot.
108
+ */
109
+ export interface HostOptions {
110
+ /** Re-encodes `standard` images (F30, H3). Default: the browser's, where there is one; null sends
111
+ * every image as given. */
112
+ imageCodec?: import('./images.js').ImageCodec | null;
113
+ /** @internal */
114
+ cloudUrl?: string;
115
+ /** Public, project-scoped enrollment key; never an OpenRouter secret. */
116
+ projectKey: string;
117
+ /** Exact app user identity (1–200 UTF-16 code units, no padding or control characters). Required with
118
+ * serverKey; also partitions the default local store. Cloud issues the opaque userId. */
119
+ user?: string;
120
+ /**
121
+ * Which character this Runtime is, when one user talks to several. Each agent gets its
122
+ * own store, session, history and memory, so two can be open at once. Omit it and the
123
+ * Runtime keeps the exact identity and store it had before agents existed.
124
+ */
125
+ agentId?: string;
126
+ storage: RuntimeStorage;
127
+ /**
128
+ * Where the Runtime credential is kept, under `<storageKey>.secrets`. Defaults to
129
+ * `storage`: a browser has no secret store. A Node or desktop host can pass one backed
130
+ * by the OS keychain. The mobile SDKs use Keychain and Keystore.
131
+ */
132
+ secretStorage?: RuntimeStorage;
133
+ storageKey?: string;
134
+ /**
135
+ * A debug key issued in Croche Studio ("cdt_…"). It vouches for this install in
136
+ * place of App Attest / Play Integrity, so simulators, emulators and web hosts can
137
+ * register; Cloud gives such an install a small development model key. Never ship it in a
138
+ * release build: the native SDKs warn loudly when they see one there.
139
+ */
140
+ debugKey?: string;
141
+ /**
142
+ * A web app's project server key from Croche Studio ("csk_…"). A web app runs the Runtime
143
+ * on its OWN backend (Node), never in the browser: the server key admits that backend as a
144
+ * production install, billed to Runtime Credit. Open one Runtime per end user with
145
+ * `user` set to your stable user id. Refused in a browser.
146
+ */
147
+ serverKey?: string;
148
+ requestTimeoutMs?: number;
149
+ maxPendingEvents?: number;
150
+ /**
151
+ * Stream the reply as it is written (default true): text.delta events arrive while the
152
+ * model writes instead of all at once. Deltas are provisional; turn.completed's result
153
+ * is authoritative.
154
+ */
155
+ streaming?: boolean;
156
+ /**
157
+ * Background upkeep (default true): after each turn and every maintenanceIntervalMs, the
158
+ * Runtime delivers its outbox of call reports and syncs balances, policy and the model
159
+ * key. Browsers also check on a visible foreground return, coalesced within the interval.
160
+ * Turns never wait for it. False disables the timer and foreground hook; call maintain() yourself.
161
+ */
162
+ backgroundSync?: boolean;
163
+ /**
164
+ * The turn archive (F20): every finished turn, in full (its messages, tool calls and results,
165
+ * and image references with their alt text, never image bytes), kept on this device by the
166
+ * storage's `archive` capability. Past `maxBytes` (65536 to 1073741824; default 8388608) the
167
+ * oldest segment of 100 turns is deleted. `clearHistory()` deletes it all.
168
+ */
169
+ archive?: { maxBytes?: number };
170
+ /** How often background upkeep checks whether work is due. Default 60000, minimum 1000. */
171
+ maintenanceIntervalMs?: number;
172
+ /** How long a synced policy is used before upkeep syncs again. Default 300000. */
173
+ syncIntervalMs?: number;
174
+ /** After a failed upkeep, how long to wait before trying again. Default 60000. */
175
+ maintenanceBackoffMs?: number;
176
+ /** Dependency injection for transport tests and host networking adapters. */
177
+ fetch?: typeof fetch;
178
+ /**
179
+ * The clock the Runtime reads (epoch ms or a Date). Defaults to the wall clock. Tests and
180
+ * simulations use it to replay days of use in minutes: idle periods, sync intervals and
181
+ * timestamps all follow it. Never persisted and never sent to the model.
182
+ */
183
+ clock?: () => number | Date;
184
+ /**
185
+ * Every paid model call, whatever caused it: a message's own calls, summary, and memory
186
+ * prepares during upkeep (which belong to no send() result). One event per call, once its cost
187
+ * is known (`costStatus` 'reported', 'estimated' or 'none'). Use it for your own usage display or ledger;
188
+ * per-user limits are already enforced by the Runtime and Cloud. Delivery is at least once: a
189
+ * crash between settling a cost and saving it re-settles that call on reopen, so dedupe by
190
+ * `operationId`.
191
+ */
192
+ onUsage?: (event: RuntimeUsageEvent) => void;
193
+ /** The person's IANA time zone for the dated messages; defaults to the host's own (the device on mobile). */
194
+ timeZone?: string;
195
+ /** Opt-in runtime diagnostics: app inputs/tools/results, never private model request bodies. */
196
+ onDebugEvent?: (event: RuntimeDebugEvent) => void;
197
+ /** Public builds provide runtime tracing only. Untyped 'full' is refused at open with invalid_configuration; a debugKey cannot enable it. */
198
+ debugVisibility?: 'runtime';
199
+ }
200
+
201
+ /**
202
+ * Single-agent app and host options. Unknown configuration properties fail with
203
+ * `invalid_configuration`. App `reasoning` accepts `default`, `off`, `low`, `medium` or `high`.
204
+ */
205
+ export type RuntimeOptions = AppOptions & HostOptions;
206
+
207
+ export interface CrocheTools {
208
+ /** Model-owned save/replace pair, on by default when memory is enabled. */
209
+ 'memory.save'?: boolean;
210
+ /** Defaults to the save switch; explicit true keeps earlier facts readable when save is off. */
211
+ 'memory.recall'?: boolean;
212
+ 'memory.history'?: boolean;
213
+ wiki?: boolean;
214
+ /** Off by default. Enables schedule at/list/cancel; an app tool named schedule is then refused.
215
+ * Notes run through deliverDue() at or after their time, never before. */
216
+ schedule?: boolean;
217
+ }
218
+
219
+ export interface RuntimeMemoryOptions {
220
+ /** Defaults to true. A person's own choice (`runtime.memory.enabled(…)`) wins. */
221
+ enabled?: boolean;
222
+ /** Memory-list token budget, 125–16777216; defaults to min(window/5, 800).
223
+ * The separate conversation summary has half this budget. View budgeting deletes no fact. */
224
+ maxTokens?: number;
225
+ /**
226
+ * App guidance on what matters to keep, in save guidance and summary instructions.
227
+ * Unset or "" omits the app slot; Croche's fixed rules are not app guidance.
228
+ */
229
+ policy?: string;
230
+ /**
231
+ * How long the conversation stays active after the last model call, while the provider's
232
+ * prompt cache may be warm. Once it passes, the agent is inactive: a ready summary is applied;
233
+ * otherwise a fitting stored history answers first and preparation follows the reply.
234
+ * Overflow summary remains inline. 60000–604800000, or 0 to turn
235
+ * it off. Default 300000 (5 minutes). Must exceed prepareAfterMs. Measured on the clock the
236
+ * host gives the Runtime.
237
+ */
238
+ activeMs?: number;
239
+ /**
240
+ * @deprecated The former name of activeMs, still accepted. Setting both to different values
241
+ * is invalid_configuration.
242
+ */
243
+ idleAfterMs?: number;
244
+ /**
245
+ * Quiet time after which upkeep prepares memory while the prompt cache may be warm.
246
+ * A fitting cold reply makes preparation due immediately when this is nonzero.
247
+ * 30000–604800000, or 0 to never prepare. Default 240000 (4 minutes). See runtime.wakeAt().
248
+ */
249
+ prepareAfterMs?: number;
250
+ /**
251
+ * Recent conversation kept verbatim across the inactive transition, in estimated tokens (0-16777216,
252
+ * default 1000, at most half the window). The newest whole turns are kept while both this and
253
+ * keepVerbatimTurns hold, and always at least one. Only older turns are folded into memory.
254
+ */
255
+ keepVerbatimTokens?: number;
256
+ /** Most turns kept verbatim across the inactive transition (1-200, default 20). */
257
+ keepVerbatimTurns?: number;
258
+ /** Least older text (estimated tokens, 125-16777216) an inactive fold must remove to be worth its call. Default 2500. */
259
+ foldMinTokens?: number;
260
+ /**
261
+ * Estimated token budget of a model-invoked memory recall or history result
262
+ * (50-16777216, default 300, at most a tenth of the window).
263
+ * Recall searches saved facts only; no automatic excerpts are injected.
264
+ * Full recall lines use this share; cut results budget fact text only, with
265
+ * their compact header and fixed notices counted as extra request framing.
266
+ * History budgets its whole labelled result, including its cut notice.
267
+ */
268
+ recallTokens?: number;
269
+ }
270
+
271
+ /** One remembered fact. `source` is who wrote it last. */
272
+ export interface MemoryItem {
273
+ id: string;
274
+ text: string;
275
+ source: 'agent';
276
+ createdAt: string;
277
+ updatedAt: string;
278
+ /** The conversation unit that saved this fact (`t142`; F21). */
279
+ turnN: number;
280
+ /** Turn numbers the model cited with --ref. */
281
+ refs: number[];
282
+ /** A replacement is a new id; earlier versions stay until deleted or FIFO-evicted. */
283
+ replaces?: string;
284
+ replacedBy?: string;
285
+ }
286
+
287
+ /** Everything memory holds for this person, for a user data request. */
288
+ export interface MemoryExport {
289
+ enabled: boolean;
290
+ /** Current and replaced AI-written facts. The conversation summary is not memory. */
291
+ items: MemoryItem[];
292
+ }
293
+
294
+ /** A durable AI-written memory changed. At most once; list() is the source of truth.
295
+ * `id` is '' for clear. `source` identifies who wrote the fact, not who deleted it. */
296
+ export interface MemoryChangedEvent {
297
+ type: 'memory.changed';
298
+ id: string;
299
+ source: 'agent';
300
+ action: 'save' | 'replace' | 'delete' | 'clear';
301
+ }
302
+
303
+ /** What the Runtime currently remembers beyond the visible context window. */
304
+ export interface RuntimeMemory {
305
+ enabled: boolean;
306
+ /** The notes the model sees: the items rendered one line each at the last reduction (inactive,
307
+ * compaction or a fresh conversation). Empty until memory holds an item. */
308
+ text: string;
309
+ updatedAt: string | null;
310
+ /** Conversation turns folded into memory so far in this session. */
311
+ compactedTurns: number;
312
+ /** The remembered items, without their history. */
313
+ items: MemoryItem[];
314
+ }
315
+
316
+ /**
317
+ * Only the AI writes memories. `memory.delete(id)` removes that memory and its earlier
318
+ * versions; `memory.clear()` removes every memory. The summary of earlier conversation is
319
+ * part of the conversation, not memory: `clearHistory()` or `Croche.deleteStore()` removes it.
320
+ * Kept turns and the turn archive are not rewritten by memory deletes.
321
+ * A write while another operation runs resolves at once with `{ deferred: true }`
322
+ * (`DeferredWrite`).
323
+ */
324
+ export interface RuntimeMemoryApi {
325
+ (): RuntimeMemory;
326
+ list(): MemoryItem[];
327
+ delete(id: string): Promise<{ deleted: boolean } | DeferredWrite>;
328
+ /** Remove every AI-written memory; the conversation summary stays. */
329
+ clear(): Promise<{ cleared: number } | DeferredWrite>;
330
+ /** Turn memory on or off for this person; the choice outlives `clearHistory()`. */
331
+ enabled(on: boolean): Promise<void | DeferredWrite>;
332
+ export(): MemoryExport;
333
+ /** Replaces the observer of durable `memory.changed` hints (at most once).
334
+ * A crash can lose the hint after the write; list() is the source of truth. */
335
+ onChanged(listener: ((event: MemoryChangedEvent) => void) | undefined): void;
336
+ }
337
+
338
+ /**
339
+ * One wiki document: a path such as `menu/stew.md` and its markdown (at most 64 KB; 2,000
340
+ * documents and 8 MB in all). The title is the first `#` heading. Optional frontmatter may set
341
+ * `summary`, `keywords` and `agents` (only those agents see the document).
342
+ */
343
+ export interface WikiDocument {
344
+ path: string;
345
+ markdown: string;
346
+ /** Only these agents see the document; overrides the frontmatter's `agents`. */
347
+ agents?: string[];
348
+ /**
349
+ * `'app'` (default): the app's, same for every user, held in memory. `'user'`: this user's
350
+ * own (saved recipes, lesson notes), stored with their state (at most 200 documents and
351
+ * 256 KB as stored). A user's document must be under `user/`, which the app's may not use. Only
352
+ * `put` takes `'user'`.
353
+ */
354
+ scope?: 'app' | 'user';
355
+ }
356
+
357
+ /** A document of this user's own: `put` stores it and resolves once it is durable. */
358
+ export type UserWikiDocument = WikiDocument & { scope: 'user' };
359
+
360
+ /** This user's own documents after a `put`. */
361
+ export interface UserWikiResult {
362
+ documents: number;
363
+ bytes: number;
364
+ }
365
+
366
+ /** `CrocheRuntime.create({ wiki })` with this agent's own path filter. */
367
+ export interface WikiOptions {
368
+ docs?: WikiDocument[];
369
+ /** Path globs this agent sees (all when absent): `*` stays in a folder, `**` spans folders. */
370
+ include?: string[];
371
+ /** Path globs this agent never sees, even when included. At most 50 globs each. */
372
+ exclude?: string[];
373
+ }
374
+
375
+ /** What `runtime.wiki.set()` installed. The same documents give the same digest everywhere. */
376
+ export interface WikiDigest {
377
+ documents: number;
378
+ bytes: number;
379
+ /** `sha256:` and 64 hex characters. */
380
+ digest: string;
381
+ }
382
+
383
+ /** A wiki document as `runtime.wiki.list()` shows it. */
384
+ export interface WikiEntry {
385
+ path: string;
386
+ title: string;
387
+ summary?: string;
388
+ characters: number;
389
+ /** Parts `read` returns it in (4,000 characters each). */
390
+ parts: number;
391
+ /** `'user'` for this user's own document; absent for the app's. */
392
+ scope?: 'user';
393
+ }
394
+
395
+ /**
396
+ * What a write (memory, this user's own documents, the allowance) resolves with when it was
397
+ * called while another operation ran: accepted, not yet applied. The Runtime applies it, in call
398
+ * order, when that operation ends; a message sent after the write sees it, one sent before does
399
+ * not. It is held in this process until then: closing first drops it. A write that cannot apply
400
+ * then is reported as a `write.failed` debug event.
401
+ */
402
+ export interface DeferredWrite {
403
+ deferred: true;
404
+ }
405
+
406
+ /** `runtime.wiki`. */
407
+ export interface RuntimeWiki {
408
+ /** Replace every app document at once and say what was installed; on an error nothing changes. */
409
+ set(docs: WikiDocument[]): WikiDigest;
410
+ /** `set`, without the digest. */
411
+ load(docs: WikiDocument[]): void;
412
+ /** This user's own documents: stored, durable when the promise resolves. */
413
+ put(docs: UserWikiDocument | UserWikiDocument[]): Promise<UserWikiResult | DeferredWrite>;
414
+ /** Add app documents or replace those with the same path, atomically. */
415
+ put(docs: WikiDocument | WikiDocument[]): void;
416
+ /** Remove one of this user's own documents; whether it existed. */
417
+ remove(path: string, options: { scope: 'user' }): Promise<boolean | DeferredWrite>;
418
+ /** Remove one app document; whether it existed. */
419
+ remove(path: string): boolean;
420
+ /** Remove every one of this user's own documents; how many. `clearHistory` keeps them. */
421
+ clear(options: { scope: 'user' }): Promise<number | DeferredWrite>;
422
+ /** Documents under `folder` (all by default), by path. */
423
+ list(folder?: string): WikiEntry[];
424
+ /** One part (1-based) of a document, or null when there is no such document or part. */
425
+ read(path: string, part?: number): WikiPage | null;
426
+ /** The best matches (at most `limit`, and 5), best first. */
427
+ search(query: string, limit?: number): WikiHit[];
428
+ }
429
+
430
+ /** One `runtime.wiki.search()` match. */
431
+ export interface WikiHit {
432
+ path: string;
433
+ title: string;
434
+ snippet: string;
435
+ score: number;
436
+ }
437
+
438
+ /** One part of a wiki document. */
439
+ export interface WikiPage {
440
+ path: string;
441
+ title: string;
442
+ /** 1-based. */
443
+ part: number;
444
+ parts: number;
445
+ text: string;
446
+ }
447
+
448
+ /** A replaceable local observer on an existing Runtime handle. */
449
+ export interface RuntimeDebugObserverOptions {
450
+ onDebugEvent: (event: RuntimeDebugEvent) => void;
451
+ /** Runtime tracing only in public builds; an untyped full upgrade is refused atomically. */
452
+ visibility?: 'runtime';
453
+ }
454
+
455
+ export type RuntimeDebugEventType =
456
+ | 'input.received' | 'input.replayed' | 'model.request' | 'model.response' | 'model.error' | 'model.recovery'
457
+ | 'marker' | 'tool.requested' | 'tool.started' | 'tool.completed' | 'tool.failed'
458
+ | 'turn.completed' | 'runtime.ready' | 'runtime.error' | 'runtime.warning' | 'memory.inactive' | 'memory.prepared' | 'memory.prepare_failed' | 'memory.compacted' | 'memory.error'
459
+ | 'model.gateway_error' | 'model.stream_mismatch' | 'maintenance.preempted' | 'cloud.unreachable' | 'telemetry.rejected'
460
+ | 'attestation.fallback' | 'runtime.reregistered' | 'runtime.state'
461
+ | 'command.repaired' | 'commands.relisted' | 'gateway.routing' | 'gateway.routing_rejected'
462
+ | 'gateway.unsupported' | 'budget.unsupported_currency'
463
+ | 'memory.refused'
464
+ | 'memory.upkeep' | 'outbox.bounded' | 'output.retry'
465
+ | 'tokens.table_refused' | 'turn.history_kept' | 'turn.reply_with_commands' | 'write.failed'
466
+ /** At open: held sends a closed or killed Runtime left, all resumed as the next turns
467
+ * (`data.inputs`), or a held record that could not be read. */
468
+ | 'held.resumed' | 'held.unreadable' | 'input.refused'
469
+ /** `setTools`/`setMode` changed what the model may see (`data: {mode, visible, shown}`, names
470
+ * only); filtered names the mode's list lacks (`tools.unmatched`, `data: {mode, names}`); and a
471
+ * mode this agent declares that the opened config lacks applied no overlay (`mode.missing`).
472
+ * A sync's delivered app config, for the next open (`config.delivered`, `data: {revision_id,
473
+ * stored, refused?: {code, path}}`; `stored` false when the record had moved on or it failed
474
+ * verification; a refusal is kept and reported to Cloud as `app_config_applied.refused`), and
475
+ * a sync sent without the config report because the project record could not be read
476
+ * (`config.report_skipped`, `data: {code}`). */
477
+ | 'tools.changed' | 'tools.unmatched' | 'mode.missing' | 'config.delivered' | 'config.report_skipped'
478
+ /** A command still running at its round's wait (H2, `tool.late`), and late results
479
+ * recorded (`tool.results_accepted`). Their delivery is `tool.completed`/`tool.failed` with
480
+ * `late: true`. A late turn not started because the calls since the last outside input reached
481
+ * `maxIterations` (`tool.late_held`): the results wait for the next outside input. Images a
482
+ * command returned that its carrier did not attach (`tool.images_omitted`: `data.count`, and
483
+ * `data.reasons`, each `no_vision`, `over_limit` or `pending_limit`; H3). */
484
+ | 'tool.late' | 'tool.results_accepted' | 'tool.late_held' | 'tool.images_omitted'
485
+ /** A response made more tool calls than one round allows: none ran, each failed, and the model
486
+ * was told once (`data.count`, the calls refused). */
487
+ | 'tool.calls_refused'
488
+ /** An error code a tool or host gave that a record cannot keep (not 1–80 of `[A-Za-z0-9_.-]`)
489
+ * was replaced by the producer's generic code (`data.producer`: `tool`, `model_transport`,
490
+ * `cloud_transport`; `data.length`). The rejected text is never echoed. */
491
+ | 'error.code_replaced'
492
+ /** Every delivered model call: how much of the last call's request it shares, what the
493
+ * provider reports as cached, and the cause of a miss (`data.cause`: `first_call`, `hit`,
494
+ * `segment` with `data.partsAt` the first part that changed, `provider`, `not_reported`). */
495
+ | 'model.cache'
496
+ /** A call's gateway-reported answering model differs from its requested primary
497
+ * (`data: {requested, used}`). Model fallback is allowed, not an error or a Core retry.
498
+ * Missing or unusable model identifiers produce no substitution event. */
499
+ | 'model.substituted'
500
+ /** A failed schedule delivery spent these sources, never retried (`schedule.refused`:
501
+ * `data.ids`, `data.error`, `data.retry`: `permanent` for the code, or `dispatched` because the
502
+ * turn had dispatched a command, whose effect may have happened); or the host could not
503
+ * register the schedule (`schedule.degraded`: `data.reason`). A transient failure before any
504
+ * command was dispatched keeps notes and the heartbeat for a retry (`schedule.retry`:
505
+ * `data.ids`, `data.retryAt`, `data.error`; a source still pending is never named in
506
+ * `schedule.refused`), until a note's retry comes a day after its time (`schedule.expired`:
507
+ * `data.id`, `data.attempts`, `data.error`). */
508
+ | 'schedule.refused' | 'schedule.degraded' | 'schedule.retry' | 'schedule.expired'
509
+ /** The turn archive (F20): the storage keeps none (said once per open), or an archive call failed. */
510
+ | 'archive.unavailable' | 'archive.failed'
511
+ /** Turns left the request with no summarization call (A4), oldest first, in one batch
512
+ * (`data.turns`, through `data.through` / `data.throughN`). `memory.unsummarized`: memory on,
513
+ * saved facts are shown in the memory pair; raw turns remain in the archive. `context.reduced`: memory off, and only turns
514
+ * the turn archive holds; a store without one keeps every turn and never sends the oldest. */
515
+ | 'memory.unsummarized' | 'context.reduced';
516
+
517
+ /** `data` of a `runtime.state` debug event: what the Runtime is doing, sent when it changes. */
518
+ export interface RuntimeStateData {
519
+ /** The stream `state`'s partition, plus `closed`: an in-time tool call is `running`. */
520
+ status: 'idle' | 'running' | 'waiting' | 'closed';
521
+ /** The running operation's type (`send`, `sync`, `upkeep`, …). */
522
+ operation: string | null;
523
+ activeTurn: string | null;
524
+ /** Operations waiting behind the running one, tool changes included. */
525
+ queueDepth: number;
526
+ /** The first app tool call in flight; `command` is `null` for a tool's root command (no command word). */
527
+ runningTool: { callId: string; tool: string; command: string | null } | null;
528
+ /** Every app tool call of the current round, in call order: a model response's calls run together. */
529
+ runningTools: { callId: string; tool: string; command: string | null }[];
530
+ /**
531
+ * The latest conversation request's size in estimated tokens, as the window counts it (tools
532
+ * included), and the window (`maxContextTokens`). When the previous request's reported input
533
+ * was comparable, `usedTokens` is that report (`reportedTokens`) plus the estimate of what was
534
+ * appended (`estimatedTokens`); otherwise all of it is estimated and `reportedTokens` is null.
535
+ */
536
+ context: { usedTokens: number | null; limitTokens: number; estimatedTokens: number | null; reportedTokens: number | null };
537
+ /**
538
+ * Provider usage since `since`; `cached` is part of `input`, `reasoning` part of `output`.
539
+ * A call whose usage is absent or not whole is counted in `callsWithoutUsage` instead.
540
+ */
541
+ tokens: { input: number; cached: number; output: number; reasoning: number; callsWithoutUsage: number };
542
+ /** Gateway-reported cost, and calls charged an estimate because the gateway gave none. */
543
+ cost: { reportedUsd: number; estimatedUsd: number; estimatedCalls: number };
544
+ /** When this Runtime opened: the totals cover since then and are not persisted. */
545
+ since: string | null;
546
+ }
547
+
548
+ /**
549
+ * `data.config` of an `input.received` debug event: which configuration the turn runs on.
550
+ * `app.id` is `sha256:` and 64 hex digits; the Croche snapshot's id format is not decided yet.
551
+ */
552
+ export interface RuntimeConfigIdentity {
553
+ /** `id` hashes the effective app-owned configuration, never a separate snapshot export.
554
+ * Null if it cannot use the bounded project-config canonicalizer; diagnostic only.
555
+ * No published version is assigned here: `version` is null. */
556
+ app: { id: string | null; version: number | null };
557
+ /** No Croche snapshot is delivered yet: `id` and `version` are null, and `renderer` (Runtime
558
+ * version + compiled text table) names the Croche defaults in use. */
559
+ croche: { id: string | null; version: number | null; renderer: string };
560
+ }
561
+
562
+ /** Diagnostic content is separate from privacy-preserving Cloud telemetry. */
563
+ export interface RuntimeDebugEvent {
564
+ id: string;
565
+ timestamp: string;
566
+ /** Monotonically increasing within one open of the Runtime; restarts at the next open. */
567
+ sequence: number;
568
+ /**
569
+ * Which open of this Runtime's store emitted the event: it increases on every open (not
570
+ * necessarily by one). `runtimeInstanceId` persists across opens, so events order by
571
+ * (`openSequence`, `sequence`). An open that fails or is refused emits no debug events.
572
+ */
573
+ openSequence: number;
574
+ runtimeInstanceId: string;
575
+ sessionId: string;
576
+ projectId: string;
577
+ /** The Runtime's own agent, from its options; null when it has none (never inferred). */
578
+ agentId?: string | null;
579
+ /**
580
+ * The projection the Core generated this event under: `runtime` (public: the app's own traffic,
581
+ * no model request bodies, instructions or private facts) or `full`. Stamped per event, so a
582
+ * re-attach never relabels an earlier one. Treat anything other than `runtime` as not public.
583
+ */
584
+ visibility?: 'full' | 'runtime';
585
+ /** Envelope version. A missing `v` reads as 1. */
586
+ v?: number;
587
+ appName?: string;
588
+ turnId?: string;
589
+ operationId?: string;
590
+ callId?: string;
591
+ type: RuntimeDebugEventType;
592
+ data: JsonValue;
593
+ }
594
+
595
+ /**
596
+ * One message to the agent. Either one input (`text`, `kind`, `images`) or a stack (`inputs`): several inputs
597
+ * that arrived together, in order, answered as ONE turn with one model call, each in its own channel
598
+ * so the model tells the person's words from the app's. Approval for application actions belongs
599
+ * in the app's tool handler, not in the input protocol.
600
+ */
601
+ export type SendInput = {
602
+ /** Immutable application message identity, retained across delivery retries. */
603
+ id: string;
604
+ /** Optional app state, separate from the person's words. Useful when the request needs it,
605
+ * such as a command or button acting on app data, or after that state changed. Without it,
606
+ * this input carries only the message; earlier states stay as sent until older turns are folded. */
607
+ context?: JsonValue;
608
+ } & ({ text: string; kind?: 'user' | 'event'; images?: InputImage[]; inputs?: never } | { inputs: StackedInput[]; text?: never; kind?: never; images?: never });
609
+
610
+ export interface StackedInput {
611
+ /** user: what the app says the person said. event: the app's own note or event. Default user. */
612
+ kind?: 'user' | 'event';
613
+ text?: string;
614
+ /**
615
+ * Images, only when the project's model accepts them (otherwise the send fails with
616
+ * images_unsupported; nothing is dropped). At most 4 per message, 3 MB each, 6 MB together.
617
+ * Kept for the active period only; later turns see "[image: <alt> | from the person, <date>]".
618
+ */
619
+ images?: InputImage[];
620
+ }
621
+ /**
622
+ * How an image is sent (F30, H3). `standard` (the default): at most 512 px on its longest side, never
623
+ * upscaled, as PNG or JPEG, whichever is smaller (transparency kept; a GIF becomes its first
624
+ * frame). `high`: as given, within the limits, for text, screenshots and dense detail. An https
625
+ * `url` image is never changed. Node sends every image as given.
626
+ */
627
+ export type ImageResolution = 'standard' | 'high';
628
+ export type InputImage = { alt?: string; /** Wins over the send's or tool result's `imageResolution`. */ resolution?: ImageResolution } & (
629
+ | { data: string; mime?: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif'; url?: never } /** base64 (mime required) or a data: URL */
630
+ | { url: string; mime?: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif'; data?: never } /** https only */
631
+ );
632
+
633
+ export interface SendOptions {
634
+ signal?: AbortSignal;
635
+ onEvent?: (event: RuntimeEvent) => void;
636
+ /**
637
+ * Structured output, in OpenAI's shape. The turn's result carries `output`: the reply as JSON
638
+ * the Core checked against this format. Nothing else changes without it.
639
+ *
640
+ * - The reply is checked by the Core, never trusted: one that does not parse or match is not
641
+ * kept, the same request is sent once more, then the turn fails `output_invalid`.
642
+ * - The turn shows no text: no `text.delta` and no markers, one `output` event at the end.
643
+ * Commands still run in the same turn; only the final reply is the output.
644
+ * - The call goes only to model endpoints that honour the format (OpenRouter
645
+ * `provider.require_parameters`); none: `structured_output_unsupported`, before any charge.
646
+ * - The schema may use: type, properties, required, additionalProperties, items, enum, const,
647
+ * anyOf, $ref (to "#" or "#/$defs/..."), $defs, minItems, maxItems, minLength, maxLength,
648
+ * minimum, maximum, exclusiveMinimum, exclusiveMaximum, description, title. No recursion
649
+ * ($ref cycles); at most 8 KB, 5 levels of objects/arrays, 100 properties, 10 anyOf
650
+ * alternatives each, 200 enum values, 1,000 nodes with every $ref followed. Anything else
651
+ * fails the send with `invalid_response_format` naming the schema path, before any call.
652
+ */
653
+ responseFormat?: ResponseFormat;
654
+ /** For every image of this send that does not name its own `resolution`. Default standard. */
655
+ imageResolution?: ImageResolution;
656
+ }
657
+
658
+ /** OpenAI's response_format: a JSON Schema the reply must match, or any JSON object. */
659
+ export type ResponseFormat =
660
+ | { type: 'json_schema'; json_schema: { name: string; schema: { [key: string]: JsonValue }; strict?: boolean; description?: string } }
661
+ | { type: 'json_object' };
662
+
663
+ export interface TurnResult {
664
+ turnId: string;
665
+ /** The inputs this turn answers: one, or every send held behind the previous turn that it carried. */
666
+ causedBy: string[];
667
+ status: 'completed' | 'failed' | 'cancelled' | 'interrupted';
668
+ /** All visible assistant content accumulated in this turn, even on failure/cancellation. */
669
+ text: string;
670
+ raw: string;
671
+ markers: string[];
672
+ /** Known actual cost in USD; null if any operation cost is still unknown. */
673
+ cost: number | null;
674
+ /**
675
+ * Sent with `responseFormat` and completed: the reply as JSON, checked against the format
676
+ * (`text` and `raw` hold the same reply as the model wrote it). Absent otherwise; a schema
677
+ * that admits null can complete with `output: null`.
678
+ */
679
+ output?: JsonValue;
680
+ error?: { code: string; message: string };
681
+ /**
682
+ * Held across a restart and refused before it ran (F19.4): no model call, no reply, no
683
+ * cost; `error` says why. Durable: sending the same input again answers the same.
684
+ */
685
+ refused?: true;
686
+ /**
687
+ * Images a command returned that this turn's messages did not attach (H3): the model got each
688
+ * as its `alt` instead (no image model, over 4 images / 6 MB in one message, or over the
689
+ * budget for results still waiting). Absent when none.
690
+ */
691
+ imagesOmitted?: number;
692
+ }
693
+
694
+ export interface DisplayMessage {
695
+ id: string;
696
+ role: 'user' | 'assistant';
697
+ text: string;
698
+ raw?: string;
699
+ markers?: string[];
700
+ turnId: string;
701
+ kind: 'user' | 'event';
702
+ createdAt: string;
703
+ status?: TurnResult['status'];
704
+ /** A held input refused before it ran, after a restart: why, and nothing was sent. */
705
+ error?: { code: string; message: string };
706
+ refused?: true;
707
+ }
708
+
709
+ export interface RuntimeUsageEvent {
710
+ type: 'usage';
711
+ operationId: string;
712
+ /** 'model' for an ordinary call; 'summary' for the call that writes a summary, memory prepared ahead included. */
713
+ purpose: 'model' | 'summary';
714
+ /** The inputs this call worked for, as on its `turn` event; [] for upkeep that served no input. */
715
+ causedBy: string[];
716
+ /** Gateway-reported answering model, or requested primary; modelSource disambiguates. */
717
+ model: string;
718
+ /**
719
+ * 'requested' means the answering model was unavailable. Absent on older Core events:
720
+ * model is the requested primary, not the reported answering model. Older image summaries
721
+ * could retain the text default instead of their image primary; this is not backfilled.
722
+ */
723
+ modelSource?: 'response' | 'requested';
724
+ /** The primary sent in the request, present only when it differs from model. */
725
+ requestedModel?: string;
726
+ costUsd: number;
727
+ /** 'reported' by the gateway, 'estimated' when it gave none, 'none' for a failed call that cost nothing. */
728
+ costStatus: 'reported' | 'estimated' | 'none';
729
+ /**
730
+ * The call's token counts as the gateway reported them, each present only when reported; absent
731
+ * when the call returned no usage. A map of kinds: new kinds may be added, so ignore keys you
732
+ * don't know. The names are the call record's usage (`prompt_tokens`, …) in camelCase.
733
+ */
734
+ tokens?: { prompt?: number; completion?: number; total?: number; cached?: number; cacheWrite?: number; reasoning?: number; [kind: string]: number | undefined };
735
+ }
736
+
737
+ export type RuntimeEvent =
738
+ /** inputIds: the sends this turn carries, when sends held behind the previous turn go together. */
739
+ | { type: 'turn.started'; turnId: string; messageId: string; inputIds?: string[] }
740
+ /** A send made while a turn runs is held, never refused: its place among the held sends (from 1). They run together as the next turn. */
741
+ | { type: 'input.queued'; inputId: string; position: number }
742
+ /** A held send left without running: its own signal (`cancelled`) or `clearQueued`/`clearHistory` (`cleared`). */
743
+ | { type: 'input.dropped'; inputId: string; reason: 'cancelled' | 'cleared' }
744
+ /** Append text by turnId. Deltas span model rounds; the final result contains the aggregate. */
745
+ | { type: 'text.delta'; turnId: string; text: string }
746
+ /**
747
+ * @deprecated Never emitted since croche-sdk-internal#15: text already shown is never taken back.
748
+ * When a command fails, the agent continues after it in the same turn. Kept so existing handlers
749
+ * still compile; remove yours.
750
+ */
751
+ | { type: 'text.withdrawn'; turnId: string }
752
+ | { type: 'marker'; turnId: string; name: string }
753
+ | { type: 'tool.started'; turnId: string; callId: string; name: string; args: Record<string, JsonValue> }
754
+ | { type: 'tool.completed'; turnId: string; callId: string; name: string; result: JsonValue }
755
+ | { type: 'tool.failed'; turnId: string; callId: string; name: string; error: string }
756
+ /** A structured turn's checked reply (sent with `responseFormat`), once, before `turn.completed`. */
757
+ | { type: 'output'; turnId: string; output: JsonValue }
758
+ | { type: 'turn.completed'; turnId: string; result: TurnResult }
759
+ | MemoryChangedEvent
760
+ | RuntimeUsageEvent;
761
+
762
+ export interface HostBudgetPolicy {
763
+ enabled: boolean;
764
+ /** Unknown policy currencies disable host adjustment; they are never interpreted as USD. */
765
+ currency: string;
766
+ limits: {
767
+ max_user_allowance: number;
768
+ max_single_adjustment?: number;
769
+ max_positive_adjustment_per_window?: number;
770
+ };
771
+ window?: { type: 'daily' | 'weekly' | 'monthly' | string };
772
+ version: number;
773
+ expires_at: string;
774
+ }
775
+
776
+ export interface RuntimeControl {
777
+ protocol_version: number;
778
+ control_version: number;
779
+ host_budget_control: HostBudgetPolicy;
780
+ user_allowance?: { allowance: number; policy_version?: number };
781
+ default_user_allowance?: number;
782
+ runtime_policy?: { blocked?: boolean; reason?: string; model?: string };
783
+ blocked?: null | { code: string; message: string };
784
+ }
785
+
786
+ export interface BudgetSnapshot {
787
+ userId: string;
788
+ currency: 'USD';
789
+ /** This user's remaining AI money, as of the last sync minus this device's spend since. */
790
+ allowance: number;
791
+ /** The project's remaining money, as of the last sync minus this device's spend since. */
792
+ projectRemaining?: number | null;
793
+ policyVersion: number;
794
+ /** Spend this device has not reported to Cloud yet (it stays deducted locally). */
795
+ unreportedCost?: number;
796
+ unresolvedOperations: string[];
797
+ }
798
+
799
+ export interface BudgetAdjustment {
800
+ requestedDelta: number;
801
+ appliedDelta: number;
802
+ newAllowance: number;
803
+ limitedBy?: string;
804
+ }
805
+
806
+ export interface RuntimeStatus {
807
+ core?: 'rust';
808
+ abi?: number;
809
+ version?: string;
810
+ projectId: string;
811
+ installationId: string;
812
+ runtimeInstanceId: string;
813
+ /** Croche-issued; "" until Cloud has issued it. */
814
+ userId: string;
815
+ agentId: string | null;
816
+ sessionId: string;
817
+ /** The project's main model, from Cloud; null until a model key has been delivered. */
818
+ model: string | null;
819
+ /** Main model then fallbacks, as configured for the project in Cloud. */
820
+ models?: string[] | null;
821
+ gateway?: 'openrouter' | 'vercel' | null;
822
+ gatewayKeyId?: string | null;
823
+ /** Cloud's opaque key-purpose label; it grants no additional Core capability. */
824
+ gatewayKeyPurpose?: string | null;
825
+ lastSyncAt?: string | null;
826
+ pendingEvents: number;
827
+ unresolvedOperations: string[];
828
+ closed: boolean;
829
+ }
830
+
831
+ export class CrocheError extends Error {
832
+ readonly code: string;
833
+ constructor(code: string, message: string) {
834
+ super(message);
835
+ this.name = 'CrocheError';
836
+ this.code = code;
837
+ }
838
+ }