@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.
- package/LICENSE +32 -0
- package/README.md +1184 -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 +928 -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 +96 -0
- package/docs/DEBUGGER.md +230 -0
- package/docs/S2-IMPLEMENTATION.md +585 -0
- package/docs/SKILL.md +337 -0
- package/docs/skills/croche/agents/openai.yaml +4 -0
- package/docs/skills/croche/references/agents.md +78 -0
- package/docs/skills/croche/references/first-turn.md +74 -0
- package/docs/skills/croche/references/tools.md +43 -0
- package/docs/skills/croche-cli/SKILL.md +158 -0
- package/docs/skills/croche-cli/agents/openai.yaml +4 -0
- package/docs/skills/croche-cli/references/powershell.md +47 -0
- package/docs/skills/croche-config/SKILL.md +152 -0
- package/docs/skills/croche-config/agents/openai.yaml +4 -0
- package/docs/skills/croche-config/references/models.md +12 -0
- package/docs/skills/croche-platforms/SKILL.md +55 -0
- package/docs/skills/croche-platforms/agents/openai.yaml +4 -0
- package/docs/skills/croche-platforms/references/android.md +185 -0
- package/docs/skills/croche-platforms/references/ios.md +165 -0
- package/docs/skills/croche-platforms/references/react-native.md +50 -0
- package/docs/skills/croche-platforms/references/web-backend.md +58 -0
- package/docs/skills/croche-troubleshoot/SKILL.md +72 -0
- package/docs/skills/croche-troubleshoot/agents/openai.yaml +4 -0
- package/docs/skills/croche-troubleshoot/references/recovery.md +31 -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 +838 -0
- package/src/wiki.ts +25 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type {OpenOptions} from './project-types.js';
|
|
2
|
+
import {CrocheError} from './types.js';
|
|
3
|
+
|
|
4
|
+
// #377 6078466532 / 6078489328, retention placement 6078660666.
|
|
5
|
+
// This is encoding only: no config merge, defaults, identity or record logic.
|
|
6
|
+
// timeZone is PAL-only, like clock/storage (#381 6079291889).
|
|
7
|
+
const hostFields = ['cloudUrl', 'projectKey', 'serverKey', 'debugKey', 'debugVisibility',
|
|
8
|
+
'requestTimeoutMs', 'maxPendingEvents', 'syncIntervalMs', 'maintenanceBackoffMs',
|
|
9
|
+
'archive', 'retentionBytes'] as const;
|
|
10
|
+
const runtimeFields = ['streaming', 'backgroundSync', 'maintenanceIntervalMs'] as const;
|
|
11
|
+
function pick<K extends keyof OpenOptions>(options: OpenOptions, keys: readonly K[]): Pick<OpenOptions, K> {
|
|
12
|
+
return Object.fromEntries(keys.filter(key => options[key] !== undefined).map(key => [key, options[key]])) as Pick<OpenOptions, K>;
|
|
13
|
+
}
|
|
14
|
+
/** Passed as the options JSON to WasmProject.open(pals, options, debug, usage). */
|
|
15
|
+
export function projectWire(options: OpenOptions) {
|
|
16
|
+
if (Object.hasOwn(options, 'debugToken')) throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
|
|
17
|
+
if (Object.hasOwn(options, 'defaultLanguage')) throw new CrocheError('invalid_configuration',
|
|
18
|
+
"defaultLanguage was removed from host options: set config.defaultLanguage on the project; language on project open is the app's per-user preference");
|
|
19
|
+
return {
|
|
20
|
+
host: pick(options, hostFields),
|
|
21
|
+
...(options.user === undefined ? {} : {user: options.user}),
|
|
22
|
+
config: options.config,
|
|
23
|
+
handlers: Object.keys(options.handlers ?? {}),
|
|
24
|
+
...(options.language === undefined ? {} : {language: options.language}),
|
|
25
|
+
runtime: pick(options, runtimeFields),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/** The Core owns absent-agent all-store deletion; the project record is retained. */
|
|
29
|
+
export function deleteWire(options: OpenOptions & {agent?: string}) {
|
|
30
|
+
if (Object.hasOwn(options, 'debugToken')) throw new CrocheError('invalid_configuration', 'debugToken was renamed to debugKey');
|
|
31
|
+
if (Object.hasOwn(options, 'defaultLanguage')) throw new CrocheError('invalid_configuration',
|
|
32
|
+
"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/src/sse.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
/**
|
|
8
|
+
* Incremental text/event-stream framing. Network reads can split anywhere — inside an
|
|
9
|
+
* event, between CR and LF, or between two events — so text is buffered until a blank
|
|
10
|
+
* line completes a block. Handles CRLF/CR/LF line endings, comment lines, and
|
|
11
|
+
* multi-line data (joined with "\n"). UTF-8 decoding is the caller's job (a streaming
|
|
12
|
+
* TextDecoder), so a multi-byte character split across reads is already whole here.
|
|
13
|
+
*/
|
|
14
|
+
export class EventStreamParser {
|
|
15
|
+
private buffer = '';
|
|
16
|
+
private carriageReturn = false;
|
|
17
|
+
|
|
18
|
+
/** End of stream: a held CR can no longer be half of a CRLF, so it ends its line. */
|
|
19
|
+
end(): ServerSentEvent[] {
|
|
20
|
+
if (!this.carriageReturn) return [];
|
|
21
|
+
this.carriageReturn = false;
|
|
22
|
+
return this.push('\n');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
push(text: string): ServerSentEvent[] {
|
|
26
|
+
let chunk = this.carriageReturn ? '\r' + text : text;
|
|
27
|
+
this.carriageReturn = false;
|
|
28
|
+
// A trailing CR may be the first half of CRLF; decide when the next read arrives.
|
|
29
|
+
if (chunk.endsWith('\r')) {
|
|
30
|
+
chunk = chunk.slice(0, -1);
|
|
31
|
+
this.carriageReturn = true;
|
|
32
|
+
}
|
|
33
|
+
this.buffer += chunk.replace(/\r\n?/g, '\n');
|
|
34
|
+
const events: ServerSentEvent[] = [];
|
|
35
|
+
for (let end = this.buffer.indexOf('\n\n'); end >= 0; end = this.buffer.indexOf('\n\n')) {
|
|
36
|
+
const block = this.buffer.slice(0, end);
|
|
37
|
+
this.buffer = this.buffer.slice(end + 2);
|
|
38
|
+
const event = parseBlock(block);
|
|
39
|
+
if (event) events.push(event);
|
|
40
|
+
}
|
|
41
|
+
return events;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseBlock(block: string): ServerSentEvent | null {
|
|
46
|
+
let event = 'message';
|
|
47
|
+
const data: string[] = [];
|
|
48
|
+
for (const line of block.split('\n')) {
|
|
49
|
+
if (line === '' || line.startsWith(':')) continue;
|
|
50
|
+
const colon = line.indexOf(':');
|
|
51
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
52
|
+
const value = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
|
|
53
|
+
if (field === 'event') event = value;
|
|
54
|
+
else if (field === 'data') data.push(value);
|
|
55
|
+
}
|
|
56
|
+
return data.length ? { event, data: data.join('\n') } : null;
|
|
57
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ArchiveRuntimeStorage, RuntimeStorage } from './types.js';
|
|
2
|
+
import { IndexedDbArchive, MemoryArchive } from './archive.js';
|
|
3
|
+
|
|
4
|
+
/** Explicit ephemeral storage for tests and one-shot prototypes. Its turn archive is in memory too. */
|
|
5
|
+
export class MemoryStorage implements RuntimeStorage {
|
|
6
|
+
private readonly values = new Map<string, string>();
|
|
7
|
+
readonly archive: ArchiveRuntimeStorage = new MemoryArchive();
|
|
8
|
+
async getItem(key: string) { return this.values.get(key) ?? null; }
|
|
9
|
+
async setItem(key: string, value: string) { this.values.set(key, value); }
|
|
10
|
+
async removeItem(key: string) { this.values.delete(key); }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Browser/WebView persistence. Supply sessionStorage only if ephemeral is intended.
|
|
15
|
+
* The turn archive (F20) goes to IndexedDB when the state is in `localStorage` and the page has
|
|
16
|
+
* IndexedDB; pass `archive` to choose another, or `null` for none. Over any other Storage
|
|
17
|
+
* (sessionStorage) there is none by default, so an ephemeral store never leaves durable turns.
|
|
18
|
+
*/
|
|
19
|
+
export class WebStorage implements RuntimeStorage {
|
|
20
|
+
get ownershipIdentity(): object { return this.storage; }
|
|
21
|
+
readonly archive?: ArchiveRuntimeStorage;
|
|
22
|
+
constructor(private readonly storage: Storage = globalThis.localStorage, archive?: ArchiveRuntimeStorage | null) {
|
|
23
|
+
if (!storage) throw new Error('WebStorage needs a browser Storage implementation.');
|
|
24
|
+
if (archive) this.archive = archive;
|
|
25
|
+
else if (archive === undefined && storage === globalThis.localStorage && globalThis.indexedDB) this.archive = new IndexedDbArchive();
|
|
26
|
+
}
|
|
27
|
+
async getItem(key: string) { return this.storage.getItem(key); }
|
|
28
|
+
async setItem(key: string, value: string) { this.storage.setItem(key, value); }
|
|
29
|
+
async removeItem(key: string) { this.storage.removeItem(key); }
|
|
30
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** SDK-only delivery branch. Core owns projection and ordering; this queue owns neither. */
|
|
2
|
+
export const APP_STREAM_MAX_EVENTS = 256;
|
|
3
|
+
export const APP_STREAM_MAX_BYTES = 1024 * 1024;
|
|
4
|
+
|
|
5
|
+
export type AppStreamEnd =
|
|
6
|
+
| { code: 'closed' | 'replaced' | 'invalid_configuration' }
|
|
7
|
+
| { code: string; cause?: unknown };
|
|
8
|
+
|
|
9
|
+
export interface AppStreamSubscription {
|
|
10
|
+
/** SDK-side ends settle without waiting for a hung handler; Core ends drain earlier
|
|
11
|
+
* callbacks first. No accepted input is cancelled by ending the app branch. */
|
|
12
|
+
readonly ended: Promise<AppStreamEnd>;
|
|
13
|
+
/** Ends the SDK branch without awaiting its current app handler. Native Core projection
|
|
14
|
+
* close separately joins its synchronous listener, except a listener's own self-close.
|
|
15
|
+
* An app callback that waits for work on the closer's thread deadlocks under any
|
|
16
|
+
* wait-for-callback fence. The Core fence does not await buffered SDK/UI consumers. */
|
|
17
|
+
close(): void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* An isolated serial branch of the one SDK hub (§18.15.2). Normal events are serial;
|
|
22
|
+
* an SDK-side final notification bypasses a hung callback and the dropped backlog.
|
|
23
|
+
* It may therefore overlap that callback, but no further normal event is delivered.
|
|
24
|
+
* The in-flight event counts
|
|
25
|
+
* against both caps. App code runs only in a microtask, never on Core's callback stack.
|
|
26
|
+
* Ending/replacing the branch does not wait for or cancel the app's current callback.
|
|
27
|
+
*/
|
|
28
|
+
export class AppStreamBranch<Event> implements AppStreamSubscription {
|
|
29
|
+
readonly ended: Promise<AppStreamEnd>;
|
|
30
|
+
private finish!: (end: AppStreamEnd) => void;
|
|
31
|
+
private active = true;
|
|
32
|
+
private accepting = true;
|
|
33
|
+
private silenced = false;
|
|
34
|
+
private running = false;
|
|
35
|
+
private queue: Array<{ event: Event; bytes: number; endAfter?: AppStreamEnd }> = [];
|
|
36
|
+
private count = 0;
|
|
37
|
+
private bytes = 0;
|
|
38
|
+
|
|
39
|
+
constructor(private readonly handler: (event: Event) => void | Promise<void>, private readonly terminalEvent?: (reason: AppStreamEnd) => Event) {
|
|
40
|
+
this.ended = new Promise(resolve => { this.finish = resolve; });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
push(event: Event, endAfter?: AppStreamEnd): void {
|
|
44
|
+
if (!this.active || !this.accepting) return;
|
|
45
|
+
// Own the value before returning to Core: a callback cannot mutate a future event.
|
|
46
|
+
let owned: Event;
|
|
47
|
+
let bytes: number;
|
|
48
|
+
try {
|
|
49
|
+
const json = JSON.stringify(event);
|
|
50
|
+
bytes = new TextEncoder().encode(json).byteLength;
|
|
51
|
+
owned = JSON.parse(json) as Event;
|
|
52
|
+
} catch (cause) {
|
|
53
|
+
this.end({ code: 'handler_failed', cause });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (this.count + 1 > APP_STREAM_MAX_EVENTS || this.bytes + bytes > APP_STREAM_MAX_BYTES) {
|
|
57
|
+
this.end({ code: 'subscriber_overflow' });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
this.queue.push({ event: owned, bytes, endAfter });
|
|
61
|
+
if (endAfter) this.accepting = false; // seal now: nothing may queue behind a Core end
|
|
62
|
+
this.count++;
|
|
63
|
+
this.bytes += bytes;
|
|
64
|
+
if (!this.running) {
|
|
65
|
+
this.running = true;
|
|
66
|
+
queueMicrotask(() => { void this.drain(); });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
get isOpen(): boolean { return this.active && this.accepting; }
|
|
71
|
+
get hasPendingEnd(): boolean { return this.active && !this.accepting; }
|
|
72
|
+
close(): void { this.silenced = true; this.end({ code: 'closed' }, false); }
|
|
73
|
+
|
|
74
|
+
end(reason: AppStreamEnd, notify = true): void {
|
|
75
|
+
if (!this.active) return;
|
|
76
|
+
this.active = false;
|
|
77
|
+
this.accepting = false;
|
|
78
|
+
this.queue = [];
|
|
79
|
+
this.count = 0;
|
|
80
|
+
this.bytes = 0;
|
|
81
|
+
if (notify && this.terminalEvent) {
|
|
82
|
+
const event = this.terminalEvent(reason);
|
|
83
|
+
// Terminal delivery bypasses the dropped backlog and a hung in-flight callback.
|
|
84
|
+
// It runs off the canonical stack, is attempted once, and cannot recursively fail.
|
|
85
|
+
queueMicrotask(() => {
|
|
86
|
+
if (this.silenced) return; // own close forbids even a previously scheduled notification
|
|
87
|
+
try { void Promise.resolve(this.handler(event)).catch(() => {}); }
|
|
88
|
+
catch { /* The final callback may itself throw; the branch is already ended. */ }
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
this.finish(reason);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private async drain(): Promise<void> {
|
|
95
|
+
while (this.active) {
|
|
96
|
+
const item = this.queue.shift();
|
|
97
|
+
if (!item) break;
|
|
98
|
+
try {
|
|
99
|
+
const pending = this.handler(item.event);
|
|
100
|
+
// An error-only subscription settles after invoking its one callback, even if
|
|
101
|
+
// application code never resolves. No future event can enter that branch.
|
|
102
|
+
if (item.endAfter) this.end(item.endAfter, false); // this event IS the final delivery
|
|
103
|
+
await pending;
|
|
104
|
+
}
|
|
105
|
+
catch (cause) { this.end({ code: 'handler_failed', cause }); }
|
|
106
|
+
if (!this.active) break;
|
|
107
|
+
this.count--;
|
|
108
|
+
this.bytes -= item.bytes;
|
|
109
|
+
}
|
|
110
|
+
this.running = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { CrocheError, type SendInput, type ResponseFormat, type JsonValue, type ToolContext } from './types.js';
|
|
2
|
+
import { AppStreamBranch, type AppStreamSubscription } from './stream-branch.js';
|
|
3
|
+
|
|
4
|
+
export type InputDisposition = 'queued' | 'seen' | 'answered' | 'no_reply' | 'failed' | 'cancelled' | 'settled_before_upgrade';
|
|
5
|
+
export interface StreamReceipt { id: string; status: InputDisposition; seq: number | null }
|
|
6
|
+
export interface StreamMessageEnd {
|
|
7
|
+
type: 'message.end'; id: string; seq: number; firstSeq: number;
|
|
8
|
+
status: 'completed' | 'failed' | 'cancelled' | 'interrupted'; text: string;
|
|
9
|
+
markers: string[]; causedBy: string[]; inReplyTo: string[]; at: string;
|
|
10
|
+
output?: JsonValue; error?: { code: string; message: string };
|
|
11
|
+
}
|
|
12
|
+
/** Conversation messages only: an event-kind input is not a message. No turnId. */
|
|
13
|
+
export interface UserMessageEvent {
|
|
14
|
+
type: 'input'; id: string; seq: number; firstSeq: number; kind: 'user';
|
|
15
|
+
status: InputDisposition; text?: string; at: string;
|
|
16
|
+
images?: { alt?: string; mime?: string; bytes?: number }[];
|
|
17
|
+
error?: { code: string; message: string };
|
|
18
|
+
}
|
|
19
|
+
export interface AgentMessageStartEvent { type: 'message.start'; id: string; seq: number; firstSeq: number; at: string }
|
|
20
|
+
export type MessageEvent = UserMessageEvent | AgentMessageStartEvent | StreamMessageEnd;
|
|
21
|
+
export interface PageEvent {
|
|
22
|
+
type: 'page'; messages: MessageEvent[]; reachedFloor: boolean; logId: string; clearedSeq: number;
|
|
23
|
+
}
|
|
24
|
+
/** Request bookkeeping consumes only canonical observations, never a UI window. */
|
|
25
|
+
export type RequestObservation =
|
|
26
|
+
| { type: 'input'; id: string; seq: number; status: InputDisposition }
|
|
27
|
+
| StreamMessageEnd
|
|
28
|
+
/** Canonical Core stream state, never the debugger's narrower runtime.state. */
|
|
29
|
+
| { type: 'state'; status: 'idle' | 'running' | 'waiting'; queued: number; typing: boolean; activity: string | null; tools?: string[] };
|
|
30
|
+
export type StreamEndEvent = { type: 'replaced' } | { type: 'error'; code: string; message: string; poisoned?: boolean };
|
|
31
|
+
export interface StreamConfigurationError { type: 'error'; code: 'invalid_configuration'; message: string }
|
|
32
|
+
/** A paid model call, not an execution-unit identity. */
|
|
33
|
+
export interface StreamTurnEvent { type: 'turn'; id: string; seq: number; purpose: 'model' | 'summary'; causedBy: string[] }
|
|
34
|
+
/** Target context for the S1 producer change; not synthesized by this SDK. */
|
|
35
|
+
export interface StreamToolContext extends ToolContext { causedBy: string[]; origin: 'app' | 'agent' }
|
|
36
|
+
/** Core owns the snapshot; the SDK preserves the original message-start position. */
|
|
37
|
+
export interface StreamSnapshotStreaming { messageId: string; firstSeq: number; text: string }
|
|
38
|
+
export interface StreamRequestResult {
|
|
39
|
+
id: string; status: InputDisposition; messages: StreamMessageEnd[];
|
|
40
|
+
gap?: true; legacy?: true;
|
|
41
|
+
}
|
|
42
|
+
export type StreamSelectOptions = { initialMessages?: number; after?: never }
|
|
43
|
+
| { after: { logId: string; seq: number }; initialMessages?: never };
|
|
44
|
+
export interface CapturedRequestState {
|
|
45
|
+
/** The committed H and floor captured before the retained-ends read. */
|
|
46
|
+
head: number; floor: number; status: InputDisposition;
|
|
47
|
+
/** Core's agent-wide predicate, including late and result_queued invocations. */
|
|
48
|
+
idle: boolean;
|
|
49
|
+
}
|
|
50
|
+
export interface RetainedRequestEnds { messages: StreamMessageEnd[]; gap?: true }
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Internal adapter boundary, NOT a new public/store protocol. Pending agreement with S1.
|
|
54
|
+
* One observe attachment owns the hub. select/history are Core's projection on that same
|
|
55
|
+
* attachment, not additional canonical subscriptions. Core calls the canonical observer
|
|
56
|
+
* before the app projection; no app callback/promise ever enters the canonical path.
|
|
57
|
+
* readOutcome invokes captured at its ordered capture point, then reads only matching ends
|
|
58
|
+
* through H. The hub buffers observations after that point while storage reads proceed.
|
|
59
|
+
*/
|
|
60
|
+
export interface CoreStreamPort<AppEvent> {
|
|
61
|
+
observe(onEvent: (event: RequestObservation) => void, onEnd: (cause?: unknown) => void): { close(): void };
|
|
62
|
+
select(options: StreamSelectOptions, onEvent: (event: AppEvent) => void): { close(): void; history(options: { before?: number; limit: number }): Promise<void> };
|
|
63
|
+
send(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat }): Promise<StreamReceipt>;
|
|
64
|
+
/** No id stops current work; resolves only after Core durably records the cancellation. */
|
|
65
|
+
cancel(id?: string): Promise<void>;
|
|
66
|
+
readOutcome(id: string, fromSeq: number, captured: (state: CapturedRequestState) => void): Promise<RetainedRequestEnds>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class StreamWaitError extends CrocheError {
|
|
70
|
+
constructor(code: 'observation_lost' | 'aborted', readonly receipt: StreamReceipt, readonly cause?: unknown) {
|
|
71
|
+
super(code, code === 'aborted' ? 'The wait stopped; the accepted input continues.' : 'Observation ended after acceptance. Reopen and retry the same id and input within the identity horizon.');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const terminal = (status: InputDisposition) => status !== 'queued' && status !== 'seen';
|
|
75
|
+
const validPage = (limit: number) => Number.isInteger(limit) && limit >= 1 && limit <= 256;
|
|
76
|
+
const sdkError = (code: string): StreamEndEvent => ({ type: 'error', code, message: `Subscription ended: ${code}.` });
|
|
77
|
+
/** §18.24: swap only this predicate when Core's consuming-unit end evidence lands.
|
|
78
|
+
* Default still uses idle in this internal kernel; it is NOT the final public default.
|
|
79
|
+
*/
|
|
80
|
+
const requestComplete = (status: InputDisposition | undefined, idle: boolean, _wait?: 'idle') =>
|
|
81
|
+
status !== undefined && terminal(status) && idle;
|
|
82
|
+
type Waiter = { event(event: RequestObservation): void; lost(cause?: unknown): void };
|
|
83
|
+
|
|
84
|
+
/** SDK bookkeeping and isolated app delivery; contains no Core projection or fake Core. */
|
|
85
|
+
export class StreamHub<AppEvent> {
|
|
86
|
+
private readonly observation: { close(): void };
|
|
87
|
+
private app?: AppStreamBranch<AppEvent | StreamEndEvent>;
|
|
88
|
+
private projection?: ReturnType<CoreStreamPort<AppEvent>['select']>;
|
|
89
|
+
private waiters = new Set<Waiter>();
|
|
90
|
+
private ended = false;
|
|
91
|
+
private endCause?: unknown;
|
|
92
|
+
|
|
93
|
+
constructor(private readonly port: CoreStreamPort<AppEvent>) {
|
|
94
|
+
this.observation = port.observe(event => {
|
|
95
|
+
// Direct and synchronous. Never run application code on this path.
|
|
96
|
+
for (const waiter of this.waiters) waiter.event(event);
|
|
97
|
+
}, cause => this.end(cause, true));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
subscribe(options: StreamSelectOptions & { onEvent: (event: AppEvent | StreamEndEvent) => void | Promise<void> }): AppStreamSubscription & { history(options: { before?: number; limit: number }): Promise<void> } {
|
|
101
|
+
if (this.ended) throw new CrocheError('closed', 'The subscription hub has ended.');
|
|
102
|
+
this.projection?.close();
|
|
103
|
+
this.projection = undefined;
|
|
104
|
+
this.app?.end({ code: 'replaced' });
|
|
105
|
+
const branch = new AppStreamBranch<AppEvent | StreamEndEvent>(options.onEvent, reason =>
|
|
106
|
+
reason.code === 'replaced' ? { type: 'replaced' } : sdkError(reason.code));
|
|
107
|
+
this.app = branch;
|
|
108
|
+
const count = options.initialMessages ?? 50;
|
|
109
|
+
if (!Number.isInteger(count) || count < 0 || count > 256) {
|
|
110
|
+
branch.push(sdkError('invalid_configuration'), { code: 'invalid_configuration' });
|
|
111
|
+
return { ended: branch.ended, close: () => branch.close(), history: async () => { throw new CrocheError('invalid_configuration', 'History needs a valid attached subscription.'); } };
|
|
112
|
+
}
|
|
113
|
+
// Capture this branch, not this.app: a queued old projection cannot reach its replacement.
|
|
114
|
+
const projection = this.port.select(options.after ? { after: options.after } : { initialMessages: options.initialMessages ?? 50 }, event => {
|
|
115
|
+
const live = event as { type?: string; seq?: number; code?: string };
|
|
116
|
+
const end = live.type === 'error' && live.seq === undefined
|
|
117
|
+
? { code: live.code ?? 'observation_lost' }
|
|
118
|
+
: live.type === 'replaced' ? { code: 'replaced' } : undefined;
|
|
119
|
+
branch.push(event, end);
|
|
120
|
+
});
|
|
121
|
+
this.projection = projection;
|
|
122
|
+
void branch.ended.then(() => projection.close());
|
|
123
|
+
return {
|
|
124
|
+
ended: branch.ended,
|
|
125
|
+
close: () => branch.close(),
|
|
126
|
+
history: async page => {
|
|
127
|
+
if (this.app !== branch || !branch.isOpen) throw new CrocheError('invalid_configuration', 'History needs the current subscription.');
|
|
128
|
+
if (!validPage(page.limit)) throw new CrocheError('invalid_configuration', 'History limit must be an integer from 1 to 256.');
|
|
129
|
+
return projection.history(page);
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Runtime-level target: pages go only to the current subscription generation. */
|
|
135
|
+
async history(options: { before?: number; limit: number }): Promise<void> {
|
|
136
|
+
if (!this.app?.isOpen || !this.projection) throw new CrocheError('invalid_configuration', 'History needs an attached subscription.');
|
|
137
|
+
if (!validPage(options.limit)) throw new CrocheError('invalid_configuration', 'History limit must be an integer from 1 to 256.');
|
|
138
|
+
return this.projection.history(options);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Internal target surface; acknowledgement only, never a turn result. */
|
|
142
|
+
send(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat } = {}): Promise<StreamReceipt> {
|
|
143
|
+
if (this.ended) return Promise.reject(new CrocheError('closed', 'The subscription hub has ended.'));
|
|
144
|
+
return this.port.send(input, options);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Prepared target surface. Core, not the SDK, decides what running work this stops. */
|
|
148
|
+
async cancel(id?: string): Promise<void> {
|
|
149
|
+
if (this.ended) throw new CrocheError('closed', 'The subscription hub has ended.');
|
|
150
|
+
await this.port.cancel(id);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
request(input: SendInput, options: { signal?: AbortSignal; responseFormat?: ResponseFormat; wait?: 'idle' } = {}): Promise<StreamRequestResult> {
|
|
154
|
+
if (options.signal?.aborted) return Promise.reject(new CrocheError('aborted', 'The request was aborted before sending.'));
|
|
155
|
+
if (this.ended) return Promise.reject(new CrocheError('closed', 'The subscription hub has ended.'));
|
|
156
|
+
const id = input.id;
|
|
157
|
+
return new Promise((resolve, reject) => {
|
|
158
|
+
let receipt: StreamReceipt | undefined;
|
|
159
|
+
let status: InputDisposition | undefined;
|
|
160
|
+
let complete = false;
|
|
161
|
+
let reading = true;
|
|
162
|
+
let captured = false;
|
|
163
|
+
let gap = false;
|
|
164
|
+
let done = false;
|
|
165
|
+
let lost = this.ended;
|
|
166
|
+
let lossCause = this.endCause;
|
|
167
|
+
const messages = new Map<string, StreamMessageEnd>();
|
|
168
|
+
const cleanup = () => {
|
|
169
|
+
done = true;
|
|
170
|
+
this.waiters.delete(waiter);
|
|
171
|
+
options.signal?.removeEventListener('abort', abort);
|
|
172
|
+
};
|
|
173
|
+
const fail = (error: unknown) => { if (!done) { cleanup(); reject(error); } };
|
|
174
|
+
const finish = () => {
|
|
175
|
+
if (done || reading || !receipt || !complete || !status) return;
|
|
176
|
+
cleanup();
|
|
177
|
+
resolve({ id: receipt.id, status, messages: [...messages.values()].sort((a, b) => a.seq - b.seq), ...(gap ? { gap: true as const } : {}) });
|
|
178
|
+
};
|
|
179
|
+
const apply = (event: RequestObservation) => {
|
|
180
|
+
if (complete) return;
|
|
181
|
+
if (event.type === 'input' && event.id === id && (!status || !terminal(status))) status = event.status;
|
|
182
|
+
if (event.type === 'message.end' && event.causedBy.includes(id)) messages.set(`${event.id}:${event.seq}`, event);
|
|
183
|
+
if (event.type === 'state') complete = requestComplete(status, event.status === 'idle', options.wait);
|
|
184
|
+
finish();
|
|
185
|
+
};
|
|
186
|
+
const waiter: Waiter = {
|
|
187
|
+
event: event => {
|
|
188
|
+
if (done) return;
|
|
189
|
+
apply(event);
|
|
190
|
+
},
|
|
191
|
+
lost: cause => {
|
|
192
|
+
lost = true;
|
|
193
|
+
lossCause = cause;
|
|
194
|
+
if (receipt) fail(new StreamWaitError('observation_lost', receipt, cause));
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
const abort = () => { if (receipt) fail(new StreamWaitError('aborted', receipt)); };
|
|
198
|
+
this.waiters.add(waiter); // before send; synchronous Core progress cannot outrun registration
|
|
199
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
200
|
+
void (async () => {
|
|
201
|
+
try {
|
|
202
|
+
receipt = await this.send(input, { signal: options.signal, responseFormat: options.responseFormat });
|
|
203
|
+
// Same-id terminal retries emit no new input event. Seed before idle overtakes
|
|
204
|
+
// the older capture, but never regress an already observed terminal disposition.
|
|
205
|
+
if (status === undefined || (!terminal(status) && terminal(receipt.status))) {
|
|
206
|
+
status = receipt.status;
|
|
207
|
+
}
|
|
208
|
+
if (lost) return fail(new StreamWaitError('observation_lost', receipt, lossCause));
|
|
209
|
+
if (options.signal?.aborted) return fail(new StreamWaitError('aborted', receipt));
|
|
210
|
+
if (receipt.seq === null) {
|
|
211
|
+
cleanup();
|
|
212
|
+
resolve({ id: receipt.id, status: receipt.status, messages: [], legacy: true });
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const retained = await this.port.readOutcome(receipt.id, receipt.seq, snapshot => {
|
|
216
|
+
if (done) return;
|
|
217
|
+
captured = true;
|
|
218
|
+
if (!status || !terminal(status)) status = snapshot.status;
|
|
219
|
+
gap = receipt!.seq! < snapshot.floor;
|
|
220
|
+
complete ||= requestComplete(status, snapshot.idle, options.wait);
|
|
221
|
+
});
|
|
222
|
+
if (done) return;
|
|
223
|
+
if (!captured) throw new Error('Core retained-ends read omitted its ordered capture.');
|
|
224
|
+
gap ||= retained.gap === true;
|
|
225
|
+
for (const message of retained.messages) {
|
|
226
|
+
if (message.causedBy.includes(receipt.id)) messages.set(`${message.id}:${message.seq}`, message);
|
|
227
|
+
}
|
|
228
|
+
reading = false;
|
|
229
|
+
finish();
|
|
230
|
+
} catch (error) {
|
|
231
|
+
fail(receipt ? new StreamWaitError('observation_lost', receipt, error) : error);
|
|
232
|
+
}
|
|
233
|
+
})();
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
close(): void { this.end(); this.observation.close(); }
|
|
238
|
+
private end(cause?: unknown, fromCore = false): void {
|
|
239
|
+
if (this.ended) return;
|
|
240
|
+
this.ended = true;
|
|
241
|
+
this.endCause = cause;
|
|
242
|
+
this.projection?.close();
|
|
243
|
+
// Core handed its terminal error to the projection BEFORE on_end (S1 commit 7 Q3).
|
|
244
|
+
// That callback queued it; do not mistake boundary delivery for app delivery
|
|
245
|
+
// and discard it. An explicit Runtime close remains a dropping SDK-side end.
|
|
246
|
+
if (!fromCore || !this.app?.hasPendingEnd) this.app?.end({ code: 'closed' });
|
|
247
|
+
for (const waiter of this.waiters) waiter.lost(cause);
|
|
248
|
+
}
|
|
249
|
+
}
|
package/src/stream.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// `@h1r-ai/croche/stream`: the subscription hub with no Core and no WebAssembly, for SDKs that
|
|
2
|
+
// run the Core natively and bind it as a CoreStreamPort (React Native). Internal to the Croche
|
|
3
|
+
// SDKs: apps use `Croche` / `CrocheAgent`.
|
|
4
|
+
export {StreamHub, StreamWaitError} from './stream-hub.js';
|
|
5
|
+
export type {CoreStreamPort, RequestObservation, StreamSelectOptions, StreamReceipt, StreamRequestResult,
|
|
6
|
+
CapturedRequestState, RetainedRequestEnds, StreamEndEvent} from './stream-hub.js';
|
|
7
|
+
export {CrocheError} from './types.js';
|