@jini-ai/agent-runtime 0.4.11 → 0.6.10

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 (111) hide show
  1. package/CHANGELOG.md +83 -1
  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.d.ts +2 -0
  21. package/dist/claude-stream.js +16 -5
  22. package/dist/copilot-stream.js +42 -50
  23. package/dist/defs/aider.js +3 -4
  24. package/dist/defs/amr.js +52 -61
  25. package/dist/defs/antigravity.d.ts +6 -5
  26. package/dist/defs/antigravity.js +48 -34
  27. package/dist/defs/auggie.d.ts +1 -1
  28. package/dist/defs/claude-compatible-args.d.ts +19 -0
  29. package/dist/defs/claude-compatible-args.js +42 -0
  30. package/dist/defs/claude.d.ts +7 -2
  31. package/dist/defs/claude.js +96 -85
  32. package/dist/defs/cline.d.ts +1 -1
  33. package/dist/defs/codebuddy.d.ts +1 -1
  34. package/dist/defs/codebuddy.js +29 -46
  35. package/dist/defs/codex.d.ts +15 -3
  36. package/dist/defs/codex.js +143 -108
  37. package/dist/defs/cursor-agent.d.ts +9 -7
  38. package/dist/defs/cursor-agent.js +53 -51
  39. package/dist/defs/devin.d.ts +1 -1
  40. package/dist/defs/goose.d.ts +1 -1
  41. package/dist/defs/hermes.d.ts +1 -1
  42. package/dist/defs/kilo.d.ts +1 -1
  43. package/dist/defs/kimi.d.ts +1 -1
  44. package/dist/defs/kiro.d.ts +1 -1
  45. package/dist/defs/opencode.d.ts +5 -4
  46. package/dist/defs/opencode.js +26 -32
  47. package/dist/defs/pi.d.ts +6 -5
  48. package/dist/defs/pi.js +24 -26
  49. package/dist/defs/qoder.d.ts +4 -3
  50. package/dist/defs/qoder.js +25 -25
  51. package/dist/defs/reasonix.d.ts +1 -1
  52. package/dist/defs/shared.d.ts +12 -3
  53. package/dist/defs/shared.js +19 -13
  54. package/dist/defs/trae-cli.d.ts +1 -1
  55. package/dist/defs/vibe.d.ts +1 -1
  56. package/dist/detection.d.ts +13 -20
  57. package/dist/detection.js +129 -111
  58. package/dist/env.js +56 -41
  59. package/dist/executables.js +103 -114
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.js +1 -0
  62. package/dist/json-event-stream.js +611 -527
  63. package/dist/launch.js +44 -37
  64. package/dist/model-discovery-adapters.d.ts +17 -0
  65. package/dist/model-discovery-adapters.js +223 -164
  66. package/dist/model-discovery-config.js +107 -87
  67. package/dist/model-discovery-sdk.d.ts +16 -2
  68. package/dist/model-discovery-sdk.js +4 -3
  69. package/dist/model-discovery-shared.d.ts +14 -0
  70. package/dist/model-discovery-shared.js +50 -15
  71. package/dist/model-discovery-types.d.ts +2 -0
  72. package/dist/model-discovery.js +219 -117
  73. package/dist/models.d.ts +14 -1
  74. package/dist/models.js +75 -19
  75. package/dist/native-tool-policy.d.ts +29 -0
  76. package/dist/native-tool-policy.js +36 -0
  77. package/dist/opencode-log.js +46 -30
  78. package/dist/paths.d.ts +2 -0
  79. package/dist/paths.js +3 -3
  80. package/dist/providers/aihubmix.js +13 -18
  81. package/dist/providers/anthropic-messages.d.ts +7 -0
  82. package/dist/providers/anthropic-messages.js +45 -21
  83. package/dist/providers/azure-chat.d.ts +5 -0
  84. package/dist/providers/azure-chat.js +13 -5
  85. package/dist/providers/connection-guard.d.ts +2 -45
  86. package/dist/providers/connection-guard.js +11 -10
  87. package/dist/providers/connection-test.d.ts +4 -0
  88. package/dist/providers/connection-test.js +127 -110
  89. package/dist/providers/elevenlabs.js +4 -1
  90. package/dist/providers/google-messages.d.ts +4 -0
  91. package/dist/providers/google-messages.js +48 -23
  92. package/dist/providers/google-schema.js +17 -23
  93. package/dist/providers/model-catalog.js +160 -145
  94. package/dist/providers/oauth-callback-server.js +37 -34
  95. package/dist/providers/oauth-credentials.js +23 -23
  96. package/dist/providers/oauth-tokens.js +16 -24
  97. package/dist/providers/openai-chat.d.ts +42 -0
  98. package/dist/providers/openai-chat.js +80 -10
  99. package/dist/providers/operation-schema.d.ts +25 -0
  100. package/dist/providers/operation-schema.js +226 -0
  101. package/dist/providers/response-text.d.ts +10 -0
  102. package/dist/providers/response-text.js +23 -0
  103. package/dist/providers/tool-turn-types.d.ts +56 -9
  104. package/dist/providers/tool-turn.d.ts +7 -0
  105. package/dist/providers/tool-turn.js +120 -32
  106. package/dist/qoder-stream.js +93 -80
  107. package/dist/registry.d.ts +45 -0
  108. package/dist/registry.js +39 -0
  109. package/dist/runtime-state.d.ts +1 -1
  110. package/dist/types.d.ts +43 -1
  111. package/package.json +19 -14
