@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
package/src/agentLoop.ts CHANGED
@@ -6,6 +6,19 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
6
6
  import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
7
  import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
8
  import { normalizeAgentFailure } from './agent/providerFailure.js';
9
+ import { classifyAgentError, getRetryHintForError } from './agent/errorClassifier.js';
10
+ import {
11
+ isActionableTaskPrompt,
12
+ isGenericHandoffResponse,
13
+ isDesktopWallpaperChangePrompt,
14
+ isExecutionOrLaunchTaskPrompt,
15
+ isCodeAuthoringTaskPrompt,
16
+ extractSkillIdFromPrompt,
17
+ isDirectGameTask,
18
+ isProviderPlanOrQuotaRefusal,
19
+ isMidTaskProgressText
20
+ } from './agent/promptIntent.js';
21
+ import { validateAndNormalizeToolArgs } from './agent/toolArgValidator.js';
9
22
  import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
10
23
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
11
24
  import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
@@ -76,7 +89,7 @@ import { buildToolsList, renderToolsList, omittedCustomCount } from './toolsList
76
89
  import type { ToolListEntry } from './toolsList.js';
77
90
  import { assessVerification } from './verificationPlan.js';
78
91
  import { SmartTools } from './SmartTools.js';
79
- import { decideTools, isDirectGameTask as isDirectGameTaskDecision } from './decideTools.js';
92
+ import { decideTools } from './decideTools.js';
80
93
  import type { DecideToolsInput } from './decideTools.js';
81
94
  import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
82
95
  import type { AdmissionResult } from './saveTools.js';
@@ -176,40 +189,21 @@ export interface AgentLoopOptions {
176
189
  workspaceRoot?: string;
177
190
  memorySessionId?: string | null;
178
191
  approvalScope?: AgentLoopApprovalScope;
192
+ provider?: string;
193
+ model?: string;
179
194
  }
180
195
 
