@jini-ai/agent-runtime 0.6.15-rc.2 → 0.6.16

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 (119) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/agent-protocol/acp/rpc.js +4 -8
  3. package/dist/agent-protocol/acp/session.js +33 -37
  4. package/dist/agent-protocol/acp/text-suppression.js +10 -7
  5. package/dist/agent-protocol/acp/updates.js +4 -5
  6. package/dist/agent-protocol/core/json-line-stream.d.ts +6 -3
  7. package/dist/agent-protocol/core/json-line-stream.js +9 -10
  8. package/dist/agent-protocol/pi-rpc/events.js +27 -27
  9. package/dist/agent-protocol/pi-rpc/models.js +13 -11
  10. package/dist/agent-protocol/pi-rpc/session.js +7 -7
  11. package/dist/ai-trace/classify.js +4 -1
  12. package/dist/ai-trace/recorder.d.ts +2 -3
  13. package/dist/ai-trace/recorder.js +2 -3
  14. package/dist/ai-trace/sinks.js +19 -3
  15. package/dist/ai-trace/usage.js +3 -1
  16. package/dist/anthropic-live-models.js +0 -0
  17. package/dist/auth.js +20 -17
  18. package/dist/claude-code-models.js +29 -17
  19. package/dist/claude-filesystem-policy.d.ts +4 -3
  20. package/dist/claude-filesystem-policy.js +39 -12
  21. package/dist/claude-stream.js +65 -47
  22. package/dist/core/model-discovery-shared.js +4 -2
  23. package/dist/core/omit-keys.d.ts +7 -0
  24. package/dist/core/omit-keys.js +12 -0
  25. package/dist/defs/aider.d.ts +1 -1
  26. package/dist/defs/amp.d.ts +1 -1
  27. package/dist/defs/amp.js +2 -2
  28. package/dist/defs/amr.js +5 -9
  29. package/dist/defs/antigravity-event-stream.d.ts +19 -0
  30. package/dist/defs/antigravity-event-stream.js +83 -0
  31. package/dist/defs/antigravity.d.ts +4 -0
  32. package/dist/defs/antigravity.js +27 -15
  33. package/dist/defs/auggie.d.ts +3 -3
  34. package/dist/defs/claude.d.ts +3 -3
  35. package/dist/defs/cline.d.ts +3 -3
  36. package/dist/defs/codebuddy.d.ts +1 -1
  37. package/dist/defs/codex.js +3 -2
  38. package/dist/defs/crush.d.ts +1 -1
  39. package/dist/defs/cursor-agent.d.ts +3 -1
  40. package/dist/defs/cursor-agent.js +8 -6
  41. package/dist/defs/deepseek.d.ts +1 -1
  42. package/dist/defs/devin.d.ts +3 -3
  43. package/dist/defs/droid.d.ts +1 -1
  44. package/dist/defs/goose.d.ts +3 -3
  45. package/dist/defs/grok-build.js +7 -5
  46. package/dist/defs/hermes.d.ts +3 -3
  47. package/dist/defs/index.d.ts +0 -1
  48. package/dist/defs/index.js +0 -1
  49. package/dist/defs/kilo.d.ts +3 -3
  50. package/dist/defs/kimi.d.ts +3 -3
  51. package/dist/defs/kiro.d.ts +3 -3
  52. package/dist/defs/mimo.d.ts +1 -1
  53. package/dist/defs/opencode.d.ts +1 -1
  54. package/dist/defs/pi.d.ts +1 -1
  55. package/dist/defs/qoder.d.ts +1 -1
  56. package/dist/defs/qwen.d.ts +1 -1
  57. package/dist/defs/reasonix.d.ts +3 -3
  58. package/dist/defs/trae-cli.d.ts +3 -3
  59. package/dist/defs/vibe.d.ts +3 -3
  60. package/dist/detection.js +22 -2
  61. package/dist/executables.js +0 -1
  62. package/dist/index.d.ts +0 -1
  63. package/dist/index.js +0 -1
  64. package/dist/json-event-stream.d.ts +1 -2
  65. package/dist/json-event-stream.js +10 -9
  66. package/dist/launch.js +2 -1
  67. package/dist/metadata.js +0 -4
  68. package/dist/model-catalog-cache.js +6 -4
  69. package/dist/model-contracts.d.ts +29 -0
  70. package/dist/model-contracts.js +2 -0
  71. package/dist/model-discovery-adapters.js +47 -24
  72. package/dist/model-discovery-config.js +8 -5
  73. package/dist/model-discovery-sdk.d.ts +0 -29
  74. package/dist/model-discovery-sdk.js +0 -32
  75. package/dist/model-discovery-types.d.ts +3 -3
  76. package/dist/model-discovery-yaml.d.ts +9 -0
  77. package/dist/model-discovery-yaml.js +98 -0
  78. package/dist/model-discovery.js +10 -3
  79. package/dist/model-registry.js +2 -1
  80. package/dist/native-tool-policy.d.ts +28 -0
  81. package/dist/native-tool-policy.js +42 -0
  82. package/dist/opencode-log.js +13 -10
  83. package/dist/pi-models.js +13 -11
  84. package/dist/probe-scheduler.js +13 -5
  85. package/dist/providers/aihubmix.js +6 -7
  86. package/dist/providers/anthropic-messages.d.ts +7 -4
  87. package/dist/providers/anthropic-messages.js +22 -24
  88. package/dist/providers/azure-chat.d.ts +1 -1
  89. package/dist/providers/azure-chat.js +7 -10
  90. package/dist/providers/connection-guard.js +2 -1
  91. package/dist/providers/connection-test.js +16 -10
  92. package/dist/providers/google-messages.d.ts +1 -1
  93. package/dist/providers/google-messages.js +33 -35
  94. package/dist/providers/google.js +3 -4
  95. package/dist/providers/model-catalog.js +10 -7
  96. package/dist/providers/ollama-chat.d.ts +0 -8
  97. package/dist/providers/ollama-chat.js +17 -19
  98. package/dist/providers/openai-chat.d.ts +6 -3
  99. package/dist/providers/openai-chat.js +24 -22
  100. package/dist/providers/operation-schema.d.ts +2 -3
  101. package/dist/providers/operation-schema.js +25 -22
  102. package/dist/providers/provider-tool-policy.d.ts +13 -0
  103. package/dist/providers/provider-tool-policy.js +2 -0
  104. package/dist/providers/tool-loop-verdict.d.ts +22 -0
  105. package/dist/providers/tool-loop-verdict.js +17 -0
  106. package/dist/providers/tool-turn-types.d.ts +2 -12
  107. package/dist/providers/tool-turn.js +7 -2
  108. package/dist/registry.d.ts +1 -1
  109. package/dist/registry.js +2 -3
  110. package/dist/resolution.d.ts +21 -0
  111. package/dist/resolution.js +22 -1
  112. package/dist/role-marker-guard.d.ts +1 -1
  113. package/dist/role-marker-guard.js +1 -1
  114. package/dist/types.d.ts +8 -27
  115. package/package.json +14 -22
  116. package/dist/copilot-stream.d.ts +0 -65
  117. package/dist/copilot-stream.js +0 -123
  118. package/dist/defs/copilot.d.ts +0 -34
  119. package/dist/defs/copilot.js +0 -96
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## 0.6.16
2
+
3
+ ### Minor Changes
4
+
5
+ - Remove the GitHub Copilot CLI agent: its def, `createCopilotStreamHandler`/`CopilotStreamEvent`,
6
+ account model discovery and the `@github/copilot-sdk` optional peer, the MCP installer's `copilot`
7
+ slug, and its icon. A saved `copilot` agent id no longer resolves (`getAgentDef` returns `null`).
8
+ CopilotKit/AG-UI is unrelated and unchanged.
9
+
10
+ Drop peers no runtime entry loads: `express` from core and http-kit (type-only imports; type
11
+ consumers keep `@types/express`), `vue` from ui-kit, `react-dom` from vibecoding.
12
+
1
13
  ## 0.6.13
