@orion-agents/orion-code 0.4.3 → 0.4.5

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 (105) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/dist/acp/session-updates.d.ts +4 -3
  5. package/dist/acp/session-updates.js +23 -2
  6. package/dist/acp/sessions.js +19 -6
  7. package/dist/commands/core-command-handlers.js +10 -22
  8. package/dist/commands/diagnostic-command-handlers.js +48 -52
  9. package/dist/commands/registry.js +1 -1
  10. package/dist/commands/target-command.js +49 -6
  11. package/dist/commands/workflow-commands.js +2 -2
  12. package/dist/core/tool-artifacts.js +17 -4
  13. package/dist/framework/loop-budget-contract.d.ts +1 -12
  14. package/dist/framework/loop-budget-contract.js +1 -7
  15. package/dist/framework/loop-progress.d.ts +3 -7
  16. package/dist/framework/loop-progress.js +7 -23
  17. package/dist/framework/query.d.ts +12 -24
  18. package/dist/framework/query.js +294 -301
  19. package/dist/framework/tool-state.d.ts +4 -0
  20. package/dist/harness/assembler.js +1 -1
  21. package/dist/harness/context-harness.d.ts +12 -2
  22. package/dist/harness/context-harness.js +288 -60
  23. package/dist/harness/contract.js +3 -1
  24. package/dist/harness/drift-guard.js +67 -17
  25. package/dist/harness/goal-verification.d.ts +11 -0
  26. package/dist/harness/goal-verification.js +62 -0
  27. package/dist/harness/index.d.ts +1 -1
  28. package/dist/harness/ledger.d.ts +1 -0
  29. package/dist/harness/ledger.js +28 -4
  30. package/dist/harness/progress-controller.js +57 -35
  31. package/dist/harness/state.js +4 -0
  32. package/dist/harness/stop-controller.d.ts +0 -5
  33. package/dist/harness/stop-controller.js +11 -31
  34. package/dist/harness/task-checklist.d.ts +12 -2
  35. package/dist/harness/task-checklist.js +50 -9
  36. package/dist/harness/types.d.ts +15 -0
  37. package/dist/harness/verification.d.ts +11 -1
  38. package/dist/harness/verification.js +47 -2
  39. package/dist/print-ui/event-stream.d.ts +5 -0
  40. package/dist/print-ui/event-stream.js +22 -5
  41. package/dist/runtime/agent-loop.d.ts +2 -1
  42. package/dist/runtime/agent-loop.js +23 -17
  43. package/dist/runtime/agent-runtime-controller.d.ts +1 -1
  44. package/dist/runtime/agent-runtime-controller.js +21 -11
  45. package/dist/runtime/batch-read-service.js +21 -4
  46. package/dist/runtime/goal-lifecycle-v2.d.ts +6 -4
  47. package/dist/runtime/goal-lifecycle-v2.js +164 -56
  48. package/dist/runtime/goal-runtime-coordinator.d.ts +6 -3
  49. package/dist/runtime/goal-runtime-coordinator.js +91 -36
  50. package/dist/runtime/goals/presentation.js +3 -1
  51. package/dist/runtime/goals/types.d.ts +1 -3
  52. package/dist/runtime/goals/types.js +0 -3
  53. package/dist/runtime/loop-budget.d.ts +0 -7
  54. package/dist/runtime/loop-budget.js +8 -54
  55. package/dist/runtime/orion-runtime-v1.js +55 -14
  56. package/dist/runtime/product-orion-runtime.js +30 -13
  57. package/dist/runtime/rsi/evaluation.js +1 -7
  58. package/dist/runtime/step-snapshot.d.ts +3 -1
  59. package/dist/runtime/step-snapshot.js +11 -1
  60. package/dist/runtime/subagent-thread-runtime.js +27 -5
  61. package/dist/runtime/subagents/production.js +0 -4
  62. package/dist/runtime/task-context-recovery.js +30 -7
  63. package/dist/runtime/task-context-service.d.ts +7 -1
  64. package/dist/runtime/task-context-service.js +40 -8
  65. package/dist/runtime/thread-admission.d.ts +2 -0
  66. package/dist/runtime/thread-admission.js +9 -1
  67. package/dist/runtime/thread-runtime.d.ts +3 -0
  68. package/dist/runtime/thread-runtime.js +42 -3
  69. package/dist/runtime/thread-ui-adapter.js +1 -11
  70. package/dist/runtime/tool-gateway.d.ts +2 -0
  71. package/dist/runtime/tool-gateway.js +4 -0
  72. package/dist/runtime/tool-receipt-validator.js +4 -0
  73. package/dist/runtime/ui-events.d.ts +3 -1
  74. package/dist/runtime/ui-view-model.js +62 -59
  75. package/dist/runtime/workspace-verification.d.ts +7 -0
  76. package/dist/runtime/workspace-verification.js +98 -0
  77. package/dist/services/chat-completion-sse.d.ts +9 -0
  78. package/dist/services/chat-completion-sse.js +50 -0
  79. package/dist/services/compact/summary-generator.d.ts +1 -1
  80. package/dist/services/compact/summary-generator.js +12 -0
  81. package/dist/services/config.js +3 -7
  82. package/dist/services/global-config.d.ts +3 -11
  83. package/dist/services/global-config.js +36 -26
  84. package/dist/services/llm.d.ts +3 -1
  85. package/dist/services/llm.js +171 -285
  86. package/dist/services/provider-diagnostics.d.ts +2 -1
  87. package/dist/services/provider-diagnostics.js +15 -4
  88. package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
  89. package/dist/services/provider-resilience/error-classifier.js +14 -0
  90. package/dist/tools/core/common.d.ts +0 -11
  91. package/dist/tools/core/common.js +0 -18
  92. package/dist/tools/core/edit-file.js +61 -88
  93. package/dist/tools/core/exec-command.js +61 -80
  94. package/dist/tools/core/grep.js +84 -24
  95. package/dist/tools/core/read-file.js +3 -2
  96. package/dist/tools/core/write-file.js +5 -3
  97. package/dist/tools/todo.d.ts +2 -2
  98. package/dist/tools/todo.js +29 -10
  99. package/dist/tui-ui/chrome-view-model.js +15 -6
  100. package/dist/utils/utf8.d.ts +6 -0
  101. package/dist/utils/utf8.js +14 -0
  102. package/docs/cli-guide.md +58 -40
  103. package/docs/orion.example.yaml +4 -3
  104. package/npm-shrinkwrap.json +2 -2
  105. package/package.json +1 -1
