@orion-agents/orion-code 0.4.4 → 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 (51) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/dist/core/tool-artifacts.js +17 -4
  5. package/dist/framework/query.js +150 -16
  6. package/dist/framework/tool-state.d.ts +4 -0
  7. package/dist/harness/context-harness.d.ts +6 -2
  8. package/dist/harness/context-harness.js +221 -47
  9. package/dist/harness/contract.js +3 -1
  10. package/dist/harness/drift-guard.js +67 -17
  11. package/dist/harness/goal-verification.d.ts +11 -0
  12. package/dist/harness/goal-verification.js +62 -0
  13. package/dist/harness/ledger.js +16 -3
  14. package/dist/harness/state.js +3 -0
  15. package/dist/harness/task-checklist.d.ts +11 -1
  16. package/dist/harness/task-checklist.js +48 -4
  17. package/dist/harness/types.d.ts +10 -0
  18. package/dist/harness/verification.d.ts +11 -1
  19. package/dist/harness/verification.js +47 -2
  20. package/dist/runtime/agent-loop.js +4 -1
  21. package/dist/runtime/batch-read-service.js +21 -4
  22. package/dist/runtime/goal-runtime-coordinator.js +1 -0
  23. package/dist/runtime/product-orion-runtime.js +24 -2
  24. package/dist/runtime/task-context-recovery.js +21 -5
  25. package/dist/runtime/task-context-service.d.ts +3 -1
  26. package/dist/runtime/task-context-service.js +3 -0
  27. package/dist/runtime/workspace-verification.d.ts +2 -2
  28. package/dist/runtime/workspace-verification.js +24 -9
  29. package/dist/services/chat-completion-sse.d.ts +9 -0
  30. package/dist/services/chat-completion-sse.js +50 -0
  31. package/dist/services/compact/summary-generator.d.ts +1 -1
  32. package/dist/services/compact/summary-generator.js +12 -0
  33. package/dist/services/llm.d.ts +1 -1
  34. package/dist/services/llm.js +165 -292
  35. package/dist/services/provider-diagnostics.d.ts +1 -1
  36. package/dist/services/provider-diagnostics.js +7 -2
  37. package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
  38. package/dist/services/provider-resilience/error-classifier.js +14 -0
  39. package/dist/tools/core/common.d.ts +0 -11
  40. package/dist/tools/core/common.js +0 -18
  41. package/dist/tools/core/edit-file.js +57 -86
  42. package/dist/tools/core/exec-command.js +61 -80
  43. package/dist/tools/core/grep.js +84 -24
  44. package/dist/tools/core/read-file.js +3 -2
  45. package/dist/tools/todo.d.ts +2 -2
  46. package/dist/tools/todo.js +13 -10
  47. package/dist/utils/utf8.d.ts +6 -0
  48. package/dist/utils/utf8.js +14 -0
  49. package/docs/cli-guide.md +7 -2
  50. package/npm-shrinkwrap.json +2 -2
  51. package/package.json +1 -1
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ChatCompletionSseStream = void 0;
7
+ const openai_1 = __importDefault(require("openai"));
8
+ const streaming_1 = require("openai/core/streaming");
9
+ /** Keep the SDK's SSE framing while exposing the Chat Completions end marker. */
10
+ class ChatCompletionSseStream extends streaming_1.Stream {
11
+ constructor() {
12
+ super(...arguments);
13
+ this.doneEvent = false;
14
+ }
15
+ get sawDoneEvent() {
16
+ return this.doneEvent;
17
+ }
18
+ static fromSSEResponse(response, controller, client) {
19
+ let consumed = false;
20
+ async function* chunks() {
21
+ if (consumed)
22
+ throw new openai_1.default.OpenAIError('Cannot iterate over a consumed completion stream.');
23
+ consumed = true;
24
+ let exhaustedBody = false;
25
+ try {
26
+ for await (const event of (0, streaming_1._iterSSEMessages)(response, controller)) {
27
+ if (event.data.trim() === '[DONE]') {
28
+ stream.doneEvent = true;
29
+ return;
30
+ }
31
+ const data = JSON.parse(event.data);
32
+ if (data?.error) {
33
+ throw new openai_1.default.APIError(undefined, data.error, undefined, response.headers);
34
+ }
35
+ if (data && typeof data === 'object')
36
+ yield data;
37
+ }
38
+ exhaustedBody = true;
39
+ }
40
+ finally {
41
+ if (!exhaustedBody && !stream.doneEvent)
42
+ controller.abort();
43
+ }
44
+ }
45
+ const stream = new ChatCompletionSseStream(chunks, controller, client);
46
+ return stream;
47
+ }
48
+ }
49
+ exports.ChatCompletionSseStream = ChatCompletionSseStream;
50
+ //# sourceMappingURL=chat-completion-sse.js.map
@@ -43,7 +43,7 @@ export interface GeneratedSummary {
43
43
  semanticSummary: CompactSummary;
44
44
  diagnostics: SummaryDiagnostic[];
45
45
  }
