@causyne/agent 1.20.118 → 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 (101) 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 +51 -351
  9. package/src/agentLoop.ts +69 -363
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/browser/causyneBrowser.js +231 -136
  13. package/src/browser/causyneBrowser.ts +229 -140
  14. package/src/browser/searchProviders.js +41 -30
  15. package/src/browser/searchProviders.ts +24 -14
  16. package/src/browser/workspacePathSafety.js +50 -0
  17. package/src/browser/workspacePathSafety.ts +50 -0
  18. package/src/browser/workspacePreview.js +27 -4
  19. package/src/browser/workspacePreview.ts +28 -4
  20. package/src/cliMode.js +17 -3
  21. package/src/commands.js +15 -22
  22. package/src/config.js +42 -63
  23. package/src/configVault.js +204 -0
  24. package/src/configVault.ts +213 -0
  25. package/src/core/contextCompactor.js +70 -11
  26. package/src/core/contextCompactor.ts +83 -11
  27. package/src/creative/liveBridge.js +34 -1
  28. package/src/creative/liveBridge.ts +28 -1
  29. package/src/dynamicCatalogue.js +42 -73
  30. package/src/dynamicCatalogue.ts +74 -60
  31. package/src/entrypoint.js +77 -4
  32. package/src/headlessCli.js +304 -0
  33. package/src/headlessCli.ts +380 -0
  34. package/src/mcp/mcpClient.js +38 -11
  35. package/src/mcp/mcpClient.ts +44 -11
  36. package/src/mcp/mcpRegistry.js +2 -5
  37. package/src/mcp/mcpRegistry.ts +2 -5
  38. package/src/mcp/mcpSecurity.js +189 -0
  39. package/src/mcp/mcpSecurity.ts +190 -0
  40. package/src/observer/evidence.js +23 -0
  41. package/src/observer/evidence.ts +21 -0
  42. package/src/osKeychain.js +209 -0
  43. package/src/osKeychain.ts +245 -0
  44. package/src/providers/anthropic.js +61 -28
  45. package/src/providers/base.js +14 -0
  46. package/src/providers/byokHttp.js +354 -0
  47. package/src/providers/byokHttp.ts +454 -0
  48. package/src/providers/byokStream.js +657 -0
  49. package/src/providers/byokStream.ts +759 -0
  50. package/src/providers/dashscope-byok.js +47 -32
  51. package/src/providers/deepseek.js +43 -39
  52. package/src/providers/gemini.js +73 -38
  53. package/src/providers/moonshot.js +43 -33
  54. package/src/providers/muse.js +10 -10
  55. package/src/providers/ollama.js +46 -31
  56. package/src/providers/openai-compatible.js +57 -32
  57. package/src/providers/openrouter.js +77 -113
  58. package/src/providers/openrouter.ts +99 -118
  59. package/src/providers/qwen-byok.js +46 -23
  60. package/src/providers/toolContracts.js +9 -3
  61. package/src/providers/toolContracts.ts +9 -3
  62. package/src/providers/wireNormalizer.js +238 -0
  63. package/src/providers/wireNormalizer.ts +279 -0
  64. package/src/providers/xai.js +43 -33
  65. package/src/sandbox.js +77 -56
  66. package/src/sandboxPolicy.js +1208 -0
  67. package/src/sandboxPolicy.ts +1300 -0
  68. package/src/sessionJournal.js +47 -0
  69. package/src/sessionJournal.ts +49 -0
  70. package/src/tools/browserAutomator.js +13 -1
  71. package/src/tools/browserAutomator.ts +13 -0
  72. package/src/tools/creativeApps.js +2 -1
  73. package/src/tools/creativeApps.ts +2 -1
  74. package/src/tools/gameAssetFetcher.js +130 -26
  75. package/src/tools/gameAssetHarvester.js +80 -58
  76. package/src/tools/nativeEngine.js +1 -1
  77. package/src/tools/nativeEngine.ts +1 -1
  78. package/src/tools/osSandbox.js +473 -0
  79. package/src/tools/osSandbox.ts +554 -0
  80. package/src/tools/persistentShell.js +8 -3
  81. package/src/tools/registry.js +13 -0
  82. package/src/tools/subprocessEnv.js +197 -0
  83. package/src/tools/subprocessEnv.ts +212 -0
  84. package/src/tools/sysRun.js +39 -6
  85. package/src/tools/sysRun.ts +53 -7
  86. package/src/tools/toolScanner.js +596 -140
  87. package/src/tools/toolScanner.ts +665 -147
  88. package/src/tools/toolSelfRepair.js +243 -114
  89. package/src/tools/toolSelfRepair.ts +262 -111
  90. package/src/tools/webFetch.js +161 -24
  91. package/src/tools/webFetch.ts +157 -22
  92. package/src/tools/webSearch.js +33 -4
  93. package/src/tools/webSearch.ts +27 -4
  94. package/src/tui/sessionPicker.js +132 -35
  95. package/src/tui/sessionPicker.ts +153 -32
  96. package/src/tui/sessionPickerView.js +277 -34
  97. package/src/tui/sessionPickerView.ts +328 -34
  98. package/src/tui/statusLine.js +3 -0
  99. package/src/tui/statusLine.ts +5 -0
  100. package/src/tui/workspaceIdentity.js +133 -0
  101. package/src/tui/workspaceIdentity.ts +146 -0
