@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
@@ -17,8 +17,8 @@ exports.createFailedLoopStats = createFailedLoopStats;
17
17
  exports.query = query;
18
18
  const llm_1 = require("../services/llm");
19
19
  const provider_diagnostics_1 = require("../services/provider-diagnostics");
20
+ const tool_artifacts_1 = require("../core/tool-artifacts");
20
21
  const tool_1 = require("./tool");
21
- const strategy_tracker_1 = require("../core/strategy-tracker");
22
22
  const auto_compact_1 = require("../services/compact/auto-compact");
23
23
  const fingerprint_1 = require("../services/compact/fingerprint");
24
24
  const tool_call_groups_1 = require("../services/compact/tool-call-groups");
@@ -35,8 +35,6 @@ Object.defineProperty(exports, "DEFAULT_LOOP_BUDGET", { enumerable: true, get: f
35
35
  exports.DEFAULT_MAX_MODEL_VISIBLE_TOOL_RESULT_BYTES = 4096;
36
36
  /** Bounded recovery visibility after the shared compression allowance is spent. */
37
37
  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
38
  function isAborted(signal) {
41
39
  return signal?.aborted === true;
42
40
  }
@@ -87,11 +85,6 @@ function parseBatchReadEvidenceSteps(result) {
87
85
  ];
88
86
  });
89
87
  }
90
- const COMPLEX_LOOP_BUDGET = {
91
- maxLlmRequestsPerUserTurn: 48,
92
- maxToolCallsPerUserTurn: 180,
93
- maxModelVisibleToolBytes: 96 * 1024,
94
- };
95
88
  const TOOL_PRESSURE_COMPACT_RATIO = 0.9;