46
- export type SummaryDiagnosticCode = 'llm_request_failed' | 'llm_empty_response' | 'llm_chunked_input' | 'llm_summary_budget' | 'background_summary_reused' | 'heuristic_fallback' | 'deterministic_projection';
46
+ export type SummaryDiagnosticCode = 'llm_request_failed' | 'llm_empty_response' | 'llm_incomplete_response' | 'llm_chunked_input' | 'llm_summary_budget' | 'background_summary_reused' | 'heuristic_fallback' | 'deterministic_projection';
47
47
  export interface SummaryDiagnostic {
48
48
  code: SummaryDiagnosticCode;
49
49
  message: string;
@@ -333,6 +333,18 @@ Summary:`;
333
333
  const response = await llm.chat([{ role: 'user', content: prompt }], undefined, {
334
334
  abortSignal,
335
335
  });
336
+ if ((response.finishReason !== undefined && response.finishReason !== 'stop') ||
337
+ response.endTurn === false ||
338
+ response.toolCalls?.length) {
339
+ diagnostics.push({
340
+ code: 'llm_incomplete_response',
341
+ message: `Summary model did not complete chunk ${chunkIndex + 1} (${response.finishReason ?? 'non-final response'}).`,
342
+ fallbackUsed: true,
343
+ chunkIndex,
344
+ chunkCount: chunks.length,
345
+ });
346
+ break;
347
+ }
336
348
  if (!response.content?.trim()) {
337
349
  diagnostics.push({
338
350
  code: 'llm_empty_response',
@@ -169,7 +169,7 @@ export interface LLMResponse {
169
169
  };
170
170
  }>;
171
171
  }
172
- export type LLMFinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'unknown';
172
+ export type LLMFinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'incomplete' | 'unknown';
173
173
  export declare function normalizeFinishReason(value: unknown): LLMFinishReason | undefined;
174
174
  /** 流式回调 */
175
175
  export type StreamCallback = (chunk: string) => void;
@@ -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
  }
@@ -242,6 +246,37 @@ function readEndTurn(response) {
242
246
  return choiceEndTurn;
243
247
  return typeof response.end_turn === 'boolean' ? response.end_turn : undefined;
244
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
+ }
245
280
  class LLMService {
246
281
  constructor(config) {
247
282
  this.providerKey = 'default';
@@ -413,9 +448,6 @@ class LLMService {
413
448
  arguments: tc.function.arguments,
414
449
  },
415
450
  }));
416
- const providerFinishReason = rawFinishReason(choice?.finish_reason);
417
- const finishReason = normalizeFinishReason(providerFinishReason) ??
418
- (toolCalls && toolCalls.length > 0 ? 'tool_calls' : undefined);
419
451
  const usage = response.usage
420
452
  ? this.annotateEffortUsage(extractLLMUsage(response.usage, response, response.id), effort)
421
453
  : undefined;
@@ -431,9 +463,7 @@ class LLMService {
431
463
  content,
432
464
  usage,
433
465
  model: response.model ?? this.config.model,
434
- finishReason,
435
- rawFinishReason: providerFinishReason,
436
- endTurn: readEndTurn(response),
466
+ ...readCompletionTermination(response),
437
467
  toolCalls,
438
468
  };
439
469
  }
@@ -469,6 +499,115 @@ class LLMService {
469
499
  }
470
500
  return visibleStreamText;
471
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
+ };
472
611
  const retryConfig = {
473
612
  maxRetries: this.config.maxRetries,
474
613
  baseDelayMs: this.config.retryBaseDelay,
@@ -518,150 +657,7 @@ class LLMService {
518
657
  throwIfAborted(signal);
519
658
  await this.assertProviderRequestAllowed('chat_stream', attempt, messages, model);
520
659
  const route = this.requestRoute(modelSnapshot, model, providerKey);
521
- const params = {
522
- model,
523
- messages: this.toOpenAIMessages(messages),
524
- max_tokens: route.maxOutputTokens,
525
- temperature: this.config.temperature,
526
- stream: true,
527
- stream_options: { include_usage: true },
528
- ...(0, effort_1.buildProviderEffortParams)(route.effort),
529
- };
530
- if (tools && tools.length > 0) {
531
- params.tools = tools;
532
- }
533
- onThinking?.();
534
- const requestOptions = signal ? { signal } : undefined;
535
- const stream = (await route.client.chat.completions.create(params, requestOptions));
536
- let content = '';
537
- let usedModel = model;
538
- let usage;
539
- let providerRequestId;
540
- let providerFinishReason;
541
- let finishReason;
542
- let endTurn;
543
- const bufferForRecovery = visibleStreamText.length > 0;
544
- const toolCallsMap = new Map();
545
- for await (const chunk of stream) {
546
- throwIfAborted(signal);
547
- // Debug: log raw chunk when tool_calls present
548
- if (process.env.ORION_CODE_DEBUG_TOOLS === 'true') {
549
- const delta = chunk.choices?.[0]?.delta;
550
- if (delta?.tool_calls || chunk.choices?.[0]?.message?.tool_calls) {
551
- console.log('[DEBUG] Raw chunk:', JSON.stringify(chunk, null, 2));
552
- }
553
- }
554
- const choice = chunk.choices?.[0];
555
- const delta = choice?.delta;
556
- const msg = choice?.message;
557
- const text = delta?.content ?? (content ? '' : (msg?.content ?? ''));
558
- if (text) {
559
- content += text;
560
- emitStreamText(text, bufferForRecovery, reporter);
561
- }
562
- const thinkingDelta = delta?.reasoning_content;
563
- if (thinkingDelta) {
564
- onThinkingText?.(thinkingDelta);
565
- }
566
- if ((delta?.tool_calls?.length ?? 0) > 0 || (msg?.tool_calls?.length ?? 0) > 0) {
567
- reporter?.onToolCallDelta();
568
- }
569
- for (const tc of delta?.tool_calls ?? []) {
570
- const idx = tc.index ?? 0;
571
- const existing = toolCallsMap.get(idx);
572
- if (!existing) {
573
- toolCallsMap.set(idx, {
574
- id: tc.id ?? `call_${idx}`,
575
- type: 'function',
576
- function: {
577
- name: tc.function?.name ?? '',
578
- arguments: tc.function?.arguments ?? '',
579
- },
580
- });
581
- }
582
- else {
583
- if (tc.id)
584
- existing.id = tc.id;
585
- if (tc.function?.name)
586
- existing.function.name = tc.function.name;
587
- if (tc.function?.arguments)
588
- existing.function.arguments += tc.function.arguments;
589
- }
590
- }
591
- if (msg?.tool_calls && !delta?.tool_calls) {
592
- for (const msgTc of msg.tool_calls) {
593
- const existing = toolCallsMap.get(msgTc.index ?? 0);
594
- if (!existing && msgTc.id) {
595
- toolCallsMap.set(msgTc.index ?? 0, {
596
- id: msgTc.id,
597
- type: 'function',
598
- function: {
599
- name: msgTc.function?.name ?? '',
600
- arguments: msgTc.function?.arguments ?? '',
601
- },
602
- });
603
- }
604
- else if (existing && msgTc.function?.arguments) {
605
- existing.function.arguments += msgTc.function.arguments;
606
- }
607
- }
608
- }
609
- if (chunk.usage) {
610
- usage = this.annotateEffortUsage(extractLLMUsage(chunk.usage, chunk, chunk.id ?? providerRequestId), route.effort);
611
- }
612
- if (chunk.id)
613
- providerRequestId = chunk.id;
614
- if (chunk.model) {
615
- usedModel = chunk.model;
616
- }
617
- endTurn = readEndTurn(chunk) ?? endTurn;
618
- const chunkFinishReason = rawFinishReason(choice?.finish_reason);
619
- if (chunkFinishReason) {
620
- providerFinishReason = chunkFinishReason;
621
- finishReason = normalizeFinishReason(chunkFinishReason);
622
- reporter?.onFinishReason(chunkFinishReason);
623
- }
624
- }
625
- const toolCalls = Array.from(toolCallsMap.entries())
626
- .sort(([a], [b]) => Number(a) - Number(b))
627
- .map(([, value]) => value);
628
- for (const tc of toolCalls) {
629
- if (!tc.function.arguments || tc.function.arguments.trim() === '') {
630
- tc.function.arguments = '{}';
631
- }
632
- else {
633
- try {
634
- const parsed = JSON.parse(tc.function.arguments);
635
- tc.function.arguments = JSON.stringify(parsed);
636
- }
637
- catch {
638
- tc.function.arguments = '{}';
639
- }
640
- }
641
- }
642
- finishReason ?? (finishReason = toolCalls.length > 0 ? 'tool_calls' : undefined);
643
- const finalContent = finalizeStreamText(content, bufferForRecovery);
644
- if (usage)
645
- this.publishUsage(usage, usedModel, 'chat_stream');
646
- return {
647
- response: {
648
- content: finalContent,
649
- model: usedModel,
650
- usage,
651
- finishReason,
652
- rawFinishReason: providerFinishReason,
653
- endTurn,
654
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
655
- },
656
- usage: usage
657
- ? {
658
- promptTokens: usage.promptTokens,
659
- completionTokens: usage.completionTokens,
660
- totalTokens: usage.promptTokens + usage.completionTokens,
661
- }
662
- : undefined,
663
- providerRequestId,
664
- };
660
+ return readAttempt(route, model, signal, reporter);
665
661
  });
666
662
  // Unpack resilience result
667
663
  const response = streamResult.result;
@@ -682,146 +678,9 @@ class LLMService {
682
678
  const route = this.usingFallback && modelSnapshot.fallback
683
679
  ? modelSnapshot.fallback
684
680
  : this.requestRoute(modelSnapshot, this.config.model);
685
- const params = {
686
- model: this.config.model,
687
- messages: this.toOpenAIMessages(messages),
688
- max_tokens: route.maxOutputTokens,
689
- temperature: this.config.temperature,
690
- stream: true,
691
- stream_options: { include_usage: true },
692
- ...(0, effort_1.buildProviderEffortParams)(route.effort),
693
- };
694
- if (tools && tools.length > 0) {
695
- params.tools = tools;
696
- }
697
- onThinking?.();
698
- const requestOptions = options?.abortSignal ? { signal: options.abortSignal } : undefined;
699
- const stream = (await route.client.chat.completions.create(params, requestOptions));
700
- let content = '';
701
- let usedModel = this.config.model;
702
- let usage;
703
- let providerRequestId;
704
- let providerFinishReason;
705
- let finishReason;
706
- let endTurn;
707
- const bufferForRecovery = visibleStreamText.length > 0;
708
- const toolCallsMap = new Map();
709
- for await (const chunk of stream) {
710
- throwIfAborted(options?.abortSignal);
711
- // Debug: log raw chunk when tool_calls present (for diagnosing API compatibility)
712
- if (process.env.ORION_CODE_DEBUG_TOOLS === 'true') {
713
- const delta = chunk.choices?.[0]?.delta;
714
- if (delta?.tool_calls || chunk.choices?.[0]?.message?.tool_calls) {
715
- console.log('[DEBUG] Raw chunk:', JSON.stringify(chunk, null, 2));
716
- }
717
- }
718
- const choice = chunk.choices?.[0];
719
- const delta = choice?.delta;
720
- const msg = choice?.message;
721
- const text = delta?.content ?? (content ? '' : (msg?.content ?? ''));
722
- if (text) {
723
- content += text;
724
- emitStreamText(text, bufferForRecovery);
725
- }
726
- const thinkingDelta = delta?.reasoning_content;
727
- if (thinkingDelta) {
728
- onThinkingText?.(thinkingDelta);
729
- }
730
- // Handle tool_calls from delta (OpenAI standard streaming format).
731
- // A single stream chunk may contain multiple tool call deltas.
732
- for (const tc of delta?.tool_calls ?? []) {
733
- const idx = tc.index ?? 0;
734
- const existing = toolCallsMap.get(idx);
735
- if (!existing) {
736
- toolCallsMap.set(idx, {
737
- id: tc.id ?? `call_${idx}`,
738
- type: 'function',
739
- function: {
740
- name: tc.function?.name ?? '',
741
- arguments: tc.function?.arguments ?? '',
742
- },
743
- });
744
- }
745
- else {
746
- if (tc.id)
747
- existing.id = tc.id;
748
- if (tc.function?.name)
749
- existing.function.name = tc.function.name;
750
- if (tc.function?.arguments)
751
- existing.function.arguments += tc.function.arguments;
752
- }
753
- }
754
- // Handle tool_calls from message (some APIs like DashScope may use this format)
755
- if (msg?.tool_calls && !delta?.tool_calls) {
756
- for (const msgTc of msg.tool_calls) {
757
- const existing = toolCallsMap.get(msgTc.index ?? 0);
758
- if (!existing && msgTc.id) {
759
- toolCallsMap.set(msgTc.index ?? 0, {
760
- id: msgTc.id,
761
- type: 'function',
762
- function: {
763
- name: msgTc.function?.name ?? '',
764
- arguments: msgTc.function?.arguments ?? '',
765
- },
766
- });
767
- }
768
- else if (existing && msgTc.function?.arguments) {
769
- existing.function.arguments += msgTc.function.arguments;
770
- }
771
- }
772
- }
773
- if (chunk.usage) {
774
- usage = this.annotateEffortUsage(extractLLMUsage(chunk.usage, chunk, chunk.id ?? providerRequestId), route.effort);
775
- }
776
- if (chunk.id)
777
- providerRequestId = chunk.id;
778
- if (chunk.model) {
779
- usedModel = chunk.model;
780
- }
781
- endTurn = readEndTurn(chunk) ?? endTurn;
782
- const chunkFinishReason = rawFinishReason(choice?.finish_reason);
783
- if (chunkFinishReason) {
784
- providerFinishReason = chunkFinishReason;
785
- finishReason = normalizeFinishReason(chunkFinishReason);
786
- }
787
- }
788
- const toolCalls = Array.from(toolCallsMap.entries())
789
- .sort(([a], [b]) => Number(a) - Number(b))
790
- .map(([, value]) => value);
791
- for (const tc of toolCalls) {
792
- if (!tc.function.arguments || tc.function.arguments.trim() === '') {
793
- tc.function.arguments = '{}';
794
- }
795
- else {
796
- try {
797
- const parsed = JSON.parse(tc.function.arguments);
798
- tc.function.arguments = JSON.stringify(parsed);
799
- }
800
- catch {
801
- tc.function.arguments = '{}';
802
- }
803
- }
804
- }
805
- finishReason ?? (finishReason = toolCalls.length > 0 ? 'tool_calls' : undefined);
806
- const finalContent = finalizeStreamText(content, bufferForRecovery);
807
- if (usage)
808
- this.publishUsage(usage, usedModel, 'chat_stream');
681
+ const { response } = await readAttempt(route, this.config.model, options?.abortSignal);
809
682
  this.consecutive529Errors = 0;
810
- requestDiagnostics.finalModel = usedModel;
811
- requestDiagnostics.usingFallback = this.usingFallback;
812
- this.lastRequestDiagnostics = {
813
- ...requestDiagnostics,
814
- retryErrorTypes: [...requestDiagnostics.retryErrorTypes],
815
- };
816
- return {
817
- content: finalContent,
818
- model: usedModel,
819
- usage,
820
- finishReason,
821
- rawFinishReason: providerFinishReason,
822
- endTurn,
823
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
824
- };
683
+ return response;
825
684
  }, retryConfig);
826
685
  requestDiagnostics.finalModel = response.model;
827
686
  requestDiagnostics.usingFallback = this.usingFallback;
@@ -836,7 +695,7 @@ class LLMService {
836
695
  if (error instanceof provider_resilience_1.ProviderRetryExhaustedError) {
837
696
  this.applyResilienceDiagnostics(requestDiagnostics, error.diagnostics);
838
697
  }
839
- requestDiagnostics.finalModel = this.config.model;
698
+ requestDiagnostics.finalModel = incompleteAttempt?.model ?? this.config.model;
840
699
  requestDiagnostics.usingFallback = this.usingFallback;
841
700
  this.lastRequestDiagnostics = {
842
701
  ...requestDiagnostics,
@@ -850,7 +709,16 @@ class LLMService {
850
709
  throw error;
851
710
  if (error instanceof ProviderRequestPreflightError)
852
711
  throw error;
853
- throw (0, provider_diagnostics_1.toLLMProviderError)(error instanceof provider_resilience_1.ProviderRetryExhaustedError ? (error.originalError ?? error) : error);
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);
854
722
  }
855
723
  }
856
724
  publishUsage(usage, model, operation) {
@@ -981,7 +849,12 @@ class LLMService {
981
849
  : undefined;
982
850
  if (usage)
983
851
  this.publishUsage(usage, response.model ?? model, 'compact_summary');
984
- return { content: response.choices?.[0]?.message?.content ?? '', model, usage };
852
+ return {
853
+ content: response.choices?.[0]?.message?.content ?? '',
854
+ model,
855
+ usage,
856
+ ...readCompletionTermination(response),
857
+ };
985
858
  }
986
859
  finally {
987
860
  lease.release();
@@ -1,4 +1,4 @@
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;
@@ -103,6 +103,8 @@ function hintFor(type) {
103
103
  return 'Provider rate limit was reached. Wait before retrying, reduce request rate, or switch model/provider.';
104
104
  case 'provider_busy':
105
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.';
106
108
  case 'unsupported_effort':
107
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.';
108
110
  case 'unknown_provider_error':
@@ -110,7 +112,7 @@ function hintFor(type) {
110
112
  }
111
113
  }
112
114
  function retryableFor(type, status, message) {
113
- if (type === 'rate_limit' || type === 'provider_busy')
115
+ if (type === 'rate_limit' || type === 'provider_busy' || type === 'stream_interrupted')
114
116
  return true;
115
117
  if (type === 'auth_failed' ||
116
118
  type === 'quota_or_credit_exhausted' ||
@@ -143,7 +145,10 @@ function diagnoseProviderError(error) {
143
145
  const text = [parts.message, parts.code, parts.type].filter(Boolean).join(' ').toLowerCase();
144
146
  const code = parts.code?.toLowerCase();
145
147
  let type = 'unknown_provider_error';
146
- if (matchesAny(text, [
148
+ if (error instanceof error_classifier_1.ProviderStreamIncompleteError) {
149
+ type = 'stream_interrupted';
150
+ }
151
+ else if (matchesAny(text, [
147
152
  /\breasoning_effort\b.*\b(?:unsupported|invalid|unknown|not supported)\b/,
148
153
  /\b(?:unsupported|invalid|unknown)\b.*\breasoning effort\b/,
149
154
  /\boutput_config\.effort\b.*\b(?:unsupported|invalid|unknown|not supported)\b/,