@jini-ai/agent-runtime 0.7.3-next.2 → 0.7.3-next.3

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 (167) hide show
  1. package/README.md +38 -0
  2. package/dist/agent-protocol/acp/models.d.ts +0 -10
  3. package/dist/agent-protocol/acp/models.js +0 -10
  4. package/dist/agent-protocol/acp/rpc.d.ts +5 -1
  5. package/dist/agent-protocol/acp/rpc.js +2 -1
  6. package/dist/agent-protocol/acp/session-permission.js +4 -3
  7. package/dist/agent-protocol/acp/session-results.d.ts +3 -3
  8. package/dist/agent-protocol/acp/session-results.js +16 -16
  9. package/dist/agent-protocol/acp/session-run.js +0 -8
  10. package/dist/agent-protocol/acp/session-types.d.ts +0 -1
  11. package/dist/agent-protocol/acp/session.js +3 -2
  12. package/dist/agent-protocol/acp/text-suppression.js +75 -71
  13. package/dist/agent-protocol/pi-rpc/events.d.ts +21 -4
  14. package/dist/agent-protocol/pi-rpc/events.js +8 -8
  15. package/dist/agent-protocol/pi-rpc/internal.d.ts +6 -2
  16. package/dist/agent-protocol/pi-rpc/internal.js +6 -4
  17. package/dist/agent-protocol/pi-rpc/session.js +4 -3
  18. package/dist/anthropic-live-models.js +0 -0
  19. package/dist/claude-code-models.d.ts +3 -1
  20. package/dist/claude-code-models.js +4 -4
  21. package/dist/cli-probe-cache.d.ts +33 -0
  22. package/dist/cli-probe-cache.js +59 -0
  23. package/dist/custom-instructions.d.ts +107 -0
  24. package/dist/custom-instructions.js +80 -0
  25. package/dist/defs/{aider.d.ts → aider/index.d.ts} +2 -1
  26. package/dist/defs/{aider.js → aider/index.js} +6 -3
  27. package/dist/defs/amr/executable-env.d.ts +2 -0
  28. package/dist/defs/amr/executable-env.js +2 -0
  29. package/dist/defs/amr/executable-resolution.d.ts +5 -1
  30. package/dist/defs/amr/executable-resolution.js +1 -1
  31. package/dist/defs/antigravity/index.d.ts +1 -0
  32. package/dist/defs/antigravity/index.js +3 -0
  33. package/dist/defs/antigravity/permissions.d.ts +26 -0
  34. package/dist/defs/antigravity/permissions.js +66 -0
  35. package/dist/defs/{auggie.d.ts → auggie/index.d.ts} +1 -1
  36. package/dist/defs/{auggie.js → auggie/index.js} +3 -3
  37. package/dist/defs/claude/config-dir.d.ts +62 -0
  38. package/dist/defs/claude/config-dir.js +133 -0
  39. package/dist/defs/claude/filesystem.d.ts +33 -0
  40. package/dist/defs/claude/filesystem.js +30 -0
  41. package/dist/defs/{claude.d.ts → claude/index.d.ts} +1 -1
  42. package/dist/defs/{claude.js → claude/index.js} +9 -9
  43. package/dist/defs/claude/mcp-config.d.ts +22 -0
  44. package/dist/defs/claude/mcp-config.js +29 -0
  45. package/dist/defs/claude/mcp-delivery.d.ts +57 -0
  46. package/dist/defs/claude/mcp-delivery.js +75 -0
  47. package/dist/defs/claude/mcp-json.d.ts +34 -0
  48. package/dist/defs/claude/mcp-json.js +38 -0
  49. package/dist/defs/claude/subagent-start.d.ts +12 -0
  50. package/dist/defs/claude/subagent-start.js +35 -0
  51. package/dist/defs/{cline.d.ts → cline/index.d.ts} +1 -1
  52. package/dist/defs/{cline.js → cline/index.js} +3 -3
  53. package/dist/defs/codex/contracts.d.ts +47 -0
  54. package/dist/defs/codex/contracts.js +6 -0
  55. package/dist/defs/codex/event-stream.d.ts +5 -1
  56. package/dist/defs/codex/event-stream.js +29 -24
  57. package/dist/defs/codex/home-config.d.ts +55 -0
  58. package/dist/defs/codex/home-config.js +224 -0
  59. package/dist/defs/codex/home-staging.d.ts +57 -0
  60. package/dist/defs/codex/home-staging.js +184 -0
  61. package/dist/defs/{codex.d.ts → codex/index.d.ts} +2 -2
  62. package/dist/defs/{codex.js → codex/index.js} +3 -3
  63. package/dist/defs/codex/isolation.d.ts +29 -0
  64. package/dist/defs/codex/isolation.js +69 -0
  65. package/dist/defs/codex/launch.d.ts +4 -1
  66. package/dist/defs/codex/launch.js +1 -1
  67. package/dist/defs/codex/mcp-delivery.d.ts +8 -0
  68. package/dist/defs/codex/mcp-delivery.js +5 -0
  69. package/dist/defs/{crush.d.ts → crush/index.d.ts} +1 -1
  70. package/dist/defs/{crush.js → crush/index.js} +3 -3
  71. package/dist/defs/cursor-agent/event-stream.d.ts +5 -1
  72. package/dist/defs/cursor-agent/event-stream.js +14 -7
  73. package/dist/defs/{cursor-agent.d.ts → cursor-agent/index.d.ts} +1 -1
  74. package/dist/defs/{cursor-agent.js → cursor-agent/index.js} +4 -4
  75. package/dist/defs/{deepseek.d.ts → deepseek/index.d.ts} +2 -1
  76. package/dist/defs/{deepseek.js → deepseek/index.js} +6 -3
  77. package/dist/defs/{devin.d.ts → devin/index.d.ts} +1 -1
  78. package/dist/defs/{devin.js → devin/index.js} +3 -3
  79. package/dist/defs/{droid.d.ts → droid/index.d.ts} +1 -1
  80. package/dist/defs/{droid.js → droid/index.js} +3 -3
  81. package/dist/defs/gemini/event-stream.d.ts +5 -1
  82. package/dist/defs/gemini/event-stream.js +15 -12
  83. package/dist/defs/gemini/tool-calls.d.ts +7 -0
  84. package/dist/defs/gemini/tool-calls.js +9 -0
  85. package/dist/defs/{goose.d.ts → goose/index.d.ts} +1 -1
  86. package/dist/defs/{goose.js → goose/index.js} +3 -3
  87. package/dist/defs/{grok-build.d.ts → grok-build/index.d.ts} +1 -1
  88. package/dist/defs/{grok-build.js → grok-build/index.js} +3 -3
  89. package/dist/defs/index.d.ts +28 -28
  90. package/dist/defs/index.js +28 -28
  91. package/dist/defs/{kilo.d.ts → kilo/index.d.ts} +1 -1
  92. package/dist/defs/{kilo.js → kilo/index.js} +3 -3
  93. package/dist/defs/kimi/event-stream.d.ts +4 -1
  94. package/dist/defs/kimi/event-stream.js +6 -5
  95. package/dist/defs/{kimi.d.ts → kimi/index.d.ts} +1 -1
  96. package/dist/defs/{kimi.js → kimi/index.js} +3 -3
  97. package/dist/defs/{kiro.d.ts → kiro/index.d.ts} +1 -1
  98. package/dist/defs/{kiro.js → kiro/index.js} +3 -3
  99. package/dist/defs/mimo/constants.d.ts +2 -0
  100. package/dist/defs/mimo/constants.js +2 -0
  101. package/dist/defs/{mimo.d.ts → mimo/index.d.ts} +1 -1
  102. package/dist/defs/{mimo.js → mimo/index.js} +3 -3
  103. package/dist/defs/opencode/constants.d.ts +2 -0
  104. package/dist/defs/opencode/constants.js +2 -0
  105. package/dist/defs/opencode/event-stream.d.ts +5 -1
  106. package/dist/defs/opencode/event-stream.js +13 -11
  107. package/dist/defs/{opencode.d.ts → opencode/index.d.ts} +2 -2
  108. package/dist/defs/{opencode.js → opencode/index.js} +5 -5
  109. package/dist/defs/opencode/mcp-config.d.ts +108 -0
  110. package/dist/defs/opencode/mcp-config.js +119 -0
  111. package/dist/defs/opencode/model-discovery.d.ts +3 -1
  112. package/dist/defs/opencode/model-discovery.js +1 -1
  113. package/dist/defs/opencode/tool-calls.d.ts +7 -0
  114. package/dist/defs/opencode/tool-calls.js +12 -0
  115. package/dist/defs/{opencode-acp.d.ts → opencode-acp/index.d.ts} +2 -2
  116. package/dist/defs/{opencode-acp.js → opencode-acp/index.js} +4 -4
  117. package/dist/defs/{pi.d.ts → pi/index.d.ts} +1 -1
  118. package/dist/defs/{pi.js → pi/index.js} +3 -3
  119. package/dist/defs/pi/model-discovery.d.ts +4 -1
  120. package/dist/defs/pi/model-discovery.js +1 -1
  121. package/dist/defs/{qoder.d.ts → qoder/index.d.ts} +1 -1
  122. package/dist/defs/{qoder.js → qoder/index.js} +3 -3
  123. package/dist/defs/{qwen.d.ts → qwen/index.d.ts} +1 -1
  124. package/dist/defs/{qwen.js → qwen/index.js} +3 -3
  125. package/dist/defs/{reasonix.d.ts → reasonix/index.d.ts} +1 -1
  126. package/dist/defs/{reasonix.js → reasonix/index.js} +3 -3
  127. package/dist/defs/{trae-cli.d.ts → trae-cli/index.d.ts} +1 -1
  128. package/dist/defs/{trae-cli.js → trae-cli/index.js} +3 -3
  129. package/dist/defs/{vibe.d.ts → vibe/index.d.ts} +1 -1
  130. package/dist/defs/{vibe.js → vibe/index.js} +3 -3
  131. package/dist/executables.js +1 -1
  132. package/dist/inventory/index.d.ts +61 -0
  133. package/dist/inventory/index.js +45 -0
  134. package/dist/json-event-stream-shared.d.ts +10 -2
  135. package/dist/json-event-stream-shared.js +21 -13
  136. package/dist/json-event-stream.js +6 -5
  137. package/dist/launch.js +1 -1
  138. package/dist/model-catalog-live-discovery.d.ts +103 -0
  139. package/dist/model-catalog-live-discovery.js +111 -0
  140. package/dist/model-discovery-adapters.d.ts +6 -1
  141. package/dist/model-discovery-adapters.js +4 -3
  142. package/dist/model-discovery-config.js +1 -1
  143. package/dist/native-permissions.d.ts +19 -0
  144. package/dist/native-permissions.js +22 -0
  145. package/dist/providers/connection-guard.js +98 -83
  146. package/dist/providers/connection-test.js +0 -5
  147. package/dist/providers/oauth-provider.d.ts +1 -23
  148. package/dist/providers/oauth-provider.js +1 -35
  149. package/dist/providers/tool-turn-types.d.ts +12 -9
  150. package/dist/providers/tool-turn.d.ts +63 -1
  151. package/dist/providers/tool-turn.js +66 -0
  152. package/dist/qoder-stream.js +66 -66
  153. package/dist/role-marker-guard.js +49 -30
  154. package/dist/runtime-def-binding.js +1 -1
  155. package/dist/runtime-port-bindings.d.ts +82 -0
  156. package/dist/runtime-port-bindings.js +4 -1
  157. package/dist/runtime-strategies.d.ts +100 -0
  158. package/dist/runtime-strategies.js +129 -0
  159. package/package.json +44 -10
  160. package/dist/defs/amp.d.ts +0 -2
  161. package/dist/defs/amp.js +0 -2
  162. package/dist/defs/amr.d.ts +0 -2
  163. package/dist/defs/amr.js +0 -2
  164. package/dist/defs/codebuddy.d.ts +0 -2
  165. package/dist/defs/codebuddy.js +0 -2
  166. package/dist/defs/hermes.d.ts +0 -2
  167. package/dist/defs/hermes.js +0 -2
