@causyne/agent 1.20.120 → 1.20.121

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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
package/src/entrypoint.js CHANGED
@@ -1,6 +1,14 @@
1
1
  import { program } from 'commander';
2
2
 
3
3
  import { runTask, chatMode, execCommand, interactiveConfig } from './cliMode.js';
4
+ import {
5
+ runHeadlessTask,
6
+ composeHeadlessPrompt,
7
+ readBoundedStdin,
8
+ parseOutputFormat,
9
+ parsePermissionMode,
10
+ parseMaxTurns
11
+ } from './headlessCli.js';
4
12
  import { runLicenseCommand } from './licensing/entitlements.js';
5
13
  import { runSelfUpdate, diagnoseInstallation, formatDoctorReport } from './autoUpdate.js';
6
14
  import { printContextReport, printUsageReport, printCheckpoints, printUndo, buildStatusText, printReport } from './reporting.js';
@@ -67,7 +75,43 @@ program
67
75
  .name('causyne')
68
76
  .description('Causyne — Local desktop AI harness (alias: causyne-agent)')
69
77
  .option('-C, --cwd <directory>', 'Use this directory as the workspace')
70
- .version(pkgVersion);
78
+ .option('-p, --print [prompt]', 'Run a single non-interactive prompt and print the response')
79
+ .option('--output-format <format>', 'Output format for headless runs: text, json, stream-json')
80
+ .option('-m, --model <name>', 'Override model for this run without modifying saved config')
81
+ .option('--provider <name>', 'Override provider for this run without modifying saved config')
82
+ .option('--max-turns <count>', 'Maximum agent turns/steps for this run')
83
+ .option('--permission-mode <mode>', 'Autonomy mode override for this run (A, B, or C)')
84
+ .version(pkgVersion)
85
+ .action(async (options) => {
86
+ if (options.print === undefined && !options.outputFormat) {
87
+ if (program.args.length > 0) {
88
+ console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
89
+ process.exit(1);
90
+ }
91
+ program.outputHelp();
92
+ process.exit(0);
93
+ }
94
+ try {
95
+ parseOutputFormat(options.outputFormat);
96
+ parsePermissionMode(options.permissionMode);
97
+ parseMaxTurns(options.maxTurns);
98
+ const stdinText = await readBoundedStdin(process.stdin);
99
+ const trailing = program.args.length > 0 && typeof options.print === 'boolean'
100
+ ? program.args.join(' ')
101
+ : options.print;
102
+ const prompt = composeHeadlessPrompt(trailing, stdinText);
103
+ await runHeadlessTask(prompt, {
104
+ outputFormat: options.outputFormat || 'text',
105
+ model: options.model,
106
+ provider: options.provider,
107
+ maxTurns: options.maxTurns,
108
+ permissionMode: options.permissionMode
109
+ });
110
+ } catch (err) {
111
+ console.error(err instanceof Error ? err.message : String(err));
112
+ process.exit(2);
113
+ }
114
+ });
71
115
 
72
116
  program
73
117
  .command('update')
@@ -101,12 +145,41 @@ program
101
145
  });
102
146
 
103
147
  program
104
- .command('run <task>')
105
- .description('Run a single task directly from the CLI')
148
+ .command('run [task]')
149
+ .description('Run a single task directly from the CLI (supports piped stdin and --output-format)')
106
150
  .option('--dev-emulator', 'Retired compatibility flag; grants no additional permissions')
151
+ .option('--output-format <format>', 'Output format: text, json, stream-json')
152
+ .option('-m, --model <name>', 'Override model for this run without modifying saved config')
153
+ .option('--provider <name>', 'Override provider for this run without modifying saved config')
154
+ .option('--max-turns <count>', 'Maximum agent turns/steps for this run')
155
+ .option('--permission-mode <mode>', 'Autonomy mode override for this run (A, B, or C)')
107
156
  .action(async (task, options) => {
108
157
  announceDevEmulator(options.devEmulator);
109
- await runTask(task);
158
+ try {
159
+ if (options.outputFormat) parseOutputFormat(options.outputFormat);
160
+ parsePermissionMode(options.permissionMode);
161
+ parseMaxTurns(options.maxTurns);
162
+ const stdinText = await readBoundedStdin(process.stdin);
163
+ const prompt = composeHeadlessPrompt(task, stdinText);
164
+ if (!prompt) {
165
+ console.error('No task provided. Pass a task argument or pipe input on stdin.');
166
+ process.exit(2);
167
+ }
168
+ if (options.outputFormat || task === '-' || !task) {
169
+ await runHeadlessTask(prompt, {
170
+ outputFormat: options.outputFormat || 'text',
171
+ model: options.model,
172
+ provider: options.provider,
173
+ maxTurns: options.maxTurns,
174
+ permissionMode: options.permissionMode
175
+ });
176
+ } else {
177
+ await runTask(prompt, options);
178
+ }
179
+ } catch (err) {
180
+ console.error(err instanceof Error ? err.message : String(err));
181
+ process.exit(2);
182
+ }
110
183
  });
