@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
@@ -29,6 +29,9 @@ export type GoalRuntimeControlV2 = {
29
29
  readonly action: 'pause';
30
30
  } | {
31
31
  readonly action: 'resume';
32
+ } | {
33
+ readonly action: 'budget';
34
+ readonly budget: GoalLifecycleBudgetV2;
32
35
  } | {
33
36
  readonly action: 'clear';
34
37
  };
@@ -48,8 +51,6 @@ export interface GoalRuntimeCoordinatorOptionsV2 {
48
51
  readonly continuation?: 'agent' | 'manual';
49
52
  readonly defaultBudget?: GoalLifecycleBudgetV2;
50
53
  }
51
- /** Total resource bounds for newly created Goals, independent of per-turn checkpoints. */
52
- export declare const DEFAULT_GOAL_RUNTIME_BUDGET_V2: GoalLifecycleBudgetV2;
53
54
  export interface GoalRuntimeCommitFieldsV2 {
54
55
  readonly goalState?: GoalRuntimePersistedStateV2;
55
56
  readonly stopDecision?: StopDecision;
@@ -95,11 +96,13 @@ export declare class GoalRuntimeCoordinatorV2 {
95
96
  control(control: GoalRuntimeControlV2, turnId: string, persist?: GoalRuntimePersistTurnV2): GoalRuntimeControlResultV2;
96
97
  resume(): GoalLifecycleStateV2 | undefined;
97
98
  markTurnStarted(turnId: string, startedAt?: number, existingEvidenceRefs?: readonly string[]): void;
99
+ /** Deadline for the active turn based on persisted elapsed time. */
100
+ deadlineAt(turnId: string): number | undefined;
98
101
  /**
99
102
  * Finalize Goal state and persist it with transcript/TaskContext in one TurnCommit.
100
103
  * The persist callback must synchronously return the authoritative durable receipt.
101
104
  */
102
- commitTurn(turn: AgentLoopTurnCommitV1, persist: GoalRuntimePersistTurnV2): GoalRuntimeDurableReceiptV2;
105
+ commitTurn(turn: AgentLoopTurnCommitV1, persist: GoalRuntimePersistTurnV2, goalTurn?: boolean): GoalRuntimeDurableReceiptV2;
103
106
  /** Release an autonomous continuation only after ThreadRuntime commits the turn terminal. */
104
107
  afterDurableTerminal(turnId: string, terminal: TurnCommitV1['terminal']): (ThreadTurnRequestV1 & {
105
108
  readonly mode: 'goal';
@@ -1,17 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GoalRuntimeCoordinatorV2 = exports.DEFAULT_GOAL_RUNTIME_BUDGET_V2 = void 0;
3
+ exports.GoalRuntimeCoordinatorV2 = void 0;
4
4
  exports.readGoalRuntimePersistenceV2 = readGoalRuntimePersistenceV2;
5
5
  exports.recoverInterruptedGoalState = recoverInterruptedGoalState;
6
6
  const stop_decision_1 = require("../framework/stop-decision");
7
7
  const verification_1 = require("../harness/verification");
8
8
  const goal_lifecycle_v2_1 = require("./goal-lifecycle-v2");
9
9
  const canonical_1 = require("./protocol/canonical");
10
- /** Total resource bounds for newly created Goals, independent of per-turn checkpoints. */
11
- exports.DEFAULT_GOAL_RUNTIME_BUDGET_V2 = Object.freeze({
12
- maxTokens: 1000000,
13
- maxElapsedMs: 2 * 60 * 60 * 1000,
14
- });
15
10
  /** Validate and expose the Goal fact owned by an authoritative TurnCommit. */
16
11
  function readGoalRuntimePersistenceV2(commit) {
17
12
  return deepFreeze(structuredClone(parseGoalPersistence(commit)));
@@ -34,7 +29,8 @@ class GoalRuntimeCoordinatorV2 {
34
29
  this.clock = options.clock ?? Date.now;
35
30
  this.continuationInput = options.continuationInput ?? defaultContinuationInput;
36
31
  this.continuation = options.continuation ?? 'agent';
37
- this.defaultBudget = options.defaultBudget ?? exports.DEFAULT_GOAL_RUNTIME_BUDGET_V2;
32
+ this.defaultBudget = { ...options.defaultBudget };
33
+ (0, goal_lifecycle_v2_1.validateGoalBudget)(this.defaultBudget);
38
34
  const restored = parseGoalPersistence(options.restoredCommit);
39
35
  this.tombstoneValue = restored.tombstone;
40
36
  const definition = restored.state
@@ -48,7 +44,7 @@ class GoalRuntimeCoordinatorV2 {
48
44
  : options.definition;
49
45
  if (definition)
50
46
  this.lifecycle = createLifecycle(definition, this.clock);
51
- this.restoredContinuationAvailable = Boolean(restored.state?.status === 'active' && options.restoredCommit?.terminal === 'completed');
47
+ this.restoredContinuationAvailable = restored.state?.status === 'active';
52
48
  }
53
49
  get state() {
54
50
  return this.lifecycle?.state;
@@ -96,9 +92,15 @@ class GoalRuntimeCoordinatorV2 {
96
92
  message = 'Goal objective must not be empty.';
97
93
  break;
98
94
  }
95
+ if ((control.budget?.maxTokens ?? 0) > (this.defaultBudget.maxTokens ?? Infinity) ||
96
+ (control.budget?.maxElapsedMs ?? 0) > (this.defaultBudget.maxElapsedMs ?? Infinity)) {
97
+ accepted = false;
98
+ message = 'Requested Goal budget exceeds the configured ceiling.';
99
+ break;
100
+ }
99
101
  candidate = createLifecycle({
100
102
  objective,
101
- budget: control.budget ?? this.defaultBudget,
103
+ budget: { ...this.defaultBudget, ...control.budget },
102
104
  }, this.clock);
103
105
  tombstone = undefined;
104
106
  scheduleContinuation = true;
@@ -126,16 +128,34 @@ class GoalRuntimeCoordinatorV2 {
126
128
  break;
127
129
  }
128
130
  candidate = createLifecycleFromState(current, this.clock);
129
- if (current.status === 'paused')
130
- candidate.resume();
131
- else if (current.status !== 'active')
132
- accepted = false;
133
- if (candidate.state.status !== 'active')
134
- accepted = false;
135
- scheduleContinuation = accepted && candidate.state.status === 'active';
131
+ const resumed = candidate.resume();
132
+ accepted = current.status !== 'active' && resumed.status === 'active';
133
+ scheduleContinuation = accepted;
136
134
  message = accepted
137
135
  ? 'Goal resumed.'
138
- : `Goal cannot resume from ${current.status}; inspect its persisted budget and stop reason. An exhausted budget requires clearing and explicitly creating a new Goal with an appropriate total budget.`;
136
+ : resumed.status === 'budget_limited'
137
+ ? 'Goal budget is exhausted. Increase its total with /goal budget before resuming.'
138
+ : `Goal cannot resume from ${resumed.status}.`;
139
+ break;
140
+ }
141
+ case 'budget': {
142
+ if (!current) {
143
+ accepted = false;
144
+ message = 'No Goal exists to update.';
145
+ break;
146
+ }
147
+ candidate = createLifecycleFromState(current, this.clock);
148
+ try {
149
+ const updated = candidate.updateBudget(control.budget, this.defaultBudget);
150
+ message =
151
+ updated.status === 'budget_limited'
152
+ ? 'Goal budget updated. A resource is still exhausted.'
153
+ : 'Goal budget updated. Use /goal resume when ready.';
154
+ }
155
+ catch (error) {
156
+ accepted = false;
157
+ message = error instanceof Error ? error.message : String(error);
158
+ }
139
159
  break;
140
160
  }
141
161
  case 'clear': {
@@ -189,21 +209,45 @@ class GoalRuntimeCoordinatorV2 {
189
209
  this.turnStartedAt.set(turnId, startedAt);
190
210
  this.turnEvidenceAtStart.set(turnId, new Set(existingEvidenceRefs));
191
211
  }
212
+ /** Deadline for the active turn based on persisted elapsed time. */
213
+ deadlineAt(turnId) {
214
+ const state = this.state;
215
+ const startedAt = this.turnStartedAt.get(turnId);
216
+ if (this.closed || state?.status !== 'active' || startedAt === undefined)
217
+ return undefined;
218
+ const limit = state.budget.maxElapsedMs;
219
+ if (limit === undefined)
220
+ return undefined;
221
+ const remainingMs = Math.max(0, limit - state.elapsedMs);
222
+ return Math.min(Number.MAX_SAFE_INTEGER, startedAt + remainingMs);
223
+ }
192
224
  /**
193
225
  * Finalize Goal state and persist it with transcript/TaskContext in one TurnCommit.
194
226
  * The persist callback must synchronously return the authoritative durable receipt.
195
227
  */
196
- commitTurn(turn, persist) {
228
+ commitTurn(turn, persist, goalTurn = true) {
197
229
  if (this.closed)
198
230
  throw new Error('Closed Goal runtime cannot commit a turn.');
199
231
  const requestDecision = requestDecisionForGoal(turn);
200
- if (!this.lifecycle) {
232
+ if (!this.lifecycle || !goalTurn) {
233
+ const state = this.lifecycle?.state;
234
+ const saved = state ?? this.tombstoneValue;
201
235
  const receipt = persist({
202
- ...(this.tombstoneValue ? { goalState: this.tombstoneValue } : {}),
236
+ ...(saved ? { goalState: saved } : {}),
203
237
  ...(requestDecision ? { stopDecision: requestDecision } : {}),
204
238
  });
205
- if (this.tombstoneValue) {
206
- assertPersistedStateReceipt(this.tombstoneValue, requestDecision, receipt);
239
+ if (saved)
240
+ assertPersistedStateReceipt(saved, requestDecision, receipt);
241
+ if (state?.status === 'active') {
242
+ if (receipt.turnId !== turn.turnId)
243
+ throw new Error('Goal TurnCommit receipt has a different turnId.');
244
+ // Thread admission may have preferred a queued user turn over the last
245
+ // continuation. Offer it again at this turn's durable idle boundary.
246
+ this.restoredContinuationAvailable = false;
247
+ this.pendingContinuations.set(turn.turnId, {
248
+ terminal: receipt.terminal,
249
+ request: this.createContinuationRequest(state),
250
+ });
207
251
  }
208
252
  return receipt;
209
253
  }
@@ -247,7 +291,7 @@ class GoalRuntimeCoordinatorV2 {
247
291
  afterDurableTerminal(turnId, terminal) {
248
292
  const pending = this.pendingContinuations.get(turnId);
249
293
  this.pendingContinuations.delete(turnId);
250
- if (this.closed || !pending || pending.terminal !== terminal || terminal !== 'completed') {
294
+ if (this.closed || !pending || pending.terminal !== terminal) {
251
295
  return undefined;
252
296
  }
253
297
  return pending.request;
@@ -298,23 +342,35 @@ class GoalRuntimeCoordinatorV2 {
298
342
  const failed = turn.queryComplete.stats?.finishReason === 'failed';
299
343
  const aborted = turn.queryComplete.stats?.finishReason === 'cancelled';
300
344
  const providerFailure = isProviderFailureDecision(requestDecision);
345
+ const goalBudgetStopped = (0, goal_lifecycle_v2_1.isGoalBudgetStopReason)(requestDecision?.reason.code);
346
+ const boundaryBlocked = requestDecision?.status === 'blocked' ||
347
+ requestDecision?.reason.code === 'provider_preflight_budget' ||
348
+ turn.queryComplete.stats?.finishReason === 'compact_paused';
301
349
  // A checklist deferral can stop before the first provider request.
302
350
  const taskPlanStoppedBeforeRequests = (0, goal_lifecycle_v2_1.isTaskPlanStopDecision)(requestDecision) &&
303
351
  turn.queryComplete.stats?.llmRequests === 0 &&
304
352
  subagentTokens === 0;
305
- const accountingFailure = usage || aborted || (failed && providerFailure) || taskPlanStoppedBeforeRequests
353
+ const accountingFailure = this.lifecycle?.state.budget.maxTokens === undefined ||
354
+ usage ||
355
+ aborted ||
356
+ goalBudgetStopped ||
357
+ boundaryBlocked ||
358
+ (failed && providerFailure) ||
359
+ taskPlanStoppedBeforeRequests
306
360
  ? undefined
307
361
  : 'Goal usage accounting is unavailable; autonomous continuation is stopped fail-closed.';
308
362
  const runtimeFailure = failed && !providerFailure
309
363
  ? turn.queryComplete.content || 'Goal turn failed before a complete durable observation.'
310
364
  : undefined;
311
- const blocked = requestDecision?.status === 'blocked' ? requestDecision.reason.message : undefined;
365
+ const blocked = boundaryBlocked ? requestDecision?.reason.message : undefined;
312
366
  return {
313
367
  ...(requestDecision ? { requestDecision } : {}),
314
368
  ...(turn.taskContextCompletion ? { taskContextCompletion: turn.taskContextCompletion } : {}),
315
369
  madeProgress: madeProgress(turn),
316
370
  continuationMode: this.continuation,
317
- ...(turn.queryComplete.stats?.finishReason === 'budget_exceeded'
371
+ ...(turn.queryComplete.stats?.finishReason === 'budget_exceeded' &&
372
+ !goalBudgetStopped &&
373
+ !boundaryBlocked
318
374
  ? {
319
375
  checkpoint: checkpointEvidence(turn, startedAt, now, this.lifecycle?.state, this.turnEvidenceAtStart.get(turn.turnId)),
320
376
  }
@@ -367,7 +423,11 @@ function parseGoalPersistence(commit) {
367
423
  }
368
424
  const state = persisted;
369
425
  (0, goal_lifecycle_v2_1.assertGoalLifecycleStateV2)(state);
370
- return { state };
426
+ return {
427
+ state: state.status === 'paused' && (0, goal_lifecycle_v2_1.isGoalBudgetStopReason)(state.lastStopDecision?.reason.code)
428
+ ? createLifecycleFromState(state, Date.now).state
429
+ : state,
430
+ };
371
431
  }
372
432
  /** Keep a crashed Goal's saved budget and require a deliberate resume. */
373
433
  function recoverInterruptedGoalState(commit) {
@@ -402,7 +462,9 @@ function requestDecisionForGoal(turn) {
402
462
  ],
403
463
  nextActions: [{ kind: 'resume', label: 'Resume after provider recovery.' }],
404
464
  resources: {
465
+ ...current?.resources,
405
466
  llmRequests: { used: stats?.llmRequests ?? 0 },
467
+ toolCalls: { used: stats?.toolCalls ?? 0 },
406
468
  tokens: {
407
469
  used: (turn.queryComplete.usage?.promptTokens ?? 0) +
408
470
  (turn.queryComplete.usage?.completionTokens ?? 0),
@@ -440,15 +502,7 @@ function checkpointEvidence(turn, startedAt, now, previous, existingEvidenceRefs
440
502
  metadata.recordedAt <= now);
441
503
  })
442
504
  .map(entry => entry.id);
443
- return {
444
- unfinishedPlan: turn.taskContextState.taskTodos?.some(todo => todo.status !== 'completed') === true ||
445
- (turn.taskContextState.ledger.some(entry => entry.type === 'todo')
446
- ? (turn.taskContextState.capsule?.currentPlan.some(step => step.status !== 'completed') ??
447
- false)
448
- : (turn.taskContextState.contract?.criteria?.some(criterion => criterion.status !== 'passed' &&
449
- !(criterion.status === 'waived' && criterion.waiver?.authorizedBy === 'user')) ?? false)),
450
- verificationRefs,
451
- };
505
+ return { verificationRefs };
452
506
  }
453
507
  function isProviderFailureDecision(decision) {
454
508
  return Boolean(decision &&
@@ -32,7 +32,9 @@ function formatGoalRuntimeEvent(event) {
32
32
  case 'goal_restored':
33
33
  return `Goal restored ${event.goal.status}: ${event.goal.objective}`;
34
34
  case 'goal_updated':
35
- return `Goal ${event.goal.status}: ${event.goal.objective}`;
35
+ return event.goal.stopReason && event.goal.status !== 'complete'
36
+ ? `Goal ${event.goal.status}: ${event.goal.stopReason}`
37
+ : `Goal ${event.goal.status}: ${event.goal.objective}`;
36
38
  case 'goal_completed':
37
39
  return `Goal complete: ${event.goal.objective} | ${completionDetails(event)}`;
38
40
  case 'goal_audit_failed':
@@ -264,6 +264,7 @@ export interface RuntimeGoalSnapshot {
264
264
  objective: string;
265
265
  status: GoalStatus;
266
266
  tokenBudget?: number;
267
+ timeBudgetMs?: number;
267
268
  tokensUsed: number;
268
269
  timeUsedMs: number;
269
270
  continuationCount: number;
@@ -414,9 +415,6 @@ export declare const GOAL_INVARIANTS: {
414
415
  readonly maxConsecutiveNoProgressTurns: 3;
415
416
  /** Two blocked autonomous loops are enough to stop and ask for review. */
416
417
  readonly maxConsecutiveBlockedContinuationTurns: 2;
417
- readonly maxAutonomousLlmRequestsPerTurn: 8;
418
- readonly maxAutonomousToolCallsPerTurn: 32;
419
- readonly maxAutonomousModelVisibleBytesPerTurn: number;
420
418
  readonly tokenBudgetMin: 1;
421
419
  };
422
420
  //# sourceMappingURL=types.d.ts.map
@@ -75,9 +75,6 @@ exports.GOAL_INVARIANTS = {
75
75
  maxConsecutiveNoProgressTurns: 3,
76
76
  /** Two blocked autonomous loops are enough to stop and ask for review. */
77
77
  maxConsecutiveBlockedContinuationTurns: 2,
78
- maxAutonomousLlmRequestsPerTurn: 8,
79
- maxAutonomousToolCallsPerTurn: 32,
80
- maxAutonomousModelVisibleBytesPerTurn: 32 * 1024,
81
78
  tokenBudgetMin: 1,
82
79
  };
83
80
  //# sourceMappingURL=types.js.map
@@ -2,11 +2,4 @@ import { type LoopBudget } from '../framework/loop-budget-contract';
2
2
  import type { OrionCodeCLIConfig } from '../services/config';
3
3
  import type { HarnessState } from '../harness/types';
4
4
  export declare function resolveRuntimeLoopBudget(input: string, config: Pick<OrionCodeCLIConfig, 'agentLoop'>, harnessState?: Pick<HarnessState, 'rootObjective' | 'activeInstruction' | 'contract' | 'capsule'>): LoopBudget;
5
- /**
6
- * Autonomous Goal continuations have no fresh human decision boundary. Cap
7
- * each one even when task heuristics or config select a larger loop profile.
8
- */
9
- export declare function capAutonomousGoalLoopBudget(budget: LoopBudget): LoopBudget;
10
- /** Resolve a continuation from config only; model-authored Goal text must not promote its profile. */
11
- export declare function resolveAutonomousGoalLoopBudget(config: Pick<OrionCodeCLIConfig, 'agentLoop'>): LoopBudget;
12
5
  //# sourceMappingURL=loop-budget.d.ts.map
@@ -1,35 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveRuntimeLoopBudget = resolveRuntimeLoopBudget;
4
- exports.capAutonomousGoalLoopBudget = capAutonomousGoalLoopBudget;
5
- exports.resolveAutonomousGoalLoopBudget = resolveAutonomousGoalLoopBudget;
6
4
  const loop_budget_contract_1 = require("../framework/loop-budget-contract");
7
- const types_1 = require("./goals/types");
8
- const COMPLEX_TASK_LLM_BUDGET = 48;
9
- const RELEASE_TASK_LLM_BUDGET = 64;
10
- const COMPLEX_TASK_TOOL_BUDGET = 180;
11
- const RELEASE_TASK_TOOL_BUDGET = 240;
12
5
  const COMPLEX_TASK_MODEL_VISIBLE_BYTES = 96 * 1024;
13
6
  const RELEASE_TASK_MODEL_VISIBLE_BYTES = 128 * 1024;
14
- function toBaseProfile(value) {
15
- return value === 'complex' || value === 'release' ? value : 'default';
16
- }
17
- function applyConfigOverrides(budget, overrides) {
18
- const numericOverrides = Object.fromEntries(Object.entries(overrides?.budget ?? {}).filter(([, value]) => typeof value === 'number' && Number.isFinite(value) && value > 0));
19
- const requestPolicy = overrides?.budgetPolicy === 'fixed' || numericOverrides.maxLlmRequestsPerUserTurn !== undefined
20
- ? 'fixed'
21
- : 'adaptive';
22
- if (Object.keys(numericOverrides).length === 0)
23
- return { ...budget, requestPolicy };
24
- return {
25
- ...budget,
26
- ...numericOverrides,
27
- requestPolicy,
28
- profile: 'config',
29
- baseProfile: budget.baseProfile ?? toBaseProfile(budget.profile),
30
- configOverride: true,
31
- };
32
- }
33
7
  function looksLikeReleaseTask(input) {
34
8
  return (/(?<![\p{L}\p{N}_])(?:push|pull request|pr|publish|release|npm publish|prepublish)(?![\p{L}\p{N}_])/iu.test(input) || /(发布|发版|提交|推送)/.test(input));
35
9
  }
@@ -41,12 +15,7 @@ function looksLikeComplexTask(input) {
41
15
  /(开发|实现|重构|迁移|优化|修复|完成|完整|复杂|大任务|大的任务|大型任务|大规模|长任务|长期任务|多步骤|检查|审查|按计划|执行计划|继续)/.test(normalized));
42
16
  }
43
17
  function resolveRuntimeLoopBudget(input, config, harnessState) {
44
- let budget = {
45
- ...loop_budget_contract_1.DEFAULT_LOOP_BUDGET,
46
- profile: 'default',
47
- baseProfile: 'default',
48
- configOverride: false,
49
- };
18
+ let budget = { ...loop_budget_contract_1.DEFAULT_LOOP_BUDGET };
50
19
  const taskSegments = [
51
20
  input,
52
21
  harnessState?.rootObjective,
@@ -58,8 +27,6 @@ function resolveRuntimeLoopBudget(input, config, harnessState) {
58
27
  if (taskSegments.some(looksLikeReleaseTask)) {
59
28
  budget = {
60
29
  ...budget,
61
- maxLlmRequestsPerUserTurn: RELEASE_TASK_LLM_BUDGET,
62
- maxToolCallsPerUserTurn: RELEASE_TASK_TOOL_BUDGET,
63
30
  maxModelVisibleToolBytes: RELEASE_TASK_MODEL_VISIBLE_BYTES,
64
31
  profile: 'release',
65
32
  baseProfile: 'release',
@@ -68,30 +35,17 @@ function resolveRuntimeLoopBudget(input, config, harnessState) {
68
35
  else if (taskSegments.some(looksLikeComplexTask)) {
69
36
  budget = {
70
37
  ...budget,
71
- maxLlmRequestsPerUserTurn: COMPLEX_TASK_LLM_BUDGET,
72
- maxToolCallsPerUserTurn: COMPLEX_TASK_TOOL_BUDGET,
73
38
  maxModelVisibleToolBytes: COMPLEX_TASK_MODEL_VISIBLE_BYTES,
74
39
  profile: 'complex',
75
40
  baseProfile: 'complex',
76
41
  };
77
42
  }
78
- return applyConfigOverrides(budget, config.agentLoop);
79
- }
80
- /**
81
- * Autonomous Goal continuations have no fresh human decision boundary. Cap
82
- * each one even when task heuristics or config select a larger loop profile.
83
- */
84
- function capAutonomousGoalLoopBudget(budget) {
85
- return {
86
- ...budget,
87
- requestPolicy: 'fixed',
88
- maxLlmRequestsPerUserTurn: Math.min(budget.maxLlmRequestsPerUserTurn, types_1.GOAL_INVARIANTS.maxAutonomousLlmRequestsPerTurn),
89
- maxToolCallsPerUserTurn: Math.min(budget.maxToolCallsPerUserTurn, types_1.GOAL_INVARIANTS.maxAutonomousToolCallsPerTurn),
90
- maxModelVisibleToolBytes: Math.min(budget.maxModelVisibleToolBytes, types_1.GOAL_INVARIANTS.maxAutonomousModelVisibleBytesPerTurn),
91
- };
92
- }
93
- /** Resolve a continuation from config only; model-authored Goal text must not promote its profile. */
94
- function resolveAutonomousGoalLoopBudget(config) {
95
- return capAutonomousGoalLoopBudget(resolveRuntimeLoopBudget('', config));
43
+ const maxModelVisibleToolBytes = config.agentLoop?.budget?.maxModelVisibleToolBytes;
44
+ if (typeof maxModelVisibleToolBytes === 'number' &&
45
+ Number.isSafeInteger(maxModelVisibleToolBytes) &&
46
+ maxModelVisibleToolBytes > 0) {
47
+ return { ...budget, maxModelVisibleToolBytes, profile: 'config', configOverride: true };
48
+ }
49
+ return budget;
96
50
  }
97
51
  //# sourceMappingURL=loop-budget.js.map
@@ -4,6 +4,7 @@ exports.OrionRuntimeV1 = exports.OrionRuntimeV1Error = void 0;
4
4
  exports.createOrionRuntimeV1 = createOrionRuntimeV1;
5
5
  const fs_1 = require("fs");
6
6
  const path_1 = require("path");
7
+ const paths_1 = require("../product/paths");
7
8
  const task_checklist_1 = require("../harness/task-checklist");
8
9
  const file_lock_1 = require("../services/file-lock");
9
10
  const agent_loop_1 = require("./agent-loop");
@@ -28,6 +29,7 @@ const task_context_service_1 = require("./task-context-service");
28
29
  const thread_event_store_1 = require("./thread-event-store");
29
30
  const thread_runtime_1 = require("./thread-runtime");
30
31
  const thread_tool_journal_1 = require("./thread-tool-journal");
32
+ const workspace_verification_1 = require("./workspace-verification");
31
33
  const tool_gateway_1 = require("./tool-gateway");
32
34
  const turn_commit_1 = require("./turn-commit");
33
35
  class OrionRuntimeV1Error extends Error {
@@ -319,13 +321,25 @@ class OrionRuntimeV1 {
319
321
  ? startupProjection.turns[startupProjection.activeTurnId]
320
322
  : undefined;
321
323
  const previousCommit = restoreLatestTurnCommit(eventStore);
322
- const taskOptions = mergeTaskContextOptions(this.options.taskContext, previousCommit);
324
+ const captureWorkspace = () => (0, workspace_verification_1.captureVerificationWorkspace)(this.options.taskContext.cwd, [
325
+ (0, paths_1.getConfigDir)(),
326
+ this.options.eventStore.rootDir,
327
+ ]);
328
+ const taskOptions = {
329
+ ...mergeTaskContextOptions(this.options.taskContext, previousCommit),
330
+ captureVerificationWorkspace: captureWorkspace,
331
+ };
323
332
  const recovered = (0, task_context_recovery_1.recoverInterruptedTaskContext)({
324
333
  store: eventStore,
325
334
  previousCommit,
326
335
  taskOptions,
327
336
  loadImportedHistory: this.options.loadImportedHistory,
328
- restoreGoalState: () => (0, goal_runtime_coordinator_1.recoverInterruptedGoalState)(previousCommit),
337
+ restoreGoalState: () => {
338
+ if (orphan?.mode === 'goal')
339
+ return (0, goal_runtime_coordinator_1.recoverInterruptedGoalState)(previousCommit);
340
+ const saved = (0, goal_runtime_coordinator_1.readGoalRuntimePersistenceV2)(previousCommit);
341
+ return saved.state ?? saved.tombstone;
342
+ },
329
343
  });
330
344
  const restored = recovered ?? previousCommit;
331
345
  const taskContext = (0, task_context_service_1.createTaskContextService)({
@@ -366,7 +380,9 @@ class OrionRuntimeV1 {
366
380
  },
367
381
  });
368
382
  const todoCatalog = this.options.enableTaskTodos
369
- ? (0, builtin_tool_provider_1.createBuiltinToolCatalogV1)([(0, todo_1.createTodoWriteTool)(todos => taskContext.updateTaskTodos(todos))], { context: this.options.toolContext })
383
+ ? (0, builtin_tool_provider_1.createBuiltinToolCatalogV1)([
384
+ (0, todo_1.createTodoWriteTool)((todos, blockedReason) => taskContext.updateTaskTodos(todos, blockedReason)),
385
+ ], { context: this.options.toolContext })
370
386
  : undefined;
371
387
  const basePolicy = new first_party_tool_services_1.FirstPartyToolPolicyServiceV1(this.options.toolCatalog, this.options.toolContext);
372
388
  const todoPolicy = todoCatalog
@@ -403,7 +419,7 @@ class OrionRuntimeV1 {
403
419
  });
404
420
  const approval = new first_party_tool_services_1.FirstPartyToolApprovalServiceV1(this.options.approvalHandler);
405
421
  const sandbox = new first_party_tool_services_1.FirstPartySandboxServiceV1();
406
- const execution = new step_snapshot_1.ExecutionService(this.options.workspaceMutationCoordinator);
422
+ const execution = new step_snapshot_1.ExecutionService(this.options.workspaceMutationCoordinator, captureWorkspace);
407
423
  const toolJournal = new thread_tool_journal_1.ThreadToolInvocationJournalV1(eventStore);
408
424
  const gateway = new tool_gateway_1.ToolGateway({
409
425
  policy,
@@ -540,11 +556,18 @@ class OrionRuntimeV1 {
540
556
  },
541
557
  get remainingGoalTokens() {
542
558
  const state = goal.state;
543
- return state?.status === 'active'
559
+ return activeTurnContext?.mode === 'goal' &&
560
+ state?.status === 'active' &&
561
+ state.budget.maxTokens !== undefined
544
562
  ? Math.max(0, state.budget.maxTokens - state.tokensUsed)
545
563
  : undefined;
546
564
  },
547
- allowBudgetRecovery: true,
565
+ get goalDeadlineAt() {
566
+ return activeTurnContext?.mode === 'goal'
567
+ ? goal.deadlineAt(activeTurnContext.turnId)
568
+ : undefined;
569
+ },
570
+ allowToolPressureCompaction: true,
548
571
  onContextUsage: this.options.loop?.onContextUsage,
549
572
  compactCoordinator: this.options.loop?.compactCoordinator,
550
573
  commitTurn: commit => {
@@ -574,7 +597,7 @@ class OrionRuntimeV1 {
574
597
  ...(prepared?.plan ? { plan: prepared.plan } : {}),
575
598
  });
576
599
  return durableCommit;
577
- });
600
+ }, activeTurnContext?.mode === 'goal');
578
601
  if (!durableCommit) {
579
602
  throw new OrionRuntimeV1Error('ORION_RUNTIME_INVALID_CONFIGURATION', `Turn ${commit.turnId} completed without an authoritative TurnCommit.`);
580
603
  }
@@ -600,6 +623,11 @@ class OrionRuntimeV1 {
600
623
  run: async (context) => {
601
624
  activeTurnContext = context;
602
625
  try {
626
+ const goalId = context.mode === 'goal' ? goal.state?.goalId : undefined;
627
+ if (goalId) {
628
+ restoreGoalTaskCheckpoint(eventStore, taskContext, goalId);
629
+ goal.markTurnStarted(context.turnId, undefined, taskContext.exportState().ledger.map(entry => entry.id));
630
+ }
603
631
  return await agentLoop.run(context);
604
632
  }
605
633
  finally {
@@ -610,10 +638,6 @@ class OrionRuntimeV1 {
610
638
  maintenanceRunner: compactRunner,
611
639
  projectPath: this.options.projectPath,
612
640
  requireTurnCommit: true,
613
- onTurnStarted: turn => {
614
- goal.markTurnStarted(turn.turnId, turn.startedAt, taskContext.exportState().ledger.map(entry => entry.id));
615
- this.options.thread?.onTurnStarted?.(turn);
616
- },
617
641
  onTurnDurablyTerminal: terminal => goal.afterDurableTerminal(terminal.turnId, terminal.terminal) ??
618
642
  this.options.thread?.onTurnDurablyTerminal?.(terminal),
619
643
  onTurnSettled: async (turnId) => {
@@ -700,9 +724,11 @@ class OrionRuntimeV1 {
700
724
  ? eventStore.loadProjection().turns[restored.turnId]
701
725
  : undefined;
702
726
  if (!this.closeRequested &&
703
- !(orphan && orphan.mode !== 'maintenance' && !orphan.commit) &&
704
- restoredTurn?.status === 'completed' &&
705
- eventStore.loadProjection().queue.length === 0) {
727
+ !(orphan?.mode === 'goal' && !orphan.commit) &&
728
+ restoredTurn?.status === restored?.terminal &&
729
+ restoredTurn !== undefined &&
730
+ !thread.getAdmissionSnapshot().activeTurn &&
731
+ thread.getAdmissionSnapshot().queue.length === 0) {
706
732
  const continuation = goal.takeRestoredContinuation();
707
733
  if (continuation)
708
734
  thread.startGoalContinuation(continuation);
@@ -986,6 +1012,21 @@ function parseTaskContextState(commit) {
986
1012
  invalidConfiguration('Durable TurnCommit TaskContext is not valid JSON.');
987
1013
  }
988
1014
  }
1015
+ function restoreGoalTaskCheckpoint(store, taskContext, goalId) {
1016
+ if (taskContext.exportState().goalTaskId === goalId)
1017
+ return;
1018
+ const goalCommits = Object.values(store.loadProjection().turns)
1019
+ .flatMap(turn => (turn.mode === 'goal' && turn.commit ? [turn.commit] : []))
1020
+ .sort((left, right) => right.seq - left.seq);
1021
+ for (const saved of goalCommits) {
1022
+ const commit = (0, turn_commit_1.parseTurnCommitV1)(saved.receipt);
1023
+ const state = parseTaskContextState(commit);
1024
+ if (state.goalTaskId !== goalId)
1025
+ continue;
1026
+ taskContext.restoreGoalCheckpoint(state, commit.taskContextRevision);
1027
+ return;
1028
+ }
1029
+ }
989
1030
  async function loadRuntimeBaseMessages(compact, configured) {
990
1031
  const authoritative = compact.loadModelVisibleHistory();
991
1032
  const configuredMessages = configured ? await configured : undefined;
@@ -15,7 +15,6 @@ const token_estimate_1 = require("../utils/token-estimate");
15
15
  const debug_log_1 = require("../utils/debug-log");
16
16
  const paths_1 = require("../product/paths");
17
17
  const builtin_tool_provider_1 = require("./builtin-tool-provider");
18
- const goal_runtime_coordinator_1 = require("./goal-runtime-coordinator");
19
18
  const loop_budget_1 = require("./loop-budget");
20
19
  const legacy_thread_materializer_1 = require("./legacy-thread-materializer");
21
20
  const orion_runtime_v1_1 = require("./orion-runtime-v1");
@@ -89,10 +88,7 @@ function createProductOrionRuntimeV1(options, sessionId, activation) {
89
88
  ...(goalSeed ? { goal: goalSeed } : {}),
90
89
  goalPolicy: {
91
90
  continuation: options.config.agentLoop?.continuation ?? 'agent',
92
- defaultBudget: {
93
- ...goal_runtime_coordinator_1.DEFAULT_GOAL_RUNTIME_BUDGET_V2,
94
- ...options.config.agentLoop?.goalBudget,
95
- },
91
+ defaultBudget: options.config.agentLoop?.goalBudget,
96
92
  },
97
93
  skills: { providers: [...(options.skillProviders ?? [])] },
98
94
  mcp: {
@@ -539,10 +535,9 @@ function loadProductGoalSeed(projectPath, sessionId) {
539
535
  throw new Error(`Cannot start Goal runtime: ${loaded.message}`);
540
536
  }
541
537
  const legacy = loaded.value;
542
- const status = legacy.status === 'active' ? 'active' : legacy.status === 'complete' ? 'completed' : 'paused';
538
+ const status = legacy.status === 'complete' ? 'completed' : legacy.status;
543
539
  const budget = {
544
- maxTokens: legacy.tokenBudget ?? Number.MAX_SAFE_INTEGER,
545
- maxElapsedMs: Number.MAX_SAFE_INTEGER,
540
+ ...(legacy.tokenBudget == null ? {} : { maxTokens: legacy.tokenBudget }),
546
541
  };
547
542
  const content = {
548
543
  version: 2,
@@ -580,8 +575,8 @@ function buildGoalRuntimeContext(state) {
580
575
  `- Status: ${state.status}`,
581
576
  `- Generation: ${state.generation}`,
582
577
  `- Continuations: ${state.continuationCount}`,
583
- `- Tokens: ${state.tokensUsed}/${state.budget.maxTokens}`,
584
- `- Elapsed ms: ${state.elapsedMs}/${state.budget.maxElapsedMs}`,
578
+ `- Tokens: ${state.tokensUsed}/${state.budget.maxTokens ?? 'unlimited'}`,
579
+ `- Elapsed ms: ${state.elapsedMs}/${state.budget.maxElapsedMs ?? 'unlimited'}`,
585
580
  state.status === 'active'
586
581
  ? '- Continue autonomously; only TaskContext may verify completion.'
587
582
  : '- Do not autonomously continue this Goal unless the user explicitly resumes it.',
@@ -593,7 +588,7 @@ async function buildProductMessages(options, sessionId, eventStore, prompts, com
593
588
  const history = durable ?? legacyHistory(sessionId);
594
589
  const withoutOldSystem = history.filter(message => message.role !== 'system');
595
590
  const snapshot = options.store.getSnapshot();
596
- const goalContent = buildGoalRuntimeContext(composition.goal.state);
591
+ const goalContent = mode === 'goal' ? buildGoalRuntimeContext(composition.goal.state) : undefined;
597
592
  const review = projection.planReview;
598
593
  const planReceipt = mode !== 'plan' && review?.status === 'approved'
599
594
  ? (0, plan_review_1.findPlanReceiptForReviewV1)(projection, review)
@@ -98,13 +98,7 @@ async function runArm(task, suite, input, signal) {
98
98
  ],
99
99
  defaultModel: 'rsi-evaluation',
100
100
  subagents: { mode: 'off' },
101
- agentLoop: {
102
- continuation: 'manual',
103
- budget: {
104
- maxLlmRequestsPerUserTurn: suite.maxRequests,
105
- maxToolCallsPerUserTurn: suite.maxTools,
106
- },
107
- },
101
+ agentLoop: { continuation: 'manual' },
108
102
  }));
109
103
  const inputPath = (0, path_1.join)(sandbox, 'input.json');
110
104
  const outputPath = (0, path_1.join)(sandbox, 'arm.json');