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

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 (177) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +38 -0
  3. package/dist/agent-protocol/acp/models.d.ts +0 -10
  4. package/dist/agent-protocol/acp/models.js +0 -10
  5. package/dist/agent-protocol/acp/rpc.d.ts +5 -1
  6. package/dist/agent-protocol/acp/rpc.js +2 -1
  7. package/dist/agent-protocol/acp/session-permission.js +4 -3
  8. package/dist/agent-protocol/acp/session-results.d.ts +4 -4
  9. package/dist/agent-protocol/acp/session-results.js +30 -21
  10. package/dist/agent-protocol/acp/session-run.js +0 -8
  11. package/dist/agent-protocol/acp/session-types.d.ts +0 -1
  12. package/dist/agent-protocol/acp/session-usage.d.ts +12 -0
  13. package/dist/agent-protocol/acp/session-usage.js +29 -0
  14. package/dist/agent-protocol/acp/session.d.ts +1 -1
  15. package/dist/agent-protocol/acp/session.js +10 -4
  16. package/dist/agent-protocol/acp/text-suppression.js +75 -71
  17. package/dist/agent-protocol/pi-rpc/events.d.ts +21 -4
  18. package/dist/agent-protocol/pi-rpc/events.js +9 -9
  19. package/dist/agent-protocol/pi-rpc/internal.d.ts +6 -2
  20. package/dist/agent-protocol/pi-rpc/internal.js +6 -4
  21. package/dist/agent-protocol/pi-rpc/session.js +4 -3
  22. package/dist/anthropic-live-models.js +0 -0
  23. package/dist/claude-code-models.d.ts +3 -1
  24. package/dist/claude-code-models.js +4 -4
  25. package/dist/claude-stream-frames.js +1 -1
  26. package/dist/cli-probe-cache.d.ts +33 -0
  27. package/dist/cli-probe-cache.js +59 -0
  28. package/dist/custom-instructions.d.ts +107 -0
  29. package/dist/custom-instructions.js +80 -0
  30. package/dist/defs/{aider.d.ts → aider/index.d.ts} +2 -1
  31. package/dist/defs/{aider.js → aider/index.js} +6 -3
  32. package/dist/defs/amr/executable-env.d.ts +2 -0
  33. package/dist/defs/amr/executable-env.js +2 -0
  34. package/dist/defs/amr/executable-resolution.d.ts +5 -1
  35. package/dist/defs/amr/executable-resolution.js +1 -1
  36. package/dist/defs/antigravity/index.d.ts +1 -0
  37. package/dist/defs/antigravity/index.js +3 -0
  38. package/dist/defs/antigravity/permissions.d.ts +26 -0
  39. package/dist/defs/antigravity/permissions.js +66 -0
  40. package/dist/defs/{auggie.d.ts → auggie/index.d.ts} +1 -1
  41. package/dist/defs/{auggie.js → auggie/index.js} +3 -3
  42. package/dist/defs/claude/config-dir.d.ts +62 -0
  43. package/dist/defs/claude/config-dir.js +133 -0
  44. package/dist/defs/claude/filesystem.d.ts +33 -0
  45. package/dist/defs/claude/filesystem.js +30 -0
  46. package/dist/defs/{claude.d.ts → claude/index.d.ts} +1 -1
  47. package/dist/defs/{claude.js → claude/index.js} +9 -9
  48. package/dist/defs/claude/mcp-config.d.ts +22 -0
  49. package/dist/defs/claude/mcp-config.js +29 -0
  50. package/dist/defs/claude/mcp-delivery.d.ts +57 -0
  51. package/dist/defs/claude/mcp-delivery.js +75 -0
  52. package/dist/defs/claude/mcp-json.d.ts +34 -0
  53. package/dist/defs/claude/mcp-json.js +38 -0
  54. package/dist/defs/claude/subagent-start.d.ts +12 -0
  55. package/dist/defs/claude/subagent-start.js +35 -0
  56. package/dist/defs/{cline.d.ts → cline/index.d.ts} +1 -1
  57. package/dist/defs/{cline.js → cline/index.js} +3 -3
  58. package/dist/defs/codex/contracts.d.ts +47 -0
  59. package/dist/defs/codex/contracts.js +6 -0
  60. package/dist/defs/codex/event-stream.d.ts +5 -1
  61. package/dist/defs/codex/event-stream.js +29 -24
  62. package/dist/defs/codex/home-config.d.ts +55 -0
  63. package/dist/defs/codex/home-config.js +224 -0
  64. package/dist/defs/codex/home-staging.d.ts +57 -0
  65. package/dist/defs/codex/home-staging.js +184 -0
  66. package/dist/defs/{codex.d.ts → codex/index.d.ts} +2 -2
  67. package/dist/defs/{codex.js → codex/index.js} +3 -3
  68. package/dist/defs/codex/isolation.d.ts +29 -0
  69. package/dist/defs/codex/isolation.js +69 -0
  70. package/dist/defs/codex/launch.d.ts +4 -1
  71. package/dist/defs/codex/launch.js +1 -1
  72. package/dist/defs/codex/mcp-delivery.d.ts +8 -0
  73. package/dist/defs/codex/mcp-delivery.js +5 -0
  74. package/dist/defs/{crush.d.ts → crush/index.d.ts} +1 -1
  75. package/dist/defs/{crush.js → crush/index.js} +3 -3
  76. package/dist/defs/cursor-agent/event-stream.d.ts +5 -1
  77. package/dist/defs/cursor-agent/event-stream.js +14 -7
  78. package/dist/defs/{cursor-agent.d.ts → cursor-agent/index.d.ts} +1 -1
  79. package/dist/defs/{cursor-agent.js → cursor-agent/index.js} +4 -4
  80. package/dist/defs/{deepseek.d.ts → deepseek/index.d.ts} +2 -1
  81. package/dist/defs/{deepseek.js → deepseek/index.js} +6 -3
  82. package/dist/defs/{devin.d.ts → devin/index.d.ts} +1 -1
  83. package/dist/defs/{devin.js → devin/index.js} +3 -3
  84. package/dist/defs/{droid.d.ts → droid/index.d.ts} +1 -1
  85. package/dist/defs/{droid.js → droid/index.js} +3 -3
  86. package/dist/defs/gemini/event-stream.d.ts +5 -1
  87. package/dist/defs/gemini/event-stream.js +15 -12
  88. package/dist/defs/gemini/tool-calls.d.ts +7 -0
  89. package/dist/defs/gemini/tool-calls.js +9 -0
  90. package/dist/defs/{goose.d.ts → goose/index.d.ts} +1 -1
  91. package/dist/defs/{goose.js → goose/index.js} +3 -3
  92. package/dist/defs/{grok-build.d.ts → grok-build/index.d.ts} +1 -1
  93. package/dist/defs/{grok-build.js → grok-build/index.js} +3 -3
  94. package/dist/defs/index.d.ts +28 -28
  95. package/dist/defs/index.js +28 -28
  96. package/dist/defs/{kilo.d.ts → kilo/index.d.ts} +1 -1
  97. package/dist/defs/{kilo.js → kilo/index.js} +3 -3
  98. package/dist/defs/kimi/event-stream.d.ts +4 -1
  99. package/dist/defs/kimi/event-stream.js +6 -5
  100. package/dist/defs/{kimi.d.ts → kimi/index.d.ts} +1 -1
  101. package/dist/defs/{kimi.js → kimi/index.js} +3 -3
  102. package/dist/defs/{kiro.d.ts → kiro/index.d.ts} +1 -1
  103. package/dist/defs/{kiro.js → kiro/index.js} +3 -3
  104. package/dist/defs/mimo/constants.d.ts +2 -0
  105. package/dist/defs/mimo/constants.js +2 -0
  106. package/dist/defs/{mimo.d.ts → mimo/index.d.ts} +1 -1
  107. package/dist/defs/{mimo.js → mimo/index.js} +3 -3
  108. package/dist/defs/opencode/constants.d.ts +2 -0
  109. package/dist/defs/opencode/constants.js +2 -0
  110. package/dist/defs/opencode/event-stream.d.ts +5 -1
  111. package/dist/defs/opencode/event-stream.js +13 -11
  112. package/dist/defs/{opencode.d.ts → opencode/index.d.ts} +2 -2
  113. package/dist/defs/{opencode.js → opencode/index.js} +5 -5
  114. package/dist/defs/opencode/mcp-config.d.ts +108 -0
  115. package/dist/defs/opencode/mcp-config.js +119 -0
  116. package/dist/defs/opencode/model-discovery.d.ts +3 -1
  117. package/dist/defs/opencode/model-discovery.js +1 -1
  118. package/dist/defs/opencode/tool-calls.d.ts +7 -0
  119. package/dist/defs/opencode/tool-calls.js +12 -0
  120. package/dist/defs/{opencode-acp.d.ts → opencode-acp/index.d.ts} +2 -2
  121. package/dist/defs/{opencode-acp.js → opencode-acp/index.js} +4 -4
  122. package/dist/defs/{pi.d.ts → pi/index.d.ts} +1 -1
  123. package/dist/defs/{pi.js → pi/index.js} +3 -3
  124. package/dist/defs/pi/model-discovery.d.ts +4 -1
  125. package/dist/defs/pi/model-discovery.js +1 -1
  126. package/dist/defs/{qoder.d.ts → qoder/index.d.ts} +1 -1
  127. package/dist/defs/{qoder.js → qoder/index.js} +3 -3
  128. package/dist/defs/{qwen.d.ts → qwen/index.d.ts} +1 -1
  129. package/dist/defs/{qwen.js → qwen/index.js} +3 -3
  130. package/dist/defs/{reasonix.d.ts → reasonix/index.d.ts} +1 -1
  131. package/dist/defs/{reasonix.js → reasonix/index.js} +3 -3
  132. package/dist/defs/{trae-cli.d.ts → trae-cli/index.d.ts} +1 -1
  133. package/dist/defs/{trae-cli.js → trae-cli/index.js} +3 -3
  134. package/dist/defs/{vibe.d.ts → vibe/index.d.ts} +1 -1
  135. package/dist/defs/{vibe.js → vibe/index.js} +3 -3
  136. package/dist/executables.js +1 -1
  137. package/dist/inventory/index.d.ts +61 -0
  138. package/dist/inventory/index.js +45 -0
  139. package/dist/json-event-stream-shared.d.ts +10 -2
  140. package/dist/json-event-stream-shared.js +21 -13
  141. package/dist/json-event-stream.js +6 -5
  142. package/dist/launch.js +1 -1
  143. package/dist/model-catalog-live-discovery.d.ts +103 -0
  144. package/dist/model-catalog-live-discovery.js +111 -0
  145. package/dist/model-discovery-adapters.d.ts +6 -1
  146. package/dist/model-discovery-adapters.js +4 -3
  147. package/dist/model-discovery-config.js +1 -1
  148. package/dist/native-permissions.d.ts +19 -0
  149. package/dist/native-permissions.js +22 -0
  150. package/dist/providers/anthropic-messages.js +3 -2
  151. package/dist/providers/connection-guard.js +99 -84
  152. package/dist/providers/connection-test.js +0 -5
  153. package/dist/providers/google-messages.js +1 -1
  154. package/dist/providers/oauth-provider.d.ts +1 -23
  155. package/dist/providers/oauth-provider.js +1 -35
  156. package/dist/providers/openai-chat-request.js +1 -1
  157. package/dist/providers/tool-loop-verdict.d.ts +1 -0
  158. package/dist/providers/tool-loop-verdict.js +4 -1
  159. package/dist/providers/tool-turn-types.d.ts +12 -9
  160. package/dist/providers/tool-turn.d.ts +63 -1
  161. package/dist/providers/tool-turn.js +67 -1
  162. package/dist/qoder-stream.js +66 -66
  163. package/dist/role-marker-guard.js +49 -30
  164. package/dist/runtime-def-binding.js +1 -1
  165. package/dist/runtime-port-bindings.d.ts +82 -0
  166. package/dist/runtime-port-bindings.js +4 -1
  167. package/dist/runtime-strategies.d.ts +100 -0
  168. package/dist/runtime-strategies.js +129 -0
  169. package/package.json +44 -10
  170. package/dist/defs/amp.d.ts +0 -2
  171. package/dist/defs/amp.js +0 -2
  172. package/dist/defs/amr.d.ts +0 -2
  173. package/dist/defs/amr.js +0 -2
  174. package/dist/defs/codebuddy.d.ts +0 -2
  175. package/dist/defs/codebuddy.js +0 -2
  176. package/dist/defs/hermes.d.ts +0 -2
  177. package/dist/defs/hermes.js +0 -2
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## 0.7.4
2
+
3
+ ### Changes
4
+
5
+ - Move vendor configuration and staging behind runtime strategy ports, including Claude, Codex, and OpenCode adapters.
6
+ - Refuse inline Codex MCP configuration that breaks isolation and fit prompt variants at the actual command-line boundary.
7
+
1
8
  ## 0.7.2
