@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
package/CHANGELOG.md CHANGED
@@ -22,6 +22,19 @@ which is **not** a pass.
22
22
 
23
23
  ## [Unreleased]
24
24
 
25
+ ## [0.5.0] — UNRELEASED
26
+
27
+ - Add a desktop VS Code extension with ACP conversations, tool activity, model setup, and session resume.
28
+ - Advertise interactive model setup to ACP clients and prepare the official ACP Registry entry for Orion Code.
29
+
30
+ ## [0.4.9] — UNRELEASED
31
+
32
+ - Rebuild TUI history from retained conversation records across terminal resizes. Keep the full-width composer, tool activity, and live Thinking on an app-owned screen while preserving shell scrollback.
33
+ - Use Ctrl+T for conversation history with reasoning summaries and tool output. Ctrl+O copies the latest completed reply as Markdown. Exit appends the completed conversation tail to the shell scrollback.
34
+ - Use a compact TUI composer with its suggestions and status below the draft. A single activity row shows the current work and interrupt shortcut while a turn is running.
35
+ - Let an agent write to, poll, or cancel the same shell process within a turn and report its actual exit independently of interactive tool receipts (#410).
36
+ - Let Print validate the final reply against a JSON Schema and atomically save it with `--output-last-message` or `-o` (#411).
37
+
25
38
  ## [0.4.8] — UNRELEASED
26
39
 
27
40
  - Report the shell exit status separately from verification. Recognizable checks in pipelines show why the result is unverified and suggest a direct, bounded command for simple output filters (#408).
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Local-first, goal-driven coding agent for the terminal (CLI/TUI).
4
4
 
5
- > v0.4.8 is a candidate for model-driven turn completion and clearer command verification.
5
+ > v0.5.0 adds editor integrations for Zed and VS Code through ACP. See the [editor release plan](https://github.com/orion-agents/orion-code/blob/main/docs/plan/v0.5.0-plan.md) for listing and verification status.
6
6
  > Orion uses `orion.yaml` and can resume sessions created by v0.4.7.
7
7
  > A version number or local installation is not proof of release qualification or npm publication.
8
8
 
@@ -29,15 +29,15 @@ The exact package qualification floors are 22.12.0 / 24.0.0 / 26.0.0.
29
29
  Install the exact candidate tarball from the path where it was built.
30
30
 
31
31
  ```bash
32
- npm install -g /absolute/path/orion-agents-orion-code-0.4.8.tgz
32
+ npm install -g /absolute/path/orion-agents-orion-code-0.5.0.tgz
33
33
  orion --version
34
34
  orion doctor
35
35
  ```
36
36
 
37
- Use the following command once version 0.4.8 is available on npm.
37
+ Use the following command once version 0.5.0 is available on npm.
38
38
 
39
39
  ```bash
40
- npm install -g @orion-agents/orion-code@0.4.8
40
+ npm install -g @orion-agents/orion-code@0.5.0
41
41
  ```
42
42
 
43
43
  From a source checkout:
@@ -107,7 +107,7 @@ npm run format:check
107
107
  npm run build
108
108
  npm run test:coverage -- --runInBand
109
109
  npm run test:harness-confluence
110
- npm run release:check -- --expected-version 0.4.8
110
+ npm run release:check -- --expected-version 0.5.0
111
111
  ```
112
112
 
113
113
  Qualification binds one exact tarball's SHA-256 and source identity to installed CLI, TUI, terminal,
package/README.zh-CN.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  面向终端、本地优先的目标驱动 Coding Agent(CLI/TUI)。
4
4
 
5
- > v0.4.8 候选版让模型决定回合结束,并单独报告命令验证结果。
5
+ > v0.5.0 通过 ACP 接入 Zed 和 VS Code。上架及验收进度见[编辑器发布计划](https://github.com/orion-agents/orion-code/blob/main/docs/plan/v0.5.0-plan.md)。
6
6
  > 全局配置使用 `orion.yaml`,可恢复 v0.4.7 创建的会话。
7
7
  > 源码版本号、本地可运行、候选包验收与 npm 发布分别记录,不互相替代。
8
8
 
@@ -28,15 +28,15 @@
28
28
  用构建产出的候选包安装,请替换为实际路径。
29
29
 
30
30
  ```bash
31
- npm install -g /absolute/path/orion-agents-orion-code-0.4.8.tgz
31
+ npm install -g /absolute/path/orion-agents-orion-code-0.5.0.tgz
32
32
  orion --version
33
33
  orion doctor
34
34
  ```
35
35
 
36
- 确认 npm 已有 0.4.8 后,可按固定版本安装。
36
+ 确认 npm 已有 0.5.0 后,可按固定版本安装。
37
37
 
38
38
  ```bash
39
- npm install -g @orion-agents/orion-code@0.4.8
39
+ npm install -g @orion-agents/orion-code@0.5.0
40
40
  ```
41
41
 
42
42
  从源码运行:
@@ -104,7 +104,7 @@ npm run format:check
104
104
  npm run build
105
105
  npm run test:coverage -- --runInBand
106
106
  npm run test:harness-confluence
107
- npm run release:check -- --expected-version 0.4.8
107
+ npm run release:check -- --expected-version 0.5.0
108
108
  ```
109
109
 
110
110
  准出需绑定同一 tarball 的 SHA-256 与源码身份,在三个 Node floor 验证安装后的 CLI、TUI、
@@ -273,7 +273,7 @@ class AcpSessions {
273
273
  onActiveSessionRuntime: active => active.thread.observeCommittedEvents(events => session?.observe(events)),
274
274
  });
275
275
  if (!runtime.isConfigured || !runtime.createAgentRunner) {
276
- throw sdk_1.RequestError.authRequired(undefined, `Configure a model in ${identity_1.CONFIG_FILE_NAME}`);
276
+ throw sdk_1.RequestError.authRequired(undefined, `Run orion init to configure a model, or check the API key environment variable in ${identity_1.CONFIG_FILE_NAME}`);
277
277
  }
278
278
  if (signal.aborted || this.closing)
279
279
  throw sdk_1.RequestError.requestCancelled();
package/dist/acp/stdio.js CHANGED
@@ -6,6 +6,21 @@ const node_stream_1 = require("node:stream");
6
6
  const identity_1 = require("../product/identity");
7
7
  const version_1 = require("../product/version");
8
8
  const sessions_1 = require("./sessions");
9
+ function authMethods(capabilities) {
10
+ // The ACP Registry validator still opts in through the original capability key.
11
+ const terminal = capabilities?.auth?.terminal === true || capabilities?._meta?.['terminal-auth'] === true;
12
+ return terminal
13
+ ? [
14
+ {
15
+ id: 'orion-init',
16
+ name: 'Set up Orion Code',
17
+ description: 'Configure a model and its API key environment variable in a terminal.',
18
+ type: 'terminal',
19
+ args: ['init'],
20
+ },
21
+ ]
22
+ : [];
23
+ }
9
24
  /** Own stdout for ACP frames for the lifetime of this CLI subcommand. */
10
25
  async function runAcpStdio() {
11
26
  const stdout = process.stdout;
@@ -17,11 +32,11 @@ async function runAcpStdio() {
17
32
  const sessions = new sessions_1.AcpSessions();
18
33
  try {
19
34
  const app = (0, sdk_1.agent)()
20
- .onRequest('initialize', () => ({
35
+ .onRequest('initialize', ({ params }) => ({
21
36
  protocolVersion: sdk_1.PROTOCOL_VERSION,
22
37
  agentInfo: { name: identity_1.PRODUCT_ID, title: identity_1.DISPLAY_NAME, version: version_1.PACKAGE_VERSION },
23
38
  agentCapabilities: { loadSession: true },
24
- authMethods: [],
39
+ authMethods: authMethods(params.clientCapabilities),
25
40
  }))
26
41
  .onRequest('session/new', async ({ params, client, signal }) => {
27
42
  const session = await sessions.open(params, client, signal);
package/dist/cli.js CHANGED
@@ -76,6 +76,8 @@ function showCliHelp() {
76
76
  console.log(' --output-format <text|json|jsonl> Print-mode output format');
77
77
  console.log(' --strict-exit Use the JSONL exit-code contract with text or JSON');
78
78
  console.log(' --resume <session-id> Load a saved session before the print prompt');
79
+ console.log(' --output-schema <file> Validate the final Print reply against a JSON Schema');
80
+ console.log(' -o, --output-last-message <file> Write the final Print reply to a file');
79
81
  console.log();
80
82
  console.log(DIM('tui is the default product UI. terminal is the technical fallback.'));
81
83
  console.log();
@@ -86,6 +88,9 @@ function parseCliOptions(args) {
86
88
  let outputFormat = 'text';
87
89
  let strictExit = false;
88
90
  let resumeSessionId;
91
+ let outputSchemaPath;
92
+ let lastMessagePath;
93
+ let outputOptionError;
89
94
  const promptArgs = [];
90
95
  for (let i = 0; i < args.length; i++) {
91
96
  const arg = args[i];
@@ -105,6 +110,22 @@ function parseCliOptions(args) {
105
110
  resumeSessionId = arg === '--resume' ? (args[++i] ?? '') : arg.slice('--resume='.length);
106
111
  continue;
107
112
  }
113
+ const equals = arg.indexOf('=');
114
+ const flag = equals === -1 ? arg : arg.slice(0, equals);
115
+ if (flag === '--output-schema' || flag === '--output-last-message' || flag === '-o') {
116
+ const next = args[i + 1];
117
+ const path = equals >= 0 ? arg.slice(equals + 1) : next && !next.startsWith('-') ? args[++i] : '';
118
+ if (!path.trim()) {
119
+ outputOptionError ?? (outputOptionError = `Specify a file path for ${flag}.`);
120
+ }
121
+ else if (flag === '--output-schema') {
122
+ outputSchemaPath = path;
123
+ }
124
+ else {
125
+ lastMessagePath = path;
126
+ }
127
+ continue;
128
+ }
108
129
  const uiValue = arg === '--ui'
109
130
  ? (args[i + 1] ?? '')
110
131
  : arg.startsWith('--ui=')
@@ -142,7 +163,17 @@ function parseCliOptions(args) {
142
163
  }
143
164
  promptArgs.push(arg);
144
165
  }
145
- return { uiRenderer, printMode, outputFormat, strictExit, resumeSessionId, promptArgs };
166
+ return {
167
+ uiRenderer,
168
+ printMode,
169
+ outputFormat,
170
+ strictExit,
171
+ resumeSessionId,
172
+ outputSchemaPath,
173
+ lastMessagePath,
174
+ outputOptionError,
175
+ promptArgs,
176
+ };
146
177
  }
147
178
  async function bootstrapRuntime(uiRenderer) {
148
179
  const { createProductUiRuntime } = await Promise.resolve().then(() => __importStar(require('./runtime/product-bootstrap')));
@@ -173,11 +204,13 @@ async function main() {
173
204
  }
174
205
  return;
175
206
  }
176
- if (args.includes('--help') || args.includes('-h')) {
207
+ const separator = args.indexOf('--');
208
+ const optionArgs = separator === -1 ? args : args.slice(0, separator);
209
+ if (optionArgs.includes('--help') || optionArgs.includes('-h')) {
177
210
  showCliHelp();
178
211
  process.exit(0);
179
212
  }
180
- if (args.includes('--version') || args.includes('-v')) {
213
+ if (optionArgs.includes('--version') || optionArgs.includes('-v')) {
181
214
  console.log(`orion v${VERSION}`);
182
215
  process.exit(0);
183
216
  }
@@ -186,13 +219,21 @@ async function main() {
186
219
  await runAcpStdio();
187
220
  return;
188
221
  }
189
- if (args[0] === 'init' && args.length === 1) {
222
+ // ACP clients append the Terminal Auth arguments to the usual agent launch command.
223
+ if ((args[0] === 'init' && args.length === 1) ||
224
+ (args[0] === 'acp' && args[1] === 'init' && args.length === 2)) {
190
225
  const { runInitCommand } = await Promise.resolve().then(() => __importStar(require('./commands/init-command')));
191
226
  process.exitCode = await runInitCommand();
192
227
  return;
193
228
  }
194
229
  const options = parseCliOptions(args);
195
230
  const command = options.printMode ? undefined : options.promptArgs[0];
231
+ if (!options.printMode &&
232
+ (options.outputSchemaPath || options.lastMessagePath || options.outputOptionError)) {
233
+ console.error(ERROR('Final output options require --print.'));
234
+ process.exitCode = 1;
235
+ return;
236
+ }
196
237
  if (!options.printMode &&
197
238
  (options.outputFormat === 'jsonl' ||
198
239
  options.strictExit ||
@@ -51,11 +51,11 @@ function createResumeTranscriptWindow(sessionId, messages, totalEntries = messag
51
51
  contentTruncated || (contentTruncated = projected.truncated);
52
52
  const display = 'id' in message ? message : undefined;
53
53
  const entry = {
54
- id: `resume:${sessionId}:${index + 1}`,
54
+ ...display,
55
+ id: display?.id ?? `resume:${sessionId}:${index + 1}`,
55
56
  role: message.role,
56
57
  content: projected.value,
57
58
  title: display?.title ?? (message.role === 'user' ? 'you' : undefined),
58
- ...(display?.toolActivity ? { toolActivity: display.toolActivity } : {}),
59
59
  };
60
60
  entries.unshift(entry);
61
61
  bytes += Buffer.byteLength(projected.value, 'utf8') + RESUME_TRANSCRIPT_ENTRY_OVERHEAD_BYTES;
@@ -357,7 +357,7 @@ async function handleResume(ctx, args) {
357
357
  error: 'No previous session found for this project. Use /session list --all to list all sessions.',
358
358
  };
359
359
  }
360
- if (scope.last || scopedSessions.length === 1) {
360
+ if (scope.last || (scopedSessions.length === 1 && ctx.uiRenderer !== 'tui')) {
361
361
  return restoreSession(ctx, lastSession, true);
362
362
  }
363
363
  const picker = {
@@ -462,6 +462,11 @@ async function restoreSession(ctx, session, isLast) {
462
462
  const resumed = (0, session_storage_1.resumeSession)(selected.id) ?? selected;
463
463
  Object.assign(selected, resumed);
464
464
  ctx.replaceTranscript?.(transcriptWindow.entries);
465
+ if (ctx.onRestoreTranscriptHistory) {
466
+ const source = restoredView.resumeDisplay?.historySource;
467
+ const before = transcriptDisplayCount - transcriptWindow.entries.length;
468
+ ctx.onRestoreTranscriptHistory(source && before !== source.before ? { ...source, before } : source);
469
+ }
465
470
  if (history.length > 0) {
466
471
  const eventSummary = checkpoint?.summary.text ?? generateRestoredSessionEventSummary(history);
467
472
  ctx.sessionRestored?.({
@@ -63,7 +63,7 @@ function createSystemCommands(getVisibleCommands) {
63
63
  rendererScope: ['tui'],
64
64
  execute: () => ({
65
65
  success: true,
66
- output: 'Enter send/steer · Tab queue while working · Esc stop · Ctrl+R history · Ctrl+E editor · Ctrl+O tools · Ctrl+L redraw · Ctrl+D exit',
66
+ output: 'Enter send/steer · Tab queue while working · Esc stop · Ctrl+R history · Ctrl+E editor · Ctrl+T transcript · Ctrl+O copy reply · Ctrl+L redraw · Ctrl+D exit',
67
67
  }),
68
68
  },
69
69
  {
@@ -90,8 +90,8 @@ function createSystemCommands(getVisibleCommands) {
90
90
  },
91
91
  {
92
92
  name: 'queue',
93
- description: 'Show or clear queued follow-up messages',
94
- argumentHint: '[clear]',
93
+ description: 'Edit, reorder, or remove queued follow-up messages',
94
+ argumentHint: '[resume|clear]',
95
95
  category: 'system',
96
96
  priority: 34,
97
97
  type: 'builtin',
@@ -13,6 +13,7 @@ import type { ModelCoordinator } from '../runtime/model-coordinator';
13
13
  import type { SessionComposerControlServiceV1 } from '../runtime/session-composer-control';
14
14
  import type { SessionGoalV1 } from '../runtime/goals/types';
15
15
  import type { OrionRuntimeDiagnosticsV1 } from '../runtime/orion-runtime-v1';
16
+ import type { ThreadTranscriptHistorySource } from '../runtime/thread-session-index';
16
17
  import type { ThreadSessionRuntimeActivationV1 } from '../runtime/thread-session-view';
17
18
  import type { EditPreviewRequest, ModelPickerRequest, RuntimeSessionRestoredEvent, RuntimeSettingsMutationV1, SessionPickerRequest, TranscriptEntry, UiRendererCapabilities } from '../runtime/ui-events';
18
19
  import type { SettingsCoordinatorV1, SettingsDocumentViewV1, SettingsUpdateResultV1 } from '../services/settings-coordinator';
@@ -44,6 +45,8 @@ export interface CommandContext {
44
45
  sessionRestored?: (event: RuntimeSessionRestoredEvent) => void;
45
46
  /** Replace only the renderer's bounded transcript window; model context remains authoritative. */
46
47
  replaceTranscript?: (entries: readonly TranscriptEntry[]) => void;
48
+ /** Attach a TUI history reader after the foreground transcript has been replaced. */
49
+ onRestoreTranscriptHistory?: (source: ThreadTranscriptHistorySource | undefined) => void;
47
50
  /** Return the active session if one exists. */
48
51
  getSession?: () => SessionMeta | null;
49
52
  /** Current durable Goal state for compact checkpoint binding. */
@@ -19,7 +19,9 @@ class LoopProgress {
19
19
  }
20
20
  observe(observation) {
21
21
  const { name, args, output, fileEdit, assertion } = observation;
22
- if (name === 'todo_write')
22
+ if (name === 'todo_write' ||
23
+ name === 'process_session' ||
24
+ (name === 'exec_command' && args.interactive === true))
23
25
  return;
24
26
  const verified = assertion?.status === 'passed' ? assertion : undefined;
25
27
  const command = typeof args.command === 'string' ? args.command.trim() : '';
@@ -8,7 +8,7 @@
8
8
  * not yielded as events (callbacks cannot yield). The handleChat consumer writes
9
9
  * chunks directly to stdout via the callback.
10
10
  */
11
- import type { LLMRequestDiagnostics, LLMService, Message, StreamCallbacks } from '../services/llm';
11
+ import type { LLMRequestDiagnostics, LLMService, Message, StreamCallbacks, StructuredOutputSchema } from '../services/llm';
12
12
  import type { ProviderErrorType } from '../services/provider-diagnostics';
13
13
  import type { OrionCodeTool, ToolContext } from './tool';
14
14
  import type { CostTracker } from '../core/cost-tracker';
@@ -222,6 +222,8 @@ export interface QueryParams {
222
222
  resolveStep?: (input: QueryStepResolveInput) => QueryStepRuntime | Promise<QueryStepRuntime>;
223
223
  /** LLM service instance */
224
224
  llm: LLMService;
225
+ /** Request-local format of the final model reply for Print. */
226
+ outputSchema?: StructuredOutputSchema;
225
227
  /** Abort signal for cancellation */
226
228
  abortSignal?: AbortSignal;
227
229
  /** Streaming callbacks (onChunk writes to stdout, etc.) */
@@ -603,9 +603,11 @@ function summarizeModelVisibleToolResult(executed, maxBytes, budgetRemainingByte
603
603
  }
604
604
  // Keep a real excerpt, status and a budget signal even after exhaustion. An
605
605
  // untrusted tool's arbitrarily large metadata must not displace the excerpt.
606
- const shellMetadata = executed.prepared.tc.function.name === 'exec_command' ? envelope.metadata : undefined;
606
+ const toolName = executed.prepared.tc.function.name;
607
+ const shellMetadata = toolName === 'exec_command' || toolName === 'process_session' ? envelope.metadata : undefined;
607
608
  const feedback = shellMetadata?.verification;
608
609
  const exitCode = shellMetadata?.exitCode;
610
+ const processMetadata = (0, tool_serializer_1.projectProcessMetadata)(shellMetadata);
609
611
  const verification = (0, verification_command_1.verificationToolStatus)(feedback);
610
612
  const detailedVerification = verification && byteLength(JSON.stringify(feedback)) <= 1024 ? feedback : verification;
611
613
  const compactError = rawError ? truncateModelField(rawError, 192) : undefined;
@@ -622,6 +624,7 @@ function summarizeModelVisibleToolResult(executed, maxBytes, budgetRemainingByte
622
624
  modelVisibleCompressed: true,
623
625
  originalResultBytes: rawBytes,
624
626
  ...budgetMetadata,
627
+ ...processMetadata,
625
628
  ...(verification
626
629
  ? { verification: includeDetails ? detailedVerification : verification }
627
630
  : {}),
@@ -911,7 +914,19 @@ async function* query(params) {
911
914
  name: tool.name,
912
915
  description: tool.description,
913
916
  }));
914
- const assembleRequest = () => harness?.assembleMessages(messages, { input, tools: compactToolDescriptions }) ?? messages;
917
+ const outputSchema = params.outputSchema;
918
+ const assembleRequest = () => {
919
+ const assembled = harness?.assembleMessages(messages, { input, tools: compactToolDescriptions }) ?? messages;
920
+ if (outputSchema === undefined)
921
+ return assembled;
922
+ const instruction = 'Return the final answer as one JSON value matching the following JSON Schema. ' +
923
+ 'Do not wrap the final JSON in Markdown or include prose with it. Use tools normally.\n' +
924
+ JSON.stringify(outputSchema);
925
+ const [system, ...rest] = assembled;
926
+ return system?.role === 'system'
927
+ ? [{ ...system, content: `${system.content}\n\n${instruction}` }, ...rest]
928
+ : [{ role: 'system', content: instruction }, ...assembled];
929
+ };
915
930
  let requestMessages = assembleRequest();
916
931
  let requestEstimatedTokens = (0, token_estimate_1.estimateMessagesTokens)(requestMessages);
917
932
  const predictedTokens = autoCompact.adjustTokenEstimate(requestEstimatedTokens, llm.getModel());
@@ -1047,7 +1062,7 @@ async function* query(params) {
1047
1062
  sawReasoning || (sawReasoning = text.trim().length > 0);
1048
1063
  streamCallbacks?.onThinkingText?.(text);
1049
1064
  },
1050
- }, openaiTools, { abortSignal });
1065
+ }, openaiTools, { abortSignal, ...(outputSchema === undefined ? {} : { outputSchema }) });
1051
1066
  applyLlmRequestDiagnostics(stats, getLlmRequestDiagnostics(llm));
1052
1067
  if (response.usage) {
1053
1068
  autoCompact.recordProviderUsage(requestEstimatedTokens, response.usage.promptTokens, response.model || llm.getModel());
@@ -6,6 +6,17 @@
6
6
  */
7
7
  import type { ToolResult } from '../framework/tool';
8
8
  export declare const TOOL_RESULT_SCHEMA_VERSION = 1;
9
+ declare const PROCESS_STATUSES: readonly ["running", "exited", "failed", "cancelled", "timed_out", "aborted"];
10
+ export interface ProcessToolMetadata {
11
+ processId: string;
12
+ processStatus: (typeof PROCESS_STATUSES)[number];
13
+ outputTruncated: boolean;
14
+ exitCode?: number;
15
+ signal?: string;
16
+ inputQueued?: true;
17
+ }
18
+ /** Keep only bounded lifecycle fields when projecting a first-party process receipt. */
19
+ export declare function projectProcessMetadata(metadata?: Record<string, unknown>): ProcessToolMetadata | undefined;
9
20
  /**
10
21
  * Serialize a ToolResult to a JSON string with schema version.
11
22
  */
@@ -18,4 +29,5 @@ export declare function serializeToolResult(result: ToolResult): string;
18
29
  export declare function parseToolResultEnvelope(raw: string): ToolResult & {
19
30
  schemaVersion?: number;
20
31
  };
32
+ export {};
21
33
  //# sourceMappingURL=tool-serializer.d.ts.map
@@ -7,10 +7,45 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.TOOL_RESULT_SCHEMA_VERSION = void 0;
10
+ exports.projectProcessMetadata = projectProcessMetadata;
10
11
  exports.serializeToolResult = serializeToolResult;
11
12
  exports.parseToolResultEnvelope = parseToolResultEnvelope;
12
13
  const external_assertion_1 = require("./external-assertion");
13
14
  exports.TOOL_RESULT_SCHEMA_VERSION = 1;
15
+ const PROCESS_STATUSES = [
16
+ 'running',
17
+ 'exited',
18
+ 'failed',
19
+ 'cancelled',
20
+ 'timed_out',
21
+ 'aborted',
22
+ ];
23
+ /** Keep only bounded lifecycle fields when projecting a first-party process receipt. */
24
+ function projectProcessMetadata(metadata) {
25
+ if (!metadata)
26
+ return undefined;
27
+ const { processId, processStatus, outputTruncated, exitCode, signal, inputQueued } = metadata;
28
+ if (typeof processId !== 'string' ||
29
+ !/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/u.test(processId) ||
30
+ !PROCESS_STATUSES.includes(processStatus))
31
+ return undefined;
32
+ return {
33
+ processId,
34
+ processStatus: processStatus,
35
+ outputTruncated: outputTruncated === true,
36
+ ...(processStatus !== 'running' &&
37
+ typeof exitCode === 'number' &&
38
+ Number.isSafeInteger(exitCode)
39
+ ? { exitCode }
40
+ : {}),
41
+ ...(processStatus !== 'running' &&
42
+ typeof signal === 'string' &&
43
+ /^SIG[A-Z0-9]{1,12}$/u.test(signal)
44
+ ? { signal }
45
+ : {}),
46
+ ...(inputQueued === true ? { inputQueued } : {}),
47
+ };
48
+ }
14
49
  /**
15
50
  * Serialize a ToolResult to a JSON string with schema version.
16
51
  */
@@ -50,6 +50,8 @@ export interface ToolContext {
50
50
  cwd: string;
51
51
  config: ToolConfig;
52
52
  abortSignal?: AbortSignal;
53
+ /** Pipe-backed command handles owned by the active runtime turn. */
54
+ shellProcesses?: import('../runtime/shell-process-sessions').TurnShellProcesses;
53
55
  /** Optional current session id for turn-level tool state tracking */
54
56
  sessionId?: string;
55
57
  /** Optional turn identifier for per-turn tool bookkeeping */
@@ -131,7 +131,8 @@ class ContextLedger {
131
131
  const cwd = receipt?.cwd ?? cwdFromArgs(params.args);
132
132
  // Use summary when available to reduce evidence size
133
133
  const output = params.summary || parsed.error || params.error || parsed.output || params.result;
134
- const shell = params.name === 'exec_command' || params.name === 'bash';
134
+ const shell = (params.name === 'exec_command' || params.name === 'bash') &&
135
+ params.args.interactive !== true;
135
136
  // A production shell descriptor is conservatively write-capable. Its
136
137
  // individual invocation can still be a recognized read for task progress.
137
138
  const readOnly = params.readOnly === true || (shell && !!command && (0, bash_security_1.isReadOnlyCommand)(command));
@@ -0,0 +1,15 @@
1
+ import type { StructuredOutputSchema } from '../services/llm';
2
+ export declare class PrintDeliveryError extends Error {
3
+ readonly reasonCode: 'invalid_output_schema' | 'missing_final_output' | 'invalid_final_json' | 'output_schema_mismatch' | 'output_write_failed';
4
+ constructor(reasonCode: 'invalid_output_schema' | 'missing_final_output' | 'invalid_final_json' | 'output_schema_mismatch' | 'output_write_failed', message: string);
5
+ }
6
+ export interface PrintDelivery {
7
+ readonly schema?: StructuredOutputSchema;
8
+ deliver(finalReply: string | undefined): void;
9
+ }
10
+ /** Load and compile the requested schema before any provider request. */
11
+ export declare function preparePrintDelivery(options: {
12
+ outputSchemaPath?: string;
13
+ lastMessagePath?: string;
14
+ }): Promise<PrintDelivery | undefined>;
15
+ //# sourceMappingURL=delivery.d.ts.map
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PrintDeliveryError = void 0;
37
+ exports.preparePrintDelivery = preparePrintDelivery;
38
+ const node_fs_1 = require("node:fs");
39
+ const node_path_1 = require("node:path");
40
+ const atomic_write_1 = require("../services/atomic-write");
41
+ class PrintDeliveryError extends Error {
42
+ constructor(reasonCode, message) {
43
+ super(message);
44
+ this.reasonCode = reasonCode;
45
+ this.name = 'PrintDeliveryError';
46
+ }
47
+ }
48
+ exports.PrintDeliveryError = PrintDeliveryError;
49
+ /** Load and compile the requested schema before any provider request. */
50
+ async function preparePrintDelivery(options) {
51
+ if (options.outputSchemaPath === undefined && options.lastMessagePath === undefined) {
52
+ return undefined;
53
+ }
54
+ const schema = options.outputSchemaPath && (await compileSchema(options.outputSchemaPath));
55
+ const outputFile = options.lastMessagePath && (0, node_path_1.resolve)(options.lastMessagePath);
56
+ return {
57
+ schema: schema ? schema.document : undefined,
58
+ deliver(finalReply) {
59
+ if (!finalReply?.trim()) {
60
+ throw new PrintDeliveryError('missing_final_output', 'The completed Print turn has no final model reply to deliver.');
61
+ }
62
+ if (schema)
63
+ validateFinalOutput(finalReply, schema.validate);
64
+ if (!outputFile)
65
+ return;
66
+ try {
67
+ const content = finalReply.endsWith('\n') ? finalReply : `${finalReply}\n`;
68
+ (0, atomic_write_1.atomicWriteFileSync)(outputFile, content, { mode: 0o600, fsync: true });
69
+ }
70
+ catch (error) {
71
+ throw new PrintDeliveryError('output_write_failed', `Cannot write the final Print reply. ${errorMessage(error)}`);
72
+ }
73
+ },
74
+ };
75
+ }
76
+ async function compileSchema(path) {
77
+ try {
78
+ if (!(0, node_fs_1.statSync)(path).isFile())
79
+ throw new Error('Expected a regular JSON Schema file.');
80
+ const document = JSON.parse((0, node_fs_1.readFileSync)(path, 'utf8'));
81
+ if (typeof document !== 'boolean' &&
82
+ (document === null || typeof document !== 'object' || Array.isArray(document))) {
83
+ throw new Error('A JSON Schema must be an object or boolean.');
84
+ }
85
+ const schema = document;
86
+ const dialect = typeof schema === 'object' ? schema.$schema : undefined;
87
+ const draft2020 = typeof dialect === 'string' &&
88
+ /^https:\/\/json-schema\.org\/draft\/2020-12\/schema#?$/u.test(dialect);
89
+ const [{ default: Ajv }, { default: addFormats }] = await Promise.all([
90
+ draft2020 ? Promise.resolve().then(() => __importStar(require('ajv/dist/2020'))) : Promise.resolve().then(() => __importStar(require('ajv'))),
91
+ Promise.resolve().then(() => __importStar(require('ajv-formats'))),
92
+ ]);
93
+ const compiler = new Ajv({
94
+ strictSchema: true,
95
+ strictTypes: false,
96
+ strictTuples: false,
97
+ ownProperties: true,
98
+ });
99
+ addFormats(compiler);
100
+ if (dialect === 'https://json-schema.org/draft-07/schema#' ||
101
+ dialect === 'https://json-schema.org/draft-07/schema') {
102
+ compiler.addSchema({ $ref: 'http://json-schema.org/draft-07/schema#' }, 'https://json-schema.org/draft-07/schema');
103
+ }
104
+ const validate = compiler.compile(schema);
105
+ if ('$async' in validate && validate.$async) {
106
+ throw new Error('Asynchronous JSON Schema extensions are unsupported.');
107
+ }
108
+ return { document: schema, validate };
109
+ }
110
+ catch (error) {
111
+ throw new PrintDeliveryError('invalid_output_schema', `Cannot load the Print output schema. ${errorMessage(error)}`);
112
+ }
113
+ }
114
+ function validateFinalOutput(reply, validate) {
115
+ let value;
116
+ try {
117
+ value = JSON.parse(reply);
118
+ }
119
+ catch {
120
+ throw new PrintDeliveryError('invalid_final_json', 'The final Print reply is not valid JSON.');
121
+ }
122
+ if (validate(value))
123
+ return;
124
+ const issue = validate.errors?.[0];
125
+ const detail = issue ? ` ${issue.instancePath || '/'} ${issue.message ?? 'is invalid'}.` : '';
126
+ throw new PrintDeliveryError('output_schema_mismatch', `The final Print reply does not match the JSON Schema.${detail}`);
127
+ }
128
+ function errorMessage(error) {
129
+ return error instanceof Error ? error.message : String(error);
130
+ }
131
+ //# sourceMappingURL=delivery.js.map