@orion-agents/orion-code 0.4.3 → 0.4.4

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 (83) hide show
  1. package/CHANGELOG.md +6 -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/framework/loop-budget-contract.d.ts +1 -12
  13. package/dist/framework/loop-budget-contract.js +1 -7
  14. package/dist/framework/loop-progress.d.ts +3 -7
  15. package/dist/framework/loop-progress.js +7 -23
  16. package/dist/framework/query.d.ts +12 -24
  17. package/dist/framework/query.js +146 -287
  18. package/dist/harness/assembler.js +1 -1
  19. package/dist/harness/context-harness.d.ts +7 -1
  20. package/dist/harness/context-harness.js +68 -14
  21. package/dist/harness/index.d.ts +1 -1
  22. package/dist/harness/ledger.d.ts +1 -0
  23. package/dist/harness/ledger.js +12 -1
  24. package/dist/harness/progress-controller.js +57 -35
  25. package/dist/harness/state.js +1 -0
  26. package/dist/harness/stop-controller.d.ts +0 -5
  27. package/dist/harness/stop-controller.js +11 -31
  28. package/dist/harness/task-checklist.d.ts +1 -1
  29. package/dist/harness/task-checklist.js +2 -5
  30. package/dist/harness/types.d.ts +5 -0
  31. package/dist/print-ui/event-stream.d.ts +5 -0
  32. package/dist/print-ui/event-stream.js +22 -5
  33. package/dist/runtime/agent-loop.d.ts +2 -1
  34. package/dist/runtime/agent-loop.js +20 -17
  35. package/dist/runtime/agent-runtime-controller.d.ts +1 -1
  36. package/dist/runtime/agent-runtime-controller.js +21 -11
  37. package/dist/runtime/goal-lifecycle-v2.d.ts +6 -4
  38. package/dist/runtime/goal-lifecycle-v2.js +164 -56
  39. package/dist/runtime/goal-runtime-coordinator.d.ts +6 -3
  40. package/dist/runtime/goal-runtime-coordinator.js +90 -36
  41. package/dist/runtime/goals/presentation.js +3 -1
  42. package/dist/runtime/goals/types.d.ts +1 -3
  43. package/dist/runtime/goals/types.js +0 -3
  44. package/dist/runtime/loop-budget.d.ts +0 -7
  45. package/dist/runtime/loop-budget.js +8 -54
  46. package/dist/runtime/orion-runtime-v1.js +55 -14
  47. package/dist/runtime/product-orion-runtime.js +6 -11
  48. package/dist/runtime/rsi/evaluation.js +1 -7
  49. package/dist/runtime/step-snapshot.d.ts +3 -1
  50. package/dist/runtime/step-snapshot.js +11 -1
  51. package/dist/runtime/subagent-thread-runtime.js +27 -5
  52. package/dist/runtime/subagents/production.js +0 -4
  53. package/dist/runtime/task-context-recovery.js +9 -2
  54. package/dist/runtime/task-context-service.d.ts +5 -1
  55. package/dist/runtime/task-context-service.js +37 -8
  56. package/dist/runtime/thread-admission.d.ts +2 -0
  57. package/dist/runtime/thread-admission.js +9 -1
  58. package/dist/runtime/thread-runtime.d.ts +3 -0
  59. package/dist/runtime/thread-runtime.js +42 -3
  60. package/dist/runtime/thread-ui-adapter.js +1 -11
  61. package/dist/runtime/tool-gateway.d.ts +2 -0
  62. package/dist/runtime/tool-gateway.js +4 -0
  63. package/dist/runtime/tool-receipt-validator.js +4 -0
  64. package/dist/runtime/ui-events.d.ts +3 -1
  65. package/dist/runtime/ui-view-model.js +62 -59
  66. package/dist/runtime/workspace-verification.d.ts +7 -0
  67. package/dist/runtime/workspace-verification.js +83 -0
  68. package/dist/services/config.js +3 -7
  69. package/dist/services/global-config.d.ts +3 -11
  70. package/dist/services/global-config.js +36 -26
  71. package/dist/services/llm.d.ts +2 -0
  72. package/dist/services/llm.js +13 -0
  73. package/dist/services/provider-diagnostics.d.ts +1 -0
  74. package/dist/services/provider-diagnostics.js +8 -2
  75. package/dist/tools/core/edit-file.js +4 -2
  76. package/dist/tools/core/write-file.js +5 -3
  77. package/dist/tools/todo.d.ts +1 -1
  78. package/dist/tools/todo.js +17 -1
  79. package/dist/tui-ui/chrome-view-model.js +15 -6
  80. package/docs/cli-guide.md +53 -40
  81. package/docs/orion.example.yaml +4 -3
  82. package/npm-shrinkwrap.json +2 -2
  83. package/package.json +1 -1
