@h1r-ai/croche-react-native 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +475 -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 +836 -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/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  11. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  12. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  13. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  16. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  17. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  18. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  32. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  33. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  34. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  35. package/croche-react-native.podspec +28 -0
  36. package/ios/CrocheRuntimeBridge.swift +986 -0
  37. package/ios/RNCrocheRuntime.mm +221 -0
  38. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  39. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  40. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  41. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
  42. package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
  43. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  44. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  45. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  48. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
  49. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  50. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
  51. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  52. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  53. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  54. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  55. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  56. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  57. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  58. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  59. package/package.json +40 -4
  60. package/scripts/vendor-native.sh +56 -0
  61. package/src/NativeCrocheRuntime.ts +162 -0
  62. package/src/index.ts +660 -0
  63. package/src/project-types.ts +35 -0
  64. package/src/project.ts +426 -0
  65. package/src/protocol.ts +28 -0
  66. package/src/types.ts +9 -0
@@ -0,0 +1,35 @@
1
+ import type {CommandInvocation, JsonValue, OpenOptions, ProjectToolContext, ProjectUsageEvent, RuntimeDebugEvent} from '@h1r-ai/croche';
2
+ import type {ToolResult} from './index';
3
+ export type {AgentConfig, AgentOptions, AgentOverride, ProjectConfig, ReleasedConfig, ToolDeclaration, AgentToolControls, ProjectToolContext, ProjectUsageEvent} from '@h1r-ai/croche';
4
+
5
+ /** A tool's handler, as in TypeScript; it may return this package's `toolResult(...)` (#22). */
6
+ export type ToolHandler = (invocation: CommandInvocation, context: ProjectToolContext) =>
7
+ JsonValue | ToolResult | Promise<JsonValue | ToolResult>;
8
+
9
+ /** `Croche.open`'s options: TypeScript's, less what the native SDKs own (storage, transport). */
10
+ export interface ReactNativeOpenOptions extends Omit<OpenOptions,
11
+ 'storage'|'secretStorage'|'serverKey'|'fetch'|'clock'|'imageCodec'|'archive'|'handlers'|'onUsage'|'onDebugEvent'|'debugVisibility'> {
12
+ handlers?: Record<string, ToolHandler>;
13
+ onUsage?: (event: ProjectUsageEvent) => void;
14
+ /**
15
+ * Every agent's debug entries from its open, as on TypeScript, in development and release
16
+ * builds, at the `runtime` projection: the app's own inputs, tools, results and trace events,
17
+ * nothing from the model layer. Public builds have no `full` projection (founder, 10-12).
18
+ */
19
+ onDebugEvent?: (event: RuntimeDebugEvent) => void;
20
+ /** The only projection a public build offers. */
21
+ debugVisibility?: 'runtime';
22
+ attestation?: 'platform'|'off';
23
+ android?: {cloudProjectNumber?: number};
24
+ backgroundDelivery?: boolean|{iosTaskIdentifier?: string};
25
+ }
26
+ /** The stream `state`'s `activity` (sdk-internal #21): what a running agent waits on. An open
27
+ * string: a value this SDK does not know yet may arrive, and a stream must not fail on it. */
28
+ export type AgentActivity = 'model' | 'summary' | 'tool' | (string & {});
29
+ /** The stream's `state` event, and a snapshot's `state`. `activity` is set exactly while `status`
30
+ * is `running`; `tools` comes only with `tool`: the round's command keys in call order, never
31
+ * arguments. */
32
+ export interface AgentStateEvent {
33
+ type: 'state'; status: 'idle' | 'running' | 'waiting'; queued: number; typing: boolean;
34
+ activity: AgentActivity | null; tools?: string[];
35
+ }
package/src/project.ts ADDED
@@ -0,0 +1,426 @@
1
+ // The project API on React Native (Keel #339 6093822222): `Croche.open` → `croche.agent(id?)` →
2
+ // `CrocheAgent`, with the same members, shapes and error codes as the TypeScript SDK's
3
+ // project-core.ts. The native module binds the FFI's CoreProject (NativeCrocheRuntime.ts); this
4
+ // file runs the TypeScript SDK's StreamHub over it, so subscriptions, requests and cancels
5
+ // behave exactly as in TypeScript. Where React Native must differ (a native module, async
6
+ // calls), the difference stays in this file.
7
+ import { NativeEventEmitter, NativeModules } from 'react-native';
8
+ import { CrocheError, StreamHub, type CapturedRequestState, type CoreStreamPort, type RequestObservation,
9
+ type RetainedRequestEnds, type StreamSelectOptions } from '@h1r-ai/croche/stream';
10
+ import Native from './NativeCrocheRuntime';
11
+ import type { ReactNativeMemory } from './index';
12
+ import { EVENT_NAME, type NativeMessage, type ToolRequest } from './protocol';
13
+ import type { AgentOptions, AgentOverride, ProjectToolContext, ProjectUsageEvent, ToolHandler } from './project-types';
14
+ import type { ReactNativeOpenOptions } from './project-types';
15
+ import type { RuntimeDebugEvent } from '@h1r-ai/croche';
16
+ import type { CommandInvocation, JsonValue, ResponseFormat, SendInput, RuntimeMemory, MemoryChangedEvent, MemoryItem, MemoryExport, DeferredWrite } from './types';
17
+
18
+ /** Events are owned and projected by Core; unknown event fields remain intact. */
19
+ export type AgentEvent = { type: string; [key: string]: JsonValue | undefined };
20
+
21
+ // One emitter listener for every project and agent handle; the legacy CrocheRuntime keeps its own.
22
+ type Route = (message: NativeMessage) => void;
23
+ const routes = new Map<string, Route>();
24
+ let listening: { remove(): void } | null = null;
25
+ function route(handle: string, to: Route) {
26
+ routes.set(handle, to);
27
+ listening ??= new NativeEventEmitter(NativeModules.CrocheRuntime ?? Native)
28
+ .addListener(EVENT_NAME, payload => { const message = payload as NativeMessage; routes.get(message.handle)?.(message); });
29
+ }
30
+ function unroute(handle: string) {
31
+ routes.delete(handle);
32
+ if (routes.size === 0 && listening) { listening.remove(); listening = null; }
33
+ }
34
+ let serial = 0;
35
+ const next = (prefix: string) => `${prefix}:${Date.now().toString(36)}:${(serial++).toString(36)}`;
36
+
37
+ function nativeError(error: unknown): CrocheError {
38
+ if (error instanceof CrocheError) return error;
39
+ const e = error as { code?: unknown; message?: unknown };
40
+ const code = typeof e?.code === 'string' && /^[a-z0-9_]{1,80}$/.test(e.code) ? e.code : 'native_error';
41
+ return new CrocheError(code, typeof e?.message === 'string' ? e.message : 'The native Runtime failed.');
42
+ }
43
+ async function native<T>(operation: () => Promise<T>): Promise<T> {
44
+ try { return await operation(); } catch (error) { throw nativeError(error); }
45
+ }
46
+ function sync<T>(operation: () => T): T {
47
+ try { return operation(); } catch (error) { throw nativeError(error); }
48
+ }
49
+ /** A sync getter's JSON. A bridge that cannot throw a coded error synchronously (Android: a
50
+ * TurboModule sync throw loses its code) returns `{"error":{"code","message"}}` instead. */
51
+ function getter<T>(operation: () => string): T {
52
+ const value = JSON.parse(sync(operation)) as T & { error?: unknown };
53
+ if (value && typeof value === 'object' && 'error' in value && value.error) throw nativeError(value.error);
54
+ return value;
55
+ }
56
+ function json(value: unknown): string {
57
+ try {
58
+ return JSON.stringify(value, (_key, item) => {
59
+ if (typeof item === 'number' && !Number.isFinite(item)) throw new Error('Non-finite number');
60
+ if (['function', 'symbol', 'bigint'].includes(typeof item)) throw new Error('Non-JSON value');
61
+ return item;
62
+ });
63
+ } catch { throw new CrocheError('invalid_configuration', 'Configuration must be JSON serializable.'); }
64
+ }
65
+ /** A projection id or sequence as the native module takes it: an integer JS can hold exactly. */
66
+ function position(value: number): number {
67
+ if (!Number.isSafeInteger(value) || value < 0) throw new CrocheError('invalid_input', 'Positions are non-negative integers.');
68
+ return value;
69
+ }
70
+
71
+ // TypeScript's projectWire, plus React Native's own host choices; no storage or transport.
72
+ const hostFields = ['cloudUrl', 'projectKey', 'debugKey', 'debugVisibility', 'requestTimeoutMs',
73
+ 'maxPendingEvents', 'syncIntervalMs', 'maintenanceBackoffMs', 'retentionBytes'] as const;
74
+ const runtimeFields = ['streaming', 'backgroundSync', 'maintenanceIntervalMs'] as const;
75
+ type Options = ReactNativeOpenOptions;
76
+ function pick(options: Options, keys: readonly string[]) {
77
+ const source = options as unknown as Record<string, unknown>;
78
+ return Object.fromEntries(keys.filter(key => source[key] !== undefined).map(key => [key, source[key]]));
79
+ }
80
+ function wire(options: Options) {
81
+ return {
82
+ host: pick(options, hostFields),
83
+ ...(options.user === undefined ? {} : { user: options.user }),
84
+ config: options.config,
85
+ handlers: Object.keys(options.handlers ?? {}),
86
+ ...(options.language === undefined ? {} : { language: options.language }),
87
+ runtime: pick(options, runtimeFields),
88
+ ...pick(options, ['timeZone', 'attestation', 'android', 'backgroundDelivery']),
89
+ };
90
+ }
91
+
92
+ /** The stream port over one native agent handle. Everything arrives in Core order on `messages`. */
93
+ class NativePort implements CoreStreamPort<AgentEvent> {
94
+ private onEvent?: (event: RequestObservation) => void;
95
+ private onEnd?: (cause?: unknown) => void;
96
+ private readonly projections = new Map<number, (event: AgentEvent) => void>();
97
+ private readonly unclaimed = new Map<number, AgentEvent[]>(); // projection events before select resolved
98
+ private readonly captures = new Map<string, CapturedRequestState>();
99
+ private readonly captureWaits = new Map<string, (state: CapturedRequestState) => void>();
100
+ constructor(private readonly handle: string, private readonly sendInput: (input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat }) => Promise<import('@h1r-ai/croche/stream').StreamReceipt>) {}
101
+
102
+ message(message: NativeMessage) {
103
+ if (message.type === 'observe' || message.type === 'observeEnd') {
104
+ // The hub attaches before Native.observe is called, so nothing arrives before it.
105
+ if (message.type === 'observe') this.onEvent?.(JSON.parse(message.json) as RequestObservation);
106
+ else { const error = JSON.parse(message.json); this.onEnd?.(error === null ? undefined : nativeError(error)); }
107
+ } else if (message.type === 'projection') {
108
+ const { projection, event } = JSON.parse(message.json) as { projection: number; event: AgentEvent };
109
+ const deliver = this.projections.get(projection);
110
+ if (deliver) deliver(event);
111
+ else this.unclaimed.set(projection, [...(this.unclaimed.get(projection) ?? []), event]);
112
+ } else if (message.type === 'captured') {
113
+ const { readId, state } = JSON.parse(message.json) as { readId: string; state: CapturedRequestState };
114
+ const wait = this.captureWaits.get(readId);
115
+ if (wait) { this.captureWaits.delete(readId); wait(state); } else this.captures.set(readId, state);
116
+ }
117
+ }
118
+
119
+ observe(onEvent: (event: RequestObservation) => void, onEnd: (cause?: unknown) => void) {
120
+ this.onEvent = onEvent; this.onEnd = onEnd;
121
+ return { close: () => Native.unobserve(this.handle) };
122
+ }
123
+
124
+ select(options: StreamSelectOptions, onEvent: (event: AgentEvent) => void) {
125
+ let id: number | undefined, closed = false;
126
+ const opened = native(() => Native.select(this.handle, json(options))).then(projection => {
127
+ id = position(projection);
128
+ if (closed) { Native.closeProjection(this.handle, id); this.unclaimed.delete(id); return id; }
129
+ this.projections.set(id, onEvent);
130
+ for (const event of this.unclaimed.get(id) ?? []) onEvent(event);
131
+ this.unclaimed.delete(id);
132
+ return id;
133
+ }, (error: CrocheError) => {
134
+ // As a live end with no seq: the hub ends this subscription with the Core's code.
135
+ onEvent({ type: 'error', code: error.code, message: error.message });
136
+ throw error;
137
+ });
138
+ return {
139
+ close: () => {
140
+ if (closed) return;
141
+ closed = true;
142
+ if (id !== undefined) { this.projections.delete(id); Native.closeProjection(this.handle, id); }
143
+ },
144
+ history: async (page: { before?: number; limit: number }) => {
145
+ const projection = await opened;
146
+ await native(() => Native.history(this.handle, projection, page.before === undefined ? -1 : position(page.before), page.limit));
147
+ },
148
+ };
149
+ }
150
+
151
+ send(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat }) {
152
+ return this.sendInput(input, options);
153
+ }
154
+
155
+ cancel(id?: string): Promise<void> {
156
+ return native(() => id === undefined ? Native.cancelTurn(this.handle) : Native.cancelInput(this.handle, id));
157
+ }
158
+
159
+ async readOutcome(id: string, fromSeq: number, captured: (state: CapturedRequestState) => void): Promise<RetainedRequestEnds> {
160
+ const readId = next('read');
161
+ const capture = new Promise<CapturedRequestState>(resolve => {
162
+ const early = this.captures.get(readId);
163
+ if (early) { this.captures.delete(readId); resolve(early); } else this.captureWaits.set(readId, resolve);
164
+ });
165
+ try {
166
+ const result = JSON.parse(await native(() => Native.readOutcome(this.handle, id, position(fromSeq), readId))) as RetainedRequestEnds;
167
+ captured(await capture); // emitted before the promise resolved
168
+ return result;
169
+ } finally { this.captureWaits.delete(readId); this.captures.delete(readId); }
170
+ }
171
+ }
172
+
173
+ interface AgentInfo { id: string; name: string | null; mode: string | null; visibleTools: string[] | null; logId: string; instance?: string | null; created?: boolean }
174
+
175
+ export class CrocheAgent {
176
+ private memorySnapshot: RuntimeMemory = { enabled: true, text: '', updatedAt: null, compactedTurns: 0, items: [] };
177
+ private memoryListener?: (event: MemoryChangedEvent) => void;
178
+ /** Native memory operations use this agent's handle; the callable returns its last snapshot. */
179
+ readonly memory: ReactNativeMemory = Object.assign(() => this.memorySnapshot, {
180
+ list: () => this.memoryOp<MemoryItem[]>('list', {}, true),
181
+ delete: (id: string) => this.memoryOp<{ deleted: boolean } | DeferredWrite>('delete', { id }, true),
182
+ clear: () => this.memoryOp<{ cleared: number } | DeferredWrite>('clear', {}, true),
183
+ enabled: (on: boolean) => this.memoryOp<DeferredWrite | null>('enabled', { on }, true)
184
+ .then(out => out?.deferred === true ? out : undefined),
185
+ export: () => this.memoryOp<MemoryExport>('export', {}, true),
186
+ onChanged: async (listener: ((event: MemoryChangedEvent) => void) | undefined) => {
187
+ if (this.closed) throw new CrocheError('closed', 'The agent is closed.');
188
+ const was = this.memoryListener;
189
+ this.memoryListener = typeof listener === 'function' ? listener : undefined;
190
+ if (!was !== !this.memoryListener) await this.memoryOp<null>('observe', { on: !!this.memoryListener }, false);
191
+ },
192
+ });
193
+ private async refreshMemory(): Promise<void> {
194
+ const inspection = JSON.parse(await native(() => Native.inspect(this.handle))) as { memory: RuntimeMemory };
195
+ this.memorySnapshot = inspection.memory;
196
+ }
197
+ private async memoryOp<T>(op: string, args: object, refresh: boolean): Promise<T> {
198
+ if (this.closed) throw new CrocheError('closed', 'The agent is closed.');
199
+ const out = JSON.parse(await native(() => Native.memory(this.handle, op, json(args)))) as T;
200
+ if (refresh && !(out && typeof out === 'object' && 'deferred' in out && out.deferred === true)) {
201
+ await this.refreshMemory().catch(() => {});
202
+ }
203
+ return out;
204
+ }
205
+ private closing?: Promise<void>;
206
+ private ended = false;
207
+ private hub!: StreamHub<AgentEvent>;
208
+ private handle!: string;
209
+ private project!: Croche;
210
+ private info!: AgentInfo;
211
+ private readonly running = new Map<string, AbortController>();
212
+ private constructor() {}
213
+ /** Observation starts before the hub exists: a refusal (for example a second observer) fails the open. */
214
+ // A static method, not a static block: React Native's Babel preset has no class static blocks.
215
+ private static async attach(project: Croche, handle: string, info: AgentInfo): Promise<CrocheAgent> {
216
+ const agent = new CrocheAgent();
217
+ agent.project = project; agent.handle = handle; agent.info = info;
218
+ const port = new NativePort(handle, (input, options) => agent.receipt(input, options));
219
+ route(handle, message => {
220
+ if (message.type === 'tool') void project['runTool'](agent, parseTool(message.json), agent.running);
221
+ else if (message.type === 'toolCancel') agent.running.get((JSON.parse(message.json) as { callId: string }).callId)?.abort();
222
+ else if (message.type === 'memoryChanged') {
223
+ try { agent.memoryListener?.(JSON.parse(message.json)); } catch {}
224
+ }
225
+ else port.message(message);
226
+ });
227
+ agent.hub = new StreamHub(port);
228
+ try { await agent.refreshMemory(); await native(() => Native.observe(handle)); }
229
+ catch (error) { unroute(handle); throw error; }
230
+ return agent;
231
+ }
232
+
233
+ private state() { return getter<{ id: string; name: string | null; mode: string | null; visibleTools: string[] | null; closed: boolean }>(() => Native.agentState(this.handle)); }
234
+ get id(): string { return this.info.id; }
235
+ get instance(): string | null { return this.info.instance ?? null; }
236
+ get created(): boolean { return this.info.created ?? false; }
237
+ get name(): string | null { return this.state().name; }
238
+ get mode(): string | null { return this.state().mode; }
239
+ get visibleTools(): string[] | null { return this.state().visibleTools; }
240
+ get closed(): boolean { return this.ended || this.state().closed; }
241
+ get logId(): string { return this.info.logId; }
242
+ setTools(visible: string[] | null): Promise<void> {
243
+ return native(() => Native.agentControl(this.handle, 'setTools', json({ visible }))).then(() => undefined);
244
+ }
245
+ setMode(mode: string | null): Promise<void> {
246
+ return native(() => Native.agentControl(this.handle, 'setMode', json({ mode }))).then(() => undefined);
247
+ }
248
+ sync(): Promise<void> { return native(() => Native.agentControl(this.handle, 'sync', '{}')).then(() => undefined); }
249
+
250
+ private receipt(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat }) {
251
+ const callId = next('send');
252
+ if (options.signal?.aborted) return Promise.reject(new CrocheError('aborted', 'The send was aborted before it was accepted.'));
253
+ const abort = () => Native.cancelSend(this.handle, callId);
254
+ options.signal?.addEventListener('abort', abort, { once: true });
255
+ return native(() => Native.sendReceipt(this.handle, json(input), json(options.responseFormat ?? null), callId))
256
+ .then(receipt => JSON.parse(receipt))
257
+ .finally(() => options.signal?.removeEventListener('abort', abort));
258
+ }
259
+ send(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat } = {}) {
260
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
261
+ if (Object.hasOwn(options, 'onEvent')) return Promise.reject(new CrocheError('invalid_input', 'Use agent.subscribe for events; send has no onEvent option.'));
262
+ try { return this.hub.send(input, options); } catch (error) { return Promise.reject(error); }
263
+ }
264
+ subscribe(options: StreamSelectOptions & { onEvent: (event: AgentEvent) => void | Promise<void> }) {
265
+ return this.hub.subscribe(options);
266
+ }
267
+ history(options: { before?: number; limit: number }) { return this.hub.history(options); }
268
+ /** Sends and waits until the input is final (with `wait: 'idle'`, until the agent is idle too). */
269
+ request(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat; wait?: 'idle' } = {}) {
270
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
271
+ return this.hub.request(input, options).then(async result => {
272
+ await this.refreshMemory().catch(() => {});
273
+ return result;
274
+ });
275
+ }
276
+ /** Deletes the conversation; the app empties its list on the durable `cleared` event. */
277
+ clearHistory(): Promise<void> {
278
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
279
+ return native(() => Native.clearHistory(this.handle)).then(async () => { await this.refreshMemory().catch(() => {}); });
280
+ }
281
+ /** Cancels input `id`, or with no id stops the turn running now. */
282
+ cancel(id?: string): Promise<void> {
283
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
284
+ return this.hub.cancel(id);
285
+ }
286
+ /** Closes the agent; the Core projection fence does not await bridged or buffered UI events.
287
+ * An app callback that waits for work on the closer's thread deadlocks under any
288
+ * wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
289
+ close(): Promise<void> {
290
+ return this.closing ??= (async () => {
291
+ this.ended = true;
292
+ try { await native(() => Native.close(this.handle)); }
293
+ finally { this.hub.close(); unroute(this.handle); this.project['forget'](this); }
294
+ })();
295
+ }
296
+ }
297
+
298
+ function parseTool(body: string): ToolRequest { return JSON.parse(body) as ToolRequest; }
299
+ function isToolResult(value: unknown): value is { value?: JsonValue; images?: unknown; imageResolution?: string } {
300
+ return typeof value === 'object' && value !== null && (value as { [key: symbol]: unknown })[Symbol.for('croche.toolResult')] === true;
301
+ }
302
+
303
+ /** The project: Core owns the census, config selection and overrides, the record, ids and locks. */
304
+ export class Croche {
305
+ private readonly agents = new Map<string, CrocheAgent>();
306
+ private closing?: Promise<void>;
307
+ private readonly name = next('project');
308
+ private constructor(private readonly handlers: Record<string, ToolHandler>,
309
+ private readonly usage?: (event: ProjectUsageEvent) => void,
310
+ private readonly debug?: (event: RuntimeDebugEvent) => void) {}
311
+
312
+ static async open(options: ReactNativeOpenOptions): Promise<Croche> {
313
+ if (Object.hasOwn(options, 'debugToken')) throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
314
+ if (['storageKey', 'identity', 'storage', 'serverKey'].some(key => Object.hasOwn(options, key))) {
315
+ throw new CrocheError('invalid_configuration', 'storage, serverKey, storageKey and identity are not options on React Native.');
316
+ }
317
+ const handlers = { ...options.handlers };
318
+ if (Object.values(handlers).some(handler => typeof handler !== 'function')) {
319
+ throw new CrocheError('invalid_configuration', 'Every handler must be a function.');
320
+ }
321
+ const debug = typeof options.onDebugEvent === 'function' ? options.onDebugEvent : undefined;
322
+ const project = new Croche(handlers, options.onUsage, debug);
323
+ const body = json({ ...wire(options), ...(debug ? { debug: true } : {}) }); // frozen before any await
324
+ route(project.name, message => {
325
+ // An observer can never break the project it observes.
326
+ if (message.type === 'usage' && project.usage) {
327
+ try { project.usage({ ...JSON.parse(message.json), user: project.user, crocheUserId: project.crocheUserId }); } catch {}
328
+ } else if (message.type === 'debug' && project.debug) {
329
+ try { project.debug(JSON.parse(message.json)); } catch {}
330
+ }
331
+ });
332
+ try { await native(() => Native.projectOpen(project.name, body)); }
333
+ catch (error) { unroute(project.name); throw error; }
334
+ return project;
335
+ }
336
+
337
+ /**
338
+ * Deletes stores on this device (R8), as TypeScript: with `agent`, that agent's store for `user`,
339
+ * declared or not; without, every agent the bundled config declares, all locked first. Rejects
340
+ * `store_busy` when one is open, and then nothing is deleted. The project record is kept.
341
+ */
342
+ static async deleteStore(options: ReactNativeOpenOptions & { agent?: string }): Promise<void> {
343
+ if (Object.hasOwn(options, 'debugToken')) throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
344
+ if (['storageKey', 'identity', 'storage', 'serverKey'].some(key => Object.hasOwn(options, key))) {
345
+ throw new CrocheError('invalid_configuration', 'storage, serverKey, storageKey and identity are not options on React Native.');
346
+ }
347
+ const body = json({
348
+ host: pick(options, hostFields),
349
+ ...(options.user === undefined ? {} : { user: options.user }),
350
+ config: options.config,
351
+ ...(options.agent === undefined ? {} : { agent: options.agent }),
352
+ });
353
+ await native(() => Native.projectDeleteStore(body));
354
+ }
355
+
356
+ private info() { return getter<{ user: string | null; installationId: string | null; crocheUserId: string | null; agentIds: string[] }>(() => Native.projectInfo(this.name)); }
357
+ get user(): string | null { return this.info().user ?? null; }
358
+ get installationId(): string | null { return this.info().installationId ?? null; }
359
+ get crocheUserId(): string | null { return this.info().crocheUserId ?? null; }
360
+ get agentIds(): readonly string[] { return this.info().agentIds; }
361
+
362
+ async agent(id?: string, options: AgentOptions = {}): Promise<CrocheAgent> {
363
+ if (this.closing) throw new CrocheError('closed', 'The project is closed.');
364
+ const name = id ?? 'default';
365
+ // As TypeScript (project-core.ts): one JS object per open agent, the main one by its id and
366
+ // an instance by [id, instance]. A fresh open is always a new store, so a new handle.
367
+ const slotOf = (instance: string | null | undefined) => instance == null ? name : JSON.stringify([name, instance]);
368
+ const existing = options.fresh ? undefined : this.agents.get(slotOf(options.instance));
369
+ const handle = existing && !existing.closed ? (existing as unknown as { handle: string }).handle : next(`agent:${name}`);
370
+ // Always call Core, including cached agents: it validates override equality and closed state.
371
+ const info = JSON.parse(await native(() => Native.projectAgent(this.name, handle, id ?? '', json(options)))) as AgentInfo;
372
+ if (existing && !existing.closed) return existing;
373
+ const agent = await CrocheAgent['attach'](this, handle, info);
374
+ this.agents.set(slotOf(info.instance), agent);
375
+ return agent;
376
+ }
377
+
378
+ close(): Promise<void> {
379
+ return this.closing ??= (async () => {
380
+ try { await native(() => Native.projectClose(this.name)); }
381
+ finally {
382
+ await Promise.all([...this.agents.values()].map(agent => agent.close().catch(() => {})));
383
+ unroute(this.name);
384
+ }
385
+ })();
386
+ }
387
+
388
+ // Private, as in TypeScript (project-core.ts): RN ships its source as its types, so a public
389
+ // member here is public API. The agent reaches these through bracket access.
390
+ private forget(agent: CrocheAgent) { for (const [name, open] of this.agents) if (open === agent) this.agents.delete(name); }
391
+
392
+ /** One tool call from the Core, run by the app's handler for that tool. */
393
+ private async runTool(agent: CrocheAgent, request: ToolRequest, running: Map<string, AbortController>) {
394
+ const handler = this.handlers[request.invocation.tool];
395
+ // Nothing ran: the Runtime may tell the model so and go on (the Core's NOT_DISPATCHED).
396
+ if (!handler) { Native.resolveTool(request.callId, false, JSON.stringify({ code: 'tool_not_dispatched' })); return; }
397
+ const controller = new AbortController();
398
+ running.set(request.callId, controller);
399
+ try {
400
+ const { command, ...rest } = request.invocation;
401
+ const invocation = { ...rest, ...(command ? { command } : {}) } as CommandInvocation;
402
+ const { userId, ...context } = request.context as ToolRequest['context'] & Record<string, unknown>;
403
+ let returned: unknown;
404
+ try {
405
+ returned = await handler(invocation, { ...context, agentId: agent.id, signal: controller.signal,
406
+ user: this.user, crocheUserId: userId || null } as unknown as ProjectToolContext);
407
+ } catch {
408
+ Native.resolveTool(request.callId, false, JSON.stringify({ code: 'effect_failed' }));
409
+ return;
410
+ }
411
+ // The handler ran: what it returned is read once, inside this guard (as CrocheRuntime does).
412
+ let answer: string;
413
+ try {
414
+ if (isToolResult(returned)) {
415
+ const { value, images, imageResolution } = returned;
416
+ answer = JSON.stringify({ value: value ?? null, images: images ?? null, ...(imageResolution === 'high' || imageResolution === 'standard' ? { imageResolution } : {}) });
417
+ } else answer = JSON.stringify({ value: returned ?? null });
418
+ if (typeof answer !== 'string') throw new Error('not JSON');
419
+ } catch {
420
+ Native.resolveTool(request.callId, false, JSON.stringify({ code: 'invalid_tool_result' }));
421
+ return;
422
+ }
423
+ Native.resolveTool(request.callId, true, answer);
424
+ } finally { running.delete(request.callId); }
425
+ }
426
+ }
@@ -0,0 +1,28 @@
1
+ // The one event stream from native to JavaScript. Every message is tagged with the Runtime
2
+ // handle it belongs to, so several agents can stream and call tools at the same time.
3
+ // `json` is a JSON string for the same reason the spec uses strings: exactness.
4
+
5
+ export const EVENT_NAME = 'CrocheRuntimeEvent';
6
+
7
+ export interface NativeMessage {
8
+ handle: string;
9
+ /** "event": a RuntimeEvent. "tool": run a JavaScript tool. "toolCancel": abort one.
10
+ * "usage": a paid call's cost (RuntimeUsageEvent), sent only when the app passed onUsage.
11
+ * "debug": a project's debug entry (RuntimeDebugEvent), sent only when the app passed
12
+ * onDebugEvent to Croche.open.
13
+ * "memoryChanged": a memory.changed event, sent only while JavaScript observes memory.
14
+ * "delivered": a `deliverDue()` result that ran a delivery turn, whoever called it (the native
15
+ * SDK's timer, its foreground hook, an OS background run, or JavaScript).
16
+ * The project API's stream port (NativeCrocheRuntime.ts): "observe", "observeEnd",
17
+ * "projection", "captured". */
18
+ type: 'event' | 'tool' | 'toolCancel' | 'usage' | 'debug' | 'memoryChanged' | 'delivered'
19
+ | 'observe' | 'observeEnd' | 'projection' | 'captured';
20
+ json: string;
21
+ }
22
+
23
+ /** The body of a `tool` message. */
24
+ export interface ToolRequest {
25
+ callId: string;
26
+ invocation: { tool: string; command?: string | null; key: string; args: Record<string, unknown> };
27
+ context: { callId: string; messageId: string; userId: string; agentId: string | null };
28
+ }
package/src/types.ts ADDED
@@ -0,0 +1,9 @@
1
+ // Types only, shared with @h1r-ai/croche so web and mobile apps are written against one
2
+ // contract. Erased at build: this package ships no web Runtime code.
3
+ export type {
4
+ CommandInvocation, JsonValue, RuntimeEvent, RuntimeMemoryOptions, RuntimeStatus, RuntimeToolMetadata,
5
+ SendInput, ToolContext, TurnResult, DisplayMessage, RuntimeMemory, BudgetSnapshot, BudgetAdjustment, RuntimeOptions,
6
+ WikiDocument, UserWikiDocument, UserWikiResult, WikiOptions, WikiDigest, WikiEntry, WikiHit, WikiPage, RuntimeUsageEvent,
7
+ MemoryItem, MemoryExport, MemoryChangedEvent, ResponseFormat, DeferredWrite, DeliverDueResult, ScheduleList,
8
+ ImageResolution, InputImage, CrocheTools,
9
+ } from '@h1r-ai/croche';