@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.
- package/LICENSE +32 -0
- package/README.md +475 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/android/build.gradle +47 -0
- package/android/src/main/AndroidManifest.xml +8 -0
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +28 -0
- package/ios/CrocheRuntimeBridge.swift +986 -0
- package/ios/RNCrocheRuntime.mm +221 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
- package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +40 -4
- package/scripts/vendor-native.sh +56 -0
- package/src/NativeCrocheRuntime.ts +162 -0
- package/src/index.ts +660 -0
- package/src/project-types.ts +35 -0
- package/src/project.ts +426 -0
- package/src/protocol.ts +28 -0
- package/src/types.ts +9 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
// @h1r-ai/croche-react-native: the Croche Runtime in a React Native app, with no backend of the
|
|
2
|
+
// app's own. Decisions happen in the shared Rust Core, driven by the platform SDKs on iOS
|
|
3
|
+
// and Android; this layer only carries calls, events and tool round-trips across the bridge.
|
|
4
|
+
// It has the same shape as @h1r-ai/croche, so an app reads the same on web and mobile.
|
|
5
|
+
import { AppState, NativeEventEmitter, NativeModules } from 'react-native';
|
|
6
|
+
import Native from './NativeCrocheRuntime';
|
|
7
|
+
import { EVENT_NAME, type NativeMessage, type ToolRequest } from './protocol';
|
|
8
|
+
import { CrocheError } from '@h1r-ai/croche/stream';
|
|
9
|
+
export { Croche, CrocheAgent, type AgentEvent } from './project';
|
|
10
|
+
export type { AgentConfig, AgentOptions, AgentOverride, AgentToolControls, ProjectConfig, ProjectToolContext, ProjectUsageEvent, ReactNativeOpenOptions, ReleasedConfig, ToolDeclaration, ToolHandler, AgentActivity, AgentStateEvent } from './project-types';
|
|
11
|
+
import type {
|
|
12
|
+
CommandInvocation, JsonValue, RuntimeEvent, RuntimeMemoryOptions, RuntimeStatus, RuntimeToolMetadata,
|
|
13
|
+
SendInput, ToolContext, TurnResult, DisplayMessage, RuntimeMemory, BudgetSnapshot, BudgetAdjustment, RuntimeOptions,
|
|
14
|
+
WikiDocument, UserWikiDocument, UserWikiResult, WikiOptions, WikiDigest, WikiEntry, WikiHit, WikiPage, RuntimeUsageEvent,
|
|
15
|
+
MemoryItem, MemoryExport, MemoryChangedEvent, ResponseFormat, DeferredWrite, DeliverDueResult, ScheduleList,
|
|
16
|
+
ImageResolution, InputImage, CrocheTools,
|
|
17
|
+
} from './types';
|
|
18
|
+
|
|
19
|
+
export type { BudgetAdjustment, BudgetSnapshot, CommandInvocation, DeferredWrite, DeliverDueResult, ScheduleList, DisplayMessage, JsonValue, MemoryChangedEvent, MemoryExport, MemoryItem, ResponseFormat, RuntimeEvent, RuntimeMemory, RuntimeUsageEvent, SendInput, ToolContext, TurnResult } from './types';
|
|
20
|
+
export type { WikiDocument, UserWikiDocument, UserWikiResult, WikiOptions, WikiDigest, WikiEntry, WikiHit, WikiPage } from './types';
|
|
21
|
+
export type { ImageResolution, InputImage, CrocheTools } from './types';
|
|
22
|
+
|
|
23
|
+
// The same brand as @h1r-ai/croche's, so a result made with either package's toolResult is one.
|
|
24
|
+
const TOOL_RESULT = Symbol.for('croche.toolResult');
|
|
25
|
+
/** What a tool returns with images: its value, and the images beside it (never inside it). */
|
|
26
|
+
export interface ToolResult {
|
|
27
|
+
readonly [TOOL_RESULT]: true;
|
|
28
|
+
value: JsonValue;
|
|
29
|
+
images: InputImage[];
|
|
30
|
+
/** For every image of this result that does not name its own `resolution`. */
|
|
31
|
+
imageResolution?: ImageResolution;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A tool's result with images (H3), as on the web: `return toolResult({ placed: true }, { images: [{ data, mime, alt }] })`.
|
|
35
|
+
* The images cross the bridge beside the value and the native SDK prepares them (standard ones
|
|
36
|
+
* re-encoded at most 512 px). The same kinds and limits as a message's (at most 4, 3 MB each,
|
|
37
|
+
* 6 MB together); a violation fails that call alone with `invalid_tool_result`, and the turn goes
|
|
38
|
+
* on. A plain value is never looked inside.
|
|
39
|
+
*/
|
|
40
|
+
export function toolResult(value: JsonValue | undefined, options: { images?: InputImage[]; imageResolution?: ImageResolution } = {}): ToolResult {
|
|
41
|
+
const result = { value: value === undefined ? null : value, images: options.images ?? [] } as ToolResult;
|
|
42
|
+
Object.defineProperty(result, TOOL_RESULT, { value: true });
|
|
43
|
+
if (options.imageResolution) result.imageResolution = options.imageResolution;
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
function isToolResult(value: unknown): value is ToolResult {
|
|
47
|
+
return typeof value === 'object' && value !== null && (value as { [TOOL_RESULT]?: true })[TOOL_RESULT] === true;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* `runtime.wiki`: the same operations as the web Runtime's, asynchronous because every call
|
|
52
|
+
* crosses the bridge (as the Swift and Kotlin SDKs' are).
|
|
53
|
+
*/
|
|
54
|
+
export interface ReactNativeWiki {
|
|
55
|
+
/** Replace every app document, atomically; answers what is installed. */
|
|
56
|
+
set(docs: WikiDocument[]): Promise<WikiDigest>;
|
|
57
|
+
/** This user's own documents (under `user/`): stored, durable when the promise resolves. */
|
|
58
|
+
put(docs: UserWikiDocument | UserWikiDocument[]): Promise<UserWikiResult | DeferredWrite>;
|
|
59
|
+
/** Add app documents or replace those with the same path, atomically. */
|
|
60
|
+
put(docs: WikiDocument | WikiDocument[]): Promise<void>;
|
|
61
|
+
/** Remove one of this user's own documents, or (without options) one app document. */
|
|
62
|
+
remove(path: string, options?: { scope: 'user' }): Promise<boolean | DeferredWrite>;
|
|
63
|
+
/** Remove every one of this user's own documents; how many. `clearHistory` keeps them. */
|
|
64
|
+
clear(options: { scope: 'user' }): Promise<number | DeferredWrite>;
|
|
65
|
+
list(folder?: string): Promise<WikiEntry[]>;
|
|
66
|
+
read(path: string, part?: number): Promise<WikiPage | null>;
|
|
67
|
+
search(query: string, limit?: number): Promise<WikiHit[]>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `runtime.memory`: the same API as the web Runtime's, asynchronous because every call crosses
|
|
72
|
+
* the bridge (as the Swift and Kotlin SDKs' are). Calling it returns the snapshot as of the last
|
|
73
|
+
* completed call; each write refreshes that snapshot.
|
|
74
|
+
*/
|
|
75
|
+
export interface ReactNativeMemory {
|
|
76
|
+
(): RuntimeMemory;
|
|
77
|
+
list(): Promise<MemoryItem[]>;
|
|
78
|
+
/** Remove one AI-written memory and its earlier versions; conversation context stays. */
|
|
79
|
+
delete(id: string): Promise<{ deleted: boolean } | DeferredWrite>;
|
|
80
|
+
/** Remove every memory, not the conversation summary, kept turns or archive. */
|
|
81
|
+
clear(): Promise<{ cleared: number } | DeferredWrite>;
|
|
82
|
+
/** Turn memory on or off for this person; the choice outlives `clearHistory()`. */
|
|
83
|
+
enabled(on: boolean): Promise<void | DeferredWrite>;
|
|
84
|
+
/** Everything memory holds, history included (for a person's data request). */
|
|
85
|
+
export(): Promise<MemoryExport>;
|
|
86
|
+
/** Replaces the observer of every `memory.changed` (the app's, the model's, upkeep's). */
|
|
87
|
+
onChanged(listener: ((event: MemoryChangedEvent) => void) | undefined): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The wiki documents shipped with the app: a folder reference named `folder` in the iOS
|
|
92
|
+
* bundle, or `android/app/src/main/assets/<folder>/`. Only `.md` files, in path order.
|
|
93
|
+
*/
|
|
94
|
+
export async function wikiFromAppAssets(folder = 'wiki'): Promise<WikiDocument[]> {
|
|
95
|
+
try { return parse<WikiDocument[]>(await Native.wiki('', 'bundled', JSON.stringify({ folder }))); }
|
|
96
|
+
catch (error) { throw nativeError(error); }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface ReactNativeTool extends RuntimeToolMetadata {
|
|
100
|
+
/** Return structured rejection JSON for an action the model can correct.
|
|
101
|
+
* A throw after dispatch ends the turn because its effects may be unknown. */
|
|
102
|
+
execute(invocation: CommandInvocation, context: ToolContext): JsonValue | ToolResult | Promise<JsonValue | ToolResult>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ReactNativeRuntimeOptions {
|
|
106
|
+
/** @internal */
|
|
107
|
+
cloudUrl?: string;
|
|
108
|
+
/** The public project key. Safe to ship in the app; attestation proves the app is genuine. */
|
|
109
|
+
projectKey: string;
|
|
110
|
+
/** Exact app user identity; 1–200 UTF-16 units, no padding or control characters. */
|
|
111
|
+
user?: string;
|
|
112
|
+
/** Several characters or roles per user: each gets its own store, session, history and memory. */
|
|
113
|
+
agentId?: string;
|
|
114
|
+
instructions: string;
|
|
115
|
+
markerGuide?: string;
|
|
116
|
+
toolGuide?: string;
|
|
117
|
+
crocheTools?: CrocheTools;
|
|
118
|
+
tools?: ReactNativeTool[];
|
|
119
|
+
memory?: RuntimeMemoryOptions;
|
|
120
|
+
/**
|
|
121
|
+
* Documents the character can look up: `docs`, or `{docs, include, exclude}` where the
|
|
122
|
+
* globs choose which app documents this agent sees. Same as the web Runtime.
|
|
123
|
+
*/
|
|
124
|
+
wiki?: WikiDocument[] | WikiOptions;
|
|
125
|
+
/** Streams replies as `text.delta` events. Default true. */
|
|
126
|
+
streaming?: boolean;
|
|
127
|
+
/**
|
|
128
|
+
* Same as the web Runtime: every paid model call, whatever caused it (a message's own calls,
|
|
129
|
+
* compaction, upkeep prepares), once its cost is known. Delivery is at least once: dedupe by
|
|
130
|
+
* `operationId`. Attached at open, so a call the process died during, which open charges and
|
|
131
|
+
* reports, is not missed.
|
|
132
|
+
*/
|
|
133
|
+
onUsage?: (event: RuntimeUsageEvent) => void;
|
|
134
|
+
maxIterations?: number;
|
|
135
|
+
maxOutputTokens?: number;
|
|
136
|
+
maxContextTokens?: number;
|
|
137
|
+
requestTimeoutMs?: number;
|
|
138
|
+
/** Overrides the store name Core derives from Cloud, project, installation, user and agent. */
|
|
139
|
+
storageKey?: string;
|
|
140
|
+
/**
|
|
141
|
+
* "platform" (default): App Attest on iOS, Play Integrity on Android, when the project
|
|
142
|
+
* requires it. "off": never attest; only a project with attestation off accepts that.
|
|
143
|
+
* Simulators and emulators cannot attest.
|
|
144
|
+
*/
|
|
145
|
+
attestation?: 'platform' | 'off';
|
|
146
|
+
/** Android Play Integrity: the Google Cloud project number linked in Play Console. */
|
|
147
|
+
android?: { cloudProjectNumber?: number };
|
|
148
|
+
/**
|
|
149
|
+
* A debug key from Croche Studio ("cdt_…"): it registers this install in place of
|
|
150
|
+
* App Attest / Play Integrity, which simulators and emulators cannot do. Development
|
|
151
|
+
* builds only; a release build that carries one gets a loud warning.
|
|
152
|
+
*/
|
|
153
|
+
debugKey?: string;
|
|
154
|
+
/**
|
|
155
|
+
* Background upkeep after each turn, on a timer, and when the app returns to the foreground
|
|
156
|
+
* (default true). False turns all three off: call maintain() yourself.
|
|
157
|
+
*/
|
|
158
|
+
backgroundSync?: boolean;
|
|
159
|
+
/** How often upkeep checks whether work is due. Default 60000. Foreground returns inside it run upkeep once. */
|
|
160
|
+
maintenanceIntervalMs?: number;
|
|
161
|
+
/**
|
|
162
|
+
* A regular check-in the app turns on: a turn every `everyMs` (15 minutes to 24 hours, both
|
|
163
|
+
* included), delivered like a due note. Same as the web Runtime; outside those bounds open
|
|
164
|
+
* fails `invalid_configuration`. Off by default.
|
|
165
|
+
*/
|
|
166
|
+
heartbeat?: { everyMs: number };
|
|
167
|
+
/**
|
|
168
|
+
* Delivers the agent's scheduled notes while the app is not running, through the OS's own
|
|
169
|
+
* deferred work: BGTaskScheduler on iOS (`iosTaskIdentifier`, default "dev.croche.schedule";
|
|
170
|
+
* the app lists it in Info.plist and registers it at launch, see the README), WorkManager on
|
|
171
|
+
* Android. Inexact: never before a note's time, at the latest at the next foreground. Off by
|
|
172
|
+
* default: notes then come while the app runs and at each foreground.
|
|
173
|
+
*/
|
|
174
|
+
backgroundDelivery?: boolean | { iosTaskIdentifier?: string };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** What one round of background upkeep did. */
|
|
178
|
+
export interface MaintenanceResult { ran: boolean; ok?: boolean; preempted?: boolean; pendingEvents?: number; error?: { code: string; message: string } }
|
|
179
|
+
|
|
180
|
+
declare const __DEV__: boolean | undefined;
|
|
181
|
+
/** The founder's condition for debug keys: never silent in a shipped build. */
|
|
182
|
+
/** The options this SDK declares: a Record over the interface, so adding or removing one without this fails to compile. */
|
|
183
|
+
const DECLARED_OPTIONS: Record<keyof ReactNativeRuntimeOptions, true> = { user: true, agentId: true, android: true, attestation: true, backgroundDelivery: true, backgroundSync: true, cloudUrl: true, debugKey: true, heartbeat: true, instructions: true, maintenanceIntervalMs: true, markerGuide: true, toolGuide: true, crocheTools: true, maxContextTokens: true, maxIterations: true, maxOutputTokens: true, memory: true, onUsage: true, projectKey: true, requestTimeoutMs: true, storageKey: true, streaming: true, tools: true, wiki: true };
|
|
184
|
+
const warnedOptions = new Set<string>();
|
|
185
|
+
function warnUnknownOptions(options: ReactNativeRuntimeOptions) {
|
|
186
|
+
for (const key of Object.keys(options)) {
|
|
187
|
+
if (Object.hasOwn(DECLARED_OPTIONS, key) || warnedOptions.has(key)) continue;
|
|
188
|
+
warnedOptions.add(key);
|
|
189
|
+
// Undeclared keys still reach the Runtime as they are (Atlas, #273); only a function cannot.
|
|
190
|
+
const fate = typeof (options as unknown as Record<string, unknown>)[key] === 'function' ? 'it is dropped (a function cannot reach the Runtime)' : 'it is passed to the Runtime as is';
|
|
191
|
+
console.warn(`[Croche] Option '${key}' is not declared by the React Native SDK; ${fate}. Check its spelling.`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function warnReleaseDebugKey(options: ReactNativeRuntimeOptions) {
|
|
196
|
+
if (options.debugKey && typeof __DEV__ !== 'undefined' && !__DEV__) {
|
|
197
|
+
console.error('[Croche] A debug key (debugKey) is set in a RELEASE build. It admits any install of this project without attestation and must not ship: remove it and rely on App Attest / Play Integrity.');
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export interface RuntimeInspection {
|
|
202
|
+
status: RuntimeStatus;
|
|
203
|
+
history: DisplayMessage[];
|
|
204
|
+
memory: RuntimeMemory;
|
|
205
|
+
budget: BudgetSnapshot;
|
|
206
|
+
tools: RuntimeToolMetadata[];
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// One error class for the legacy Runtime and the project API: the TypeScript SDK's, from its
|
|
210
|
+
// WebAssembly-free entry, so `instanceof CrocheError` holds for errors the shared hub throws.
|
|
211
|
+
export { CrocheError };
|
|
212
|
+
|
|
213
|
+
type Listener = (message: NativeMessage) => void;
|
|
214
|
+
const listeners = new Map<string, Listener>();
|
|
215
|
+
let subscription: { remove(): void } | null = null;
|
|
216
|
+
let serial = 0;
|
|
217
|
+
|
|
218
|
+
function subscribe(handle: string, listener: Listener) {
|
|
219
|
+
listeners.set(handle, listener);
|
|
220
|
+
if (!subscription) {
|
|
221
|
+
const emitter = new NativeEventEmitter(NativeModules.CrocheRuntime ?? Native);
|
|
222
|
+
// RN types the payload as Object; the bridges always emit a NativeMessage.
|
|
223
|
+
subscription = emitter.addListener(EVENT_NAME, payload => {
|
|
224
|
+
const message = payload as NativeMessage;
|
|
225
|
+
listeners.get(message.handle)?.(message);
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function unsubscribe(handle: string) {
|
|
230
|
+
listeners.delete(handle);
|
|
231
|
+
if (listeners.size === 0 && subscription) { subscription.remove(); subscription = null; }
|
|
232
|
+
}
|
|
233
|
+
/** Only data crosses into the Core: tool metadata, never the callbacks. */
|
|
234
|
+
function toolMetadata(tools: ReactNativeTool[]): RuntimeToolMetadata[] {
|
|
235
|
+
if (!Array.isArray(tools)) throw new CrocheError('invalid_tool', 'Tools must be an array.');
|
|
236
|
+
for (const tool of tools) {
|
|
237
|
+
if (typeof tool?.execute !== 'function') throw new CrocheError('invalid_tool', `Tool ${tool?.name} needs an execute function.`);
|
|
238
|
+
}
|
|
239
|
+
return tools.map(({ execute: _execute, ...metadata }) => metadata);
|
|
240
|
+
}
|
|
241
|
+
function parse<T>(json: string): T { return JSON.parse(json) as T; }
|
|
242
|
+
function nativeError(error: unknown): CrocheError {
|
|
243
|
+
const e = error as { code?: unknown; message?: unknown };
|
|
244
|
+
const code = typeof e?.code === 'string' && /^[a-z0-9_]{1,80}$/.test(e.code) ? e.code : 'native_error';
|
|
245
|
+
return new CrocheError(code, typeof e?.message === 'string' ? e.message : 'The native Runtime failed.');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export class CrocheRuntime {
|
|
249
|
+
private readonly executors: Map<string, ReactNativeTool['execute']>; // accepted tools are never removed: see setTools
|
|
250
|
+
// setTools bookkeeping: the names in the list the Core offers. Changes run one at a time
|
|
251
|
+
// (`toolChange`), so this is exact whenever a change starts; `toolsIssued` settles once every
|
|
252
|
+
// change called so far has reached native, which a later send waits for.
|
|
253
|
+
private offered: Set<string>;
|
|
254
|
+
private toolChange: Promise<void> = Promise.resolve();
|
|
255
|
+
private toolsIssued: Promise<void> = Promise.resolve();
|
|
256
|
+
private toolsPending = 0;
|
|
257
|
+
private readonly running = new Map<string, AbortController>();
|
|
258
|
+
/** Each send in flight's listener, by input id: a send made while a turn runs is held, never refused. */
|
|
259
|
+
/** Each send call's listener, by input id: a retry's registration is its own (Atlas, #278). */
|
|
260
|
+
private sendListeners = new Map<string, Array<{ listener: (event: RuntimeEvent) => void }>>();
|
|
261
|
+
private calls = 0;
|
|
262
|
+
/** The listeners of each started turn: a turn carrying several held sends speaks to all of them. */
|
|
263
|
+
private turnListeners = new Map<string, Array<(event: RuntimeEvent) => void>>();
|
|
264
|
+
/** Each running turn's `turn.started`, for the sends that join it later. */
|
|
265
|
+
private turnStarts = new Map<string, Extract<RuntimeEvent, { type: 'turn.started' }>>();
|
|
266
|
+
private currentTurn: string | null = null;
|
|
267
|
+
private closed = false;
|
|
268
|
+
private inspection: RuntimeInspection;
|
|
269
|
+
|
|
270
|
+
private constructor(readonly handle: string, tools: ReactNativeTool[], inspection: RuntimeInspection,
|
|
271
|
+
private readonly usageObserver?: (event: RuntimeUsageEvent) => void) {
|
|
272
|
+
this.executors = new Map(tools.map(tool => [tool.name, tool.execute]));
|
|
273
|
+
this.offered = new Set(tools.map(tool => tool.name));
|
|
274
|
+
this.inspection = inspection;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
static async create(options: ReactNativeRuntimeOptions): Promise<CrocheRuntime> {
|
|
278
|
+
if (options && Object.hasOwn(options, 'debugToken')) throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
|
|
279
|
+
if (!options?.projectKey || typeof options.instructions !== 'string') {
|
|
280
|
+
throw new CrocheError('invalid_configuration', 'projectKey and instructions are required.');
|
|
281
|
+
}
|
|
282
|
+
warnReleaseDebugKey(options);
|
|
283
|
+
warnUnknownOptions(options);
|
|
284
|
+
const { tools = [], storageKey, attestation = 'platform', android, backgroundSync = true, maintenanceIntervalMs, wiki, onUsage, backgroundDelivery, ...core } = options;
|
|
285
|
+
const delivery = backgroundDelivery ? { iosTaskIdentifier: (typeof backgroundDelivery === 'object' && backgroundDelivery.iosTaskIdentifier) || 'dev.croche.schedule' } : undefined;
|
|
286
|
+
const wikiOptions: WikiOptions | undefined = Array.isArray(wiki) ? { docs: wiki } : wiki;
|
|
287
|
+
const { docs: wikiDocs, ...wikiGlobs } = wikiOptions ?? {};
|
|
288
|
+
const config = { ...core, tools: toolMetadata(tools),
|
|
289
|
+
...(Object.keys(wikiGlobs).length ? { wiki: wikiGlobs } : {}) };
|
|
290
|
+
const handle = `rt_${Date.now().toString(36)}_${(++serial).toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
291
|
+
const pending: NativeMessage[] = [];
|
|
292
|
+
// Tool calls can arrive during open (never in practice) and certainly during the first
|
|
293
|
+
// send; buffer until the instance exists so none is lost.
|
|
294
|
+
let runtime: CrocheRuntime | null = null;
|
|
295
|
+
subscribe(handle, message => runtime ? runtime.receive(message) : pending.push(message));
|
|
296
|
+
try {
|
|
297
|
+
const inspection = parse<RuntimeInspection>(await Native.open(handle, JSON.stringify(config),
|
|
298
|
+
JSON.stringify({ storageKey: storageKey ?? '', attestation, android: android ?? {}, backgroundSync, ...(typeof onUsage === 'function' ? { usage: true } : {}), ...(maintenanceIntervalMs === undefined ? {} : { maintenanceIntervalMs }), ...(delivery ? { backgroundDelivery: delivery } : {}) })));
|
|
299
|
+
runtime = new CrocheRuntime(handle, tools, inspection, onUsage);
|
|
300
|
+
for (const message of pending.splice(0)) runtime.receive(message);
|
|
301
|
+
if (backgroundSync !== false) runtime.watchForeground(Math.max(1000, maintenanceIntervalMs ?? 60_000));
|
|
302
|
+
} catch (error) {
|
|
303
|
+
unsubscribe(handle);
|
|
304
|
+
throw nativeError(error);
|
|
305
|
+
}
|
|
306
|
+
// The documents are in before the app's first send, as on the web.
|
|
307
|
+
if (wikiDocs) {
|
|
308
|
+
try { await runtime.wiki.set(wikiDocs); }
|
|
309
|
+
catch (error) { await runtime.close().catch(() => {}); throw error; }
|
|
310
|
+
}
|
|
311
|
+
return runtime;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The status as of the last completed call. */
|
|
315
|
+
status(): RuntimeStatus { return this.inspection.status; }
|
|
316
|
+
/** Display history as of the last completed call (restored on reopen). */
|
|
317
|
+
history(): DisplayMessage[] { return this.inspection.history; }
|
|
318
|
+
private memoryListener: ((event: MemoryChangedEvent) => void) | undefined;
|
|
319
|
+
|
|
320
|
+
/** Long-term memory: call it for the snapshot as of the last completed call; its methods manage it. */
|
|
321
|
+
readonly memory: ReactNativeMemory = Object.assign((): RuntimeMemory => this.inspection.memory, {
|
|
322
|
+
list: () => this.memoryOp<MemoryItem[]>('list', {}, false),
|
|
323
|
+
delete: (id: string) => this.memoryOp<{ deleted: boolean } | DeferredWrite>('delete', { id }, true),
|
|
324
|
+
clear: () => this.memoryOp<{ cleared: number } | DeferredWrite>('clear', {}, true),
|
|
325
|
+
// Applied, it answers nothing; called during another operation, that it was accepted.
|
|
326
|
+
enabled: (on: boolean) => this.memoryOp<DeferredWrite | null>('enabled', { on }, true).then(out => (out?.deferred === true ? out : undefined)),
|
|
327
|
+
export: () => this.memoryOp<MemoryExport>('export', {}, false),
|
|
328
|
+
onChanged: async (listener: ((event: MemoryChangedEvent) => void) | undefined) => {
|
|
329
|
+
// Native forwards changes only while observed; the listener is set first so none is lost.
|
|
330
|
+
const was = this.memoryListener;
|
|
331
|
+
this.memoryListener = typeof listener === 'function' ? listener : undefined;
|
|
332
|
+
if (!was !== !this.memoryListener) await this.memoryOp<null>('observe', { on: !!this.memoryListener }, false);
|
|
333
|
+
},
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
private async memoryOp<T>(op: string, args: object, refresh: boolean): Promise<T> {
|
|
337
|
+
this.checkOpen();
|
|
338
|
+
try {
|
|
339
|
+
const out = parse<T>(await Native.memory(this.handle, op, JSON.stringify(args)));
|
|
340
|
+
if (refresh) await this.inspect().catch(() => {});
|
|
341
|
+
return out;
|
|
342
|
+
} catch (error) { throw nativeError(error); }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* This user's money. `get` is as of the last completed call. `add` and `set` ask Cloud,
|
|
347
|
+
* which applies the project's ceilings and answers with what it applied; pass an `id`
|
|
348
|
+
* (e.g. the purchase id) to make a retry safe.
|
|
349
|
+
*/
|
|
350
|
+
readonly userBudget = {
|
|
351
|
+
get: (): BudgetSnapshot => this.inspection.budget,
|
|
352
|
+
add: (options: { amount: number; id?: string }): Promise<BudgetAdjustment | DeferredWrite> => this.adjust(options.amount, false, options.id),
|
|
353
|
+
set: (options: { amount: number; id?: string }): Promise<BudgetAdjustment | DeferredWrite> => this.adjust(options.amount, true, options.id),
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
private async adjust(amount: number, absolute: boolean, id?: string): Promise<BudgetAdjustment | DeferredWrite> {
|
|
357
|
+
this.checkOpen();
|
|
358
|
+
try {
|
|
359
|
+
const adjustment = parse<BudgetAdjustment | DeferredWrite>(await Native.adjustBudget(this.handle, amount, absolute, id ?? ''));
|
|
360
|
+
await this.inspect().catch(() => {});
|
|
361
|
+
return adjustment;
|
|
362
|
+
} catch (error) { throw nativeError(error); }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
readonly wiki: ReactNativeWiki = {
|
|
366
|
+
set: docs => this.wikiOp('set', { docs }),
|
|
367
|
+
put: ((docs: WikiDocument | WikiDocument[]) => {
|
|
368
|
+
const list = (Array.isArray(docs) ? docs : [docs]) as UserWikiDocument[];
|
|
369
|
+
const user = list.filter(d => d?.scope === 'user').length;
|
|
370
|
+
if (user > 0 && user < list.length) return Promise.reject(new CrocheError('invalid_wiki', "One put holds either the app's documents or the user's own (scope: 'user'), not both."));
|
|
371
|
+
const plain = list.map(({ scope: _scope, ...doc }) => doc);
|
|
372
|
+
return user > 0 ? this.wikiOp<UserWikiResult | DeferredWrite>('putUser', { docs: plain }) : this.wikiOp<null>('put', { docs: plain }).then(() => undefined);
|
|
373
|
+
}) as ReactNativeWiki['put'],
|
|
374
|
+
remove: (path, options) => this.wikiOp(options?.scope === 'user' ? 'removeUser' : 'remove', { path }),
|
|
375
|
+
clear: options => options?.scope === 'user'
|
|
376
|
+
? this.wikiOp('clearUser', {})
|
|
377
|
+
: Promise.reject(new CrocheError('invalid_wiki', "clear removes the user's own documents: clear({scope: 'user'}). To replace the app's, use set.")),
|
|
378
|
+
list: folder => this.wikiOp('list', folder === undefined ? {} : { folder }),
|
|
379
|
+
read: (path, part = 1) => this.wikiOp('read', { path, part }),
|
|
380
|
+
search: (query, limit = 5) => this.wikiOp('search', { query, limit }),
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* A user's own documents for several characters: each agent's Runtime has its own store, so
|
|
385
|
+
* this puts them (as `scope: 'user'`) to every Runtime given, each with its own result. A put
|
|
386
|
+
* replaces by path, so a retry is safe.
|
|
387
|
+
*/
|
|
388
|
+
static shareWiki(runtimes: CrocheRuntime[], docs: WikiDocument | WikiDocument[]): Promise<(UserWikiResult | DeferredWrite)[]> {
|
|
389
|
+
const list: UserWikiDocument[] = (Array.isArray(docs) ? docs : [docs]).map(d => ({ ...d, scope: 'user' }));
|
|
390
|
+
return Promise.all(runtimes.map(runtime => runtime.wiki.put(list)));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private async wikiOp<T>(op: string, args: object): Promise<T> {
|
|
394
|
+
this.checkOpen();
|
|
395
|
+
try { return parse<T>(await Native.wiki(this.handle, op, JSON.stringify(args))); }
|
|
396
|
+
catch (error) { throw nativeError(error); }
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Replaces the tools, as on the web. The Core validates the list at once, all or nothing:
|
|
401
|
+
* a refusal rejects and changes nothing. The swap takes its place in the queue, so turns
|
|
402
|
+
* sent before it still offer the old list; a removed or changed command answers `withdrawn`
|
|
403
|
+
* once it applies. An `execute` given here also serves turns already queued under its name.
|
|
404
|
+
*/
|
|
405
|
+
async setTools(tools: ReactNativeTool[]): Promise<void> {
|
|
406
|
+
this.checkOpen();
|
|
407
|
+
const list = toolMetadata(tools);
|
|
408
|
+
// One change at a time: until the Core's answer to the previous change reaches JavaScript,
|
|
409
|
+
// nothing here can know which list it accepted, so a later change cannot pick executors
|
|
410
|
+
// safely (Atlas, #194: a refused change must never supply the executor for an accepted one).
|
|
411
|
+
let issued!: () => void;
|
|
412
|
+
this.toolsIssued = new Promise<void>(resolve => { issued = resolve; });
|
|
413
|
+
this.toolsPending++;
|
|
414
|
+
const start = () => {
|
|
415
|
+
// Names the Core does not offer are staged before the native call: it cannot call them
|
|
416
|
+
// before it accepts the list, and may call them before its acceptance reaches JavaScript.
|
|
417
|
+
// Names it offers keep their executor until it accepts, so a refusal replaces nothing.
|
|
418
|
+
for (const tool of tools) if (!this.offered.has(tool.name)) this.executors.set(tool.name, tool.execute);
|
|
419
|
+
try { return { admitted: Native.setTools(this.handle, JSON.stringify(list)) as Promise<unknown> }; }
|
|
420
|
+
finally { issued(); }
|
|
421
|
+
};
|
|
422
|
+
// The first change of a quiet runtime reaches native before this call returns (the executor
|
|
423
|
+
// runs synchronously): a send called right after it must not reach the Core first.
|
|
424
|
+
const change = this.toolsPending === 1 ? new Promise<ReturnType<typeof start>>(resolve => resolve(start())) : this.toolChange.then(start);
|
|
425
|
+
this.toolChange = change.then(({ admitted }) => admitted).then(() => {}, () => {});
|
|
426
|
+
try {
|
|
427
|
+
// A refusal leaves staged names unreachable: the Core never offers them, and withdraws a
|
|
428
|
+
// removed name at once, so nothing needs putting back; the next accepted change re-stages.
|
|
429
|
+
try { await (await change).admitted; }
|
|
430
|
+
catch (error) { throw nativeError(error); }
|
|
431
|
+
this.offered = new Set(tools.map(tool => tool.name));
|
|
432
|
+
for (const tool of tools) this.executors.set(tool.name, tool.execute);
|
|
433
|
+
} finally { this.toolsPending--; }
|
|
434
|
+
await this.inspect().catch(() => {});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** The tools the model is offered (metadata), as of the last call. */
|
|
438
|
+
tools(): RuntimeToolMetadata[] { return this.inspection.tools; }
|
|
439
|
+
|
|
440
|
+
/** Starts a new session: forgets history and memory, keeps money and identity. */
|
|
441
|
+
async clearHistory(): Promise<void> {
|
|
442
|
+
this.checkOpen();
|
|
443
|
+
try { await Native.clearHistory(this.handle); await this.inspect().catch(() => {}); }
|
|
444
|
+
catch (error) { throw nativeError(error); }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async inspect(): Promise<RuntimeInspection> {
|
|
448
|
+
this.checkOpen();
|
|
449
|
+
try { this.inspection = parse<RuntimeInspection>(await Native.inspect(this.handle)); return this.inspection; }
|
|
450
|
+
catch (error) { throw nativeError(error); }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** `responseFormat`: structured output, as on the web (`SendOptions.responseFormat`). */
|
|
454
|
+
async send(input: SendInput, options: { onEvent?: (event: RuntimeEvent) => void; signal?: AbortSignal; responseFormat?: ResponseFormat } = {}): Promise<TurnResult> {
|
|
455
|
+
this.checkOpen();
|
|
456
|
+
// Sent while a turn runs, it is held by the Runtime and runs with the others held as the next
|
|
457
|
+
// turn (founder, 2026-10-05): never `busy`, and it never cancels the running turn.
|
|
458
|
+
const cancelled = () => new CrocheError('cancelled', 'The send was cancelled before it started.');
|
|
459
|
+
if (options.signal?.aborted) throw cancelled();
|
|
460
|
+
const call = String(++this.calls);
|
|
461
|
+
// Native hears an abort only once it has the call; before that, the abort is checked here.
|
|
462
|
+
let issued = false;
|
|
463
|
+
const abort = () => { if (issued) Native.cancelSend(this.handle, call); };
|
|
464
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
465
|
+
const registration = options.onEvent ? { listener: options.onEvent } : undefined;
|
|
466
|
+
if (registration) this.sendListeners.set(input.id, [...(this.sendListeners.get(input.id) ?? []), registration]);
|
|
467
|
+
let turnId: string | undefined;
|
|
468
|
+
try {
|
|
469
|
+
// A send called after setTools reaches native after it (the swap's place in the queue).
|
|
470
|
+
if (this.toolsPending) await this.toolsIssued;
|
|
471
|
+
if (options.signal?.aborted) throw cancelled();
|
|
472
|
+
issued = true;
|
|
473
|
+
const result = parse<TurnResult>(await Native.send(this.handle, JSON.stringify(input), JSON.stringify(options.responseFormat ?? null), call));
|
|
474
|
+
turnId = result.turnId;
|
|
475
|
+
await this.inspect().catch(() => {});
|
|
476
|
+
return result;
|
|
477
|
+
} catch (error) {
|
|
478
|
+
throw error instanceof CrocheError ? error : nativeError(error);
|
|
479
|
+
} finally {
|
|
480
|
+
// This call's registration only: another call's, even with the same callback, stays.
|
|
481
|
+
const rest = (this.sendListeners.get(input.id) ?? []).filter(r => r !== registration);
|
|
482
|
+
if (rest.length) this.sendListeners.set(input.id, rest); else this.sendListeners.delete(input.id);
|
|
483
|
+
if (turnId) { this.turnListeners.delete(turnId); this.turnStarts.delete(turnId); }
|
|
484
|
+
options.signal?.removeEventListener('abort', abort);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Stops the running turn only: messages sent while it ran still go, together, as the next turn. */
|
|
489
|
+
cancel(): void { if (!this.closed) Native.cancel(this.handle); }
|
|
490
|
+
|
|
491
|
+
/** Drops the messages held behind the running turn (each send ends `cancelled`); resolves how many. */
|
|
492
|
+
async clearQueued(): Promise<number> {
|
|
493
|
+
if (this.closed) return 0;
|
|
494
|
+
try { return await Native.clearQueued(this.handle); }
|
|
495
|
+
catch (error) { throw nativeError(error); }
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** Who hears an event: a held send hears its own `input.queued`; a turn's events go to every send it carries. */
|
|
499
|
+
private listenersFor(event: RuntimeEvent): Array<(event: RuntimeEvent) => void> {
|
|
500
|
+
const of = (ids: string[]) => this.listenersOf(ids);
|
|
501
|
+
if (event.type === 'input.queued' || event.type === 'input.dropped') return of([event.inputId]);
|
|
502
|
+
if (event.type === 'turn.started') {
|
|
503
|
+
this.currentTurn = event.turnId;
|
|
504
|
+
this.turnStarts.set(event.turnId, event);
|
|
505
|
+
this.turnListeners.set(event.turnId, of(event.inputIds ?? [event.messageId]));
|
|
506
|
+
}
|
|
507
|
+
const turnId = 'turnId' in event && typeof event.turnId === 'string' ? event.turnId : this.currentTurn;
|
|
508
|
+
const listeners = turnId ? this.turnListeners.get(turnId) : undefined;
|
|
509
|
+
// Before any turn has started (e.g. upkeep a send waits on), the oldest send in flight hears it, as before.
|
|
510
|
+
return listeners ?? [...this.sendListeners.values()].slice(0, 1).flat().map(r => r.listener);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** A callback registered by several calls carried by one turn hears each event once. */
|
|
514
|
+
private listenersOf(ids: string[]): Array<(event: RuntimeEvent) => void> {
|
|
515
|
+
return [...new Set(ids.flatMap(id => (this.sendListeners.get(id) ?? []).map(r => r.listener)))];
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Sends carried into a running turn at a later model call (`turn.joined`, S1): their listeners
|
|
520
|
+
* join the turn's, and only they hear its start, once. `turn.joined` itself reaches no send.
|
|
521
|
+
*/
|
|
522
|
+
private join(event: { turnId: string; inputIds: string[] }) {
|
|
523
|
+
const known = this.turnListeners.get(event.turnId), started = this.turnStarts.get(event.turnId);
|
|
524
|
+
if (!known || !started) return;
|
|
525
|
+
const added = this.listenersOf(event.inputIds).filter(l => !known.includes(l));
|
|
526
|
+
this.turnListeners.set(event.turnId, [...known, ...added]);
|
|
527
|
+
const start = { ...started, inputIds: [...(started.inputIds ?? [started.messageId]), ...event.inputIds] };
|
|
528
|
+
this.turnStarts.set(event.turnId, start);
|
|
529
|
+
for (const listener of added) { try { listener(start); } catch {} }
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
private removeForegroundListener?: () => void;
|
|
533
|
+
private lastForegroundAt?: number;
|
|
534
|
+
private foregroundMaintaining = false;
|
|
535
|
+
/**
|
|
536
|
+
* Upkeep when the app returns from `background` to `active`, as the web Runtime does
|
|
537
|
+
* on a visible return: once per return, and a second return inside the interval runs none. It
|
|
538
|
+
* never delays a send, and a failure here is not the user's news.
|
|
539
|
+
*/
|
|
540
|
+
private watchForeground(interval: number) {
|
|
541
|
+
let state: string | null | undefined = AppState.currentState; // undefined before the first report (RN 0.87 types)
|
|
542
|
+
const subscription = AppState.addEventListener('change', next => {
|
|
543
|
+
const returned = next === 'active' && state === 'background';
|
|
544
|
+
state = next;
|
|
545
|
+
if (!returned || this.closed || this.foregroundMaintaining) return;
|
|
546
|
+
const now = Date.now();
|
|
547
|
+
if (this.lastForegroundAt !== undefined && now >= this.lastForegroundAt && now - this.lastForegroundAt < interval) return;
|
|
548
|
+
this.lastForegroundAt = now;
|
|
549
|
+
this.foregroundMaintaining = true;
|
|
550
|
+
this.maintain().catch(() => {}).finally(() => { this.foregroundMaintaining = false; });
|
|
551
|
+
});
|
|
552
|
+
this.removeForegroundListener = () => subscription.remove();
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** One round of background upkeep now. It also runs by itself when the app returns to the foreground. */
|
|
556
|
+
async maintain(options: { force?: boolean } = {}): Promise<MaintenanceResult> {
|
|
557
|
+
this.checkOpen();
|
|
558
|
+
try { return parse<MaintenanceResult>(await Native.maintain(this.handle, options.force === true)); }
|
|
559
|
+
catch (error) { throw nativeError(error); }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Delivers the agent's scheduled notes that are due, as one turn: `{ran: false}` when none is
|
|
564
|
+
* (no turn, no cost) or one is already being delivered (`inFlight`). Never before a note's
|
|
565
|
+
* time. The native SDKs also deliver on their own while the app runs and at each foreground.
|
|
566
|
+
*/
|
|
567
|
+
async deliverDue(): Promise<DeliverDueResult> {
|
|
568
|
+
this.checkOpen();
|
|
569
|
+
let result: DeliverDueResult;
|
|
570
|
+
try { result = parse<DeliverDueResult>(await Native.deliverDue(this.handle)); }
|
|
571
|
+
catch (error) { throw nativeError(error); }
|
|
572
|
+
if (result.ran) await this.inspect().catch(() => {});
|
|
573
|
+
return result;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** The agent's pending scheduled notes, earliest first, and how many are due. */
|
|
577
|
+
async schedules(): Promise<ScheduleList> {
|
|
578
|
+
this.checkOpen();
|
|
579
|
+
try { return parse<ScheduleList>(await Native.schedules(this.handle)); }
|
|
580
|
+
catch (error) { throw nativeError(error); }
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** The Core projection fence joins its synchronous listener, not bridged or buffered UI events.
|
|
584
|
+
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
585
|
+
* wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
|
|
586
|
+
async close(): Promise<void> {
|
|
587
|
+
if (this.closed) return;
|
|
588
|
+
this.closed = true;
|
|
589
|
+
this.removeForegroundListener?.();
|
|
590
|
+
this.removeForegroundListener = undefined;
|
|
591
|
+
for (const controller of this.running.values()) controller.abort();
|
|
592
|
+
try { await Native.close(this.handle); }
|
|
593
|
+
catch (error) { throw nativeError(error); }
|
|
594
|
+
finally { unsubscribe(this.handle); }
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
private checkOpen() { if (this.closed) throw new CrocheError('closed', 'Runtime is closed.'); }
|
|
598
|
+
|
|
599
|
+
private receive(message: NativeMessage) {
|
|
600
|
+
if (message.type === 'event') {
|
|
601
|
+
const event = parse<RuntimeEvent>(message.json);
|
|
602
|
+
const joined = event as unknown as { type: string; turnId: string; inputIds: string[] };
|
|
603
|
+
if (joined.type === 'turn.joined') { this.join(joined); return; }
|
|
604
|
+
// An observer can never break the turn it observes.
|
|
605
|
+
for (const listener of this.listenersFor(event)) { try { listener(event); } catch {} }
|
|
606
|
+
} else if (message.type === 'tool') {
|
|
607
|
+
void this.runTool(parse<ToolRequest>(message.json));
|
|
608
|
+
} else if (message.type === 'toolCancel') {
|
|
609
|
+
this.running.get(parse<{ callId: string }>(message.json).callId)?.abort();
|
|
610
|
+
} else if (message.type === 'memoryChanged') {
|
|
611
|
+
// An observer can never break the Runtime it observes.
|
|
612
|
+
try { this.memoryListener?.(parse<MemoryChangedEvent>(message.json)); } catch {}
|
|
613
|
+
} else if (message.type === 'usage') {
|
|
614
|
+
// An observer can never break the Runtime it observes.
|
|
615
|
+
try { this.usageObserver?.(parse<RuntimeUsageEvent>(message.json)); } catch {}
|
|
616
|
+
} else if (message.type === 'delivered') {
|
|
617
|
+
// A delivery ran in the native SDK, perhaps on its own (its timer, its foreground hook, an
|
|
618
|
+
// OS background run): the cached history is refreshed (rook, #323 E). Internal: how the app
|
|
619
|
+
// hears of it is the public subscription (F25 on #264), not decided here.
|
|
620
|
+
if (!this.closed) void this.inspect().catch(() => {});
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
private async runTool(request: ToolRequest) {
|
|
625
|
+
const execute = this.executors.get(request.invocation.tool);
|
|
626
|
+
// Nothing ran: the Runtime may tell the model so and go on (H4; the Core's NOT_DISPATCHED).
|
|
627
|
+
if (!execute) { Native.resolveTool(request.callId, false, JSON.stringify({ code: 'tool_not_dispatched' })); return; }
|
|
628
|
+
const controller = new AbortController();
|
|
629
|
+
this.running.set(request.callId, controller);
|
|
630
|
+
try {
|
|
631
|
+
const { command, ...rest } = request.invocation;
|
|
632
|
+
const invocation = { ...rest, ...(command ? { command } : {}) } as CommandInvocation;
|
|
633
|
+
let returned: unknown;
|
|
634
|
+
try {
|
|
635
|
+
returned = await execute(invocation, { ...request.context, signal: controller.signal } as ToolContext);
|
|
636
|
+
} catch {
|
|
637
|
+
Native.resolveTool(request.callId, false, JSON.stringify({ code: 'effect_failed' }));
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
// The handler ran: what it returned is read once, inside this guard. Always an envelope:
|
|
641
|
+
// `{value}`, and with a toolResult its images beside it (the native SDK prepares them and
|
|
642
|
+
// refuses malformed ones as invalid_tool_result, H3). Anything unreadable fails this call
|
|
643
|
+
// alone with the bridge's own invalid_tool_result, never the app's error (Atlas, #351 P1-2).
|
|
644
|
+
let answer: string;
|
|
645
|
+
try {
|
|
646
|
+
if (isToolResult(returned)) {
|
|
647
|
+
const { value, images, imageResolution } = returned;
|
|
648
|
+
answer = JSON.stringify({ value: value ?? null, images: images ?? null, ...(imageResolution === 'high' || imageResolution === 'standard' ? { imageResolution } : {}) });
|
|
649
|
+
} else answer = JSON.stringify({ value: returned ?? null });
|
|
650
|
+
if (typeof answer !== 'string') throw new Error('not JSON');
|
|
651
|
+
} catch {
|
|
652
|
+
Native.resolveTool(request.callId, false, JSON.stringify({ code: 'invalid_tool_result' }));
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
Native.resolveTool(request.callId, true, answer);
|
|
656
|
+
} finally {
|
|
657
|
+
this.running.delete(request.callId);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|