96
89
  class QueryLoopError extends Error {
97
90
  constructor(error, stats, aggregateUsage) {
@@ -119,12 +112,21 @@ function createLoopStats() {
119
112
  providerRetryErrorTypes: [],
120
113
  providerFallbackCount: 0,
121
114
  providerUsingFallback: false,
122
- singleReadOnlyStreak: 0,
123
- batchReadSuggestionCount: 0,
124
115
  localFastPathUsed: false,
125
116
  };
126
117
  }
127
118
  function stopDecisionForLoop(stats, finishReason) {
119
+ const resources = {
120
+ turns: { used: stats.turnsStarted },
121
+ llmRequests: { used: stats.llmRequests },
122
+ toolCalls: { used: stats.toolCalls },
123
+ modelVisibleToolBytes: {
124
+ used: stats.modelVisibleToolBytes,
125
+ ...(stats.loopBudgetMaxModelVisibleBytes === undefined
126
+ ? {}
127
+ : { limit: stats.loopBudgetMaxModelVisibleBytes }),
128
+ },
129
+ };
128
130
  if (finishReason === 'compact_paused' && stats.compactFailure) {
129
131
  const failure = stats.compactFailure;
130
132
  return (0, stop_decision_1.createStopDecision)({
@@ -146,6 +148,7 @@ function stopDecisionForLoop(stats, finishReason) {
146
148
  { kind: 'resume', label: 'Resume after changing context or budget', command: '继续' },
147
149
  ],
148
150
  resources: {
151
+ ...resources,
149
152
  tokens: {
150
153
  used: Math.max(0, Math.round(failure.afterTokens ?? failure.beforeTokens)),
151
154
  limit: Math.max(0, Math.round(failure.targetTokens)),
@@ -153,36 +156,19 @@ function stopDecisionForLoop(stats, finishReason) {
153
156
  },
154
157
  });
155
158
  }
156
- const budgetWithoutProgress = finishReason === 'budget_exceeded' && stats.budgetExhaustedWithoutProgress;
157
159
  const missingOutput = finishReason === 'failed' ? stats.missingAssistantOutput : undefined;
158
160
  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';
161
+ const status = finishReason === 'completed' ||
162
+ finishReason === 'cancelled' ||
163
+ finishReason === 'failed' ||
164
+ finishReason === 'blocked'
165
+ ? finishReason
166
+ : 'stopped';
168
167
  const reasonCode = providerStop?.code ??
169
168
  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);
169
+ (finishReason === 'budget_exceeded'
170
+ ? (stats.budgetStopCode ?? 'resource_budget')
171
+ : finishReason);
186
172
  const resumable = finishReason === 'budget_exceeded' ||
187
173
  finishReason === 'completion_gate' ||
188
174
  finishReason === 'blocked' ||
@@ -259,35 +245,13 @@ function stopDecisionForLoop(stats, finishReason) {
259
245
  message: providerStop?.message ??
260
246
  (missingOutput
261
247
  ? 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}`),
248
+ : finishReason === 'budget_exceeded'
249
+ ? (stats.budgetExceededReason ?? 'Request resource budget reached')
250
+ : `Request finished with ${finishReason}`),
267
251
  },
268
252
  evidence,
269
253
  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
- },
254
+ resources,
291
255
  });
292
256
  }
293
257
  /** Rebuild terminal loop stats and its StopDecision as one atomic projection. */
@@ -338,18 +302,14 @@ function isLoopBudgetBaseProfile(value) {
338
302
  return value === 'default' || value === 'complex' || value === 'release';
339
303
  }
340
304
  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;
305
+ const visibleBytes = partial?.maxModelVisibleToolBytes;
306
+ const hasOverride = visibleBytes !== undefined && Number.isSafeInteger(visibleBytes) && visibleBytes > 0;
307
+ const hasProfile = partial?.profile !== undefined || partial?.baseProfile !== undefined;
308
+ const configOverride = partial?.configOverride === true || (hasOverride && !hasProfile);
346
309
  return {
347
- ...loop_budget_contract_1.DEFAULT_LOOP_BUDGET,
348
- ...numericOverrides,
349
- requestPolicy: partial?.requestPolicy ??
350
- (configOverride && numericOverrides.maxLlmRequestsPerUserTurn !== undefined
351
- ? 'fixed'
352
- : 'adaptive'),
310
+ maxModelVisibleToolBytes: hasOverride
311
+ ? visibleBytes
312
+ : loop_budget_contract_1.DEFAULT_LOOP_BUDGET.maxModelVisibleToolBytes,
353
313
  profile: isLoopBudgetSource(partial?.profile)
354
314
  ? partial.profile
355
315
  : configOverride
@@ -363,38 +323,11 @@ function resolveLoopBudget(partial) {
363
323
  }
364
324
  function applyLoopBudgetStats(stats, budget) {
365
325
  stats.loopBudgetSource = budget.profile ?? 'default';
366
- stats.loopBudgetRequestPolicy = budget.requestPolicy;
367
326
  stats.loopBudgetBaseProfile =
368
327
  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
328
  stats.loopBudgetMaxModelVisibleBytes = budget.maxModelVisibleToolBytes;
376
329
  stats.loopBudgetConfigOverride = budget.configOverride === true;
377
330
  }
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
331
  function getLlmRequestDiagnostics(llm) {
399
332
  const diagnosticsReader = llm.getLastRequestDiagnostics;
400
333
  return typeof diagnosticsReader === 'function' ? diagnosticsReader.call(llm) : undefined;
@@ -418,47 +351,22 @@ function applyLlmRequestDiagnostics(stats, diagnostics) {
418
351
  stats.providerFallbackToModel = diagnostics.fallbackToModel;
419
352
  }
420
353
  }
421
- const REQUEST_BUDGET_WITHOUT_PROGRESS = 'Agent loop exhausted its request budget without successful tool work.';
422
354
  function missingAssistantOutputMessage(toolCalls) {
423
355
  const recovery = toolCalls
424
356
  ? 'Inspect the recorded tool results and ask for a checkpoint before repeating work.'
425
357
  : 'Retry the request, select another model, or ask for a brief checkpoint.';
426
358
  return `Model returned no visible response. ${recovery}`;
427
359
  }
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.';
360
+ function budgetExceededEvent(llm, stats, code, reason) {
445
361
  return {
446
362
  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'),
363
+ content: reason,
455
364
  model: llm.getModel(),
456
365
  stats: cloneLoopStats({
457
366
  ...stats,
367
+ budgetStopCode: code,
458
368
  budgetExceededReason: reason,
459
- ...(withoutProgress ? { budgetExhaustedWithoutProgress: true } : {}),
460
- continuationActions,
461
- continuationHint,
369
+ continuationActions: ['inspect_loop_stats'],
462
370
  }, 'budget_exceeded'),
463
371
  };
464
372
  }
@@ -545,7 +453,92 @@ function truncateModelField(text, maxSerializedBytes) {
545
453
  }
546
454
  return result;
547
455
  }
548
- function summarizeModelVisibleToolResult(executed, maxBytes, budgetRemainingBytes, budgetLimitBytes) {
456
+ function parseBatchPreviewSteps(output) {
457
+ const batch = parseRecord(output);
458
+ if (batch?.version !== 1 ||
459
+ !Array.isArray(batch.steps) ||
460
+ batch.steps.length === 0 ||
461
+ batch.steps.length > 8)
462
+ return;
463
+ const steps = [];
464
+ for (const [index, step] of batch.steps.entries()) {
465
+ if (!isRecord(step) ||
466
+ step.index !== index + 1 ||
467
+ typeof step.tool !== 'string' ||
468
+ !/^[a-z_]{1,32}$/u.test(step.tool) ||
469
+ (step.state !== 'completed' && step.state !== 'skipped') ||
470
+ typeof step.success !== 'boolean' ||
471
+ typeof step.output !== 'string')
472
+ return;
473
+ const terminal = typeof step.terminal === 'string' &&
474
+ ['completed', 'failed', 'interrupted', 'indeterminate'].includes(step.terminal)
475
+ ? step.terminal
476
+ : undefined;
477
+ steps.push({
478
+ index: step.index,
479
+ tool: step.tool,
480
+ state: step.state,
481
+ success: step.success,
482
+ terminal,
483
+ output: step.output,
484
+ truncated: step.truncated === true,
485
+ });
486
+ }
487
+ return steps;
488
+ }
489
+ function projectBatchPreview(steps, compactEnvelope, minimalEnvelope, maxBytes) {
490
+ const succeeded = steps.filter(step => step.state === 'completed' && step.success).length;
491
+ const skipped = steps.filter(step => step.state === 'skipped').length;
492
+ const failed = steps.length - succeeded - skipped;
493
+ const makePreview = (childBytes) => compactEnvelope(JSON.stringify({
494
+ version: 1,
495
+ success: failed === 0 && skipped === 0,
496
+ succeeded,
497
+ failed,
498
+ skipped,
499
+ steps: steps.map(step => {
500
+ const output = takeUtf8Prefix(step.output, childBytes);
501
+ return {
502
+ ...step,
503
+ output,
504
+ truncated: step.truncated || output.length < step.output.length,
505
+ };
506
+ }),
507
+ }));
508
+ let preview = makePreview(0);
509
+ if (byteLength(preview) > maxBytes) {
510
+ // The recovery floor normally fits even eight object rows. Keep the same
511
+ // child identities and terminal states for callers with a smaller limit.
512
+ const output = JSON.stringify({
513
+ version: 1,
514
+ stepFields: ['index', 'status', 'truncated'],
515
+ steps: steps.map(step => [
516
+ step.index,
517
+ step.state === 'skipped'
518
+ ? 'skipped'
519
+ : (step.terminal ?? (step.success ? 'completed' : 'failed')),
520
+ step.truncated || step.output.length > 0,
521
+ ]),
522
+ });
523
+ const compact = compactEnvelope(output);
524
+ return byteLength(compact) <= maxBytes ? compact : minimalEnvelope(output);
525
+ }
526
+ let low = 1;
527
+ let high = maxBytes;
528
+ while (low <= high) {
529
+ const middle = Math.floor((low + high) / 2);
530
+ const candidate = makePreview(middle);
531
+ if (byteLength(candidate) <= maxBytes) {
532
+ preview = candidate;
533
+ low = middle + 1;
534
+ }
535
+ else {
536
+ high = middle - 1;
537
+ }
538
+ }
539
+ return preview;
540
+ }
541
+ function summarizeModelVisibleToolResult(executed, maxBytes, budgetRemainingBytes, budgetLimitBytes, projectPath) {
549
542
  const rawBytes = byteLength(executed.result);
550
543
  const fullOutputBytes = executed.outputBytes ?? rawBytes;
551
544
  const envelope = (0, tool_serializer_1.parseToolResultEnvelope)(executed.result);
@@ -569,6 +562,44 @@ function summarizeModelVisibleToolResult(executed, maxBytes, budgetRemainingByte
569
562
  if (byteLength(fullResult) <= maxBytes) {
570
563
  return { result: fullResult, bytes: byteLength(fullResult), summarizedBytes: 0 };
571
564
  }
565
+ if (executed.prepared.tc.function.name === 'batch_read') {
566
+ const steps = parseBatchPreviewSteps(output);
567
+ if (steps) {
568
+ const existing = executed.artifactRef;
569
+ const artifact = existing &&
570
+ /^[a-z0-9_-]{1,64}$/iu.test(existing.id) &&
571
+ Number.isSafeInteger(existing.outputBytes)
572
+ ? existing
573
+ : (0, tool_artifacts_1.storeArtifact)(projectPath, 'batch_read', output, byteLength(output));
574
+ const artifactRef = artifact
575
+ ? { id: artifact.id, outputBytes: artifact.outputBytes }
576
+ : undefined;
577
+ const minimal = { success: executed.success, artifactRef };
578
+ const compactSummary = summary ? truncateModelField(summary, 128) : undefined;
579
+ const compactError = rawError ? truncateModelField(rawError, 128) : undefined;
580
+ const result = projectBatchPreview(steps, compactOutput => (0, tool_serializer_1.serializeToolResult)({
581
+ ...minimal,
582
+ output: compactOutput,
583
+ outputBytes: fullOutputBytes,
584
+ summary: compactSummary,
585
+ error: compactError,
586
+ metadata: {
587
+ modelVisibleCompressed: true,
588
+ originalResultBytes: rawBytes,
589
+ ...budgetMetadata,
590
+ },
591
+ }), compactOutput => (0, tool_serializer_1.serializeToolResult)({
592
+ ...minimal,
593
+ output: compactOutput,
594
+ metadata: {
595
+ modelVisibleCompressed: true,
596
+ budgetExhausted: budgetMetadata.budgetExhausted,
597
+ },
598
+ }), maxBytes);
599
+ const bytes = byteLength(result);
600
+ return { result, bytes, summarizedBytes: Math.max(0, fullOutputBytes - bytes), artifactRef };
601
+ }
602
+ }
572
603
  // Keep a real excerpt, status and a budget signal even after exhaustion. An
573
604
  // untrusted tool's arbitrarily large metadata must not displace the excerpt.
574
605
  const compactError = rawError ? truncateModelField(rawError, 192) : undefined;
@@ -748,20 +779,28 @@ function compactPausedEvent(llm, stats, failure, content) {
748
779
  * }
749
780
  */
750
781
  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;
782
+ const { messages, tools: initialTools, toolExecutor: initialToolExecutor, llm, abortSignal: userSignal, goalDeadlineAt, streamCallbacks, costTracker, strategyTracker, harness, maxParallelToolCalls = 6, } = params;
783
+ const remainingTime = goalDeadlineAt === undefined ? undefined : Math.max(0, goalDeadlineAt - Date.now());
784
+ // The provider and tools retain their own per-operation timeouts for distant deadlines.
785
+ const goalTimeSignal = remainingTime !== undefined && remainingTime <= 2147483647
786
+ ? AbortSignal.timeout(Math.ceil(remainingTime))
787
+ : undefined;
788
+ const abortSignal = userSignal && goalTimeSignal
789
+ ? AbortSignal.any([userSignal, goalTimeSignal])
790
+ : (userSignal ?? goalTimeSignal);
791
+ const interrupted = () => isAborted(abortSignal) || (goalDeadlineAt !== undefined && Date.now() >= goalDeadlineAt);
792
+ let input = params.input;
753
793
  let turn = 0;
754
- let consecutiveCompletionGateBlocks = 0;
794
+ const rejectedCompletionStates = new Set();
755
795
  let successfulToolCalls = 0;
756
796
  const stats = createLoopStats();
757
797
  let pendingCompact;
758
798
  const uncompactedMessages = messages.map(message => ({ ...message }));
759
799
  const appendMessage = (message) => {
760
800
  messages.push(message);
761
- uncompactedMessages.push({ ...message });
762
- if (pendingCompact) {
763
- pendingCompact.uncompactedHistory = uncompactedMessages.map(entry => ({ ...entry }));
764
- }
801
+ const snapshot = { ...message };
802
+ uncompactedMessages.push(snapshot);
803
+ pendingCompact?.uncompactedHistory.push(snapshot);
765
804
  };
766
805
  let compactPrepareSource;
767
806
  const captureCompactPrepareSource = () => {
@@ -778,26 +817,21 @@ async function* query(params) {
778
817
  return compactPrepareSource;
779
818
  };
780
819
  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' };
820
+ const loopBudget = resolveLoopBudget(params.loopBudget);
794
821
  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;
822
+ const progress = new loop_progress_1.LoopProgress(params.toolContext?.cwd ?? process.cwd());
823
+ function interruptedCompleteEvent() {
824
+ return attachCompactCommit(isAborted(userSignal)
825
+ ? cancelledCompleteEvent(llm, stats)
826
+ : budgetExceededEvent(llm, stats, 'goal_time_budget', 'Goal elapsed time allowance reached.'), pendingCompact, messages, aggregateUsage);
827
+ }
828
+ function appendSteering(steering) {
829
+ for (const text of steering)
830
+ appendMessage({ role: 'user', content: text });
831
+ if (steering.length > 0)
832
+ input = steering[steering.length - 1];
833
+ }
799
834
  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
835
  function goalTokenBudgetStop() {
802
836
  if (params.remainingGoalTokens === undefined)
803
837
  return undefined;
@@ -805,17 +839,13 @@ async function* query(params) {
805
839
  const used = usage.promptTokens + usage.completionTokens;
806
840
  if (used < params.remainingGoalTokens)
807
841
  return undefined;
808
- return attachCompactCommit(budgetExceededEvent(llm, stats, 'Goal token allowance reached'), pendingCompact, messages, usage);
842
+ return attachCompactCommit(budgetExceededEvent(llm, stats, 'goal_token_budget', 'Goal token allowance reached.'), pendingCompact, messages, usage);
809
843
  }
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
844
  while (true) {
815
845
  turn++;
816
846
  // Check abort
817
- if (isAborted(abortSignal)) {
818
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
847
+ if (interrupted()) {
848
+ yield interruptedCompleteEvent();
819
849
  return;
820
850
  }
821
851
  const goalBudgetBeforeRequest = goalTokenBudgetStop();
@@ -823,9 +853,10 @@ async function* query(params) {
823
853
  yield goalBudgetBeforeRequest;
824
854
  return;
825
855
  }
856
+ appendSteering(params.takePendingSteering?.() ?? []);
826
857
  const planStop = params.checkTaskPlanStop?.();
827
858
  if (planStop) {
828
- const finish = cloneLoopStats(stats, 'completion_gate');
859
+ const finish = cloneLoopStats(stats, planStop.code === 'task_step_blocked' ? 'blocked' : 'completion_gate');
829
860
  const decision = finish.stopDecision;
830
861
  finish.stopDecision = {
831
862
  ...decision,
@@ -839,66 +870,11 @@ async function* query(params) {
839
870
  yield attachCompactCommit({ type: 'complete', content: planStop.message, model: llm.getModel(), stats: finish }, pendingCompact, messages, aggregateUsage);
840
871
  return;
841
872
  }
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 &&
873
+ const toolOutputPressure = params.allowToolPressureCompaction === true &&
892
874
  successfulToolCalls > 0 &&
893
- consecutiveCompletionGateBlocks === 0 &&
894
- stats.toolCalls < loopBudget.maxToolCallsPerUserTurn &&
895
875
  stats.modelVisibleToolBytes >=
896
876
  Math.ceil(loopBudget.maxModelVisibleToolBytes * TOOL_PRESSURE_COMPACT_RATIO);
897
877
  const shouldTryBudgetCompact = toolOutputPressure && !pendingCompact && stats.budgetCompaction === undefined;
898
- if (requestLimitReached && !shouldTryBudgetCompact) {
899
- yield requestBudgetStop();
900
- return;
901
- }
902
878
  const resolvedStep = params.resolveStep
903
879
  ? await params.resolveStep({
904
880
  requestIndex: turn - 1,
@@ -918,10 +894,8 @@ async function* query(params) {
918
894
  tools: tools.map(tool => tool.name),
919
895
  });
920
896
  // Request start
921
- if (!requestLimitReached) {
922
- yield { type: 'request_start', model: llm.getModel(), turn };
923
- stats.turnsStarted = turn;
924
- }
897
+ yield { type: 'request_start', model: llm.getModel(), turn };
898
+ stats.turnsStarted = turn;
925
899
  const coordinator = params.compactCoordinator;
926
900
  coordinator?.configure({
927
901
  modelId: llm.getModel(),
@@ -974,14 +948,14 @@ async function* query(params) {
974
948
  compactPrepareSource = undefined;
975
949
  // The speculative validator may have written diagnostics for a prompt
976
950
  // the provider will never receive. Restore the original assembly.
977
- if (candidatePromptAssembled && harness && !requestLimitReached) {
951
+ if (candidatePromptAssembled && harness) {
978
952
  requestMessages = assembleRequest();
979
953
  requestEstimatedTokens = (0, token_estimate_1.estimateMessagesTokens)(requestMessages);
980
954
  }
981
955
  }
982
956
  }
983
- if (isAborted(abortSignal)) {
984
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
957
+ if (interrupted()) {
958
+ yield interruptedCompleteEvent();
985
959
  return;
986
960
  }
987
961
  if (!budgetCompactDue && preCompactAttempt.status === 'paused') {
@@ -1019,10 +993,6 @@ async function* query(params) {
1019
993
  after: contextAfterPredictiveCompact,
1020
994
  });
1021
995
  }
1022
- if (requestLimitReached) {
1023
- yield requestBudgetStop();
1024
- return;
1025
- }
1026
996
  const assemblyStats = harness?.toJSON().promptAssemblyStats;
1027
997
  if (assemblyStats) {
1028
998
  yield {
@@ -1058,8 +1028,8 @@ async function* query(params) {
1058
1028
  return;
1059
1029
  }
1060
1030
  }
1061
- if (isAborted(abortSignal)) {
1062
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
1031
+ if (interrupted()) {
1032
+ yield interruptedCompleteEvent();
1063
1033
  return;
1064
1034
  }
1065
1035
  if (resolvedStep.bindModelRequest) {
@@ -1091,13 +1061,13 @@ async function* query(params) {
1091
1061
  }
1092
1062
  catch (error) {
1093
1063
  applyLlmRequestDiagnostics(stats, getLlmRequestDiagnostics(llm));
1094
- if (isAborted(abortSignal)) {
1095
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
1064
+ if (interrupted()) {
1065
+ yield interruptedCompleteEvent();
1096
1066
  return;
1097
1067
  }
1098
1068
  if (error instanceof llm_1.ProviderRequestPreflightError) {
1099
1069
  stats.llmRequests = Math.max(0, stats.llmRequests - 1);
1100
- yield attachCompactCommit(budgetExceededEvent(llm, stats, error.message), pendingCompact, messages, aggregateUsage);
1070
+ yield attachCompactCommit(budgetExceededEvent(llm, stats, 'provider_preflight_budget', error.message), pendingCompact, messages, aggregateUsage);
1101
1071
  return;
1102
1072
  }
1103
1073
  if (error instanceof provider_diagnostics_1.LLMProviderError) {
@@ -1132,28 +1102,34 @@ async function* query(params) {
1132
1102
  completionTokens: (aggregateUsage?.completionTokens ?? 0) + response.usage.completionTokens,
1133
1103
  };
1134
1104
  }
1135
- if (isAborted(abortSignal)) {
1136
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
1105
+ if (interrupted()) {
1106
+ yield interruptedCompleteEvent();
1137
1107
  return;
1138
1108
  }
1139
1109
  const visibleContent = (0, terminal_text_1.hasVisibleAssistantText)(response.content) ? response.content : '';
1140
- if (response.finishReason === 'length' || response.finishReason === 'content_filter') {
1110
+ if (response.finishReason === 'length' ||
1111
+ response.finishReason === 'content_filter' ||
1112
+ response.finishReason === 'incomplete') {
1141
1113
  if (visibleContent) {
1142
1114
  appendMessage({ role: 'assistant', content: visibleContent });
1143
1115
  if (holdAssistant)
1144
1116
  streamCallbacks?.onChunk?.(visibleContent);
1145
1117
  yield { type: 'message', role: 'assistant', content: visibleContent };
1146
1118
  }
1147
- stats.providerStop =
1148
- response.finishReason === 'length'
1149
- ? {
1150
- code: 'provider_output_limit',
1151
- message: 'The provider reached its output token limit. Continue with a narrower request.',
1152
- }
1153
- : {
1154
- code: 'provider_content_filter',
1155
- message: 'The provider stopped generation at its content filter.',
1156
- };
1119
+ stats.providerStop = {
1120
+ length: {
1121
+ code: 'provider_output_limit',
1122
+ message: 'The provider reached its output token limit. Continue with a narrower request.',
1123
+ },
1124
+ content_filter: {
1125
+ code: 'provider_content_filter',
1126
+ message: 'The provider stopped generation at its content filter.',
1127
+ },
1128
+ incomplete: {
1129
+ code: 'provider_stream_incomplete',
1130
+ message: 'The provider stream ended with an incomplete response. Retry the request.',
1131
+ },
1132
+ }[response.finishReason];
1157
1133
  yield attachCompactCommit({
1158
1134
  type: 'complete',
1159
1135
  content: stats.providerStop.message,
@@ -1171,12 +1147,7 @@ async function* query(params) {
1171
1147
  // Handle tool calls
1172
1148
  if (response.toolCalls && response.toolCalls.length > 0) {
1173
1149
  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.
1150
+ // Pair every authorized call with its result before sampling again.
1180
1151
  const assistantMsg = {
1181
1152
  role: 'assistant',
1182
1153
  content: visibleContent,
@@ -1194,8 +1165,12 @@ async function* query(params) {
1194
1165
  const preparedCalls = (0, tool_call_orchestrator_1.prepareToolCalls)({
1195
1166
  toolCalls,
1196
1167
  tools,
1197
- startApproach: (toolName) => strategyTracker.startApproach(toolName),
1198
- addToolToTracker: (attemptId, toolName) => strategyTracker.addTool(attemptId, toolName),
1168
+ ...(strategyTracker
1169
+ ? {
1170
+ startApproach: (toolName) => strategyTracker.startApproach(toolName),
1171
+ addToolToTracker: (attemptId, toolName) => strategyTracker.addTool(attemptId, toolName),
1172
+ }
1173
+ : {}),
1199
1174
  harnessDriftCheck: harness
1200
1175
  ? ({ name, args }) => harness.beforeToolUse({ name, args })
1201
1176
  : undefined,
@@ -1209,13 +1184,6 @@ async function* query(params) {
1209
1184
  stats.unsafeToolCalls++;
1210
1185
  }
1211
1186
  }
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
1187
  const answeredToolCallIds = new Set();
1220
1188
  const preparedCallById = new Map(preparedCalls.map(call => [call.tc.id, call]));
1221
1189
  for (const prepared of preparedCalls) {
@@ -1234,15 +1202,15 @@ async function* query(params) {
1234
1202
  harnessBlockedResult: harness ? drift => harness.asToolBlockedResult(drift) : undefined,
1235
1203
  maxParallelToolCalls,
1236
1204
  })) {
1237
- if (isAborted(abortSignal)) {
1238
- yield attachCompactCommit(cancelledCompleteEvent(llm, stats), pendingCompact, messages, aggregateUsage);
1205
+ if (interrupted()) {
1206
+ yield interruptedCompleteEvent();
1239
1207
  return;
1240
1208
  }
1241
1209
  const { prepared } = executed;
1242
1210
  const { tc, args, attemptId } = prepared;
1243
1211
  const remainingModelVisibleBytes = Math.max(0, loopBudget.maxModelVisibleToolBytes - stats.modelVisibleToolBytes);
1244
1212
  const visibilityFloor = Math.min(exports.MIN_MODEL_VISIBLE_TOOL_RESULT_BYTES, maxModelVisibleToolResultBytes);
1245
- const modelVisible = summarizeModelVisibleToolResult(executed, Math.max(visibilityFloor, Math.min(maxModelVisibleToolResultBytes, remainingModelVisibleBytes)), remainingModelVisibleBytes, loopBudget.maxModelVisibleToolBytes);
1213
+ const modelVisible = summarizeModelVisibleToolResult(executed, Math.max(visibilityFloor, Math.min(maxModelVisibleToolResultBytes, remainingModelVisibleBytes)), remainingModelVisibleBytes, loopBudget.maxModelVisibleToolBytes, params.toolContext?.cwd);
1246
1214
  stats.toolResultBytes += executed.outputBytes ?? byteLength(executed.result);
1247
1215
  stats.modelVisibleToolBytes += modelVisible.bytes;
1248
1216
  stats.summarizedBytes += modelVisible.summarizedBytes;
@@ -1254,7 +1222,7 @@ async function* query(params) {
1254
1222
  stats.lastToolSuccess = executed.success;
1255
1223
  if (executed.success)
1256
1224
  successfulToolCalls++;
1257
- strategyTracker.recordResult(attemptId, executed.strategyResult, executed.strategyError, executed.duration);
1225
+ strategyTracker?.recordResult(attemptId, executed.strategyResult, executed.strategyError, executed.duration);
1258
1226
  harness?.recordToolResult({
1259
1227
  name: tc.function.name,
1260
1228
  args,
@@ -1268,8 +1236,7 @@ async function* query(params) {
1268
1236
  changedFile: executed.changedFile,
1269
1237
  readOnly: prepared.tool?.isReadOnly?.(args) === true,
1270
1238
  });
1271
- if (progress &&
1272
- prepared.tool &&
1239
+ if (prepared.tool &&
1273
1240
  executed.resultTrust === 'structured' &&
1274
1241
  executed.success &&
1275
1242
  tc.function.name !== 'batch_read' &&
@@ -1280,12 +1247,12 @@ async function* query(params) {
1280
1247
  output: (0, tool_serializer_1.parseToolResultEnvelope)(executed.result).output ?? '',
1281
1248
  fileEdit: prepared.tool.isFileEdit?.(args) === true,
1282
1249
  assertion: executed.externalAssertion,
1283
- }, stats.llmRequests);
1250
+ });
1284
1251
  }
1285
- if ((harness || progress) && tc.function.name === 'batch_read' && prepared.tool) {
1252
+ if (tc.function.name === 'batch_read' && prepared.tool) {
1286
1253
  for (const step of parseBatchReadEvidenceSteps(executed.result)) {
1287
1254
  if (step.success) {
1288
- progress?.observe({ name: step.tool, args: step.args, output: step.output }, stats.llmRequests);
1255
+ progress.observe({ name: step.tool, args: step.args, output: step.output });
1289
1256
  }
1290
1257
  harness?.recordToolResult({
1291
1258
  name: step.tool,
@@ -1303,6 +1270,7 @@ async function* query(params) {
1303
1270
  });
1304
1271
  }
1305
1272
  }
1273
+ stats.toolProgressObservations = progress.observations;
1306
1274
  if (executed.permissionDecision) {
1307
1275
  yield {
1308
1276
  type: 'permission_decision',
@@ -1323,7 +1291,7 @@ async function* query(params) {
1323
1291
  modelVisibleResult: modelVisible.result,
1324
1292
  duration: executed.duration,
1325
1293
  success: executed.success,
1326
- artifactRef: executed.artifactRef,
1294
+ artifactRef: modelVisible.artifactRef ?? executed.artifactRef,
1327
1295
  externalAssertion: executed.externalAssertion,
1328
1296
  error: executed.error,
1329
1297
  summary: executed.summary,
@@ -1345,7 +1313,7 @@ async function* query(params) {
1345
1313
  const skippedError = `Skipped after permission denial for ${tc.function.name}.`;
1346
1314
  const skippedResult = JSON.stringify({ success: false, error: skippedError });
1347
1315
  const skippedBytes = byteLength(skippedResult);
1348
- strategyTracker.recordResult(skippedPrepared.attemptId, 'failed', skippedError, 0);
1316
+ strategyTracker?.recordResult(skippedPrepared.attemptId, 'failed', skippedError, 0);
1349
1317
  harness?.recordToolResult({
1350
1318
  name: skipped.function.name,
1351
1319
  args: skippedPrepared.args,
@@ -1385,33 +1353,35 @@ async function* query(params) {
1385
1353
  yield attachCompactCommit(permissionBlockedEvent(llm, stats, tc.function.name, executed.error, executed.permissionDecision.source), pendingCompact, messages, aggregateUsage);
1386
1354
  return;
1387
1355
  }
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
1356
  }
1412
1357
  // Continue to next turn
1413
1358
  continue;
1414
1359
  }
1360
+ if (response.finishReason === 'tool_calls') {
1361
+ stats.providerStop = {
1362
+ code: 'provider_missing_tool_calls',
1363
+ message: 'The provider requested tool use without returning a tool call.',
1364
+ };
1365
+ yield attachCompactCommit({
1366
+ type: 'complete',
1367
+ content: stats.providerStop.message,
1368
+ model: response.model || llm.getModel(),
1369
+ stats: cloneLoopStats(stats, 'failed'),
1370
+ }, pendingCompact, messages, aggregateUsage);
1371
+ return;
1372
+ }
1373
+ const queuedSteering = params.takePendingSteering?.() ?? [];
1374
+ if (response.endTurn === false || queuedSteering.length > 0) {
1375
+ if (visibleContent) {
1376
+ appendMessage({ role: 'assistant', content: visibleContent });
1377
+ harness?.recordAssistantResponse({ ...response, content: visibleContent });
1378
+ if (holdAssistant)
1379
+ streamCallbacks?.onChunk?.(visibleContent);
1380
+ yield { type: 'message', role: 'assistant', content: visibleContent };
1381
+ }
1382
+ appendSteering(queuedSteering);
1383
+ continue;
1384
+ }
1415
1385
  // A clean provider stop may consist entirely of reasoning or invisible text.
1416
1386
  // Do not persist it or hand it to the completion gate as a final answer.
1417
1387
  if (!visibleContent) {
@@ -1436,14 +1406,28 @@ async function* query(params) {
1436
1406
  // No tool calls — done, unless the harness requires one more pass.
1437
1407
  const completionGate = harness?.beforeComplete();
1438
1408
  if (completionGate && !completionGate.canComplete) {
1439
- consecutiveCompletionGateBlocks++;
1440
- if (consecutiveCompletionGateBlocks >= 2) {
1409
+ const rejectedState = JSON.stringify([
1410
+ completionGate.missing,
1411
+ completionGate.progressDelta?.workspaceStateHash,
1412
+ completionGate.criterionResults?.map(result => [
1413
+ result.criterionId,
1414
+ result.status,
1415
+ result.verificationProblems,
1416
+ ]),
1417
+ ]);
1418
+ if (rejectedCompletionStates.has(rejectedState)) {
1441
1419
  const missing = completionGate.missing?.length
1442
1420
  ? completionGate.missing.join('; ')
1443
1421
  : 'required verification evidence is missing';
1444
1422
  const stoppedStats = cloneLoopStats(stats, 'completion_gate');
1445
1423
  if (completionGate.stopDecision) {
1446
- stoppedStats.stopDecision = completionGate.stopDecision;
1424
+ stoppedStats.stopDecision = {
1425
+ ...completionGate.stopDecision,
1426
+ resources: {
1427
+ ...stoppedStats.stopDecision?.resources,
1428
+ ...completionGate.stopDecision.resources,
1429
+ },
1430
+ };
1447
1431
  }
1448
1432
  yield attachCompactCommit({
1449
1433
  type: 'complete',
@@ -1453,11 +1437,11 @@ async function* query(params) {
1453
1437
  }, pendingCompact, messages, aggregateUsage);
1454
1438
  return;
1455
1439
  }
1440
+ rejectedCompletionStates.add(rejectedState);
1456
1441
  appendMessage(harness.asCompletionBlockedMessage(completionGate));
1457
1442
  stats.finishReason = 'completion_gate';
1458
1443
  continue;
1459
1444
  }
1460
- consecutiveCompletionGateBlocks = 0;
1461
1445
  if (holdAssistant) {
1462
1446
  appendMessage(assistantMsg);
1463
1447
  harness?.recordAssistantResponse(response);
@@ -1487,6 +1471,10 @@ async function* query(params) {
1487
1471
  const postCompactAttempt = pendingCompact
1488
1472
  ? await autoCompact.ensureHeadroomAndCompactOutcome(messages, currentContextTokens, validatePostCompact, abortSignal)
1489
1473
  : await autoCompact.checkAndCompactOutcome(messages, currentContextTokens, validatePostCompact, abortSignal);
1474
+ if (interrupted()) {
1475
+ yield interruptedCompleteEvent();
1476
+ return;
1477
+ }
1490
1478
  if (postCompactAttempt.status === 'paused') {
1491
1479
  yield attachCompactCommit(compactPausedEvent(llm, stats, postCompactAttempt.failure, response.content), pendingCompact, messages, aggregateUsage);
1492
1480
  return;
@@ -1519,6 +1507,11 @@ async function* query(params) {
1519
1507
  after: contextBeforeThresholdCompact,
1520
1508
  };
1521
1509
  }
1510
+ const finalSteering = params.takePendingSteering?.(true) ?? [];
1511
+ if (finalSteering.length > 0) {
1512
+ appendSteering(finalSteering);
1513
+ continue;
1514
+ }
1522
1515
  yield {
1523
1516
  type: 'complete',
1524
1517
  content: response.content,