@@ -155,11 +155,13 @@ export interface BoundToolExecutionResultV1 {
155
155
  readonly terminal: 'completed' | 'failed' | 'interrupted' | 'indeterminate';
156
156
  readonly result: ToolResult;
157
157
  readonly durationMs: number;
158
+ readonly verificationWorkspace?: string | null;
158
159
  }
159
160
  /** The only runtime primitive allowed to call a frozen concrete tool executor. */
160
161
  export declare class ExecutionService {
161
162
  private readonly workspaceMutations?;
162
- constructor(workspaceMutations?: WorkspaceMutationCoordinatorV1 | undefined);
163
+ private readonly captureVerificationWorkspace?;
164
+ constructor(workspaceMutations?: WorkspaceMutationCoordinatorV1 | undefined, captureVerificationWorkspace?: (() => string | null) | undefined);
163
165
  run(request: BoundToolExecutionRequestV1): Promise<BoundToolExecutionResultV1>;
164
166
  }
165
167
  export interface StepSnapshotV1 {
@@ -5,6 +5,7 @@ exports.captureStepSnapshotV1 = captureStepSnapshotV1;
5
5
  exports.createCapabilityPlanV1 = createCapabilityPlanV1;
6
6
  exports.createAuthoritySnapshotV1 = createAuthoritySnapshotV1;
7
7
  exports.createExecutionPolicySnapshotV1 = createExecutionPolicySnapshotV1;
8
+ const verification_command_1 = require("../framework/verification-command");
8
9
  const tool_artifacts_1 = require("../core/tool-artifacts");
9
10
  const canonical_1 = require("./protocol/canonical");
10
11
  const runtime_protocol_v1_1 = require("./protocol/runtime-protocol-v1");
@@ -105,8 +106,9 @@ class ToolRouterSnapshotV1 {
105
106
  exports.ToolRouterSnapshotV1 = ToolRouterSnapshotV1;
106
107
  /** The only runtime primitive allowed to call a frozen concrete tool executor. */
107
108
  class ExecutionService {
108
- constructor(workspaceMutations) {
109
+ constructor(workspaceMutations, captureVerificationWorkspace) {
109
110
  this.workspaceMutations = workspaceMutations;
111
+ this.captureVerificationWorkspace = captureVerificationWorkspace;
110
112
  }
111
113
  async run(request) {
112
114
  const startedAt = Date.now();
@@ -147,6 +149,13 @@ class ExecutionService {
147
149
  }, execute)
148
150
  : await execute();
149
151
  const presented = persistLargeToolOutput(request.context.cwd, request.toolName, result);
152
+ // Capture the completed check's actual workspace, after any
153
+ // test-generated files have been written and before committing its receipt.
154
+ const verificationWorkspace = descriptor?.executorId === 'builtin:exec_command:v1' &&
155
+ typeof request.args.command === 'string' &&
156
+ (0, verification_command_1.classifyDirectVerificationCommand)(request.args.command)
157
+ ? this.captureVerificationWorkspace?.()
158
+ : undefined;
150
159
  return {
151
160
  terminal: timeoutController.signal.aborted
152
161
  ? 'interrupted'
@@ -155,6 +164,7 @@ class ExecutionService {
155
164
  : 'failed',
156
165
  result: presented,
157
166
  durationMs: Date.now() - startedAt,
167
+ ...(verificationWorkspace !== undefined ? { verificationWorkspace } : {}),
158
168
  };
159
169
  }
160
170
  catch (error) {
@@ -286,16 +286,19 @@ class SubagentThreadRuntimeV1 {
286
286
  }
287
287
  const projection = store.loadProjection();
288
288
  const turn = projection.turns[admission.turnId];
289
- if (budget.failure)
290
- throw budget.failure;
291
289
  if (!turn || turn.status === 'active' || !turn.commit) {
290
+ if (budget.failure)
291
+ throw budget.failure;
292
292
  throw new SubagentThreadRuntimeError('ORION_SUBAGENT_CHILD_COMMIT_MISSING', 'Child AgentLoop did not durably publish a terminal TurnCommitV1.');
293
293
  }
294
294
  const childCommit = (0, turn_commit_1.parseTurnCommitV1)(turn.commit.receipt);
295
295
  assertIndependentStepSnapshots(parent.stepSnapshotDigest, childCommit, turn.status);
296
296
  const usage = budget.snapshot();
297
- const stopDecision = childStopDecision(childCommit, turn.status, usage, budget.limits, parent);
298
- const summary = boundedChildSummary(projection, admission.turnId, childCommit, this.options.maxSummaryBytes);
297
+ const budgetFailure = turn.status === 'interrupted' ? undefined : budget.failure;
298
+ const stopDecision = childStopDecision(childCommit, turn.status, usage, budget.limits, parent, budgetFailure);
299
+ const summary = budgetFailure
300
+ ? truncateUtf8(budgetFailure.message, this.options.maxSummaryBytes)
301
+ : boundedChildSummary(projection, admission.turnId, childCommit, this.options.maxSummaryBytes);
299
302
  const evidenceItems = boundedEvidence(evidence.snapshot(), childCommit, this.options.maxEvidenceItems, this.options.maxEvidenceBytes);
300
303
  const receipt = createSubagentThreadReceiptV1({
301
304
  receiptId: (0, runtime_protocol_v1_1.createRuntimeId)(),
@@ -695,7 +698,7 @@ function assertIndependentStepSnapshots(parentStepSnapshotDigest, child, termina
695
698
  throw new SubagentThreadRuntimeError('ORION_SUBAGENT_CHILD_SNAPSHOT_INVALID', 'Child StepSnapshotV1 aliases a parent snapshot digest.');
696
699
  }
697
700
  }
698
- function childStopDecision(commit, terminal, usage, limits, parent) {
701
+ function childStopDecision(commit, terminal, usage, limits, parent, budgetFailure) {
699
702
  const parsed = parseStopDecision(commit);
700
703
  const status = terminal === 'interrupted' ? 'cancelled' : terminal === 'failed' ? 'failed' : 'completed';
701
704
  const base = parsed ??
@@ -718,8 +721,27 @@ function childStopDecision(commit, terminal, usage, limits, parent) {
718
721
  return (0, stop_decision_1.createStopDecision)({
719
722
  ...base,
720
723
  scope: 'subagent',
724
+ ...(budgetFailure
725
+ ? {
726
+ status: 'stopped',
727
+ disposition: 'resume_allowed',
728
+ reason: { code: 'subagent_budget_exceeded', message: budgetFailure.message },
729
+ nextActions: [
730
+ { kind: 'retry', label: 'Inspect the child budget before retrying.' },
731
+ ],
732
+ }
733
+ : {}),
721
734
  evidence: [
722
735
  ...base.evidence,
736
+ ...(budgetFailure
737
+ ? [
738
+ {
739
+ kind: 'resource_limit',
740
+ source: 'subagent-lease',
741
+ detail: budgetFailure.message,
742
+ },
743
+ ]
744
+ : []),
723
745
  {
724
746
  kind: 'runtime',
725
747
  source: 'subagent-thread-runtime',
@@ -281,10 +281,6 @@ class ProductionSubagentRuntimeV1 {
281
281
  gateway,
282
282
  loadBaseMessages: () => baseMessages.map(message => ({ ...message })),
283
283
  toolContext: () => context,
284
- loopBudget: {
285
- maxLlmRequestsPerUserTurn: input.budget.limits.maxModelRequests,
286
- maxToolCallsPerUserTurn: input.budget.limits.maxToolCalls,
287
- },
288
284
  commitTurn: commit => commitAgentLoopTurn(turnCommits, commit),
289
285
  });
290
286
  return new CommitCompletingChildRunnerV1(agentLoop, input, taskContext, turnCommits, baseMessages);
@@ -87,17 +87,20 @@ function projectTaskToolEvidence(receipt, args, cwd) {
87
87
  toolReceiptDigest: receipt.digest,
88
88
  command,
89
89
  cwd: (0, path_1.resolve)(cwd, typeof args.cwd === 'string' ? (0, common_1.normalizeToolPath)(args.cwd) : '.'),
90
- passed: receipt.success,
90
+ passed: receipt.success && receipt.verificationWorkspace !== null,
91
91
  }
92
92
  : undefined;
93
93
  return { changedFile, verification };
94
94
  }
95
95
  function recordTaskTodoToolReceipt(taskContext, todo, receipt, { changedFile, verification }) {
96
+ if (verification && receipt.verificationWorkspace !== undefined) {
97
+ taskContext.observeVerificationWorkspace(receipt.verificationWorkspace);
98
+ }
96
99
  if (!todo || receipt.terminalPhase !== 'execute' || (!receipt.success && !verification))
97
100
  return;
98
101
  taskContext.recordTaskTodoReceipt(todo, {
99
102
  digest: receipt.digest,
100
- passed: receipt.success,
103
+ passed: verification?.passed ?? receipt.success,
101
104
  kind: (0, verification_command_1.isLocalVerificationKind)(verification?.kind) ? verification.kind : undefined,
102
105
  changedFile,
103
106
  command: verification?.command,
@@ -171,6 +174,7 @@ function recoverInterruptedTaskContext(input) {
171
174
  state: seed.state,
172
175
  revision: seed.revision,
173
176
  requireLocalVerificationReceipt: true,
177
+ captureVerificationWorkspace: undefined,
174
178
  });
175
179
  let unconfirmedWorkspaceRevisions = 0;
176
180
  for (const event of events) {
@@ -196,6 +200,9 @@ function recoverInterruptedTaskContext(input) {
196
200
  unconfirmedWorkspaceRevisions++;
197
201
  }
198
202
  }
203
+ if (taskOptions.captureVerificationWorkspace) {
204
+ taskContext.refreshVerificationWorkspace(taskOptions.captureVerificationWorkspace);
205
+ }
199
206
  taskContext.recordProgress(seed.progressAtAdmission, unconfirmedWorkspaceRevisions);
200
207
  taskContextState = taskContext.exportState();
201
208
  taskContextRevision = taskContext.revision;
@@ -13,6 +13,7 @@ export interface TaskContextServiceOptions {
13
13
  readonly config?: HarnessConfig;
14
14
  readonly revision?: number;
15
15
  readonly requireLocalVerificationReceipt?: boolean;
16
+ readonly captureVerificationWorkspace?: () => string | null;
16
17
  }
17
18
  export interface TaskContextToolInput {
18
19
  readonly name: string;
@@ -69,6 +70,8 @@ export interface TaskContextService {
69
70
  observeAppliedSkills(skills: TaskContextAppliedSkill[]): void;
70
71
  checkToolUse(input: TaskContextToolInput): DeepReadonly<DriftCheckResult>;
71
72
  observeToolResult(input: TaskContextToolResultInput): void;
73
+ observeVerificationWorkspace(fingerprint: string | null): void;
74
+ refreshVerificationWorkspace(capture?: () => string | null): void;
72
75
  noteIndeterminateWorkspaceChange(): void;
73
76
  observeTurn(input: TaskContextTurnInput): DeepReadonly<TurnSummary> | undefined;
74
77
  activeTaskTodo(): string | undefined;
@@ -77,7 +80,7 @@ export interface TaskContextService {
77
80
  prepareTaskPlanStopCheck(): ReturnType<HarnessKernel['prepareTaskPlanStopCheck']>;
78
81
  requiresVerification(): boolean;
79
82
  recordTaskTodoReceipt(step: string, observation: TaskTodoObservation): void;
80
- updateTaskTodos(todos: NonNullable<HarnessState['taskTodos']>): string | undefined;
83
+ updateTaskTodos(todos: NonNullable<HarnessState['taskTodos']>, blockedReason?: string): string | undefined;
81
84
  progressState(): HarnessProgressState;
82
85
  recordProgress(baseline: HarnessProgressState, unconfirmedWorkspaceRevisions?: number): void;
83
86
  auditCompletion(enforceTaskTodos?: boolean, requireEveryCriterion?: boolean): TaskContextCompletionDecisionV1;
@@ -90,6 +93,7 @@ export interface TaskContextService {
90
93
  getCapsule(): DeepReadonly<ContextCapsule> | undefined;
91
94
  explain(): TaskContextExplanation;
92
95
  snapshot(): DeepReadonly<TaskContextSnapshotV1>;
96
+ restoreGoalCheckpoint(state: HarnessState, revision: number): void;
93
97
  /** Mutable clone intended for the future atomic TurnCommit owner. */
94
98
  exportState(): HarnessState;
95
99
  }
@@ -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,6 +39,7 @@ 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
  }
39
45
  classifyIntent(input) {
@@ -57,6 +63,14 @@ class HarnessKernelTaskContextService {
57
63
  observeToolResult(input) {
58
64
  this.mutate(() => this.kernel.recordToolResult(input));
59
65
  }
66
+ observeVerificationWorkspace(fingerprint) {
67
+ this.mutate(() => this.kernel.observeVerificationWorkspace(fingerprint));
68
+ }
69
+ refreshVerificationWorkspace(capture = this.captureVerificationWorkspace) {
70
+ if (capture && this.kernel.hasCurrentWorkspaceVerification(true)) {
71
+ this.observeVerificationWorkspace(capture());
72
+ }
73
+ }
60
74
  noteIndeterminateWorkspaceChange() {
61
75
  this.mutate(() => this.kernel.noteIndeterminateWorkspaceChange());
62
76
  }
@@ -82,8 +96,10 @@ class HarnessKernelTaskContextService {
82
96
  recordTaskTodoReceipt(step, observation) {
83
97
  this.mutate(() => this.kernel.recordTaskTodoReceipt(step, observation));
84
98
  }
85
- updateTaskTodos(todos) {
86
- return this.mutate(() => this.kernel.updateTaskTodos(todos));
99
+ updateTaskTodos(todos, blockedReason) {
100
+ if (todos.some(todo => todo.status === 'completed'))
101
+ this.refreshVerificationWorkspace();
102
+ return this.mutate(() => this.kernel.updateTaskTodos(todos, blockedReason));
87
103
  }
88
104
  progressState() {
89
105
  return this.kernel.progressState();
@@ -92,6 +108,7 @@ class HarnessKernelTaskContextService {
92
108
  this.mutate(() => this.kernel.recordProgress(baseline, unconfirmedWorkspaceRevisions));
93
109
  }
94
110
  auditCompletion(enforceTaskTodos = false, requireEveryCriterion = false) {
111
+ this.refreshVerificationWorkspace();
95
112
  const result = this.mutate(() => this.kernel.beforeComplete(enforceTaskTodos, requireEveryCriterion));
96
113
  return immutableClone({
97
114
  ...result,
@@ -139,6 +156,18 @@ class HarnessKernelTaskContextService {
139
156
  exportState() {
140
157
  return structuredClone(this.kernel.toJSON());
141
158
  }
159
+ restoreGoalCheckpoint(state, revision) {
160
+ const counts = this.kernel.progressState().progressCountedByReason;
161
+ this.kernel = this.createKernel({
162
+ ...state,
163
+ progressState: {
164
+ schemaVersion: 1,
165
+ ...state.progressState,
166
+ ...(counts ? { progressCountedByReason: counts } : {}),
167
+ },
168
+ });
169
+ this.revisionValue = Math.max(this.revisionValue, revision) + 1;
170
+ }
142
171
  mutate(operation) {
143
172
  const before = this.kernel.toJSON().updatedAt;
144
173
  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;