@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
@@ -1,14 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GoalLifecycleServiceV2 = void 0;
4
+ exports.isGoalBudgetStopReason = isGoalBudgetStopReason;
4
5
  exports.isTaskPlanStopDecision = isTaskPlanStopDecision;
5
6
  exports.assertGoalLifecycleStateV2 = assertGoalLifecycleStateV2;
7
+ exports.validateGoalBudget = validateGoalBudget;
6
8
  const crypto_1 = require("crypto");
7
9
  const stop_decision_1 = require("../framework/stop-decision");
8
10
  const canonical_1 = require("./protocol/canonical");
9
11
  const runtime_protocol_v1_1 = require("./protocol/runtime-protocol-v1");
10
- const MAX_NO_PROGRESS_TURNS = 3;
11
- const MAX_BLOCKED_CONTINUATIONS = 2;
12
+ const GOAL_BUDGET_RESOURCES = [
13
+ { key: 'maxTokens', used: 'tokensUsed', flag: '--max-tokens', unit: 'tokens' },
14
+ { key: 'maxElapsedMs', used: 'elapsedMs', flag: '--max-elapsed-ms', unit: 'ms' },
15
+ ];
16
+ function isGoalBudgetStopReason(code) {
17
+ return code === 'goal_budget' || code === 'goal_token_budget' || code === 'goal_time_budget';
18
+ }
12
19
  function isTaskPlanStopDecision(decision) {
13
20
  return (decision?.scope === 'request' &&
14
21
  (decision.status === 'stopped' || decision.status === 'blocked') &&
@@ -24,11 +31,20 @@ class GoalLifecycleServiceV2 {
24
31
  this.clock = options.clock ?? Date.now;
25
32
  if (options.state) {
26
33
  assertGoalLifecycleStateV2(options.state);
27
- this.stateValue = deepFreeze(structuredClone(options.state));
34
+ const restored = options.state;
35
+ const decision = restored.lastStopDecision;
36
+ this.stateValue =
37
+ restored.status === 'paused' && decision && isGoalBudgetStopReason(decision.reason.code)
38
+ ? withDigest({
39
+ ...withoutDigest(restored),
40
+ status: 'budget_limited',
41
+ lastStopDecision: goalBudgetDecision(restored, decision.reason.code),
42
+ })
43
+ : deepFreeze(structuredClone(restored));
28
44
  return;
29
45
  }
30
46
  const objective = options.objective.trim();
31
- validateBudget(options.budget);
47
+ validateGoalBudget(options.budget);
32
48
  if (!objective)
33
49
  throw new Error('Goal objective must not be empty');
34
50
  const now = this.clock();
@@ -66,10 +82,20 @@ class GoalLifecycleServiceV2 {
66
82
  const continuationCount = this.stateValue.continuationCount + 1;
67
83
  const noProgressCount = observation.madeProgress ? 0 : this.stateValue.noProgressCount + 1;
68
84
  const blockedCount = observation.blocked ? this.stateValue.blockedCount + 1 : 0;
85
+ const requestReason = observation.requestDecision?.reason;
86
+ const usage = { tokensUsed, elapsedMs, budget: this.stateValue.budget };
87
+ const exhausted = exhaustedGoalBudget(usage);
88
+ const budgetCode = isGoalBudgetStopReason(requestReason?.code)
89
+ ? requestReason?.code
90
+ : exhausted?.key === 'maxTokens'
91
+ ? 'goal_token_budget'
92
+ : exhausted
93
+ ? 'goal_time_budget'
94
+ : undefined;
69
95
  const resourceSnapshot = {
96
+ ...observation.requestDecision?.resources,
70
97
  turns: { used: continuationCount },
71
- tokens: { used: tokensUsed, limit: this.stateValue.budget.maxTokens },
72
- elapsedMs: { used: elapsedMs, limit: this.stateValue.budget.maxElapsedMs },
98
+ ...goalResources(usage),
73
99
  };
74
100
  let status = 'active';
75
101
  let decision;
@@ -84,21 +110,25 @@ class GoalLifecycleServiceV2 {
84
110
  else if (observation.requestDecision?.status === 'failed' &&
85
111
  (observation.requestDecision.disposition === 'resume_allowed' ||
86
112
  isProviderFailure(observation.requestDecision))) {
87
- status = 'paused';
88
- decision = goalDecision('failed', 'pause_scope', observation.requestDecision.disposition === 'resume_allowed'
113
+ const quota = observation.requestDecision.reason.code === 'provider_quota_or_credit_exhausted';
114
+ status = quota ? 'usage_limited' : 'paused';
115
+ decision = goalDecision('failed', 'pause_scope', quota || observation.requestDecision.disposition === 'resume_allowed'
89
116
  ? observation.requestDecision.reason.code
90
117
  : 'provider_failure', observation.requestDecision.reason.message, resourceSnapshot);
91
118
  }
92
- else if (tokensUsed >= this.stateValue.budget.maxTokens ||
93
- elapsedMs >= this.stateValue.budget.maxElapsedMs) {
94
- status = 'paused';
95
- decision = goalDecision('stopped', 'pause_scope', 'goal_budget', 'Goal budget reached. The saved budget cannot be reset by resume; inspect the receipts, then clear and explicitly create a new Goal with an appropriate budget.', resourceSnapshot);
119
+ else if (budgetCode) {
120
+ status = 'budget_limited';
121
+ decision = goalBudgetDecision(usage, budgetCode, resourceSnapshot);
96
122
  }
97
123
  else if (isTaskPlanStopDecision(observation.requestDecision)) {
98
124
  const { code, message } = observation.requestDecision.reason;
99
- status = 'paused';
125
+ status = code === 'task_step_blocked' ? 'blocked' : 'paused';
100
126
  decision = goalDecision(code === 'task_step_blocked' ? 'blocked' : 'stopped', 'pause_scope', code, message, resourceSnapshot);
101
127
  }
128
+ else if (observation.blocked) {
129
+ status = 'blocked';
130
+ decision = goalDecision('blocked', 'pause_scope', requestReason?.code ?? 'blocked', observation.blocked, resourceSnapshot);
131
+ }
102
132
  else if (hasVerifiedGoalCompletion(observation.taskContextCompletion)) {
103
133
  status = 'completed';
104
134
  decision = (0, stop_decision_1.createStopDecision)({
@@ -122,30 +152,18 @@ class GoalLifecycleServiceV2 {
122
152
  resources: resourceSnapshot,
123
153
  });
124
154
  }
125
- else if (blockedCount >= MAX_BLOCKED_CONTINUATIONS) {
126
- status = 'paused';
127
- decision = goalDecision('blocked', 'pause_scope', 'blocked', observation.blocked ?? 'Goal remained blocked.', resourceSnapshot);
128
- }
129
- else if (noProgressCount >= MAX_NO_PROGRESS_TURNS) {
130
- status = 'paused';
131
- decision = goalDecision('stopped', 'pause_scope', 'no_progress', `Goal made no observable progress for ${MAX_NO_PROGRESS_TURNS} turns.`, resourceSnapshot);
132
- }
133
155
  else if (observation.continuationMode === 'manual') {
134
156
  status = 'paused';
135
157
  decision = goalDecision('stopped', 'pause_scope', 'goal_manual_continuation', 'Goal checkpoint saved. Manual continuation is enabled; use /goal resume for the next turn.', resourceSnapshot);
136
158
  }
137
159
  else if (observation.checkpoint) {
138
- const verified = observation.checkpoint.unfinishedPlan && observation.checkpoint.verificationRefs.length > 0;
139
- status = verified ? 'active' : 'paused';
140
160
  decision = (0, stop_decision_1.createStopDecision)({
141
161
  scope: 'goal',
142
162
  status: 'stopped',
143
- disposition: verified ? 'resume_allowed' : 'pause_scope',
163
+ disposition: 'resume_allowed',
144
164
  reason: {
145
- code: verified ? 'goal_checkpoint' : 'goal_checkpoint_unverified',
146
- message: verified
147
- ? 'Goal checkpoint saved with fresh successful verification and an unfinished plan; continuing automatically.'
148
- : 'Goal checkpoint saved. Automatic continuation requires an unfinished plan and fresh successful verification from this turn; inspect the evidence, then use /goal resume.',
165
+ code: 'goal_checkpoint',
166
+ message: 'Goal checkpoint saved; continuing from the durable task state.',
149
167
  },
150
168
  evidence: observation.checkpoint.verificationRefs.map(ref => ({
151
169
  kind: 'verification',
@@ -153,15 +171,9 @@ class GoalLifecycleServiceV2 {
153
171
  detail: ref,
154
172
  })),
155
173
  evidenceRefs: [...observation.checkpoint.verificationRefs],
156
- nextActions: verified
157
- ? [{ kind: 'inspect', label: 'Inspect the durable checkpoint and ongoing Goal.' }]
158
- : [
159
- {
160
- kind: 'resume',
161
- label: 'Resume after inspecting the checkpoint.',
162
- command: '/goal resume',
163
- },
164
- ],
174
+ nextActions: [
175
+ { kind: 'inspect', label: 'Inspect the durable checkpoint and ongoing Goal.' },
176
+ ],
165
177
  resources: resourceSnapshot,
166
178
  });
167
179
  }
@@ -193,11 +205,18 @@ class GoalLifecycleServiceV2 {
193
205
  return this.transition('paused', reason, message);
194
206
  }
195
207
  resume() {
196
- if (this.stateValue.status !== 'paused')
208
+ if (!['paused', 'blocked', 'usage_limited'].includes(this.stateValue.status))
197
209
  return this.state;
198
- if (this.stateValue.tokensUsed >= this.stateValue.budget.maxTokens ||
199
- this.stateValue.elapsedMs >= this.stateValue.budget.maxElapsedMs)
210
+ const exhausted = exhaustedGoalBudget(this.stateValue);
211
+ if (exhausted) {
212
+ this.stateValue = withDigest({
213
+ ...withoutDigest(this.stateValue),
214
+ status: 'budget_limited',
215
+ lastStopDecision: goalBudgetDecision(this.stateValue),
216
+ updatedAt: Math.max(this.stateValue.updatedAt + 1, this.clock()),
217
+ });
200
218
  return this.state;
219
+ }
201
220
  const content = {
202
221
  ...withoutDigest(this.stateValue),
203
222
  status: 'active',
@@ -210,11 +229,50 @@ class GoalLifecycleServiceV2 {
210
229
  this.stateValue = withDigest(content);
211
230
  return this.state;
212
231
  }
232
+ updateBudget(update, ceilings) {
233
+ const state = this.stateValue;
234
+ if (!['paused', 'blocked', 'usage_limited', 'budget_limited'].includes(state.status)) {
235
+ throw new Error(`Goal budget cannot change while the Goal is ${state.status}.`);
236
+ }
237
+ validateGoalBudget(update);
238
+ if (update.maxTokens === undefined && update.maxElapsedMs === undefined) {
239
+ throw new Error('Specify a new total token or elapsed-time limit.');
240
+ }
241
+ for (const { key, used, flag, unit } of GOAL_BUDGET_RESOURCES) {
242
+ const next = update[key];
243
+ if (next === undefined)
244
+ continue;
245
+ const ceiling = ceilings[key];
246
+ if (ceiling !== undefined && next > ceiling) {
247
+ throw new Error(`${flag} exceeds the configured ceiling of ${ceiling} ${unit}.`);
248
+ }
249
+ if (next <= Math.max(state.budget[key] ?? 0, state[used])) {
250
+ throw new Error(`${flag} must exceed the saved limit and the ${state[used]} ${unit} already used.`);
251
+ }
252
+ }
253
+ const budget = { ...state.budget, ...update };
254
+ const usage = { ...state, budget };
255
+ const exhausted = exhaustedGoalBudget(usage);
256
+ const status = state.status === 'budget_limited' && !exhausted ? 'paused' : state.status;
257
+ const resources = { turns: { used: state.continuationCount }, ...goalResources(usage) };
258
+ const decision = status === 'budget_limited'
259
+ ? goalBudgetDecision(usage, undefined, resources)
260
+ : state.status === 'budget_limited'
261
+ ? goalDecision('stopped', 'pause_scope', 'goal_budget_updated', 'Goal budget updated. Use /goal resume to continue from the saved checkpoint.', resources)
262
+ : state.lastStopDecision && (0, stop_decision_1.createStopDecision)({ ...state.lastStopDecision, resources });
263
+ this.stateValue = withDigest({
264
+ ...withoutDigest(state),
265
+ budget,
266
+ status,
267
+ ...(decision ? { lastStopDecision: decision } : {}),
268
+ updatedAt: Math.max(state.updatedAt + 1, this.clock()),
269
+ });
270
+ return this.state;
271
+ }
213
272
  transition(status, code, message) {
214
273
  const decision = goalDecision(status === 'failed' ? 'failed' : 'stopped', 'pause_scope', code, message, {
215
274
  turns: { used: this.stateValue.continuationCount },
216
- tokens: { used: this.stateValue.tokensUsed, limit: this.stateValue.budget.maxTokens },
217
- elapsedMs: { used: this.stateValue.elapsedMs, limit: this.stateValue.budget.maxElapsedMs },
275
+ ...goalResources(this.stateValue),
218
276
  });
219
277
  this.stateValue = withDigest({
220
278
  ...withoutDigest(this.stateValue),
@@ -242,7 +300,7 @@ function assertGoalLifecycleStateV2(state) {
242
300
  (0, canonical_1.digestRuntimeValue)(content) !== digest) {
243
301
  throw new Error('GoalLifecycleStateV2 failed integrity validation');
244
302
  }
245
- validateBudget(state.budget);
303
+ validateGoalBudget(state.budget);
246
304
  for (const value of [
247
305
  state.generation,
248
306
  state.continuationCount,
@@ -256,6 +314,58 @@ function assertGoalLifecycleStateV2(state) {
256
314
  }
257
315
  }
258
316
  }
317
+ function exhaustedGoalBudget(usage) {
318
+ return GOAL_BUDGET_RESOURCES.find(({ key, used }) => {
319
+ const limit = usage.budget[key];
320
+ return limit !== undefined && usage[used] >= limit;
321
+ });
322
+ }
323
+ function goalResources({ budget, tokensUsed, elapsedMs }) {
324
+ return {
325
+ tokens: {
326
+ used: tokensUsed,
327
+ ...(budget.maxTokens === undefined ? {} : { limit: budget.maxTokens }),
328
+ },
329
+ elapsedMs: {
330
+ used: elapsedMs,
331
+ ...(budget.maxElapsedMs === undefined ? {} : { limit: budget.maxElapsedMs }),
332
+ },
333
+ };
334
+ }
335
+ function goalBudgetDecision(usage, code, resources = goalResources(usage)) {
336
+ const exhausted = GOAL_BUDGET_RESOURCES.filter(({ key, used }) => {
337
+ const limit = usage.budget[key];
338
+ return limit !== undefined && usage[used] >= limit;
339
+ });
340
+ const affected = exhausted.length
341
+ ? exhausted
342
+ : GOAL_BUDGET_RESOURCES.filter(({ key }) => code === 'goal_token_budget' ? key === 'maxTokens' : key === 'maxElapsedMs');
343
+ const command = `/goal budget ${affected.map(({ flag }) => `${flag} <new-total>`).join(' ')}`;
344
+ const limits = affected
345
+ .map(({ key, used, unit }) => `${usage[used]}/${usage.budget[key] ?? 'unlimited'} ${unit}`)
346
+ .join(', ');
347
+ const message = `Goal budget reached (${limits}). Progress saved. Use ${command}, then /goal resume.`;
348
+ return (0, stop_decision_1.createStopDecision)({
349
+ scope: 'goal',
350
+ status: 'stopped',
351
+ disposition: 'pause_scope',
352
+ reason: {
353
+ code: code ?? (affected[0]?.key === 'maxTokens' ? 'goal_token_budget' : 'goal_time_budget'),
354
+ message,
355
+ },
356
+ evidence: [{ kind: 'resource_limit', source: 'goal-lifecycle-v2', detail: limits }],
357
+ nextActions: [
358
+ {
359
+ kind: 'inspect',
360
+ label: 'Inspect the saved Goal usage and checkpoint.',
361
+ command: '/goal status',
362
+ },
363
+ { kind: 'raise_budget', label: 'Authorize a higher total, then resume.', command },
364
+ ],
365
+ resumable: false,
366
+ resources,
367
+ });
368
+ }
259
369
  function goalDecision(status, disposition, code, message, resources) {
260
370
  return (0, stop_decision_1.createStopDecision)({
261
371
  scope: 'goal',
@@ -263,14 +373,8 @@ function goalDecision(status, disposition, code, message, resources) {
263
373
  disposition,
264
374
  reason: { code, message },
265
375
  evidence: [{ kind: 'runtime', source: 'goal-lifecycle-v2', detail: message }],
266
- nextActions: code === 'goal_budget'
267
- ? [
268
- { kind: 'inspect', label: 'Inspect the saved Goal usage and receipts.' },
269
- {
270
- kind: 'change_input',
271
- label: 'Explicitly clear and create a new Goal after configuring its total budget.',
272
- },
273
- ]
376
+ nextActions: code === 'persistence_error'
377
+ ? [{ kind: 'inspect', label: 'Inspect the saved Goal state.' }]
274
378
  : [
275
379
  { kind: 'inspect', label: 'Inspect the durable Goal state.' },
276
380
  {
@@ -279,6 +383,7 @@ function goalDecision(status, disposition, code, message, resources) {
279
383
  command: '/goal resume',
280
384
  },
281
385
  ],
386
+ resumable: code !== 'persistence_error',
282
387
  resources,
283
388
  });
284
389
  }
@@ -286,11 +391,14 @@ function isProviderFailure(decision) {
286
391
  return (decision.evidence.some(item => item.kind === 'provider') ||
287
392
  /provider|network|auth|rate.?limit/iu.test(decision.reason.code));
288
393
  }
289
- function validateBudget(budget) {
290
- if (!Number.isSafeInteger(budget.maxTokens) ||
291
- budget.maxTokens <= 0 ||
292
- !Number.isSafeInteger(budget.maxElapsedMs) ||
293
- budget.maxElapsedMs <= 0) {
394
+ function validateGoalBudget(budget) {
395
+ if (!budget ||
396
+ typeof budget !== 'object' ||
397
+ Array.isArray(budget) ||
398
+ GOAL_BUDGET_RESOURCES.some(({ key }) => {
399
+ const value = budget[key];
400
+ return value !== undefined && (!Number.isSafeInteger(value) || value <= 0);
401
+ })) {
294
402
  throw new Error('Goal budget values must be positive safe integers');
295
403
  }
296
404
  }
@@ -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 &&
@@ -554,6 +608,7 @@ function defaultContinuationInput(state) {
554
608
  return [
555
609
  'Continue the active Goal using saved state and receipts.',
556
610
  `Objective: ${objective}`,
611
+ 'Use the current TaskContext verification requirements when the user has corrected a check.',
557
612
  'Do not claim completion unless the TaskContext completion gate verifies every criterion.',
558
613
  ].join('\n');
559
614
  }
@@ -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