@@ -16,17 +16,22 @@ function immutableClone(value) {
16
16
  }
17
17
  class HarnessKernelTaskContextService {
18
18
  constructor(options) {
19
+ this.options = options;
19
20
  this.serviceId = 'task-context';
20
21
  if (!Number.isSafeInteger(options.revision ?? 0) || (options.revision ?? 0) < 0) {
21
22
  throw new RangeError('TaskContext revision must be a non-negative safe integer.');
22
23
  }
23
24
  this.revisionValue = options.revision ?? 0;
24
- this.kernel = new context_harness_1.HarnessKernel({
25
- cwd: options.cwd,
26
- modelId: options.modelId,
27
- state: options.state ? structuredClone(options.state) : undefined,
28
- config: { completionGate: 'block', ...options.config },
29
- requireLocalVerificationReceipt: options.requireLocalVerificationReceipt,
25
+ this.captureVerificationWorkspace = options.captureVerificationWorkspace;
26
+ this.kernel = this.createKernel(options.state);
27
+ }
28
+ createKernel(state) {
29
+ return new context_harness_1.HarnessKernel({
30
+ cwd: this.options.cwd,
31
+ modelId: this.options.modelId,
32
+ state: state ? structuredClone(state) : undefined,
33
+ config: { completionGate: 'block', ...this.options.config },
34
+ requireLocalVerificationReceipt: this.options.requireLocalVerificationReceipt,
30
35
  });
31
36
  }
32
37
  get revision() {
@@ -34,8 +39,12 @@ class HarnessKernelTaskContextService {
34
39
  }
35
40
  observeUserInput(input, goalTaskId) {
36
41
  const result = this.mutate(() => this.kernel.updateContractFromUserInput(input, goalTaskId));
42
+ this.refreshVerificationWorkspace();
37
43
  return result ? immutableClone(result) : undefined;
38
44
  }
45
+ observeGoalSteering(input, goalId) {
46
+ this.mutate(() => this.kernel.observeGoalSteering(input, goalId));
47
+ }
39
48
  classifyIntent(input) {
40
49
  return immutableClone(this.kernel.classifyIntent(input));
41
50
  }
@@ -57,6 +66,14 @@ class HarnessKernelTaskContextService {
57
66
  observeToolResult(input) {
58
67
  this.mutate(() => this.kernel.recordToolResult(input));
59
68
  }
69
+ observeVerificationWorkspace(fingerprint) {
70
+ this.mutate(() => this.kernel.observeVerificationWorkspace(fingerprint));
71
+ }
72
+ refreshVerificationWorkspace(capture = this.captureVerificationWorkspace) {
73
+ if (capture && this.kernel.hasCurrentWorkspaceVerification(true)) {
74
+ this.observeVerificationWorkspace(capture());
75
+ }
76
+ }
60
77
  noteIndeterminateWorkspaceChange() {
61
78
  this.mutate(() => this.kernel.noteIndeterminateWorkspaceChange());
62
79
  }
@@ -82,8 +99,10 @@ class HarnessKernelTaskContextService {
82
99
  recordTaskTodoReceipt(step, observation) {
83
100
  this.mutate(() => this.kernel.recordTaskTodoReceipt(step, observation));
84
101
  }
85
- updateTaskTodos(todos) {
86
- return this.mutate(() => this.kernel.updateTaskTodos(todos));
102
+ updateTaskTodos(todos, blockedReason) {
103
+ if (todos.some(todo => todo.status === 'completed'))
104
+ this.refreshVerificationWorkspace();
105
+ return this.mutate(() => this.kernel.updateTaskTodos(todos, blockedReason));
87
106
  }
88
107
  progressState() {
89
108
  return this.kernel.progressState();
@@ -92,6 +111,7 @@ class HarnessKernelTaskContextService {
92
111
  this.mutate(() => this.kernel.recordProgress(baseline, unconfirmedWorkspaceRevisions));
93
112
  }
94
113
  auditCompletion(enforceTaskTodos = false, requireEveryCriterion = false) {
114
+ this.refreshVerificationWorkspace();
95
115
  const result = this.mutate(() => this.kernel.beforeComplete(enforceTaskTodos, requireEveryCriterion));
96
116
  return immutableClone({
97
117
  ...result,
@@ -139,6 +159,18 @@ class HarnessKernelTaskContextService {
139
159
  exportState() {
140
160
  return structuredClone(this.kernel.toJSON());
141
161
  }
162
+ restoreGoalCheckpoint(state, revision) {
163
+ const counts = this.kernel.progressState().progressCountedByReason;
164
+ this.kernel = this.createKernel({
165
+ ...state,
166
+ progressState: {
167
+ schemaVersion: 1,
168
+ ...state.progressState,
169
+ ...(counts ? { progressCountedByReason: counts } : {}),
170
+ },
171
+ });
172
+ this.revisionValue = Math.max(this.revisionValue, revision) + 1;
173
+ }
142
174
  mutate(operation) {
143
175
  const before = this.kernel.toJSON().updatedAt;
144
176
  const result = operation();
@@ -14,6 +14,7 @@ export interface ActiveThreadTurnV1 {
14
14
  readonly kind: ThreadTurnKindV1;
15
15
  readonly startedAt: number;
16
16
  readonly interruptIntentId?: string;
17
+ readonly steeringClosed?: true;
17
18
  }
18
19
  export interface QueuedThreadTurnV1 {
19
20
  readonly queueId: string;
@@ -107,6 +108,7 @@ export declare class ThreadAdmissionControllerV1 {
107
108
  start(request: ThreadTurnRequestV1, pendingFollowupId?: string): TurnAdmissionV1;
108
109
  followUp(request: ThreadTurnRequestV1): TurnAdmissionV1;
109
110
  steer(input: string): TurnAdmissionV1;
111
+ closeSteering(turnId: string): void;
110
112
  interrupt(): InterruptAdmissionV1;
111
113
  finish(turnId: string): ThreadTurnFinishV1;
112
114
  /**
@@ -57,8 +57,11 @@ class ThreadAdmissionControllerV1 {
57
57
  return rejected('shutdown');
58
58
  if (!this.activeTurn)
59
59
  return rejected('no_active_turn');
60
- if (this.activeTurn.kind === 'maintenance')
60
+ if (this.activeTurn.kind === 'maintenance' ||
61
+ this.activeTurn.steeringClosed ||
62
+ this.activeTurn.interruptIntentId) {
61
63
  return rejected('non_steerable');
64
+ }
62
65
  if (!validInput(input, this.maxInputBytes))
63
66
  return rejected('invalid_input');
64
67
  return {
@@ -67,6 +70,11 @@ class ThreadAdmissionControllerV1 {
67
70
  itemId: this.nextId('steer item'),
68
71
  };
69
72
  }
73
+ closeSteering(turnId) {
74
+ if (this.activeTurn?.turnId === turnId && !this.activeTurn.steeringClosed) {
75
+ this.activeTurn = { ...this.activeTurn, steeringClosed: true };
76
+ }
77
+ }
70
78
  interrupt() {
71
79
  if (this.shutdown)
72
80
  return { status: 'rejected', reason: 'shutdown' };
@@ -65,6 +65,8 @@ export interface ThreadTurnExecutionContextV1 {
65
65
  readonly outputDigest?: string;
66
66
  }): void;
67
67
  failItem(handle: ThreadItemHandleV1, error: string): void;
68
+ /** Drain committed input in order. A closing drain seals the turn only when empty. */
69
+ takePendingSteering?(closeIfEmpty?: boolean): string[];
68
70
  onSteer(handler: (input: string, itemId: string) => void | Promise<void>): void;
69
71
  }
70
72
  export interface ThreadTurnRunnerV1 {
@@ -119,6 +121,7 @@ export declare class ThreadRuntimeV1 {
119
121
  private readonly compactMaintenance;
120
122
  private readonly goalControlTurns;
121
123
  private readonly queuedGoalControls;
124
+ private readonly pendingSteering;
122
125
  private activeAbort;
123
126
  private activeTurnId;
124
127
  private activeRun;
@@ -11,6 +11,7 @@ class ThreadRuntimeV1 {
11
11
  this.compactMaintenance = new Map();
12
12
  this.goalControlTurns = new Map();
13
13
  this.queuedGoalControls = new Map();
14
+ this.pendingSteering = new Map();
14
15
  this.idleWaiters = new Set();
15
16
  this.closed = false;
16
17
  this.store = options.store;
@@ -126,7 +127,14 @@ class ThreadRuntimeV1 {
126
127
  payload: { type: 'item.completed', data: { content: steerInput } },
127
128
  },
128
129
  ]);
129
- void Promise.resolve(this.steerHandler?.(steerInput, result.itemId)).catch(() => undefined);
130
+ if (this.activeTurnId === result.activeTurnId) {
131
+ try {
132
+ void Promise.resolve(this.steerHandler?.(steerInput, result.itemId)).catch(() => undefined);
133
+ }
134
+ catch {
135
+ // A callback cannot veto already committed input.
136
+ }
137
+ }
130
138
  break;
131
139
  }
132
140
  case 'interrupt_requested':
@@ -336,6 +344,7 @@ class ThreadRuntimeV1 {
336
344
  request.onRejected?.('shutdown');
337
345
  this.goalControlTurns.clear();
338
346
  this.queuedGoalControls.clear();
347
+ this.pendingSteering.clear();
339
348
  this.admission.close();
340
349
  this.activeAbort?.abort(reason);
341
350
  this.consumers.clear();
@@ -412,8 +421,10 @@ class ThreadRuntimeV1 {
412
421
  }
413
422
  }
414
423
  scheduleTurn(active) {
424
+ // Admission can open a turn after the preceding terminal is durable but
425
+ // before its resources settle. That run's finally block starts the new turn.
415
426
  if (this.activeRun)
416
- throw new Error('ThreadRuntime attempted to schedule a second active run');
427
+ return;
417
428
  const abortController = new AbortController();
418
429
  this.activeAbort = abortController;
419
430
  this.activeTurnId = active.turnId;
@@ -515,13 +526,28 @@ class ThreadRuntimeV1 {
515
526
  failItem: (handle, error) => {
516
527
  this.commitAndPublish([{ ...handle, payload: { type: 'item.failed', data: { error } } }]);
517
528
  },
529
+ takePendingSteering: closeIfEmpty => {
530
+ if (this.closed || this.activeTurnId !== active.turnId || abortSignal.aborted)
531
+ return [];
532
+ const pending = this.pendingSteering.get(active.turnId);
533
+ if (pending) {
534
+ this.pendingSteering.delete(active.turnId);
535
+ return pending;
536
+ }
537
+ if (closeIfEmpty)
538
+ this.admission.closeSteering(active.turnId);
539
+ return [];
540
+ },
518
541
  onSteer: handler => {
519
- this.steerHandler = handler;
542
+ if (this.activeTurnId === active.turnId)
543
+ this.steerHandler = handler;
520
544
  },
521
545
  };
522
546
  }
523
547
  finalizeTurn(active, outcome) {
524
548
  const turnId = active.turnId;
549
+ this.admission.closeSteering(turnId);
550
+ this.pendingSteering.delete(turnId);
525
551
  const goalControl = this.goalControlTurns.has(turnId);
526
552
  let terminalPublished = false;
527
553
  try {
@@ -694,6 +720,19 @@ class ThreadRuntimeV1 {
694
720
  }
695
721
  publish(events) {
696
722
  for (const event of events) {
723
+ // Project committed steering before a live observer can drain it or submit more input.
724
+ if (event.turnId && event.durability === 'durable') {
725
+ if (event.payload.type === 'turn.steered') {
726
+ const pending = this.pendingSteering.get(event.turnId);
727
+ if (pending)
728
+ pending.push(event.payload.data.input);
729
+ else
730
+ this.pendingSteering.set(event.turnId, [event.payload.data.input]);
731
+ }
732
+ else if (event.payload.type === 'turn.interrupt_requested') {
733
+ this.pendingSteering.delete(event.turnId);
734
+ }
735
+ }
697
736
  for (const buffer of this.consumers.values())
698
737
  buffer.offer(event);
699
738
  }
@@ -338,17 +338,6 @@ class ThreadUiAdapterV1 {
338
338
  }
339
339
  projectGoalCommit(receipt) {
340
340
  const persistence = (0, goal_runtime_coordinator_1.readGoalRuntimePersistenceV2)((0, turn_commit_1.parseTurnCommitV1)(receipt));
341
- if (persistence.state?.status === 'completed') {
342
- this.emit({
343
- type: 'goal_event',
344
- event: {
345
- type: 'goal_cleared',
346
- goalId: persistence.state.goalId,
347
- reason: 'completion_auto_exit',
348
- },
349
- });
350
- return;
351
- }
352
341
  if (persistence.state) {
353
342
  this.emit({
354
343
  type: 'goal_event',
@@ -598,6 +587,7 @@ function goalUiSnapshot(state) {
598
587
  ? 'blocked'
599
588
  : state.status,
600
589
  tokenBudget: state.budget.maxTokens,
590
+ timeBudgetMs: state.budget.maxElapsedMs,
601
591
  tokensUsed: state.tokensUsed,
602
592
  timeUsedMs: state.elapsedMs,
603
593
  continuationCount: state.continuationCount,
@@ -95,6 +95,8 @@ export interface ToolInvocationReceiptV1 {
95
95
  readonly success: boolean;
96
96
  readonly result: ToolResult;
97
97
  readonly outputDigest: string;
98
+ /** Runtime-captured workspace identity for this local verification result. */
99
+ readonly verificationWorkspace?: string | null;
98
100
  readonly startedAt: number;
99
101
  readonly finishedAt: number;
100
102
  readonly durationMs: number;
@@ -197,6 +197,7 @@ class ToolGateway {
197
197
  terminalPhase: 'execute',
198
198
  result: executed.result,
199
199
  durationMs: executed.durationMs,
200
+ verificationWorkspace: executed.verificationWorkspace,
200
201
  });
201
202
  }
202
203
  async commitTerminal(invocation, intent, outcome) {
@@ -222,6 +223,9 @@ class ToolGateway {
222
223
  success: outcome.terminal === 'completed' && outcome.result.success,
223
224
  result: structuredClone(outcome.result),
224
225
  outputDigest: (0, canonical_1.digestRuntimeValue)(outcome.result),
226
+ ...(outcome.verificationWorkspace !== undefined
227
+ ? { verificationWorkspace: outcome.verificationWorkspace }
228
+ : {}),
225
229
  startedAt: intent.startedAt,
226
230
  finishedAt,
227
231
  durationMs: outcome.durationMs ?? Math.max(0, finishedAt - intent.startedAt),
@@ -73,6 +73,10 @@ function validateDurableToolInvocationReceiptV1(input) {
73
73
  !isSha256(parsed.executionPolicyDigest) ||
74
74
  !isSha256(parsed.intentDigest) ||
75
75
  !isSha256(parsed.outputDigest) ||
76
+ (parsed.verificationWorkspace !== undefined &&
77
+ (parsed.toolName !== 'exec_command' ||
78
+ parsed.terminalPhase !== 'execute' ||
79
+ (parsed.verificationWorkspace !== null && !isSha256(parsed.verificationWorkspace)))) ||
76
80
  !validToolResult(parsed.result) ||
77
81
  (0, canonical_1.digestRuntimeValue)(parsed.result) !== parsed.outputDigest ||
78
82
  parsed.success !== (parsed.terminal === 'completed' && parsed.result.success) ||
@@ -1,6 +1,7 @@
1
1
  import type { FollowupQueueStore } from './followup-queue-store';
2
2
  import type { Store } from '../framework/store';
3
3
  import type { LoopContinuationAction, LoopStats } from '../framework/query';
4
+ import type { StopNextAction } from '../framework/stop-decision';
4
5
  import type { LLMService } from '../services/llm';
5
6
  import type { CompactCoordinator } from '../services/compact';
6
7
  import type { ModelCoordinator } from './model-coordinator';
@@ -95,7 +96,7 @@ export interface TranscriptEntry {
95
96
  }
96
97
  export interface LoopBudgetStopView {
97
98
  schemaVersion: 1;
98
- kind: 'llm_request_limit' | 'tool_call_limit' | 'provider_preflight_limit' | 'other';
99
+ kind: 'llm_request_limit' | 'tool_call_limit' | 'goal_token_budget' | 'goal_time_budget' | 'provider_preflight_limit' | 'other';
99
100
  reason: string;
100
101
  reasonCode?: string;
101
102
  recoverable: true;
@@ -120,6 +121,7 @@ export interface LoopBudgetStopView {
120
121
  success?: boolean;
121
122
  };
122
123
  actions: LoopContinuationAction[];
124
+ nextActions?: StopNextAction[];
123
125
  }
124
126
  export interface TranscriptAppendEntry extends Omit<TranscriptEntry, 'id'> {
125
127
  live?: boolean;
@@ -41,18 +41,22 @@ const ui_events_1 = require("./ui-events");
41
41
  const format_1 = require("../services/format");
42
42
  const verification_profile_1 = require("../services/verification-profile");
43
43
  const style_1 = require("../tui-core/style");
44
+ const BUDGET_STOP_KINDS = new Map([
45
+ ['llm_request_budget', 'llm_request_limit'],
46
+ ['budget_paused_compact_pending', 'llm_request_limit'],
47
+ ['request_safety_limit', 'llm_request_limit'],
48
+ ['tool_call_budget', 'tool_call_limit'],
49
+ ['goal_token_budget', 'goal_token_budget'],
50
+ ['goal_time_budget', 'goal_time_budget'],
51
+ ['provider_preflight_budget', 'provider_preflight_limit'],
52
+ ]);
44
53
  /** Build the renderer-neutral recovery card for a recoverable loop-budget stop. */
45
54
  function createLoopBudgetStopView(stats) {
46
- const reason = (0, style_1.sanitizeTerminalText)(stats.stopDecision?.reason.message ?? stats.budgetExceededReason ?? 'agent loop budget reached', 1)
55
+ const decision = stats.stopDecision;
56
+ const reasonCode = decision?.reason.code ?? stats.budgetStopCode;
57
+ const reason = (0, style_1.sanitizeTerminalText)(decision?.reason.message ?? stats.budgetExceededReason ?? 'Execution budget reached', 1)
47
58
  .replace(/\s+/gu, ' ')
48
59
  .trim();
49
- const kind = /LLM request budget/iu.test(reason)
50
- ? 'llm_request_limit'
51
- : /tool call budget/iu.test(reason)
52
- ? 'tool_call_limit'
53
- : /preflight|provider/iu.test(reason)
54
- ? 'provider_preflight_limit'
55
- : 'other';
56
60
  const tool = stats.lastToolName
57
61
  ? (0, style_1.sanitizeTerminalText)(stats.lastToolName, 1).replace(/\s+/gu, ' ').trim()
58
62
  : '';
@@ -61,31 +65,18 @@ function createLoopBudgetStopView(stats) {
61
65
  : '';
62
66
  return {
63
67
  schemaVersion: 1,
64
- kind,
68
+ kind: BUDGET_STOP_KINDS.get(reasonCode ?? '') ?? 'other',
65
69
  reason,
66
- ...(stats.stopDecision ? { reasonCode: stats.stopDecision.reason.code } : {}),
70
+ ...(reasonCode ? { reasonCode } : {}),
67
71
  recoverable: true,
68
72
  statePreserved: true,
69
73
  source: stats.loopBudgetSource,
70
- llmRequests: {
71
- current: stats.llmRequests,
72
- ...(typeof stats.loopBudgetMaxLlmRequests === 'number'
73
- ? { maximum: stats.loopBudgetMaxLlmRequests }
74
- : {}),
75
- },
76
- toolCalls: {
77
- current: stats.toolCalls,
78
- ...(typeof stats.loopBudgetMaxToolCalls === 'number'
79
- ? { maximum: stats.loopBudgetMaxToolCalls }
80
- : {}),
81
- },
74
+ llmRequests: { current: decision?.resources.llmRequests?.used ?? stats.llmRequests },
75
+ toolCalls: { current: decision?.resources.toolCalls?.used ?? stats.toolCalls },
82
76
  modelVisibleToolBytes: {
83
77
  current: stats.modelVisibleToolBytes,
84
78
  maximum: stats.loopBudgetMaxModelVisibleBytes,
85
79
  },
86
- ...(stats.loopBudgetBaseLlmRequests === undefined
87
- ? {}
88
- : { baseLlmRequestLimit: stats.loopBudgetBaseLlmRequests }),
89
80
  ...(tool
90
81
  ? {
91
82
  stopPoint: {
@@ -97,9 +88,8 @@ function createLoopBudgetStopView(stats) {
97
88
  },
98
89
  }
99
90
  : {}),
100
- actions: stats.continuationActions?.length
101
- ? [...stats.continuationActions]
102
- : ['reply_continue', 'narrow_instruction', 'inspect_loop_stats', 'raise_budget'],
91
+ actions: [...(stats.continuationActions ?? [])],
92
+ ...(decision ? { nextActions: [...decision.nextActions] } : {}),
103
93
  };
104
94
  }
105
95
  /** Select Chinese only when the current user instruction contains Han characters. */
@@ -108,39 +98,52 @@ function budgetStopLocaleForInput(input) {
108
98
  }
109
99
  /** Format every recovery action explicitly; no renderer may hide it in collapsed details. */
110
100
  function formatLoopBudgetStopView(view, locale = 'en') {
111
- const count = (current, maximum, unit) => maximum === undefined ? `${current} ${unit}` : `${current}/${maximum} ${unit}`;
112
- const llm = count(view.llmRequests.current, view.llmRequests.maximum, locale === 'zh-CN' ? '次模型请求' : 'model requests');
113
- const tools = count(view.toolCalls.current, view.toolCalls.maximum, locale === 'zh-CN' ? '次工具调用' : 'tool calls');
101
+ const chinese = locale === 'zh-CN';
102
+ const goal = view.kind === 'goal_token_budget' || view.kind === 'goal_time_budget';
103
+ const heading = goal
104
+ ? chinese
105
+ ? 'Goal 已暂停'
106
+ : 'Goal paused'
107
+ : chinese
108
+ ? '本轮已暂停'
109
+ : 'Turn paused';
110
+ const usage = chinese
111
+ ? `${view.llmRequests.current} 次模型请求,${view.toolCalls.current} 次工具调用`
112
+ : `${view.llmRequests.current} model requests, ${view.toolCalls.current} tool calls`;
113
+ const lines = [`${heading} · ${usage}`, view.reason];
114
114
  const visibleToolBytes = view.modelVisibleToolBytes;
115
- const pressure = visibleToolBytes
116
- ? count(visibleToolBytes.current, visibleToolBytes.maximum, 'bytes')
117
- : undefined;
118
- const stopPoint = view.stopPoint
119
- ? `${view.stopPoint.tool}${view.stopPoint.summary ? ` — ${view.stopPoint.summary}` : ''}`
120
- : undefined;
121
- if (locale === 'zh-CN') {
122
- const lines = [
123
- `本轮已暂停:达到单次响应的执行预算(${llm},${tools})。`,
124
- '这不是任务失败;当前会话状态已保存。',
125
- ];
126
- lines.push(view.reason);
127
- if (pressure)
128
- lines.push(`模型可见工具输出 ${pressure}(${view.source ?? 'default'})`);
129
- if (stopPoint)
130
- lines.push(`停止位置:${stopPoint}`);
131
- lines.push('下一步:', '• 回复 `继续`,按同一目标接着执行。', '• 或给出一个更小、更具体的下一步。', '• 运行 `/usage` 查看请求与工具用量。', '• 对确实需要更长运行的任务,在 orion.yaml 中调高 `agentLoop.budget`。');
132
- return lines.join('\n');
133
- }
134
- const lines = [
135
- `Turn paused: the per-response execution budget was reached (${llm}, ${tools}).`,
136
- 'This is recoverable, not a task failure; the current session state is saved.',
115
+ if (visibleToolBytes) {
116
+ const shown = (0, format_1.formatBytes)(visibleToolBytes.current);
117
+ const allowance = visibleToolBytes.maximum === undefined ? '' : ` / ${(0, format_1.formatBytes)(visibleToolBytes.maximum)}`;
118
+ lines.push(`${chinese ? '模型可见工具输出' : 'Model-visible tool output'} ${shown}${allowance}`);
119
+ }
120
+ if (view.stopPoint) {
121
+ const { tool, summary } = view.stopPoint;
122
+ lines.push(`${chinese ? '停止位置' : 'Stopped after'} · ${tool}${summary ? ` — ${summary}` : ''}`);
123
+ }
124
+ const actions = view.nextActions?.map(action => {
125
+ const command = action.command ? ` · \`${action.command}\`` : '';
126
+ return `${action.label}${command}`;
127
+ }) ?? [
128
+ ...(view.actions.includes('reply_continue') && !goal
129
+ ? [
130
+ chinese
131
+ ? '回复 `继续`,按同一目标接着执行。'
132
+ : 'Reply `继续` to continue the same objective.',
133
+ ]
134
+ : []),
135
+ ...(view.actions.includes('narrow_instruction')
136
+ ? [chinese ? '给出一个更具体的下一步。' : 'Give a smaller, concrete next step.']
137
+ : []),
138
+ ...(view.actions.includes('inspect_loop_stats')
139
+ ? [
140
+ chinese
141
+ ? '运行 `/usage` 查看请求与工具用量。'
142
+ : 'Run `/usage` to inspect request and tool usage.',
143
+ ]
144
+ : []),
137
145
  ];
138
- lines.push(view.reason);
139
- if (pressure)
140
- lines.push(`Model-visible tool output ${pressure} (${view.source ?? 'default'})`);
141
- if (stopPoint)
142
- lines.push(`Stopped after: ${stopPoint}`);
143
- lines.push('Next:', '• Reply `继续` to continue the same objective.', '• Or give a smaller, concrete next step.', '• Run `/usage` to inspect request and tool usage.', '• For intentional long work, raise `agentLoop.budget` in orion.yaml.');
146
+ lines.push(...actions.map(action => `• ${action}`));
144
147
  return lines.join('\n');
145
148
  }
146
149
  /**
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Observe file identities at verification boundaries without reading file contents.
3
+ * Git supplies the tracked and nonignored file scope, plus the staged object
4
+ * and HEAD identities used by diff checks. Other projects use the filesystem walk.
5
+ */
6
+ export declare function captureVerificationWorkspace(workspace: string, runtimeDirectories: readonly string[]): string | null;
7
+ //# sourceMappingURL=workspace-verification.d.ts.map
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.captureVerificationWorkspace = captureVerificationWorkspace;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ const ignoredDirectories = new Set([
9
+ '.git',
10
+ 'node_modules',
11
+ '.venv',
12
+ '__pycache__',
13
+ '.pytest_cache',
14
+ '.mypy_cache',
15
+ ]);
16
+ /**
17
+ * Observe file identities at verification boundaries without reading file contents.
18
+ * Git supplies the tracked and nonignored file scope, plus the staged object
19
+ * and HEAD identities used by diff checks. Other projects use the filesystem walk.
20
+ */
21
+ function captureVerificationWorkspace(workspace, runtimeDirectories) {
22
+ try {
23
+ const root = (0, node_fs_1.realpathSync)(workspace);
24
+ const excluded = new Set(runtimeDirectories
25
+ .map(path => (0, node_path_1.relative)(workspace, path))
26
+ .filter(path => path && path !== '..' && !path.startsWith('..' + node_path_1.sep) && !(0, node_path_1.isAbsolute)(path))
27
+ .map(path => path.split(node_path_1.sep).join('/')));
28
+ const gitScope = listGitScope(root);
29
+ const digest = (0, node_crypto_1.createHash)('sha256').update('workspace-verification-v2\0' + root + '\0');
30
+ const visit = (directory, prefix, scope, scopeOffset = 0) => {
31
+ if (scope) {
32
+ digest.update('git\0' + prefix + '\0');
33
+ digest.update(scope.head + '\0');
34
+ digest.update(scope.indexDigest + '\0');
35
+ }
36
+ const entries = (0, node_fs_1.readdirSync)(directory, { withFileTypes: true }).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
37
+ for (const entry of entries) {
38
+ const path = prefix + entry.name;
39
+ if (excluded.has(path) || ignoredDirectories.has(entry.name))
40
+ continue;
41
+ const scopedPath = path.slice(scopeOffset);
42
+ if (scope && !scope.files.has(scopedPath) && !scope.ancestors.has(scopedPath))
43
+ continue;
44
+ const absolute = (0, node_path_1.join)(directory, entry.name);
45
+ const stats = (0, node_fs_1.lstatSync)(absolute, { bigint: true });
46
+ if (stats.isDirectory()) {
47
+ // A gitlink lists the directory itself only. Inspect its worktree
48
+ // against its own ignore rules rather than hashing the gitlink alone.
49
+ if (scope?.files.has(scopedPath) && !scope.ancestors.has(scopedPath)) {
50
+ const nested = (0, node_fs_1.existsSync)((0, node_path_1.join)(absolute, '.git')) ? listGitScope(absolute) : undefined;
51
+ visit(absolute, path + '/', nested, path.length + 1);
52
+ }
53
+ else {
54
+ visit(absolute, path + '/', scope, scopeOffset);
55
+ }
56
+ continue;
57
+ }
58
+ digest.update([path, stats.dev, stats.ino, stats.mode, stats.size, stats.mtimeNs, stats.ctimeNs].join('\0') + '\0');
59
+ }
60
+ };
61
+ visit(root, '', gitScope);
62
+ return digest.digest('hex');
63
+ }
64
+ catch {
65
+ // An incomplete observation must not keep a previous check current.
66
+ return null;
67
+ }
68
+ }
69
+ function listGitScope(root) {
70
+ let search = root;
71
+ while (!(0, node_fs_1.existsSync)((0, node_path_1.join)(search, '.git'))) {
72
+ const parent = (0, node_path_1.dirname)(search);
73
+ if (parent === search)
74
+ return undefined;
75
+ search = parent;
76
+ }
77
+ const options = { cwd: root, timeout: 2000, maxBuffer: 8 * 1024 * 1024 };
78
+ const listed = (0, node_child_process_1.spawnSync)('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.'], options);
79
+ const staged = (0, node_child_process_1.spawnSync)('git', ['ls-files', '--stage', '-z', '--', '.'], options);
80
+ const head = (0, node_child_process_1.spawnSync)('git', ['rev-parse', '--verify', '--quiet', 'HEAD'], options);
81
+ if (listed.status !== 0 || staged.status !== 0 || (head.status !== 0 && head.status !== 1)) {
82
+ throw new Error('Git verification scope could not be observed.');
83
+ }
84
+ const files = new Set(listed.stdout.toString('utf8').split('\0').filter(Boolean));
85
+ const ancestors = new Set();
86
+ for (const path of files) {
87
+ for (let slash = path.indexOf('/'); slash >= 0; slash = path.indexOf('/', slash + 1)) {
88
+ ancestors.add(path.slice(0, slash));
89
+ }
90
+ }
91
+ return {
92
+ files,
93
+ ancestors,
94
+ head: head.stdout.toString('utf8').trim(),
95
+ indexDigest: (0, node_crypto_1.createHash)('sha256').update(staged.stdout).digest('hex'),
96
+ };
97
+ }
98
+ //# sourceMappingURL=workspace-verification.js.map
@@ -0,0 +1,9 @@
1
+ import OpenAI from 'openai';
2
+ import { Stream } from 'openai/core/streaming';
3
+ /** Keep the SDK's SSE framing while exposing the Chat Completions end marker. */
4
+ export declare class ChatCompletionSseStream<Chunk> extends Stream<Chunk> {
5
+ private doneEvent;
6
+ get sawDoneEvent(): boolean;
7
+ static fromSSEResponse<Item>(response: Response, controller: AbortController, client?: OpenAI): ChatCompletionSseStream<Item>;
8
+ }
9
+ //# sourceMappingURL=chat-completion-sse.d.ts.map