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