@orion-agents/orion-code 0.4.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/dist/acp/sessions.js +1 -1
  5. package/dist/acp/stdio.js +17 -2
  6. package/dist/cli.js +45 -4
  7. package/dist/commands/session-command-handlers.js +8 -3
  8. package/dist/commands/system-commands.js +3 -3
  9. package/dist/commands/types.d.ts +3 -0
  10. package/dist/framework/loop-progress.js +3 -1
  11. package/dist/framework/query.d.ts +3 -1
  12. package/dist/framework/query.js +18 -3
  13. package/dist/framework/tool-serializer.d.ts +12 -0
  14. package/dist/framework/tool-serializer.js +35 -0
  15. package/dist/framework/tool.d.ts +2 -0
  16. package/dist/harness/ledger.js +2 -1
  17. package/dist/print-ui/delivery.d.ts +15 -0
  18. package/dist/print-ui/delivery.js +131 -0
  19. package/dist/print-ui/event-stream.d.ts +6 -1
  20. package/dist/print-ui/event-stream.js +56 -10
  21. package/dist/print-ui/launch.d.ts +5 -0
  22. package/dist/print-ui/launch.js +66 -9
  23. package/dist/runtime/agent-loop.d.ts +3 -1
  24. package/dist/runtime/agent-loop.js +20 -8
  25. package/dist/runtime/agent-runtime-controller.d.ts +4 -1
  26. package/dist/runtime/agent-runtime-controller.js +36 -22
  27. package/dist/runtime/agent-runtime-runner.d.ts +4 -0
  28. package/dist/runtime/agent-runtime-runner.js +9 -0
  29. package/dist/runtime/builtin-tool-provider.js +6 -5
  30. package/dist/runtime/composer/layout.d.ts +1 -1
  31. package/dist/runtime/composer/layout.js +5 -5
  32. package/dist/runtime/core-tools/descriptors.d.ts +1 -1
  33. package/dist/runtime/core-tools/descriptors.js +39 -1
  34. package/dist/runtime/first-party-core-provider.js +1 -0
  35. package/dist/runtime/first-party-tool-services.js +10 -0
  36. package/dist/runtime/goals/evidence.js +2 -0
  37. package/dist/runtime/legacy-thread-materializer.d.ts +7 -0
  38. package/dist/runtime/legacy-thread-materializer.js +32 -6
  39. package/dist/runtime/orion-runtime-v1.d.ts +2 -1
  40. package/dist/runtime/orion-runtime-v1.js +1 -0
  41. package/dist/runtime/product-bootstrap.d.ts +2 -0
  42. package/dist/runtime/product-bootstrap.js +1 -0
  43. package/dist/runtime/product-orion-runtime.d.ts +2 -1
  44. package/dist/runtime/product-orion-runtime.js +1 -0
  45. package/dist/runtime/release-receipts.d.ts +0 -1
  46. package/dist/runtime/release-receipts.js +8 -3
  47. package/dist/runtime/rich-text/layout.d.ts +3 -1
  48. package/dist/runtime/rich-text/layout.js +37 -22
  49. package/dist/runtime/shell-process-sessions.d.ts +41 -0
  50. package/dist/runtime/shell-process-sessions.js +258 -0
  51. package/dist/runtime/step-snapshot.js +4 -1
  52. package/dist/runtime/subagents/presets.d.ts +1 -1
  53. package/dist/runtime/subagents/presets.js +1 -0
  54. package/dist/runtime/task-context-recovery.js +7 -0
  55. package/dist/runtime/thread-event-store.d.ts +3 -0
  56. package/dist/runtime/thread-event-store.js +35 -22
  57. package/dist/runtime/thread-session-index.d.ts +15 -3
  58. package/dist/runtime/thread-session-index.js +152 -45
  59. package/dist/runtime/thread-session-view.js +1 -1
  60. package/dist/runtime/thread-ui-adapter.d.ts +1 -1
  61. package/dist/runtime/thread-ui-adapter.js +14 -8
  62. package/dist/runtime/tool-gateway.d.ts +1 -0
  63. package/dist/runtime/tool-gateway.js +1 -0
  64. package/dist/runtime/tool-transcript-entry.d.ts +8 -1
  65. package/dist/runtime/tool-transcript-entry.js +35 -7
  66. package/dist/runtime/ui-events.d.ts +7 -0
  67. package/dist/services/global-config.d.ts +1 -1
  68. package/dist/services/global-config.js +2 -0
  69. package/dist/services/llm.d.ts +3 -0
  70. package/dist/services/llm.js +48 -4
  71. package/dist/terminal-ui/raw-editor.js +2 -1
  72. package/dist/tools/core/exec-command.js +51 -42
  73. package/dist/tools/core/index.d.ts +2 -1
  74. package/dist/tools/core/index.js +4 -1
  75. package/dist/tools/core/process-session.d.ts +2 -0
  76. package/dist/tools/core/process-session.js +54 -0
  77. package/dist/tui-core/frame.d.ts +2 -0
  78. package/dist/tui-core/frame.js +19 -0
  79. package/dist/tui-core/input-parser.d.ts +4 -1
  80. package/dist/tui-core/input-parser.js +22 -0
  81. package/dist/tui-ui/chrome-view-model.d.ts +0 -2
  82. package/dist/tui-ui/chrome-view-model.js +54 -56
  83. package/dist/tui-ui/launch.js +133 -202
  84. package/dist/tui-ui/layout.d.ts +16 -41
  85. package/dist/tui-ui/layout.js +408 -295
  86. package/dist/tui-ui/render-scheduler.d.ts +2 -5
  87. package/dist/tui-ui/render-scheduler.js +10 -10
  88. package/dist/tui-ui/response-clipboard.d.ts +17 -0
  89. package/dist/tui-ui/response-clipboard.js +201 -0
  90. package/dist/tui-ui/runner.d.ts +65 -80
  91. package/dist/tui-ui/runner.js +545 -738
  92. package/dist/tui-ui/session-picker-preview.d.ts +8 -0
  93. package/dist/tui-ui/session-picker-preview.js +119 -0
  94. package/dist/tui-ui/session-picker.d.ts +20 -0
  95. package/dist/tui-ui/session-picker.js +42 -0
  96. package/dist/tui-ui/state.d.ts +34 -81
  97. package/dist/tui-ui/state.js +155 -288
  98. package/dist/tui-ui/terminal-image.d.ts +3 -7
  99. package/dist/tui-ui/terminal-image.js +18 -47
  100. package/dist/tui-ui/terminal-viewport.d.ts +55 -0
  101. package/dist/tui-ui/terminal-viewport.js +221 -0
  102. package/dist/tui-ui/transcript-layout.d.ts +5 -0
  103. package/dist/tui-ui/transcript-layout.js +43 -28
  104. package/dist/tui-ui/transcript-pager.d.ts +39 -0
  105. package/dist/tui-ui/transcript-pager.js +278 -0
  106. package/dist/tui-ui/transcript-tool-output.d.ts +16 -0
  107. package/dist/tui-ui/transcript-tool-output.js +102 -0
  108. package/dist/utils/bounded-file.d.ts +4 -0
  109. package/dist/utils/bounded-file.js +30 -0
  110. package/dist/utils/command-process.d.ts +4 -0
  111. package/dist/utils/command-process.js +23 -0
  112. package/docs/cli-guide.md +50 -6
  113. package/npm-shrinkwrap.json +115 -15
  114. package/package.json +4 -1
  115. package/dist/tui-ui/inline-surface.d.ts +0 -191
  116. package/dist/tui-ui/inline-surface.js +0 -644
  117. package/dist/tui-ui/input-ownership.d.ts +0 -46
  118. package/dist/tui-ui/input-ownership.js +0 -74
  119. package/dist/tui-ui/transcript-inspector-layout.d.ts +0 -9
  120. package/dist/tui-ui/transcript-inspector-layout.js +0 -107
  121. package/dist/tui-ui/transcript-inspector-surface.d.ts +0 -18
  122. package/dist/tui-ui/transcript-inspector-surface.js +0 -91
  123. package/dist/tui-ui/transcript-inspector.d.ts +0 -36
  124. package/dist/tui-ui/transcript-inspector.js +0 -129
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TurnShellProcesses = exports.MAX_PROCESS_INPUT_BYTES = exports.MAX_PROCESS_YIELD_MS = exports.DEFAULT_PROCESS_YIELD_MS = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const path_1 = require("path");
6
+ const command_process_1 = require("../utils/command-process");
7
+ const utf8_1 = require("../utils/utf8");
8
+ exports.DEFAULT_PROCESS_YIELD_MS = 500;
9
+ exports.MAX_PROCESS_YIELD_MS = 5000;
10
+ exports.MAX_PROCESS_INPUT_BYTES = 65536;
11
+ const MAX_PROCESS_SESSIONS = 8;
12
+ const KILL_GRACE_MS = 500;
13
+ /** Retained commands belong to one running Thread/Turn and are never restored from storage. */
14
+ class TurnShellProcesses {
15
+ constructor(turnSignal) {
16
+ this.turnSignal = turnSignal;
17
+ this.sessions = new Map();
18
+ this.abort = () => void this.close();
19
+ turnSignal?.addEventListener('abort', this.abort, { once: true });
20
+ }
21
+ async start(options) {
22
+ if (this.closing || this.turnSignal?.aborted || options.signal?.aborted) {
23
+ return failure('Process start was interrupted.');
24
+ }
25
+ if (this.sessions.size >= MAX_PROCESS_SESSIONS) {
26
+ return failure(`This turn has ${MAX_PROCESS_SESSIONS} process handles. Poll or cancel one first.`);
27
+ }
28
+ let session;
29
+ try {
30
+ session = new ShellProcess(options);
31
+ }
32
+ catch (error) {
33
+ return failure(error instanceof Error ? error.message : String(error));
34
+ }
35
+ this.sessions.set(session.id, session);
36
+ await session.started;
37
+ await session.wait(options.yieldMs, options.signal);
38
+ if (options.signal?.aborted || this.turnSignal?.aborted || this.closing) {
39
+ await session.stop('aborted');
40
+ this.sessions.delete(session.id);
41
+ return failure('Process start was interrupted.');
42
+ }
43
+ return this.read(session);
44
+ }
45
+ backendFor(processId, projectRoot) {
46
+ return this.get(processId, projectRoot)?.options.backend;
47
+ }
48
+ async operate(request) {
49
+ const session = this.get(request.processId, request.projectRoot);
50
+ if (!session)
51
+ return failure('Unknown or expired processId for this turn and workspace.');
52
+ if (request.signal?.aborted)
53
+ return failure('Process operation was interrupted.');
54
+ if (session.busy)
55
+ return failure('Another operation is in progress for this processId.');
56
+ session.busy = true;
57
+ try {
58
+ if (request.action === 'cancel') {
59
+ await session.stop('cancelled');
60
+ return this.read(session);
61
+ }
62
+ if (request.action === 'write') {
63
+ const problem = session.write(request.input ?? '');
64
+ if (problem)
65
+ return failure(problem);
66
+ }
67
+ await session.wait(request.yieldMs, request.signal, request.action === 'write');
68
+ if (request.signal?.aborted || this.closing) {
69
+ return failure('Process operation was interrupted.');
70
+ }
71
+ return this.read(session, request.action === 'write');
72
+ }
73
+ finally {
74
+ session.busy = false;
75
+ }
76
+ }
77
+ close() {
78
+ if (!this.closing) {
79
+ this.turnSignal?.removeEventListener('abort', this.abort);
80
+ this.closing = Promise.all([...this.sessions.values()].map(session => session.stop('aborted'))).then(() => this.sessions.clear());
81
+ }
82
+ return this.closing;
83
+ }
84
+ get(processId, projectRoot) {
85
+ if (this.closing || this.turnSignal?.aborted)
86
+ return undefined;
87
+ const session = this.sessions.get(processId);
88
+ return session?.options.projectRoot === (0, path_1.resolve)(projectRoot) ? session : undefined;
89
+ }
90
+ read(session, wroteInput = false) {
91
+ const result = session.read(wroteInput);
92
+ if (session.terminal)
93
+ this.sessions.delete(session.id);
94
+ return result;
95
+ }
96
+ }
97
+ exports.TurnShellProcesses = TurnShellProcesses;
98
+ class ShellProcess {
99
+ constructor(options) {
100
+ this.options = options;
101
+ this.id = (0, crypto_1.randomUUID)();
102
+ this.busy = false;
103
+ this.inputPending = false;
104
+ this.output = { text: '', bytes: 0, truncated: false };
105
+ this.child = (0, command_process_1.spawnCommandProcess)(options.file, options.args, options.cwd);
106
+ const { child } = this;
107
+ this.started = new Promise(done => {
108
+ child.once('spawn', done);
109
+ child.once('close', done);
110
+ });
111
+ this.closed = new Promise(done => {
112
+ let spawnError;
113
+ child.on('error', error => {
114
+ if (!child.pid)
115
+ spawnError = error.message;
116
+ });
117
+ child.once('close', (code, signal) => {
118
+ clearTimeout(this.timeout);
119
+ if (!this.termination && process.platform !== 'win32') {
120
+ // A shell can exit with a background process whose pipes were redirected.
121
+ (0, command_process_1.signalCommandProcess)(child, 'SIGKILL');
122
+ }
123
+ this.exit = { code: spawnError ? null : code, signal, error: spawnError };
124
+ this.notify?.();
125
+ done();
126
+ });
127
+ });
128
+ // Stdin can emit EPIPE after write() has accepted the input, including
129
+ // when exit and write race. Keep the error on this handle.
130
+ child.stdin.on('error', error => {
131
+ this.inputError = error.message;
132
+ this.notify?.();
133
+ });
134
+ child.stdout.setEncoding('utf8').on('data', (chunk) => this.append('stdout', chunk));
135
+ child.stderr.setEncoding('utf8').on('data', (chunk) => this.append('stderr', chunk));
136
+ this.timeout = setTimeout(() => void this.stop('timed_out'), options.timeoutMs);
137
+ this.timeout.unref();
138
+ }
139
+ get terminal() {
140
+ return this.exit !== undefined;
141
+ }
142
+ write(input) {
143
+ const { child } = this;
144
+ if (this.exit || child.exitCode !== null || child.signalCode !== null || this.stoppedBy) {
145
+ return 'The process has stopped accepting input. Poll to read its final output.';
146
+ }
147
+ if (this.inputError || !child.stdin.writable) {
148
+ return `Process stdin is unavailable${this.inputError ? `: ${this.inputError}` : '.'}`;
149
+ }
150
+ if (this.inputPending)
151
+ return 'A previous stdin write is still pending.';
152
+ this.inputPending = true;
153
+ child.stdin.write(input, error => {
154
+ this.inputPending = false;
155
+ if (error) {
156
+ this.inputError = error.message;
157
+ this.notify?.();
158
+ }
159
+ });
160
+ return undefined;
161
+ }
162
+ wait(yieldMs, signal, wroteInput = false) {
163
+ if (this.exit ||
164
+ this.output.bytes ||
165
+ (wroteInput && this.inputError) ||
166
+ !yieldMs ||
167
+ signal?.aborted)
168
+ return;
169
+ return new Promise(resolve => {
170
+ const finish = () => {
171
+ clearTimeout(timer);
172
+ signal?.removeEventListener('abort', finish);
173
+ this.notify = undefined;
174
+ resolve();
175
+ };
176
+ const timer = setTimeout(finish, yieldMs);
177
+ signal?.addEventListener('abort', finish, { once: true });
178
+ this.notify = finish;
179
+ });
180
+ }
181
+ async stop(reason) {
182
+ if (!this.exit && !this.termination) {
183
+ this.stoppedBy = reason;
184
+ this.termination = this.terminate();
185
+ }
186
+ await this.termination;
187
+ }
188
+ read(wroteInput) {
189
+ const { exit, stoppedBy, output } = this;
190
+ const status = exit ? (stoppedBy ?? (exit.error ? 'failed' : 'exited')) : 'running';
191
+ const inputError = wroteInput ? this.inputError : undefined;
192
+ const error = inputError ??
193
+ (status === 'timed_out'
194
+ ? `Process timed out after ${this.options.timeoutMs}ms.`
195
+ : status === 'aborted'
196
+ ? 'Process was interrupted.'
197
+ : (exit?.error ??
198
+ (status === 'exited' && exit?.code !== 0
199
+ ? exit?.signal
200
+ ? `Process terminated by signal ${exit.signal}.`
201
+ : `Process exited with code ${exit?.code}.`
202
+ : undefined)));
203
+ const result = {
204
+ success: !error,
205
+ output: output.text,
206
+ ...(error ? { error } : {}),
207
+ metadata: {
208
+ processId: this.id,
209
+ processStatus: status,
210
+ outputTruncated: output.truncated,
211
+ ...(typeof exit?.code === 'number' ? { exitCode: exit.code } : {}),
212
+ ...(exit?.signal ? { signal: exit.signal } : {}),
213
+ ...(wroteInput && !inputError ? { inputQueued: true } : {}),
214
+ ...(this.inputError ? { stdinError: this.inputError } : {}),
215
+ },
216
+ };
217
+ this.output = { text: '', bytes: 0, truncated: false };
218
+ return result;
219
+ }
220
+ append(stream, chunk) {
221
+ const { output } = this;
222
+ if (output.truncated)
223
+ return;
224
+ const section = output.stream === stream || (!output.stream && stream === 'stdout')
225
+ ? chunk
226
+ : `${output.stream ? '\n' : ''}[${stream}]\n${chunk}`;
227
+ const bounded = (0, utf8_1.truncateToBytes)(section, this.options.maxOutputBytes - output.bytes);
228
+ output.text += bounded.text;
229
+ output.bytes += bounded.bytes;
230
+ output.truncated = bounded.text.length < section.length;
231
+ output.stream = stream;
232
+ this.notify?.();
233
+ }
234
+ async terminate() {
235
+ const { child } = this;
236
+ const signalled = (0, command_process_1.signalCommandProcess)(child, 'SIGTERM');
237
+ const escalation = signalled
238
+ ? setTimeout(() => {
239
+ (0, command_process_1.signalCommandProcess)(child, 'SIGKILL');
240
+ // A descendant that deliberately changes process groups can still hold a pipe open.
241
+ child.stdin.destroy();
242
+ child.stdout.destroy();
243
+ child.stderr.destroy();
244
+ }, KILL_GRACE_MS)
245
+ : undefined;
246
+ // Keep a guard for descendants with redirected pipes, which can outlive the shell.
247
+ await this.closed;
248
+ if (escalation) {
249
+ clearTimeout(escalation);
250
+ if (process.platform !== 'win32')
251
+ (0, command_process_1.signalCommandProcess)(child, 'SIGKILL');
252
+ }
253
+ }
254
+ }
255
+ function failure(error) {
256
+ return { success: false, output: '', error };
257
+ }
258
+ //# sourceMappingURL=shell-process-sessions.js.map
@@ -140,7 +140,9 @@ class ExecutionService {
140
140
  try {
141
141
  const execute = () => request.snapshot.toolRouter.executeBound(EXECUTION_SERVICE_TOKEN, request.toolName, structuredClone(request.args), { ...request.context, abortSignal: timeoutController.signal });
142
142
  const descriptor = request.snapshot.toolRouter.resolveDescriptor(request.toolName);
143
- const result = descriptor?.risk.effect === 'workspace_write' && this.workspaceMutations
143
+ const workspaceWrite = descriptor?.risk.effect === 'workspace_write' &&
144
+ (descriptor.name !== 'process_session' || request.args.action === 'write');
145
+ const result = workspaceWrite && this.workspaceMutations
144
146
  ? await this.workspaceMutations.runWorkspaceMutation({
145
147
  workspaceId: request.snapshot.authority.projectRoot,
146
148
  invocationId: request.invocationId,
@@ -156,6 +158,7 @@ class ExecutionService {
156
158
  ? 'completed'
157
159
  : 'failed';
158
160
  const command = descriptor?.executorId === 'builtin:exec_command:v1' &&
161
+ request.args.interactive !== true &&
159
162
  typeof request.args.command === 'string'
160
163
  ? request.args.command
161
164
  : undefined;
@@ -15,7 +15,7 @@ export declare const READ_ONLY_INVESTIGATION_TOOLS: readonly ["read_file", "list
15
15
  * supervisor can assert that a filtered tool list contains none of these,
16
16
  * even if future tools are added upstream.
17
17
  */
18
- export declare const SUBAGENT_FORBIDDEN_TOOLS: readonly ["exec_command", "edit_file", "write_file", "memory_save", "memory_recall", "memory_forget", "orion-code", "subtask", "mcp_call", "mcp_list", "history_search"];
18
+ export declare const SUBAGENT_FORBIDDEN_TOOLS: readonly ["exec_command", "process_session", "edit_file", "write_file", "memory_save", "memory_recall", "memory_forget", "orion-code", "subtask", "mcp_call", "mcp_list", "history_search"];
19
19
  export interface RolePreset {
20
20
  role: SubagentRole;
21
21
  /** Tool names the child may use. */
@@ -32,6 +32,7 @@ exports.READ_ONLY_INVESTIGATION_TOOLS = [
32
32
  */
33
33
  exports.SUBAGENT_FORBIDDEN_TOOLS = [
34
34
  'exec_command',
35
+ 'process_session',
35
36
  'edit_file',
36
37
  'write_file',
37
38
  'memory_save',
@@ -23,6 +23,9 @@ function createTaskRecoveryBinder(taskContext, previousCommitDigest, progressAtA
23
23
  const { descriptor, name, args, cwd, activeTodoId } = input;
24
24
  if (descriptor?.executorId !== `builtin:${name}:v1`)
25
25
  return undefined;
26
+ if (name === 'process_session' || (name === 'exec_command' && args.interactive === true)) {
27
+ return undefined;
28
+ }
26
29
  if (!activeTodoId &&
27
30
  !['write_file', 'edit_file', 'read_file', 'todo_write', 'exec_command'].includes(name)) {
28
31
  return undefined;
@@ -84,6 +87,7 @@ function projectTaskToolEvidence(receipt, args, cwd) {
84
87
  ? (0, verification_1.workspaceArtifactPath)(cwd, reportedWritePath)
85
88
  : undefined;
86
89
  const command = receipt.toolName === 'exec_command' &&
90
+ args.interactive !== true &&
87
91
  (receipt.terminal === 'completed' ||
88
92
  (receipt.terminal === 'failed' && (0, verification_command_1.hasNonzeroShellExitCode)(receipt.result.metadata))) &&
89
93
  receipt.verificationWorkspace !== null &&
@@ -105,6 +109,9 @@ function projectTaskToolEvidence(receipt, args, cwd) {
105
109
  return { changedFile, verification };
106
110
  }
107
111
  function recordTaskTodoToolReceipt(taskContext, todo, receipt, { changedFile, verification }) {
112
+ if (receipt.toolName === 'process_session' ||
113
+ (receipt.toolName === 'exec_command' && receipt.result.metadata?.processId !== undefined))
114
+ return;
108
115
  if (receipt.verificationWorkspace !== undefined) {
109
116
  taskContext.observeVerificationWorkspace(receipt.verificationWorkspace);
110
117
  }
@@ -146,6 +146,9 @@ export declare class ThreadEventStore {
146
146
  * receipt is missing, stale, or lacks their required cutover proof.
147
147
  */
148
148
  capturePersistedCheckpointHead(): ThreadCheckpointHeadV1 | undefined;
149
+ /** A best-effort read for previews that must never wait for the writer lock. */
150
+ peekPersistedCheckpointHead(maxBytes: number): ThreadCheckpointHeadV1 | undefined;
151
+ private readPersistedCheckpointHead;
149
152
  /** Capture the catalog read model and its exact verified log identity atomically. */
150
153
  captureReadModelHead(): ThreadReadModelHeadV1;
151
154
  loadProjection(): ThreadProjectionV1;
@@ -6,6 +6,7 @@ const fs_1 = require("fs");
6
6
  const path_1 = require("path");
7
7
  const atomic_write_1 = require("../services/atomic-write");
8
8
  const file_lock_1 = require("../services/file-lock");
9
+ const bounded_file_1 = require("../utils/bounded-file");
9
10
  const canonical_1 = require("./protocol/canonical");
10
11
  const runtime_protocol_v1_1 = require("./protocol/runtime-protocol-v1");
11
12
  const thread_projection_1 = require("./thread-projection");
@@ -279,26 +280,33 @@ class ThreadEventStore {
279
280
  * receipt is missing, stale, or lacks their required cutover proof.
280
281
  */
281
282
  capturePersistedCheckpointHead() {
282
- return this.withLogLock(() => {
283
- const identity = readFileIdentity(this.logPath);
284
- const cached = this.cachedHead;
285
- if (cached?.logFingerprint === identity.fingerprint) {
286
- return checkpointHead(cached);
287
- }
288
- const stored = readStoredThreadHead(this.headPath, this.threadId);
289
- if (!stored ||
290
- !sameStoredLogIdentity(stored.log, identity) ||
291
- stored.safeByteLength + stored.discardedTailBytes !== identity.bytes) {
292
- return undefined;
293
- }
294
- return deepFreeze({
295
- cursor: stored.cursor,
296
- projectionDigest: stored.projectionDigest,
297
- lastEventTimestamp: stored.lastEventTimestamp,
298
- lastRecordHash: stored.lastRecordHash,
299
- log: { ...stored.log },
300
- verifiedPrefixes: stored.verifiedPrefixes.map(prefix => ({ ...prefix })),
301
- });
283
+ return this.withLogLock(() => this.readPersistedCheckpointHead());
284
+ }
285
+ /** A best-effort read for previews that must never wait for the writer lock. */
286
+ peekPersistedCheckpointHead(maxBytes) {
287
+ return this.readPersistedCheckpointHead(maxBytes);
288
+ }
289
+ readPersistedCheckpointHead(maxBytes) {
290
+ const identity = readFileIdentity(this.logPath);
291
+ const cached = this.cachedHead;
292
+ if (cached?.logFingerprint === identity.fingerprint) {
293
+ return checkpointHead(cached);
294
+ }
295
+ const stored = readStoredThreadHead(this.headPath, this.threadId, maxBytes);
296
+ if (!stored ||
297
+ !sameStoredLogIdentity(stored.log, identity) ||
298
+ stored.safeByteLength + stored.discardedTailBytes !== identity.bytes ||
299
+ (maxBytes !== undefined &&
300
+ readFileIdentity(this.logPath).fingerprint !== identity.fingerprint)) {
301
+ return undefined;
302
+ }
303
+ return deepFreeze({
304
+ cursor: stored.cursor,
305
+ projectionDigest: stored.projectionDigest,
306
+ lastEventTimestamp: stored.lastEventTimestamp,
307
+ lastRecordHash: stored.lastRecordHash,
308
+ log: { ...stored.log },
309
+ verifiedPrefixes: stored.verifiedPrefixes.map(prefix => ({ ...prefix })),
302
310
  });
303
311
  }
304
312
  /** Capture the catalog read model and its exact verified log identity atomically. */
@@ -778,11 +786,16 @@ function projectionFileMatches(path, expected) {
778
786
  projection.digest === expected.digest &&
779
787
  (0, thread_projection_1.verifyThreadProjectionDigest)(projection));
780
788
  }
781
- function readStoredThreadHead(path, threadId) {
789
+ function readStoredThreadHead(path, threadId, maxBytes) {
782
790
  if (!(0, fs_1.existsSync)(path))
783
791
  return null;
784
792
  try {
785
- const value = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
793
+ const contentText = maxBytes === undefined
794
+ ? (0, fs_1.readFileSync)(path, 'utf8')
795
+ : (0, bounded_file_1.readBoundedRegularFileSync)(path, maxBytes)?.toString('utf8');
796
+ if (contentText === undefined)
797
+ return null;
798
+ const value = JSON.parse(contentText);
786
799
  if (!isRecord(value))
787
800
  return null;
788
801
  const { digest: _digest, ...content } = value;
@@ -21,12 +21,23 @@ export interface ThreadSessionTranscriptMessageV1 {
21
21
  readonly appliedSkills?: readonly string[];
22
22
  }
23
23
  export declare const RESUME_TRANSCRIPT_WINDOW_MESSAGES = 50;
24
+ /** Process-local history reader bound to the verified snapshot captured at resume. */
25
+ export interface ThreadTranscriptHistorySource {
26
+ readonly before: number;
27
+ readonly recentEntries: readonly TranscriptEntry[];
28
+ readonly latestCompletedReply?: string;
29
+ readBefore(cursor: number): {
30
+ readonly entries: readonly TranscriptEntry[];
31
+ readonly before: number;
32
+ };
33
+ }
24
34
  export interface ThreadResumeDisplayV1 {
25
35
  readonly entries: readonly TranscriptEntry[];
26
36
  readonly totalEntries: number;
37
+ readonly historySource?: ThreadTranscriptHistorySource;
27
38
  }
28
- /** UI-only window. These entries must never be used for model history recovery. */
29
- export declare function projectThreadResumeDisplay(items: Readonly<Record<string, ItemProjectionV1>>): ThreadResumeDisplayV1;
39
+ /** UI-only window and lazy history pages. Model recovery uses its own durable history. */
40
+ export declare function projectThreadResumeDisplay(items: Readonly<Record<string, ItemProjectionV1>>, events?: readonly RuntimeEventEnvelopeV1[]): ThreadResumeDisplayV1;
30
41
  export interface ThreadSessionTurnCommitV1 {
31
42
  readonly seq: number;
32
43
  readonly receipt: string;
@@ -95,13 +106,14 @@ export declare function advanceThreadSessionIndexV1(input: {
95
106
  readonly projection: ThreadProjectionV1;
96
107
  readonly committedEvents: readonly RuntimeEventEnvelopeV1[];
97
108
  }): boolean;
98
- export declare function loadThreadSessionIndexManifestV1(rootDir: string, threadId: string, head: ThreadSessionIndexHeadV1): ThreadSessionIndexManifestV1 | undefined;
109
+ export declare function loadThreadSessionIndexManifestV1(rootDir: string, threadId: string, head: ThreadSessionIndexHeadV1, maxFileBytes?: number): ThreadSessionIndexManifestV1 | undefined;
99
110
  export declare function loadThreadSessionIndexedPageV1(input: {
100
111
  readonly rootDir: string;
101
112
  readonly threadId: string;
102
113
  readonly head: ThreadSessionIndexHeadV1;
103
114
  readonly cursor?: string;
104
115
  readonly pageSize?: number;
116
+ readonly maxFileBytes?: number;
105
117
  }): ThreadSessionIndexedPageV1 | undefined;
106
118
  export declare function projectTranscriptMessages(items: Readonly<Record<string, ItemProjectionV1>>, events: readonly RuntimeEventEnvelopeV1[]): readonly ThreadSessionTranscriptMessageV1[];
107
119
  export {};