package/README.md CHANGED
@@ -61,3 +61,41 @@ redaction and PKCE helpers; consumers receive it automatically on installation.
61
61
  Provider network predicates now live in `@jini-ai/platform/net`; secret redaction lives in `@jini-ai/core` and takes `{ input }` with `{ exactSecrets }`. Runtime no longer re-exports those utilities. Core's conservative policy retains model/request identifiers and returns categorized redaction markers. Model catalog hosts pass core `Clock` (`nowMs()`); ACP transport values use `UnknownRecord` to avoid claiming validated JSON.
62
62
 
63
63
  PKCE providers pass `{ verifierBytes: 64 }` to the main OAuth API. Fixed-issuer token operations use its URL guard, bounded parser, timeout, redirect refusal and typed errors; the runtime maps normalized tokens into its existing persisted provider DTO. Pending callbacks use the main storage factory with an explicit exclusive expiry option and an unref scheduler. The cache is bounded to the main 256-entry default. The conversion report remains in the repository for relocation and is excluded from package files.
64
+
65
+ ## Wiring
66
+
67
+ - **Provider tool turns / BYOK** (`@jini-ai/agent-runtime/providers/tool-turn`): the host calls
68
+ `runProviderToolTurn({ protocol, adapters: providerTurnAdapters, apiKey, model, system, messages, tools, executeTool, onEvent }, { baseUrl, maxTokens, maxToolTurns, signal, getToolSnapshot, onSchemaFallback, onUnexposedToolCall })`
69
+ directly — no host wrapper. The host injects `executeTool` (its own tool surface/executor),
70
+ `onEvent` (its transport), any product policy values (e.g. its meta-tool `maxToolTurns`, a
71
+ visitor `maxTokens` cap, a stored-credential `baseUrl`) and may replace any entry of `adapters`
72
+ (tests inject a fake adapter here instead of mocking the module). A stored free-form provider
73
+ string is narrowed with `resolveProviderProtocol({ provider })` (null when no adapter matches).
74
+
75
+ - **Stored-credential live Claude models** (`@jini-ai/agent-runtime/model-catalog/live-discovery`):
76
+ the host creates ONE instance per app lifetime with
77
+ `createLiveModelDiscovery({ resolveCredential, defaultBaseUrl, clock, discover })`, binding
78
+ `discover: (required) => fetchLiveClaudeModels({ ...required, warn })` with its own `warn(message)`
79
+ log sink (the engine never writes to the console; the host adds any log-line prefix)
80
+ — the TTL cache is instance-owned, never module state. The host injects `resolveCredential` (its
81
+ own stored execution-credential read + decrypt for `{ workspaceId, principalId }`, `null` when
82
+ absent), `defaultBaseUrl` (its provider catalog's Anthropic endpoint) and `clock`; its agent-list
83
+ handler merges the result into the static list with `unionModels({ fallback, live })`.
84
+ - **CLI inventory cache** (`@jini-ai/agent-runtime/cli-probe-cache`): the host calls
85
+ `createCliProbeCache({ initial, probe }, { expiresAt, retryAfterMs })`, injecting `initial` (the
86
+ empty/placeholder snapshot), `probe` (its detection/inventory port) and optionally the catalog
87
+ expiry reader and failure cooldown (e.g. `MODEL_CATALOG_TTL_MS`/`MODEL_NEGATIVE_TTL_MS`). HTTP
88
+ readers call `read({})`; Rescan calls `read({ force: true })`.
89
+ - **Custom instructions overlay** (`@jini-ai/agent-runtime/custom-instructions`): the host injects
90
+ `settingsRepo`, `getEffective` (from `@jini-ai/core/settings`), `instructionsNamespace` (its
91
+ settings namespace holding the `custom` key), `warn(message, error)` (its log sink for the
92
+ fail-open read; the host adds any log-line prefix) and optionally `settingsReady`. The daemon builds one
93
+ `createCustomInstructionsCache({ ...deps, workspaceId })`, calls `refresh()` before each run and wires
94
+ `readOverlay()` into `PromptAugmenter.systemOverlay()`; BYOK turns call
95
+ `resolveCustomInstructions` + `formatCustomInstructionsOverlay` directly.
96
+ - **Native permission layer saves** (`@jini-ai/agent-runtime/native-permissions`): a host reads its
97
+ stored permission layer raw (for example with `readUserLayerObject` from `@jini-ai/core/settings`)
98
+ and calls `patchNativePermissionLayer({ raw, defaults, agentId?, capabilities?, enabled?,
99
+ masterSaveFields? })`, injecting `defaults` (its product permission defaults) and
100
+ `masterSaveFields` (fields stamped on a master-level save, e.g. a migration marker), then writes
101
+ the result back through its settings `set`.
@@ -107,16 +107,6 @@ export declare function normalizeModels({ models, defaultModelOption }: {
107
107
  }, { configOptions }?: {
108
108
  configOptions?: unknown;
109
109
  }): ModelOption[];
110
- /**
111
- * Returns `true` for JSON-RPC error codes that indicate a model-selection
112
- * failure from which the session can recover by falling back to the default
113
- * model and sending the prompt anyway.
114
- *
115
- * @param code - The `error.code` value from a JSON-RPC error response.
116
- */
117
- export declare function modelSelectionErrorIsRecoverable({ code }: {
118
- code: unknown;
119
- }, _optional?: Record<string, never>): boolean;
120
110
  /**
121
111
  * Reads the currently active model id from a `session/new` (or
122
112
  * `session/set_model`) result object, checking `configOptions` first and
@@ -179,16 +179,6 @@ function legacyModelOptions({ models, defaultModelOption, }) {
179
179
  const currentId = typeof modelsObj?.currentModelId === 'string' ? modelsObj.currentModelId : null;
180
180
  return buildModelOptions({ defaultModelOption, currentId, entries: available.map(legacyModelEntry) });
181
181
  }
182
- /**
183
- * Returns `true` for JSON-RPC error codes that indicate a model-selection
184
- * failure from which the session can recover by falling back to the default
185
- * model and sending the prompt anyway.
186
- *
187
- * @param code - The `error.code` value from a JSON-RPC error response.
188
- */
189
- export function modelSelectionErrorIsRecoverable({ code }, _optional = {}) {
190
- return code === -32603 || code === -32602 || code === -32601 || code === -32002;
191
- }
192
182
  /**
193
183
  * Reads the currently active model id from a `session/new` (or
194
184
  * `session/set_model`) result object, checking `configOptions` first and
@@ -44,7 +44,11 @@ export declare function sendRpcError({ writable, id, code, message }: {
44
44
  * Type guard that returns `true` when `value` is a valid JSON-RPC id
45
45
  * (a `number` or `string`). Used before replying to incoming requests.
46
46
  */
47
- export declare function isJsonRpcId(value: unknown): value is JsonRpcId;
47
+ export declare function isJsonRpcId(required: {
48
+ value: unknown;
49
+ }, _optional?: Record<string, never>): required is {
50
+ value: JsonRpcId;
51
+ };
48
52
  /**
49
53
  * Extracts a human-readable error message from a raw JSON-RPC response object
50
54
  * that contains an `error` field. Returns an empty string when the response
@@ -30,7 +30,8 @@ export function sendRpcError({ writable, id, code, message }, _optional = {}) {
30
30
  * Type guard that returns `true` when `value` is a valid JSON-RPC id
31
31
  * (a `number` or `string`). Used before replying to incoming requests.
32
32
  */
33
- export function isJsonRpcId(value) {
33
+ export function isJsonRpcId(required, _optional = {}) {
34
+ const { value } = required;
34
35
  return typeof value === 'number' || typeof value === 'string';
35
36
  }
36
37
  /**
@@ -88,20 +88,21 @@ function askPermissionHandler(reply, params) {
88
88
  export function replyPermission({ run, raw }, _optional = {}) {
89
89
  const params = asObject({ value: raw.params });
90
90
  const toolCall = asObject({ value: params?.toolCall });
91
- if (!isJsonRpcId(raw.id)) {
91
+ const id = { value: raw.id };
92
+ if (!isJsonRpcId(id)) {
92
93
  // No response can be correlated without a valid id; drop it rather
93
94
  // than failing the run.
94
95
  logPermissionDecision({ run, toolCall });
95
96
  return;
96
97
  }
97
98
  const reply = {
98
- run, requestId: raw.id, toolCall, optionRecords: offeredPermissionOptions(params),
99
+ run, requestId: id.value, toolCall, optionRecords: offeredPermissionOptions(params),
99
100
  };
100
101
  if (!params) {
101
102
  respondToPermission(reply, { outcome: 'cancelled' });
102
103
  return;
103
104
  }
104
- run.pendingPermissionRequests.set(raw.id, () => logPermissionDecision({ run, toolCall }));
105
+ run.pendingPermissionRequests.set(id.value, () => logPermissionDecision({ run, toolCall }));
105
106
  // Human decision time is outside the agent's inactivity budget. All timer
106
107
  // resets stay paused until the last pending permission response is sent.
107
108
  clearStageTimer({ run });
@@ -3,9 +3,9 @@ import { type AcpSessionState, type AcpSessionEffects } from './session-types.js
3
3
  /**
4
4
  * Handles a JSON-RPC error frame from the agent.
5
5
  *
6
- * -32603 unexpected-id errors are cleanup noise. Expected-id model selection
7
- * failures are recoverable; all other RPC errors are real protocol failures
8
- * for initialize/session/new/session/prompt.
6
+ * -32603 unexpected-id errors are cleanup noise. A model selection request
7
+ * is only sent for an explicit non-default model, so a rejected selection
8
+ * cannot fall back to the default.
9
9
  */
10
10
  export declare function handleRpcError({ state, effects, obj, error, rpcErr, }: {
11
11
  state: AcpSessionState;
@@ -2,7 +2,7 @@ import { asObject } from './json.js';
2
2
  import { ACP_AUTH_REQUIRED_ERROR_CODE, unsupportedAcpProtocolVersionMessage } from './constants.js';
3
3
  import { accountFailureDetails } from './account-failure.js';
4
4
  import { rpcErrorData, rpcErrorRetryable, promotedOpenCodeSessionErrorPayload, formatUsage } from './rpc.js';
5
- import { findEffortConfigOption, findModelConfigOption, currentModelFromSessionResult, modelSelectionErrorIsRecoverable } from './models.js';
5
+ import { findEffortConfigOption, findModelConfigOption, currentModelFromSessionResult } from './models.js';
6
6
  import { buildAcpSessionNewParams } from './session-params.js';
7
7
  import {} from './session-types.js';
8
8
  /** `typeof value === 'string' ? value : null` as a named predicate — too trivial to export on its own. */
@@ -12,23 +12,19 @@ function asOptionalString(value) {
12
12
  /**
13
13
  * Handles a JSON-RPC error frame from the agent.
14
14
  *
15
- * -32603 unexpected-id errors are cleanup noise. Expected-id model selection
16
- * failures are recoverable; all other RPC errors are real protocol failures
17
- * for initialize/session/new/session/prompt.
15
+ * -32603 unexpected-id errors are cleanup noise. A model selection request
16
+ * is only sent for an explicit non-default model, so a rejected selection
17
+ * cannot fall back to the default.
18
18
  */
19
19
  export function handleRpcError({ state, effects, obj, error, rpcErr, }, _optional = {}) {
20
- if (isRecoverableModelSelectionError({ state, effects, obj, error })) {
21
- effects.recoverFromModelSelectionError();
20
+ if (isUnexpectedInternalError({ state, obj, error })) {
22
21
  return;
23
22
  }
24
- if (error?.code === -32603 && obj.id !== state.expectedId) {
25
- return;
26
- }
27
- if (error?.code === ACP_AUTH_REQUIRED_ERROR_CODE && /auth/i.test(rpcErr)) {
23
+ if (isAuthRequiredError({ error, rpcErr })) {
28
24
  failAuthRequired({ effects, rpcErr });
29
25
  return;
30
26
  }
31
- if (awaitingModelSelectionReply({ state, obj }) && effects.model && effects.model !== 'default') {
27
+ if (isRejectedModelReply({ state, obj, effects })) {
32
28
  effects.fail(`This agent did not accept the model "${effects.model}". Pick a model from its list and retry. (${rpcErr})`, {
33
29
  details: { kind: 'model_unsupported', model: effects.model }, retryable: false,
34
30
  });
@@ -36,6 +32,15 @@ export function handleRpcError({ state, effects, obj, error, rpcErr, }, _optiona
36
32
  }
37
33
  failWithRpcError({ effects, obj, rpcErr });
38
34
  }
35
+ function isUnexpectedInternalError({ state, obj, error }, _optional = {}) {
36
+ return error?.code === -32603 && obj.id !== state.expectedId;
37
+ }
38
+ function isAuthRequiredError({ error, rpcErr }, _optional = {}) {
39
+ return error?.code === ACP_AUTH_REQUIRED_ERROR_CODE && /auth/i.test(rpcErr);
40
+ }
41
+ function isRejectedModelReply({ state, obj, effects }, _optional = {}) {
42
+ return awaitingModelSelectionReply({ state, obj }) && !!effects.model && effects.model !== 'default';
43
+ }
39
44
  function failAuthRequired({ effects, rpcErr }) {
40
45
  const message = `This agent is not signed in. Sign in to its command-line tool on this computer, then retry. (${rpcErr})`;
41
46
  effects.failWithPayload({ message, error: { code: 'AUTH_REQUIRED', message, retryable: false,
@@ -44,11 +49,6 @@ function failAuthRequired({ effects, rpcErr }) {
44
49
  function awaitingModelSelectionReply({ state, obj }) {
45
50
  return state.setModelRequestId !== null && obj.id === state.setModelRequestId && state.promptRequestId === null;
46
51
  }
47
- /** True when `obj` is a recoverable error answering our own `session/set_model`
48
- * request, sent before any prompt, for a run that asked for no specific model. */
49
- function isRecoverableModelSelectionError({ state, effects, obj, error, }) {
50
- return awaitingModelSelectionReply({ state, obj }) && modelSelectionErrorIsRecoverable({ code: error?.code }) && (!effects.model || effects.model === 'default');
51
- }
52
52
  /** Fails the run for a real RPC error, promoting a known OpenCode session error
53
53
  * payload when present and carrying the RPC `data` details and retryability. */
54
54
  function failWithRpcError({ effects, obj, rpcErr, }) {
@@ -389,13 +389,6 @@ function finishCleanPrompt(run, { usageSource } = {}) {
389
389
  child.once('close', () => clearTimeout(cleanExitTimer));
390
390
  } });
391
391
  }
392
- function recoverFromModelSelectionError(run) {
393
- const { state } = run;
394
- state.setModelRequestId = null;
395
- state.activeModel = state.activeModel || 'default';
396
- sendAgent({ run, payload: { type: 'status', label: 'model', model: state.activeModel } });
397
- sendPrompt(run);
398
- }
399
392
  /** Binds the run to the side-effect bundle the exported ACP handlers consume. */
400
393
  export function buildAcpEffects({ run }, _optional = {}) {
401
394
  const { options, resolved } = run;
@@ -405,7 +398,6 @@ export function buildAcpEffects({ run }, _optional = {}) {
405
398
  failWithPayload: (payload) => failWithPayload({ run, payload }),
406
399
  writeRpc: (id, method, params, timeoutLabel) => writeRpc({ run, id, method, params, timeoutLabel }),
407
400
  sendPrompt: () => sendPrompt(run),
408
- recoverFromModelSelectionError: () => recoverFromModelSelectionError(run),
409
401
  finishCleanPrompt: (usageSource) => finishCleanPrompt(run, { usageSource }),
410
402
  emitVisibleTextDelta: (delta) => emitVisibleTextDelta(run, { delta }),
411
403
  noteArtifactTextSuppression: (reason) => noteArtifactTextSuppression(run, { reason }),
@@ -135,7 +135,6 @@ export interface AcpSessionEffects {
135
135
  failWithPayload: (payload: UnknownRecord) => void;
136
136
  writeRpc: (id: JsonRpcId, method: string, params: unknown, timeoutLabel: string) => void;
137
137
  sendPrompt: () => void;
138
- recoverFromModelSelectionError: () => void;
139
138
  finishCleanPrompt: (usageSource?: unknown) => void;
140
139
  emitVisibleTextDelta: (delta: string) => void;
141
140
  noteArtifactTextSuppression: (reason: string) => void;
@@ -162,10 +162,11 @@ function routeAcpMessage({ run, effects, obj, rawLine }) {
162
162
  routeResultById({ state, effects, obj, result: asObject({ value: obj.result }), rawLine });
163
163
  }
164
164
  function replyMethodNotFound({ run, obj }) {
165
- if (!isJsonRpcId(obj.id))
165
+ const id = { value: obj.id };
166
+ if (!isJsonRpcId(id))
166
167
  return;
167
168
  try {
168
- sendRpcError({ writable: run.stdin, id: obj.id, code: -32601, message: `Method not found: ${String(obj.method)}` });
169
+ sendRpcError({ writable: run.stdin, id: id.value, code: -32601, message: `Method not found: ${String(obj.method)}` });
169
170
  }
170
171
  catch { /* broken pipe: transport lifecycle owns process failure */ }
171
172
  }
@@ -57,6 +57,55 @@ export function createToolCallTextSuppressor() {
57
57
  isPossibleClose: isPossibleToolCallClose,
58
58
  });
59
59
  }
60
+ /** Adds one suppressed span to the diagnostic counters. */
61
+ function noteSuppressed(state, text) {
62
+ if (text.length <= 0)
63
+ return;
64
+ state.suppressedChars += text.length;
65
+ state.suppressedChunks += 1;
66
+ }
67
+ /** One step while inside a block: swallow up to the close tag, then hand the remainder back to `stripText`. */
68
+ function stripSuppressed(state, matchers, current) {
69
+ const close = matchers.closeRe.exec(current);
70
+ if (!close || close.index === undefined) {
71
+ const closeCandidateStart = possibleTagStart(current, matchers.isPossibleClose);
72
+ if (closeCandidateStart !== -1) {
73
+ state.candidate = current.slice(closeCandidateStart);
74
+ noteSuppressed(state, current.slice(0, closeCandidateStart));
75
+ }
76
+ else {
77
+ noteSuppressed(state, current);
78
+ }
79
+ return '';
80
+ }
81
+ state.suppressing = false;
82
+ const end = close.index + close[0].length;
83
+ state.closedBlocks += 1;
84
+ noteSuppressed(state, current.slice(0, end));
85
+ return stripText(state, matchers, current.slice(end));
86
+ }
87
+ /** One step while visible: emit up to an open tag (then continue inside it) or hold back a possible tag start. */
88
+ function stripVisible(state, matchers, current) {
89
+ const open = matchers.openRe.exec(current);
90
+ if (open && open.index !== undefined) {
91
+ state.suppressing = true;
92
+ state.openedBlocks += 1;
93
+ const prefix = current.slice(0, open.index);
94
+ const tail = current.slice(open.index + open[0].length);
95
+ noteSuppressed(state, open[0]);
96
+ return `${prefix}${stripText(state, matchers, tail)}`;
97
+ }
98
+ const candidateStart = possibleTagStart(current, matchers.isPossibleOpen);
99
+ if (candidateStart === -1)
100
+ return current;
101
+ state.candidate = current.slice(candidateStart);
102
+ return current.slice(0, candidateStart);
103
+ }
104
+ function stripText(state, matchers, text) {
105
+ const current = `${state.candidate}${text}`;
106
+ state.candidate = '';
107
+ return state.suppressing ? stripSuppressed(state, matchers, current) : stripVisible(state, matchers, current);
108
+ }
60
109
  /**
61
110
  * Builds a stateful `ArtifactTextSuppressor` for one open/close tag pair.
62
111
  * Shared implementation behind both `createDsmlArtifactTextSuppressor` and
@@ -69,77 +118,32 @@ export function createToolCallTextSuppressor() {
69
118
  * @param args.isPossibleClose - Same, for the closing tag.
70
119
  */
71
120
  function createTaggedTextSuppressor(args) {
72
- let suppressing = false;
73
- let candidate = '';
74
- let suppressedChars = 0;
75
- let suppressedChunks = 0;
76
- let openedBlocks = 0;
77
- let closedBlocks = 0;
78
- function noteSuppressed(text) {
79
- if (text.length <= 0)
80
- return;
81
- suppressedChars += text.length;
82
- suppressedChunks += 1;
83
- }
84
- function strip(text) {
85
- const current = `${candidate}${text}`;
86
- candidate = '';
87
- if (suppressing) {
88
- const close = args.closeRe.exec(current);
89
- if (!close || close.index === undefined) {
90
- const closeCandidateStart = possibleTagStart(current, args.isPossibleClose);
91
- if (closeCandidateStart !== -1) {
92
- candidate = current.slice(closeCandidateStart);
93
- noteSuppressed(current.slice(0, closeCandidateStart));
94
- }
95
- else {
96
- noteSuppressed(current);
97
- }
98
- return '';
99
- }
100
- suppressing = false;
101
- const end = close.index + close[0].length;
102
- closedBlocks += 1;
103
- noteSuppressed(current.slice(0, end));
104
- return strip(current.slice(end));
105
- }
106
- const open = args.openRe.exec(current);
107
- if (open && open.index !== undefined) {
108
- suppressing = true;
109
- openedBlocks += 1;
110
- const prefix = current.slice(0, open.index);
111
- const tail = current.slice(open.index + open[0].length);
112
- noteSuppressed(open[0]);
113
- return `${prefix}${strip(tail)}`;
114
- }
115
- const candidateStart = possibleTagStart(current, args.isPossibleOpen);
116
- if (candidateStart === -1)
117
- return current;
118
- candidate = current.slice(candidateStart);
119
- return current.slice(0, candidateStart);
120
- }
121
- function flush() {
122
- const text = candidate;
123
- candidate = '';
124
- return suppressing ? '' : text;
125
- }
126
- function isSuppressing() {
127
- return suppressing;
128
- }
129
- function hasPendingCandidate() {
130
- return candidate.length > 0;
131
- }
132
- function stats() {
133
- return {
134
- suppressedChars,
135
- suppressedChunks,
136
- openedBlocks,
137
- closedBlocks,
138
- pendingCandidateChars: candidate.length,
139
- suppressing,
140
- };
141
- }
142
- return { strip, flush, isSuppressing, hasPendingCandidate, stats };
121
+ const state = {
122
+ suppressing: false,
123
+ candidate: '',
124
+ suppressedChars: 0,
125
+ suppressedChunks: 0,
126
+ openedBlocks: 0,
127
+ closedBlocks: 0,
128
+ };
129
+ return {
130
+ strip: (text) => stripText(state, args, text),
131
+ flush: () => {
132
+ const text = state.candidate;
133
+ state.candidate = '';
134
+ return state.suppressing ? '' : text;
135
+ },
136
+ isSuppressing: () => state.suppressing,
137
+ hasPendingCandidate: () => state.candidate.length > 0,
138
+ stats: () => ({
139
+ suppressedChars: state.suppressedChars,
140
+ suppressedChunks: state.suppressedChunks,
141
+ openedBlocks: state.openedBlocks,
142
+ closedBlocks: state.closedBlocks,
143
+ pendingCandidateChars: state.candidate.length,
144
+ suppressing: state.suppressing,
145
+ }),
146
+ };
143
147
  }
144
148
  /**
145
149
  * Runs `text` through `suppressor` and, if any visible text survives,
@@ -29,13 +29,30 @@ export declare function emitTurnEndErrorIfPresent({ message, raw, send }: {
29
29
  raw: JsonRecord;
30
30
  send: SendAgentEvent;
31
31
  }, _optional?: Record<string, never>): void;
32
- export declare function handleTurnEnd(raw: JsonRecord, send: SendAgentEvent, ctx: PiRpcContext): null;
33
- export declare function handleAssistantTextDelta(ev: JsonRecord, send: SendAgentEvent, ctx: PiRpcContext): void;
32
+ export declare function handleTurnEnd({ raw, send, ctx }: {
33
+ raw: JsonRecord;
34
+ send: SendAgentEvent;
35
+ ctx: PiRpcContext;
36
+ }, _optional?: Record<string, never>): null;
37
+ export declare function handleAssistantTextDelta({ ev, send, ctx }: {
38
+ ev: JsonRecord;
39
+ send: SendAgentEvent;
40
+ ctx: PiRpcContext;
41
+ }, _optional?: Record<string, never>): void;
34
42
  export declare function handleAssistantThinkingDelta(ev: JsonRecord, send: SendAgentEvent): void;
35
43
  export declare function handleAssistantThinkingStart(_ev: JsonRecord, send: SendAgentEvent): void;
36
44
  export declare function handleAssistantThinkingEnd(_ev: JsonRecord, send: SendAgentEvent): void;
37
- export declare function handleAssistantError(ev: JsonRecord, send: SendAgentEvent, _ctx: PiRpcContext, raw: JsonRecord): void;
38
- export declare function handleMessageUpdate(raw: JsonRecord, send: SendAgentEvent, ctx: PiRpcContext): null;
45
+ export declare function handleAssistantError({ ev, send, _ctx, raw }: {
46
+ ev: JsonRecord;
47
+ send: SendAgentEvent;
48
+ _ctx: PiRpcContext;
49
+ raw: JsonRecord;
50
+ }, _optional?: Record<string, never>): void;
51
+ export declare function handleMessageUpdate({ raw, send, ctx }: {
52
+ raw: JsonRecord;
53
+ send: SendAgentEvent;
54
+ ctx: PiRpcContext;
55
+ }, _optional?: Record<string, never>): null;
39
56
  export declare function handleMessageEnd(): null;
40
57
  export declare function handleToolExecutionStart(raw: JsonRecord, send: SendAgentEvent): null;
41
58
  export declare function handleToolExecutionEnd(raw: JsonRecord, send: SendAgentEvent): null;
@@ -62,7 +62,7 @@ export function emitTurnEndErrorIfPresent({ message, raw, send }, _optional = {}
62
62
  : 'Pi agent error';
63
63
  send({ event: 'agent', payload: { type: 'error', message: messageText, raw } });
64
64
  }
65
- export function handleTurnEnd(raw, send, ctx) {
65
+ export function handleTurnEnd({ raw, send, ctx }, _optional = {}) {
66
66
  const message = getRecord({ value: raw.message });
67
67
  const messageUsage = getRecord({ value: message?.usage });
68
68
  if (messageUsage)
@@ -70,7 +70,7 @@ export function handleTurnEnd(raw, send, ctx) {
70
70
  emitTurnEndErrorIfPresent({ message, raw, send });
71
71
  return null;
72
72
  }
73
- export function handleAssistantTextDelta(ev, send, ctx) {
73
+ export function handleAssistantTextDelta({ ev, send, ctx }, _optional = {}) {
74
74
  if (typeof ev.delta !== 'string')
75
75
  return;
76
76
  if (!ctx.sentFirstToken.value) {
@@ -98,18 +98,18 @@ export function handleAssistantThinkingEnd(_ev, send) {
98
98
  // the model returns an error (e.g. aborted, context overflow).
99
99
  // Surface it so sendAgentEvent's error-handling path sets
100
100
  // agentStreamError and the run flips to `failed` on close.
101
- export function handleAssistantError(ev, send, _ctx, raw) {
101
+ export function handleAssistantError({ ev, send, _ctx, raw }, _optional = {}) {
102
102
  const message = nonEmptyString(ev.reason) ?? nonEmptyString(ev.delta) ?? 'Agent error';
103
103
  send({ event: 'agent', payload: { type: 'error', message, raw } });
104
104
  }
105
105
  const ASSISTANT_MESSAGE_EVENT_HANDLERS = {
106
- text_delta: handleAssistantTextDelta,
106
+ text_delta: (ev, send, ctx) => handleAssistantTextDelta({ ev, send, ctx }),
107
107
  thinking_delta: handleAssistantThinkingDelta,
108
108
  thinking_start: handleAssistantThinkingStart,
109
109
  thinking_end: handleAssistantThinkingEnd,
110
- error: handleAssistantError,
110
+ error: (ev, send, ctx, raw) => handleAssistantError({ ev, send, _ctx: ctx, raw }),
111
111
  };
112
- export function handleMessageUpdate(raw, send, ctx) {
112
+ export function handleMessageUpdate({ raw, send, ctx }, _optional = {}) {
113
113
  const ev = getRecord({ value: raw.assistantMessageEvent });
114
114
  const handler = typeof ev?.type === 'string' ? ASSISTANT_MESSAGE_EVENT_HANDLERS[ev.type] : undefined;
115
115
  if (ev && handler)
@@ -176,8 +176,8 @@ const PI_RPC_EVENT_HANDLERS = {
176
176
  agent_start: handleAgentStart,
177
177
  agent_end: handleAgentEnd,
178
178
  turn_start: handleTurnStart,
179
- turn_end: handleTurnEnd,
180
- message_update: handleMessageUpdate,
179
+ turn_end: (raw, send, ctx) => handleTurnEnd({ raw, send, ctx }),
180
+ message_update: (raw, send, ctx) => handleMessageUpdate({ raw, send, ctx }),
181
181
  message_end: handleMessageEnd,
182
182
  tool_execution_start: handleToolExecutionStart,
183
183
  tool_execution_end: handleToolExecutionEnd,
@@ -22,7 +22,11 @@ export type TokenUsage = {
22
22
  * Returns `true` when `value` is a non-null object, narrowing it to
23
23
  * `JsonRecord` for safe property access on RPC message payloads.
24
24
  */
25
- export declare function isRecord(value: unknown): value is JsonRecord;
25
+ export declare function isRecord(required: {
26
+ value: unknown;
27
+ }, _optional?: Record<string, never>): required is {
28
+ value: JsonRecord;
29
+ };
26
30
  /**
27
31
  * Extracts a human-readable message string from an unknown thrown value;
28
32
  * falls back to `String(err)` for non-Error objects.
@@ -48,7 +52,7 @@ export declare function errorCode({ err }: {
48
52
  *
49
53
  * @param value - An arbitrary value from a parsed JSON payload.
50
54
  */
51
- export declare function getRecord({ value }: {
55
+ export declare function getRecord(required: {
52
56
  value: unknown;
53
57
  }, _optional?: Record<string, never>): JsonRecord | undefined;
54
58
  //# sourceMappingURL=internal.d.ts.map
@@ -7,7 +7,8 @@
7
7
  * Returns `true` when `value` is a non-null object, narrowing it to
8
8
  * `JsonRecord` for safe property access on RPC message payloads.
9
9
  */
10
- export function isRecord(value) {
10
+ export function isRecord(required, _optional = {}) {
11
+ const { value } = required;
11
12
  return typeof value === 'object' && value !== null;
12
13
  }
13
14
  /**
@@ -27,7 +28,8 @@ export function errorMessage({ err }, _optional = {}) {
27
28
  * @param err - Any caught value from a try/catch or error callback.
28
29
  */
29
30
  export function errorCode({ err }, _optional = {}) {
30
- return isRecord(err) && typeof err.code === 'string' ? err.code : undefined;
31
+ const record = getRecord({ value: err });
32
+ return typeof record?.code === 'string' ? record.code : undefined;
31
33
  }
32
34
  /**
33
35
  * Returns `value` cast to `JsonRecord` when it is a non-null object, or
@@ -35,7 +37,7 @@ export function errorCode({ err }, _optional = {}) {
35
37
  *
36
38
  * @param value - An arbitrary value from a parsed JSON payload.
37
39
  */
38
- export function getRecord({ value }, _optional = {}) {
39
- return isRecord(value) ? value : undefined;
40
+ export function getRecord(required, _optional = {}) {
41
+ return isRecord(required) ? required.value : undefined;
40
42
  }
41
43
  //# sourceMappingURL=internal.js.map
@@ -8,7 +8,7 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { createJsonLineStream } from '../core/index.js';
10
10
  import { mapPiRpcEvent } from './events.js';
11
- import { isRecord, errorMessage, errorCode, getRecord } from './internal.js';
11
+ import { errorMessage, errorCode, getRecord } from './internal.js';
12
12
  // Image forwarding budgets to prevent large synchronous base64 work.
13
13
  /** Maximum number of images forwarded per prompt turn. */
14
14
  export const MAX_IMAGE_COUNT = 10;
@@ -352,8 +352,9 @@ function handlePiAgentEnd(run) {
352
352
  child.kill('SIGTERM');
353
353
  }, gracefulShutdownMs);
354
354
  }
355
- function handlePiMessage({ run, raw }) {
356
- if (!isRecord(raw))
355
+ function handlePiMessage({ run, raw: value }) {
356
+ const raw = getRecord({ value });
357
+ if (!raw)
357
358
  return;
358
359
  // Once finished (agent_end or abort), stop processing — the run is
359
360
  // over, so no more agent events should be emitted. We still drain
Binary file
@@ -13,7 +13,9 @@ export declare const CLAUDE_CODE_INITIALIZE_REQUEST = "{\"type\":\"control_reque
13
13
  export declare const CLAUDE_CODE_INITIALIZE_ARGS: readonly string[];
14
14
  /** Strips the bracketed context-window variant marker (`claude-fable-5-1[1m]`) —
15
15
  * `models.ts#sanitizeCustomModel` rejects brackets, and `--model` accepts the bare name. */
16
- export declare function normalizeClaudePickerModelId(raw: string): string;
16
+ export declare function normalizeClaudePickerModelId({ raw }: {
17
+ raw: string;
18
+ }, _optional?: Record<string, never>): string;
17
19
  /** Outcome of parsing `~/.claude.json`. The failure reasons are distinct so the freshness guard can
18
20
  * say WHY it skipped; the runtime treats every failure as "nothing to add". */
19
21
  export type ClaudeCodePickerCacheParse = {
@@ -6,7 +6,7 @@ import { defaultRuntimeState } from './runtime-state.js';
6
6
  * `codex debug models`.
7
7
  *
8
8
  * **Why this exists.** `claude` has no list-models subcommand, so without an `ANTHROPIC_API_KEY` the
9
- * picker used to render `defs/claude.ts`'s hand-written `CLAUDE_FALLBACK_MODELS` and nothing else. A
9
+ * picker used to render `defs/claude/index.ts`'s hand-written `CLAUDE_FALLBACK_MODELS` and nothing else. A
10
10
  * subscription-only install therefore never saw a new model (e.g. `claude-opus-5-5`) until someone
11
11
  * edited that array and republished.
12
12
  *
@@ -69,7 +69,7 @@ export const CLAUDE_CODE_INITIALIZE_ARGS = [
69
69
  ];
70
70
  /** Strips the bracketed context-window variant marker (`claude-fable-5-1[1m]`) —
71
71
  * `models.ts#sanitizeCustomModel` rejects brackets, and `--model` accepts the bare name. */
72
- export function normalizeClaudePickerModelId(raw) {
72
+ export function normalizeClaudePickerModelId({ raw }, _optional = {}) {
73
73
  return stripTrailingBracketGroup(raw).trim();
74
74
  }
75
75
  /** `x[1m]` -> `x`: drops a final `[...]` group (one containing no `]`); leaves `raw` alone otherwise.
@@ -103,7 +103,7 @@ export function parseClaudeCodePickerCache({ raw }, _optional = {}) {
103
103
  const ids = cached
104
104
  .map((entry) => (entry && typeof entry === 'object' ? entry.value : null))
105
105
  .filter((value) => typeof value === 'string')
106
- .map(normalizeClaudePickerModelId)
106
+ .map(raw => normalizeClaudePickerModelId({ raw }))
107
107
  .filter((id) => id.length > 0);
108
108
  return ids.length > 0 ? { ok: true, ids } : { ok: false, reason: 'no-usable-values' };
109
109
  }
@@ -137,7 +137,7 @@ function initializeEntryRows(entry) {
137
137
  const rows = [];
138
138
  const displayName = typeof entry.displayName === 'string' ? entry.displayName : '';
139
139
  for (const raw of [entry.value, entry.resolvedModel]) {
140
- const id = typeof raw === 'string' ? normalizeClaudePickerModelId(raw) : 'default';
140
+ const id = typeof raw === 'string' ? normalizeClaudePickerModelId({ raw }) : 'default';
141
141
  // A non-string value contributes nothing, same as the `default` sentinel.
142
142
  if (id === 'default' || sanitizeCustomModel({ id: id }) !== id)
143
143
  continue;