@causyne/agent 1.20.87 → 1.20.91

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) {
@@ -2549,7 +2594,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2549
2594
  const recovery = this.timeMachine.observe(action.name, actionArgs, actionOutcome, coldObserver.getToolOutcomes(this.taskId));
2550
2595
  // Pause now, not at the end of a potentially long peer turn.
2551
2596
  // An abort is a yield checkpoint, not a user denial or task success.
2552
- if (recovery.kind === 'consent') {
2597
+ if (recovery.kind === 'consent' && action.name.toLowerCase() !== 'skill') {
2553
2598
  this._pendingConsent ??= { recovery, tool: action.name };
2554
2599
  nativeControl.abort();
2555
2600
  }
@@ -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,31 @@ 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
+ }
2859
+ if (canonical === 'fs_read_skill') {
2860
+ if (!toolParams.skill_id) {
2861
+ toolParams.skill_id = toolParams.id || toolParams.name || toolParams.skill || '';
2862
+ }
2863
+ if (!toolParams.skill_id) {
2864
+ const prompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2865
+ const match = prompt.match(/(?:skill|read)\s+([a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*)/i);
2866
+ if (match && match[1]) {
2867
+ toolParams.skill_id = match[1].trim();
2868
+ }
2869
+ }
2870
+ delete toolParams.id;
2871
+ delete toolParams.name;
2872
+ delete toolParams.skill;
2873
+ }
2802
2874
  if (Object.keys(toolParams).length > 0 && !this.validateToolArgs(canonical, toolParams)) {
2803
2875
  response.toolCalls = [{
2804
2876
  id: `host_auto_${Date.now()}`,
@@ -2842,6 +2914,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2842
2914
  // Add assistant response to history. This is the ONLY place the turn is
2843
2915
  // recorded — the completion and guard branches below used to push it a
2844
2916
  // second time, duplicating every finished turn in the history.
2917
+ // Validate tool IDs before adding history or launching prefetch. A
2918
+ // duplicate ID can alias two results and corrupt the provider protocol.
2919
+ const batchAudit = validateToolCallBatch(response.toolCalls);
2920
+ if (!batchAudit.valid) {
2921
+ this.emitEvent({ type: 'error', message: `Provider tool-call protocol error: ${batchAudit.reason}. No host tools from this batch were executed.` });
2922
+ auditLog.log({ event: 'invalid_tool_call_batch', taskId: this.taskId, reason: batchAudit.reason });
2923
+ this.memoryManager.saveHistory(this.messages);
2924
+ break;
2925
+ }
2845
2926
  const hasToolCalls = Boolean(response.toolCalls && response.toolCalls.length > 0);
2846
2927
  const assistantMsg = {
2847
2928
  role: 'assistant',
@@ -4482,6 +4563,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4482
4563
  }
4483
4564
  }
4484
4565
  catch (e) {
4566
+ // Providers sometimes throw strings or plain objects. Normalize once
4567
+ // without discarding partial usage or typed provider error codes.
4568
+ e = normalizeAgentFailure(e);
4485
4569
  // A peer can fail after completing billable steps. Charge those steps
4486
4570
  // once even when no final result was returned, including action and
4487
4571
  // wall-clock limits, before deciding whether recovery is possible.
@@ -4707,15 +4791,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4707
4791
  */
4708
4792
  async backoff(attempt) {
4709
4793
  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
- });
4794
+ await waitForAbortableDelay(delay, this.abortController?.signal);
4719
4795
  }
4720
4796
  // V5: Classify errors for intelligent retry decisions
4721
4797
  classifyError(error) {
@@ -4844,6 +4920,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
4844
4920
  if ((toolName === 'codebase_search' || toolName === 'web_search') && !args.query) {
4845
4921
  return 'Missing required "query" argument';
4846
4922
  }
4923
+ // 5. Tool search must have a query, pack, or names array
4924
+ if (toolName === 'tool_search') {
4925
+ const q = typeof args.query === 'string' ? args.query.trim() : '';
4926
+ const p = typeof args.pack === 'string' ? args.pack.trim() : '';
4927
+ const n = Array.isArray(args.names) && args.names.length > 0;
4928
+ if (!q && !p && !n) {
4929
+ return 'Missing required "query" or "pack" argument';
4930
+ }
4931
+ }
4847
4932
  return null; // No validation errors
4848
4933
  }
4849
4934
  }
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) {
@@ -2651,7 +2688,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2651
2688
  );
2652
2689
  // Pause now, not at the end of a potentially long peer turn.
2653
2690
  // An abort is a yield checkpoint, not a user denial or task success.
2654
- if (recovery.kind === 'consent') {
2691
+ if (recovery.kind === 'consent' && action.name.toLowerCase() !== 'skill') {
2655
2692
  this._pendingConsent ??= { recovery, tool: action.name };
2656
2693
  nativeControl.abort();
2657
2694
  } else if (!this._pendingConsent && recovery.kind === 'replan') {
@@ -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,34 @@ 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
+
2969
+ if (canonical === 'fs_read_skill') {
2970
+ if (!toolParams.skill_id) {
2971
+ toolParams.skill_id = toolParams.id || toolParams.name || toolParams.skill || '';
2972
+ }
2973
+ if (!toolParams.skill_id) {
2974
+ const prompt = (this.currentTaskPrompt || this.userPrompt || '').trim();
2975
+ const match = prompt.match(/(?:skill|read)\s+([a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*)/i);
2976
+ if (match && match[1]) {
2977
+ toolParams.skill_id = match[1].trim();
2978
+ }
2979
+ }
2980
+ delete toolParams.id;
2981
+ delete toolParams.name;
2982
+ delete toolParams.skill;
2983
+ }
2984
+
2917
2985
  if (Object.keys(toolParams).length > 0 && !this.validateToolArgs(canonical, toolParams)) {
2918
2986
  response.toolCalls = [{
2919
2987
  id: `host_auto_${Date.now()}`,
@@ -2958,6 +3026,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2958
3026
  // Add assistant response to history. This is the ONLY place the turn is
2959
3027
  // recorded — the completion and guard branches below used to push it a
2960
3028
  // second time, duplicating every finished turn in the history.
3029
+ // Validate tool IDs before adding history or launching prefetch. A
3030
+ // duplicate ID can alias two results and corrupt the provider protocol.
3031
+ const batchAudit = validateToolCallBatch(response.toolCalls);
3032
+ if (!batchAudit.valid) {
3033
+ this.emitEvent({ type: 'error', message: `Provider tool-call protocol error: ${batchAudit.reason}. No host tools from this batch were executed.` });
3034
+ auditLog.log({ event: 'invalid_tool_call_batch', taskId: this.taskId, reason: batchAudit.reason });
3035
+ this.memoryManager.saveHistory(this.messages);
3036
+ break;
3037
+ }
2961
3038
  const hasToolCalls = Boolean(response.toolCalls && response.toolCalls.length > 0);
2962
3039
  const assistantMsg: any = {
2963
3040
  role: 'assistant',
@@ -4724,6 +4801,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4724
4801
  }
4725
4802
 
4726
4803
  } catch (e: any) {
4804
+ // Providers sometimes throw strings or plain objects. Normalize once
4805
+ // without discarding partial usage or typed provider error codes.
4806
+ e = normalizeAgentFailure(e);
4727
4807
  // A peer can fail after completing billable steps. Charge those steps
4728
4808
  // once even when no final result was returned, including action and
4729
4809
  // wall-clock limits, before deciding whether recovery is possible.
@@ -4963,14 +5043,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4963
5043
  */
4964
5044
  async backoff(attempt: number) {
4965
5045
  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
- });
5046
+ await waitForAbortableDelay(delay, this.abortController?.signal);
4974
5047
  }
4975
5048
 
4976
5049
  // V5: Classify errors for intelligent retry decisions
@@ -5108,6 +5181,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
5108
5181
  return 'Missing required "query" argument';
5109
5182
  }
5110
5183
 
5184
+ // 5. Tool search must have a query, pack, or names array
5185
+ if (toolName === 'tool_search') {
5186
+ const q = typeof args.query === 'string' ? args.query.trim() : '';
5187
+ const p = typeof args.pack === 'string' ? args.pack.trim() : '';
5188
+ const n = Array.isArray(args.names) && args.names.length > 0;
5189
+ if (!q && !p && !n) {
5190
+ return 'Missing required "query" or "pack" argument';
5191
+ }
5192
+ }
5193
+
5111
5194
  return null; // No validation errors
5112
5195
  }
5113
5196
  }
@@ -10,6 +10,7 @@ import { createHash } from 'node:crypto';
10
10
  import path from 'node:path';
11
11
  import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
12
12
  import { extractToolCallJsonObjects, stripToolCallMarkup, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
13
+ import { canonicalizeToolName } from '../tools/toolSelfRepair.js';
13
14
  function fingerprint(value) {
14
15
  return createHash('sha256').update(JSON.stringify(value)).digest('hex');
15
16
  }
@@ -93,7 +94,8 @@ export class AcpProvider extends LLMProvider {
93
94
  '\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
94
95
  '1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
95
96
  ' - Your native function-calling channel ONLY accepts your own native tools (such as `read`, `write`, `edit`, `bash`, `glob`, `grep`, `todowrite`, and configured MCP tools). Use your native tools directly for workspace file reads/writes, shell commands, and todo checklists (use `todowrite` if available instead of calling `update_plan` as a native function).\n' +
96
- ' - Causyne host tools listed under [Available Tools] / [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
97
+ ' - Causyne host tools listed under [Available Tools] / [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`, `fs_read_skill`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
98
+ ' - Bundled Causyne skills must be read via the host tool `fs_read_skill`. Do NOT call peer-native `skill` or functions for Causyne skills. To read a skill, write `<tool_call>{"name": "fs_read_skill", "arguments": {"skill_id": "domain/name"}}</tool_call>` directly in your assistant text response.\n' +
97
99
  ' - To invoke a Causyne host tool, write `<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>` directly in your assistant text response with NO native function call in that step; Causyne will execute the host tool and return the result on the next turn.\n' +
98
100
  '2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
99
101
  ' - Keep ALL temporary files, server logs, and headless browser screenshots inside the active workspace directory (for example, `./.shots/preview.png` or `./server.log`). NEVER write to, read from, or `cp`/`mv` paths in `/tmp` or outside the workspace root, as the host sandbox rejects `/tmp` access.\n\n[Language & Communication Directive]\nDynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language.');
@@ -160,7 +162,8 @@ export class AcpProvider extends LLMProvider {
160
162
  '\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
161
163
  '1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
162
164
  ' - Your native function-calling channel ONLY accepts your own native tools (such as `read`, `write`, `edit`, `bash`, `glob`, `grep`, `todowrite`, and configured MCP tools). Use your native tools directly for workspace file reads/writes, shell commands, and todo checklists (use `todowrite` if available instead of calling `update_plan` as a native function).\n' +
163
- ' - Causyne host tools listed under [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
165
+ ' - Causyne host tools listed under [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`, `fs_read_skill`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
166
+ ' - Bundled Causyne skills must be read via the host tool `fs_read_skill`. Do NOT call peer-native `skill` or functions for Causyne skills. To read a skill, write `<tool_call>{"name": "fs_read_skill", "arguments": {"skill_id": "domain/name"}}</tool_call>` directly in your assistant text response.\n' +
164
167
  ' - To invoke a Causyne host tool, write `<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>` directly in your assistant text response with NO native function call in that step; Causyne will execute the host tool and return the result on the next turn.\n' +
165
168
  '2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
166
169
  ' - Keep ALL temporary files, server logs, and headless browser screenshots inside the active workspace directory (for example, `./.shots/preview.png` or `./server.log`). NEVER write to, read from, or `cp`/`mv` paths in `/tmp` or outside the workspace root, as the host sandbox rejects `/tmp` access.');
@@ -478,12 +481,22 @@ export class AcpProvider extends LLMProvider {
478
481
  || earlier?.parameters?.__invalidTool === true
479
482
  || (typeof input.error === 'string' && input.error.length > 0 && typeof input.tool === 'string');
480
483
  if (isInvalidPseudoTool) {
481
- const requested = typeof input.tool === 'string' ? input.tool : '';
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
484
+ const rawRequested = typeof input.tool === 'string' ? input.tool : '';
485
+ const canonicalRequested = canonicalizeToolName(rawRequested);
486
+ const hasDirectMatch = normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === rawRequested);
487
+ const hasCanonicalMatch = normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === canonicalRequested);
488
+ const requested = hasDirectMatch ? rawRequested : (hasCanonicalMatch ? canonicalRequested : '');
489
+ if (!this.toolRoutingError && requested) {
490
+ let rawArgs = (input.args && typeof input.args === 'object') ? input.args
484
491
  : (input.parameters && typeof input.parameters === 'object') ? input.parameters
485
- : (earlier?.parameters && typeof earlier.parameters === 'object') ? earlier.parameters
492
+ : (earlier?.parameters && typeof earlier.parameters === 'object' && !earlier.parameters.__pendingStub) ? earlier.parameters
486
493
  : undefined;
494
+ if (rawArgs && typeof rawArgs === 'object') {
495
+ const cleanArgs = { ...rawArgs };
496
+ delete cleanArgs.__pendingStub;
497
+ delete cleanArgs.__invalidTool;
498
+ rawArgs = Object.keys(cleanArgs).length > 0 ? cleanArgs : undefined;
499
+ }
487
500
  this.toolRoutingError = {
488
501
  tool: requested,
489
502
  message: typeof input.error === 'string' ? input.error : 'Host tool requested through the peer-native channel',
@@ -495,6 +508,28 @@ export class AcpProvider extends LLMProvider {
495
508
  this.turnActions.delete(id);
496
509
  return;
497
510
  }
511
+ const isPeerNativeSkill = rawTitle.toLowerCase() === 'skill'
512
+ || name.toLowerCase() === 'skill'
513
+ || earlier?.name === 'skill';
514
+ const isFailedSkill = isPeerNativeSkill && (updateObj.status === 'failed'
515
+ || (typeof input.error === 'string' && /Skill\s+.*not found/i.test(input.error))
516
+ || (typeof updateObj.error === 'string' && /Skill\s+.*not found/i.test(updateObj.error))
517
+ || (typeof rawOutputObj?.error === 'string' && /Skill\s+.*not found/i.test(rawOutputObj.error)));
518
+ if (isFailedSkill) {
519
+ if (!this.toolRoutingError) {
520
+ const requestedSkill = String(input.name || input.id || input.skill_id || input.skill || input.path
521
+ || earlier?.parameters?.name || earlier?.parameters?.id || earlier?.parameters?.skill_id || '').trim();
522
+ this.toolRoutingError = {
523
+ tool: 'fs_read_skill',
524
+ message: `Peer-native skill not found in peer catalog; routed to Causyne host tool fs_read_skill`,
525
+ parameters: requestedSkill ? { skill_id: requestedSkill } : undefined
526
+ };
527
+ client.notifyCancel(sessionId);
528
+ }
529
+ this.liveFileActions.delete(id);
530
+ this.turnActions.delete(id);
531
+ return;
532
+ }
498
533
  const locationPath = updateObj.locations?.[0]?.path;
499
534
  const inputPath = typeof input.path === 'string' ? input.path
500
535
  : typeof input.filePath === 'string' ? input.filePath