2
14
 
3
15
  ### Patch Changes
@@ -44,11 +44,8 @@ export function rpcErrorMessage(raw) {
44
44
  if (!obj || !error) {
45
45
  return '';
46
46
  }
47
- const message = typeof error.message === 'string' && error.message.trim()
48
- ? error.message
49
- : typeof error.code === 'number'
50
- ? String(error.code)
51
- : 'json-rpc error';
47
+ const codeText = typeof error.code === 'number' ? String(error.code) : 'json-rpc error';
48
+ const message = typeof error.message === 'string' && error.message.trim() ? error.message : codeText;
52
49
  return typeof obj.id === 'number'
53
50
  ? `json-rpc id ${obj.id}: ${message}`
54
51
  : message;
@@ -151,9 +148,8 @@ export function formatUsage(usage) {
151
148
  */
152
149
  export function choosePermissionOutcome(options, policy = {}) {
153
150
  const list = Array.isArray(options) ? options : [];
154
- const kinds = policy.permissionMode === 'bypass'
155
- ? policy.cliParity ? ['allow_once', 'allow_always', 'reject_once', 'reject_always'] : ['allow_once', 'reject_once', 'reject_always']
156
- : ['reject_once', 'reject_always'];
151
+ const bypassKinds = policy.cliParity ? ['allow_once', 'allow_always', 'reject_once', 'reject_always'] : ['allow_once', 'reject_once', 'reject_always'];
152
+ const kinds = policy.permissionMode === 'bypass' ? bypassKinds : ['reject_once', 'reject_always'];
157
153
  for (const kind of kinds) {
158
154
  const option = list.find((value) => {
159
155
  const record = asObject(value);
@@ -25,6 +25,8 @@ import { findModelConfigOption, currentModelFromSessionResult, modelSelectionErr
25
25
  import { buildAcpSessionNewParams, buildPromptBlocks } from './session-params.js';
26
26
  import { noopAccountFailureClassifier } from './account-failure.js';
27
27
  /** ACP `PermissionOptionKind` values; other offered options are ignored. */
28
+ /** `source` tag on every diagnostic this session reports about the ACP JSON-RPC stream. */
29
+ const ACP_JSON_RPC_SOURCE = 'acp-json-rpc';
28
30
  const ACP_PERMISSION_OPTION_KINDS = ['allow_once', 'allow_always', 'reject_once', 'reject_always'];
29
31
  /** ACP `ToolKind` values; anything else is logged as `other`. */
30
32
  const ACP_TOOL_KINDS = ['read', 'edit', 'delete', 'move', 'search', 'execute', 'think', 'fetch', 'switch_mode', 'other'];
@@ -100,10 +102,8 @@ export function handleRpcError({ state, effects, obj, error, rpcErr, }) {
100
102
  /** True when `obj` is a recoverable error answering our own `session/set_model`
101
103
  * request, sent before any prompt, for a run that asked for no specific model. */
102
104
  function isRecoverableModelSelectionError({ state, effects, obj, error, }) {
103
- return (obj.id === state.setModelRequestId &&
104
- modelSelectionErrorIsRecoverable(error?.code) &&
105
- state.promptRequestId === null &&
106
- (!effects.model || effects.model === 'default'));
105
+ const awaitingSetModel = obj.id === state.setModelRequestId && state.promptRequestId === null;
106
+ return awaitingSetModel && modelSelectionErrorIsRecoverable(error?.code) && (!effects.model || effects.model === 'default');
107
107
  }
108
108
  /** Fails the run for a real RPC error, promoting a known OpenCode session error
109
109
  * payload when present and carrying the RPC `data` details and retryability. */
@@ -221,8 +221,7 @@ export function handleMessageChunkUpdate({ state, effects, update, }) {
221
221
  const isCumulativeSnapshot = state.emittedTextBuffer.length > 0 &&
222
222
  text.length > state.emittedTextBuffer.length && text.startsWith(state.emittedTextBuffer);
223
223
  const delta = isCumulativeSnapshot ? text.slice(state.emittedTextBuffer.length) : text;
224
- if (delta.length === 0)
225
- return;
224
+ // text is nonempty above; a cumulative snapshot is strictly longer than the prior buffer.
226
225
  state.emittedTextChunk = true;
227
226
  state.emittedTextBuffer += delta;
228
227
  const toolCallStrippedDelta = stripToolCallText({ effects, delta });
@@ -547,8 +546,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
547
546
  });
548
547
  throw error;
549
548
  }
550
- const stdin = child.stdin;
551
- const stdout = child.stdout;
549
+ const { stdin, stdout } = child;
552
550
  const state = createAcpSessionState();
553
551
  let emittedFirstTokenStatus = false;
554
552
  let rawAcpShapeDiagnosticCount = 0;
@@ -662,29 +660,27 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
662
660
  clearStageTimer();
663
661
  const useModelUnavailable = modelUnavailableErrorCode &&
664
662
  (options.forceModelUnavailable || isModelUnavailableError(message));
665
- sendFailure({ payload: useModelUnavailable
666
- ? amrModelUnavailablePayload(message)
667
- : options.details === undefined && options.retryable === undefined
668
- ? { message }
669
- : {
670
- message,
671
- error: {
672
- code: 'AGENT_EXECUTION_FAILED',
673
- message,
674
- retryable: options.retryable ?? false,
675
- // Every real call site that reaches this branch (the
676
- // RPC-error path and the no-visible-output path) always
677
- // supplies `details` whenever it supplies `retryable`, and
678
- // `retryable` is itself derived from the same `details`
679
- // source at the RPC-error call site — so `options.details`
680
- // is never actually undefined here. Spreading it
681
- // unconditionally (rather than conditionally omitting the
682
- // key) is behaviorally identical for every real caller;
683
- // simplified per this package's coverage-driven
684
- // dead-branch discipline. See archived provenance ledger.
685
- details: options.details,
686
- },
687
- } });
663
+ const bareFailure = options.details === undefined && options.retryable === undefined;
664
+ const failurePayload = bareFailure ? { message } : {
665
+ message,
666
+ error: {
667
+ code: 'AGENT_EXECUTION_FAILED',
668
+ message,
669
+ retryable: options.retryable ?? false,
670
+ // Every real call site that reaches this branch (the
671
+ // RPC-error path and the no-visible-output path) always
672
+ // supplies `details` whenever it supplies `retryable`, and
673
+ // `retryable` is itself derived from the same `details`
674
+ // source at the RPC-error call site — so `options.details`
675
+ // is never actually undefined here. Spreading it
676
+ // unconditionally (rather than conditionally omitting the
677
+ // key) is behaviorally identical for every real caller;
678
+ // simplified per this package's coverage-driven
679
+ // dead-branch discipline. See archived provenance ledger.
680
+ details: options.details,
681
+ },
682
+ };
683
+ sendFailure({ payload: useModelUnavailable ? amrModelUnavailablePayload(message) : failurePayload });
688
684
  if (!child.killed)
689
685
  child.kill('SIGTERM');
690
686
  };
@@ -706,7 +702,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
706
702
  send({ event: 'agent', payload: {
707
703
  type: 'diagnostic',
708
704
  name: 'acp_raw_event_shape',
709
- source: 'acp-json-rpc',
705
+ source: ACP_JSON_RPC_SOURCE,
710
706
  elapsedMs: Date.now() - runStartedAt,
711
707
  shape: acpRawEventShape(update),
712
708
  } });
@@ -749,7 +745,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
749
745
  send({ event: 'agent', payload: {
750
746
  type: 'diagnostic',
751
747
  name: 'acp_artifact_text_suppression',
752
- source: 'acp-json-rpc',
748
+ source: ACP_JSON_RPC_SOURCE,
753
749
  elapsedMs: Date.now() - runStartedAt,
754
750
  reason,
755
751
  suppressedChars: artifactTextSuppressionSummary.suppressedChars,
@@ -767,7 +763,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
767
763
  send({ event: 'agent', payload: {
768
764
  type: 'diagnostic',
769
765
  name: 'unexpected_text_artifact_in_filesystem_run',
770
- source: 'acp-json-rpc',
766
+ source: ACP_JSON_RPC_SOURCE,
771
767
  elapsedMs: Date.now() - runStartedAt,
772
768
  suppressedChars: artifactTextSuppressionSummary.suppressedChars,
773
769
  suppressedChunks: artifactTextSuppressionSummary.suppressedChunks,
@@ -778,7 +774,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
778
774
  send({ event: 'agent', payload: {
779
775
  type: 'diagnostic',
780
776
  name: 'acp_artifact_text_suppression_summary',
781
- source: 'acp-json-rpc',
777
+ source: ACP_JSON_RPC_SOURCE,
782
778
  elapsedMs: Date.now() - runStartedAt,
783
779
  ...artifactTextSuppressionSummary,
784
780
  } });
@@ -799,7 +795,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
799
795
  send({ event: 'agent', payload: {
800
796
  type: 'diagnostic',
801
797
  name: 'acp_tool_call_text_suppression',
802
- source: 'acp-json-rpc',
798
+ source: ACP_JSON_RPC_SOURCE,
803
799
  elapsedMs: Date.now() - runStartedAt,
804
800
  reason,
805
801
  suppressedChars: toolCallTextSuppressionSummary.suppressedChars,
@@ -816,7 +812,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
816
812
  send({ event: 'agent', payload: {
817
813
  type: 'diagnostic',
818
814
  name: 'acp_tool_call_text_suppression_summary',
819
- source: 'acp-json-rpc',
815
+ source: ACP_JSON_RPC_SOURCE,
820
816
  elapsedMs: Date.now() - runStartedAt,
821
817
  ...toolCallTextSuppressionSummary,
822
818
  } });
@@ -16,8 +16,14 @@
16
16
  * repo's coverage-discipline convention calls for refactoring dead branches
17
17
  * away rather than either of those. See archived provenance ledger.
18
18
  */
19
- const ARTIFACT_OPEN_RE = /(?:<\s*\|?\s*DSML[\s,]+artifact\b[^>]*>|<\s*artifact\b[^>]*>)/i;
20
- const DSML_ARTIFACT_CLOSE_RE = /(?:<\/artifact>|<\/\s*\|?\s*DSML\s*>|<\s*\|?\s*\/\s*DSML\s*\|?\s*>)/i;
19
+ const ARTIFACT_OPEN_RE = /<\s*(?:(?:\|\s*)?DSML[\s,]+)?artifact\b[^>]*>/i;
20
+ // The three closing spellings, tried in this order: `</artifact>`, `</|DSML>` (slash first),
21
+ // and `<|/DSML|>` (pipe first, optional trailing pipe). Whitespace may separate every token.
22
+ const DSML_ARTIFACT_CLOSE_RE = new RegExp([
23
+ /<\/artifact>/,
24
+ /<\/\s*(?:\|\s*)?DSML\s*>/,
25
+ /<\s*(?:\|\s*)?\/\s*DSML\s*(?:\|\s*)?>/,
26
+ ].map((spelling) => spelling.source).join('|'), 'i');
21
27
  const DSML_OPEN_CANONICAL = 'dsmlartifact';
22
28
  const ARTIFACT_OPEN_CANONICAL = 'artifact';
23
29
  const ARTIFACT_CLOSE_CANONICALS = ['artifact', 'dsml'];
@@ -182,11 +188,8 @@ function isPossibleDsmlArtifactOpen(text) {
182
188
  if (!text.startsWith('<') || text.includes('>'))
183
189
  return false;
184
190
  const compact = text.toLowerCase().replace(/[<|,\s]/g, '');
185
- return compact.length === 0 ||
186
- DSML_OPEN_CANONICAL.startsWith(compact) ||
187
- compact.startsWith(DSML_OPEN_CANONICAL) ||
188
- ARTIFACT_OPEN_CANONICAL.startsWith(compact) ||
189
- compact.startsWith(ARTIFACT_OPEN_CANONICAL);
191
+ // An empty `compact` (a bare `<`) is a prefix of every canonical form, so it matches too.
192
+ return [DSML_OPEN_CANONICAL, ARTIFACT_OPEN_CANONICAL].some((canonical) => canonical.startsWith(compact) || compact.startsWith(canonical));
190
193
  }
191
194
  /**
192
195
  * Returns `true` when `text` is a `<`-prefixed, not-yet-closed fragment that
@@ -11,9 +11,7 @@ import { accountFailureDetails, noopAccountFailureClassifier, } from './account-
11
11
  * @returns A flat diagnostic object suitable for inclusion in an agent event payload.
12
12
  */
13
13
  export function acpRawEventShape(update) {
14
- const content = update.content;
15
- const rawInput = update.rawInput;
16
- const locations = update.locations;
14
+ const { content, rawInput, locations } = update;
17
15
  return {
18
16
  sessionUpdate: typeof update.sessionUpdate === 'string' ? update.sessionUpdate : null,
19
17
  keys: objectKeys(update),
@@ -54,6 +52,7 @@ export function isAcpCompletedStatus(update) {
54
52
  const status = acpUpdateStatus(update);
55
53
  return status === 'completed' || status === 'complete' || status === 'succeeded' || status === 'success';
56
54
  }
55
+ const ACP_TERMINAL_FAILURE_STATUSES = new Set(['failed', 'failure', 'error', 'cancelled', 'canceled']);
57
56
  /**
58
57
  * Returns `true` when the update's `status` field represents a terminal
59
58
  * failure state (`failed`, `failure`, `error`, `cancelled`, or `canceled`).
@@ -61,7 +60,7 @@ export function isAcpCompletedStatus(update) {
61
60
  */
62
61
  export function isAcpTerminalFailureStatus(update) {
63
62
  const status = acpUpdateStatus(update);
64
- return status === 'failed' || status === 'failure' || status === 'error' || status === 'cancelled' || status === 'canceled';
63
+ return ACP_TERMINAL_FAILURE_STATUSES.has(status);
65
64
  }
66
65
  /**
67
66
  * Returns `true` when the update's status is `'retry'`. Signals that the AMR
@@ -274,7 +273,7 @@ function titlePath(update) {
274
273
  // Keeping the real extension lets `isArtifactPath` correctly EXCLUDE
275
274
  // non-artifact writes (e.g. "edit config.json"), matching the claude path.
276
275
  const title = typeof update.title === 'string' ? update.title : '';
277
- const match = title.match(/[\w./-]+\.[A-Za-z0-9]+/);
276
+ const match = title.match(/(?<![\w./-])[\w./-]+\.[A-Za-z0-9]+/);
278
277
  if (match?.[0])
279
278
  return match[0];
280
279
  return null;
@@ -74,15 +74,17 @@ export type JsonScanStepResult = 'invalid' | 'incomplete' | {
74
74
  };
75
75
  export declare function afterValue(state: JsonScanState): void;
76
76
  export declare function parseString(value: string, start: number): number | null;
77
- export declare function parseLiteral(value: string, start: number, literal: string): number | null | false;
77
+ /** Index of a scanned value's last character, `null` when the input ends mid-value, `false` when it is not valid JSON. */
78
+ type JsonScanEnd = number | null | false;
79
+ export declare function parseLiteral(value: string, start: number, literal: string): JsonScanEnd;
78
80
  export declare function parseIntegerDigits(value: string, start: number): number | false;
79
81
  export declare function parseFractionDigits(value: string, start: number): number | false;
80
82
  export declare function parseExponentDigits(value: string, start: number): number | false;
81
83
  export declare function parseNumber(value: string, start: number): number | false;
82
84
  export declare function parseStringValue(state: JsonScanState, index: number): number | null;
83
85
  export declare function parseNumberValue(state: JsonScanState, index: number): number | false;
84
- export declare function parseLiteralValue(state: JsonScanState, index: number, literal: string): number | null | false;
85
- export declare function parseValue(state: JsonScanState, index: number): number | null | false;
86
+ export declare function parseLiteralValue(state: JsonScanState, index: number, literal: string): JsonScanEnd;
87
+ export declare function parseValue(state: JsonScanState, index: number): JsonScanEnd;
86
88
  export declare function stepRootFrame(state: JsonScanState, index: number): JsonScanStepResult;
87
89
  export declare function stepObjectKeyOrEnd(state: JsonScanState, current: JsonObjectScanFrame, index: number, char: string): JsonScanStepResult;
88
90
  export declare function stepObjectColon(current: JsonObjectScanFrame, index: number, char: string): JsonScanStepResult;
@@ -108,4 +110,5 @@ export declare function selectStep(state: JsonScanState, index: number, char: st
108
110
  * accumulated stdout lines from an ACP subprocess.
109
111
  */
110
112
  export declare function classifyJsonCandidate(value: string): 'complete' | 'incomplete' | 'invalid';
113
+ export {};
111
114
  //# sourceMappingURL=json-line-stream.d.ts.map
@@ -164,7 +164,7 @@ export function parseLiteral(value, start, literal) {
164
164
  return start + literal.length - 1;
165
165
  }
166
166
  function isDigit(char) {
167
- return /[0-9]/.test(char ?? '');
167
+ return /\d/.test(char ?? '');
168
168
  }
169
169
  function consumeDigits(value, start) {
170
170
  let index = start;
@@ -233,9 +233,8 @@ function openContainer(state, index, frame) {
233
233
  }
234
234
  export function parseLiteralValue(state, index, literal) {
235
235
  const end = parseLiteral(state.value, index, literal);
236
- if (end === false || end === null)
237
- return end;
238
- afterValue(state);
236
+ if (typeof end === 'number')
237
+ afterValue(state);
239
238
  return end;
240
239
  }
241
240
  const LITERAL_STARTS = { t: 'true', f: 'false', n: 'null' };
@@ -255,7 +254,7 @@ export function parseValue(state, index) {
255
254
  // with an `index` already known to be within `value`'s bounds, so `char`
256
255
  // is always defined here; the non-null assertion documents that instead
257
256
  // of a `?? ''` fallback that could never actually be exercised.
258
- if (char === '-' || /[0-9]/.test(char))
257
+ if (char === '-' || /\d/.test(char))
259
258
  return parseNumberValue(state, index);
260
259
  return false;
261
260
  }
@@ -367,18 +366,18 @@ export function selectStep(state, index, char) {
367
366
  */
368
367
  export function classifyJsonCandidate(value) {
369
368
  const state = { value, stack: [], rootComplete: false };
370
- for (let index = 0; index < value.length; index += 1) {
369
+ let index = 0;
370
+ while (index < value.length) {
371
371
  // The loop bound (`index < value.length`) guarantees this index always
372
372
  // yields a defined character; the non-null assertion documents that
373
373
  // runtime invariant in place of a `noUncheckedIndexedAccess`-driven
374
374
  // guard that could never actually trigger.
375
375
  const char = value[index];
376
- if (/\s/.test(char))
377
- continue;
378
- const step = selectStep(state, index, char);
376
+ // Whitespace between tokens is skipped; a step reports the last index it consumed.
377
+ const step = /\s/.test(char) ? null : selectStep(state, index, char);
379
378
  if (step === 'invalid' || step === 'incomplete')
380
379
  return step;
381
- index = step.nextIndex;
380
+ index = (step === null ? index : step.nextIndex) + 1;
382
381
  }
383
382
  return state.rootComplete && state.stack.length === 0 ? 'complete' : 'incomplete';
384
383
  }
@@ -1,4 +1,21 @@
1
1
  import { getRecord } from './internal.js';
2
+ /** `value` when it is a non-empty string, else `undefined`. */
3
+ function nonEmptyString(value) {
4
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
5
+ }
6
+ /** Text blocks verbatim, any other block as its JSON, one per line. */
7
+ function toolResultText(content) {
8
+ return content
9
+ .map((c) => {
10
+ const item = getRecord(c);
11
+ return item?.type === 'text' ? String(item.text ?? '') : JSON.stringify(c);
12
+ })
13
+ .join('\n');
14
+ }
15
+ /** A plain-string result as is; anything else carries no text. */
16
+ function nonArrayToolResultText(content) {
17
+ return typeof content === 'string' ? content : '';
18
+ }
2
19
  export function handleAgentStart(_raw, send) {
3
20
  send({ event: 'agent', payload: { type: 'status', label: 'working' } });
4
21
  return null;
@@ -82,11 +99,7 @@ export function handleAssistantThinkingEnd(_ev, send) {
82
99
  // Surface it so sendAgentEvent's error-handling path sets
83
100
  // agentStreamError and the run flips to `failed` on close.
84
101
  export function handleAssistantError(ev, send, _ctx, raw) {
85
- const message = typeof ev.reason === 'string' && ev.reason.length > 0
86
- ? ev.reason
87
- : typeof ev.delta === 'string' && ev.delta.length > 0
88
- ? ev.delta
89
- : 'Agent error';
102
+ const message = nonEmptyString(ev.reason) ?? nonEmptyString(ev.delta) ?? 'Agent error';
90
103
  send({ event: 'agent', payload: { type: 'error', message, raw } });
91
104
  }
92
105
  const ASSISTANT_MESSAGE_EVENT_HANDLERS = {
@@ -97,12 +110,10 @@ const ASSISTANT_MESSAGE_EVENT_HANDLERS = {
97
110
  error: handleAssistantError,
98
111
  };
99
112
  export function handleMessageUpdate(raw, send, ctx) {
100
- const assistantMessageEvent = getRecord(raw.assistantMessageEvent);
101
- if (!assistantMessageEvent)
102
- return null;
103
- const ev = assistantMessageEvent;
104
- const handler = typeof ev.type === 'string' ? ASSISTANT_MESSAGE_EVENT_HANDLERS[ev.type] : undefined;
105
- handler?.(ev, send, ctx, raw);
113
+ const ev = getRecord(raw.assistantMessageEvent);
114
+ const handler = typeof ev?.type === 'string' ? ASSISTANT_MESSAGE_EVENT_HANDLERS[ev.type] : undefined;
115
+ if (ev && handler)
116
+ handler(ev, send, ctx, raw);
106
117
  return null;
107
118
  }
108
119
  export function handleMessageEnd() {
@@ -123,16 +134,7 @@ export function handleToolExecutionStart(raw, send) {
123
134
  export function handleToolExecutionEnd(raw, send) {
124
135
  const result = getRecord(raw.result);
125
136
  const content = result?.content;
126
- const text = Array.isArray(content)
127
- ? content
128
- .map((c) => {
129
- const item = getRecord(c);
130
- return item?.type === 'text' ? String(item.text ?? '') : JSON.stringify(c);
131
- })
132
- .join('\n')
133
- : typeof content === 'string'
134
- ? content
135
- : '';
137
+ const text = Array.isArray(content) ? toolResultText(content) : nonArrayToolResultText(content);
136
138
  send({ event: 'agent', payload: {
137
139
  type: 'tool_result',
138
140
  toolUseId: raw.toolCallId ?? null,
@@ -164,12 +166,10 @@ export function handleAutoRetryEnd(raw, send) {
164
166
  // Auto-retry exhausted — the agent is about to give up. Surface
165
167
  // the final error so the daemon marks the run as failed rather
166
168
  // than silently succeeding with empty output.
167
- if (raw.success !== false)
168
- return null;
169
- const message = typeof raw.finalError === 'string' && raw.finalError.length > 0
170
- ? raw.finalError
171
- : 'Auto-retry exhausted';
172
- send({ event: 'agent', payload: { type: 'error', message, raw } });
169
+ if (raw.success === false) {
170
+ const message = nonEmptyString(raw.finalError) ?? 'Auto-retry exhausted';
171
+ send({ event: 'agent', payload: { type: 'error', message, raw } });
172
+ }
173
173
  return null;
174
174
  }
175
175
  const PI_RPC_EVENT_HANDLERS = {
@@ -28,21 +28,23 @@ export function parsePiModels({ stdout }) {
28
28
  // defined; the non-null assertion documents that runtime invariant
29
29
  // instead of a `noUncheckedIndexedAccess`-driven guard that could never
30
30
  // actually trigger.
31
- const line = lines[i];
32
- const parts = line.split(/\s+/);
33
- if (parts.length < 2)
34
- continue;
35
- // `parts.length >= 2` (just checked) guarantees both indices are
36
- // defined; same non-null-assertion rationale as above.
37
- const provider = parts[0];
38
- const modelId = parts[1];
39
- // Skip duplicates (some providers list the same model under multiple names).
40
- const fullId = `${provider}/${modelId}`;
41
- if (seen.has(fullId))
31
+ const fullId = providerModelId(lines[i]);
32
+ // Skip rows without both columns, and duplicates (some providers list the
33
+ // same model under multiple names).
34
+ if (fullId === null || seen.has(fullId))
42
35
  continue;
43
36
  seen.add(fullId);
44
37
  entries.push({ id: fullId, label: fullId });
45
38
  }
46
39
  return entries.length > 1 ? entries : null;
47
40
  }
41
+ /** `provider/model` from one table row's first two whitespace-separated columns, or `null` when
42
+ * the row has fewer than two. */
43
+ function providerModelId(line) {
44
+ const parts = line.split(/\s+/);
45
+ if (parts.length < 2)
46
+ return null;
47
+ // `parts.length >= 2` (just checked) guarantees both indices are defined.
48
+ return `${parts[0]}/${parts[1]}`;
49
+ }
48
50
  //# sourceMappingURL=models.js.map
@@ -196,10 +196,10 @@ export function buildPiImagePayloads(imagePaths, uploadRoot) {
196
196
  if (images.length >= MAX_IMAGE_COUNT)
197
197
  break;
198
198
  const read = tryReadImagePayload(imgPath, uploadRoot, totalBytes);
199
- if (!read)
200
- continue;
201
- images.push(read.payload);
202
- totalBytes += read.size;
199
+ if (read) {
200
+ images.push(read.payload);
201
+ totalBytes += read.size;
202
+ }
203
203
  }
204
204
  return images;
205
205
  }
@@ -251,8 +251,7 @@ export function handlePiResponseMessage({ raw, parentSessionRpcId, promptRpcId,
251
251
  */
252
252
  export function attachPiRpcSession(requiredArgs, optionalArgs = {}) {
253
253
  const { child, prompt, cwd, model, send, imagePaths, uploadRoot, parentSession, gracefulShutdownMs = 5000, } = { ...optionalArgs, ...requiredArgs };
254
- const stdin = child.stdin;
255
- const stdout = child.stdout;
254
+ const { stdin, stdout } = child;
256
255
  if (stdin === null) {
257
256
  throw new Error('pi RPC child process is missing stdin');
258
257
  }
@@ -270,7 +269,8 @@ export function attachPiRpcSession(requiredArgs, optionalArgs = {}) {
270
269
  function sendCommand(writable, type, params = {}) {
271
270
  if (!stdinOpen)
272
271
  return null;
273
- const id = nextRpcId++;
272
+ const id = nextRpcId;
273
+ nextRpcId += 1;
274
274
  writable.write(`${JSON.stringify({ id, type, ...params })}\n`);
275
275
  return id;
276
276
  }
@@ -1,7 +1,10 @@
1
1
  const CLASS_PATTERNS = [
2
2
  ['denied', /\b(permission denied|denied|not allowed|not permitted|forbidden|unauthori[sz]ed|requires approval|user rejected|rejected by user)\b/i],
3
3
  ['timeout', /\b(timed? ?out|timeout|deadline exceeded|ETIMEDOUT)\b/i],
4
- ['input_validation', /\b(unknown (input|argument|parameter|property|field)|invalid (input|argument|arguments|parameter|params)|missing required|is required|required (property|parameter|field)|validation (error|failed)|schema|must be (a|an|of)|expected .+ (got|received)|InputValidationError|unrecognized key)\b/i],
4
+ // Input validation is spread over several patterns (checked in order) to keep each one readable.
5
+ ['input_validation', /\b(unknown (input|argument|parameter|property|field)|invalid (input|argument|arguments|parameter|params))\b/i],
6
+ ['input_validation', /\b(missing required|is required|required (property|parameter|field)|validation (error|failed)|schema)\b/i],
7
+ ['input_validation', /\b(must be (a|an|of)|expected .+ (got|received)|InputValidationError|unrecognized key)\b/i],
5
8
  ];
6
9
  export function classifyToolError({ content }) {
7
10
  for (const [errorClass, pattern] of CLASS_PATTERNS) {
@@ -4,7 +4,7 @@
4
4
  * Turns the normalized agent-event stream into {@link AiTraceEvent}s. Every provider path in the
5
5
  * runtime already converges on one vocabulary before the daemon sees it — `status` (model),
6
6
  * `text_delta`, `thinking_delta`, `tool_use`, `tool_result`, `usage`, `turn_end`, `error`, `end`
7
- * — emitted by `claude-stream`, `copilot-stream`, `qoder-stream`, `json-event-stream` (Codex,
7
+ * — emitted by `claude-stream`, `qoder-stream`, `json-event-stream` (Codex,
8
8
  * OpenCode, Cursor, Kimi), the ACP session (Gemini/Codex/Hermes over ACP) and
9
9
  * `runProviderToolTurn` (OpenAI/Anthropic/Azure/Google HTTP). Tapping that one vocabulary is
10
10
  * what makes tracing provider-agnostic: no per-vendor code lives here.
@@ -12,8 +12,7 @@
12
12
  * A model turn follows explicit request boundaries (`status: requesting`, `end`) when the stream has them;
13
13
  * otherwise each usage report closes one turn (CLI per-step or per-run usage).
14
14
  * Within a request, usage reports are snapshots, not boundaries: a final frame can contain usage AND more text.
15
- * HTTP tool-turn produces one turn per call; CLIs that report once per run (Claude Code `result`,
16
- * Copilot) produce one turn per run with all its tool calls — the granularity the provider gave,
15
+ * HTTP tool-turn produces one turn per call; CLIs that report once per run (Claude Code `result`) produce one turn per run with all its tool calls — the granularity the provider gave,
17
16
  * not a guess.
18
17
  */
19
18
  import { type CaptureTextOptions } from './capture.js';
@@ -4,7 +4,7 @@
4
4
  * Turns the normalized agent-event stream into {@link AiTraceEvent}s. Every provider path in the
5
5
  * runtime already converges on one vocabulary before the daemon sees it — `status` (model),
6
6
  * `text_delta`, `thinking_delta`, `tool_use`, `tool_result`, `usage`, `turn_end`, `error`, `end`
7
- * — emitted by `claude-stream`, `copilot-stream`, `qoder-stream`, `json-event-stream` (Codex,
7
+ * — emitted by `claude-stream`, `qoder-stream`, `json-event-stream` (Codex,
8
8
  * OpenCode, Cursor, Kimi), the ACP session (Gemini/Codex/Hermes over ACP) and
9
9
  * `runProviderToolTurn` (OpenAI/Anthropic/Azure/Google HTTP). Tapping that one vocabulary is
10
10
  * what makes tracing provider-agnostic: no per-vendor code lives here.
@@ -12,8 +12,7 @@
12
12
  * A model turn follows explicit request boundaries (`status: requesting`, `end`) when the stream has them;
13
13
  * otherwise each usage report closes one turn (CLI per-step or per-run usage).
14
14
  * Within a request, usage reports are snapshots, not boundaries: a final frame can contain usage AND more text.
15
- * HTTP tool-turn produces one turn per call; CLIs that report once per run (Claude Code `result`,
16
- * Copilot) produce one turn per run with all its tool calls — the granularity the provider gave,
15
+ * HTTP tool-turn produces one turn per call; CLIs that report once per run (Claude Code `result`) produce one turn per run with all its tool calls — the granularity the provider gave,
17
16
  * not a guess.
18
17
  */
19
18
  import { captureText, stringifyForCapture } from './capture.js';
@@ -10,9 +10,23 @@ function eventForCapture({ event, mode }) {
10
10
  case 'model_turn': return { ...event, input: text(event.input), output: text(event.output), reasoning: text(event.reasoning), errorContent: text(event.errorContent), error: event.error === null ? null : 'model_error' };
11
11
  case 'tool_call': return { ...event, input: text(event.input), output: text(event.output) };
12
12
  case 'run_finished': return { ...event, error: event.error === null ? null : { ...event.error, message: 'run_error', content: text(event.error.content) } };
13
+ default: {
14
+ // Unreachable: every AiTraceEvent kind has a case above, and a new kind fails typecheck here.
15
+ const unhandled = event;
16
+ throw new TypeError(`Unknown AI trace event kind: ${String(unhandled.kind)}`);
17
+ }
13
18
  }
14
19
  }
15
20
  export const noopAiTraceSink = { record: () => { } };
21
+ /** Calls `load` right away and settles with its result; a synchronous throw becomes a rejection. */
22
+ function settleSync(load) {
23
+ try {
24
+ return Promise.resolve(load());
25
+ }
26
+ catch (error) {
27
+ return Promise.reject(error);
28
+ }
29
+ }
16
30
  export function createRecordingAiTraceSink(_required = {}) {
17
31
  const events = [];
18
32
  return { events, record: (event) => void events.push(event) };
@@ -91,7 +105,7 @@ export function createLazyAiTraceSink({ load }, { maxQueued = DEFAULT_LAZY_SINK_
91
105
  }
92
106
  }
93
107
  // Invoke load synchronously for existing hosts, but contain a synchronous throw as well as rejection.
94
- const loading = new Promise((resolve) => resolve(load()));
108
+ const loading = settleSync(load);
95
109
  const ready = loading.then((sink) => {
96
110
  target = sink;
97
111
  for (const event of queue)
@@ -106,8 +120,10 @@ export function createLazyAiTraceSink({ load }, { maxQueued = DEFAULT_LAZY_SINK_
106
120
  ready,
107
121
  dropped: () => dropped,
108
122
  record(event) {
109
- if (target)
110
- return deliver(event);
123
+ if (target) {
124
+ deliver(event);
125
+ return;
126
+ }
111
127
  if (queue.length >= maxQueued) {
112
128
  queue.shift();
113
129
  dropped += 1;
@@ -38,6 +38,8 @@ export function normalizeAiUsage({ usage }, _options = {}) {
38
38
  }
39
39
  /** Adds two nullable counters; `null + null` stays `null` so "never reported" survives totals. */
40
40
  export function addNullable(a, b) {
41
- return a === null && b === null ? null : (a ?? 0) + (b ?? 0);
41
+ if (a === null && b === null)
42
+ return null;
43
+ return (a ?? 0) + (b ?? 0);
42
44
  }
43
45
  //# sourceMappingURL=usage.js.map
Binary file