@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.
- package/CHANGELOG.md +14 -0
- package/README.md +4 -4
- package/README.zh-CN.md +4 -4
- package/dist/acp/session-updates.d.ts +4 -3
- package/dist/acp/session-updates.js +23 -2
- package/dist/acp/sessions.js +19 -6
- package/dist/commands/core-command-handlers.js +10 -22
- package/dist/commands/diagnostic-command-handlers.js +48 -52
- package/dist/commands/registry.js +1 -1
- package/dist/commands/target-command.js +49 -6
- package/dist/commands/workflow-commands.js +2 -2
- package/dist/core/tool-artifacts.js +17 -4
- package/dist/framework/loop-budget-contract.d.ts +1 -12
- package/dist/framework/loop-budget-contract.js +1 -7
- package/dist/framework/loop-progress.d.ts +3 -7
- package/dist/framework/loop-progress.js +7 -23
- package/dist/framework/query.d.ts +12 -24
- package/dist/framework/query.js +294 -301
- package/dist/framework/tool-state.d.ts +4 -0
- package/dist/harness/assembler.js +1 -1
- package/dist/harness/context-harness.d.ts +12 -2
- package/dist/harness/context-harness.js +288 -60
- package/dist/harness/contract.js +3 -1
- package/dist/harness/drift-guard.js +67 -17
- package/dist/harness/goal-verification.d.ts +11 -0
- package/dist/harness/goal-verification.js +62 -0
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/ledger.d.ts +1 -0
- package/dist/harness/ledger.js +28 -4
- package/dist/harness/progress-controller.js +57 -35
- package/dist/harness/state.js +4 -0
- package/dist/harness/stop-controller.d.ts +0 -5
- package/dist/harness/stop-controller.js +11 -31
- package/dist/harness/task-checklist.d.ts +12 -2
- package/dist/harness/task-checklist.js +50 -9
- package/dist/harness/types.d.ts +15 -0
- package/dist/harness/verification.d.ts +11 -1
- package/dist/harness/verification.js +47 -2
- package/dist/print-ui/event-stream.d.ts +5 -0
- package/dist/print-ui/event-stream.js +22 -5
- package/dist/runtime/agent-loop.d.ts +2 -1
- package/dist/runtime/agent-loop.js +23 -17
- package/dist/runtime/agent-runtime-controller.d.ts +1 -1
- package/dist/runtime/agent-runtime-controller.js +21 -11
- package/dist/runtime/batch-read-service.js +21 -4
- package/dist/runtime/goal-lifecycle-v2.d.ts +6 -4
- package/dist/runtime/goal-lifecycle-v2.js +164 -56
- package/dist/runtime/goal-runtime-coordinator.d.ts +6 -3
- package/dist/runtime/goal-runtime-coordinator.js +91 -36
- package/dist/runtime/goals/presentation.js +3 -1
- package/dist/runtime/goals/types.d.ts +1 -3
- package/dist/runtime/goals/types.js +0 -3
- package/dist/runtime/loop-budget.d.ts +0 -7
- package/dist/runtime/loop-budget.js +8 -54
- package/dist/runtime/orion-runtime-v1.js +55 -14
- package/dist/runtime/product-orion-runtime.js +30 -13
- package/dist/runtime/rsi/evaluation.js +1 -7
- package/dist/runtime/step-snapshot.d.ts +3 -1
- package/dist/runtime/step-snapshot.js +11 -1
- package/dist/runtime/subagent-thread-runtime.js +27 -5
- package/dist/runtime/subagents/production.js +0 -4
- package/dist/runtime/task-context-recovery.js +30 -7
- package/dist/runtime/task-context-service.d.ts +7 -1
- package/dist/runtime/task-context-service.js +40 -8
- package/dist/runtime/thread-admission.d.ts +2 -0
- package/dist/runtime/thread-admission.js +9 -1
- package/dist/runtime/thread-runtime.d.ts +3 -0
- package/dist/runtime/thread-runtime.js +42 -3
- package/dist/runtime/thread-ui-adapter.js +1 -11
- package/dist/runtime/tool-gateway.d.ts +2 -0
- package/dist/runtime/tool-gateway.js +4 -0
- package/dist/runtime/tool-receipt-validator.js +4 -0
- package/dist/runtime/ui-events.d.ts +3 -1
- package/dist/runtime/ui-view-model.js +62 -59
- package/dist/runtime/workspace-verification.d.ts +7 -0
- package/dist/runtime/workspace-verification.js +98 -0
- package/dist/services/chat-completion-sse.d.ts +9 -0
- package/dist/services/chat-completion-sse.js +50 -0
- package/dist/services/compact/summary-generator.d.ts +1 -1
- package/dist/services/compact/summary-generator.js +12 -0
- package/dist/services/config.js +3 -7
- package/dist/services/global-config.d.ts +3 -11
- package/dist/services/global-config.js +36 -26
- package/dist/services/llm.d.ts +3 -1
- package/dist/services/llm.js +171 -285
- package/dist/services/provider-diagnostics.d.ts +2 -1
- package/dist/services/provider-diagnostics.js +15 -4
- package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
- package/dist/services/provider-resilience/error-classifier.js +14 -0
- package/dist/tools/core/common.d.ts +0 -11
- package/dist/tools/core/common.js +0 -18
- package/dist/tools/core/edit-file.js +61 -88
- package/dist/tools/core/exec-command.js +61 -80
- package/dist/tools/core/grep.js +84 -24
- package/dist/tools/core/read-file.js +3 -2
- package/dist/tools/core/write-file.js +5 -3
- package/dist/tools/todo.d.ts +2 -2
- package/dist/tools/todo.js +29 -10
- package/dist/tui-ui/chrome-view-model.js +15 -6
- package/dist/utils/utf8.d.ts +6 -0
- package/dist/utils/utf8.js +14 -0
- package/docs/cli-guide.md +58 -40
- package/docs/orion.example.yaml +4 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/services/llm.js
CHANGED
|
@@ -15,11 +15,13 @@ exports.LLMService = exports.ProviderRequestPreflightError = exports.FallbackTri
|
|
|
15
15
|
exports.normalizeFinishReason = normalizeFinishReason;
|
|
16
16
|
const openai_1 = __importDefault(require("openai"));
|
|
17
17
|
const crypto_1 = require("crypto");
|
|
18
|
+
const chat_completion_sse_1 = require("./chat-completion-sse");
|
|
18
19
|
const provider_diagnostics_1 = require("./provider-diagnostics");
|
|
19
20
|
const provider_resilience_1 = require("./provider-resilience");
|
|
20
21
|
const tool_call_groups_1 = require("./compact/tool-call-groups");
|
|
21
22
|
const token_estimate_1 = require("../utils/token-estimate");
|
|
22
23
|
const effort_1 = require("./effort");
|
|
24
|
+
const error_classifier_1 = require("./provider-resilience/error-classifier");
|
|
23
25
|
var provider_diagnostics_2 = require("./provider-diagnostics");
|
|
24
26
|
Object.defineProperty(exports, "LLMProviderError", { enumerable: true, get: function () { return provider_diagnostics_2.LLMProviderError; } });
|
|
25
27
|
/** Fallback 触发错误 */
|
|
@@ -83,6 +85,8 @@ function providerErrorTypeForFailureKind(kind) {
|
|
|
83
85
|
return 'provider_busy';
|
|
84
86
|
case 'unsupported_effort':
|
|
85
87
|
return 'unsupported_effort';
|
|
88
|
+
case 'stream_interrupted':
|
|
89
|
+
return 'stream_interrupted';
|
|
86
90
|
default:
|
|
87
91
|
return 'unknown_provider_error';
|
|
88
92
|
}
|
|
@@ -236,6 +240,43 @@ function extractLLMUsage(usage, response, requestId) {
|
|
|
236
240
|
requestId: requestId || (0, crypto_1.randomUUID)(),
|
|
237
241
|
};
|
|
238
242
|
}
|
|
243
|
+
function readEndTurn(response) {
|
|
244
|
+
const choiceEndTurn = response.choices?.[0]?.end_turn;
|
|
245
|
+
if (typeof choiceEndTurn === 'boolean')
|
|
246
|
+
return choiceEndTurn;
|
|
247
|
+
return typeof response.end_turn === 'boolean' ? response.end_turn : undefined;
|
|
248
|
+
}
|
|
249
|
+
function readCompletionTermination(response) {
|
|
250
|
+
const choice = response.choices?.[0];
|
|
251
|
+
const raw = rawFinishReason(choice?.finish_reason);
|
|
252
|
+
return {
|
|
253
|
+
finishReason: normalizeFinishReason(raw) ??
|
|
254
|
+
(choice?.message?.tool_calls?.length ? 'tool_calls' : undefined),
|
|
255
|
+
rawFinishReason: raw,
|
|
256
|
+
endTurn: readEndTurn(response),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
function parseStreamToolArguments(text) {
|
|
260
|
+
try {
|
|
261
|
+
const value = JSON.parse(text);
|
|
262
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
263
|
+
return value;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// An incomplete argument fragment may be followed by more frames.
|
|
268
|
+
}
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
function normalizeCompleteStreamToolCall(call) {
|
|
272
|
+
if (!call.function.name.trim())
|
|
273
|
+
return false;
|
|
274
|
+
const args = parseStreamToolArguments(call.function.arguments.trim() || '{}');
|
|
275
|
+
if (!args)
|
|
276
|
+
return false;
|
|
277
|
+
call.function.arguments = JSON.stringify(args);
|
|
278
|
+
return true;
|
|
279
|
+
}
|
|
239
280
|
class LLMService {
|
|
240
281
|
constructor(config) {
|
|
241
282
|
this.providerKey = 'default';
|
|
@@ -407,9 +448,6 @@ class LLMService {
|
|
|
407
448
|
arguments: tc.function.arguments,
|
|
408
449
|
},
|
|
409
450
|
}));
|
|
410
|
-
const providerFinishReason = rawFinishReason(choice?.finish_reason);
|
|
411
|
-
const finishReason = normalizeFinishReason(providerFinishReason) ??
|
|
412
|
-
(toolCalls && toolCalls.length > 0 ? 'tool_calls' : undefined);
|
|
413
451
|
const usage = response.usage
|
|
414
452
|
? this.annotateEffortUsage(extractLLMUsage(response.usage, response, response.id), effort)
|
|
415
453
|
: undefined;
|
|
@@ -425,8 +463,7 @@ class LLMService {
|
|
|
425
463
|
content,
|
|
426
464
|
usage,
|
|
427
465
|
model: response.model ?? this.config.model,
|
|
428
|
-
|
|
429
|
-
rawFinishReason: providerFinishReason,
|
|
466
|
+
...readCompletionTermination(response),
|
|
430
467
|
toolCalls,
|
|
431
468
|
};
|
|
432
469
|
}
|
|
@@ -462,6 +499,115 @@ class LLMService {
|
|
|
462
499
|
}
|
|
463
500
|
return visibleStreamText;
|
|
464
501
|
};
|
|
502
|
+
let incompleteAttempt;
|
|
503
|
+
const readAttempt = async (route, model, signal, reporter) => {
|
|
504
|
+
const params = {
|
|
505
|
+
model,
|
|
506
|
+
messages: this.toOpenAIMessages(messages),
|
|
507
|
+
max_tokens: route.maxOutputTokens,
|
|
508
|
+
temperature: this.config.temperature,
|
|
509
|
+
stream: true,
|
|
510
|
+
stream_options: { include_usage: true },
|
|
511
|
+
...(0, effort_1.buildProviderEffortParams)(route.effort),
|
|
512
|
+
...(tools?.length ? { tools: tools } : {}),
|
|
513
|
+
};
|
|
514
|
+
onThinking?.();
|
|
515
|
+
const stream = (await route.client.chat.completions.create(params, { ...(signal ? { signal } : {}), __streamClass: chat_completion_sse_1.ChatCompletionSseStream }));
|
|
516
|
+
let content = '';
|
|
517
|
+
let usedModel = model;
|
|
518
|
+
let usage;
|
|
519
|
+
let providerRequestId;
|
|
520
|
+
let providerFinishReason;
|
|
521
|
+
let endTurn;
|
|
522
|
+
const bufferForRecovery = visibleStreamText.length > 0;
|
|
523
|
+
const toolCallsMap = new Map();
|
|
524
|
+
for await (const chunk of stream) {
|
|
525
|
+
throwIfAborted(signal);
|
|
526
|
+
const choice = chunk.choices?.[0];
|
|
527
|
+
const delta = choice?.delta;
|
|
528
|
+
const message = choice?.message;
|
|
529
|
+
const text = delta?.content ?? (content ? '' : (message?.content ?? ''));
|
|
530
|
+
if (text) {
|
|
531
|
+
content += text;
|
|
532
|
+
emitStreamText(text, bufferForRecovery, reporter);
|
|
533
|
+
}
|
|
534
|
+
if (delta?.reasoning_content)
|
|
535
|
+
onThinkingText?.(delta.reasoning_content);
|
|
536
|
+
const calls = delta?.tool_calls ?? message?.tool_calls ?? [];
|
|
537
|
+
if (calls.length > 0) {
|
|
538
|
+
reporter?.onToolCallDelta();
|
|
539
|
+
if (process.env.ORION_CODE_DEBUG_TOOLS === 'true') {
|
|
540
|
+
console.log('[DEBUG] Raw chunk:', JSON.stringify(chunk, null, 2));
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
for (const [position, call] of calls.entries()) {
|
|
544
|
+
const index = call.index ?? position;
|
|
545
|
+
const previous = toolCallsMap.get(index);
|
|
546
|
+
if (!delta?.tool_calls && !call.id && !previous)
|
|
547
|
+
continue;
|
|
548
|
+
const fragment = call.function?.arguments ?? '';
|
|
549
|
+
// Some gateways use message frames for deltas. A full named call
|
|
550
|
+
// in a message frame can also carry the authoritative snapshot.
|
|
551
|
+
const snapshot = !delta?.tool_calls && call.function?.name && parseStreamToolArguments(fragment);
|
|
552
|
+
toolCallsMap.set(index, {
|
|
553
|
+
id: call.id ?? previous?.id ?? 'call_' + index,
|
|
554
|
+
type: 'function',
|
|
555
|
+
function: {
|
|
556
|
+
name: call.function?.name || previous?.function.name || '',
|
|
557
|
+
arguments: snapshot ? fragment : (previous?.function.arguments ?? '') + fragment,
|
|
558
|
+
},
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
if (chunk.usage) {
|
|
562
|
+
usage = this.annotateEffortUsage(extractLLMUsage(chunk.usage, chunk, chunk.id ?? providerRequestId), route.effort);
|
|
563
|
+
}
|
|
564
|
+
providerRequestId = chunk.id ?? providerRequestId;
|
|
565
|
+
usedModel = chunk.model ?? usedModel;
|
|
566
|
+
endTurn = readEndTurn(chunk) ?? endTurn;
|
|
567
|
+
const finish = rawFinishReason(choice?.finish_reason);
|
|
568
|
+
if (finish) {
|
|
569
|
+
providerFinishReason = finish;
|
|
570
|
+
reporter?.onFinishReason(finish);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
throwIfAborted(signal);
|
|
574
|
+
const sawDoneEvent = stream instanceof chat_completion_sse_1.ChatCompletionSseStream && stream.sawDoneEvent;
|
|
575
|
+
let finishReason = normalizeFinishReason(providerFinishReason);
|
|
576
|
+
const toolCalls = finishReason === 'length' || finishReason === 'content_filter'
|
|
577
|
+
? []
|
|
578
|
+
: [...toolCallsMap.entries()].sort(([a], [b]) => a - b).map(([, call]) => call);
|
|
579
|
+
if ((!providerFinishReason && endTurn !== true && !sawDoneEvent) ||
|
|
580
|
+
!toolCalls.every(normalizeCompleteStreamToolCall)) {
|
|
581
|
+
incompleteAttempt = { model: usedModel, usage };
|
|
582
|
+
throw new error_classifier_1.ProviderStreamIncompleteError();
|
|
583
|
+
}
|
|
584
|
+
if (!providerFinishReason)
|
|
585
|
+
reporter?.onFinishReason(sawDoneEvent ? '[DONE]' : 'end_turn');
|
|
586
|
+
finishReason ?? (finishReason = toolCalls.length > 0 ? 'tool_calls' : 'stop');
|
|
587
|
+
const response = {
|
|
588
|
+
content: finalizeStreamText(content, bufferForRecovery),
|
|
589
|
+
model: usedModel,
|
|
590
|
+
usage,
|
|
591
|
+
finishReason,
|
|
592
|
+
rawFinishReason: providerFinishReason,
|
|
593
|
+
endTurn,
|
|
594
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
595
|
+
};
|
|
596
|
+
incompleteAttempt = undefined;
|
|
597
|
+
if (usage)
|
|
598
|
+
this.publishUsage(usage, usedModel, 'chat_stream');
|
|
599
|
+
return {
|
|
600
|
+
response,
|
|
601
|
+
usage: usage
|
|
602
|
+
? {
|
|
603
|
+
promptTokens: usage.promptTokens,
|
|
604
|
+
completionTokens: usage.completionTokens,
|
|
605
|
+
totalTokens: usage.promptTokens + usage.completionTokens,
|
|
606
|
+
}
|
|
607
|
+
: undefined,
|
|
608
|
+
providerRequestId,
|
|
609
|
+
};
|
|
610
|
+
};
|
|
465
611
|
const retryConfig = {
|
|
466
612
|
maxRetries: this.config.maxRetries,
|
|
467
613
|
baseDelayMs: this.config.retryBaseDelay,
|
|
@@ -511,147 +657,7 @@ class LLMService {
|
|
|
511
657
|
throwIfAborted(signal);
|
|
512
658
|
await this.assertProviderRequestAllowed('chat_stream', attempt, messages, model);
|
|
513
659
|
const route = this.requestRoute(modelSnapshot, model, providerKey);
|
|
514
|
-
|
|
515
|
-
model,
|
|
516
|
-
messages: this.toOpenAIMessages(messages),
|
|
517
|
-
max_tokens: route.maxOutputTokens,
|
|
518
|
-
temperature: this.config.temperature,
|
|
519
|
-
stream: true,
|
|
520
|
-
stream_options: { include_usage: true },
|
|
521
|
-
...(0, effort_1.buildProviderEffortParams)(route.effort),
|
|
522
|
-
};
|
|
523
|
-
if (tools && tools.length > 0) {
|
|
524
|
-
params.tools = tools;
|
|
525
|
-
}
|
|
526
|
-
onThinking?.();
|
|
527
|
-
const requestOptions = signal ? { signal } : undefined;
|
|
528
|
-
const stream = (await route.client.chat.completions.create(params, requestOptions));
|
|
529
|
-
let content = '';
|
|
530
|
-
let usedModel = model;
|
|
531
|
-
let usage;
|
|
532
|
-
let providerRequestId;
|
|
533
|
-
let providerFinishReason;
|
|
534
|
-
let finishReason;
|
|
535
|
-
const bufferForRecovery = visibleStreamText.length > 0;
|
|
536
|
-
const toolCallsMap = new Map();
|
|
537
|
-
for await (const chunk of stream) {
|
|
538
|
-
throwIfAborted(signal);
|
|
539
|
-
// Debug: log raw chunk when tool_calls present
|
|
540
|
-
if (process.env.ORION_CODE_DEBUG_TOOLS === 'true') {
|
|
541
|
-
const delta = chunk.choices?.[0]?.delta;
|
|
542
|
-
if (delta?.tool_calls || chunk.choices?.[0]?.message?.tool_calls) {
|
|
543
|
-
console.log('[DEBUG] Raw chunk:', JSON.stringify(chunk, null, 2));
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
const choice = chunk.choices?.[0];
|
|
547
|
-
const delta = choice?.delta;
|
|
548
|
-
const msg = choice?.message;
|
|
549
|
-
const text = delta?.content ?? (content ? '' : (msg?.content ?? ''));
|
|
550
|
-
if (text) {
|
|
551
|
-
content += text;
|
|
552
|
-
emitStreamText(text, bufferForRecovery, reporter);
|
|
553
|
-
}
|
|
554
|
-
const thinkingDelta = delta?.reasoning_content;
|
|
555
|
-
if (thinkingDelta) {
|
|
556
|
-
onThinkingText?.(thinkingDelta);
|
|
557
|
-
}
|
|
558
|
-
if ((delta?.tool_calls?.length ?? 0) > 0 || (msg?.tool_calls?.length ?? 0) > 0) {
|
|
559
|
-
reporter?.onToolCallDelta();
|
|
560
|
-
}
|
|
561
|
-
for (const tc of delta?.tool_calls ?? []) {
|
|
562
|
-
const idx = tc.index ?? 0;
|
|
563
|
-
const existing = toolCallsMap.get(idx);
|
|
564
|
-
if (!existing) {
|
|
565
|
-
toolCallsMap.set(idx, {
|
|
566
|
-
id: tc.id ?? `call_${idx}`,
|
|
567
|
-
type: 'function',
|
|
568
|
-
function: {
|
|
569
|
-
name: tc.function?.name ?? '',
|
|
570
|
-
arguments: tc.function?.arguments ?? '',
|
|
571
|
-
},
|
|
572
|
-
});
|
|
573
|
-
}
|
|
574
|
-
else {
|
|
575
|
-
if (tc.id)
|
|
576
|
-
existing.id = tc.id;
|
|
577
|
-
if (tc.function?.name)
|
|
578
|
-
existing.function.name = tc.function.name;
|
|
579
|
-
if (tc.function?.arguments)
|
|
580
|
-
existing.function.arguments += tc.function.arguments;
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
if (msg?.tool_calls && !delta?.tool_calls) {
|
|
584
|
-
for (const msgTc of msg.tool_calls) {
|
|
585
|
-
const existing = toolCallsMap.get(msgTc.index ?? 0);
|
|
586
|
-
if (!existing && msgTc.id) {
|
|
587
|
-
toolCallsMap.set(msgTc.index ?? 0, {
|
|
588
|
-
id: msgTc.id,
|
|
589
|
-
type: 'function',
|
|
590
|
-
function: {
|
|
591
|
-
name: msgTc.function?.name ?? '',
|
|
592
|
-
arguments: msgTc.function?.arguments ?? '',
|
|
593
|
-
},
|
|
594
|
-
});
|
|
595
|
-
}
|
|
596
|
-
else if (existing && msgTc.function?.arguments) {
|
|
597
|
-
existing.function.arguments += msgTc.function.arguments;
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
if (chunk.usage) {
|
|
602
|
-
usage = this.annotateEffortUsage(extractLLMUsage(chunk.usage, chunk, chunk.id ?? providerRequestId), route.effort);
|
|
603
|
-
}
|
|
604
|
-
if (chunk.id)
|
|
605
|
-
providerRequestId = chunk.id;
|
|
606
|
-
if (chunk.model) {
|
|
607
|
-
usedModel = chunk.model;
|
|
608
|
-
}
|
|
609
|
-
const chunkFinishReason = rawFinishReason(choice?.finish_reason);
|
|
610
|
-
if (chunkFinishReason) {
|
|
611
|
-
providerFinishReason = chunkFinishReason;
|
|
612
|
-
finishReason = normalizeFinishReason(chunkFinishReason);
|
|
613
|
-
reporter?.onFinishReason(chunkFinishReason);
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
const toolCalls = Array.from(toolCallsMap.entries())
|
|
617
|
-
.sort(([a], [b]) => Number(a) - Number(b))
|
|
618
|
-
.map(([, value]) => value);
|
|
619
|
-
for (const tc of toolCalls) {
|
|
620
|
-
if (!tc.function.arguments || tc.function.arguments.trim() === '') {
|
|
621
|
-
tc.function.arguments = '{}';
|
|
622
|
-
}
|
|
623
|
-
else {
|
|
624
|
-
try {
|
|
625
|
-
const parsed = JSON.parse(tc.function.arguments);
|
|
626
|
-
tc.function.arguments = JSON.stringify(parsed);
|
|
627
|
-
}
|
|
628
|
-
catch {
|
|
629
|
-
tc.function.arguments = '{}';
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
finishReason ?? (finishReason = toolCalls.length > 0 ? 'tool_calls' : undefined);
|
|
634
|
-
const finalContent = finalizeStreamText(content, bufferForRecovery);
|
|
635
|
-
if (usage)
|
|
636
|
-
this.publishUsage(usage, usedModel, 'chat_stream');
|
|
637
|
-
return {
|
|
638
|
-
response: {
|
|
639
|
-
content: finalContent,
|
|
640
|
-
model: usedModel,
|
|
641
|
-
usage,
|
|
642
|
-
finishReason,
|
|
643
|
-
rawFinishReason: providerFinishReason,
|
|
644
|
-
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
645
|
-
},
|
|
646
|
-
usage: usage
|
|
647
|
-
? {
|
|
648
|
-
promptTokens: usage.promptTokens,
|
|
649
|
-
completionTokens: usage.completionTokens,
|
|
650
|
-
totalTokens: usage.promptTokens + usage.completionTokens,
|
|
651
|
-
}
|
|
652
|
-
: undefined,
|
|
653
|
-
providerRequestId,
|
|
654
|
-
};
|
|
660
|
+
return readAttempt(route, model, signal, reporter);
|
|
655
661
|
});
|
|
656
662
|
// Unpack resilience result
|
|
657
663
|
const response = streamResult.result;
|
|
@@ -672,143 +678,9 @@ class LLMService {
|
|
|
672
678
|
const route = this.usingFallback && modelSnapshot.fallback
|
|
673
679
|
? modelSnapshot.fallback
|
|
674
680
|
: this.requestRoute(modelSnapshot, this.config.model);
|
|
675
|
-
const
|
|
676
|
-
model: this.config.model,
|
|
677
|
-
messages: this.toOpenAIMessages(messages),
|
|
678
|
-
max_tokens: route.maxOutputTokens,
|
|
679
|
-
temperature: this.config.temperature,
|
|
680
|
-
stream: true,
|
|
681
|
-
stream_options: { include_usage: true },
|
|
682
|
-
...(0, effort_1.buildProviderEffortParams)(route.effort),
|
|
683
|
-
};
|
|
684
|
-
if (tools && tools.length > 0) {
|
|
685
|
-
params.tools = tools;
|
|
686
|
-
}
|
|
687
|
-
onThinking?.();
|
|
688
|
-
const requestOptions = options?.abortSignal ? { signal: options.abortSignal } : undefined;
|
|
689
|
-
const stream = (await route.client.chat.completions.create(params, requestOptions));
|
|
690
|
-
let content = '';
|
|
691
|
-
let usedModel = this.config.model;
|
|
692
|
-
let usage;
|
|
693
|
-
let providerRequestId;
|
|
694
|
-
let providerFinishReason;
|
|
695
|
-
let finishReason;
|
|
696
|
-
const bufferForRecovery = visibleStreamText.length > 0;
|
|
697
|
-
const toolCallsMap = new Map();
|
|
698
|
-
for await (const chunk of stream) {
|
|
699
|
-
throwIfAborted(options?.abortSignal);
|
|
700
|
-
// Debug: log raw chunk when tool_calls present (for diagnosing API compatibility)
|
|
701
|
-
if (process.env.ORION_CODE_DEBUG_TOOLS === 'true') {
|
|
702
|
-
const delta = chunk.choices?.[0]?.delta;
|
|
703
|
-
if (delta?.tool_calls || chunk.choices?.[0]?.message?.tool_calls) {
|
|
704
|
-
console.log('[DEBUG] Raw chunk:', JSON.stringify(chunk, null, 2));
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
const choice = chunk.choices?.[0];
|
|
708
|
-
const delta = choice?.delta;
|
|
709
|
-
const msg = choice?.message;
|
|
710
|
-
const text = delta?.content ?? (content ? '' : (msg?.content ?? ''));
|
|
711
|
-
if (text) {
|
|
712
|
-
content += text;
|
|
713
|
-
emitStreamText(text, bufferForRecovery);
|
|
714
|
-
}
|
|
715
|
-
const thinkingDelta = delta?.reasoning_content;
|
|
716
|
-
if (thinkingDelta) {
|
|
717
|
-
onThinkingText?.(thinkingDelta);
|
|
718
|
-
}
|
|
719
|
-
// Handle tool_calls from delta (OpenAI standard streaming format).
|
|
720
|
-
// A single stream chunk may contain multiple tool call deltas.
|
|
721
|
-
for (const tc of delta?.tool_calls ?? []) {
|
|
722
|
-
const idx = tc.index ?? 0;
|
|
723
|
-
const existing = toolCallsMap.get(idx);
|
|
724
|
-
if (!existing) {
|
|
725
|
-
toolCallsMap.set(idx, {
|
|
726
|
-
id: tc.id ?? `call_${idx}`,
|
|
727
|
-
type: 'function',
|
|
728
|
-
function: {
|
|
729
|
-
name: tc.function?.name ?? '',
|
|
730
|
-
arguments: tc.function?.arguments ?? '',
|
|
731
|
-
},
|
|
732
|
-
});
|
|
733
|
-
}
|
|
734
|
-
else {
|
|
735
|
-
if (tc.id)
|
|
736
|
-
existing.id = tc.id;
|
|
737
|
-
if (tc.function?.name)
|
|
738
|
-
existing.function.name = tc.function.name;
|
|
739
|
-
if (tc.function?.arguments)
|
|
740
|
-
existing.function.arguments += tc.function.arguments;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
// Handle tool_calls from message (some APIs like DashScope may use this format)
|
|
744
|
-
if (msg?.tool_calls && !delta?.tool_calls) {
|
|
745
|
-
for (const msgTc of msg.tool_calls) {
|
|
746
|
-
const existing = toolCallsMap.get(msgTc.index ?? 0);
|
|
747
|
-
if (!existing && msgTc.id) {
|
|
748
|
-
toolCallsMap.set(msgTc.index ?? 0, {
|
|
749
|
-
id: msgTc.id,
|
|
750
|
-
type: 'function',
|
|
751
|
-
function: {
|
|
752
|
-
name: msgTc.function?.name ?? '',
|
|
753
|
-
arguments: msgTc.function?.arguments ?? '',
|
|
754
|
-
},
|
|
755
|
-
});
|
|
756
|
-
}
|
|
757
|
-
else if (existing && msgTc.function?.arguments) {
|
|
758
|
-
existing.function.arguments += msgTc.function.arguments;
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
if (chunk.usage) {
|
|
763
|
-
usage = this.annotateEffortUsage(extractLLMUsage(chunk.usage, chunk, chunk.id ?? providerRequestId), route.effort);
|
|
764
|
-
}
|
|
765
|
-
if (chunk.id)
|
|
766
|
-
providerRequestId = chunk.id;
|
|
767
|
-
if (chunk.model) {
|
|
768
|
-
usedModel = chunk.model;
|
|
769
|
-
}
|
|
770
|
-
const chunkFinishReason = rawFinishReason(choice?.finish_reason);
|
|
771
|
-
if (chunkFinishReason) {
|
|
772
|
-
providerFinishReason = chunkFinishReason;
|
|
773
|
-
finishReason = normalizeFinishReason(chunkFinishReason);
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
const toolCalls = Array.from(toolCallsMap.entries())
|
|
777
|
-
.sort(([a], [b]) => Number(a) - Number(b))
|
|
778
|
-
.map(([, value]) => value);
|
|
779
|
-
for (const tc of toolCalls) {
|
|
780
|
-
if (!tc.function.arguments || tc.function.arguments.trim() === '') {
|
|
781
|
-
tc.function.arguments = '{}';
|
|
782
|
-
}
|
|
783
|
-
else {
|
|
784
|
-
try {
|
|
785
|
-
const parsed = JSON.parse(tc.function.arguments);
|
|
786
|
-
tc.function.arguments = JSON.stringify(parsed);
|
|
787
|
-
}
|
|
788
|
-
catch {
|
|
789
|
-
tc.function.arguments = '{}';
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
finishReason ?? (finishReason = toolCalls.length > 0 ? 'tool_calls' : undefined);
|
|
794
|
-
const finalContent = finalizeStreamText(content, bufferForRecovery);
|
|
795
|
-
if (usage)
|
|
796
|
-
this.publishUsage(usage, usedModel, 'chat_stream');
|
|
681
|
+
const { response } = await readAttempt(route, this.config.model, options?.abortSignal);
|
|
797
682
|
this.consecutive529Errors = 0;
|
|
798
|
-
|
|
799
|
-
requestDiagnostics.usingFallback = this.usingFallback;
|
|
800
|
-
this.lastRequestDiagnostics = {
|
|
801
|
-
...requestDiagnostics,
|
|
802
|
-
retryErrorTypes: [...requestDiagnostics.retryErrorTypes],
|
|
803
|
-
};
|
|
804
|
-
return {
|
|
805
|
-
content: finalContent,
|
|
806
|
-
model: usedModel,
|
|
807
|
-
usage,
|
|
808
|
-
finishReason,
|
|
809
|
-
rawFinishReason: providerFinishReason,
|
|
810
|
-
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
811
|
-
};
|
|
683
|
+
return response;
|
|
812
684
|
}, retryConfig);
|
|
813
685
|
requestDiagnostics.finalModel = response.model;
|
|
814
686
|
requestDiagnostics.usingFallback = this.usingFallback;
|
|
@@ -823,7 +695,7 @@ class LLMService {
|
|
|
823
695
|
if (error instanceof provider_resilience_1.ProviderRetryExhaustedError) {
|
|
824
696
|
this.applyResilienceDiagnostics(requestDiagnostics, error.diagnostics);
|
|
825
697
|
}
|
|
826
|
-
requestDiagnostics.finalModel = this.config.model;
|
|
698
|
+
requestDiagnostics.finalModel = incompleteAttempt?.model ?? this.config.model;
|
|
827
699
|
requestDiagnostics.usingFallback = this.usingFallback;
|
|
828
700
|
this.lastRequestDiagnostics = {
|
|
829
701
|
...requestDiagnostics,
|
|
@@ -837,7 +709,16 @@ class LLMService {
|
|
|
837
709
|
throw error;
|
|
838
710
|
if (error instanceof ProviderRequestPreflightError)
|
|
839
711
|
throw error;
|
|
840
|
-
|
|
712
|
+
const cause = error instanceof provider_resilience_1.ProviderRetryExhaustedError ? (error.originalError ?? error) : error;
|
|
713
|
+
// A retry can fail before producing another stream. Keep the incomplete
|
|
714
|
+
// attempt's visible output even if the last provider error has changed.
|
|
715
|
+
if (incompleteAttempt) {
|
|
716
|
+
const { model, usage } = incompleteAttempt;
|
|
717
|
+
if (usage)
|
|
718
|
+
this.publishUsage(usage, model, 'chat_stream');
|
|
719
|
+
return { content: visibleStreamText, model, usage, finishReason: 'incomplete' };
|
|
720
|
+
}
|
|
721
|
+
throw (0, provider_diagnostics_1.toLLMProviderError)(cause);
|
|
841
722
|
}
|
|
842
723
|
}
|
|
843
724
|
publishUsage(usage, model, operation) {
|
|
@@ -968,7 +849,12 @@ class LLMService {
|
|
|
968
849
|
: undefined;
|
|
969
850
|
if (usage)
|
|
970
851
|
this.publishUsage(usage, response.model ?? model, 'compact_summary');
|
|
971
|
-
return {
|
|
852
|
+
return {
|
|
853
|
+
content: response.choices?.[0]?.message?.content ?? '',
|
|
854
|
+
model,
|
|
855
|
+
usage,
|
|
856
|
+
...readCompletionTermination(response),
|
|
857
|
+
};
|
|
972
858
|
}
|
|
973
859
|
finally {
|
|
974
860
|
lease.release();
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
export type ProviderErrorType = 'model_not_found' | 'invalid_endpoint' | 'auth_failed' | 'quota_or_credit_exhausted' | 'rate_limit' | 'provider_busy' | 'unsupported_effort' | 'unknown_provider_error';
|
|
1
|
+
export type ProviderErrorType = 'model_not_found' | 'invalid_endpoint' | 'auth_failed' | 'quota_or_credit_exhausted' | 'rate_limit' | 'provider_busy' | 'stream_interrupted' | 'unsupported_effort' | 'unknown_provider_error';
|
|
2
2
|
export interface ProviderErrorDiagnostic {
|
|
3
3
|
type: ProviderErrorType;
|
|
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));
|
|
@@ -102,6 +103,8 @@ function hintFor(type) {
|
|
|
102
103
|
return 'Provider rate limit was reached. Wait before retrying, reduce request rate, or switch model/provider.';
|
|
103
104
|
case 'provider_busy':
|
|
104
105
|
return 'Provider is busy or overloaded. Retry later or configure fallbackModel in orion.yaml.';
|
|
106
|
+
case 'stream_interrupted':
|
|
107
|
+
return 'The provider stream ended with an incomplete response. Retry or select another provider.';
|
|
105
108
|
case 'unsupported_effort':
|
|
106
109
|
return 'The provider rejected the configured effort override. Use /effort auto or select a supported level; Orion did not retry without the explicit override.';
|
|
107
110
|
case 'unknown_provider_error':
|
|
@@ -109,7 +112,7 @@ function hintFor(type) {
|
|
|
109
112
|
}
|
|
110
113
|
}
|
|
111
114
|
function retryableFor(type, status, message) {
|
|
112
|
-
if (type === 'rate_limit' || type === 'provider_busy')
|
|
115
|
+
if (type === 'rate_limit' || type === 'provider_busy' || type === 'stream_interrupted')
|
|
113
116
|
return true;
|
|
114
117
|
if (type === 'auth_failed' ||
|
|
115
118
|
type === 'quota_or_credit_exhausted' ||
|
|
@@ -142,7 +145,10 @@ function diagnoseProviderError(error) {
|
|
|
142
145
|
const text = [parts.message, parts.code, parts.type].filter(Boolean).join(' ').toLowerCase();
|
|
143
146
|
const code = parts.code?.toLowerCase();
|
|
144
147
|
let type = 'unknown_provider_error';
|
|
145
|
-
if (
|
|
148
|
+
if (error instanceof error_classifier_1.ProviderStreamIncompleteError) {
|
|
149
|
+
type = 'stream_interrupted';
|
|
150
|
+
}
|
|
151
|
+
else if (matchesAny(text, [
|
|
146
152
|
/\breasoning_effort\b.*\b(?:unsupported|invalid|unknown|not supported)\b/,
|
|
147
153
|
/\b(?:unsupported|invalid|unknown)\b.*\breasoning effort\b/,
|
|
148
154
|
/\boutput_config\.effort\b.*\b(?:unsupported|invalid|unknown|not supported)\b/,
|
|
@@ -160,7 +166,8 @@ function diagnoseProviderError(error) {
|
|
|
160
166
|
])) {
|
|
161
167
|
type = 'model_not_found';
|
|
162
168
|
}
|
|
163
|
-
else if (
|
|
169
|
+
else if (parts.status === 402 ||
|
|
170
|
+
code === '11210' ||
|
|
164
171
|
matchesAny(text, [
|
|
165
172
|
/\bnotenoughcverror\b/,
|
|
166
173
|
/\bnot enough cverror\b/,
|
|
@@ -228,11 +235,14 @@ function diagnoseProviderError(error) {
|
|
|
228
235
|
])) {
|
|
229
236
|
type = 'invalid_endpoint';
|
|
230
237
|
}
|
|
238
|
+
const retryAfter = type === 'quota_or_credit_exhausted' ? (0, error_classifier_1.extractRetryAfterMs)(error) : undefined;
|
|
239
|
+
const retryAt = retryAfter === undefined ? undefined : new Date(Date.now() + retryAfter);
|
|
231
240
|
return {
|
|
232
241
|
type,
|
|
233
242
|
retryable: retryableFor(type, parts.status, text),
|
|
234
243
|
status: parts.status,
|
|
235
244
|
code: parts.code,
|
|
245
|
+
...(retryAt && Number.isFinite(retryAt.getTime()) ? { retryAt: retryAt.toISOString() } : {}),
|
|
236
246
|
providerMessage: parts.message,
|
|
237
247
|
hint: hintFor(type),
|
|
238
248
|
};
|
|
@@ -247,7 +257,8 @@ function toLLMProviderError(error) {
|
|
|
247
257
|
function formatProviderErrorMessage(diagnostic) {
|
|
248
258
|
const status = diagnostic.status ? ` status=${diagnostic.status}` : '';
|
|
249
259
|
const code = diagnostic.code ? ` code=${diagnostic.code}` : '';
|
|
250
|
-
|
|
260
|
+
const retry = diagnostic.retryAt ? ` Provider retry time: ${diagnostic.retryAt}.` : '';
|
|
261
|
+
return `LLM provider error [${diagnostic.type}${status}${code}]: ${diagnostic.hint}${retry}`;
|
|
251
262
|
}
|
|
252
263
|
function endpointDiagnostics(baseUrl) {
|
|
253
264
|
if (!baseUrl) {
|
|
@@ -11,6 +11,9 @@ export interface ClassificationResult {
|
|
|
11
11
|
retryAfterMs?: number;
|
|
12
12
|
status?: number;
|
|
13
13
|
}
|
|
14
|
+
export declare class ProviderStreamIncompleteError extends Error {
|
|
15
|
+
constructor();
|
|
16
|
+
}
|
|
14
17
|
export declare function classifyProviderError(error: unknown, semanticDeltaSeen: boolean): ClassificationResult;
|
|
15
18
|
export declare function extractRetryAfterMs(error: unknown): number | undefined;
|
|
16
19
|
//# sourceMappingURL=error-classifier.d.ts.map
|
|
@@ -6,8 +6,16 @@
|
|
|
6
6
|
* and RetryDisposition. Typed signals take priority over string matching.
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.ProviderStreamIncompleteError = void 0;
|
|
9
10
|
exports.classifyProviderError = classifyProviderError;
|
|
10
11
|
exports.extractRetryAfterMs = extractRetryAfterMs;
|
|
12
|
+
class ProviderStreamIncompleteError extends Error {
|
|
13
|
+
constructor() {
|
|
14
|
+
super('The provider stream ended with an incomplete response.');
|
|
15
|
+
this.name = 'ProviderStreamIncompleteError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.ProviderStreamIncompleteError = ProviderStreamIncompleteError;
|
|
11
19
|
function classifyProviderError(error, semanticDeltaSeen) {
|
|
12
20
|
// Local budget/policy preflight failures happen before any provider request.
|
|
13
21
|
// Keep them fail-fast so the caller can preserve the typed control signal.
|
|
@@ -18,6 +26,12 @@ function classifyProviderError(error, semanticDeltaSeen) {
|
|
|
18
26
|
if (isAbortError(error)) {
|
|
19
27
|
return { kind: 'aborted', disposition: 'fail_fast' };
|
|
20
28
|
}
|
|
29
|
+
if (error instanceof ProviderStreamIncompleteError) {
|
|
30
|
+
return {
|
|
31
|
+
kind: 'stream_interrupted',
|
|
32
|
+
disposition: semanticDeltaSeen ? 'recover_stream' : 'retry_precommit',
|
|
33
|
+
};
|
|
34
|
+
}
|
|
21
35
|
// Extract status and headers
|
|
22
36
|
const status = extractStatus(error);
|
|
23
37
|
const retryAfterMs = extractRetryAfterMs(error);
|