@causyne/agent 1.20.118 → 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 (101) 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 +51 -351
  9. package/src/agentLoop.ts +69 -363
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/browser/causyneBrowser.js +231 -136
  13. package/src/browser/causyneBrowser.ts +229 -140
  14. package/src/browser/searchProviders.js +41 -30
  15. package/src/browser/searchProviders.ts +24 -14
  16. package/src/browser/workspacePathSafety.js +50 -0
  17. package/src/browser/workspacePathSafety.ts +50 -0
  18. package/src/browser/workspacePreview.js +27 -4
  19. package/src/browser/workspacePreview.ts +28 -4
  20. package/src/cliMode.js +17 -3
  21. package/src/commands.js +15 -22
  22. package/src/config.js +42 -63
  23. package/src/configVault.js +204 -0
  24. package/src/configVault.ts +213 -0
  25. package/src/core/contextCompactor.js +70 -11
  26. package/src/core/contextCompactor.ts +83 -11
  27. package/src/creative/liveBridge.js +34 -1
  28. package/src/creative/liveBridge.ts +28 -1
  29. package/src/dynamicCatalogue.js +42 -73
  30. package/src/dynamicCatalogue.ts +74 -60
  31. package/src/entrypoint.js +77 -4
  32. package/src/headlessCli.js +304 -0
  33. package/src/headlessCli.ts +380 -0
  34. package/src/mcp/mcpClient.js +38 -11
  35. package/src/mcp/mcpClient.ts +44 -11
  36. package/src/mcp/mcpRegistry.js +2 -5
  37. package/src/mcp/mcpRegistry.ts +2 -5
  38. package/src/mcp/mcpSecurity.js +189 -0
  39. package/src/mcp/mcpSecurity.ts +190 -0
  40. package/src/observer/evidence.js +23 -0
  41. package/src/observer/evidence.ts +21 -0
  42. package/src/osKeychain.js +209 -0
  43. package/src/osKeychain.ts +245 -0
  44. package/src/providers/anthropic.js +61 -28
  45. package/src/providers/base.js +14 -0
  46. package/src/providers/byokHttp.js +354 -0
  47. package/src/providers/byokHttp.ts +454 -0
  48. package/src/providers/byokStream.js +657 -0
  49. package/src/providers/byokStream.ts +759 -0
  50. package/src/providers/dashscope-byok.js +47 -32
  51. package/src/providers/deepseek.js +43 -39
  52. package/src/providers/gemini.js +73 -38
  53. package/src/providers/moonshot.js +43 -33
  54. package/src/providers/muse.js +10 -10
  55. package/src/providers/ollama.js +46 -31
  56. package/src/providers/openai-compatible.js +57 -32
  57. package/src/providers/openrouter.js +77 -113
  58. package/src/providers/openrouter.ts +99 -118
  59. package/src/providers/qwen-byok.js +46 -23
  60. package/src/providers/toolContracts.js +9 -3
  61. package/src/providers/toolContracts.ts +9 -3
  62. package/src/providers/wireNormalizer.js +238 -0
  63. package/src/providers/wireNormalizer.ts +279 -0
  64. package/src/providers/xai.js +43 -33
  65. package/src/sandbox.js +77 -56
  66. package/src/sandboxPolicy.js +1208 -0
  67. package/src/sandboxPolicy.ts +1300 -0
  68. package/src/sessionJournal.js +47 -0
  69. package/src/sessionJournal.ts +49 -0
  70. package/src/tools/browserAutomator.js +13 -1
  71. package/src/tools/browserAutomator.ts +13 -0
  72. package/src/tools/creativeApps.js +2 -1
  73. package/src/tools/creativeApps.ts +2 -1
  74. package/src/tools/gameAssetFetcher.js +130 -26
  75. package/src/tools/gameAssetHarvester.js +80 -58
  76. package/src/tools/nativeEngine.js +1 -1
  77. package/src/tools/nativeEngine.ts +1 -1
  78. package/src/tools/osSandbox.js +473 -0
  79. package/src/tools/osSandbox.ts +554 -0
  80. package/src/tools/persistentShell.js +8 -3
  81. package/src/tools/registry.js +13 -0
  82. package/src/tools/subprocessEnv.js +197 -0
  83. package/src/tools/subprocessEnv.ts +212 -0
  84. package/src/tools/sysRun.js +39 -6
  85. package/src/tools/sysRun.ts +53 -7
  86. package/src/tools/toolScanner.js +596 -140
  87. package/src/tools/toolScanner.ts +665 -147
  88. package/src/tools/toolSelfRepair.js +243 -114
  89. package/src/tools/toolSelfRepair.ts +262 -111
  90. package/src/tools/webFetch.js +161 -24
  91. package/src/tools/webFetch.ts +157 -22
  92. package/src/tools/webSearch.js +33 -4
  93. package/src/tools/webSearch.ts +27 -4
  94. package/src/tui/sessionPicker.js +132 -35
  95. package/src/tui/sessionPicker.ts +153 -32
  96. package/src/tui/sessionPickerView.js +277 -34
  97. package/src/tui/sessionPickerView.ts +328 -34
  98. package/src/tui/statusLine.js +3 -0
  99. package/src/tui/statusLine.ts +5 -0
  100. package/src/tui/workspaceIdentity.js +133 -0
  101. package/src/tui/workspaceIdentity.ts +146 -0
