@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
@@ -0,0 +1,57 @@
1
+ import { CrocheError } from './types.js';
2
+ import type { CoreInput, CoreOutput } from './core-abi.js';
3
+ import { CORE_WASM_BASE64, CORE_WASM_SHA256 } from './core-wasm-bytes.js';
4
+ import * as bindgen from './core-bindgen.js';
5
+
6
+ export { CORE_WASM_SHA256 };
7
+ export const CORE_ABI_VERSION = 1;
8
+ let loaded = false;
9
+ const MAX_ABI_BYTES = 32 * 1024 * 1024;
10
+
11
+ /** The shared Rust Core (wasm-bindgen), instantiated once from the embedded bytes. */
12
+ export function core(): typeof bindgen {
13
+ if (loaded) return bindgen;
14
+ if (typeof WebAssembly === 'undefined') {
15
+ throw new CrocheError('core_unavailable', 'This host needs WebAssembly or a native Croche Core binding.');
16
+ }
17
+ try {
18
+ const binary = Uint8Array.from(atob(CORE_WASM_BASE64), value => value.charCodeAt(0));
19
+ // Embedded at package build time: installed consumers need no Rust compiler, asset URL,
20
+ // network fetch, eval(), or generated JavaScript functions.
21
+ bindgen.initSync({ module: new WebAssembly.Module(binary) });
22
+ loaded = true;
23
+ return bindgen;
24
+ } catch {
25
+ throw new CrocheError('core_unavailable', "Unable to load the shared Rust Core. A browser CSP must allow 'wasm-unsafe-eval' in script-src.");
26
+ }
27
+ }
28
+
29
+ /** The entire semantic transition crosses this ABI; there is no TypeScript fallback engine. */
30
+ export function coreStep(input: CoreInput): CoreOutput {
31
+ let text: string;
32
+ try { text = JSON.stringify(input); }
33
+ catch { throw new CrocheError('invalid_input', 'Core inputs must be JSON serializable.'); }
34
+ if (text.length > MAX_ABI_BYTES) throw new CrocheError('store_full', 'Core state and input exceed the 32 MiB ABI limit.');
35
+ const step = core().step;
36
+ try {
37
+ const output = JSON.parse(step(text)) as CoreOutput;
38
+ if (output.abi !== 2) throw new Error('Unsupported Core ABI');
39
+ return output;
40
+ } catch {
41
+ throw new CrocheError('core_error', 'The shared Rust Core could not complete its transition. Reopen from durable storage.');
42
+ }
43
+ }
44
+
45
+ /** Strong host entropy, not a replacement for the Core's identity or policy logic. */
46
+ export function coreNonce(): string {
47
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
48
+ if (!globalThis.crypto?.getRandomValues) throw new CrocheError('host_unavailable', 'The host must provide cryptographically secure random values.');
49
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), value => value.toString(16).padStart(2, '0')).join('');
50
+ }
51
+
52
+ export function parseCoreMarkers(raw: string): { raw: string; text: string; markers: string[] } {
53
+ const output = coreStep({ abi: 2, config: {}, state: null, machine: null, command: { type: 'parse_markers', raw }, now: new Date().toISOString(), nonce: coreNonce() });
54
+ if (output.error) throw new CrocheError(output.error.code, output.error.message);
55
+ const { raw: original, text, markers } = output.result;
56
+ return { raw: original, text, markers };
57
+ }
package/src/debug.ts ADDED
@@ -0,0 +1,160 @@
1
+ import type { RuntimeDebugEvent } from './types.js';
2
+
3
+ export type { RuntimeDebugEvent, RuntimeStateData } from './types.js';
4
+
5
+ export interface LocalDebuggerOptions {
6
+ url?: string;
7
+ /** Local collector pairing token, unrelated to Cloud/provider credentials. */
8
+ token: string;
9
+ appName?: string;
10
+ /** Optional transport injection for tests or host networking adapters. */
11
+ fetch?: typeof fetch;
12
+ }
13
+
14
+ export interface DebugDeliveryStatus {
15
+ sent: number;
16
+ dropped: number;
17
+ pending: number;
18
+ droppedByReason: Record<string, number>;
19
+ lastError?: string;
20
+ }
21
+
22
+ export interface LocalDebugger {
23
+ onEvent(event: RuntimeDebugEvent): void;
24
+ /** Wait for one best-effort delivery of currently queued events; never retries. */
25
+ flush(): Promise<DebugDeliveryStatus>;
26
+ /** Stop accepting events and settle the remaining bounded queue. */
27
+ close(): Promise<DebugDeliveryStatus>;
28
+ }
29
+
30
+ const MAX_EVENT_BYTES = 128 * 1024;
31
+ const MAX_BATCH_BYTES = 1024 * 1024;
32
+ const MAX_QUEUE_BYTES = 4 * 1024 * 1024;
33
+ const MAX_QUEUE_EVENTS = 500;
34
+ const MAX_BATCH_EVENTS = 100;
35
+ const FLUSH_INTERVAL_MS = 100;
36
+ const REQUEST_TIMEOUT_MS = 2000;
37
+
38
+ /** Browser-compatible, development-only local trace transport. Never used by default. */
39
+ export function createLocalDebugger(options: LocalDebuggerOptions): LocalDebugger {
40
+ const base = new URL(options.url ?? 'http://127.0.0.1:8790');
41
+ if (!['http:', 'https:'].includes(base.protocol) || !['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname) ||
42
+ base.username || base.password || base.search || base.hash || !['', '/'].includes(base.pathname)) {
43
+ throw new Error('The local debugger URL must be a loopback HTTP(S) origin without credentials or a path.');
44
+ }
45
+ if (!options.token || options.token.length > 4096 || /[\r\n]/.test(options.token)) throw new Error('A valid local debugger pairing token is required.');
46
+ if (options.appName !== undefined && (typeof options.appName !== 'string' || options.appName.length > 200)) throw new Error('Debugger appName must contain at most 200 characters.');
47
+ const endpoint = `${base.origin}/api/events`;
48
+ const sourceId = globalThis.crypto.randomUUID();
49
+ const token = options.token;
50
+ const appName = options.appName;
51
+ const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
52
+ const encoder = new TextEncoder();
53
+ const queue: Array<{ json: string; bytes: number; id: string }> = [];
54
+ let queueBytes = 0;
55
+ let sent = 0;
56
+ let dropped = 0;
57
+ let reportedDrops = 0;
58
+ const droppedByReason: Record<string, number> = {};
59
+ let lastError: string | undefined;
60
+ let closed = false;
61
+ let timer: ReturnType<typeof setTimeout> | undefined;
62
+ let active: Promise<DebugDeliveryStatus> | undefined;
63
+ let closing: Promise<DebugDeliveryStatus> | undefined;
64
+
65
+ const status = (): DebugDeliveryStatus => ({ sent, dropped, pending: queue.length, droppedByReason: { ...droppedByReason }, ...(lastError ? { lastError } : {}) });
66
+ const drop = (count: number, reason: string) => {
67
+ dropped += count; droppedByReason[reason] = (droppedByReason[reason] ?? 0) + count;
68
+ };
69
+ const schedule = (includeDrops = false) => {
70
+ if (closed || timer || active || (!queue.length && !(includeDrops && dropped > reportedDrops))) return;
71
+ timer = setTimeout(() => { timer = undefined; void flush(); }, FLUSH_INTERVAL_MS);
72
+ (timer as unknown as { unref?: () => void }).unref?.();
73
+ };
74
+
75
+ const deliver = async (): Promise<DebugDeliveryStatus> => {
76
+ // Bound one flush even if a busy Runtime continuously emits more diagnostics.
77
+ let remaining = queue.length;
78
+ let metadataOnly = remaining === 0 && dropped > reportedDrops;
79
+ while ((remaining > 0 && queue.length > 0) || metadataOnly) {
80
+ const batch: Array<{ json: string; bytes: number; id: string }> = [];
81
+ let bytes = 4096; // Envelope/drop metadata and punctuation allowance.
82
+ while (queue.length && batch.length < MAX_BATCH_EVENTS && remaining > 0 && bytes + queue[0].bytes < MAX_BATCH_BYTES) {
83
+ const event = queue.shift()!; queueBytes -= event.bytes; remaining--; batch.push(event); bytes += event.bytes + 1;
84
+ }
85
+ if (!batch.length && !metadataOnly) break;
86
+ metadataOnly = false;
87
+ const dropCount = dropped;
88
+ const dropMetadata = dropCount > reportedDrops ? `,"dropped":${JSON.stringify({ sourceId, events: dropCount, reasons: droppedByReason })}` : '';
89
+ const body = `{"events":[${batch.map(event => event.json).join(',')}]${dropMetadata}}`;
90
+ const controller = new AbortController();
91
+ let requestTimeout: ReturnType<typeof setTimeout> | undefined;
92
+ try {
93
+ const timeout = new Promise<never>((_, reject) => {
94
+ requestTimeout = setTimeout(() => { controller.abort(); reject(new Error('timeout')); }, REQUEST_TIMEOUT_MS);
95
+ });
96
+ const response = await Promise.race([transport(endpoint, {
97
+ method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
98
+ body, signal: controller.signal, credentials: 'omit', redirect: 'error',
99
+ }), timeout]);
100
+ if (!response.ok) {
101
+ lastError = `http_${response.status}`; drop(batch.length, 'delivery_failed');
102
+ } else {
103
+ const acknowledgement = await Promise.race([response.json(), timeout]) as { accepted?: unknown; duplicate?: unknown };
104
+ if (!Array.isArray(acknowledgement.accepted) || !Array.isArray(acknowledgement.duplicate)) {
105
+ lastError = 'invalid_acknowledgement'; drop(batch.length, 'delivery_failed');
106
+ } else {
107
+ const acknowledged = new Set([...acknowledgement.accepted, ...acknowledgement.duplicate]);
108
+ const accepted = batch.filter(event => acknowledged.has(event.id)).length;
109
+ sent += accepted;
110
+ if (accepted < batch.length) { drop(batch.length - accepted, 'collector_rejected'); lastError = 'collector_rejected'; }
111
+ else lastError = undefined;
112
+ reportedDrops = dropCount;
113
+ }
114
+ }
115
+ } catch {
116
+ lastError = controller.signal.aborted ? 'request_timeout' : 'network_error';
117
+ drop(batch.length, 'delivery_failed');
118
+ } finally { clearTimeout(requestTimeout); }
119
+ }
120
+ return status();
121
+ };
122
+
123
+ const flush = (): Promise<DebugDeliveryStatus> => {
124
+ if (timer) { clearTimeout(timer); timer = undefined; }
125
+ if (active) return active;
126
+ active = deliver();
127
+ void active.finally(() => { active = undefined; schedule(); });
128
+ return active;
129
+ };
130
+
131
+ return {
132
+ onEvent(event) {
133
+ if (closed) { drop(1, 'closed'); return; }
134
+ try {
135
+ const json = JSON.stringify({ ...event, ...(appName === undefined ? {} : { appName }) });
136
+ const bytes = encoder.encode(json).byteLength;
137
+ if (bytes > MAX_EVENT_BYTES) { drop(1, 'event_too_large'); schedule(true); return; }
138
+ // Retain the most recent trace when a developer leaves a collector paused/offline.
139
+ while (queue.length >= MAX_QUEUE_EVENTS || queueBytes + bytes > MAX_QUEUE_BYTES) {
140
+ const discarded = queue.shift(); if (!discarded) break;
141
+ queueBytes -= discarded.bytes; drop(1, 'queue_full');
142
+ }
143
+ queue.push({ json, bytes, id: event.id }); queueBytes += bytes;
144
+ schedule();
145
+ } catch { drop(1, 'invalid_event'); schedule(true); }
146
+ },
147
+ flush,
148
+ close() {
149
+ if (closing) return closing;
150
+ closed = true;
151
+ if (timer) { clearTimeout(timer); timer = undefined; }
152
+ closing = (async () => {
153
+ await flush();
154
+ if (queue.length) await flush();
155
+ return status();
156
+ })();
157
+ return closing;
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,269 @@
1
+ import { link, open, readdir, readFile, unlink } from 'node:fs/promises';
2
+ import { closeSync, fsyncSync, linkSync, openSync, readFileSync, readlinkSync, unlinkSync, writeSync } from 'node:fs';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { hostname } from 'node:os';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { CrocheError } from './types.js';
8
+
9
+ // The cross-process lock behind the Node FileStorage (W1). Internal: not a package export.
10
+ //
11
+ // The lock is a chain of generation records `<lock>.<n>`. The highest generation decides who
12
+ // holds it, and nothing ever deletes the highest one:
13
+ // - Each record is written in full to a private file first, then published under its generation
14
+ // name with link(), which fails if that generation exists. There is no empty or half-written
15
+ // record to judge, so a creator paused at any point is never mistaken for a dead one (Atlas,
16
+ // #313 P1-1).
17
+ // - Taking the lock means creating generation n+1, when record n is `free` (released) or held
18
+ // by a process that no longer exists, judged only inside this process's own PID scope (see
19
+ // `keeps`). Exactly one creator gets n+1, and no step
20
+ // removes a file to make room, so no remover can act on a check that has gone stale (Atlas,
21
+ // #313 P1-2). There is no age-based takeover anywhere: time passing proves nothing.
22
+ // - A creator that finds a generation above its own after publishing (it was paused, others went
23
+ // on, and its generation had been cleaned up) withdraws it and reports store_busy.
24
+ // - Records below the highest are cleaned up; removing one never changes who holds the lock.
25
+ // Every unlink here targets a record below the top (or the owner's own, after a `free` record
26
+ // went above it), so no removal can act on ownership, however long its process was paused.
27
+ // - Writes are fenced: the owner checks that its own record is still on top before each write
28
+ // and fails with `store_busy` otherwise (FileStorage).
29
+ // - No clock decides anything. A record's `at` is for people reading it.
30
+ // - A pid means something only inside one PID namespace on one boot of one host. Liveness
31
+ // (`kill(pid, 0)`) and the incarnation are consulted only for a record written in this
32
+ // process's own scope (host, boot id and PID namespace all equal); any other record is
33
+ // ambiguous (another container may be alive with the same pid) and is never taken over
34
+ // (Atlas, #313 at f182e8c).
35
+ // - macOS has a scope too (Keel #393 6087163235): the boot is kern.bootsessionuuid, a random
36
+ // UUID per boot, and there are no PID namespaces. The host is not part of it there: a Mac's
37
+ // hostname follows the network it is on, and equal per-boot UUIDs already name one machine.
38
+ // A record names its OS, and a Linux record and a macOS record are never in one scope (a
39
+ // directory shared with a container). Windows has no scope: nothing held is taken over.
40
+
41
+ /** Lock records this module holds, by lock path: the generation and its nonce. */
42
+ const held = new Map<string, { generation: number; nonce: string }>();
43
+ let exitHook = false;
44
+ /** How many times an acquisition re-reads after the chain moved under it. */
45
+ const ATTEMPTS = 5;
46
+
47
+ export type LockRecord = {
48
+ pid: number; host: string; nonce: string; at: number; state: 'held' | 'free';
49
+ /** Where the writer's pid means something, and which process it was, where the OS says so
50
+ * without a clock: the OS, the boot, the PID namespace, and (Linux) the process's start in
51
+ * clock ticks since boot. A record with a boot and no `os` was written on Linux, the only
52
+ * scope there was before macOS's. */
53
+ os?: string; boot?: string; pidns?: string; start?: string;
54
+ };
55
+
56
+ export type Incarnation = { os: 'linux' | 'darwin'; boot: string; pidns: string; start?: string };
57
+
58
+ /** The PID namespace macOS records name: it has none, so every process shares this one. */
59
+ export const DARWIN_PIDNS = 'darwin';
60
+
61
+ /** This process's scope and incarnation, or null where the OS cannot say (Windows, or anything
62
+ * here failing): then no held record is taken over.
63
+ * - Linux (/proc): the boot id (/proc/sys/kernel/random/boot_id), the PID namespace (the inode in
64
+ * readlink /proc/self/ns/pid, `pid:[N]`), and the start in clock ticks since boot
65
+ * (/proc/self/stat field 22).
66
+ * - macOS: kern.bootsessionuuid (sysctl), and the one PID namespace. No start: the one the OS
67
+ * gives is wall-clock text in the reader's time zone, so the same pid is always this process.
68
+ * None moves with the wall clock, and every thread of the process reads the same values. */
69
+ export function incarnation(): Incarnation | null {
70
+ if (cached !== undefined) return cached;
71
+ cached = process.platform === 'darwin' ? darwin() : process.platform === 'linux' ? linux() : null;
72
+ return cached;
73
+ }
74
+ let cached: Incarnation | null | undefined;
75
+
76
+ function linux(): Incarnation | null {
77
+ try {
78
+ const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
79
+ const pidns = /^pid:\[([0-9]+)\]$/.exec(readlinkSync('/proc/self/ns/pid'))?.[1];
80
+ const stat = readFileSync('/proc/self/stat', 'utf8');
81
+ // Field 2 is the command name in parentheses, which may hold spaces: count from after it.
82
+ const start = stat.slice(stat.lastIndexOf(')') + 2).split(' ')[22 - 3];
83
+ return boot && pidns && /^[0-9]+$/.test(start ?? '') ? { os: 'linux', boot, pidns, start } : null;
84
+ } catch { return null; }
85
+ }
86
+
87
+ const UUID = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
88
+ function darwin(): Incarnation | null {
89
+ try {
90
+ const boot = execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'],
91
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 }).trim();
92
+ return UUID.test(boot) ? { os: 'darwin', boot, pidns: DARWIN_PIDNS } : null;
93
+ } catch { return null; }
94
+ }
95
+
96
+ /** Whether `pid` may be a live process on this machine. `kill(pid, 0)` sends nothing; it checks
97
+ * existence. Only ESRCH (no such process) means absent. Every other error (EPERM: it exists but
98
+ * belongs to another user; EACCES, ENOSYS, EINVAL, anything unknown) means the check could not
99
+ * prove death, and an unproven death never authorizes a takeover. */
100
+ function alive(pid: number): boolean {
101
+ try { process.kill(pid, 0); return true; }
102
+ catch (error) { return (error as NodeJS.ErrnoException).code !== 'ESRCH'; }
103
+ }
104
+
105
+ const code = (error: unknown) => (error as NodeJS.ErrnoException).code;
106
+
107
+ /** The generations of `path` present now, highest first. */
108
+ export async function generations(path: string): Promise<number[]> {
109
+ const prefix = `${basename(path)}.`;
110
+ const names = await readdir(dirname(path)).catch(error => { if (code(error) === 'ENOENT') return [] as string[]; throw error; });
111
+ return names
112
+ .filter(name => name.startsWith(prefix) && /^[1-9][0-9]*$/.test(name.slice(prefix.length)))
113
+ .map(name => Number(name.slice(prefix.length)))
114
+ .filter(Number.isSafeInteger)
115
+ .sort((a, b) => b - a);
116
+ }
117
+
118
+ /** Record `generation` of `path`: 'absent' if it is gone, null if it cannot be read as one. */
119
+ export async function lockRecord(path: string, generation: number): Promise<LockRecord | null | 'absent'> {
120
+ let text: string;
121
+ try { text = await readFile(`${path}.${generation}`, 'utf8'); }
122
+ catch (error) { if (code(error) === 'ENOENT') return 'absent'; throw error; }
123
+ try {
124
+ const value = JSON.parse(text) as LockRecord;
125
+ return Number.isInteger(value?.pid) && value.pid > 0 && typeof value.nonce === 'string' && typeof value.host === 'string'
126
+ && (value.state === 'held' || value.state === 'free') ? value : null;
127
+ } catch { return null; }
128
+ }
129
+
130
+ const record = (state: LockRecord['state'], nonce: string): LockRecord =>
131
+ ({ pid: process.pid, host: hostname(), nonce, at: Date.now(), state, ...(incarnation() ?? {}) });
132
+ const temporary = (path: string) => join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
133
+
134
+ /** Publishes `value` as generation `generation`, complete and fsynced before it is visible.
135
+ * False: that generation already exists. */
136
+ async function publish(path: string, generation: number, value: LockRecord): Promise<boolean> {
137
+ const draft = temporary(path);
138
+ const file = await open(draft, 'wx', 0o600);
139
+ try { await file.writeFile(JSON.stringify(value)); await file.sync(); }
140
+ finally { await file.close(); }
141
+ try { await link(draft, `${path}.${generation}`); return true; }
142
+ catch (error) { if (code(error) === 'EEXIST') return false; throw error; }
143
+ finally { await unlink(draft).catch(() => {}); }
144
+ }
145
+
146
+ /** The same, synchronously, for the exit hook. */
147
+ function publishSync(path: string, generation: number, value: LockRecord): boolean {
148
+ const draft = temporary(path);
149
+ const fd = openSync(draft, 'wx', 0o600);
150
+ try { writeSync(fd, JSON.stringify(value)); fsyncSync(fd); }
151
+ finally { closeSync(fd); }
152
+ try { linkSync(draft, `${path}.${generation}`); return true; }
153
+ catch (error) { if (code(error) === 'EEXIST') return false; throw error; }
154
+ finally { try { unlinkSync(draft); } catch { /* best effort */ } }
155
+ }
156
+
157
+ /** Removes the generations below `top`. None of them decides anything any more. */
158
+ async function prune(path: string, top: number) {
159
+ for (const generation of await generations(path).catch(() => [] as number[])) {
160
+ if (generation < top) await unlink(`${path}.${generation}`).catch(() => {});
161
+ }
162
+ }
163
+
164
+ /** Whether `found` was written in this process's own PID scope: this OS, this boot and this PID
165
+ * namespace (and on Linux this host, checked first in `keeps`). Only there does a pid name one
166
+ * process this one can check. A record without the evidence, or a process that has no scope, is
167
+ * never in scope. */
168
+ function inScope(found: LockRecord): boolean {
169
+ const me = incarnation();
170
+ return !!me && typeof found.boot === 'string' && typeof found.pidns === 'string'
171
+ && (found.os ?? 'linux') === me.os && found.boot === me.boot && found.pidns === me.pidns;
172
+ }
173
+
174
+ /** Why the record on top keeps the lock, or null when it may be taken. */
175
+ function keeps(found: LockRecord | null, generation: number, path: string): string | null {
176
+ const record = `${path}.${generation}`;
177
+ if (!found) {
178
+ return `its lock record ${record} cannot be read. The lock publishes only complete, fsynced records, so this is damage or a foreign writer; it is never taken over. If no process uses this store, remove the ${basename(path)}.* records`;
179
+ }
180
+ if (found.state === 'free') return null;
181
+ // macOS's scope is its boot alone: its hostname follows the network (measured, #393).
182
+ if (found.host !== hostname() && incarnation()?.os !== 'darwin') {
183
+ return `pid ${found.pid} on host ${found.host}, record ${record}. Another host's owner is never taken over, since a shared directory's other host cannot be checked. If that host is gone (a container restarted under a new hostname), remove the ${basename(path)}.* records`;
184
+ }
185
+ if (!inScope(found)) {
186
+ return `pid ${found.pid} on host ${found.host}, record ${record}, written outside this process's PID scope (another OS, boot or PID namespace, or no way to tell here): a store directory shared between containers or PID namespaces, or a container or machine that restarted after a crash. Its owner cannot be checked from here, so it is never taken over. Use one store directory per container (or per host process tree). If no process uses this store any more, stop every user of it, then remove the ${basename(path)}.* records`;
187
+ }
188
+ if (found.pid === process.pid) {
189
+ // The same pid in this scope: this process (another copy of the SDK, a worker thread), or an
190
+ // earlier process that had this pid on this boot and in this namespace (another start). With
191
+ // no start to compare (macOS), it is this process.
192
+ const start = incarnation()!.start;
193
+ if (typeof found.start === 'string' && typeof start === 'string' && found.start !== start) return null;
194
+ return `this process (pid ${found.pid}: another copy of the SDK, or a worker thread), record ${record}`;
195
+ }
196
+ return alive(found.pid) ? `pid ${found.pid}, record ${record}` : null;
197
+ }
198
+
199
+ /** Releases what this process still holds if it exits without closing (an exit hook runs only
200
+ * synchronous code). A killed process runs nothing; its record is held by a pid that no longer
201
+ * exists, and the next opener takes the lock over. */
202
+ function releaseAtExit() {
203
+ if (exitHook) return;
204
+ exitHook = true;
205
+ process.once('exit', () => {
206
+ for (const [path, mine] of held) {
207
+ try { publishSync(path, mine.generation + 1, record('free', mine.nonce)); unlinkSync(`${path}.${mine.generation}`); }
208
+ catch { /* best effort */ }
209
+ }
210
+ });
211
+ }
212
+
213
+ export type FileLock = {
214
+ /** Publishes a `free` record above this owner's (only while it is still on top), then runs
215
+ * `released`. */
216
+ release: () => Promise<void>;
217
+ /** The fence: throws `store_busy` unless this owner's record (generation and nonce) is still
218
+ * the one on top. */
219
+ verify: () => Promise<void>;
220
+ };
221
+
222
+ /** Holds the lock at `path` for this process, or fails with `store_busy`. */
223
+ export async function acquireFileLock(path: string, released: () => void): Promise<FileLock> {
224
+ const nonce = randomUUID();
225
+ let mine: number | null = null;
226
+ let reason = 'the lock kept changing while it was read';
227
+ try {
228
+ for (let attempt = 0; attempt < ATTEMPTS && mine === null; attempt += 1) {
229
+ const [top = 0] = await generations(path);
230
+ if (top > 0) {
231
+ const found = await lockRecord(path, top);
232
+ if (found === 'absent') continue;
233
+ const why = keeps(found, top, path);
234
+ if (why) { reason = why; break; }
235
+ }
236
+ if (!(await publish(path, top + 1, record('held', nonce)))) continue;
237
+ // Paused creators can publish a generation that was already cleaned up below the top.
238
+ const [now = 0] = await generations(path);
239
+ if (now !== top + 1) { await unlink(`${path}.${top + 1}`).catch(() => {}); continue; }
240
+ mine = top + 1;
241
+ }
242
+ } catch (error) {
243
+ throw new CrocheError('store_busy', `The store's lock file could not be created: ${(error as Error).message}`);
244
+ }
245
+ if (mine === null) throw new CrocheError('store_busy', `This file namespace is open in another process (${reason}).`);
246
+ await prune(path, mine);
247
+ held.set(path, { generation: mine, nonce });
248
+ releaseAtExit();
249
+ const generation = mine;
250
+ const verify = async () => {
251
+ const [top = 0] = await generations(path);
252
+ const found = top === generation ? await lockRecord(path, generation) : null;
253
+ if (!found || found === 'absent' || found.nonce !== nonce || found.state !== 'held') {
254
+ throw new CrocheError('store_busy', `This owner's lock record ${generation} is no longer the one on top (now ${top || 'none'}); the write was refused.`);
255
+ }
256
+ };
257
+ const release = async () => {
258
+ held.delete(path);
259
+ try {
260
+ const [top = 0] = await generations(path);
261
+ const found = top === generation ? await lockRecord(path, generation) : null;
262
+ if (found && found !== 'absent' && found.nonce === nonce && await publish(path, generation + 1, record('free', nonce))) {
263
+ await unlink(`${path}.${generation}`).catch(() => {});
264
+ }
265
+ } catch { /* the next opener checks the pid */ }
266
+ released();
267
+ };
268
+ return { release, verify };
269
+ }
package/src/images.ts ADDED
@@ -0,0 +1,174 @@
1
+ import type { ImageResolution, InputImage, JsonValue } from './types.js';
2
+
3
+ /**
4
+ * Images on the way to the Core (F30, H3). A `standard` image (the default) is sent at most
5
+ * STANDARD_MAX_SIDE pixels on its longest side, never upscaled, re-encoded to whichever of PNG and
6
+ * JPEG is smaller (an image with transparent pixels stays PNG; a GIF becomes its first frame).
7
+ * A `high` image is sent as given, within the 3 MB / 6 MB limits: for text, screenshots and dense
8
+ * detail. An https `url` image is never fetched or changed. With no codec (Node), images pass
9
+ * through unchanged.
10
+ */
11
+ export const STANDARD_MAX_SIDE = 512;
12
+ const JPEG_QUALITY = 0.7;
13
+
14
+ const TOOL_RESULT = Symbol.for('croche.toolResult');
15
+ /** What a tool returns with images: its value, and the images beside it (never inside it). */
16
+ export interface ToolResult {
17
+ readonly [TOOL_RESULT]: true;
18
+ value: JsonValue;
19
+ images: InputImage[];
20
+ /** For every image of this result that does not name its own `resolution`. */
21
+ imageResolution?: ImageResolution;
22
+ }
23
+ /**
24
+ * A tool's result with images: `return toolResult({ placed: true }, { images: [{ data, mime, alt }] })`.
25
+ * The same image kinds and limits as a message's (at most 4, 3 MB each, 6 MB together); a
26
+ * violation fails that call alone with `invalid_tool_result`, and the turn goes on. A plain
27
+ * value is never looked inside.
28
+ */
29
+ export function toolResult(value: JsonValue | undefined, options: { images?: InputImage[]; imageResolution?: ImageResolution } = {}): ToolResult {
30
+ const result = { value: value === undefined ? null : value, images: options.images ?? [] } as ToolResult;
31
+ Object.defineProperty(result, TOOL_RESULT, { value: true });
32
+ if (options.imageResolution) result.imageResolution = options.imageResolution;
33
+ return result;
34
+ }
35
+ export function isToolResult(value: unknown): value is ToolResult {
36
+ return typeof value === 'object' && value !== null && (value as { [TOOL_RESULT]?: true })[TOOL_RESULT] === true;
37
+ }
38
+
39
+ /** Decodes and re-encodes images on this platform. */
40
+ export interface ImageCodec {
41
+ /** The decoded image, or null when this platform cannot decode it. */
42
+ open(bytes: Uint8Array, mime: string): Promise<OpenedImage | null>;
43
+ }
44
+ export interface OpenedImage {
45
+ width: number;
46
+ height: number;
47
+ /** Draws it at this size (a GIF's first frame): PNG, and JPEG unless a pixel is transparent. */
48
+ render(width: number, height: number): Promise<{ png: Uint8Array; jpeg?: Uint8Array }>;
49
+ close(): void;
50
+ }
51
+
52
+ /** The browser's codec (createImageBitmap and OffscreenCanvas), where there is one. */
53
+ export function browserCodec(): ImageCodec | undefined {
54
+ if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas !== 'function') return undefined;
55
+ const bytesOf = async (blob: Blob) => new Uint8Array(await blob.arrayBuffer());
56
+ return {
57
+ async open(bytes, mime) {
58
+ const bitmap = await createImageBitmap(new Blob([bytes as BlobPart], { type: mime }));
59
+ return {
60
+ width: bitmap.width,
61
+ height: bitmap.height,
62
+ async render(width, height) {
63
+ const canvas = new OffscreenCanvas(width, height);
64
+ const context = canvas.getContext('2d')!;
65
+ context.drawImage(bitmap, 0, 0, width, height);
66
+ const pixels = context.getImageData(0, 0, width, height).data;
67
+ let alpha = false;
68
+ for (let i = 3; i < pixels.length && !alpha; i += 4) alpha = pixels[i]! < 255;
69
+ const png = await bytesOf(await canvas.convertToBlob({ type: 'image/png' }));
70
+ if (alpha) return { png };
71
+ return { png, jpeg: await bytesOf(await canvas.convertToBlob({ type: 'image/jpeg', quality: JPEG_QUALITY })) };
72
+ },
73
+ close: () => bitmap.close(),
74
+ };
75
+ },
76
+ };
77
+ }
78
+
79
+ /** Whether `prepareImage` would change this image (so a send must wait for it). */
80
+ export function preparable(image: unknown, fallback: ImageResolution | undefined, codec: ImageCodec | undefined): boolean {
81
+ return !!codec && wellFormed(image) !== null
82
+ && ((image as InputImage).resolution ?? fallback ?? 'standard') === 'standard';
83
+ }
84
+
85
+ const MIMES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
86
+ /**
87
+ * A base64 image the Core would accept as given, by its shape (the Core's own rules: an object,
88
+ * `data` and no `url`, its mime one of the four and agreeing with a data URL's, base64 text, an
89
+ * `alt` of at most 500 characters), with its mime and body; null otherwise. Only such an image is
90
+ * re-encoded (Atlas, #351 P1-3): anything else passes unchanged, so the Core refuses it exactly as
91
+ * it would with no codec. Sizes are judged on what is sent, after re-encoding.
92
+ */
93
+ function wellFormed(image: unknown): { mime: string; body: string } | null {
94
+ if (typeof image !== 'object' || image === null || Array.isArray(image)) return null;
95
+ const { data, url, mime, alt } = image as { data?: unknown; url?: unknown; mime?: unknown; alt?: unknown };
96
+ if (url !== undefined || typeof data !== 'string') return null;
97
+ if (mime !== undefined && mime !== null && !(typeof mime === 'string' && MIMES.includes(mime))) return null;
98
+ if (alt !== undefined && alt !== null && !(typeof alt === 'string' && alt.length <= 500)) return null;
99
+ let type = typeof mime === 'string' ? mime : undefined;
100
+ let body = data;
101
+ if (data.startsWith('data:')) {
102
+ const comma = data.indexOf(',');
103
+ if (comma < 0) return null;
104
+ const head = data.slice(5, comma);
105
+ if (!head.endsWith(';base64')) return null;
106
+ const given = head.slice(0, -';base64'.length);
107
+ if (type !== undefined && type !== given) return null;
108
+ type = given;
109
+ body = data.slice(comma + 1);
110
+ }
111
+ if (!type || !MIMES.includes(type)) return null;
112
+ const bare = body.replace(/=+$/, '');
113
+ if (!bare || body.length - bare.length > 2 || !/^[A-Za-z0-9+/]+$/.test(bare)) return null;
114
+ return { mime: type, body };
115
+ }
116
+
117
+ /** The image as it is sent: `resolution` resolved (the image's own, else `fallback`, else
118
+ * standard) and removed. Anything it cannot read passes unchanged, for the Core to judge. */
119
+ export async function prepareImage(image: InputImage, fallback: ImageResolution | undefined, codec: ImageCodec | undefined): Promise<InputImage> {
120
+ // Malformed: exactly as given, for the Core to refuse (never rebuilt into a clean image).
121
+ if (wellFormed(image) === null) return image;
122
+ const { resolution: _resolution, ...given } = image;
123
+ if (!preparable(image, fallback, codec)) return given as InputImage;
124
+ const parsed = dataOf((given as { data: string }).data, given.mime);
125
+ if (!parsed) return given as InputImage;
126
+ let opened: OpenedImage | null = null;
127
+ try { opened = await codec!.open(parsed.bytes, parsed.mime); }
128
+ catch { opened = null; }
129
+ if (!opened) return given as InputImage;
130
+ try {
131
+ const scale = Math.min(1, STANDARD_MAX_SIDE / Math.max(opened.width, opened.height, 1));
132
+ const width = Math.max(1, Math.round(opened.width * scale));
133
+ const height = Math.max(1, Math.round(opened.height * scale));
134
+ const out = await opened.render(width, height);
135
+ const candidates: Array<{ mime: string; bytes: Uint8Array; original?: true }> = [{ mime: 'image/png', bytes: out.png }];
136
+ if (out.jpeg) candidates.push({ mime: 'image/jpeg', bytes: out.jpeg });
137
+ // Already within the size: the original stays when it is the smallest (a GIF always becomes
138
+ // its first frame, so the original GIF is no candidate).
139
+ if (scale === 1 && parsed.mime !== 'image/gif') candidates.push({ mime: parsed.mime, bytes: parsed.bytes, original: true });
140
+ const best = candidates.reduce((a, b) => (b.bytes.length < a.bytes.length ? b : a));
141
+ if (best.original) return given as InputImage;
142
+ const sent: InputImage = { data: base64(best.bytes), mime: best.mime as never };
143
+ if (given.alt !== undefined) sent.alt = given.alt;
144
+ return sent;
145
+ } catch {
146
+ return given as InputImage;
147
+ } finally {
148
+ opened.close();
149
+ }
150
+ }
151
+
152
+ function dataOf(data: string, mime: string | undefined): { mime: string; bytes: Uint8Array } | null {
153
+ let body = data;
154
+ let type = mime;
155
+ if (data.startsWith('data:')) {
156
+ const comma = data.indexOf(',');
157
+ const head = data.slice(5, comma);
158
+ if (comma < 0 || !head.endsWith(';base64')) return null;
159
+ type = head.slice(0, -';base64'.length);
160
+ body = data.slice(comma + 1);
161
+ }
162
+ if (!type) return null;
163
+ try {
164
+ const binary = atob(body);
165
+ const bytes = new Uint8Array(binary.length);
166
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
167
+ return { mime: type, bytes };
168
+ } catch { return null; }
169
+ }
170
+ function base64(bytes: Uint8Array): string {
171
+ let binary = '';
172
+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
173
+ return btoa(binary);
174
+ }