@causyne/agent 1.20.87 → 1.20.90

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/src/agentLoop.js CHANGED
@@ -3,6 +3,9 @@ import { NetworkHostGuard } from './reliability/networkHostGuard.js';
3
3
  import { inspectRequestedImageAssets } from './reliability/assetEvidence.js';
4
4
  import { inspect3DVisualEvidence } from './reliability/visualEvidence.js';
5
5
  import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/entitlements.js';
6
+ import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
+ import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
+ import { normalizeAgentFailure } from './agent/providerFailure.js';
6
9
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
7
10
  import { createHash, randomUUID } from 'crypto';
8
11
  import { execFileSync } from 'node:child_process';
@@ -1575,12 +1578,19 @@ export class AgentLoop {
1575
1578
  }
1576
1579
  this.maxCircuitBreaker = this.maxSteps;
1577
1580
  }
1578
- // CAUSYNE_ENTITLEMENT_V1: outer lifecycle wrapper, no agent-orchestration rewrite.
1581
+ // AgentLoop lifetime is single-flight: a second run must not reset an active
1582
+ // tool batch, its cancellation signal, message history, or approval scope.
1579
1583
  async run() {
1584
+ if (this._runActive === true) {
1585
+ this.emitEvent({ type: 'error', message: 'AgentLoop is already running. Wait for the current task to finish before starting another.' });
1586
+ return;
1587
+ }
1588
+ this._runActive = true;
1589
+ this.stopRequested = false;
1580
1590
  this.rearmAbortController();
1581
1591
  this._causyneTaskOutcome = 'incomplete';
1582
- this._networkHostGuard.reset();
1583
1592
  const gate = getProcessEntitlementGate();
1593
+ let gateStarted = false;
1584
1594
  const onEntitlementBlocked = (error) => {
1585
1595
  if (this.stopRequested)
1586
1596
  return;
@@ -1589,30 +1599,65 @@ export class AgentLoop {
1589
1599
  this.emitEvent({ type: 'error', message: `Causyne access paused: ${explanation} No workspace state was removed.` });
1590
1600
  };
1591
1601
  try {
1592
- await gate.begin(onEntitlementBlocked);
1593
- }
1594
- catch (error) {
1595
- if (error instanceof EntitlementAccessError) {
1596
- this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1602
+ this._networkHostGuard.reset();
1603
+ // Resume a saved session safely. Missing tool results are explicit
1604
+ // uncertainties, never fabricated executions or successes.
1605
+ const restored = repairUnansweredToolCalls(this.messages);
1606
+ if (restored.repaired > 0) {
1607
+ this.memoryManager.saveHistory(this.messages);
1608
+ this.notice(`Recovered ${restored.repaired} unanswered tool-call record(s). Workspace effects were not assumed.`, 'warning');
1609
+ }
1610
+ if (restored.unresolved > 0) {
1611
+ this.emitEvent({ type: 'error', message: `Conversation history contains ${restored.unresolved} ambiguous tool-call identifier(s). The task was stopped before sending invalid history to the provider.` });
1597
1612
  return;
1598
1613
  }
1599
- throw error;
1600
- }
1601
- this._entitlementGate = gate;
1602
- try {
1614
+ try {
1615
+ await gate.begin(onEntitlementBlocked);
1616
+ gateStarted = true;
1617
+ }
1618
+ catch (error) {
1619
+ if (error instanceof EntitlementAccessError) {
1620
+ this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1621
+ return;
1622
+ }
1623
+ throw error;
1624
+ }
1625
+ // A user can press Esc while the licensing network request is pending.
1626
+ // Never allow the inner task to clear that cancellation after an await.
1627
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1628
+ return;
1629
+ this._entitlementGate = gate;
1603
1630
  await this.runLicensedCore();
1604
1631
  }
1605
1632
  finally {
1606
1633
  this._entitlementGate = null;
1607
- gate.end(onEntitlementBlocked);
1634
+ try {
1635
+ if (gateStarted)
1636
+ gate.end(onEntitlementBlocked);
1637
+ }
1638
+ finally {
1639
+ try {
1640
+ const settled = repairUnansweredToolCalls(this.messages);
1641
+ if (settled.repaired > 0)
1642
+ this.memoryManager.saveHistory(this.messages);
1643
+ if (settled.unresolved > 0)
1644
+ this.debugLog(`Unresolved tool-call identifiers: ${settled.unresolved}`);
1645
+ }
1646
+ catch (error) {
1647
+ this.debugLog(`Tool-turn recovery failed: ${error instanceof Error ? error.message : String(error)}`);
1648
+ }
1649
+ finally {
1650
+ this._runActive = false;
1651
+ }
1652
+ }
1608
1653
  }
1609
1654
  }
1610
1655
  /** Existing run implementation moved unchanged; wrapper above owns metering. */
1611
1656
  async runLicensedCore() {
1612
- this.stopRequested = false;
1613
- // A task that was stopped must not poison the next one — see
1614
- // rearmAbortController(). This has to happen before any tool can run.
1615
- this.rearmAbortController();
1657
+ // run() owns cancellation and rearms it exactly once, before awaiting
1658
+ // entitlements. A second reset here could resurrect an aborted task.
1659
+ if (this.stopRequested || this.abortController?.signal?.aborted)
1660
+ return;
1616
1661
  // Refresh tier limits on every task run
1617
1662
  this.updateTierLimits();
1618
1663
  if (!this.llm) {
@@ -2783,14 +2828,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2783
2828
  }
2784
2829
  // If the peer attempted to call a registered Causyne host tool through its
2785
2830
  // native channel and provided complete, valid arguments (or we can infer
2786
- // the target for reverse_engineering), auto-bridge it into response.toolCalls
2787
- // BEFORE recording assistantMsg so it executes immediately in this turn.
2831
+ // the target for reverse_engineering or tool_search), auto-bridge it into
2832
+ // response.toolCalls BEFORE recording assistantMsg so it executes immediately in this turn.
2788
2833
  if ((!response.toolCalls || response.toolCalls.length === 0) && response.toolRoutingError) {
2789
2834
  const rawName = response.toolRoutingError.tool;
2790
2835
  const resolved = resolveTool(rawName);
2791
2836
  if (resolved) {
2792
2837
  const canonical = canonicalToolName(rawName);
2793
2838
  const toolParams = { ...(response.toolRoutingError.parameters || {}) };
2839
+ delete toolParams.__pendingStub;
2840
+ delete toolParams.__invalidTool;
2794
2841
  if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2795
2842
  const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2796
2843
  if (promptMatch && promptMatch[1]) {
@@ -2799,6 +2846,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2799
2846
  toolParams.action = 'inspect';
2800
2847
  }
2801
2848
  }
2849
+ if (canonical === 'tool_search' && !toolParams.query && !toolParams.pack && (!Array.isArray(toolParams.names) || toolParams.names.length === 0)) {
2850
+ const prompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2851
+ const match = prompt.match(/(?:capabilities\s+matching|matching|query[:\s]+|search(?:ing)?\s+for(?:\s+capabilities\s+matching)?|for)\s+([^\n\r]+)/i);
2852
+ if (match && match[1]) {
2853
+ const inferred = match[1].trim().replace(/^["'`]+|["'`.,;]+$/g, '');
2854
+ if (inferred) {
2855
+ toolParams.query = inferred;
2856
+ }
2857
+ }
2858
+ }
2802
2859
  if (Object.keys(toolParams).length > 0 && !this.validateToolArgs(canonical, toolParams)) {
2803
2860
  response.toolCalls = [{
2804
2861
  id: `host_auto_${Date.now()}`,
@@ -2842,6 +2899,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2842
2899
  // Add assistant response to history. This is the ONLY place the turn is
2843
2900
  // recorded — the completion and guard branches below used to push it a
2844
2901
  // second time, duplicating every finished turn in the history.
2902
+ // Validate tool IDs before adding history or launching prefetch. A
2903
+ // duplicate ID can alias two results and corrupt the provider protocol.
2904
+ const batchAudit = validateToolCallBatch(response.toolCalls);
2905
+ if (!batchAudit.valid) {
2906
+ this.emitEvent({ type: 'error', message: `Provider tool-call protocol error: ${batchAudit.reason}. No host tools from this batch were executed.` });
2907
+ auditLog.log({ event: 'invalid_tool_call_batch', taskId: this.taskId, reason: batchAudit.reason });
2908
+ this.memoryManager.saveHistory(this.messages);
2909
+ break;
2910
+ }
2845
2911
  const hasToolCalls = Boolean(response.toolCalls && response.toolCalls.length > 0);
2846
2912
  const assistantMsg = {
2847
2913
  role: 'assistant',
@@ -4482,6 +4548,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4482
4548
  }
4483
4549
  }
4484
4550
  catch (e) {
4551
+ // Providers sometimes throw strings or plain objects. Normalize once
4552
+ // without discarding partial usage or typed provider error codes.
4553
+ e = normalizeAgentFailure(e);
4485
4554
  // A peer can fail after completing billable steps. Charge those steps
4486
4555
  // once even when no final result was returned, including action and
4487
4556
  // wall-clock limits, before deciding whether recovery is possible.
@@ -4707,15 +4776,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4707
4776
  */
4708
4777
  async backoff(attempt) {
4709
4778
  const delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
4710
- await new Promise((resolve) => {
4711
- const timer = setTimeout(resolve, delay);
4712
- if (timer.unref)
4713
- timer.unref();
4714
- const signal = this.abortController && this.abortController.signal;
4715
- if (signal) {
4716
- signal.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
4717
- }
4718
- });
4779
+ await waitForAbortableDelay(delay, this.abortController?.signal);
4719
4780
  }
4720
4781
  // V5: Classify errors for intelligent retry decisions
4721
4782
  classifyError(error) {
@@ -4844,6 +4905,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4844
4905
  if ((toolName === 'codebase_search' || toolName === 'web_search') && !args.query) {
4845
4906
  return 'Missing required "query" argument';
4846
4907
  }
4908
+ // 5. Tool search must have a query, pack, or names array
4909
+ if (toolName === 'tool_search') {
4910
+ const q = typeof args.query === 'string' ? args.query.trim() : '';
4911
+ const p = typeof args.pack === 'string' ? args.pack.trim() : '';
4912
+ const n = Array.isArray(args.names) && args.names.length > 0;
4913
+ if (!q && !p && !n) {
4914
+ return 'Missing required "query" or "pack" argument';
4915
+ }
4916
+ }
4847
4917
  return null; // No validation errors
4848
4918
  }
4849
4919
  }
package/src/agentLoop.ts CHANGED
@@ -3,6 +3,9 @@ import { NetworkHostGuard } from './reliability/networkHostGuard.js';
3
3
  import { inspectRequestedImageAssets } from './reliability/assetEvidence.js';
4
4
  import { inspect3DVisualEvidence } from './reliability/visualEvidence.js';
5
5
  import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/entitlements.js';
6
+ import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
7
+ import { waitForAbortableDelay } from './agent/abortableDelay.js';
8
+ import { normalizeAgentFailure } from './agent/providerFailure.js';
6
9
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
7
10
  import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
8
11
  import { createHash, randomUUID } from 'crypto';
@@ -1642,12 +1645,19 @@ export class AgentLoop {
1642
1645
  this.maxCircuitBreaker = this.maxSteps;
1643
1646
  }
1644
1647
 
1645
- // CAUSYNE_ENTITLEMENT_V1: outer lifecycle wrapper, no agent-orchestration rewrite.
1648
+ // AgentLoop lifetime is single-flight: a second run must not reset an active
1649
+ // tool batch, its cancellation signal, message history, or approval scope.
1646
1650
  async run() {
1651
+ if (this._runActive === true) {
1652
+ this.emitEvent({ type: 'error', message: 'AgentLoop is already running. Wait for the current task to finish before starting another.' });
1653
+ return;
1654
+ }
1655
+ this._runActive = true;
1656
+ this.stopRequested = false;
1647
1657
  this.rearmAbortController();
1648
1658
  this._causyneTaskOutcome = 'incomplete';
1649
- this._networkHostGuard.reset();
1650
1659
  const gate = getProcessEntitlementGate();
1660
+ let gateStarted = false;
1651
1661
  const onEntitlementBlocked = (error: unknown): void => {
1652
1662
  if (this.stopRequested) return;
1653
1663
  this.stopRequested = true;
@@ -1655,29 +1665,56 @@ export class AgentLoop {
1655
1665
  this.emitEvent({ type: 'error', message: `Causyne access paused: ${explanation} No workspace state was removed.` });
1656
1666
  };
1657
1667
  try {
1658
- await gate.begin(onEntitlementBlocked);
1659
- } catch (error: unknown) {
1660
- if (error instanceof EntitlementAccessError) {
1661
- this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1668
+ this._networkHostGuard.reset();
1669
+ // Resume a saved session safely. Missing tool results are explicit
1670
+ // uncertainties, never fabricated executions or successes.
1671
+ const restored = repairUnansweredToolCalls(this.messages);
1672
+ if (restored.repaired > 0) {
1673
+ this.memoryManager.saveHistory(this.messages);
1674
+ this.notice(`Recovered ${restored.repaired} unanswered tool-call record(s). Workspace effects were not assumed.`, 'warning');
1675
+ }
1676
+ if (restored.unresolved > 0) {
1677
+ this.emitEvent({ type: 'error', message: `Conversation history contains ${restored.unresolved} ambiguous tool-call identifier(s). The task was stopped before sending invalid history to the provider.` });
1662
1678
  return;
1663
1679
  }
1664
- throw error;
1665
- }
1666
- this._entitlementGate = gate;
1667
- try {
1680
+ try {
1681
+ await gate.begin(onEntitlementBlocked);
1682
+ gateStarted = true;
1683
+ } catch (error: unknown) {
1684
+ if (error instanceof EntitlementAccessError) {
1685
+ this.emitEvent({ type: 'error', message: `Causyne access unavailable: ${error.message}` });
1686
+ return;
1687
+ }
1688
+ throw error;
1689
+ }
1690
+ // A user can press Esc while the licensing network request is pending.
1691
+ // Never allow the inner task to clear that cancellation after an await.
1692
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1693
+ this._entitlementGate = gate;
1668
1694
  await this.runLicensedCore();
1669
1695
  } finally {
1670
1696
  this._entitlementGate = null;
1671
- gate.end(onEntitlementBlocked);
1697
+ try {
1698
+ if (gateStarted) gate.end(onEntitlementBlocked);
1699
+ } finally {
1700
+ try {
1701
+ const settled = repairUnansweredToolCalls(this.messages);
1702
+ if (settled.repaired > 0) this.memoryManager.saveHistory(this.messages);
1703
+ if (settled.unresolved > 0) this.debugLog(`Unresolved tool-call identifiers: ${settled.unresolved}`);
1704
+ } catch (error: unknown) {
1705
+ this.debugLog(`Tool-turn recovery failed: ${error instanceof Error ? error.message : String(error)}`);
1706
+ } finally {
1707
+ this._runActive = false;
1708
+ }
1709
+ }
1672
1710
  }
1673
1711
  }
1674
1712
 
1675
1713
  /** Existing run implementation moved unchanged; wrapper above owns metering. */
1676
1714
  async runLicensedCore() {
1677
- this.stopRequested = false;
1678
- // A task that was stopped must not poison the next one — see
1679
- // rearmAbortController(). This has to happen before any tool can run.
1680
- this.rearmAbortController();
1715
+ // run() owns cancellation and rearms it exactly once, before awaiting
1716
+ // entitlements. A second reset here could resurrect an aborted task.
1717
+ if (this.stopRequested || this.abortController?.signal?.aborted) return;
1681
1718
  // Refresh tier limits on every task run
1682
1719
  this.updateTierLimits();
1683
1720
  if (!this.llm) {
@@ -2899,14 +2936,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
2899
2936
 
2900
2937
  // If the peer attempted to call a registered Causyne host tool through its
2901
2938
  // native channel and provided complete, valid arguments (or we can infer
2902
- // the target for reverse_engineering), auto-bridge it into response.toolCalls
2903
- // BEFORE recording assistantMsg so it executes immediately in this turn.
2939
+ // the target for reverse_engineering or tool_search), auto-bridge it into
2940
+ // response.toolCalls BEFORE recording assistantMsg so it executes immediately in this turn.
2904
2941
  if ((!response.toolCalls || response.toolCalls.length === 0) && response.toolRoutingError) {
2905
2942
  const rawName = response.toolRoutingError.tool;
2906
2943
  const resolved = resolveTool(rawName);
2907
2944
  if (resolved) {
2908
2945
  const canonical = canonicalToolName(rawName);
2909
2946
  const toolParams: Record<string, unknown> = { ...(response.toolRoutingError.parameters || {}) };
2947
+ delete toolParams.__pendingStub;
2948
+ delete toolParams.__invalidTool;
2949
+
2910
2950
  if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2911
2951
  const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2912
2952
  if (promptMatch && promptMatch[1]) {
@@ -2914,6 +2954,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
2914
2954
  if (!toolParams.action) toolParams.action = 'inspect';
2915
2955
  }
2916
2956
  }
2957
+
2958
+ if (canonical === 'tool_search' && !toolParams.query && !toolParams.pack && (!Array.isArray(toolParams.names) || toolParams.names.length === 0)) {
2959
+ const prompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2960
+ const match = prompt.match(/(?:capabilities\s+matching|matching|query[:\s]+|search(?:ing)?\s+for(?:\s+capabilities\s+matching)?|for)\s+([^\n\r]+)/i);
2961
+ if (match && match[1]) {
2962
+ const inferred = match[1].trim().replace(/^["'`]+|["'`.,;]+$/g, '');
2963
+ if (inferred) {
2964
+ toolParams.query = inferred;
2965
+ }
2966
+ }
2967
+ }
2968
+
2917
2969
  if (Object.keys(toolParams).length > 0 && !this.validateToolArgs(canonical, toolParams)) {
2918
2970
  response.toolCalls = [{
2919
2971
  id: `host_auto_${Date.now()}`,
@@ -2958,6 +3010,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2958
3010
  // Add assistant response to history. This is the ONLY place the turn is
2959
3011
  // recorded — the completion and guard branches below used to push it a
2960
3012
  // second time, duplicating every finished turn in the history.
3013
+ // Validate tool IDs before adding history or launching prefetch. A
3014
+ // duplicate ID can alias two results and corrupt the provider protocol.
3015
+ const batchAudit = validateToolCallBatch(response.toolCalls);
3016
+ if (!batchAudit.valid) {
3017
+ this.emitEvent({ type: 'error', message: `Provider tool-call protocol error: ${batchAudit.reason}. No host tools from this batch were executed.` });
3018
+ auditLog.log({ event: 'invalid_tool_call_batch', taskId: this.taskId, reason: batchAudit.reason });
3019
+ this.memoryManager.saveHistory(this.messages);
3020
+ break;
3021
+ }
2961
3022
  const hasToolCalls = Boolean(response.toolCalls && response.toolCalls.length > 0);
2962
3023
  const assistantMsg: any = {
2963
3024
  role: 'assistant',
@@ -4724,6 +4785,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4724
4785
  }
4725
4786
 
4726
4787
  } catch (e: any) {
4788
+ // Providers sometimes throw strings or plain objects. Normalize once
4789
+ // without discarding partial usage or typed provider error codes.
4790
+ e = normalizeAgentFailure(e);
4727
4791
  // A peer can fail after completing billable steps. Charge those steps
4728
4792
  // once even when no final result was returned, including action and
4729
4793
  // wall-clock limits, before deciding whether recovery is possible.
@@ -4963,14 +5027,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4963
5027
  */
4964
5028
  async backoff(attempt: number) {
4965
5029
  const delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
4966
- await new Promise<void>((resolve) => {
4967
- const timer = setTimeout(resolve, delay);
4968
- if (timer.unref) timer.unref();
4969
- const signal = this.abortController && this.abortController.signal;
4970
- if (signal) {
4971
- signal.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
4972
- }
4973
- });
5030
+ await waitForAbortableDelay(delay, this.abortController?.signal);
4974
5031
  }
4975
5032
 
4976
5033
  // V5: Classify errors for intelligent retry decisions
@@ -5108,6 +5165,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
5108
5165
  return 'Missing required "query" argument';
5109
5166
  }
5110
5167
 
5168
+ // 5. Tool search must have a query, pack, or names array
5169
+ if (toolName === 'tool_search') {
5170
+ const q = typeof args.query === 'string' ? args.query.trim() : '';
5171
+ const p = typeof args.pack === 'string' ? args.pack.trim() : '';
5172
+ const n = Array.isArray(args.names) && args.names.length > 0;
5173
+ if (!q && !p && !n) {
5174
+ return 'Missing required "query" or "pack" argument';
5175
+ }
5176
+ }
5177
+
5111
5178
  return null; // No validation errors
5112
5179
  }
5113
5180
  }
@@ -480,10 +480,16 @@ export class AcpProvider extends LLMProvider {
480
480
  if (isInvalidPseudoTool) {
481
481
  const requested = typeof input.tool === 'string' ? input.tool : '';
482
482
  if (!this.toolRoutingError && requested && normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === requested)) {
483
- const rawArgs = (input.args && typeof input.args === 'object') ? input.args
483
+ let rawArgs = (input.args && typeof input.args === 'object') ? input.args
484
484
  : (input.parameters && typeof input.parameters === 'object') ? input.parameters
485
- : (earlier?.parameters && typeof earlier.parameters === 'object') ? earlier.parameters
485
+ : (earlier?.parameters && typeof earlier.parameters === 'object' && !earlier.parameters.__pendingStub) ? earlier.parameters
486
486
  : undefined;
487
+ if (rawArgs && typeof rawArgs === 'object') {
488
+ const cleanArgs = { ...rawArgs };
489
+ delete cleanArgs.__pendingStub;
490
+ delete cleanArgs.__invalidTool;
491
+ rawArgs = Object.keys(cleanArgs).length > 0 ? cleanArgs : undefined;
492
+ }
487
493
  this.toolRoutingError = {
488
494
  tool: requested,
489
495
  message: typeof input.error === 'string' ? input.error : 'Host tool requested through the peer-native channel',
@@ -481,10 +481,16 @@ export class AcpProvider extends LLMProvider {
481
481
  if (isInvalidPseudoTool) {
482
482
  const requested = typeof input.tool === 'string' ? input.tool : '';
483
483
  if (!this.toolRoutingError && requested && normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === requested)) {
484
- const rawArgs = (input.args && typeof input.args === 'object') ? input.args
484
+ let rawArgs = (input.args && typeof input.args === 'object') ? input.args
485
485
  : (input.parameters && typeof input.parameters === 'object') ? input.parameters
486
- : (earlier?.parameters && typeof earlier.parameters === 'object') ? earlier.parameters
486
+ : (earlier?.parameters && typeof earlier.parameters === 'object' && !earlier.parameters.__pendingStub) ? earlier.parameters
487
487
  : undefined;
488
+ if (rawArgs && typeof rawArgs === 'object') {
489
+ const cleanArgs = { ...rawArgs };
490
+ delete (cleanArgs as any).__pendingStub;
491
+ delete (cleanArgs as any).__invalidTool;
492
+ rawArgs = Object.keys(cleanArgs).length > 0 ? cleanArgs : undefined;
493
+ }
488
494
  this.toolRoutingError = {
489
495
  tool: requested,
490
496
  message: typeof input.error === 'string' ? input.error : 'Host tool requested through the peer-native channel',
package/src/sandbox.js CHANGED
@@ -4,6 +4,7 @@ import { isIP } from 'node:net';
4
4
  import { loadConfig } from './config.js';
5
5
  import { isDevEmulator } from './devMode.js';
6
6
  import { validateBrowserActSandbox } from './browser/causyneBrowser.js';
7
+ import { isPhysicalPathAllowed } from './agent/workspaceBoundary.js';
7
8
 
8
9
 
9
10
  function maskQuotedSpans(text) {
@@ -374,49 +375,14 @@ export class Sandbox {
374
375
  }
375
376
 
376
377
  isPathAllowed(targetPath) {
377
- // Expand ~
378
- let resolved = targetPath;
379
- if (resolved.startsWith('~/')) {
380
- resolved = path.join(os.homedir(), resolved.slice(2));
381
- }
382
- resolved = path.resolve(resolved);
383
-
384
- // V5: Block system-critical paths BEFORE checking allowed paths (OS Protection)
385
- const isWindows = os.platform() === 'win32';
386
- let isBlocked = false;
387
-
388
- if (isWindows) {
389
- const WIN_BLOCKED = ['C:\\Windows', 'C:\\Program Files', 'C:\\ProgramData'];
390
- isBlocked = WIN_BLOCKED.some(blocked => resolved.toLowerCase().startsWith(blocked.toLowerCase()));
391
- } else {
392
- const UNIX_BLOCKED = ['/etc', '/usr/bin', '/usr/sbin', '/sbin', '/bin', '/System', '/private/var'];
393
- isBlocked = UNIX_BLOCKED.some(blocked => resolved.startsWith(blocked));
394
- }
395
-
396
- if (isBlocked) {
397
- return false;
398
- }
399
-
400
- // V6: Override workspace limits if grantAllAccess is active
401
- if (this.grantAllAccess) {
402
- return true;
403
- }
404
-
405
- // Check if resolved path is inside any allowed workspace path.
406
- //
407
- // L2 (local-path audit): this was a bare `resolved.startsWith(allowedBase)`,
408
- // which is a STRING prefix test, not a PATH containment test. With the scope
409
- // set to /Users/x/Projects it also accepted /Users/x/Projects-secret and
410
- // /Users/x/ProjectsBACKUP — any sibling whose name merely begins with the
411
- // workspace name. The separator check is what makes it a directory boundary.
412
- return this.workspacePaths.some(workspace => {
413
- let allowedBase = workspace;
414
- if (allowedBase.startsWith('~/')) {
415
- allowedBase = path.join(os.homedir(), allowedBase.slice(2));
416
- }
417
- allowedBase = path.resolve(allowedBase);
418
- return resolved === allowedBase || resolved.startsWith(allowedBase + path.sep);
419
- });
378
+ if (typeof targetPath !== 'string' || targetPath.length === 0) return false;
379
+ const expand = (value) => value.startsWith('~/')
380
+ ? path.join(os.homedir(), value.slice(2)) : value;
381
+ const workspaces = Array.isArray(this.workspacePaths)
382
+ ? this.workspacePaths.filter(item => typeof item === 'string').map(expand) : [];
383
+ // Resolve physical ancestors, including symlinks, before checking the scope.
384
+ // Missing destination files remain possible inside a valid workspace.
385
+ return isPhysicalPathAllowed(expand(targetPath), workspaces, this.grantAllAccess === true);
420
386
  }
421
387
 
422
388
  isInternalUrl(urlString, { allowLoopback = false } = {}) {