@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.
Files changed (84) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +63 -2
  5. package/dist/booking.d.ts +50 -0
  6. package/dist/booking.js +52 -0
  7. package/dist/delegate.d.ts +87 -0
  8. package/dist/delegate.js +143 -0
  9. package/dist/errors.d.ts +36 -0
  10. package/dist/errors.js +37 -0
  11. package/dist/host/alive.d.ts +2 -0
  12. package/dist/host/alive.js +28 -0
  13. package/dist/host/box-slot.d.ts +26 -0
  14. package/dist/host/box-slot.js +112 -0
  15. package/dist/host/box.d.ts +104 -0
  16. package/dist/host/box.js +16 -0
  17. package/dist/host/egress-proxy.d.ts +45 -0
  18. package/dist/host/egress-proxy.js +416 -0
  19. package/dist/host/egress-table.d.ts +24 -0
  20. package/dist/host/egress-table.js +165 -0
  21. package/dist/host/index.d.ts +16 -0
  22. package/dist/host/index.js +12 -0
  23. package/dist/host/overhead.d.ts +53 -0
  24. package/dist/host/overhead.js +75 -0
  25. package/dist/host/parent-death.d.ts +15 -0
  26. package/dist/host/parent-death.js +42 -0
  27. package/dist/host/parent-watch.d.ts +1 -0
  28. package/dist/host/parent-watch.js +38 -0
  29. package/dist/host/pinned-binary.d.ts +6 -0
  30. package/dist/host/pinned-binary.js +48 -0
  31. package/dist/host/proxy.d.ts +212 -0
  32. package/dist/host/proxy.js +808 -0
  33. package/dist/host/serial.d.ts +3 -0
  34. package/dist/host/serial.js +10 -0
  35. package/dist/index.d.ts +13 -0
  36. package/dist/index.js +7 -0
  37. package/dist/kernel/blobs.d.ts +16 -0
  38. package/dist/kernel/blobs.js +59 -0
  39. package/dist/kernel/drive.d.ts +40 -0
  40. package/dist/kernel/drive.js +239 -0
  41. package/dist/kernel/errors.d.ts +27 -0
  42. package/dist/kernel/errors.js +42 -0
  43. package/dist/kernel/follow-up.d.ts +67 -0
  44. package/dist/kernel/follow-up.js +146 -0
  45. package/dist/kernel/halt.d.ts +11 -0
  46. package/dist/kernel/halt.js +17 -0
  47. package/dist/kernel/index.d.ts +8 -0
  48. package/dist/kernel/index.js +5 -0
  49. package/dist/kernel/types.d.ts +129 -0
  50. package/dist/kernel/types.js +1 -0
  51. package/dist/process/builtins.d.ts +142 -0
  52. package/dist/process/builtins.js +207 -0
  53. package/dist/process/inbox.d.ts +29 -0
  54. package/dist/process/inbox.js +52 -0
  55. package/dist/process/index.d.ts +9 -0
  56. package/dist/process/index.js +11 -0
  57. package/dist/process/journal.d.ts +111 -0
  58. package/dist/process/journal.js +232 -0
  59. package/dist/process/records.d.ts +143 -0
  60. package/dist/process/records.js +142 -0
  61. package/dist/process/recovery.d.ts +76 -0
  62. package/dist/process/recovery.js +139 -0
  63. package/dist/process/settle.d.ts +22 -0
  64. package/dist/process/settle.js +38 -0
  65. package/dist/process/tail.d.ts +20 -0
  66. package/dist/process/tail.js +53 -0
  67. package/dist/process/tools.d.ts +105 -0
  68. package/dist/process/tools.js +120 -0
  69. package/dist/process/zod.d.ts +32 -0
  70. package/dist/process/zod.js +109 -0
  71. package/dist/runner.d.ts +154 -0
  72. package/dist/runner.js +559 -0
  73. package/dist/schema-check-cases.d.ts +7 -0
  74. package/dist/schema-check-cases.js +73 -0
  75. package/dist/schema-check.d.ts +3 -0
  76. package/dist/schema-check.js +88 -0
  77. package/dist/skill-files.d.ts +23 -0
  78. package/dist/skill-files.js +136 -0
  79. package/dist/testing.d.ts +91 -0
  80. package/dist/testing.js +196 -0
  81. package/dist/types.d.ts +256 -0
  82. package/dist/types.js +17 -0
  83. package/package.json +74 -4
  84. package/vendor/durable-harness/UPSTREAM.json +67 -0