@@ -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,
@@ -92,23 +92,27 @@ export function acpUpdateDiagnosticText(value, depth = 0) {
92
92
  return value.flatMap((item) => acpUpdateDiagnosticText(item, depth + 1));
93
93
  }
94
94
  const obj = asObject(value);
95
- if (!obj)
96
- return [];
95
+ return obj ? objectDiagnosticText({ obj, depth }) : [];
96
+ }
97
+ /** Keys `acpUpdateDiagnosticText` descends into on an object, in order. */
98
+ const DIAGNOSTIC_TEXT_KEYS = [
99
+ 'type',
100
+ 'status',
101
+ 'code',
102
+ 'message',
103
+ 'detail',
104
+ 'details',
105
+ 'error',
106
+ 'recovery',
107
+ 'pauseReason',
108
+ 'content',
109
+ 'text',
110
+ 'rawInput',
111
+ ];
112
+ /** Collects diagnostic text from each present `DIAGNOSTIC_TEXT_KEYS` entry of `obj`. */
113
+ function objectDiagnosticText({ obj, depth }) {
97
114
  const parts = [];
98
- for (const key of [
99
- 'type',
100
- 'status',
101
- 'code',
102
- 'message',
103
- 'detail',
104
- 'details',
105
- 'error',
106
- 'recovery',
107
- 'pauseReason',
108
- 'content',
109
- 'text',
110
- 'rawInput',
111
- ]) {
115
+ for (const key of DIAGNOSTIC_TEXT_KEYS) {
112
116
  if (key in obj) {
113
117
  parts.push(...acpUpdateDiagnosticText(obj[key], depth + 1));
114
118
  }
@@ -133,18 +137,7 @@ export function promotedAmrRetryStatusPayload(update, classifier = noopAccountFa
133
137
  const failure = classifier.classify({ text: diagnosticText });
134
138
  if (!failure)
135
139
  return null;
136
- return {
137
- message: failure.message,
138
- error: {
139
- code: failure.code,
140
- message: failure.message,
141
- retryable: false,
142
- details: {
143
- ...accountFailureDetails(failure),
144
- promoted_by: 'agent_runtime_acp_retry_status',
145
- },
146
- },
147
- };
140
+ return promotedFailurePayload({ failure, promotedBy: 'agent_runtime_acp_retry_status' });
148
141
  }
149
142
  /**
150
143
  * Scans a rolling tail of AMR stderr output for known retry/session-failure
@@ -165,6 +158,11 @@ export function promotedAmrStderrPayload(chunk, classifier = noopAccountFailureC
165
158
  const failure = classifier.classify({ text: chunk });
166
159
  if (!failure)
167
160
  return null;
161
+ return promotedFailurePayload({ failure, promotedBy: 'agent_runtime_acp_stderr_retry_status' });
162
+ }
163
+ /** Shapes a classified account failure into the non-retryable error payload
164
+ * both AMR promoters emit, tagged with which promoter produced it. */
165
+ function promotedFailurePayload({ failure, promotedBy }) {
168
166
  return {
169
167
  message: failure.message,
170
168
  error: {
@@ -173,7 +171,7 @@ export function promotedAmrStderrPayload(chunk, classifier = noopAccountFailureC
173
171
  retryable: false,
174
172
  details: {
175
173
  ...accountFailureDetails(failure),
176
- promoted_by: 'agent_runtime_acp_stderr_retry_status',
174
+ promoted_by: promotedBy,
177
175
  },
178
176
  },
179
177
  };
@@ -239,23 +237,39 @@ export function isAcpArtifactWriteUpdate(update, writeToolCallIds) {
239
237
  * @returns An absolute or relative file path string, or `null` when absent.
240
238
  */
241
239
  export function acpArtifactWritePath(update) {
240
+ return entryArrayPath(update) ?? rawInputPath(update) ?? titlePath(update);
241
+ }
242
+ /** Returns the trimmed string when `value` is a non-blank string, else `null`. */
243
+ function trimmedNonEmpty(value) {
244
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
245
+ }
246
+ /** Source 1 of `acpArtifactWritePath`. */
247
+ function entryArrayPath(update) {
242
248
  // 1. ACP `locations: [{ path }]` and `content: [{ path }]` (diff entries).
243
249
  for (const field of [update.locations, update.content]) {
244
250
  if (!Array.isArray(field))
245
251
  continue;
246
252
  for (const entry of field) {
247
- const path = asObject(entry)?.path;
248
- if (typeof path === 'string' && path.trim())
249
- return path.trim();
253
+ const path = trimmedNonEmpty(asObject(entry)?.path);
254
+ if (path)
255
+ return path;
250
256
  }
251
257
  }
258
+ return null;
259
+ }
260
+ /** Source 2 of `acpArtifactWritePath`. */
261
+ function rawInputPath(update) {
252
262
  // 2. Tool input echoed by some agents as `rawInput.{path,file_path,filename}`.
253
263
  const rawInput = asObject(update.rawInput);
254
264
  for (const key of ['path', 'file_path', 'filename']) {
255
- const value = rawInput?.[key];
256
- if (typeof value === 'string' && value.trim())
257
- return value.trim();
265
+ const value = trimmedNonEmpty(rawInput?.[key]);
266
+ if (value)
267
+ return value;
258
268
  }
269
+ return null;
270
+ }
271
+ /** Source 3 of `acpArtifactWritePath`. */
272
+ function titlePath(update) {
259
273
  // 3. A filename token embedded in the human title, e.g. "Write index.html".
260
274
  // Keeping the real extension lets `isArtifactPath` correctly EXCLUDE
261
275
  // non-artifact writes (e.g. "edit config.json"), matching the claude path.
@@ -173,8 +173,10 @@ export function tryReadImagePayload(imgPath, uploadRoot, totalBytesSoFar) {
173
173
  size: stat.size,
174
174
  };
175
175
  }
176
- catch (_err) {
176
+ catch {
177
177
  // Skip unreadable images rather than failing the entire run.
178
+ // Filesystem errors can contain private paths; report only the fixed diagnostic.
179
+ console.warn('[pi-rpc] Image attachment could not be read; skipping it.');
178
180
  return null;
179
181
  }
180
182
  }
@@ -1,3 +1,4 @@
1
+ import { listProviderModels } from './providers/model-catalog.js';
1
2
  import type { RuntimeEnv, RuntimeModelOption } from './types.js';
2
3
  /** Test-only reset — this module-scope cache would otherwise leak a stubbed `fetch`'s result across
3
4
  * test cases. */
@@ -33,13 +34,20 @@ export declare function mergeLiveModels(fallback: readonly RuntimeModelOption[],
33
34
  * Returns the Claude model list with the account's live catalog merged in, or `null` when there is
34
35
  * nothing to merge.
35
36
  *
36
- * @param env - The composed environment for the `claude` agent.
37
- * @param fallbackModels - The def's static list; always fully present in a non-null result.
38
- * @param now - Injectable clock for TTL tests.
37
+ * @param required.env - The composed environment for the `claude` agent.
38
+ * @param required.fallbackModels - The def's static list; always fully present in a non-null result.
39
+ * @param optional.now - Injectable clock for TTL tests.
40
+ * @param optional.listModels - The provider catalog port (`listProviderModels` by default).
39
41
  * @returns The merged list, or `null` for every no-credential / failed-call outcome — which the
40
42
  * caller treats as "keep the static list", never as an error.
41
43
  * @complexity O(1) plus, at most, one cached outbound HTTPS call bounded by
42
44
  * {@link LIVE_MODEL_TIMEOUT_MS}.
43
45
  */
44
- export declare function loadAnthropicLiveModels(env: RuntimeEnv, _fallbackModels: readonly RuntimeModelOption[], now?: () => number): Promise<RuntimeModelOption[] | null>;
46
+ export declare function loadAnthropicLiveModels({ env }: {
47
+ readonly env: RuntimeEnv;
48
+ readonly fallbackModels: readonly RuntimeModelOption[];
49
+ }, { now, listModels }?: {
50
+ readonly now?: () => number;
51
+ readonly listModels?: typeof listProviderModels;
52
+ }): Promise<RuntimeModelOption[] | null>;
45
53
  //# sourceMappingURL=anthropic-live-models.d.ts.map
Binary file
package/dist/auth.js CHANGED
@@ -20,10 +20,10 @@
20
20
  */
21
21
  import { execAgentFile } from './invocation.js';
22
22
  const DEFAULT_HOST_NAME = 'the host application';
23
- function cursorAuthGuidanceText(hostName) {
23
+ export function cursorAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
24
24
  return `Cursor Agent is not authenticated. Run \`cursor-agent login\`, then \`cursor-agent status\`, and retry. For automation, ensure CURSOR_API_KEY is set in ${hostName}'s process environment.`;
25
25
  }
26
- function deepseekAuthGuidanceText(hostName) {
26
+ export function deepseekAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
27
27
  return `DeepSeek TUI is installed but is not authenticated. Add or verify your API key in \`~/.deepseek/config.toml\` as \`api_key = "..."\`, or expose DEEPSEEK_API_KEY to ${hostName}'s daemon process, then retry. If ${hostName} is launched outside an interactive shell, shell rc files such as ~/.zshrc may not be loaded.`;
28
28
  }
29
29
  // agy's print mode (`-p`) detects a missing OAuth token, prints the
@@ -36,7 +36,7 @@ function deepseekAuthGuidanceText(hostName) {
36
36
  // browser, completes OAuth, and writes the credentials to the system
37
37
  // keyring — both `-p` and TUI invocations read from there afterward, so
38
38
  // the chat run can succeed on retry.
39
- function antigravityAuthGuidanceText(hostName) {
39
+ export function antigravityAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
40
40
  return `Antigravity needs to sign in. The agy CLI's keyring entry has expired or been cleared, and \`-p\` print mode cannot complete OAuth on its own (it has no field to paste the auth code into).\n\nFix: open a terminal and run \`agy\` once — it will open Google sign-in in your browser, accept the redirect, and store the token in your system keyring. After you finish, return here and retry this chat. You only need to do this once; the keyring entry persists across both terminal and ${hostName} runs.`;
41
41
  }
42
42
  // agy's account-level quota is per-model (consumer accounts get a
@@ -46,32 +46,14 @@ function antigravityAuthGuidanceText(hostName) {
46
46
  // your administrator to enable overages. Resets in <H>h<M>m<S>s.
47
47
  // to the `--log-file`. Print mode emits nothing on stdout/stderr, so
48
48
  // without log inspection the failure misreads as missing-OAuth.
49
- function antigravityQuotaGuidanceText() {
50
- return 'Antigravity returned "RESOURCE_EXHAUSTED: Individual quota reached" for the current model. Each Antigravity model (Gemini 3 Pro / Flash, Claude 4.6, GPT-OSS) has its own quota.\n\nFix: open `agy` in a terminal and use its Switch Model picker (the menu at the bottom of the TUI) to pick a model with available quota, then retry here. Quotas reset automatically on Antigravity\'s schedule.';
51
- }
52
- function reasonixAuthGuidanceText(hostName) {
53
- return `DeepSeek Reasonix is installed but is not authenticated. Add your API key in \`~/.reasonix/config.json\` under \`apiKey\`, or expose DEEPSEEK_API_KEY to ${hostName}'s daemon process, then retry. If ${hostName} is launched outside an interactive shell, shell rc files such as ~/.zshrc may not be loaded.`;
54
- }
55
- function claudeAuthGuidanceText(hostName) {
56
- return `Claude Code is installed but is not authenticated. Run \`claude auth login\` or open \`claude\` and complete login in a terminal, then rescan. If ${hostName} was launched outside an interactive shell, your shell rc files (e.g. ~/.zshrc) may not be loaded into its environment.`;
57
- }
58
- export function cursorAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
59
- return cursorAuthGuidanceText(hostName);
60
- }
61
- export function deepseekAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
62
- return deepseekAuthGuidanceText(hostName);
63
- }
64
- export function antigravityAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
65
- return antigravityAuthGuidanceText(hostName);
66
- }
67
49
  export function antigravityQuotaGuidance() {
68
- return antigravityQuotaGuidanceText();
50
+ return 'Antigravity returned "RESOURCE_EXHAUSTED: Individual quota reached" for the current model. Each Antigravity model (Gemini 3 Pro / Flash, Claude 4.6, GPT-OSS) has its own quota.\n\nFix: open `agy` in a terminal and use its Switch Model picker (the menu at the bottom of the TUI) to pick a model with available quota, then retry here. Quotas reset automatically on Antigravity\'s schedule.';
69
51
  }
70
52
  export function reasonixAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
71
- return reasonixAuthGuidanceText(hostName);
53
+ return `DeepSeek Reasonix is installed but is not authenticated. Add your API key in \`~/.reasonix/config.json\` under \`apiKey\`, or expose DEEPSEEK_API_KEY to ${hostName}'s daemon process, then retry. If ${hostName} is launched outside an interactive shell, shell rc files such as ~/.zshrc may not be loaded.`;
72
54
  }
73
55
  export function claudeAuthGuidance({}, { hostName = DEFAULT_HOST_NAME } = {}) {
74
- return claudeAuthGuidanceText(hostName);
56
+ return `Claude Code is installed but is not authenticated. Run \`claude auth login\` or open \`claude\` and complete login in a terminal, then rescan. If ${hostName} was launched outside an interactive shell, your shell rc files (e.g. ~/.zshrc) may not be loaded into its environment.`;
75
57
  }
76
58
  export function isCursorAuthFailureText({ text }) {
77
59
  const value = String(text || '');
@@ -121,10 +103,11 @@ export function isReasonixAuthFailureText({ text }) {
121
103
  (/DEEPSEEK_API_KEY/i.test(value) &&
122
104
  /auth|missing|not set|required|unauthorized|invalid/i.test(value)));
123
105
  }
124
- export function isClaudeAuthFailureText({ text }) {
125
- const value = String(text || '');
126
- if (!value.trim())
127
- return false;
106
+ // Structured verdict from `claude auth status` JSON: a boolean when either key
107
+ // is a boolean (`true` wins), undefined when the text is not JSON or carries
108
+ // neither key. Property access on a JSON `null` throws inside the `try`, which
109
+ // deliberately lands in the same text-matching fallback as invalid JSON.
110
+ function claudeJsonAuthFailure({ value }) {
128
111
  try {
129
112
  const parsed = JSON.parse(value);
130
113
  if (parsed.authenticated === true || parsed.loggedIn === true)
@@ -135,6 +118,9 @@ export function isClaudeAuthFailureText({ text }) {
135
118
  catch {
136
119
  // Fall through to text matching below.
137
120
  }
121
+ return undefined;
122
+ }
123
+ function claudeTextAuthFailure({ value }) {
138
124
  if (/"authenticated"\s*:\s*true/i.test(value) || /"loggedIn"\s*:\s*true/i.test(value)) {
139
125
  return false;
140
126
  }
@@ -145,33 +131,27 @@ export function isClaudeAuthFailureText({ text }) {
145
131
  /authentication required/i.test(value) ||
146
132
  /please (?:sign|log)[ _-]?in/i.test(value));
147
133
  }
134
+ export function isClaudeAuthFailureText({ text }) {
135
+ const value = String(text || '');
136
+ if (!value.trim())
137
+ return false;
138
+ return claudeJsonAuthFailure({ value }) ?? claudeTextAuthFailure({ value });
139
+ }
140
+ // Agents that ship a bespoke auth-failure classifier + tailored sign-in hint.
141
+ // Map (not an object literal) so an arbitrary agent id can never hit a
142
+ // prototype key.
143
+ const TAILORED_AUTH_CLASSIFIERS = new Map([
144
+ ['claude', { isFailure: isClaudeAuthFailureText, guidance: ({ hostName }) => claudeAuthGuidance({}, { hostName }) }],
145
+ ['cursor-agent', { isFailure: isCursorAuthFailureText, guidance: ({ hostName }) => cursorAuthGuidance({}, { hostName }) }],
146
+ ['deepseek', { isFailure: isDeepSeekAuthFailureText, guidance: ({ hostName }) => deepseekAuthGuidance({}, { hostName }) }],
147
+ ['antigravity', { isFailure: isAntigravityAuthFailureText, guidance: ({ hostName }) => antigravityAuthGuidance({}, { hostName }) }],
148
+ ['reasonix', { isFailure: isReasonixAuthFailureText, guidance: ({ hostName }) => reasonixAuthGuidance({}, { hostName }) }],
149
+ ]);
148
150
  export function classifyAgentAuthFailure({ agentId, text }, { hostName = DEFAULT_HOST_NAME } = {}) {
149
- if (agentId === 'claude') {
150
- if (!isClaudeAuthFailureText({ text: text }))
151
- return null;
152
- return { status: 'missing', message: claudeAuthGuidance({}, { hostName: hostName }) };
153
- }
154
- if (agentId === 'cursor-agent') {
155
- if (!isCursorAuthFailureText({ text: text }))
156
- return null;
157
- return { status: 'missing', message: cursorAuthGuidance({}, { hostName: hostName }) };
158
- }
159
- if (agentId === 'deepseek') {
160
- if (!isDeepSeekAuthFailureText({ text: text }))
161
- return null;
162
- return { status: 'missing', message: deepseekAuthGuidance({}, { hostName: hostName }) };
163
- }
164
- if (agentId === 'antigravity') {
165
- if (!isAntigravityAuthFailureText({ text: text }))
166
- return null;
167
- return { status: 'missing', message: antigravityAuthGuidance({}, { hostName: hostName }) };
168
- }
169
- if (agentId === 'reasonix') {
170
- if (!isReasonixAuthFailureText({ text: text }))
171
- return null;
172
- return { status: 'missing', message: reasonixAuthGuidance({}, { hostName: hostName }) };
173
- }
174
- return null;
151
+ const classifier = TAILORED_AUTH_CLASSIFIERS.get(agentId);
152
+ if (!classifier?.isFailure({ text: text }))
153
+ return null;
154
+ return { status: 'missing', message: classifier.guidance({ hostName: hostName }) };
175
155
  }
176
156
  // A bare HTTP status number (`500`, `429`, …) is too noisy to trust on its own
177
157
  // — agent stderr is full of unrelated numbers (`line 500`, `read 502 bytes`,
@@ -216,7 +196,7 @@ export function classifyAgentServiceFailure({ text }) {
216
196
  const PROBE_TAIL_BYTES = 400;
217
197
  // Both real call sites (`withProbeTails`, immediately below) already hold a
218
198
  // `string` — `probeAgentAuthStatus` normalizes `stdout`/`stderr` to `''` via
219
- // `typeof stdout === 'string' ? stdout : ''` before either ever reaches here
199
+ // `stringOrEmpty` before either ever reaches here
220
200
  // — so a `value: unknown` parameter plus a runtime `typeof` guard was dead
221
201
  // code for every real caller. Narrowed to `string` to remove the
222
202
  // unreachable branch instead of padding a test around it.
@@ -245,12 +225,13 @@ function genericAuthGuidance(agentName, hostName) {
245
225
  return `${agentName} appears to be installed but is not authenticated. Sign in with the CLI in a terminal, then rescan. If ${hostName} was launched outside an interactive shell, your shell rc files (e.g. ~/.zshrc) may not be loaded into its environment.`;
246
226
  }
247
227
  // Agents that ship a bespoke auth-failure classifier + tailored sign-in hint
248
- // via `classifyAgentAuthFailure`. For these, a null result is authoritative
228
+ // via `classifyAgentAuthFailure` (`TAILORED_AUTH_CLASSIFIERS`). For these, a null result is authoritative
249
229
  // ("authenticated"); we must NOT second-guess it with the broad generic
250
230
  // regex (e.g. cursor-agent's healthy `status` output mentions "login" in
251
231
  // ways the generic matcher would misread). The generic classifier is only a
252
232
  // fallback for adapters with no tailored classifier of their own.
253
- const TAILORED_AUTH_AGENTS = new Set(['claude', 'cursor-agent', 'deepseek', 'antigravity', 'reasonix']);
233
+ // (The tailored set is `TAILORED_AUTH_CLASSIFIERS`' keys, so the two lists
234
+ // can no longer drift apart.)
254
235
  function hasNonEmptyEnv(env, keys) {
255
236
  return keys.some((key) => {
256
237
  const value = env[key];
@@ -273,7 +254,7 @@ function hasProbeSatisfyingApiKey(def, env) {
273
254
  // HTTP/text classifier so it still gets a usable signal without bespoke
274
255
  // regexes.
275
256
  function classifyProbedAuthFailure(def, text, hostName) {
276
- if (TAILORED_AUTH_AGENTS.has(def.id)) {
257
+ if (TAILORED_AUTH_CLASSIFIERS.has(def.id)) {
277
258
  return classifyAgentAuthFailure({ agentId: def.id, text: text }, { hostName: hostName });
278
259
  }
279
260
  if (classifyAgentServiceFailure({ text: text }) === 'AGENT_AUTH_REQUIRED') {
@@ -281,6 +262,49 @@ function classifyProbedAuthFailure(def, text, hostName) {
281
262
  }
282
263
  return null;
283
264
  }
265
+ function stringOrEmpty(value) {
266
+ return typeof value === 'string' ? value : '';
267
+ }
268
+ // Classify the probe's combined output and, on a missing-auth result, attach
269
+ // the exit context and the stdout/stderr tails.
270
+ function probedFailureWithContext({ def, output, stdoutText, stderrText, exitCode, signal }, { hostName }) {
271
+ const failure = classifyProbedAuthFailure(def, output, hostName);
272
+ if (!failure)
273
+ return null;
274
+ return withProbeTails({ ...failure, exitCode, signal }, stdoutText, stderrText);
275
+ }
276
+ async function runAuthProbe({ def, probe, resolvedBin, env }, { hostName }) {
277
+ const { stdout, stderr } = await execAgentFile({ command: resolvedBin, args: probe.args }, { options: {
278
+ env: env,
279
+ timeout: probe.timeoutMs ?? 5000,
280
+ maxBuffer: 1024 * 1024,
281
+ } });
282
+ const stdoutText = stringOrEmpty(stdout);
283
+ const stderrText = stringOrEmpty(stderr);
284
+ const output = `${stdoutText}\n${stderrText}`;
285
+ return (probedFailureWithContext({ def, output, stdoutText, stderrText, exitCode: 0, signal: null }, { hostName }) ?? { status: 'ok' });
286
+ }
287
+ function probeRejectionResult({ def, probe, error }, { hostName }) {
288
+ const err = error;
289
+ const stdoutText = stringOrEmpty(err.stdout);
290
+ const stderrText = stringOrEmpty(err.stderr);
291
+ const output = [err.message, stdoutText, stderrText].join('\n');
292
+ // util.promisify(execFile) attaches `code` and `signal` to the
293
+ // rejection error. `code` may be a number (real non-zero exit) or a
294
+ // Node ErrnoException string ("ENOENT"); only the numeric form is
295
+ // meaningful as an exit code.
296
+ const exitCode = typeof err.code === 'number' ? err.code : null;
297
+ const signal = typeof err.signal === 'string' ? err.signal : null;
298
+ const failure = probedFailureWithContext({ def, output, stdoutText, stderrText, exitCode, signal }, { hostName });
299
+ if (failure)
300
+ return failure;
301
+ return withProbeTails({
302
+ status: 'unknown',
303
+ message: `${def.name || def.id} authentication status could not be verified with \`${def.id} ${probe.args.join(' ')}\`.`,
304
+ exitCode,
305
+ signal,
306
+ }, stdoutText, stderrText);
307
+ }
284
308
  // Run an adapter's declared authentication probe (a cheap, side-effect-free
285
309
  // status/whoami command) and classify the result. Returns null when the
286
310
  // adapter declares no `authProbe` — those agents are never actively probed;
@@ -292,41 +316,10 @@ export async function probeAgentAuthStatus({ def, resolvedBin, env }, { hostName
292
316
  if (hasProbeSatisfyingApiKey(def, env))
293
317
  return { status: 'ok' };
294
318
  try {
295
- const { stdout, stderr } = await execAgentFile({ command: resolvedBin, args: probe.args }, { options: {
296
- env: env,
297
- timeout: probe.timeoutMs ?? 5000,
298
- maxBuffer: 1024 * 1024,
299
- } });
300
- const stdoutText = typeof stdout === 'string' ? stdout : '';
301
- const stderrText = typeof stderr === 'string' ? stderr : '';
302
- const output = `${stdoutText}\n${stderrText}`;
303
- const failure = classifyProbedAuthFailure(def, output, hostName);
304
- if (failure) {
305
- return withProbeTails({ ...failure, exitCode: 0, signal: null }, stdoutText, stderrText);
306
- }
307
- return { status: 'ok' };
319
+ return await runAuthProbe({ def, probe, resolvedBin, env }, { hostName });
308
320
  }
309
321
  catch (error) {
310
- const err = error;
311
- const stdoutText = typeof err.stdout === 'string' ? err.stdout : '';
312
- const stderrText = typeof err.stderr === 'string' ? err.stderr : '';
313
- const output = [err.message, stdoutText, stderrText].join('\n');
314
- // util.promisify(execFile) attaches `code` and `signal` to the
315
- // rejection error. `code` may be a number (real non-zero exit) or a
316
- // Node ErrnoException string ("ENOENT"); only the numeric form is
317
- // meaningful as an exit code.
318
- const numericExit = typeof err.code === 'number' ? err.code : null;
319
- const childSignal = typeof err.signal === 'string' ? err.signal : null;
320
- const failure = classifyProbedAuthFailure(def, output, hostName);
321
- if (failure) {
322
- return withProbeTails({ ...failure, exitCode: numericExit, signal: childSignal }, stdoutText, stderrText);
323
- }
324
- return withProbeTails({
325
- status: 'unknown',
326
- message: `${def.name || def.id} authentication status could not be verified with \`${def.id} ${probe.args.join(' ')}\`.`,
327
- exitCode: numericExit,
328
- signal: childSignal,
329
- }, stdoutText, stderrText);
322
+ return probeRejectionResult({ def, probe, error }, { hostName });
330
323
  }
331
324
  }
332
325
  //# sourceMappingURL=auth.js.map
@@ -49,6 +49,12 @@ export interface ClaudeCodeModelIo {
49
49
  }
50
50
  /** Test-only: install fake I/O (or `null` to restore the real one) and clear the process cache. */
51
51
  export declare function setClaudeCodeModelIoForTesting(io: ClaudeCodeModelIo | null): void;
52
+ /** Options for the object call form of {@link loadClaudeCodeModels}. */
53
+ export interface ClaudeCodeModelsOptions {
54
+ state?: AgentRuntimeState;
55
+ io?: ClaudeCodeModelIo;
56
+ now?: () => number;
57
+ }
52
58
  /**
53
59
  * Returns the `claude` model list from the CLI's own picker catalog, or `null` when discovery fails. Needs no API key.
54
60
  *
@@ -59,11 +65,6 @@ export declare function setClaudeCodeModelIoForTesting(io: ClaudeCodeModelIo | n
59
65
  * @complexity O(f + l) plus, at most once per {@link CLAUDE_CODE_MODEL_CACHE_TTL_MS} per cache key,
60
66
  * one CLI spawn bounded by {@link CLAUDE_CODE_INIT_TIMEOUT_MS} and one file read.
61
67
  */
62
- export interface ClaudeCodeModelsOptions {
63
- state?: AgentRuntimeState;
64
- io?: ClaudeCodeModelIo;
65
- now?: () => number;
66
- }
67
68
  export declare function loadClaudeCodeModels(required: {
68
69
  bin: string;
69
70
  env: RuntimeEnv;