@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,13 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_TASK_STEP_FAILURES = exports.TASK_CHECKLIST_REQUIRED = void 0;
3
+ exports.TASK_RECOVERY_STRATEGY_HISTORY_LIMIT = exports.TASK_CHECKLIST_REQUIRED = void 0;
4
4
  exports.supportsExecutionChecklist = supportsExecutionChecklist;
5
5
  exports.requestedTaskDeferral = requestedTaskDeferral;
6
6
  exports.taskTodoDisplayStatus = taskTodoDisplayStatus;
7
7
  exports.requestedWorkspaceChanges = requestedWorkspaceChanges;
8
8
  exports.isImplementationTodo = isImplementationTodo;
9
+ exports.todoFileTargets = todoFileTargets;
10
+ exports.clarifiesTodoFileTarget = clarifiesTodoFileTarget;
9
11
  exports.workspaceChangeTargets = workspaceChangeTargets;
10
12
  exports.executionChecklistIssue = executionChecklistIssue;
13
+ const path_1 = require("path");
11
14
  const verification_1 = require("./verification");
12
15
  const writeInstruction = /^(?:(?:please|first|then|also)\s+)*(?:implement|add|apply|edit|update|modify|change|adjust|fix|refactor|migrate|remove|rename|replace|rewrite|create|patch|write|wire|introduce|optimi[sz]e)\b|^(?:(?:请|帮我|先|再|同时)\s*)*(?:实现|开发|接入|新增|添加|应用|修改|改动|更新|调整|修复|重构|迁移|移除|删除|替换|重写|创建|编写|优化)/iu;
13
16
  const multipleChanges = /\b(?:multi[- ](?:file|step)|cross[- ]file|multiple files|several files|across (?:the )?(?:files|modules|packages))\b|跨文件|跨模块|多步骤|多个文件|多处改动/iu;
@@ -16,11 +19,11 @@ const fileExtension = /\.[a-z][a-z0-9]{0,7}$/iu;
16
19
  const referenceClause = /\s+(?:to (?:match|follow|use)|based on|according to|using|after reading|as (?:in|described in))\s+|(?:,|\s)*(?:参考|参照|依据|基于|对照|按照)/iu;
17
20
  const checkInstruction = /^(?:(?:verify|validate|check|review)\b|验收|验证|核对|检查|审阅)/iu;
18
21
  const sameFileScope = /^(?:(?:edit|modify|change|update)\s+(?:only\s+)?(?:this|that|the same)\s+file(?:\s+only)?|(?:只)?(?:修改|编辑|更新)(?:这个|该|同一)文件)[.,,。]?$/iu;
19
- exports.TASK_CHECKLIST_REQUIRED = 'Create an execution checklist with todo_write before changing the workspace. Include distinct implementation and verification steps. You can inspect files first.';
22
+ exports.TASK_CHECKLIST_REQUIRED = 'Create an execution checklist with todo_write before changing the workspace. Include the implementation work and a verification check. You can inspect files first.';
20
23
  function supportsExecutionChecklist(mode) {
21
24
  return mode === 'build' || mode === 'auto' || mode === 'goal';
22
25
  }
23
- exports.MAX_TASK_STEP_FAILURES = 4;
26
+ exports.TASK_RECOVERY_STRATEGY_HISTORY_LIMIT = 4;
24
27
  /** Deferral is applied from explicit user input. Tool arguments cannot defer work. */
