@h1r-ai/croche 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/README.md +1184 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/dist/archive.d.ts +47 -0
- package/dist/archive.js +217 -0
- package/dist/atomic-replace.d.ts +18 -0
- package/dist/atomic-replace.js +39 -0
- package/dist/commands.d.ts +56 -0
- package/dist/commands.js +1 -0
- package/dist/control.d.ts +62 -0
- package/dist/control.js +269 -0
- package/dist/core-abi.d.ts +110 -0
- package/dist/core-abi.js +1 -0
- package/dist/core-bindgen.d.ts +413 -0
- package/dist/core-bindgen.js +1533 -0
- package/dist/core-runtime.d.ts +214 -0
- package/dist/core-runtime.js +837 -0
- package/dist/core-wasm-bytes.d.ts +4 -0
- package/dist/core-wasm-bytes.js +5 -0
- package/dist/core-wasm.d.ts +16 -0
- package/dist/core-wasm.js +63 -0
- package/dist/debug.d.ts +26 -0
- package/dist/debug.js +171 -0
- package/dist/file-lock.d.ts +46 -0
- package/dist/file-lock.js +300 -0
- package/dist/images.d.ts +53 -0
- package/dist/images.js +179 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +9 -0
- package/dist/markers.d.ts +1 -0
- package/dist/markers.js +1 -0
- package/dist/node.d.ts +46 -0
- package/dist/node.js +281 -0
- package/dist/project-core.d.ts +79 -0
- package/dist/project-core.js +261 -0
- package/dist/project-session.d.ts +44 -0
- package/dist/project-session.js +143 -0
- package/dist/project-types.d.ts +97 -0
- package/dist/project-types.js +1 -0
- package/dist/project-wire.d.ts +19 -0
- package/dist/project-wire.js +39 -0
- package/dist/sse.d.ts +19 -0
- package/dist/sse.js +53 -0
- package/dist/storage.d.ts +24 -0
- package/dist/storage.js +32 -0
- package/dist/stream-branch.d.ts +47 -0
- package/dist/stream-branch.js +107 -0
- package/dist/stream-hub.d.ts +207 -0
- package/dist/stream-hub.js +210 -0
- package/dist/stream.d.ts +3 -0
- package/dist/stream.js +5 -0
- package/dist/types.d.ts +928 -0
- package/dist/types.js +8 -0
- package/dist/wiki.d.ts +15 -0
- package/dist/wiki.js +25 -0
- package/docs/CODING-AGENT.md +96 -0
- package/docs/DEBUGGER.md +230 -0
- package/docs/S2-IMPLEMENTATION.md +585 -0
- package/docs/SKILL.md +337 -0
- package/docs/skills/croche/agents/openai.yaml +4 -0
- package/docs/skills/croche/references/agents.md +78 -0
- package/docs/skills/croche/references/first-turn.md +74 -0
- package/docs/skills/croche/references/tools.md +43 -0
- package/docs/skills/croche-cli/SKILL.md +158 -0
- package/docs/skills/croche-cli/agents/openai.yaml +4 -0
- package/docs/skills/croche-cli/references/powershell.md +47 -0
- package/docs/skills/croche-config/SKILL.md +152 -0
- package/docs/skills/croche-config/agents/openai.yaml +4 -0
- package/docs/skills/croche-config/references/models.md +12 -0
- package/docs/skills/croche-platforms/SKILL.md +55 -0
- package/docs/skills/croche-platforms/agents/openai.yaml +4 -0
- package/docs/skills/croche-platforms/references/android.md +185 -0
- package/docs/skills/croche-platforms/references/ios.md +165 -0
- package/docs/skills/croche-platforms/references/react-native.md +50 -0
- package/docs/skills/croche-platforms/references/web-backend.md +58 -0
- package/docs/skills/croche-troubleshoot/SKILL.md +72 -0
- package/docs/skills/croche-troubleshoot/agents/openai.yaml +4 -0
- package/docs/skills/croche-troubleshoot/references/recovery.md +31 -0
- package/package.json +52 -4
- package/src/archive.ts +188 -0
- package/src/atomic-replace.ts +43 -0
- package/src/commands.ts +62 -0
- package/src/control.ts +179 -0
- package/src/core-abi.ts +52 -0
- package/src/core-bindgen.ts +1557 -0
- package/src/core-runtime.ts +750 -0
- package/src/core-wasm-bytes.ts +5 -0
- package/src/core-wasm.ts +57 -0
- package/src/debug.ts +160 -0
- package/src/file-lock.ts +269 -0
- package/src/images.ts +174 -0
- package/src/index.ts +15 -0
- package/src/markers.ts +1 -0
- package/src/node.ts +194 -0
- package/src/project-core.ts +231 -0
- package/src/project-session.ts +118 -0
- package/src/project-types.ts +77 -0
- package/src/project-wire.ts +39 -0
- package/src/sse.ts +57 -0
- package/src/storage.ts +30 -0
- package/src/stream-branch.ts +112 -0
- package/src/stream-hub.ts +249 -0
- package/src/stream.ts +7 -0
- package/src/types.ts +838 -0
- package/src/wiki.ts +25 -0
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
import { core, coreNonce } from './core-wasm.js';
|
|
2
|
+
import { archiveAppend, archiveClear, archiveRead } from './archive.js';
|
|
3
|
+
import type { CoreObject } from './core-abi.js';
|
|
4
|
+
import type { CoreRuntimeOptions, RuntimeTool, RuntimeToolMetadata } from './commands.js';
|
|
5
|
+
import type {OpenOptions as ProjectOpenOptions, ToolHandler, ProjectToolContext} from './project-types.js';
|
|
6
|
+
import type {HostOptions} from './types.js';
|
|
7
|
+
import { browserCodec, isToolResult, preparable, prepareImage, type ImageCodec } from './images.js';
|
|
8
|
+
import {
|
|
9
|
+
CrocheError, type BudgetAdjustment, type BudgetSnapshot, type DeferredWrite, type DisplayMessage,
|
|
10
|
+
type JsonValue, type RuntimeDebugEvent, type RuntimeDebugObserverOptions, type RuntimeEvent, type RuntimeUsageEvent, type RuntimeMemory, type RuntimeStatus, type RuntimeStorage,
|
|
11
|
+
type InputImage, type SendInput, type SendOptions, type TurnResult, type MemoryChangedEvent, type MemoryExport, type MemoryItem, type RuntimeMemoryApi,
|
|
12
|
+
type RuntimeWiki, type UserWikiDocument, type UserWikiResult, type WikiDigest, type WikiDocument, type WikiEntry, type WikiHit, type WikiPage,
|
|
13
|
+
} from './types.js';
|
|
14
|
+
|
|
15
|
+
// Mirrors the protocol default; kept standalone so published SDK imports need no workspace.
|
|
16
|
+
export const DEFAULT_MODEL = 'deepseek/deepseek-v4.1-flash';
|
|
17
|
+
export const SDK_VERSION = '0.5.1';
|
|
18
|
+
const DEFAULT_MAINTENANCE_INTERVAL_MS = 60_000;
|
|
19
|
+
/** What one round of background upkeep did. */
|
|
20
|
+
export interface MaintenanceResult { ran: boolean; ok?: boolean; preempted?: boolean; pendingEvents?: number; error?: { code: string; message: string } }
|
|
21
|
+
/** What `deliverDue()` did: nothing due (or a delivery already running: `inFlight`), or one turn
|
|
22
|
+
* that carried the notes `ids` (`"heartbeat"` among them for the app's heartbeat).
|
|
23
|
+
* `delivered: true` means they are spent: never delivered again, and the heartbeat's next period
|
|
24
|
+
* counts from now. Spent is not answered: a spent note's turn may have failed (`error`, also on
|
|
25
|
+
* `turn.error`), and then the note says so (`failed: <code>`, plus `retry`: `permanent` for the
|
|
26
|
+
* code, `dispatched` when the turn had dispatched a command, so a retry could run it twice,
|
|
27
|
+
* `expired` a day after the note's time).
|
|
28
|
+
* `delivered: false` means something stays pending: the turn was cancelled, or it failed
|
|
29
|
+
* transiently before dispatching any command, and the notes and the heartbeat are tried again
|
|
30
|
+
* from `retryAt` (`error` says why).
|
|
31
|
+
* `error` without a turn: refused before any turn began (spent, or retried, by the same rule). */
|
|
32
|
+
export interface DeliverDueResult { ran: boolean; inFlight?: boolean; ids?: string[]; delivered?: boolean; turn?: TurnResult; retryAt?: string; error?: { code: string; message: string } }
|
|
33
|
+
/** The agent's pending scheduled notes, earliest first, and how many are due now; with the
|
|
34
|
+
* `heartbeat` option, also its next time and whether it is due (not in `pending` or `due`).
|
|
35
|
+
* A note or heartbeat whose delivery failed transiently carries `attempts` and is not due
|
|
36
|
+
* before `retryAt`; for the heartbeat these are retry attempts, not heartbeat periods. */
|
|
37
|
+
export interface ScheduleList { pending: Array<{ id: string; at: string; note: string; attempts?: number; retryAt?: string }>; due: number; heartbeat?: { at: string; due: boolean; attempts?: number; retryAt?: string } }
|
|
38
|
+
const localOwners = new WeakMap<object, Set<string>>();
|
|
39
|
+
/** The longest delay a JS timer holds (2^31 - 1 ms, about 24.8 days); a longer one fires at once.
|
|
40
|
+
* A note further away is reached in steps, each re-checked against its time. */
|
|
41
|
+
export const SCHEDULE_TIMER_MAX_MS = 2_147_483_647;
|
|
42
|
+
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
|
43
|
+
type Binding = { metadata?: RuntimeToolMetadata; execute: RuntimeTool['execute'] };
|
|
44
|
+
type Inspection = { status: RuntimeStatus; history: DisplayMessage[]; memory: RuntimeMemory; budget: BudgetSnapshot; tools: RuntimeToolMetadata[] };
|
|
45
|
+
|
|
46
|
+
function observer<T>(callback: ((value: T) => unknown) | undefined, value: T) {
|
|
47
|
+
if (!callback) return;
|
|
48
|
+
try { void Promise.resolve(callback(value)).catch(() => {}); }
|
|
49
|
+
catch { /* Observers cannot invalidate the Core's durable transition. */ }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function failure(error: unknown, fallback: string): { code: string; message: string } {
|
|
53
|
+
const code = error instanceof CrocheError ? error.code : fallback;
|
|
54
|
+
return { code, message: error instanceof Error ? error.message.slice(0, 1000) : 'The host operation failed.' };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A Tool callback's rejection as an error the Runtime owns: its `code` and `message` are read
|
|
59
|
+
* once, and the app's object is never passed on, so a getter cannot answer differently later.
|
|
60
|
+
* "Nothing ran" is the host's to say, never a handler's: `tool_not_dispatched` or
|
|
61
|
+
* `host_unresponsive` from handler code (perhaps another Runtime's error passed on) becomes
|
|
62
|
+
* `tool_failed`, since the handler may have had its effect. A getter that throws is the same.
|
|
63
|
+
* Otherwise this keeps what the Core read before: a string `code` (else `tool_failed`) and a
|
|
64
|
+
* string `message` (or the thrown string).
|
|
65
|
+
*/
|
|
66
|
+
function handlerError(error: unknown): CrocheError {
|
|
67
|
+
const fallback = 'The Tool callback failed. Its effects may have completed.';
|
|
68
|
+
try {
|
|
69
|
+
const object = (typeof error === 'object' || typeof error === 'function') && error !== null;
|
|
70
|
+
const code: unknown = object ? (error as { code?: unknown }).code : undefined;
|
|
71
|
+
const message: unknown = object ? (error as { message?: unknown }).message : error;
|
|
72
|
+
const owned = typeof code === 'string' && code !== 'tool_not_dispatched' && code !== 'host_unresponsive' ? code : 'tool_failed';
|
|
73
|
+
return new CrocheError(owned, typeof message === 'string' ? message : fallback);
|
|
74
|
+
} catch {
|
|
75
|
+
return new CrocheError('tool_failed', fallback);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function serializable(value: unknown): JsonValue {
|
|
80
|
+
const result = JSON.stringify(value, (_key, item: unknown) => {
|
|
81
|
+
if (typeof item === 'number' && !Number.isFinite(item)) throw new Error('Non-finite JSON number');
|
|
82
|
+
if (['undefined', 'function', 'symbol', 'bigint'].includes(typeof item)) throw new Error('Non-JSON value');
|
|
83
|
+
return item;
|
|
84
|
+
});
|
|
85
|
+
if (result === undefined) throw new Error('Missing JSON value');
|
|
86
|
+
return JSON.parse(result);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The time the Core sees. A host clock (tests, simulations) replaces the wall clock. */
|
|
90
|
+
/** Minutes east of UTC in `timeZone` (IANA) at `at`, or the host's own offset. */
|
|
91
|
+
function localOffsetMinutes(at: Date, timeZone?: string): number {
|
|
92
|
+
if (!timeZone) return -at.getTimezoneOffset();
|
|
93
|
+
try {
|
|
94
|
+
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
|
|
95
|
+
.formatToParts(at).map(p => [p.type, p.value]));
|
|
96
|
+
const asUtc = Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour, +parts.minute);
|
|
97
|
+
return Math.round((asUtc - Math.floor(at.getTime() / 60000) * 60000) / 60000);
|
|
98
|
+
} catch { return -at.getTimezoneOffset(); }
|
|
99
|
+
}
|
|
100
|
+
function hostNow(clock?: () => number | Date): string {
|
|
101
|
+
if (!clock) return new Date().toISOString();
|
|
102
|
+
const value = clock();
|
|
103
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
104
|
+
if (Number.isNaN(date.getTime())) throw new CrocheError('invalid_configuration', 'clock() must return a valid time.');
|
|
105
|
+
return date.toISOString();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
type WasmRuntime = InstanceType<ReturnType<typeof core>['WasmRuntime']>;
|
|
110
|
+
/** Internal PAL reuse; not exported by the package or a public Runtime API name. */
|
|
111
|
+
type ProjectPal = {host: ReturnType<CrocheRuntime['host']>; attach(handle: WasmRuntime): CrocheRuntime};
|
|
112
|
+
export let projectPal: (options: ProjectOpenOptions, user: () => string | null) => ProjectPal;
|
|
113
|
+
/** Internal receipt-send reuse; not exported by the package. */
|
|
114
|
+
export const receiptSend = Symbol('receipt-send');
|
|
115
|
+
type WasmCancel = InstanceType<ReturnType<typeof core>['WasmCancel']>;
|
|
116
|
+
type WasmSink = InstanceType<ReturnType<typeof core>['WasmSink']>;
|
|
117
|
+
type HttpRequest = { url: string; method: string; headers: [string, string][]; body: string; timeoutMs: number };
|
|
118
|
+
|
|
119
|
+
function rethrow(error: unknown): never {
|
|
120
|
+
if (error instanceof CrocheError) throw error;
|
|
121
|
+
const e = error as { code?: unknown; message?: unknown } | null;
|
|
122
|
+
if (e && typeof e.code === 'string') throw new CrocheError(e.code, typeof e.message === 'string' ? e.message : 'The Runtime operation failed.');
|
|
123
|
+
throw new CrocheError('core_error', 'The shared Rust Core could not complete its transition. Reopen from durable storage.');
|
|
124
|
+
}
|
|
125
|
+
async function settle<T>(promise: Promise<string>, map: (value: unknown) => T = value => value as T): Promise<T> {
|
|
126
|
+
try { return map(JSON.parse(await held(promise))); } catch (error) { return rethrow(error); }
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Keeps Node running while the app awaits one of the Runtime's operations. The Core's own
|
|
130
|
+
* timers (`sleep`) are unref'd so an idle Runtime never holds the process open, but an
|
|
131
|
+
* operation may wait on nothing else: a round's 3-second wait for a command that never
|
|
132
|
+
* settles, or close's 2-second bound for running commands (H2). Without this, Node would exit
|
|
133
|
+
* with the app's await unsettled.
|
|
134
|
+
*/
|
|
135
|
+
function held<T>(promise: Promise<T>): Promise<T> {
|
|
136
|
+
const alive = setInterval(() => {}, 0x7fffffff);
|
|
137
|
+
return promise.finally(() => clearInterval(alive));
|
|
138
|
+
}
|
|
139
|
+
/** A write's answer: what it did, or, called while another operation ran, that it was accepted. */
|
|
140
|
+
function settleWrite<T>(promise: Promise<string>, map: (value: unknown) => T = value => value as T): Promise<T | DeferredWrite> {
|
|
141
|
+
return settle(promise, value => ((value as { deferred?: unknown } | null)?.deferred === true ? { deferred: true } : map(value)));
|
|
142
|
+
}
|
|
143
|
+
const WIKI_SHAPE = 'Wiki documents are [{path, markdown, agents?}]: strings, and agents a list of agent ids.';
|
|
144
|
+
function wikiJson(docs: WikiDocument[]): string {
|
|
145
|
+
if (!Array.isArray(docs)) throw new CrocheError('invalid_wiki', WIKI_SHAPE);
|
|
146
|
+
try { return JSON.stringify(docs.map(d => ({ path: d?.path, markdown: d?.markdown, ...(d?.agents === undefined ? {} : { agents: d.agents }) }))); }
|
|
147
|
+
catch { throw new CrocheError('invalid_wiki', WIKI_SHAPE); }
|
|
148
|
+
}
|
|
149
|
+
function call<T>(run: () => T): T {
|
|
150
|
+
try { return run(); } catch (error) { return rethrow(error); }
|
|
151
|
+
}
|
|
152
|
+
let storeIdentities = 0;
|
|
153
|
+
const storeIds = new WeakMap<object, string>();
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Web/Node SDK. The Runtime (its state, its turn loop, upkeep, cancellation, persistence order)
|
|
157
|
+
* is the shared Rust Core; this class is its PAL for web and Node (fetch, storage, locks, timers,
|
|
158
|
+
* the app's tool callbacks) and the typed API over it.
|
|
159
|
+
*/
|
|
160
|
+
export class CrocheRuntime {
|
|
161
|
+
private core!: WasmRuntime;
|
|
162
|
+
private bindings = new Map<string, Binding>();
|
|
163
|
+
private debugObserver?: RuntimeDebugObserverOptions['onDebugEvent'];
|
|
164
|
+
private usageObserver?: (event: RuntimeUsageEvent) => void;
|
|
165
|
+
private readonly transport: typeof fetch;
|
|
166
|
+
private wakeTimer?: ReturnType<typeof setTimeout>;
|
|
167
|
+
private releaseLock?: () => void | Promise<void>;
|
|
168
|
+
/** Whether this instance holds an exclusive lock on its store (the storage's own, or a Web Lock).
|
|
169
|
+
* Only such an instance arms schedule timers: without one, two tabs or processes on one store
|
|
170
|
+
* would each deliver. */
|
|
171
|
+
private lockHeld = false;
|
|
172
|
+
private ready = false;
|
|
173
|
+
private scheduleEntries: Array<{ id: string; at: string }> = [];
|
|
174
|
+
private scheduleTimer?: ReturnType<typeof setTimeout>;
|
|
175
|
+
private removeForegroundListener?: () => void;
|
|
176
|
+
private lastForegroundAt?: number;
|
|
177
|
+
private foregroundMaintaining = false;
|
|
178
|
+
|
|
179
|
+
readonly userBudget = {
|
|
180
|
+
get: (): BudgetSnapshot => this.inspect().budget,
|
|
181
|
+
/** Cloud applies the developer's ceilings and answers. Pass `id` to make a retry safe. */
|
|
182
|
+
add: ({ amount, id }: { amount: number; id?: string }): Promise<BudgetAdjustment | DeferredWrite> => this.adjust(amount, false, id),
|
|
183
|
+
set: ({ amount, id }: { amount: number; id?: string }): Promise<BudgetAdjustment | DeferredWrite> => this.adjust(amount, true, id),
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The app's knowledge documents, held by the Rust Core in memory (never stored: load them on
|
|
188
|
+
* each open). The agent never sees a document unless it searches or reads it with the built-in
|
|
189
|
+
* `wiki` command; `list`, `read` and `search` here are that same view.
|
|
190
|
+
*/
|
|
191
|
+
readonly wiki: RuntimeWiki = {
|
|
192
|
+
set: (docs: WikiDocument[]): WikiDigest => { this.checkOpen(); return call(() => JSON.parse(this.core.wikiSet(wikiJson(docs))) as WikiDigest); },
|
|
193
|
+
load: (docs: WikiDocument[]): void => { this.wiki.set(docs); },
|
|
194
|
+
put: ((docs: WikiDocument | WikiDocument[]): void | Promise<UserWikiResult | DeferredWrite> => {
|
|
195
|
+
this.checkOpen();
|
|
196
|
+
const list = Array.isArray(docs) ? docs : [docs];
|
|
197
|
+
const user = list.filter(d => d?.scope === 'user').length;
|
|
198
|
+
if (user > 0 && user < list.length) throw new CrocheError('invalid_wiki', "One put holds either the app's documents or the user's own (scope: 'user'), not both.");
|
|
199
|
+
if (user > 0) {
|
|
200
|
+
let json: string;
|
|
201
|
+
try { json = wikiJson(list); } catch (error) { return Promise.reject(error); }
|
|
202
|
+
return settleWrite(this.core.wikiPutUser(json), value => value as UserWikiResult);
|
|
203
|
+
}
|
|
204
|
+
call(() => this.core.wikiPut(wikiJson(list)));
|
|
205
|
+
}) as RuntimeWiki['put'],
|
|
206
|
+
remove: ((path: string, options?: { scope: 'user' }): boolean | Promise<boolean | DeferredWrite> => {
|
|
207
|
+
this.checkOpen();
|
|
208
|
+
if (options?.scope === 'user') return settleWrite(this.core.wikiRemoveUser(String(path)), value => (value as { removed: boolean }).removed);
|
|
209
|
+
return call(() => this.core.wikiRemove(String(path)));
|
|
210
|
+
}) as RuntimeWiki['remove'],
|
|
211
|
+
clear: (options: { scope: 'user' }): Promise<number | DeferredWrite> => {
|
|
212
|
+
this.checkOpen();
|
|
213
|
+
if (options?.scope !== 'user') return Promise.reject(new CrocheError('invalid_wiki', "clear removes the user's own documents: clear({scope: 'user'}). To empty the app's, set([])."));
|
|
214
|
+
return settleWrite(this.core.wikiClearUser(), value => (value as { cleared: number }).cleared);
|
|
215
|
+
},
|
|
216
|
+
/** Documents under `folder` (all by default), by path. */
|
|
217
|
+
list: (folder?: string): WikiEntry[] => { this.checkOpen(); return call(() => JSON.parse(this.core.wikiList(folder)) as WikiEntry[]); },
|
|
218
|
+
/** One part (1-based) of a document, or null when there is no such document or part. */
|
|
219
|
+
read: (path: string, part = 1): WikiPage | null => {
|
|
220
|
+
this.checkOpen();
|
|
221
|
+
if (!Number.isInteger(part) || part < 1) return null;
|
|
222
|
+
return call(() => JSON.parse(this.core.wikiRead(String(path), Math.min(part, 0xffffffff))) as WikiPage | null);
|
|
223
|
+
},
|
|
224
|
+
/** The best matches (at most `limit`, and 5), best first. */
|
|
225
|
+
search: (query: string, limit = 5): WikiHit[] => {
|
|
226
|
+
this.checkOpen();
|
|
227
|
+
return call(() => JSON.parse(this.core.wikiSearch(String(query), Math.max(0, Math.min(Math.floor(limit) || 0, 5)))) as WikiHit[]);
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
private readonly secretStorage: RuntimeStorage;
|
|
232
|
+
private readonly codec: ImageCodec | undefined;
|
|
233
|
+
/** Ordered calls still waiting to be admitted (`ordered`), and the last one's admission. */
|
|
234
|
+
private waiting = 0;
|
|
235
|
+
private admitted: Promise<void> = Promise.resolve();
|
|
236
|
+
private constructor(private readonly options: HostOptions) {
|
|
237
|
+
this.secretStorage = options.secretStorage ?? options.storage;
|
|
238
|
+
this.codec = options.imageCodec === null ? undefined : options.imageCodec ?? browserCodec();
|
|
239
|
+
this.debugObserver = options.onDebugEvent;
|
|
240
|
+
this.usageObserver = options.onUsage;
|
|
241
|
+
this.transport = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
242
|
+
if (!this.transport) throw new CrocheError('host_unavailable', 'The host must provide fetch or a transport adapter.');
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** The factory owns opening/config resolution. This creates only a host per store. */
|
|
246
|
+
static { projectPal = (options: ProjectOpenOptions, user: () => string | null) => {
|
|
247
|
+
const runtime = new CrocheRuntime({...options, onUsage: undefined});
|
|
248
|
+
for (const [name, handler] of Object.entries(options.handlers ?? {})) {
|
|
249
|
+
const execute: ToolHandler = handler;
|
|
250
|
+
runtime.bindings.set(name, {
|
|
251
|
+
execute: (invocation, context) => {
|
|
252
|
+
const {userId, ...rest} = context;
|
|
253
|
+
return execute(invocation, {...rest, user: user(), crocheUserId: userId || null} as ProjectToolContext);
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
host: runtime.host(),
|
|
259
|
+
attach: (handle: WasmRuntime) => {
|
|
260
|
+
runtime.core = handle;
|
|
261
|
+
runtime.ready = true;
|
|
262
|
+
runtime.armSchedule();
|
|
263
|
+
runtime.watchForeground(options.maintenanceIntervalMs ?? DEFAULT_MAINTENANCE_INTERVAL_MS);
|
|
264
|
+
return runtime;
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}; }
|
|
268
|
+
|
|
269
|
+
static async create(options: CoreRuntimeOptions): Promise<CrocheRuntime> {
|
|
270
|
+
// A server key is a project secret: it belongs on the app's backend, never in a page.
|
|
271
|
+
if (options?.serverKey !== undefined && typeof (globalThis as { document?: unknown }).document !== 'undefined') {
|
|
272
|
+
throw new CrocheError('invalid_configuration', 'serverKey is a server secret: run the Runtime on your backend, never in a browser.');
|
|
273
|
+
}
|
|
274
|
+
if (!options?.storage || typeof options.storage.getItem !== 'function' || typeof options.storage.setItem !== 'function') {
|
|
275
|
+
throw new CrocheError('invalid_configuration', 'Atomic Runtime storage is required.');
|
|
276
|
+
}
|
|
277
|
+
// Only data crosses the Core boundary. Private callbacks and host adapters
|
|
278
|
+
// are neither serialized into prompts nor persisted in the Runtime snapshot.
|
|
279
|
+
if (options.storage.archive !== undefined) {
|
|
280
|
+
const a = options.storage.archive as unknown as Record<string, unknown> | null;
|
|
281
|
+
if (!a || ['appendLine', 'readLines', 'replaceLines', 'remove', 'entries'].some(m => typeof a[m] !== 'function')) {
|
|
282
|
+
throw new CrocheError('invalid_configuration', 'storage.archive needs appendLine, readLines, replaceLines, remove and entries.');
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
const { storage: _storage, secretStorage: _secretStorage, fetch: _fetch, onDebugEvent: _debug, onUsage: _usage, timeZone: _timeZone, tools: _tools, wiki: wikiOption, backgroundSync: _background, maintenanceIntervalMs: _interval, clock: _clock, ...data } = options;
|
|
286
|
+
let config: CoreObject;
|
|
287
|
+
try { config = clone(data); }
|
|
288
|
+
catch { throw new CrocheError('invalid_configuration', 'Runtime configuration must be JSON serializable.'); }
|
|
289
|
+
const interval = Math.max(1000, options.maintenanceIntervalMs ?? DEFAULT_MAINTENANCE_INTERVAL_MS);
|
|
290
|
+
if (options.backgroundSync !== false && !Number.isFinite(interval)) throw new CrocheError('invalid_configuration', 'maintenanceIntervalMs must be finite.');
|
|
291
|
+
const runtime = new CrocheRuntime(options);
|
|
292
|
+
const metadata = runtime.toolMetadata(options.tools ?? []);
|
|
293
|
+
config.tools = metadata.list;
|
|
294
|
+
// Documents are data the Core holds, not configuration; this agent's globs are configuration.
|
|
295
|
+
const wikiDocs = Array.isArray(wikiOption) ? wikiOption : wikiOption?.docs;
|
|
296
|
+
if (wikiOption !== undefined && !Array.isArray(wikiOption)) {
|
|
297
|
+
if (wikiOption === null || typeof wikiOption !== 'object') throw new CrocheError('invalid_configuration', 'wiki is a list of documents or {docs, include, exclude}.');
|
|
298
|
+
const { docs: _docs, ...globs } = wikiOption;
|
|
299
|
+
config.wiki = clone(globs);
|
|
300
|
+
}
|
|
301
|
+
const open = { streaming: options.streaming !== false, backgroundSync: options.backgroundSync !== false && !options.clock, maintenanceIntervalMs: interval, ...(options.storageKey === undefined ? {} : { storageKey: options.storageKey }) };
|
|
302
|
+
const { WasmRuntime } = core();
|
|
303
|
+
hostNow(options.clock);
|
|
304
|
+
const debug = runtime.debugObserver ? (event: string) => observer(runtime.debugObserver, JSON.parse(event)) : undefined;
|
|
305
|
+
const usage = (event: string) => observer(runtime.usageObserver, JSON.parse(event));
|
|
306
|
+
try { runtime.core = await (WasmRuntime.open(runtime.host(), JSON.stringify(config), JSON.stringify(open), debug, usage) as Promise<WasmRuntime>); }
|
|
307
|
+
catch (error) { rethrow(error); }
|
|
308
|
+
runtime.bindings = metadata.bindings;
|
|
309
|
+
if (wikiDocs !== undefined) {
|
|
310
|
+
try { runtime.wiki.set(wikiDocs); }
|
|
311
|
+
catch (error) { await runtime.close(); throw error; }
|
|
312
|
+
}
|
|
313
|
+
// The pending set arrived during open (the Core announces it at every open): a note already
|
|
314
|
+
// due is delivered now, the rest when their time comes.
|
|
315
|
+
runtime.ready = true;
|
|
316
|
+
runtime.armSchedule();
|
|
317
|
+
runtime.watchForeground(interval);
|
|
318
|
+
return runtime;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Shares documents of the user's own with several characters. Each agent's Runtime has its
|
|
323
|
+
* own store, so this puts them (as `scope: 'user'`) to every Runtime given, each with its own
|
|
324
|
+
* `agents` filter applied. A put replaces by path, so retrying after a failure is safe.
|
|
325
|
+
*/
|
|
326
|
+
static shareWiki(runtimes: CrocheRuntime[], docs: WikiDocument | WikiDocument[]): Promise<(UserWikiResult | DeferredWrite)[]> {
|
|
327
|
+
const list: UserWikiDocument[] = (Array.isArray(docs) ? docs : [docs]).map(d => ({ ...d, scope: 'user' }));
|
|
328
|
+
return Promise.all(runtimes.map(runtime => runtime.wiki.put(list)));
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
private toolMetadata(tools: RuntimeTool[]): { list: RuntimeToolMetadata[]; bindings: Map<string, Binding> } {
|
|
332
|
+
const bindings = new Map<string, Binding>();
|
|
333
|
+
try {
|
|
334
|
+
const list = tools.map(tool => {
|
|
335
|
+
if (typeof tool.execute !== 'function') throw new Error('Missing handler');
|
|
336
|
+
const entry = clone({ name: tool.name, summary: tool.summary, commands: tool.commands });
|
|
337
|
+
bindings.set(tool.name, { metadata: entry, execute: tool.execute });
|
|
338
|
+
return entry;
|
|
339
|
+
});
|
|
340
|
+
return { list, bindings };
|
|
341
|
+
} catch { throw new CrocheError('invalid_tool', 'Tools need serializable command declarations and execute handlers.'); }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Registry validation is atomic and performed by Rust; a refusal changes nothing here
|
|
345
|
+
* or in the Core. The model learns of the change from the next turn: in that message, so the
|
|
346
|
+
* cached prompt stays warm, until a new conversation or a pause rebuilds the list itself
|
|
347
|
+
* (internal#2). Revocation applies at
|
|
348
|
+
* once: an announced callback that has not started is not run, and a removed or changed
|
|
349
|
+
* command answers `withdrawn` for the rest of the turn. */
|
|
350
|
+
setTools(tools: RuntimeTool[]): void {
|
|
351
|
+
this.checkOpen();
|
|
352
|
+
const next = this.toolMetadata(tools);
|
|
353
|
+
call(() => this.core.setToolDeclarations(JSON.stringify(next.list)));
|
|
354
|
+
this.bindings = next.bindings;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Attach, replace or detach local diagnostics without reopening the Runtime.
|
|
358
|
+
* Only future observations are delivered; attaching during work may capture a
|
|
359
|
+
* response without its earlier request. This never replays past model bodies.
|
|
360
|
+
* Observer exceptions and mutations cannot affect execution or durable state. */
|
|
361
|
+
setDebugObserver(options?: RuntimeDebugObserverOptions): void {
|
|
362
|
+
this.checkOpen();
|
|
363
|
+
let callback: RuntimeDebugObserverOptions['onDebugEvent'] | undefined;
|
|
364
|
+
// Public types offer runtime only; untyped callers and private tools can still supply full.
|
|
365
|
+
// Let Core decide build availability before replacing this observer.
|
|
366
|
+
let visibility: string = 'runtime';
|
|
367
|
+
if (options !== undefined) {
|
|
368
|
+
if (!options || typeof options !== 'object') throw new CrocheError('invalid_configuration', 'Debug observer options require a callback.');
|
|
369
|
+
callback = options.onDebugEvent;
|
|
370
|
+
visibility = options.visibility ?? 'runtime';
|
|
371
|
+
if (typeof callback !== 'function' || !['runtime', 'full'].includes(visibility)) {
|
|
372
|
+
throw new CrocheError('invalid_configuration', 'Debug observer requires a callback and runtime or full visibility.');
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
call(() => this.core.setDebugObserver(callback ? (event: string) => observer(callback, JSON.parse(event)) : undefined, visibility === 'full'));
|
|
376
|
+
this.debugObserver = callback;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
history(): DisplayMessage[] { return this.inspect().history; }
|
|
380
|
+
status(): RuntimeStatus { return { ...this.inspect().status, closed: this.core.isClosed() }; }
|
|
381
|
+
tools(): RuntimeToolMetadata[] { return this.inspect().tools; }
|
|
382
|
+
/** Long-term memory: call it for a read-only snapshot, use its methods to manage it. */
|
|
383
|
+
readonly memory: RuntimeMemoryApi = Object.assign(
|
|
384
|
+
(): RuntimeMemory => { const memory = this.inspect().memory; return { ...memory, updatedAt: memory.updatedAt ?? null }; },
|
|
385
|
+
{
|
|
386
|
+
list: (): MemoryItem[] => this.memoryRead('list') as MemoryItem[],
|
|
387
|
+
delete: (id: string): Promise<{ deleted: boolean } | DeferredWrite> => { this.checkOpen(); return settleWrite(this.core.memoryDelete(id)); },
|
|
388
|
+
clear: (): Promise<{ cleared: number } | DeferredWrite> => { this.checkOpen(); return settleWrite(this.core.memoryClear()); },
|
|
389
|
+
enabled: (on: boolean): Promise<void | DeferredWrite> => { this.checkOpen(); return settleWrite(this.core.memorySetEnabled(on), () => undefined); },
|
|
390
|
+
export: (): MemoryExport => this.memoryRead('export') as MemoryExport,
|
|
391
|
+
onChanged: (listener: ((event: MemoryChangedEvent) => void) | undefined): void => {
|
|
392
|
+
call(() => this.core.setMemoryObserver(listener ? (event: string) => observer(listener, JSON.parse(event)) : undefined));
|
|
393
|
+
},
|
|
394
|
+
},
|
|
395
|
+
);
|
|
396
|
+
|
|
397
|
+
send(input: SendInput, options: SendOptions = {}): Promise<TurnResult> {
|
|
398
|
+
return this.prepareSend(input, options, (ready) => this.reserve(ready, options));
|
|
399
|
+
}
|
|
400
|
+
[receiptSend](input: SendInput, options: Pick<SendOptions, 'signal' | 'responseFormat' | 'imageResolution'> = {}): Promise<import('./stream-hub.js').StreamReceipt> {
|
|
401
|
+
return this.prepareSend(input, options, ready => {
|
|
402
|
+
let text: string, format: string | undefined;
|
|
403
|
+
try { text = JSON.stringify(ready); }
|
|
404
|
+
catch { return Promise.reject(new CrocheError('invalid_input', 'The input must be JSON serializable.')); }
|
|
405
|
+
try { format = options.responseFormat === undefined ? undefined : JSON.stringify(options.responseFormat); }
|
|
406
|
+
catch { return Promise.reject(new CrocheError('invalid_response_format', 'The response format must be JSON serializable.')); }
|
|
407
|
+
try { return settle(this.core.send(text, undefined, this.cancelFor(options.signal), format)); }
|
|
408
|
+
catch (error) { return settle(Promise.reject(error)); }
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
private prepareSend<T>(input: SendInput, options: Pick<SendOptions, 'imageResolution'>, admit: (ready: SendInput) => Promise<T>): Promise<T> {
|
|
412
|
+
this.checkOpen();
|
|
413
|
+
// Images the codec re-encodes are prepared first (H3), at once and side by side; each send
|
|
414
|
+
// is still admitted in caller order (`ordered`). With nothing to prepare (Node, url or high
|
|
415
|
+
// images) and nothing ahead, the turn is reserved before send() returns, as always.
|
|
416
|
+
const stack = (input as { inputs?: Array<{ images?: unknown }> }).inputs;
|
|
417
|
+
// Read once; an input that cannot be read is the Core's to refuse, never a throw from here.
|
|
418
|
+
let images: unknown[] = [];
|
|
419
|
+
try {
|
|
420
|
+
images = Array.isArray(stack) ? stack.flatMap(i => { const list = i?.images; return Array.isArray(list) ? list as unknown[] : []; }) : Array.isArray(input.images) ? input.images : [];
|
|
421
|
+
} catch { images = []; }
|
|
422
|
+
const prepared = images.some(i => preparable(i, options.imageResolution, this.codec))
|
|
423
|
+
? (async () => ({
|
|
424
|
+
...input,
|
|
425
|
+
...(Array.isArray(stack) ? { inputs: await Promise.all(stack.map(async i => {
|
|
426
|
+
const list = i?.images;
|
|
427
|
+
return Array.isArray(list)
|
|
428
|
+
? { ...i, images: await Promise.all((list as InputImage[]).map(image => prepareImage(image, options.imageResolution, this.codec))) }
|
|
429
|
+
: i;
|
|
430
|
+
})) } : { images: await Promise.all((images as InputImage[]).map(image => prepareImage(image, options.imageResolution, this.codec))) }),
|
|
431
|
+
}) as SendInput)()
|
|
432
|
+
: undefined;
|
|
433
|
+
return this.ordered(prepared, ready => admit(ready ?? input));
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Admits calls to the Core in the order they were made (Atlas, #351 P1-4): a send waiting on
|
|
437
|
+
* its images holds back every ordered call after it (sends, clearHistory, clearQueued), never
|
|
438
|
+
* one before it. Only admission waits, never a turn. A preparation that fails rejects its own
|
|
439
|
+
* call alone; the next is admitted as usual. With nothing waiting, `admit` runs at once.
|
|
440
|
+
*/
|
|
441
|
+
private ordered<R, T>(prepared: Promise<R> | undefined, admit: (ready: R | undefined) => Promise<T>): Promise<T> {
|
|
442
|
+
if (!prepared && this.waiting === 0) return admit(undefined);
|
|
443
|
+
// Its outcome is observed now, as it starts, never only once the calls ahead are admitted:
|
|
444
|
+
// a preparation that fails while it waits is this call's rejection, never an unhandled one
|
|
445
|
+
// (Atlas, #351 6054040729), and never the next call's.
|
|
446
|
+
const settled = prepared?.then(value => ({ ok: true as const, value }), (error: unknown) => ({ ok: false as const, error }));
|
|
447
|
+
this.waiting++;
|
|
448
|
+
const before = this.admitted;
|
|
449
|
+
const entry = (async () => {
|
|
450
|
+
await before;
|
|
451
|
+
const outcome = await settled;
|
|
452
|
+
if (outcome && !outcome.ok) throw outcome.error;
|
|
453
|
+
const ready = outcome?.value;
|
|
454
|
+
// Closed while it waited: the typed `closed`, never a call into a freed Core.
|
|
455
|
+
this.checkOpen();
|
|
456
|
+
return { out: admit(ready) };
|
|
457
|
+
})();
|
|
458
|
+
this.admitted = entry.then(() => {}, () => {}).finally(() => { this.waiting--; });
|
|
459
|
+
return entry.then(r => r.out);
|
|
460
|
+
}
|
|
461
|
+
private reserve(input: SendInput, options: SendOptions): Promise<TurnResult> {
|
|
462
|
+
let text: string;
|
|
463
|
+
try { text = JSON.stringify(input); }
|
|
464
|
+
catch { return Promise.reject(new CrocheError('invalid_input', 'The input must be JSON serializable.')); }
|
|
465
|
+
let format: string | undefined;
|
|
466
|
+
try { format = options.responseFormat === undefined ? undefined : JSON.stringify(options.responseFormat); }
|
|
467
|
+
catch { return Promise.reject(new CrocheError('invalid_response_format', 'The response format must be JSON serializable.')); }
|
|
468
|
+
const cancel = this.cancelFor(options.signal);
|
|
469
|
+
const onEvent = options.onEvent;
|
|
470
|
+
// Called now, not later: the Core reserves the turn before send() returns.
|
|
471
|
+
let sent: Promise<string>;
|
|
472
|
+
// Transitional (S1): the turn-result form until S2 moves the SDK to the receipt `send`.
|
|
473
|
+
try { sent = this.core.sendForResult(text ?? 'null', onEvent ? (event: string) => observer(onEvent, JSON.parse(event)) : undefined, cancel, format); }
|
|
474
|
+
catch (error) { return settle(Promise.reject(error)); }
|
|
475
|
+
return settle(sent);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
sync(): Promise<void> { return this.run('sync'); }
|
|
479
|
+
/**
|
|
480
|
+
* One round of background upkeep: deliver the outbox of call reports, then sync balances,
|
|
481
|
+
* policy and the model key. The Core does work only when some is due and backs off after a
|
|
482
|
+
* failure. It runs by itself after each turn and on a timer (backgroundSync, default on);
|
|
483
|
+
* browsers also call it on a visible foreground return unless backgroundSync is false.
|
|
484
|
+
* Node has no foreground hook. It never delays a turn: a send takes over
|
|
485
|
+
* while it waits on Cloud.
|
|
486
|
+
*/
|
|
487
|
+
maintain(options: { force?: boolean } = {}): Promise<MaintenanceResult> {
|
|
488
|
+
this.checkOpen();
|
|
489
|
+
return settle(this.core.maintain(options.force === true));
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Delivers the agent's scheduled notes that are due (`crocheTools.schedule`), as one turn whose
|
|
493
|
+
* message holds one schedule channel per note. Never before a note's time, best effort after
|
|
494
|
+
* it: call it when the app returns to the foreground. Nothing due: no turn and no cost.
|
|
495
|
+
* While the Runtime is open and holds its store's lock, a timer calls it at the earliest
|
|
496
|
+
* note's time, and at open for notes already due.
|
|
497
|
+
*/
|
|
498
|
+
deliverDue(): Promise<DeliverDueResult> {
|
|
499
|
+
this.checkOpen();
|
|
500
|
+
return settle(this.core.deliverDue());
|
|
501
|
+
}
|
|
502
|
+
/** The agent's pending scheduled notes. */
|
|
503
|
+
schedules(): ScheduleList {
|
|
504
|
+
this.checkOpen();
|
|
505
|
+
try { return JSON.parse(this.core.schedules()) as ScheduleList; } catch (error) { return rethrow(error); }
|
|
506
|
+
}
|
|
507
|
+
flush(): Promise<void> { return this.run('flush'); }
|
|
508
|
+
clearHistory(): Promise<void> { return this.ordered(undefined, () => this.run('clear_history')); }
|
|
509
|
+
/** Stops the running turn only: messages sent while it ran still go, together, as the next turn
|
|
510
|
+
* (a send's own `signal` drops just that send while it is held; once its turn has started, the
|
|
511
|
+
* turn stops, for every send it carries). */
|
|
512
|
+
cancel(): void { if (!this.core.isClosed()) void this.core.cancelTurn().catch(() => {}); } // stops at the call
|
|
513
|
+
/** Drops the messages held behind the running turn (each send ends `cancelled`); returns how many. */
|
|
514
|
+
clearQueued(): Promise<number> {
|
|
515
|
+
return this.ordered(undefined, async () => (this.core.isClosed() ? 0 : Number(await this.core.clearQueued())));
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** When the Runtime next wants upkeep, in epoch ms (the same unit as the `clock` option), or null.
|
|
519
|
+
* With an injected clock, call maintain() once clock() reaches it. */
|
|
520
|
+
wakeAt(): number | null { return this.core.wakeAt() ?? null; }
|
|
521
|
+
|
|
522
|
+
/** The Core projection fence joins its synchronous listener, not buffered SDK/UI consumers.
|
|
523
|
+
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
524
|
+
* wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
|
|
525
|
+
async close(): Promise<void> {
|
|
526
|
+
this.removeForegroundListener?.();
|
|
527
|
+
this.removeForegroundListener = undefined;
|
|
528
|
+
if (this.wakeTimer) clearTimeout(this.wakeTimer);
|
|
529
|
+
this.wakeTimer = undefined;
|
|
530
|
+
this.ready = false;
|
|
531
|
+
this.clearScheduleTimer();
|
|
532
|
+
await held(this.core.close());
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private now(): number { try { return Date.parse(hostNow(this.options.clock)); } catch { return Number.NaN; } }
|
|
536
|
+
/** Browsers have foreground transitions; Node has none. Core owns due/backoff decisions. */
|
|
537
|
+
private watchForeground(interval: number) {
|
|
538
|
+
if (this.options.backgroundSync === false || typeof document === 'undefined') return;
|
|
539
|
+
const page = document;
|
|
540
|
+
const visible = () => {
|
|
541
|
+
if (page.visibilityState !== 'visible' || !this.ready || this.foregroundMaintaining) return;
|
|
542
|
+
const now = this.now();
|
|
543
|
+
if (this.lastForegroundAt !== undefined && now >= this.lastForegroundAt && now - this.lastForegroundAt < interval) return;
|
|
544
|
+
this.lastForegroundAt = now;
|
|
545
|
+
this.foregroundMaintaining = true;
|
|
546
|
+
try {
|
|
547
|
+
void this.maintain().catch(() => {}).finally(() => { this.foregroundMaintaining = false; });
|
|
548
|
+
} catch { this.foregroundMaintaining = false; /* closed meanwhile */ }
|
|
549
|
+
};
|
|
550
|
+
page.addEventListener('visibilitychange', visible);
|
|
551
|
+
this.removeForegroundListener = () => page.removeEventListener('visibilitychange', visible);
|
|
552
|
+
}
|
|
553
|
+
private clearScheduleTimer() {
|
|
554
|
+
if (this.scheduleTimer) clearTimeout(this.scheduleTimer);
|
|
555
|
+
this.scheduleTimer = undefined;
|
|
556
|
+
}
|
|
557
|
+
/** One timer, at the earliest pending note: never before its time (a clamped step that ends
|
|
558
|
+
* early re-arms instead of delivering), best effort after. Re-armed at each schedule effect. */
|
|
559
|
+
private armSchedule() {
|
|
560
|
+
this.clearScheduleTimer();
|
|
561
|
+
if (!this.ready || !this.lockHeld || this.scheduleEntries.length === 0) return;
|
|
562
|
+
const earliest = Math.min(...this.scheduleEntries.map(entry => Date.parse(entry.at)));
|
|
563
|
+
const now = this.now();
|
|
564
|
+
if (!Number.isFinite(earliest) || !Number.isFinite(now)) return;
|
|
565
|
+
const delay = Math.min(Math.max(0, earliest - now), SCHEDULE_TIMER_MAX_MS);
|
|
566
|
+
this.scheduleTimer = setTimeout(() => {
|
|
567
|
+
this.scheduleTimer = undefined;
|
|
568
|
+
if (!(this.now() >= earliest)) { this.armSchedule(); return; }
|
|
569
|
+
// A delivery changes the set, and its effect re-arms the timer.
|
|
570
|
+
try { void this.deliverDue().catch(() => {}); } catch { /* closed meanwhile */ }
|
|
571
|
+
}, delay);
|
|
572
|
+
// A pending note never keeps a Node process alive (as the upkeep timer does not).
|
|
573
|
+
(this.scheduleTimer as { unref?: () => void }).unref?.();
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
private run(command: string): Promise<void> {
|
|
577
|
+
this.checkOpen();
|
|
578
|
+
return settle(this.core.run(command), () => undefined);
|
|
579
|
+
}
|
|
580
|
+
private adjust(amount: number, absolute: boolean, id?: string): Promise<BudgetAdjustment | DeferredWrite> {
|
|
581
|
+
this.checkOpen();
|
|
582
|
+
return settleWrite(this.core.adjustBudget(amount, absolute, id));
|
|
583
|
+
}
|
|
584
|
+
private memoryRead(op: 'list' | 'export'): unknown {
|
|
585
|
+
return call(() => JSON.parse(this.core.memoryRead(op)));
|
|
586
|
+
}
|
|
587
|
+
private inspect(): Inspection {
|
|
588
|
+
return call(() => JSON.parse(this.core.inspect()) as Inspection);
|
|
589
|
+
}
|
|
590
|
+
private checkOpen() {
|
|
591
|
+
call(() => this.core.checkOpen());
|
|
592
|
+
}
|
|
593
|
+
private cancelFor(signal?: AbortSignal): WasmCancel {
|
|
594
|
+
const cancel = new (core().WasmCancel)();
|
|
595
|
+
if (!signal) return cancel;
|
|
596
|
+
if (signal.aborted) cancel.cancel();
|
|
597
|
+
else signal.addEventListener('abort', () => cancel.cancel(), { once: true });
|
|
598
|
+
return cancel;
|
|
599
|
+
}
|
|
600
|
+
private signalFor(cancel: WasmCancel): AbortSignal {
|
|
601
|
+
const controller = new AbortController();
|
|
602
|
+
cancel.onCancel(() => controller.abort());
|
|
603
|
+
return controller.signal;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** The PAL for web and Node. Everything else is the Core's. */
|
|
607
|
+
private host() {
|
|
608
|
+
const storage = this.options.storage;
|
|
609
|
+
const secretStorage = this.secretStorage;
|
|
610
|
+
const identity = storage.ownershipIdentity ?? storage;
|
|
611
|
+
// The turn archive (F20): present only when the storage has one; without these calls the
|
|
612
|
+
// Core answers `archive_unavailable` itself and nothing else changes (F20.6).
|
|
613
|
+
const archive = storage.archive;
|
|
614
|
+
const archiveCalls = archive ? {
|
|
615
|
+
archiveAppend: (key: string, n: number, record: string, maxBytes: number) => archiveAppend(archive, key, n, record, maxBytes),
|
|
616
|
+
archiveRead: async (key: string, from: number, to: number) => JSON.stringify(await archiveRead(archive, key, from, to)),
|
|
617
|
+
archiveClear: (key: string, from: number | null, to: number | null) => archiveClear(archive, key, from, to),
|
|
618
|
+
} : {};
|
|
619
|
+
// The message log (S1, rev 4 §17.13): in lines, in entries `log<NNNNNN>` apart from the
|
|
620
|
+
// archive's, when the storage appends lines; otherwise in keyed items through read/write.
|
|
621
|
+
const logCalls = archive ? {
|
|
622
|
+
logAppendLine: (key: string, entry: string, line: string) => archive.appendLine(key, entry, line),
|
|
623
|
+
logReadLines: async (key: string, entry: string) => JSON.stringify(await archive.readLines(key, entry)),
|
|
624
|
+
logReplaceLines: (key: string, entry: string, lines: string) => archive.replaceLines(key, entry, JSON.parse(lines) as string[]),
|
|
625
|
+
logRemove: (key: string, entry: string) => archive.remove(key, entry),
|
|
626
|
+
logEntries: async (key: string) => JSON.stringify((await archive.entries(key, 'log')).map(e => e.entry).filter(e => /^log\d{6}$/.test(e))),
|
|
627
|
+
} : {};
|
|
628
|
+
return {
|
|
629
|
+
...archiveCalls,
|
|
630
|
+
...logCalls,
|
|
631
|
+
http: (request: HttpRequest, sink: WasmSink, cancel: WasmCancel) => this.http(request, sink, cancel),
|
|
632
|
+
read: async (key: string) => storage.getItem(key),
|
|
633
|
+
write: async (key: string, value: string) => storage.setItem(key, value),
|
|
634
|
+
readSecret: async (key: string) => secretStorage.getItem(key),
|
|
635
|
+
writeSecret: async (key: string, value: string) => secretStorage.setItem(key, value),
|
|
636
|
+
remove: async (key: string) => storage.removeItem(key),
|
|
637
|
+
removeSecret: async (key: string) => secretStorage.removeItem(key),
|
|
638
|
+
lock: (key: string) => this.acquireLock(key),
|
|
639
|
+
unlock: async () => { await this.releaseLock?.(); this.releaseLock = undefined; },
|
|
640
|
+
storeIdentity: () => {
|
|
641
|
+
let id = storeIds.get(identity);
|
|
642
|
+
if (!id) { id = `store_${++storeIdentities}`; storeIds.set(identity, id); }
|
|
643
|
+
return id;
|
|
644
|
+
},
|
|
645
|
+
tool: (invocation: string, cancel: WasmCancel) => this.tool(invocation, cancel),
|
|
646
|
+
sleep: (ms: number) => new Promise<void>(resolve => {
|
|
647
|
+
const timer = setTimeout(resolve, ms);
|
|
648
|
+
(timer as { unref?: () => void }).unref?.();
|
|
649
|
+
}),
|
|
650
|
+
// A host function called from the Core must not throw: an invalid clock becomes an
|
|
651
|
+
// invalid time, which the Core refuses.
|
|
652
|
+
nowMs: () => { try { return Date.parse(hostNow(this.options.clock)); } catch { return Number.NaN; } },
|
|
653
|
+
utcOffsetMinutes: (atMs: number) => localOffsetMinutes(new Date(atMs), this.options.timeZone),
|
|
654
|
+
random: () => { try { return coreNonce(); } catch { return ''; } },
|
|
655
|
+
wake: (atMs: number | null) => {
|
|
656
|
+
if (this.wakeTimer) clearTimeout(this.wakeTimer);
|
|
657
|
+
this.wakeTimer = undefined;
|
|
658
|
+
if (atMs === null) return;
|
|
659
|
+
this.wakeTimer = setTimeout(() => { this.wakeTimer = undefined; void this.core?.tick().catch(() => {}); }, Math.max(0, atMs - Date.now()));
|
|
660
|
+
(this.wakeTimer as { unref?: () => void }).unref?.();
|
|
661
|
+
},
|
|
662
|
+
// The whole pending set, after each durable change and at open. Without a store lock no
|
|
663
|
+
// timer is armed (the app calls deliverDue() itself), and the Core reports
|
|
664
|
+
// schedule.degraded {reason: 'no_lock'}.
|
|
665
|
+
schedule: (entries: string) => {
|
|
666
|
+
const list = JSON.parse(entries) as Array<{ id: string; at: string }>;
|
|
667
|
+
this.scheduleEntries = Array.isArray(list) ? list : [];
|
|
668
|
+
this.armSchedule();
|
|
669
|
+
if (!this.lockHeld && this.scheduleEntries.length > 0) {
|
|
670
|
+
throw new CrocheError('no_lock', 'This store has no lock (no storage acquireLock and no Web Locks): scheduled notes are delivered only when the app calls deliverDue().');
|
|
671
|
+
}
|
|
672
|
+
},
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
private async http(request: HttpRequest, sink: WasmSink, cancel: WasmCancel): Promise<void> {
|
|
677
|
+
const signal = this.signalFor(cancel);
|
|
678
|
+
const response = await this.transport(request.url, {
|
|
679
|
+
method: request.method, headers: Object.fromEntries(request.headers), body: request.body,
|
|
680
|
+
signal, credentials: 'omit', redirect: 'error',
|
|
681
|
+
});
|
|
682
|
+
sink.head(response.status, [...response.headers.entries()]);
|
|
683
|
+
if (!response.body?.getReader) {
|
|
684
|
+
// Some native fetch adapters expose text() without a ReadableStream.
|
|
685
|
+
sink.chunk(new TextEncoder().encode(await response.text()));
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
const reader = response.body.getReader();
|
|
689
|
+
try {
|
|
690
|
+
for (;;) {
|
|
691
|
+
const part = await reader.read();
|
|
692
|
+
if (part.done) return;
|
|
693
|
+
if (!sink.chunk(part.value)) { await reader.cancel().catch(() => {}); throw new CrocheError('invalid_response', 'The response exceeds its bound.'); }
|
|
694
|
+
}
|
|
695
|
+
} finally { reader.releaseLock?.(); }
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
private async tool(text: string, cancel: WasmCancel): Promise<string | { value: string; images: unknown }> {
|
|
699
|
+
const invocation = JSON.parse(text) as { tool: string; command?: string; key: string; args: JsonValue; context: CoreObject };
|
|
700
|
+
const binding = this.bindings.get(invocation.tool);
|
|
701
|
+
// 'tool_not_dispatched': no handler ran, so the Core may tell the model the tool is gone.
|
|
702
|
+
if (!binding) throw new CrocheError('tool_not_dispatched', 'The application changed this Tool before its callback started.');
|
|
703
|
+
if (cancel.isCancelled()) throw new CrocheError('cancelled', 'The operation was cancelled before dispatch.');
|
|
704
|
+
let value: unknown;
|
|
705
|
+
try {
|
|
706
|
+
value = await binding.execute({
|
|
707
|
+
tool: invocation.tool, ...(invocation.command ? { command: invocation.command } : {}), key: invocation.key, args: invocation.args,
|
|
708
|
+
} as Parameters<RuntimeTool['execute']>[0], { ...invocation.context, signal: this.signalFor(cancel) } as unknown as Parameters<RuntimeTool['execute']>[1]);
|
|
709
|
+
} catch (error) {
|
|
710
|
+
throw handlerError(error);
|
|
711
|
+
}
|
|
712
|
+
// The handler ran: from here on, whatever it returned is read once, inside this guard. A
|
|
713
|
+
// result with images (`toolResult`) goes as its value and its images, beside each other; a
|
|
714
|
+
// plain value is never looked inside (H3). Anything unreadable or malformed (a throwing
|
|
715
|
+
// getter, a non-JSON value, images that are not a list) fails this call alone with our own
|
|
716
|
+
// `invalid_tool_result`: never the app's error, which could claim the call never ran
|
|
717
|
+
// (Atlas, #351 P1-2; H1's provenance rule).
|
|
718
|
+
try {
|
|
719
|
+
if (!isToolResult(value)) return JSON.stringify(serializable(value));
|
|
720
|
+
const { value: given, images, imageResolution } = value;
|
|
721
|
+
const json = JSON.stringify(serializable(given));
|
|
722
|
+
if (images === undefined || images === null) return { value: json, images: [] };
|
|
723
|
+
if (!Array.isArray(images)) throw new Error('not a list');
|
|
724
|
+
// A JSON copy of the list, taken once: what is prepared and sent is what was read.
|
|
725
|
+
const copied = JSON.parse(JSON.stringify(images)) as InputImage[];
|
|
726
|
+
const resolution = imageResolution === 'high' || imageResolution === 'standard' ? imageResolution : undefined;
|
|
727
|
+
return { value: json, images: await Promise.all(copied.map(image => prepareImage(image, resolution, this.codec))) };
|
|
728
|
+
} catch {
|
|
729
|
+
throw new CrocheError('invalid_tool_result', 'The Tool callback did not return a JSON value with valid images. Its effects may have completed.');
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
private async acquireLock(key: string) {
|
|
734
|
+
const storage = this.options.storage;
|
|
735
|
+
if (storage.acquireLock) {
|
|
736
|
+
const release = await storage.acquireLock(key);
|
|
737
|
+
this.releaseLock = () => { this.lockHeld = false; return release(); };
|
|
738
|
+
this.lockHeld = true;
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const locks = globalThis.navigator?.locks;
|
|
742
|
+
if (!locks) return;
|
|
743
|
+
await new Promise<void>((resolve, reject) => {
|
|
744
|
+
void locks.request(key, { ifAvailable: true }, async lock => {
|
|
745
|
+
if (!lock) { reject(new CrocheError('store_busy', 'This Runtime store is already open in another tab.')); return; }
|
|
746
|
+
await new Promise<void>(release => { this.releaseLock = () => { this.lockHeld = false; release(); }; this.lockHeld = true; resolve(); });
|
|
747
|
+
}).catch(reject);
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
}
|