@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
package/dist/images.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ImageResolution, InputImage, JsonValue } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Images on the way to the Core (F30, H3). A `standard` image (the default) is sent at most
|
|
4
|
+
* STANDARD_MAX_SIDE pixels on its longest side, never upscaled, re-encoded to whichever of PNG and
|
|
5
|
+
* JPEG is smaller (an image with transparent pixels stays PNG; a GIF becomes its first frame).
|
|
6
|
+
* A `high` image is sent as given, within the 3 MB / 6 MB limits: for text, screenshots and dense
|
|
7
|
+
* detail. An https `url` image is never fetched or changed. With no codec (Node), images pass
|
|
8
|
+
* through unchanged.
|
|
9
|
+
*/
|
|
10
|
+
export declare const STANDARD_MAX_SIDE = 512;
|
|
11
|
+
declare const TOOL_RESULT: unique symbol;
|
|
12
|
+
/** What a tool returns with images: its value, and the images beside it (never inside it). */
|
|
13
|
+
export interface ToolResult {
|
|
14
|
+
readonly [TOOL_RESULT]: true;
|
|
15
|
+
value: JsonValue;
|
|
16
|
+
images: InputImage[];
|
|
17
|
+
/** For every image of this result that does not name its own `resolution`. */
|
|
18
|
+
imageResolution?: ImageResolution;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A tool's result with images: `return toolResult({ placed: true }, { images: [{ data, mime, alt }] })`.
|
|
22
|
+
* The same image kinds and limits as a message's (at most 4, 3 MB each, 6 MB together); a
|
|
23
|
+
* violation fails that call alone with `invalid_tool_result`, and the turn goes on. A plain
|
|
24
|
+
* value is never looked inside.
|
|
25
|
+
*/
|
|
26
|
+
export declare function toolResult(value: JsonValue | undefined, options?: {
|
|
27
|
+
images?: InputImage[];
|
|
28
|
+
imageResolution?: ImageResolution;
|
|
29
|
+
}): ToolResult;
|
|
30
|
+
export declare function isToolResult(value: unknown): value is ToolResult;
|
|
31
|
+
/** Decodes and re-encodes images on this platform. */
|
|
32
|
+
export interface ImageCodec {
|
|
33
|
+
/** The decoded image, or null when this platform cannot decode it. */
|
|
34
|
+
open(bytes: Uint8Array, mime: string): Promise<OpenedImage | null>;
|
|
35
|
+
}
|
|
36
|
+
export interface OpenedImage {
|
|
37
|
+
width: number;
|
|
38
|
+
height: number;
|
|
39
|
+
/** Draws it at this size (a GIF's first frame): PNG, and JPEG unless a pixel is transparent. */
|
|
40
|
+
render(width: number, height: number): Promise<{
|
|
41
|
+
png: Uint8Array;
|
|
42
|
+
jpeg?: Uint8Array;
|
|
43
|
+
}>;
|
|
44
|
+
close(): void;
|
|
45
|
+
}
|
|
46
|
+
/** The browser's codec (createImageBitmap and OffscreenCanvas), where there is one. */
|
|
47
|
+
export declare function browserCodec(): ImageCodec | undefined;
|
|
48
|
+
/** Whether `prepareImage` would change this image (so a send must wait for it). */
|
|
49
|
+
export declare function preparable(image: unknown, fallback: ImageResolution | undefined, codec: ImageCodec | undefined): boolean;
|
|
50
|
+
/** The image as it is sent: `resolution` resolved (the image's own, else `fallback`, else
|
|
51
|
+
* standard) and removed. Anything it cannot read passes unchanged, for the Core to judge. */
|
|
52
|
+
export declare function prepareImage(image: InputImage, fallback: ImageResolution | undefined, codec: ImageCodec | undefined): Promise<InputImage>;
|
|
53
|
+
export {};
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Images on the way to the Core (F30, H3). A `standard` image (the default) is sent at most
|
|
3
|
+
* STANDARD_MAX_SIDE pixels on its longest side, never upscaled, re-encoded to whichever of PNG and
|
|
4
|
+
* JPEG is smaller (an image with transparent pixels stays PNG; a GIF becomes its first frame).
|
|
5
|
+
* A `high` image is sent as given, within the 3 MB / 6 MB limits: for text, screenshots and dense
|
|
6
|
+
* detail. An https `url` image is never fetched or changed. With no codec (Node), images pass
|
|
7
|
+
* through unchanged.
|
|
8
|
+
*/
|
|
9
|
+
export const STANDARD_MAX_SIDE = 512;
|
|
10
|
+
const JPEG_QUALITY = 0.7;
|
|
11
|
+
const TOOL_RESULT = Symbol.for('croche.toolResult');
|
|
12
|
+
/**
|
|
13
|
+
* A tool's result with images: `return toolResult({ placed: true }, { images: [{ data, mime, alt }] })`.
|
|
14
|
+
* The same image kinds and limits as a message's (at most 4, 3 MB each, 6 MB together); a
|
|
15
|
+
* violation fails that call alone with `invalid_tool_result`, and the turn goes on. A plain
|
|
16
|
+
* value is never looked inside.
|
|
17
|
+
*/
|
|
18
|
+
export function toolResult(value, options = {}) {
|
|
19
|
+
const result = { value: value === undefined ? null : value, images: options.images ?? [] };
|
|
20
|
+
Object.defineProperty(result, TOOL_RESULT, { value: true });
|
|
21
|
+
if (options.imageResolution)
|
|
22
|
+
result.imageResolution = options.imageResolution;
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
export function isToolResult(value) {
|
|
26
|
+
return typeof value === 'object' && value !== null && value[TOOL_RESULT] === true;
|
|
27
|
+
}
|
|
28
|
+
/** The browser's codec (createImageBitmap and OffscreenCanvas), where there is one. */
|
|
29
|
+
export function browserCodec() {
|
|
30
|
+
if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas !== 'function')
|
|
31
|
+
return undefined;
|
|
32
|
+
const bytesOf = async (blob) => new Uint8Array(await blob.arrayBuffer());
|
|
33
|
+
return {
|
|
34
|
+
async open(bytes, mime) {
|
|
35
|
+
const bitmap = await createImageBitmap(new Blob([bytes], { type: mime }));
|
|
36
|
+
return {
|
|
37
|
+
width: bitmap.width,
|
|
38
|
+
height: bitmap.height,
|
|
39
|
+
async render(width, height) {
|
|
40
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
41
|
+
const context = canvas.getContext('2d');
|
|
42
|
+
context.drawImage(bitmap, 0, 0, width, height);
|
|
43
|
+
const pixels = context.getImageData(0, 0, width, height).data;
|
|
44
|
+
let alpha = false;
|
|
45
|
+
for (let i = 3; i < pixels.length && !alpha; i += 4)
|
|
46
|
+
alpha = pixels[i] < 255;
|
|
47
|
+
const png = await bytesOf(await canvas.convertToBlob({ type: 'image/png' }));
|
|
48
|
+
if (alpha)
|
|
49
|
+
return { png };
|
|
50
|
+
return { png, jpeg: await bytesOf(await canvas.convertToBlob({ type: 'image/jpeg', quality: JPEG_QUALITY })) };
|
|
51
|
+
},
|
|
52
|
+
close: () => bitmap.close(),
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Whether `prepareImage` would change this image (so a send must wait for it). */
|
|
58
|
+
export function preparable(image, fallback, codec) {
|
|
59
|
+
return !!codec && wellFormed(image) !== null
|
|
60
|
+
&& (image.resolution ?? fallback ?? 'standard') === 'standard';
|
|
61
|
+
}
|
|
62
|
+
const MIMES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
|
|
63
|
+
/**
|
|
64
|
+
* A base64 image the Core would accept as given, by its shape (the Core's own rules: an object,
|
|
65
|
+
* `data` and no `url`, its mime one of the four and agreeing with a data URL's, base64 text, an
|
|
66
|
+
* `alt` of at most 500 characters), with its mime and body; null otherwise. Only such an image is
|
|
67
|
+
* re-encoded (Atlas, #351 P1-3): anything else passes unchanged, so the Core refuses it exactly as
|
|
68
|
+
* it would with no codec. Sizes are judged on what is sent, after re-encoding.
|
|
69
|
+
*/
|
|
70
|
+
function wellFormed(image) {
|
|
71
|
+
if (typeof image !== 'object' || image === null || Array.isArray(image))
|
|
72
|
+
return null;
|
|
73
|
+
const { data, url, mime, alt } = image;
|
|
74
|
+
if (url !== undefined || typeof data !== 'string')
|
|
75
|
+
return null;
|
|
76
|
+
if (mime !== undefined && mime !== null && !(typeof mime === 'string' && MIMES.includes(mime)))
|
|
77
|
+
return null;
|
|
78
|
+
if (alt !== undefined && alt !== null && !(typeof alt === 'string' && alt.length <= 500))
|
|
79
|
+
return null;
|
|
80
|
+
let type = typeof mime === 'string' ? mime : undefined;
|
|
81
|
+
let body = data;
|
|
82
|
+
if (data.startsWith('data:')) {
|
|
83
|
+
const comma = data.indexOf(',');
|
|
84
|
+
if (comma < 0)
|
|
85
|
+
return null;
|
|
86
|
+
const head = data.slice(5, comma);
|
|
87
|
+
if (!head.endsWith(';base64'))
|
|
88
|
+
return null;
|
|
89
|
+
const given = head.slice(0, -';base64'.length);
|
|
90
|
+
if (type !== undefined && type !== given)
|
|
91
|
+
return null;
|
|
92
|
+
type = given;
|
|
93
|
+
body = data.slice(comma + 1);
|
|
94
|
+
}
|
|
95
|
+
if (!type || !MIMES.includes(type))
|
|
96
|
+
return null;
|
|
97
|
+
const bare = body.replace(/=+$/, '');
|
|
98
|
+
if (!bare || body.length - bare.length > 2 || !/^[A-Za-z0-9+/]+$/.test(bare))
|
|
99
|
+
return null;
|
|
100
|
+
return { mime: type, body };
|
|
101
|
+
}
|
|
102
|
+
/** The image as it is sent: `resolution` resolved (the image's own, else `fallback`, else
|
|
103
|
+
* standard) and removed. Anything it cannot read passes unchanged, for the Core to judge. */
|
|
104
|
+
export async function prepareImage(image, fallback, codec) {
|
|
105
|
+
// Malformed: exactly as given, for the Core to refuse (never rebuilt into a clean image).
|
|
106
|
+
if (wellFormed(image) === null)
|
|
107
|
+
return image;
|
|
108
|
+
const { resolution: _resolution, ...given } = image;
|
|
109
|
+
if (!preparable(image, fallback, codec))
|
|
110
|
+
return given;
|
|
111
|
+
const parsed = dataOf(given.data, given.mime);
|
|
112
|
+
if (!parsed)
|
|
113
|
+
return given;
|
|
114
|
+
let opened = null;
|
|
115
|
+
try {
|
|
116
|
+
opened = await codec.open(parsed.bytes, parsed.mime);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
opened = null;
|
|
120
|
+
}
|
|
121
|
+
if (!opened)
|
|
122
|
+
return given;
|
|
123
|
+
try {
|
|
124
|
+
const scale = Math.min(1, STANDARD_MAX_SIDE / Math.max(opened.width, opened.height, 1));
|
|
125
|
+
const width = Math.max(1, Math.round(opened.width * scale));
|
|
126
|
+
const height = Math.max(1, Math.round(opened.height * scale));
|
|
127
|
+
const out = await opened.render(width, height);
|
|
128
|
+
const candidates = [{ mime: 'image/png', bytes: out.png }];
|
|
129
|
+
if (out.jpeg)
|
|
130
|
+
candidates.push({ mime: 'image/jpeg', bytes: out.jpeg });
|
|
131
|
+
// Already within the size: the original stays when it is the smallest (a GIF always becomes
|
|
132
|
+
// its first frame, so the original GIF is no candidate).
|
|
133
|
+
if (scale === 1 && parsed.mime !== 'image/gif')
|
|
134
|
+
candidates.push({ mime: parsed.mime, bytes: parsed.bytes, original: true });
|
|
135
|
+
const best = candidates.reduce((a, b) => (b.bytes.length < a.bytes.length ? b : a));
|
|
136
|
+
if (best.original)
|
|
137
|
+
return given;
|
|
138
|
+
const sent = { data: base64(best.bytes), mime: best.mime };
|
|
139
|
+
if (given.alt !== undefined)
|
|
140
|
+
sent.alt = given.alt;
|
|
141
|
+
return sent;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return given;
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
opened.close();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function dataOf(data, mime) {
|
|
151
|
+
let body = data;
|
|
152
|
+
let type = mime;
|
|
153
|
+
if (data.startsWith('data:')) {
|
|
154
|
+
const comma = data.indexOf(',');
|
|
155
|
+
const head = data.slice(5, comma);
|
|
156
|
+
if (comma < 0 || !head.endsWith(';base64'))
|
|
157
|
+
return null;
|
|
158
|
+
type = head.slice(0, -';base64'.length);
|
|
159
|
+
body = data.slice(comma + 1);
|
|
160
|
+
}
|
|
161
|
+
if (!type)
|
|
162
|
+
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++)
|
|
167
|
+
bytes[i] = binary.charCodeAt(i);
|
|
168
|
+
return { mime: type, bytes };
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function base64(bytes) {
|
|
175
|
+
let binary = '';
|
|
176
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
177
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
178
|
+
return btoa(binary);
|
|
179
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
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
|
+
export type { AgentConfig, AgentOverride, AgentOptions, ProjectConfig, ReleasedConfig, ToolDeclaration, ToolHandler, AgentToolControls, ProjectToolContext, ProjectUsageEvent, OpenOptions, AgentActivity, AgentStateEvent } from './project-types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { CrocheRuntime, DEFAULT_MODEL, SDK_VERSION } from './core-runtime.js';
|
|
2
|
+
export { MemoryStorage, WebStorage } from './storage.js';
|
|
3
|
+
export { IndexedDbArchive } from './archive.js';
|
|
4
|
+
export { parseMarkers } from './markers.js';
|
|
5
|
+
export { toolResult, STANDARD_MAX_SIDE } from './images.js';
|
|
6
|
+
export { wikiFromModules } from './wiki.js';
|
|
7
|
+
export * from './types.js';
|
|
8
|
+
export { CORE_ABI_VERSION, CORE_WASM_SHA256 } from './core-wasm.js';
|
|
9
|
+
export { Croche, CrocheAgent } from './project-core.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { parseCoreMarkers as parseMarkers } from './core-wasm.js';
|
package/dist/markers.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { parseCoreMarkers as parseMarkers } from './core-wasm.js';
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ArchiveRuntimeStorage, RuntimeStorage, WikiDocument } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* One process owns a directory. Values are private and replaced with atomic rename.
|
|
4
|
+
* The turn archive (F20) is files beside a store's own file: `<store file>.archive0001`, one per
|
|
5
|
+
* 100 turns, JSON lines. A torn last line (a crash mid-append) is never read, and the next
|
|
6
|
+
* append writes a newline first so it cannot swallow the next record. A segment is rewritten
|
|
7
|
+
* (a ranged clear) to a temporary beside it and renamed over it; the Runtime holds the store's
|
|
8
|
+
* lock (`acquireLock`) for its whole life, so every archive call runs under it.
|
|
9
|
+
*
|
|
10
|
+
* One owner per directory and key, across processes: lock records `<key hash>.lock.<n>` beside
|
|
11
|
+
* the value, each published whole and exclusively, holding the owner's pid (see file-lock.ts). A
|
|
12
|
+
* second process gets `store_busy`. A lock left by a process that died is taken over at the next
|
|
13
|
+
* open, never because of its age.
|
|
14
|
+
*/
|
|
15
|
+
export declare class FileStorage implements RuntimeStorage {
|
|
16
|
+
private readonly directory;
|
|
17
|
+
/**
|
|
18
|
+
* The locks this instance holds, by store key: each write first checks they are still its own.
|
|
19
|
+
* "Each write" includes the turn archive: an append, a segment rewrite's rename, and a segment's
|
|
20
|
+
* deletion are each fenced at the point they change the file.
|
|
21
|
+
*/
|
|
22
|
+
private readonly fences;
|
|
23
|
+
constructor(directory: string);
|
|
24
|
+
/** Throws `store_busy` if a lock this instance holds is no longer its own. */
|
|
25
|
+
private fence;
|
|
26
|
+
private path;
|
|
27
|
+
readonly archive: ArchiveRuntimeStorage;
|
|
28
|
+
/**
|
|
29
|
+
* The step that makes a segment rewrite visible: one rename over the old file. A crash before
|
|
30
|
+
* it leaves the old segment whole and a stale temporary, which the next open deletes. Like a
|
|
31
|
+
* value's replacement, a briefly blocked rename is retried on Windows (`replaceFile`).
|
|
32
|
+
*/
|
|
33
|
+
protected commitEntry(temporary: string, target: string): Promise<void>;
|
|
34
|
+
acquireLock(key: string): Promise<() => Promise<void>>;
|
|
35
|
+
/** Segment rewrites a crash interrupted (`<segment>.tmp-<nonce>`): deleted, as the owner opens. */
|
|
36
|
+
private removeStaleTemporaries;
|
|
37
|
+
getItem(key: string): Promise<string | null>;
|
|
38
|
+
setItem(key: string, value: string): Promise<void>;
|
|
39
|
+
removeItem(key: string): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The `.md` files under `dir` as wiki documents, paths relative to it with `/` (`menu/stew.md`),
|
|
43
|
+
* in name order. Subfolders are read; symbolic links and other files are skipped, as the native
|
|
44
|
+
* SDKs' loaders do. Pass the result as `wiki: { docs }` or to `runtime.wiki.set`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function wikiFromDirectory(dir: string): Promise<WikiDocument[]>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
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 { CrocheError } from './types.js';
|
|
6
|
+
import { acquireFileLock } from './file-lock.js';
|
|
7
|
+
const owners = new Set();
|
|
8
|
+
const ENTRY = /^[a-z0-9]+$/;
|
|
9
|
+
const STALE = /^archive\d{4}\.tmp-[0-9a-f-]+$/;
|
|
10
|
+
function entryPath(file, entry) {
|
|
11
|
+
if (!ENTRY.test(entry))
|
|
12
|
+
throw new CrocheError('invalid_input', 'An archive entry name is [a-z0-9]+.');
|
|
13
|
+
return `${file}.${entry}`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* One process owns a directory. Values are private and replaced with atomic rename.
|
|
17
|
+
* The turn archive (F20) is files beside a store's own file: `<store file>.archive0001`, one per
|
|
18
|
+
* 100 turns, JSON lines. A torn last line (a crash mid-append) is never read, and the next
|
|
19
|
+
* append writes a newline first so it cannot swallow the next record. A segment is rewritten
|
|
20
|
+
* (a ranged clear) to a temporary beside it and renamed over it; the Runtime holds the store's
|
|
21
|
+
* lock (`acquireLock`) for its whole life, so every archive call runs under it.
|
|
22
|
+
*
|
|
23
|
+
* One owner per directory and key, across processes: lock records `<key hash>.lock.<n>` beside
|
|
24
|
+
* the value, each published whole and exclusively, holding the owner's pid (see file-lock.ts). A
|
|
25
|
+
* second process gets `store_busy`. A lock left by a process that died is taken over at the next
|
|
26
|
+
* open, never because of its age.
|
|
27
|
+
*/
|
|
28
|
+
export class FileStorage {
|
|
29
|
+
directory;
|
|
30
|
+
/**
|
|
31
|
+
* The locks this instance holds, by store key: each write first checks they are still its own.
|
|
32
|
+
* "Each write" includes the turn archive: an append, a segment rewrite's rename, and a segment's
|
|
33
|
+
* deletion are each fenced at the point they change the file.
|
|
34
|
+
*/
|
|
35
|
+
fences = new Map();
|
|
36
|
+
constructor(directory) {
|
|
37
|
+
this.directory = directory;
|
|
38
|
+
}
|
|
39
|
+
/** Throws `store_busy` if a lock this instance holds is no longer its own. */
|
|
40
|
+
async fence(key) {
|
|
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;
|
|
44
|
+
for (const root of this.fences.keys()) {
|
|
45
|
+
if ((key === root || key.startsWith(`${root}.`)) && (owner === undefined || root.length > owner.length))
|
|
46
|
+
owner = root;
|
|
47
|
+
}
|
|
48
|
+
if (owner !== undefined)
|
|
49
|
+
await this.fences.get(owner)();
|
|
50
|
+
// Keep the existing fence for arbitrary application keys that are not
|
|
51
|
+
// sidecars of a named namespace.
|
|
52
|
+
else
|
|
53
|
+
for (const verify of this.fences.values())
|
|
54
|
+
await verify();
|
|
55
|
+
}
|
|
56
|
+
path(key) { return join(this.directory, `${createHash('sha256').update(key).digest('hex')}.json`); }
|
|
57
|
+
archive = {
|
|
58
|
+
appendLine: async (key, entry, line) => {
|
|
59
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
60
|
+
const file = await open(entryPath(this.path(key), entry), 'a+', 0o600);
|
|
61
|
+
try {
|
|
62
|
+
const { size } = await file.stat();
|
|
63
|
+
let prefix = '';
|
|
64
|
+
if (size > 0) {
|
|
65
|
+
const last = Buffer.alloc(1);
|
|
66
|
+
await file.read(last, 0, 1, size - 1);
|
|
67
|
+
if (last[0] !== 0x0a)
|
|
68
|
+
prefix = '\n';
|
|
69
|
+
}
|
|
70
|
+
await this.fence(key);
|
|
71
|
+
await file.appendFile(`${prefix}${line}\n`, 'utf8');
|
|
72
|
+
await file.sync();
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
await file.close();
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
readLines: async (key, entry) => {
|
|
79
|
+
let text;
|
|
80
|
+
try {
|
|
81
|
+
text = await readFile(entryPath(this.path(key), entry), 'utf8');
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (error.code === 'ENOENT')
|
|
85
|
+
return [];
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
const lines = text.split('\n');
|
|
89
|
+
// The piece after the last newline is a torn line ('' when the file ends cleanly).
|
|
90
|
+
lines.pop();
|
|
91
|
+
return lines.filter(line => line.length > 0);
|
|
92
|
+
},
|
|
93
|
+
replaceLines: async (key, entry, lines) => {
|
|
94
|
+
const target = entryPath(this.path(key), entry);
|
|
95
|
+
if (!lines.length) {
|
|
96
|
+
await this.archive.remove(key, entry);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
100
|
+
// `<segment>.tmp-<nonce>`: '.' and '-' are outside the entry rule, so a temporary is never
|
|
101
|
+
// an entry (not a segment, not `held` or `lock`), and `entries` never lists one.
|
|
102
|
+
const temporary = `${target}.tmp-${randomUUID()}`;
|
|
103
|
+
const file = await open(temporary, 'w', 0o600);
|
|
104
|
+
try {
|
|
105
|
+
await file.writeFile(lines.map(line => `${line}\n`).join(''), 'utf8');
|
|
106
|
+
await file.sync();
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
await file.close();
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
await this.fence(key);
|
|
113
|
+
await this.commitEntry(temporary, target);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
await unlink(temporary).catch(() => { });
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
remove: async (key, entry) => {
|
|
121
|
+
await this.fence(key);
|
|
122
|
+
try {
|
|
123
|
+
await unlink(entryPath(this.path(key), entry));
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (error.code !== 'ENOENT')
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
entries: async (key, prefix) => {
|
|
131
|
+
const base = `${createHash('sha256').update(key).digest('hex')}.json.`;
|
|
132
|
+
let names;
|
|
133
|
+
try {
|
|
134
|
+
names = await readdir(this.directory);
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (error.code === 'ENOENT')
|
|
138
|
+
return [];
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
const out = [];
|
|
142
|
+
for (const name of names) {
|
|
143
|
+
const entry = name.slice(base.length);
|
|
144
|
+
if (!name.startsWith(base) || !entry.startsWith(prefix) || !ENTRY.test(entry))
|
|
145
|
+
continue;
|
|
146
|
+
try {
|
|
147
|
+
out.push({ entry, bytes: (await stat(join(this.directory, name))).size });
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
if (error.code !== 'ENOENT')
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* The step that makes a segment rewrite visible: one rename over the old file. A crash before
|
|
159
|
+
* it leaves the old segment whole and a stale temporary, which the next open deletes. Like a
|
|
160
|
+
* value's replacement, a briefly blocked rename is retried on Windows (`replaceFile`).
|
|
161
|
+
*/
|
|
162
|
+
async commitEntry(temporary, target) {
|
|
163
|
+
await replaceFile(temporary, target);
|
|
164
|
+
}
|
|
165
|
+
async acquireLock(key) {
|
|
166
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
167
|
+
const identity = join(await realpath(this.directory), `${createHash('sha256').update(key).digest('hex')}.json`);
|
|
168
|
+
if (owners.has(identity))
|
|
169
|
+
throw new CrocheError('store_busy', 'This file namespace already has an owner in this process.');
|
|
170
|
+
owners.add(identity);
|
|
171
|
+
const path = identity.replace(/\.json$/, '.lock');
|
|
172
|
+
let lock;
|
|
173
|
+
try {
|
|
174
|
+
lock = await acquireFileLock(path, () => { owners.delete(identity); this.fences.delete(key); });
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
owners.delete(identity);
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
// Only the owner may remove a crash's segment temporaries: another process's may be live.
|
|
181
|
+
try {
|
|
182
|
+
await this.removeStaleTemporaries(key);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
await lock.release();
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
this.fences.set(key, lock.verify);
|
|
189
|
+
return lock.release;
|
|
190
|
+
}
|
|
191
|
+
/** Segment rewrites a crash interrupted (`<segment>.tmp-<nonce>`): deleted, as the owner opens. */
|
|
192
|
+
async removeStaleTemporaries(key) {
|
|
193
|
+
const base = `${createHash('sha256').update(key).digest('hex')}.json.`;
|
|
194
|
+
let names;
|
|
195
|
+
try {
|
|
196
|
+
names = await readdir(this.directory);
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (error.code === 'ENOENT')
|
|
200
|
+
return;
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
for (const name of names) {
|
|
204
|
+
if (!name.startsWith(base) || !STALE.test(name.slice(base.length)))
|
|
205
|
+
continue;
|
|
206
|
+
try {
|
|
207
|
+
await unlink(join(this.directory, name));
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
if (error.code !== 'ENOENT')
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async getItem(key) {
|
|
216
|
+
try {
|
|
217
|
+
return await readFile(this.path(key), 'utf8');
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
if (error.code === 'ENOENT')
|
|
221
|
+
return null;
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async setItem(key, value) {
|
|
226
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
227
|
+
const target = this.path(key);
|
|
228
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
229
|
+
await writeFile(temporary, value, { mode: 0o600 });
|
|
230
|
+
try {
|
|
231
|
+
await this.fence(key);
|
|
232
|
+
await replaceFile(temporary, target);
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
await unlink(temporary).catch(() => { });
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async removeItem(key) {
|
|
240
|
+
await this.fence(key);
|
|
241
|
+
try {
|
|
242
|
+
await unlink(this.path(key));
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
if (error.code !== 'ENOENT')
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** The wiki holds at most this many documents; a folder with more is refused while it is read. */
|
|
251
|
+
const WIKI_MAX_DOCUMENTS = 2000;
|
|
252
|
+
/**
|
|
253
|
+
* The `.md` files under `dir` as wiki documents, paths relative to it with `/` (`menu/stew.md`),
|
|
254
|
+
* in name order. Subfolders are read; symbolic links and other files are skipped, as the native
|
|
255
|
+
* SDKs' loaders do. Pass the result as `wiki: { docs }` or to `runtime.wiki.set`.
|
|
256
|
+
*/
|
|
257
|
+
export async function wikiFromDirectory(dir) {
|
|
258
|
+
const out = [];
|
|
259
|
+
async function walk(at, prefix) {
|
|
260
|
+
let entries;
|
|
261
|
+
try {
|
|
262
|
+
entries = await readdir(at, { withFileTypes: true });
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
throw new CrocheError('invalid_wiki', `${at}: ${error.message}`);
|
|
266
|
+
}
|
|
267
|
+
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
268
|
+
for (const entry of entries) {
|
|
269
|
+
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
270
|
+
if (entry.isDirectory())
|
|
271
|
+
await walk(join(at, entry.name), path);
|
|
272
|
+
else if (entry.isFile() && entry.name.endsWith('.md')) {
|
|
273
|
+
if (out.length >= WIKI_MAX_DOCUMENTS)
|
|
274
|
+
throw new CrocheError('invalid_wiki', `The wiki holds at most ${WIKI_MAX_DOCUMENTS} documents`);
|
|
275
|
+
out.push({ path, markdown: await readFile(join(at, entry.name), 'utf8') });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
await walk(dir, '');
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { AgentOptions, AgentToolControls, OpenOptions } from './project-types.js';
|
|
2
|
+
import { type StreamSelectOptions } from './stream-hub.js';
|
|
3
|
+
import type { SendInput, SendOptions, JsonValue, RuntimeMemoryApi } from './types.js';
|
|
4
|
+
/** Events are owned and projected by Core; unknown event fields remain intact. */
|
|
5
|
+
export type AgentEvent = {
|
|
6
|
+
type: string;
|
|
7
|
+
[key: string]: JsonValue | undefined;
|
|
8
|
+
};
|
|
9
|
+
export declare class CrocheAgent implements AgentToolControls {
|
|
10
|
+
/** The same memory API as this agent's host Runtime. */
|
|
11
|
+
get memory(): RuntimeMemoryApi;
|
|
12
|
+
private closing?;
|
|
13
|
+
private ended;
|
|
14
|
+
private hub;
|
|
15
|
+
private handle;
|
|
16
|
+
private host;
|
|
17
|
+
private constructor();
|
|
18
|
+
private initialize;
|
|
19
|
+
get id(): string;
|
|
20
|
+
get instance(): string | null;
|
|
21
|
+
get created(): boolean;
|
|
22
|
+
get name(): string | null;
|
|
23
|
+
get mode(): string | null;
|
|
24
|
+
get visibleTools(): string[] | null;
|
|
25
|
+
setTools(visible: string[] | null): Promise<void>;
|
|
26
|
+
setMode(mode: string | null): Promise<void>;
|
|
27
|
+
get closed(): boolean;
|
|
28
|
+
get logId(): string;
|
|
29
|
+
sync(): Promise<void>;
|
|
30
|
+
send(input: SendInput, options?: Pick<SendOptions, 'signal' | 'responseFormat' | 'imageResolution'>): Promise<import("./stream-hub.js").StreamReceipt>;
|
|
31
|
+
subscribe(options: StreamSelectOptions & {
|
|
32
|
+
onEvent: (event: AgentEvent) => void | Promise<void>;
|
|
33
|
+
}): import("./stream-branch.js").AppStreamSubscription & {
|
|
34
|
+
history(options: {
|
|
35
|
+
before?: number;
|
|
36
|
+
limit: number;
|
|
37
|
+
}): Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
history(options: {
|
|
40
|
+
before?: number;
|
|
41
|
+
limit: number;
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
/** Sends and waits until the input is final (with `wait: 'idle'`, until the agent is idle too). */
|
|
44
|
+
request(input: SendInput, options?: Pick<SendOptions, 'signal' | 'responseFormat'> & {
|
|
45
|
+
wait?: 'idle';
|
|
46
|
+
}): Promise<import("./stream-hub.js").StreamRequestResult>;
|
|
47
|
+
/** Deletes the conversation; the app empties its list on the durable `cleared` event. */
|
|
48
|
+
clearHistory(): Promise<void>;
|
|
49
|
+
/** Cancels input `id`, or with no id stops the turn running now; resolves once the stop is saved. */
|
|
50
|
+
cancel(id?: string): Promise<void>;
|
|
51
|
+
/** Closes the agent; the Core projection fence does not await buffered SDK/UI consumers.
|
|
52
|
+
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
53
|
+
* wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
|
|
54
|
+
close(): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
/** Core owns the census, config selection/overrides, record, ids, locks and lifecycle. */
|
|
57
|
+
export declare class Croche {
|
|
58
|
+
private readonly agents;
|
|
59
|
+
private closing?;
|
|
60
|
+
private handle;
|
|
61
|
+
private pals;
|
|
62
|
+
private constructor();
|
|
63
|
+
static open(options: OpenOptions): Promise<Croche>;
|
|
64
|
+
/**
|
|
65
|
+
* Deletes stores on this device (R8): with `agent`, that agent's store for `user`, declared or
|
|
66
|
+
* not, including its instances; without, declared main stores and every registered instance
|
|
67
|
+
* for that user, including retired agents. All stores are locked first. Rejects `store_busy`
|
|
68
|
+
* when one is open, and then nothing is deleted. The project record is kept.
|
|
69
|
+
*/
|
|
70
|
+
static deleteStore(options: OpenOptions & {
|
|
71
|
+
agent?: string;
|
|
72
|
+
}): Promise<void>;
|
|
73
|
+
get user(): string | null;
|
|
74
|
+
get installationId(): string | null;
|
|
75
|
+
get crocheUserId(): string | null;
|
|
76
|
+
get agentIds(): readonly string[];
|
|
77
|
+
agent(id?: string, options?: AgentOptions): Promise<CrocheAgent>;
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
}
|