@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
@@ -41,18 +41,22 @@ const ui_events_1 = require("./ui-events");
41
41
  const format_1 = require("../services/format");
42
42
  const verification_profile_1 = require("../services/verification-profile");
43
43
  const style_1 = require("../tui-core/style");
44
+ const BUDGET_STOP_KINDS = new Map([
45
+ ['llm_request_budget', 'llm_request_limit'],
46
+ ['budget_paused_compact_pending', 'llm_request_limit'],
47
+ ['request_safety_limit', 'llm_request_limit'],
48
+ ['tool_call_budget', 'tool_call_limit'],
49
+ ['goal_token_budget', 'goal_token_budget'],
50
+ ['goal_time_budget', 'goal_time_budget'],
51
+ ['provider_preflight_budget', 'provider_preflight_limit'],
52
+ ]);
44
53
  /** Build the renderer-neutral recovery card for a recoverable loop-budget stop. */
45
54
  function createLoopBudgetStopView(stats) {
46
- const reason = (0, style_1.sanitizeTerminalText)(stats.stopDecision?.reason.message ?? stats.budgetExceededReason ?? 'agent loop budget reached', 1)
55
+ const decision = stats.stopDecision;
56
+ const reasonCode = decision?.reason.code ?? stats.budgetStopCode;
57
+ const reason = (0, style_1.sanitizeTerminalText)(decision?.reason.message ?? stats.budgetExceededReason ?? 'Execution budget reached', 1)
47
58
  .replace(/\s+/gu, ' ')
48
59
  .trim();
49
- const kind = /LLM request budget/iu.test(reason)
50
- ? 'llm_request_limit'
51
- : /tool call budget/iu.test(reason)
52
- ? 'tool_call_limit'
53
- : /preflight|provider/iu.test(reason)
54
- ? 'provider_preflight_limit'
55
- : 'other';
56
60
  const tool = stats.lastToolName
57
61
  ? (0, style_1.sanitizeTerminalText)(stats.lastToolName, 1).replace(/\s+/gu, ' ').trim()
58
62
  : '';
@@ -61,31 +65,18 @@ function createLoopBudgetStopView(stats) {
61
65
  : '';
62
66
  return {
63
67
  schemaVersion: 1,
64
- kind,
68
+ kind: BUDGET_STOP_KINDS.get(reasonCode ?? '') ?? 'other',
65
69
  reason,
66
- ...(stats.stopDecision ? { reasonCode: stats.stopDecision.reason.code } : {}),
70
+ ...(reasonCode ? { reasonCode } : {}),
67
71
  recoverable: true,
68
72
  statePreserved: true,
69
73
  source: stats.loopBudgetSource,
70
- llmRequests: {
71
- current: stats.llmRequests,
72
- ...(typeof stats.loopBudgetMaxLlmRequests === 'number'
73
- ? { maximum: stats.loopBudgetMaxLlmRequests }
74
- : {}),
75
- },
76
- toolCalls: {
77
- current: stats.toolCalls,
78
- ...(typeof stats.loopBudgetMaxToolCalls === 'number'
79
- ? { maximum: stats.loopBudgetMaxToolCalls }
80
- : {}),
81
- },
74
+ llmRequests: { current: decision?.resources.llmRequests?.used ?? stats.llmRequests },
75
+ toolCalls: { current: decision?.resources.toolCalls?.used ?? stats.toolCalls },
82
76
  modelVisibleToolBytes: {
83
77
  current: stats.modelVisibleToolBytes,
84
78
  maximum: stats.loopBudgetMaxModelVisibleBytes,
85
79
  },
86
- ...(stats.loopBudgetBaseLlmRequests === undefined
87
- ? {}
88
- : { baseLlmRequestLimit: stats.loopBudgetBaseLlmRequests }),
89
80
  ...(tool
90
81
  ? {
91
82
  stopPoint: {
@@ -97,9 +88,8 @@ function createLoopBudgetStopView(stats) {
97
88
  },
98
89
  }
99
90
  : {}),
100
- actions: stats.continuationActions?.length
101
- ? [...stats.continuationActions]
102
- : ['reply_continue', 'narrow_instruction', 'inspect_loop_stats', 'raise_budget'],
91
+ actions: [...(stats.continuationActions ?? [])],
92
+ ...(decision ? { nextActions: [...decision.nextActions] } : {}),
103
93
  };
104
94
  }
105
95
  /** Select Chinese only when the current user instruction contains Han characters. */
@@ -108,39 +98,52 @@ function budgetStopLocaleForInput(input) {
108
98
  }
109
99
  /** Format every recovery action explicitly; no renderer may hide it in collapsed details. */
110
100
  function formatLoopBudgetStopView(view, locale = 'en') {
111
- const count = (current, maximum, unit) => maximum === undefined ? `${current} ${unit}` : `${current}/${maximum} ${unit}`;
112
- const llm = count(view.llmRequests.current, view.llmRequests.maximum, locale === 'zh-CN' ? '次模型请求' : 'model requests');
113
- const tools = count(view.toolCalls.current, view.toolCalls.maximum, locale === 'zh-CN' ? '次工具调用' : 'tool calls');
101
+ const chinese = locale === 'zh-CN';
102
+ const goal = view.kind === 'goal_token_budget' || view.kind === 'goal_time_budget';
103
+ const heading = goal
104
+ ? chinese
105
+ ? 'Goal 已暂停'
106
+ : 'Goal paused'
107
+ : chinese
108
+ ? '本轮已暂停'
109
+ : 'Turn paused';
110
+ const usage = chinese
111
+ ? `${view.llmRequests.current} 次模型请求,${view.toolCalls.current} 次工具调用`
112
+ : `${view.llmRequests.current} model requests, ${view.toolCalls.current} tool calls`;
113
+ const lines = [`${heading} · ${usage}`, view.reason];
114
114
  const visibleToolBytes = view.modelVisibleToolBytes;
115
- const pressure = visibleToolBytes
116
- ? count(visibleToolBytes.current, visibleToolBytes.maximum, 'bytes')
117
- : undefined;
118
- const stopPoint = view.stopPoint
119
- ? `${view.stopPoint.tool}${view.stopPoint.summary ? ` — ${view.stopPoint.summary}` : ''}`
120
- : undefined;
121
- if (locale === 'zh-CN') {
122
- const lines = [
123
- `本轮已暂停:达到单次响应的执行预算(${llm},${tools})。`,
124
- '这不是任务失败;当前会话状态已保存。',
125
- ];
126
- lines.push(view.reason);
127
- if (pressure)
128
- lines.push(`模型可见工具输出 ${pressure}(${view.source ?? 'default'})`);
129
- if (stopPoint)
130
- lines.push(`停止位置:${stopPoint}`);
131
- lines.push('下一步:', '• 回复 `继续`,按同一目标接着执行。', '• 或给出一个更小、更具体的下一步。', '• 运行 `/usage` 查看请求与工具用量。', '• 对确实需要更长运行的任务,在 orion.yaml 中调高 `agentLoop.budget`。');
132
- return lines.join('\n');
133
- }
134
- const lines = [
135
- `Turn paused: the per-response execution budget was reached (${llm}, ${tools}).`,
136
- 'This is recoverable, not a task failure; the current session state is saved.',
115
+ if (visibleToolBytes) {
116
+ const shown = (0, format_1.formatBytes)(visibleToolBytes.current);
117
+ const allowance = visibleToolBytes.maximum === undefined ? '' : ` / ${(0, format_1.formatBytes)(visibleToolBytes.maximum)}`;
118
+ lines.push(`${chinese ? '模型可见工具输出' : 'Model-visible tool output'} ${shown}${allowance}`);
119
+ }
120
+ if (view.stopPoint) {
121
+ const { tool, summary } = view.stopPoint;
122
+ lines.push(`${chinese ? '停止位置' : 'Stopped after'} · ${tool}${summary ? ` — ${summary}` : ''}`);
123
+ }
124
+ const actions = view.nextActions?.map(action => {
125
+ const command = action.command ? ` · \`${action.command}\`` : '';
126
+ return `${action.label}${command}`;
127
+ }) ?? [
128
+ ...(view.actions.includes('reply_continue') && !goal
129
+ ? [
130
+ chinese
131
+ ? '回复 `继续`,按同一目标接着执行。'
132
+ : 'Reply `继续` to continue the same objective.',
133
+ ]
134
+ : []),
135
+ ...(view.actions.includes('narrow_instruction')
136
+ ? [chinese ? '给出一个更具体的下一步。' : 'Give a smaller, concrete next step.']
137
+ : []),
138
+ ...(view.actions.includes('inspect_loop_stats')
139
+ ? [
140
+ chinese
141
+ ? '运行 `/usage` 查看请求与工具用量。'
142
+ : 'Run `/usage` to inspect request and tool usage.',
143
+ ]
144
+ : []),
137
145
  ];
138
- lines.push(view.reason);
139
- if (pressure)
140
- lines.push(`Model-visible tool output ${pressure} (${view.source ?? 'default'})`);
141
- if (stopPoint)
142
- lines.push(`Stopped after: ${stopPoint}`);
143
- lines.push('Next:', '• Reply `继续` to continue the same objective.', '• Or give a smaller, concrete next step.', '• Run `/usage` to inspect request and tool usage.', '• For intentional long work, raise `agentLoop.budget` in orion.yaml.');
146
+ lines.push(...actions.map(action => `• ${action}`));
144
147
  return lines.join('\n');
145
148
  }
146
149
  /**
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Observe file identities at verification boundaries without reading file contents.
3
+ * Git supplies the tracked and nonignored file scope when available. Other projects
4
+ * use the same filesystem walk without a Git filter.
5
+ */
6
+ export declare function captureVerificationWorkspace(workspace: string, runtimeDirectories: readonly string[]): string | null;
7
+ //# sourceMappingURL=workspace-verification.d.ts.map
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.captureVerificationWorkspace = captureVerificationWorkspace;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_fs_1 = require("node:fs");
7
+ const node_path_1 = require("node:path");
8
+ const ignoredDirectories = new Set([
9
+ '.git',
10
+ 'node_modules',
11
+ '.venv',
12
+ '__pycache__',
13
+ '.pytest_cache',
14
+ '.mypy_cache',
15
+ ]);
16
+ /**
17
+ * Observe file identities at verification boundaries without reading file contents.
18
+ * Git supplies the tracked and nonignored file scope when available. Other projects
19
+ * use the same filesystem walk without a Git filter.
20
+ */
21
+ function captureVerificationWorkspace(workspace, runtimeDirectories) {
22
+ try {
23
+ const root = (0, node_fs_1.realpathSync)(workspace);
24
+ const excluded = new Set(runtimeDirectories
25
+ .map(path => (0, node_path_1.relative)(workspace, path))
26
+ .filter(path => path && path !== '..' && !path.startsWith('..' + node_path_1.sep) && !(0, node_path_1.isAbsolute)(path))
27
+ .map(path => path.split(node_path_1.sep).join('/')));
28
+ const gitScope = listGitScope(root);
29
+ const digest = (0, node_crypto_1.createHash)('sha256').update('workspace-verification-v1\0' + root + '\0');
30
+ const visit = (directory, prefix, scope, scopeOffset = 0) => {
31
+ const entries = (0, node_fs_1.readdirSync)(directory, { withFileTypes: true }).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
32
+ for (const entry of entries) {
33
+ const path = prefix + entry.name;
34
+ if (excluded.has(path) || ignoredDirectories.has(entry.name))
35
+ continue;
36
+ const scopedPath = path.slice(scopeOffset);
37
+ if (scope && !scope.files.has(scopedPath) && !scope.ancestors.has(scopedPath))
38
+ continue;
39
+ const absolute = (0, node_path_1.join)(directory, entry.name);
40
+ const stats = (0, node_fs_1.lstatSync)(absolute, { bigint: true });
41
+ if (stats.isDirectory()) {
42
+ // A gitlink lists the directory itself only. Inspect its worktree
43
+ // against its own ignore rules rather than hashing the gitlink alone.
44
+ if (scope?.files.has(scopedPath) && !scope.ancestors.has(scopedPath)) {
45
+ visit(absolute, path + '/', listGitScope(absolute), path.length + 1);
46
+ }
47
+ else {
48
+ visit(absolute, path + '/', scope, scopeOffset);
49
+ }
50
+ continue;
51
+ }
52
+ digest.update([path, stats.dev, stats.ino, stats.mode, stats.size, stats.mtimeNs, stats.ctimeNs].join('\0') + '\0');
53
+ }
54
+ };
55
+ visit(root, '', gitScope);
56
+ return digest.digest('hex');
57
+ }
58
+ catch {
59
+ // An incomplete observation must not keep a previous check current.
60
+ return null;
61
+ }
62
+ }
63
+ function listGitScope(root) {
64
+ let search = root;
65
+ while (!(0, node_fs_1.existsSync)((0, node_path_1.join)(search, '.git'))) {
66
+ const parent = (0, node_path_1.dirname)(search);
67
+ if (parent === search)
68
+ return undefined;
69
+ search = parent;
70
+ }
71
+ const listed = (0, node_child_process_1.spawnSync)('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.'], { cwd: root, encoding: 'utf8', timeout: 2000, maxBuffer: 8 * 1024 * 1024 });
72
+ if (listed.status !== 0)
73
+ return undefined;
74
+ const files = new Set(listed.stdout.split('\0').filter(Boolean));
75
+ const ancestors = new Set();
76
+ for (const path of files) {
77
+ for (let slash = path.indexOf('/'); slash >= 0; slash = path.indexOf('/', slash + 1)) {
78
+ ancestors.add(path.slice(0, slash));
79
+ }
80
+ }
81
+ return { files, ancestors };
82
+ }
83
+ //# sourceMappingURL=workspace-verification.js.map
@@ -129,19 +129,15 @@ function loadUIConfig(globalConfig, overrides) {
129
129
  };
130
130
  }
131
131
  function loadAgentLoopConfig(globalConfig, overrides) {
132
- const budget = {
133
- ...globalConfig.agentLoop?.budget,
134
- ...overrides.agentLoop?.budget,
135
- };
132
+ const maxModelVisibleToolBytes = overrides.agentLoop?.budget?.maxModelVisibleToolBytes ??
133
+ globalConfig.agentLoop?.budget?.maxModelVisibleToolBytes;
136
134
  const continuation = overrides.agentLoop?.continuation ?? globalConfig.agentLoop?.continuation;
137
- const budgetPolicy = overrides.agentLoop?.budgetPolicy ?? globalConfig.agentLoop?.budgetPolicy;
138
135
  const goalBudget = {
139
136
  ...globalConfig.agentLoop?.goalBudget,
140
137
  ...overrides.agentLoop?.goalBudget,
141
138
  };
142
139
  const result = {
143
- ...(budgetPolicy ? { budgetPolicy } : {}),
144
- ...(Object.keys(budget).length > 0 ? { budget } : {}),
140
+ ...(maxModelVisibleToolBytes === undefined ? {} : { budget: { maxModelVisibleToolBytes } }),
145
141
  ...(continuation ? { continuation } : {}),
146
142
  ...(Object.keys(goalBudget).length > 0 ? { goalBudget } : {}),
147
143
  };
@@ -98,25 +98,17 @@ export interface SkillsConfig {
98
98
  /** Paths to skill roots or direct skill directories. */
99
99
  paths?: string[];
100
100
  }
101
- /** Agent-loop guardrails. Defaults remain internal, these fields only override them. */
101
+ /** Model-visible tool output compression. */
102
102
  export interface AgentLoopBudgetConfig {
103
- /** Maximum LLM requests allowed for one user turn. */
104
- maxLlmRequestsPerUserTurn?: number;
105
- /** Maximum tool calls allowed for one user turn. */
106
- maxToolCallsPerUserTurn?: number;
107
- /** Consecutive single read-only tool turns before injecting a batch_read hint. */
108
- maxReadOnlyFragmentation?: number;
109
103
  /** Shared tool-output compression allowance; bounded per-result recovery previews remain. */
110
104
  maxModelVisibleToolBytes?: number;
111
105
  }
112
106
  export interface AgentLoopConfig {
113
- /** Fixed uses the selected profile or explicitly configured request maximum. */
114
- budgetPolicy?: 'adaptive' | 'fixed';
115
- /** Optional budget overrides. Orion Code may still raise defaults for complex tasks. */
107
+ /** Optional tool-output compression allowance overrides. */
116
108
  budget?: AgentLoopBudgetConfig;
117
109
  /** Whether an explicitly created Goal may schedule another turn without user input. */
118
110
  continuation?: 'agent' | 'manual';
119
- /** Total bounds for newly created Goals; persisted Goal budgets survive restart/resume. */
111
+ /** Optional defaults and authorization ceilings for newly assigned Goal budgets. */
120
112
  goalBudget?: {
121
113
  maxTokens?: number;
122
114
  maxElapsedMs?: number;
@@ -272,12 +272,7 @@ function validateGlobalConfigDocumentStrict(value) {
272
272
  if (value.agentLoop !== undefined) {
273
273
  if (!isRecord(value.agentLoop))
274
274
  invalidField('agentLoop');
275
- validateKnownKeys(value.agentLoop, ['budgetPolicy', 'budget', 'continuation', 'goalBudget'], 'agentLoop');
276
- if (value.agentLoop.budgetPolicy !== undefined &&
277
- value.agentLoop.budgetPolicy !== 'adaptive' &&
278
- value.agentLoop.budgetPolicy !== 'fixed') {
279
- invalidField('agentLoop.budgetPolicy');
280
- }
275
+ validateKnownKeys(value.agentLoop, ['budget', 'continuation', 'goalBudget'], 'agentLoop');
281
276
  if (value.agentLoop.continuation !== undefined &&
282
277
  value.agentLoop.continuation !== 'agent' &&
283
278
  value.agentLoop.continuation !== 'manual') {
@@ -297,20 +292,8 @@ function validateGlobalConfigDocumentStrict(value) {
297
292
  if (value.agentLoop.budget !== undefined) {
298
293
  if (!isRecord(value.agentLoop.budget))
299
294
  invalidField('agentLoop.budget');
300
- validateKnownKeys(value.agentLoop.budget, [
301
- 'maxLlmRequestsPerUserTurn',
302
- 'maxToolCallsPerUserTurn',
303
- 'maxReadOnlyFragmentation',
304
- 'maxModelVisibleToolBytes',
305
- ], 'agentLoop.budget');
306
- for (const key of [
307
- 'maxLlmRequestsPerUserTurn',
308
- 'maxToolCallsPerUserTurn',
309
- 'maxReadOnlyFragmentation',
310
- 'maxModelVisibleToolBytes',
311
- ]) {
312
- validateOptionalPositiveInteger(value.agentLoop.budget, key, `agentLoop.budget.${key}`);
313
- }
295
+ validateKnownKeys(value.agentLoop.budget, ['maxModelVisibleToolBytes'], 'agentLoop.budget');
296
+ validateOptionalPositiveInteger(value.agentLoop.budget, 'maxModelVisibleToolBytes', 'agentLoop.budget.maxModelVisibleToolBytes');
314
297
  }
315
298
  }
316
299
  if (value.subagents !== undefined) {
@@ -429,6 +412,30 @@ function validateGlobalConfigDocumentStrict(value) {
429
412
  invalidField('providers/models');
430
413
  }
431
414
  }
415
+ /** Make retired turn counters inert while retaining supported settings and strict tree checks. */
416
+ function withoutRetiredAgentLoopSettings(document) {
417
+ if (!isRecord(document) || !isRecord(document.agentLoop))
418
+ return document;
419
+ validateDocumentTree(document);
420
+ const agentLoop = { ...document.agentLoop };
421
+ delete agentLoop.budgetPolicy;
422
+ if (isRecord(agentLoop.budget)) {
423
+ const budget = { ...agentLoop.budget };
424
+ delete budget.maxLlmRequestsPerUserTurn;
425
+ delete budget.maxToolCallsPerUserTurn;
426
+ delete budget.maxReadOnlyFragmentation;
427
+ if (Object.keys(budget).length > 0)
428
+ agentLoop.budget = budget;
429
+ else
430
+ delete agentLoop.budget;
431
+ }
432
+ const normalized = { ...document };
433
+ if (Object.keys(agentLoop).length > 0)
434
+ normalized.agentLoop = agentLoop;
435
+ else
436
+ delete normalized.agentLoop;
437
+ return normalized;
438
+ }
432
439
  /** Parse exact file bytes through the strict Settings validator. */
433
440
  function parseGlobalConfigDocumentStrict(content) {
434
441
  const text = typeof content === 'string' ? content : content.toString('utf8');
@@ -468,13 +475,15 @@ function parseGlobalConfigDocumentStrict(content) {
468
475
  })),
469
476
  };
470
477
  }
471
- validateGlobalConfigDocumentStrict(parsed);
472
- return parsed;
478
+ const document = withoutRetiredAgentLoopSettings(parsed);
479
+ validateGlobalConfigDocumentStrict(document);
480
+ return document;
473
481
  }
474
482
  /** Canonical YAML write path. Comments are not retained after a settings mutation. */
475
483
  function serializeGlobalConfigDocumentStrict(document) {
476
- validateGlobalConfigDocumentStrict(document);
477
- return (0, js_yaml_1.dump)(document, { noRefs: true, lineWidth: -1, sortKeys: false });
484
+ const normalized = withoutRetiredAgentLoopSettings(document);
485
+ validateGlobalConfigDocumentStrict(normalized);
486
+ return (0, js_yaml_1.dump)(normalized, { noRefs: true, lineWidth: -1, sortKeys: false });
478
487
  }
479
488
  const TUI_THEME_PREFERENCES = new Set([
480
489
  'orion-pixel',
@@ -664,8 +673,9 @@ function saveGlobalConfig(config) {
664
673
  }, { waitMs: 10000 });
665
674
  }
666
675
  function saveGlobalConfigUnlocked(path, config) {
667
- validateGlobalConfigDocumentStrict(config);
668
- (0, atomic_write_1.atomicWriteFileSync)(path, serializeGlobalConfigDocumentStrict(sanitizeGlobalConfig(config)), { mode: 0o600, fsync: true });
676
+ const document = withoutRetiredAgentLoopSettings(config);
677
+ validateGlobalConfigDocumentStrict(document);
678
+ (0, atomic_write_1.atomicWriteFileSync)(path, serializeGlobalConfigDocumentStrict(sanitizeGlobalConfig(document)), { mode: 0o600, fsync: true });
669
679
  }
670
680
  /**
671
681
  * 更新全局配置(部分更新)
@@ -157,6 +157,8 @@ export interface LLMResponse {
157
157
  finishReason?: LLMFinishReason;
158
158
  /** Exact non-empty provider finish_reason for diagnostics and compatibility. */
159
159
  rawFinishReason?: string;
160
+ /** Explicit provider signal about ending the turn, when supplied. */
161
+ endTurn?: boolean;
160
162
  /** 工具调用 */
161
163
  toolCalls?: Array<{
162
164
  id: string;
@@ -236,6 +236,12 @@ function extractLLMUsage(usage, response, requestId) {
236
236
  requestId: requestId || (0, crypto_1.randomUUID)(),
237
237
  };
238
238
  }
239
+ function readEndTurn(response) {
240
+ const choiceEndTurn = response.choices?.[0]?.end_turn;
241
+ if (typeof choiceEndTurn === 'boolean')
242
+ return choiceEndTurn;
243
+ return typeof response.end_turn === 'boolean' ? response.end_turn : undefined;
244
+ }
239
245
  class LLMService {
240
246
  constructor(config) {
241
247
  this.providerKey = 'default';
@@ -427,6 +433,7 @@ class LLMService {
427
433
  model: response.model ?? this.config.model,
428
434
  finishReason,
429
435
  rawFinishReason: providerFinishReason,
436
+ endTurn: readEndTurn(response),
430
437
  toolCalls,
431
438
  };
432
439
  }
@@ -532,6 +539,7 @@ class LLMService {
532
539
  let providerRequestId;
533
540
  let providerFinishReason;
534
541
  let finishReason;
542
+ let endTurn;
535
543
  const bufferForRecovery = visibleStreamText.length > 0;
536
544
  const toolCallsMap = new Map();
537
545
  for await (const chunk of stream) {
@@ -606,6 +614,7 @@ class LLMService {
606
614
  if (chunk.model) {
607
615
  usedModel = chunk.model;
608
616
  }
617
+ endTurn = readEndTurn(chunk) ?? endTurn;
609
618
  const chunkFinishReason = rawFinishReason(choice?.finish_reason);
610
619
  if (chunkFinishReason) {
611
620
  providerFinishReason = chunkFinishReason;
@@ -641,6 +650,7 @@ class LLMService {
641
650
  usage,
642
651
  finishReason,
643
652
  rawFinishReason: providerFinishReason,
653
+ endTurn,
644
654
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
645
655
  },
646
656
  usage: usage
@@ -693,6 +703,7 @@ class LLMService {
693
703
  let providerRequestId;
694
704
  let providerFinishReason;
695
705
  let finishReason;
706
+ let endTurn;
696
707
  const bufferForRecovery = visibleStreamText.length > 0;
697
708
  const toolCallsMap = new Map();
698
709
  for await (const chunk of stream) {
@@ -767,6 +778,7 @@ class LLMService {
767
778
  if (chunk.model) {
768
779
  usedModel = chunk.model;
769
780
  }
781
+ endTurn = readEndTurn(chunk) ?? endTurn;
770
782
  const chunkFinishReason = rawFinishReason(choice?.finish_reason);
771
783
  if (chunkFinishReason) {
772
784
  providerFinishReason = chunkFinishReason;
@@ -807,6 +819,7 @@ class LLMService {
807
819
  usage,
808
820
  finishReason,
809
821
  rawFinishReason: providerFinishReason,
822
+ endTurn,
810
823
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
811
824
  };
812
825
  }, retryConfig);
@@ -4,6 +4,7 @@ export interface ProviderErrorDiagnostic {
4
4
  retryable: boolean;
5
5
  status?: number;
6
6
  code?: string;
7
+ retryAt?: string;
7
8
  providerMessage: string;
8
9
  hint: string;
9
10
  }
@@ -7,6 +7,7 @@ exports.toLLMProviderError = toLLMProviderError;
7
7
  exports.formatProviderErrorMessage = formatProviderErrorMessage;
8
8
  exports.diagnoseProviderConfig = diagnoseProviderConfig;
9
9
  const model_context_1 = require("./model-context");
10
+ const error_classifier_1 = require("./provider-resilience/error-classifier");
10
11
  class LLMProviderError extends Error {
11
12
  constructor(diagnostic) {
12
13
  super(formatProviderErrorMessage(diagnostic));
@@ -160,7 +161,8 @@ function diagnoseProviderError(error) {
160
161
  ])) {
161
162
  type = 'model_not_found';
162
163
  }
163
- else if (code === '11210' ||
164
+ else if (parts.status === 402 ||
165
+ code === '11210' ||
164
166
  matchesAny(text, [
165
167
  /\bnotenoughcverror\b/,
166
168
  /\bnot enough cverror\b/,
@@ -228,11 +230,14 @@ function diagnoseProviderError(error) {
228
230
  ])) {
229
231
  type = 'invalid_endpoint';
230
232
  }
233
+ const retryAfter = type === 'quota_or_credit_exhausted' ? (0, error_classifier_1.extractRetryAfterMs)(error) : undefined;
234
+ const retryAt = retryAfter === undefined ? undefined : new Date(Date.now() + retryAfter);
231
235
  return {
232
236
  type,
233
237
  retryable: retryableFor(type, parts.status, text),
234
238
  status: parts.status,
235
239
  code: parts.code,
240
+ ...(retryAt && Number.isFinite(retryAt.getTime()) ? { retryAt: retryAt.toISOString() } : {}),
236
241
  providerMessage: parts.message,
237
242
  hint: hintFor(type),
238
243
  };
@@ -247,7 +252,8 @@ function toLLMProviderError(error) {
247
252
  function formatProviderErrorMessage(diagnostic) {
248
253
  const status = diagnostic.status ? ` status=${diagnostic.status}` : '';
249
254
  const code = diagnostic.code ? ` code=${diagnostic.code}` : '';
250
- return `LLM provider error [${diagnostic.type}${status}${code}]: ${diagnostic.hint}`;
255
+ const retry = diagnostic.retryAt ? ` Provider retry time: ${diagnostic.retryAt}.` : '';
256
+ return `LLM provider error [${diagnostic.type}${status}${code}]: ${diagnostic.hint}${retry}`;
251
257
  }
252
258
  function endpointDiagnostics(baseUrl) {
253
259
  if (!baseUrl) {
@@ -260,7 +260,8 @@ async function editFile_(path, old_string, new_string, replace_all, fuzzy_match,
260
260
  const match = fuzzyResult.matches[0];
261
261
  const idx = content.indexOf(match);
262
262
  const newContent = content.slice(0, idx) + new_string + content.slice(idx + match.length);
263
- (0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
263
+ if (newContent !== content)
264
+ (0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
264
265
  return {
265
266
  success: true,
266
267
  output: `Fuzzy edited ${normalizedPath} (matched by ${fuzzyResult.strategy}, "${match.slice(0, 50)}...")`,
@@ -285,7 +286,8 @@ async function editFile_(path, old_string, new_string, replace_all, fuzzy_match,
285
286
  const idx = content.indexOf(old_string);
286
287
  newContent = content.slice(0, idx) + new_string + content.slice(idx + old_string.length);
287
288
  }
288
- (0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
289
+ if (newContent !== content)
290
+ (0, fs_1.writeFileSync)(resolved, newContent, 'utf-8');
289
291
  return {
290
292
  success: true,
291
293
  output: `Replaced ${count} occurrence(s) of old_string with new_string in ${normalizedPath}`,
@@ -54,9 +54,11 @@ async function writeFileSync_(path, content, cwd) {
54
54
  const previous = (0, common_1.safeStatSync)(resolved);
55
55
  const bytes = Buffer.byteLength(content, 'utf8');
56
56
  const previousText = previous && previous.size === bytes && previous.isFile() ? (0, common_1.safeReadFileSync)(resolved) : null;
57
- const changed = !previous || previous.size !== bytes || (previousText !== null && previousText !== content);
58
- (0, fs_1.mkdirSync)((0, path_1.dirname)(resolved), { recursive: true });
59
- (0, fs_1.writeFileSync)(resolved, content, 'utf-8');
57
+ const changed = previousText !== content;
58
+ if (changed) {
59
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(resolved), { recursive: true });
60
+ (0, fs_1.writeFileSync)(resolved, content, 'utf-8');
61
+ }
60
62
  return {
61
63
  success: true,
62
64
  output: `Wrote ${content.split('\n').length} lines to ${normalizedPath}`,
@@ -9,7 +9,7 @@ import { type OrionCodeTool } from '../framework/tool';
9
9
  import type { TodoItem, ToolStateStore } from '../framework/tool-state';
10
10
  export declare const MAX_TODOS = 8;
11
11
  export declare const MAX_TODO_TEXT = 120;
12
- export declare function createTodoWriteTool(save: (todos: TodoItem[]) => string | void): OrionCodeTool;
12
+ export declare function createTodoWriteTool(save: (todos: TodoItem[], blockedReason?: string) => string | void): OrionCodeTool;
13
13
  export declare function createTodoTools(state: ToolStateStore): OrionCodeTool[];
14
14
  /** Get current todos (for UI display) */
15
15
  export declare function getCurrentTodos(state: ToolStateStore): TodoItem[];
@@ -70,6 +70,10 @@ ${TODO_PROMPT}`,
70
70
  parameters: {
71
71
  type: 'object',
72
72
  properties: {
73
+ blockedReason: {
74
+ type: 'string',
75
+ description: 'Report a concrete blocker and finish the current turn with the active step open.',
76
+ },
73
77
  todos: {
74
78
  type: 'array',
75
79
  minItems: 1,
@@ -150,7 +154,19 @@ ${TODO_PROMPT}`,
150
154
  error: 'Only one task can be in_progress at a time',
151
155
  };
152
156
  }
153
- const error = save(normalized);
157
+ const blocker = args.blockedReason;
158
+ if (blocker !== undefined &&
159
+ (typeof blocker !== 'string' ||
160
+ !blocker.trim() ||
161
+ blocker.length > 400 ||
162
+ inProgressCount !== 1)) {
163
+ return {
164
+ success: false,
165
+ output: '',
166
+ error: 'A blocker requires one active todo and a reason of up to 400 characters.',
167
+ };
168
+ }
169
+ const error = typeof blocker === 'string' ? save(normalized, blocker.trim()) : save(normalized);
154
170
  if (error)
155
171
  return { success: false, output: '', error };
156
172
  const completed = normalized.filter(todo => todo.status === 'completed').length;