@h1r-ai/croche 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/README.md +1176 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/dist/archive.d.ts +47 -0
- package/dist/archive.js +217 -0
- package/dist/atomic-replace.d.ts +18 -0
- package/dist/atomic-replace.js +39 -0
- package/dist/commands.d.ts +56 -0
- package/dist/commands.js +1 -0
- package/dist/control.d.ts +62 -0
- package/dist/control.js +269 -0
- package/dist/core-abi.d.ts +110 -0
- package/dist/core-abi.js +1 -0
- package/dist/core-bindgen.d.ts +413 -0
- package/dist/core-bindgen.js +1533 -0
- package/dist/core-runtime.d.ts +214 -0
- package/dist/core-runtime.js +837 -0
- package/dist/core-wasm-bytes.d.ts +4 -0
- package/dist/core-wasm-bytes.js +5 -0
- package/dist/core-wasm.d.ts +16 -0
- package/dist/core-wasm.js +63 -0
- package/dist/debug.d.ts +26 -0
- package/dist/debug.js +171 -0
- package/dist/file-lock.d.ts +46 -0
- package/dist/file-lock.js +300 -0
- package/dist/images.d.ts +53 -0
- package/dist/images.js +179 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +9 -0
- package/dist/markers.d.ts +1 -0
- package/dist/markers.js +1 -0
- package/dist/node.d.ts +46 -0
- package/dist/node.js +281 -0
- package/dist/project-core.d.ts +79 -0
- package/dist/project-core.js +261 -0
- package/dist/project-session.d.ts +44 -0
- package/dist/project-session.js +143 -0
- package/dist/project-types.d.ts +97 -0
- package/dist/project-types.js +1 -0
- package/dist/project-wire.d.ts +19 -0
- package/dist/project-wire.js +39 -0
- package/dist/sse.d.ts +19 -0
- package/dist/sse.js +53 -0
- package/dist/storage.d.ts +24 -0
- package/dist/storage.js +32 -0
- package/dist/stream-branch.d.ts +47 -0
- package/dist/stream-branch.js +107 -0
- package/dist/stream-hub.d.ts +207 -0
- package/dist/stream-hub.js +210 -0
- package/dist/stream.d.ts +3 -0
- package/dist/stream.js +5 -0
- package/dist/types.d.ts +930 -0
- package/dist/types.js +8 -0
- package/dist/wiki.d.ts +15 -0
- package/dist/wiki.js +25 -0
- package/docs/CODING-AGENT.md +92 -0
- package/docs/DEBUGGER.md +230 -0
- package/docs/S2-IMPLEMENTATION.md +585 -0
- package/docs/SKILL.md +295 -0
- package/package.json +52 -4
- package/src/archive.ts +188 -0
- package/src/atomic-replace.ts +43 -0
- package/src/commands.ts +62 -0
- package/src/control.ts +179 -0
- package/src/core-abi.ts +52 -0
- package/src/core-bindgen.ts +1557 -0
- package/src/core-runtime.ts +750 -0
- package/src/core-wasm-bytes.ts +5 -0
- package/src/core-wasm.ts +57 -0
- package/src/debug.ts +160 -0
- package/src/file-lock.ts +269 -0
- package/src/images.ts +174 -0
- package/src/index.ts +15 -0
- package/src/markers.ts +1 -0
- package/src/node.ts +194 -0
- package/src/project-core.ts +231 -0
- package/src/project-session.ts +118 -0
- package/src/project-types.ts +77 -0
- package/src/project-wire.ts +39 -0
- package/src/sse.ts +57 -0
- package/src/storage.ts +30 -0
- package/src/stream-branch.ts +112 -0
- package/src/stream-hub.ts +249 -0
- package/src/stream.ts +7 -0
- package/src/types.ts +840 -0
- package/src/wiki.ts +25 -0
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { core } from './core-wasm.js';
|
|
2
|
+
import { projectPal, receiptSend } from './core-runtime.js';
|
|
3
|
+
import { CrocheError } from './types.js';
|
|
4
|
+
import { deleteWire, projectWire } from './project-wire.js';
|
|
5
|
+
import { StreamHub } from './stream-hub.js';
|
|
6
|
+
function rethrow(error) {
|
|
7
|
+
if (error instanceof CrocheError)
|
|
8
|
+
throw error;
|
|
9
|
+
const value = error;
|
|
10
|
+
if (value && typeof value.code === 'string')
|
|
11
|
+
throw new CrocheError(value.code, typeof value.message === 'string' ? value.message : 'The Core operation failed.');
|
|
12
|
+
throw new CrocheError('core_error', 'The shared Core could not complete this operation.');
|
|
13
|
+
}
|
|
14
|
+
function call(operation) { try {
|
|
15
|
+
return operation();
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return rethrow(error);
|
|
19
|
+
} }
|
|
20
|
+
async function held(operation) {
|
|
21
|
+
const alive = setInterval(() => { }, 0x7fffffff);
|
|
22
|
+
try {
|
|
23
|
+
return await operation();
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
return rethrow(error);
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
clearInterval(alive);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function json(value) {
|
|
33
|
+
try {
|
|
34
|
+
return JSON.stringify(value, (_key, item) => {
|
|
35
|
+
if (typeof item === 'number' && !Number.isFinite(item))
|
|
36
|
+
throw new Error('Non-finite number');
|
|
37
|
+
if (['function', 'symbol', 'bigint'].includes(typeof item))
|
|
38
|
+
throw new Error('Non-JSON value');
|
|
39
|
+
return item;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new CrocheError('invalid_configuration', 'Configuration must be JSON serializable.');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function observe(callback, event) {
|
|
47
|
+
try {
|
|
48
|
+
void Promise.resolve(callback?.(event)).catch(() => { });
|
|
49
|
+
}
|
|
50
|
+
catch { /* Host observer isolation. */ }
|
|
51
|
+
}
|
|
52
|
+
let agentFromCore;
|
|
53
|
+
export class CrocheAgent {
|
|
54
|
+
/** The same memory API as this agent's host Runtime. */
|
|
55
|
+
get memory() { return this.host.memory; }
|
|
56
|
+
closing;
|
|
57
|
+
ended = false;
|
|
58
|
+
hub;
|
|
59
|
+
handle;
|
|
60
|
+
host;
|
|
61
|
+
constructor() { }
|
|
62
|
+
initialize(handle, host) {
|
|
63
|
+
this.handle = handle;
|
|
64
|
+
this.host = host;
|
|
65
|
+
const port = {
|
|
66
|
+
observe: (onEvent, onEnd) => {
|
|
67
|
+
call(() => handle.observe((event) => onEvent(JSON.parse(event)), (error) => onEnd(JSON.parse(error))));
|
|
68
|
+
return { close: () => call(() => handle.unobserve()) };
|
|
69
|
+
},
|
|
70
|
+
select: (options, onEvent) => {
|
|
71
|
+
const id = call(() => handle.select(json(options), (event) => onEvent(JSON.parse(event))));
|
|
72
|
+
return { close: () => call(() => handle.closeProjection(id)),
|
|
73
|
+
history: options => held(() => handle.history(id, options.before, options.limit)) };
|
|
74
|
+
},
|
|
75
|
+
send: (input, options) => host[receiptSend](input, options),
|
|
76
|
+
cancel: id => held(() => id === undefined ? handle.cancelTurn() : handle.cancel(id)),
|
|
77
|
+
readOutcome: async (id, from, captured) => JSON.parse(await held(() => handle.readOutcome(id, from, (event) => captured(JSON.parse(event))))),
|
|
78
|
+
};
|
|
79
|
+
this.hub = new StreamHub(port);
|
|
80
|
+
}
|
|
81
|
+
static {
|
|
82
|
+
agentFromCore = (handle, host) => {
|
|
83
|
+
const agent = new CrocheAgent();
|
|
84
|
+
agent.initialize(handle, host);
|
|
85
|
+
return agent;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
get id() { return call(() => this.handle.agentId()); }
|
|
89
|
+
get instance() { return call(() => this.handle.instance()) ?? null; }
|
|
90
|
+
get created() { return call(() => this.handle.created()); }
|
|
91
|
+
get name() { return call(() => this.handle.name()) ?? null; }
|
|
92
|
+
get mode() { return call(() => this.handle.mode()) ?? null; }
|
|
93
|
+
get visibleTools() {
|
|
94
|
+
return call(() => {
|
|
95
|
+
const names = this.handle.visibleTools();
|
|
96
|
+
return names == null ? null : JSON.parse(names);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
setTools(visible) {
|
|
100
|
+
return held(() => this.handle.setTools(visible === null ? undefined : json(visible)));
|
|
101
|
+
}
|
|
102
|
+
setMode(mode) {
|
|
103
|
+
return held(() => this.handle.setMode(mode ?? undefined));
|
|
104
|
+
}
|
|
105
|
+
get closed() { return call(() => this.handle.isClosed()); }
|
|
106
|
+
get logId() { return call(() => this.handle.logId()); }
|
|
107
|
+
sync() { return this.host.sync(); }
|
|
108
|
+
send(input, options = {}) {
|
|
109
|
+
// Image preparation is host-local; the actual receipt and observation are Core's.
|
|
110
|
+
if (this.ended)
|
|
111
|
+
return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
|
|
112
|
+
if (Object.hasOwn(options, 'onEvent'))
|
|
113
|
+
return Promise.reject(new CrocheError('invalid_input', 'Use agent.subscribe for events; send has no onEvent option.'));
|
|
114
|
+
try {
|
|
115
|
+
return this.host[receiptSend](input, options);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
return Promise.reject(error);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
subscribe(options) {
|
|
122
|
+
return this.hub.subscribe(options);
|
|
123
|
+
}
|
|
124
|
+
history(options) { return this.hub.history(options); }
|
|
125
|
+
/** Sends and waits until the input is final (with `wait: 'idle'`, until the agent is idle too). */
|
|
126
|
+
request(input, options = {}) {
|
|
127
|
+
if (this.ended)
|
|
128
|
+
return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
|
|
129
|
+
return this.hub.request(input, options);
|
|
130
|
+
}
|
|
131
|
+
/** Deletes the conversation; the app empties its list on the durable `cleared` event. */
|
|
132
|
+
clearHistory() {
|
|
133
|
+
if (this.ended)
|
|
134
|
+
return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
|
|
135
|
+
return this.host.clearHistory();
|
|
136
|
+
}
|
|
137
|
+
/** Cancels input `id`, or with no id stops the turn running now; resolves once the stop is saved. */
|
|
138
|
+
cancel(id) {
|
|
139
|
+
if (this.ended)
|
|
140
|
+
return Promise.reject(new CrocheError('closed', 'The agent is closed.'));
|
|
141
|
+
return this.hub.cancel(id);
|
|
142
|
+
}
|
|
143
|
+
/** Closes the agent; the Core projection fence does not await buffered SDK/UI consumers.
|
|
144
|
+
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
145
|
+
* wait-for-callback fence. A synchronous Core-listener self-close does not wait on itself. */
|
|
146
|
+
close() {
|
|
147
|
+
return this.closing ??= (async () => {
|
|
148
|
+
this.ended = true;
|
|
149
|
+
try {
|
|
150
|
+
await this.host.close();
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
this.hub.close();
|
|
154
|
+
}
|
|
155
|
+
})();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Core owns the census, config selection/overrides, record, ids, locks and lifecycle. */
|
|
159
|
+
export class Croche {
|
|
160
|
+
agents = new Map();
|
|
161
|
+
closing;
|
|
162
|
+
handle;
|
|
163
|
+
pals;
|
|
164
|
+
constructor() { }
|
|
165
|
+
static async open(options) {
|
|
166
|
+
if (['storageKey', 'identity'].some(key => Object.hasOwn(options, key))) {
|
|
167
|
+
throw new CrocheError('invalid_configuration', 'storageKey and identity overrides are not supported.');
|
|
168
|
+
}
|
|
169
|
+
if (options.serverKey !== undefined && typeof document !== 'undefined') {
|
|
170
|
+
throw new CrocheError('invalid_configuration', 'serverKey belongs on your backend, never in a browser.');
|
|
171
|
+
}
|
|
172
|
+
if (!options.storage || typeof options.storage.getItem !== 'function' || typeof options.storage.setItem !== 'function') {
|
|
173
|
+
throw new CrocheError('invalid_configuration', 'Atomic Runtime storage is required.');
|
|
174
|
+
}
|
|
175
|
+
const archive = options.storage.archive;
|
|
176
|
+
if (archive !== undefined && (!archive ||
|
|
177
|
+
['appendLine', 'readLines', 'replaceLines', 'remove', 'entries'].some(key => typeof archive[key] !== 'function'))) {
|
|
178
|
+
throw new CrocheError('invalid_configuration', 'storage.archive needs appendLine, readLines, replaceLines, remove and entries.');
|
|
179
|
+
}
|
|
180
|
+
const language = options.language ?? (typeof document !== 'undefined' && typeof navigator !== 'undefined' ? navigator.language : undefined);
|
|
181
|
+
const owned = { ...options, ...(language === undefined ? {} : { language }), handlers: { ...options.handlers } };
|
|
182
|
+
if (Object.values(owned.handlers).some(handler => typeof handler !== 'function')) {
|
|
183
|
+
throw new CrocheError('invalid_configuration', 'Every handler must be a function.');
|
|
184
|
+
}
|
|
185
|
+
// Freeze the bundled data before awaiting the record; caller mutation cannot change
|
|
186
|
+
// later agent opens. Core, not this encoding, validates every schema/override field.
|
|
187
|
+
const wire = json(projectWire(owned));
|
|
188
|
+
const pals = new Map();
|
|
189
|
+
let project;
|
|
190
|
+
const factory = (agent) => {
|
|
191
|
+
// A new host whenever Core asks for one. A closed/reopened agent must not reuse
|
|
192
|
+
// a closed timer owner. Record PAL and default-agent PAL are separate requests.
|
|
193
|
+
const pal = projectPal(owned, () => project.user);
|
|
194
|
+
if (!agent.startsWith('["$gc",'))
|
|
195
|
+
pals.set(agent, pal);
|
|
196
|
+
return pal.host;
|
|
197
|
+
};
|
|
198
|
+
const debug = owned.onDebugEvent ? (event) => observe(owned.onDebugEvent, JSON.parse(event)) : undefined;
|
|
199
|
+
const usage = owned.onUsage ? (event) => observe(owned.onUsage, {
|
|
200
|
+
...JSON.parse(event), user: project.user, crocheUserId: project.crocheUserId,
|
|
201
|
+
}) : undefined;
|
|
202
|
+
const handle = await held(() => core().WasmProject.open(factory, wire, debug, usage));
|
|
203
|
+
project = new Croche();
|
|
204
|
+
project.handle = handle;
|
|
205
|
+
project.pals = pals;
|
|
206
|
+
return project;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Deletes stores on this device (R8): with `agent`, that agent's store for `user`, declared or
|
|
210
|
+
* not, including its instances; without, declared main stores and every registered instance
|
|
211
|
+
* for that user, including retired agents. All stores are locked first. Rejects `store_busy`
|
|
212
|
+
* when one is open, and then nothing is deleted. The project record is kept.
|
|
213
|
+
*/
|
|
214
|
+
static async deleteStore(options) {
|
|
215
|
+
if (!options.storage || typeof options.storage.getItem !== 'function' || typeof options.storage.setItem !== 'function') {
|
|
216
|
+
throw new CrocheError('invalid_configuration', 'Atomic Runtime storage is required.');
|
|
217
|
+
}
|
|
218
|
+
const factory = (_agent) => projectPal(options, () => options.user ?? null).host;
|
|
219
|
+
await held(() => core().WasmProject.deleteStore(factory, json(deleteWire(options))));
|
|
220
|
+
}
|
|
221
|
+
get user() { return call(() => this.handle.user()) ?? null; }
|
|
222
|
+
get installationId() { return call(() => this.handle.installationId()) ?? null; }
|
|
223
|
+
get crocheUserId() { return call(() => this.handle.crocheUserId()) ?? null; }
|
|
224
|
+
get agentIds() { return call(() => JSON.parse(this.handle.agentIds())); }
|
|
225
|
+
async agent(id, options = {}) {
|
|
226
|
+
// Core prunes its closed slots on open; release the corresponding JS handles and hosts too.
|
|
227
|
+
for (const [slot, agent] of this.agents) {
|
|
228
|
+
if (agent.closed) {
|
|
229
|
+
this.agents.delete(slot);
|
|
230
|
+
this.pals.delete(slot);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// Always call Core, including cached agents: it validates override equality and closed
|
|
234
|
+
// state. The map only preserves the JS object's identity, never admission policy.
|
|
235
|
+
const handle = await held(() => this.handle.agentWithOptions(id, json(options)));
|
|
236
|
+
const name = id ?? 'default';
|
|
237
|
+
const instance = call(() => handle.instance());
|
|
238
|
+
const slot = instance == null ? name : JSON.stringify([name, instance]);
|
|
239
|
+
const existing = this.agents.get(slot);
|
|
240
|
+
if (existing && !existing.closed) {
|
|
241
|
+
handle.free();
|
|
242
|
+
return existing;
|
|
243
|
+
}
|
|
244
|
+
const pal = this.pals.get(slot);
|
|
245
|
+
if (!pal)
|
|
246
|
+
throw new CrocheError('core_error', 'Core opened an agent without requesting its host.');
|
|
247
|
+
const agent = agentFromCore(handle, pal.attach(handle));
|
|
248
|
+
this.agents.set(slot, agent);
|
|
249
|
+
return agent;
|
|
250
|
+
}
|
|
251
|
+
close() {
|
|
252
|
+
return this.closing ??= (async () => {
|
|
253
|
+
try {
|
|
254
|
+
await held(() => this.handle.close());
|
|
255
|
+
}
|
|
256
|
+
finally {
|
|
257
|
+
await Promise.all([...this.agents.values()].map(agent => agent.close()));
|
|
258
|
+
}
|
|
259
|
+
})();
|
|
260
|
+
}
|
|
261
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { AgentOverride, OpenOptions } from './project-types.js';
|
|
2
|
+
/** Target SDK surface. Not exported from the package until a real Core adapter is bound. */
|
|
3
|
+
export interface AgentSession {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly name: string | null;
|
|
6
|
+
close(): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export interface ProjectIdentity {
|
|
9
|
+
crocheUserId: string | null;
|
|
10
|
+
installationId: string | null;
|
|
11
|
+
}
|
|
12
|
+
/** Internal injection boundary, not a proposed Rust ABI. Core owns config/identity/storage. */
|
|
13
|
+
export interface ProjectDriver<A extends AgentSession> {
|
|
14
|
+
identity(): ProjectIdentity;
|
|
15
|
+
openAgent(id: string, override?: AgentOverride): Promise<A>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
export interface ProjectFactoryPort<A extends AgentSession> {
|
|
19
|
+
open(options: OpenOptions): Promise<ProjectDriver<A>>;
|
|
20
|
+
deleteStore(options: OpenOptions & {
|
|
21
|
+
agent?: string;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** Project lifecycle only: does not merge config, derive storage keys, mint ids or issue credit. */
|
|
25
|
+
export declare class ProjectSession<A extends AgentSession> {
|
|
26
|
+
private readonly options;
|
|
27
|
+
private readonly driver;
|
|
28
|
+
private readonly ids;
|
|
29
|
+
private readonly agents;
|
|
30
|
+
private closing?;
|
|
31
|
+
private closed;
|
|
32
|
+
private constructor();
|
|
33
|
+
static open<A extends AgentSession>(options: OpenOptions, port: ProjectFactoryPort<A>): Promise<ProjectSession<A>>;
|
|
34
|
+
get user(): string | null;
|
|
35
|
+
get crocheUserId(): string | null;
|
|
36
|
+
get installationId(): string | null;
|
|
37
|
+
agent(id?: string, options?: {
|
|
38
|
+
config?: AgentOverride;
|
|
39
|
+
}): Promise<A>;
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
static deleteStore<A extends AgentSession>(options: OpenOptions & {
|
|
42
|
+
agent?: string;
|
|
43
|
+
}, port: ProjectFactoryPort<A>): Promise<void>;
|
|
44
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { CrocheError } from './types.js';
|
|
2
|
+
const invalid = (message) => new CrocheError('invalid_configuration', message);
|
|
3
|
+
function copy(value) {
|
|
4
|
+
try {
|
|
5
|
+
return JSON.parse(JSON.stringify(value, (_key, item) => {
|
|
6
|
+
if (typeof item === 'number' && !Number.isFinite(item))
|
|
7
|
+
throw invalid('Configuration contains a non-finite number.');
|
|
8
|
+
if (typeof item === 'function' || typeof item === 'symbol')
|
|
9
|
+
throw invalid('Configuration cannot contain callbacks.');
|
|
10
|
+
return item;
|
|
11
|
+
}));
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw invalid('Configuration must be JSON serializable.');
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Comparison only; not a hash, canonicalization contract or config resolver. */
|
|
18
|
+
function ordered(value) {
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return value.map(ordered);
|
|
21
|
+
if (value && typeof value === 'object')
|
|
22
|
+
return Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function bundled(options) {
|
|
26
|
+
return 'version' in options.config ? options.config.config : options.config;
|
|
27
|
+
}
|
|
28
|
+
function checkHandlers(config, handlers, declared = new Set()) {
|
|
29
|
+
if (!config || typeof config !== 'object')
|
|
30
|
+
return declared;
|
|
31
|
+
const node = config;
|
|
32
|
+
if (Array.isArray(node.tools))
|
|
33
|
+
for (const tool of node.tools) {
|
|
34
|
+
if (!tool || typeof tool.name !== 'string' || !Object.hasOwn(handlers ?? {}, tool.name) || typeof handlers?.[tool.name] !== 'function')
|
|
35
|
+
throw invalid('Every tool declaration needs a registered handler.');
|
|
36
|
+
declared.add(tool.name);
|
|
37
|
+
}
|
|
38
|
+
for (const child of Object.values(node.languages ?? {}))
|
|
39
|
+
checkHandlers(child, handlers, declared);
|
|
40
|
+
for (const child of Object.values(node.agents ?? {}))
|
|
41
|
+
checkHandlers(child, handlers, declared);
|
|
42
|
+
for (const child of Object.values(node.modes ?? {}))
|
|
43
|
+
checkHandlers(child, handlers, declared);
|
|
44
|
+
return declared;
|
|
45
|
+
}
|
|
46
|
+
function checkId(id, ids) {
|
|
47
|
+
if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(id) || !ids.has(id))
|
|
48
|
+
throw invalid('The agent id is not declared in the bundled config.');
|
|
49
|
+
}
|
|
50
|
+
/** Project lifecycle only: does not merge config, derive storage keys, mint ids or issue credit. */
|
|
51
|
+
export class ProjectSession {
|
|
52
|
+
options;
|
|
53
|
+
driver;
|
|
54
|
+
ids;
|
|
55
|
+
agents = new Map();
|
|
56
|
+
closing;
|
|
57
|
+
closed = false;
|
|
58
|
+
constructor(options, driver, ids) {
|
|
59
|
+
this.options = options;
|
|
60
|
+
this.driver = driver;
|
|
61
|
+
this.ids = ids;
|
|
62
|
+
}
|
|
63
|
+
static async open(options, port) {
|
|
64
|
+
if (options.user !== undefined && (typeof options.user !== 'string' || options.user.length < 1 || options.user.length > 200))
|
|
65
|
+
throw invalid('user must be a string of 1 to 200 characters.');
|
|
66
|
+
if (options.serverKey !== undefined && options.user === undefined)
|
|
67
|
+
throw invalid('Server opens require user.');
|
|
68
|
+
const language = options.language ?? (typeof document !== 'undefined' && typeof navigator !== 'undefined' ? navigator.language : undefined);
|
|
69
|
+
const owned = { ...options, ...(language === undefined ? {} : { language }), config: copy(options.config), handlers: { ...options.handlers } };
|
|
70
|
+
const declared = checkHandlers(bundled(owned), owned.handlers);
|
|
71
|
+
if (Object.keys(owned.handlers).some(name => !declared.has(name)))
|
|
72
|
+
throw invalid('Every registered handler needs a tool declaration in the bundled config.');
|
|
73
|
+
const ids = new Set(['default', ...Object.keys(bundled(owned).agents ?? {})]);
|
|
74
|
+
for (const id of ids)
|
|
75
|
+
checkId(id, ids);
|
|
76
|
+
return new ProjectSession(owned, await port.open(owned), ids);
|
|
77
|
+
}
|
|
78
|
+
get user() { return this.options.user ?? null; }
|
|
79
|
+
get crocheUserId() { return this.driver.identity().crocheUserId; }
|
|
80
|
+
get installationId() { return this.driver.identity().installationId; }
|
|
81
|
+
async agent(id = 'default', options = {}) {
|
|
82
|
+
if (this.closed)
|
|
83
|
+
throw new CrocheError('closed', 'The project is closed.');
|
|
84
|
+
checkId(id, this.ids);
|
|
85
|
+
const override = options.config === undefined ? undefined : copy(options.config);
|
|
86
|
+
if (override && ('agents' in override || 'defaultLanguage' in override))
|
|
87
|
+
throw invalid('Code override cannot set agents or defaultLanguage.');
|
|
88
|
+
checkHandlers(override, this.options.handlers);
|
|
89
|
+
const key = JSON.stringify(ordered(override ?? {}));
|
|
90
|
+
const current = this.agents.get(id);
|
|
91
|
+
if (current) {
|
|
92
|
+
if (current.closing) {
|
|
93
|
+
await current.closing;
|
|
94
|
+
return this.agent(id, options);
|
|
95
|
+
}
|
|
96
|
+
if (override !== undefined && current.key !== key)
|
|
97
|
+
throw invalid('Agent is already open with another configuration.');
|
|
98
|
+
return current.open;
|
|
99
|
+
}
|
|
100
|
+
const entry = { key, open: Promise.resolve().then(() => this.driver.openAgent(id, override)) };
|
|
101
|
+
this.agents.set(id, entry);
|
|
102
|
+
try {
|
|
103
|
+
const agent = await entry.open;
|
|
104
|
+
const close = agent.close.bind(agent);
|
|
105
|
+
let closing;
|
|
106
|
+
agent.close = () => entry.closing ??= closing ??= (async () => {
|
|
107
|
+
try {
|
|
108
|
+
await close();
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
if (this.agents.get(id) === entry)
|
|
112
|
+
this.agents.delete(id);
|
|
113
|
+
}
|
|
114
|
+
})();
|
|
115
|
+
if (this.closed) {
|
|
116
|
+
await agent.close();
|
|
117
|
+
throw new CrocheError('closed', 'The project closed while the agent opened.');
|
|
118
|
+
}
|
|
119
|
+
return agent;
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (this.agents.get(id) === entry)
|
|
123
|
+
this.agents.delete(id);
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
close() {
|
|
128
|
+
return this.closing ??= (async () => {
|
|
129
|
+
this.closed = true;
|
|
130
|
+
const agents = await Promise.allSettled([...this.agents.values()].map(entry => entry.open));
|
|
131
|
+
const results = await Promise.allSettled(agents.flatMap(result => result.status === 'fulfilled' ? [result.value.close()] : []));
|
|
132
|
+
const cleanup = await Promise.allSettled([this.driver.close()]);
|
|
133
|
+
const failure = [...results, ...cleanup].find((result) => result.status === 'rejected');
|
|
134
|
+
if (failure)
|
|
135
|
+
throw failure.reason;
|
|
136
|
+
})();
|
|
137
|
+
}
|
|
138
|
+
static async deleteStore(options, port) {
|
|
139
|
+
// Core owns the all-declared-agent lock/delete transaction. Explicit ids may
|
|
140
|
+
// name a store no longer declared in this bundle; do not resolve or reject it here.
|
|
141
|
+
await port.deleteStore(options);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
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
|
+
/** Replaceable declarations, never handler implementations. */
|
|
5
|
+
export interface ToolDeclaration {
|
|
6
|
+
name: string;
|
|
7
|
+
summary: string;
|
|
8
|
+
commands: RuntimeCommand[];
|
|
9
|
+
}
|
|
10
|
+
export type DeepPartial<T> = T extends readonly unknown[] ? T : T extends object ? {
|
|
11
|
+
[K in keyof T]?: DeepPartial<T[K]>;
|
|
12
|
+
} : T;
|
|
13
|
+
export interface AgentConfig extends Pick<AppOptions, 'instructions' | 'markerGuide' | 'maxContextTokens' | 'maxOutputTokens' | 'maxIterations' | 'crocheTools' | 'heartbeat'> {
|
|
14
|
+
toolGuide?: string;
|
|
15
|
+
modes?: Record<string, {
|
|
16
|
+
tools?: ToolDeclaration[];
|
|
17
|
+
toolGuide?: string;
|
|
18
|
+
}>;
|
|
19
|
+
tools?: ToolDeclaration[];
|
|
20
|
+
wiki?: WikiOptions;
|
|
21
|
+
memory?: RuntimeMemoryOptions;
|
|
22
|
+
model?: string;
|
|
23
|
+
/** Croche's level, mapped to each model's own setting; `default` sends none. */
|
|
24
|
+
reasoning?: 'default' | 'off' | 'low' | 'medium' | 'high';
|
|
25
|
+
/** The base configuration's language tag, default "en"; the sole project default. */
|
|
26
|
+
defaultLanguage?: string;
|
|
27
|
+
languages?: Record<string, AgentOverride>;
|
|
28
|
+
}
|
|
29
|
+
/** Only agents have names. A code override cannot introduce agents/defaultLanguage. */
|
|
30
|
+
export type AgentOverride = DeepPartial<Omit<AgentConfig, 'defaultLanguage'>> & {
|
|
31
|
+
name?: string;
|
|
32
|
+
};
|
|
33
|
+
export interface ProjectConfig extends AgentConfig {
|
|
34
|
+
agents?: Record<string, AgentOverride>;
|
|
35
|
+
/** Shared instance storage budget, project level only. Integer 0..1 GiB; default 16 MiB. */
|
|
36
|
+
instances?: {
|
|
37
|
+
maxBytes?: number;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** A named instance opens or creates; fresh always generates a new key. */
|
|
41
|
+
export interface AgentOptions {
|
|
42
|
+
instance?: string;
|
|
43
|
+
fresh?: boolean;
|
|
44
|
+
config?: AgentOverride;
|
|
45
|
+
}
|
|
46
|
+
export interface ReleasedConfig {
|
|
47
|
+
version: number;
|
|
48
|
+
revision: string;
|
|
49
|
+
config: ProjectConfig;
|
|
50
|
+
}
|
|
51
|
+
/** Core-owned, in-memory controls; take effect at the next model call. */
|
|
52
|
+
export interface AgentToolControls {
|
|
53
|
+
readonly mode: string | null;
|
|
54
|
+
readonly visibleTools: string[] | null;
|
|
55
|
+
setTools(visible: string[] | null): Promise<void>;
|
|
56
|
+
setMode(mode: string | null): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
export interface ProjectToolContext extends Omit<ToolContext, 'userId' | 'accountLabel' | 'agentId'> {
|
|
59
|
+
agentId: string;
|
|
60
|
+
user: string | null;
|
|
61
|
+
crocheUserId: string | null;
|
|
62
|
+
causedBy: string[];
|
|
63
|
+
origin: 'app' | 'agent';
|
|
64
|
+
}
|
|
65
|
+
export type ToolHandler = (invocation: CommandInvocation, context: ProjectToolContext) => JsonValue | ToolResult | Promise<JsonValue | ToolResult>;
|
|
66
|
+
export interface ProjectUsageEvent extends RuntimeUsageEvent {
|
|
67
|
+
user: string | null;
|
|
68
|
+
crocheUserId: string | null;
|
|
69
|
+
/** Named or generated instance key; null for the main agent. */
|
|
70
|
+
instance: string | null;
|
|
71
|
+
}
|
|
72
|
+
/** Host options never enter a remotely replaceable config. No host-set install/store identity. */
|
|
73
|
+
export interface OpenOptions extends Pick<HostOptions, 'cloudUrl' | 'projectKey' | 'storage' | 'secretStorage' | 'serverKey' | 'debugKey' | 'timeZone' | 'onDebugEvent' | 'debugVisibility' | 'backgroundSync' | 'maintenanceIntervalMs' | 'requestTimeoutMs' | 'maxPendingEvents' | 'archive' | 'imageCodec' | 'fetch' | 'clock' | 'syncIntervalMs' | 'maintenanceBackoffMs' | 'streaming'> {
|
|
74
|
+
user?: string;
|
|
75
|
+
/** The app's preferred language for this user; browser defaults to navigator.language,
|
|
76
|
+
* otherwise config.defaultLanguage ("en" when omitted). Never inferred from user text. */
|
|
77
|
+
language?: string;
|
|
78
|
+
/** Host-only retention budget, copied unchanged; Core owns validation and defaults. */
|
|
79
|
+
retentionBytes?: number;
|
|
80
|
+
config: ProjectConfig | ReleasedConfig;
|
|
81
|
+
handlers?: Record<string, ToolHandler>;
|
|
82
|
+
onUsage?: (event: ProjectUsageEvent) => void;
|
|
83
|
+
}
|
|
84
|
+
/** The stream `state`'s `activity` (sdk-internal #21): what a running agent waits on. An open
|
|
85
|
+
* string: a value this SDK does not know yet may arrive, and a stream must not fail on it. */
|
|
86
|
+
export type AgentActivity = 'model' | 'summary' | 'tool' | (string & {});
|
|
87
|
+
/** The stream's `state` event, and a snapshot's `state`. `activity` is set exactly while `status`
|
|
88
|
+
* is `running`; `tools` comes only with `tool`: the round's command keys in call order, never
|
|
89
|
+
* arguments. */
|
|
90
|
+
export interface AgentStateEvent {
|
|
91
|
+
type: 'state';
|
|
92
|
+
status: 'idle' | 'running' | 'waiting';
|
|
93
|
+
queued: number;
|
|
94
|
+
typing: boolean;
|
|
95
|
+
activity: AgentActivity | null;
|
|
96
|
+
tools?: string[];
|
|
97
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { OpenOptions } from './project-types.js';
|
|
2
|
+
/** Passed as the options JSON to WasmProject.open(pals, options, debug, usage). */
|
|
3
|
+
export declare function projectWire(options: OpenOptions): {
|
|
4
|
+
runtime: Pick<OpenOptions, "backgroundSync" | "maintenanceIntervalMs" | "streaming">;
|
|
5
|
+
language?: string | undefined;
|
|
6
|
+
config: import("./project-types.js").ProjectConfig | import("./project-types.js").ReleasedConfig;
|
|
7
|
+
handlers: string[];
|
|
8
|
+
user?: string | undefined;
|
|
9
|
+
host: Pick<OpenOptions, "archive" | "cloudUrl" | "projectKey" | "serverKey" | "debugKey" | "debugVisibility" | "requestTimeoutMs" | "maxPendingEvents" | "syncIntervalMs" | "maintenanceBackoffMs" | "retentionBytes">;
|
|
10
|
+
};
|
|
11
|
+
/** The Core owns absent-agent all-store deletion; the project record is retained. */
|
|
12
|
+
export declare function deleteWire(options: OpenOptions & {
|
|
13
|
+
agent?: string;
|
|
14
|
+
}): {
|
|
15
|
+
agent?: string | undefined;
|
|
16
|
+
config: import("./project-types.js").ProjectConfig | import("./project-types.js").ReleasedConfig;
|
|
17
|
+
user?: string | undefined;
|
|
18
|
+
host: Pick<OpenOptions, "archive" | "cloudUrl" | "projectKey" | "serverKey" | "debugKey" | "debugVisibility" | "requestTimeoutMs" | "maxPendingEvents" | "syncIntervalMs" | "maintenanceBackoffMs" | "retentionBytes">;
|
|
19
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { CrocheError } from './types.js';
|
|
2
|
+
// #377 6078466532 / 6078489328, retention placement 6078660666.
|
|
3
|
+
// This is encoding only: no config merge, defaults, identity or record logic.
|
|
4
|
+
// timeZone is PAL-only, like clock/storage (#381 6079291889).
|
|
5
|
+
const hostFields = ['cloudUrl', 'projectKey', 'serverKey', 'debugKey', 'debugVisibility',
|
|
6
|
+
'requestTimeoutMs', 'maxPendingEvents', 'syncIntervalMs', 'maintenanceBackoffMs',
|
|
7
|
+
'archive', 'retentionBytes'];
|
|
8
|
+
const runtimeFields = ['streaming', 'backgroundSync', 'maintenanceIntervalMs'];
|
|
9
|
+
function pick(options, keys) {
|
|
10
|
+
return Object.fromEntries(keys.filter(key => options[key] !== undefined).map(key => [key, options[key]]));
|
|
11
|
+
}
|
|
12
|
+
/** Passed as the options JSON to WasmProject.open(pals, options, debug, usage). */
|
|
13
|
+
export function projectWire(options) {
|
|
14
|
+
if (Object.hasOwn(options, 'debugToken'))
|
|
15
|
+
throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
|
|
16
|
+
if (Object.hasOwn(options, 'defaultLanguage'))
|
|
17
|
+
throw new CrocheError('invalid_configuration', "defaultLanguage was removed from host options: set config.defaultLanguage on the project; language on project open is the app's per-user preference");
|
|
18
|
+
return {
|
|
19
|
+
host: pick(options, hostFields),
|
|
20
|
+
...(options.user === undefined ? {} : { user: options.user }),
|
|
21
|
+
config: options.config,
|
|
22
|
+
handlers: Object.keys(options.handlers ?? {}),
|
|
23
|
+
...(options.language === undefined ? {} : { language: options.language }),
|
|
24
|
+
runtime: pick(options, runtimeFields),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** The Core owns absent-agent all-store deletion; the project record is retained. */
|
|
28
|
+
export function deleteWire(options) {
|
|
29
|
+
if (Object.hasOwn(options, 'debugToken'))
|
|
30
|
+
throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
|
|
31
|
+
if (Object.hasOwn(options, 'defaultLanguage'))
|
|
32
|
+
throw new CrocheError('invalid_configuration', "defaultLanguage was removed from host options: set config.defaultLanguage on the project; language on project open is the app's per-user preference");
|
|
33
|
+
return {
|
|
34
|
+
host: pick(options, hostFields),
|
|
35
|
+
...(options.user === undefined ? {} : { user: options.user }),
|
|
36
|
+
config: options.config,
|
|
37
|
+
...(options.agent === undefined ? {} : { agent: options.agent }),
|
|
38
|
+
};
|
|
39
|
+
}
|
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** One server-sent event. `event` defaults to "message" when the block names none. */
|
|
2
|
+
export interface ServerSentEvent {
|
|
3
|
+
event: string;
|
|
4
|
+
data: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Incremental text/event-stream framing. Network reads can split anywhere — inside an
|
|
8
|
+
* event, between CR and LF, or between two events — so text is buffered until a blank
|
|
9
|
+
* line completes a block. Handles CRLF/CR/LF line endings, comment lines, and
|
|
10
|
+
* multi-line data (joined with "\n"). UTF-8 decoding is the caller's job (a streaming
|
|
11
|
+
* TextDecoder), so a multi-byte character split across reads is already whole here.
|
|
12
|
+
*/
|
|
13
|
+
export declare class EventStreamParser {
|
|
14
|
+
private buffer;
|
|
15
|
+
private carriageReturn;
|
|
16
|
+
/** End of stream: a held CR can no longer be half of a CRLF, so it ends its line. */
|
|
17
|
+
end(): ServerSentEvent[];
|
|
18
|
+
push(text: string): ServerSentEvent[];
|
|
19
|
+
}
|