@causyne/agent 1.20.120 → 1.20.121

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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
@@ -31,11 +31,18 @@ export interface CodexCompactedState {
31
31
  readonly toolsSummary: string;
32
32
  }
33
33
 
34
+ export interface PlanStepAnchor {
35
+ readonly step?: string | undefined;
36
+ readonly title?: string | undefined;
37
+ readonly status?: string | undefined;
38
+ }
39
+
34
40
  export interface CompactionOptions {
35
41
  readonly keepRecentTurns?: number;
36
42
  readonly taskId?: string;
37
43
  readonly originalPrompt?: string;
38
44
  readonly maxCharPool?: number;
45
+ readonly activePlan?: readonly PlanStepAnchor[] | undefined;
39
46
  }
40
47
 
41
48
  export interface CompactionResult {
@@ -49,13 +56,58 @@ export interface CompactionResult {
49
56
  readonly reason?: string;
50
57
  }
51
58
 
59
+ /**
60
+ * Adjusts a candidate compaction split index so compaction NEVER severs a
61
+ * `role: 'tool'` result from its preceding `role: 'assistant'` `tool_calls`
62
+ * message (which would cause HTTP 400 invalid tool-turn errors on OpenAI,
63
+ * Anthropic, and Gemini).
64
+ *
65
+ * Returns a safe `splitIndex` in `[1, messages.length - 2]`, or `-1` if no
66
+ * safe split exists.
67
+ */
68
+ export function findSafeCompactionSplitIndex(
69
+ messages: ReadonlyArray<{ role?: string; tool_calls?: unknown }>,
70
+ targetSplitIndex: number
71
+ ): number {
72
+ const maxSplit = messages.length - 2;
73
+ if (maxSplit < 1) return -1;
74
+ let split = Math.min(Math.max(1, targetSplitIndex), maxSplit);
75
+
76
+ // If the first retained message (`split + 1`) is a `tool` result, walk back
77
+ // until the owning `assistant` message with `tool_calls` is also retained.
78
+ if (messages[split + 1]?.role === 'tool') {
79
+ let back = split;
80
+ while (back >= 1 && messages[back + 1]?.role === 'tool') {
81
+ back -= 1;
82
+ }
83
+ // Also retain the owning `assistant` message if `back + 1` was still `tool`
84
+ if (back >= 1 && messages[back]?.role === 'assistant' && Array.isArray(messages[back]?.tool_calls)) {
85
+ back -= 1;
86
+ }
87
+ if (back >= 1 && messages[back + 1]?.role !== 'tool') {
88
+ return back;
89
+ }
90
+ // Otherwise walk forward past the contiguous `tool` results while keeping at least 1 recent message
91
+ let forward = split;
92
+ while (forward < maxSplit && messages[forward + 1]?.role === 'tool') {
93
+ forward += 1;
94
+ }
95
+ if (forward <= maxSplit && messages[forward + 1]?.role !== 'tool') {
96
+ return forward;
97
+ }
98
+ return -1;
99
+ }
100
+
101
+ return split;
102
+ }
103
+
52
104
  /**
53
105
  * Extracts a high-fidelity, structured state summary from dropped message history.
54
- * Mirrors the state preservation architecture of OpenAI Codex and Claude Code.
55
106
  */
56
107
  export function buildCodexStyleSummary(
57
108
  droppedMessages: readonly ToolObservation[],
58
- originalPrompt?: string
109
+ originalPrompt?: string,
110
+ extra?: { activePlan?: readonly PlanStepAnchor[] | undefined }
59
111
  ): string {
60
112
  const createdFiles = new Set<string>();
61
113
  const modifiedFiles = new Set<string>();
@@ -77,11 +129,11 @@ export function buildCodexStyleSummary(
77
129
  if (typeof rawArgs === 'string') {
78
130
  const parsed = JSON.parse(rawArgs);
79
131
  if (parsed && typeof parsed === 'object') {
80
- const target = String(parsed.path || parsed.file_path || parsed.target || '');
132
+ const target = String(parsed.path || parsed.file_path || parsed.target || parsed.destination || '');
81
133
  if (target) {
82
134
  if (['fs_write', 'write_to_file', 'writeFile'].includes(fnName)) {
83
135
  createdFiles.add(target);
84
- } else if (['fs_edit', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
136
+ } else if (['fs_edit', 'MultiEdit', 'multi_edit', 'fs_move', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
85
137
  modifiedFiles.add(target);
86
138
  } else if (['fs_read', 'view_file', 'readFile'].includes(fnName)) {
87
139
  inspectedFiles.add(target);
@@ -167,6 +219,21 @@ export function buildCodexStyleSummary(
167
219
  sections.push(`**Prior Failures Handled:** ${[...failures].slice(0, 4).join(' | ')}`);
168
220
  }
169
221
 
222
+ if (Array.isArray(extra?.activePlan) && extra.activePlan.length > 0) {
223
+ const planLines = extra.activePlan
224
+ .slice(0, 12)
225
+ .map(item => {
226
+ const label = String(item.step || item.title || '').trim();
227
+ if (!label) return '';
228
+ const status = String(item.status || 'pending').trim();
229
+ return `- [${status}] ${label}`;
230
+ })
231
+ .filter(Boolean);
232
+ if (planLines.length > 0) {
233
+ sections.push(`**Active Implementation Plan:**\n${planLines.join('\n')}`);
234
+ }
235
+ }
236
+
170
237
  sections.push(
171
238
  '**Directive for Continuation:** Completed workspace files and session artifacts on disk are preserved. '
172
239
  + 'Do not re-scan or repeat verified setup steps. Continue forward execution and complete the remaining requirements.'
@@ -215,9 +282,10 @@ export function compactSessionMessages(
215
282
  taskId: options.taskId ?? 'compaction'
216
283
  });
217
284
 
218
- // Calculate split index for physical compaction:
285
+ // Calculate turn-boundary-safe split index for physical compaction:
219
286
  // Messages from index 1 to splitIndex will be collapsed into a single summary
220
- const splitIndex = messages.length - keepRecentTurns - 1;
287
+ // without ever orphaning a `role: 'tool'` result from its `assistant` `tool_calls`.
288
+ const splitIndex = findSafeCompactionSplitIndex(messages, messages.length - keepRecentTurns - 1);
221
289
  if (splitIndex < 1) {
222
290
  return {
223
291
  compacted: false,
@@ -227,7 +295,7 @@ export function compactSessionMessages(
227
295
  initialChars,
228
296
  finalChars: measureMessages(messages),
229
297
  summaryText: '',
230
- reason: 'Split index out of range.'
298
+ reason: 'Split index out of range or would break an active tool-call turn.'
231
299
  };
232
300
  }
233
301
 
@@ -236,7 +304,9 @@ export function compactSessionMessages(
236
304
  ? messages[0].content
237
305
  : options.originalPrompt;
238
306
 
239
- const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt);
307
+ const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt, {
308
+ activePlan: options.activePlan
309
+ });
240
310
  const fullRecoverableSummary = buildRecoverableDroppedSummary(dropped, structuredSummary);
241
311
 
242
312
  const removed = compactInPlace(messages, splitIndex, fullRecoverableSummary);
@@ -275,7 +345,8 @@ export function autoCompactIfUnderPressure(
275
345
  const result = compactSessionMessages(loop.messages, {
276
346
  keepRecentTurns: 4,
277
347
  taskId: loop.taskId,
278
- originalPrompt: loop.currentTaskPrompt || loop.userPrompt
348
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
349
+ activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
279
350
  });
280
351
 
281
352
  if (result.compacted) {
@@ -320,7 +391,8 @@ export async function runCompactSlashCommand(
320
391
  const result = compactSessionMessages(loop.messages, {
321
392
  keepRecentTurns: 4,
322
393
  taskId: loop.taskId || 'manual-compact',
323
- originalPrompt: loop.currentTaskPrompt || loop.userPrompt
394
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
395
+ activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
324
396
  });
325
397
 
326
398
  if (!result.compacted) {
@@ -338,7 +410,7 @@ export async function runCompactSlashCommand(
338
410
  const finalKb = (result.finalChars / 1024).toFixed(1);
339
411
 
340
412
  const report = [
341
- '✔ Context successfully compacted (OpenAI Codex structured state model).',
413
+ '✔ Context successfully compacted (Causyne structured state model).',
342
414
  '',
343
415
  ` • Earlier messages condensed: ${result.removedCount}`,
344
416
  ` • Memory reclaimed: ${reclaimedKb} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`,
@@ -16,6 +16,7 @@ import { execFile } from 'node:child_process';
16
16
  import { promisify } from 'node:util';
17
17
  import { causyneHome } from './utils/paths.js';
18
18
  import { MODEL_CATALOGUE, PEER_MODEL_CATALOGUE, DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
19
+ import { validateProviderEndpointUrl, readBoundedResponseText } from './providers/byokHttp.js';
19
20
  import { BASELINE_ANTIGRAVITY_MODELS, ANTIGRAVITY_MODELS, ANTIGRAVITY_MODEL_IDS, ANTIGRAVITY_LABEL_BY_ID, registerAntigravityModel, replaceAntigravityModels, parseAgyModelsOutput, isAntigravityOnboarded, resolveAgyBinary } from './providers/antigravity.js';
20
21
  import { isBinaryOnPath, BUILTIN_PEER_PRESETS, probePresetAuth, testPeerHandshake } from './acp/agentCatalog.js';
21
22
  import { getPeerProfile } from './acp/peerProfiles.js';
@@ -881,16 +882,30 @@ export async function fetchLiveModels(provider, config = {}) {
881
882
  const peer = peerIdFromProviderKey(norm);
882
883
  if (peer)
883
884
  return discoverPeerModels(peer);
885
+ const MAX_DISCOVERY_BYTES = 4 * 1024 * 1024;
886
+ const fetchDiscoveryJson = async (rawUrl, headers = {}, hasApiKey = false) => {
887
+ const safeUrl = validateProviderEndpointUrl(rawUrl, {
888
+ hasApiKey,
889
+ providerLabel: norm
890
+ });
891
+ const res = await fetch(safeUrl, {
892
+ headers,
893
+ redirect: 'error',
894
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
895
+ });
896
+ if (!res.ok)
897
+ return null;
898
+ if (!res.body && typeof res.text !== 'function' && typeof res.json === 'function') {
899
+ return (await res.json());
900
+ }
901
+ const text = await readBoundedResponseText(res, MAX_DISCOVERY_BYTES, { truncate: false, label: norm });
902
+ return JSON.parse(text);
903
+ };
884
904
  try {
885
905
  if (norm === 'ollama') {
886
906
  const host = (baseUrl || 'http://127.0.0.1:11434').replace(/\/+$/, '');
887
- const res = await fetch(`${host}/api/tags`, {
888
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
889
- });
890
- if (!res.ok)
891
- return [];
892
- const data = await res.json();
893
- if (Array.isArray(data.models)) {
907
+ const data = await fetchDiscoveryJson(`${host}/api/tags`, {}, false);
908
+ if (Array.isArray(data?.models)) {
894
909
  return data.models
895
910
  .map((m) => (m.name || '').replace(/:latest$/, ''))
896
911
  .filter(Boolean);
@@ -900,14 +915,8 @@ export async function fetchLiveModels(provider, config = {}) {
900
915
  if (!apiKey)
901
916
  return [];
902
917
  const host = (baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
903
- const res = await fetch(`${host}/models`, {
904
- headers: { Authorization: `Bearer ${apiKey}` },
905
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
906
- });
907
- if (!res.ok)
908
- return [];
909
- const data = await res.json();
910
- if (Array.isArray(data.data)) {
918
+ const data = await fetchDiscoveryJson(`${host}/models`, { Authorization: `Bearer ${apiKey}` }, true);
919
+ if (Array.isArray(data?.data)) {
911
920
  return data.data
912
921
  .map((m) => m.id || '')
913
922
  .filter((id) => /^(gpt|o1|o3|chatgpt)/i.test(id))
@@ -917,13 +926,9 @@ export async function fetchLiveModels(provider, config = {}) {
917
926
  if (norm === 'gemini') {
918
927
  if (!apiKey)
919
928
  return [];
920
- const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey)}`, {
921
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
922
- });
923
- if (!res.ok)
924
- return [];
925
- const data = await res.json();
926
- if (Array.isArray(data.models)) {
929
+ // Send API key in x-goog-api-key header rather than query string (CWE-598).
930
+ const data = await fetchDiscoveryJson('https://generativelanguage.googleapis.com/v1beta/models', { 'x-goog-api-key': apiKey }, true);
931
+ if (Array.isArray(data?.models)) {
927
932
  return data.models
928
933
  .filter((m) => m.supportedGenerationMethods?.includes('generateContent'))
929
934
  .map((m) => (m.name || '').replace(/^models\//, ''))
@@ -934,17 +939,11 @@ export async function fetchLiveModels(provider, config = {}) {
934
939
  if (norm === 'anthropic') {
935
940
  if (!apiKey)
936
941
  return [];
937
- const res = await fetch('https://api.anthropic.com/v1/models', {
938
- headers: {
939
- 'x-api-key': apiKey,
940
- 'anthropic-version': '2023-06-01'
941
- },
942
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
943
- });
944
- if (!res.ok)
945
- return [];
946
- const data = await res.json();
947
- if (Array.isArray(data.data)) {
942
+ const data = await fetchDiscoveryJson('https://api.anthropic.com/v1/models', {
943
+ 'x-api-key': apiKey,
944
+ 'anthropic-version': '2023-06-01'
945
+ }, true);
946
+ if (Array.isArray(data?.data)) {
948
947
  return data.data
949
948
  .map((m) => m.id || '')
950
949
  .filter(Boolean)
@@ -954,14 +953,8 @@ export async function fetchLiveModels(provider, config = {}) {
954
953
  if (norm === 'deepseek') {
955
954
  if (!apiKey)
956
955
  return [];
957
- const res = await fetch('https://api.deepseek.com/models', {
958
- headers: { Authorization: `Bearer ${apiKey}` },
959
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
960
- });
961
- if (!res.ok)
962
- return [];
963
- const data = await res.json();
964
- if (Array.isArray(data.data)) {
956
+ const data = await fetchDiscoveryJson('https://api.deepseek.com/models', { Authorization: `Bearer ${apiKey}` }, true);
957
+ if (Array.isArray(data?.data)) {
965
958
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
966
959
  }
967
960
  }
@@ -969,14 +962,8 @@ export async function fetchLiveModels(provider, config = {}) {
969
962
  if (!apiKey)
970
963
  return [];
971
964
  const host = (baseUrl || 'https://api.x.ai/v1').replace(/\/+$/, '');
972
- const res = await fetch(`${host}/models`, {
973
- headers: { Authorization: `Bearer ${apiKey}` },
974
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
975
- });
976
- if (!res.ok)
977
- return [];
978
- const data = await res.json();
979
- if (Array.isArray(data.data)) {
965
+ const data = await fetchDiscoveryJson(`${host}/models`, { Authorization: `Bearer ${apiKey}` }, true);
966
+ if (Array.isArray(data?.data)) {
980
967
  return data.data.map((m) => m.id || '').filter((id) => /^(grok)/i.test(id)).sort();
981
968
  }
982
969
  }
@@ -984,14 +971,8 @@ export async function fetchLiveModels(provider, config = {}) {
984
971
  if (!apiKey)
985
972
  return [];
986
973
  const host = (baseUrl || 'https://api.moonshot.cn/v1').replace(/\/+$/, '');
987
- const res = await fetch(`${host}/models`, {
988
- headers: { Authorization: `Bearer ${apiKey}` },
989
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
990
- });
991
- if (!res.ok)
992
- return [];
993
- const data = await res.json();
994
- if (Array.isArray(data.data)) {
974
+ const data = await fetchDiscoveryJson(`${host}/models`, { Authorization: `Bearer ${apiKey}` }, true);
975
+ if (Array.isArray(data?.data)) {
995
976
  return data.data.map((m) => m.id || '').filter((id) => /^(kimi|moonshot)/i.test(id)).sort();
996
977
  }
997
978
  }
@@ -999,14 +980,8 @@ export async function fetchLiveModels(provider, config = {}) {
999
980
  if (!apiKey)
1000
981
  return [];
1001
982
  const host = (baseUrl || 'https://dashscope.aliyuncs.com/compatible-mode/v1').replace(/\/+$/, '');
1002
- const res = await fetch(`${host}/models`, {
1003
- headers: { Authorization: `Bearer ${apiKey}` },
1004
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1005
- });
1006
- if (!res.ok)
1007
- return [];
1008
- const data = await res.json();
1009
- if (Array.isArray(data.data)) {
983
+ const data = await fetchDiscoveryJson(`${host}/models`, { Authorization: `Bearer ${apiKey}` }, true);
984
+ if (Array.isArray(data?.data)) {
1010
985
  return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1011
986
  }
1012
987
  }
@@ -1024,14 +999,8 @@ export async function fetchLiveModels(provider, config = {}) {
1024
999
  const headers = {};
1025
1000
  if (apiKey)
1026
1001
  headers['Authorization'] = `Bearer ${apiKey}`;
1027
- const res = await fetch(`${host}/models`, {
1028
- headers,
1029
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1030
- });
1031
- if (!res.ok)
1032
- return [];
1033
- const data = await res.json();
1034
- if (Array.isArray(data.data)) {
1002
+ const data = await fetchDiscoveryJson(`${host}/models`, headers, Boolean(apiKey));
1003
+ if (Array.isArray(data?.data)) {
1035
1004
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
1036
1005
  }
1037
1006
  }
@@ -17,6 +17,7 @@ import { execFile } from 'node:child_process';
17
17
  import { promisify } from 'node:util';
18
18
  import { causyneHome } from './utils/paths.js';
19
19
  import { MODEL_CATALOGUE, PEER_MODEL_CATALOGUE, DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
20
+ import { validateProviderEndpointUrl, readBoundedResponseText } from './providers/byokHttp.js';
20
21
  import {
21
22
  BASELINE_ANTIGRAVITY_MODELS,
22
23
  ANTIGRAVITY_MODELS,
@@ -953,15 +954,34 @@ export async function fetchLiveModels(
953
954
  const peer = peerIdFromProviderKey(norm);
954
955
  if (peer) return discoverPeerModels(peer);
955
956
 
957
+ const MAX_DISCOVERY_BYTES = 4 * 1024 * 1024;
958
+ const fetchDiscoveryJson = async <T>(
959
+ rawUrl: string,
960
+ headers: Record<string, string> = {},
961
+ hasApiKey = false
962
+ ): Promise<T | null> => {
963
+ const safeUrl = validateProviderEndpointUrl(rawUrl, {
964
+ hasApiKey,
965
+ providerLabel: norm
966
+ });
967
+ const res = await fetch(safeUrl, {
968
+ headers,
969
+ redirect: 'error',
970
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
971
+ });
972
+ if (!res.ok) return null;
973
+ if (!res.body && typeof res.text !== 'function' && typeof res.json === 'function') {
974
+ return (await res.json()) as T;
975
+ }
976
+ const text = await readBoundedResponseText(res, MAX_DISCOVERY_BYTES, { truncate: false, label: norm });
977
+ return JSON.parse(text) as T;
978
+ };
979
+
956
980
  try {
957
981
  if (norm === 'ollama') {
958
982
  const host = (baseUrl || 'http://127.0.0.1:11434').replace(/\/+$/, '');
959
- const res = await fetch(`${host}/api/tags`, {
960
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
961
- });
962
- if (!res.ok) return [];
963
- const data = await res.json() as { models?: Array<{ name?: string }> };
964
- if (Array.isArray(data.models)) {
983
+ const data = await fetchDiscoveryJson<{ models?: Array<{ name?: string }> }>(`${host}/api/tags`, {}, false);
984
+ if (Array.isArray(data?.models)) {
965
985
  return data.models
966
986
  .map((m) => (m.name || '').replace(/:latest$/, ''))
967
987
  .filter(Boolean);
@@ -971,13 +991,12 @@ export async function fetchLiveModels(
971
991
  if (norm === 'openai') {
972
992
  if (!apiKey) return [];
973
993
  const host = (baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
974
- const res = await fetch(`${host}/models`, {
975
- headers: { Authorization: `Bearer ${apiKey}` },
976
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
977
- });
978
- if (!res.ok) return [];
979
- const data = await res.json() as { data?: Array<{ id?: string }> };
980
- if (Array.isArray(data.data)) {
994
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
995
+ `${host}/models`,
996
+ { Authorization: `Bearer ${apiKey}` },
997
+ true
998
+ );
999
+ if (Array.isArray(data?.data)) {
981
1000
  return data.data
982
1001
  .map((m) => m.id || '')
983
1002
  .filter((id) => /^(gpt|o1|o3|chatgpt)/i.test(id))
@@ -987,12 +1006,13 @@ export async function fetchLiveModels(
987
1006
 
988
1007
  if (norm === 'gemini') {
989
1008
  if (!apiKey) return [];
990
- const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey)}`, {
991
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
992
- });
993
- if (!res.ok) return [];
994
- const data = await res.json() as { models?: Array<{ name?: string; supportedGenerationMethods?: string[] }> };
995
- if (Array.isArray(data.models)) {
1009
+ // Send API key in x-goog-api-key header rather than query string (CWE-598).
1010
+ const data = await fetchDiscoveryJson<{ models?: Array<{ name?: string; supportedGenerationMethods?: string[] }> }>(
1011
+ 'https://generativelanguage.googleapis.com/v1beta/models',
1012
+ { 'x-goog-api-key': apiKey },
1013
+ true
1014
+ );
1015
+ if (Array.isArray(data?.models)) {
996
1016
  return data.models
997
1017
  .filter((m) => m.supportedGenerationMethods?.includes('generateContent'))
998
1018
  .map((m) => (m.name || '').replace(/^models\//, ''))
@@ -1003,16 +1023,15 @@ export async function fetchLiveModels(
1003
1023
 
1004
1024
  if (norm === 'anthropic') {
1005
1025
  if (!apiKey) return [];
1006
- const res = await fetch('https://api.anthropic.com/v1/models', {
1007
- headers: {
1026
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1027
+ 'https://api.anthropic.com/v1/models',
1028
+ {
1008
1029
  'x-api-key': apiKey,
1009
1030
  'anthropic-version': '2023-06-01'
1010
1031
  },
1011
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1012
- });
1013
- if (!res.ok) return [];
1014
- const data = await res.json() as { data?: Array<{ id?: string }> };
1015
- if (Array.isArray(data.data)) {
1032
+ true
1033
+ );
1034
+ if (Array.isArray(data?.data)) {
1016
1035
  return data.data
1017
1036
  .map((m) => m.id || '')
1018
1037
  .filter(Boolean)
@@ -1022,13 +1041,12 @@ export async function fetchLiveModels(
1022
1041
 
1023
1042
  if (norm === 'deepseek') {
1024
1043
  if (!apiKey) return [];
1025
- const res = await fetch('https://api.deepseek.com/models', {
1026
- headers: { Authorization: `Bearer ${apiKey}` },
1027
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1028
- });
1029
- if (!res.ok) return [];
1030
- const data = await res.json() as { data?: Array<{ id?: string }> };
1031
- if (Array.isArray(data.data)) {
1044
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1045
+ 'https://api.deepseek.com/models',
1046
+ { Authorization: `Bearer ${apiKey}` },
1047
+ true
1048
+ );
1049
+ if (Array.isArray(data?.data)) {
1032
1050
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
1033
1051
  }
1034
1052
  }
@@ -1036,13 +1054,12 @@ export async function fetchLiveModels(
1036
1054
  if (norm === 'xai') {
1037
1055
  if (!apiKey) return [];
1038
1056
  const host = (baseUrl || 'https://api.x.ai/v1').replace(/\/+$/, '');
1039
- const res = await fetch(`${host}/models`, {
1040
- headers: { Authorization: `Bearer ${apiKey}` },
1041
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1042
- });
1043
- if (!res.ok) return [];
1044
- const data = await res.json() as { data?: Array<{ id?: string }> };
1045
- if (Array.isArray(data.data)) {
1057
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1058
+ `${host}/models`,
1059
+ { Authorization: `Bearer ${apiKey}` },
1060
+ true
1061
+ );
1062
+ if (Array.isArray(data?.data)) {
1046
1063
  return data.data.map((m) => m.id || '').filter((id) => /^(grok)/i.test(id)).sort();
1047
1064
  }
1048
1065
  }
@@ -1050,13 +1067,12 @@ export async function fetchLiveModels(
1050
1067
  if (norm === 'moonshot') {
1051
1068
  if (!apiKey) return [];
1052
1069
  const host = (baseUrl || 'https://api.moonshot.cn/v1').replace(/\/+$/, '');
1053
- const res = await fetch(`${host}/models`, {
1054
- headers: { Authorization: `Bearer ${apiKey}` },
1055
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1056
- });
1057
- if (!res.ok) return [];
1058
- const data = await res.json() as { data?: Array<{ id?: string }> };
1059
- if (Array.isArray(data.data)) {
1070
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1071
+ `${host}/models`,
1072
+ { Authorization: `Bearer ${apiKey}` },
1073
+ true
1074
+ );
1075
+ if (Array.isArray(data?.data)) {
1060
1076
  return data.data.map((m) => m.id || '').filter((id) => /^(kimi|moonshot)/i.test(id)).sort();
1061
1077
  }
1062
1078
  }
@@ -1064,13 +1080,12 @@ export async function fetchLiveModels(
1064
1080
  if (norm === 'dashscope-byok' || norm === 'qwen') {
1065
1081
  if (!apiKey) return [];
1066
1082
  const host = (baseUrl || 'https://dashscope.aliyuncs.com/compatible-mode/v1').replace(/\/+$/, '');
1067
- const res = await fetch(`${host}/models`, {
1068
- headers: { Authorization: `Bearer ${apiKey}` },
1069
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1070
- });
1071
- if (!res.ok) return [];
1072
- const data = await res.json() as { data?: Array<{ id?: string }> };
1073
- if (Array.isArray(data.data)) {
1083
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1084
+ `${host}/models`,
1085
+ { Authorization: `Bearer ${apiKey}` },
1086
+ true
1087
+ );
1088
+ if (Array.isArray(data?.data)) {
1074
1089
  return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1075
1090
  }
1076
1091
  }
@@ -1088,13 +1103,12 @@ export async function fetchLiveModels(
1088
1103
  const host = baseUrl.replace(/\/+$/, '');
1089
1104
  const headers: Record<string, string> = {};
1090
1105
  if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
1091
- const res = await fetch(`${host}/models`, {
1106
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1107
+ `${host}/models`,
1092
1108
  headers,
1093
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1094
- });
1095
- if (!res.ok) return [];
1096
- const data = await res.json() as { data?: Array<{ id?: string }> };
1097
- if (Array.isArray(data.data)) {
1109
+ Boolean(apiKey)
1110
+ );
1111
+ if (Array.isArray(data?.data)) {
1098
1112
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
1099
1113
  }
1100
1114
  }