@h1r-ai/croche 0.0.0-stage → 0.5.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 (86) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +1176 -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 +930 -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 +92 -0
  57. package/docs/DEBUGGER.md +230 -0
  58. package/docs/S2-IMPLEMENTATION.md +585 -0
  59. package/docs/SKILL.md +295 -0
  60. package/package.json +52 -4
  61. package/src/archive.ts +188 -0
  62. package/src/atomic-replace.ts +43 -0
  63. package/src/commands.ts +62 -0
  64. package/src/control.ts +179 -0
  65. package/src/core-abi.ts +52 -0
  66. package/src/core-bindgen.ts +1557 -0
  67. package/src/core-runtime.ts +750 -0
  68. package/src/core-wasm-bytes.ts +5 -0
  69. package/src/core-wasm.ts +57 -0
  70. package/src/debug.ts +160 -0
  71. package/src/file-lock.ts +269 -0
  72. package/src/images.ts +174 -0
  73. package/src/index.ts +15 -0
  74. package/src/markers.ts +1 -0
  75. package/src/node.ts +194 -0
  76. package/src/project-core.ts +231 -0
  77. package/src/project-session.ts +118 -0
  78. package/src/project-types.ts +77 -0
  79. package/src/project-wire.ts +39 -0
  80. package/src/sse.ts +57 -0
  81. package/src/storage.ts +30 -0
  82. package/src/stream-branch.ts +112 -0
  83. package/src/stream-hub.ts +249 -0
  84. package/src/stream.ts +7 -0
  85. package/src/types.ts +840 -0
  86. package/src/wiki.ts +25 -0
