@causyne/agent 1.20.11 → 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 (86) 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 +264 -82
  34. package/src/providers/antigravity.ts +273 -87
  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/subagent/sidechainHarness.js +66 -0
  54. package/src/subagent/sidechainHarness.ts +91 -0
  55. package/src/taskContinuation.js +12 -0
  56. package/src/taskContinuation.ts +13 -0
  57. package/src/tokenTracker.js +406 -539
  58. package/src/tokenTracker.ts +569 -0
  59. package/src/toolPacks.d.ts +2 -0
  60. package/src/toolPacks.js +1 -1
  61. package/src/tools/argumentValidation.js +56 -0
  62. package/src/tools/argumentValidation.ts +50 -0
  63. package/src/tools/browserAutomator.js +2 -2
  64. package/src/tools/browserAutomator.ts +3 -2
  65. package/src/tools/deferredMcpSearch.js +188 -201
  66. package/src/tools/deferredMcpSearch.ts +250 -0
  67. package/src/tools/generateMediaViaApi.js +305 -331
  68. package/src/tools/generateMediaViaApi.ts +330 -0
  69. package/src/tools/historyPruner.js +5 -0
  70. package/src/tools/historyPruner.ts +5 -0
  71. package/src/tools/payloadSanitizer.js +92 -0
  72. package/src/tools/payloadSanitizer.ts +113 -0
  73. package/src/tools/registry.d.ts +1 -0
  74. package/src/tools/sysRun.js +47 -18
  75. package/src/tools/sysRun.ts +52 -20
  76. package/src/tools/toolOutputStore.js +180 -0
  77. package/src/tools/toolOutputStore.ts +209 -0
  78. package/src/tools/toolSelfRepair.js +26 -1
  79. package/src/tools/toolSelfRepair.ts +25 -1
  80. package/src/tui/chatRenderer.d.ts +1 -0
  81. package/src/tui/chatRenderer.js +4 -2
  82. package/src/tui/codeStreamRenderer.js +36 -8
  83. package/src/tui/codeStreamRenderer.ts +38 -8
  84. package/src/tui/stageSurface.js +1 -0
  85. package/src/tui/text.js +4 -1
  86. package/src/tokenTracker.d.ts +0 -1
