@parcha/agentrun-kernel 0.0.0-stage → 0.1.0-beta.30
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/CHANGELOG.md +181 -0
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +63 -2
- package/dist/booking.d.ts +50 -0
- package/dist/booking.js +52 -0
- package/dist/delegate.d.ts +87 -0
- package/dist/delegate.js +143 -0
- package/dist/errors.d.ts +36 -0
- package/dist/errors.js +37 -0
- package/dist/host/alive.d.ts +2 -0
- package/dist/host/alive.js +28 -0
- package/dist/host/box-slot.d.ts +26 -0
- package/dist/host/box-slot.js +112 -0
- package/dist/host/box.d.ts +104 -0
- package/dist/host/box.js +16 -0
- package/dist/host/egress-proxy.d.ts +45 -0
- package/dist/host/egress-proxy.js +416 -0
- package/dist/host/egress-table.d.ts +24 -0
- package/dist/host/egress-table.js +165 -0
- package/dist/host/index.d.ts +16 -0
- package/dist/host/index.js +12 -0
- package/dist/host/overhead.d.ts +53 -0
- package/dist/host/overhead.js +75 -0
- package/dist/host/parent-death.d.ts +15 -0
- package/dist/host/parent-death.js +42 -0
- package/dist/host/parent-watch.d.ts +1 -0
- package/dist/host/parent-watch.js +38 -0
- package/dist/host/pinned-binary.d.ts +6 -0
- package/dist/host/pinned-binary.js +48 -0
- package/dist/host/proxy.d.ts +212 -0
- package/dist/host/proxy.js +808 -0
- package/dist/host/serial.d.ts +3 -0
- package/dist/host/serial.js +10 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +7 -0
- package/dist/kernel/blobs.d.ts +16 -0
- package/dist/kernel/blobs.js +59 -0
- package/dist/kernel/drive.d.ts +40 -0
- package/dist/kernel/drive.js +239 -0
- package/dist/kernel/errors.d.ts +27 -0
- package/dist/kernel/errors.js +42 -0
- package/dist/kernel/follow-up.d.ts +67 -0
- package/dist/kernel/follow-up.js +146 -0
- package/dist/kernel/halt.d.ts +11 -0
- package/dist/kernel/halt.js +17 -0
- package/dist/kernel/index.d.ts +8 -0
- package/dist/kernel/index.js +5 -0
- package/dist/kernel/types.d.ts +129 -0
- package/dist/kernel/types.js +1 -0
- package/dist/process/builtins.d.ts +142 -0
- package/dist/process/builtins.js +207 -0
- package/dist/process/inbox.d.ts +29 -0
- package/dist/process/inbox.js +52 -0
- package/dist/process/index.d.ts +9 -0
- package/dist/process/index.js +11 -0
- package/dist/process/journal.d.ts +111 -0
- package/dist/process/journal.js +232 -0
- package/dist/process/records.d.ts +143 -0
- package/dist/process/records.js +142 -0
- package/dist/process/recovery.d.ts +76 -0
- package/dist/process/recovery.js +139 -0
- package/dist/process/settle.d.ts +22 -0
- package/dist/process/settle.js +38 -0
- package/dist/process/tail.d.ts +20 -0
- package/dist/process/tail.js +53 -0
- package/dist/process/tools.d.ts +105 -0
- package/dist/process/tools.js +120 -0
- package/dist/process/zod.d.ts +32 -0
- package/dist/process/zod.js +109 -0
- package/dist/runner.d.ts +154 -0
- package/dist/runner.js +559 -0
- package/dist/schema-check-cases.d.ts +7 -0
- package/dist/schema-check-cases.js +73 -0
- package/dist/schema-check.d.ts +3 -0
- package/dist/schema-check.js +88 -0
- package/dist/skill-files.d.ts +23 -0
- package/dist/skill-files.js +136 -0
- package/dist/testing.d.ts +91 -0
- package/dist/testing.js +196 -0
- package/dist/types.d.ts +256 -0
- package/dist/types.js +17 -0
- package/package.json +74 -4
- package/vendor/durable-harness/UPSTREAM.json +67 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
|
+
// From github.com/vercel-labs/durable-harness, packages/harness-process/src/builtins.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
+
// Changed by Parcha, imports rewritten for AgentRun; patches: 001-begin-reservation, 002-message-prefix, 003-comments-name-this-host
|
|
4
|
+
import { EffectFailure, EffectInterrupted, Fatal, hostToolIO } from '../kernel/index.js';
|
|
5
|
+
import { clip, failureText, toolKey } from './tools.js';
|
|
6
|
+
/**
|
|
7
|
+
* The built-in calls of one drive. Build one per `drive(ctx)`.
|
|
8
|
+
*
|
|
9
|
+
* A call the drive leaves open (the harness's process died mid-call, the
|
|
10
|
+
* drive stopped) is dealt with by `close`: interrupted if the drive is
|
|
11
|
+
* still live, else left to the kernel (a stopped drive's intent is released
|
|
12
|
+
* or recovered as interrupted by the next delivery).
|
|
13
|
+
*/
|
|
14
|
+
export class BuiltinCalls {
|
|
15
|
+
ctx;
|
|
16
|
+
options;
|
|
17
|
+
open = new Map();
|
|
18
|
+
/** Each call id's first `begin`, reserved before it awaits anything. */
|
|
19
|
+
begun = new Map();
|
|
20
|
+
replay;
|
|
21
|
+
live;
|
|
22
|
+
outputChars;
|
|
23
|
+
constructor(ctx, options = {}) {
|
|
24
|
+
this.ctx = ctx;
|
|
25
|
+
this.options = options;
|
|
26
|
+
this.replay = options.replay ?? (() => 'never');
|
|
27
|
+
this.live = options.live ?? true;
|
|
28
|
+
this.outputChars = options.outputChars ?? 8000;
|
|
29
|
+
}
|
|
30
|
+
/** Calls begun and not ended. */
|
|
31
|
+
get size() {
|
|
32
|
+
return this.open.size;
|
|
33
|
+
}
|
|
34
|
+
/** Whether this call is open in this drive. */
|
|
35
|
+
has(callId) {
|
|
36
|
+
return this.open.has(callId);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The harness is about to run `call`: commit its intent. Resolves once the
|
|
40
|
+
* intent is committed (`{ run: true }`), or at once with the log's answer
|
|
41
|
+
* when the call id already has an outcome (`{ run: false }`). Rejects if
|
|
42
|
+
* the intent cannot be committed (the drive lost the session, a write
|
|
43
|
+
* failed): the drive is halted, and the hook must refuse the call.
|
|
44
|
+
*/
|
|
45
|
+
begin(call) {
|
|
46
|
+
if (!call.callId)
|
|
47
|
+
return Promise.reject(new TypeError(`agentrun-kernel: a built-in ${call.name} call has no call id`));
|
|
48
|
+
const first = this.begun.get(call.callId);
|
|
49
|
+
if (first)
|
|
50
|
+
return this.again(call.callId, first);
|
|
51
|
+
const start = this.beginOnce(call);
|
|
52
|
+
this.begun.set(call.callId, start);
|
|
53
|
+
// A call that will not run is done with now; one that runs is, once its outcome is in (beginOnce's `done`).
|
|
54
|
+
start.then((s) => { if (!s.run)
|
|
55
|
+
this.begun.delete(call.callId); }, () => this.begun.delete(call.callId));
|
|
56
|
+
return start;
|
|
57
|
+
}
|
|
58
|
+
/** The same call begun again: never run it twice. Wait for the first begin, then for its outcome, from the log. */
|
|
59
|
+
async again(callId, first) {
|
|
60
|
+
const start = await first;
|
|
61
|
+
if (!start.run)
|
|
62
|
+
return start;
|
|
63
|
+
await this.open.get(callId)?.done;
|
|
64
|
+
// The first call's outcome could not be written: the drive stopped, and this caller stops with it.
|
|
65
|
+
if (this.ctx.signal.aborted)
|
|
66
|
+
throw this.ctx.signal.reason;
|
|
67
|
+
const known = this.ctx.state().effects.get(toolKey(callId));
|
|
68
|
+
if (known?.status === 'completed')
|
|
69
|
+
return { run: false, result: { text: String(known.output ?? ''), isError: false } };
|
|
70
|
+
if (known?.status === 'failed' && known.error)
|
|
71
|
+
return { run: false, result: { text: failureText(known.error), isError: true, ...(known.error.interrupted ? { interrupted: true } : {}) } };
|
|
72
|
+
throw new Fatal(`agentrun-kernel: built-in call ${callId} has no recorded outcome`);
|
|
73
|
+
}
|
|
74
|
+
async beginOnce(call) {
|
|
75
|
+
const key = toolKey(call.callId);
|
|
76
|
+
const known = this.ctx.state().effects.get(key);
|
|
77
|
+
if (known?.status === 'completed')
|
|
78
|
+
return { run: false, result: { text: String(known.output ?? ''), isError: false } };
|
|
79
|
+
if (known?.status === 'failed' && known.error)
|
|
80
|
+
return { run: false, result: { text: failureText(known.error), isError: true, ...(known.error.interrupted ? { interrupted: true } : {}) } };
|
|
81
|
+
const replay = call.replay ?? this.replay(call.name);
|
|
82
|
+
try {
|
|
83
|
+
if (replay === 'never')
|
|
84
|
+
await this.options.beforeNever?.(call);
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
this.ctx.halt?.(err);
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
let started;
|
|
91
|
+
const committed = new Promise((r) => (started = r));
|
|
92
|
+
let settle;
|
|
93
|
+
const outcome = new Promise((r) => (settle = r));
|
|
94
|
+
let failed;
|
|
95
|
+
let ran = false;
|
|
96
|
+
const around = this.options.around;
|
|
97
|
+
const effect = this.ctx.effect(key, { name: `tool.${call.name}`, replay, input: call.input }, async (io) => {
|
|
98
|
+
let running;
|
|
99
|
+
// The call itself, once: a wrapper that calls `run` again gets the same promise.
|
|
100
|
+
const body = () => (running ??= (async () => {
|
|
101
|
+
ran = true;
|
|
102
|
+
started();
|
|
103
|
+
if (this.live)
|
|
104
|
+
this.ctx.live({ type: 'tool_start', name: call.name, args: call.input, callId: call.callId });
|
|
105
|
+
const result = await new Promise((resolve, reject) => {
|
|
106
|
+
const stop = () => reject(io.signal.reason ?? new Error('the drive stopped'));
|
|
107
|
+
if (io.signal.aborted)
|
|
108
|
+
return stop();
|
|
109
|
+
io.signal.addEventListener('abort', stop, { once: true });
|
|
110
|
+
void outcome.then((o) => {
|
|
111
|
+
io.signal.removeEventListener('abort', stop);
|
|
112
|
+
resolve(o);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
if (!result.ok)
|
|
116
|
+
throw result.error;
|
|
117
|
+
return result.text;
|
|
118
|
+
})());
|
|
119
|
+
return around ? around(call, body, hostToolIO(io, this.ctx)) : body();
|
|
120
|
+
});
|
|
121
|
+
const done = effect.then(() => {
|
|
122
|
+
// A call its wrapper settled without letting it run never started, on the live stream either.
|
|
123
|
+
if (this.live && (ran || !around))
|
|
124
|
+
this.ctx.live({ type: 'tool_end', name: call.name, callId: call.callId });
|
|
125
|
+
}, (err) => {
|
|
126
|
+
if (err instanceof EffectFailure) {
|
|
127
|
+
// Nor one its wrapper failed before it ran.
|
|
128
|
+
if (this.live && (ran || !around))
|
|
129
|
+
this.ctx.live({ type: 'tool_end', name: call.name, callId: call.callId, isError: true });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
// Not this call's outcome: the drive stopped, or a write failed. Stop the drive.
|
|
133
|
+
failed = err;
|
|
134
|
+
this.ctx.halt?.(err);
|
|
135
|
+
});
|
|
136
|
+
this.open.set(call.callId, { settle, done });
|
|
137
|
+
void done.finally(() => { this.open.delete(call.callId); this.begun.delete(call.callId); });
|
|
138
|
+
await Promise.race([committed, done]);
|
|
139
|
+
if (failed !== undefined)
|
|
140
|
+
throw failed;
|
|
141
|
+
// Settled before its intent (replayed from the log by a concurrent read), or by a wrapper that never let it run: answer from the log.
|
|
142
|
+
const after = this.ctx.state().effects.get(key);
|
|
143
|
+
if (!this.open.has(call.callId) && after?.status === 'completed')
|
|
144
|
+
return { run: false, result: { text: String(after.output ?? ''), isError: false } };
|
|
145
|
+
// The wrapper failed the call before letting it run: answer with that failure.
|
|
146
|
+
if (around && !ran) {
|
|
147
|
+
const error = after?.status === 'failed' && after.error ? failureText(after.error) : 'the tool failed before it ran';
|
|
148
|
+
return { run: false, result: { text: error, isError: true } };
|
|
149
|
+
}
|
|
150
|
+
return { run: true };
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The call ended: commit its outcome. `isError` (the tool reported a
|
|
154
|
+
* failure) commits a failed step with `text` as its error. Resolves once
|
|
155
|
+
* the outcome is committed (or the drive stopped first). A call this
|
|
156
|
+
* drive never began (a hook that fired without its `begin`) is begun and
|
|
157
|
+
* ended here: recorded after the fact.
|
|
158
|
+
*/
|
|
159
|
+
async end(callId, result) {
|
|
160
|
+
let open = this.open.get(callId);
|
|
161
|
+
// Its begin is still committing the intent: end that call, not a second one.
|
|
162
|
+
if (!open && this.begun.has(callId)) {
|
|
163
|
+
await this.begun.get(callId).catch(() => undefined);
|
|
164
|
+
open = this.open.get(callId);
|
|
165
|
+
}
|
|
166
|
+
if (!open) {
|
|
167
|
+
if (this.ctx.isMemoized(toolKey(callId)))
|
|
168
|
+
return;
|
|
169
|
+
const started = await this.begin({ callId, name: result.name ?? 'builtin', input: result.input ?? null, replay: 'safe' }).catch(() => undefined);
|
|
170
|
+
if (!started?.run)
|
|
171
|
+
return;
|
|
172
|
+
open = this.open.get(callId);
|
|
173
|
+
if (!open)
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const text = clip(result.text, this.outputChars);
|
|
177
|
+
open.settle(result.isError ? { ok: false, error: new Error(text || 'the tool failed') } : { ok: true, text });
|
|
178
|
+
await open.done;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* The harness can no longer report these calls (its process exited mid-call):
|
|
182
|
+
* commit each open call as interrupted, "may or may not have taken effect".
|
|
183
|
+
* A no-op once the drive stopped (the kernel resolves its intents).
|
|
184
|
+
*/
|
|
185
|
+
async interruptAll(reason = 'the harness stopped before this call reported its result: it may or may not have taken effect') {
|
|
186
|
+
const open = [...this.open.values()];
|
|
187
|
+
if (this.ctx.signal.aborted)
|
|
188
|
+
return;
|
|
189
|
+
for (const o of open)
|
|
190
|
+
o.settle({ ok: false, error: new EffectInterrupted(reason) });
|
|
191
|
+
await Promise.all(open.map((o) => o.done));
|
|
192
|
+
}
|
|
193
|
+
/** Wait for every open call to settle, or `ms` to pass. */
|
|
194
|
+
async settled(ms) {
|
|
195
|
+
const open = [...this.open.values()].map((o) => o.done);
|
|
196
|
+
if (!open.length)
|
|
197
|
+
return;
|
|
198
|
+
let timer;
|
|
199
|
+
await Promise.race([Promise.all(open), new Promise((r) => (timer = setTimeout(r, ms)))]);
|
|
200
|
+
clearTimeout(timer);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** A tool name list as a replay classifier: these are `safe`, the rest `never`. */
|
|
204
|
+
export function replayBy(safe) {
|
|
205
|
+
const set = new Set(safe);
|
|
206
|
+
return (name) => (set.has(name) ? 'safe' : 'never');
|
|
207
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { DriveContext, Submission } from '../kernel/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Place submissions before the harness's runtime sees them: one record-only
|
|
4
|
+
* effect `place:<first id>` whose `placed` names them. Placement is what
|
|
5
|
+
* takes a submission off `ctx.pending()` and what a withdraw races (a
|
|
6
|
+
* withdraw committed first wins, and this throws `Restart`: the drive
|
|
7
|
+
* rebuilds without the withdrawn submission). Sending only after placing
|
|
8
|
+
* means the kernel's withdraw rule is exact, and a crash between the two
|
|
9
|
+
* re-sends instead of losing the message.
|
|
10
|
+
*
|
|
11
|
+
* The demo's transcript shows a placed submission where its placement is in
|
|
12
|
+
* the log, so a harness that places right before sending gets its prompts
|
|
13
|
+
* in the right place for free.
|
|
14
|
+
*/
|
|
15
|
+
export declare function placeSubmissions(ctx: DriveContext, submissions: Submission[], name?: string): Promise<void>;
|
|
16
|
+
export interface WaitOptions {
|
|
17
|
+
/** How often to read the inbox when the kernel offers no hints. Default 500 ms (5 s with hints). */
|
|
18
|
+
pollMs?: number;
|
|
19
|
+
/** Stop waiting (resolves `[]`). `ctx.signal` always stops it too. */
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The submissions waiting to be placed, as soon as there are any: refreshes
|
|
24
|
+
* the log on every hint (`ctx.onHint`) and on a poll. Resolves `[]` when
|
|
25
|
+
* `ctx.signal` or `options.signal` aborts. A drive that has nothing left to
|
|
26
|
+
* do should return instead of waiting; this is for a harness that keeps its
|
|
27
|
+
* runtime up while a turn runs (steers) or for a short idle grace.
|
|
28
|
+
*/
|
|
29
|
+
export declare function waitForSubmissions(ctx: DriveContext, options?: WaitOptions): Promise<Submission[]>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Place submissions before the harness's runtime sees them: one record-only
|
|
3
|
+
* effect `place:<first id>` whose `placed` names them. Placement is what
|
|
4
|
+
* takes a submission off `ctx.pending()` and what a withdraw races (a
|
|
5
|
+
* withdraw committed first wins, and this throws `Restart`: the drive
|
|
6
|
+
* rebuilds without the withdrawn submission). Sending only after placing
|
|
7
|
+
* means the kernel's withdraw rule is exact, and a crash between the two
|
|
8
|
+
* re-sends instead of losing the message.
|
|
9
|
+
*
|
|
10
|
+
* The demo's transcript shows a placed submission where its placement is in
|
|
11
|
+
* the log, so a harness that places right before sending gets its prompts
|
|
12
|
+
* in the right place for free.
|
|
13
|
+
*/
|
|
14
|
+
export async function placeSubmissions(ctx, submissions, name = 'place') {
|
|
15
|
+
if (submissions.length === 0)
|
|
16
|
+
return;
|
|
17
|
+
const ids = submissions.map((s) => s.id);
|
|
18
|
+
await ctx.effect(`place:${ids[0]}`, { name, replay: 'safe', input: { ids }, placed: ids }, async () => true);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The submissions waiting to be placed, as soon as there are any: refreshes
|
|
22
|
+
* the log on every hint (`ctx.onHint`) and on a poll. Resolves `[]` when
|
|
23
|
+
* `ctx.signal` or `options.signal` aborts. A drive that has nothing left to
|
|
24
|
+
* do should return instead of waiting; this is for a harness that keeps its
|
|
25
|
+
* runtime up while a turn runs (steers) or for a short idle grace.
|
|
26
|
+
*/
|
|
27
|
+
export async function waitForSubmissions(ctx, options = {}) {
|
|
28
|
+
const signals = [ctx.signal, options.signal].filter((s) => !!s);
|
|
29
|
+
const stop = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
|
|
30
|
+
const pollMs = options.pollMs ?? (ctx.onHint ? 5000 : 500);
|
|
31
|
+
for (;;) {
|
|
32
|
+
if (stop.aborted)
|
|
33
|
+
return [];
|
|
34
|
+
const pending = ctx.pending();
|
|
35
|
+
if (pending.length > 0)
|
|
36
|
+
return pending;
|
|
37
|
+
await new Promise((resolve) => {
|
|
38
|
+
const timer = setTimeout(done, pollMs);
|
|
39
|
+
const off = ctx.onHint?.(() => done());
|
|
40
|
+
stop.addEventListener('abort', done, { once: true });
|
|
41
|
+
function done() {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
off?.();
|
|
44
|
+
stop.removeEventListener('abort', done);
|
|
45
|
+
resolve();
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
if (stop.aborted)
|
|
49
|
+
return [];
|
|
50
|
+
await ctx.refresh();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from "./records.js";
|
|
2
|
+
export * from "./recovery.js";
|
|
3
|
+
export * from "./journal.js";
|
|
4
|
+
export * from "./tools.js";
|
|
5
|
+
export * from "./builtins.js";
|
|
6
|
+
export * from "./inbox.js";
|
|
7
|
+
export * from "./tail.js";
|
|
8
|
+
export * from "./zod.js";
|
|
9
|
+
export * from "./settle.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The shared layer for harnesses that run as a child process, copied from another project (each file's header
|
|
2
|
+
// says from where, and UPSTREAM.json records it), on AgentRun's kernel (../kernel).
|
|
3
|
+
export * from "./records.js";
|
|
4
|
+
export * from "./recovery.js";
|
|
5
|
+
export * from "./journal.js";
|
|
6
|
+
export * from "./tools.js";
|
|
7
|
+
export * from "./builtins.js";
|
|
8
|
+
export * from "./inbox.js";
|
|
9
|
+
export * from "./tail.js";
|
|
10
|
+
export * from "./zod.js";
|
|
11
|
+
export * from "./settle.js";
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { blobStreamName, type DriveContext, readBlobs } from '../kernel/index.js';
|
|
2
|
+
import { type JournalRecord, type TranscriptEntry } from './records.js';
|
|
3
|
+
/**
|
|
4
|
+
* Records longer than this (as JSON text) go to the blob stream instead of
|
|
5
|
+
* the log. The log is folded whole on every cold drive and polled by every
|
|
6
|
+
* viewer, so it should stay lean. The World's own limit is far higher (see
|
|
7
|
+
* the README, "Payload limits").
|
|
8
|
+
*/
|
|
9
|
+
export declare const DEFAULT_INLINE_MAX_BYTES: number;
|
|
10
|
+
/**
|
|
11
|
+
* The session's blob stream (harness-world's `blobs.ts`): content-addressed,
|
|
12
|
+
* append-only, one line per blob (or per piece of one). Shared with the
|
|
13
|
+
* document-backed workspace, which keeps its large files there.
|
|
14
|
+
*/
|
|
15
|
+
export { blobStreamName, readBlobs };
|
|
16
|
+
export interface NativeJournalOptions {
|
|
17
|
+
/** Offload records whose JSON text is longer than this. Default `DEFAULT_INLINE_MAX_BYTES`. */
|
|
18
|
+
inlineMaxBytes?: number;
|
|
19
|
+
/**
|
|
20
|
+
* Called once, with the error, when a batch write fails or is refused.
|
|
21
|
+
* Default: `ctx.halt(err)`, which stops the drive (and so kills the child
|
|
22
|
+
* a `ProcessHost` spawned with `ctx.signal`).
|
|
23
|
+
*/
|
|
24
|
+
onPoison?: (err: unknown) => void;
|
|
25
|
+
/** Characters per blob chunk. Default 2M. */
|
|
26
|
+
blobPieceChars?: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The writer (and reader) of a process harness's native journal, for one drive.
|
|
30
|
+
*
|
|
31
|
+
* `append` queues a record; the journal keeps one batch in flight and
|
|
32
|
+
* commits everything queued behind it as the next batch (group commit), one
|
|
33
|
+
* record-only effect `journal:<n>` per batch. `flush()` is the barrier: it
|
|
34
|
+
* resolves once every record appended before it is committed. Call it before
|
|
35
|
+
* a `replay: 'never'` tool runs (the tool bridge's `beforeNever`) and at the
|
|
36
|
+
* end of a turn.
|
|
37
|
+
*
|
|
38
|
+
* Under run-ahead durability (`DriverOptions.runAhead`) a batch is issued,
|
|
39
|
+
* not yet durable, when its effect returns; the kernel waits for it at its
|
|
40
|
+
* own barriers (before a `never` effect, before the drive goes idle), so
|
|
41
|
+
* `flush()` before a `never` tool still means "in the log before the tool".
|
|
42
|
+
*
|
|
43
|
+
* The journal's writes are in-band writes of the drive: they go through
|
|
44
|
+
* `ctx.effect`, so the writer fence (once a newer drive opens the session,
|
|
45
|
+
* this drive's writes are refused: a `Restart`), first-writer-wins per key and the
|
|
46
|
+
* outcome rules apply. A failed or refused write poisons the journal
|
|
47
|
+
* (`append` becomes a no-op, `flush` rejects) and halts the drive. So does a
|
|
48
|
+
* batch number another writer took first (two drives of one session, the
|
|
49
|
+
* other's batch already in this drive's fold, where `ctx.effect` would hand
|
|
50
|
+
* back its result as if it were this batch's): that is a `Restart`, and the
|
|
51
|
+
* drive rebuilds from the log instead of losing the batch's records.
|
|
52
|
+
*/
|
|
53
|
+
export declare class NativeJournal {
|
|
54
|
+
private readonly ctx;
|
|
55
|
+
private readonly inlineMax;
|
|
56
|
+
private readonly onPoison;
|
|
57
|
+
private readonly pieceChars;
|
|
58
|
+
/** The next batch number. */
|
|
59
|
+
private n;
|
|
60
|
+
/** Next position per stream (log plus queue). */
|
|
61
|
+
private readonly next;
|
|
62
|
+
/** Record ids in the log or queued. */
|
|
63
|
+
private readonly ids;
|
|
64
|
+
/** Blobs known to be in the blob stream. */
|
|
65
|
+
private readonly blobs;
|
|
66
|
+
private queue;
|
|
67
|
+
private inflight;
|
|
68
|
+
private appended;
|
|
69
|
+
private written;
|
|
70
|
+
private waiters;
|
|
71
|
+
private failure;
|
|
72
|
+
/** This writer, in each batch's output: a batch is this journal's only if it says so. */
|
|
73
|
+
private readonly writer;
|
|
74
|
+
constructor(ctx: DriveContext, options?: NativeJournalOptions);
|
|
75
|
+
/** The error that poisoned this journal, if one did. */
|
|
76
|
+
get poisoned(): unknown;
|
|
77
|
+
/** How many records `stream` has (committed plus queued). */
|
|
78
|
+
length(stream: string): number;
|
|
79
|
+
/** Whether a record with this id is in the log or queued. */
|
|
80
|
+
has(id: string): boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Queue a record (a JSON value) on `stream`. Returns `false` when it was
|
|
83
|
+
* not queued: a record with the same `id` is already in the log or queued
|
|
84
|
+
* (dedupe), or the journal is poisoned.
|
|
85
|
+
*/
|
|
86
|
+
append(stream: string, data: unknown, options?: {
|
|
87
|
+
id?: string;
|
|
88
|
+
}): boolean;
|
|
89
|
+
/** Append an entry to the normalized transcript. */
|
|
90
|
+
message(entry: TranscriptEntry): boolean;
|
|
91
|
+
/** Resolves once every record appended so far is committed; rejects if the journal is poisoned. */
|
|
92
|
+
flush(): Promise<void>;
|
|
93
|
+
/** The records of `stream` (or every stream) in the log, in order. Offloaded ones have `data: undefined`. */
|
|
94
|
+
records<T = unknown>(stream?: string): JournalRecord<T>[];
|
|
95
|
+
/** The same records with their blobs read back from the blob stream and checked against their hashes. */
|
|
96
|
+
read<T = unknown>(stream?: string): Promise<JournalRecord<T>[]>;
|
|
97
|
+
private pump;
|
|
98
|
+
private settleWaiters;
|
|
99
|
+
private poison;
|
|
100
|
+
private write;
|
|
101
|
+
/** A record as the batch stores it: inline, or offloaded to the blob stream (written before the batch). */
|
|
102
|
+
private store;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Read a session's journal with offloaded records resolved: the blob stream
|
|
106
|
+
* is read once and every blob is checked against its hash. A blob the log
|
|
107
|
+
* names but the stream does not hold is `Fatal` (the batch commits only
|
|
108
|
+
* after its blobs are written, so the session cannot continue); a read that
|
|
109
|
+
* fails is thrown as it is (the delivery is retried).
|
|
110
|
+
*/
|
|
111
|
+
export declare function readJournal<T = unknown>(ctx: Pick<DriveContext, 'world' | 'runId' | 'state'>, stream?: string): Promise<JournalRecord<T>[]>;
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
|
+
// From github.com/vercel-labs/durable-harness, packages/harness-process/src/journal.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
+
// Changed by Parcha, imports rewritten for AgentRun; patches: 002-message-prefix, 004-comments-name-the-session-writer
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { BLOB_PIECE_CHARS, blobStreamName, Fatal, readBlobs, Restart, sha256Hex, writeBlob } from '../kernel/index.js';
|
|
6
|
+
import { JOURNAL, journalBatches, journalKey, journalRecords, TRANSCRIPT, } from './records.js';
|
|
7
|
+
/**
|
|
8
|
+
* Records longer than this (as JSON text) go to the blob stream instead of
|
|
9
|
+
* the log. The log is folded whole on every cold drive and polled by every
|
|
10
|
+
* viewer, so it should stay lean. The World's own limit is far higher (see
|
|
11
|
+
* the README, "Payload limits").
|
|
12
|
+
*/
|
|
13
|
+
export const DEFAULT_INLINE_MAX_BYTES = 32 * 1024;
|
|
14
|
+
/**
|
|
15
|
+
* The session's blob stream (harness-world's `blobs.ts`): content-addressed,
|
|
16
|
+
* append-only, one line per blob (or per piece of one). Shared with the
|
|
17
|
+
* document-backed workspace, which keeps its large files there.
|
|
18
|
+
*/
|
|
19
|
+
export { blobStreamName, readBlobs };
|
|
20
|
+
const encoder = new TextEncoder();
|
|
21
|
+
/**
|
|
22
|
+
* The writer (and reader) of a process harness's native journal, for one drive.
|
|
23
|
+
*
|
|
24
|
+
* `append` queues a record; the journal keeps one batch in flight and
|
|
25
|
+
* commits everything queued behind it as the next batch (group commit), one
|
|
26
|
+
* record-only effect `journal:<n>` per batch. `flush()` is the barrier: it
|
|
27
|
+
* resolves once every record appended before it is committed. Call it before
|
|
28
|
+
* a `replay: 'never'` tool runs (the tool bridge's `beforeNever`) and at the
|
|
29
|
+
* end of a turn.
|
|
30
|
+
*
|
|
31
|
+
* Under run-ahead durability (`DriverOptions.runAhead`) a batch is issued,
|
|
32
|
+
* not yet durable, when its effect returns; the kernel waits for it at its
|
|
33
|
+
* own barriers (before a `never` effect, before the drive goes idle), so
|
|
34
|
+
* `flush()` before a `never` tool still means "in the log before the tool".
|
|
35
|
+
*
|
|
36
|
+
* The journal's writes are in-band writes of the drive: they go through
|
|
37
|
+
* `ctx.effect`, so the writer fence (once a newer drive opens the session,
|
|
38
|
+
* this drive's writes are refused: a `Restart`), first-writer-wins per key and the
|
|
39
|
+
* outcome rules apply. A failed or refused write poisons the journal
|
|
40
|
+
* (`append` becomes a no-op, `flush` rejects) and halts the drive. So does a
|
|
41
|
+
* batch number another writer took first (two drives of one session, the
|
|
42
|
+
* other's batch already in this drive's fold, where `ctx.effect` would hand
|
|
43
|
+
* back its result as if it were this batch's): that is a `Restart`, and the
|
|
44
|
+
* drive rebuilds from the log instead of losing the batch's records.
|
|
45
|
+
*/
|
|
46
|
+
export class NativeJournal {
|
|
47
|
+
ctx;
|
|
48
|
+
inlineMax;
|
|
49
|
+
onPoison;
|
|
50
|
+
pieceChars;
|
|
51
|
+
/** The next batch number. */
|
|
52
|
+
n;
|
|
53
|
+
/** Next position per stream (log plus queue). */
|
|
54
|
+
next = new Map();
|
|
55
|
+
/** Record ids in the log or queued. */
|
|
56
|
+
ids = new Set();
|
|
57
|
+
/** Blobs known to be in the blob stream. */
|
|
58
|
+
blobs = new Set();
|
|
59
|
+
queue = [];
|
|
60
|
+
inflight;
|
|
61
|
+
appended = 0;
|
|
62
|
+
written = 0;
|
|
63
|
+
waiters = [];
|
|
64
|
+
failure;
|
|
65
|
+
/** This writer, in each batch's output: a batch is this journal's only if it says so. */
|
|
66
|
+
writer = randomUUID();
|
|
67
|
+
constructor(ctx, options = {}) {
|
|
68
|
+
this.ctx = ctx;
|
|
69
|
+
this.inlineMax = options.inlineMaxBytes ?? DEFAULT_INLINE_MAX_BYTES;
|
|
70
|
+
this.onPoison = options.onPoison ?? ((err) => ctx.halt?.(err));
|
|
71
|
+
this.pieceChars = options.blobPieceChars ?? BLOB_PIECE_CHARS;
|
|
72
|
+
const state = ctx.state();
|
|
73
|
+
this.n = journalBatches(state).length;
|
|
74
|
+
for (const r of journalRecords(state)) {
|
|
75
|
+
this.next.set(r.stream, r.seq + 1);
|
|
76
|
+
if (r.id !== undefined)
|
|
77
|
+
this.ids.add(r.id);
|
|
78
|
+
if (r.blob)
|
|
79
|
+
this.blobs.add(r.blob);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** The error that poisoned this journal, if one did. */
|
|
83
|
+
get poisoned() {
|
|
84
|
+
return this.failure?.err;
|
|
85
|
+
}
|
|
86
|
+
/** How many records `stream` has (committed plus queued). */
|
|
87
|
+
length(stream) {
|
|
88
|
+
return this.next.get(stream) ?? 0;
|
|
89
|
+
}
|
|
90
|
+
/** Whether a record with this id is in the log or queued. */
|
|
91
|
+
has(id) {
|
|
92
|
+
return this.ids.has(id);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Queue a record (a JSON value) on `stream`. Returns `false` when it was
|
|
96
|
+
* not queued: a record with the same `id` is already in the log or queued
|
|
97
|
+
* (dedupe), or the journal is poisoned.
|
|
98
|
+
*/
|
|
99
|
+
append(stream, data, options = {}) {
|
|
100
|
+
if (this.failure)
|
|
101
|
+
return false;
|
|
102
|
+
if (options.id !== undefined) {
|
|
103
|
+
if (this.ids.has(options.id))
|
|
104
|
+
return false;
|
|
105
|
+
this.ids.add(options.id);
|
|
106
|
+
}
|
|
107
|
+
const seq = this.next.get(stream) ?? 0;
|
|
108
|
+
this.next.set(stream, seq + 1);
|
|
109
|
+
this.queue.push({ stream, seq, data, ...(options.id !== undefined ? { id: options.id } : {}) });
|
|
110
|
+
this.appended++;
|
|
111
|
+
this.pump();
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
/** Append an entry to the normalized transcript. */
|
|
115
|
+
message(entry) {
|
|
116
|
+
return this.append(TRANSCRIPT, entry);
|
|
117
|
+
}
|
|
118
|
+
/** Resolves once every record appended so far is committed; rejects if the journal is poisoned. */
|
|
119
|
+
flush() {
|
|
120
|
+
if (this.failure)
|
|
121
|
+
return Promise.reject(this.failure.err);
|
|
122
|
+
if (this.written >= this.appended)
|
|
123
|
+
return Promise.resolve();
|
|
124
|
+
return new Promise((resolve, reject) => this.waiters.push({ target: this.appended, resolve, reject }));
|
|
125
|
+
}
|
|
126
|
+
/** The records of `stream` (or every stream) in the log, in order. Offloaded ones have `data: undefined`. */
|
|
127
|
+
records(stream) {
|
|
128
|
+
return journalRecords(this.ctx.state(), stream);
|
|
129
|
+
}
|
|
130
|
+
/** The same records with their blobs read back from the blob stream and checked against their hashes. */
|
|
131
|
+
read(stream) {
|
|
132
|
+
return readJournal(this.ctx, stream);
|
|
133
|
+
}
|
|
134
|
+
pump() {
|
|
135
|
+
if (this.inflight)
|
|
136
|
+
return;
|
|
137
|
+
this.inflight = (async () => {
|
|
138
|
+
// Let a synchronous burst of appends ride in one batch.
|
|
139
|
+
await Promise.resolve();
|
|
140
|
+
while (this.queue.length > 0 && !this.failure) {
|
|
141
|
+
const batch = this.queue;
|
|
142
|
+
this.queue = [];
|
|
143
|
+
try {
|
|
144
|
+
await this.write(batch);
|
|
145
|
+
}
|
|
146
|
+
catch (err) {
|
|
147
|
+
this.poison(err);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
this.written += batch.length;
|
|
151
|
+
this.settleWaiters();
|
|
152
|
+
}
|
|
153
|
+
})().finally(() => {
|
|
154
|
+
this.inflight = undefined;
|
|
155
|
+
if (this.queue.length > 0 && !this.failure)
|
|
156
|
+
this.pump();
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
settleWaiters() {
|
|
160
|
+
const still = [];
|
|
161
|
+
for (const w of this.waiters) {
|
|
162
|
+
if (this.written >= w.target)
|
|
163
|
+
w.resolve();
|
|
164
|
+
else
|
|
165
|
+
still.push(w);
|
|
166
|
+
}
|
|
167
|
+
this.waiters = still;
|
|
168
|
+
}
|
|
169
|
+
poison(err) {
|
|
170
|
+
if (this.failure)
|
|
171
|
+
return;
|
|
172
|
+
this.failure = { err };
|
|
173
|
+
this.queue = [];
|
|
174
|
+
for (const w of this.waiters.splice(0))
|
|
175
|
+
w.reject(err);
|
|
176
|
+
this.onPoison(err);
|
|
177
|
+
}
|
|
178
|
+
async write(queued) {
|
|
179
|
+
const streams = {};
|
|
180
|
+
for (const q of queued) {
|
|
181
|
+
const part = (streams[q.stream] ??= { from: q.seq, entries: [] });
|
|
182
|
+
part.entries.push(await this.store(q));
|
|
183
|
+
}
|
|
184
|
+
const n = this.n;
|
|
185
|
+
const batch = { v: 1, n, streams };
|
|
186
|
+
const writer = this.writer;
|
|
187
|
+
const out = await this.ctx.effect(journalKey(n), { name: JOURNAL, replay: 'safe', input: batch }, async () => ({ n, records: queued.length, writer }));
|
|
188
|
+
if (out?.writer !== writer)
|
|
189
|
+
throw new Restart(`agentrun-kernel: journal batch ${n} was written by another drive`);
|
|
190
|
+
this.n = n + 1;
|
|
191
|
+
}
|
|
192
|
+
/** A record as the batch stores it: inline, or offloaded to the blob stream (written before the batch). */
|
|
193
|
+
async store(q) {
|
|
194
|
+
const id = q.id !== undefined ? { id: q.id } : {};
|
|
195
|
+
// The transcript is what UIs read from the fold: it always stays inline.
|
|
196
|
+
if (q.stream === TRANSCRIPT)
|
|
197
|
+
return { ...id, data: q.data };
|
|
198
|
+
const text = JSON.stringify(q.data);
|
|
199
|
+
if (text === undefined)
|
|
200
|
+
throw new TypeError(`agentrun-kernel: journal record on ${q.stream} is not JSON`);
|
|
201
|
+
const bytes = encoder.encode(text).length;
|
|
202
|
+
if (bytes <= this.inlineMax)
|
|
203
|
+
return { ...id, data: q.data };
|
|
204
|
+
const hash = await sha256Hex(text);
|
|
205
|
+
if (!this.blobs.has(hash)) {
|
|
206
|
+
await writeBlob(this.ctx.world, this.ctx.runId, text, { hash, pieceChars: this.pieceChars });
|
|
207
|
+
this.blobs.add(hash);
|
|
208
|
+
}
|
|
209
|
+
return { ...id, blob: hash, bytes };
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Read a session's journal with offloaded records resolved: the blob stream
|
|
214
|
+
* is read once and every blob is checked against its hash. A blob the log
|
|
215
|
+
* names but the stream does not hold is `Fatal` (the batch commits only
|
|
216
|
+
* after its blobs are written, so the session cannot continue); a read that
|
|
217
|
+
* fails is thrown as it is (the delivery is retried).
|
|
218
|
+
*/
|
|
219
|
+
export async function readJournal(ctx, stream) {
|
|
220
|
+
const records = journalRecords(ctx.state(), stream);
|
|
221
|
+
if (!records.some((r) => r.blob))
|
|
222
|
+
return records;
|
|
223
|
+
const blobs = await readBlobs(ctx.world, ctx.runId);
|
|
224
|
+
return records.map((r) => {
|
|
225
|
+
if (!r.blob)
|
|
226
|
+
return r;
|
|
227
|
+
const text = blobs.get(r.blob);
|
|
228
|
+
if (text === undefined)
|
|
229
|
+
throw new Fatal(`agentrun-kernel: journal blob ${r.blob} (${r.stream} #${r.seq}) is missing from ${blobStreamName(ctx.runId)}`);
|
|
230
|
+
return { ...r, data: JSON.parse(text) };
|
|
231
|
+
});
|
|
232
|
+
}
|