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