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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/agent-protocol/acp/rpc.js +4 -8
  3. package/dist/agent-protocol/acp/session.js +33 -37
  4. package/dist/agent-protocol/acp/text-suppression.js +10 -7
  5. package/dist/agent-protocol/acp/updates.js +4 -5
  6. package/dist/agent-protocol/core/json-line-stream.d.ts +6 -3
  7. package/dist/agent-protocol/core/json-line-stream.js +9 -10
  8. package/dist/agent-protocol/pi-rpc/events.js +27 -27
  9. package/dist/agent-protocol/pi-rpc/models.js +13 -11
  10. package/dist/agent-protocol/pi-rpc/session.js +7 -7
  11. package/dist/ai-trace/classify.js +4 -1
  12. package/dist/ai-trace/recorder.d.ts +2 -3
  13. package/dist/ai-trace/recorder.js +2 -3
  14. package/dist/ai-trace/sinks.js +19 -3
  15. package/dist/ai-trace/usage.js +3 -1
  16. package/dist/anthropic-live-models.js +0 -0
  17. package/dist/auth.js +20 -17
  18. package/dist/claude-code-models.js +29 -17
  19. package/dist/claude-filesystem-policy.d.ts +4 -3
  20. package/dist/claude-filesystem-policy.js +39 -12
  21. package/dist/claude-stream.js +65 -47
  22. package/dist/core/model-discovery-shared.js +4 -2
  23. package/dist/core/omit-keys.d.ts +7 -0
  24. package/dist/core/omit-keys.js +12 -0
  25. package/dist/defs/aider.d.ts +1 -1
  26. package/dist/defs/amp.d.ts +1 -1
  27. package/dist/defs/amp.js +2 -2
  28. package/dist/defs/amr.js +5 -9
  29. package/dist/defs/antigravity-event-stream.d.ts +19 -0
  30. package/dist/defs/antigravity-event-stream.js +83 -0
  31. package/dist/defs/antigravity.d.ts +4 -0
  32. package/dist/defs/antigravity.js +27 -15
  33. package/dist/defs/auggie.d.ts +3 -3
  34. package/dist/defs/claude.d.ts +3 -3
  35. package/dist/defs/cline.d.ts +3 -3
  36. package/dist/defs/codebuddy.d.ts +1 -1
  37. package/dist/defs/codex.js +3 -2
  38. package/dist/defs/crush.d.ts +1 -1
  39. package/dist/defs/cursor-agent.d.ts +3 -1
  40. package/dist/defs/cursor-agent.js +8 -6
  41. package/dist/defs/deepseek.d.ts +1 -1
  42. package/dist/defs/devin.d.ts +3 -3
  43. package/dist/defs/droid.d.ts +1 -1
  44. package/dist/defs/goose.d.ts +3 -3
  45. package/dist/defs/grok-build.js +7 -5
  46. package/dist/defs/hermes.d.ts +3 -3
  47. package/dist/defs/index.d.ts +0 -1
  48. package/dist/defs/index.js +0 -1
  49. package/dist/defs/kilo.d.ts +3 -3
  50. package/dist/defs/kimi.d.ts +3 -3
  51. package/dist/defs/kiro.d.ts +3 -3
  52. package/dist/defs/mimo.d.ts +1 -1
  53. package/dist/defs/opencode.d.ts +1 -1
  54. package/dist/defs/pi.d.ts +1 -1
  55. package/dist/defs/qoder.d.ts +1 -1
  56. package/dist/defs/qwen.d.ts +1 -1
  57. package/dist/defs/reasonix.d.ts +3 -3
  58. package/dist/defs/trae-cli.d.ts +3 -3
  59. package/dist/defs/vibe.d.ts +3 -3
  60. package/dist/detection.js +22 -2
  61. package/dist/executables.js +0 -1
  62. package/dist/index.d.ts +0 -1
  63. package/dist/index.js +0 -1
  64. package/dist/json-event-stream.d.ts +1 -2
  65. package/dist/json-event-stream.js +10 -9
  66. package/dist/launch.js +2 -1
  67. package/dist/metadata.js +0 -4
  68. package/dist/model-catalog-cache.js +6 -4
  69. package/dist/model-contracts.d.ts +29 -0
  70. package/dist/model-contracts.js +2 -0
  71. package/dist/model-discovery-adapters.js +47 -24
  72. package/dist/model-discovery-config.js +8 -5
  73. package/dist/model-discovery-sdk.d.ts +0 -29
  74. package/dist/model-discovery-sdk.js +0 -32
  75. package/dist/model-discovery-types.d.ts +3 -3
  76. package/dist/model-discovery-yaml.d.ts +9 -0
  77. package/dist/model-discovery-yaml.js +98 -0
  78. package/dist/model-discovery.js +10 -3
  79. package/dist/model-registry.js +2 -1
  80. package/dist/native-tool-policy.d.ts +28 -0
  81. package/dist/native-tool-policy.js +42 -0
  82. package/dist/opencode-log.js +13 -10
  83. package/dist/pi-models.js +13 -11
  84. package/dist/probe-scheduler.js +13 -5
  85. package/dist/providers/aihubmix.js +6 -7
  86. package/dist/providers/anthropic-messages.d.ts +7 -4
  87. package/dist/providers/anthropic-messages.js +22 -24
  88. package/dist/providers/azure-chat.d.ts +1 -1
  89. package/dist/providers/azure-chat.js +7 -10
  90. package/dist/providers/connection-guard.js +2 -1
  91. package/dist/providers/connection-test.js +16 -10
  92. package/dist/providers/google-messages.d.ts +1 -1
  93. package/dist/providers/google-messages.js +33 -35
  94. package/dist/providers/google.js +3 -4
  95. package/dist/providers/model-catalog.js +10 -7
  96. package/dist/providers/ollama-chat.d.ts +0 -8
  97. package/dist/providers/ollama-chat.js +17 -19
  98. package/dist/providers/openai-chat.d.ts +6 -3
  99. package/dist/providers/openai-chat.js +24 -22
  100. package/dist/providers/operation-schema.d.ts +2 -3
  101. package/dist/providers/operation-schema.js +25 -22
  102. package/dist/providers/provider-tool-policy.d.ts +13 -0
  103. package/dist/providers/provider-tool-policy.js +2 -0
  104. package/dist/providers/tool-loop-verdict.d.ts +22 -0
  105. package/dist/providers/tool-loop-verdict.js +17 -0
  106. package/dist/providers/tool-turn-types.d.ts +2 -12
  107. package/dist/providers/tool-turn.js +7 -2
  108. package/dist/registry.d.ts +1 -1
  109. package/dist/registry.js +2 -3
  110. package/dist/resolution.d.ts +21 -0
  111. package/dist/resolution.js +22 -1
  112. package/dist/role-marker-guard.d.ts +1 -1
  113. package/dist/role-marker-guard.js +1 -1
  114. package/dist/types.d.ts +8 -27
  115. package/package.json +14 -22
  116. package/dist/copilot-stream.d.ts +0 -65
  117. package/dist/copilot-stream.js +0 -123
  118. package/dist/defs/copilot.d.ts +0 -34
  119. package/dist/defs/copilot.js +0 -96
