@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.
Files changed (105) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +1184 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/dist/archive.d.ts +47 -0
  5. package/dist/archive.js +217 -0
  6. package/dist/atomic-replace.d.ts +18 -0
  7. package/dist/atomic-replace.js +39 -0
  8. package/dist/commands.d.ts +56 -0
  9. package/dist/commands.js +1 -0
  10. package/dist/control.d.ts +62 -0
  11. package/dist/control.js +269 -0
  12. package/dist/core-abi.d.ts +110 -0
  13. package/dist/core-abi.js +1 -0
  14. package/dist/core-bindgen.d.ts +413 -0
  15. package/dist/core-bindgen.js +1533 -0
  16. package/dist/core-runtime.d.ts +214 -0
  17. package/dist/core-runtime.js +837 -0
  18. package/dist/core-wasm-bytes.d.ts +4 -0
  19. package/dist/core-wasm-bytes.js +5 -0
  20. package/dist/core-wasm.d.ts +16 -0
  21. package/dist/core-wasm.js +63 -0
  22. package/dist/debug.d.ts +26 -0
  23. package/dist/debug.js +171 -0
  24. package/dist/file-lock.d.ts +46 -0
  25. package/dist/file-lock.js +300 -0
  26. package/dist/images.d.ts +53 -0
  27. package/dist/images.js +179 -0
  28. package/dist/index.d.ts +14 -0
  29. package/dist/index.js +9 -0
  30. package/dist/markers.d.ts +1 -0
  31. package/dist/markers.js +1 -0
  32. package/dist/node.d.ts +46 -0
  33. package/dist/node.js +281 -0
  34. package/dist/project-core.d.ts +79 -0
  35. package/dist/project-core.js +261 -0
  36. package/dist/project-session.d.ts +44 -0
  37. package/dist/project-session.js +143 -0
  38. package/dist/project-types.d.ts +97 -0
  39. package/dist/project-types.js +1 -0
  40. package/dist/project-wire.d.ts +19 -0
  41. package/dist/project-wire.js +39 -0
  42. package/dist/sse.d.ts +19 -0
  43. package/dist/sse.js +53 -0
  44. package/dist/storage.d.ts +24 -0
  45. package/dist/storage.js +32 -0
  46. package/dist/stream-branch.d.ts +47 -0
  47. package/dist/stream-branch.js +107 -0
  48. package/dist/stream-hub.d.ts +207 -0
  49. package/dist/stream-hub.js +210 -0
  50. package/dist/stream.d.ts +3 -0
  51. package/dist/stream.js +5 -0
  52. package/dist/types.d.ts +928 -0
  53. package/dist/types.js +8 -0
  54. package/dist/wiki.d.ts +15 -0
  55. package/dist/wiki.js +25 -0
  56. package/docs/CODING-AGENT.md +96 -0
  57. package/docs/DEBUGGER.md +230 -0
  58. package/docs/S2-IMPLEMENTATION.md +585 -0
  59. package/docs/SKILL.md +337 -0
  60. package/docs/skills/croche/agents/openai.yaml +4 -0
  61. package/docs/skills/croche/references/agents.md +78 -0
  62. package/docs/skills/croche/references/first-turn.md +74 -0
  63. package/docs/skills/croche/references/tools.md +43 -0
  64. package/docs/skills/croche-cli/SKILL.md +158 -0
  65. package/docs/skills/croche-cli/agents/openai.yaml +4 -0
  66. package/docs/skills/croche-cli/references/powershell.md +47 -0
  67. package/docs/skills/croche-config/SKILL.md +152 -0
  68. package/docs/skills/croche-config/agents/openai.yaml +4 -0
  69. package/docs/skills/croche-config/references/models.md +12 -0
  70. package/docs/skills/croche-platforms/SKILL.md +55 -0
  71. package/docs/skills/croche-platforms/agents/openai.yaml +4 -0
  72. package/docs/skills/croche-platforms/references/android.md +185 -0
  73. package/docs/skills/croche-platforms/references/ios.md +165 -0
  74. package/docs/skills/croche-platforms/references/react-native.md +50 -0
  75. package/docs/skills/croche-platforms/references/web-backend.md +58 -0
  76. package/docs/skills/croche-troubleshoot/SKILL.md +72 -0
  77. package/docs/skills/croche-troubleshoot/agents/openai.yaml +4 -0
  78. package/docs/skills/croche-troubleshoot/references/recovery.md +31 -0
  79. package/package.json +52 -4
  80. package/src/archive.ts +188 -0
  81. package/src/atomic-replace.ts +43 -0
  82. package/src/commands.ts +62 -0
  83. package/src/control.ts +179 -0
  84. package/src/core-abi.ts +52 -0
  85. package/src/core-bindgen.ts +1557 -0
  86. package/src/core-runtime.ts +750 -0
  87. package/src/core-wasm-bytes.ts +5 -0
  88. package/src/core-wasm.ts +57 -0
  89. package/src/debug.ts +160 -0
  90. package/src/file-lock.ts +269 -0
  91. package/src/images.ts +174 -0
  92. package/src/index.ts +15 -0
  93. package/src/markers.ts +1 -0
  94. package/src/node.ts +194 -0
  95. package/src/project-core.ts +231 -0
  96. package/src/project-session.ts +118 -0
  97. package/src/project-types.ts +77 -0
  98. package/src/project-wire.ts +39 -0
  99. package/src/sse.ts +57 -0
  100. package/src/storage.ts +30 -0
  101. package/src/stream-branch.ts +112 -0
  102. package/src/stream-hub.ts +249 -0
  103. package/src/stream.ts +7 -0
  104. package/src/types.ts +838 -0
  105. package/src/wiki.ts +25 -0
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ export { CrocheRuntime, DEFAULT_MODEL, SDK_VERSION } from './core-runtime.js';
2
+ export type { DeliverDueResult, ScheduleList } from './core-runtime.js';
3
+ export { MemoryStorage, WebStorage } from './storage.js';
4
+ export { IndexedDbArchive } from './archive.js';
5
+ export { parseMarkers } from './markers.js';
6
+ export { toolResult, STANDARD_MAX_SIDE } from './images.js';
7
+ export type { ToolResult, ImageCodec, OpenedImage } from './images.js';
8
+ export { wikiFromModules } from './wiki.js';
9
+ export * from './types.js';
10
+ export type { RuntimeCommand, CommandArgument, CommandInvocation, RuntimeToolMetadata } from './commands.js';
11
+ export { CORE_ABI_VERSION, CORE_WASM_SHA256 } from './core-wasm.js';
12
+ export {Croche, CrocheAgent} from './project-core.js';
13
+ export type {AgentEvent} from './project-core.js';
14
+ // Shared declarations for Project→Agent SDKs.
15
+ export type {AgentConfig, AgentOverride, AgentOptions, ProjectConfig, ReleasedConfig, ToolDeclaration, ToolHandler, AgentToolControls, ProjectToolContext, ProjectUsageEvent, OpenOptions, AgentActivity, AgentStateEvent} from './project-types.js';
package/src/markers.ts ADDED
@@ -0,0 +1 @@
1
+ export { parseCoreMarkers as parseMarkers } from './core-wasm.js';
package/src/node.ts ADDED
@@ -0,0 +1,194 @@
1
+ import { replaceFile } from './atomic-replace.js';
2
+ import { mkdir, open, readdir, readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import type { ArchiveRuntimeStorage, RuntimeStorage, WikiDocument } from './types.js';
6
+ import { CrocheError } from './types.js';
7
+ import { acquireFileLock } from './file-lock.js';
8
+
9
+ const owners = new Set<string>();
10
+
11
+ const ENTRY = /^[a-z0-9]+$/;
12
+ const STALE = /^archive\d{4}\.tmp-[0-9a-f-]+$/;
13
+ function entryPath(file: string, entry: string): string {
14
+ if (!ENTRY.test(entry)) throw new CrocheError('invalid_input', 'An archive entry name is [a-z0-9]+.');
15
+ return `${file}.${entry}`;
16
+ }
17
+
18
+ /**
19
+ * One process owns a directory. Values are private and replaced with atomic rename.
20
+ * The turn archive (F20) is files beside a store's own file: `<store file>.archive0001`, one per
21
+ * 100 turns, JSON lines. A torn last line (a crash mid-append) is never read, and the next
22
+ * append writes a newline first so it cannot swallow the next record. A segment is rewritten
23
+ * (a ranged clear) to a temporary beside it and renamed over it; the Runtime holds the store's
24
+ * lock (`acquireLock`) for its whole life, so every archive call runs under it.
25
+ *
26
+ * One owner per directory and key, across processes: lock records `<key hash>.lock.<n>` beside
27
+ * the value, each published whole and exclusively, holding the owner's pid (see file-lock.ts). A
28
+ * second process gets `store_busy`. A lock left by a process that died is taken over at the next
29
+ * open, never because of its age.
30
+ */
31
+ export class FileStorage implements RuntimeStorage {
32
+ /**
33
+ * The locks this instance holds, by store key: each write first checks they are still its own.
34
+ * "Each write" includes the turn archive: an append, a segment rewrite's rename, and a segment's
35
+ * deletion are each fenced at the point they change the file.
36
+ */
37
+ private readonly fences = new Map<string, () => Promise<void>>();
38
+ constructor(private readonly directory: string) {}
39
+ /** Throws `store_busy` if a lock this instance holds is no longer its own. */
40
+ private async fence(key: string) {
41
+ // A backend serves many stores. A released project/other-agent lock must not
42
+ // fence this write; sidecars are protected by their own root namespace.
43
+ let owner: string | undefined;
44
+ for (const root of this.fences.keys()) {
45
+ if ((key === root || key.startsWith(`${root}.`)) && (owner === undefined || root.length > owner.length)) owner = root;
46
+ }
47
+ if (owner !== undefined) await this.fences.get(owner)!();
48
+ // Keep the existing fence for arbitrary application keys that are not
49
+ // sidecars of a named namespace.
50
+ else for (const verify of this.fences.values()) await verify();
51
+ }
52
+ private path(key: string) { return join(this.directory, `${createHash('sha256').update(key).digest('hex')}.json`); }
53
+ readonly archive: ArchiveRuntimeStorage = {
54
+ appendLine: async (key, entry, line) => {
55
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
56
+ const file = await open(entryPath(this.path(key), entry), 'a+', 0o600);
57
+ try {
58
+ const { size } = await file.stat();
59
+ let prefix = '';
60
+ if (size > 0) {
61
+ const last = Buffer.alloc(1);
62
+ await file.read(last, 0, 1, size - 1);
63
+ if (last[0] !== 0x0a) prefix = '\n';
64
+ }
65
+ await this.fence(key);
66
+ await file.appendFile(`${prefix}${line}\n`, 'utf8');
67
+ await file.sync();
68
+ } finally { await file.close(); }
69
+ },
70
+ readLines: async (key, entry) => {
71
+ let text: string;
72
+ try { text = await readFile(entryPath(this.path(key), entry), 'utf8'); }
73
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
74
+ const lines = text.split('\n');
75
+ // The piece after the last newline is a torn line ('' when the file ends cleanly).
76
+ lines.pop();
77
+ return lines.filter(line => line.length > 0);
78
+ },
79
+ replaceLines: async (key, entry, lines) => {
80
+ const target = entryPath(this.path(key), entry);
81
+ if (!lines.length) { await this.archive.remove(key, entry); return; }
82
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
83
+ // `<segment>.tmp-<nonce>`: '.' and '-' are outside the entry rule, so a temporary is never
84
+ // an entry (not a segment, not `held` or `lock`), and `entries` never lists one.
85
+ const temporary = `${target}.tmp-${randomUUID()}`;
86
+ const file = await open(temporary, 'w', 0o600);
87
+ try {
88
+ await file.writeFile(lines.map(line => `${line}\n`).join(''), 'utf8');
89
+ await file.sync();
90
+ } finally { await file.close(); }
91
+ try { await this.fence(key); await this.commitEntry(temporary, target); }
92
+ catch (error) { await unlink(temporary).catch(() => {}); throw error; }
93
+ },
94
+ remove: async (key, entry) => {
95
+ await this.fence(key);
96
+ try { await unlink(entryPath(this.path(key), entry)); }
97
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
98
+ },
99
+ entries: async (key, prefix) => {
100
+ const base = `${createHash('sha256').update(key).digest('hex')}.json.`;
101
+ let names: string[];
102
+ try { names = await readdir(this.directory); }
103
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
104
+ const out: Array<{ entry: string; bytes: number }> = [];
105
+ for (const name of names) {
106
+ const entry = name.slice(base.length);
107
+ if (!name.startsWith(base) || !entry.startsWith(prefix) || !ENTRY.test(entry)) continue;
108
+ try { out.push({ entry, bytes: (await stat(join(this.directory, name))).size }); }
109
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
110
+ }
111
+ return out;
112
+ },
113
+ };
114
+ /**
115
+ * The step that makes a segment rewrite visible: one rename over the old file. A crash before
116
+ * it leaves the old segment whole and a stale temporary, which the next open deletes. Like a
117
+ * value's replacement, a briefly blocked rename is retried on Windows (`replaceFile`).
118
+ */
119
+ protected async commitEntry(temporary: string, target: string) {
120
+ await replaceFile(temporary, target);
121
+ }
122
+ async acquireLock(key: string) {
123
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
124
+ const identity = join(await realpath(this.directory), `${createHash('sha256').update(key).digest('hex')}.json`);
125
+ if (owners.has(identity)) throw new CrocheError('store_busy', 'This file namespace already has an owner in this process.');
126
+ owners.add(identity);
127
+ const path = identity.replace(/\.json$/, '.lock');
128
+ let lock;
129
+ try { lock = await acquireFileLock(path, () => { owners.delete(identity); this.fences.delete(key); }); }
130
+ catch (error) { owners.delete(identity); throw error; }
131
+ // Only the owner may remove a crash's segment temporaries: another process's may be live.
132
+ try { await this.removeStaleTemporaries(key); }
133
+ catch (error) { await lock.release(); throw error; }
134
+ this.fences.set(key, lock.verify);
135
+ return lock.release;
136
+ }
137
+ /** Segment rewrites a crash interrupted (`<segment>.tmp-<nonce>`): deleted, as the owner opens. */
138
+ private async removeStaleTemporaries(key: string) {
139
+ const base = `${createHash('sha256').update(key).digest('hex')}.json.`;
140
+ let names: string[];
141
+ try { names = await readdir(this.directory); }
142
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; }
143
+ for (const name of names) {
144
+ if (!name.startsWith(base) || !STALE.test(name.slice(base.length))) continue;
145
+ try { await unlink(join(this.directory, name)); }
146
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
147
+ }
148
+ }
149
+ async getItem(key: string) {
150
+ try { return await readFile(this.path(key), 'utf8'); }
151
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
152
+ }
153
+ async setItem(key: string, value: string) {
154
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
155
+ const target = this.path(key);
156
+ const temporary = `${target}.${randomUUID()}.tmp`;
157
+ await writeFile(temporary, value, { mode: 0o600 });
158
+ try { await this.fence(key); await replaceFile(temporary, target); }
159
+ catch (error) { await unlink(temporary).catch(() => {}); throw error; }
160
+ }
161
+ async removeItem(key: string) {
162
+ await this.fence(key);
163
+ try { await unlink(this.path(key)); }
164
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
165
+ }
166
+ }
167
+
168
+ /** The wiki holds at most this many documents; a folder with more is refused while it is read. */
169
+ const WIKI_MAX_DOCUMENTS = 2000;
170
+
171
+ /**
172
+ * The `.md` files under `dir` as wiki documents, paths relative to it with `/` (`menu/stew.md`),
173
+ * in name order. Subfolders are read; symbolic links and other files are skipped, as the native
174
+ * SDKs' loaders do. Pass the result as `wiki: { docs }` or to `runtime.wiki.set`.
175
+ */
176
+ export async function wikiFromDirectory(dir: string): Promise<WikiDocument[]> {
177
+ const out: WikiDocument[] = [];
178
+ async function walk(at: string, prefix: string): Promise<void> {
179
+ let entries;
180
+ try { entries = await readdir(at, { withFileTypes: true }); }
181
+ catch (error) { throw new CrocheError('invalid_wiki', `${at}: ${(error as Error).message}`); }
182
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
183
+ for (const entry of entries) {
184
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
185
+ if (entry.isDirectory()) await walk(join(at, entry.name), path);
186
+ else if (entry.isFile() && entry.name.endsWith('.md')) {
187
+ if (out.length >= WIKI_MAX_DOCUMENTS) throw new CrocheError('invalid_wiki', `The wiki holds at most ${WIKI_MAX_DOCUMENTS} documents`);
188
+ out.push({ path, markdown: await readFile(join(at, entry.name), 'utf8') });
189
+ }
190
+ }
191
+ }
192
+ await walk(dir, '');
193
+ return out;
194
+ }
@@ -0,0 +1,231 @@
1
+ import {core} from './core-wasm.js';
2
+ import {CrocheRuntime, projectPal, receiptSend} from './core-runtime.js';
3
+ import {CrocheError} from './types.js';
4
+ import type {AgentOptions, AgentToolControls, OpenOptions} from './project-types.js';
5
+ import {deleteWire, projectWire} from './project-wire.js';
6
+ import {StreamHub, type CoreStreamPort, type RequestObservation, type StreamSelectOptions} from './stream-hub.js';
7
+ import type {SendInput, SendOptions, JsonValue, RuntimeMemoryApi} from './types.js';
8
+
9
+ type WasmProject = InstanceType<ReturnType<typeof core>['WasmProject']>;
10
+ type WasmAgent = InstanceType<ReturnType<typeof core>['WasmRuntime']>;
11
+ type Pal = ReturnType<typeof projectPal>;
12
+
13
+ function rethrow(error: unknown): never {
14
+ if (error instanceof CrocheError) throw error;
15
+ const value = error as {code?: unknown; message?: unknown} | null;
16
+ if (value && typeof value.code === 'string') throw new CrocheError(value.code,
17
+ typeof value.message === 'string' ? value.message : 'The Core operation failed.');
18
+ throw new CrocheError('core_error', 'The shared Core could not complete this operation.');
19
+ }
20
+ function call<T>(operation: () => T): T { try { return operation(); } catch (error) { return rethrow(error); } }
21
+ async function held<T>(operation: () => Promise<T>): Promise<T> {
22
+ const alive = setInterval(() => {}, 0x7fffffff);
23
+ try { return await operation(); } catch (error) { return rethrow(error); }
24
+ finally { clearInterval(alive); }
25
+ }
26
+ function json(value: unknown): string {
27
+ try {
28
+ return JSON.stringify(value, (_key, item) => {
29
+ if (typeof item === 'number' && !Number.isFinite(item)) throw new Error('Non-finite number');
30
+ if (['function', 'symbol', 'bigint'].includes(typeof item)) throw new Error('Non-JSON value');
31
+ return item;
32
+ });
33
+ } catch { throw new CrocheError('invalid_configuration', 'Configuration must be JSON serializable.'); }
34
+ }
35
+ function observe<T>(callback: ((event: T) => void) | undefined, event: T) {
36
+ try { void Promise.resolve(callback?.(event)).catch(() => {}); } catch { /* Host observer isolation. */ }
37
+ }
38
+
39
+ /** Events are owned and projected by Core; unknown event fields remain intact. */
40
+ export type AgentEvent = {type: string; [key: string]: JsonValue | undefined};
41
+ let agentFromCore: (handle: WasmAgent, host: CrocheRuntime) => CrocheAgent;
42
+ export class CrocheAgent implements AgentToolControls {
43
+ /** The same memory API as this agent's host Runtime. */
44
+ get memory(): RuntimeMemoryApi { return this.host.memory; }
45
+
46
+ private closing?: Promise<void>;
47
+ private ended = false;
48
+ private hub!: StreamHub<AgentEvent>;
49
+ private handle!: WasmAgent;
50
+ private host!: CrocheRuntime;
51
+ private constructor() {}
52
+ private initialize(handle: WasmAgent, host: CrocheRuntime) {
53
+ this.handle = handle;
54
+ this.host = host;
55
+ const port: CoreStreamPort<AgentEvent> = {
56
+ observe: (onEvent, onEnd) => {
57
+ call(() => handle.observe((event: string) => onEvent(JSON.parse(event) as RequestObservation),
58
+ (error: string) => onEnd(JSON.parse(error))));
59
+ return {close: () => call(() => handle.unobserve())};
60
+ },
61
+ select: (options, onEvent) => {
62
+ const id = call(() => handle.select(json(options), (event: string) => onEvent(JSON.parse(event))));
63
+ return {close: () => call(() => handle.closeProjection(id)),
64
+ history: options => held(() => handle.history(id, options.before, options.limit))};
65
+ },
66
+ send: (input, options) => host[receiptSend](input, options),
67
+ cancel: id => held(() => id === undefined ? handle.cancelTurn() : handle.cancel(id)),
68
+ readOutcome: async (id, from, captured) => JSON.parse(await held(() =>
69
+ handle.readOutcome(id, from, (event: string) => captured(JSON.parse(event))))),
70
+ };
71
+ this.hub = new StreamHub(port);
72
+ }
73
+ static { agentFromCore = (handle, host) => {
74
+ const agent = new CrocheAgent();
75
+ agent.initialize(handle, host);
76
+ return agent;
77
+ }; }
78
+ get id(): string { return call(() => this.handle.agentId()); }
79
+ get instance(): string | null { return call(() => this.handle.instance()) ?? null; }
80
+ get created(): boolean { return call(() => this.handle.created()); }
81
+ get name(): string | null { return call(() => this.handle.name()) ?? null; }
82
+ get mode(): string | null { return call(() => this.handle.mode()) ?? null; }
83
+ get visibleTools(): string[] | null {
84
+ return call(() => {
85
+ const names = this.handle.visibleTools();
86
+ return names == null ? null : JSON.parse(names) as string[];
87
+ });
88
+ }
89
+ setTools(visible: string[] | null): Promise<void> {
90
+ return held(() => this.handle.setTools(visible === null ? undefined : json(visible)));
91
+ }
92
+ setMode(mode: string | null): Promise<void> {
93
+ return held(() => this.handle.setMode(mode ?? undefined));
94
+ }
95
+ get closed(): boolean { return call(() => this.handle.isClosed()); }
96
+ get logId(): string { return call(() => this.handle.logId()); }
97
+ sync(): Promise<void> { return this.host.sync(); }
98
+ send(input: SendInput, options: Pick<SendOptions, 'signal' | 'responseFormat' | 'imageResolution'> = {}) {
99
+ // Image preparation is host-local; the actual receipt and observation are Core's.
100
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
101
+ if (Object.hasOwn(options, 'onEvent')) return Promise.reject(new CrocheError('invalid_input', 'Use agent.subscribe for events; send has no onEvent option.'));
102
+ try { return this.host[receiptSend](input, options); }
103
+ catch (error) { return Promise.reject(error); }
104
+ }
105
+ subscribe(options: StreamSelectOptions & {onEvent: (event: AgentEvent) => void | Promise<void>}) {
106
+ return this.hub.subscribe(options);
107
+ }
108
+ history(options: {before?: number; limit: number}) { return this.hub.history(options); }
109
+ /** Sends and waits until the input is final (with `wait: 'idle'`, until the agent is idle too). */
110
+ request(input: SendInput, options: Pick<SendOptions, 'signal' | 'responseFormat'> & {wait?: 'idle'} = {}) {
111
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
112
+ return this.hub.request(input, options);
113
+ }
114
+ /** Deletes the conversation; the app empties its list on the durable `cleared` event. */
115
+ clearHistory(): Promise<void> {
116
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
117
+ return this.host.clearHistory();
118
+ }
119
+ /** Cancels input `id`, or with no id stops the turn running now; resolves once the stop is saved. */
120
+ cancel(id?: string): Promise<void> {
121
+ if (this.ended) return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
122
+ return this.hub.cancel(id);
123
+ }
124
+ /** Closes the agent; the Core projection fence does not await buffered SDK/UI consumers.
125
+ * An app callback that waits for work on the closer's thread deadlocks under any
126
+ * wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
127
+ close(): Promise<void> {
128
+ return this.closing ??= (async () => {
129
+ this.ended = true;
130
+ try { await this.host.close(); } finally { this.hub.close(); }
131
+ })();
132
+ }
133
+ }
134
+
135
+ /** Core owns the census, config selection/overrides, record, ids, locks and lifecycle. */
136
+ export class Croche {
137
+ private readonly agents = new Map<string, CrocheAgent>();
138
+ private closing?: Promise<void>;
139
+ private handle!: WasmProject;
140
+ private pals!: Map<string, Pal>;
141
+ private constructor() {}
142
+
143
+ static async open(options: OpenOptions): Promise<Croche> {
144
+ if (['storageKey', 'identity'].some(key => Object.hasOwn(options, key))) {
145
+ throw new CrocheError('invalid_configuration', 'storageKey and identity overrides are not supported.');
146
+ }
147
+ if (options.serverKey !== undefined && typeof document !== 'undefined') {
148
+ throw new CrocheError('invalid_configuration', 'serverKey belongs on your backend, never in a browser.');
149
+ }
150
+ if (!options.storage || typeof options.storage.getItem !== 'function' || typeof options.storage.setItem !== 'function') {
151
+ throw new CrocheError('invalid_configuration', 'Atomic Runtime storage is required.');
152
+ }
153
+ const archive = options.storage.archive;
154
+ if (archive !== undefined && (!archive ||
155
+ ['appendLine', 'readLines', 'replaceLines', 'remove', 'entries'].some(key => typeof (archive as unknown as Record<string, unknown>)[key] !== 'function'))) {
156
+ throw new CrocheError('invalid_configuration', 'storage.archive needs appendLine, readLines, replaceLines, remove and entries.');
157
+ }
158
+ const language = options.language ?? (typeof document !== 'undefined' && typeof navigator !== 'undefined' ? navigator.language : undefined);
159
+ const owned = {...options, ...(language === undefined ? {} : {language}), handlers: {...options.handlers}};
160
+ if (Object.values(owned.handlers).some(handler => typeof handler !== 'function')) {
161
+ throw new CrocheError('invalid_configuration', 'Every handler must be a function.');
162
+ }
163
+ // Freeze the bundled data before awaiting the record; caller mutation cannot change
164
+ // later agent opens. Core, not this encoding, validates every schema/override field.
165
+ const wire = json(projectWire(owned));
166
+ const pals = new Map<string, Pal>();
167
+ let project!: Croche;
168
+ const factory = (agent: string) => {
169
+ // A new host whenever Core asks for one. A closed/reopened agent must not reuse
170
+ // a closed timer owner. Record PAL and default-agent PAL are separate requests.
171
+ const pal = projectPal(owned, () => project.user);
172
+ if (!agent.startsWith('["$gc",')) pals.set(agent, pal);
173
+ return pal.host;
174
+ };
175
+ const debug = owned.onDebugEvent ? (event: string) => observe(owned.onDebugEvent, JSON.parse(event)) : undefined;
176
+ const usage = owned.onUsage ? (event: string) => observe(owned.onUsage, {
177
+ ...JSON.parse(event), user: project.user, crocheUserId: project.crocheUserId,
178
+ }) : undefined;
179
+ const handle = await held(() => core().WasmProject.open(factory, wire, debug, usage) as Promise<WasmProject>);
180
+ project = new Croche();
181
+ project.handle = handle;
182
+ project.pals = pals;
183
+ return project;
184
+ }
185
+
186
+ /**
187
+ * Deletes stores on this device (R8): with `agent`, that agent's store for `user`, declared or
188
+ * not, including its instances; without, declared main stores and every registered instance
189
+ * for that user, including retired agents. All stores are locked first. Rejects `store_busy`
190
+ * when one is open, and then nothing is deleted. The project record is kept.
191
+ */
192
+ static async deleteStore(options: OpenOptions & {agent?: string}): Promise<void> {
193
+ if (!options.storage || typeof options.storage.getItem !== 'function' || typeof options.storage.setItem !== 'function') {
194
+ throw new CrocheError('invalid_configuration', 'Atomic Runtime storage is required.');
195
+ }
196
+ const factory = (_agent: string) => projectPal(options, () => options.user ?? null).host;
197
+ await held(() => core().WasmProject.deleteStore(factory, json(deleteWire(options))) as Promise<unknown>);
198
+ }
199
+
200
+ get user(): string | null { return call(() => this.handle.user()) ?? null; }
201
+ get installationId(): string | null { return call(() => this.handle.installationId()) ?? null; }
202
+ get crocheUserId(): string | null { return call(() => this.handle.crocheUserId()) ?? null; }
203
+ get agentIds(): readonly string[] { return call(() => JSON.parse(this.handle.agentIds()) as string[]); }
204
+
205
+ async agent(id?: string, options: AgentOptions = {}): Promise<CrocheAgent> {
206
+ // Core prunes its closed slots on open; release the corresponding JS handles and hosts too.
207
+ for (const [slot, agent] of this.agents) {
208
+ if (agent.closed) { this.agents.delete(slot); this.pals.delete(slot); }
209
+ }
210
+ // Always call Core, including cached agents: it validates override equality and closed
211
+ // state. The map only preserves the JS object's identity, never admission policy.
212
+ const handle = await held(() => this.handle.agentWithOptions(id, json(options)) as Promise<WasmAgent>);
213
+ const name = id ?? 'default';
214
+ const instance = call(() => handle.instance());
215
+ const slot = instance == null ? name : JSON.stringify([name, instance]);
216
+ const existing = this.agents.get(slot);
217
+ if (existing && !existing.closed) { handle.free(); return existing; }
218
+ const pal = this.pals.get(slot);
219
+ if (!pal) throw new CrocheError('core_error', 'Core opened an agent without requesting its host.');
220
+ const agent = agentFromCore(handle, pal.attach(handle));
221
+ this.agents.set(slot, agent);
222
+ return agent;
223
+ }
224
+
225
+ close(): Promise<void> {
226
+ return this.closing ??= (async () => {
227
+ try { await held(() => this.handle.close()); }
228
+ finally { await Promise.all([...this.agents.values()].map(agent => agent.close())); }
229
+ })();
230
+ }
231
+ }
@@ -0,0 +1,118 @@
1
+ import { CrocheError } from './types.js';
2
+ import type { AgentOverride, OpenOptions, ProjectConfig } from './project-types.js';
3
+
4
+ /** Target SDK surface. Not exported from the package until a real Core adapter is bound. */
5
+ export interface AgentSession { readonly id: string; readonly name: string | null; close(): Promise<void> }
6
+ export interface ProjectIdentity { crocheUserId: string | null; installationId: string | null }
7
+ /** Internal injection boundary, not a proposed Rust ABI. Core owns config/identity/storage. */
8
+ export interface ProjectDriver<A extends AgentSession> {
9
+ identity(): ProjectIdentity;
10
+ openAgent(id: string, override?: AgentOverride): Promise<A>;
11
+ close(): Promise<void>;
12
+ }
13
+ export interface ProjectFactoryPort<A extends AgentSession> {
14
+ open(options: OpenOptions): Promise<ProjectDriver<A>>;
15
+ deleteStore(options: OpenOptions & { agent?: string }): Promise<void>;
16
+ }
17
+ const invalid = (message: string) => new CrocheError('invalid_configuration', message);
18
+ function copy<T>(value: T): T {
19
+ try {
20
+ return JSON.parse(JSON.stringify(value, (_key, item) => {
21
+ if (typeof item === 'number' && !Number.isFinite(item)) throw invalid('Configuration contains a non-finite number.');
22
+ if (typeof item === 'function' || typeof item === 'symbol') throw invalid('Configuration cannot contain callbacks.');
23
+ return item;
24
+ }));
25
+ } catch { throw invalid('Configuration must be JSON serializable.'); }
26
+ }
27
+ /** Comparison only; not a hash, canonicalization contract or config resolver. */
28
+ function ordered(value: unknown): unknown {
29
+ if (Array.isArray(value)) return value.map(ordered);
30
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered((value as Record<string, unknown>)[key])]));
31
+ return value;
32
+ }
33
+ function bundled(options: OpenOptions): ProjectConfig {
34
+ return 'version' in options.config ? options.config.config : options.config;
35
+ }
36
+ function checkHandlers(config: unknown, handlers: OpenOptions['handlers'], declared = new Set<string>()): Set<string> {
37
+ if (!config || typeof config !== 'object') return declared;
38
+ const node = config as { tools?: { name: string }[]; languages?: Record<string, unknown>; agents?: Record<string, unknown>; modes?: Record<string, unknown> };
39
+ if (Array.isArray(node.tools)) for (const tool of node.tools) {
40
+ if (!tool || typeof tool.name !== 'string' || !Object.hasOwn(handlers ?? {}, tool.name) || typeof handlers?.[tool.name] !== 'function') throw invalid('Every tool declaration needs a registered handler.');
41
+ declared.add(tool.name);
42
+ }
43
+ for (const child of Object.values(node.languages ?? {})) checkHandlers(child, handlers, declared);
44
+ for (const child of Object.values(node.agents ?? {})) checkHandlers(child, handlers, declared);
45
+ for (const child of Object.values(node.modes ?? {})) checkHandlers(child, handlers, declared);
46
+ return declared;
47
+ }
48
+ function checkId(id: string, ids: Set<string>) {
49
+ if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(id) || !ids.has(id)) throw invalid('The agent id is not declared in the bundled config.');
50
+ }
51
+ type Entry<A> = { key: string; open: Promise<A>; closing?: Promise<void> };
52
+
53
+ /** Project lifecycle only: does not merge config, derive storage keys, mint ids or issue credit. */
54
+ export class ProjectSession<A extends AgentSession> {
55
+ private readonly agents = new Map<string, Entry<A>>();
56
+ private closing?: Promise<void>;
57
+ private closed = false;
58
+ private constructor(private readonly options: OpenOptions, private readonly driver: ProjectDriver<A>, private readonly ids: Set<string>) {}
59
+ static async open<A extends AgentSession>(options: OpenOptions, port: ProjectFactoryPort<A>): Promise<ProjectSession<A>> {
60
+ if (options.user !== undefined && (typeof options.user !== 'string' || options.user.length < 1 || options.user.length > 200)) throw invalid('user must be a string of 1 to 200 characters.');
61
+ if (options.serverKey !== undefined && options.user === undefined) throw invalid('Server opens require user.');
62
+ const language = options.language ?? (typeof document !== 'undefined' && typeof navigator !== 'undefined' ? navigator.language : undefined);
63
+ const owned = { ...options, ...(language === undefined ? {} : {language}), config: copy(options.config), handlers: { ...options.handlers } };
64
+ const declared = checkHandlers(bundled(owned), owned.handlers);
65
+ if (Object.keys(owned.handlers).some(name => !declared.has(name))) throw invalid('Every registered handler needs a tool declaration in the bundled config.');
66
+ const ids = new Set(['default', ...Object.keys(bundled(owned).agents ?? {})]);
67
+ for (const id of ids) checkId(id, ids);
68
+ return new ProjectSession(owned, await port.open(owned), ids);
69
+ }
70
+ get user(): string | null { return this.options.user ?? null; }
71
+ get crocheUserId(): string | null { return this.driver.identity().crocheUserId; }
72
+ get installationId(): string | null { return this.driver.identity().installationId; }
73
+ async agent(id = 'default', options: { config?: AgentOverride } = {}): Promise<A> {
74
+ if (this.closed) throw new CrocheError('closed', 'The project is closed.');
75
+ checkId(id, this.ids);
76
+ const override = options.config === undefined ? undefined : copy(options.config);
77
+ if (override && ('agents' in override || 'defaultLanguage' in override)) throw invalid('Code override cannot set agents or defaultLanguage.');
78
+ checkHandlers(override, this.options.handlers);
79
+ const key = JSON.stringify(ordered(override ?? {}));
80
+ const current = this.agents.get(id);
81
+ if (current) {
82
+ if (current.closing) { await current.closing; return this.agent(id, options); }
83
+ if (override !== undefined && current.key !== key) throw invalid('Agent is already open with another configuration.');
84
+ return current.open;
85
+ }
86
+ const entry: Entry<A> = { key, open: Promise.resolve().then(() => this.driver.openAgent(id, override)) };
87
+ this.agents.set(id, entry);
88
+ try {
89
+ const agent = await entry.open;
90
+ const close = agent.close.bind(agent);
91
+ let closing: Promise<void> | undefined;
92
+ agent.close = () => entry.closing ??= closing ??= (async () => {
93
+ try { await close(); }
94
+ finally { if (this.agents.get(id) === entry) this.agents.delete(id); }
95
+ })();
96
+ if (this.closed) { await agent.close(); throw new CrocheError('closed', 'The project closed while the agent opened.'); }
97
+ return agent;
98
+ } catch (error) {
99
+ if (this.agents.get(id) === entry) this.agents.delete(id);
100
+ throw error;
101
+ }
102
+ }
103
+ close(): Promise<void> {
104
+ return this.closing ??= (async () => {
105
+ this.closed = true;
106
+ const agents = await Promise.allSettled([...this.agents.values()].map(entry => entry.open));
107
+ const results = await Promise.allSettled(agents.flatMap(result => result.status === 'fulfilled' ? [result.value.close()] : []));
108
+ const cleanup = await Promise.allSettled([this.driver.close()]);
109
+ const failure = [...results, ...cleanup].find((result): result is PromiseRejectedResult => result.status === 'rejected');
110
+ if (failure) throw failure.reason;
111
+ })();
112
+ }
113
+ static async deleteStore<A extends AgentSession>(options: OpenOptions & { agent?: string }, port: ProjectFactoryPort<A>): Promise<void> {
114
+ // Core owns the all-declared-agent lock/delete transaction. Explicit ids may
115
+ // name a store no longer declared in this bundle; do not resolve or reject it here.
116
+ await port.deleteStore(options);
117
+ }
118
+ }
@@ -0,0 +1,77 @@
1
+ import type { RuntimeCommand, CommandInvocation } from './commands.js';
2
+ import type { ToolResult } from './images.js';
3
+ import type { AppOptions, HostOptions, JsonValue, RuntimeMemoryOptions, RuntimeUsageEvent, ToolContext, WikiOptions } from './types.js';
4
+
5
+ /** Replaceable declarations, never handler implementations. */
6
+ export interface ToolDeclaration { name: string; summary: string; commands: RuntimeCommand[] }
7
+ export type DeepPartial<T> = T extends readonly unknown[] ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;
8
+ export interface AgentConfig extends Pick<AppOptions, 'instructions' | 'markerGuide' | 'maxContextTokens' | 'maxOutputTokens' | 'maxIterations' | 'crocheTools' | 'heartbeat'> {
9
+ toolGuide?: string;
10
+ modes?: Record<string, {tools?: ToolDeclaration[]; toolGuide?: string}>;
11
+ tools?: ToolDeclaration[];
12
+ wiki?: WikiOptions;
13
+ memory?: RuntimeMemoryOptions;
14
+ model?: string;
15
+ /** Croche's level, mapped to each model's own setting; `default` sends none. */
16
+ reasoning?: 'default' | 'off' | 'low' | 'medium' | 'high';
17
+ /** The base configuration's language tag, default "en"; the sole project default. */
18
+ defaultLanguage?: string;
19
+ languages?: Record<string, AgentOverride>;
20
+ }
21
+ /** Only agents have names. A code override cannot introduce agents/defaultLanguage. */
22
+ export type AgentOverride = DeepPartial<Omit<AgentConfig, 'defaultLanguage'>> & { name?: string };
23
+ export interface ProjectConfig extends AgentConfig {
24
+ agents?: Record<string, AgentOverride>;
25
+ /** Shared instance storage budget, project level only. Integer 0..1 GiB; default 16 MiB. */
26
+ instances?: {maxBytes?: number};
27
+ }
28
+ /** A named instance opens or creates; fresh always generates a new key. */
29
+ export interface AgentOptions { instance?: string; fresh?: boolean; config?: AgentOverride }
30
+ export interface ReleasedConfig { version: number; revision: string; config: ProjectConfig }
31
+ /** Core-owned, in-memory controls; take effect at the next model call. */
32
+ export interface AgentToolControls {
33
+ readonly mode: string|null;
34
+ readonly visibleTools: string[]|null;
35
+ setTools(visible: string[]|null): Promise<void>;
36
+ setMode(mode: string|null): Promise<void>;
37
+ }
38
+ export interface ProjectToolContext extends Omit<ToolContext, 'userId' | 'accountLabel' | 'agentId'> {
39
+ agentId: string;
40
+ user: string | null;
41
+ crocheUserId: string | null;
42
+ causedBy: string[];
43
+ origin: 'app' | 'agent';
44
+ }
45
+ export type ToolHandler = (invocation: CommandInvocation, context: ProjectToolContext) => JsonValue | ToolResult | Promise<JsonValue | ToolResult>;
46
+ export interface ProjectUsageEvent extends RuntimeUsageEvent {
47
+ user: string | null;
48
+ crocheUserId: string | null;
49
+ /** Named or generated instance key; null for the main agent. */
50
+ instance: string | null;
51
+ }
52
+ /** Host options never enter a remotely replaceable config. No host-set install/store identity. */
53
+ export interface OpenOptions extends Pick<HostOptions,
54
+ 'cloudUrl' | 'projectKey' | 'storage' | 'secretStorage' | 'serverKey' | 'debugKey' |
55
+ 'timeZone' | 'onDebugEvent' | 'debugVisibility' | 'backgroundSync' | 'maintenanceIntervalMs' |
56
+ 'requestTimeoutMs' | 'maxPendingEvents' | 'archive' | 'imageCodec' | 'fetch' | 'clock' |
57
+ 'syncIntervalMs' | 'maintenanceBackoffMs' | 'streaming'> {
58
+ user?: string;
59
+ /** The user's language; defaults to the device locale (browser navigator.language, React Native
60
+ * the device locale), otherwise config.defaultLanguage ("en" when omitted). Never inferred from user text. */
61
+ language?: string;
62
+ /** Host-only retention budget, copied unchanged; Core owns validation and defaults. */
63
+ retentionBytes?: number;
64
+ config: ProjectConfig | ReleasedConfig;
65
+ handlers?: Record<string, ToolHandler>;
66
+ onUsage?: (event: ProjectUsageEvent) => void;
67
+ }
68
+ /** The stream `state`'s `activity` (sdk-internal #21): what a running agent waits on. An open
69
+ * string: a value this SDK does not know yet may arrive, and a stream must not fail on it. */
70
+ export type AgentActivity = 'model' | 'summary' | 'tool' | (string & {});
71
+ /** The stream's `state` event, and a snapshot's `state`. `activity` is set exactly while `status`
72
+ * is `running`; `tools` comes only with `tool`: the round's command keys in call order, never
73
+ * arguments. */
74
+ export interface AgentStateEvent {
75
+ type: 'state'; status: 'idle' | 'running' | 'waiting'; queued: number; typing: boolean;
76
+ activity: AgentActivity | null; tools?: string[];
77
+ }