@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
@@ -18,7 +18,6 @@ exports.query = query;
18
18
  const llm_1 = require("../services/llm");
19
19
  const provider_diagnostics_1 = require("../services/provider-diagnostics");
20
20
  const tool_1 = require("./tool");
21
- const strategy_tracker_1 = require("../core/strategy-tracker");
22
21
  const auto_compact_1 = require("../services/compact/auto-compact");
23
22
  const fingerprint_1 = require("../services/compact/fingerprint");
24
23
  const tool_call_groups_1 = require("../services/compact/tool-call-groups");
@@ -35,8 +34,6 @@ Object.defineProperty(exports, "DEFAULT_LOOP_BUDGET", { enumerable: true, get: f
35
34
  exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES = 4096;
36
35
  /** Bounded recovery visibility after the shared compression allowance is spent. */
37
36
  exports.MIN_MODEL_VISIBLE_TOOL_RESULT_BYTES = 2048;
38
- /** Read-only tools eligible for the fragmentation hint; kept loop-local so Query has no tool registry. */
39
- const BATCH_READ_ALLOWED_TOOLS = new Set(['git_status', 'list_files', 'glob', 'grep', 'read_file']);
40
37
  function isAborted(signal) {
41
38
  return signal?.aborted === true;
42
39
  }
@@ -87,11 +84,6 @@ function parseBatchReadEvidenceSteps(result) {
87
84
  ];
88
85
  });
89
86
  }
90
- const COMPLEX_LOOP_BUDGET = {
91
- maxLlmRequestsPerUserTurn: 48,
92
- maxToolCallsPerUserTurn: 180,
93
- maxModelVisibleToolBytes: 96 * 1024,
94
- };
95
87
  const TOOL_PRESSURE_COMPACT_RATIO = 0.9;
96
88
  class QueryLoopError extends Error {
97
89
  constructor(error, stats, aggregateUsage) {
@@ -119,12 +111,21 @@ function createLoopStats() {
119
111
  providerRetryErrorTypes: [],
120
112
  providerFallbackCount: 0,
121
113
  providerUsingFallback: false,
122
- singleReadOnlyStreak: 0,
123
- batchReadSuggestionCount: 0,
124
114
  localFastPathUsed: false,
125
115
  };
126
116
  }
127
117
  function stopDecisionForLoop(stats, finishReason) {
118
+ const resources = {
119
+ turns: { used: stats.turnsStarted },
120
+ llmRequests: { used: stats.llmRequests },
121
+ toolCalls: { used: stats.toolCalls },
122
+ modelVisibleToolBytes: {
123
+ used: stats.modelVisibleToolBytes,
124
+ ...(stats.loopBudgetMaxModelVisibleBytes === undefined
125
+ ? {}
126
+ : { limit: stats.loopBudgetMaxModelVisibleBytes }),
127
+ },
128
+ };
128
129
  if (finishReason === 'compact_paused' && stats.compactFailure) {
129
130
  const failure = stats.compactFailure;
130
131
  return (0, stop_decision_1.createStopDecision)({
@@ -146,6 +147,7 @@ function stopDecisionForLoop(stats, finishReason) {
146
147
  { kind: 'resume', label: 'Resume after changing context or budget', command: '继续' },
147
148
  ],
148
149
  resources: {
150
+ ...resources,
149
151
  tokens: {
150
152
  used: Math.max(0, Math.round(failure.afterTokens ?? failure.beforeTokens)),
151
153
  limit: Math.max(0, Math.round(failure.targetTokens)),
@@ -153,36 +155,19 @@ function stopDecisionForLoop(stats, finishReason) {
153
155
  },
154
156
  });
155
157
  }
156
- const budgetWithoutProgress = finishReason === 'budget_exceeded' && stats.budgetExhaustedWithoutProgress;
157
158
  const missingOutput = finishReason === 'failed' ? stats.missingAssistantOutput : undefined;
158
159
  const providerStop = finishReason === 'failed' ? stats.providerStop : undefined;
159
- const status = finishReason === 'completed'
160
- ? 'completed'
161
- : finishReason === 'cancelled'
162
- ? 'cancelled'
163
- : finishReason === 'failed' || budgetWithoutProgress
164
- ? 'failed'
165
- : finishReason === 'blocked'
166
- ? 'blocked'
167
- : 'stopped';
160
+ const status = finishReason === 'completed' ||
161
+ finishReason === 'cancelled' ||
162
+ finishReason === 'failed' ||
163
+ finishReason === 'blocked'
164
+ ? finishReason
165
+ : 'stopped';
168
166
  const reasonCode = providerStop?.code ??
169
167
  missingOutput ??
170
- (finishReason === 'budget_exceeded' ? stats.adaptiveStop : undefined) ??
171
- (budgetWithoutProgress
172
- ? 'budget_exhausted_without_progress'
173
- : finishReason === 'budget_exceeded'
174
- ? /LLM request budget/iu.test(stats.budgetExceededReason ?? '')
175
- ? stats.budgetCompactPending
176
- ? 'budget_paused_compact_pending'
177
- : stats.budgetCompaction === 'disabled'
178
- ? 'context_compact_disabled'
179
- : 'llm_request_budget'
180
- : /tool call budget/iu.test(stats.budgetExceededReason ?? '')
181
- ? 'tool_call_budget'
182
- : /preflight|provider/iu.test(stats.budgetExceededReason ?? '')
183
- ? 'provider_preflight_budget'
184
- : 'resource_budget'
185
- : finishReason);
168
+ (finishReason === 'budget_exceeded'
169
+ ? (stats.budgetStopCode ?? 'resource_budget')
170
+ : finishReason);
186
171
  const resumable = finishReason === 'budget_exceeded' ||
187
172
  finishReason === 'completion_gate' ||
188
173
  finishReason === 'blocked' ||
@@ -259,35 +244,13 @@ function stopDecisionForLoop(stats, finishReason) {
259
244
  message: providerStop?.message ??
260
245
  (missingOutput
261
246
  ? missingAssistantOutputMessage(stats.toolCalls)
262
- : budgetWithoutProgress
263
- ? (stats.adaptiveStop && stats.budgetExceededReason) || REQUEST_BUDGET_WITHOUT_PROGRESS
264
- : finishReason === 'budget_exceeded'
265
- ? budgetStopReason(stats)
266
- : `Request finished with ${finishReason}`),
247
+ : finishReason === 'budget_exceeded'
248
+ ? (stats.budgetExceededReason ?? 'Request resource budget reached')
249
+ : `Request finished with ${finishReason}`),
267
250
  },
268
251
  evidence,
269
252
  nextActions,
270
- resources: {
271
- turns: { used: stats.turnsStarted },
272
- llmRequests: {
273
- used: stats.llmRequests,
274
- ...(stats.loopBudgetMaxLlmRequests === undefined
275
- ? {}
276
- : { limit: stats.loopBudgetMaxLlmRequests }),
277
- },
278
- toolCalls: {
279
- used: stats.toolCalls,
280
- ...(stats.loopBudgetMaxToolCalls === undefined
281
- ? {}
282
- : { limit: stats.loopBudgetMaxToolCalls }),
283
- },
284
- modelVisibleToolBytes: {
285
- used: stats.modelVisibleToolBytes,
286
- ...(stats.loopBudgetMaxModelVisibleBytes === undefined
287
- ? {}
288
- : { limit: stats.loopBudgetMaxModelVisibleBytes }),
289
- },
290
- },
253
+ resources,
291
254
  });
292
255
  }