2
9
 
3
10
  ### Patch Changes
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;
@@ -14,7 +14,7 @@ export declare function handleRpcError({ state, effects, obj, error, rpcErr, }:
14
14
  error: UnknownRecord | null;
15
15
  rpcErr: string;
16
16
  }, _optional?: Record<string, never>): void;
17
- /** Handles the `initialize` ack: sends `session/load` (resume) or `session/new` (fresh). */
17
+ /** Handles the `initialize` ack: restores an advertised session or creates a fresh one. */
18
18
  export declare function handleInitializeAck({ state, effects, result }: {
19
19
  state: AcpSessionState;
20
20
  effects: AcpSessionEffects;
@@ -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, }) {
@@ -64,26 +64,35 @@ function failWithRpcError({ effects, obj, rpcErr, }) {
64
64
  ...(retryable === undefined ? {} : { retryable }),
65
65
  });
66
66
  }
67
- /** Handles the `initialize` ack: sends `session/load` (resume) or `session/new` (fresh). */
67
+ /** Prefer no-replay resume when advertised; older peers still use load. */
68
+ function sessionRestoreMethod({ result }) {
69
+ const capabilities = asObject({ value: result.agentCapabilities });
70
+ const sessions = asObject({ value: capabilities?.sessionCapabilities });
71
+ if (asObject({ value: sessions?.resume }))
72
+ return 'session/resume';
73
+ return capabilities?.loadSession === true ? 'session/load' : null;
74
+ }
75
+ /** Handles the `initialize` ack: restores an advertised session or creates a fresh one. */
68
76
  export function handleInitializeAck({ state, effects, result }, _optional = {}) {
69
77
  const message = unsupportedAcpProtocolVersionMessage({ protocolVersion: result.protocolVersion });
70
78
  if (message) {
71
79
  effects.fail(message);
72
80
  return;
73
81
  }
74
- if (effects.resumeSessionId && asObject({ value: result.agentCapabilities })?.loadSession !== true) {
82
+ const restoreMethod = sessionRestoreMethod({ result });
83
+ if (effects.resumeSessionId && !restoreMethod) {
75
84
  effects.fail('This agent cannot reopen a saved conversation (it does not offer session/load); a new conversation is needed.', { details: { reason: 'load_session_unsupported' } });
76
85
  return;
77
86
  }
78
87
  state.expectedId = state.nextId;
79
- if (effects.resumeSessionId) {
88
+ if (effects.resumeSessionId && restoreMethod) {
80
89
  // Resume the prior upstream session instead of creating a fresh one.
81
- effects.writeRpc(state.nextId, 'session/load', {
90
+ effects.writeRpc(state.nextId, restoreMethod, {
82
91
  ...buildAcpSessionNewParams({ cwd: effects.effectiveCwd }, effects.mcpServers
83
92
  ? { mcpServers: effects.mcpServers, envFormat: effects.envFormat }
84
93
  : { envFormat: effects.envFormat }),
85
94
  sessionId: effects.resumeSessionId,
86
- }, 'session/load');
95
+ }, restoreMethod);
87
96
  }
88
97
  else {
89
98
  effects.writeRpc(state.nextId, 'session/new', buildAcpSessionNewParams({ cwd: effects.effectiveCwd }, effects.mcpServers ? { mcpServers: effects.mcpServers, envFormat: effects.envFormat } : { envFormat: effects.envFormat }), 'session/new');
@@ -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;
@@ -0,0 +1,12 @@
1
+ import type { AcpSessionEffects, AcpSessionState } from './session-types.js';
2
+ import type { UnknownRecord } from './types.js';
3
+ /** Preserve session snapshots without charging them again as per-turn usage.
4
+ * ACP used/size describe the current context, not billable input/output tokens;
5
+ * cost is cumulative and its unit is not necessarily USD. O(1), no retained state.
6
+ */
7
+ export declare function handleUsageUpdate({ state, effects, update }: {
8
+ state: Pick<AcpSessionState, 'durableSessionId' | 'sessionId'>;
9
+ effects: Pick<AcpSessionEffects, 'send'>;
10
+ update: UnknownRecord;
11
+ }): void;
12
+ //# sourceMappingURL=session-usage.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { asObject } from './json.js';
2
+ function isTokenCount({ value }) {
3
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
4
+ }
5
+ function sessionCost({ value }) {
6
+ const cost = asObject({ value });
7
+ if (!cost || typeof cost.amount !== 'number' || !Number.isFinite(cost.amount) || cost.amount < 0)
8
+ return null;
9
+ if (typeof cost.currency !== 'string' || !cost.currency.trim())
10
+ return null;
11
+ return { amount: cost.amount, currency: cost.currency };
12
+ }
13
+ /** Preserve session snapshots without charging them again as per-turn usage.
14
+ * ACP used/size describe the current context, not billable input/output tokens;
15
+ * cost is cumulative and its unit is not necessarily USD. O(1), no retained state.
16
+ */
17
+ export function handleUsageUpdate({ state, effects, update }) {
18
+ if (!isTokenCount({ value: update.used }) || !isTokenCount({ value: update.size }))
19
+ return;
20
+ const cost = sessionCost({ value: update.cost });
21
+ const sessionId = state.durableSessionId ?? state.sessionId;
22
+ effects.send({ event: 'agent', payload: {
23
+ type: 'usage', usage: null,
24
+ contextWindow: { used: update.used, size: update.size },
25
+ ...(cost ? { sessionCost: cost } : {}),
26
+ ...(cost?.currency === 'USD' && sessionId ? { cumulativeCostUsd: cost.amount, costSessionId: sessionId } : {}),
27
+ } });
28
+ }
29
+ //# sourceMappingURL=session-usage.js.map
@@ -17,7 +17,7 @@ export declare function handleSessionUpdate({ state, effects, update, }: {
17
17
  *
18
18
  * Sequence:
19
19
  * 1. Sends `initialize` to confirm the protocol version.
20
- * 2. Sends `session/new` (or `session/load` when `resumeSessionId` is set).
20
+ * 2. Sends `session/new` (or advertised `session/resume`/`session/load` for a saved session).
21
21
  * 3. Optionally sends `session/set_model` when a non-default model is requested.
22
22
  * 4. Sends `session/prompt` with the user's prompt and any image attachments.
23
23
  * 5. Streams `session/update` events to the `send` callback, translating:
@@ -1,6 +1,6 @@
1
1
  /** @module agent-protocol/acp/session
2
2
  * ACP session orchestrator: performs the full initialize → session/new (or
3
- * session/load) → session/prompt handshake with an already-spawned ACP
3
+ * session/resume or session/load) → session/prompt handshake with an already-spawned ACP
4
4
  * subprocess, streams updates to the daemon event bus, handles permission
5
5
  * replies, artifact-write mirroring, DSML text suppression, and clean abort.
6
6
  * Depends on every other acp/ file and the core JSON-line stream. Consumed by
@@ -27,6 +27,7 @@ import {} from './session-types.js';
27
27
  import { handleThoughtChunkUpdate, handleMessageChunkUpdate } from './session-text-updates.js';
28
28
  import { handleToolCallUpdate } from './session-tool-updates.js';
29
29
  import { handleRpcError, routeResultById } from './session-results.js';
30
+ import { handleUsageUpdate } from './session-usage.js';
30
31
  /** Promotes an AMR retry-status `session/update` into a structured account-failure error, if the classifier matches. Returns `true` when it did (and thus failed the session). */
31
32
  export function tryPromoteAmrRetryStatus({ effects, update, }, _optional = {}) {
32
33
  const promotedPayload = promotedAmrRetryStatusPayload({ update }, { classifier: effects.accountFailureClassifier });
@@ -67,6 +68,10 @@ function currentModelUpdateId(update) {
67
68
  }
68
69
  /** Routes a `session/update` to its streaming-kind handler (thought, message, tool call). */
69
70
  function routeSessionUpdateKind({ state, effects, update, }) {
71
+ if (update.sessionUpdate === 'usage_update') {
72
+ handleUsageUpdate({ state, effects, update });
73
+ return;
74
+ }
70
75
  if (update.sessionUpdate === 'agent_thought_chunk') {
71
76
  handleThoughtChunkUpdate({ state, effects, update });
72
77
  return;
@@ -96,7 +101,7 @@ function resolveAcpSessionOptionDefaults(options) {
96
101
  *
97
102
  * Sequence:
98
103
  * 1. Sends `initialize` to confirm the protocol version.
99
- * 2. Sends `session/new` (or `session/load` when `resumeSessionId` is set).
104
+ * 2. Sends `session/new` (or advertised `session/resume`/`session/load` for a saved session).
100
105
  * 3. Optionally sends `session/set_model` when a non-default model is requested.
101
106
  * 4. Sends `session/prompt` with the user's prompt and any image attachments.
102
107
  * 5. Streams `session/update` events to the `send` callback, translating:
@@ -162,10 +167,11 @@ function routeAcpMessage({ run, effects, obj, rawLine }) {
162
167
  routeResultById({ state, effects, obj, result: asObject({ value: obj.result }), rawLine });
163
168
  }
164
169
  function replyMethodNotFound({ run, obj }) {
165
- if (!isJsonRpcId(obj.id))
170
+ const id = { value: obj.id };
171
+ if (!isJsonRpcId(id))
166
172
  return;
167
173
  try {
168
- sendRpcError({ writable: run.stdin, id: obj.id, code: -32601, message: `Method not found: ${String(obj.method)}` });
174
+ sendRpcError({ writable: run.stdin, id: id.value, code: -32601, message: `Method not found: ${String(obj.method)}` });
169
175
  }
170
176
  catch { /* broken pipe: transport lifecycle owns process failure */ }
171
177
  }
@@ -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;