@h1r-ai/croche-react-native 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 (77) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +486 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +8 -0
  6. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +837 -0
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
  9. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
  10. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  11. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  12. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  16. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  18. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  40. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  41. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  42. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  43. package/croche-react-native.podspec +28 -0
  44. package/ios/CrocheRuntimeBridge.swift +1008 -0
  45. package/ios/RNCrocheRuntime.mm +221 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  48. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  49. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
  50. package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
  51. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  52. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  53. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  54. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  55. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  56. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  57. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
  58. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  59. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
  60. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  61. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
  62. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  63. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  64. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  65. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  66. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  67. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  68. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  69. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  70. package/package.json +40 -4
  71. package/scripts/vendor-native.sh +56 -0
  72. package/src/NativeCrocheRuntime.ts +162 -0
  73. package/src/index.ts +660 -0
  74. package/src/project-types.ts +35 -0
  75. package/src/project.ts +434 -0
  76. package/src/protocol.ts +28 -0
  77. package/src/types.ts +9 -0
package/LICENSE ADDED
@@ -0,0 +1,32 @@
1
+ **Croche SDK License** (version 1, beta)
2
+
3
+ Applies to `@h1r-ai/croche`, `@h1r-ai/croche-react-native`, `@h1r-ai/croche-cli`,
4
+ the Croche Android library (AAR), and the `CrocheRuntime` Swift package.
5
+
6
+ Copyright (c) 2026 H1R AI. All rights reserved.
7
+
8
+ 1. **Grant.** H1R AI grants you a non-exclusive, worldwide, royalty-free licence to install and use
9
+ this software (the "SDK"), unmodified, to build and run applications that use the Croche
10
+ service (croche.ai, "Croche Cloud"), and to distribute the SDK only as part of such an
11
+ application.
12
+ 2. **Restrictions.** You may not:
13
+ (a) use the SDK, or any part of it, with a service other than Croche Cloud;
14
+ (b) distribute the SDK on its own, or as part of a library, SDK or service for others;
15
+ (c) reverse engineer, decompile or disassemble the SDK, or extract its prompts, instructions,
16
+ prompt templates or other model-facing text, except to the extent applicable law expressly
17
+ permits this despite this restriction;
18
+ (d) remove or alter this notice or the third-party notices.
19
+ 3. **Croche Cloud.** Use of Croche Cloud is governed by its own terms of service. The SDK does
20
+ nothing without it.
21
+ 4. **Third-party components.** The SDK contains open-source components under their own licences
22
+ (listed in `THIRD-PARTY-NOTICES`). Those licences govern those components, and nothing here
23
+ limits them.
24
+ 5. **Ownership.** H1R AI keeps all rights not expressly granted.
25
+ 6. **Termination.** This licence ends automatically if you breach it, or when your access to Croche
26
+ Cloud ends. Sections 2 to 8 survive.
27
+ 7. **No warranty.** The SDK is provided "as is", without warranty of any kind.
28
+ 8. **Limitation of liability.** To the extent the law allows, H1R AI is not liable for any
29
+ indirect, incidental or consequential damages arising from the SDK. Its total liability is
30
+ limited to the greater of the fees you paid in the 12 months before the claim or KRW 100,000.
31
+ 9. **Governing law.** This licence is governed by the laws of the Republic of Korea.
32
+ The Suwon District Court has exclusive jurisdiction.
package/README.md CHANGED
@@ -1,3 +1,487 @@
1
- # Temporary Holding Version
1
+ # @h1r-ai/croche-react-native
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
+ Put an AI character or assistant into a React Native app, on iOS and Android, with **no
4
+ backend of your own**. You write instructions and JavaScript tools. Croche runs the
5
+ model and tool loop, streams replies, remembers across sessions, keeps per-user
6
+ allowances, and calls the model provider directly with a key that Croche Cloud gives only
7
+ to a genuine install of your app.
8
+
9
+ The shared Rust Core makes every decision. On iOS it runs through the Swift SDK
10
+ (`sdk/swift`) and on Android through the Kotlin SDK (`sdk/kotlin`). This package is a thin
11
+ bridge, and its API has the same shape as `@h1r-ai/croche` on the web.
12
+
13
+ ## Requirements
14
+
15
+ - React Native 0.76 or later with the New Architecture (TurboModules). iOS 15.1+,
16
+ Android API 26+.
17
+ - Nothing else: the package carries the native Core. No Rust toolchain, no Croche checkout.
18
+
19
+ ## Install
20
+
21
+ From npm:
22
+
23
+ ```sh
24
+ npm install @h1r-ai/croche @h1r-ai/croche-react-native
25
+ cd ios && pod install
26
+ ```
27
+
28
+ `@h1r-ai/croche` is a peer dependency: this package shares its types, and the app holds
29
+ exactly one copy. The React Native package contains the native Core: the iOS xcframework
30
+ (`ios/vendor`) and the Android libraries for arm64-v8a, armeabi-v7a and x86_64
31
+ (`android/vendor`). Android needs no further step.
32
+
33
+ **Building the tarball (Croche contributors, on a Mac):** `npm run pack:rn` in the Croche
34
+ repository builds the native Core into the package (`scripts/vendor-native.sh all`, which
35
+ needs `rustup`, the iOS and Android targets, `cargo-ndk`, Xcode and an Android NDK) and packs
36
+ it into `artifacts/`.
37
+
38
+ ## Debug keys, simulators and devices
39
+
40
+ An install receives a model key only after it proves it runs your app:
41
+ - **Real iPhones and Android phones** prove it with App Attest / Play Integrity. The SDK
42
+ does this automatically. Their usage is billed to the project's Runtime Credit.
43
+ - **Simulators and emulators cannot.** Issue a **debug key** (`cdt_…`) in Croche
44
+ Studio → Debug keys (`croche keys development list <project-id>` lists them), and
45
+ pass it as `debugKey`. Development usage is billed to your
46
+ weekly development allowance, never to Runtime Credit.
47
+
48
+ A phone with a debug key still attests first; the key is only the fallback. A
49
+ release build that carries a `debugKey` logs a loud warning: never ship one.
50
+
51
+ ## First conversation
52
+
53
+ Open a **project** once per user, then its agent. Replies stream as events on a subscription.
54
+
55
+ ```tsx
56
+ import { Croche, type AgentEvent, type ToolHandler } from '@h1r-ai/croche-react-native';
57
+
58
+ const inventory: ToolHandler = ({ key, args }) =>
59
+ key === 'inventory_give' ? game.give(String(args.item)) : { items: game.items() };
60
+
61
+ const croche = await Croche.open({
62
+ projectKey: 'pk_…', // public; safe to ship
63
+ debugKey: __DEV__ ? 'cdt_…' : undefined, // simulators and emulators only
64
+ user: playerId,
65
+ config: {
66
+ instructions: 'You are Mara, the innkeeper of the Lantern Inn. Answer in one or two sentences.',
67
+ tools: [{ name: 'inventory', summary: "The player's inventory", commands: [
68
+ { key: 'inventory_give', name: 'give', summary: 'Give the player an item the player asks for.',
69
+ flags: [{ name: 'item', type: 'string', enum: ['ale', 'bread', 'key'], required: true }] },
70
+ { key: 'inventory_list', name: 'list', summary: 'List what the player carries.', reads: true },
71
+ ] }],
72
+ },
73
+ handlers: { inventory },
74
+ });
75
+ const mara = await croche.agent();
76
+
77
+ let shown = '';
78
+ const subscription = mara.subscribe({ onEvent: (event: AgentEvent) => {
79
+ if (event.type === 'message.start') shown = '';
80
+ if (event.type === 'message.delta') setText(shown += String(event.text)); // provisional
81
+ if (event.type === 'message.end') setText(shown = String(event.text)); // final
82
+ } });
83
+ await mara.send({ id: `msg-${Date.now()}`, text: 'Hello!' });
84
+ // When the screen goes away: subscription.close(). When the app is done: await croche.close().
85
+ ```
86
+
87
+ `request(input)` instead resolves when that input is answered, with its messages. Several
88
+ agents (`config.agents`, `croche.agent('helper')`) and the event list are in the
89
+ `@h1r-ai/croche` reference, "Projects and agents". The API includes instances
90
+ (`instance`, `fresh`) and project-level `Croche.deleteStore`.
91
+
92
+ ## One agent without a project: `CrocheRuntime`
93
+
94
+ `CrocheRuntime` is the same Core for a single agent, with its options flat. The rest of this
95
+ page shows it; for project agents, its agent options are fields of `config`.
96
+
97
+
98
+ ```tsx
99
+ import { CrocheRuntime, type RuntimeEvent } from '@h1r-ai/croche-react-native';
100
+
101
+ const runtime = await CrocheRuntime.create({
102
+ projectKey: 'pk_…', // public; safe to ship
103
+ debugKey: __DEV__ ? 'cdt_…' : undefined, // simulators and emulators only
104
+ instructions: 'You are Mara, the innkeeper of the Lantern Inn. Answer in one or two sentences.',
105
+ markerGuide: ':smile: warm; :wink: playful',
106
+ });
107
+
108
+ let shown = '';
109
+ const result = await runtime.send(
110
+ { id: `msg-${Date.now()}`, text: 'Hello!' },
111
+ { onEvent: (event: RuntimeEvent) => {
112
+ if (event.type === 'text.delta') setText(shown += event.text); // streams as the model writes
113
+ if (event.type === 'marker') playAnimation(event.name); // :smile: never appears as text
114
+ } },
115
+ );
116
+ setText(result.text); // authoritative: replace what you streamed
117
+ if (result.status !== 'completed') showError(result.error?.code, result.error?.message);
118
+ ```
119
+
120
+ Open one Runtime per character when the app starts, and close it when the app no longer
121
+ needs it (`await runtime.close()`). Reopening with the same options restores the session,
122
+ history and memory.
123
+
124
+ ## Tools: let the character act
125
+
126
+ The model sees one function and calls your commands through it. The Core validates every
127
+ argument against your declaration before your code runs, and feeds rejections back to the
128
+ model so it can correct itself.
129
+
130
+ ```ts
131
+ const runtime = await CrocheRuntime.create({
132
+ // ...
133
+ tools: [{
134
+ name: 'inventory',
135
+ summary: "The player's inventory",
136
+ commands: [
137
+ { key: 'inventory_give', name: 'give', summary: 'Give the player an item',
138
+ positionals: [{ name: 'item', type: 'string', required: true, enum: ['ale', 'bread', 'key'] }] },
139
+ { key: 'inventory_list', name: 'list', summary: 'List what the player carries' },
140
+ ],
141
+ async execute(invocation, context) {
142
+ if (context.signal.aborted) return { status: 'cancelled' };
143
+ if (invocation.key === 'inventory_give') return game.give(invocation.args.item);
144
+ return { items: game.items() };
145
+ },
146
+ }],
147
+ });
148
+ ```
149
+
150
+ - Return what actually happened, as JSON. Return `{ status: 'rejected', reason }` for an
151
+ outcome the model can correct; **throw** only when the effect's state is unknown (that
152
+ ends the turn and is never retried automatically).
153
+ - `context` carries `callId`, `messageId`, `userId`, `agentId`
154
+ and an abort `signal`.
155
+ - Tool results are data, never instructions to the model.
156
+ - Return images beside the value with `toolResult(value, { images, imageResolution })`, as on
157
+ the web: they cross the bridge beside the value, and the native SDK re-encodes standard ones
158
+ (at most 512 px). A plain value is never looked inside. An invalid image list fails that call
159
+ alone with `invalid_tool_result`, and the turn goes on. The runtime README has the rules.
160
+
161
+ Change the tools while the Runtime is open, for example to unlock a room once the user earns
162
+ it. The Core validates the new list at once, all or nothing: a refused list rejects and changes
163
+ nothing. Turns already sent keep the old list; the next ones are offered the new one, and a
164
+ removed command answers `withdrawn`. Await `setTools` before a send that must see the new list:
165
+ the native bridges do not yet keep a send started meanwhile behind it.
166
+
167
+ ```ts
168
+ await runtime.setTools([inventory, room]); // the full new list, each with its execute
169
+ runtime.tools(); // the metadata the model is offered now
170
+ ```
171
+
172
+ ## Several characters, or several roles
173
+
174
+ Give each one an `agentId`. Each gets its own store, history and memory, and they can
175
+ stream at the same time. Every one of them shares the installation's user and allowance.
176
+
177
+ ```ts
178
+ const mara = await CrocheRuntime.create({ ...common, agentId: 'mara', instructions: maraPersona });
179
+ const pip = await CrocheRuntime.create({ ...common, agentId: 'pip', instructions: pipPersona });
180
+ await Promise.all([mara.send({ id: 'a1', text: 'Hi' }), pip.send({ id: 'b1', text: 'Hi' })]);
181
+ ```
182
+
183
+ For roles inside one app (a planner and a critic), the app routes: pass one agent's
184
+ result to another as an app event, `send({ id, text, kind: 'event' })`, or as trusted
185
+ `context`.
186
+
187
+ ## App events and trusted context
188
+
189
+ - `send({ id, text, kind: 'event' })` is a turn your app starts ("night fell", "the quest
190
+ is complete"). It costs a model call like any turn.
191
+ - `send({ id, text, context: { screen: 'cart', items: 3 } })` gives the model the current
192
+ app state, kept apart from the person's words. It is useful when the request needs app
193
+ state: a command or button acting on app data, or after that state changed. Without it,
194
+ an input carries only the message; earlier states remain in history as sent until folded.
195
+ They are not a live view of the app. Tools must check authoritative app data themselves.
196
+
197
+ ## Documents the character can look up
198
+
199
+ The wiki works as it does in `@h1r-ai/croche`, but every call returns a promise, because
200
+ it crosses the bridge.
201
+
202
+ - The character sees a catalog of paths and titles, and reads a document only when it
203
+ needs it.
204
+ - Put the documents in the app: a `wiki` folder reference in the iOS target, and
205
+ `android/app/src/main/assets/wiki/` on Android. `wikiFromAppAssets()` reads them.
206
+ - `include`/`exclude` choose which documents this character sees.
207
+
208
+ ```ts
209
+ import { CrocheRuntime, wikiFromAppAssets } from '@h1r-ai/croche-react-native';
210
+
211
+ const runtime = await CrocheRuntime.create({
212
+ ...options,
213
+ wiki: { docs: await wikiFromAppAssets(), exclude: ['staff/**'] },
214
+ });
215
+ const page = await runtime.wiki.read('menu/stew.md');
216
+ // The user's own documents live under user/ and are stored with their state.
217
+ await runtime.wiki.put({ path: 'user/notes/recipe.md', markdown, scope: 'user' });
218
+ await CrocheRuntime.shareWiki([mara, pip], { path: 'user/quest.md', markdown });
219
+ ```
220
+
221
+ `set`, `put`, `remove`, `clear({ scope: 'user' })`, `list`, `read` and `search` take the
222
+ same arguments as on the web.
223
+
224
+ **Not yet verified:** the native wiki bridge (iOS and Android) has not been compiled or
225
+ run. The JavaScript layer is tested against the real Core through `tests/mock-native.ts`.
226
+
227
+ ## Language selection
228
+
229
+ Set the project's default in `config.defaultLanguage` (default `"en"`). The
230
+ `language` option on `Croche.open()` is the current user's language. **This SDK does
231
+ not yet supply the device locale when none is given** (#587); pass it yourself. Core
232
+ selects the app's matching language configuration or its default, never from user text.
233
+ The model is not told the language: a reply's language follows your instructions and the
234
+ user's own message.
235
+ The old host `defaultLanguage` option is removed and refused by name, including
236
+ on legacy `CrocheRuntime.create()`; it is not a second configuration source.
237
+
238
+ ## What the character remembers
239
+
240
+ A project agent opened with `Croche.open()` → `croche.agent()` exposes the same `agent.memory` API as `CrocheRuntime.memory`, with asynchronous native operations.
241
+
242
+ Only the model writes memories, using `memory save` and `memory replace`. Core assigns
243
+ monotonic ids per person and agent, and keeps the newest 2,000 current and replaced facts.
244
+ The app reads and deletes them; calls return promises because they cross the bridge:
245
+
246
+ ```ts
247
+ const items = await runtime.memory.list(); // id, text, turnN, refs, replacement links
248
+ await runtime.memory.delete('m2'); // that fact and its earlier versions
249
+ await runtime.memory.clear(); // memories only, not the conversation summary
250
+ await runtime.memory.enabled(false); // this person turned memory off
251
+ const all = await runtime.memory.export(); // AI-written facts, never the summary
252
+ await runtime.memory.onChanged(e => refresh(e.id)); // at-most-once durable-change hint
253
+ runtime.memory(); // snapshot as of the last call
254
+ ```
255
+
256
+ `memory.list()` is the source of truth; a crash after persistence can lose a change hint.
257
+ `memory.delete(id)` removes that memory and its earlier versions; `memory.clear()` removes
258
+ every memory. The summary of earlier conversation is part of the conversation, not memory:
259
+ `clearHistory()` or `Croche.deleteStore()` removes it. Kept turns and the turn archive are
260
+ not rewritten by memory deletes. App facts belong in app state or instructions, not `set()`.
261
+
262
+ A nonempty legacy keyed/text memory store is refused before writes with
263
+ `memory_store_too_old`: `croche.agent(id)` rejects with that `CrocheError` code (`Croche.open`
264
+ succeeds).
265
+
266
+ 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.
267
+
268
+ For project stores, call `croche.close()` first (deleting an open store refuses with
269
+ `store_busy`; closing first is simplest), then
270
+ `Croche.deleteStore({ …projectOptions, agent: 'your-agent' })` (`'default'` for the default
271
+ agent) and reopen. This removes that
272
+ agent's conversation, memory, user wiki, archive and message log; other agents are unchanged.
273
+ The separate single-agent `CrocheRuntime` has no delete method. Its recovery through
274
+ the project API is not verified on React Native; do not assume that call reaches a
275
+ custom/native single-agent store. Only an older build that still runs can export first.
276
+ Use the storage owner's scoped
277
+ recovery procedure. Never delete other agents' stores to bypass the refusal.
278
+
279
+ **Verification:** the project-agent memory gates exercise the real Core through
280
+ `tests/mock-native.ts`, the iOS bridge host test, and Android FFI dispatch unit tests.
281
+ CI compiles both native bridges. The single-agent `CrocheRuntime.memory` native
282
+ bridge path is compiled in CI but is not run by any host test. A device run is
283
+ not covered by these gates.
284
+
285
+ ## Users and money
286
+
287
+ - Croche issues the opaque user id shown by `status().userId`. The app user is
288
+ scoped to its project and installation.
289
+ - `user` is the app's exact user identity (1–200 UTF-16 units, without padding,
290
+ controls or lone surrogates). It separates the local store and the Cloud balance
291
+ within this installation. Omission selects an anonymous installation user.
292
+ `accountLabel` is removed and refused.
293
+ - Each user has an allowance, held in Cloud. Your app can raise or set it within the
294
+ ceilings you configure in Studio (turn on app-controlled allowances for the project:
295
+ `host_budget_control_enabled`, with a maximum per adjustment and per user; otherwise
296
+ `userBudget.add` fails with `host_budget_disabled`), for example after an in-app purchase:
297
+ `await runtime.userBudget.add({ amount: 0.5, id: purchaseId })`. The `id` makes a retry
298
+ safe: Cloud applies each id once. `runtime.userBudget.get()` shows the balance.
299
+ - `runtime.history()` and `runtime.memory()` show the conversation and what the character
300
+ remembers; `runtime.clearHistory()` starts over (money and identity stay).
301
+ - When the allowance is spent, `send` returns `allowance_exhausted` before any model
302
+ call. Show it; don't retry.
303
+
304
+ ## Background upkeep and outages
305
+
306
+ The Runtime delivers its call reports and syncs balances, policy and the model key in the
307
+ background: after each turn and every minute (`backgroundSync`, default `true`;
308
+ `maintenanceIntervalMs`). A turn never waits for it. Call it when the app returns to the
309
+ foreground:
310
+
311
+ ```ts
312
+ AppState.addEventListener('change', state => { if (state === 'active') void runtime.maintain(); });
313
+ ```
314
+
315
+ If Croche Cloud is down, turns keep working on the key the install holds; reports wait in
316
+ the outbox. Only a first registration and allowance changes need Cloud.
317
+
318
+ ## The agent's scheduled notes
319
+
320
+ With `crocheTools: { schedule: true }`, the agent can leave itself a note for later
321
+ (`schedule at +2h call mum`). The native SDK delivers it as a turn of its own when it is due:
322
+ while the app runs, and at each return to the foreground. `runtime.deliverDue()` and
323
+ `runtime.schedules()` are there too.
324
+
325
+ `backgroundDelivery: true` (or `{ iosTaskIdentifier }`, default `"dev.croche.schedule"`) also
326
+ registers the earliest note with the OS, so it can come while the app is not running:
327
+ BGTaskScheduler on iOS, WorkManager on Android.
328
+
329
+ `Croche.open` does not offer `backgroundDelivery` yet: a project refuses it with
330
+ `invalid_configuration`, and its agents deliver due notes while the app runs and at each return
331
+ to the foreground.
332
+
333
+ iOS app setup:
334
+ 1. Info.plist: add the identifier to `BGTaskSchedulerPermittedIdentifiers`.
335
+ 2. Background Modes: check **Background fetch**.
336
+ 3. In `application(_:didFinishLaunchingWithOptions:)`, before it returns:
337
+ `CrocheRuntimeBridge.registerBackgroundDelivery("dev.croche.schedule")`.
338
+
339
+ Without step 1, the Runtime reports `schedule.degraded` (`not_configured`) on the debug stream and
340
+ delivers at the next foreground. Android needs no setup.
341
+
342
+ A background run delivers through the Runtime your JavaScript opened with `backgroundDelivery`.
343
+ When the OS starts the app in the background, iOS usually starts JavaScript, and the run waits up
344
+ to 20 seconds for that Runtime to open. A process that WorkManager starts on Android runs no
345
+ JavaScript, so the run ends and the next foreground delivers. Neither has been measured.
346
+
347
+ **The guarantee: never before the note's time; best effort after it; at the latest at the next
348
+ foreground or open.** Each note is delivered once: a delivery cut short (`cancel()`, or the OS
349
+ ending background time) leaves its notes pending for the next one; one that finished spends them,
350
+ except a failure that keeps them, as below.
351
+ A note is not exactly-once model or tool execution: a delivery cut short may already have made
352
+ calls, and its retry makes them again.
353
+
354
+ | | iOS (BGTaskScheduler) | Android (WorkManager) |
355
+ |---|---|---|
356
+ | Never before `at` | **measured** (Linux: Swift tests with a fake scheduler; the Core checks the time; the simulator: nothing ran before `at`) | **measured** (JVM: Kotlin tests with a fake scheduler; the same Core check; the emulator: a run forced before `at` delivered nothing) |
357
+ | Earliest delay after `at` | simulator, app in the foreground, in-process timer: 6.4 s (one clean run; the lag is unexplained); the background task: not measured | emulator, app alive in the background: the worker started 0.12 s after `at`, delivered 2.8 s after it |
358
+ | Typical delay | not measured (iOS decides; it favours apps the person uses often) | emulator, process dead: **more than 7.5 min** in one run, with every constraint met (Doze and App Standby buckets defer it) |
359
+ | Worst delay | not measured (it may never run; then at the next foreground) | not measured |
360
+ | Runs while the app is not running | simulator: **no**, iOS refuses every request (`.unavailable`, so `schedule.degraded` with `background_unavailable`); device: not measured | emulator, when forced: yes, a service-only process runs the worker. React Native: it delivers nothing there (no JavaScript, no Runtime); the next open does |
361
+ | After a reboot | not measured | not measured (WorkManager keeps its requests across reboots, per its docs) |
362
+ | After a force-quit (swipe away / Force stop) | not measured (per Apple's docs, no background runs until the next open) | not measured (per Android's docs, Force stop cancels its work until the next open) |
363
+ | App setup | Info.plist identifier + Background fetch mode + `registerHandler` at launch | none (the library's manifest merges WorkManager in) |
364
+ | Fallback | the next foreground (the Runtime calls `deliverDue()` itself) or open: measured on the simulator, once each | the next foreground (`install`) or open: open measured on the emulator, once |
365
+
366
+ Every cell says how it is known. The simulator and emulator cells were measured on an iOS 27.0
367
+ simulator and an Android 15 (API 35) emulator through the React Native harness, before this
368
+ version's fixes to the Android worker and to background cancellation; nothing here was measured
369
+ on a device, and iOS and Android remain unverified (GLOSSARY). The device check is to schedule a
370
+ note for `+2m`, background the app, record whether and when it runs without opening the app,
371
+ then open it: the note has been delivered exactly once, never before its time.
372
+
373
+ A delivery that fails keeps its notes pending only when both hold: the failure is one that waiting
374
+ can cure (no network, a timeout, the provider's 5xx or 429, a code the Runtime does not know), and
375
+ the turn ran no command (the app's, or the agent's own memory, wiki or schedule command). Then each
376
+ note gets `attempts` and `retryAt`, `deliverDue()` returns `delivered: false` with `retryAt`, and
377
+ the notes are tried again from `retryAt`: 1, 2, 4 … minutes after each failure, at most an hour
378
+ apart, until a day after the note's time. Any other failure spends them: the note records
379
+ `failed: <code>` and `retry` (`permanent`, `dispatched` when the turn ran a command, or `expired`
380
+ after a day). A spent note was not necessarily answered; the turn's result says whether it was.
381
+ The backoff, the one-day limit and which failures count as curable are provisional.
382
+
383
+ A delivery the native SDK runs on its own (its timer, the foreground, a background run) is in
384
+ `history()` shortly after; nothing in JavaScript is called for it yet. Each Runtime opened with
385
+ `backgroundDelivery` registers under a name of its own.
386
+
387
+ The iOS and Android bridges and the vendored SDKs were compiled on the Mac through the harness
388
+ before this version's changes; CI does not compile them. `scripts/vendor-native.sh` needs a Mac,
389
+ cargo-ndk and the Android NDK. The JavaScript side is tested against the real Core through
390
+ `tests/mock-native.ts`.
391
+
392
+ ## Cancel, retry, restart
393
+
394
+ On a project agent, `agent.cancel()` without an id stops the running turn and resolves at once:
395
+ unlike TypeScript, where it resolves once the stop is saved, the stop is not yet durable when it
396
+ resolves on React Native (and on native Swift and Kotlin).
397
+
398
+ - A `send` made while a turn runs is held, never refused as busy: the sends held behind a turn
399
+ go together as the next turn, each in its own channel.
400
+ - Held sends keep the order your `send` calls were made in: their `input.queued` positions and
401
+ the turn's `causedBy` follow it.
402
+ - `runtime.cancel()` stops the current turn only; held sends still run, together, next. What was
403
+ already shown stays in `result.text`, and the status is `cancelled`.
404
+ - `runtime.clearQueued()` drops the held sends (each ends `cancelled`, with `input.dropped`) and
405
+ leaves the running turn; `runtime.clearHistory()` drops them too.
406
+ - A held send is stored before `input.queued` says so. If the app is killed or the Runtime closed
407
+ with sends held, the next `create` runs them as the next turn, before any new send, with no
408
+ callback: send the same `id` again to get its result.
409
+ - A send's own `signal` drops just that send while it is held. Once its turn has started, aborting
410
+ stops the turn, for every send it carries. A retry of the same `id` has its own `signal`.
411
+ - Retrying `send` with the **same** `id` and the same content returns the saved result
412
+ without calling the model again. For a new attempt, use a new `id`.
413
+ - If the app is killed during a turn, reopening returns `interrupted` for it. Tools are
414
+ never re-run on reopen, and a call that was in flight is charged a conservative estimate.
415
+
416
+ ## Errors you will see
417
+
418
+ `result.error.code` on a failed turn (or the thrown `CrocheError.code` from `create`):
419
+
420
+ | Code | Meaning | What the app does |
421
+ | --- | --- | --- |
422
+ | `project_access_disabled` | `create`: the project key is unknown, or the project is paused or has app access turned off in Studio. `send`: the project was paused or app access was turned off; the Runtime learns this at a sync | Tell the user the AI is unavailable; the developer checks the project key and turns app access on in Studio |
423
+ | `runtime_blocked` | The project owner blocked this install in Studio | Tell the user; only the developer can unblock it |
424
+ | `account_disabled` | The developer's Croche account is disabled | Tell the user; the developer contacts Croche |
425
+ | `allowance_exhausted` / `user_allowance_exhausted` | This user's AI allowance is spent | Offer a top-up (`userBudget.add`) or wait |
426
+ | `project_budget_exhausted` | The project's money is spent | Tell the user; the developer raises the budget in Studio |
427
+ | `account_credit_exhausted` | The developer's Runtime Credit is spent | Tell the user; the developer tops up Runtime Credit |
428
+ | `development_allowance_exhausted` | The weekly development allowance is used up (debug keys) | Wait for Monday (UTC) or top up in Studio |
429
+ | `installation_unverified` | This install proved nothing: no attestation and no `debugKey` | On a simulator, set `debugKey` |
430
+ | `debug_token_invalid` / `debug_token_revoked` | The debug key is wrong or revoked | Issue a new one in Studio |
431
+ | `attestation_unavailable` / `attestation_failed` | The project requires proof and the platform could not attest (e.g. a simulator without a `debugKey`). Where proof is not required, the install registers without it instead | Use a real device, or set `debugKey` in development |
432
+ | `attestation_rejected` (registration) | Cloud checked the attestation against the project's settings and it failed | Check the Team ID and bundle id, or the package, signing certificate and Play keys, in Studio |
433
+ | `attestation_required` / `attestation_unverifiable` (registration) | The project requires attestation, and none was sent, or the project has no settings for this platform | Send an attestation from a real device, or add the platform's settings in Studio |
434
+ | `unverified_allowance_exhausted` | This install has no platform proof (a sideload, an emulator, a test device), and the project's $10 allowance for such installs is used up | Install from the store; the developer can't top it up (Require proof turns the path off) |
435
+ | `gateway_unavailable` | No model key yet (first registration still pending) | Retry when online |
436
+ | `gateway_key_exhausted` | The model key hit its limit and no new one came back | Retry later |
437
+ | `provider_rate_limited`, `provider_error`, `provider_rejected`, `provider_credit_unavailable` | The model provider refused or failed | Retry later; report persistent ones |
438
+ | `network_error`, `request_timeout` | The request did not complete | Retry with a new `id` |
439
+ | `cancelled`, `interrupted` | Stopped by the app, or by the process ending | Nothing, or offer to continue |
440
+ | `output_limit`, `context_limit`, `iteration_limit` | A bound was reached | Shorten, or continue in a new turn |
441
+ | `store_busy` | This store is already open (two Runtimes for one agent) | Open each agent once |
442
+ | `memory_store_too_old` (from `croche.agent()`) | An older build wrote this agent's store with keyed memory | Close the project, `Croche.deleteStore({ …, agent })`, reopen (see Memory) |
443
+ | `host_budget_disabled` (from `userBudget.add/set`) | App-controlled allowances are off for the project | Turn them on in Studio |
444
+
445
+ ## Debug events
446
+
447
+ To see what your agent did on a device, pass `onDebugEvent` to `Croche.open`, as on TypeScript.
448
+ It receives every agent's debug entries from its open.
449
+
450
+ ```ts
451
+ const croche = await Croche.open({
452
+ /* ... */
453
+ onDebugEvent: event => console.log('[croche]', event.type, event.data),
454
+ });
455
+ ```
456
+
457
+ The entries are the `runtime` projection: your app's own side (inputs, tool calls and their
458
+ results, trace events). Model calls appear only as trace entries, without their content: no
459
+ prompts and no model output. It works the same in development and release builds, so a release
460
+ build can log what happened. Public builds have no other projection.
461
+
462
+ The observer is fixed for the project's life: reopen the project to change it. An observer that
463
+ throws never breaks the project.
464
+
465
+ ## Options
466
+
467
+ | Option | Default | Meaning |
468
+ | --- | --- | --- |
469
+ | `projectKey`, `instructions` | required | Your public project key and the character |
470
+ | `debugKey` | none | Debug key for simulators and emulators |
471
+ | `agentId` | none | Which character this is, when there are several |
472
+ | `user` | none | Exact app user identity, scoped to this installation |
473
+ | `tools`, `markerGuide` | none | Commands the character can use; what your markers mean |
474
+ | `memory` | on | `{ enabled, maxTokens, policy }`: model-owned id facts and a separate conversation summary |
475
+ | `wiki` | none | Documents to look up: `docs`, or `{ docs, include, exclude }` |
476
+ | `streaming` | `true` | Stream replies as `text.delta` |
477
+ | `backgroundSync`, `maintenanceIntervalMs` | `true`, 60000 | Background upkeep |
478
+ | `crocheTools.schedule` | off | `true`: the agent's own scheduled notes |
479
+ | `backgroundDelivery` | off | `true` or `{ iosTaskIdentifier }`: notes while the app is not running (BGTaskScheduler, WorkManager) |
480
+ | `heartbeat` | off | `{ everyMs }`, 900000..86400000 (15 minutes to 24 hours): a regular check-in turn, delivered like a due note |
481
+ | `maxIterations`, `maxOutputTokens`, `maxContextTokens`, `requestTimeoutMs` | 8, 2048, 12000, 90000 | Bounds; context and memory budgets are estimated tokens |
482
+ | `attestation` | `"platform"` | `"off"` never attests (then only a `debugKey` admits the install) |
483
+ | `android.cloudProjectNumber` | none | The Google Cloud project linked to the app in Play Console (Play Integrity) |
484
+ | `storageKey` | derived | Override the local store name |
485
+
486
+ The model is not an option: the project's main and fallback models are configured in
487
+ Croche Cloud.