@causyne/agent 1.19.0 → 1.20.5

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 (128) hide show
  1. package/README.md +0 -18
  2. package/package.json +1 -1
  3. package/src/acp/client.js +2 -1
  4. package/src/acp/client.ts +2 -1
  5. package/src/acp/server.js +5 -6
  6. package/src/acp/server.ts +4 -6
  7. package/src/agentLoop.d.ts +1 -0
  8. package/src/agentLoop.js +505 -241
  9. package/src/agentLoop.ts +527 -258
  10. package/src/agentPolicy.js +9 -0
  11. package/src/agentPolicy.ts +9 -0
  12. package/src/approvalPolicy.js +55 -0
  13. package/src/approvalPolicy.ts +66 -0
  14. package/src/browser/browserRuntime.js +217 -14
  15. package/src/browser/browserRuntime.ts +255 -14
  16. package/src/browser/causyneBrowser.js +1215 -68
  17. package/src/browser/causyneBrowser.ts +1340 -72
  18. package/src/cliMode.js +66 -37
  19. package/src/commands.js +343 -72
  20. package/src/config.js +22 -12
  21. package/src/continuum/ingest.js +1 -1
  22. package/src/continuum/ingest.ts +1 -1
  23. package/src/continuum/ui/continuumPicker.js +18 -1
  24. package/src/continuum/ui/continuumPicker.ts +19 -1
  25. package/src/dynamicCatalogue.js +87 -20
  26. package/src/dynamicCatalogue.ts +85 -15
  27. package/src/launchIntent.js +40 -0
  28. package/src/launchIntent.ts +49 -0
  29. package/src/memoryManager.js +36 -8
  30. package/src/modelCatalogue.js +2 -0
  31. package/src/planCache.js +320 -11
  32. package/src/planCache.ts +402 -13
  33. package/src/providers/acp.js +67 -1
  34. package/src/providers/acp.ts +65 -2
  35. package/src/providers/antigravity.d.ts +5 -1
  36. package/src/providers/antigravity.js +643 -32
  37. package/src/providers/antigravity.ts +671 -33
  38. package/src/providers/base.d.ts +9 -0
  39. package/src/providers/factory.js +2 -0
  40. package/src/providers/pi.js +157 -0
  41. package/src/providers/pi.ts +144 -0
  42. package/src/provisioning/capabilityProvisioner.js +17 -0
  43. package/src/provisioning/capabilityTools.js +1 -1
  44. package/src/sandbox.js +30 -39
  45. package/src/sessionJournal.js +66 -10
  46. package/src/sessionJournal.ts +84 -10
  47. package/src/taskShape.js +9 -9
  48. package/src/taskShape.ts +9 -9
  49. package/src/timeMachine.js +124 -0
  50. package/src/timeMachine.ts +141 -0
  51. package/src/toolPacks.js +4 -10
  52. package/src/tools/archive.js +196 -59
  53. package/src/tools/archive.ts +220 -0
  54. package/src/tools/browserAutomator.js +78 -9
  55. package/src/tools/browserAutomator.ts +90 -9
  56. package/src/tools/desktopOpen.js +114 -31
  57. package/src/tools/desktopOpen.ts +144 -0
  58. package/src/tools/gitExec.js +5 -3
  59. package/src/tools/nativeEngine.js +4 -3
  60. package/src/tools/nativeEngine.ts +5 -3
  61. package/src/tools/openSourceToolProvisioner.js +5 -4
  62. package/src/tools/openSourceToolProvisioner.ts +5 -4
  63. package/src/tools/registry.js +3 -0
  64. package/src/tools/screenshot.js +55 -71
  65. package/src/tools/screenshot.ts +70 -0
  66. package/src/tools/sysRun.js +284 -117
  67. package/src/tools/sysRun.ts +347 -0
  68. package/src/tools/toolSelfRepair.js +109 -2
  69. package/src/tools/toolSelfRepair.ts +100 -2
  70. package/src/tools/updatePlan.js +49 -1
  71. package/src/tools/updatePlan.ts +43 -1
  72. package/src/tools/viewImage.js +93 -78
  73. package/src/tools/viewImage.ts +116 -0
  74. package/src/tools/webFetch.js +20 -6
  75. package/src/tools/webFetch.ts +26 -6
  76. package/src/tui/block.d.ts +1 -0
  77. package/src/tui/chatRenderer.d.ts +21 -0
  78. package/src/tui/chatRenderer.js +118 -45
  79. package/src/tui/clipboardSync.js +28 -1
  80. package/src/tui/clipboardSync.ts +26 -1
  81. package/src/tui/codeProgress.js +299 -0
  82. package/src/tui/codeProgress.ts +304 -0
  83. package/src/tui/codeStreamRenderer.js +116 -0
  84. package/src/tui/codeStreamRenderer.ts +124 -0
  85. package/src/tui/commandPresentation.js +11 -0
  86. package/src/tui/commandPresentation.ts +18 -0
  87. package/src/tui/completion.js +45 -13
  88. package/src/tui/composerControls.js +66 -0
  89. package/src/tui/composerControls.ts +78 -0
  90. package/src/tui/diff.d.ts +2 -0
  91. package/src/tui/home.js +4 -2
  92. package/src/tui/homeTransition.js +21 -0
  93. package/src/tui/homeTransition.ts +27 -0
  94. package/src/tui/homeView.js +62 -0
  95. package/src/tui/homeView.ts +91 -0
  96. package/src/tui/layout.js +46 -0
  97. package/src/tui/layout.ts +52 -0
  98. package/src/tui/messageActionPlacement.js +16 -0
  99. package/src/tui/messageActionPlacement.ts +25 -0
  100. package/src/tui/messageInteraction.js +221 -0
  101. package/src/tui/messageInteraction.ts +275 -0
  102. package/src/tui/modelPicker.js +13 -0
  103. package/src/tui/modelPicker.ts +12 -0
  104. package/src/tui/mouseHover.js +6 -0
  105. package/src/tui/mouseHover.ts +5 -0
  106. package/src/tui/prompt.js +199 -52
  107. package/src/tui/resizeRecovery.js +15 -0
  108. package/src/tui/resizeRecovery.ts +27 -0
  109. package/src/tui/scrollInteraction.js +97 -0
  110. package/src/tui/scrollInteraction.ts +189 -0
  111. package/src/tui/sessionLayout.js +12 -0
  112. package/src/tui/sessionLayout.ts +12 -0
  113. package/src/tui/sessionPicker.js +280 -0
  114. package/src/tui/sessionPicker.ts +364 -0
  115. package/src/tui/sessionSidebar.js +78 -0
  116. package/src/tui/sessionSidebar.ts +95 -0
  117. package/src/tui/setup.js +1 -1
  118. package/src/tui/setup.ts +1 -1
  119. package/src/tui/stageSurface.js +128 -57
  120. package/src/tui/statusLine.js +5 -5
  121. package/src/tui/text.d.ts +5 -0
  122. package/src/tui/textLayout.js +23 -0
  123. package/src/tui/textLayout.ts +28 -0
  124. package/src/tui/viewport.js +204 -279
  125. package/src/tui/viewport.ts +326 -0
  126. package/src/types/contracts.ts +54 -0
  127. package/src/utils/paths.js +5 -4
  128. package/src/utils/paths.ts +5 -5
