@causyne/agent 1.20.10 → 1.20.12

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 (88) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. package/src/tokenTracker.d.ts +0 -1
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @file src/infra/telemetry.ts
3
+ * Causyne Agent — Structured OpenTelemetry-Compatible Turn Telemetry
4
+ *
5
+ * Tracks fine-grained per-turn token metrics, cache hits, tool latency, and
6
+ * memory compaction savings for real-time performance auditing.
7
+ *
8
+ * Authorship: Strict TypeScript (Causyne Agent).
9
+ */
10
+
11
+ export interface TurnTelemetryRecord {
12
+ sessionId: string;
13
+ taskId: string;
14
+ turnIndex: number;
15
+ provider: string;
16
+ model: string;
17
+ promptTokens: number;
18
+ completionTokens: number;
19
+ cachedPromptTokens: number;
20
+ noncachedTokens: number;
21
+ durationMs: number;
22
+ planCacheHit: boolean;
23
+ toolOutputTruncatedCount: number;
24
+ historyCompactedChars: number;
25
+ timestamp: number;
26
+ }
27
+
28
+ export class TelemetryCollector {
29
+ private records: TurnTelemetryRecord[] = [];
30
+
31
+ public recordTurn(record: Omit<TurnTelemetryRecord, 'timestamp'>): TurnTelemetryRecord {
32
+ const fullRecord: TurnTelemetryRecord = {
33
+ ...record,
34
+ timestamp: Date.now()
35
+ };
36
+ this.records.push(fullRecord);
37
+ return fullRecord;
38
+ }
39
+
40
+ public getRecordsForTask(taskId: string): readonly TurnTelemetryRecord[] {
41
+ return this.records.filter(r => r.taskId === taskId);
42
+ }
43
+
44
+ public getSummary(taskId?: string): {
45
+ totalPromptTokens: number;
46
+ totalCompletionTokens: number;
47
+ totalCachedPromptTokens: number;
48
+ totalNoncachedTokens: number;
49
+ totalDurationMs: number;
50
+ turnCount: number;
51
+ } {
52
+ const active = taskId ? this.getRecordsForTask(taskId) : this.records;
53
+ return {
54
+ totalPromptTokens: active.reduce((sum, r) => sum + r.promptTokens, 0),
55
+ totalCompletionTokens: active.reduce((sum, r) => sum + r.completionTokens, 0),
56
+ totalCachedPromptTokens: active.reduce((sum, r) => sum + r.cachedPromptTokens, 0),
57
+ totalNoncachedTokens: active.reduce((sum, r) => sum + r.noncachedTokens, 0),
58
+ totalDurationMs: active.reduce((sum, r) => sum + r.durationMs, 0),
59
+ turnCount: active.length
60
+ };
61
+ }
62
+
63
+ public clear(): void {
64
+ this.records = [];
65
+ }
66
+ }
67
+
68
+ export const defaultTelemetry = new TelemetryCollector();
@@ -30,7 +30,7 @@ const HONEST_CAVEATS = [
30
30
  /\b(?:partially|incompletely)\s+(?:done|fixed|implemented|verified)\b/i
31
31
  ];
32
32
  const TEST_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test|node\s+--test|pytest|cargo\s+test|go\s+test|mvn\s+test|gradle\s+test|dotnet\s+test|swift\s+test)\b/i;
33
- const BUILD_OR_CHECK_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:build|check|lint|typecheck|types)|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|cargo\s+check|go\s+vet|ruby\s+-c|php\s+-l)\b/i;
33
+ const BUILD_OR_CHECK_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:build|check|lint|typecheck|types)|node\s+(?:--check|-c)|py_compile|compileall|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|cargo\s+check|go\s+vet|ruby\s+-c|php\s+-l)\b/i;
34
34
  const TESTS_CLAIM = /\b(?:all\s+)?tests?\b[^.\n]{0,40}\b(?:pass|passed|passing|green|succeed|succeeded)\b/i;
35
35
  const BUILD_CLAIM = /\b(?:build|typecheck|types|lint|compilation)\b[^.\n]{0,40}\b(?:pass|passed|passing|clean|succeed|succeeded)\b/i;