@@ -12,11 +12,50 @@
12
12
  */
13
13
  import { pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments, buildRecoverableDroppedSummary } from '../historyPruner.js';
14
14
  import { compactInPlace, measureMessages, CHARS_PER_TOKEN } from '../contextManager.js';
15
+ /**
16
+ * Adjusts a candidate compaction split index so compaction NEVER severs a
17
+ * `role: 'tool'` result from its preceding `role: 'assistant'` `tool_calls`
18
+ * message (which would cause HTTP 400 invalid tool-turn errors on OpenAI,
19
+ * Anthropic, and Gemini).
20
+ *
21
+ * Returns a safe `splitIndex` in `[1, messages.length - 2]`, or `-1` if no
22
+ * safe split exists.
23
+ */
24
+ export function findSafeCompactionSplitIndex(messages, targetSplitIndex) {
25
+ const maxSplit = messages.length - 2;
26
+ if (maxSplit < 1)
27
+ return -1;
28
+ let split = Math.min(Math.max(1, targetSplitIndex), maxSplit);
29
+ // If the first retained message (`split + 1`) is a `tool` result, walk back
30
+ // until the owning `assistant` message with `tool_calls` is also retained.
31
+ if (messages[split + 1]?.role === 'tool') {
32
+ let back = split;
33
+ while (back >= 1 && messages[back + 1]?.role === 'tool') {
34
+ back -= 1;
35
+ }
36
+ // Also retain the owning `assistant` message if `back + 1` was still `tool`
37
+ if (back >= 1 && messages[back]?.role === 'assistant' && Array.isArray(messages[back]?.tool_calls)) {
38
+ back -= 1;
39
+ }
40
+ if (back >= 1 && messages[back + 1]?.role !== 'tool') {
41
+ return back;
42
+ }
43
+ // Otherwise walk forward past the contiguous `tool` results while keeping at least 1 recent message
44
+ let forward = split;
45
+ while (forward < maxSplit && messages[forward + 1]?.role === 'tool') {
46
+ forward += 1;
47
+ }
48
+ if (forward <= maxSplit && messages[forward + 1]?.role !== 'tool') {
49
+ return forward;
50
+ }
51
+ return -1;
52
+ }
53
+ return split;
54
+ }
15
55
  /**
16
56
  * Extracts a high-fidelity, structured state summary from dropped message history.
17
- * Mirrors the state preservation architecture of OpenAI Codex and Claude Code.
18
57
  */