@@ -27,12 +27,20 @@ export interface ChatResponseToolCall {
27
27
  };
28
28
  }
29
29
 
30
+ export interface ChatResponseAction {
31
+ name: string;
32
+ status: 'running' | 'completed' | 'failed';
33
+ detail?: string | undefined;
34
+ parameters?: Record<string, unknown> | undefined;
35
+ }
36
+
30
37
  export interface ChatResponse {
31
38
  content: string;
32
39
  usage: ChatResponseUsage;
33
40
  toolCalls?: ChatResponseToolCall[] | undefined;
34
41
  reasoningContent?: string | undefined;
35
42
  thinkingBlocks?: any[] | undefined;
43
+ externalActions?: ChatResponseAction[] | undefined;
36
44
  }
37
45
 
38
46
  export interface ChatOptions {
@@ -42,6 +50,7 @@ export interface ChatOptions {
42
50
  signal?: AbortSignal | undefined;
43
51
  onChunk?: ((chunk: string) => void) | undefined;
44
52
  onReasoningChunk?: ((chunk: string) => void) | undefined;
53
+ onNativeAction?: ((action: ChatResponseAction) => void) | undefined;
45
54
  coreToolCount?: number | undefined;
46
55
  [key: string]: any;
47
56
  }
@@ -17,6 +17,7 @@ import { XAIProvider } from './xai.js';
17
17
  import { MoonshotProvider } from './moonshot.js';
18
18
  import { MuseProvider } from './muse.js';
19
19
  import { AcpProvider, isAcpProvider } from './acp.js';
20
+ import { PiProvider, isPiProvider } from './pi.js';
20
21
  import { AntigravityProvider, isAntigravityProvider } from './antigravity.js';
21
22
 
22
23
  export function createProvider(config) {
@@ -35,6 +36,7 @@ export function createProvider(config) {
35
36
  // model family is Muse, and users say either.
36
37
  if (p === 'muse' || p === 'meta') return new MuseProvider(config);
37
38
  if (isAcpProvider(p)) return new AcpProvider(config);
39
+ if (isPiProvider(p)) return new PiProvider(config);
38
40
  if (isAntigravityProvider(p)) return new AntigravityProvider(config);
39
41
 
40
42
  throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
@@ -0,0 +1,157 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { AcpProvider } from './acp.js';
3
+ import { LLMProvider } from './base.js';
4
+ export function isPiProvider(provider) {
5
+ return typeof provider === 'string' && provider.toLowerCase() === 'pi';
6
+ }
7
+ export const PI_SETUP_PROVIDER = {
8
+ id: 'pi', label: 'Pi coding agent', hint: 'local Pi RPC · uses Causyne tools',
9
+ category: 'Peer Agent', model: 'default'
10
+ };
11
+ /** Pi supplies reasoning over RPC; Causyne remains the sole executor of tools. */
12
+ export class PiProvider extends LLMProvider {
13
+ command;
14
+ formatter;
15
+ constructor(config = {}) {
16
+ super(config);
17
+ this.command = config.command || 'pi';
18
+ this.model = config.model || 'default';
19
+ this.formatter = new AcpProvider({ provider: 'acp/opencode' });
20
+ this.visionModels = [];
21
+ this.audioModels = [];
22
+ }
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'];
26
+ if (this.model !== 'default')
27
+ args.push('--model', this.model);
28
+ const cwd = typeof options.workspaceRoot === 'string' && options.workspaceRoot
29
+ ? options.workspaceRoot : process.cwd();
30
+ const prompt = this.formatter.formatConversation(messages, options.tools || [])
31
+ .replace('over ACP.', 'over Pi RPC.');
32
+ return new Promise((resolve, reject) => {
33
+ const child = spawn(this.command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'],
34
+ env: process.env, shell: false });
35
+ let buffer = '';
36
+ let stderr = '';
37
+ let streamed = '';
38
+ let finalText = '';
39
+ let stopReason = '';
40
+ let acknowledged = false;
41
+ let settled = false;
42
+ let finished = false;
43
+ let usage = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
44
+ const cleanup = () => {
45
+ options.signal?.removeEventListener('abort', abort);
46
+ child.stdin.end();
47
+ if (!child.killed)
48
+ child.kill();
49
+ };
50
+ const fail = (error) => {
51
+ if (finished)
52
+ return;
53
+ finished = true;
54
+ cleanup();
55
+ reject(error);
56
+ };
57
+ const complete = () => {
58
+ if (finished || !acknowledged || !settled)
59
+ return;
60
+ if (stopReason === 'error' || stopReason === 'aborted') {
61
+ fail(new Error(`Pi ended with ${stopReason}${stderr ? `: ${stderr.slice(-400)}` : ''}`));
62
+ return;
63
+ }
64
+ finished = true;
65
+ cleanup();
66
+ const raw = finalText || streamed;
67
+ resolve({
68
+ content: raw.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim(),
69
+ usage,
70
+ toolCalls: this.formatter.extractToolCalls(raw)
71
+ });
72
+ };
73
+ const abort = () => fail(new Error('Pi request aborted'));
74
+ if (options.signal?.aborted) {
75
+ abort();
76
+ return;
77
+ }
78
+ options.signal?.addEventListener('abort', abort, { once: true });
79
+ const handle = (record) => {
80
+ if (record.type === 'response' && record.id === 'causyne-state') {
81
+ if (!record.success || !record.data?.model
82
+ || record.data.model.provider === 'unknown' || record.data.model.id === 'unknown') {
83
+ fail(new Error('Pi has no active model. Open Pi and configure a model login before selecting Pi in Causyne.'));
84
+ return;
85
+ }
86
+ child.stdin.write(JSON.stringify({ id: 'causyne-prompt', type: 'prompt', message: prompt }) + '\n');
87
+ }
88
+ else if (record.type === 'response' && record.id === 'causyne-prompt') {
89
+ if (!record.success) {
90
+ fail(new Error(`Pi rejected the prompt: ${String(record.error || 'unknown error')}`));
91
+ return;
92
+ }
93
+ acknowledged = true;
94
+ if (record.data?.disposition === 'handled')
95
+ settled = true;
96
+ complete();
97
+ }
98
+ else if (record.type === 'message_update') {
99
+ const update = record.assistantMessageEvent;
100
+ if (update?.type === 'text_delta' && typeof update.delta === 'string') {
101
+ streamed += update.delta;
102
+ options.onChunk?.(update.delta);
103
+ }
104
+ else if (update?.type === 'thinking_delta' && typeof update.delta === 'string') {
105
+ options.onReasoningChunk?.(update.delta);
106
+ }
107
+ }
108
+ else if (record.type === 'message_end' && record.message?.role === 'assistant') {
109
+ const message = record.message;
110
+ finalText = Array.isArray(message.content)
111
+ ? message.content.filter((part) => part?.type === 'text').map((part) => String(part.text || '')).join('')
112
+ : String(message.content || '');
113
+ stopReason = String(message.stopReason || '');
114
+ const data = message.usage || {};
115
+ usage = {
116
+ promptTokens: Number(data.input) || 0,
117
+ completionTokens: Number(data.output) || 0,
118
+ cachedPromptTokens: Number(data.cacheRead) || 0
119
+ };
120
+ }
121
+ else if (record.type === 'agent_settled') {
122
+ if (record.aborted)
123
+ stopReason = 'aborted';
124
+ settled = true;
125
+ complete();
126
+ }
127
+ };
128
+ child.stdout.setEncoding('utf8');
129
+ child.stdout.on('data', (chunk) => {
130
+ buffer += chunk;
131
+ let index;
132
+ while ((index = buffer.indexOf('\n')) >= 0) {
133
+ const line = buffer.slice(0, index).replace(/\r$/, '');
134
+ buffer = buffer.slice(index + 1);
135
+ if (!line)
136
+ continue;
137
+ try {
138
+ handle(JSON.parse(line));
139
+ }
140
+ catch (error) {
141
+ fail(new Error(`Invalid Pi RPC record: ${String(error)}`));
142
+ return;
143
+ }
144
+ }
145
+ });
146
+ child.stderr.setEncoding('utf8');
147
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-2000); });
148
+ child.on('error', error => fail(new Error(`Pi CLI unavailable: ${error.message}`)));
149
+ child.on('close', code => {
150
+ if (!finished)
151
+ fail(new Error(`Pi RPC exited before completion (${code ?? 'unknown'})${stderr ? `: ${stderr.slice(-400)}` : ''}`));
152
+ });
153
+ child.stdin.on('error', error => fail(new Error(`Pi RPC input failed: ${error.message}`)));
154
+ child.stdin.write(JSON.stringify({ id: 'causyne-state', type: 'get_state' }) + '\n');
155
+ });
156
+ }
157
+ }
@@ -0,0 +1,144 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { AcpProvider } from './acp.js';
3
+ import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse } from './base.js';
4
+
5
+ export function isPiProvider(provider?: string | null): boolean {
6
+ return typeof provider === 'string' && provider.toLowerCase() === 'pi';
7
+ }
8
+
9
+ export const PI_SETUP_PROVIDER = {
10
+ id: 'pi', label: 'Pi coding agent', hint: 'local Pi RPC · uses Causyne tools',
11
+ category: 'Peer Agent', model: 'default'
12
+ };
13
+
14
+ /** Pi supplies reasoning over RPC; Causyne remains the sole executor of tools. */
15
+ export class PiProvider extends LLMProvider {
16
+ private readonly command: string;
17
+ private readonly formatter: AcpProvider;
18
+
19
+ constructor(config: ProviderConfig = {}) {
20
+ super(config);
21
+ this.command = config.command || 'pi';
22
+ this.model = config.model || 'default';
23
+ this.formatter = new AcpProvider({ provider: 'acp/opencode' });
24
+ this.visionModels = [];
25
+ this.audioModels = [];
26
+ }
27
+
28
+ override async chat(messages: unknown[], options: ChatOptions = {}): Promise<ChatResponse> {
29
+ const args = ['--mode', 'rpc', '--no-session', '--no-tools', '--no-extensions',
30
+ '--no-mcp', '--no-context-files', '--no-skills', '--no-prompt-templates'];
31
+ if (this.model !== 'default') args.push('--model', this.model);
32
+ const cwd = typeof options.workspaceRoot === 'string' && options.workspaceRoot
33
+ ? options.workspaceRoot : process.cwd();
34
+ const prompt = this.formatter.formatConversation(messages, options.tools || [])
35
+ .replace('over ACP.', 'over Pi RPC.');
36
+
37
+ return new Promise<ChatResponse>((resolve, reject) => {
38
+ const child = spawn(this.command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'],
39
+ env: process.env, shell: false });
40
+ let buffer = '';
41
+ let stderr = '';
42
+ let streamed = '';
43
+ let finalText = '';
44
+ let stopReason = '';
45
+ let acknowledged = false;
46
+ let settled = false;
47
+ let finished = false;
48
+ let usage = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
49
+
50
+ const cleanup = (): void => {
51
+ options.signal?.removeEventListener('abort', abort);
52
+ child.stdin.end();
53
+ if (!child.killed) child.kill();
54
+ };
55
+ const fail = (error: Error): void => {
56
+ if (finished) return;
57
+ finished = true;
58
+ cleanup();
59
+ reject(error);
60
+ };
61
+ const complete = (): void => {
62
+ if (finished || !acknowledged || !settled) return;
63
+ if (stopReason === 'error' || stopReason === 'aborted') {
64
+ fail(new Error(`Pi ended with ${stopReason}${stderr ? `: ${stderr.slice(-400)}` : ''}`));
65
+ return;
66
+ }
67
+ finished = true;
68
+ cleanup();
69
+ const raw = finalText || streamed;
70
+ resolve({
71
+ content: raw.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim(),
72
+ usage,
73
+ toolCalls: this.formatter.extractToolCalls(raw)
74
+ });
75
+ };
76
+ const abort = (): void => fail(new Error('Pi request aborted'));
77
+ if (options.signal?.aborted) { abort(); return; }
78
+ options.signal?.addEventListener('abort', abort, { once: true });
79
+
80
+ const handle = (record: Record<string, any>): void => {
81
+ if (record.type === 'response' && record.id === 'causyne-state') {
82
+ if (!record.success || !record.data?.model
83
+ || record.data.model.provider === 'unknown' || record.data.model.id === 'unknown') {
84
+ fail(new Error('Pi has no active model. Open Pi and configure a model login before selecting Pi in Causyne.'));
85
+ return;
86
+ }
87
+ child.stdin.write(JSON.stringify({ id: 'causyne-prompt', type: 'prompt', message: prompt }) + '\n');
88
+ } else if (record.type === 'response' && record.id === 'causyne-prompt') {
89
+ if (!record.success) {
90
+ fail(new Error(`Pi rejected the prompt: ${String(record.error || 'unknown error')}`));
91
+ return;
92
+ }
93
+ acknowledged = true;
94
+ if (record.data?.disposition === 'handled') settled = true;
95
+ complete();
96
+ } else if (record.type === 'message_update') {
97
+ const update = record.assistantMessageEvent;
98
+ if (update?.type === 'text_delta' && typeof update.delta === 'string') {
99
+ streamed += update.delta;
100
+ options.onChunk?.(update.delta);
101
+ } else if (update?.type === 'thinking_delta' && typeof update.delta === 'string') {
102
+ options.onReasoningChunk?.(update.delta);
103
+ }
104
+ } else if (record.type === 'message_end' && record.message?.role === 'assistant') {
105
+ const message = record.message;
106
+ finalText = Array.isArray(message.content)
107
+ ? message.content.filter((part: any) => part?.type === 'text').map((part: any) => String(part.text || '')).join('')
108
+ : String(message.content || '');
109
+ stopReason = String(message.stopReason || '');
110
+ const data = message.usage || {};
111
+ usage = {
112
+ promptTokens: Number(data.input) || 0,
113
+ completionTokens: Number(data.output) || 0,
114
+ cachedPromptTokens: Number(data.cacheRead) || 0
115
+ };
116
+ } else if (record.type === 'agent_settled') {
117
+ if (record.aborted) stopReason = 'aborted';
118
+ settled = true;
119
+ complete();
120
+ }
121
+ };
122
+ child.stdout.setEncoding('utf8');
123
+ child.stdout.on('data', (chunk: string) => {
124
+ buffer += chunk;
125
+ let index: number;
126
+ while ((index = buffer.indexOf('\n')) >= 0) {
127
+ const line = buffer.slice(0, index).replace(/\r$/, '');
128
+ buffer = buffer.slice(index + 1);
129
+ if (!line) continue;
130
+ try { handle(JSON.parse(line) as Record<string, any>); }
131
+ catch (error) { fail(new Error(`Invalid Pi RPC record: ${String(error)}`)); return; }
132
+ }
133
+ });
134
+ child.stderr.setEncoding('utf8');
135
+ child.stderr.on('data', (chunk: string) => { stderr = (stderr + chunk).slice(-2000); });
136
+ child.on('error', error => fail(new Error(`Pi CLI unavailable: ${error.message}`)));
137
+ child.on('close', code => {
138
+ if (!finished) fail(new Error(`Pi RPC exited before completion (${code ?? 'unknown'})${stderr ? `: ${stderr.slice(-400)}` : ''}`));
139
+ });
140
+ child.stdin.on('error', error => fail(new Error(`Pi RPC input failed: ${error.message}`)));
141
+ child.stdin.write(JSON.stringify({ id: 'causyne-state', type: 'get_state' }) + '\n');
142
+ });
143
+ }
144
+ }
@@ -8,6 +8,7 @@ import { pathToFileURL } from 'url';
8
8
  import { loadConfig, saveConfig } from '../config.js';
