@causyne/agent 1.20.74 → 1.20.75

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.74",
3
+ "version": "1.20.75",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -27,7 +27,7 @@ import { lookupPlan, recordPlan, recordPlanAsync, recordMiss, renderPlanHint, to
27
27
  import { routedConfig } from './modelRouter.js';
28
28
  import { assessStep, isThrashing } from './uncertainty.js';
29
29
  import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
30
- import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks } from './implementationPlan.js';
30
+ import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks, extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from './implementationPlan.js';
31
31
  import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
32
32
  import { AGENT_USER_POLICY } from './agentPolicy.js';
33
33
  import { VFETracker } from './vfeTracker.js';
@@ -2748,6 +2748,33 @@ You are operating in a text-and-code modality without direct image pixel renderi
2748
2748
  }
2749
2749
  }
2750
2750
  }
2751
+ // General Provider Tool Call Extraction Fallback:
2752
+ // If the model did not emit structured API tool calls, but output <tool_call> envelopes
2753
+ // in its content text, extract them so tools execute seamlessly across all general providers.
2754
+ if ((!response.toolCalls || response.toolCalls.length === 0) && response.content) {
2755
+ const textCalls = [];
2756
+ let callIndex = 0;
2757
+ for (const parsed of extractToolCallJsonObjects(response.content)) {
2758
+ const fnObj = parsed.function && typeof parsed.function === 'object'
2759
+ ? parsed.function
2760
+ : null;
2761
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
2762
+ if (!name)
2763
+ continue;
2764
+ const rawArgs = resolveToolCallEnvelopeArguments(parsed);
2765
+ textCalls.push({
2766
+ id: `text_call_${Date.now()}_${callIndex++}`,
2767
+ type: 'function',
2768
+ function: {
2769
+ name: canonicalToolName(name),
2770
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
2771
+ }
2772
+ });
2773
+ }
2774
+ if (textCalls.length > 0) {
2775
+ response.toolCalls = textCalls;
2776
+ }
2777
+ }
2751
2778
  // Add assistant response to history. This is the ONLY place the turn is
2752
2779
  // recorded — the completion and guard branches below used to push it a
2753
2780
  // second time, duplicating every finished turn in the history.
package/src/agentLoop.ts CHANGED
@@ -39,7 +39,7 @@ import {
39
39
  import { routedConfig } from './modelRouter.js';
40
40
  import { assessStep, isThrashing } from './uncertainty.js';
41
41
  import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
42
- import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks } from './implementationPlan.js';
42
+ import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks, extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from './implementationPlan.js';
43
43
  import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
44
44
  import { AGENT_USER_POLICY } from './agentPolicy.js';
45
45
  import { VFETracker } from './vfeTracker.js';
@@ -2867,6 +2867,33 @@ You are operating in a text-and-code modality without direct image pixel renderi
2867
2867
  }
2868
2868
  }
2869
2869
 
2870
+ // General Provider Tool Call Extraction Fallback:
2871
+ // If the model did not emit structured API tool calls, but output <tool_call> envelopes
2872
+ // in its content text, extract them so tools execute seamlessly across all general providers.
2873
+ if ((!response.toolCalls || response.toolCalls.length === 0) && response.content) {
2874
+ const textCalls: any[] = [];
2875
+ let callIndex = 0;
2876
+ for (const parsed of extractToolCallJsonObjects(response.content)) {
2877
+ const fnObj = parsed.function && typeof parsed.function === 'object'
2878
+ ? (parsed.function as Record<string, unknown>)
2879
+ : null;
2880
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
2881
+ if (!name) continue;
2882
+ const rawArgs = resolveToolCallEnvelopeArguments(parsed);
2883
+ textCalls.push({
2884
+ id: `text_call_${Date.now()}_${callIndex++}`,
2885
+ type: 'function',
2886
+ function: {
2887
+ name: canonicalToolName(name),
2888
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
2889
+ }
2890
+ });
2891
+ }
2892
+ if (textCalls.length > 0) {
2893
+ response.toolCalls = textCalls;
2894
+ }
2895
+ }
2896
+
2870
2897
  // Add assistant response to history. This is the ONLY place the turn is