@@ -0,0 +1,58 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { causyneHome } from '../utils/paths.js';
5
+ export const INFERENCE_AGENT_NAME = 'causyne-inference';
6
+ export const INFERENCE_AGENT_DEFINITION = `---
7
+ name: causyne-inference
8
+ description: Autonomous inference and execution engine for Causyne Agent across global developer workflows.
9
+ mainAgent: true
10
+ subagent: false
11
+ inheritMcp: true
12
+ ---
13
+ # System Prompt
14
+ You are an autonomous AI engineering engine operating in unison with Causyne Agent, built for billions of users worldwide.
15
+ You operate with full developer capabilities, preserving ACP, MCP, and native tooling interoperability.
16
+ Causyne coordinates the workspace, implementation checklist, and secure execution environment.
17
+ When invoking Causyne workspace tools, output:
18
+ <tool_call>{"name":"tool_name","arguments":{}}</tool_call>
19
+ Causyne Agent seamlessly maps, coordinates, and validates tool executions in the active workspace.
20
+ Never disable or degrade ACP capabilities. Retain full reasoning, execution capability, and professional engineering discipline.
21
+ The inference process directory is private adapter state, not the user's workspace. Work with the workspace paths supplied by Causyne. Never claim that a requested action happened without its tool result.
22
+ `;
23
+ /**
24
+ * Historical adapter-state helper, retained for compatibility checks only.
25
+ * Normal product sessions must not call this or substitute this workspace/profile.
26
+ */
27
+ export function ensureAntigravityBridgeWorkspace() {
28
+ const root = path.join(causyneHome(), 'provider-bridges', 'antigravity-inference-v1');
29
+ const agents = path.join(root, '.agents', 'agents');
30
+ for (const directory of [root, path.join(root, '.agents'), agents]) {
31
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
32
+ if (fs.lstatSync(directory).isSymbolicLink())
33
+ throw new Error('Causyne inference directory must not be a symlink');
34
+ }
35
+ const target = path.join(agents, `${INFERENCE_AGENT_NAME}.md`);
36
+ try {
37
+ if (fs.lstatSync(target).isSymbolicLink())
38
+ throw new Error('Causyne inference profile must not be a symlink');
39
+ if (fs.readFileSync(target, 'utf8') === INFERENCE_AGENT_DEFINITION)
40
+ return root;
41
+ }
42
+ catch (error) {
43
+ if (error.code !== 'ENOENT')
44
+ throw error;
45
+ }
46
+ const temporary = path.join(agents, `.${randomUUID()}.tmp`);
47
+ try {
48
+ fs.writeFileSync(temporary, INFERENCE_AGENT_DEFINITION, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
49
+ fs.renameSync(temporary, target);
50
+ }
51
+ finally {
52
+ try {
53
+ fs.unlinkSync(temporary);
54
+ }
55
+ catch { /* Renamed or already removed. */ }
56
+ }
57
+ return root;
58
+ }
@@ -0,0 +1,51 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { causyneHome } from '../utils/paths.js';
5
+
6
+ export const INFERENCE_AGENT_NAME = 'causyne-inference';
7
+ export const INFERENCE_AGENT_DEFINITION = `---
8
+ name: causyne-inference
9
+ description: Autonomous inference and execution engine for Causyne Agent across global developer workflows.
10
+ mainAgent: true
11
+ subagent: false
12
+ inheritMcp: true
13
+ ---
14
+ # System Prompt
15
+ You are an autonomous AI engineering engine operating in unison with Causyne Agent, built for billions of users worldwide.
16
+ You operate with full developer capabilities, preserving ACP, MCP, and native tooling interoperability.
17
+ Causyne coordinates the workspace, implementation checklist, and secure execution environment.
18
+ When invoking Causyne workspace tools, output:
19
+ <tool_call>{"name":"tool_name","arguments":{}}</tool_call>
20
+ Causyne Agent seamlessly maps, coordinates, and validates tool executions in the active workspace.
21
+ Never disable or degrade ACP capabilities. Retain full reasoning, execution capability, and professional engineering discipline.
22
+ The inference process directory is private adapter state, not the user's workspace. Work with the workspace paths supplied by Causyne. Never claim that a requested action happened without its tool result.
23
+ `;
24
+
25
+ /**
26
+ * Historical adapter-state helper, retained for compatibility checks only.
27
+ * Normal product sessions must not call this or substitute this workspace/profile.
28
+ */
29
+ export function ensureAntigravityBridgeWorkspace(): string {
30
+ const root = path.join(causyneHome(), 'provider-bridges', 'antigravity-inference-v1');
31
+ const agents = path.join(root, '.agents', 'agents');
32
+ for (const directory of [root, path.join(root, '.agents'), agents]) {
33
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
34
+ if (fs.lstatSync(directory).isSymbolicLink()) throw new Error('Causyne inference directory must not be a symlink');
35
+ }
36
+ const target = path.join(agents, `${INFERENCE_AGENT_NAME}.md`);
37
+ try {
38
+ if (fs.lstatSync(target).isSymbolicLink()) throw new Error('Causyne inference profile must not be a symlink');
39
+ if (fs.readFileSync(target, 'utf8') === INFERENCE_AGENT_DEFINITION) return root;
40
+ } catch (error: unknown) {
41
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
42
+ }
43
+ const temporary = path.join(agents, `.${randomUUID()}.tmp`);
44
+ try {
45
+ fs.writeFileSync(temporary, INFERENCE_AGENT_DEFINITION, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
46
+ fs.renameSync(temporary, target);
47
+ } finally {
48
+ try { fs.unlinkSync(temporary); } catch { /* Renamed or already removed. */ }
49
+ }
50
+ return root;
51
+ }
@@ -1,3 +1,5 @@
1
+ import type { RequestPermissionRequest, RequestPermissionResponse } from '../acp/protocol.js';
2
+
1
3
  export interface ProviderConfig {
2
4
  apiKey?: string | undefined;
3
5
  model?: string | undefined;
@@ -14,6 +16,7 @@ export interface ChatResponseUsage {
14
16
  promptTokens: number;
15
17
  completionTokens: number;
16
18
  cachedPromptTokens?: number | undefined;
19
+ uncachedPromptTokens?: number | undefined;
17
20
  measurement?: 'provider_reported' | 'text_estimate' | undefined;
18
21
  cacheMeasurement?: 'provider_reported' | 'unavailable' | undefined;
19
22
  totalTokens?: number | undefined;
@@ -30,6 +33,7 @@ export interface ChatResponseToolCall {
30
33
  }
31
34
 
32
35
  export interface ChatResponseAction {
36
+ id?: string | undefined;
33
37
  name: string;
34
38
  status: 'running' | 'completed' | 'failed';
35
39
  detail?: string | undefined;
@@ -47,6 +51,11 @@ export interface ChatResponse {
47
51
  }
48
52
 
49
53
  export interface ChatOptions {
54
+ onPeerPermission?: ((request: RequestPermissionRequest) => Promise<RequestPermissionResponse['outcome']>) | undefined;
55
+ onPeerFileRead?: ((file: string, options?: { line?: number; limit?: number }) => Promise<string>) | undefined;
56
+ onPeerFileWrite?: ((file: string, content: string) => Promise<void>) | undefined;
57
+ peerMcpServers?: unknown[] | undefined;
58
+ tokenBudgetBasis?: 'total' | 'noncached' | undefined;
50
59
  tools?: any[] | undefined;
51
60
  temperature?: number | undefined;
52
61
  maxRetries?: number | undefined;
@@ -0,0 +1,110 @@
1
+ export function noncachedTokens(usage) {
2
+ const finite = (value) => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
3
+ const input = usage.uncachedPromptTokens !== undefined
4
+ ? finite(usage.uncachedPromptTokens)
5
+ // Cache reads larger than input prove these are separate peer counters.
6
+ // Do not erase fresh input by subtracting that counter again.
7
+ : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
8
+ ? finite(usage.promptTokens)
9
+ : Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
10
+ return input + finite(usage.completionTokens);
11
+ }
12
+ export function actionLimitFor(archetype) {
13
+ if (archetype === 'desktop_personalization')
14
+ return 12;
15
+ if (archetype === 'media_3d_generation')
16
+ return 25;
17
+ return 35;
18
+ }
19
+ export function tokenLimitFor(archetype) {
20
+ if (archetype === 'desktop_personalization')
21
+ return 150_000;
22
+ if (archetype === 'media_3d_generation')
23
+ return 400_000;
24
+ if (archetype === 'web_engineering' || archetype === 'web_fullstack')
25
+ return 500_000;
26
+ return 100_000;
27
+ }
28
+ export function turnTokenLimitFor(archetype) {
29
+ if (archetype === 'web_engineering' || archetype === 'web_fullstack')
30
+ return 250_000;
31
+ if (archetype === 'media_3d_generation')
32
+ return 200_000;
33
+ if (archetype === 'desktop_personalization')
34
+ return 100_000;
35
+ return 100_000;
36
+ }
37
+ export class EfficiencyCheckpoint extends Error {
38
+ code = 'CAUSYNE_EFFICIENCY_CHECKPOINT';
39
+ reason;
40
+ used;
41
+ limit;
42
+ scope;
43
+ constructor(reason, used, limit, scope = 'task') {
44
+ const scopeLabel = scope === 'turn' ? 'single-turn' : 'task';
45
+ super(`Efficiency checkpoint: ${used.toLocaleString()} ${reason} reached the ${limit.toLocaleString()} ${scopeLabel} limit. `
46
+ + 'Work is unfinished. Session history is retained; continue from this checkpoint without repeating completed actions.');
47
+ this.name = 'EfficiencyCheckpoint';
48
+ this.reason = reason;
49
+ this.used = used;
50
+ this.limit = limit;
51
+ this.scope = scope;
52
+ }
53
+ }
54
+ export class UnifiedBudgetEnforcer {
55
+ maxTurnTokens;
56
+ maxTurnActions;
57
+ maxTaskTokens;
58
+ tokens = 0;
59
+ actions = 0;
60
+ nativeIds = new Set();
61
+ constructor(maxTurnTokens = 100_000, maxTurnActions = 35, maxTaskTokens) {
62
+ if (!Number.isFinite(maxTurnTokens) || maxTurnTokens <= 0
63
+ || !Number.isSafeInteger(maxTurnActions) || maxTurnActions <= 0) {
64
+ throw new Error('Invalid efficiency limits');
65
+ }
66
+ this.maxTurnTokens = maxTurnTokens;
67
+ this.maxTurnActions = maxTurnActions;
68
+ this.maxTaskTokens = typeof maxTaskTokens === 'number' && Number.isFinite(maxTaskTokens) && maxTaskTokens > 0
69
+ ? Math.max(maxTaskTokens, maxTurnTokens)
70
+ : maxTurnTokens;
71
+ }
72
+ recordUsage(usage) {
73
+ const fresh = noncachedTokens(usage);
74
+ if (fresh >= this.maxTurnTokens) {
75
+ throw new EfficiencyCheckpoint('tokens', fresh, this.maxTurnTokens, 'turn');
76
+ }
77
+ this.tokens += fresh;
78
+ if (this.tokens >= this.maxTaskTokens) {
79
+ throw new EfficiencyCheckpoint('tokens', this.tokens, this.maxTaskTokens, 'task');
80
+ }
81
+ }
82
+ recordAction(nativeId) {
83
+ if (nativeId && this.nativeIds.has(nativeId))
84
+ return;
85
+ if (this.actions >= this.maxTurnActions) {
86
+ throw new EfficiencyCheckpoint('actions', this.actions, this.maxTurnActions, 'task');
87
+ }
88
+ if (nativeId)
89
+ this.nativeIds.add(nativeId);
90
+ this.actions++;
91
+ }
92
+ getRemainingTokens() {
93
+ return Math.max(0, this.maxTaskTokens - this.tokens);
94
+ }
95
+ getRemainingTurnTokens() {
96
+ return this.maxTurnTokens;
97
+ }
98
+ getRemainingActions() {
99
+ return Math.max(0, this.maxTurnActions - this.actions);
100
+ }
101
+ snapshot() {
102
+ return {
103
+ noncachedTokens: this.tokens,
104
+ actions: this.actions,
105
+ tokenLimit: this.maxTurnTokens,
106
+ taskTokenLimit: this.maxTaskTokens,
107
+ actionLimit: this.maxTurnActions
108
+ };
109
+ }
110
+ }
@@ -0,0 +1,122 @@
1
+ /** Shared turn accounting for direct providers and agent peers. */
2
+ export interface BudgetUsage {
3
+ promptTokens: number;
4
+ completionTokens: number;
5
+ cachedPromptTokens?: number | undefined;
6
+ uncachedPromptTokens?: number | undefined;
7
+ measurement?: string | undefined;
8
+ }
9
+
10
+ export function noncachedTokens(usage: BudgetUsage): number {
11
+ const finite = (value: number | undefined): number => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
12
+ const input = usage.uncachedPromptTokens !== undefined
13
+ ? finite(usage.uncachedPromptTokens)
14
+ // Cache reads larger than input prove these are separate peer counters.
15
+ // Do not erase fresh input by subtracting that counter again.
16
+ : finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
17
+ ? finite(usage.promptTokens)
18
+ : Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
19
+ return input + finite(usage.completionTokens);
20
+ }
21
+
22
+ export function actionLimitFor(archetype: string): number {
23
+ if (archetype === 'desktop_personalization') return 12;
24
+ if (archetype === 'media_3d_generation') return 25;
25
+ return 35;
26
+ }
27
+
28
+ export function tokenLimitFor(archetype: string): number {
29
+ if (archetype === 'desktop_personalization') return 150_000;
30
+ if (archetype === 'media_3d_generation') return 400_000;
31
+ if (archetype === 'web_engineering' || archetype === 'web_fullstack') return 500_000;
32
+ return 100_000;
33
+ }
34
+
35
+ export function turnTokenLimitFor(archetype: string): number {
36
+ if (archetype === 'web_engineering' || archetype === 'web_fullstack') return 250_000;
37
+ if (archetype === 'media_3d_generation') return 200_000;
38
+ if (archetype === 'desktop_personalization') return 100_000;
39
+ return 100_000;
40
+ }
41
+
42
+ export class EfficiencyCheckpoint extends Error {
43
+ readonly code = 'CAUSYNE_EFFICIENCY_CHECKPOINT';
44
+ readonly reason: 'tokens' | 'actions';
45
+ readonly used: number;
46
+ readonly limit: number;
47
+ readonly scope: 'turn' | 'task';
48
+
49
+ constructor(reason: 'tokens' | 'actions', used: number, limit: number, scope: 'turn' | 'task' = 'task') {
50
+ const scopeLabel = scope === 'turn' ? 'single-turn' : 'task';
51
+ super(`Efficiency checkpoint: ${used.toLocaleString()} ${reason} reached the ${limit.toLocaleString()} ${scopeLabel} limit. `
52
+ + 'Work is unfinished. Session history is retained; continue from this checkpoint without repeating completed actions.');
53
+ this.name = 'EfficiencyCheckpoint';
54
+ this.reason = reason;
55
+ this.used = used;
56
+ this.limit = limit;
57
+ this.scope = scope;
58
+ }
59
+ }
60
+
61
+ export class UnifiedBudgetEnforcer {
62
+ readonly maxTurnTokens: number;
63
+ readonly maxTurnActions: number;
64
+ readonly maxTaskTokens: number;
65
+ private tokens = 0;
66
+ private actions = 0;
67
+ private readonly nativeIds = new Set<string>();
68
+
69
+ constructor(maxTurnTokens = 100_000, maxTurnActions = 35, maxTaskTokens?: number) {
70
+ if (!Number.isFinite(maxTurnTokens) || maxTurnTokens <= 0
71
+ || !Number.isSafeInteger(maxTurnActions) || maxTurnActions <= 0) {
72
+ throw new Error('Invalid efficiency limits');
73
+ }
74
+ this.maxTurnTokens = maxTurnTokens;
75
+ this.maxTurnActions = maxTurnActions;
76
+ this.maxTaskTokens = typeof maxTaskTokens === 'number' && Number.isFinite(maxTaskTokens) && maxTaskTokens > 0
77
+ ? Math.max(maxTaskTokens, maxTurnTokens)
78
+ : maxTurnTokens;
79
+ }
80
+
81
+ recordUsage(usage: BudgetUsage): void {
82
+ const fresh = noncachedTokens(usage);
83
+ if (fresh >= this.maxTurnTokens) {
84
+ throw new EfficiencyCheckpoint('tokens', fresh, this.maxTurnTokens, 'turn');
85
+ }
86
+ this.tokens += fresh;
87
+ if (this.tokens >= this.maxTaskTokens) {
88
+ throw new EfficiencyCheckpoint('tokens', this.tokens, this.maxTaskTokens, 'task');
89
+ }
90
+ }
91
+
92
+ recordAction(nativeId?: string): void {
93
+ if (nativeId && this.nativeIds.has(nativeId)) return;
94
+ if (this.actions >= this.maxTurnActions) {
95
+ throw new EfficiencyCheckpoint('actions', this.actions, this.maxTurnActions, 'task');
96
+ }
97
+ if (nativeId) this.nativeIds.add(nativeId);
98
+ this.actions++;
99
+ }
100
+
101
+ getRemainingTokens(): number {
102
+ return Math.max(0, this.maxTaskTokens - this.tokens);
103
+ }
104
+
105
+ getRemainingTurnTokens(): number {
106
+ return this.maxTurnTokens;
107
+ }
108
+
109
+ getRemainingActions(): number {
110
+ return Math.max(0, this.maxTurnActions - this.actions);
111
+ }
112
+
113
+ snapshot(): { noncachedTokens: number; actions: number; tokenLimit: number; taskTokenLimit: number; actionLimit: number } {
114
+ return {
115
+ noncachedTokens: this.tokens,
116
+ actions: this.actions,
117
+ tokenLimit: this.maxTurnTokens,
118
+ taskTokenLimit: this.maxTaskTokens,
119
+ actionLimit: this.maxTurnActions
120
+ };
121
+ }
122
+ }
@@ -0,0 +1,6 @@
1
+ /** Shared product behavior, independent of any developer machine or peer. */
2
+ export const PEER_COLLABORATION_POLICY = 'Causyne Agent is a general-purpose product intended for users worldwide, with a long-term ambition to serve billions. ' +
3
+ 'Causyne tools complement connected agents; they do not replace or disable the peer\'s native tools, MCP servers, skills, or configured capabilities. ' +
4
+ 'Use the user-selected workspace and preserve the peer\'s account and project configuration. ' +
5
+ 'All actions remain subject to user authorization, applicable permission policies, and truthful outcome reporting. ' +
6
+ 'A diagnostic probe does not define the permissions of a normal user session.';
@@ -0,0 +1,7 @@
1
+ /** Shared product behavior, independent of any developer machine or peer. */
2
+ export const PEER_COLLABORATION_POLICY =
3
+ 'Causyne Agent is a general-purpose product intended for users worldwide, with a long-term ambition to serve billions. ' +
4
+ 'Causyne tools complement connected agents; they do not replace or disable the peer\'s native tools, MCP servers, skills, or configured capabilities. ' +
5
+ 'Use the user-selected workspace and preserve the peer\'s account and project configuration. ' +
6
+ 'All actions remain subject to user authorization, applicable permission policies, and truthful outcome reporting. ' +
7
+ 'A diagnostic probe does not define the permissions of a normal user session.';
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @file src/providers/loopGuard.ts
3
+ * Causyne Agent — Sliding-Window Loop Guard & Context Overflow Detector
4
+ *
5
+ * Ported & elevated from Hermes Agent (gateway/bot_loop_guard.py & gateway/run_turn.py).
6
+ * Protects against conversational bounce-back, self-sustaining loops, and
7
+ * accurately detects context overflow without false positives from auth tokens.
8
+ *
9
+ * Authorship: Strict TypeScript (Causyne Agent).
10
+ */
11
+ const CONTEXT_OVERFLOW_PHRASES = [
12
+ 'request entity too large',
13
+ 'prompt is too long',
14
+ 'too many tokens',
15
+ 'context length exceeded',
16
+ 'maximum context length',
17
+ 'input is too long',
18
+ 'token limit exceeded',
19
+ 'exceeds model context window',
20
+ 'context window is full',
21
+ 'prompt token count exceeds',
22
+ 'string too long for context',
23
+ 'payload too large'
24
+ ];
25
+ export class CausyneLoopGuard {
26
+ timestamps = [];
27
+ inCooldownUntil = 0;
28
+ config;
29
+ constructor(customConfig) {
30
+ this.config = {
31
+ maxEvents: customConfig?.maxEvents ?? 15,
32
+ windowMs: customConfig?.windowMs ?? 120_000,
33
+ cooldownMs: customConfig?.cooldownMs ?? 300_000
34
+ };
35
+ }
36
+ recordAction() {
37
+ const now = Date.now();
38
+ if (now < this.inCooldownUntil) {
39
+ const waitSeconds = Math.ceil((this.inCooldownUntil - now) / 1000);
40
+ return {
41
+ allowed: false,
42
+ waitSeconds,
43
+ reason: `LoopGuard cooldown active. Rate limit exceeded; wait ${waitSeconds}s before retrying.`
44
+ };
45
+ }
46
+ // Prune events outside the sliding window
47
+ this.timestamps = this.timestamps.filter(t => now - t <= this.config.windowMs);
48
+ this.timestamps.push(now);
49
+ if (this.timestamps.length > this.config.maxEvents) {
50
+ this.inCooldownUntil = now + this.config.cooldownMs;
51
+ const waitSeconds = Math.ceil(this.config.cooldownMs / 1000);
52
+ return {
53
+ allowed: false,
54
+ waitSeconds,
55
+ reason: `LoopGuard threshold tripped: ${this.timestamps.length} actions within ${Math.round(this.config.windowMs / 1000)}s window. Cooldown enforced for ${waitSeconds}s.`
56
+ };
57
+ }
58
+ return { allowed: true };
59
+ }
60
+ reset() {
61
+ this.timestamps = [];
62
+ this.inCooldownUntil = 0;
63
+ }
64
+ getStatus() {
65
+ const now = Date.now();
66
+ const active = this.timestamps.filter(t => now - t <= this.config.windowMs).length;
67
+ const remaining = Math.max(0, this.inCooldownUntil - now);
68
+ return {
69
+ activeEvents: active,
70
+ inCooldown: remaining > 0,
71
+ remainingCooldownMs: remaining
72
+ };
73
+ }
74
+ }
75
+ /**
76
+ * Accurately classifies provider context overflow errors from stderr / error messages
77
+ * without false positives from API authentication tokens or general 400 Bad Requests.
78
+ */
79
+ export function isContextOverflowError(errorMessage) {
80
+ if (!errorMessage || typeof errorMessage !== 'string')
81
+ return false;
82
+ const normalized = errorMessage.toLowerCase();
83
+ return CONTEXT_OVERFLOW_PHRASES.some(phrase => normalized.includes(phrase));
84
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * @file src/providers/loopGuard.ts
3
+ * Causyne Agent — Sliding-Window Loop Guard & Context Overflow Detector
4
+ *
5
+ * Ported & elevated from Hermes Agent (gateway/bot_loop_guard.py & gateway/run_turn.py).
6
+ * Protects against conversational bounce-back, self-sustaining loops, and
7
+ * accurately detects context overflow without false positives from auth tokens.
8
+ *
9
+ * Authorship: Strict TypeScript (Causyne Agent).
10
+ */
11
+
12
+ export interface LoopGuardConfig {
13
+ maxEvents: number; // Default: 15 events
14
+ windowMs: number; // Default: 120,000 ms (2 minutes)
15
+ cooldownMs: number; // Default: 300,000 ms (5 minutes)
16
+ }
17
+
18
+ export interface LoopGuardCheckResult {
19
+ allowed: boolean;
20
+ waitSeconds?: number;
21
+ reason?: string;
22
+ }
23
+
24
+ const CONTEXT_OVERFLOW_PHRASES: readonly string[] = [
25
+ 'request entity too large',
26
+ 'prompt is too long',
27
+ 'too many tokens',
28
+ 'context length exceeded',
29
+ 'maximum context length',
30
+ 'input is too long',
31
+ 'token limit exceeded',
32
+ 'exceeds model context window',
33
+ 'context window is full',
34
+ 'prompt token count exceeds',
35
+ 'string too long for context',
36
+ 'payload too large'
37
+ ];
38
+
39
+ export class CausyneLoopGuard {
40
+ private timestamps: number[] = [];
41
+ private inCooldownUntil = 0;
42
+ private readonly config: LoopGuardConfig;
43
+
44
+ constructor(customConfig?: Partial<LoopGuardConfig>) {
45
+ this.config = {
46
+ maxEvents: customConfig?.maxEvents ?? 15,
47
+ windowMs: customConfig?.windowMs ?? 120_000,
48
+ cooldownMs: customConfig?.cooldownMs ?? 300_000
49
+ };
50
+ }
51
+
52
+ public recordAction(): LoopGuardCheckResult {
53
+ const now = Date.now();
54
+ if (now < this.inCooldownUntil) {
55
+ const waitSeconds = Math.ceil((this.inCooldownUntil - now) / 1000);
56
+ return {
57
+ allowed: false,
58
+ waitSeconds,
59
+ reason: `LoopGuard cooldown active. Rate limit exceeded; wait ${waitSeconds}s before retrying.`
60
+ };
61
+ }
62
+
63
+ // Prune events outside the sliding window
64
+ this.timestamps = this.timestamps.filter(t => now - t <= this.config.windowMs);
65
+ this.timestamps.push(now);
66
+
67
+ if (this.timestamps.length > this.config.maxEvents) {
68
+ this.inCooldownUntil = now + this.config.cooldownMs;
69
+ const waitSeconds = Math.ceil(this.config.cooldownMs / 1000);
70
+ return {
71
+ allowed: false,
72
+ waitSeconds,
73
+ reason: `LoopGuard threshold tripped: ${this.timestamps.length} actions within ${Math.round(this.config.windowMs / 1000)}s window. Cooldown enforced for ${waitSeconds}s.`
74
+ };
75
+ }
76
+
77
+ return { allowed: true };
78
+ }
79
+
80
+ public reset(): void {
81
+ this.timestamps = [];
82
+ this.inCooldownUntil = 0;
83
+ }
84
+
85
+ public getStatus(): { activeEvents: number; inCooldown: boolean; remainingCooldownMs: number } {
86
+ const now = Date.now();
87
+ const active = this.timestamps.filter(t => now - t <= this.config.windowMs).length;
88
+ const remaining = Math.max(0, this.inCooldownUntil - now);
89
+ return {
90
+ activeEvents: active,
91
+ inCooldown: remaining > 0,
92
+ remainingCooldownMs: remaining
93
+ };
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Accurately classifies provider context overflow errors from stderr / error messages
99
+ * without false positives from API authentication tokens or general 400 Bad Requests.
100
+ */
101
+ export function isContextOverflowError(errorMessage: unknown): boolean {
102
+ if (!errorMessage || typeof errorMessage !== 'string') return false;
103
+ const normalized = errorMessage.toLowerCase();
104
+ return CONTEXT_OVERFLOW_PHRASES.some(phrase => normalized.includes(phrase));
105
+ }
@@ -8,7 +8,7 @@ export const PI_SETUP_PROVIDER = {
8
8
  id: 'pi', label: 'Pi coding agent', hint: 'local Pi RPC · uses Causyne tools',
9
9
  category: 'Peer Agent', model: 'default'
10
10
  };
11
- /** Pi supplies reasoning over RPC; Causyne remains the sole executor of tools. */
11
+ /** Pi collaborates over RPC with its configured capabilities intact. */
12
12
  export class PiProvider extends LLMProvider {
13
13
  command;
14
14
  formatter;
@@ -21,8 +21,7 @@ export class PiProvider extends LLMProvider {
21
21
  this.audioModels = [];
22
22
  }
23
23
  async chat(messages, options = {}) {
24
- const args = ['--mode', 'rpc', '--no-session', '--no-tools', '--no-extensions',
25
- '--no-mcp', '--no-context-files', '--no-skills', '--no-prompt-templates'];
24
+ const args = ['--mode', 'rpc', '--no-session'];
26
25
  if (this.model !== 'default')
27
26
  args.push('--model', this.model);
28
27
  const cwd = typeof options.workspaceRoot === 'string' && options.workspaceRoot
@@ -41,6 +40,7 @@ export class PiProvider extends LLMProvider {
41
40
  let settled = false;
42
41
  let finished = false;
43
42
  let usage = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
43
+ const nativeActions = new Map();
44
44
  const cleanup = () => {
45
45
  options.signal?.removeEventListener('abort', abort);
46
46
  child.stdin.end();
@@ -67,6 +67,7 @@ export class PiProvider extends LLMProvider {
67
67
  resolve({
68
68
  content: raw.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim(),
69
69
  usage,
70
+ externalActions: [...nativeActions.values()].filter(action => action.status !== 'running'),
70
71
  toolCalls: this.formatter.extractToolCalls(raw)
71
72
  });
72
73
  };
@@ -109,6 +110,17 @@ export class PiProvider extends LLMProvider {
109
110
  options.onReasoningChunk?.(update.delta);
110
111
  }
111
112
  }
113
+ else if (record.type === 'tool_execution_start' || record.type === 'tool_execution_end') {
114
+ const id = String(record.toolCallId || '');
115
+ const earlier = nativeActions.get(id);
116
+ const action = {
117
+ id, name: String(record.toolName || earlier?.name || 'pi_tool'),
118
+ parameters: record.args || earlier?.parameters || {},
119
+ status: record.type === 'tool_execution_start' ? 'running' : record.isError ? 'failed' : 'completed'
120
+ };
121
+ nativeActions.set(id, action);
122
+ options.onNativeAction?.(action);
123
+ }
112
124
  else if (record.type === 'message_end' && record.message?.role === 'assistant') {
113
125
  const message = record.message;
114
126
  finalText = Array.isArray(message.content)
@@ -117,9 +129,10 @@ export class PiProvider extends LLMProvider {
117
129
  stopReason = String(message.stopReason || '');
118
130
  const data = message.usage || {};
119
131
  usage = {
120
- promptTokens: Number(data.input) || 0,
121
- completionTokens: Number(data.output) || 0,
122
- cachedPromptTokens: Number(data.cacheRead) || 0,
132
+ promptTokens: usage.promptTokens + (Number(data.input) || 0),
133
+ uncachedPromptTokens: (usage.uncachedPromptTokens || 0) + (Number(data.input) || 0),
134
+ completionTokens: usage.completionTokens + (Number(data.output) || 0),
135
+ cachedPromptTokens: (usage.cachedPromptTokens || 0) + (Number(data.cacheRead) || 0),
123
136
  measurement: data.input != null && data.output != null ? 'provider_reported' : 'text_estimate',
124
137
  cacheMeasurement: data.cacheRead != null ? 'provider_reported' : 'unavailable'
125
138
  };