@jini-ai/agent-runtime 0.4.11 → 0.4.12

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 (110) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/acp-model-probe.d.ts +2 -20
  3. package/dist/agent-protocol/acp/json.js +46 -37
  4. package/dist/agent-protocol/acp/models.js +91 -73
  5. package/dist/agent-protocol/acp/rpc.d.ts +3 -2
  6. package/dist/agent-protocol/acp/rpc.js +3 -2
  7. package/dist/agent-protocol/acp/session-params.d.ts +1 -1
  8. package/dist/agent-protocol/acp/session-params.js +33 -30
  9. package/dist/agent-protocol/acp/session.d.ts +3 -1
  10. package/dist/agent-protocol/acp/session.js +62 -24
  11. package/dist/agent-protocol/acp/updates.js +49 -35
  12. package/dist/agent-protocol/pi-rpc/session.js +3 -1
  13. package/dist/anthropic-live-models.d.ts +12 -4
  14. package/dist/anthropic-live-models.js +0 -0
  15. package/dist/auth.js +84 -91
  16. package/dist/claude-code-models.d.ts +6 -5
  17. package/dist/claude-code-models.js +19 -12
  18. package/dist/claude-segment-usage.d.ts +3 -3
  19. package/dist/claude-segment-usage.js +63 -29
  20. package/dist/claude-stream.js +12 -5
  21. package/dist/copilot-stream.js +42 -50
  22. package/dist/defs/aider.js +3 -4
  23. package/dist/defs/amr.js +52 -61
  24. package/dist/defs/antigravity.d.ts +6 -5
  25. package/dist/defs/antigravity.js +48 -34
  26. package/dist/defs/auggie.d.ts +1 -1
  27. package/dist/defs/claude-compatible-args.d.ts +19 -0
  28. package/dist/defs/claude-compatible-args.js +42 -0
  29. package/dist/defs/claude.d.ts +7 -2
  30. package/dist/defs/claude.js +96 -85
  31. package/dist/defs/cline.d.ts +1 -1
  32. package/dist/defs/codebuddy.d.ts +1 -1
  33. package/dist/defs/codebuddy.js +29 -46
  34. package/dist/defs/codex.d.ts +15 -3
  35. package/dist/defs/codex.js +143 -108
  36. package/dist/defs/cursor-agent.d.ts +9 -7
  37. package/dist/defs/cursor-agent.js +53 -51
  38. package/dist/defs/devin.d.ts +1 -1
  39. package/dist/defs/goose.d.ts +1 -1
  40. package/dist/defs/hermes.d.ts +1 -1
  41. package/dist/defs/kilo.d.ts +1 -1
  42. package/dist/defs/kimi.d.ts +1 -1
  43. package/dist/defs/kiro.d.ts +1 -1
  44. package/dist/defs/opencode.d.ts +5 -4
  45. package/dist/defs/opencode.js +26 -32
  46. package/dist/defs/pi.d.ts +6 -5
  47. package/dist/defs/pi.js +24 -26
  48. package/dist/defs/qoder.d.ts +4 -3
  49. package/dist/defs/qoder.js +25 -25
  50. package/dist/defs/reasonix.d.ts +1 -1
  51. package/dist/defs/shared.d.ts +12 -3
  52. package/dist/defs/shared.js +19 -13
  53. package/dist/defs/trae-cli.d.ts +1 -1
  54. package/dist/defs/vibe.d.ts +1 -1
  55. package/dist/detection.d.ts +13 -20
  56. package/dist/detection.js +129 -111
  57. package/dist/env.js +56 -41
  58. package/dist/executables.js +103 -114
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.js +1 -0
  61. package/dist/json-event-stream.js +611 -527
  62. package/dist/launch.js +44 -37
  63. package/dist/model-discovery-adapters.d.ts +17 -0
  64. package/dist/model-discovery-adapters.js +223 -164
  65. package/dist/model-discovery-config.js +107 -87
  66. package/dist/model-discovery-sdk.d.ts +16 -2
  67. package/dist/model-discovery-sdk.js +4 -3
  68. package/dist/model-discovery-shared.d.ts +14 -0
  69. package/dist/model-discovery-shared.js +50 -15
  70. package/dist/model-discovery-types.d.ts +2 -0
  71. package/dist/model-discovery.js +219 -117
  72. package/dist/models.d.ts +14 -1
  73. package/dist/models.js +75 -19
  74. package/dist/native-tool-policy.d.ts +29 -0
  75. package/dist/native-tool-policy.js +36 -0
  76. package/dist/opencode-log.js +46 -30
  77. package/dist/paths.d.ts +2 -0
  78. package/dist/paths.js +3 -3
  79. package/dist/providers/aihubmix.js +13 -18
  80. package/dist/providers/anthropic-messages.d.ts +7 -0
  81. package/dist/providers/anthropic-messages.js +45 -21
  82. package/dist/providers/azure-chat.d.ts +5 -0
  83. package/dist/providers/azure-chat.js +13 -5
  84. package/dist/providers/connection-guard.d.ts +2 -45
  85. package/dist/providers/connection-guard.js +11 -10
  86. package/dist/providers/connection-test.d.ts +4 -0
  87. package/dist/providers/connection-test.js +127 -110
  88. package/dist/providers/elevenlabs.js +4 -1
  89. package/dist/providers/google-messages.d.ts +4 -0
  90. package/dist/providers/google-messages.js +48 -23
  91. package/dist/providers/google-schema.js +17 -23
  92. package/dist/providers/model-catalog.js +160 -145
  93. package/dist/providers/oauth-callback-server.js +37 -34
  94. package/dist/providers/oauth-credentials.js +23 -23
  95. package/dist/providers/oauth-tokens.js +16 -24
  96. package/dist/providers/openai-chat.d.ts +42 -0
  97. package/dist/providers/openai-chat.js +80 -10
  98. package/dist/providers/operation-schema.d.ts +25 -0
  99. package/dist/providers/operation-schema.js +226 -0
  100. package/dist/providers/response-text.d.ts +10 -0
  101. package/dist/providers/response-text.js +23 -0
  102. package/dist/providers/tool-turn-types.d.ts +35 -9
  103. package/dist/providers/tool-turn.d.ts +7 -0
  104. package/dist/providers/tool-turn.js +113 -32
  105. package/dist/qoder-stream.js +93 -80
  106. package/dist/registry.d.ts +45 -0
  107. package/dist/registry.js +39 -0
  108. package/dist/runtime-state.d.ts +1 -1
  109. package/dist/types.d.ts +43 -1
  110. package/package.json +16 -7
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## 0.4.12 — 2026-10-22
2
+
3
+ - 2026-10-22: Probe-gated chromeIntegration build option, declarative supportsSubagents, network-capture and asset-harvest fixes, coverage.
4
+
1
5
  ## 0.4.11 — 2026-10-14