2871
2898
  // recorded — the completion and guard branches below used to push it a
2872
2899
  // second time, duplicating every finished turn in the history.
@@ -224,8 +224,8 @@ export function renderAuthPage(options) {
224
224
  `<span class="meta-val lime">${options.model || OPENROUTER_FREE_MODEL}</span>` +
225
225
  '</div>' +
226
226
  '<div class="meta-row" style="margin-bottom:8px;">' +
227
- '<span class="meta-label">Privacy Guard</span>' +
228
- '<span class="meta-val" style="color:#9da697;">provider.data_collection = &quot;deny&quot;</span>' +
227
+ '<span class="meta-label">Routing Tier</span>' +
228
+ '<span class="meta-val" style="color:#9da697;">Community Free Inference (Zero Cost)</span>' +
229
229
  '</div>' +
230
230
  '<div class="meta-row">' +
231
231
  '<span class="meta-label">Protocol</span>' +
@@ -272,8 +272,8 @@ export function renderAuthPage(options: RenderAuthPageOptions): string {
272
272
  `<span class="meta-val lime">${options.model || OPENROUTER_FREE_MODEL}</span>` +
273
273
  '</div>' +
274
274
  '<div class="meta-row" style="margin-bottom:8px;">' +
275
- '<span class="meta-label">Privacy Guard</span>' +
276
- '<span class="meta-val" style="color:#9da697;">provider.data_collection = &quot;deny&quot;</span>' +
275
+ '<span class="meta-label">Routing Tier</span>' +
276
+ '<span class="meta-val" style="color:#9da697;">Community Free Inference (Zero Cost)</span>' +
277
277
  '</div>' +
278
278
  '<div class="meta-row">' +
279
279
  '<span class="meta-label">Protocol</span>' +
@@ -7,6 +7,7 @@ import { capabilityDirectory, ensureCapability, loadCapabilityPackage } from '..
7
7
  import { resolveBrowserRuntime } from './browserRuntime.js';
8
8
  import { assertPublicWebUrl, assertBrowserNavigableUrl } from './urlPolicy.js';
9
9
  import { windowSnapshot } from './snapshotWindow.js';
10
+ import { searchPublicWeb } from './searchProviders.js';
10
11
  const NAVIGATION_TIMEOUT_MS = 30_000;
11
12
  const ACTION_TIMEOUT_MS = 12_000;
12
13
  const IFRAME_SNAPSHOT_TIMEOUT_MS = 3_000;
@@ -721,27 +722,43 @@ export class CausyneBrowser {
721
722
  const cleaned = String(query ?? '').trim();
722
723
  if (!cleaned || cleaned.length > 1_000)
723
724
  throw new Error('Search query must contain 1-1000 characters');
724
- await this.start();
725
- const state = await this.activeTab();
726
- const targets = [
727
- { engine: 'google', url: `https://www.google.com/search?q=${encodeURIComponent(cleaned)}` },
728
- { engine: 'duckduckgo', url: `https://duckduckgo.com/html/?q=${encodeURIComponent(cleaned)}` },
729
- { engine: 'bing', url: `https://www.bing.com/search?q=${encodeURIComponent(cleaned)}` }
730
- ];
731
725
  const failures = [];
732
- for (const target of targets) {
733
- try {
734
- await this.navigate(state, target.url);
735
- await state.page.waitForTimeout(250);
736
- const extracted = await state.page.evaluate(SEARCH_EXTRACT_SCRIPT);
737
- if (Array.isArray(extracted) && extracted.length > 0) {
738
- return extracted.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
726
+ try {
727
+ await this.start();
728
+ const state = await this.activeTab();
729
+ const targets = [
730
+ { engine: 'google', url: `https://www.google.com/search?q=${encodeURIComponent(cleaned)}` },
731
+ { engine: 'duckduckgo', url: `https://duckduckgo.com/html/?q=${encodeURIComponent(cleaned)}` },
732
+ { engine: 'bing', url: `https://www.bing.com/search?q=${encodeURIComponent(cleaned)}` }
733
+ ];
734
+ for (const target of targets) {
735
+ try {
736
+ await this.navigate(state, target.url);
737
+ await state.page.waitForTimeout(500);
738
+ const extracted = await state.page.evaluate(SEARCH_EXTRACT_SCRIPT);
739
+ if (Array.isArray(extracted) && extracted.length > 0) {
740
+ return extracted.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
741
+ }
742
+ failures.push(`${target.engine}: no organic results`);
743
+ }
744
+ catch (error) {
745
+ failures.push(`${target.engine}: ${errorMessage(error)}`);
739
746
  }
740
- failures.push(`${target.engine}: no organic results`);
741
747
  }
742
- catch (error) {
743
- failures.push(`${target.engine}: ${errorMessage(error)}`);
748
+ }
749
+ catch (browserErr) {
750
+ failures.push(`browser_session: ${errorMessage(browserErr)}`);
751
+ }
752
+ // High-reliability search fallback: query lightweight search providers (DuckDuckGo HTML / Bing RSS) directly
753
+ try {
754
+ const publicResults = await searchPublicWeb(cleaned);
755
+ if (Array.isArray(publicResults) && publicResults.length > 0) {
756
+ return publicResults.slice(0, MAX_SEARCH_RESULTS);
744
757
  }
758
+ failures.push('public_web: no organic results');
759
+ }
760
+ catch (pubErr) {
761
+ failures.push(`public_web: ${errorMessage(pubErr)}`);
745
762
  }
746
763
  throw new Error(`Search providers exhausted. ${failures.join('; ')}`);
747
764
  }
@@ -12,6 +12,7 @@ import {
12
12
  import { resolveBrowserRuntime, type PreparedBrowserRuntime } from './browserRuntime.js';
13
13
  import { assertPublicWebUrl, assertBrowserNavigableUrl } from './urlPolicy.js';
14
14
  import { windowSnapshot, type SnapshotWindow } from './snapshotWindow.js';
15
+ import { searchPublicWeb } from './searchProviders.js';
15
16
 
16
17
  const NAVIGATION_TIMEOUT_MS = 30_000;
17
18
  const ACTION_TIMEOUT_MS = 12_000;
@@ -989,27 +990,44 @@ export class CausyneBrowser {
989
990
  async search(query: string): Promise<SearchResult[]> {
990
991
  const cleaned = String(query ?? '').trim();
991
992
  if (!cleaned || cleaned.length > 1_000) throw new Error('Search query must contain 1-1000 characters');
992
- await this.start();
993
- const state = await this.activeTab();
994
- const targets = [
995
- { engine: 'google', url: `https://www.google.com/search?q=${encodeURIComponent(cleaned)}` },
996
- { engine: 'duckduckgo', url: `https://duckduckgo.com/html/?q=${encodeURIComponent(cleaned)}` },
997
- { engine: 'bing', url: `https://www.bing.com/search?q=${encodeURIComponent(cleaned)}` }
998
- ];
999
993
  const failures: string[] = [];
1000
- for (const target of targets) {
1001
- try {
1002
- await this.navigate(state, target.url);
1003
- await state.page.waitForTimeout(250);
1004
- const extracted = await state.page.evaluate<Array<Omit<SearchResult, 'engine'>>>(SEARCH_EXTRACT_SCRIPT);
1005
- if (Array.isArray(extracted) && extracted.length > 0) {
1006
- return extracted.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
994
+
995
+ try {
996
+ await this.start();
997
+ const state = await this.activeTab();
998
+ const targets = [
999
+ { engine: 'google', url: `https://www.google.com/search?q=${encodeURIComponent(cleaned)}` },
1000
+ { engine: 'duckduckgo', url: `https://duckduckgo.com/html/?q=${encodeURIComponent(cleaned)}` },
1001
+ { engine: 'bing', url: `https://www.bing.com/search?q=${encodeURIComponent(cleaned)}` }
1002
+ ];
1003
+ for (const target of targets) {
1004
+ try {
1005
+ await this.navigate(state, target.url);
1006
+ await state.page.waitForTimeout(500);
1007
+ const extracted = await state.page.evaluate<Array<Omit<SearchResult, 'engine'>>>(SEARCH_EXTRACT_SCRIPT);
1008
+ if (Array.isArray(extracted) && extracted.length > 0) {
1009
+ return extracted.slice(0, MAX_SEARCH_RESULTS).map(result => ({ ...result, engine: target.engine }));
1010
+ }
1011
+ failures.push(`${target.engine}: no organic results`);
1012
+ } catch (error) {
1013
+ failures.push(`${target.engine}: ${errorMessage(error)}`);
1007
1014
  }
1008
- failures.push(`${target.engine}: no organic results`);
1009
- } catch (error) {
1010
- failures.push(`${target.engine}: ${errorMessage(error)}`);
1011
1015
  }
1016
+ } catch (browserErr) {
1017
+ failures.push(`browser_session: ${errorMessage(browserErr)}`);
1018
+ }
1019
+
1020
+ // High-reliability search fallback: query lightweight search providers (DuckDuckGo HTML / Bing RSS) directly
1021
+ try {
1022
+ const publicResults = await searchPublicWeb(cleaned);
1023
+ if (Array.isArray(publicResults) && publicResults.length > 0) {
1024
+ return publicResults.slice(0, MAX_SEARCH_RESULTS);
1025
+ }
1026
+ failures.push('public_web: no organic results');
1027
+ } catch (pubErr) {
1028
+ failures.push(`public_web: ${errorMessage(pubErr)}`);
1012
1029
  }
1030
+
1013
1031
  throw new Error(`Search providers exhausted. ${failures.join('; ')}`);
1014
1032
  }
1015
1033
 
@@ -9,6 +9,7 @@
9
9
  import { LLMProvider } from './base.js';
10
10
  import { canonicalModelId } from '../modelIds.js';
11
11
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
12
+ import { extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
12
13
  export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
13
14
  export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
14
15
  export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
@@ -140,7 +141,8 @@ export class OpenRouterProvider extends LLMProvider {
140
141
  if (status === 400 || status === 404) {
141
142
  if (lowered.includes('data_collection') || lowered.includes('no provider available') || lowered.includes('data policy')) {
142
143
  throw new OpenRouterPrivacyConstraintError(`No free provider is currently available matching the privacy policy (data_collection='${this.dataCollection}'). ` +
143
- `You can retry shortly, or inspect your preference with /openrouter status.`);
144
+ `Free community models on OpenRouter typically require data collection. ` +
145
+ `Run "/openrouter allow" to permit free model routing, or inspect your preference with /openrouter status.`);
144
146
  }
145
147
  if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
146
148
  throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.');
@@ -162,6 +164,12 @@ export class OpenRouterProvider extends LLMProvider {
162
164
  toolCalls = this.normalizeToolCalls(message.tool_calls);
163
165
  reasoningContent = message.reasoning || message.reasoning_content || '';
164
166
  }
167
+ if (toolCalls.length === 0 && content) {
168
+ const extracted = this.extractToolCallsFromContent(content);
169
+ if (extracted.length > 0) {
170
+ toolCalls = extracted;
171
+ }
172
+ }
165
173
  const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
166
174
  const usage = this.normalizeUsage(rawUsage);
167
175
  return {
@@ -270,6 +278,12 @@ export class OpenRouterProvider extends LLMProvider {
270
278
  });
271
279
  }
272
280
  }
281
+ if (toolCalls.length === 0 && content) {
282
+ const extracted = this.extractToolCallsFromContent(content);
283
+ if (extracted.length > 0) {
284
+ toolCalls.push(...extracted);
285
+ }
286
+ }
273
287
  const usage = this.normalizeUsage(rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
274
288
  return {
275
289
  content,
@@ -278,6 +292,33 @@ export class OpenRouterProvider extends LLMProvider {
278
292
  usage
279
293
  };
280
294
  }
295
+ /**
296
+ * Extract tool calls embedded in content text (e.g. <tool_call> envelopes).
297
+ */
298
+ extractToolCallsFromContent(text) {
299
+ const calls = [];
300
+ if (!text || typeof text !== 'string')
301
+ return calls;
302
+ let index = 0;
303
+ for (const parsed of extractToolCallJsonObjects(text)) {
304
+ const fnObj = parsed.function && typeof parsed.function === 'object'
305
+ ? parsed.function
306
+ : null;
307
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
308
+ if (!name)
309
+ continue;
310
+ const rawArgs = resolveToolCallEnvelopeArguments(parsed);
311
+ calls.push({
312
+ id: `call_text_${Date.now()}_${index++}`,
313
+ type: 'function',
314
+ function: {
315
+ name,
316
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
317
+ }
318
+ });
319
+ }
320
+ return calls;
321
+ }
281
322
  /**
282
323
  * Safely normalize tool calls from provider message.
283
324
  */
@@ -10,6 +10,7 @@
10
10
  import { LLMProvider } from './base.js';
11
11
  import { canonicalModelId } from '../modelIds.js';
12
12
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
13
+ import { extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
13
14
  import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
14
15
 
15
16
  export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
@@ -167,7 +168,8 @@ export class OpenRouterProvider extends LLMProvider {
167
168
  if (lowered.includes('data_collection') || lowered.includes('no provider available') || lowered.includes('data policy')) {
168
169
  throw new OpenRouterPrivacyConstraintError(
169
170
  `No free provider is currently available matching the privacy policy (data_collection='${this.dataCollection}'). ` +
170
- `You can retry shortly, or inspect your preference with /openrouter status.`
171
+ `Free community models on OpenRouter typically require data collection. ` +
172
+ `Run "/openrouter allow" to permit free model routing, or inspect your preference with /openrouter status.`
171
173
  );
172
174
  }
173
175
  if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
@@ -196,6 +198,13 @@ export class OpenRouterProvider extends LLMProvider {
196
198
  reasoningContent = message.reasoning || message.reasoning_content || '';
197
199
  }
198
200
 
201
+ if (toolCalls.length === 0 && content) {
202
+ const extracted = this.extractToolCallsFromContent(content);
203
+ if (extracted.length > 0) {
204
+ toolCalls = extracted;
205
+ }
206
+ }
207
+
199
208
  const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
200
209
  const usage: ChatResponseUsage = this.normalizeUsage(rawUsage);
201
210
 
@@ -310,6 +319,13 @@ export class OpenRouterProvider extends LLMProvider {
310
319
  }
311
320
  }
312
321
 
322
+ if (toolCalls.length === 0 && content) {
323
+ const extracted = this.extractToolCallsFromContent(content);
324
+ if (extracted.length > 0) {
325
+ toolCalls.push(...extracted);
326
+ }
327
+ }
328
+
313
329
  const usage: ChatResponseUsage = this.normalizeUsage(
314
330
  rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
315
331
  );
@@ -322,6 +338,32 @@ export class OpenRouterProvider extends LLMProvider {
322
338
  };
323
339
  }
324
340
 
341
+ /**
342
+ * Extract tool calls embedded in content text (e.g. <tool_call> envelopes).
343
+ */
344
+ private extractToolCallsFromContent(text: string): ChatResponseToolCall[] {
345
+ const calls: ChatResponseToolCall[] = [];
346
+ if (!text || typeof text !== 'string') return calls;
347
+ let index = 0;
348
+ for (const parsed of extractToolCallJsonObjects(text)) {
349
+ const fnObj = parsed.function && typeof parsed.function === 'object'
350
+ ? (parsed.function as Record<string, unknown>)
351
+ : null;
352
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
353
+ if (!name) continue;
354
+ const rawArgs = resolveToolCallEnvelopeArguments(parsed);
355
+ calls.push({
356
+ id: `call_text_${Date.now()}_${index++}`,
357
+ type: 'function',
358
+ function: {
359
+ name,
360
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
361
+ }
362
+ });
363
+ }
364
+ return calls;
365
+ }
366
+
325
367
  /**
326
368
  * Safely normalize tool calls from provider message.
327
369
  */
@@ -229,7 +229,7 @@ export const sysRun = {
229
229
  properties: {
230
230
  command: { type: 'string', description: 'The shell command to run' },
231
231
  cwd: { type: 'string', description: 'Working directory' },
232
- timeout: { type: 'number', description: 'Timeout in ms (default 60000)' }
232
+ timeout: { type: 'number', description: 'Execution timeout in milliseconds or seconds (e.g. 60 or 60000, default 60000ms). Values <= 600 are interpreted as seconds.' }
233
233
  },
234
234
  required: ['command']
235
235
  }
@@ -237,7 +237,29 @@ export const sysRun = {
237
237
  async execute(args, context = {}) {
238
238
  const rawCommand = (args?.command || '').trim();
239
239
  const cwd = args?.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
240
- const timeoutMs = args?.timeout || 60000;
240
+ let timeoutMs = 60000;
241
+ const rawTimeout = args?.timeout;
242
+ if (typeof rawTimeout === 'number' && Number.isFinite(rawTimeout) && rawTimeout > 0) {
243
+ timeoutMs = rawTimeout <= 600 ? Math.round(rawTimeout * 1000) : Math.round(rawTimeout);
244
+ }
245
+ else if (typeof rawTimeout === 'string') {
246
+ const match = rawTimeout.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m)?$/i);
247
+ if (match && match[1]) {
248
+ const val = parseFloat(match[1]);
249
+ const unit = (match[2] || '').toLowerCase();
250
+ if (unit === 'ms')
251
+ timeoutMs = Math.round(val);
252
+ else if (unit === 'm')
253
+ timeoutMs = Math.round(val * 60 * 1000);
254
+ else if (unit === 's')
255
+ timeoutMs = Math.round(val * 1000);
256
+ else
257
+ timeoutMs = val <= 600 ? Math.round(val * 1000) : Math.round(val);
258
+ }
259
+ }
260
+ if (timeoutMs < 1000) {
261
+ timeoutMs = 1000;
262
+ }
241
263
  const signal = context.signal;
242
264
  // A foreground server waits forever for requests. Keep launch-only turns
243
265
  // responsive and make it explicit that starting is not a readiness check.
@@ -299,7 +299,7 @@ export const sysRun = {
299
299
  properties: {
300
300
  command: { type: 'string', description: 'The shell command to run' },
301
301
  cwd: { type: 'string', description: 'Working directory' },
302
- timeout: { type: 'number', description: 'Timeout in ms (default 60000)' }
302
+ timeout: { type: 'number', description: 'Execution timeout in milliseconds or seconds (e.g. 60 or 60000, default 60000ms). Values <= 600 are interpreted as seconds.' }
303
303
  },
304
304
  required: ['command']
305
305
  }
@@ -308,7 +308,24 @@ export const sysRun = {
308
308
  async execute(args: SysRunArgs, context: SysRunContext = {}): Promise<SysRunResult> {
309
309
  const rawCommand = (args?.command || '').trim();
310
310
  const cwd = args?.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
311
- const timeoutMs = args?.timeout || 60000;
311
+ let timeoutMs = 60000;
312
+ const rawTimeout = (args as unknown as Record<string, unknown>)?.timeout;
313
+ if (typeof rawTimeout === 'number' && Number.isFinite(rawTimeout) && rawTimeout > 0) {
314
+ timeoutMs = rawTimeout <= 600 ? Math.round(rawTimeout * 1000) : Math.round(rawTimeout);
315
+ } else if (typeof rawTimeout === 'string') {
316
+ const match = rawTimeout.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m)?$/i);
317
+ if (match && match[1]) {
318
+ const val = parseFloat(match[1]);
319
+ const unit = (match[2] || '').toLowerCase();
320
+ if (unit === 'ms') timeoutMs = Math.round(val);
321
+ else if (unit === 'm') timeoutMs = Math.round(val * 60 * 1000);
322
+ else if (unit === 's') timeoutMs = Math.round(val * 1000);
323
+ else timeoutMs = val <= 600 ? Math.round(val * 1000) : Math.round(val);
324
+ }
325
+ }
326
+ if (timeoutMs < 1000) {
327
+ timeoutMs = 1000;
328
+ }
312
329
  const signal = context.signal;
313
330
 
314
331
  // A foreground server waits forever for requests. Keep launch-only turns
@@ -217,11 +217,17 @@ const PARAMETER_ALIASES = {
217
217
  filter: [
218
218
  'pattern', 'glob', 'regex', 'matching'
219
219
  ],
220
+ cwd: [
221
+ 'dir', 'directory', 'workdir', 'working_dir', 'workingDir', 'workingDirectory', 'path', 'folder'
222
+ ],
223
+ outputFile: [
224
+ 'output', 'out', 'output_file', 'destination', 'dest', 'target_file', 'file_path', 'file', 'target'
225
+ ],
220
226
  options: [
221
227
  'opts', 'config', 'settings', 'params'
222
228
  ],
223
229
  timeout: [
224
- 'timeoutMs', 'timeout_ms', 'timeoutSec', 'duration'
230
+ 'timeoutMs', 'timeout_ms', 'timeoutSec', 'timeout_seconds', 'duration', 'timeout_s', 'time_limit'
225
231
  ],
226
232
  url: [
227
233
  'link', 'href', 'endpoint', 'uri', 'target_url'
@@ -764,7 +770,25 @@ export function coerceArgumentTypes(toolName, args, schema) {
764
770
  if (expectedType === 'number' || expectedType === 'integer') {
765
771
  if (typeof val === 'string') {
766
772
  const trimmed = val.trim();
767
- if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
773
+ const timeMatch = (key === 'timeout' || key === 'timeoutMs' || key === 'timeout_ms' || key === 'duration')
774
+ ? trimmed.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m)?$/i)
775
+ : null;
776
+ if (timeMatch && timeMatch[1]) {
777
+ const rawVal = parseFloat(timeMatch[1]);
778
+ const unit = (timeMatch[2] || '').toLowerCase();
779
+ let ms = rawVal;
780
+ if (unit === 'ms')
781
+ ms = rawVal;
782
+ else if (unit === 'm')
783
+ ms = rawVal * 60 * 1000;
784
+ else if (unit === 's')
785
+ ms = rawVal * 1000;
786
+ else
787
+ ms = rawVal <= 600 ? rawVal * 1000 : rawVal;
788
+ modified[key] = expectedType === 'integer' ? Math.round(ms) : ms;
789
+ repairs.push(`Normalized time string "${val}" -> ${modified[key]}ms for parameter '${key}'`);
790
+ }
791
+ else if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
768
792
  const num = expectedType === 'integer' ? parseInt(trimmed, 10) : parseFloat(trimmed);
769
793
  if (!isNaN(num)) {
770
794
  modified[key] = num;
@@ -772,6 +796,12 @@ export function coerceArgumentTypes(toolName, args, schema) {
772
796
  }
773
797
  }
774
798
  }
799
+ else if (typeof val === 'number' && (key === 'timeout' || key === 'timeoutMs')) {
800
+ if (val > 0 && val <= 600) {
801
+ modified[key] = Math.round(val * 1000);
802
+ repairs.push(`Scaled timeout from seconds (${val}s) -> ${modified[key]}ms for parameter '${key}'`);
803
+ }
804
+ }
775
805
  else if (Array.isArray(val) && val.length === 1) {
776
806
  const item = val[0];
777
807
  if (typeof item === 'number') {
@@ -250,11 +250,17 @@ const PARAMETER_ALIASES: Record<string, string[]> = {
250
250
  filter: [
251
251
  'pattern', 'glob', 'regex', 'matching'
252
252
  ],
253
+ cwd: [
254
+ 'dir', 'directory', 'workdir', 'working_dir', 'workingDir', 'workingDirectory', 'path', 'folder'
255
+ ],
256
+ outputFile: [
257
+ 'output', 'out', 'output_file', 'destination', 'dest', 'target_file', 'file_path', 'file', 'target'
258
+ ],
253
259
  options: [
254
260
  'opts', 'config', 'settings', 'params'
255
261
  ],
256
262
  timeout: [
257
- 'timeoutMs', 'timeout_ms', 'timeoutSec', 'duration'
263
+ 'timeoutMs', 'timeout_ms', 'timeoutSec', 'timeout_seconds', 'duration', 'timeout_s', 'time_limit'
258
264
  ],
259
265
  url: [
260
266
  'link', 'href', 'endpoint', 'uri', 'target_url'
@@ -806,13 +812,31 @@ export function coerceArgumentTypes(
806
812
  if (expectedType === 'number' || expectedType === 'integer') {
807
813
  if (typeof val === 'string') {
808
814
  const trimmed = val.trim();
809
- if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
815
+ const timeMatch = (key === 'timeout' || key === 'timeoutMs' || key === 'timeout_ms' || key === 'duration')
816
+ ? trimmed.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m)?$/i)
817
+ : null;
818
+ if (timeMatch && timeMatch[1]) {
819
+ const rawVal = parseFloat(timeMatch[1]);
820
+ const unit = (timeMatch[2] || '').toLowerCase();
821
+ let ms = rawVal;
822
+ if (unit === 'ms') ms = rawVal;
823
+ else if (unit === 'm') ms = rawVal * 60 * 1000;
824
+ else if (unit === 's') ms = rawVal * 1000;
825
+ else ms = rawVal <= 600 ? rawVal * 1000 : rawVal;
826
+ modified[key] = expectedType === 'integer' ? Math.round(ms) : ms;
827
+ repairs.push(`Normalized time string "${val}" -> ${modified[key]}ms for parameter '${key}'`);
828
+ } else if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
810
829
  const num = expectedType === 'integer' ? parseInt(trimmed, 10) : parseFloat(trimmed);
811
830
  if (!isNaN(num)) {
812
831
  modified[key] = num;
813
832
  repairs.push(`Coerced string "${val}" -> number ${num} for parameter '${key}'`);
814
833
  }
815
834
  }
835
+ } else if (typeof val === 'number' && (key === 'timeout' || key === 'timeoutMs')) {
836
+ if (val > 0 && val <= 600) {
837
+ modified[key] = Math.round(val * 1000);
838
+ repairs.push(`Scaled timeout from seconds (${val}s) -> ${modified[key]}ms for parameter '${key}'`);
839
+ }
816
840
  } else if (Array.isArray(val) && val.length === 1) {
817
841
  const item = val[0];
818
842
  if (typeof item === 'number') {