181
- export function isActionableTaskPrompt(text: string): boolean {
182
- const t = (text || '').trim();
183
- if (!t) return false;
184
- // A no-execution request can be satisfied by analysis without mandatory tool calls.
185
- if (isNoExecutionPrompt(t)) return false;
186
- const pureGreeting = /^(hi|hello|hey|yo|halo|hai|p|assalamu['a]?[l]?aikum|good\s+(morning|afternoon|evening))[.!?, ]*$/i.test(t);
187
- if (pureGreeting) return false;
188
- const actionKeywords = /\b(continue|resume|proceed|lanjut\w*|create|build|make|write|code|implement|fix|optimize|refactor|generate|add|setup|install|run|open|launch|start|play|serve|preview|deploy|delete|remove|update|change|test|review|inspect|search|find|download|buat\w*|bikin\w*|perbaik\w*|tambah\w*|ubah\w*|hapus\w*|jalan\w*|pasang\w*|analis\w*|cek\w*|rancang\w*|desain\w*|kerjakan\w*|tolong\w*|bantu\w*|ganti\w*|tulis\w*|kembangkan\w*)\b/i;
189
- if (actionKeywords.test(t)) return true;
190
- return false; // Length alone does not turn an information question into an execution order.
191
- }
192
-
193
- export function isGenericHandoffResponse(text: string): boolean {
194
- const answer = (text || '').trim();
195
- if (!answer || answer.length > 500) return false;
196
- const lower = answer.toLowerCase();
197
- const handoff = /\b(let me know what you would like to do next|what would you like me to do next|how (can|may) i help|what can i help you with|feel free to (ask|tell me))\b/i.test(lower);
198
- const verifiedOutcome = /\b(completed|changed|set the (desktop|wallpaper)|saved|created|installed|verified|downloaded|finished)\b/i.test(lower);
199
- return handoff && !verifiedOutcome;
200
- }
201
-
202
- export function isDesktopWallpaperChangePrompt(text: string): boolean {
203
- const t = (text || '').trim();
204
- if (!t) return false;
205
- // Explanatory questions or prompts that explicitly forbid execution are never wallpaper mutation requests
206
- if (isNoExecutionPrompt(t) || isReadOnlyOrExplanatoryPrompt(t)) return false;
207
- if (/^(?:why|how|what|does|can\s+you\s+explain|explain|tell\s+me|show\s+me\s+how)\b/i.test(t)) return false;
208
- if (/\b(?:why|how)\s+does\b/i.test(t)) return false;
209
- // Debugging wallpaper-related source or regexes is not a request to mutate macOS.
210
- if (/\b(?:test|review|audit|analy[sz]e|debug|refactor|inspect|explain|write|implement)\b[\s\S]{0,140}\b(?:regex|code|source|logic|verification|readback|function|script|test)\b/i.test(t)) return false;
211
- return /\b(?:change|set|switch|replace)\s+(?:(?:my|the|this|current|desktop|mac|macos)\s+){0,4}(?:desktop picture|wallpaper|desktop background)\b/i.test(t);
212
- }
196
+ export {
197
+ isActionableTaskPrompt,
198
+ isGenericHandoffResponse,
199
+ isDesktopWallpaperChangePrompt,
200
+ isExecutionOrLaunchTaskPrompt,
201
+ isCodeAuthoringTaskPrompt,
202
+ extractSkillIdFromPrompt,
203
+ isDirectGameTask,
204
+ isProviderPlanOrQuotaRefusal,
205
+ isMidTaskProgressText
206
+ };
213
207
 
214
208
  function readMacDesktopPictures(): string | null {
215
209
  try {
@@ -221,169 +215,6 @@ function readMacDesktopPictures(): string | null {
221
215
  }
222
216
  }
223
217
 
224
- export function isExecutionOrLaunchTaskPrompt(text: string): boolean {
225
- const t = (text || '').trim();
226
- if (!t) return false;
227
- return /\b(open|launch|start|run|play|serve|preview)\b/i.test(t)
228
- && !/\b(create|build|make|write|code|implement|generate|refactor)\b/i.test(t);
229
- }
230
-
231
- export function isCodeAuthoringTaskPrompt(text: string): boolean {
232
- const t = (text || '').trim();
233
- if (!t) return false;
234
- if (isExecutionOrLaunchTaskPrompt(t)) return false;
235
- return /\b(create|build|make|write|code|implement|generate|game|3js|three?\.?js|three?js|app)\b/i.test(t);
236
- }
237
-
238
- export function extractSkillIdFromPrompt(prompt: string): string {
239
- const text = String(prompt || '').trim();
240
- if (!text) return '';
241
- const stopWords = new Set([
242
- 'the', 'a', 'an', 'this', 'that', 'from', 'in', 'with',
243
- 'using', 'for', 'to', 'by', 'and', 'or', 'of'
244
- ]);
245
- const leadingTrim = new Set(['`', '"', "'", '(', '[']);
246
- const trailingTrim = new Set(['`', '"', "'", ')', ',', '.', ';', ':', '!', '?', ']', '\\']);
247
- const cleanCandidate = (raw: string): string => {
248
- const trimmed = raw.trim();
249
- let start = 0;
250
- let end = trimmed.length;
251
- while (start < end && leadingTrim.has(trimmed[start]!)) start++;
252
- while (end > start && trailingTrim.has(trimmed[end - 1]!)) end--;
253
- const stripped = trimmed.slice(start, end);
254
- if (!stripped || stopWords.has(stripped.toLowerCase())) return '';
255
- if (/^(?:fs_read_skill|fs_read_skil|read_skill|read_skil|tool_search)$/i.test(stripped)) {
256
- return '';
257
- }
258
- return stripped;
259
- };
260
- const isFileExt = (candidate: string): boolean =>
261
- /\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|json|html|css|gradle|apk|aab|dex)$/i.test(candidate);
262
-
263
- const cuedSlashMatch = text.match(
264
- /(?:\bskill_id|\bskill|\bfs_read_skil{1,2})(?:\s*[:=]\s*|\s+)[`"']?([a-zA-Z0-9][a-zA-Z0-9_.-]{0,80}\/[a-zA-Z0-9][a-zA-Z0-9_.-]{0,120})[`"']?/i
265
- );
266
- if (cuedSlashMatch?.[1]) {
267
- const candidate = cleanCandidate(cuedSlashMatch[1]);
268
- if (candidate && !isFileExt(candidate)) {
269
- return candidate;
270
- }
271
- }
272
- for (const m of text.matchAll(/\b([a-zA-Z0-9][a-zA-Z0-9_.-]{0,80}\/[a-zA-Z0-9][a-zA-Z0-9_.-]{0,120})\b/g)) {
273
- const candidate = cleanCandidate(m[1] || '');
274
- if (candidate && !isFileExt(candidate)) {
275
- return candidate;
276
- }
277
- }
278
- const explicitQuotedMatch = text.match(
279
- /(?:\bskill_id|\bskill)(?:\s*[:=]\s*|\s+)(?:the\s+)?[`"']([^`"'\n\r]{2,120})[`"']/i
280
- );
281
- if (explicitQuotedMatch?.[1]) {
282
- const candidate = cleanCandidate(explicitQuotedMatch[1]);
283
- if (candidate) return candidate;
284
- }
285
- const bareMatch = text.match(
286
- /(?:\bskill_id\s*[:=]\s*|\bskill\s*[:=]\s*|\bskill\s+(?:called\s+|named\s+)?)([a-zA-Z0-9][a-zA-Z0-9_.-]{1,120})/i
287
- );
288
- if (bareMatch?.[1]) {
289
- const candidate = cleanCandidate(bareMatch[1]);
290
- if (candidate) return candidate;
291
- }
292
- return '';
293
- }
294
-
295
- export function isDirectGameTask(text: string): boolean {
296
- return isDirectGameTaskDecision(text);
297
- }
298
-
299
- export function isProviderPlanOrQuotaRefusal(text: string): boolean {
300
- if (!text || typeof text !== 'string') return false;
301
- const trimmed = text.trim();
302
- if (!trimmed || trimmed.length > 320) return false;
303
- if (/^upgrade your plan to continue\.?$/i.test(trimmed)) return true;
304
- return /\b(upgrade your plan to continue|insufficient[_ ]quota|credit balance is too low|billing hard limit|quota exceeded for|plan limit reached|subscription required to continue)\b/i.test(trimmed);
305
- }
306
-
307
- /**
308
- * Detects when an agent response is an intermediate mid-task progress note or
309
- * transition announcement (e.g. "Real assets verified. Writing the Tesla-style
310
- * redesign now." or "Let me look at the newer assets... Pulling their real
311
- * stills and confirming embeddability.") rather than a finished answer.
312
- */
313
- export function isMidTaskProgressText(text: string): boolean {
314
- if (!text || typeof text !== 'string') return false;
315
- const trimmed = text.trim();
316
- if (!trimmed || trimmed.length > 480) return false;
317
-
318
- const lower = trimmed.toLowerCase();
319
- if (
320
- lower.includes('?') ||
321
- lower.includes('let me know') ||
322
- lower.includes('how can i help') ||
323
- lower.includes('how may i help') ||
324
- lower.includes('how can i assist') ||
325
- lower.includes('what would you like') ||
326
- lower.includes('what can i help') ||
327
- lower.includes('feel free to')
328
- ) {
329
- return false;
330
- }
331
-
332
- if (trimmed.includes('```')) return false;
333
-
334
- const sentences = trimmed
335
- .split(/(?:(?<=[.!])\s+|\n+)/)
336
- .map(s => s.trim())
337
- .filter(Boolean);
338
- const lastSentence = (sentences[sentences.length - 1] || trimmed).trim();
339
- const lastLower = lastSentence.toLowerCase();
340
-
341
- if (trimmed.length <= 280 && (trimmed.endsWith(':') || trimmed.endsWith('...') || trimmed.endsWith('…'))) {
342
- return true;
343
- }
344
-
345
- const intentPrefixes = [
346
- 'let me ',
347
- "i'll ",
348
- 'i will ',
349
- 'now i ',
350
- 'now let me ',
351
- "now i'll ",
352
- 'now i will ',
353
- 'next, i ',
354
- 'next i ',
355
- "next, i'll ",
356
- "next i'll ",
357
- 'first, i ',
358
- 'first i ',
359
- 'let us ',
360
- "let's ",
361
- 'i shall ',
362
- 'we will ',
363
- "we'll ",
364
- 'i am going to ',
365
- "i'm going to ",
366
- 'going to '
367
- ];
368
- if (intentPrefixes.some(prefix => lastLower.startsWith(prefix) || (trimmed.length <= 280 && lower.startsWith(prefix)))) {
369
- if (!/\b(?:task completed|all done|everything is ready|finished|complete\.)\b/i.test(lastSentence)) {
370
- return true;
371
- }
372
- }
373
-
374
- const gerundStart = /^(?:now\s+|next,?\s+|currently\s+|still\s+)?(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|setting up|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting|installing|opening|switching|retrying|continuing)\b/i;
375
- if (gerundStart.test(lastSentence) && lastSentence.length <= 220) {
376
- return true;
377
- }
378
-
379
- const actionNowSuffix = /\b(?:writing|pulling|checking|inspecting|building|creating|updating|applying|implementing|generating|fetching|downloading|testing|running|fixing|configuring|refactoring|adding|modifying|replacing|launching|starting|verifying|confirming|reading|searching|analyzing|preparing|compiling|rendering|extracting)\b[^.!?\n]{1,120}\b(?:now|next)\.?$/i;
380
- if (actionNowSuffix.test(lastSentence)) {
381
- return true;
382
- }
383
-
384
- return false;
385
- }
386
-
387
218
  const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your capabilities are the tools actually available in this session. Never invent a capability or claim an action occurred without evidence.
388
219
 
389
220
  ${PEER_COLLABORATION_POLICY}
@@ -708,11 +539,19 @@ export class AgentLoop {
708
539
  ? options.workspaceRoot
709
540
  : process.cwd();
710
541
  this.autonomyOverride = null;
542
+ this.providerOverride = typeof options.provider === 'string' && options.provider.trim()
543
+ ? options.provider.trim()
544
+ : null;
545
+ this.modelOverride = typeof options.model === 'string' && options.model.trim()
546
+ ? options.model.trim()
547
+ : null;
711
548
  this.approvalScope = options.approvalScope && typeof options.approvalScope.isAlwaysAllowed === 'function'
712
549
  ? options.approvalScope
713
550
  : processApprovalScope;
714
551
 
715
552
  this.config = loadConfig();
553
+ if (this.providerOverride) this.config.provider = this.providerOverride;
554
+ if (this.modelOverride) this.config.model = this.modelOverride;
716
555
  this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
717
556
 
718
557
  // Retire spilled tool outputs past their retention window. Fire-and-forget
@@ -1721,6 +1560,8 @@ export class AgentLoop {
1721
1560
  updateTierLimits() {
1722
1561
  this.config = loadConfig();
1723
1562
  if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
1563
+ if (this.providerOverride) this.config.provider = this.providerOverride;
1564
+ if (this.modelOverride) this.config.model = this.modelOverride;
1724
1565
  if (typeof this.initializeProvider === 'function') {
1725
1566
  const nextProvider = this.initializeProvider();
1726
1567
  if (nextProvider) {
@@ -5274,69 +5115,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
5274
5115
 
5275
5116
  // V5: Classify errors for intelligent retry decisions
5276
5117
  classifyError(error: any) {
5277
- if (error?.code === 'PROVIDER_NO_PROGRESS') return 'fatal';
5278
- if (error?.code === 'AGY_NATIVE_ACTION_DENIED'
5279
- || error?.code === 'AGY_NATIVE_ACTION_BUDGET'
5280
- || error?.code === 'AGY_DESKTOP_TASK_LIMIT') return 'fatal';
5281
- // A provider may have charged for completed steps before the turn failed.
5282
- // Replaying that turn can repeat actions and spend the same tokens again.
5283
- const spent = Number(error?.partialUsage?.promptTokens || 0)
5284
- + Number(error?.partialUsage?.completionTokens || 0);
5285
- if (spent > 0) return 'fatal';
5286
- const msg = (typeof error === 'string' ? error : error?.message || '').toLowerCase();
5287
-
5288
- if (error?.name === 'OpenRouterPrivacyConstraintError'
5289
- || msg.includes('matching the privacy policy')
5290
- || msg.includes('data_collection=')) {
5291
- return 'fatal';
5292
- }
5293
- if (msg.includes('free usage limit') || msg.includes('subscribe to opencode') || msg.includes('opencode.ai/go') || msg.includes('insufficient_quota') || msg.includes('credit balance is too low')) {
5294
- return 'fatal';
5295
- }
5296
- if (msg.includes('syntax') || msg.includes('unexpected token') || msg.includes('invalid json')) {
5297
- return 'syntax_error';
5298
- }
5299
- if (msg.includes('enoent') || msg.includes('no such file') || msg.includes('not found') || msg.includes('does not exist')) {
5300
- return 'path_not_found';
5301
- }
5302
- if (msg.includes('econnrefused') || msg.includes('econnreset') || msg.includes('etimedout') || msg.includes('fetch failed') || msg.includes('network')) {
5303
- return "network_error";
5304
- }
5305
- if (msg.includes('rate limit') || msg.includes('429') || msg.includes('too many requests') || msg.includes('quota')) {
5306
- return 'rate_limit';
5307
- }
5308
- if (msg.includes('eacces') || msg.includes('permission denied') || msg.includes('eperm')) {
5309
- return 'permission_denied';
5310
- }
5311
- if (msg.includes('401') || msg.includes('403') || msg.includes('unauthorized') || msg.includes('api key')) {
5312
- return 'auth_error';
5313
- }
5314
- if (msg.includes('400') || msg.includes('invalid_parameter') || msg.includes('invalid_request') || msg.includes('required property') || msg.includes('bad request')) {
5315
- return 'invalid_request_error';
5316
- }
5317
- if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
5318
- return 'fatal';
5319
- }
5320
- if (error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError) {
5321
- return 'fatal';
5322
- }
5323
-
5324
- return 'unknown_error';
5118
+ return classifyAgentError(error);
5325
5119
  }
5326
5120
 
5327
5121
  // V5: Provide actionable retry hints per error type
5328
5122
  getRetryHint(errorType: string) {
5329
- const hints: Record<string, string> = {
5330
- 'syntax_error': 'Check your command syntax or JSON structure. Ensure quotes are balanced.',
5331
- 'path_not_found': 'The file or directory does not exist. Use fs.list to verify the path first, or create it with fs.write/mkdir.',
5332
- ["network_error"]: "Network connectivity issue. Wait a moment and retry. If persistent, check if the URL is correct.",
5333
- 'rate_limit': 'API rate limit hit. Wait 5-10 seconds before retrying.',
5334
- 'permission_denied': 'Permission denied. Check if the path is within allowed workspace paths. Try a different directory.',
5335
- 'auth_error': 'Authentication failed. Do NOT retry — the API key may be invalid.',
5336
- 'invalid_request_error': 'API request format error (400 Bad Request). Do NOT retry — check model parameter compliance.',
5337
- 'unknown_error': 'An unexpected error occurred. Try a different approach entirely.'
5338
- };
5339
- return hints[errorType] || hints['unknown_error'];
5123
+ return getRetryHintForError(errorType);
5340
5124
  }
5341
5125
 
5342
5126
  async runPreToolUse(toolName: string, args: any, toolCallId: string) {
@@ -5364,98 +5148,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
5364
5148
  }
5365
5149
 
5366
5150
  // V5: Validate tool call arguments before execution
5367
-
5368
5151
  validateToolArgs(toolName: string, args: any) {
5369
- if (!args || typeof args !== 'object') {
5370
- return 'Tool arguments must be a JSON object';
5371
- }
5372
-
5373
- const baseDir = this.workspaceRoot || process.cwd();
5374
- const resolveOne = (raw: string): string | null => {
5375
- const val = raw.trim();
5376
- if (!val || /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(val)) {
5377
- return null;
5378
- }
5379
- if (val === '~' || val.startsWith('~/') || val.startsWith('~\\')) {
5380
- return val.replace(/^~(?=$|[\\/])/, os.homedir());
5381
- }
5382
- if (!path.isAbsolute(val)) {
5383
- return path.resolve(baseDir, val);
5384
- }
5385
- return val;
5386
- };
5387
-
5388
- // 1. File operations must have absolute paths (fs_read_skill uses skill-relative file_path)
5389
- const nonPathTargetTools = new Set(['vision_inspect_ui', 'astryx_oracle', 'desktop_act']);
5390
- if (toolName !== 'fs_read_skill') {
5391
- const pathFields = [
5392
- 'path', 'searchPath', 'cwd', 'directory',
5393
- 'source', 'destination', 'file_path', 'filePath', 'filepath',
5394
- 'targetFile', 'outputFile', 'outputPath',
5395
- ...(nonPathTargetTools.has(toolName) ? [] : ['target'])
5396
- ];
5397
- for (const field of pathFields) {
5398
- if (args[field] && typeof args[field] === 'string') {
5399
- const resolved = resolveOne(args[field]);
5400
- if (resolved !== null) {
5401
- args[field] = resolved;
5402
- }
5403
- }
5404
- }
5405
- if (Array.isArray(args.target_directories)) {
5406
- args.target_directories = args.target_directories.map((entry: unknown) => {
5407
- if (typeof entry !== 'string') return entry;
5408
- return resolveOne(entry) ?? entry;
5409
- });
5410
- }
5411
- }
5412
-
5413
- // 2. Terminal commands must have a command string
5414
- if ((toolName === 'sysRun' || toolName === 'sysRunBg') && !args.command) {
5415
- return 'Missing required "command" argument';
5416
- }
5417
-
5418
- // 3. File write must have a path AND content.
5419
- //
5420
- // These branches were dead: canonicalToolName() (called on every tool name
5421
- // before this runs) normalises '.'→'_', so `toolName` is 'fs_write', never
5422
- // 'fs.write'. The old 'fs.write' / 'codebase.search' / 'web.search' literals
5423
- // could never match, so the model's missing-argument mistakes reached the
5424
- // tool as runtime exceptions instead of a corrective message. Matched on the
5425
- // canonical names now, and fs_write's `content` is actually checked (the old
5426
- // comment said "must have content" but the code only looked at `path`).
5427
- if (toolName === 'fs_write' && !args.path) {
5428
- return 'Missing required "path" argument';
5429
- }
5430
- if (toolName === 'fs_write' && args.content === undefined) {
5431
- return 'Missing required "content" argument';
5432
- }
5433
-
5434
- // 4. Search must have a query
5435
- if ((toolName === 'codebase_search' || toolName === 'web_search') && !args.query) {
5436
- return 'Missing required "query" argument';
5437
- }
5438
-
5439
- // 5. Tool search must have a query, pack, or names array
5440
- if (toolName === 'tool_search') {
5441
- const q = typeof args.query === 'string'
5442
- ? args.query.trim()
5443
- : (Array.isArray(args.query) ? args.query.map(String).join(' ').trim() : '');
5444
- const p = typeof args.pack === 'string' ? args.pack.trim() : '';
5445
- const n = Array.isArray(args.names) && args.names.length > 0;
5446
- if (!q && !p && !n) {
5447
- return 'Missing required "query" or "pack" argument';
5448
- }
5449
- }
5450
-
5451
- // 6. Skill reader must have a non-empty skill_id
5452
- if (toolName === 'fs_read_skill') {
5453
- const sid = typeof args.skill_id === 'string' ? args.skill_id.trim() : '';
5454
- if (!sid) {
5455
- return 'Missing required "skill_id" argument';
5456
- }
5457
- }
5458
-
5459
- return null; // No validation errors
5152
+ return validateAndNormalizeToolArgs(toolName, args, this.workspaceRoot || process.cwd());
5460
5153
  }
5461
5154
  }
package/src/autoUpdate.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // causyne.com installer. A source checkout is never rewritten. Commands are
5
5
  // passed as argv arrays with shell disabled, and the only accepted package is
6
6
  // the public @causyne/agent package from the npm registry.
7
+ import crypto from 'node:crypto';
7
8
  import fs from 'node:fs';
8
9
  import path from 'node:path';
9
10
  import { fileURLToPath } from 'node:url';
@@ -11,6 +12,8 @@ import { spawnSync } from 'node:child_process';
11
12
  import { UI } from './utils/cli_ui.js';
12
13
  import { causyneHome } from './utils/paths.js';
13
14
  import { getPackageVersion } from './version.js';
15
+ import { probeOsSandbox, resolveOsSandboxMode } from './tools/osSandbox.js';
16
+ import { probeOsKeychain, resolveKeychainMode } from './osKeychain.js';
14
17
  const PACKAGE_NAME = '@causyne/agent';
15
18
  const REGISTRY_LATEST = 'https://registry.npmjs.org/@causyne%2fagent/latest';
16
19
  const DEFAULT_CHECK_INTERVAL_MS = 0; // A bare 'causyne' checks the published version on every launch
@@ -140,23 +143,110 @@ function writeState(state, options = {}) {
140
143
  // Update state is an optimisation. Failure must never stop the CLI.
141
144
  }
142
145
  }
143
- export async function latestPackageVersion(options = {}) {
146
+ const SRI_PATTERN = /^(sha512|sha384|sha256)-([A-Za-z0-9+/]+={0,2})$/;
147
+ function isOfficialRegistryHttpsUrl(rawUrl) {
148
+ if (typeof rawUrl !== 'string' || !rawUrl.trim())
149
+ return false;
150
+ try {
151
+ const parsed = new URL(rawUrl.trim());
152
+ return parsed.protocol === 'https:' && parsed.hostname === 'registry.npmjs.org';
153
+ }
154
+ catch {
155
+ return false;
156
+ }
157
+ }
158
+ /**
159
+ * Verifies constant-time SRI integrity (`sha512-...`, `sha384-...`, or `sha256-...`)
160
+ * of a downloaded tarball buffer against the registry-declared integrity string.
161
+ */
162
+ export function verifyTarballIntegrity(data, expectedIntegrity) {
163
+ if (!Buffer.isBuffer(data) || typeof expectedIntegrity !== 'string')
164
+ return false;
165
+ const match = expectedIntegrity.trim().match(SRI_PATTERN);
166
+ if (!match)
167
+ return false;
168
+ const algorithm = match[1];
169
+ const expectedDigest = Buffer.from(match[2], 'base64');
170
+ const actualDigest = crypto.createHash(algorithm).update(data).digest();
171
+ if (expectedDigest.length !== actualDigest.length)
172
+ return false;
173
+ return crypto.timingSafeEqual(expectedDigest, actualDigest);
174
+ }
175
+ /**
176
+ * Validates npm registry metadata for `@causyne/agent`, enforcing official HTTPS
177
+ * tarball origin, valid SRI integrity format, and optional Sigstore provenance
178
+ * attestation checks (`requireProvenance` or `CAUSYNE_REQUIRE_PROVENANCE=1`).
179
+ */
180
+ export function verifyRegistryMetadataIntegrity(metadata, options = {}) {
181
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
182
+ throw new Error('npm registry returned invalid package metadata');
183
+ }
184
+ const record = metadata;
185
+ if (record.name !== PACKAGE_NAME || typeof record.version !== 'string' || !versionParts(record.version)) {
186
+ throw new Error('npm registry returned invalid package metadata');
187
+ }
188
+ let tarballUrl;
189
+ let integrity;
190
+ let attestationUrl;
191
+ let provenanceVerified = false;
192
+ if (record.dist !== undefined) {
193
+ if (!record.dist || typeof record.dist !== 'object' || Array.isArray(record.dist)) {
194
+ throw new Error('npm registry returned malformed dist metadata');
195
+ }
196
+ if (record.dist.tarball !== undefined) {
197
+ if (!isOfficialRegistryHttpsUrl(record.dist.tarball)) {
198
+ throw new Error('npm registry tarball URL must use HTTPS on registry.npmjs.org');
199
+ }
200
+ tarballUrl = record.dist.tarball;
201
+ }
202
+ if (record.dist.integrity !== undefined) {
203
+ if (typeof record.dist.integrity !== 'string' || !SRI_PATTERN.test(record.dist.integrity.trim())) {
204
+ throw new Error('npm registry returned malformed SRI integrity digest');
205
+ }
206
+ integrity = record.dist.integrity.trim();
207
+ }
208
+ if (record.dist.attestations && typeof record.dist.attestations === 'object') {
209
+ const attUrl = record.dist.attestations.url;
210
+ const predicateType = record.dist.attestations.provenance?.predicateType;
211
+ if (isOfficialRegistryHttpsUrl(attUrl) && typeof predicateType === 'string' && predicateType.length > 0) {
212
+ attestationUrl = attUrl;
213
+ provenanceVerified = true;
214
+ }
215
+ }
216
+ }
217
+ if (options.requireProvenance && !provenanceVerified) {
218
+ throw new Error(`Release ${PACKAGE_NAME}@${record.version} lacks verified npm provenance attestations.`);
219
+ }
220
+ return {
221
+ version: record.version,
222
+ ...(tarballUrl ? { tarballUrl } : {}),
223
+ ...(integrity ? { integrity } : {}),
224
+ provenanceVerified,
225
+ ...(attestationUrl ? { attestationUrl } : {})
226
+ };
227
+ }
228
+ export async function latestPackageRelease(options = {}) {
144
229
  const fetchImpl = options.fetchImpl || globalThis.fetch;
145
230
  if (typeof fetchImpl !== 'function')
146
231
  throw new Error('This Node.js runtime has no fetch implementation.');
147
232
  const timeoutMs = options.timeoutMs || 3500;
148
233
  const signal = options.signal || AbortSignal.timeout(timeoutMs);
234
+ const env = options.env || process.env;
235
+ const requireProvenance = options.requireProvenance
236
+ ?? (env.CAUSYNE_REQUIRE_PROVENANCE === '1' || env.CAUSYNE_REQUIRE_PROVENANCE === 'true');
149
237
  const response = await fetchImpl(REGISTRY_LATEST, {
150
238
  headers: { accept: 'application/json', 'user-agent': `causyne/${getPackageVersion()}` },
239
+ redirect: 'error',
151
240
  signal
152
241
  });
153
242
  if (!response.ok)
154
243
  throw new Error(`npm registry returned HTTP ${response.status}`);
155
- const metadata = (await response.json());
156
- if (metadata.name !== PACKAGE_NAME || !versionParts(metadata.version)) {
157
- throw new Error('npm registry returned invalid package metadata');
158
- }
159
- return metadata.version;
244
+ const metadata = await response.json();
245
+ return verifyRegistryMetadataIntegrity(metadata, { requireProvenance });
246
+ }
247
+ export async function latestPackageVersion(options = {}) {
248
+ const release = await latestPackageRelease(options);
249
+ return release.version;
160
250
  }
161
251
  function installLatest(info, options = {}) {
162
252
  if (!info.prefix) {
@@ -195,8 +285,14 @@ function installLatest(info, options = {}) {
195
285
  }
196
286
  export async function checkForUpdate(options = {}) {
197
287
  const current = options.currentVersion || getPackageVersion();
198
- const latest = await latestPackageVersion(options);
199
- return { current, latest, available: compareVersions(latest, current) > 0 };
288
+ const release = await latestPackageRelease(options);
289
+ return {
290
+ current,
291
+ latest: release.version,
292
+ available: compareVersions(release.version, current) > 0,
293
+ provenanceVerified: release.provenanceVerified,
294
+ ...(release.integrity ? { integrity: release.integrity } : {})
295
+ };
200
296
  }
201
297
  export async function runSelfUpdate(verbose = false, options = {}) {
202
298
  const info = installationInfo(options);
@@ -277,14 +373,21 @@ export async function diagnoseInstallation(options = {}) {
277
373
  };
278
374
  }
279
375
  export function formatDoctorReport(status, runtime = process) {
376
+ const sandboxCap = probeOsSandbox();
377
+ const sandboxMode = resolveOsSandboxMode(runtime.env);
378
+ const keychainCap = probeOsKeychain({ env: runtime.env });
379
+ const keychainMode = resolveKeychainMode(runtime.env);
280
380
  const rows = [
281
381
  `Version : ${status.current || 'unknown'}`,
282
382
  `Latest : ${status.latest || `unavailable (${status.error || 'unknown error'})`}`,
383
+ `Provenance : ${status.provenanceVerified ? 'verified (npm Sigstore attestation)' : 'unverified / not reported'}`,
283
384
  `Installation : ${status.type}`,
284
385
  `Package root : ${status.packageRoot}`,
285
386
  `NPM command : ${status.npmCommand}`,
286
387
  `Node.js : ${runtime.version}`,
287
388
  `Platform : ${runtime.platform} ${runtime.arch}`,
389
+ `OS Sandbox : ${sandboxMode.mode} (backend: ${sandboxCap.backend}${sandboxCap.available ? ', available' : ', unavailable'})`,
390
+ `OS Keychain : ${keychainMode} (backend: ${keychainCap.backend}${keychainCap.available ? ', available' : ', unavailable'})`,
288
391
  `Auto updates : ${status.autoUpdates ? 'enabled' : 'disabled'}`,
289
392
  `Workspace : ${runtime.cwd()}`
290
393
  ];