2
6
 
3
7
  - Gemini: `applyGoogleUsage` adds `input_tokens` (`promptTokenCount`) and `output_tokens` (`candidatesTokenCount` + `thoughtsTokenCount`) next to the raw `usageMetadata` fields, so usage reducers show Gemini token counts (024fe7e8).
@@ -5,26 +5,8 @@
5
5
  * and null restores native transport. noopAcpModelProbe is an explicit opt-out that returns no
6
6
  * live models, allowing detection to fall back to the def's static catalog.
7
7
  */
8
- import type { RuntimeEnv, RuntimeModelOption } from './types.js';
9
- export interface AcpModelProbeRequest {
10
- bin: string;
11
- args: string[];
12
- cwd?: string;
13
- env?: RuntimeEnv;
14
- timeoutMs?: number;
15
- signal?: AbortSignal;
16
- clientName?: string;
17
- clientVersion?: string;
18
- defaultModelOption?: RuntimeModelOption;
19
- }
20
- export interface AcpModelProbe {
21
- detectModels(requiredArgs: Pick<AcpModelProbeRequest, 'bin' | 'args'>, optionalArgs?: Omit<AcpModelProbeRequest, 'bin' | 'args'>): Promise<RuntimeModelOption[]>;
22
- /** Optional metadata capability preserves a native current selection without guessing from order. */
23
- detectMetadata?(requiredArgs: Pick<AcpModelProbeRequest, 'bin' | 'args'>, optionalArgs?: Omit<AcpModelProbeRequest, 'bin' | 'args'>): Promise<{
24
- models: RuntimeModelOption[];
25
- currentModelId: string | null;
26
- }>;
27
- }
8
+ import type { AcpModelProbe, AcpModelProbeRequest, RuntimeModelOption } from './types.js';
9
+ export type { AcpModelProbeRequest, AcpModelProbe } from './types.js';
28
10
  export declare const noopAcpModelProbe: AcpModelProbe;
29
11
  /** Native adapter selected once by each host composition; independent of the compatibility setter. */
30
12
  export declare const nativeAcpModelProbe: AcpModelProbe;