19
- export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
58
+ export function buildCodexStyleSummary(droppedMessages, originalPrompt, extra) {
20
59
  const createdFiles = new Set();
21
60
  const modifiedFiles = new Set();
22
61
  const inspectedFiles = new Set();
@@ -35,12 +74,12 @@ export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
35
74
  if (typeof rawArgs === 'string') {
36
75
  const parsed = JSON.parse(rawArgs);
37
76
  if (parsed && typeof parsed === 'object') {
38
- const target = String(parsed.path || parsed.file_path || parsed.target || '');
77
+ const target = String(parsed.path || parsed.file_path || parsed.target || parsed.destination || '');
39
78
  if (target) {
40
79
  if (['fs_write', 'write_to_file', 'writeFile'].includes(fnName)) {
41
80
  createdFiles.add(target);
42
81
  }
43
- else if (['fs_edit', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
82
+ else if (['fs_edit', 'MultiEdit', 'multi_edit', 'fs_move', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
44
83
  modifiedFiles.add(target);
45
84
  }
46
85
  else if (['fs_read', 'view_file', 'readFile'].includes(fnName)) {
@@ -124,6 +163,21 @@ export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
124
163
  if (failures.size > 0) {
125
164
  sections.push(`**Prior Failures Handled:** ${[...failures].slice(0, 4).join(' | ')}`);
126
165
  }
166
+ if (Array.isArray(extra?.activePlan) && extra.activePlan.length > 0) {
167
+ const planLines = extra.activePlan
168
+ .slice(0, 12)
169
+ .map(item => {
170
+ const label = String(item.step || item.title || '').trim();
171
+ if (!label)
172
+ return '';
173
+ const status = String(item.status || 'pending').trim();
174
+ return `- [${status}] ${label}`;
175
+ })
176
+ .filter(Boolean);
177
+ if (planLines.length > 0) {
178
+ sections.push(`**Active Implementation Plan:**\n${planLines.join('\n')}`);
179
+ }
180
+ }
127
181
  sections.push('**Directive for Continuation:** Completed workspace files and session artifacts on disk are preserved. '
128
182
  + 'Do not re-scan or repeat verified setup steps. Continue forward execution and complete the remaining requirements.');
129
183
  return sections.join('\n\n');
@@ -162,9 +216,10 @@ export function compactSessionMessages(messages, options = {}) {
162
216
  threshold: 1500,
163
217
  taskId: options.taskId ?? 'compaction'
164
218
  });
165
- // Calculate split index for physical compaction:
219
+ // Calculate turn-boundary-safe split index for physical compaction:
166
220
  // Messages from index 1 to splitIndex will be collapsed into a single summary
167
- const splitIndex = messages.length - keepRecentTurns - 1;
221
+ // without ever orphaning a `role: 'tool'` result from its `assistant` `tool_calls`.
222
+ const splitIndex = findSafeCompactionSplitIndex(messages, messages.length - keepRecentTurns - 1);
168
223
  if (splitIndex < 1) {
169
224
  return {
170
225
  compacted: false,
@@ -174,14 +229,16 @@ export function compactSessionMessages(messages, options = {}) {
174
229
  initialChars,
175
230
  finalChars: measureMessages(messages),
176
231
  summaryText: '',
177
- reason: 'Split index out of range.'
232
+ reason: 'Split index out of range or would break an active tool-call turn.'
178
233
  };
179
234
  }
180
235
  const dropped = messages.slice(1, splitIndex + 1);
181
236
  const rootPrompt = typeof messages[0]?.content === 'string'
182
237
  ? messages[0].content
183
238
  : options.originalPrompt;
184
- const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt);
239
+ const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt, {
240
+ activePlan: options.activePlan
241
+ });
185
242
  const fullRecoverableSummary = buildRecoverableDroppedSummary(dropped, structuredSummary);
186
243
  const removed = compactInPlace(messages, splitIndex, fullRecoverableSummary);
187
244
  const finalChars = measureMessages(messages);
@@ -212,7 +269,8 @@ export function autoCompactIfUnderPressure(loop, options = {}) {
212
269
  const result = compactSessionMessages(loop.messages, {
213
270
  keepRecentTurns: 4,
214
271
  taskId: loop.taskId,
215
- originalPrompt: loop.currentTaskPrompt || loop.userPrompt
272
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
273
+ activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
216
274
  });
217
275
  if (result.compacted) {
218
276
  if (loop.memoryManager && typeof loop.memoryManager.saveHistory === 'function') {
@@ -249,7 +307,8 @@ export async function runCompactSlashCommand(_argv, ctx) {
249
307
  const result = compactSessionMessages(loop.messages, {
250
308
  keepRecentTurns: 4,
251
309
  taskId: loop.taskId || 'manual-compact',
252
- originalPrompt: loop.currentTaskPrompt || loop.userPrompt
310
+ originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
311
+ activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
253
312
  });
254
313
  if (!result.compacted) {
255
314
  return {
@@ -263,7 +322,7 @@ export async function runCompactSlashCommand(_argv, ctx) {
263
322
  const reclaimedKb = (result.reclaimedChars / 1024).toFixed(1);
264
323
  const finalKb = (result.finalChars / 1024).toFixed(1);
265
324
  const report = [
266
- '✔ Context successfully compacted (OpenAI Codex structured state model).',
325
+ '✔ Context successfully compacted (Causyne structured state model).',
267
326
  '',
268
327
  ` • Earlier messages condensed: ${result.removedCount}`,
269
328
  ` • Memory reclaimed: ${reclaimedKb} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`,
@@ -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)`,
@@ -704,6 +704,39 @@ export function validateGameEngineJob(value) {
704
704
  }
705
705
  return [nums[0], nums[1], nums[2]];
706
706
  };
707
+ const normalizePropertyValue = (val) => {
708
+ if (typeof val !== 'string')
709
+ return val;
710
+ const trimmed = val.trim();
711
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
712
+ try {
713
+ const parsed = JSON.parse(trimmed);
714
+ if (typeof parsed === 'string')
715
+ return parsed;
716
+ }
717
+ catch {
718
+ // Keep raw string
719
+ }
720
+ }
721
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
722
+ try {
723
+ return JSON.parse(trimmed);
724
+ }
725
+ catch {
726
+ return val;
727
+ }
728
+ }
729
+ if (trimmed === 'true')
730
+ return true;
731
+ if (trimmed === 'false')
732
+ return false;
733
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
734
+ const num = Number(trimmed);
735
+ if (Number.isFinite(num))
736
+ return num;
737
+ }
738
+ return val;
739
+ };
707
740
  return {
708
741
  engine: engineInput,
709
742
  canonicalEngine,
@@ -716,7 +749,7 @@ export function validateGameEngineJob(value) {
716
749
  objectPath: typeof raw.objectPath === 'string' ? raw.objectPath.trim() : undefined,
717
750
  functionName: typeof raw.functionName === 'string' ? raw.functionName.trim() : undefined,
718
751
  propertyName: typeof raw.propertyName === 'string' ? raw.propertyName.trim() : undefined,
719
- propertyValue: raw.propertyValue,
752
+ propertyValue: normalizePropertyValue(raw.propertyValue),
720
753
  parameters: raw.parameters && typeof raw.parameters === 'object' && !Array.isArray(raw.parameters)
721
754
  ? raw.parameters
722
755
  : undefined,
@@ -948,6 +948,33 @@ export function validateGameEngineJob(value: unknown): GameEngineJob {
948
948
  return [nums[0]!, nums[1]!, nums[2]!];
949
949
  };
950
950
 
951
+ const normalizePropertyValue = (val: unknown): unknown => {
952
+ if (typeof val !== 'string') return val;
953
+ const trimmed = val.trim();
954
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
955
+ try {
956
+ const parsed = JSON.parse(trimmed);
957
+ if (typeof parsed === 'string') return parsed;
958
+ } catch {
959
+ // Keep raw string
960
+ }
961
+ }
962
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
963
+ try {
964
+ return JSON.parse(trimmed);
965
+ } catch {
966
+ return val;
967
+ }
968
+ }
969
+ if (trimmed === 'true') return true;
970
+ if (trimmed === 'false') return false;
971
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
972
+ const num = Number(trimmed);
973
+ if (Number.isFinite(num)) return num;
974
+ }
975
+ return val;
976
+ };
977
+
951
978
  return {
952
979
  engine: engineInput,
953
980
  canonicalEngine,
@@ -960,7 +987,7 @@ export function validateGameEngineJob(value: unknown): GameEngineJob {
960
987
  objectPath: typeof raw.objectPath === 'string' ? raw.objectPath.trim() : undefined,
961
988
  functionName: typeof raw.functionName === 'string' ? raw.functionName.trim() : undefined,
962
989
  propertyName: typeof raw.propertyName === 'string' ? raw.propertyName.trim() : undefined,
963
- propertyValue: raw.propertyValue,
990
+ propertyValue: normalizePropertyValue(raw.propertyValue),
964
991
  parameters: raw.parameters && typeof raw.parameters === 'object' && !Array.isArray(raw.parameters)
965
992
  ? (raw.parameters as Record<string, unknown>)
966
993
  : undefined,
@@ -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
  }