9
9
  import { isGroupGranted, isGroupDeclined } from './capabilityConsent.js';
10
10
  import { causyneHome } from '../utils/paths.js';
11
+ import { currentToolAutonomyMode } from '../approvalPolicy.js';
11
12
 
12
13
  const CAPABILITY_DIR = path.join(causyneHome(), 'capabilities');
13
14
 
@@ -185,11 +186,27 @@ export async function provisionCapabilities(groups = []) {
185
186
  * unavailable, not that something crashed.
186
187
  */
187
188
  export async function ensureCapability(group) {
189
+ if (isGroupDeclined(group)) {
190
+ return { ok: false, group, reason: `The "${group}" capability was explicitly disabled by the user.` };
191
+ }
188
192
  const status = groupStatus(group);
189
193
  if (status.state === 'ready') return { ok: true, group };
190
194
  if (status.state === 'unknown') return { ok: false, group, reason: `Unknown capability group "${group}".` };
191
195
 
192
196
  if (status.state === 'needs-consent') {
197
+ // Mode C authorizes installation needed by the in-scope tool call. This
198
+ // does not persist a standing capability grant across sessions. A group
199
+ // explicitly revoked by the user stays disabled.
200
+ if (currentToolAutonomyMode() === 'C' && !isGroupDeclined(group)) {
201
+ try {
202
+ await provisionCapabilities([group]);
203
+ } catch (e) {
204
+ return { ok: false, group, reason: `The "${group}" capability could not be prepared: ${e.message}` };
205
+ }
206
+ return isGroupInstalled(group)
207
+ ? { ok: true, group }
208
+ : { ok: false, group, reason: `The "${group}" capability is unavailable in this environment.` };
209
+ }
193
210
  return {
194
211
  ok: false,
195
212
  group,
@@ -15,7 +15,7 @@ export const TOOLS_BY_GROUP = {
15
15
  vision: ['screenshot', 'vision_inspect_ui', 'game_canvas_audit', 'game_web_runtime_inspector'],
16
16
  ocr: [],
17
17
  system: ['process_list'],
18
- desktop: ['clipboard', 'desktop_open'],
18
+ desktop: ['clipboard'],
19
19
  archive: ['archive']
20
20
  };
21
21
 
package/src/sandbox.js CHANGED
@@ -3,6 +3,7 @@ import os from 'os';
3
3
  import { isIP } from 'node:net';
4
4
  import { loadConfig } from './config.js';
5
5
  import { isDevEmulator } from './devMode.js';
6
+ import { validateBrowserActSandbox } from './browser/causyneBrowser.js';
6
7
 
7
8
 
8
9
  function maskQuotedSpans(text) {
@@ -99,8 +100,8 @@ const INTERPRETER_INVOCATION = /(^|\s)(sh|bash|zsh|ksh|dash|fish|eval|xargs|ssh|
99
100
  *
100
101
  * A user may deliberately select a workspace that contains credential material.
101
102
  * These paths are not silently trusted just because they sit below that root:
102
- * touching one is classified 'extreme', which always requires explicit approval
103
- * in every autonomy mode, including Mode C.
103
+ * touching one is classified 'extreme' for supervised-mode approval and audit.
104
+ * Mode C still applies the selected-workspace boundary and hard safety blocks.
104
105
  */
105
106
  const CREDENTIAL_PATHS = [
106
107
  /(^|\/)\.ssh(\/|$)/,
@@ -243,9 +244,8 @@ export class Sandbox {
243
244
  }
244
245
  }
245
246
 
246
- // L4: when an explicitly selected workspace contains credential material,
247
- // it gets a human in the loop rather than silent access. 'extreme' is the
248
- // one risk level Mode C cannot auto-approve.
247
+ // L4: classify credential material in an explicitly selected workspace as
248
+ // extreme. The approval policy interprets that signal by autonomy mode.
249
249
  for (const p of pathsToCheck) {
250
250
  if (typeof p === 'string' && isCredentialPath(p)) {
251
251
  return { allowed: true, risk: 'extreme', reason: `Touches credential material: ${p}` };
@@ -267,6 +267,15 @@ export class Sandbox {
267
267
  return { allowed: true, risk: 'moderate' };
268
268
  }
269
269
 
270
+ if (toolName === 'gitOp') {
271
+ const command = String(args.command || '');
272
+ const risk = this.classifyCommandRisk(`git ${command}`);
273
+ if (risk === 'forbidden') {
274
+ return { allowed: false, reason: 'Command is permanently blocked for safety', risk: 'forbidden' };
275
+ }
276
+ return { allowed: true, risk: /\bbranch\s+-D\b/.test(command) ? 'dangerous' : risk };
277
+ }
278
+
270
279
  // 4. SSRF protection (for web fetch)
271
280
  if (toolName === 'web_fetch' && args.url) {
272
281
  if (this.isInternalUrl(args.url)) {
@@ -278,24 +287,12 @@ export class Sandbox {
278
287
  }
279
288
 
280
289
  if (toolName === 'browser_act') {
281
- const actions = Array.isArray(args.actions) ? args.actions : [];
282
- let hasDownload = false;
283
- for (const action of actions) {
284
- if (action && action.url && this.isInternalUrl(action.url)) {
285
- return { allowed: false, reason: 'Cannot navigate the agent browser to an internal or invalid URL', risk: 'forbidden' };
286
- }
287
- if (action && ['download', 'screenshot'].includes(action.type)) {
288
- if (!action.outputFile || !this.isPathAllowed(path.resolve(this.workspacePaths[0], action.outputFile))) {
289
- return { allowed: false, reason: 'Browser downloads must stay inside the selected workspace', risk: 'forbidden' };
290
- }
291
- hasDownload = true;
292
- }
293
- }
294
- if (hasDownload) return { allowed: true, risk: 'extreme', reason: 'Writes browser content to the selected workspace' };
295
- if (actions.some(action => ['click', 'clickIndex', 'type', 'typeIndex', 'selectOption', 'keyPress'].includes(action?.type))) {
296
- return { allowed: true, risk: 'dangerous', reason: 'Interacts with a website through the dedicated agent browser' };
297
- }
298
- return { allowed: true, risk: 'safe' };
290
+ return validateBrowserActSandbox(
291
+ args,
292
+ this.workspacePaths[0],
293
+ url => this.isInternalUrl(url),
294
+ targetPath => this.isPathAllowed(targetPath)
295
+ );
299
296
  }
300
297
 
301
298
  if (toolName === 'creative_apps') {
@@ -317,24 +314,21 @@ export class Sandbox {
317
314
  return { allowed: true, risk: 'extreme', reason: 'Downloads a third-party asset to disk' };
318
315
  }
319
316
 
320
- // Heavy AI downloads ALWAYS require consent (even in Mode C)
317
+ // Keep downloads classified as extreme for supervised modes and auditing.
318
+ // Mode C approval is decided separately by the TypeScript approval policy.
321
319
  if (toolName === 'manage_local_dependencies') {
322
320
  // grant_capability installs third-party packages into the user's home
323
- // directory, so it belongs in exactly the same consent class as the other
324
- // download actions. Routing it here is what keeps ZM-01 true: nothing is
325
- // ever installed without an explicit human approval.
321
+ // directory. Classification remains visible even when Mode C proceeds.
326
322
  const heavyActions = ['pipInst', 'grant_capability', 'grant_mcp_server'];
327
323
  if (heavyActions.includes(args.action)) {
328
- return { allowed: true, risk: 'extreme' }; // Upgraded from dangerous to extreme for safe C Mode handling
324
+ return { allowed: true, risk: 'extreme' };
329
325
  }
330
326
  return { allowed: true, risk: 'moderate' };
331
327
  }
332
328
 
333
- // Plugins are code extensions. Creation and enablement change the future
334
- // executable surface, and an enabled plugin call crosses from Causyne's
335
- // reviewed code into user/third-party code. Keep both explicit and
336
- // session-revocable even though the plugin process also runs under Node's
337
- // filesystem/network/child-process permission model.
329
+ // Plugins are code extensions. Keep their risk classification visible to
330
+ // supervised modes and audit logs; Mode C still uses workspace and hard
331
+ // policy checks before execution.
338
332
  if (toolName === 'plugin_manager') {
339
333
  return ['create', 'enable'].includes(args.action)
340
334
  ? { allowed: true, risk: 'extreme', reason: 'Creates or trusts executable plugin code' }
@@ -359,12 +353,9 @@ export class Sandbox {
359
353
  if (toolName === 'proc_term') {
360
354
  return { allowed: true, risk: 'dangerous' };
361
355
  }
362
- // Driving the mouse and keyboard reaches every application the user is
363
- // signed into — mail, banking, anything with a session open. There is no
364
- // safe subset and no autonomy mode in which it should run unannounced, so
365
-
366
- // Mode C. Section 4 says gated, not walled — the capability is real, the
367
- // human just says yes first.
356
+ // Desktop interaction reaches applications the user is signed into.
357
+ // Keep the extreme risk signal for supervised modes and auditing; Mode C
358
+ // follows the owner's autonomous approval policy after hard checks.
368
359
  if (toolName === 'desktop_act' || toolName === 'computer_use') {
369
360
  return { allowed: true, risk: 'extreme' };
370
361
  }
@@ -224,6 +224,20 @@ export function titleFrom(text) {
224
224
  return 'Untitled';
225
225
  return clean.length > 60 ? `${clean.slice(0, 57)}…` : clean;
226
226
  }
227
+ const PLACEHOLDER_TITLE = /^(?:untitled|hi|hello|hey|halo|hai|continue|lanjut|open it(?: for me)?|new session\b.*)$/i;
228
+ const NON_TASK_MESSAGE = /^(?:hi|hello|hey|halo|hai|continue|lanjut|open it|open it for me|thanks|thank you)[.!?\s]*$/i;
229
+ /** Recover a useful title when a session began with a greeting or placeholder. */
230
+ function sessionTitle(title, messages, createdAt) {
231
+ if (title.trim() && !PLACEHOLDER_TITLE.test(title.trim()))
232
+ return title;
233
+ const prompt = messages.find((message) => {
234
+ if (message.role !== 'user' || typeof message.content !== 'string')
235
+ return false;
236
+ const text = message.content.trim();
237
+ return text.length > 12 && !NON_TASK_MESSAGE.test(text) && !text.startsWith('[decayed]');
238
+ });
239
+ return prompt ? titleFrom(prompt.content) : `New session - ${new Date(createdAt).toISOString().replace('T', ' ').slice(0, 16)} UTC`;
240
+ }
227
241
  export function listSessions() {
228
242
  try {
229
243
  ensureDir();
@@ -239,7 +253,7 @@ export function listSessions() {
239
253
  if (!session)
240
254
  continue;
241
255
  const { messages, ...metadata } = session;
242
- rows.push({ ...metadata, messageCount: messages.length });
256
+ rows.push({ ...metadata, title: sessionTitle(metadata.title, messages, metadata.createdAt), messageCount: messages.length });
243
257
  }
244
258
  return rows.sort((left, right) => right.updatedAt - left.updatedAt);
245
259
  }
@@ -280,8 +294,9 @@ export function createSession(workspace, title = 'Untitled', makeActive = true)
280
294
  writeNewTranscript(session);
281
295
  if (makeActive)
282
296
  setActiveSession(session.id);
283
- pruneSessions();
284
- return session;
297
+ // Session creation must never silently delete older conversations. Retention
298
+ // is an explicit maintenance operation, separate from starting a chat.
299
+ return { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) };
285
300
  }
286
301
  /**
287
302
  * Read one conversation without making it the active session.
@@ -290,7 +305,8 @@ export function createSession(workspace, title = 'Untitled', makeActive = true)
290
305
  * they only need the transcript that belongs to their own id.
291
306
  */
292
307
  export function getSession(id) {
293
- return readSession(id);
308
+ const session = readSession(id);
309
+ return session ? { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) } : null;
294
310
  }
295
311
  export function getActiveSessionId() {
296
312
  try {
@@ -314,12 +330,25 @@ export function setActiveSession(id) {
314
330
  return false;
315
331
  }
316
332
  }
317
- export function resolveSession(workspace) {
333
+ export function resolveSession(workspace, options = {}) {
318
334
  const workspaceText = String(workspace ?? '');
319
335
  ensureDir();
320
336
  migrateLegacyHistory(workspaceText);
337
+ if (options.forceNew) {
338
+ return createSession(workspaceText);
339
+ }
321
340
  const key = workspaceKey(workspaceText);
322
341
  const now = Date.now();
342
+ // 1. Check preferred session or active.json pointer for this workspace
343
+ const targetId = options.preferredId || getActiveSessionId();
344
+ if (targetId) {
345
+ const active = readSession(targetId);
346
+ if (active && (!active.workspace || active.workspaceKey === key) && now - active.updatedAt < RESUME_WINDOW_MS) {
347
+ setActiveSession(active.id);
348
+ return { ...active, title: sessionTitle(active.title, active.messages, active.createdAt) };
349
+ }
350
+ }
351
+ // 2. Resume most recent workspace conversation within resume window
323
352
  const candidate = listSessions()
324
353
  .filter((row) => row.workspace && row.workspaceKey === key)
325
354
  .find((row) => now - row.updatedAt < RESUME_WINDOW_MS);
@@ -327,7 +356,7 @@ export function resolveSession(workspace) {
327
356
  const session = readSession(candidate.id);
328
357
  if (session) {
329
358
  setActiveSession(session.id);
330
- return session;
359
+ return { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) };
331
360
  }
332
361
  }
333
362
  return createSession(workspaceText);
@@ -337,7 +366,35 @@ export function switchSession(id) {
337
366
  if (!session)
338
367
  return null;
339
368
  setActiveSession(session.id);
340
- return session;
369
+ return { ...session, title: sessionTitle(session.title, session.messages, session.createdAt) };
370
+ }
371
+ /**
372
+ * Fork an existing session into a new conversation in the same workspace.
373
+ *
374
+ * CRITICAL TRUST & PERMISSION INVARIANT (Claude Code Architecture, p. 24):
375
+ * Forking copies conversation history up to the designated turn, creating a
376
+ * distinct trajectory. Permissions, standing approvals, and tool allowlists
377
+ * are strictly bound to the originating session lifecycle and must NEVER be
378
+ * inherited into a fork. The forked session starts with fresh, ungranted
379
+ * permissions so that user authorization and trust are freshly established.
380
+ */
381
+ export function forkSession(sourceId, options = {}) {
382
+ const source = getSession(sourceId);
383
+ if (!source)
384
+ return null;
385
+ const targetWorkspace = options.workspace || source.workspace || process.cwd();
386
+ const sourceTitle = source.title && source.title !== 'Untitled' ? source.title : 'Conversation';
387
+ const newTitle = options.title || `Fork of ${sourceTitle}`;
388
+ const newSession = createSession(targetWorkspace, newTitle, options.makeActive ?? true);
389
+ let messagesToCopy = Array.isArray(source.messages) ? source.messages : [];
390
+ if (typeof options.upToMessageIndex === 'number' && options.upToMessageIndex >= 0) {
391
+ messagesToCopy = messagesToCopy.slice(0, options.upToMessageIndex + 1);
392
+ }
393
+ if (messagesToCopy.length > 0) {
394
+ const clonedMessages = JSON.parse(JSON.stringify(messagesToCopy));
395
+ saveSessionMessages(newSession.id, clonedMessages);
396
+ }
397
+ return readSession(newSession.id);
341
398
  }
342
399
  function messageEqual(left, right) {
343
400
  return JSON.stringify(left) === JSON.stringify(right);
@@ -366,9 +423,8 @@ export function saveSessionMessages(id, messages) {
366
423
  return false;
367
424
  const nextMessages = messages.slice();
368
425
  const firstUser = nextMessages.find((message) => message.role === 'user' && typeof message.content === 'string');
369
- const nextTitle = (!session.title || session.title === 'Untitled') && firstUser
370
- ? titleFrom(firstUser.content)
371
- : session.title;
426
+ const nextTitle = sessionTitle(session.title, nextMessages, session.createdAt)
427
+ || (firstUser ? titleFrom(firstUser.content) : session.title);
372
428
  const prefix = session.messages.length <= nextMessages.length
373
429
  && session.messages.every((message, index) => {
374
430
  const next = nextMessages[index];