@@ -0,0 +1,143 @@
1
+ import type { EffectRecord, SessionState } from '../kernel/index.js';
2
+ /**
3
+ * The shape of a process harness's records in the run's log, and the pure
4
+ * readers for it. No Node imports: UIs (the demo's transcript, in a browser
5
+ * tab) read sessions with this module.
6
+ *
7
+ * A process harness mirrors its native session state (Codex's rollout) into
8
+ * the log as **journal batches**: record-only effects named `journal`, keyed
9
+ * `journal:<n>`, each carrying the records appended since the last batch,
10
+ * grouped by stream. The kernel's rules make the batches linear: the first
11
+ * committed step per key wins, a stale driver's step is fenced (its writer is
12
+ * refused once a newer drive opens the session), and a batch
13
+ * counts only once its outcome is committed. Every reader, the writer
14
+ * included, sees the same records in the same order.
15
+ *
16
+ * Next to its native streams, every process harness writes one normalized
17
+ * stream, `transcript` (`TranscriptEntry`), so one view renders any of them.
18
+ */
19
+ /** The effect name of every journal batch (`step//harness-world//journal` in dashboards). */
20
+ export declare const JOURNAL = "journal";
21
+ /** The normalized transcript's stream name. */
22
+ export declare const TRANSCRIPT = "transcript";
23
+ /** The memo key of batch `n`. */
24
+ export declare const journalKey: (n: number) => string;
25
+ /**
26
+ * One record as a batch stores it: its JSON value inline (`data`), or, when
27
+ * it is large, the SHA-256 of its JSON text (`blob`), whose bytes are in the
28
+ * session's blob stream (see `NativeJournal`).
29
+ */
30
+ export interface StoredEntry {
31
+ /** The harness's own id for the record, if it has one (dedupe). */
32
+ id?: string;
33
+ data?: unknown;
34
+ blob?: string;
35
+ /** Length of the offloaded JSON text. */
36
+ bytes?: number;
37
+ }
38
+ /** A `journal` effect's input. */
39
+ export interface JournalBatch {
40
+ v: 1;
41
+ /** This batch's number: it is the `n`-th accepted batch of the session. */
42
+ n: number;
43
+ /** Records per stream, with the stream position of the first. */
44
+ streams: Record<string, {
45
+ from: number;
46
+ entries: StoredEntry[];
47
+ }>;
48
+ }
49
+ /** A record read back from the log. */
50
+ export interface JournalRecord<T = unknown> {
51
+ stream: string;
52
+ /** 0-based position in its stream. */
53
+ seq: number;
54
+ id?: string;
55
+ /** The record. `undefined` for an offloaded one read here; `NativeJournal.read` resolves blobs. */
56
+ data: T;
57
+ blob?: string;
58
+ /** The batch it arrived in. */
59
+ batch: number;
60
+ stepId: string;
61
+ /** The batch's index in `SessionState.effectOrder` (to relate records to other effects). */
62
+ at: number;
63
+ }
64
+ /** A tool call an assistant message made. Its effect is `tool:<id>` (see `toolBridge`). */
65
+ export interface TranscriptToolCall {
66
+ id: string;
67
+ name: string;
68
+ }
69
+ /**
70
+ * The normalized transcript. User prompts are not here: they appear through
71
+ * the submissions the harness placed (`placeSubmissions`). What is here:
72
+ *
73
+ * - `message` / `assistant`: the model's text, and the tool calls it made
74
+ * (their inputs and results are the tool effects themselves);
75
+ * - `message` / `user` with `synthetic`: a message the harness sent itself,
76
+ * such as a recovery note;
77
+ * - `turn`: a turn boundary. A turn is open from the first placement after
78
+ * the last `turn` entry until the next one.
79
+ */
80
+ export type TranscriptEntry = {
81
+ type: 'message';
82
+ role: 'assistant';
83
+ text: string;
84
+ toolCalls?: TranscriptToolCall[];
85
+ } | {
86
+ type: 'message';
87
+ role: 'user';
88
+ text: string;
89
+ synthetic: string;
90
+ } | {
91
+ type: 'turn';
92
+ status: 'completed' | 'failed' | 'interrupted';
93
+ error?: string;
94
+ };
95
+ export interface BatchRef {
96
+ batch: JournalBatch;
97
+ record: EffectRecord;
98
+ /** Index in `effectOrder`. */
99
+ at: number;
100
+ }
101
+ /**
102
+ * The accepted batches, in order: `journal:0`, `journal:1`, ... up to the
103
+ * first that has no committed outcome. A batch whose intent landed but whose
104
+ * outcome did not (its writer died between the two writes) does not count;
105
+ * the next writer reuses its key.
106
+ */
107
+ export declare function journalBatches(state: SessionState): BatchRef[];
108
+ /** Every record of `stream` (or of every stream), in log order. Offloaded records have `data: undefined`. */
109
+ export declare function journalRecords<T = unknown>(state: SessionState, stream?: string): JournalRecord<T>[];
110
+ /** The normalized transcript, in log order. */
111
+ export declare function transcriptOf(state: SessionState): JournalRecord<TranscriptEntry>[];
112
+ /**
113
+ * Where the last turn ended: the `effectOrder` index of the batch holding
114
+ * the last `turn` entry, or of the last `unavailable` fact (a turn the
115
+ * harness could not run: it is over, with an error, and nothing in it is
116
+ * recovered), or -1 if no turn has ended yet. Everything after it belongs to
117
+ * the current (or an interrupted) turn.
118
+ */
119
+ export declare function lastTurnEnd(state: SessionState): number;
120
+ /**
121
+ * A batch input for UIs: the transcript entries as they are, every other
122
+ * stream as a count (native records can be large, and a page polling a
123
+ * session should not carry them).
124
+ */
125
+ export declare function summarizeBatch(input: unknown): unknown;
126
+ /** The transcript entries of one batch input (inline only; transcript entries are never offloaded). */
127
+ export declare function batchTranscript(input: unknown): TranscriptEntry[];
128
+ export interface OpenTurn {
129
+ /** `effectOrder` index of the batch that ended the previous turn (-1: none ended yet). */
130
+ since: number;
131
+ /** Submissions placed in this turn. */
132
+ placed: string[];
133
+ /** Tool calls made in it. */
134
+ calls: EffectRecord[];
135
+ /** Transcript entries written in it (assistant text, earlier recovery notes). */
136
+ entries: JournalRecord<TranscriptEntry>[];
137
+ }
138
+ /**
139
+ * The turn that has not ended: everything after the last `turn` entry of
140
+ * the transcript. `undefined` when the last turn ended and nothing happened
141
+ * since (nothing to recover; new submissions start a new turn as usual).
142
+ */
143
+ export declare function openTurn(state: SessionState): OpenTurn | undefined;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The shape of a process harness's records in the run's log, and the pure
3
+ * readers for it. No Node imports: UIs (the demo's transcript, in a browser
4
+ * tab) read sessions with this module.
5
+ *
6
+ * A process harness mirrors its native session state (Codex's rollout) into
7
+ * the log as **journal batches**: record-only effects named `journal`, keyed
8
+ * `journal:<n>`, each carrying the records appended since the last batch,
9
+ * grouped by stream. The kernel's rules make the batches linear: the first
10
+ * committed step per key wins, a stale driver's step is fenced (its writer is
11
+ * refused once a newer drive opens the session), and a batch
12
+ * counts only once its outcome is committed. Every reader, the writer
13
+ * included, sees the same records in the same order.
14
+ *
15
+ * Next to its native streams, every process harness writes one normalized
16
+ * stream, `transcript` (`TranscriptEntry`), so one view renders any of them.
17
+ */
18
+ /** The effect name of every journal batch (`step//harness-world//journal` in dashboards). */
19
+ export const JOURNAL = 'journal';
20
+ /** The normalized transcript's stream name. */
21
+ export const TRANSCRIPT = 'transcript';
22
+ /** The memo key of batch `n`. */
23
+ export const journalKey = (n) => `${JOURNAL}:${n}`;
24
+ /**
25
+ * The accepted batches, in order: `journal:0`, `journal:1`, ... up to the
26
+ * first that has no committed outcome. A batch whose intent landed but whose
27
+ * outcome did not (its writer died between the two writes) does not count;
28
+ * the next writer reuses its key.
29
+ */
30
+ export function journalBatches(state) {
31
+ const index = new Map();
32
+ state.effectOrder.forEach((r, i) => index.set(r, i));
33
+ const out = [];
34
+ for (let n = 0;; n++) {
35
+ const record = state.effects.get(journalKey(n));
36
+ if (!record || record.status !== 'completed' || record.name !== JOURNAL)
37
+ break;
38
+ out.push({ batch: record.input, record, at: index.get(record) ?? -1 });
39
+ }
40
+ return out;
41
+ }
42
+ /** Every record of `stream` (or of every stream), in log order. Offloaded records have `data: undefined`. */
43
+ export function journalRecords(state, stream) {
44
+ const out = [];
45
+ const seqs = new Map();
46
+ for (const { batch, record, at } of journalBatches(state)) {
47
+ for (const [name, part] of Object.entries(batch.streams ?? {})) {
48
+ if (stream !== undefined && name !== stream)
49
+ continue;
50
+ for (const entry of part.entries) {
51
+ const seq = seqs.get(name) ?? 0;
52
+ seqs.set(name, seq + 1);
53
+ out.push({
54
+ stream: name,
55
+ seq,
56
+ ...(entry.id !== undefined ? { id: entry.id } : {}),
57
+ data: entry.data,
58
+ ...(entry.blob ? { blob: entry.blob } : {}),
59
+ batch: batch.n,
60
+ stepId: record.stepId,
61
+ at,
62
+ });
63
+ }
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ /** The normalized transcript, in log order. */
69
+ export function transcriptOf(state) {
70
+ return journalRecords(state, TRANSCRIPT);
71
+ }
72
+ /**
73
+ * The `effectOrder` index of the last `unavailable` fact (harness-world's
74
+ * `lastUnavailable`, spelled here so this module stays type-only on the
75
+ * kernel), or -1.
76
+ */
77
+ function lastUnavailable(state) {
78
+ for (let i = state.effectOrder.length - 1; i >= 0; i--)
79
+ if (state.effectOrder[i].name === 'unavailable')
80
+ return i;
81
+ return -1;
82
+ }
83
+ /**
84
+ * Where the last turn ended: the `effectOrder` index of the batch holding
85
+ * the last `turn` entry, or of the last `unavailable` fact (a turn the
86
+ * harness could not run: it is over, with an error, and nothing in it is
87
+ * recovered), or -1 if no turn has ended yet. Everything after it belongs to
88
+ * the current (or an interrupted) turn.
89
+ */
90
+ export function lastTurnEnd(state) {
91
+ let at = -1;
92
+ for (const r of transcriptOf(state))
93
+ if (r.data?.type === 'turn')
94
+ at = r.at;
95
+ return Math.max(at, lastUnavailable(state));
96
+ }
97
+ /**
98
+ * A batch input for UIs: the transcript entries as they are, every other
99
+ * stream as a count (native records can be large, and a page polling a
100
+ * session should not carry them).
101
+ */
102
+ export function summarizeBatch(input) {
103
+ const batch = input;
104
+ if (!batch || typeof batch !== 'object' || !batch.streams)
105
+ return input;
106
+ const streams = {};
107
+ for (const [name, part] of Object.entries(batch.streams)) {
108
+ streams[name] =
109
+ name === TRANSCRIPT
110
+ ? part
111
+ : {
112
+ from: part.from,
113
+ count: part.entries.length,
114
+ blobs: part.entries.filter((e) => e.blob).length,
115
+ };
116
+ }
117
+ return { v: batch.v, n: batch.n, streams };
118
+ }
119
+ /** The transcript entries of one batch input (inline only; transcript entries are never offloaded). */
120
+ export function batchTranscript(input) {
121
+ const part = input?.streams?.[TRANSCRIPT];
122
+ return (part?.entries ?? []).map((e) => e.data).filter(Boolean);
123
+ }
124
+ /**
125
+ * The turn that has not ended: everything after the last `turn` entry of
126
+ * the transcript. `undefined` when the last turn ended and nothing happened
127
+ * since (nothing to recover; new submissions start a new turn as usual).
128
+ */
129
+ export function openTurn(state) {
130
+ const transcript = transcriptOf(state);
131
+ const end = transcript.findLast((r) => r.data?.type === 'turn');
132
+ const failed = lastUnavailable(state);
133
+ const since = Math.max(end?.at ?? -1, failed);
134
+ const after = state.effectOrder.slice(since + 1);
135
+ // A crash drill's own step places its chaos submission: that is not a turn.
136
+ const placed = after.filter((e) => e.placed.length > 0 && !e.name.startsWith('tool.') && e.name !== 'chaos').flatMap((e) => e.placed);
137
+ const calls = after.filter((e) => e.name.startsWith('tool.'));
138
+ const entries = transcript.filter((r) => (end ? r.seq > end.seq : true) && r.at > failed);
139
+ if (placed.length === 0 && calls.length === 0 && entries.length === 0)
140
+ return undefined;
141
+ return { since, placed, calls, entries };
142
+ }
@@ -0,0 +1,76 @@
1
+ import { type ReplayPolicy, type SessionState, type Submission } from '../kernel/index.js';
2
+ import { type OpenTurn, openTurn } from './records.js';
3
+ export { type OpenTurn, openTurn };
4
+ /**
5
+ * The recovery note: what a process harness tells its model when it resumes
6
+ * a turn a crash cut off. A CLI harness resumes its own session natively,
7
+ * but it never knows what happened to the calls that were in flight (Codex
8
+ * needs an output injected for a dangling call), and a resumed session needs a new
9
+ * user message to move. The note is that message, built from the log: the
10
+ * calls since the turn began, each with what the log knows about it.
11
+ */
12
+ export interface RecoveryCall {
13
+ callId: string;
14
+ name: string;
15
+ input: unknown;
16
+ replay: ReplayPolicy;
17
+ /**
18
+ * - `completed`: the result is recorded (`output`);
19
+ * - `failed`: the tool failed and said so (`error`);
20
+ * - `interrupted`: a `replay: 'never'` call whose outcome was lost: it may
21
+ * have taken effect;
22
+ * - `retryable`: a `replay: 'safe'` call that was interrupted: safe to repeat;
23
+ * - `running`: still open in the log (build the note after the kernel's
24
+ * recovery has resolved intents; a drive's own context always has).
25
+ */
26
+ status: 'completed' | 'failed' | 'interrupted' | 'retryable' | 'running';
27
+ output?: string;
28
+ error?: string;
29
+ }
30
+ export interface RecoveryOptions {
31
+ /** Pending submissions to fold into the note. Default: every pending one. Pass `[]` to place them separately. */
32
+ pending?: Submission[];
33
+ /**
34
+ * Quote the prompts placed in the interrupted turn. For a harness whose
35
+ * native session may have lost them (the crash came before the record of
36
+ * the message was in the log).
37
+ */
38
+ prompts?: boolean;
39
+ /** How much of a tool's output, input or error to quote. Default 1500 characters. */
40
+ clipChars?: number;
41
+ }
42
+ export interface RecoveryNote {
43
+ /** The message to send the harness, as a user message. */
44
+ text: string;
45
+ calls: RecoveryCall[];
46
+ /** The pending submissions the note carries: place these with it (`placeSubmissions`). */
47
+ pending: Submission[];
48
+ turn: OpenTurn;
49
+ }
50
+ /** The note for the open turn, or `undefined` if no turn is open. */
51
+ export declare function recoveryNote(state: SessionState, options?: RecoveryOptions): RecoveryNote | undefined;
52
+ /**
53
+ * The note as a harness carries it outside the user's turn (a system prompt, a developer item): from the harness, about the
54
+ * turn before, in the harness's own words only. It names each call and says how it ended, and never quotes what a tool was
55
+ * given or answered with (that is data the agent read, not something the harness may speak for), a prompt, or a pending message.
56
+ * `undefined` when no turn is open.
57
+ */
58
+ export declare function recoverySystemNote(state: SessionState): string | undefined;
59
+ /** The user's turn that resumes a cut-off turn: only the user's words (the prompts the session never got, then the messages sent since), or a bare nudge. */
60
+ export declare function recoveryUserTurn(lost: string[], pending: string[]): string;
61
+ /**
62
+ * The live event a harness sends as it resumes a turn a crash cut off,
63
+ * before the model answers again: the model starts the step the crash
64
+ * interrupted over, so what a reader saw of its reply is replaced.
65
+ * `text` is the turn's text as the log kept it (the assistant text of its
66
+ * finished steps, and the text before each tool call); a reader shows it in
67
+ * place of what it showed of the turn so far (everything since the last
68
+ * `idle`), and appends what streams after it. `parts` is the same text, one
69
+ * entry per kept step, for a reader that shows tool calls between them: a
70
+ * turn on screen with more text than `parts` has a cut-off reply last.
71
+ */
72
+ export declare function restartEvent(turn: OpenTurn): {
73
+ type: 'restart';
74
+ text: string;
75
+ parts: string[];
76
+ };
@@ -0,0 +1,139 @@
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/recovery.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
+ // Changed by Parcha, imports rewritten for AgentRun; patches: 003-comments-name-this-host, 009-recovery-system-note, 010-recovery-note-statuses-only
4
+ import { pendingSubmissions } from '../kernel/index.js';
5
+ import { openTurn } from './records.js';
6
+ export { openTurn };
7
+ /** The note for the open turn, or `undefined` if no turn is open. */
8
+ export function recoveryNote(state, options = {}) {
9
+ const turn = openTurn(state);
10
+ if (!turn)
11
+ return undefined;
12
+ const max = options.clipChars ?? 1500;
13
+ const calls = turn.calls.map((e) => recoveryCall(e, max));
14
+ const pending = options.pending ?? pendingSubmissions(state);
15
+ const lines = [
16
+ '[Recovery] Your previous turn was interrupted: the process running it stopped, and this session was resumed from its durable log.',
17
+ ];
18
+ if (options.prompts) {
19
+ const texts = turn.placed
20
+ .map((id) => state.submissions.find((s) => s.id === id)?.text)
21
+ .filter((t) => !!t);
22
+ if (texts.length)
23
+ lines.push('', 'The user\'s message in that turn:', ...texts.map((t) => quote(clip(t, max))));
24
+ }
25
+ lines.push('');
26
+ if (calls.length === 0)
27
+ lines.push('No tool call had started in that turn.');
28
+ else {
29
+ lines.push('What the log records about the tool calls since that turn began:');
30
+ for (const c of calls)
31
+ lines.push(...describe(c));
32
+ }
33
+ lines.push('', 'Check the actual state before repeating anything that may have taken effect, then carry on with the task.');
34
+ if (pending.length) {
35
+ lines.push('', 'New messages since then:');
36
+ for (const s of pending)
37
+ lines.push(quote(s.text ?? ''));
38
+ }
39
+ return { text: lines.join('\n'), calls, pending, turn };
40
+ }
41
+ /**
42
+ * The note as a harness carries it outside the user's turn (a system prompt, a developer item): from the harness, about the
43
+ * turn before, in the harness's own words only. It names each call and says how it ended, and never quotes what a tool was
44
+ * given or answered with (that is data the agent read, not something the harness may speak for), a prompt, or a pending message.
45
+ * `undefined` when no turn is open.
46
+ */
47
+ export function recoverySystemNote(state) {
48
+ const turn = openTurn(state);
49
+ if (!turn)
50
+ return undefined;
51
+ const calls = turn.calls.map((e) => recoveryCall(e, 0));
52
+ const lines = [
53
+ 'The harness, not the user, adds this about the turn before this one:',
54
+ '[Recovery] Your previous turn was interrupted: the process running it stopped, and this session was resumed from its durable log.',
55
+ '',
56
+ ];
57
+ if (calls.length === 0)
58
+ lines.push('No tool call had started in that turn.');
59
+ else {
60
+ lines.push('What the log records about the tool calls since that turn began (none was run again):');
61
+ for (const c of calls)
62
+ lines.push(`- ${c.name}, call ${c.callId}: ${ended(c)}`);
63
+ lines.push('', 'The output of those calls is not shown here. Check the actual state before relying on it.');
64
+ }
65
+ lines.push('', 'Check the actual state before repeating anything that may have taken effect, then carry on with the task.');
66
+ return lines.join('\n');
67
+ }
68
+ function ended(c) {
69
+ switch (c.status) {
70
+ case 'completed':
71
+ return 'completed.';
72
+ case 'failed':
73
+ return 'failed.';
74
+ case 'interrupted':
75
+ return 'interrupted before it reported a result. It is not safe to repeat, and it may have taken effect.';
76
+ case 'retryable':
77
+ return 'interrupted before it reported a result. It is safe to repeat.';
78
+ case 'running':
79
+ return 'interrupted, and it may still be running. It may have taken effect.';
80
+ }
81
+ }
82
+ /** The user's turn that resumes a cut-off turn: only the user's words (the prompts the session never got, then the messages sent since), or a bare nudge. */
83
+ export function recoveryUserTurn(lost, pending) {
84
+ const words = [...lost, ...pending].filter((t) => t !== '');
85
+ return words.length ? words.join('\n\n') : 'Continue.';
86
+ }
87
+ function recoveryCall(e, max) {
88
+ const base = {
89
+ callId: e.key.startsWith('tool:') ? e.key.slice(5) : e.key,
90
+ name: e.name.slice('tool.'.length),
91
+ input: e.input,
92
+ replay: e.replay,
93
+ };
94
+ if (e.status === 'completed')
95
+ return { ...base, status: 'completed', output: clip(text(e.output), max) };
96
+ if (e.status === 'pending')
97
+ return { ...base, status: 'retryable' };
98
+ if (e.status === 'running')
99
+ return { ...base, status: 'running' };
100
+ if (e.error?.interrupted)
101
+ return { ...base, status: e.replay === 'safe' ? 'retryable' : 'interrupted' };
102
+ return { ...base, status: 'failed', error: clip(e.error?.message ?? 'failed', max) };
103
+ }
104
+ function describe(c) {
105
+ const head = `- ${c.name}(${clip(text(c.input), 300)}), call ${c.callId}:`;
106
+ switch (c.status) {
107
+ case 'completed':
108
+ return [`${head} completed. Its result:`, ...indent(c.output ?? '')];
109
+ case 'failed':
110
+ return [`${head} failed: ${c.error}`];
111
+ case 'interrupted':
112
+ return [`${head} interrupted before it reported a result. It is not safe to repeat, and it may have taken effect: check before repeating it.`];
113
+ case 'retryable':
114
+ return [`${head} interrupted before it reported a result. It is safe to repeat.`];
115
+ case 'running':
116
+ return [`${head} interrupted, and it may still be running. It may have taken effect: check before repeating it.`];
117
+ }
118
+ }
119
+ const text = (v) => (typeof v === 'string' ? v : JSON.stringify(v) ?? String(v));
120
+ const quote = (t) => t.split('\n').map((l) => `> ${l}`).join('\n');
121
+ const indent = (t) => t.split('\n').map((l) => ` ${l}`);
122
+ function clip(t, max) {
123
+ return t.length <= max ? t : `${t.slice(0, max)}… [${t.length - max} more characters]`;
124
+ }
125
+ /**
126
+ * The live event a harness sends as it resumes a turn a crash cut off,
127
+ * before the model answers again: the model starts the step the crash
128
+ * interrupted over, so what a reader saw of its reply is replaced.
129
+ * `text` is the turn's text as the log kept it (the assistant text of its
130
+ * finished steps, and the text before each tool call); a reader shows it in
131
+ * place of what it showed of the turn so far (everything since the last
132
+ * `idle`), and appends what streams after it. `parts` is the same text, one
133
+ * entry per kept step, for a reader that shows tool calls between them: a
134
+ * turn on screen with more text than `parts` has a cut-off reply last.
135
+ */
136
+ export function restartEvent(turn) {
137
+ const parts = turn.entries.flatMap((r) => (r.data?.type === 'message' && r.data.role === 'assistant' && r.data.text ? [r.data.text] : []));
138
+ return { type: 'restart', text: parts.join('\n\n'), parts };
139
+ }
@@ -0,0 +1,22 @@
1
+ import { type Drive } from "../kernel/index.js";
2
+ /** How a settle treats the open turn's prompts beyond those still pending. */
3
+ export interface SettleOptions {
4
+ /** Placed prompts and follow-ups the harness's CLI never recorded (its own record, as the session keeps it): carried,
5
+ * as a pending one is. */
6
+ readonly unsent?: readonly string[];
7
+ /** The submission of a host's own prompt (a follow-up's, `FollowUpTarget.settleOpenTurn`'s `opening`): withdrawn
8
+ * while pending, never carried, and the only one withdrawn. */
9
+ readonly host?: string;
10
+ }
11
+ /**
12
+ * Records the session's open turn as ended in its transcript, the record a turn that ends writes (so `openTurn` finds
13
+ * none, and the next turn carries no recovery note for it), and runs nothing. Input the turn never placed (a stop that
14
+ * landed before the harness took its prompt) is withdrawn first, so no later open finds it pending and nothing of it
15
+ * runs on its own; a prompt or follow-up is withdrawn with `carry`, so its text stays in the conversation, carried into
16
+ * the next one (the kernel's pendingSubmissions). A steer is not carried. So is a placed one its harness never sent
17
+ * (`unsent`: the adapter reads its CLI's own record), and a host's prompt (`host`) is dropped instead. It is the write behind
18
+ * `AdapterSession.settleOpenTurn()` for a turn the person stopped, which is never resumed. The adapter checks that a
19
+ * turn is open. The end is the kernel's for the session's own stop (`abortedOutcome` of its `SessionHalt`), the one
20
+ * path an interrupted turn's end takes, though the turn never ran in this process.
21
+ */
22
+ export declare function settleTurn(drive: Drive, options?: SettleOptions): Promise<void>;
@@ -0,0 +1,38 @@
1
+ // AgentRun's own (not copied): how a process harness settles a turn its session left open.
2
+ import { abortedOutcome, pendingSubmissions, SessionHalt } from "../kernel/index.js";
3
+ import { NativeJournal } from "./journal.js";
4
+ /**
5
+ * Records the session's open turn as ended in its transcript, the record a turn that ends writes (so `openTurn` finds
6
+ * none, and the next turn carries no recovery note for it), and runs nothing. Input the turn never placed (a stop that
7
+ * landed before the harness took its prompt) is withdrawn first, so no later open finds it pending and nothing of it
8
+ * runs on its own; a prompt or follow-up is withdrawn with `carry`, so its text stays in the conversation, carried into
9
+ * the next one (the kernel's pendingSubmissions). A steer is not carried. So is a placed one its harness never sent
10
+ * (`unsent`: the adapter reads its CLI's own record), and a host's prompt (`host`) is dropped instead. It is the write behind
11
+ * `AdapterSession.settleOpenTurn()` for a turn the person stopped, which is never resumed. The adapter checks that a
12
+ * turn is open. The end is the kernel's for the session's own stop (`abortedOutcome` of its `SessionHalt`), the one
13
+ * path an interrupted turn's end takes, though the turn never ran in this process.
14
+ */
15
+ export async function settleTurn(drive, options = {}) {
16
+ const state = drive.state();
17
+ // A placed prompt or follow-up its CLI never recorded (the stop landed between its placement and the CLI's record of
18
+ // it) is carried too, first, as it came first. It stays placed, so nothing sends it on its own. A host's is not.
19
+ for (const id of options.unsent ?? []) {
20
+ const submission = state.submissions.find((s) => s.id === id);
21
+ if (id === options.host || !state.placed.has(id) || (submission?.kind !== "prompt" && submission?.kind !== "followUp"))
22
+ continue;
23
+ await drive.submit({ id: `withdraw:${id}`, kind: "withdraw", target: id, carry: true, unsent: true });
24
+ }
25
+ // A follow-up's settle names its own prompt (`host`): that one is withdrawn and never carried, and the rest is left
26
+ // as it is (kernel/follow-up.ts). A person's stop withdraws every prompt pending.
27
+ const pending = pendingSubmissions(drive.state()).filter((s) => options.host === undefined || s.id === options.host);
28
+ for (const submission of pending) {
29
+ // A prompt or follow-up the person stopped stays in the conversation: its text is carried into the next one
30
+ // (pendingSubmissions). A stopped steer is dropped, and so is a host's prompt: one that never ran is not sent.
31
+ const carry = submission.kind !== "steer" && submission.id !== options.host;
32
+ await drive.submit({ id: `withdraw:${submission.id}`, kind: "withdraw", target: submission.id, ...(carry ? { carry: true } : {}) });
33
+ }
34
+ const { status, error } = abortedOutcome(AbortSignal.abort(new SessionHalt("interrupted")));
35
+ const journal = new NativeJournal(drive);
36
+ journal.message({ type: "turn", status, ...(error === undefined ? {} : { error }) });
37
+ await journal.flush();
38
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A line-complete tail of an append-only file (a JSONL transcript, a
3
+ * rollout): `read()` returns the lines completed since the last read and
4
+ * keeps a partial last line for the next one. For mirroring a native
5
+ * session file into the journal as the harness writes it.
6
+ */
7
+ export declare class FileTail {
8
+ readonly path: string;
9
+ /** Byte offset already consumed (the length of what the journal already holds). */
10
+ offset: number;
11
+ constructor(path: string,
12
+ /** Byte offset already consumed (the length of what the journal already holds). */
13
+ offset?: number);
14
+ /**
15
+ * The complete lines appended since the last read. Throws if the file is
16
+ * now shorter than what was read: it was rewritten, not appended to, and
17
+ * the journal can no longer mirror it line by line.
18
+ */
19
+ read(): string[];
20
+ }
@@ -0,0 +1,53 @@
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/tail.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
+ // Changed by Parcha, patches: 002-message-prefix
4
+ import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
5
+ /**
6
+ * A line-complete tail of an append-only file (a JSONL transcript, a
7
+ * rollout): `read()` returns the lines completed since the last read and
8
+ * keeps a partial last line for the next one. For mirroring a native
9
+ * session file into the journal as the harness writes it.
10
+ */
11
+ export class FileTail {
12
+ path;
13
+ offset;
14
+ constructor(path,
15
+ /** Byte offset already consumed (the length of what the journal already holds). */
16
+ offset = 0) {
17
+ this.path = path;
18
+ this.offset = offset;
19
+ }
20
+ /**
21
+ * The complete lines appended since the last read. Throws if the file is
22
+ * now shorter than what was read: it was rewritten, not appended to, and
23
+ * the journal can no longer mirror it line by line.
24
+ */
25
+ read() {
26
+ let fd;
27
+ try {
28
+ fd = openSync(this.path, 'r');
29
+ }
30
+ catch (err) {
31
+ if (err.code === 'ENOENT')
32
+ return [];
33
+ throw err;
34
+ }
35
+ try {
36
+ const size = fstatSync(fd).size;
37
+ if (size < this.offset)
38
+ throw new Error(`agentrun-kernel: ${this.path} shrank from ${this.offset} to ${size} bytes`);
39
+ if (size === this.offset)
40
+ return [];
41
+ const buf = Buffer.alloc(size - this.offset);
42
+ readSync(fd, buf, 0, buf.length, this.offset);
43
+ const last = buf.lastIndexOf(0x0a);
44
+ if (last < 0)
45
+ return [];
46
+ this.offset += last + 1;
47
+ return buf.subarray(0, last).toString('utf8').split('\n');
48
+ }
49
+ finally {
50
+ closeSync(fd);
51
+ }
52
+ }
53
+ }