@@ -17,6 +17,7 @@ import { execFile } from 'node:child_process';
17
17
  import { promisify } from 'node:util';
18
18
  import { causyneHome } from './utils/paths.js';
19
19
  import { MODEL_CATALOGUE, PEER_MODEL_CATALOGUE, DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
20
+ import { validateProviderEndpointUrl, readBoundedResponseText } from './providers/byokHttp.js';
20
21
  import {
21
22
  BASELINE_ANTIGRAVITY_MODELS,
22
23
  ANTIGRAVITY_MODELS,
@@ -953,15 +954,34 @@ export async function fetchLiveModels(
953
954
  const peer = peerIdFromProviderKey(norm);
954
955
  if (peer) return discoverPeerModels(peer);
955
956
 
957
+ const MAX_DISCOVERY_BYTES = 4 * 1024 * 1024;
958
+ const fetchDiscoveryJson = async <T>(
959
+ rawUrl: string,
960
+ headers: Record<string, string> = {},
961
+ hasApiKey = false
962
+ ): Promise<T | null> => {
963
+ const safeUrl = validateProviderEndpointUrl(rawUrl, {
964
+ hasApiKey,
965
+ providerLabel: norm
966
+ });
967
+ const res = await fetch(safeUrl, {
968
+ headers,
969
+ redirect: 'error',
970
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
971
+ });
972
+ if (!res.ok) return null;
973
+ if (!res.body && typeof res.text !== 'function' && typeof res.json === 'function') {
974
+ return (await res.json()) as T;
975
+ }
976
+ const text = await readBoundedResponseText(res, MAX_DISCOVERY_BYTES, { truncate: false, label: norm });
977
+ return JSON.parse(text) as T;
978
+ };
979
+
956
980
  try {
957
981
  if (norm === 'ollama') {
958
982
  const host = (baseUrl || 'http://127.0.0.1:11434').replace(/\/+$/, '');
959
- const res = await fetch(`${host}/api/tags`, {
960
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
961
- });
962
- if (!res.ok) return [];
963
- const data = await res.json() as { models?: Array<{ name?: string }> };
964
- if (Array.isArray(data.models)) {
983
+ const data = await fetchDiscoveryJson<{ models?: Array<{ name?: string }> }>(`${host}/api/tags`, {}, false);
984
+ if (Array.isArray(data?.models)) {
965
985
  return data.models
966
986
  .map((m) => (m.name || '').replace(/:latest$/, ''))
967
987
  .filter(Boolean);
@@ -971,13 +991,12 @@ export async function fetchLiveModels(
971
991
  if (norm === 'openai') {
972
992
  if (!apiKey) return [];
973
993
  const host = (baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
974
- const res = await fetch(`${host}/models`, {
975
- headers: { Authorization: `Bearer ${apiKey}` },
976
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
977
- });
978
- if (!res.ok) return [];
979
- const data = await res.json() as { data?: Array<{ id?: string }> };
980
- if (Array.isArray(data.data)) {
994
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
995
+ `${host}/models`,
996
+ { Authorization: `Bearer ${apiKey}` },
997
+ true
998
+ );
999
+ if (Array.isArray(data?.data)) {
981
1000
  return data.data
982
1001
  .map((m) => m.id || '')
983
1002
  .filter((id) => /^(gpt|o1|o3|chatgpt)/i.test(id))
@@ -987,12 +1006,13 @@ export async function fetchLiveModels(
987
1006
 
988
1007
  if (norm === 'gemini') {
989
1008
  if (!apiKey) return [];
990
- const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey)}`, {
991
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
992
- });
993
- if (!res.ok) return [];
994
- const data = await res.json() as { models?: Array<{ name?: string; supportedGenerationMethods?: string[] }> };
995
- if (Array.isArray(data.models)) {
1009
+ // Send API key in x-goog-api-key header rather than query string (CWE-598).
1010
+ const data = await fetchDiscoveryJson<{ models?: Array<{ name?: string; supportedGenerationMethods?: string[] }> }>(
1011
+ 'https://generativelanguage.googleapis.com/v1beta/models',
1012
+ { 'x-goog-api-key': apiKey },
1013
+ true
1014
+ );
1015
+ if (Array.isArray(data?.models)) {
996
1016
  return data.models
997
1017
  .filter((m) => m.supportedGenerationMethods?.includes('generateContent'))
998
1018
  .map((m) => (m.name || '').replace(/^models\//, ''))
@@ -1003,16 +1023,15 @@ export async function fetchLiveModels(
1003
1023
 
1004
1024
  if (norm === 'anthropic') {
1005
1025
  if (!apiKey) return [];
1006
- const res = await fetch('https://api.anthropic.com/v1/models', {
1007
- headers: {
1026
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1027
+ 'https://api.anthropic.com/v1/models',
1028
+ {
1008
1029
  'x-api-key': apiKey,
1009
1030
  'anthropic-version': '2023-06-01'
1010
1031
  },
1011
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1012
- });
1013
- if (!res.ok) return [];
1014
- const data = await res.json() as { data?: Array<{ id?: string }> };
1015
- if (Array.isArray(data.data)) {
1032
+ true
1033
+ );
1034
+ if (Array.isArray(data?.data)) {
1016
1035
  return data.data
1017
1036
  .map((m) => m.id || '')
1018
1037
  .filter(Boolean)
@@ -1022,13 +1041,12 @@ export async function fetchLiveModels(
1022
1041
 
1023
1042
  if (norm === 'deepseek') {
1024
1043
  if (!apiKey) return [];
1025
- const res = await fetch('https://api.deepseek.com/models', {
1026
- headers: { Authorization: `Bearer ${apiKey}` },
1027
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1028
- });
1029
- if (!res.ok) return [];
1030
- const data = await res.json() as { data?: Array<{ id?: string }> };
1031
- if (Array.isArray(data.data)) {
1044
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1045
+ 'https://api.deepseek.com/models',
1046
+ { Authorization: `Bearer ${apiKey}` },
1047
+ true
1048
+ );
1049
+ if (Array.isArray(data?.data)) {
1032
1050
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
1033
1051
  }
1034
1052
  }
@@ -1036,13 +1054,12 @@ export async function fetchLiveModels(
1036
1054
  if (norm === 'xai') {
1037
1055
  if (!apiKey) return [];
1038
1056
  const host = (baseUrl || 'https://api.x.ai/v1').replace(/\/+$/, '');
1039
- const res = await fetch(`${host}/models`, {
1040
- headers: { Authorization: `Bearer ${apiKey}` },
1041
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1042
- });
1043
- if (!res.ok) return [];
1044
- const data = await res.json() as { data?: Array<{ id?: string }> };
1045
- if (Array.isArray(data.data)) {
1057
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1058
+ `${host}/models`,
1059
+ { Authorization: `Bearer ${apiKey}` },
1060
+ true
1061
+ );
1062
+ if (Array.isArray(data?.data)) {
1046
1063
  return data.data.map((m) => m.id || '').filter((id) => /^(grok)/i.test(id)).sort();
1047
1064
  }
1048
1065
  }
@@ -1050,13 +1067,12 @@ export async function fetchLiveModels(
1050
1067
  if (norm === 'moonshot') {
1051
1068
  if (!apiKey) return [];
1052
1069
  const host = (baseUrl || 'https://api.moonshot.cn/v1').replace(/\/+$/, '');
1053
- const res = await fetch(`${host}/models`, {
1054
- headers: { Authorization: `Bearer ${apiKey}` },
1055
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1056
- });
1057
- if (!res.ok) return [];
1058
- const data = await res.json() as { data?: Array<{ id?: string }> };
1059
- if (Array.isArray(data.data)) {
1070
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1071
+ `${host}/models`,
1072
+ { Authorization: `Bearer ${apiKey}` },
1073
+ true
1074
+ );
1075
+ if (Array.isArray(data?.data)) {
1060
1076
  return data.data.map((m) => m.id || '').filter((id) => /^(kimi|moonshot)/i.test(id)).sort();
1061
1077
  }
1062
1078
  }
@@ -1064,13 +1080,12 @@ export async function fetchLiveModels(
1064
1080
  if (norm === 'dashscope-byok' || norm === 'qwen') {
1065
1081
  if (!apiKey) return [];
1066
1082
  const host = (baseUrl || 'https://dashscope.aliyuncs.com/compatible-mode/v1').replace(/\/+$/, '');
1067
- const res = await fetch(`${host}/models`, {
1068
- headers: { Authorization: `Bearer ${apiKey}` },
1069
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1070
- });
1071
- if (!res.ok) return [];
1072
- const data = await res.json() as { data?: Array<{ id?: string }> };
1073
- if (Array.isArray(data.data)) {
1083
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1084
+ `${host}/models`,
1085
+ { Authorization: `Bearer ${apiKey}` },
1086
+ true
1087
+ );
1088
+ if (Array.isArray(data?.data)) {
1074
1089
  return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1075
1090
  }
1076
1091
  }
@@ -1088,13 +1103,12 @@ export async function fetchLiveModels(
1088
1103
  const host = baseUrl.replace(/\/+$/, '');
1089
1104
  const headers: Record<string, string> = {};
1090
1105
  if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
1091
- const res = await fetch(`${host}/models`, {
1106
+ const data = await fetchDiscoveryJson<{ data?: Array<{ id?: string }> }>(
1107
+ `${host}/models`,
1092
1108
  headers,
1093
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1094
- });
1095
- if (!res.ok) return [];
1096
- const data = await res.json() as { data?: Array<{ id?: string }> };
1097
- if (Array.isArray(data.data)) {
1109
+ Boolean(apiKey)
1110
+ );
1111
+ if (Array.isArray(data?.data)) {
1098
1112
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
1099
1113
  }
1100
1114
  }
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
+ }