package/dist/auth.js CHANGED
@@ -59,12 +59,14 @@ export function isCursorAuthFailureText({ text }) {
59
59
  const value = String(text || '');
60
60
  if (!value.trim())
61
61
  return false;
62
- return (/authentication required/i.test(value) ||
63
- /not authenticated/i.test(value) ||
64
- /not logged in/i.test(value) ||
65
- /unauthenticated/i.test(value) ||
66
- /agent login/i.test(value) ||
67
- /cursor_api_key/i.test(value));
62
+ return [
63
+ /authentication required/i,
64
+ /not authenticated/i,
65
+ /not logged in/i,
66
+ /unauthenticated/i,
67
+ /agent login/i,
68
+ /cursor_api_key/i,
69
+ ].some((pattern) => pattern.test(value));
68
70
  }
69
71
  // agy's plain-mode output when no keyring credentials are available:
70
72
  // - Top of stdout: "Authentication required. Please visit the URL to log in: <URL>"
@@ -88,11 +90,10 @@ export function isDeepSeekAuthFailureText({ text }) {
88
90
  const value = String(text || '');
89
91
  if (!value.trim())
90
92
  return false;
91
- return (/KEY=<your-key>/i.test(value) ||
92
- /api_key\s*=\s*["']<your-key>["']/i.test(value) ||
93
- (/~\/\.deepseek\/config\.toml/i.test(value) && /api[_ -]?key|KEY=/i.test(value)) ||
94
- (/DEEPSEEK_API_KEY/i.test(value) &&
95
- /auth|api[_ -]?key|missing|not set|required|unauthorized/i.test(value)));
93
+ const placeholderKey = /KEY=<your-key>/i.test(value) || /api_key\s*=\s*["']<your-key>["']/i.test(value);
94
+ const configMentionsKey = /~\/\.deepseek\/config\.toml/i.test(value) && /api[_ -]?key|KEY=/i.test(value);
95
+ const envKeyProblem = /DEEPSEEK_API_KEY/i.test(value) && /auth|api[_ -]?key|missing|not set|required|unauthorized/i.test(value);
96
+ return placeholderKey || configMentionsKey || envKeyProblem;
96
97
  }
97
98
  export function isReasonixAuthFailureText({ text }) {
98
99
  const value = String(text || '');
@@ -124,12 +125,14 @@ function claudeTextAuthFailure({ value }) {
124
125
  if (/"authenticated"\s*:\s*true/i.test(value) || /"loggedIn"\s*:\s*true/i.test(value)) {
125
126
  return false;
126
127
  }
127
- return (/"authenticated"\s*:\s*false/i.test(value) ||
128
- /"loggedIn"\s*:\s*false/i.test(value) ||
129
- /not authenticated/i.test(value) ||
130
- /not logged[ _-]?in/i.test(value) ||
131
- /authentication required/i.test(value) ||
132
- /please (?:sign|log)[ _-]?in/i.test(value));
128
+ return [
129
+ /"authenticated"\s*:\s*false/i,
130
+ /"loggedIn"\s*:\s*false/i,
131
+ /not authenticated/i,
132
+ /not logged[ _-]?in/i,
133
+ /authentication required/i,
134
+ /please (?:sign|log)[ _-]?in/i,
135
+ ].some((pattern) => pattern.test(value));
133
136
  }
134
137
  export function isClaudeAuthFailureText({ text }) {
135
138
  const value = String(text || '');
@@ -69,7 +69,16 @@ export const CLAUDE_CODE_INITIALIZE_ARGS = [
69
69
  /** Strips the bracketed context-window variant marker (`claude-fable-5-1[1m]`) —
70
70
  * `models.ts#sanitizeCustomModel` rejects brackets, and `--model` accepts the bare name. */
71
71
  export function normalizeClaudePickerModelId(raw) {
72
- return raw.replace(/\[[^\]]*\]$/, '').trim();
72
+ return stripTrailingBracketGroup(raw).trim();
73
+ }
74
+ /** `x[1m]` -> `x`: drops a final `[...]` group (one containing no `]`); leaves `raw` alone otherwise.
75
+ * Same result as `raw.replace(/\[[^\]]*\]$/, '')`, in one linear pass. */
76
+ function stripTrailingBracketGroup(raw) {
77
+ if (!raw.endsWith(']'))
78
+ return raw;
79
+ const close = raw.length - 1;
80
+ const open = raw.indexOf('[', raw.lastIndexOf(']', close - 1) + 1);
81
+ return open !== -1 && open < close ? raw.slice(0, open) : raw;
73
82
  }
74
83
  /**
75
84
  * Parses the raw text of `~/.claude.json` down to the model ids in `additionalModelOptionsCache`.
@@ -97,22 +106,26 @@ export function parseClaudeCodePickerCache(raw) {
97
106
  .filter((id) => id.length > 0);
98
107
  return ids.length > 0 ? { ok: true, ids } : { ok: false, reason: 'no-usable-values' };
99
108
  }
109
+ /** The models array of one successful `control_response` line, or `null` for any other line. */
110
+ function initializeModelsFromLine(line) {
111
+ try {
112
+ const msg = JSON.parse(line);
113
+ if (msg.type !== 'control_response' || msg.response?.subtype !== 'success')
114
+ return null;
115
+ const models = msg.response.response?.models;
116
+ return Array.isArray(models) ? models : null;
117
+ }
118
+ catch {
119
+ // Not a JSON line (or a truncated one on timeout) — keep scanning.
120
+ return null;
121
+ }
122
+ }
100
123
  /** Pulls `response.response.models` out of the one `control_response` line, or `null`. */
101
124
  function findInitializeModels(stdout) {
102
125
  for (const line of stdout.split('\n')) {
103
- if (!line.includes('control_response'))
104
- continue;
105
- try {
106
- const msg = JSON.parse(line);
107
- if (msg.type !== 'control_response' || msg.response?.subtype !== 'success')
108
- continue;
109
- const models = msg.response.response?.models;
110
- if (Array.isArray(models))
111
- return models;
112
- }
113
- catch {
114
- // Not a JSON line (or a truncated one on timeout) — keep scanning.
115
- }
126
+ const models = line.includes('control_response') ? initializeModelsFromLine(line) : null;
127
+ if (models)
128
+ return models;
116
129
  }
117
130
  return null;
118
131
  }
@@ -123,9 +136,8 @@ function initializeEntryRows(entry) {
123
136
  const rows = [];
124
137
  const displayName = typeof entry.displayName === 'string' ? entry.displayName : '';
125
138
  for (const raw of [entry.value, entry.resolvedModel]) {
126
- if (typeof raw !== 'string')
127
- continue;
128
- const id = normalizeClaudePickerModelId(raw);
139
+ const id = typeof raw === 'string' ? normalizeClaudePickerModelId(raw) : 'default';
140
+ // A non-string value contributes nothing, same as the `default` sentinel.
129
141
  if (id === 'default' || sanitizeCustomModel({ id: id }) !== id)
130
142
  continue;
131
143
  const isAlias = !id.startsWith('claude-');
@@ -53,16 +53,17 @@ export declare function claudeFilesystemRuntimePaths(required: {
53
53
  * Personal/project layers are excluded separately. Preserve host hooks and secret denies.
54
54
  * Phase 1 leaves network policy unconfigured; the CLI's sandbox network defaults still apply.
55
55
  * https://code.claude.com/docs/en/permissions#working-directories
56
- * O(s + r) serialization for s host settings bytes and r runtime exception paths. Pure with
57
- * injectable host facts; errors reject malformed/file-based settings rather than dropping policy.
56
+ * O(s + r * t) for s host settings bytes, r scratch aliases and t deny roots, with injectable
57
+ * realpath lookups; errors reject malformed settings, inaccessible or read-denied scratch.
58
58
  * @example claudeFilesystemSettings({ options: { filesystemRoot: '/site' } }, { platform: 'darwin', uid: 501 })
59
59
  */
60
60
  export declare function claudeFilesystemSettings(required: {
61
61
  options: RuntimeBuildOptions;
62
- }, { platform, homeDir, tempDir, uid, }?: {
62
+ }, { platform, homeDir, tempDir, uid, realpath, }?: {
63
63
  platform?: NodeJS.Platform;
64
64
  homeDir?: string;
65
65
  tempDir?: string;
66
66
  uid?: number | null | undefined;
67
+ realpath?: (path: string) => string;
67
68
  }): string;
68
69
  //# sourceMappingURL=claude-filesystem-policy.d.ts.map
@@ -124,13 +124,13 @@ export function claudeFilesystemRuntimePaths(required, _optional = {}) {
124
124
  * Personal/project layers are excluded separately. Preserve host hooks and secret denies.
125
125
  * Phase 1 leaves network policy unconfigured; the CLI's sandbox network defaults still apply.
126
126
  * https://code.claude.com/docs/en/permissions#working-directories
127
- * O(s + r) serialization for s host settings bytes and r runtime exception paths. Pure with
128
- * injectable host facts; errors reject malformed/file-based settings rather than dropping policy.
127
+ * O(s + r * t) for s host settings bytes, r scratch aliases and t deny roots, with injectable
128
+ * realpath lookups; errors reject malformed settings, inaccessible or read-denied scratch.
129
129
  * @example claudeFilesystemSettings({ options: { filesystemRoot: '/site' } }, { platform: 'darwin', uid: 501 })
130
130
  */
131
- export function claudeFilesystemSettings(required, { platform = process.platform, homeDir = homedir(), tempDir = tmpdir(), uid, } = {}) {
131
+ export function claudeFilesystemSettings(required, { platform = process.platform, homeDir = homedir(), tempDir = tmpdir(), uid, realpath = realpathSync, } = {}) {
132
132
  const { options } = required;
133
- const runtimeTempPaths = claudeRuntimeTempPaths({ options, platform }, { uid });
133
+ const runtimeTempPaths = claudeRuntimeTempPaths({ options, platform }, { uid, realpath });
134
134
  const settings = options.settings ? JSON.parse(options.settings) : {};
135
135
  if (!settings || typeof settings !== 'object' || Array.isArray(settings))
136
136
  throw new Error('Host settings must be a JSON object');
@@ -141,7 +141,7 @@ export function claudeFilesystemSettings(required, { platform = process.platform
141
141
  ...readOnlyEditDenies({ permissions, readOnlyDirs }, {}) },
142
142
  sandbox: { enabled: platform !== 'win32', failIfUnavailable: platform !== 'win32',
143
143
  allowUnsandboxedCommands: platform === 'win32', excludedCommands: [],
144
- filesystem: filesystemSandboxPaths({ options, homeDir, tempDir, runtimeTempPaths, readOnlyDirs }, {}),
144
+ filesystem: filesystemSandboxPaths({ options, homeDir, tempDir, runtimeTempPaths, readOnlyDirs }, { realpath }),
145
145
  },
146
146
  });
147
147
  }
@@ -164,9 +164,11 @@ function readOnlyEditDenies({ permissions, readOnlyDirs }, _optional = {}) {
164
164
  }
165
165
  /** Exact scratch subtree inside the executor's private per-run CLAUDE_CODE_TMPDIR.
166
166
  * Missing bases grant nothing; long bases are refused so Bash cannot fall back to shared scratch.
167
- * Pure, O(p) time/space for p path bytes; invalid Unix host facts throw before policy generation.
167
+ * Resolve the existing base, since Claude creates its UID child only after settings are built.
168
+ * O(p) time/space for p path bytes plus one injected lookup; inaccessible bases and invalid
169
+ * Unix host facts throw before policy generation. A not-yet-created base keeps its literal grant.
168
170
  */
169
- function claudeRuntimeTempPaths({ options, platform }, { uid } = {}) {
171
+ function claudeRuntimeTempPaths({ options, platform }, { uid, realpath = realpathSync } = {}) {
170
172
  if (platform === 'win32')
171
173
  return [];
172
174
  const base = options.filesystemRuntimeTempBase;
@@ -175,9 +177,17 @@ function claudeRuntimeTempPaths({ options, platform }, { uid } = {}) {
175
177
  if (!isAbsolute(base))
176
178
  throw new Error('Runtime temp base must be absolute');
177
179
  const runtimeTemp = resolve(base, `claude-${requireUnixUid({}, { uid })}`);
178
- if (Buffer.byteLength(runtimeTemp) > 44)
180
+ const paths = claudeTempAliases({ path: runtimeTemp, platform }, {});
181
+ try {
182
+ paths.push(resolve(realpath(base), basename(runtimeTemp)));
183
+ }
184
+ catch (error) {
185
+ if (error.code !== 'ENOENT')
186
+ throw error;
187
+ }
188
+ if (paths.some(path => Buffer.byteLength(path) > 44))
179
189
  throw new Error('Runtime temp path must not exceed 44 bytes');
180
- return claudeTempAliases({ path: runtimeTemp, platform }, {});
190
+ return [...new Set(paths)];
181
191
  }
182
192
  /** The host UID that names Claude's scratch subtree; fails closed rather than granting a guessed path. O(1). */
183
193
  function requireUnixUid(_required = {}, { uid = process.getuid?.() } = {}) {
@@ -195,12 +205,29 @@ function claudeTempAliases({ path, platform }, _optional = {}) {
195
205
  /** Build explicit filesystem exceptions; shared temp and the rest of home remain denied.
196
206
  * Claude's exact scratch subtree in the executor-created per-run directory is a read/write
197
207
  * infrastructure exception so Bash can track cwd. Shared and other runs' scratch stay denied.
198
- * Pure, O(r + t) for r runtime paths and t shared temp roots; no filesystem access.
208
+ * Read denies also restrict create/unlink; reject overlapping scratch rather than widen reads.
209
+ * O(r * t) containment checks for r scratch aliases and t deny roots, plus t realpath lookups.
199
210
  */
200
- function filesystemSandboxPaths({ options, homeDir, tempDir, runtimeTempPaths, readOnlyDirs }, _optional = {}) {
211
+ function filesystemSandboxPaths({ options, homeDir, tempDir, runtimeTempPaths, readOnlyDirs }, { realpath = realpathSync } = {}) {
201
212
  const privateTemp = options.filesystemTempDir ?? resolve(options.filesystemRoot, '.agent-runtime', 'tmp');
202
213
  const sharedTempRoots = [...new Set(['/tmp', '/private/tmp', tempDir, ...(options.filesystemSharedTempRoots ?? [])])];
203
- return { denyRead: [homeDir, ...sharedTempRoots],
214
+ const denyRead = [homeDir, ...sharedTempRoots];
215
+ if (runtimeTempPaths.length > 0) {
216
+ const deniedPaths = denyRead.flatMap(dir => {
217
+ try {
218
+ return [dir, realpath(dir)];
219
+ }
220
+ catch (error) {
221
+ if (error.code !== 'ENOENT')
222
+ throw error;
223
+ return [dir];
224
+ }
225
+ });
226
+ if (runtimeTempPaths.some(path => deniedPaths.some(dir => isSameOrInside({ path, dir }, {})))) {
227
+ throw new Error('Runtime temp path must not be inside a read-denied directory');
228
+ }
229
+ }
230
+ return { denyRead,
204
231
  // Owner 2026-10-23: git config is a read-only infrastructure exception, never all of home.
205
232
  allowRead: [options.filesystemRoot, privateTemp, resolve(homeDir, '.gitconfig'),
206
233
  resolve(homeDir, '.config/git/config'), ...(options.filesystemRuntimeReadPaths ?? []), ...runtimeTempPaths, ...readOnlyDirs],
@@ -39,6 +39,10 @@
39
39
  import { readDelegatedResult } from '@jini-ai/protocol';
40
40
  import { createRoleMarkerGuard } from './role-marker-guard.js';
41
41
  import { createClaudeSegmentUsage } from './claude-segment-usage.js';
42
+ /** The first argument that is a string (possibly empty), or `undefined` when none is. */
43
+ function firstString(...values) {
44
+ return values.find((value) => typeof value === 'string');
45
+ }
42
46
  function isRecord(value) {
43
47
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
44
48
  }
@@ -100,11 +104,7 @@ export function runtimeTaskIdFromCreate(input, counter) {
100
104
  return nextGeneratedRuntimeTaskId(counter);
101
105
  }
102
106
  export function applyTaskCreate(input, tasks, counter) {
103
- const content = typeof input.subject === 'string'
104
- ? input.subject
105
- : typeof input.description === 'string'
106
- ? input.description
107
- : '';
107
+ const content = firstString(input.subject, input.description) ?? '';
108
108
  if (!content)
109
109
  return false;
110
110
  const id = runtimeTaskIdFromCreate(input, counter);
@@ -123,11 +123,7 @@ export function applyTaskUpdate(input, tasks) {
123
123
  const existing = tasks.get(input.taskId);
124
124
  if (!existing)
125
125
  return false;
126
- const content = typeof input.subject === 'string'
127
- ? input.subject
128
- : typeof input.description === 'string'
129
- ? input.description
130
- : existing.content;
126
+ const content = firstString(input.subject, input.description) ?? existing.content;
131
127
  const activeForm = typeof input.activeForm === 'string' ? input.activeForm : existing.activeForm;
132
128
  tasks.set(input.taskId, {
133
129
  ...existing,
@@ -144,9 +140,7 @@ export function emitCanonicalTaskSnapshot(toolUseId, name, input, registry, onEv
144
140
  return true;
145
141
  const applied = name === 'TaskCreate'
146
142
  ? applyTaskCreate(input, registry.tasks, registry.counter)
147
- : name === 'TaskUpdate'
148
- ? applyTaskUpdate(input, registry.tasks)
149
- : false;
143
+ : name === 'TaskUpdate' && applyTaskUpdate(input, registry.tasks);
150
144
  if (!applied)
151
145
  return false;
152
146
  // Coverage-driven refactor (2026-07-18, no behavior change): the
@@ -227,10 +221,33 @@ function isHtmlArtifact(candidate) {
227
221
  return /\btype\s*=\s*["']text\/html["']/i.test(openTag);
228
222
  }
229
223
  function normalizeArtifactEchoContent(value) {
230
- return value
224
+ const normalized = value
231
225
  .replace(/^\uFEFF/, '')
232
- .replace(/\r\n?/g, '\n')
233
- .replace(/^(?:\s|\\r|\\n)+|(?:\s|\\r|\\n)+$/g, '');
226
+ .replace(/\r\n?/g, '\n');
227
+ return trimEchoPadding(normalized);
228
+ }
229
+ /** Length of the padding token (whitespace, or a literal `\r`/`\n` escape) starting at `index`; 0 if none. */
230
+ function echoPaddingAt(text, index) {
231
+ if (/\s/.test(text.charAt(index)))
232
+ return 1;
233
+ return text.startsWith('\\r', index) || text.startsWith('\\n', index) ? 2 : 0;
234
+ }
235
+ /** Length of the padding token ending just before `end`; 0 if none. */
236
+ function echoPaddingBefore(text, end) {
237
+ if (end > 0 && /\s/.test(text.charAt(end - 1)))
238
+ return 1;
239
+ return end > 1 && echoPaddingAt(text, end - 2) === 2 ? 2 : 0;
240
+ }
241
+ /** Strips leading and trailing runs of whitespace and literal `\r`/`\n` escapes. Same result as
242
+ * `text.replace(/^(?:\s|\\r|\\n)+|(?:\s|\\r|\\n)+$/g, '')`, without its quadratic backtracking. */
243
+ function trimEchoPadding(text) {
244
+ let start = 0;
245
+ for (let step = echoPaddingAt(text, start); step > 0; step = echoPaddingAt(text, start))
246
+ start += step;
247
+ let end = text.length;
248
+ for (let step = echoPaddingBefore(text, end); step > 0 && end - step >= start; step = echoPaddingBefore(text, end))
249
+ end -= step;
250
+ return text.slice(start, end);
234
251
  }
235
252
  export function isRedundantWrittenArtifact(candidate, ctx) {
236
253
  const gt = candidate.indexOf('>');
@@ -555,18 +572,21 @@ export function createClaudeStreamHandler({ onEvent }, options = {}) {
555
572
  while ((nl = buffer.indexOf('\n')) !== -1) {
556
573
  const line = buffer.slice(0, nl).trim();
557
574
  buffer = buffer.slice(nl + 1);
558
- if (!line)
559
- continue;
560
- let obj;
561
- try {
562
- obj = JSON.parse(line);
563
- }
564
- catch {
565
- onEvent({ type: 'raw', line });
566
- continue;
567
- }
568
- handleObject(obj);
575
+ if (line)
576
+ feedLine(line);
577
+ }
578
+ }
579
+ /** One complete, non-blank line: a JSON object is handled, anything else passes through raw. */
580
+ function feedLine(line) {
581
+ let obj;
582
+ try {
583
+ obj = JSON.parse(line);
584
+ }
585
+ catch {
586
+ onEvent({ type: 'raw', line });
587
+ return;
569
588
  }
589
+ handleObject(obj);
570
590
  }
571
591
  function flush() {
572
592
  const rem = buffer.trim();
@@ -666,13 +686,8 @@ export function createClaudeStreamHandler({ onEvent }, options = {}) {
666
686
  currentMessageStreamedThinking = false;
667
687
  }
668
688
  function handleResultMessage(obj) {
669
- // Explicit annotation: the `&&`/`||` chain's inferred type includes a phantom `false` (TS
670
- // widens each unresolved `&&` branch to its check's boolean), even though no runtime path
671
- // through this chain can ever produce the literal `false` — the last `|| null` guarantees a
672
- // string or null. Pinning the declared type to what's actually true, not casting past it.
673
- const stopReason = (typeof obj.stop_reason === 'string' && obj.stop_reason) ||
674
- (typeof obj.terminal_reason === 'string' && obj.terminal_reason) ||
675
- null;
689
+ // The first non-empty string of `stop_reason`, then `terminal_reason`; otherwise null.
690
+ const stopReason = [obj.stop_reason, obj.terminal_reason].find((reason) => typeof reason === 'string' && reason !== '') ?? null;
676
691
  // Claude Code 2.1.201 does not always emit a terminal
677
692
  // stream_event/message_delta. In that wire shape, the top-level result
678
693
  // is the only frame carrying `end_turn`. Surface it as a turn boundary
@@ -760,26 +775,29 @@ export function createClaudeStreamHandler({ onEvent }, options = {}) {
760
775
  applyInputJsonDelta(state, delta.partial_json, onEvent);
761
776
  }
762
777
  }
763
- function handleContentBlockStop(ev) {
764
- const key = blockKey(ev.index);
765
- const state = blocks.get(key);
766
- if (state && state.type === 'tool_use' && typeof state.id === 'string' && state.input.trim()) {
778
+ /** Emits a finished tool_use block from its streamed JSON text, else from its complete input value. */
779
+ function emitFinishedToolBlock(state, id) {
780
+ if (state.input.trim()) {
767
781
  try {
768
- emitToolUse(state.id, state.name, JSON.parse(state.input));
769
- streamedToolUseIds.add(state.id);
782
+ emitToolUse(id, state.name, JSON.parse(state.input));
783
+ streamedToolUseIds.add(id);
770
784
  }
771
785
  catch {
772
786
  // Fall through to the final assistant wrapper's input if the
773
787
  // streamed JSON is malformed or incomplete.
774
788
  }
789
+ return;
775
790
  }
776
- else if (state &&
777
- state.type === 'tool_use' &&
778
- typeof state.id === 'string' &&
779
- state.inputValue !== undefined) {
780
- emitToolUse(state.id, state.name, state.inputValue);
781
- streamedToolUseIds.add(state.id);
782
- }
791
+ if (state.inputValue === undefined)
792
+ return;
793
+ emitToolUse(id, state.name, state.inputValue);
794
+ streamedToolUseIds.add(id);
795
+ }
796
+ function handleContentBlockStop(ev) {
797
+ const key = blockKey(ev.index);
798
+ const state = blocks.get(key);
799
+ if (state?.type === 'tool_use' && typeof state.id === 'string')
800
+ emitFinishedToolBlock(state, state.id);
783
801
  blocks.delete(key);
784
802
  }
785
803
  // Usage is keyed per message; an id-less message is keyed by its epoch.
@@ -29,9 +29,11 @@ function addConcreteChoice({ choices, row }) {
29
29
  // Older cached inventories can attach a default-policy label to a resolved concrete ID.
30
30
  const label = row.id === 'default' || /^default\b/i.test(row.label) ? id : row.label;
31
31
  const existing = choices.get(id);
32
- if (!existing)
32
+ if (!existing) {
33
33
  choices.set(id, { ...row, id, label, identityKind: 'concrete' });
34
- else if (existing.label === id && label !== id)
34
+ return;
35
+ }
36
+ if (existing.label === id && label !== id)
35
37
  choices.set(id, { ...existing, label });
36
38
  }
37
39
  /** The resolved concrete default id when it is missing from `choices`, else undefined. */
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @file Copy an object without some of its keys — what `const { a: _a, ...rest } = source` does,
3
+ * without binding a throwaway name for every dropped key.
4
+ */
5
+ /** A shallow copy of `source`'s own enumerable properties, minus `keys`. @complexity O(own keys). */
6
+ export declare function omitKeys<T extends object, K extends keyof T>(source: T, keys: readonly K[]): Omit<T, K>;
7
+ //# sourceMappingURL=omit-keys.d.ts.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @file Copy an object without some of its keys — what `const { a: _a, ...rest } = source` does,
3
+ * without binding a throwaway name for every dropped key.
4
+ */
5
+ /** A shallow copy of `source`'s own enumerable properties, minus `keys`. @complexity O(own keys). */
6
+ export function omitKeys(source, keys) {
7
+ const copy = { ...source };
8
+ for (const key of keys)
9
+ delete copy[key];
10
+ return copy;
11
+ }
12
+ //# sourceMappingURL=omit-keys.js.map
@@ -3,7 +3,7 @@ export declare const aiderAgentDef: {
3
3
  name: string;
4
4
  bin: string;
5
5
  versionArgs: string[];
6
- fallbackModels: import("../types.js").RuntimeModelOption[];
6
+ fallbackModels: import("../model-contracts.js").RuntimeModelOption[];
7
7
  fallbackModelsAssertedAt: string;
8
8
  buildArgs: ({ prompt, imagePaths: _imagePaths }: {
9
9
  prompt: string;
@@ -3,7 +3,7 @@ export declare const ampAgentDef: {
3
3
  name: string;
4
4
  bin: string;
5
5
  versionArgs: string[];
6
- fallbackModels: import("../types.js").RuntimeModelOption[];
6
+ fallbackModels: import("../model-contracts.js").RuntimeModelOption[];
7
7
  supportsCustomModel: false;
8
8
  supportsConcreteModelSelection: false;
9
9
  buildArgs: ({ prompt: _prompt, imagePaths: _imagePaths }: {
package/dist/defs/amp.js CHANGED
@@ -10,12 +10,12 @@ import { DEFAULT_MODEL_OPTION } from './shared.js';
10
10
  // prints only its final assistant message (we read the structured
11
11
  // stream instead). The prompt is delivered via stdin (`promptViaStdin`),
12
12
  // matching the `echo "..." | amp -x` shape documented in `amp --help`.
13
- // This avoids the argv length caps that bite copilot/claude on a single
13
+ // This avoids the argv length caps that bite Claude on a single
14
14
  // `-p <body>` argv entry.
15
15
  // - `--stream-json` (requires `--execute`) switches stdout to the
16
16
  // Claude-Code-compatible JSONL stream the daemon already parses.
17
17
  // - `--dangerously-allow-all` is the non-interactive auto-approve flag
18
- // (Amp's equivalent of Copilot's `--allow-all-tools` / Codex's headless
18
+ // (Amp's equivalent of Codex's headless
19
19
  // auto-approve): without it the agent blocks waiting for human approval
20
20
  // on every tool call.
21
21
  //
package/dist/defs/amr.js CHANGED
@@ -61,22 +61,22 @@ function stripPrefix({ value, prefix }) {
61
61
  // interpolation the way it restricts a method call on a possibly-undefined
62
62
  // value).
63
63
  function normalizeKnownVelaVersionId(rawId) {
64
- const claude = /^claude[_-](haiku|opus|sonnet)[_-](\d+)[_-](\d+)(.*)$/i.exec(rawId);
64
+ const claude = /^claude[_-](haiku|opus|sonnet)[_-](\d+)[_-](\d+)(?!\d)(.*)$/i.exec(rawId);
65
65
  if (claude) {
66
66
  const [, family, major, minor, suffix = ''] = claude;
67
67
  return `claude-${family.toLowerCase()}-${major}.${minor}${suffix.replace(/_/g, '-')}`;
68
68
  }
69
- const gpt = /^gpt_(\d+)_(\d+)(.*)$/i.exec(rawId);
69
+ const gpt = /^gpt_(\d+)_(\d+)(?!\d)(.*)$/i.exec(rawId);
70
70
  if (gpt) {
71
71
  const [, major, minor, suffix = ''] = gpt;
72
72
  return `gpt-${major}.${minor}${suffix.replace(/_/g, '-')}`;
73
73
  }
74
- const gemini = /^gemini_(\d+)_(\d+)(.*)$/i.exec(rawId);
74
+ const gemini = /^gemini_(\d+)_(\d+)(?!\d)(.*)$/i.exec(rawId);
75
75
  if (gemini) {
76
76
  const [, major, minor, suffix = ''] = gemini;
77
77
  return `gemini-${major}.${minor}${suffix.replace(/_/g, '-')}`;
78
78
  }
79
- const minimax = /^minimax_m(\d+)_(\d+)(.*)$/i.exec(rawId);
79
+ const minimax = /^minimax_m(\d+)_(\d+)(?!\d)(.*)$/i.exec(rawId);
80
80
  if (minimax) {
81
81
  const [, major, minor, suffix = ''] = minimax;
82
82
  return `minimax-m${major}.${minor}${suffix.replace(/_/g, '-')}`;
@@ -234,11 +234,7 @@ export async function fetchVelaBillingSummary({ resolvedBin, env }) {
234
234
  // Use `balanceUsd` — the same field the console wallet page renders as the
235
235
  // headline "余额" — so the two surfaces always agree. Fall back to the total
236
236
  // available only if `balanceUsd` is missing.
237
- const balanceUsd = typeof data.balanceUsd === 'string'
238
- ? data.balanceUsd
239
- : typeof data.totalAvailableCreditsUsd === 'string'
240
- ? data.totalAvailableCreditsUsd
241
- : null;
237
+ const balanceUsd = [data.balanceUsd, data.totalAvailableCreditsUsd].find((value) => typeof value === 'string') ?? null;
242
238
  // `membershipTier` is omitted for free accounts. A SUCCESSFUL summary with no
243
239
  // tier therefore means "free" — normalize to the explicit sentinel so the UI
244
240
  // shows the plan and the Upgrade CTA for free users. "Unknown" (billing
@@ -0,0 +1,19 @@
1
+ /** agy's documented stream-json protocol, distinct from Gemini CLI's legacy wire format.
2
+ * https://antigravity.google/docs/cli/headless/#tool-calls-in-the-stream */
3
+ type Frame = Record<string, unknown>;
4
+ type Emit = (event: Frame) => void;
5
+ export interface AntigravityStreamState {
6
+ textEmitted: boolean;
7
+ toolUses: Set<string>;
8
+ toolResults: Set<string>;
9
+ }
10
+ /** Translate real tool receipts through the shared tool_use/tool_result audit channel.
11
+ * Pure except for the caller-owned parser state and event sink. O(1) per frame.
12
+ */
13
+ export declare function handleAntigravityEvent({ frame, emit, state }: {
14
+ frame: unknown;
15
+ emit: Emit;
16
+ state: AntigravityStreamState;
17
+ }, _options?: Record<string, never>): boolean;
18
+ export {};
19
+ //# sourceMappingURL=antigravity-event-stream.d.ts.map
@@ -0,0 +1,83 @@
1
+ function record(value) {
2
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
3
+ }
4
+ /** Native edits record paths, never patches or complete document contents. */
5
+ function nativeTool({ name, parameters }, _options = {}) {
6
+ if (name === 'run_command')
7
+ return { name: 'Bash', input: { command: parameters.CommandLine } };
8
+ if (name === 'write_to_file')
9
+ return { name: 'Write', input: { file_path: parameters.TargetFile } };
10
+ if (name === 'replace_file_content' || name === 'multi_replace_file_content') {
11
+ return { name: 'Edit', input: { file_path: parameters.TargetFile } };
12
+ }
13
+ return { name, input: parameters };
14
+ }
15
+ /** ACTIVE and DONE can describe the same call; a DONE-only receipt must also be audited. */
16
+ function toolStep({ step, emit, state }, _options = {}) {
17
+ if (typeof step.conversation_id !== 'string' || typeof step.step_index !== 'number')
18
+ return;
19
+ const info = record(step.tool_info);
20
+ const name = info.name ?? step.tool_name;
21
+ if (typeof name !== 'string')
22
+ return;
23
+ // A tool-name-only ACTIVE frame cannot supply the command/path yet; wait for its receipt.
24
+ if (info.parameters === undefined && step.state !== 'DONE')
25
+ return;
26
+ const id = `${step.conversation_id}:${step.step_index}`;
27
+ if (!state.toolUses.has(id)) {
28
+ state.toolUses.add(id);
29
+ emit({ type: 'tool_use', id, ...nativeTool({ name, parameters: record(info.parameters) }) });
30
+ }
31
+ toolResult({ step, info, id, emit, state });
32
+ }
33
+ function toolResult({ step, info, id, emit, state }, _options = {}) {
34
+ if (step.state !== 'DONE' || state.toolResults.has(id))
35
+ return;
36
+ state.toolResults.add(id);
37
+ const error = record(info.error);
38
+ const content = typeof error.message === 'string' ? error.message : info.output;
39
+ emit({ type: 'tool_result', toolUseId: id, content: typeof content === 'string' ? content : '',
40
+ isError: info.error !== undefined && info.error !== null });
41
+ }
42
+ function responseText({ text, emit, state }, _options = {}) {
43
+ if (typeof text !== 'string' || text.length === 0)
44
+ return;
45
+ state.textEmitted = true;
46
+ emit({ type: 'text_delta', delta: text });
47
+ }
48
+ /** The terminal response repeats streamed deltas. Errors must survive even on exit zero. */
49
+ function terminalResult({ result, emit, state }, _options = {}) {
50
+ if (!state.textEmitted)
51
+ responseText({ text: result.response, emit, state });
52
+ if (result.status !== 'SUCCESS') {
53
+ emit({ type: 'error', message: typeof result.error === 'string' ? result.error : 'Antigravity did not complete the turn.' });
54
+ }
55
+ if (result.usage !== undefined) {
56
+ const usage = record(result.usage);
57
+ emit({ type: 'usage', usage: { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens,
58
+ thought_tokens: usage.thinking_tokens, cached_read_tokens: usage.cache_read_tokens } });
59
+ }
60
+ }
61
+ /** Translate real tool receipts through the shared tool_use/tool_result audit channel.
62
+ * Pure except for the caller-owned parser state and event sink. O(1) per frame.
63
+ */
64
+ export function handleAntigravityEvent({ frame, emit, state }, _options = {}) {
65
+ const obj = record(frame);
66
+ if (obj.event === 'init') {
67
+ emit({ type: 'status', label: 'initializing', model: record(obj.init).model });
68
+ return true;
69
+ }
70
+ if (obj.event === 'result') {
71
+ terminalResult({ result: record(obj.result), emit, state });
72
+ return true;
73
+ }
74
+ if (obj.event !== 'step_update')
75
+ return false;
76
+ const step = record(obj.step_update);
77
+ if (step.step_type === 'agent_response')
78
+ responseText({ text: step.text_delta, emit, state });
79
+ if (step.step_type === 'tool')
80
+ toolStep({ step, emit, state });
81
+ return true;
82
+ }
83
+ //# sourceMappingURL=antigravity-event-stream.js.map