25
28
  function requestedTaskDeferral(input) {
26
29
  const text = input.trim();
@@ -39,9 +42,6 @@ function requestedTaskDeferral(input) {
39
42
  function taskTodoDisplayStatus(todo) {
40
43
  if (todo.deferredReason)
41
44
  return 'deferred';
42
- if (todo.status === 'in_progress' &&
43
- (todo.recovery?.consecutiveFailures ?? 0) >= exports.MAX_TASK_STEP_FAILURES)
44
- return 'blocked';
45
45
  return todo.status;
46
46
  }
47
47
  function modificationClauses(instruction) {
@@ -54,10 +54,13 @@ function modificationClauses(instruction) {
54
54
  function pathsInActions(actions) {
55
55
  return [
56
56
  ...new Set(actions.flatMap(action => (action.split(referenceClause, 1)[0].match(pathToken) ?? [])
57
- .map(token => token.replace(/^\x60|\x60$|\.+$/gu, ''))
57
+ .map(normalizePathToken)
58
58
  .filter(token => fileExtension.test(token)))),
59
59
  ];
60
60
  }
61
+ function normalizePathToken(token) {
62
+ return token.replace(/^\x60|\x60$|\.+$/gu, '');
63
+ }
61
64
  function requestedWorkspaceChanges(instruction) {
62
65
  const actions = modificationClauses(instruction);
63
66
  const paths = pathsInActions(actions);
@@ -75,7 +78,45 @@ function isVerification(todo) {
75
78
  return Boolean(todo.verification?.length) || checkInstruction.test(todo.content);
76
79
  }
77
80
  function isImplementationTodo(todo) {
78
- return !isVerification(todo) && modificationClauses(todo.content).length > 0;
81
+ return modificationClauses(todo.content).length > 0;
82
+ }
83
+ function isBasename(path) {
84
+ return !/[\\/]/u.test(path);
85
+ }
86
+ function todoFileTargets(content, cwd, taskTargets) {
87
+ return requestedWorkspaceChanges(content).paths.map(declared => {
88
+ const path = (0, verification_1.workspaceArtifactPath)(cwd, declared);
89
+ if (!path)
90
+ return { declared, candidates: [], unscopedBasename: false };
91
+ const bare = isBasename(declared);
92
+ const scoped = bare ? taskTargets.filter(target => (0, path_1.basename)(target) === path) : [];
93
+ return {
94
+ declared,
95
+ candidates: scoped.length ? scoped : [path],
96
+ unscopedBasename: bare && scoped.length === 0,
97
+ };
98
+ });
99
+ }
100
+ /** A clarification changes only an unresolved file token, retaining the todo and its evidence. */
101
+ function clarifiesTodoFileTarget(previous, next, cwd, taskTargets) {
102
+ const original = todoFileTargets(previous.content, cwd, taskTargets);
103
+ const replacement = todoFileTargets(next.content, cwd, taskTargets);
104
+ if (original.length !== replacement.length)
105
+ return false;
106
+ const changed = original.flatMap((from, index) => from.declared === replacement[index].declared ? [] : [{ from, to: replacement[index] }]);
107
+ if (changed.length !== 1)
108
+ return false;
109
+ const [{ from, to }] = changed;
110
+ if (!isBasename(from.declared) || isBasename(to.declared) || (0, path_1.isAbsolute)(to.declared))
111
+ return false;
112
+ const destination = to.candidates[0];
113
+ return (destination !== undefined &&
114
+ (0, path_1.basename)(destination) === from.declared &&
115
+ (from.unscopedBasename || from.candidates.includes(destination)) &&
116
+ withoutTarget(previous.content, from.declared) === withoutTarget(next.content, to.declared));
117
+ }
118
+ function withoutTarget(content, target) {
119
+ return content.replace(pathToken, token => normalizePathToken(token) === target ? '<path>' : token);
79
120
  }
80
121
  function workspaceChangeTargets(root, paths) {
81
122
  return [
@@ -88,7 +129,7 @@ function executionChecklistIssue(todos, targets, cwd) {
88
129
  const implementation = todos.filter(isImplementationTodo);
89
130
  if (!todos.some(isVerification) || implementation.length === 0)
90
131
  return exports.TASK_CHECKLIST_REQUIRED;
91
- const planned = new Set(workspaceChangeTargets(cwd, implementation.flatMap(todo => requestedWorkspaceChanges(todo.content).paths)));
132
+ const planned = new Set(implementation.flatMap(todo => todoFileTargets(todo.content, cwd, targets).flatMap(target => target.candidates.length === 1 ? target.candidates : [])));
92
133
  const missing = targets.filter(path => !planned.has(path));
93
134
  return missing.length ? `${exports.TASK_CHECKLIST_REQUIRED} Include: ${missing.join(', ')}.` : undefined;
94
135
  }
@@ -245,12 +245,14 @@ export interface HarnessState {
245
245
  ledger: ContextLedgerEntry[];
246
246
  /** Monotonic revision of observed workspace writes, retained independently of the ledger. */
247
247
  workspaceRevision?: number;
248
+ verificationWorkspace?: string;
248
249
  capsule?: ContextCapsule;
249
250
  completionBlockCount?: number;
250
251
  taskEpoch?: number;
251
252
  taskChecklistRequired?: boolean;
252
253
  taskChecklistTargets?: string[];
253
254
  goalTaskId?: string;
255
+ goalVerificationBlocker?: string;
254
256
  taskTodos?: (Omit<TaskTodoItem, 'id'> & {
255
257
  id?: string;
256
258
  })[];
@@ -309,10 +311,19 @@ export interface CompletionCriterionResult {
309
311
  status: TaskCriterionStatus;
310
312
  applicable: boolean;
311
313
  evidenceRefs: string[];
314
+ verificationProblems?: VerificationProblem[];
312
315
  requiredKinds: VerificationKind[];
313
316
  missingKinds: VerificationKind[];
314
317
  failedKinds: VerificationKind[];
315
318
  }
319
+ export interface VerificationProblem {
320
+ kind: VerificationKind;
321
+ status: 'failed' | 'stale' | 'missing';
322
+ command?: string;
323
+ cwd?: string;
324
+ exitCode?: number;
325
+ failureFingerprint?: string;
326
+ }
316
327
  export interface ProgressSnapshot {
317
328
  fingerprint: string;
318
329
  criterionStates: Array<{
@@ -325,6 +336,7 @@ export interface ProgressSnapshot {
325
336
  verificationObservations?: string[];
326
337
  exploredPaths?: string[];
327
338
  explorationObservations?: string[];
339
+ decisionObservations?: string[];
328
340
  todoStateHash?: string;
329
341
  decisions: string[];
330
342
  blockers: string[];
@@ -333,6 +345,7 @@ export interface ProgressSnapshot {
333
345
  workspaceStateHash: string;
334
346
  }
335
347
  export type ProgressReason = 'workspace_change' | 'verification_change' | 'explicit_task_state' | 'readonly_exploration' | 'agent_output' | 'no_effect';
348
+ export type ProgressCounts = Record<Exclude<ProgressReason, 'no_effect'>, number>;
336
349
  export interface ProgressDelta {
337
350
  schemaVersion: 1;
338
351
  changed: boolean;
@@ -357,6 +370,8 @@ export interface HarnessProgressState {
357
370
  schemaVersion: 1;
358
371
  snapshot?: ProgressSnapshot;
359
372
  lastDelta?: ProgressDelta;
373
+ /** Cumulative observations by category since progress counting began for this thread. */
374
+ progressCountedByReason?: ProgressCounts;
360
375
  }
361
376
  export interface CapabilityProfile {
362
377
  schemaVersion: 1;
@@ -9,13 +9,23 @@ export declare function workspaceArtifactPath(root: string, path: string): strin
9
9
  export declare function latestArtifactWrite(ledger: readonly ContextLedgerEntry[], contractId: string, cwd: string, path: string): ContextLedgerEntry | undefined;
10
10
  export declare function classifyVerificationCommand(command: string | undefined): VerificationKind;
11
11
  export declare function requiredVerificationKinds(statement: string): VerificationKind[];
12
- interface RequestedCheck {
12
+ export interface RequestedCheck {
13
13
  readonly kind: VerificationCommandKind;
14
14
  readonly command: string;
15
15
  readonly cwd?: string;
16
16
  }
17
17
  /** Quoted commands preserve user-specified test selectors and workspace scope. */
18
18
  export declare function requestedLocalChecks(statement: string): RequestedCheck[];
19
+ interface LocatedCheck extends RequestedCheck {
20
+ readonly start: number;
21
+ readonly end: number;
22
+ readonly cwdStart?: number;
23
+ readonly cwdEnd?: number;
24
+ }
25
+ export declare function locateRequestedChecks(statement: string): LocatedCheck[];
26
+ export declare function equalRequestedChecks(left: RequestedCheck, right: RequestedCheck, workspace: string): boolean;
27
+ /** Rewrite only the selected command and its own directory literal. */
28
+ export declare function replaceRequestedCheck(statement: string, previous: RequestedCheck, next: RequestedCheck, workspace: string): string;
19
29
  export declare function matchesRequestedCheck(entry: ContextLedgerEntry, check: RequestedCheck, workspace: string): boolean;
20
30
  export declare function verificationKindForEntry(entry: ContextLedgerEntry, requireLocalReceipt?: boolean): VerificationKind;
21
31
  export declare function isTrustedEvidence(entry: ContextLedgerEntry): boolean;
@@ -6,6 +6,9 @@ exports.latestArtifactWrite = latestArtifactWrite;
6
6
  exports.classifyVerificationCommand = classifyVerificationCommand;
7
7
  exports.requiredVerificationKinds = requiredVerificationKinds;
8
8
  exports.requestedLocalChecks = requestedLocalChecks;
9
+ exports.locateRequestedChecks = locateRequestedChecks;
10
+ exports.equalRequestedChecks = equalRequestedChecks;
11
+ exports.replaceRequestedCheck = replaceRequestedCheck;
9
12
  exports.matchesRequestedCheck = matchesRequestedCheck;
10
13
  exports.verificationKindForEntry = verificationKindForEntry;
11
14
  exports.isTrustedEvidence = isTrustedEvidence;
@@ -152,6 +155,9 @@ function requiredVerificationKinds(statement) {
152
155
  }
153
156
  /** Quoted commands preserve user-specified test selectors and workspace scope. */
154
157
  function requestedLocalChecks(statement) {
158
+ return locateRequestedChecks(statement).map(({ kind, command, cwd }) => ({ kind, command, cwd }));
159
+ }
160
+ function locateRequestedChecks(statement) {
155
161
  const checks = [];
156
162
  for (const match of statement.matchAll(/\x60([^\x60\r\n]+)\x60/gu)) {
157
163
  const [span, literal] = match;
@@ -164,11 +170,50 @@ function requestedLocalChecks(statement) {
164
170
  const after = statement.slice(index + span.length);
165
171
  const trailing = after.match(/^\s*(?:(?:in|inside|under)\s+|在\s*)\x60([^\x60\r\n]+)\x60/iu);
166
172
  const leading = before.match(/(?:\b(?:in|inside|under)\s+|在\s*)\x60([^\x60\r\n]+)\x60\s*(?:中|内|下)?\s*[,,]?\s*(?:run|execute|运行|执行)\s*$/iu);
167
- const cwd = (trailing?.[1] ?? leading?.[1])?.trim();
168
- checks.push({ kind, command, cwd });
173
+ const cwdMatch = trailing ?? leading;
174
+ const cwd = cwdMatch?.[1].trim();
175
+ const cwdStart = cwdMatch
176
+ ? (trailing ? index + span.length : (leading?.index ?? 0)) + cwdMatch[0].indexOf('`') + 1
177
+ : undefined;
178
+ checks.push({
179
+ kind,
180
+ command,
181
+ cwd,
182
+ start: index,
183
+ end: index + span.length,
184
+ ...(cwdStart === undefined
185
+ ? {}
186
+ : { cwdStart, cwdEnd: cwdStart + (cwdMatch?.[1].length ?? 0) }),
187
+ });
169
188
  }
170
189
  return checks;
171
190
  }
191
+ function equalRequestedChecks(left, right, workspace) {
192
+ return (left.kind === right.kind &&
193
+ left.command === right.command &&
194
+ (0, path_1.resolve)(workspace, left.cwd ?? '.') === (0, path_1.resolve)(workspace, right.cwd ?? '.'));
195
+ }
196
+ /** Rewrite only the selected command and its own directory literal. */
197
+ function replaceRequestedCheck(statement, previous, next, workspace) {
198
+ const edits = [];
199
+ for (const check of locateRequestedChecks(statement)) {
200
+ if (!equalRequestedChecks(check, previous, workspace))
201
+ continue;
202
+ const needsDirectory = next.cwd && !check.cwd && (0, path_1.resolve)(workspace, next.cwd) !== workspace;
203
+ edits.push({
204
+ start: check.start,
205
+ end: check.end,
206
+ text: '\x60' + next.command + '\x60' + (needsDirectory ? ' in \x60' + next.cwd + '\x60' : ''),
207
+ });
208
+ if (check.cwdStart !== undefined && check.cwdEnd !== undefined && next.cwd !== check.cwd) {
209
+ edits.push({ start: check.cwdStart, end: check.cwdEnd, text: next.cwd ?? '.' });
210
+ }
211
+ }
212
+ for (const { start, end, text } of edits.sort((left, right) => right.start - left.start)) {
213
+ statement = statement.slice(0, start) + text + statement.slice(end);
214
+ }
215
+ return statement;
216
+ }
172
217
  function matchesRequestedCheck(entry, check, workspace) {
173
218
  const { command, cwd } = entry.metadata ?? {};
174
219
  return (typeof command === 'string' &&
@@ -10,7 +10,12 @@ declare const EXIT_CODES: {
10
10
  export interface PrintOutcome {
11
11
  status: keyof typeof EXIT_CODES;
12
12
  reasonCode: string;
13
+ reasonMessage?: string;
13
14
  resumable: boolean;
15
+ metrics?: {
16
+ llmRequests: number;
17
+ toolCalls: number;
18
+ };
14
19
  }
15
20
  /** Versioned shell protocol. Internal receipts, tool arguments and reasoning stay in Runtime. */
16
21
  export declare class PrintEventStreamV1 {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PrintEventStreamV1 = void 0;
4
4
  const tool_transcript_entry_1 = require("../runtime/tool-transcript-entry");
5
5
  const turn_commit_1 = require("../runtime/turn-commit");
6
+ const redaction_1 = require("../services/redaction");
6
7
  const EXIT_CODES = {
7
8
  completed: 0,
8
9
  failed: 1,
@@ -11,7 +12,9 @@ const EXIT_CODES = {
11
12
  cancelled: 130,
12
13
  };
13
14
  function decisionOutcome(decision) {
14
- const { status, reason, resumable } = decision;
15
+ const { status, disposition, reason, resumable, resources } = decision;
16
+ const llmRequests = resources.llmRequests?.used;
17
+ const toolCalls = resources.toolCalls?.used;
15
18
  return {
16
19
  status: status === 'stopped' ||
17
20
  status === 'blocked' ||
@@ -19,7 +22,12 @@ function decisionOutcome(decision) {
19
22
  ? 'incomplete'
20
23
  : status,
21
24
  reasonCode: reason.code,
22
- resumable: resumable ?? status === 'stopped',
25
+ ...(status === 'completed' ? {} : { reasonMessage: (0, redaction_1.redactTraceText)(reason.message) }),
26
+ resumable: resumable ??
27
+ (status === 'stopped' || (status === 'blocked' && disposition === 'resume_allowed')),
28
+ ...(llmRequests === undefined || toolCalls === undefined
29
+ ? {}
30
+ : { metrics: { llmRequests, toolCalls } }),
23
31
  };
24
32
  }
25
33
  /** Versioned shell protocol. Internal receipts, tool arguments and reasoning stay in Runtime. */
@@ -74,7 +82,16 @@ class PrintEventStreamV1 {
74
82
  ? { status: 'failed', reasonCode: 'event_projection_failed', resumable: false }
75
83
  : (this.terminalOutcome ?? fallback);
76
84
  const exitCode = EXIT_CODES[outcome.status];
77
- this.emit({ type: 'result', ...outcome, exitCode });
85
+ const committed = this.committedOutcome;
86
+ const metrics = committed?.metrics;
87
+ const reasonMessage = committed?.reasonCode === outcome.reasonCode ? committed.reasonMessage : undefined;
88
+ this.emit({
89
+ type: 'result',
90
+ ...outcome,
91
+ ...(metrics ? { metrics } : {}),
92
+ ...(reasonMessage === undefined ? {} : { reasonMessage }),
93
+ exitCode,
94
+ });
78
95
  this.exitCode = exitCode;
79
96
  return exitCode;
80
97
  }
@@ -127,9 +144,9 @@ class PrintEventStreamV1 {
127
144
  };
128
145
  return;
129
146
  case 'turn.interrupted':
130
- this.terminalOutcome = {
147
+ this.terminalOutcome = this.committedOutcome ?? {
131
148
  status: 'cancelled',
132
- reasonCode: this.committedOutcome?.reasonCode ?? 'cancelled',
149
+ reasonCode: 'cancelled',
133
150
  resumable: true,
134
151
  };
135
152
  return;
@@ -51,7 +51,8 @@ export interface AgentLoopOptionsV1 {
51
51
  readonly streamCallbacks?: StreamCallbacks;
52
52
  readonly loopBudget?: Partial<LoopBudget>;
53
53
  readonly remainingGoalTokens?: QueryParams['remainingGoalTokens'];
54
- readonly allowBudgetRecovery?: boolean;
54
+ readonly goalDeadlineAt?: QueryParams['goalDeadlineAt'];
55
+ readonly allowToolPressureCompaction?: boolean;
55
56
  readonly enableTaskTodos?: boolean;
56
57
  readonly resolveGoalTask?: () => {
57
58
  readonly goalId: string;
@@ -137,7 +137,7 @@ class AgentLoopV1 {
137
137
  threadId: context.threadId,
138
138
  turnId: context.turnId,
139
139
  requestIndex: stepInput.requestIndex,
140
- input: context.input,
140
+ input: stepInput.input ?? context.input,
141
141
  mode: context.mode,
142
142
  messages: stepInput.messages,
143
143
  taskContextRevision: this.options.taskContext.revision,
@@ -179,8 +179,20 @@ class AgentLoopV1 {
179
179
  },
180
180
  loopBudget: this.options.loopBudget,
181
181
  remainingGoalTokens: this.options.remainingGoalTokens,
182
- allowBudgetRecovery: this.options.allowBudgetRecovery === true &&
182
+ goalDeadlineAt: this.options.goalDeadlineAt,
183
+ allowToolPressureCompaction: this.options.allowToolPressureCompaction === true &&
183
184
  (context.mode === 'build' || context.mode === 'auto'),
185
+ takePendingSteering: closeIfEmpty => {
186
+ const inputs = context.takePendingSteering?.(closeIfEmpty) ?? [];
187
+ for (const input of inputs) {
188
+ taskContextCompletion = undefined;
189
+ if (goal)
190
+ this.options.taskContext.observeGoalSteering(input, goal.goalId);
191
+ else
192
+ this.options.taskContext.observeUserInput(input);
193
+ }
194
+ return inputs;
195
+ },
184
196
  onContextUsage: this.options.onContextUsage,
185
197
  compactCoordinator: this.options.compactCoordinator,
186
198
  })) {
@@ -189,29 +201,23 @@ class AgentLoopV1 {
189
201
  finishReasoning();
190
202
  completeAssistant(assistantContent);
191
203
  activeStep = undefined;
204
+ taskContextCompletion = undefined;
192
205
  break;
193
206
  case 'assistant_tool_calls':
194
207
  case 'message':
195
208
  finishReasoning();
196
209
  completeAssistant(event.content);
197
210
  break;
198
- case 'budget_recovery': {
199
- const content = event.reason === 'progress'
200
- ? 'Observed new tool evidence. Continuing the task.'
201
- : 'No new tool evidence yet. Trying a different step before pausing.';
202
- const item = context.startItem({ kind: 'reasoning', name: 'loop:progress-checkpoint' });
203
- context.completeItem(item, { content, summary: content });
204
- break;
205
- }
206
- case 'warning':
207
- case 'strategy_exhausted': {
208
- const content = event.type === 'warning' ? event.message : event.suggestion;
211
+ case 'warning': {
212
+ const content = event.message;
209
213
  const item = context.startItem({ kind: 'reasoning', stepId: activeStep?.stepId });
210
214
  context.completeItem(item, { content, summary: compactSummary(content) });
211
215
  break;
212
216
  }
213
217
  case 'complete':
214
- if (executionChecklist && event.stats?.finishReason === 'completion_gate') {
218
+ if (executionChecklist &&
219
+ (event.stats?.finishReason === 'completion_gate' ||
220
+ event.stats?.stopDecision?.reason.code === 'task_step_blocked')) {
215
221
  const item = context.startItem({ kind: 'message', role: 'system' });
216
222
  context.completeItem(item, {
217
223
  content: event.content,
@@ -260,10 +266,10 @@ class AgentLoopV1 {
260
266
  ? { status: 'interrupted', reason: abortReason(context.abortSignal) }
261
267
  : { status: 'failed', error: 'AgentLoop ended without a terminal Query event' };
262
268
  }
269
+ // The completion audit can precede the final visible answer or be bypassed
270
+ // by a terminal provider/tool outcome. Account for the entire committed turn.
271
+ this.options.taskContext.recordProgress(progressAtAdmission);
263
272
  if (completeEvent.stats?.finishReason === 'budget_exceeded') {
264
- // A completion gate may have run before the last tools, or not at all.
265
- // Record progress for the whole turn without running another completion audit.
266
- this.options.taskContext.recordProgress(progressAtAdmission);
267
273
  taskContextCompletion = undefined;
268
274
  }
269
275
  const commitContent = {
@@ -79,6 +79,7 @@ export declare class AgentRuntimeController {
79
79
  private readonly goalControlRuns;
80
80
  private activeGoalRuntimeTransitions;
81
81
  private goalRuntimeActive;
82
+ private goalEventRevision;
82
83
  private settingsBoundarySynchronizations;
83
84
  private reportedInvalidConfigRevision?;
84
85
  private stopping;
@@ -157,7 +158,6 @@ export declare class AgentRuntimeController {
157
158
  requestToolPermission(request: AgentRuntimeToolPermissionRequest): Promise<boolean>;
158
159
  private startGoalControl;
159
160
  private renderGoalControl;
160
- private observeGoalControlResult;
161
161
  private observeGoalRuntimeEvent;
162
162
  private recordPermissionDecision;
163
163
  private rejectPendingPermissions;
@@ -61,6 +61,7 @@ class AgentRuntimeController {
61
61
  this.goalControlRuns = new Set();
62
62
  this.activeGoalRuntimeTransitions = 0;
63
63
  this.goalRuntimeActive = false;
64
+ this.goalEventRevision = 0;
64
65
  this.settingsBoundarySynchronizations = 0;
65
66
  this.stopping = false;
66
67
  this.nextPermissionRequestId = 1;
@@ -1072,8 +1073,9 @@ class AgentRuntimeController {
1072
1073
  return { type: 'command_handled' };
1073
1074
  }
1074
1075
  const startsGoal = goalControl.action === 'create' || goalControl.action === 'resume';
1076
+ const requiresIdle = startsGoal || goalControl.action === 'budget';
1075
1077
  if ((this.hasActiveTurn() || this.goalControlRuns.size > 0 || this.goalRuntimeActive) &&
1076
- startsGoal) {
1078
+ requiresIdle) {
1077
1079
  const message = `/goal ${goalControl.action} is unavailable while Goal work is running; use /goal pause or /goal clear first.`;
1078
1080
  this.emitStatus(message);
1079
1081
  return { type: 'command_ignored' };
@@ -1090,9 +1092,10 @@ class AgentRuntimeController {
1090
1092
  .then(async () => {
1091
1093
  if (interruptedRun)
1092
1094
  await interruptedRun.catch(() => undefined);
1093
- if (startsGoal && !(await this.synchronizeSettingsAtLogicalBoundary()))
1095
+ if (requiresIdle && !(await this.synchronizeSettingsAtLogicalBoundary()))
1094
1096
  return;
1095
1097
  this.activeGoalRuntimeTransitions += 1;
1098
+ const goalEventRevision = this.goalEventRevision;
1096
1099
  let result;
1097
1100
  try {
1098
1101
  result = await this.runner.controlGoal(goalControl);
@@ -1100,7 +1103,11 @@ class AgentRuntimeController {
1100
1103
  finally {
1101
1104
  this.activeGoalRuntimeTransitions -= 1;
1102
1105
  }
1103
- this.observeGoalControlResult(result);
1106
+ if (goalEventRevision === this.goalEventRevision &&
1107
+ result.accepted &&
1108
+ result.action !== 'status') {
1109
+ this.goalRuntimeActive = result.state?.status === 'active' || result.scheduleContinuation;
1110
+ }
1104
1111
  this.renderGoalControl(result);
1105
1112
  // Pause/clear must remain available while Goal work is active. Reconcile
1106
1113
  // pending runtime-sensitive edits only after that work has stopped.
@@ -1128,17 +1135,13 @@ class AgentRuntimeController {
1128
1135
  });
1129
1136
  this.emitStatus(summary);
1130
1137
  }
1131
- observeGoalControlResult(result) {
1132
- if (!result.accepted)
1133
- return;
1134
- this.goalRuntimeActive =
1135
- (result.action === 'create' || result.action === 'resume') && result.scheduleContinuation;
1136
- }
1137
1138
  observeGoalRuntimeEvent(event) {
1138
1139
  if (event.type === 'goal_updated') {
1140
+ this.goalEventRevision += 1;
1139
1141
  this.goalRuntimeActive = event.goal.status === 'active';
1140
1142
  }
1141
1143
  else if (event.type === 'goal_cleared' || event.type === 'goal_completed') {
1144
+ this.goalEventRevision += 1;
1142
1145
  this.goalRuntimeActive = false;
1143
1146
  }
1144
1147
  }
@@ -1225,8 +1228,12 @@ function formatGoalRuntimeStatus(result) {
1225
1228
  const objective = state.objective.length > 80 ? `${state.objective.slice(0, 77)}...` : state.objective;
1226
1229
  return [
1227
1230
  result.message,
1228
- `Goal: [${state.status}] ${objective}`,
1229
- `Progress: ${state.continuationCount} turns · ${state.tokensUsed}/${state.budget.maxTokens} tokens · ${state.elapsedMs}/${state.budget.maxElapsedMs}ms`,
1231
+ `Goal: [${state.status}] ${objective} (${state.goalId})`,
1232
+ `Progress: ${state.continuationCount} turns · ${state.tokensUsed}/${state.budget.maxTokens ?? 'unlimited'} tokens · ${state.elapsedMs}/${state.budget.maxElapsedMs ?? 'unlimited'} ms`,
1233
+ ...(state.lastStopDecision ? [state.lastStopDecision.reason.message] : []),
1234
+ ...(state.lastStopDecision?.evidenceRefs?.length
1235
+ ? [`Evidence: ${state.lastStopDecision.evidenceRefs.join(', ')}`]
1236
+ : []),
1230
1237
  ].join('\n');
1231
1238
  }
1232
1239
  function normalizeGoalRuntimeControl(control) {
@@ -1237,6 +1244,9 @@ function normalizeGoalRuntimeControl(control) {
1237
1244
  ...(control.budget ? { budget: control.budget } : {}),
1238
1245
  };
1239
1246
  }
1247
+ if (control.action === 'budget') {
1248
+ return { action: 'budget', budget: { ...control.budget } };
1249
+ }
1240
1250
  return { action: control.action };
1241
1251
  }
1242
1252
  function commandIdentity(command, success) {
@@ -5,6 +5,7 @@ exports.createBatchReadToolV1 = createBatchReadToolV1;
5
5
  exports.parseBatchReadStepsV1 = parseBatchReadStepsV1;
6
6
  const crypto_1 = require("crypto");
7
7
  const tool_artifacts_1 = require("../core/tool-artifacts");
8
+ const utf8_1 = require("../utils/utf8");
8
9
  exports.BATCH_READ_SERVICE_VERSION_V1 = 1;
9
10
  exports.BATCH_READ_MAX_STEPS_V1 = 8;
10
11
  exports.BATCH_READ_CHILD_OUTPUT_BYTES_V1 = 1600;
@@ -115,13 +116,28 @@ class BatchReadExecutionServiceV1 {
115
116
  skipped,
116
117
  steps: results,
117
118
  };
118
- const output = JSON.stringify(payload);
119
+ const stepsPreview = results.map(step => {
120
+ const clipped = (0, utf8_1.truncateToBytes)(step.output, exports.BATCH_READ_CHILD_OUTPUT_BYTES_V1);
121
+ return clipped.text === step.output
122
+ ? step
123
+ : { ...step, output: clipped.text, truncated: true };
124
+ });
125
+ const completeOutput = JSON.stringify(payload);
126
+ const outputBytes = Buffer.byteLength(completeOutput, 'utf8');
127
+ const hasClippedStep = stepsPreview.some((step, index) => step !== results[index]);
128
+ const artifact = hasClippedStep
129
+ ? (0, tool_artifacts_1.storeArtifact)(input.invocation.context.cwd, 'batch_read', completeOutput, outputBytes)
130
+ : undefined;
131
+ const output = hasClippedStep
132
+ ? JSON.stringify({ ...payload, steps: stepsPreview })
133
+ : completeOutput;
119
134
  const result = {
120
135
  schemaVersion: 1,
121
136
  success,
122
137
  output,
123
138
  summary,
124
- outputBytes: Buffer.byteLength(output, 'utf8'),
139
+ outputBytes,
140
+ ...(artifact ? { artifactRef: { id: artifact.id, outputBytes: artifact.outputBytes } } : {}),
125
141
  ...(!success
126
142
  ? { error: interrupted ? 'batch_read was interrupted.' : `${failed} child step(s) failed.` }
127
143
  : {}),
@@ -181,8 +197,9 @@ function completedStep(index, step, child) {
181
197
  state: 'completed',
182
198
  success: child.receipt.success,
183
199
  summary: child.result.summary ?? summarize(raw),
184
- output: (0, tool_artifacts_1.truncateForContext)(raw, exports.BATCH_READ_CHILD_OUTPUT_BYTES_V1),
185
- outputBytes: Buffer.byteLength(raw, 'utf8'),
200
+ output: raw,
201
+ outputBytes: child.result.outputBytes ?? Buffer.byteLength(raw, 'utf8'),
202
+ ...(child.result.artifactRef ? { truncated: true, artifactRef: child.result.artifactRef } : {}),
186
203
  invocationId: child.receipt.invocationId,
187
204
  receiptDigest: child.receipt.digest,
188
205
  terminal: child.receipt.terminal,
@@ -1,10 +1,10 @@
1
1
  import { type StopDecision } from '../framework/stop-decision';
2
2
  import type { TaskPlanStop } from '../harness/types';
3
3
  import type { TaskContextCompletionDecisionV1 } from './task-context-service';
4
- export type GoalLifecycleStatusV2 = 'active' | 'paused' | 'completed' | 'failed';
4
+ export type GoalLifecycleStatusV2 = 'active' | 'paused' | 'blocked' | 'usage_limited' | 'budget_limited' | 'completed' | 'failed';
5
5
  export interface GoalLifecycleBudgetV2 {
6
- readonly maxTokens: number;
7
- readonly maxElapsedMs: number;
6
+ readonly maxTokens?: number;
7
+ readonly maxElapsedMs?: number;
8
8
  }
9
9
  export interface GoalLifecycleStateV2 {
10
10
  readonly version: 2;
@@ -35,7 +35,6 @@ export interface GoalTurnObservationV2 {
35
35
  readonly continuationMode?: 'agent' | 'manual';
36
36
  /** Present only at a per-turn resource boundary; these refs must be verified by TaskContext. */
37
37
  readonly checkpoint?: {
38
- readonly unfinishedPlan: boolean;
39
38
  readonly verificationRefs: readonly string[];
40
39
  };
41
40
  }
@@ -51,6 +50,7 @@ export interface GoalLifecycleOptionsV2 {
51
50
  readonly clock?: () => number;
52
51
  readonly state?: GoalLifecycleStateV2;
53
52
  }
53
+ export declare function isGoalBudgetStopReason(code: string | undefined): boolean;
54
54
  export declare function isTaskPlanStopDecision(decision: StopDecision | undefined): decision is StopDecision & {
55
55
  reason: TaskPlanStop;
56
56
  };
@@ -67,7 +67,9 @@ export declare class GoalLifecycleServiceV2 {
67
67
  finalizeTurn(observation: GoalTurnObservationV2): GoalTurnResolutionV2;
68
68
  pause(message?: string, reason?: string): GoalLifecycleStateV2;
69
69
  resume(): GoalLifecycleStateV2;
70
+ updateBudget(update: GoalLifecycleBudgetV2, ceilings: GoalLifecycleBudgetV2): GoalLifecycleStateV2;
70
71
  private transition;
71
72
  }
72
73
  export declare function assertGoalLifecycleStateV2(state: GoalLifecycleStateV2): void;
74
+ export declare function validateGoalBudget(budget: GoalLifecycleBudgetV2): void;
73
75
  //# sourceMappingURL=goal-lifecycle-v2.d.ts.map