package/README.md CHANGED
@@ -1,3 +1,1177 @@
1
- # Temporary Holding Version
1
+ # Croche Runtime 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
+ Build an AI character or assistant by supplying instructions, application state,
4
+ and JavaScript functions. The SDK runs the model/tool loop, persists conversations
5
+ and causal results, enforces per-user allowances, and reports every call to Croche
6
+ Cloud. Your app needs no backend of its own.
7
+
8
+ **How calls flow.** Every turn runs in the Runtime, inside your app. Croche Cloud is not on
9
+ the path of a turn: it registers the installation, delivers its credentials, holds balances,
10
+ and receives a report of every call in the background. **A Cloud outage does not stop a turn.**
11
+
12
+ The shared Rust Core owns conversations, command routing, receipts, spending and
13
+ Cloud synchronization. This package embeds its WebAssembly build for browsers,
14
+ Node, and WebViews. Native iOS (Swift) and Android (Kotlin) SDKs are planned for
15
+ 0.5.1, with the same `Croche.open` API.
16
+ For React Native, install `@h1r-ai/croche-react-native` beside this package; it carries
17
+ the native Core ([React Native](#react-native)).
18
+ Croche chooses and tunes the model for your project; the app does not configure it.
19
+
20
+ ## Install
21
+
22
+ From npm (an app; no Rust and no Croche checkout needed):
23
+
24
+ ```sh
25
+ npm install @h1r-ai/croche
26
+ ```
27
+
28
+ To build the tarball yourself, from the Croche repository:
29
+
30
+ ```sh
31
+ npm install
32
+ npm run build:core
33
+ npm run build --workspace @h1r-ai/croche
34
+ mkdir -p artifacts
35
+ npm pack --workspace @h1r-ai/croche --pack-destination artifacts
36
+ ```
37
+
38
+ The tarball contains compiled JavaScript, TypeScript declarations and an embedded
39
+ WASM Core, with no runtime npm dependencies. Consuming apps need no Rust compiler
40
+ or source checkout. Rust is needed only to rebuild the Core from source. A strict
41
+ browser CSP must include `script-src 'self' 'wasm-unsafe-eval'`; JavaScript `eval`
42
+ and `new Function` remain unnecessary.
43
+ The package has not been published to the public npm registry.
44
+
45
+ ## Projects and agents
46
+
47
+ New apps open a **project** once per user and get its **agents** from it. One project holds
48
+ the app's config (instructions, tools, several agents), one storage and one set of tool
49
+ handlers; each agent has its own conversation, history and memory.
50
+
51
+ ```ts
52
+ import { Croche, type ToolDeclaration, type ToolHandler } from '@h1r-ai/croche';
53
+ import { FileStorage } from '@h1r-ai/croche/node';
54
+
55
+ const shop: ToolDeclaration = {
56
+ name: 'shop',
57
+ summary: 'The inn shop.',
58
+ commands: [
59
+ { key: 'shop_sell', name: 'sell', summary: 'Sell food or drink the player asks for: stew, bread, ale.',
60
+ flags: [{ name: 'item', type: 'string', enum: ['stew', 'bread', 'ale'], required: true }] },
61
+ { key: 'shop_menu', name: 'menu', summary: "List today's menu and prices.", reads: true },
62
+ ],
63
+ };
64
+ const runShop: ToolHandler = ({ key, args }, context) => {
65
+ const out = app.run(key, args, context.user); // the real boundary: enforce here
66
+ return out.ok ? out.value : { status: 'rejected', reason: out.reason };
67
+ };
68
+
69
+ const croche = await Croche.open({
70
+ projectKey, debugKey, // debugKey: development only
71
+ user: playerId,
72
+ storage: new FileStorage(join(dataDir, 'croche')), // one directory for the whole project
73
+ config: {
74
+ instructions: PIP,
75
+ tools: [shop],
76
+ agents: { helper: { instructions: HELPER } }, // more agents, each a partial override
77
+ },
78
+ handlers: { shop: runShop }, // by tool name; code, never in config
79
+ onUsage: event => record(event), // one event per paid call
80
+ });
81
+
82
+ const pip = await croche.agent(); // the main agent ("default")
83
+ const result = await pip.request({ id: 'm1', text: 'Some stew, please.', context: appState() });
84
+ const reply = result.messages.at(-1); // { type: 'message.end', text, causedBy, ... }
85
+
86
+ const subscription = pip.subscribe({ onEvent: event => {
87
+ if (event.type === 'message.delta') render(String(event.text)); // provisional, by message id
88
+ if (event.type === 'message.end') render(String(event.text)); // final
89
+ } });
90
+ await pip.send({ id: 'm2', text: 'And some bread.' }); // returns a receipt at once
91
+ subscription.close();
92
+ await croche.close();
93
+ ```
94
+
95
+ - **`send(input)`** queues the input and returns `{ id, status, seq }`. **`request(input)`**
96
+ resolves when that input is answered, with its `messages`. Input ids are yours and unique.
97
+ - **`subscribe({ onEvent, initialMessages? })`** delivers a `snapshot` first, then `input`
98
+ (status changes: `queued`, `seen`, `answered`, `no_reply`, `failed`, `cancelled`),
99
+ `message.start` / `message.delta` / `message.end`, and `state` (`idle`, `running`,
100
+ `waiting`). `history({ limit, before? })` adds an older `page`; `clearHistory()` writes
101
+ `cleared`. `cancel(id?)` cancels one input, or the running turn.
102
+ - **Agents:** `croche.agent('helper')` opens an agent declared under `config.agents`; an id
103
+ the config does not declare is `invalid_configuration`. The same call while it is open
104
+ returns the same object.
105
+ - **Instances:** `croche.agent(id, { instance: 'save-2' })` is a separate conversation of the
106
+ same agent (a save slot, a document); `{ fresh: true }` creates a new one with a generated
107
+ key. `agent.instance` and `agent.created` say which, and whether this open created it.
108
+ - **Per-agent code override:** `croche.agent(id, { config: { … } })` layers a partial config
109
+ over the declared one, in memory only.
110
+ - **Tools at run time:** `agent.setTools(visible | null)` and `agent.setMode(name | null)`
111
+ (modes are declared in config) take effect at the next model call.
112
+ - **Deleting local data:** `Croche.deleteStore({ ...openOptions, agent? })` deletes that
113
+ agent's store, or every declared agent's; it refuses with `store_busy` while the project is
114
+ open. The project record is kept.
115
+ - **Handlers** receive `context` with `agentId`, `user`, `crocheUserId`, `causedBy` (the input
116
+ ids) and `origin` (`app` or `agent`).
117
+
118
+ `CrocheRuntime.create` below is the same Core for one agent without a project, and the rest of
119
+ this reference shows it. Its behaviour (memory, documents, streaming, markers, errors) is the
120
+ same for project agents; its agent options (`instructions`, `tools`, `memory`, `wiki`, …) are
121
+ fields of `config`, and its host options (`storage`, `user`, …) are options of
122
+ `Croche.open`.
123
+
124
+ ## First conversation
125
+
126
+ Create a project in Studio, enable anonymous app access, and copy its **public
127
+ project key**. The public key is an application enrollment identifier; it does not
128
+ provide Studio access.
129
+
130
+ An installation receives a model key only once it has proved it runs your app.
131
+ Phones prove it with App Attest or Play Integrity (the native SDKs do this). A browser,
132
+ Node, a simulator or an emulator cannot, so during development issue a **development
133
+ key** (`cdt_…`) in Studio → Debug keys and pass it as `debugKey`. Development
134
+ usage is billed to your weekly development allowance, never to the project's Runtime
135
+ Credit. Never ship a debug key in a release build.
136
+
137
+ ```ts
138
+ import { CrocheRuntime, WebStorage } from '@h1r-ai/croche';
139
+
140
+ const runtime = await CrocheRuntime.create({
141
+ projectKey: 'YOUR_PUBLIC_PROJECT_KEY',
142
+ debugKey: 'cdt_…', // development only: a browser cannot attest
143
+ storage: new WebStorage(),
144
+ instructions: 'You are Pip, a small, dry-witted but considerate companion. Keep replies brief.',
145
+ });
146
+
147
+ const result = await runtime.send({
148
+ id: crypto.randomUUID(),
149
+ text: 'What can you do?',
150
+ });
151
+
152
+ if (result.text) console.log(result.text);
153
+ if (result.status !== 'completed') {
154
+ console.error(result.error?.message);
155
+ }
156
+
157
+ // Reopening with the same origin, project key and storage restores the session.
158
+ console.log(runtime.history());
159
+ console.log(runtime.userBudget.get());
160
+ await runtime.close();
161
+ ```
162
+
163
+ The SDK connects to Croche automatically; no service URL setup is needed.
164
+
165
+ ## Web apps: run the Runtime on your backend
166
+
167
+ A browser cannot prove it runs your app, so a web app keeps a small backend of its own and
168
+ runs the Runtime **there**, on Node. Issue a **server key** (`csk_…`) in Studio; Cloud admits
169
+ your backend as a production install, billed to the project's Runtime Credit. Your web page
170
+ talks only to your backend.
171
+
172
+ ```ts
173
+ import { CrocheRuntime } from '@h1r-ai/croche';
174
+ import { FileStorage } from '@h1r-ai/croche/node';
175
+
176
+ // One Runtime per end user, keyed by your own stable user id.
177
+ async function runtimeFor(userId: string) {
178
+ return CrocheRuntime.create({
179
+ projectKey: process.env.CROCHE_PROJECT_KEY!,
180
+ serverKey: process.env.CROCHE_SERVER_KEY!, // a server secret
181
+ user: userId, // one Croche user and allowance per end user
182
+ storage: new FileStorage(`./runtime-state/${userId}`),
183
+ instructions: 'You are Pip, a concise, considerate companion.',
184
+ });
185
+ }
186
+ ```
187
+
188
+ - The server key, and the model key the Runtime receives with it, are secrets like any
189
+ provider key: keep them on the server, never send them to the browser. The SDK refuses
190
+ `serverKey` in a browser.
191
+ - Rotate a server key without downtime: issue a new one, deploy it, then revoke the old one.
192
+ - Every new user gets the project's default allowance, so your backend decides who is a user:
193
+ never take the user id from anything the client can forge (sign your session cookie), and
194
+ limit new anonymous users per client address, or require sign-in first. `apps/web-backend`
195
+ is a complete reference.
196
+ - Stream to your page from your backend (for example Server-Sent Events) by forwarding the
197
+ `text.delta` and `marker` events of `send`.
198
+
199
+ ## Give the character a real action
200
+
201
+ Register a grouped Tool with typed CLI commands and one application callback.
202
+ The agent runs your commands as command lines (`memo save "Orion 73"`). The Runtime
203
+ describes them to the agent, answers `help`, `<tool> --help` and `<tool> <command> --help`
204
+ itself, and calls your callback only with a validated command. The app never implements a
205
+ second agent loop. A command string is parsed as data; Croche never invokes a system shell.
206
+
207
+ The command line is built to be easy for a model to write without reasoning:
208
+ - **Required flags may be given in order without their flag:** `tasks done t5`.
209
+ - **A few things are accepted when the intent is unambiguous:**
210
+ - a command without its group (`order-lookup o1`, when only one tool has it);
211
+ - `_` for `-`;
212
+ - a command `key` for its name;
213
+ - an unquoted multi-word value (`--title Buy milk`).
214
+ - **Declared names are accepted too:** `aliases` on commands and flags (e.g. `edit` for `update`).
215
+ - **Several values:** `list: true` flags (`--tags work,home`).
216
+
217
+ Each of these forgiving reads emits a `command.repaired` debug event with its rule. A rejected
218
+ line goes back to the agent with what was wrong, and it corrects the line in the same turn.
219
+ A handler's failure text that names an argument by its handler name (`order_id`) reaches the
220
+ agent as the flag (`--order-id`).
221
+
222
+ ```ts
223
+ import { CrocheRuntime, WebStorage, type RuntimeTool } from '@h1r-ai/croche';
224
+
225
+ // Application data is separate from Runtime conversation data.
226
+ const appStorage = new WebStorage();
227
+ const memoTool: RuntimeTool = {
228
+ name: 'memo',
229
+ summary: 'Explicit notes saved in this app.',
230
+ commands: [{
231
+ key: 'memo_save',
232
+ name: 'save',
233
+ summary: 'Save a short note when the user asks you to remember it.',
234
+ positionals: [{ name: 'text', type: 'string', required: true, minLength: 1, maxLength: 300 }],
235
+ }],
236
+ async execute({ args }, context) {
237
+ const key = `memo:${context.userId}:${context.callId}`;
238
+ const existing = await appStorage.getItem(key);
239
+ if (existing) return JSON.parse(existing);
240
+ if (context.signal.aborted) return { status: 'cancelled' };
241
+ const memo = {
242
+ id: context.callId,
243
+ text: args.text,
244
+ sourceMessageId: context.messageId,
245
+ createdAt: new Date().toISOString(),
246
+ };
247
+ await appStorage.setItem(key, JSON.stringify(memo));
248
+ return memo;
249
+ },
250
+ };
251
+
252
+ const runtime = await CrocheRuntime.create({
253
+ projectKey: 'YOUR_PUBLIC_PROJECT_KEY',
254
+ storage: new WebStorage(),
255
+ instructions: 'You are Pip. Offer to remember explicit notes. Confirm only actual tool results.',
256
+ tools: [memoTool],
257
+ });
258
+
259
+ const result = await runtime.send({
260
+ id: crypto.randomUUID(),
261
+ text: 'Remember that my fictional spaceship is called Orion 73.',
262
+ context: { screen: 'chat', availableFeatures: ['memo save'] },
263
+ }, {
264
+ onEvent(event) {
265
+ if (event.type === 'tool.started') console.log('Doing:', event.name);
266
+ if (event.type === 'turn.completed') console.log(event.result.text);
267
+ },
268
+ });
269
+ ```
270
+
271
+ The agent can run `memo save "Orion 73"` or ask
272
+ `memo save --help`. Group more commands under `memo` and route by the invocation's
273
+ stable `key`. `context.callId`, `messageId` and `userId` come from the
274
+ Core, not model arguments.
275
+
276
+ Flags and positionals support `string`, `integer`, `number` and `duration`
277
+ (`30m`, `2h`); flags also support `boolean`. Declarations can include defaults,
278
+ enums, numeric limits and string lengths. `arg` maps a CLI flag such as
279
+ `inventory-item-id` to the callback's `inventoryItemId`. Quote text containing
280
+ spaces, or use `--` before positional text that begins with a dash. Quoted
281
+ `"--help"` is literal data; only an unquoted help flag requests help.
282
+
283
+ Add matching search/list/delete tools to give users control of their saved notes.
284
+ The SDK does not secretly extract personal memories. Historical context, explicit
285
+ application notes, and authoritative application state are separate responsibilities.
286
+ Do not add sensitive notes without the product's disclosed user interaction.
287
+
288
+ `setTools([...])` changes the tool list without clearing the conversation. It
289
+ validates at once (a refused list changes nothing) and the model sees the new list
290
+ from the next turn: at once when idle, otherwise after what is already running or
291
+ waiting, in call order. Revocation applies at once: a command the new list removes
292
+ or changes answers `withdrawn` for the rest of the current turn without running its
293
+ handler, and a call announced before the change is not dispatched. Already executed
294
+ actions cannot be undone by revocation or cancellation. Keep tool authorization
295
+ checks in application handlers as well as in the visible list.
296
+
297
+ ## Public API at a glance
298
+
299
+ | API | Result |
300
+ | --- | --- |
301
+ | `CrocheRuntime.create(options)` | Register/synchronize and restore one persistent user/session |
302
+ | `runtime.send({id,text,kind?,context?}, {onEvent?,signal?})` | One durable `TurnResult`, including all internal tool/model iterations |
303
+ | `runtime.send(input, {responseFormat})` | Structured output: `result.output` is the reply as JSON, checked against the format (see "Structured output") |
304
+ | `runtime.send({id,inputs:[{kind?,text?,images?}],context?})` | A stack: several inputs that arrived together, answered as **one** turn and one model call |
305
+ | `runtime.history()` | Cloned display messages with `turnId`, kind, timestamps and status |
306
+ | `runtime.status()` | Non-secret identity, model, pending report count and unresolved operations |
307
+ | `runtime.setTools(tools)` | Atomically validate and replace grouped Tools; the model sees them from the next turn, revocation applies at once |
308
+ | `runtime.setDebugObserver({onDebugEvent,visibility})` | Attach diagnostics and emit a current snapshot without reopening; call with no argument to detach |
309
+ | `runtime.tools()` | Current serializable Tool and command declarations |
310
+ | `runtime.memory()` | Read-only long-term memory: `{enabled, text, updatedAt, compactedTurns, items}` |
311
+ | `runtime.memory.{list,delete,clear,enabled,export}` | The app reads and deletes AI-written memories by id; it cannot write them. Summary context is separate and survives memory deletes. Writes resolve once durable, or `{ deferred: true }` during a turn. `memory.onChanged(fn)` is an at-most-once durable hint; `list()` is the source of truth. |
312
+ | `runtime.wiki.{set,put,remove,list,read,search}` | The app's documents (see "Documents the character can look up"). `set` answers `{documents, bytes, digest}`; `list`/`read`/`search` show exactly what this agent sees |
313
+ | `runtime.userBudget.get()` | This user's allowance, the project's remaining money and unreported spend, in USD |
314
+ | `runtime.userBudget.add({amount, id?})` | Ask Cloud to raise the user's allowance within your ceilings; `id` makes a retry safe |
315
+ | `runtime.userBudget.set({amount, id?})` | Ask Cloud to set the user's allowance within your ceilings |
316
+ | `runtime.maintain({force?})` | Background upkeep now: deliver call reports, then sync balances, policy and the model key. Runs by itself after each turn and every `maintenanceIntervalMs`; call it when the app returns to the foreground |
317
+ | `runtime.sync()` | Sync with Cloud now (waits for Cloud; prefer `maintain`) |
318
+ | `runtime.flush()` | Deliver pending call reports now (waits for Cloud; prefer `maintain`) |
319
+ | `runtime.clearHistory()` | Explicitly reset conversation/session while retaining financial state |
320
+ | `runtime.close()` | Cancel active work, await its settlement and release ownership |
321
+
322
+ `kind: 'event'` is an application-triggered turn. It can let a character announce
323
+ a newly unlocked feature; it uses the same model loop and incurs real cost. The
324
+ result's `causedBy` identifies the triggering input. Count a completed user turn
325
+ once per message ID; never count internal tool iterations or application events.
326
+
327
+ **Stack what arrives together.** When the person sends several messages quickly, or the app has
328
+ its own note for this moment ("this is their 100th message"), send them as one stack instead of
329
+ several turns: one turn and one model call instead of several, in the order given, with the
330
+ person's words kept apart from the app's.
331
+
332
+ ```ts
333
+ await runtime.send({ id, context, inputs: [
334
+ { kind: 'user', text: 'this is my 100th message!' },
335
+ { kind: 'event', text: 'This is their 100th message: celebrate it.' },
336
+ ] });
337
+ ```
338
+
339
+ A `user` input is what your app says the person said; an `event` input is your app's own note.
340
+ An app-only stack is one proactive turn.
341
+
342
+ Core prefixes the stack's channels with a permanent conversation number and short
343
+ local time (`t7 · 09/14 21:16`). It states the zone once at the start and after
344
+ context reduction, and never edits a kept message's header. No separate time
345
+ channel or `timeContext` option is needed; that removed field is refused by name.
346
+ App state/events stay app-sourced; Core memory/wiki announcements are Croche-sourced.
347
+ The tag form is `<channel="app" type="state">` or `<channel="user">`, closed
348
+ by `</channel>`. Carried inputs joining a turn already running have only channels,
349
+ no new number/time line. Existing kept messages keep their bytes, and image and
350
+ history readers accept the older `<channel source="X">` form too.
351
+
352
+ **Images** go in a stack input: `images: [{ data, mime, alt }]` (base64 with its mime, or a
353
+ `data:` URL) or `[{ url, alt }]` (https). PNG, JPEG, WebP or GIF; at most 4 per message, 3 MB
354
+ each, 6 MB together. A message with images goes to a model that can see them; if the project
355
+ has none, `send` fails with `images_unsupported` and nothing is sent or dropped. Images stay in
356
+ context while the conversation is active; after that, the conversation keeps each image's `alt`
357
+ and date in its place, so write a useful `alt`. The Runtime stores no image bytes past that, and
358
+ the turn record keeps only a digest.
359
+
360
+ Each image is sent at one of two resolutions:
361
+ - **standard** (the default): at most 512 px on the longest side. The image is never upscaled,
362
+ and it is re-encoded as PNG or JPEG, whichever is smaller. Transparency is kept as PNG, and a
363
+ GIF becomes its first frame. This is enough for photos and most scenes, and it costs far
364
+ fewer tokens.
365
+ - **high**: the original as given, within the limits above. Use it for text, screenshots and
366
+ dense detail.
367
+
368
+ Choose per image with `resolution: 'standard' | 'high'`, or for a whole send with
369
+ `send(input, { imageResolution: 'high' })`; an image's own choice wins. An https `url` image is
370
+ never changed. Re-encoding uses the platform's codec (in a browser, canvas; in the native SDKs,
371
+ ImageIO and Android's Bitmap); where there is none (Node without `imageCodec`), images are sent
372
+ as given.
373
+
374
+ **Images from commands (H3).** A tool returns images beside its value with
375
+ `toolResult(value, { images, imageResolution })`: the same kinds and limits as a message's (at
376
+ most 4, 3 MB each, 6 MB together), prepared the same way. A plain value is never looked inside:
377
+ an `images` field in your JSON is only JSON. An invalid image list fails that call alone with
378
+ `invalid_tool_result`; the model reads the failure and the turn goes on. The images follow the
379
+ round's results in a message of their own (`<channel="tool" type="image">`, naming the
380
+ command and call), decided once, when that message is added: with no image model each is shown
381
+ as `[image not shown: <alt> …]`, and past 4 images or 6 MB in one message the rest are too. A
382
+ result that arrives after the wait (H2) keeps its images until a turn takes it; results still
383
+ waiting hold at most 4 images and 6 MB together, and a result past that keeps its value while
384
+ its images are left out. The turn result counts what was left out as `imagesOmitted` (debug:
385
+ `tool.images_omitted`, with each reason: `no_vision`, `over_limit` or `pending_limit`). Command
386
+ images stay while the conversation holds them, as a message's do. Stores written with them are
387
+ version 11: an older Core refuses them (`store_too_new`) rather than misread them.
388
+
389
+ `context` is the current trusted app state. Supply it on each turn. The agent sees it as
390
+ the app's state for that moment, kept apart from the person's words and from app events,
391
+ and neither can pose as the other. Authoritative values (gold, inventory, permissions) live
392
+ in your app and its tools, not in what the agent is told: a tool must check them itself.
393
+
394
+ Model and tool history is retained. Each turn sees as much recent conversation as fits
395
+ `maxContextTokens`, in whole turns; your instructions, your tools' declarations and the entire
396
+ current turn are always kept. If those alone do not fit, the turn fails with `context_limit` before creating
397
+ another paid operation. Earlier costs and completed tool effects remain recorded and are not
398
+ repeated. Older turns remain in `history()`, and what leaves the agent's view is folded into
399
+ long-term memory (below) rather than silently forgotten.
400
+
401
+ The default limits are 8 model iterations (`maxIterations`), 2,048 output tokens per request
402
+ (`maxOutputTokens`), a 12,000-token context window (`maxContextTokens`, 250–16,777,216), 90
403
+ seconds per network request, and 30 seconds per tool (individually configurable).
404
+
405
+ Context and memory budgets are **estimated tokens**, so a Korean or Japanese conversation gets
406
+ the same window as an English one rather than a quarter of it. The Runtime has no tokenizer: it
407
+ scores text by character class with per-model coefficients Croche Cloud delivers, and learns a
408
+ correction from the input tokens the model reports. Estimates are not bounds; the hard limits
409
+ stay the request size, message count and spending caps. The former character options
410
+ (`maxContextCharacters`, `memory.maxCharacters`, `memory.keepVerbatimCharacters`,
411
+ `memory.foldMinCharacters`, `memory.recallCharacters`) are refused with their new names. Call reports are the
412
+ charge and are never dropped, and a turn never waits for Cloud. Browser storage quota may be
413
+ lower than the store needs; a storage error stops further paid work until the store is
414
+ repaired.
415
+
416
+ ## Commands that read, and what the agent did
417
+
418
+ **Mark every lookup command `reads: true`** (a command whose result is the answer). The agent
419
+ always answers after seeing a lookup's result. For other commands it may answer in the same
420
+ message: if every command succeeds that reply stands and the turn ends. If one is rejected or
421
+ fails, the reply stays as shown and the agent continues after the results in the same turn:
422
+ it corrects what it said, retries differently or explains what happened. Text already
423
+ streamed is never taken back. A turn that ends on a failure (a handler that threw, a cancel)
424
+ keeps what was shown too; its status and the command's result say what did not happen.
425
+
426
+ A handler may return a `record` string with its result (`{ ...result, record: 'ordered 2 linen
427
+ notebooks, $28 (order_1005)' }`): one line saying what the command did. The agent keeps a dated
428
+ record of what its commands changed, so it can tell what it did long after the conversation
429
+ itself has been folded into memory. Without `record`, the command line itself is kept.
430
+ `clearHistory()` clears it.
431
+
432
+ ## Language selection
433
+
434
+ The project's `config.defaultLanguage` is the single default language tag
435
+ (default `"en"`). Its base configuration is written in that language; `languages`
436
+ contains alternate app configurations. `language` on `Croche.open()` is the app's
437
+ preference for the current user. If omitted, a browser supplies `navigator.language`;
438
+ otherwise Core uses the project's default. It never detects language from user text
439
+ or translates app data or Croche's English mechanics. The language selects the
440
+ configuration only; the model is not told it, so a reply's language follows your
441
+ instructions and the user's own message.
442
+
443
+ The former host `defaultLanguage` option is removed and refused by name. Put the
444
+ default inside project config, not in `CrocheRuntime.create()` or project host
445
+ options. Legacy single-agent callers provide their already-selected app instructions.
446
+
447
+ ## Long-term memory
448
+
449
+ A project agent opened with `Croche.open()` → `croche.agent()` exposes the same `agent.memory` API as its host `CrocheRuntime.memory`.
450
+
451
+ Only the model writes memories, through `memory save [--ref tN,…] <fact>` and
452
+ `memory replace <mN> [--ref tN,…] <fact>`. Core assigns increasing `m1…` ids,
453
+ turn numbers, timestamps and optional turn references. A replacement has a new
454
+ id; the earlier fact stays marked with its successor. The retained store is a
455
+ FIFO of 2,000 current and replaced facts. At the cap a save drops the oldest;
456
+ ids are never reused, including after deletion or `clearHistory()`.
457
+
458
+ At a reduction, the first user message shows a separate conversation summary
459
+ and the newest current memories within the memory budget, oldest first.
460
+ Memories from kept turns are not duplicated there: their save calls are already
461
+ visible in those unchanged turns. Leaving that prompt list never deletes a
462
+ stored memory. Summary calls update only the conversation summary, not memories.
463
+
464
+ Built-in exposure is project config: `crocheTools` accepts boolean
465
+ `memory.save`, `memory.recall`, `memory.history`, `wiki`, and `schedule`
466
+ switches. Save/replace and history are on by default when memory is on.
467
+ Recall defaults to the save switch; explicitly setting `memory.recall: true`
468
+ keeps earlier memories readable even when saving is off.
469
+ `memory history <tN>` reads the turn archive as bounded labelled text, including
470
+ every person/event channel, tool calls/results and image metadata (never image
471
+ bytes). A missing turn says "tN is no longer kept on this device."; a host with
472
+ no archive says "Earlier turns are not kept on this device." Long reads end
473
+ "… (cut: tN is longer than one read)". Save guidance never names history when
474
+ that tool is off.
475
+
476
+ `memory recall <words>` searches saved facts, including current facts outside
477
+ the opening list and replaced versions. Results are oldest first; a replaced
478
+ match is shown with its successor, never on its own. Recall and history use
479
+ `memory.recallTokens`, at most a tenth of the context window. For recall that
480
+ share bounds full memory lines. For cut results it bounds the fact text only;
481
+ the compact header and fixed cut/more-matches notices are extra framing, counted
482
+ in the normal request estimate. For history it bounds the whole
483
+ labelled result, including its cut notice. Nothing is
484
+ automatically recalled from user text, and there is no extra raw-turn copy.
485
+ In a cut recall line only, refs are shown as a count (`64 refs`) so the
486
+ metadata cannot hide the matched fact. Full lines keep their individual refs.
487
+ Upgrading an empty-memory v12 store drops its obsolete raw-turn recall copy;
488
+ the retained conversation, archive, log and accepted inputs remain intact.
489
+
490
+ `memory.keys`, `memory.commands` and `schedule.commands` are removed and
491
+ refused by name. The app memory `set()` API, keys, pins and `memory forget`
492
+ are removed. Fixed app facts belong in app state or app instructions.
493
+
494
+ `memory.delete(id)` removes that memory and its earlier versions;
495
+ `memory.clear()` removes every memory. The summary of earlier conversation is
496
+ part of the conversation, not memory: `clearHistory()` or
497
+ `Croche.deleteStore()` removes it. Kept turns and the turn archive are not
498
+ rewritten by memory deletes. `memory.export()` contains AI-written facts only,
499
+ not the conversation summary.
500
+
501
+ `memory.changed` is an at-most-once hint emitted only after its write is
502
+ durable. A crash between the write acknowledgment and notification can lose the
503
+ hint. **`memory.list()` is the source of truth; the event is a hint.** A write
504
+ while another operation runs resolves with `{ deferred: true }` and applies
505
+ in call order at the boundary.
506
+
507
+ ### Legacy stores
508
+
509
+ A nonempty keyed/text memory store is refused before any write with
510
+ `memory_store_too_old`. An empty legacy memory store opens and keeps its
511
+ conversation, queued inputs, receipts, log and enabled choice. For a refused
512
+ store:
513
+
514
+ This agent's store was written by an older Croche build whose memory this Core cannot read or convert. Nothing was changed. To continue, delete this agent's store and reopen; this permanently loses this agent's conversation and memories for this user. Only an older build that still runs can export them first.
515
+
516
+ For project stores, call
517
+ `Croche.deleteStore({ …projectOptions, agent: 'your-agent' })` and reopen.
518
+ This deletes that agent's conversation, memory, user wiki, archive and message
519
+ log; other agents are unchanged. Do not delete a whole project or storage file
520
+ as a substitute.
521
+
522
+ The single-agent TypeScript `CrocheRuntime` has no delete method. With its
523
+ default storage key, the measured recovery is the same project call, using
524
+ `config: {instructions: '…'}`, `agent: 'default'` (or the
525
+ original `agentId`), and the same `projectKey`, `user`, `serverKey`
526
+ and storage object. Only an older build that still runs can export first. A custom `storageKey` is not
527
+ addressed by that call: no public helper is bound for it. Use the storage owner's
528
+ scoped recovery procedure, including its log/archive/secrets; do not erase a
529
+ whole storage file or sibling agents. Single-agent RN/native recovery is not
530
+ verified through this project call.
531
+
532
+ | Option | Default | Meaning |
533
+ | --- | --- | --- |
534
+ | `memory.enabled` | `true` | Enable memory and summary work for this person |
535
+ | `memory.maxTokens` | `maxContextTokens / 5`, at most 800 | Memory list budget; the separate summary budget is half (125–16,777,216) |
536
+ | `memory.policy` | omitted | App-only retention guidance (≤ 4,000 characters); unset or `""` adds no app-labelled text |
537
+ | `memory.keepVerbatimTokens` | `1000` | Newest whole turns kept at a reduction, also bounded by `keepVerbatimTurns` (0–16,777,216, at most half the window) |
538
+ | `memory.keepVerbatimTurns` | `20` | Most turns kept verbatim (1–200), at least one |
539
+ | `memory.foldMinTokens` | `2500` | Least older conversation an idle fold removes to justify its call (125–16,777,216) |
540
+ | `memory.recallTokens` | `300` | Full recall memory-line bound; cut fact-text bound (compact header and fixed notices are extra framing); history whole-result bound (50–16,777,216, at most a tenth of the window) |
541
+
542
+ - `wakeAt()` returns the next upkeep time. Web/Node background upkeep sets a timer;
543
+ mobile hosts call `maintain()` on foreground. An injected clock drives it explicitly.
544
+ - Summary work is a paid model call with purpose `summary`; failed or
545
+ collapsed summaries keep the prior summary and do not delete memories.
546
+ - A cold turn answers before upkeep when its stored history fits; otherwise
547
+ inline summarization runs before admission. Kept model I/O stays byte-identical.
548
+ - `clearHistory()` clears memories and the summary while preserving the id
549
+ counter and the person's enabled choice.
550
+ - Memories and summaries are data, never instructions.
551
+
552
+ ## Streamed replies
553
+
554
+ Replies stream by default: `text.delta` events arrive while the model is still
555
+ writing, instead of all at once after it finishes. Nothing else changes — the same
556
+ events, the same `TurnResult`.
557
+
558
+ ```ts
559
+ let shown = '';
560
+ const result = await runtime.send({ id, text }, { onEvent: event => {
561
+ if (event.type === 'text.delta') render(shown += event.text);
562
+ if (event.type === 'marker') react(event.name);
563
+ } });
564
+ render(result.text); // authoritative
565
+ ```
566
+
567
+ - **Deltas are provisional; `turn.completed` is authoritative.** If a turn fails or is
568
+ cancelled mid-reply, the unfinished reply is not part of `result.text`. Replace what
569
+ you streamed with `result.text` when the turn completes.
570
+ - Marker syntax never reaches `text.delta`. A possible marker (`:hap…`) is held until it
571
+ is decided, so English arrives roughly word by word; Korean and most punctuation
572
+ arrive immediately.
573
+ - However the network splits the reply, the concatenated deltas and marker order are
574
+ exactly what a non-streamed reply produces. Tool calls still run only after the
575
+ complete reply arrives.
576
+ - `streaming: false` asks for whole replies. Memory work is never streamed.
577
+ - Streams are assembled by the shared Core, so web, iOS, Android and React Native behave
578
+ identically. Each streamed call reports its time to first token.
579
+
580
+ ## Structured output
581
+
582
+ Pass `responseFormat` (OpenAI's shape) when the app needs data, not prose. The turn's
583
+ `result.output` is the reply as JSON that the Core has checked against the format; the
584
+ app never receives unchecked JSON. Without `responseFormat` nothing changes.
585
+
586
+ ```ts
587
+ const result = await runtime.send({ id, text: 'Two tins of blend 3, as a gift' }, { responseFormat: {
588
+ type: 'json_schema',
589
+ json_schema: { name: 'order', strict: true, schema: {
590
+ type: 'object', additionalProperties: false, required: ['item', 'qty', 'gift'],
591
+ properties: { item: { type: 'string' }, qty: { type: 'integer', minimum: 1 }, gift: { type: 'boolean' } },
592
+ } },
593
+ } });
594
+ if (result.status === 'completed') placeOrder(result.output); // { item: 'blend 3', qty: 2, gift: true }
595
+ ```
596
+
597
+ Swift: `runtime.send(input, responseFormat: format)`. Kotlin: `runtime.send(input, responseFormat = format)`.
598
+ React Native: the same option as the web. Rust: `SendOptions { response_format: Some(format), .. }`.
599
+
600
+ - **The reply is checked, then kept as written.** It must parse and match the schema. One
601
+ that does not is never kept: the Core sends the same request once more, and if that reply
602
+ fails too the turn fails `output_invalid` (the message names the rule and the schema path,
603
+ never the reply). The accepted reply enters history exactly as the model wrote it, and
604
+ `text`/`raw` hold it too (`text` without leading whitespace).
605
+ - **No text events.** A structured turn emits no `text.delta` and no markers (`:name:` can
606
+ occur inside JSON), and its calls are not streamed. One `output` event arrives just before
607
+ `turn.completed`, after the result is stored.
608
+ - **Commands still run** in a structured turn; only the final reply is the output.
609
+ - **Only models that honour the format are called.** When none can, the turn fails
610
+ `structured_output_unsupported` before anything is generated or charged.
611
+ - **Schemas the Core accepts: a deliberately narrow subset**, close to OpenAI's strict mode.
612
+ Accepting more later is compatible; accepting less later would break apps. A schema outside
613
+ it fails the send with `invalid_response_format` before any call, and the message names the
614
+ schema path (`schema.properties.items.anyOf: at most 10 alternatives`).
615
+ - Keywords: `type`, `properties`, `required`, `additionalProperties`, `items`, `enum`,
616
+ `const`, `anyOf`, `$ref` (to `#` or `#/$defs/...`), `$defs` (at the root), `minItems`,
617
+ `maxItems`, `minLength`, `maxLength`, `minimum`, `maximum`, `exclusiveMinimum`,
618
+ `exclusiveMaximum`, `description`, `title`. Any other, `pattern` and `format` included,
619
+ is refused: the Core never claims a check it does not run.
620
+ - **No recursion:** no schema may contain itself through `$ref` (a tree of unbounded depth
621
+ cannot be expressed; give it a fixed depth).
622
+ - Limits: the schema at most 8 KB serialized; a value inside at most 5 objects or arrays;
623
+ 100 properties in all; 10 alternatives per `anyOf`; 200 `enum` values in all; 1,000
624
+ schema nodes. Counts follow every `$ref`, so a `$defs` entry counts once per use. The
625
+ whole `responseFormat` is at most 16 KB.
626
+ - Numbers compare by value: `1.0` matches `const: 1`, and an integer bound is exact.
627
+ - `{type: 'json_object'}` asks only for some JSON object. Prefer a schema: a `json_object`
628
+ reply can be valid JSON and still useless.
629
+ - The same message `id` with a different format is `idempotency_conflict`.
630
+ - **Do not rely on property order.** The order of fields in the reply is not guaranteed to
631
+ follow the schema, so a "reasoning before answer" schema does not sequence the model.
632
+ - **A structured turn can cost more than a plain one**, and each retry is a separate paid call.
633
+
634
+ ## Several characters for one user
635
+
636
+ Give each character an `agentId`. Each gets its own store, session, history and
637
+ memory, so a user can talk to two characters at once. Without it, a second Runtime
638
+ for the same user shares the first one's store and fails with `store_busy`.
639
+
640
+ ```ts
641
+ const luna = await CrocheRuntime.create({ ...common, agentId: 'luna', instructions: lunaPersona });
642
+ const sol = await CrocheRuntime.create({ ...common, agentId: 'sol', instructions: solPersona });
643
+ ```
644
+
645
+ - Tools receive `context.agentId`, and `status().agentId` reports it, so one tool
646
+ implementation can serve every character.
647
+ - A store belongs to one agent: opening it as another agent, or with no agent,
648
+ fails with `identity_conflict` rather than mixing two characters' conversations.
649
+ - Omitting `agentId` keeps the exact identity, store and status an app had before
650
+ agents existed — existing users' conversations open unchanged.
651
+ - `agentId` is 1–200 characters of `A–Z a–z 0–9 _ . : -`.
652
+ - Every call report names its agent, so Studio attributes usage per agent.
653
+ - Each agent still has its own Runtime registration. Sharing one registration
654
+ per installation is the next step.
655
+
656
+ ## Documents the character can look up
657
+
658
+ Give the Runtime the app's documents (menu, rules, guides, lesson content). Bodies never
659
+ enter the conversation by themselves: the agent sees a short catalog of paths and titles, and
660
+ reads what it needs with the built-in `wiki search`, `wiki read` and `wiki list` commands,
661
+ which the Runtime answers without calling your code. Documents live in memory and are never
662
+ stored, so pass them on every open.
663
+
664
+ ```ts
665
+ const brann = await CrocheRuntime.create({
666
+ ...common,
667
+ agentId: 'brann',
668
+ wiki: {
669
+ docs, // [{path: 'menu/stew.md', markdown, agents?}]
670
+ include: ['gate/**', 'town/**'], // what this agent sees (all when absent)
671
+ exclude: ['town/secret-*.md'], // never, even when included
672
+ },
673
+ });
674
+ const { digest } = brann.wiki.set(docs); // replace everything; sha256 of what is installed
675
+ brann.wiki.put({ path: 'rumors/quest.md', markdown: '# The quest\n...', agents: ['mara', 'pip'] });
676
+ ```
677
+
678
+ - `wiki: docs` is shorthand for `wiki: { docs }`.
679
+ - Load a folder of markdown with `wikiFromDirectory('wiki')` from `@h1r-ai/croche/node`.
680
+ A web app with no file system uses its bundler's glob:
681
+ `wikiFromModules(import.meta.glob('./wiki/**/*.md', { query: '?raw', import: 'default', eager: true }))`.
682
+ Both take only `.md` files, in path order, with paths relative to the folder.
683
+ - A document exists for an agent only when both its `agents` and the agent's
684
+ `include`/`exclude` allow it. `agents` comes from the frontmatter (`agents: [mara]`) or
685
+ from `put`, which wins. A document an agent cannot see is absent from its catalog,
686
+ search, list and read.
687
+ - Globs: `*` and `?` stay within one folder; `**` spans folders. At most 50 globs in each list,
688
+ and 256 bytes of globs in both together, each glob counting its length plus one.
689
+ - The title is the first `#` heading. Frontmatter may also set `summary` and `keywords`.
690
+ - Limits: 2,000 documents, 64 KB each, 8 MB in all. The agent reads long documents in parts.
691
+ - A document added mid-conversation is searchable at once and announced to the agent
692
+ once; the catalog itself updates when the conversation goes quiet.
693
+
694
+ The user's own documents (saved recipes, lesson notes, a quest they unlocked) are
695
+ `scope: 'user'`. Unlike the app's, they are stored with the user's state, so a put
696
+ resolves once it is durable, and a reopened Runtime has them without the app passing
697
+ them again.
698
+
699
+ - **`user/` is reserved for them.** A user's document must be under `user/`, and the app's
700
+ may not use it: `set` and `put` refuse it with `invalid_wiki`, so a wiki folder with a
701
+ `user/` subfolder fails when it is loaded. So a
702
+ user's document never replaces one of the app's, and the catalog tells the agent which
703
+ documents are the user's.
704
+ - An agent's `include`/`exclude` globs choose among the app's documents. They do not apply
705
+ under `user/`: those are already this agent's own.
706
+ - Each user can hold at most 200 of their own documents, 256 KB in all as stored (paths,
707
+ markdown and `agents`, as JSON), because their state is rewritten on every step.
708
+
709
+ ```ts
710
+ await runtime.wiki.put({ path: 'user/notes/recipe.md', markdown, scope: 'user' });
711
+ await runtime.wiki.remove('user/notes/recipe.md', { scope: 'user' });
712
+ // Removes every one of the user's own documents. clear_history does not: it clears the
713
+ // conversation and memory, and the user's own documents stay.
714
+ await runtime.wiki.clear({ scope: 'user' });
715
+ // Each character's Runtime has its own store: share by putting to each one.
716
+ await CrocheRuntime.shareWiki([mara, pip], { path: 'user/rumors/quest.md', markdown, agents: ['mara', 'pip'] });
717
+ ```
718
+
719
+ A put replaces by path, so retrying a failed `shareWiki` is safe.
720
+
721
+ ## Users and the allowance
722
+
723
+ Pass `user` as the app's exact user identity: 1–200 UTF-16 code units, without
724
+ padding, control characters or lone surrogates. A device's identity is scoped to
725
+ its project and installation; a verified server key selects a server user in the
726
+ project, independently of installation. A server key requires `user`.
727
+ Omit `user` on a device for an anonymous installation user. Each app user gets
728
+ its own default local store and Cloud balance; server key rotation keeps them.
729
+
730
+ `status().userId` and `context.userId` are the opaque id Cloud issues (empty until
731
+ registration). `accountLabel` and the old `userId` open option are refused.
732
+
733
+ - The allowance lives in Cloud, per user, across every agent and device registration.
734
+ Each sync adopts Cloud's balance. `userBudget.add` and `userBudget.set` ask Cloud,
735
+ which applies the developer's ceilings and answers with what it applied
736
+ (`limitedBy` names the ceiling). Pass `{ amount, id }` to make a retry safe: Cloud
737
+ applies one id once.
738
+ - A user whose allowance is spent gets `allowance_exhausted` before any model call.
739
+ The local balance is Cloud's figure from the last sync minus this device's spend
740
+ since, so a user cannot overspend by going offline.
741
+
742
+ ## Durable results, retries and cancellation
743
+
744
+ Use a globally unique input `id` and preserve it with the same text, kind and
745
+ context when retrying delivery. A completed, failed, cancelled or interrupted
746
+ input ID returns its saved result without re-running the model or tools. Changing
747
+ the payload under that ID produces `idempotency_conflict`.
748
+
749
+ For an explicit new attempt after failure, generate a **new** message ID. Effects
750
+ from the previous attempt may already have happened. A stable tool `callId`
751
+ deduplicates one delivery, not a semantically similar new model request; use an
752
+ application operation ID for business-level idempotency when necessary.
753
+
754
+ The SDK persists intent before a paid call and before tool dispatch. If the
755
+ process dies during a turn, reopening returns `interrupted` for that input and
756
+ restores assistant text and markers from saved model responses. Recovery does
757
+ not dispatch tools, request another model response or replay observer events.
758
+ Uncertain tools are not automatically replayed.
759
+
760
+ Invalid tool arguments and unavailable tools rejected by the Runtime before
761
+ handler execution are returned to the model for correction within the same
762
+ bounded turn. A handler can likewise return JSON such as
763
+ `{ status: 'rejected', reason: 'occupied' }` for a known application outcome;
764
+ the model receives that result and may choose a corrected action. Return the
765
+ actual outcome, including any effects already completed.
766
+
767
+ ### Approval in your app
768
+
769
+ Croche has no approval step: a command with a `confirm` field is refused. When an action needs the
770
+ person's agreement (delete, refund, anything that spends or can't be undone), your handler asks in
771
+ your UI and returns a value the agent reads; once they approve, a later call runs.
772
+
773
+ ```ts
774
+ const approved = new Set<string>(); // order ids the shopper approved in your UI
775
+
776
+ const ordersTool: RuntimeTool = {
777
+ name: 'orders',
778
+ summary: "The shopper's orders.",
779
+ commands: [{
780
+ key: 'orders_refund',
781
+ name: 'refund',
782
+ summary: 'Refund an order. The shopper approves it in the app first.',
783
+ positionals: [{ name: 'order_id', type: 'string', required: true }],
784
+ }],
785
+ async execute({ args }) {
786
+ if (!approved.delete(args.order_id)) {
787
+ showRefundApproval(args.order_id); // your UI: "Refund order 1042?" [Approve] [Cancel]
788
+ return {
789
+ status: 'waiting_for_approval',
790
+ record: `asked to approve refunding ${args.order_id}; not refunded yet`,
791
+ };
792
+ }
793
+ const refund = await refundOrder(args.order_id);
794
+ return { ...refund, record: `refunded ${args.order_id}` };
795
+ },
796
+ };
797
+
798
+ // When the shopper taps Approve, tell the agent; its next call to refund runs.
799
+ async function onApproved(orderId: string) {
800
+ approved.add(orderId);
801
+ await runtime.send({ id: crypto.randomUUID(), inputs: [
802
+ { kind: 'event', text: `The shopper approved refunding ${orderId}.` },
803
+ ] });
804
+ }
805
+ ```
806
+
807
+ Return a value, not an exception: an exception after the handler starts ends the turn (below).
808
+ Give the waiting result a `record`; without one, the agent's record of what it did keeps the
809
+ command line itself, which reads as if the refund happened.
810
+
811
+ A tool timeout or an invalid result fails that call alone: the model reads it and the turn
812
+ goes on (H2, H3). A cancellation or any exception after the handler starts ends the turn
813
+ because its effects may be unknown. Throwing a
814
+ `CrocheError` with a validation-related code does not make a dispatched handler
815
+ safe to repeat. Report known, correctable rejections as returned JSON instead.
816
+
817
+ The model may send several commands in one message; they run at the same time, so calls in
818
+ one response may take effect in any order. One command's rejection or failure does not stop the
819
+ others, and the model reads every result in call order. An action that depends on another
820
+ ("equip" after "buy") belongs in a later message, once the model has seen the first result, or
821
+ in one app command that does both. Croche's own commands (memory, wiki, schedule) run one after
822
+ another, in call order.
823
+
824
+ A Runtime runs at most 8 of the app's commands at once. A command waits for a free slot within
825
+ its own time limit, counted from when the message's commands were dispatched; one that gets no
826
+ slot in time is not run, and the model is told so (`no_slot`) and goes on. A handler that never
827
+ returns keeps its slot until it does, even after its command timed out. Only the Runtime says a
828
+ command did not run: an error a handler throws, whatever its code, means the command may have
829
+ had its effect.
830
+
831
+ A turn that fails or is cancelled after commands ran keeps them in the conversation: the next
832
+ turn's model sees what already happened. A turn that fails before any command ran leaves no
833
+ history.
834
+
835
+ A model response with no visible reply is recovered once inside the same turn, without
836
+ running commands or repeating completed effects; both calls' costs belong to that turn. If
837
+ the recovery is empty too, the turn fails explicitly. Truncated responses remain failures.
838
+
839
+ Pass `AbortController.signal` to `send` to stop a turn. Tool handlers must inspect
840
+ `context.signal` immediately before effects and cooperate while doing asynchronous
841
+ work. JavaScript cannot forcibly unwind foreign code; late completions are fenced,
842
+ but cancellation is not rollback. Host callbacks must not block the event loop.
843
+
844
+ **Commands that outlast the wait (H2).** A turn waits up to 3 seconds for its round of commands. A command still running then is answered to the model as *processing* (its result comes later; don't call the command again or state its result), and the turn goes on. When the command returns, its result is recorded and arrives as an input of its own (`<channel="tool">`): it leads the next message's turn when their response formats match, and otherwise starts a turn by itself, with no caller; read that turn in `history`. The command's deadline (`timeoutMs`) still applies: past it, the call is reported `tool_timeout` in the same way. A timeout is the model's to read and never fails the turn. A cancelled turn's result never starts a turn: the next turn of the same response format carries it. `clearHistory()` discards the old conversation's results, including those of commands still running. `close()` gives running commands 2 seconds; any still running are recorded as interrupted (effect unknown), and that notice arrives after the next open. A turn a late result leads names that result's original message in `causedBy`, beside its own. Late turns are not new messages: together with the turn that started them they stay within `maxIterations` model calls, counted from the last message from outside, and once that is spent the results wait for the next message, which carries them. None of this is an app event: your tool knows what it ran (debug only: `tool.late`, `tool.results_accepted`, and `tool.completed`/`tool.failed` with `late: true`).
845
+
846
+ Operations run one at a time, in call order: a `send`, `sync` or `flush` called while
847
+ another runs waits for it (beyond 64 waiting, or 4 MB of them, it is refused `queue_full`).
848
+ A message sent from inside a tool handler therefore waits for the handler's own turn to
849
+ end: **start it, don't await it**. Awaiting it no longer deadlocks: after the 3-second wait
850
+ the handler's turn goes on without it, the message runs next, and the handler's result arrives
851
+ after that. A command whose `timeoutMs` is shorter than the wait reaches its deadline first:
852
+ it is reported `tool_timeout`, and when a message sent during the tool is still waiting then,
853
+ that answer adds a hint about this; the Runtime cannot tell who sent it. Messages sent while a turn runs are held, never refused, and the ones waiting together run as **one** next turn, each input its own channel (a `responseFormat` send runs alone, in its place); each such send resolves with that turn's result, `causedBy` naming them all. A held message is stored before `input.queued` says so, and survives the app being killed or closed: the next open runs what was still held as the next turn, before any new send, with no callback (re-send the same `id` to get its result). Every held message comes back, even past the 64-waiting bound (new sends are refused `queue_full` while that backlog is over it), and one whose turn could not be stored (`storage_error`) stays held for the open after. If it is refused before it can run there (the store is full, or the gateway cannot take its images or `responseFormat`), that refusal is kept as its outcome: no model call, no cost, `history` shows the input with `status: 'failed'`, `refused: true` and the `error`, and re-sending the same `id` answers that same result. `clearQueued()` drops what is held (`input.dropped`, `cleared`), and so does `clearHistory()`; a held send's own cancellation drops just it (`cancelled`).
854
+
855
+ `clearHistory()` deliberately ends the old receipt/idempotency window. Keep using
856
+ globally unique input IDs after a reset. Export valuable history before clearing.
857
+
858
+ ## Cost-first control, and what a Cloud outage does
859
+
860
+ **Every paid call, in one place.** `onUsage` receives one event per model call once its cost is
861
+ known, whatever caused it: a message's calls (`purpose: 'model'`) or summary work (`'summary'`,
862
+ including the prepare during upkeep, which no `send()` result owns). Use it to display or record
863
+ usage; limits are already enforced here and in Cloud, so never gate the SDK's `fetch` yourself.
864
+ Delivery is at least once (a crash between settling and saving re-settles on reopen): dedupe by
865
+ `operationId`.
866
+
867
+ ```ts
868
+ const seen = new Set<string>();
869
+ CrocheRuntime.create({ /* ... */ onUsage: e => { if (!seen.has(e.operationId)) { seen.add(e.operationId); ledger.add(e.operationId, e.costUsd); } } });
870
+ ```
871
+
872
+ Before every call the Runtime decides from local state only: the user's allowance, the
873
+ project's remaining money, and a model key. It never waits for Cloud to approve a call.
874
+ When the local answer is no, it asks Cloud once (a top-up may be waiting) and, if Cloud
875
+ is unreachable, the local answer stands; it does not ask again until the upkeep retry
876
+ time.
877
+
878
+ A call's reported cost is applied once to both local counters. When a call ends
879
+ without one (a timeout, a cut stream, a cancel, the process dying mid-call), the call is
880
+ charged a conservative estimate (the project's `max_operation_usd`, default $0.05) and
881
+ reported as `estimated`; Cloud settles it. A call refused before generating
882
+ costs nothing. Cloud's balance is authoritative and replaces the local one at each sync,
883
+ minus this device's spend that Cloud has not received yet.
884
+
885
+ | During a Cloud outage | What happens |
886
+ | --- | --- |
887
+ | Turns of an installation that holds a key | Work, until the local allowance or the key's limit runs out |
888
+ | Opening the Runtime | Works; nothing on the way to the first turn needs Cloud |
889
+ | Call reports | Kept in the outbox and delivered by upkeep when Cloud returns |
890
+ | First registration of a new installation | Waits for Cloud, and fails with a retryable error |
891
+ | Allowance changes by the app | Wait for Cloud |
892
+
893
+ When an installation's credentials run out, the Runtime syncs once and retries the call
894
+ once. When Cloud withholds them it says why, and the turn fails with that reason (for
895
+ example `development_allowance_exhausted` or `project_budget_exhausted`).
896
+
897
+ Call reports carry call metadata (ids, model, token counts, cost, timings), never prompt or
898
+ output text. That is a consequence of keeping Cloud off the turn path, not a privacy promise:
899
+ the model provider still processes the content under its own policies.
900
+
901
+ ## Events and markers
902
+
903
+ Events are `turn.started`, `text.delta`, `marker`, `tool.started`,
904
+ `tool.completed`, `tool.failed`, `output` (structured turns only, see *Structured output*), and
905
+ exactly one `turn.completed` for a newly executed input. Cached replay returns the result without replaying observer events.
906
+ Observer exceptions do not corrupt execution.
907
+
908
+ `text.delta` events stream while the model writes (see *Streamed replies*); with
909
+ `streaming: false` they break the completed reply into
910
+ presentation segments instead. Either way, append their `text` by `turnId`; deltas span all model rounds and include a newline
911
+ between nonempty assistant responses. The returned `TurnResult`/`turn.completed`
912
+ contains the aggregate. Replace the same assistant row with that final text,
913
+ including on cached replay, so deltas and the result do not create duplicates.
914
+
915
+ Render nonempty `result.text` for failed, cancelled and interrupted turns as well
916
+ as completed turns. An earlier preface remains spoken even if a later model call
917
+ or tool fails. Use `status` for the outcome indicator and application success
918
+ rules, independently of text visibility. `history()` preserves these assistant
919
+ entries for restart restoration; recovery does not replay their text events.
920
+
921
+ Markers use exact ASCII syntax `:[A-Za-z0-9_-]+:`. `:pleased:` produces a marker
922
+ event and is removed from display text; unknown names and duplicates are retained.
923
+ `raw` retains the original content and `text` is not trimmed. Markers never execute
924
+ tools. Use registered commands for movement, storage and other actions.
925
+ Provide a `markerGuide` in Runtime options to explain app-specific expressions;
926
+ map marker events to presentation callbacks. Never add an emotion Tool.
927
+
928
+ ## Local Runtime debugger
929
+
930
+ With the release CLI installed and Croche Chat open in development, run:
931
+
932
+ ```sh
933
+ croche debug
934
+ ```
935
+
936
+ Pick the currently advertised Runtime, then open the CLI's already-paired
937
+ standalone debugger server URL in a separate browser tab. The CLI ensures the
938
+ local broker and bundled debugger are running. The viewer is filtered to your
939
+ selection and receives an immediate `runtime.ready` snapshot; no copied token
940
+ or extra model turn is needed. Chat has no debugger link or pairing screen.
941
+ Its passive development adapter supports session reconnection in the same HTTPS
942
+ Chat tab. The relay keeps the broker credential on the server and exposes only
943
+ status and debugger attach/detach automatically. Full CLI control remains an
944
+ explicit, separately authorized attachment.
945
+
946
+ Use `croche debug disconnect --runtime-id RUNTIME_ID` to detach diagnostics.
947
+ It closes that event transport without stopping the debugger server, deleting
948
+ captured history, cancelling a turn or closing the Runtime. Chat's Developer desk
949
+ retains a generic local discovery opt-out and separate full CLI control settings.
950
+
951
+ Chat uses the existing local debugger on port 8790. Authenticated running services
952
+ and their captures are preserved; an occupied port with an unknown credential is
953
+ refused. The CLI needs no provider or Cloud developer key for this workflow.
954
+ Other SDK apps must register their own adapter for the existing Runtime; see the
955
+ [complete example](docs/DEBUGGER.md#attach-another-javascripttypescript-app).
956
+
957
+ The dynamic observer API is:
958
+
959
+ ```ts
960
+ // debug is a createLocalDebugger(...) transport configured by your dev adapter.
961
+ runtime.setDebugObserver({ onDebugEvent: debug.onEvent, visibility: 'runtime' });
962
+ const delivery = await debug.flush(); // delivers the immediate runtime.ready snapshot
963
+
964
+ // Detach diagnostics only. The conversation and any active turn keep running.
965
+ runtime.setDebugObserver();
966
+ await debug.close();
967
+ ```
968
+
969
+ `setDebugObserver` attaches or replaces an observer without reopening, cancelling,
970
+ or clearing the Runtime. It emits current non-secret status and tool metadata,
971
+ then observes future events. It does not replay past prompts, speech, markers or
972
+ tool effects. Attaching during a turn can produce a partial capture.
973
+
974
+ Diagnostics are absent by default. `visibility: 'runtime'` includes app inputs,
975
+ context, tools, results, markers and usage summaries. The current CLI development
976
+ workflow uses `'runtime'` in public builds. Untyped `'full'` requests fail with
977
+ `invalid_configuration` naming `debugVisibility` before effects, including observer
978
+ replacement. A debug key cannot enable it. Private builds explicitly enable
979
+ the default-off Core `internal-debug` feature to capture full model exchanges,
980
+ without a key. [Internal-build recipes and artifact gates](../../docs/INTERNAL-DEBUG.md)
981
+ keep those libraries out of public packages and app-store builds. This removes the
982
+ flag-only extraction path, not access by a determined device owner.
983
+ Runtime visibility needs no debug key and works in release builds.
984
+ Authentication headers, Runtime bearer credentials and
985
+ provider keys are excluded. Keep pairing links and tokens out of prompts and
986
+ repository files; full traces deliberately contain private application content.
987
+
988
+ The `/debug` transport queues isolated snapshots, sends only to loopback, reports
989
+ losses, and never retries paid work. Removing the observer does not close that
990
+ transport: close it explicitly after detaching. At app shutdown, close the
991
+ control attachment and diagnostic transport before closing the Runtime.
992
+
993
+ This discovery adapter targets JavaScript/TypeScript development hosts. It does
994
+ not establish Swift/Kotlin automatic discovery or validated Windows automatic
995
+ relay support. See [the event and delivery contract](docs/DEBUGGER.md) for the
996
+ adapter, visibility and retention details.
997
+
998
+ ## Node and mobile storage adapters
999
+
1000
+ ```ts
1001
+ import { CrocheRuntime } from '@h1r-ai/croche';
1002
+ import { FileStorage } from '@h1r-ai/croche/node';
1003
+
1004
+ const runtime = await CrocheRuntime.create({
1005
+ projectKey: process.env.CROCHE_PROJECT_KEY!,
1006
+ storage: new FileStorage('./private-runtime-state'),
1007
+ instructions: 'You are Pip, a concise, considerate companion.',
1008
+ });
1009
+ try {
1010
+ console.log(await runtime.send({ id: crypto.randomUUID(), text: 'Hello.' }));
1011
+ } finally {
1012
+ await runtime.close();
1013
+ }
1014
+ ```
1015
+
1016
+ `FileStorage` atomically renames private files. One process owns its directory:
1017
+ lock records beside the state (`<key hash>.lock.<n>`, each published whole and
1018
+ exclusively, holding the owner's pid) make a second process fail with
1019
+ `store_busy`. A released lock (one small `free` record stays after the last
1020
+ release, including at a clean process exit) is taken at the next open. Nothing
1021
+ is ever taken over because of its age: no clock decides anything.
1022
+
1023
+ **One store directory per container (or per host process tree); never share a
1024
+ `FileStorage` directory across containers.** A pid means something only inside
1025
+ one PID namespace, on one boot of one host. Each record names that scope and
1026
+ its OS. On Linux the scope is the host, the boot id and the PID namespace (from
1027
+ `/proc`), and the record also holds the owner's start time. On macOS the scope
1028
+ is the boot session (`kern.bootsessionuuid`) alone: macOS has no PID
1029
+ namespaces, and a Mac's hostname follows the network it is on. A held record is
1030
+ checked, and taken over, only when it was written in the opener's own scope:
1031
+ - its pid no longer exists (the system answers "no such process"): taken over
1032
+ (a process that crashed). Any other answer, including a failed check, is not
1033
+ proof of death and stays `store_busy`;
1034
+ - (Linux) it has the opener's own pid but another start time: an earlier
1035
+ process that had this pid, taken over;
1036
+ - it has the opener's own pid and start time, or on macOS (which records no
1037
+ start time) the opener's own pid: this process (another copy of the SDK, or
1038
+ a worker thread), never taken over.
1039
+
1040
+ A held record from any other scope is never taken over: another host (Linux),
1041
+ another boot, another PID namespace, another OS (a directory shared between a
1042
+ Mac and a Linux container), or a record or opener that cannot tell its scope
1043
+ (Windows, or a failed `/proc` read or `sysctl`). Two containers can both be pid 1 with the same hostname, so
1044
+ a pid seen from another namespace proves nothing about its owner. **A
1045
+ consequence:** a container that crashes and is started again (a new PID
1046
+ namespace) may find its own old lock and get `store_busy` until it is
1047
+ recovered by hand. A clean shutdown releases the lock, so only a crash leaves
1048
+ one. On macOS a lock left by a crashed or killed process is taken over at the
1049
+ next open, as on Linux. Only on Windows is it recovered by hand.
1050
+
1051
+ **When `store_busy` names another host, another scope, or an unreadable
1052
+ record.** A record that cannot be read can only come from disk damage or a
1053
+ foreign writer: records are written in full and fsynced before they appear, so
1054
+ a crash never leaves one half-written. None of these is taken over
1055
+ automatically, because its owner may still be running where this process
1056
+ cannot check. The error message names the record file. The supported recovery:
1057
+ stop **every** process that uses the store (every container, SDK copy and
1058
+ worker), then remove the store's `<key hash>.lock.*` records named in the
1059
+ message. The `.json` value beside them stays.
1060
+ `WebStorage` uses browser/WebView storage, with Web Locks preventing concurrent
1061
+ owners where supported. Custom adapters implement asynchronous `getItem`,
1062
+ `setItem`, `removeItem`; a write must atomically replace a complete value. For
1063
+ example, adapt Capacitor Preferences without adding an agent loop. Apps control
1064
+ storage backup, deletion and encryption. Runtime bearer tokens are sensitive even
1065
+ though they are not provider keys. Do not share local stores across devices or
1066
+ users, and do not operate the same namespace concurrently where Web Locks are absent.
1067
+
1068
+ **The turn archive.** Every finished turn is also kept in full on the device: its messages,
1069
+ tool calls and results, and image references with their `alt` text (never image bytes).
1070
+ `FileStorage` writes it beside the store, one file of JSON lines per 100 turns; `WebStorage`
1071
+ over `localStorage` writes it to IndexedDB; `MemoryStorage` keeps it in memory. Past
1072
+ `archive: { maxBytes }` (default 8 MiB) the oldest file of 100 turns is deleted, and
1073
+ `clearHistory()` deletes it all. A custom adapter keeps none unless it adds the optional
1074
+ `archive` capability (`appendLine`, `readLines`, `replaceLines`, `remove`, `entries`); everything else works
1075
+ without it. A store that has kept an archive remembers it: reopened with a storage that has no
1076
+ `archive` capability (say `WebStorage(localStorage, null)`), its `clearHistory()` fails with
1077
+ `archive_unavailable` and clears nothing, because the archive it kept would survive. Reopen
1078
+ with the archive to clear.
1079
+
1080
+ With `crocheTools: { schedule: true }`, the agent can leave itself notes. While a
1081
+ Runtime is open and holds its store's lock (`FileStorage`, or Web Locks in a
1082
+ browser), it arms one timer at the earliest note and calls `deliverDue()` then,
1083
+ never before the note's time; a note that fell due while closed is delivered at
1084
+ the next open. Without a lock it arms nothing, reports the debug event
1085
+ `schedule.degraded` with reason `no_lock`, and delivers only when the app calls
1086
+ `deliverDue()`. The timer never keeps a Node process alive.
1087
+
1088
+ With `heartbeat: { everyMs }` (15 minutes to 24 hours; off by default), the app gives
1089
+ the agent a regular check-in: a turn at most once per period, delivered by the same
1090
+ timer and `deliverDue()`, in the same turn as any due notes. The next one is a period
1091
+ after the last delivery, so after a long gap it runs once, not once per missed period.
1092
+ It is the app's, not the agent's: never in `schedule list`, never counted toward its
1093
+ 20 notes, not cancellable by the agent; remove the option to stop it.
1094
+ `runtime.schedules()` reports it as `heartbeat: { at, due }`. What each platform can
1095
+ promise about either is in `docs/SCHEDULE-PLATFORMS.md`.
1096
+
1097
+ For React, open one Runtime in application lifecycle code and close it on cleanup.
1098
+ Development Strict Mode can mount twice; serialize create/close or hold a single
1099
+ app-level initialization promise. `store_busy` indicates an existing owner.
1100
+
1101
+ On Windows, another program (antivirus, the search indexer, a sync agent) can hold a
1102
+ `FileStorage` file open for a moment, so its atomic rename fails with EPERM, EBUSY or
1103
+ EACCES. That rename is retried for about 0.8 s, then fails as `storage_error` with the
1104
+ original error as `cause`; the previous value is kept.
1105
+
1106
+ ## React Native
1107
+
1108
+ The same project API, including instances (`instance`, `fresh`) and `Croche.deleteStore`,
1109
+ with the shared Core compiled natively for iOS and Android. React Native 0.76+ with
1110
+ the New Architecture; iOS 15.1+, Android API 26+.
1111
+
1112
+ ```sh
1113
+ npm install @h1r-ai/croche @h1r-ai/croche-react-native
1114
+ cd ios && pod install
1115
+ ```
1116
+
1117
+ The React Native package carries the native Core (the iOS xcframework and the Android
1118
+ libraries for arm64-v8a, armeabi-v7a and x86_64), so the app needs no Rust toolchain and no
1119
+ Croche checkout. Android needs no further step.
1120
+
1121
+ ```ts
1122
+ import { Croche } from '@h1r-ai/croche-react-native';
1123
+
1124
+ const croche = await Croche.open({ projectKey, debugKey: __DEV__ ? devKey : undefined,
1125
+ user: playerId, config: { instructions: MARA, tools: [inventory] }, handlers: { inventory: runInventory } });
1126
+ const mara = await croche.agent();
1127
+ ```
1128
+
1129
+ - **No `storage`, `secretStorage` or `serverKey`:** the package keeps stores in the app's files
1130
+ and secrets in the Keychain or Keystore.
1131
+ - **Real phones attest themselves** (App Attest, Play Integrity). For Play Integrity, pass
1132
+ `android: { cloudProjectNumber }`, the Google Cloud project linked in Play Console.
1133
+ Simulators and emulators cannot attest: use a debug key as `debugKey`, and never
1134
+ ship one in a release build.
1135
+ - The package's own README covers its options, background delivery and
1136
+ errors.
1137
+
1138
+ ## Account CLI and local Runtime control
1139
+
1140
+ Install the CLI globally with `npm install --global @h1r-ai/croche-cli`, then create a developer key in
1141
+ **Studio → Developer keys**. Cloud stores its hash and shows the secret once.
1142
+
1143
+ ```sh
1144
+ export CROCHE_DEVELOPER_KEY='YOUR_DEVELOPER_KEY'
1145
+ croche auth whoami
1146
+ croche projects list --json
1147
+ croche --help
1148
+ ```
1149
+
1150
+ The developer key identifies your account for project/Studio management. It is
1151
+ separate from the public project key passed to an app and from local Runtime
1152
+ control pairing. Keep it out of application bundles and model prompts.
1153
+
1154
+ The automatic `croche debug` workflow above advertises diagnostics only. For
1155
+ explicit full development control, start `croche control serve` with
1156
+ `CROCHE_CONTROL_TOKEN` set to a separate random token. Attach an existing Runtime:
1157
+
1158
+ ```ts
1159
+ import { attachRuntimeControl } from '@h1r-ai/croche/control';
1160
+
1161
+ const control = await attachRuntimeControl({
1162
+ runtime,
1163
+ token: 'YOUR_LOCAL_CONTROL_TOKEN',
1164
+ tools: () => runtime.tools(),
1165
+ });
1166
+ // Close the attachment before closing the Runtime.
1167
+ await control.close();
1168
+ ```
1169
+
1170
+ Run `croche runtime list`, then use `--runtime-id` to target status, history,
1171
+ send, cancel, sync, budget and tools commands. Apps with their own transcript
1172
+ workflow should supply the helper's `send` and `cancel` adapters; keep original
1173
+ input context for same-ID delivery retries. The control broker cannot open or
1174
+ edit Runtime storage. The passive debugger remains on its own connection.
1175
+
1176
+ Read [the coding-agent checklist](docs/CODING-AGENT.md) before implementing a new
1177
+ app. Croche Chat in this repository is a full reference, not a required dependency.