36
36
  const MUTATING_TOOLS = new Set([
@@ -383,13 +383,18 @@ export class ColdObserver {
383
383
  const lastFailure = outcomes.findLastIndex((outcome) => !outcome.success);
384
384
  const successAfterFailure = lastFailure >= 0
385
385
  && outcomes.slice(lastFailure + 1).some((outcome) => outcome.success);
386
- const hasTestRun = outcomes.some((outcome) => outcome.success
386
+ const isCodeMutation = (outcome) => outcome.success
387
+ && ['fs_write', 'fs_edit', 'MultiEdit'].includes(outcome.tool)
388
+ && /\.(?:[cm]?[jt]sx?|py|rb|php|go|rs|java|kt|kts|swift|c|cc|cpp|h|hpp|cs|fs|sh|sql|html|css|scss|sass|vue|svelte)$/i.test(outcome.path);
389
+ const lastCodeChange = outcomes.findLastIndex(isCodeMutation);
390
+ const checks = outcomes.slice(lastCodeChange + 1);
391
+ const hasTestRun = checks.some((outcome) => outcome.success
387
392
  && (TEST_COMMAND.test(outcome.command) || TEST_COMMAND.test(outcome.tool)));
388
- const hasBuildRun = outcomes.some((outcome) => outcome.success
393
+ const hasBuildRun = checks.some((outcome) => outcome.success
389
394
  && (BUILD_OR_CHECK_COMMAND.test(outcome.command) || outcome.tool === 'code_verify_syntax'));
390
- const modifiedCode = outcomes.some((outcome) => outcome.success
391
- && ['fs_write', 'fs_edit', 'MultiEdit'].includes(outcome.tool)
392
- && /\.(?:[cm]?[jt]sx?|py|rb|php|go|rs|java|kt|kts|swift|c|cc|cpp|h|hpp|cs|fs|sh|sql|html|css|scss|sass|vue|svelte)$/i.test(outcome.path));
395
+ const modifiedCode = lastCodeChange >= 0;
396
+ const declarativeOnly = modifiedCode && outcomes.filter(isCodeMutation).every(outcome => /\.(?:html|css)$/i.test(outcome.path));
397
+ const hasRenderedCheck = checks.some(outcome => outcome.success && outcome.rendered === true);
393
398
  let overconfident = false;
394
399
  let confidence = 0;
395
400
  let discrepancy = '';
@@ -412,7 +417,7 @@ export class ColdObserver {
412
417
  discrepancy = 'claimed a passing build or check without a successful verification command';
413
418
  coldDirective = '[OBSERVER] You claimed that a build or check passed, but no successful verification command appears in this task. Run the relevant command and report its actual result, or state that it is unverified.';
414
419
  }
415
- else if (!caveat && modifiedCode && !hasBuildRun && !hasTestRun) {
420
+ else if (!caveat && modifiedCode && !hasBuildRun && !hasTestRun && !(declarativeOnly && hasRenderedCheck)) {
416
421
  overconfident = true;
417
422
  confidence = 0.72;
418
423
  discrepancy = 'code was modified without a successful test or syntax check';
@@ -91,7 +91,7 @@ const HONEST_CAVEATS = [
91
91
  ];
92
92
 
93
93
  const TEST_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test|node\s+--test|pytest|cargo\s+test|go\s+test|mvn\s+test|gradle\s+test|dotnet\s+test|swift\s+test)\b/i;
94
- const BUILD_OR_CHECK_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:build|check|lint|typecheck|types)|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|cargo\s+check|go\s+vet|ruby\s+-c|php\s+-l)\b/i;
94
+ const BUILD_OR_CHECK_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:build|check|lint|typecheck|types)|node\s+(?:--check|-c)|py_compile|compileall|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|cargo\s+check|go\s+vet|ruby\s+-c|php\s+-l)\b/i;
95
95
  const TESTS_CLAIM = /\b(?:all\s+)?tests?\b[^.\n]{0,40}\b(?:pass|passed|passing|green|succeed|succeeded)\b/i;
96
96
  const BUILD_CLAIM = /\b(?:build|typecheck|types|lint|compilation)\b[^.\n]{0,40}\b(?:pass|passed|passing|clean|succeed|succeeded)\b/i;
97
97
 
@@ -458,13 +458,18 @@ export class ColdObserver {
458
458
  const lastFailure = outcomes.findLastIndex((outcome) => !outcome.success);
459
459
  const successAfterFailure = lastFailure >= 0
460
460
  && outcomes.slice(lastFailure + 1).some((outcome) => outcome.success);
461
- const hasTestRun = outcomes.some((outcome) => outcome.success
461
+ const isCodeMutation = (outcome: ToolOutcome): boolean => outcome.success
462
+ && ['fs_write', 'fs_edit', 'MultiEdit'].includes(outcome.tool)
463
+ && /\.(?:[cm]?[jt]sx?|py|rb|php|go|rs|java|kt|kts|swift|c|cc|cpp|h|hpp|cs|fs|sh|sql|html|css|scss|sass|vue|svelte)$/i.test(outcome.path);
464
+ const lastCodeChange = outcomes.findLastIndex(isCodeMutation);
465
+ const checks = outcomes.slice(lastCodeChange + 1);
466
+ const hasTestRun = checks.some((outcome) => outcome.success
462
467
  && (TEST_COMMAND.test(outcome.command) || TEST_COMMAND.test(outcome.tool)));
463
- const hasBuildRun = outcomes.some((outcome) => outcome.success
468
+ const hasBuildRun = checks.some((outcome) => outcome.success
464
469
  && (BUILD_OR_CHECK_COMMAND.test(outcome.command) || outcome.tool === 'code_verify_syntax'));
465
- const modifiedCode = outcomes.some((outcome) => outcome.success
466
- && ['fs_write', 'fs_edit', 'MultiEdit'].includes(outcome.tool)
467
- && /\.(?:[cm]?[jt]sx?|py|rb|php|go|rs|java|kt|kts|swift|c|cc|cpp|h|hpp|cs|fs|sh|sql|html|css|scss|sass|vue|svelte)$/i.test(outcome.path));
470
+ const modifiedCode = lastCodeChange >= 0;
471
+ const declarativeOnly = modifiedCode && outcomes.filter(isCodeMutation).every(outcome => /\.(?:html|css)$/i.test(outcome.path));
472
+ const hasRenderedCheck = checks.some(outcome => outcome.success && outcome.rendered === true);
468
473
 
469
474
  let overconfident = false;
470
475
  let confidence = 0;
@@ -486,7 +491,7 @@ export class ColdObserver {
486
491
  confidence = 0.82;
487
492
  discrepancy = 'claimed a passing build or check without a successful verification command';
488
493
  coldDirective = '[OBSERVER] You claimed that a build or check passed, but no successful verification command appears in this task. Run the relevant command and report its actual result, or state that it is unverified.';
489
- } else if (!caveat && modifiedCode && !hasBuildRun && !hasTestRun) {
494
+ } else if (!caveat && modifiedCode && !hasBuildRun && !hasTestRun && !(declarativeOnly && hasRenderedCheck)) {
490
495
  overconfident = true;
491
496
  confidence = 0.72;
492
497
  discrepancy = 'code was modified without a successful test or syntax check';
@@ -27,7 +27,7 @@ const CODE_EXTENSIONS = new Set([
27
27
  '.h', '.hpp', '.cs', '.fs', '.sh', '.bash', '.zsh', '.fish', '.sql',
28
28
  '.html', '.css', '.scss', '.sass', '.vue', '.svelte'
29
29
  ]);
30
- const VERIFICATION_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|check|build|lint|typecheck|types)|node\s+--test|pytest|py_compile|compileall|cargo\s+(?:test|check)|go\s+(?:test|vet)|mvn\s+test|gradle\s+test|dotnet\s+test|swift\s+test|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|ruby\s+-c|php\s+-l)\b/i;
30
+ const VERIFICATION_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|check|build|lint|typecheck|types)|node\s+(?:--test|--check|-c)|pytest|py_compile|compileall|cargo\s+(?:test|check)|go\s+(?:test|vet)|mvn\s+test|gradle\s+test|dotnet\s+test|swift\s+test|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|ruby\s+-c|php\s+-l)\b/i;
31
31
  const HIGH_RISK_COMMANDS = [
32
32
  { pattern: /\bgit\s+reset\s+--hard\b/i, code: 'git-reset-hard', detail: 'git reset --hard discards uncommitted work' },
33
33
  { pattern: /\bgit\s+clean\s+-[a-z]*[fdx][a-z]*/i, code: 'git-clean', detail: 'git clean permanently removes untracked files' },
@@ -422,6 +422,11 @@ export function outcomeFromResult(tool, args, result, at) {
422
422
  const command = typeof args.command === 'string'
423
423
  ? args.command
424
424
  : typeof args.cmd === 'string' ? args.cmd : '';
425
+ const browserData = Array.isArray(record.data) ? record.data : [];
426
+ const rendered = success && tool === 'browser_act' && browserData.some((item) => {
427
+ const action = item;
428
+ return ['snapshot', 'scrape'].includes(action?.action || '') && Array.isArray(action.data?.runtimeErrors) && action.data.runtimeErrors.length === 0;
429
+ });
425
430
  return {
426
431
  tool,
427
432
  args: boundedArgs(args),
@@ -430,6 +435,7 @@ export function outcomeFromResult(tool, args, result, at) {
430
435
  exitCode,
431
436
  command: command.slice(0, 600),
432
437
  path: pathArgument(args).slice(0, 400),
433
- at
438
+ at,
439
+ ...(rendered ? { rendered: true } : {})
434
440
  };
435
441
  }
@@ -38,6 +38,7 @@ export interface ToolOutcome {
38
38
  command: string;
39
39
  path: string;
40
40
  at: number;
41
+ rendered?: boolean;
41
42
  }
42
43
 
43
44
  const SEVERITY_WEIGHT: Record<RiskSeverity, number> = {
@@ -68,7 +69,7 @@ const CODE_EXTENSIONS = new Set([
68
69
  '.html', '.css', '.scss', '.sass', '.vue', '.svelte'
69
70
  ]);
70
71
 
71
- const VERIFICATION_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|check|build|lint|typecheck|types)|node\s+--test|pytest|py_compile|compileall|cargo\s+(?:test|check)|go\s+(?:test|vet)|mvn\s+test|gradle\s+test|dotnet\s+test|swift\s+test|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|ruby\s+-c|php\s+-l)\b/i;
72
+ const VERIFICATION_COMMAND = /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|check|build|lint|typecheck|types)|node\s+(?:--test|--check|-c)|pytest|py_compile|compileall|cargo\s+(?:test|check)|go\s+(?:test|vet)|mvn\s+test|gradle\s+test|dotnet\s+test|swift\s+test|tsc(?:\s|$)|eslint|biome\s+(?:check|ci)|ruby\s+-c|php\s+-l)\b/i;
72
73
 
73
74
  const HIGH_RISK_COMMANDS: Array<{ pattern: RegExp; code: string; detail: string; severity?: RiskSeverity }> = [
74
75
  { pattern: /\bgit\s+reset\s+--hard\b/i, code: 'git-reset-hard', detail: 'git reset --hard discards uncommitted work' },
@@ -486,6 +487,11 @@ export function outcomeFromResult(tool: string, args: Record<string, unknown>, r
486
487
  const command = typeof args.command === 'string'
487
488
  ? args.command
488
489
  : typeof args.cmd === 'string' ? args.cmd : '';
490
+ const browserData = Array.isArray(record.data) ? record.data : [];
491
+ const rendered = success && tool === 'browser_act' && browserData.some((item: unknown) => {
492
+ const action = item as { action?: string; data?: { runtimeErrors?: unknown[] } };
493
+ return ['snapshot', 'scrape'].includes(action?.action || '') && Array.isArray(action.data?.runtimeErrors) && action.data.runtimeErrors.length === 0;
494
+ });
489
495
  return {
490
496
  tool,
491
497
  args: boundedArgs(args),
@@ -494,6 +500,7 @@ export function outcomeFromResult(tool: string, args: Record<string, unknown>, r
494
500
  exitCode,
495
501
  command: command.slice(0, 600),
496
502
  path: pathArgument(args).slice(0, 400),
497
- at
503
+ at,
504
+ ...(rendered ? { rendered: true } : {})
498
505
  };
499
506
  }
@@ -0,0 +1,36 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { causyneHome } from './utils/paths.js';
4
+ function normalizePathKey(filePath) {
5
+ const resolved = path.resolve(filePath);
6
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
7
+ }
8
+ /** Read only an exact output file already attached to this session's history. */
9
+ export function isOutputRecoveryRead(tool, target, knownPaths) {
10
+ if (tool !== 'fs_read' || typeof target !== 'string')
11
+ return false;
12
+ const targetKey = normalizePathKey(target);
13
+ const isKnown = Array.from(knownPaths).some(known => normalizePathKey(known) === targetKey);
14
+ if (!isKnown)
15
+ return false;
16
+ try {
17
+ const resolved = path.resolve(target);
18
+ const stat = fs.lstatSync(resolved);
19
+ if (!stat.isFile() || stat.isSymbolicLink())
20
+ return false;
21
+ const real = fs.realpathSync(resolved);
22
+ const realKey = process.platform === 'win32' ? real.toLowerCase() : real;
23
+ return ['outputs', 'tool-output'].some(directory => {
24
+ const root = path.join(causyneHome(), directory);
25
+ if (!fs.existsSync(root))
26
+ return false;
27
+ const realRoot = fs.realpathSync(root);
28
+ const rootKey = process.platform === 'win32' ? realRoot.toLowerCase() : realRoot;
29
+ const relative = path.relative(rootKey, realKey);
30
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
31
+ });
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { causyneHome } from './utils/paths.js';
4
+
5
+ function normalizePathKey(filePath: string): string {
6
+ const resolved = path.resolve(filePath);
7
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
8
+ }
9
+
10
+ /** Read only an exact output file already attached to this session's history. */
11
+ export function isOutputRecoveryRead(tool: string, target: unknown, knownPaths: ReadonlySet<string>): boolean {
12
+ if (tool !== 'fs_read' || typeof target !== 'string') return false;
13
+ const targetKey = normalizePathKey(target);
14
+ const isKnown = Array.from(knownPaths).some(known => normalizePathKey(known) === targetKey);
15
+ if (!isKnown) return false;
16
+
17
+ try {
18
+ const resolved = path.resolve(target);
19
+ const stat = fs.lstatSync(resolved);
20
+ if (!stat.isFile() || stat.isSymbolicLink()) return false;
21
+ const real = fs.realpathSync(resolved);
22
+ const realKey = process.platform === 'win32' ? real.toLowerCase() : real;
23
+
24
+ return ['outputs', 'tool-output'].some(directory => {
25
+ const root = path.join(causyneHome(), directory);
26
+ if (!fs.existsSync(root)) return false;
27
+ const realRoot = fs.realpathSync(root);
28
+ const rootKey = process.platform === 'win32' ? realRoot.toLowerCase() : realRoot;
29
+ const relative = path.relative(rootKey, realKey);
30
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
31
+ });
32
+ } catch { return false; }
33
+ }
@@ -1,3 +1,4 @@
1
+ import { formatToolContracts, toolContractUpdate } from './toolContracts.js';
1
2
  import { canonicalModelId } from '../modelIds.js';
2
3
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
4
  import { saveCachedModels } from '../dynamicCatalogue.js';
@@ -5,6 +6,12 @@ import { LLMProvider } from './base.js';
5
6
  import { AcpClient } from '../acp/client.js';
6
7
  import { getPeerProfile } from '../acp/peerProfiles.js';
7
8
  import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
9
+ import { createHash } from 'node:crypto';
10
+ import path from 'node:path';
11
+ import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
12
+ function fingerprint(value) {
13
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
14
+ }
8
15
  export function isAcpProvider(provider) {
9
16
  if (!provider)
10
17
  return false;
@@ -19,10 +26,13 @@ export class AcpProvider extends LLMProvider {
19
26
  activeClient = null;
20
27
  activeSessionId = null;
21
28
  currentTurnAborted = false;
29
+ currentTurnSawAction = false;
22
30
  currentTurnChunkHandler = null;
23
31
  currentTurnReasoningHandler = null;
24
32
  currentTurnNativeActionHandler = null;
25
33
  liveFileActions = new Map();
34
+ transportSnapshot = null;
35
+ peerServices = null;
26
36
  constructor(config = {}) {
27
37
  super(config);
28
38
  const providerStr = String(config.provider || '').toLowerCase().trim();
@@ -71,15 +81,9 @@ export class AcpProvider extends LLMProvider {
71
81
  }
72
82
  formatConversation(messages, tools = []) {
73
83
  const lines = [];
74
- lines.push('[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. Do NOT invoke your own internal host CLI tools or execute commands directly. When an action or tool is required, output an explicit tool call in this exact format:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent will execute the tool in its secure environment and return the results back to you.\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.');
84
+ lines.push('[System Instructions]\nYou are collaborating with Causyne Agent over the Agent Client Protocol (ACP). Use the negotiated ACP capabilities and preserve configured native tools, MCPs, skills, and project settings. When requesting workspace tools from the Causyne host, format your calls as:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent coordinates, validates, and executes the tools in the active workspace and returns results back to you, preserving your full reasoning and ACP capabilities. ' + PEER_COLLABORATION_POLICY + '\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.');
75
85
  if (tools && tools.length > 0) {
76
- const toolSummaries = tools.map(t => {
77
- const name = t.name || t.function?.name || 'unknown';
78
- const desc = t.description || t.function?.description || '';
79
- const params = t.parameters || t.input_schema || t.function?.parameters || {};
80
- const paramKeys = Object.keys(params.properties || {}).join(', ');
81
- return `- ${name}(${paramKeys}): ${desc}`;
82
- }).join('\n');
86
+ const toolSummaries = formatToolContracts(tools);
83
87
  lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
84
88
  }
85
89
  const seenToolOutputs = new Set();
@@ -126,7 +130,7 @@ export class AcpProvider extends LLMProvider {
126
130
  }
127
131
  return lines.join('\n\n');
128
132
  }
129
- formatPromptBlocks(messages, tools = [], imageSupport = false) {
133
+ formatPromptBlocks(messages, tools = [], imageSupport = false, includeBridgeInstructions = true, toolContext = '') {
130
134
  const blocks = [];
131
135
  let pending = [];
132
136
  const flush = () => {
@@ -135,19 +139,15 @@ export class AcpProvider extends LLMProvider {
135
139
  blocks.push({ type: 'text', text: pending.join('\n\n') });
136
140
  pending = [];
137
141
  };
138
- pending.push('[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. Do NOT invoke your own internal host CLI tools or execute commands directly. When an action or tool is required, output an explicit tool call in this exact format:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent will execute the tool in its secure environment and return the results back to you.');
142
+ if (includeBridgeInstructions) {
143
+ pending.push('[System Instructions]\nYou are collaborating with Causyne Agent over the Agent Client Protocol (ACP). Use the negotiated ACP capabilities and preserve configured native tools, MCPs, skills, and project settings. When requesting workspace tools from the Causyne host, format your calls as:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent coordinates, validates, and executes the tools in the active workspace and returns results back to you, preserving your full reasoning and ACP capabilities. ' + PEER_COLLABORATION_POLICY);
144
+ }
139
145
  if (tools && tools.length > 0) {
140
- const toolSummaries = tools.map(t => {
141
- const name = t.name || t.function?.name || 'unknown';
142
- const desc = t.description || t.function?.description || '';
143
- const params = t.parameters || t.input_schema || t.function?.parameters || {};
144
- const paramKeys = Object.keys(params.properties || {}).join(', ');
145
- return `- ${name}(${paramKeys}): ${desc}`;
146
- }).join('\n');
147
- pending.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
146
+ const toolSummaries = formatToolContracts(tools);
147
+ pending.push(`[Current Available Tools — this list replaces earlier tool lists]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
148
148
  }
149
- const seenToolOutputs = new Set();
150
- const seenAssistantCalls = new Set();
149
+ if (toolContext)
150
+ pending.push(toolContext);
151
151
  for (const msg of messages) {
152
152
  const role = this._roleLabel(msg);
153
153
  let text = '';
@@ -157,22 +157,10 @@ export class AcpProvider extends LLMProvider {
157
157
  else if (Array.isArray(msg.content)) {
158
158
  text = msg.content.map((c) => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
159
159
  }
160
- if (msg.role === 'tool' && text.trim()) {
161
- const normalized = text.trim();
162
- if (seenToolOutputs.has(normalized)) {
163
- continue;
164
- }
165
- seenToolOutputs.add(normalized);
166
- }
167
160
  if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
168
161
  for (const tc of msg.tool_calls) {
169
162
  const fn = tc.function || {};
170
163
  const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
171
- const callSig = `${fn.name}:${fnArgs}`;
172
- if (seenAssistantCalls.has(callSig)) {
173
- continue;
174
- }
175
- seenAssistantCalls.add(callSig);
176
164
  text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
177
165
  }
178
166
  }
@@ -302,7 +290,7 @@ export class AcpProvider extends LLMProvider {
302
290
  }
303
291
  return calls;
304
292
  }
305
- async getOrCreateClient(signal) {
293
+ async getOrCreateClient(signal, workspaceRoot = process.cwd()) {
306
294
  if (signal?.aborted) {
307
295
  const abortErr = new Error('ACP request aborted by user');
308
296
  abortErr.name = 'AbortError';
@@ -314,15 +302,23 @@ export class AcpProvider extends LLMProvider {
314
302
  const client = new AcpClient({
315
303
  command: this.command,
316
304
  args: this.args,
317
- cwd: process.cwd(),
305
+ cwd: workspaceRoot,
318
306
  promptTimeoutMs: 900_000,
307
+ allowHostTools: true,
319
308
  permissionHandler: async (req) => {
320
- if (this.currentTurnAborted || signal?.aborted)
309
+ if (this.currentTurnAborted || this.peerServices?.signal?.aborted)
321
310
  return { outcome: 'cancelled' };
322
- const allowOpt = req.options?.find(o => o.kind === 'allow_once' || o.kind === 'allow_always' || o.optionId === 'allow');
323
- if (allowOpt)
324
- return { outcome: 'selected', optionId: allowOpt.optionId };
325
- return { outcome: 'cancelled' };
311
+ return this.peerServices?.onPeerPermission?.(req) ?? { outcome: 'cancelled' };
312
+ },
313
+ fsReadHandler: async (file, options) => {
314
+ if (!this.peerServices?.onPeerFileRead)
315
+ throw new Error('The ACP client has no file-read service attached');
316
+ return this.peerServices.onPeerFileRead(file, options);
317
+ },
318
+ fsWriteHandler: async (file, content) => {
319
+ if (!this.peerServices?.onPeerFileWrite)
320
+ throw new Error('The ACP client has no file-write service attached');
321
+ await this.peerServices.onPeerFileWrite(file, content);
326
322
  },
327
323
  onUpdate: (_sessionId, update) => {
328
324
  if (this.currentTurnAborted)
@@ -341,10 +337,13 @@ export class AcpProvider extends LLMProvider {
341
337
  this.currentTurnChunkHandler(text);
342
338
  }
343
339
  else if (updateObj.sessionUpdate === 'tool_call' || updateObj.sessionUpdate === 'tool_call_update') {
340
+ this.currentTurnSawAction = true;
344
341
  const id = String(updateObj.toolCallId || '');
345
342
  const earlier = this.liveFileActions.get(id);
346
343
  const kind = updateObj.kind || (earlier?.name === 'fs_edit' ? 'edit' : earlier?.name === 'fs_delete' ? 'delete' : earlier?.name === 'fs_move' ? 'move' : '');
347
- const name = kind === 'edit' ? 'fs_edit' : kind === 'delete' ? 'fs_delete' : kind === 'move' ? 'fs_move' : '';
344
+ const name = kind === 'edit' ? 'fs_edit' : kind === 'delete' ? 'fs_delete' : kind === 'move' ? 'fs_move'
345
+ : kind === 'read' ? 'fs_read' : kind === 'search' ? 'codebase_search' : kind === 'fetch' ? 'web_fetch'
346
+ : kind === 'execute' ? 'sysRun' : String(updateObj.title || earlier?.name || 'provider_tool');
348
347
  if (name && id) {
349
348
  const diff = Array.isArray(updateObj.content)
350
349
  ? updateObj.content.find((item) => item?.type === 'diff')
@@ -357,7 +356,7 @@ export class AcpProvider extends LLMProvider {
357
356
  ...(updateObj.locations?.[0]?.path ? { path: updateObj.locations[0].path } : {})
358
357
  };
359
358
  const status = updateObj.status === 'completed' ? 'completed' : updateObj.status === 'failed' ? 'failed' : 'running';
360
- const action = { name, status, parameters,
359
+ const action = { id: `acp:${id}`, name, status, parameters,
361
360
  detail: String(parameters.path || updateObj.title || '') };
362
361
  if (status === 'running')
363
362
  this.liveFileActions.set(id, action);
@@ -376,7 +375,7 @@ export class AcpProvider extends LLMProvider {
376
375
  }
377
376
  });
378
377
  await client.start(signal);
379
- const sessionId = await client.newSession(process.cwd(), [], signal);
378
+ const sessionId = await client.newSession(workspaceRoot, this.peerServices?.peerMcpServers || [], signal);
380
379
  const sessionModels = client.getSessionModels(sessionId);
381
380
  const liveModels = sessionModels.availableModels;
382
381
  if (liveModels.length > 0 && !process.env.NODE_TEST_CONTEXT) {
@@ -449,6 +448,7 @@ export class AcpProvider extends LLMProvider {
449
448
  const client = this.activeClient;
450
449
  this.activeClient = null;
451
450
  this.activeSessionId = null;
451
+ this.transportSnapshot = null;
452
452
  if (client) {
453
453
  try {
454
454
  await client.close();
@@ -459,7 +459,9 @@ export class AcpProvider extends LLMProvider {
459
459
  }
460
460
  }
461
461
  async chat(messages, options = {}) {
462
+ this.peerServices = options;
462
463
  this.currentTurnAborted = Boolean(options.signal?.aborted);
464
+ this.currentTurnSawAction = false;
463
465
  if (this.currentTurnAborted) {
464
466
  const abortErr = new Error('ACP request aborted by user');
465
467
  abortErr.name = 'AbortError';
@@ -474,10 +476,50 @@ export class AcpProvider extends LLMProvider {
474
476
  };
475
477
  options.signal?.addEventListener('abort', onAbort, { once: true });
476
478
  try {
477
- const { client, sessionId } = await this.getOrCreateClient(options.signal);
479
+ const workspaceRoot = path.resolve(String(options.workspaceRoot || process.cwd()));
480
+ const conversationId = String(options.conversationId || options.taskId || '__default__');
481
+ const systemMessages = messages.filter(message => message.role === 'system');
482
+ const historyMessages = messages.filter(message => message.role !== 'system');
483
+ const systemHashes = systemMessages.map(fingerprint);
484
+ const historyHashes = historyMessages.map(fingerprint);
485
+ const toolHash = fingerprint(options.tools || []);
486
+ let previous = this.transportSnapshot;
487
+ const sessionChanged = previous && (previous.workspaceRoot !== workspaceRoot || previous.conversationId !== conversationId);
488
+ const historyDiverged = previous && (historyHashes.length < previous.historyHashes.length ||
489
+ previous.historyHashes.some((hash, index) => historyHashes[index] !== hash));
490
+ const systemShapeChanged = previous && systemHashes.length < previous.systemHashes.length;
491
+ if (sessionChanged || historyDiverged || systemShapeChanged) {
492
+ await this.close();
493
+ previous = null;
494
+ }
495
+ const { client, sessionId } = await this.getOrCreateClient(options.signal, workspaceRoot);
478
496
  const supportsImages = client.agentCapabilities?.promptCapabilities?.image === true;
479
- const promptBlocks = this.formatPromptBlocks(messages, options.tools, supportsImages);
480
- const promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
497
+ let promptMessages = messages;
498
+ let promptTools = options.tools || [];
499
+ let includeBridgeInstructions = true;
500
+ let toolContext = '';
501
+ if (previous) {
502
+ const changedSystem = systemMessages.filter((_, index) => systemHashes[index] !== previous.systemHashes[index]);
503
+ const newHistory = historyMessages.slice(previous.historyHashes.length);
504
+ // The peer already generated its previous assistant turn. AgentLoop
505
+ // records that turn for stateless BYOK APIs; replaying it into ACP would
506
+ // duplicate the peer's own response before the next tool result.
507
+ const firstNew = newHistory[0];
508
+ if (firstNew?.role === 'assistant' &&
509
+ firstNew.content === previous.lastResponse.content &&
510
+ fingerprint(firstNew.tool_calls || []) === fingerprint(previous.lastResponse.toolCalls)) {
511
+ newHistory.shift();
512
+ }
513
+ promptMessages = [
514
+ ...changedSystem.map(message => ({ ...message, content: `[Current system context — replaces the prior version of this section]\n${message.content}` })),
515
+ ...newHistory
516
+ ];
517
+ toolContext = toolContractUpdate(options.tools || [], previous.tools);
518
+ promptTools = [];
519
+ includeBridgeInstructions = false;
520
+ }
521
+ let promptBlocks = this.formatPromptBlocks(promptMessages, promptTools, supportsImages, includeBridgeInstructions, toolContext);
522
+ let promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
481
523
  let result;
482
524
  try {
483
525
  result = await client.prompt(sessionId, promptBlocks, options.signal);
@@ -486,9 +528,15 @@ export class AcpProvider extends LLMProvider {
486
528
  if (this.currentTurnAborted || options.signal?.aborted || promptErr?.name === 'AbortError') {
487
529
  throw promptErr;
488
530
  }
531
+ // Replaying after a peer executed native tools can duplicate mutations
532
+ // and charges. Restart only before any observed native action.
533
+ if (this.currentTurnSawAction)
534
+ throw promptErr;
489
535
  // If peer failed before any user abort, try recreating client once in case connection dropped
490
536
  await this.close();
491
- const fresh = await this.getOrCreateClient(options.signal);
537
+ const fresh = await this.getOrCreateClient(options.signal, workspaceRoot);
538
+ promptBlocks = this.formatPromptBlocks(messages, options.tools, fresh.client.agentCapabilities?.promptCapabilities?.image === true);
539
+ promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
492
540
  result = await fresh.client.prompt(fresh.sessionId, promptBlocks, options.signal);
493
541
  }
494
542
  if (this.currentTurnAborted || options.signal?.aborted) {
@@ -500,6 +548,10 @@ export class AcpProvider extends LLMProvider {
500
548
  const toolCalls = this.extractToolCalls(rawContent);
501
549
  // Strip tool call XML from chat content display
502
550
  let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
551
+ this.transportSnapshot = {
552
+ conversationId, workspaceRoot, systemHashes, historyHashes, toolHash, tools: structuredClone(options.tools || []),
553
+ lastResponse: { content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`), toolCalls }
554
+ };
503
555
  const response = {
504
556
  content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`),
505
557
  usage: {
@@ -510,6 +562,21 @@ export class AcpProvider extends LLMProvider {
510
562
  cacheMeasurement: 'unavailable'
511
563
  }
512
564
  };
565
+ const usage = result?.usage;
566
+ if (usage && Number.isFinite(usage.inputTokens) && usage.inputTokens >= 0
567
+ && Number.isFinite(usage.outputTokens) && usage.outputTokens >= 0) {
568
+ const safeCount = (value) => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
569
+ const cached = safeCount(usage.cachedReadTokens);
570
+ const writes = safeCount(usage.cachedWriteTokens);
571
+ response.usage = {
572
+ promptTokens: usage.inputTokens + cached + writes,
573
+ uncachedPromptTokens: usage.inputTokens + writes,
574
+ completionTokens: usage.outputTokens + safeCount(usage.thoughtTokens),
575
+ cachedPromptTokens: cached,
576
+ measurement: 'provider_reported',
577
+ cacheMeasurement: usage.cachedReadTokens !== undefined ? 'provider_reported' : 'unavailable'
578
+ };
579
+ }
513
580
  if (toolCalls.length > 0) {
514
581
  response.toolCalls = toolCalls;
515
582
  }
@@ -530,6 +597,7 @@ export class AcpProvider extends LLMProvider {
530
597
  }
531
598
  finally {
532
599
  options.signal?.removeEventListener('abort', onAbort);
600
+ this.peerServices = null;
533
601
  this.currentTurnChunkHandler = null;
534
602
  this.currentTurnReasoningHandler = null;
535
603
  this.currentTurnNativeActionHandler = null;