@orion-agents/orion-code 0.4.4 → 0.4.6

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 +15 -0
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +4 -4
  4. package/dist/commands/context-commands.js +16 -28
  5. package/dist/commands/context-tool-command-handlers.d.ts +2 -3
  6. package/dist/commands/context-tool-command-handlers.js +2 -20
  7. package/dist/commands/registry.js +24 -61
  8. package/dist/commands/retired-commands.d.ts +2 -0
  9. package/dist/commands/retired-commands.js +24 -0
  10. package/dist/commands/session-command-handlers.d.ts +3 -2
  11. package/dist/commands/session-command-handlers.js +41 -42
  12. package/dist/commands/session-commands.js +21 -0
  13. package/dist/commands/system-commands.js +2 -27
  14. package/dist/commands/tool-commands.js +0 -10
  15. package/dist/commands/types.d.ts +6 -4
  16. package/dist/commands/workflow-commands.js +0 -24
  17. package/dist/core/tool-artifacts.js +17 -4
  18. package/dist/framework/query.js +151 -17
  19. package/dist/framework/tool-state.d.ts +4 -0
  20. package/dist/harness/context-harness.d.ts +7 -3
  21. package/dist/harness/context-harness.js +222 -48
  22. package/dist/harness/contract.js +3 -1
  23. package/dist/harness/drift-guard.js +67 -17
  24. package/dist/harness/goal-verification.d.ts +11 -0
  25. package/dist/harness/goal-verification.js +62 -0
  26. package/dist/harness/ledger.js +16 -3
  27. package/dist/harness/state.js +3 -0
  28. package/dist/harness/stop-controller.js +1 -1
  29. package/dist/harness/task-checklist.d.ts +11 -1
  30. package/dist/harness/task-checklist.js +48 -4
  31. package/dist/harness/types.d.ts +10 -0
  32. package/dist/harness/verification.d.ts +11 -1
  33. package/dist/harness/verification.js +47 -2
  34. package/dist/runtime/agent-loop.js +4 -1
  35. package/dist/runtime/agent-runtime-controller.d.ts +4 -2
  36. package/dist/runtime/agent-runtime-controller.js +115 -30
  37. package/dist/runtime/batch-read-service.js +21 -4
  38. package/dist/runtime/goal-runtime-coordinator.js +1 -0
  39. package/dist/runtime/orion-session-runner.js +3 -5
  40. package/dist/runtime/product-bootstrap.js +24 -11
  41. package/dist/runtime/product-orion-runtime.js +24 -2
  42. package/dist/runtime/task-context-recovery.js +21 -5
  43. package/dist/runtime/task-context-service.d.ts +3 -1
  44. package/dist/runtime/task-context-service.js +3 -0
  45. package/dist/runtime/ui-events.d.ts +4 -1
  46. package/dist/runtime/ui-view-model.js +7 -3
  47. package/dist/runtime/workspace-verification.d.ts +2 -2
  48. package/dist/runtime/workspace-verification.js +24 -9
  49. package/dist/services/chat-completion-sse.d.ts +9 -0
  50. package/dist/services/chat-completion-sse.js +50 -0
  51. package/dist/services/compact/summary-generator.d.ts +1 -1
  52. package/dist/services/compact/summary-generator.js +12 -0
  53. package/dist/services/llm.d.ts +1 -1
  54. package/dist/services/llm.js +165 -292
  55. package/dist/services/provider-diagnostics.d.ts +1 -1
  56. package/dist/services/provider-diagnostics.js +7 -2
  57. package/dist/services/provider-resilience/error-classifier.d.ts +3 -0
  58. package/dist/services/provider-resilience/error-classifier.js +14 -0
  59. package/dist/skills/builtin/security-check/SKILL.md +2 -2
  60. package/dist/skills/builtin/test-gen/SKILL.md +2 -2
  61. package/dist/terminal-ui/launch.js +1 -1
  62. package/dist/tools/core/common.d.ts +0 -11
  63. package/dist/tools/core/common.js +0 -18
  64. package/dist/tools/core/edit-file.js +57 -86
  65. package/dist/tools/core/exec-command.js +61 -80
  66. package/dist/tools/core/grep.js +84 -24
  67. package/dist/tools/core/read-file.js +3 -2
  68. package/dist/tools/todo.d.ts +2 -2
  69. package/dist/tools/todo.js +13 -10
  70. package/dist/tui-ui/launch.js +4 -1
  71. package/dist/tui-ui/layout.d.ts +2 -2
  72. package/dist/tui-ui/layout.js +59 -47
  73. package/dist/tui-ui/pickers.d.ts +3 -1
  74. package/dist/tui-ui/pickers.js +17 -11
  75. package/dist/tui-ui/runner.d.ts +1 -1
  76. package/dist/tui-ui/runner.js +61 -68
  77. package/dist/tui-ui/state.d.ts +4 -0
  78. package/dist/tui-ui/state.js +33 -2
  79. package/dist/utils/utf8.d.ts +6 -0
  80. package/dist/utils/utf8.js +14 -0
  81. package/docs/cli-guide.md +27 -3
  82. package/npm-shrinkwrap.json +2 -2
  83. package/package.json +1 -1
@@ -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/,
@@ -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);
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: security-check
3
3
  description: Scan code for security vulnerabilities
4
- trigger: /security
4
+ trigger: /skill security-check
5
5
  tools:
6
6
  - read_file
7
7
  - glob
@@ -17,7 +17,7 @@ Identify potential security vulnerabilities in code.
17
17
 
18
18
  ## Usage
19
19
 
20
- Trigger: `/security [path]`
20
+ Run `/skill security-check <task>` with the code or dependencies to review.
21
21
 
22
22
  ## Security Patterns to Check
23
23
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: test-gen
3
3
  description: Generate test cases for existing code
4
- trigger: /test-gen
4
+ trigger: /skill test-gen
5
5
  tools:
6
6
  - read_file
7
7
  - write_file
@@ -17,7 +17,7 @@ Generate test cases for existing functions and modules.
17
17
 
18
18
  ## Usage
19
19
 
20
- Trigger: `/test-gen [path]` or `/test-gen [function]`
20
+ Run `/skill test-gen <task>` with the file, function, or behavior to test.
21
21
 
22
22
  ## Test Generation Strategy
23
23
 
@@ -661,7 +661,7 @@ class TerminalEventSink {
661
661
  sessionRestored(event) {
662
662
  this.append({
663
663
  role: 'status',
664
- title: 'resume',
664
+ title: event.reason === 'new' ? 'new' : 'resume',
665
665
  content: formatTerminalSessionRestored(event),
666
666
  });
667
667
  }