111
184
 
112
185
  program
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Causyne Agent — Headless / CI Automation CLI Runner
3
+ *
4
+ * Provides non-interactive single-task execution (`-p/--print`, `run`),
5
+ * bounded stdin piping, per-invocation overrides (`--model`, `--provider`,
6
+ * `--max-turns`, `--permission-mode`) without mutating saved config, and
7
+ * machine-readable output formats (`text`, `json`, `stream-json`).
8
+ */
9
+ import { AgentLoop } from './agentLoop.js';
10
+ import { safeDisplay } from './tui/text.js';
11
+ export const MAX_STDIN_PROMPT_BYTES = 1_048_576;
12
+ export const MAX_HEADLESS_TURNS = 500;
13
+ export function parseOutputFormat(raw) {
14
+ if (raw === undefined || raw === null || raw === '')
15
+ return 'text';
16
+ const normalized = String(raw).trim().toLowerCase();
17
+ if (normalized === 'text' || normalized === 'json' || normalized === 'stream-json') {
18
+ return normalized;
19
+ }
20
+ throw new Error(`Invalid --output-format "${raw}". Expected one of: text, json, stream-json.`);
21
+ }
22
+ export function parsePermissionMode(raw) {
23
+ if (raw === undefined || raw === null || raw === '')
24
+ return undefined;
25
+ const normalized = String(raw).trim().toUpperCase();
26
+ if (normalized === 'A' || normalized === 'SUPERVISED' || normalized === 'STRICT')
27
+ return 'A';
28
+ if (normalized === 'B' || normalized === 'BALANCED' || normalized === 'DEFAULT')
29
+ return 'B';
30
+ if (normalized === 'C' || normalized === 'AUTONOMOUS' || normalized === 'AUTO')
31
+ return 'C';
32
+ throw new Error(`Invalid --permission-mode "${raw}". Expected A (supervised), B (balanced), or C (autonomous).`);
33
+ }
34
+ export function parseMaxTurns(raw) {
35
+ if (raw === undefined || raw === null || raw === '')
36
+ return undefined;
37
+ const parsed = typeof raw === 'number' ? raw : Number.parseInt(String(raw).trim(), 10);
38
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_HEADLESS_TURNS) {
39
+ throw new Error(`Invalid --max-turns "${raw}". Expected an integer between 1 and ${MAX_HEADLESS_TURNS}.`);
40
+ }
41
+ return parsed;
42
+ }
43
+ export function composeHeadlessPrompt(promptArg, stdinText) {
44
+ const cleanStdin = stdinText.trim();
45
+ const rawPrompt = typeof promptArg === 'string' ? promptArg.trim() : '';
46
+ const effectivePrompt = rawPrompt === '-' ? '' : rawPrompt;
47
+ if (effectivePrompt && cleanStdin) {
48
+ return `${effectivePrompt}\n\n<stdin>\n${cleanStdin}\n</stdin>`;
49
+ }
50
+ if (effectivePrompt)
51
+ return effectivePrompt;
52
+ if (cleanStdin)
53
+ return cleanStdin;
54
+ return '';
55
+ }
56
+ export async function readBoundedStdin(stream = process.stdin, maxBytes = MAX_STDIN_PROMPT_BYTES) {
57
+ if (!stream || stream.isTTY)
58
+ return '';
59
+ return await new Promise((resolve, reject) => {
60
+ const chunks = [];
61
+ let totalBytes = 0;
62
+ let truncated = false;
63
+ const onData = (chunk) => {
64
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
65
+ if (truncated)
66
+ return;
67
+ const remaining = maxBytes - totalBytes;
68
+ if (buf.length <= remaining) {
69
+ chunks.push(buf);
70
+ totalBytes += buf.length;
71
+ }
72
+ else {
73
+ if (remaining > 0)
74
+ chunks.push(buf.subarray(0, remaining));
75
+ totalBytes = maxBytes;
76
+ truncated = true;
77
+ }
78
+ };
79
+ const cleanup = () => {
80
+ stream.removeListener('data', onData);
81
+ stream.removeListener('end', onEnd);
82
+ stream.removeListener('error', onError);
83
+ };
84
+ const onEnd = () => {
85
+ cleanup();
86
+ const text = Buffer.concat(chunks).toString('utf8');
87
+ resolve(truncated ? `${text}\n\n[stdin truncated at ${maxBytes} bytes]` : text);
88
+ };
89
+ const onError = (err) => {
90
+ cleanup();
91
+ reject(err);
92
+ };
93
+ stream.on('data', onData);
94
+ stream.on('end', onEnd);
95
+ stream.on('error', onError);
96
+ });
97
+ }
98
+ function isRecord(value) {
99
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
100
+ }
101
+ export class HeadlessEventSink {
102
+ readyState = 1;
103
+ response = '';
104
+ errors = [];
105
+ toolCalls = [];
106
+ usage = null;
107
+ format;
108
+ stdout;
109
+ streamedPrefix = '';
110
+ constructor(format, stdout = process.stdout) {
111
+ this.format = format;
112
+ this.stdout = stdout;
113
+ }
114
+ emitStreamLine(payload) {
115
+ if (this.format !== 'stream-json')
116
+ return;
117
+ this.stdout.write(`${JSON.stringify(payload)}\n`);
118
+ }
119
+ send(data) {
120
+ let parsed;
121
+ try {
122
+ parsed = JSON.parse(data);
123
+ }
124
+ catch {
125
+ return;
126
+ }
127
+ if (!isRecord(parsed) || typeof parsed.type !== 'string')
128
+ return;
129
+ const type = parsed.type;
130
+ if (type === 'agent_message') {
131
+ const content = typeof parsed.content === 'string' ? safeDisplay(parsed.content) : '';
132
+ const streaming = Boolean(parsed.streaming);
133
+ if (streaming) {
134
+ const delta = content.startsWith(this.streamedPrefix)
135
+ ? content.slice(this.streamedPrefix.length)
136
+ : content;
137
+ this.streamedPrefix = content;
138
+ this.response = content;
139
+ if (delta) {
140
+ this.emitStreamLine({ type: 'delta', text: delta });
141
+ }
142
+ }
143
+ else {
144
+ this.streamedPrefix = '';
145
+ if (content) {
146
+ this.response = content;
147
+ this.emitStreamLine({ type: 'message', role: 'assistant', text: content });
148
+ }
149
+ }
150
+ return;
151
+ }
152
+ if (type === 'step_start') {
153
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
154
+ this.toolCalls.push({ tool, status: 'started' });
155
+ this.emitStreamLine({ type: 'tool_call', tool });
156
+ return;
157
+ }
158
+ if (type === 'step_complete') {
159
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
160
+ const last = [...this.toolCalls].reverse().find(entry => entry.tool === tool && entry.status === 'started');
161
+ if (last)
162
+ last.status = 'completed';
163
+ else
164
+ this.toolCalls.push({ tool, status: 'completed' });
165
+ this.emitStreamLine({ type: 'tool_result', tool, ok: true });
166
+ return;
167
+ }
168
+ if (type === 'step_error') {
169
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
170
+ const errText = typeof parsed.error === 'string' ? safeDisplay(parsed.error) : 'Tool failed';
171
+ const last = [...this.toolCalls].reverse().find(entry => entry.tool === tool && entry.status === 'started');
172
+ if (last) {
173
+ last.status = 'error';
174
+ last.error = errText;
175
+ }
176
+ else {
177
+ this.toolCalls.push({ tool, status: 'error', error: errText });
178
+ }
179
+ this.emitStreamLine({ type: 'tool_result', tool, ok: false, error: errText });
180
+ return;
181
+ }
182
+ if (type === 'error') {
183
+ const message = typeof parsed.message === 'string' ? safeDisplay(parsed.message) : 'Unknown error';
184
+ this.errors.push(message);
185
+ this.emitStreamLine({ type: 'error', message });
186
+ return;
187
+ }
188
+ if (type === 'usage_update') {
189
+ const summary = {};
190
+ if (typeof parsed.inputTokens === 'number')
191
+ summary.inputTokens = parsed.inputTokens;
192
+ if (typeof parsed.outputTokens === 'number')
193
+ summary.outputTokens = parsed.outputTokens;
194
+ if (typeof parsed.totalTokens === 'number')
195
+ summary.totalTokens = parsed.totalTokens;
196
+ if (typeof parsed.estimatedCostUsd === 'number')
197
+ summary.estimatedCostUsd = parsed.estimatedCostUsd;
198
+ if (Object.keys(summary).length > 0) {
199
+ this.usage = summary;
200
+ this.emitStreamLine({ type: 'usage', ...summary });
201
+ }
202
+ }
203
+ }
204
+ }
205
+ export async function runHeadlessTask(taskPrompt, options = {}) {
206
+ const startedAt = Date.now();
207
+ const format = parseOutputFormat(options.outputFormat);
208
+ const permissionMode = parsePermissionMode(options.permissionMode);
209
+ const maxTurns = parseMaxTurns(options.maxTurns);
210
+ const stdout = options.stdout ?? process.stdout;
211
+ const stderr = options.stderr ?? process.stderr;
212
+ const cleanPrompt = String(taskPrompt ?? '').trim();
213
+ const taskId = `cli_headless_${startedAt}`;
214
+ const sink = new HeadlessEventSink(format, stdout);
215
+ if (!cleanPrompt) {
216
+ const emptyResult = {
217
+ ok: false,
218
+ status: 'error',
219
+ taskId,
220
+ sessionId: null,
221
+ provider: '',
222
+ model: '',
223
+ response: '',
224
+ error: 'No prompt provided. Pass a prompt argument or pipe input on stdin.',
225
+ steps: 0,
226
+ toolCalls: [],
227
+ usage: null,
228
+ durationMs: Date.now() - startedAt
229
+ };
230
+ if (format === 'json' || format === 'stream-json') {
231
+ stdout.write(`${JSON.stringify(format === 'stream-json' ? { type: 'result', ...emptyResult } : emptyResult)}\n`);
232
+ }
233
+ else {
234
+ stderr.write(`${emptyResult.error}\n`);
235
+ }
236
+ process.exitCode = 2;
237
+ return emptyResult;
238
+ }
239
+ const loop = options.loopFactory
240
+ ? options.loopFactory(sink, taskId, cleanPrompt)
241
+ : new AgentLoop(sink, taskId, cleanPrompt, {
242
+ ...(options.workspaceRoot ? { workspaceRoot: options.workspaceRoot } : {}),
243
+ ...(options.provider ? { provider: options.provider } : {}),
244
+ ...(options.model ? { model: options.model } : {})
245
+ });
246
+ if (permissionMode)
247
+ loop.autonomyOverride = permissionMode;
248
+ if (options.provider)
249
+ loop.providerOverride = options.provider;
250
+ if (options.model)
251
+ loop.modelOverride = options.model;
252
+ if (maxTurns !== undefined)
253
+ loop.maxStepsCeiling = maxTurns;
254
+ // Non-interactive approval boundary: never hang waiting for a TTY prompt.
255
+ loop.waitForApproval = async () => false;
256
+ loop.waitForDecision = async () => null;
257
+ if (format === 'stream-json') {
258
+ stdout.write(`${JSON.stringify({
259
+ type: 'start',
260
+ taskId,
261
+ provider: options.provider || loop.config?.provider || '',
262
+ model: options.model || loop.config?.model || ''
263
+ })}\n`);
264
+ }
265
+ let fatalError = null;
266
+ try {
267
+ await loop.run();
268
+ }
269
+ catch (err) {
270
+ fatalError = safeDisplay(err instanceof Error ? err.message : String(err));
271
+ }
272
+ const completed = fatalError === null && loop._causyneTaskOutcome === 'completed';
273
+ const lastError = fatalError ?? (sink.errors.length > 0 ? sink.errors[sink.errors.length - 1] ?? null : null);
274
+ const result = {
275
+ ok: completed,
276
+ status: fatalError ? 'error' : (completed ? 'completed' : 'incomplete'),
277
+ taskId,
278
+ sessionId: loop.memoryManager?.sessionId ?? null,
279
+ provider: String(options.provider || loop.config?.provider || ''),
280
+ model: String(options.model || loop.config?.model || ''),
281
+ response: sink.response,
282
+ error: completed ? null : (lastError || 'No verified task completion was recorded.'),
283
+ steps: typeof loop.stepsCompleted === 'number' ? loop.stepsCompleted : 0,
284
+ toolCalls: sink.toolCalls,
285
+ usage: sink.usage,
286
+ durationMs: Date.now() - startedAt
287
+ };
288
+ if (format === 'json') {
289
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
290
+ }
291
+ else if (format === 'stream-json') {
292
+ stdout.write(`${JSON.stringify({ type: 'result', ...result })}\n`);
293
+ }
294
+ else {
295
+ if (result.response) {
296
+ stdout.write(result.response.endsWith('\n') ? result.response : `${result.response}\n`);
297
+ }
298
+ if (!result.ok && result.error) {
299
+ stderr.write(`${result.error}\n`);
300
+ }
301
+ }
302
+ process.exitCode = result.ok ? 0 : 1;
303
+ return result;
304
+ }