293
256
  /** Rebuild terminal loop stats and its StopDecision as one atomic projection. */
@@ -338,18 +301,14 @@ function isLoopBudgetBaseProfile(value) {
338
301
  return value === 'default' || value === 'complex' || value === 'release';
339
302
  }
340
303
  function resolveLoopBudget(partial) {
341
- const numericOverrides = Object.fromEntries(Object.entries(partial ?? {}).filter(([, value]) => typeof value === 'number' && Number.isFinite(value) && value > 0));
342
- const hasNumericOverrides = Object.keys(numericOverrides).length > 0;
343
- const hasExplicitProfile = partial?.profile !== undefined || partial?.baseProfile !== undefined;
344
- const inferredConfigOverride = hasNumericOverrides && !hasExplicitProfile;
345
- const configOverride = partial?.configOverride === true || inferredConfigOverride;
304
+ const visibleBytes = partial?.maxModelVisibleToolBytes;
305
+ const hasOverride = visibleBytes !== undefined && Number.isSafeInteger(visibleBytes) && visibleBytes > 0;
306
+ const hasProfile = partial?.profile !== undefined || partial?.baseProfile !== undefined;
307
+ const configOverride = partial?.configOverride === true || (hasOverride && !hasProfile);
346
308
  return {
347
- ...loop_budget_contract_1.DEFAULT_LOOP_BUDGET,
348
- ...numericOverrides,
349
- requestPolicy: partial?.requestPolicy ??
350
- (configOverride && numericOverrides.maxLlmRequestsPerUserTurn !== undefined
351
- ? 'fixed'
352
- : 'adaptive'),
309
+ maxModelVisibleToolBytes: hasOverride
310
+ ? visibleBytes
311
+ : loop_budget_contract_1.DEFAULT_LOOP_BUDGET.maxModelVisibleToolBytes,
353
312
  profile: isLoopBudgetSource(partial?.profile)
354
313
  ? partial.profile
355
314
  : configOverride
@@ -363,38 +322,11 @@ function resolveLoopBudget(partial) {
363
322
  }
364
323
  function applyLoopBudgetStats(stats, budget) {
365
324
  stats.loopBudgetSource = budget.profile ?? 'default';
366
- stats.loopBudgetRequestPolicy = budget.requestPolicy;
367
325
  stats.loopBudgetBaseProfile =
368
326
  budget.baseProfile ?? (budget.profile === 'config' ? 'default' : (budget.profile ?? 'default'));
369
- stats.loopBudgetMaxLlmRequests =
370
- budget.requestPolicy === 'adaptive'
371
- ? loop_budget_contract_1.ADAPTIVE_REQUEST_SAFETY_LIMIT
372
- : budget.maxLlmRequestsPerUserTurn;
373
- stats.loopBudgetMaxToolCalls = budget.maxToolCallsPerUserTurn;
374
- stats.loopBudgetMaxReadOnlyFragmentation = budget.maxReadOnlyFragmentation;
375
327
  stats.loopBudgetMaxModelVisibleBytes = budget.maxModelVisibleToolBytes;
376
328
  stats.loopBudgetConfigOverride = budget.configOverride === true;
377
329
  }
378
- function shouldPromoteDefaultBudget(stats, budget) {
379
- if (budget.requestPolicy !== 'adaptive' ||
380
- budget.configOverride === true ||
381
- budget.profile !== 'default')
382
- return false;
383
- if (stats.llmRequests < budget.maxLlmRequestsPerUserTurn)
384
- return false;
385
- return (stats.toolCalls >= 8 || stats.readOnlyToolCalls >= 6 || stats.modelVisibleToolBytes >= 16 * 1024);
386
- }
387
- function promoteDefaultBudgetToComplex(budget) {
388
- return {
389
- ...budget,
390
- maxLlmRequestsPerUserTurn: Math.max(budget.maxLlmRequestsPerUserTurn, COMPLEX_LOOP_BUDGET.maxLlmRequestsPerUserTurn),
391
- maxToolCallsPerUserTurn: Math.max(budget.maxToolCallsPerUserTurn, COMPLEX_LOOP_BUDGET.maxToolCallsPerUserTurn),
392
- maxModelVisibleToolBytes: Math.max(budget.maxModelVisibleToolBytes, COMPLEX_LOOP_BUDGET.maxModelVisibleToolBytes),
393
- profile: 'complex',
394
- baseProfile: 'complex',
395
- configOverride: false,
396
- };
397
- }
398
330
  function getLlmRequestDiagnostics(llm) {
399
331
  const diagnosticsReader = llm.getLastRequestDiagnostics;
400
332
  return typeof diagnosticsReader === 'function' ? diagnosticsReader.call(llm) : undefined;
@@ -418,47 +350,22 @@ function applyLlmRequestDiagnostics(stats, diagnostics) {
418
350
  stats.providerFallbackToModel = diagnostics.fallbackToModel;
419
351
  }
420
352
  }
421
- const REQUEST_BUDGET_WITHOUT_PROGRESS = 'Agent loop exhausted its request budget without successful tool work.';
422
353
  function missingAssistantOutputMessage(toolCalls) {
423
354
  const recovery = toolCalls
424
355
  ? 'Inspect the recorded tool results and ask for a checkpoint before repeating work.'
425
356
  : 'Retry the request, select another model, or ask for a brief checkpoint.';
426
357
  return `Model returned no visible response. ${recovery}`;
427
358
  }
428
- function budgetStopReason(stats) {
429
- const limit = stats.budgetExceededReason ?? 'Request resource budget reached';
430
- if (stats.budgetCompactPending)
431
- return `${limit}. A compact checkpoint is pending.`;
432
- if (stats.budgetCompaction === 'disabled')
433
- return `${limit}. Auto-compaction is disabled.`;
434
- if (stats.budgetCompaction === 'unavailable')
435
- return `${limit}. Compaction did not free enough context.`;
436
- return limit;
437
- }
438
- function budgetExceededEvent(llm, stats, reason, withoutProgress = false) {
439
- const continuationActions = withoutProgress
440
- ? ['inspect_loop_stats', 'narrow_instruction']
441
- : ['reply_continue', 'narrow_instruction', 'inspect_loop_stats', 'raise_budget'];
442
- const continuationHint = withoutProgress
443
- ? 'Inspect /usage and give a narrower next step or ask for a brief checkpoint.'
444
- : 'Reply `继续` to continue the same objective, give a narrower next step, inspect /usage, or raise agentLoop.budget for intentional long work.';
359
+ function budgetExceededEvent(llm, stats, code, reason) {
445
360
  return {
446
361
  type: 'complete',
447
- content: withoutProgress
448
- ? `${stats.adaptiveStop ? reason : REQUEST_BUDGET_WITHOUT_PROGRESS} Session history was saved. ${continuationHint}`
449
- : [
450
- `Agent loop budget reached: ${reason}.`,
451
- 'I stopped this turn to avoid unnecessary model requests and preserved the current session state.',
452
- 'To continue the same objective, reply `继续` or provide the next concrete step.',
453
- 'Use /usage to inspect request/tool counts. For intentional long work, raise agentLoop.budget in orion.yaml.',
454
- ].join('\n'),
362
+ content: reason,
455
363
  model: llm.getModel(),
456
364
  stats: cloneLoopStats({
457
365
  ...stats,
366
+ budgetStopCode: code,
458
367
  budgetExceededReason: reason,
459
- ...(withoutProgress ? { budgetExhaustedWithoutProgress: true } : {}),
460
- continuationActions,
461
- continuationHint,
368
+ continuationActions: ['inspect_loop_stats'],
462
369
  }, 'budget_exceeded'),
463
370
  };
464
371
  }
@@ -748,20 +655,28 @@ function compactPausedEvent(llm, stats, failure, content) {
748
655
  * }
749
656
  */
750
657
  async function* query(params) {
751
- const { messages, tools: initialTools, toolExecutor: initialToolExecutor, llm, abortSignal, streamCallbacks, costTracker, strategyTracker = (0, strategy_tracker_1.createStrategyTracker)({ maxAttempts: 5 }), // 增加到 5 次
752
- harness, input, maxParallelToolCalls = 6, } = params;
658
+ const { messages, tools: initialTools, toolExecutor: initialToolExecutor, llm, abortSignal: userSignal, goalDeadlineAt, streamCallbacks, costTracker, strategyTracker, harness, maxParallelToolCalls = 6, } = params;
659
+ const remainingTime = goalDeadlineAt === undefined ? undefined : Math.max(0, goalDeadlineAt - Date.now());
660
+ // The provider and tools retain their own per-operation timeouts for distant deadlines.
661
+ const goalTimeSignal = remainingTime !== undefined && remainingTime <= 2147483647
662
+ ? AbortSignal.timeout(Math.ceil(remainingTime))
663
+ : undefined;
664
+ const abortSignal = userSignal && goalTimeSignal
665
+ ? AbortSignal.any([userSignal, goalTimeSignal])
666
+ : (userSignal ?? goalTimeSignal);
667
+ const interrupted = () => isAborted(abortSignal) || (goalDeadlineAt !== undefined && Date.now() >= goalDeadlineAt);
668
+ let input = params.input;
753
669
  let turn = 0;
754
- let consecutiveCompletionGateBlocks = 0;
670
+ const rejectedCompletionStates = new Set();
755
671
  let successfulToolCalls = 0;
756
672
  const stats = createLoopStats();
757
673
  let pendingCompact;
758
674
  const uncompactedMessages = messages.map(message => ({ ...message }));
759
675
  const appendMessage = (message) => {
760
676
  messages.push(message);
761
- uncompactedMessages.push({ ...message });
762
- if (pendingCompact) {
763
- pendingCompact.uncompactedHistory = uncompactedMessages.map(entry => ({ ...entry }));
764
- }
677
+ const snapshot = { ...message };
678
+ uncompactedMessages.push(snapshot);
679
+ pendingCompact?.uncompactedHistory.push(snapshot);
765
680
  };
766
681
  let compactPrepareSource;
767
682
  const captureCompactPrepareSource = () => {
@@ -778,26 +693,21 @@ async function* query(params) {
778
693
  return compactPrepareSource;
779
694
  };
780
695
  let aggregateUsage;
781
- // Preserve the old option as a resource-budget alias. It no longer emits a
782
- // task-like `max_turns` completion or claims that the objective completed.
783
- const legacyRequestBudget = typeof params.maxTurns === 'number' && Number.isFinite(params.maxTurns) && params.maxTurns > 0
784
- ? Math.floor(params.maxTurns)
785
- : undefined;
786
- let loopBudget = resolveLoopBudget({
787
- ...params.loopBudget,
788
- ...(params.loopBudget?.maxLlmRequestsPerUserTurn === undefined && legacyRequestBudget
789
- ? { maxLlmRequestsPerUserTurn: legacyRequestBudget, requestPolicy: 'fixed' }
790
- : {}),
791
- });
792
- if (params.allowBudgetRecovery === false)
793
- loopBudget = { ...loopBudget, requestPolicy: 'fixed' };
696
+ const loopBudget = resolveLoopBudget(params.loopBudget);
794
697
  applyLoopBudgetStats(stats, loopBudget);
795
- const progress = loopBudget.requestPolicy === 'adaptive'
796
- ? new loop_progress_1.LoopProgress(params.toolContext?.cwd ?? process.cwd())
797
- : undefined;
798
- let nextProgressCheckpoint = loopBudget.maxLlmRequestsPerUserTurn;
698
+ const progress = new loop_progress_1.LoopProgress(params.toolContext?.cwd ?? process.cwd());
699
+ function interruptedCompleteEvent() {
700
+ return attachCompactCommit(isAborted(userSignal)
701
+ ? cancelledCompleteEvent(llm, stats)
702
+ : budgetExceededEvent(llm, stats, 'goal_time_budget', 'Goal elapsed time allowance reached.'), pendingCompact, messages, aggregateUsage);
703
+ }
704
+ function appendSteering(steering) {
705
+ for (const text of steering)
706
+ appendMessage({ role: 'user', content: text });
707
+ if (steering.length > 0)
708
+ input = steering[steering.length - 1];
709
+ }
799
710
  const maxModelVisibleToolResultBytes = Math.max(512, params.maxModelVisibleToolResultBytes ?? exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES);
800
- const fragmentedReadOnlyTools = new Set(BATCH_READ_ALLOWED_TOOLS);
801
711
  function goalTokenBudgetStop() {
802
712
  if (params.remainingGoalTokens === undefined)
803
713
  return undefined;
@@ -805,17 +715,13 @@ async function* query(params) {
805
715
  const used = usage.promptTokens + usage.completionTokens;
806
716
  if (used < params.remainingGoalTokens)
807
717
  return undefined;
808
- return attachCompactCommit(budgetExceededEvent(llm, stats, 'Goal token allowance reached'), pendingCompact, messages, usage);
718
+ return attachCompactCommit(budgetExceededEvent(llm, stats, 'goal_token_budget', 'Goal token allowance reached.'), pendingCompact, messages, usage);
809
719
  }
810
- function requestBudgetStop() {
811
- return attachCompactCommit(budgetExceededEvent(llm, { ...stats, ...(pendingCompact ? { budgetCompactPending: true } : {}) }, `LLM request budget ${loopBudget.maxLlmRequestsPerUserTurn} reached`, successfulToolCalls === 0 && consecutiveCompletionGateBlocks === 0), pendingCompact, messages, aggregateUsage);
812
- }
813
- // 无限循环,依赖安全机制停止
814
720
  while (true) {
815
721
  turn++;
816
722
  // Check abort
817
- if (isAborted(abortSignal)) {
818
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
723
+ if (interrupted()) {
724
+ yield interruptedCompleteEvent();
819
725
  return;
820
726
  }
821
727
  const goalBudgetBeforeRequest = goalTokenBudgetStop();
@@ -823,9 +729,10 @@ async function* query(params) {
823
729
  yield goalBudgetBeforeRequest;
824
730
  return;
825
731
  }
732
+ appendSteering(params.takePendingSteering?.() ?? []);
826
733
  const planStop = params.checkTaskPlanStop?.();
827
734
  if (planStop) {
828
- const finish = cloneLoopStats(stats, 'completion_gate');
735
+ const finish = cloneLoopStats(stats, planStop.code === 'task_step_blocked' ? 'blocked' : 'completion_gate');
829
736
  const decision = finish.stopDecision;
830
737
  finish.stopDecision = {
831
738
  ...decision,
@@ -839,66 +746,11 @@ async function* query(params) {
839
746
  yield attachCompactCommit({ type: 'complete', content: planStop.message, model: llm.getModel(), stats: finish }, pendingCompact, messages, aggregateUsage);
840
747
  return;
841
748
  }
842
- if (progress?.recentlyAdvanced(stats.llmRequests) &&
843
- shouldPromoteDefaultBudget(stats, loopBudget)) {
844
- loopBudget = promoteDefaultBudgetToComplex(loopBudget);
845
- applyLoopBudgetStats(stats, loopBudget);
846
- }
847
- if (progress) {
848
- const checkpoint = progress.checkpoint(stats.llmRequests);
849
- const activeStep = checkpoint !== 'working' && params.checkTaskPlanStop
850
- ? harness?.toJSON().taskTodos?.find(todo => todo.status === 'in_progress')?.content
851
- : undefined;
852
- const safetyLimitReached = stats.llmRequests >= loop_budget_contract_1.ADAPTIVE_REQUEST_SAFETY_LIMIT;
853
- if (safetyLimitReached || checkpoint === 'stop') {
854
- const adaptiveStop = safetyLimitReached
855
- ? 'request_safety_limit'
856
- : 'no_progress_after_recovery';
857
- const reason = safetyLimitReached
858
- ? `Adaptive loop reached its emergency ceiling of ${loop_budget_contract_1.ADAPTIVE_REQUEST_SAFETY_LIMIT} model requests`
859
- : activeStep
860
- ? `The checklist step “${activeStep}” did not produce new evidence after a recovery attempt.`
861
- : 'No new tool evidence was observed after attempting a narrower recovery step.';
862
- yield attachCompactCommit(budgetExceededEvent(llm, { ...stats, adaptiveStop }, reason, !safetyLimitReached), pendingCompact, messages, aggregateUsage);
863
- return;
864
- }
865
- if (checkpoint === 'recover') {
866
- appendMessage({
867
- role: 'system',
868
- content: activeStep
869
- ? `[Orion Code loop] The current checklist step is “${activeStep}”. Try a materially different, bounded action that addresses this step and report the observed blocker if it remains.`
870
- : '[Orion Code loop] No new tool evidence was observed recently. Try one materially different, bounded check that advances the user objective, or report the verified blocker without repeating earlier calls.',
871
- });
872
- yield {
873
- type: 'budget_recovery',
874
- additionalRequests: loop_progress_1.ADAPTIVE_CHECKPOINT_REQUESTS,
875
- reason: 'recovery',
876
- };
877
- }
878
- else if (stats.llmRequests >= nextProgressCheckpoint &&
879
- progress.recentlyAdvanced(stats.llmRequests)) {
880
- yield {
881
- type: 'budget_recovery',
882
- additionalRequests: loop_progress_1.ADAPTIVE_CHECKPOINT_REQUESTS,
883
- reason: 'progress',
884
- };
885
- }
886
- if (stats.llmRequests >= nextProgressCheckpoint) {
887
- nextProgressCheckpoint = stats.llmRequests + loop_progress_1.ADAPTIVE_CHECKPOINT_REQUESTS;
888
- }
889
- }
890
- const requestLimitReached = !progress && stats.llmRequests >= loopBudget.maxLlmRequestsPerUserTurn;
891
- const toolOutputPressure = params.allowBudgetRecovery === true &&
749
+ const toolOutputPressure = params.allowToolPressureCompaction === true &&
892
750
  successfulToolCalls > 0 &&
893
- consecutiveCompletionGateBlocks === 0 &&
894
- stats.toolCalls < loopBudget.maxToolCallsPerUserTurn &&
895
751
  stats.modelVisibleToolBytes >=
896
752
  Math.ceil(loopBudget.maxModelVisibleToolBytes * TOOL_PRESSURE_COMPACT_RATIO);
897
753
  const shouldTryBudgetCompact = toolOutputPressure && !pendingCompact && stats.budgetCompaction === undefined;
898
- if (requestLimitReached && !shouldTryBudgetCompact) {
899
- yield requestBudgetStop();
900
- return;
901
- }
902
754
  const resolvedStep = params.resolveStep
903
755
  ? await params.resolveStep({
904
756
  requestIndex: turn - 1,
@@ -918,10 +770,8 @@ async function* query(params) {
918
770
  tools: tools.map(tool => tool.name),
919
771
  });
920
772
  // Request start
921
- if (!requestLimitReached) {
922
- yield { type: 'request_start', model: llm.getModel(), turn };
923
- stats.turnsStarted = turn;
924
- }
773
+ yield { type: 'request_start', model: llm.getModel(), turn };
774
+ stats.turnsStarted = turn;
925
775
  const coordinator = params.compactCoordinator;
926
776
  coordinator?.configure({
927
777
  modelId: llm.getModel(),
@@ -974,14 +824,14 @@ async function* query(params) {
974
824
  compactPrepareSource = undefined;
975
825
  // The speculative validator may have written diagnostics for a prompt
976
826
  // the provider will never receive. Restore the original assembly.
977
- if (candidatePromptAssembled && harness && !requestLimitReached) {
827
+ if (candidatePromptAssembled && harness) {
978
828
  requestMessages = assembleRequest();
979
829
  requestEstimatedTokens = (0, token_estimate_1.estimateMessagesTokens)(requestMessages);
980
830
  }
981
831
  }
982
832
  }
983
- if (isAborted(abortSignal)) {
984
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
833
+ if (interrupted()) {
834
+ yield interruptedCompleteEvent();
985
835
  return;
986
836
  }
987
837
  if (!budgetCompactDue && preCompactAttempt.status === 'paused') {
@@ -1019,10 +869,6 @@ async function* query(params) {
1019
869
  after: contextAfterPredictiveCompact,
1020
870
  });
1021
871
  }
1022
- if (requestLimitReached) {
1023
- yield requestBudgetStop();
1024
- return;
1025
- }
1026
872
  const assemblyStats = harness?.toJSON().promptAssemblyStats;
1027
873
  if (assemblyStats) {
1028
874
  yield {
@@ -1058,8 +904,8 @@ async function* query(params) {
1058
904
  return;
1059
905
  }
1060
906
  }
1061
- if (isAborted(abortSignal)) {
1062
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
907
+ if (interrupted()) {
908
+ yield interruptedCompleteEvent();
1063
909
  return;
1064
910
  }
1065
911
  if (resolvedStep.bindModelRequest) {
@@ -1091,13 +937,13 @@ async function* query(params) {
1091
937
  }
1092
938
  catch (error) {
1093
939
  applyLlmRequestDiagnostics(stats, getLlmRequestDiagnostics(llm));
1094
- if (isAborted(abortSignal)) {
1095
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
940
+ if (interrupted()) {
941
+ yield interruptedCompleteEvent();
1096
942
  return;
1097
943
  }
1098
944
  if (error instanceof llm_1.ProviderRequestPreflightError) {
1099
945
  stats.llmRequests = Math.max(0, stats.llmRequests - 1);
1100
- yield attachCompactCommit(budgetExceededEvent(llm, stats, error.message), pendingCompact, messages, aggregateUsage);
946
+ yield attachCompactCommit(budgetExceededEvent(llm, stats, 'provider_preflight_budget', error.message), pendingCompact, messages, aggregateUsage);
1101
947
  return;
1102
948
  }
1103
949
  if (error instanceof provider_diagnostics_1.LLMProviderError) {
@@ -1132,8 +978,8 @@ async function* query(params) {
1132
978
  completionTokens: (aggregateUsage?.completionTokens ?? 0) + response.usage.completionTokens,
1133
979
  };
1134
980
  }
1135
- if (isAborted(abortSignal)) {
1136
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
981
+ if (interrupted()) {
982
+ yield interruptedCompleteEvent();
1137
983
  return;
1138
984
  }
1139
985
  const visibleContent = (0, terminal_text_1.hasVisibleAssistantText)(response.content) ? response.content : '';
@@ -1171,12 +1017,7 @@ async function* query(params) {
1171
1017
  // Handle tool calls
1172
1018
  if (response.toolCalls && response.toolCalls.length > 0) {
1173
1019
  const toolCalls = response.toolCalls;
1174
- if (stats.toolCalls + toolCalls.length > loopBudget.maxToolCallsPerUserTurn) {
1175
- yield attachCompactCommit(budgetExceededEvent(llm, stats, `tool call budget ${loopBudget.maxToolCallsPerUserTurn} would be exceeded by ${toolCalls.length} requested tools`), pendingCompact, messages, aggregateUsage);
1176
- return;
1177
- }
1178
- // Save assistant tool-call message only after budget checks, so future
1179
- // requests never inherit unresolved tool calls if this turn is stopped.
1020
+ // Pair every authorized call with its result before sampling again.
1180
1021
  const assistantMsg = {
1181
1022
  role: 'assistant',
1182
1023
  content: visibleContent,
@@ -1194,8 +1035,12 @@ async function* query(params) {
1194
1035
  const preparedCalls = (0, tool_call_orchestrator_1.prepareToolCalls)({
1195
1036
  toolCalls,
1196
1037
  tools,
1197
- startApproach: (toolName) => strategyTracker.startApproach(toolName),
1198
- addToolToTracker: (attemptId, toolName) => strategyTracker.addTool(attemptId, toolName),
1038
+ ...(strategyTracker
1039
+ ? {
1040
+ startApproach: (toolName) => strategyTracker.startApproach(toolName),
1041
+ addToolToTracker: (attemptId, toolName) => strategyTracker.addTool(attemptId, toolName),
1042
+ }
1043
+ : {}),
1199
1044
  harnessDriftCheck: harness
1200
1045
  ? ({ name, args }) => harness.beforeToolUse({ name, args })
1201
1046
  : undefined,
@@ -1209,13 +1054,6 @@ async function* query(params) {
1209
1054
  stats.unsafeToolCalls++;
1210
1055
  }
1211
1056
  }
1212
- const singleFragmentedReadOnlyCall = preparedCalls.length === 1 &&
1213
- preparedCalls[0].tool?.isReadOnly?.(preparedCalls[0].args) === true &&
1214
- fragmentedReadOnlyTools.has(preparedCalls[0].tc.function.name);
1215
- stats.singleReadOnlyStreak = singleFragmentedReadOnlyCall
1216
- ? stats.singleReadOnlyStreak + 1
1217
- : 0;
1218
- let pendingStrategySuggestion;
1219
1057
  const answeredToolCallIds = new Set();
1220
1058
  const preparedCallById = new Map(preparedCalls.map(call => [call.tc.id, call]));
1221
1059
  for (const prepared of preparedCalls) {
@@ -1234,8 +1072,8 @@ async function* query(params) {
1234
1072
  harnessBlockedResult: harness ? drift => harness.asToolBlockedResult(drift) : undefined,
1235
1073
  maxParallelToolCalls,
1236
1074
  })) {
1237
- if (isAborted(abortSignal)) {
1238
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
1075
+ if (interrupted()) {
1076
+ yield interruptedCompleteEvent();
1239
1077
  return;
1240
1078
  }
1241
1079
  const { prepared } = executed;
@@ -1254,7 +1092,7 @@ async function* query(params) {
1254
1092
  stats.lastToolSuccess = executed.success;
1255
1093
  if (executed.success)
1256
1094
  successfulToolCalls++;
1257
- strategyTracker.recordResult(attemptId, executed.strategyResult, executed.strategyError, executed.duration);
1095
+ strategyTracker?.recordResult(attemptId, executed.strategyResult, executed.strategyError, executed.duration);
1258
1096
  harness?.recordToolResult({
1259
1097
  name: tc.function.name,
1260
1098
  args,
@@ -1268,8 +1106,7 @@ async function* query(params) {
1268
1106
  changedFile: executed.changedFile,
1269
1107
  readOnly: prepared.tool?.isReadOnly?.(args) === true,
1270
1108
  });
1271
- if (progress &&
1272
- prepared.tool &&
1109
+ if (prepared.tool &&
1273
1110
  executed.resultTrust === 'structured' &&
1274
1111
  executed.success &&
1275
1112
  tc.function.name !== 'batch_read' &&
@@ -1280,12 +1117,12 @@ async function* query(params) {
1280
1117
  output: (0, tool_serializer_1.parseToolResultEnvelope)(executed.result).output ?? '',
1281
1118
  fileEdit: prepared.tool.isFileEdit?.(args) === true,
1282
1119
  assertion: executed.externalAssertion,
1283
- }, stats.llmRequests);
1120
+ });
1284
1121
  }
1285
- if ((harness || progress) && tc.function.name === 'batch_read' && prepared.tool) {
1122
+ if (tc.function.name === 'batch_read' && prepared.tool) {
1286
1123
  for (const step of parseBatchReadEvidenceSteps(executed.result)) {
1287
1124
  if (step.success) {
1288
- progress?.observe({ name: step.tool, args: step.args, output: step.output }, stats.llmRequests);
1125
+ progress.observe({ name: step.tool, args: step.args, output: step.output });
1289
1126
  }
1290
1127
  harness?.recordToolResult({
1291
1128
  name: step.tool,
@@ -1303,6 +1140,7 @@ async function* query(params) {
1303
1140
  });
1304
1141
  }
1305
1142
  }
1143
+ stats.toolProgressObservations = progress.observations;
1306
1144
  if (executed.permissionDecision) {
1307
1145
  yield {
1308
1146
  type: 'permission_decision',
@@ -1345,7 +1183,7 @@ async function* query(params) {
1345
1183
  const skippedError = `Skipped after permission denial for ${tc.function.name}.`;
1346
1184
  const skippedResult = JSON.stringify({ success: false, error: skippedError });
1347
1185
  const skippedBytes = byteLength(skippedResult);
1348
- strategyTracker.recordResult(skippedPrepared.attemptId, 'failed', skippedError, 0);
1186
+ strategyTracker?.recordResult(skippedPrepared.attemptId, 'failed', skippedError, 0);
1349
1187
  harness?.recordToolResult({
1350
1188
  name: skipped.function.name,
1351
1189
  args: skippedPrepared.args,
@@ -1385,33 +1223,35 @@ async function* query(params) {
1385
1223
  yield attachCompactCommit(permissionBlockedEvent(llm, stats, tc.function.name, executed.error, executed.permissionDecision.source), pendingCompact, messages, aggregateUsage);
1386
1224
  return;
1387
1225
  }
1388
- if (!pendingStrategySuggestion && strategyTracker.isExhausted()) {
1389
- pendingStrategySuggestion = strategyTracker.suggestAlternative() ?? undefined;
1390
- }
1391
- }
1392
- if (pendingStrategySuggestion) {
1393
- yield { type: 'strategy_exhausted', suggestion: pendingStrategySuggestion };
1394
- appendMessage({
1395
- role: 'user',
1396
- content: pendingStrategySuggestion,
1397
- });
1398
- strategyTracker.reset();
1399
- }
1400
- if (stats.singleReadOnlyStreak >= loopBudget.maxReadOnlyFragmentation) {
1401
- appendMessage({
1402
- role: 'system',
1403
- content: [
1404
- '[Orion Code loop hint]',
1405
- `You have made ${stats.singleReadOnlyStreak} consecutive turns with a single read-only local tool call.`,
1406
- 'For independent local exploration, prefer batch_read with up to 8 steps using git_status, list_files, glob, grep, and read_file.',
1407
- ].join(' '),
1408
- });
1409
- stats.batchReadSuggestionCount++;
1410
- stats.singleReadOnlyStreak = 0;
1411
1226
  }
1412
1227
  // Continue to next turn
1413
1228
  continue;
1414
1229
  }
1230
+ if (response.finishReason === 'tool_calls') {
1231
+ stats.providerStop = {
1232
+ code: 'provider_missing_tool_calls',
1233
+ message: 'The provider requested tool use without returning a tool call.',
1234
+ };
1235
+ yield attachCompactCommit({
1236
+ type: 'complete',
1237
+ content: stats.providerStop.message,
1238
+ model: response.model || llm.getModel(),
1239
+ stats: cloneLoopStats(stats, 'failed'),
1240
+ }, pendingCompact, messages, aggregateUsage);
1241
+ return;
1242
+ }
1243
+ const queuedSteering = params.takePendingSteering?.() ?? [];
1244
+ if (response.endTurn === false || queuedSteering.length > 0) {
1245
+ if (visibleContent) {
1246
+ appendMessage({ role: 'assistant', content: visibleContent });
1247
+ harness?.recordAssistantResponse({ ...response, content: visibleContent });
1248
+ if (holdAssistant)
1249
+ streamCallbacks?.onChunk?.(visibleContent);
1250
+ yield { type: 'message', role: 'assistant', content: visibleContent };
1251
+ }
1252
+ appendSteering(queuedSteering);
1253
+ continue;
1254
+ }
1415
1255
  // A clean provider stop may consist entirely of reasoning or invisible text.
1416
1256
  // Do not persist it or hand it to the completion gate as a final answer.
1417
1257
  if (!visibleContent) {
@@ -1436,14 +1276,24 @@ async function* query(params) {
1436
1276
  // No tool calls — done, unless the harness requires one more pass.
1437
1277
  const completionGate = harness?.beforeComplete();
1438
1278
  if (completionGate && !completionGate.canComplete) {
1439
- consecutiveCompletionGateBlocks++;
1440
- if (consecutiveCompletionGateBlocks >= 2) {
1279
+ const rejectedState = JSON.stringify([
1280
+ completionGate.missing,
1281
+ completionGate.stopDecision?.criterionStates,
1282
+ completionGate.stopDecision?.evidenceRefs,
1283
+ ]);
1284
+ if (rejectedCompletionStates.has(rejectedState)) {
1441
1285
  const missing = completionGate.missing?.length
1442
1286
  ? completionGate.missing.join('; ')
1443
1287
  : 'required verification evidence is missing';
1444
1288
  const stoppedStats = cloneLoopStats(stats, 'completion_gate');
1445
1289
  if (completionGate.stopDecision) {
1446
- stoppedStats.stopDecision = completionGate.stopDecision;
1290
+ stoppedStats.stopDecision = {
1291
+ ...completionGate.stopDecision,
1292
+ resources: {
1293
+ ...stoppedStats.stopDecision?.resources,
1294
+ ...completionGate.stopDecision.resources,
1295
+ },
1296
+ };
1447
1297
  }
1448
1298
  yield attachCompactCommit({
1449
1299
  type: 'complete',
@@ -1453,11 +1303,11 @@ async function* query(params) {
1453
1303
  }, pendingCompact, messages, aggregateUsage);
1454
1304
  return;
1455
1305
  }
1306
+ rejectedCompletionStates.add(rejectedState);
1456
1307
  appendMessage(harness.asCompletionBlockedMessage(completionGate));
1457
1308
  stats.finishReason = 'completion_gate';
1458
1309
  continue;
1459
1310
  }
1460
- consecutiveCompletionGateBlocks = 0;
1461
1311
  if (holdAssistant) {
1462
1312
  appendMessage(assistantMsg);
1463
1313
  harness?.recordAssistantResponse(response);
@@ -1487,6 +1337,10 @@ async function* query(params) {
1487
1337
  const postCompactAttempt = pendingCompact
1488
1338
  ? await autoCompact.ensureHeadroomAndCompactOutcome(messages, currentContextTokens, validatePostCompact, abortSignal)
1489
1339
  : await autoCompact.checkAndCompactOutcome(messages, currentContextTokens, validatePostCompact, abortSignal);
1340
+ if (interrupted()) {
1341
+ yield interruptedCompleteEvent();
1342
+ return;
1343
+ }
1490
1344
  if (postCompactAttempt.status === 'paused') {
1491
1345
  yield attachCompactCommit(compactPausedEvent(llm, stats, postCompactAttempt.failure, response.content), pendingCompact, messages, aggregateUsage);
1492
1346
  return;
@@ -1519,6 +1373,11 @@ async function* query(params) {
1519
1373
  after: contextBeforeThresholdCompact,
1520
1374
  };
1521
1375
  }
1376
+ const finalSteering = params.takePendingSteering?.(true) ?? [];
1377
+ if (finalSteering.length > 0) {
1378
+ appendSteering(finalSteering);
1379
+ continue;
1380
+ }
1522
1381
  yield {
1523
1382
  type: 'complete',
1524
1383
  content: response.content,