@@ -85,29 +85,54 @@ export function extractAcpTextValue(value, depth = 0) {
85
85
  return null;
86
86
  if (typeof value === 'string')
87
87
  return value.length > 0 ? value : null;
88
- if (Array.isArray(value)) {
89
- const text = value
90
- .map((item) => extractAcpTextValue(item, depth + 1))
91
- .filter((part) => typeof part === 'string' && part.length > 0)
92
- .join('');
93
- return text.length > 0 ? text : null;
94
- }
88
+ if (Array.isArray(value))
89
+ return joinAcpArrayText({ items: value, depth });
95
90
  const obj = asObject(value);
96
91
  if (!obj)
97
92
  return null;
98
- for (const key of [
99
- 'text',
100
- 'delta',
101
- 'content',
102
- 'message',
103
- 'output',
104
- 'answer',
105
- 'value',
106
- 'body',
107
- 'parts',
108
- 'choices',
109
- ]) {
110
- const text = extractAcpTextValue(obj[key], depth + 1);
93
+ return firstAcpKeyText({ obj, keys: NESTED_TEXT_KEYS, depth: depth + 1 });
94
+ }
95
+ /** Key order `extractAcpTextValue` probes on nested objects. */
96
+ const NESTED_TEXT_KEYS = [
97
+ 'text',
98
+ 'delta',
99
+ 'content',
100
+ 'message',
101
+ 'output',
102
+ 'answer',
103
+ 'value',
104
+ 'body',
105
+ 'parts',
106
+ 'choices',
107
+ ];
108
+ /** Key order `extractAcpUpdateText` probes on the top-level update object
109
+ * (`content` first, unlike the nested order). */
110
+ const UPDATE_TEXT_KEYS = [
111
+ 'content',
112
+ 'text',
113
+ 'delta',
114
+ 'message',
115
+ 'output',
116
+ 'answer',
117
+ 'value',
118
+ 'body',
119
+ 'parts',
120
+ 'choices',
121
+ ];
122
+ /** Concatenates the non-empty text of every array item (one level deeper),
123
+ * or `null` when the joined text is empty. */
124
+ function joinAcpArrayText({ items, depth }) {
125
+ const text = items
126
+ .map((item) => extractAcpTextValue(item, depth + 1))
127
+ .filter((part) => typeof part === 'string' && part.length > 0)
128
+ .join('');
129
+ return text.length > 0 ? text : null;
130
+ }
131
+ /** Returns the first non-empty text found under `keys` of `obj`, traversing
132
+ * each value at `depth`. */
133
+ function firstAcpKeyText({ obj, keys, depth, }) {
134
+ for (const key of keys) {
135
+ const text = extractAcpTextValue(obj[key], depth);
111
136
  if (text)
112
137
  return text;
113
138
  }
@@ -123,22 +148,6 @@ export function extractAcpTextValue(value, depth = 0) {
123
148
  * @returns The first non-empty text string, or `null` when none is present.
124
149
  */
125
150
  export function extractAcpUpdateText(update) {
126
- for (const key of [
127
- 'content',
128
- 'text',
129
- 'delta',
130
- 'message',
131
- 'output',
132
- 'answer',
133
- 'value',
134
- 'body',
135
- 'parts',
136
- 'choices',
137
- ]) {
138
- const text = extractAcpTextValue(update[key]);
139
- if (text)
140
- return text;
141
- }
142
- return null;
151
+ return firstAcpKeyText({ obj: update, keys: UPDATE_TEXT_KEYS, depth: 0 });
143
152
  }
144
153
  //# sourceMappingURL=json.js.map
@@ -55,28 +55,63 @@ export function isModelConfigOption(option, configId) {
55
55
  export function findModelConfigOption(configOptions) {
56
56
  const options = Array.isArray(configOptions) ? configOptions : [];
57
57
  for (const rawOption of options) {
58
- const option = asObject(rawOption);
59
- if (!option)
60
- continue;
61
- const configId = typeof option.id === 'string' ? option.id.trim() : '';
62
- if (!configId)
63
- continue;
64
- const type = typeof option.type === 'string' ? option.type.trim() : '';
65
- if (type && type !== 'select')
66
- continue;
67
- if (!isModelConfigOption(option, configId))
68
- continue;
69
- const currentValue = typeof option.currentValue === 'string' && option.currentValue.trim()
70
- ? option.currentValue.trim()
71
- : null;
72
- return {
73
- configId,
74
- currentValue,
75
- values: Array.isArray(option.options) ? option.options : [],
76
- };
58
+ const parsed = parseModelConfigOption(rawOption);
59
+ if (parsed)
60
+ return parsed;
77
61
  }
78
62
  return null;
79
63
  }
64
+ /** Returns the trimmed string when `value` is a string, else `''`. */
65
+ function trimmedOrEmpty(value) {
66
+ return typeof value === 'string' ? value.trim() : '';
67
+ }
68
+ /** Parses one `configOptions` entry, returning it only when it is a
69
+ * select-type (or untyped) model-selection option with a non-blank id. */
70
+ function parseModelConfigOption(rawOption) {
71
+ const option = asObject(rawOption);
72
+ if (!option)
73
+ return null;
74
+ const configId = trimmedOrEmpty(option.id);
75
+ if (!configId)
76
+ return null;
77
+ const type = trimmedOrEmpty(option.type);
78
+ if (type && type !== 'select')
79
+ return null;
80
+ if (!isModelConfigOption(option, configId))
81
+ return null;
82
+ return {
83
+ configId,
84
+ currentValue: trimmedOrEmpty(option.currentValue) || null,
85
+ values: Array.isArray(option.options) ? option.options : [],
86
+ };
87
+ }
88
+ /** Builds the deduplicated option list: `defaultModelOption` first, then each
89
+ * entry with a non-blank unseen id, labelled `name (id)` when a distinct name
90
+ * exists and suffixed ` • current` for `currentId`. */
91
+ function buildModelOptions({ defaultModelOption, currentId, entries, }) {
92
+ const seen = new Set([defaultModelOption.id]);
93
+ const out = [defaultModelOption];
94
+ for (const { id, name } of entries) {
95
+ if (!id || seen.has(id))
96
+ continue;
97
+ seen.add(id);
98
+ const labelBase = name && name !== id ? `${name} (${id})` : id;
99
+ out.push({ id, label: id === currentId ? `${labelBase} • current` : labelBase });
100
+ }
101
+ return out;
102
+ }
103
+ /** Reads a config-option value entry: id from `value` (when non-blank) else `id`. */
104
+ function configOptionEntry(value) {
105
+ return {
106
+ id: trimmedOrEmpty(value.value) || trimmedOrEmpty(value.id),
107
+ name: trimmedOrEmpty(value.name),
108
+ };
109
+ }
110
+ /** Reads a legacy `models.availableModels` entry. */
111
+ function legacyModelEntry(model) {
112
+ const obj = asObject(model);
113
+ return { id: trimmedOrEmpty(obj?.modelId), name: trimmedOrEmpty(obj?.name) };
114
+ }
80
115
  /**
81
116
  * Extracts and normalises the available models list from an ACP
82
117
  * `configOptions` array (preferred) into a `ModelOption[]`. Prepends
@@ -91,26 +126,18 @@ export function normalizeModelConfigOptions(configOptions, defaultModelOption) {
91
126
  const modelConfig = findModelConfigOption(configOptions);
92
127
  if (!modelConfig)
93
128
  return null;
94
- const seen = new Set([defaultModelOption.id]);
95
- const out = [defaultModelOption];
129
+ const entries = [];
96
130
  for (const rawValue of modelConfig.values) {
97
131
  const value = asObject(rawValue);
98
- if (!value)
99
- continue;
100
- const id = typeof value.value === 'string' && value.value.trim()
101
- ? value.value.trim()
102
- : typeof value.id === 'string'
103
- ? value.id.trim()
104
- : '';
105
- if (!id || seen.has(id))
106
- continue;
107
- seen.add(id);
108
- const name = typeof value.name === 'string' ? value.name.trim() : '';
109
- const isCurrent = id === modelConfig.currentValue;
110
- const labelBase = name && name !== id ? `${name} (${id})` : id;
111
- out.push({ id, label: isCurrent ? `${labelBase} • current` : labelBase });
132
+ if (value)
133
+ entries.push(configOptionEntry(value));
112
134
  }
113
- return { currentModelId: modelConfig.currentValue, models: out };
135
+ const models = buildModelOptions({
136
+ defaultModelOption,
137
+ currentId: modelConfig.currentValue,
138
+ entries,
139
+ });
140
+ return { currentModelId: modelConfig.currentValue, models };
114
141
  }
115
142
  /**
116
143
  * Produces the final ordered `ModelOption[]` for a session, merging the
@@ -128,22 +155,15 @@ export function normalizeModels({ models, defaultModelOption }, { configOptions
128
155
  if (configModels && configModels.models.length > 1) {
129
156
  return configModels.models;
130
157
  }
158
+ const out = legacyModelOptions({ models, defaultModelOption });
159
+ return out.length > 1 || !configModels ? out : configModels.models;
160
+ }
161
+ /** The legacy `result.models.availableModels` path of `normalizeModels`. */
162
+ function legacyModelOptions({ models, defaultModelOption, }) {
131
163
  const modelsObj = asObject(models);
132
164
  const available = Array.isArray(modelsObj?.availableModels) ? modelsObj.availableModels : [];
133
- const currentModelId = typeof modelsObj?.currentModelId === 'string' ? modelsObj.currentModelId : null;
134
- const seen = new Set([defaultModelOption.id]);
135
- const out = [defaultModelOption];
136
- for (const model of available) {
137
- const id = typeof model?.modelId === 'string' ? model.modelId.trim() : '';
138
- if (!id || seen.has(id))
139
- continue;
140
- seen.add(id);
141
- const name = typeof model?.name === 'string' ? model.name.trim() : '';
142
- const isCurrent = id === currentModelId;
143
- const labelBase = name && name !== id ? `${name} (${id})` : id;
144
- out.push({ id, label: isCurrent ? `${labelBase} • current` : labelBase });
145
- }
146
- return out.length > 1 || !configModels ? out : configModels.models;
165
+ const currentId = typeof modelsObj?.currentModelId === 'string' ? modelsObj.currentModelId : null;
166
+ return buildModelOptions({ defaultModelOption, currentId, entries: available.map(legacyModelEntry) });
147
167
  }
148
168
  /**
149
169
  * Returns `true` for JSON-RPC error codes that indicate a model-selection
@@ -206,7 +226,6 @@ export async function detectAcpModels(requiredArgs, optionalArgs = {}) {
206
226
  let stderrBuf = '';
207
227
  let stdoutBytes = 0;
208
228
  let expectedId = 1;
209
- let nextId = 2;
210
229
  let timer = null;
211
230
  const finish = (fn, value) => {
212
231
  if (settled)
@@ -250,37 +269,36 @@ export async function detectAcpModels(requiredArgs, optionalArgs = {}) {
250
269
  fail(`stdin write failed: ${errorMessage(err)}`);
251
270
  }
252
271
  };
253
- const sendSessionNew = () => {
254
- expectedId = nextId;
255
- writeRpc(nextId, 'session/new', buildAcpSessionNewParams({ cwd: cwd }));
256
- nextId += 1;
272
+ const handleRpcError = (obj, rpcErr) => {
273
+ // JSON-RPC -32603 "Internal error" during model detection:
274
+ // If this is for the current expected-id (initialize/session/new),
275
+ // it's a real probe failure — reject immediately.
276
+ // Otherwise it's cleanup noise — suppress it.
277
+ if (asObject(obj?.error)?.code === -32603 && obj?.id !== expectedId)
278
+ return;
279
+ fail(rpcErr);
280
+ };
281
+ const handleResult = (result) => {
282
+ if (expectedId === 1) {
283
+ expectedId = 2;
284
+ writeRpc(2, 'session/new', buildAcpSessionNewParams({ cwd: cwd }));
285
+ return;
286
+ }
287
+ onSessionResult?.(result);
288
+ const models = normalizeModels({ models: result.models, defaultModelOption: defaultModelOption }, { configOptions: result.configOptions });
289
+ finish(resolve, models);
257
290
  };
258
291
  const parser = createJsonLineStream({ onMessage: ({ message: raw }) => {
259
292
  const obj = asObject(raw);
260
- const error = asObject(obj?.error);
261
- const result = asObject(obj?.result);
262
293
  const rpcErr = rpcErrorMessage(raw);
263
294
  if (rpcErr) {
264
- // JSON-RPC -32603 "Internal error" during model detection:
265
- // If this is for the current expected-id (initialize/session/new),
266
- // it's a real probe failure — reject immediately.
267
- // Otherwise it's cleanup noise — suppress it.
268
- if (error?.code === -32603 && obj?.id !== expectedId)
269
- return;
270
- fail(rpcErr);
295
+ handleRpcError(obj, rpcErr);
271
296
  return;
272
297
  }
298
+ const result = asObject(obj?.result);
273
299
  if (obj?.id !== expectedId || !result)
274
300
  return;
275
- if (expectedId === 1) {
276
- sendSessionNew();
277
- return;
278
- }
279
- if (expectedId === 2) {
280
- onSessionResult?.(result);
281
- const models = normalizeModels({ models: result.models, defaultModelOption: defaultModelOption }, { configOptions: result.configOptions });
282
- finish(resolve, models);
283
- }
301
+ handleResult(result);
284
302
  } });
285
303
  child.stdout.on('data', (chunk) => {
286
304
  stdoutBytes += Buffer.byteLength(String(chunk), 'utf8');
@@ -99,12 +99,13 @@ export declare function formatUsage(usage: unknown): FormattedUsage | null;
99
99
  /**
100
100
  * Selects the best permission-outcome `optionId` to reply with when an ACP
101
101
  * agent sends a `session/request_permission` request. Bypass permits only
102
- * this invocation; otherwise reject. Never broaden approval to future calls.
102
+ * this invocation; otherwise reject. Trusted CLI parity may accept allow_always if that is
103
+ * the only offered approval, matching an explicitly bypassed native CLI.
103
104
  *
104
105
  * @param options - The `params.options` array from the incoming permission request.
105
106
  * @param policy - The existing run permission mode; absence is conservative.
106
107
  * @returns An offered `optionId`, or `null` when no safe choice exists.
107
108
  * @complexity O(n) time and O(1) space for n offered options.
108
109
  */
109
- export declare function choosePermissionOutcome(options: unknown, policy?: Pick<RuntimeBuildOptions, 'permissionMode'>): string | null;
110
+ export declare function choosePermissionOutcome(options: unknown, policy?: Pick<RuntimeBuildOptions, 'permissionMode' | 'cliParity'>): string | null;
110
111
  //# sourceMappingURL=rpc.d.ts.map
@@ -141,7 +141,8 @@ export function formatUsage(usage) {
141
141
  /**
142
142
  * Selects the best permission-outcome `optionId` to reply with when an ACP
143
143
  * agent sends a `session/request_permission` request. Bypass permits only
144
- * this invocation; otherwise reject. Never broaden approval to future calls.
144
+ * this invocation; otherwise reject. Trusted CLI parity may accept allow_always if that is
145
+ * the only offered approval, matching an explicitly bypassed native CLI.
145
146
  *
146
147
  * @param options - The `params.options` array from the incoming permission request.
147
148
  * @param policy - The existing run permission mode; absence is conservative.
@@ -151,7 +152,7 @@ export function formatUsage(usage) {
151
152
  export function choosePermissionOutcome(options, policy = {}) {
152
153
  const list = Array.isArray(options) ? options : [];
153
154
  const kinds = policy.permissionMode === 'bypass'
154
- ? ['allow_once', 'reject_once', 'reject_always']
155
+ ? policy.cliParity ? ['allow_once', 'allow_always', 'reject_once', 'reject_always'] : ['allow_once', 'reject_once', 'reject_always']
155
156
  : ['reject_once', 'reject_always'];
156
157
  for (const kind of kinds) {
157
158
  const option = list.find((value) => {
@@ -40,7 +40,7 @@ export declare function buildAcpSessionNewParams({ cwd }: {
40
40
  name: string;
41
41
  command: string;
42
42
  args: any[];
43
- env: any;
43
+ env: unknown;
44
44
  }[];
45
45
  };
46
46
  /**
@@ -28,38 +28,41 @@ export function buildAcpSessionNewParams({ cwd }, options = {}) {
28
28
  // agents can run through the skill + CLI path without MCP support. Do not
29
29
  // auto-install or mutate user/global MCP config; callers must pass an
30
30
  // explicit per-session MCP descriptor when a compatible agent supports it.
31
- mcpServers: servers.map((s) => {
32
- const rawEnv = s?.env;
33
- // Already a plain object — pass through in map mode, convert to
34
- // array in array mode (e.g. live-artifacts MCP from
35
- // buildLiveArtifactsMcpServersForAgent which already respects
36
- // acpMcpEnvFormat).
37
- const isPlainObject = rawEnv && typeof rawEnv === 'object' && !Array.isArray(rawEnv);
38
- if (wantsMap && isPlainObject) {
39
- return {
40
- type: typeof s?.type === 'string' ? s.type : 'stdio',
41
- name: typeof s?.name === 'string' ? s.name : '',
42
- command: typeof s?.command === 'string' ? s.command : '',
43
- args: Array.isArray(s?.args) ? s.args : [],
44
- env: rawEnv,
45
- };
46
- }
47
- const envArr = Array.isArray(rawEnv) ? rawEnv : [];
48
- const env = wantsMap
49
- ? Object.fromEntries(envArr.map((e) => [e?.name ?? '', e?.value ?? '']))
50
- : isPlainObject
51
- ? Object.entries(rawEnv).map(([name, value]) => ({ name, value }))
52
- : envArr;
53
- return {
54
- type: typeof s?.type === 'string' ? s.type : 'stdio',
55
- name: typeof s?.name === 'string' ? s.name : '',
56
- command: typeof s?.command === 'string' ? s.command : '',
57
- args: Array.isArray(s?.args) ? s.args : [],
58
- env,
59
- };
60
- }),
31
+ mcpServers: servers.map((server) => normalizeMcpServer({ server, wantsMap })),
61
32
  };
62
33
  }
34
+ /** Returns `value` when it is a string, else `fallback`. */
35
+ function stringOr({ value, fallback }) {
36
+ return typeof value === 'string' ? value : fallback;
37
+ }
38
+ /** Normalises one caller-supplied MCP server descriptor into the wire shape
39
+ * (`type`/`name`/`command`/`args`/`env`, in that key order). */
40
+ function normalizeMcpServer({ server: s, wantsMap, }) {
41
+ return {
42
+ type: stringOr({ value: s?.type, fallback: 'stdio' }),
43
+ name: stringOr({ value: s?.name, fallback: '' }),
44
+ command: stringOr({ value: s?.command, fallback: '' }),
45
+ args: Array.isArray(s?.args) ? s.args : [],
46
+ env: normalizeMcpEnv({ rawEnv: s?.env, wantsMap }),
47
+ };
48
+ }
49
+ /** Converts an MCP server `env` value to the requested wire format. */
50
+ function normalizeMcpEnv({ rawEnv, wantsMap }) {
51
+ // Already a plain object — pass through in map mode, convert to
52
+ // array in array mode (e.g. live-artifacts MCP from
53
+ // buildLiveArtifactsMcpServersForAgent which already respects
54
+ // acpMcpEnvFormat).
55
+ const isPlainObject = rawEnv && typeof rawEnv === 'object' && !Array.isArray(rawEnv);
56
+ if (isPlainObject) {
57
+ return wantsMap
58
+ ? rawEnv
59
+ : Object.entries(rawEnv).map(([name, value]) => ({ name, value }));
60
+ }
61
+ const envArr = Array.isArray(rawEnv) ? rawEnv : [];
62
+ return wantsMap
63
+ ? Object.fromEntries(envArr.map((e) => [e?.name ?? '', e?.value ?? '']))
64
+ : envArr;
65
+ }
63
66
  /**
64
67
  * Assembles the `prompt` array for a `session/prompt` ACP call. Always
65
68
  * includes a leading `{ type: 'text', text: prompt }` block, followed by
@@ -49,6 +49,8 @@ export interface AcpSessionController {
49
49
  * `send` are optional and carry sensible defaults.
50
50
  */
51
51
  export interface AttachAcpSessionOptions {
52
+ /** Host-authorized parity: bypass native permission requests; disable silence watchdog. */
53
+ cliParity?: boolean;
52
54
  child: AcpChildProcess;
53
55
  prompt: string;
54
56
  cwd?: string;
@@ -127,7 +129,7 @@ export interface AcpSessionEffects {
127
129
  details?: unknown;
128
130
  retryable?: boolean;
129
131
  }) => void;
130
- failWithPayload: (payload: unknown) => void;
132
+ failWithPayload: (payload: UnknownRecord) => void;
131
133
  writeRpc: (id: JsonRpcId, method: string, params: unknown, timeoutLabel: string) => void;
132
134
  sendPrompt: () => void;
133
135
  recoverFromModelSelectionError: () => void;
@@ -54,6 +54,28 @@ export function createAcpSessionState() {
54
54
  acpArtifactRunEventState: new Map(),
55
55
  };
56
56
  }
57
+ /** The well-formed options of a permission request: a non-empty `optionId`
58
+ * and an ACP `PermissionOptionKind`; anything else offered is ignored. */
59
+ function offeredPermissionOptions(params) {
60
+ if (!Array.isArray(params?.options))
61
+ return [];
62
+ return params.options.filter((option) => {
63
+ const record = asObject(option);
64
+ return typeof record?.optionId === 'string' && record.optionId !== '' &&
65
+ typeof record.kind === 'string' && ACP_PERMISSION_OPTION_KINDS.includes(record.kind);
66
+ });
67
+ }
68
+ /** The tool call's ACP `ToolKind` for permission logging, `other` when absent or unknown. */
69
+ function permissionToolKind(toolCall) {
70
+ return typeof toolCall?.kind === 'string' && ACP_TOOL_KINDS.includes(toolCall.kind) ? toolCall.kind : 'other';
71
+ }
72
+ /** The permission decision used when no `onPermissionRequest` handler is
73
+ * injected: the option `choosePermissionOutcome` picks under the run's
74
+ * `permissionMode` / `cliParity`, or a cancellation when it picks none. */
75
+ function defaultPermissionDecision({ optionRecords }, { permissionMode, cliParity, } = {}) {
76
+ const optionId = choosePermissionOutcome(optionRecords, { ...(permissionMode ? { permissionMode } : {}), ...(cliParity ? { cliParity: true } : {}) });
77
+ return optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' };
78
+ }
57
79
  /** `typeof value === 'string' ? value : null` as a named predicate — too trivial to export on its own. */
58
80
  function asOptionalString(value) {
59
81
  return typeof value === 'string' ? value : null;
@@ -74,16 +96,26 @@ function resolveModelConfigId(modelConfig) {
74
96
  * for initialize/session/new/session/prompt.
75
97
  */
76
98
  export function handleRpcError({ state, effects, obj, error, rpcErr, }) {
77
- if (obj.id === state.setModelRequestId &&
78
- modelSelectionErrorIsRecoverable(error?.code) &&
79
- state.promptRequestId === null &&
80
- (!effects.model || effects.model === 'default')) {
99
+ if (isRecoverableModelSelectionError({ state, effects, obj, error })) {
81
100
  effects.recoverFromModelSelectionError();
82
101
  return;
83
102
  }
84
103
  if (error?.code === -32603 && obj.id !== state.expectedId) {
85
104
  return;
86
105
  }
106
+ failWithRpcError({ effects, obj, rpcErr });
107
+ }
108
+ /** True when `obj` is a recoverable error answering our own `session/set_model`
109
+ * request, sent before any prompt, for a run that asked for no specific model. */
110
+ function isRecoverableModelSelectionError({ state, effects, obj, error, }) {
111
+ return (obj.id === state.setModelRequestId &&
112
+ modelSelectionErrorIsRecoverable(error?.code) &&
113
+ state.promptRequestId === null &&
114
+ (!effects.model || effects.model === 'default'));
115
+ }
116
+ /** Fails the run for a real RPC error, promoting a known OpenCode session error
117
+ * payload when present and carrying the RPC `data` details and retryability. */
118
+ function failWithRpcError({ effects, obj, rpcErr, }) {
87
119
  const details = rpcErrorData(obj);
88
120
  const promotedPayload = promotedOpenCodeSessionErrorPayload(details, rpcErr);
89
121
  if (promotedPayload) {
@@ -304,13 +336,7 @@ export function handleToolCallUpdate({ state, effects, update, }) {
304
336
  }
305
337
  /** Top-level `session/update` dispatcher: emits a generic status for non-streaming update kinds, then routes to the matching per-kind handler. */
306
338
  export function handleSessionUpdate({ state, effects, update, }) {
307
- // Model/config updates are authoritative protocol metadata, not assistant self-report.
308
- const changedModel = currentModelFromSessionResult(update)
309
- ?? (update.sessionUpdate === 'current_model_update' && typeof update.currentModelId === 'string' ? update.currentModelId : null);
310
- if (changedModel && changedModel !== state.activeModel) {
311
- state.activeModel = changedModel;
312
- effects.send({ event: 'agent', payload: { type: 'status', label: 'model', model: changedModel } });
313
- }
339
+ applyModelChangeUpdate({ state, effects, update });
314
340
  if (effects.modelUnavailableErrorCode && tryPromoteAmrRetryStatus({ effects, update }))
315
341
  return;
316
342
  if (update.sessionUpdate !== 'agent_message_chunk' && update.sessionUpdate !== 'agent_thought_chunk') {
@@ -321,6 +347,25 @@ export function handleSessionUpdate({ state, effects, update, }) {
321
347
  } });
322
348
  effects.emitAcpRawShapeDiagnostic(update);
323
349
  }
350
+ routeSessionUpdateKind({ state, effects, update });
351
+ }
352
+ /** Tracks a model switch reported by a `session/update` and emits a `model` status when it changes. */
353
+ function applyModelChangeUpdate({ state, effects, update, }) {
354
+ // Model/config updates are authoritative protocol metadata, not assistant self-report.
355
+ const changedModel = currentModelFromSessionResult(update) ?? currentModelUpdateId(update);
356
+ if (changedModel && changedModel !== state.activeModel) {
357
+ state.activeModel = changedModel;
358
+ effects.send({ event: 'agent', payload: { type: 'status', label: 'model', model: changedModel } });
359
+ }
360
+ }
361
+ /** The `currentModelId` of a `current_model_update` notification, else `null`. */
362
+ function currentModelUpdateId(update) {
363
+ return update.sessionUpdate === 'current_model_update' && typeof update.currentModelId === 'string'
364
+ ? update.currentModelId
365
+ : null;
366
+ }
367
+ /** Routes a `session/update` to its streaming-kind handler (thought, message, tool call). */
368
+ function routeSessionUpdateKind({ state, effects, update, }) {
324
369
  if (update.sessionUpdate === 'agent_thought_chunk') {
325
370
  handleThoughtChunkUpdate({ state, effects, update });
326
371
  return;
@@ -449,7 +494,7 @@ function resolveAcpSessionOptionDefaults(options) {
449
494
  envFormat: options.envFormat ?? 'array',
450
495
  clientName: options.clientName ?? 'agent-runtime',
451
496
  clientVersion: options.clientVersion ?? 'runtime-adapter',
452
- stageTimeoutMs: options.stageTimeoutMs ?? DEFAULT_STAGE_TIMEOUT_MS,
497
+ stageTimeoutMs: options.cliParity && options.permissionMode === 'bypass' ? 0 : options.stageTimeoutMs ?? DEFAULT_STAGE_TIMEOUT_MS,
453
498
  executionProfile: options.executionProfile ?? 'filesystem',
454
499
  accountFailureClassifier: options.accountFailureClassifier ?? noopAccountFailureClassifier,
455
500
  };
@@ -565,7 +610,7 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
565
610
  send({ event: 'error', payload });
566
611
  return;
567
612
  }
568
- const original = asObject(payload) ?? {};
613
+ const original = payload;
569
614
  const originalError = asObject(original.error);
570
615
  send({ event: 'error', payload: {
571
616
  ...original,
@@ -823,19 +868,13 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
823
868
  const replyPermission = (raw) => {
824
869
  const params = asObject(raw.params);
825
870
  const toolCall = asObject(params?.toolCall);
826
- const optionRecords = Array.isArray(params?.options)
827
- ? params.options.filter((option) => {
828
- const record = asObject(option);
829
- return typeof record?.optionId === 'string' && record.optionId !== '' &&
830
- typeof record.kind === 'string' && ACP_PERMISSION_OPTION_KINDS.includes(record.kind);
831
- })
832
- : [];
871
+ const optionRecords = offeredPermissionOptions(params);
833
872
  // One status event per request. Only protocol categories leave this
834
873
  // boundary: titles, names, option ids and raw arguments can contain
835
874
  // commands, paths or credentials.
836
875
  const logDecision = (selected) => {
837
876
  try {
838
- const tool = typeof toolCall?.kind === 'string' && ACP_TOOL_KINDS.includes(toolCall.kind) ? toolCall.kind : 'other';
877
+ const tool = permissionToolKind(toolCall);
839
878
  send({ event: 'agent', payload: { type: 'status', label: 'acp_permission', detail: `tool=${tool} decision=${selected?.kind ?? 'cancelled'}` } });
840
879
  }
841
880
  catch {
@@ -878,13 +917,12 @@ export function attachAcpSession(requiredArgs, optionalArgs = {}) {
878
917
  pendingPermissionRequests.set(requestId, () => logDecision());
879
918
  try {
880
919
  if (!onPermissionRequest) {
881
- const optionId = choosePermissionOutcome(optionRecords, permissionMode ? { permissionMode } : {});
882
- respond(optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' });
920
+ respond(defaultPermissionDecision({ optionRecords }, { permissionMode, cliParity: options.cliParity }));
883
921
  return;
884
922
  }
885
923
  const request = {
886
924
  requestId,
887
- sessionId: typeof params.sessionId === 'string' ? params.sessionId : null,
925
+ sessionId: asOptionalString(params.sessionId),
888
926
  toolCall: toolCall ?? null,
889
927
  options: optionRecords,
890
928
  rawParams: params,