@causyne/agent 1.20.120 → 1.20.122

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 (276) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
@@ -0,0 +1,381 @@
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
+
10
+ import { AgentLoop, type AgentLoopEventSink } from './agentLoop.js';
11
+ import { safeDisplay } from './tui/text.js';
12
+
13
+ export type HeadlessOutputFormat = 'text' | 'json' | 'stream-json';
14
+ export type AutonomyModeCode = 'A' | 'B' | 'C';
15
+
16
+ export const MAX_STDIN_PROMPT_BYTES = 1_048_576;
17
+ export const MAX_HEADLESS_TURNS = 500;
18
+
19
+ export interface HeadlessToolRecord {
20
+ tool: string;
21
+ status: 'started' | 'completed' | 'error';
22
+ error?: string | undefined;
23
+ }
24
+
25
+ export interface HeadlessUsageSummary {
26
+ inputTokens?: number | undefined;
27
+ outputTokens?: number | undefined;
28
+ totalTokens?: number | undefined;
29
+ estimatedCostUsd?: number | undefined;
30
+ }
31
+
32
+ export interface HeadlessRunResult {
33
+ ok: boolean;
34
+ status: 'completed' | 'incomplete' | 'error';
35
+ taskId: string;
36
+ sessionId: string | null;
37
+ provider: string;
38
+ model: string;
39
+ response: string;
40
+ error: string | null;
41
+ steps: number;
42
+ toolCalls: HeadlessToolRecord[];
43
+ usage: HeadlessUsageSummary | null;
44
+ durationMs: number;
45
+ }
46
+
47
+ export interface HeadlessLoopLike {
48
+ config?: { provider?: string; model?: string; autonomyMode?: string };
49
+ memoryManager?: { sessionId?: string | null };
50
+ stepsCompleted?: number;
51
+ _causyneTaskOutcome?: string;
52
+ autonomyOverride?: string | null;
53
+ providerOverride?: string | null;
54
+ modelOverride?: string | null;
55
+ maxStepsCeiling?: number | null;
56
+ waitForApproval?: (toolCallId: string) => Promise<boolean>;
57
+ waitForDecision?: (request: unknown) => Promise<unknown>;
58
+ run: () => Promise<void>;
59
+ }
60
+
61
+ export interface HeadlessRunOptions {
62
+ outputFormat?: HeadlessOutputFormat | string | undefined;
63
+ model?: string | undefined;
64
+ provider?: string | undefined;
65
+ maxTurns?: number | string | undefined;
66
+ permissionMode?: string | undefined;
67
+ workspaceRoot?: string | undefined;
68
+ stdout?: { write: (chunk: string) => unknown } | undefined;
69
+ stderr?: { write: (chunk: string) => unknown } | undefined;
70
+ loopFactory?: ((sink: AgentLoopEventSink, taskId: string, prompt: string) => HeadlessLoopLike) | undefined;
71
+ }
72
+
73
+ export function parseOutputFormat(raw?: unknown): HeadlessOutputFormat {
74
+ if (raw === undefined || raw === null || raw === '') return 'text';
75
+ const normalized = String(raw).trim().toLowerCase();
76
+ if (normalized === 'text' || normalized === 'json' || normalized === 'stream-json') {
77
+ return normalized;
78
+ }
79
+ throw new Error(`Invalid --output-format "${raw}". Expected one of: text, json, stream-json.`);
80
+ }
81
+
82
+ export function parsePermissionMode(raw?: unknown): AutonomyModeCode | undefined {
83
+ if (raw === undefined || raw === null || raw === '') return undefined;
84
+ const normalized = String(raw).trim().toUpperCase();
85
+ if (normalized === 'A' || normalized === 'SUPERVISED' || normalized === 'STRICT') return 'A';
86
+ if (normalized === 'B' || normalized === 'BALANCED' || normalized === 'DEFAULT') return 'B';
87
+ if (normalized === 'C' || normalized === 'AUTONOMOUS' || normalized === 'AUTO') return 'C';
88
+ throw new Error(`Invalid --permission-mode "${raw}". Expected A (supervised), B (balanced), or C (autonomous).`);
89
+ }
90
+
91
+ export function parseMaxTurns(raw?: unknown): number | undefined {
92
+ if (raw === undefined || raw === null || raw === '') return undefined;
93
+ const trimmed = String(raw).trim();
94
+ const parsed = typeof raw === 'number' ? raw : (/^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN);
95
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_HEADLESS_TURNS) {
96
+ throw new Error(`Invalid --max-turns "${raw}". Expected an integer between 1 and ${MAX_HEADLESS_TURNS}.`);
97
+ }
98
+ return parsed;
99
+ }
100
+
101
+ export function composeHeadlessPrompt(
102
+ promptArg: string | boolean | undefined,
103
+ stdinText: string
104
+ ): string {
105
+ const cleanStdin = stdinText.trim();
106
+ const rawPrompt = typeof promptArg === 'string' ? promptArg.trim() : '';
107
+ const effectivePrompt = rawPrompt === '-' ? '' : rawPrompt;
108
+
109
+ if (effectivePrompt && cleanStdin) {
110
+ return `${effectivePrompt}\n\n<stdin>\n${cleanStdin}\n</stdin>`;
111
+ }
112
+ if (effectivePrompt) return effectivePrompt;
113
+ if (cleanStdin) return cleanStdin;
114
+ return '';
115
+ }
116
+
117
+ export async function readBoundedStdin(
118
+ stream: NodeJS.ReadableStream & { isTTY?: boolean } = process.stdin,
119
+ maxBytes = MAX_STDIN_PROMPT_BYTES
120
+ ): Promise<string> {
121
+ if (!stream || stream.isTTY) return '';
122
+
123
+ return await new Promise<string>((resolve, reject) => {
124
+ const chunks: Buffer[] = [];
125
+ let totalBytes = 0;
126
+ let truncated = false;
127
+
128
+ const onData = (chunk: Buffer | string): void => {
129
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
130
+ if (truncated) return;
131
+ const remaining = maxBytes - totalBytes;
132
+ if (buf.length <= remaining) {
133
+ chunks.push(buf);
134
+ totalBytes += buf.length;
135
+ } else {
136
+ if (remaining > 0) chunks.push(buf.subarray(0, remaining));
137
+ totalBytes = maxBytes;
138
+ truncated = true;
139
+ }
140
+ };
141
+
142
+ const cleanup = (): void => {
143
+ stream.removeListener('data', onData);
144
+ stream.removeListener('end', onEnd);
145
+ stream.removeListener('error', onError);
146
+ };
147
+
148
+ const onEnd = (): void => {
149
+ cleanup();
150
+ const text = Buffer.concat(chunks).toString('utf8');
151
+ resolve(truncated ? `${text}\n\n[stdin truncated at ${maxBytes} bytes]` : text);
152
+ };
153
+
154
+ const onError = (err: Error): void => {
155
+ cleanup();
156
+ reject(err);
157
+ };
158
+
159
+ stream.on('data', onData);
160
+ stream.on('end', onEnd);
161
+ stream.on('error', onError);
162
+ });
163
+ }
164
+
165
+ function isRecord(value: unknown): value is Record<string, unknown> {
166
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
167
+ }
168
+
169
+ export class HeadlessEventSink implements AgentLoopEventSink {
170
+ readyState = 1;
171
+ response = '';
172
+ errors: string[] = [];
173
+ toolCalls: HeadlessToolRecord[] = [];
174
+ usage: HeadlessUsageSummary | null = null;
175
+
176
+ private readonly format: HeadlessOutputFormat;
177
+ private readonly stdout: { write: (chunk: string) => unknown };
178
+ private streamedPrefix = '';
179
+
180
+ constructor(
181
+ format: HeadlessOutputFormat,
182
+ stdout: { write: (chunk: string) => unknown } = process.stdout
183
+ ) {
184
+ this.format = format;
185
+ this.stdout = stdout;
186
+ }
187
+
188
+ private emitStreamLine(payload: Record<string, unknown>): void {
189
+ if (this.format !== 'stream-json') return;
190
+ this.stdout.write(`${JSON.stringify(payload)}\n`);
191
+ }
192
+
193
+ send(data: string): void {
194
+ let parsed: unknown;
195
+ try {
196
+ parsed = JSON.parse(data);
197
+ } catch {
198
+ return;
199
+ }
200
+ if (!isRecord(parsed) || typeof parsed.type !== 'string') return;
201
+
202
+ const type = parsed.type;
203
+
204
+ if (type === 'agent_message') {
205
+ const content = typeof parsed.content === 'string' ? safeDisplay(parsed.content) : '';
206
+ const streaming = Boolean(parsed.streaming);
207
+ if (streaming) {
208
+ const delta = content.startsWith(this.streamedPrefix)
209
+ ? content.slice(this.streamedPrefix.length)
210
+ : content;
211
+ this.streamedPrefix = content;
212
+ this.response = content;
213
+ if (delta) {
214
+ this.emitStreamLine({ type: 'delta', text: delta });
215
+ }
216
+ } else {
217
+ this.streamedPrefix = '';
218
+ if (content) {
219
+ this.response = content;
220
+ this.emitStreamLine({ type: 'message', role: 'assistant', text: content });
221
+ }
222
+ }
223
+ return;
224
+ }
225
+
226
+ if (type === 'step_start') {
227
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
228
+ this.toolCalls.push({ tool, status: 'started' });
229
+ this.emitStreamLine({ type: 'tool_call', tool });
230
+ return;
231
+ }
232
+
233
+ if (type === 'step_complete') {
234
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
235
+ const last = [...this.toolCalls].reverse().find(entry => entry.tool === tool && entry.status === 'started');
236
+ if (last) last.status = 'completed';
237
+ else this.toolCalls.push({ tool, status: 'completed' });
238
+ this.emitStreamLine({ type: 'tool_result', tool, ok: true });
239
+ return;
240
+ }
241
+
242
+ if (type === 'step_error') {
243
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
244
+ const errText = typeof parsed.error === 'string' ? safeDisplay(parsed.error) : 'Tool failed';
245
+ const last = [...this.toolCalls].reverse().find(entry => entry.tool === tool && entry.status === 'started');
246
+ if (last) {
247
+ last.status = 'error';
248
+ last.error = errText;
249
+ } else {
250
+ this.toolCalls.push({ tool, status: 'error', error: errText });
251
+ }
252
+ this.emitStreamLine({ type: 'tool_result', tool, ok: false, error: errText });
253
+ return;
254
+ }
255
+
256
+ if (type === 'error') {
257
+ const message = typeof parsed.message === 'string' ? safeDisplay(parsed.message) : 'Unknown error';
258
+ this.errors.push(message);
259
+ this.emitStreamLine({ type: 'error', message });
260
+ return;
261
+ }
262
+
263
+ if (type === 'usage_update') {
264
+ const summary: HeadlessUsageSummary = {};
265
+ if (typeof parsed.inputTokens === 'number') summary.inputTokens = parsed.inputTokens;
266
+ if (typeof parsed.outputTokens === 'number') summary.outputTokens = parsed.outputTokens;
267
+ if (typeof parsed.totalTokens === 'number') summary.totalTokens = parsed.totalTokens;
268
+ if (typeof parsed.estimatedCostUsd === 'number') summary.estimatedCostUsd = parsed.estimatedCostUsd;
269
+ if (Object.keys(summary).length > 0) {
270
+ this.usage = summary;
271
+ this.emitStreamLine({ type: 'usage', ...summary });
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ export async function runHeadlessTask(
278
+ taskPrompt: string,
279
+ options: HeadlessRunOptions = {}
280
+ ): Promise<HeadlessRunResult> {
281
+ const startedAt = Date.now();
282
+ const format = parseOutputFormat(options.outputFormat);
283
+ const permissionMode = parsePermissionMode(options.permissionMode);
284
+ const maxTurns = parseMaxTurns(options.maxTurns);
285
+ const stdout = options.stdout ?? process.stdout;
286
+ const stderr = options.stderr ?? process.stderr;
287
+
288
+ const cleanPrompt = String(taskPrompt ?? '').trim();
289
+ const taskId = `cli_headless_${startedAt}`;
290
+ const sink = new HeadlessEventSink(format, stdout);
291
+
292
+ if (!cleanPrompt) {
293
+ const emptyResult: HeadlessRunResult = {
294
+ ok: false,
295
+ status: 'error',
296
+ taskId,
297
+ sessionId: null,
298
+ provider: '',
299
+ model: '',
300
+ response: '',
301
+ error: 'No prompt provided. Pass a prompt argument or pipe input on stdin.',
302
+ steps: 0,
303
+ toolCalls: [],
304
+ usage: null,
305
+ durationMs: Date.now() - startedAt
306
+ };
307
+ if (format === 'json' || format === 'stream-json') {
308
+ stdout.write(`${JSON.stringify(format === 'stream-json' ? { type: 'result', ...emptyResult } : emptyResult)}\n`);
309
+ } else {
310
+ stderr.write(`${emptyResult.error}\n`);
311
+ }
312
+ process.exitCode = 2;
313
+ return emptyResult;
314
+ }
315
+
316
+ const loop: HeadlessLoopLike = options.loopFactory
317
+ ? options.loopFactory(sink, taskId, cleanPrompt)
318
+ : new AgentLoop(sink, taskId, cleanPrompt, {
319
+ ...(options.workspaceRoot ? { workspaceRoot: options.workspaceRoot } : {}),
320
+ ...(options.provider ? { provider: options.provider } : {}),
321
+ ...(options.model ? { model: options.model } : {})
322
+ });
323
+
324
+ if (permissionMode) loop.autonomyOverride = permissionMode;
325
+ if (options.provider) loop.providerOverride = options.provider;
326
+ if (options.model) loop.modelOverride = options.model;
327
+ if (maxTurns !== undefined) loop.maxStepsCeiling = maxTurns;
328
+
329
+ // Non-interactive approval boundary: never hang waiting for a TTY prompt.
330
+ loop.waitForApproval = async () => false;
331
+ loop.waitForDecision = async () => null;
332
+
333
+ if (format === 'stream-json') {
334
+ stdout.write(`${JSON.stringify({
335
+ type: 'start',
336
+ taskId,
337
+ provider: options.provider || loop.config?.provider || '',
338
+ model: options.model || loop.config?.model || ''
339
+ })}\n`);
340
+ }
341
+
342
+ let fatalError: string | null = null;
343
+ try {
344
+ await loop.run();
345
+ } catch (err: unknown) {
346
+ fatalError = safeDisplay(err instanceof Error ? err.message : String(err));
347
+ }
348
+
349
+ const completed = fatalError === null && loop._causyneTaskOutcome === 'completed';
350
+ const lastError = fatalError ?? (sink.errors.length > 0 ? sink.errors[sink.errors.length - 1] ?? null : null);
351
+ const result: HeadlessRunResult = {
352
+ ok: completed,
353
+ status: fatalError ? 'error' : (completed ? 'completed' : 'incomplete'),
354
+ taskId,
355
+ sessionId: loop.memoryManager?.sessionId ?? null,
356
+ provider: String(options.provider || loop.config?.provider || ''),
357
+ model: String(options.model || loop.config?.model || ''),
358
+ response: sink.response,
359
+ error: completed ? null : (lastError || 'No verified task completion was recorded.'),
360
+ steps: typeof loop.stepsCompleted === 'number' ? loop.stepsCompleted : 0,
361
+ toolCalls: sink.toolCalls,
362
+ usage: sink.usage,
363
+ durationMs: Date.now() - startedAt
364
+ };
365
+
366
+ if (format === 'json') {
367
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
368
+ } else if (format === 'stream-json') {
369
+ stdout.write(`${JSON.stringify({ type: 'result', ...result })}\n`);
370
+ } else {
371
+ if (result.response) {
372
+ stdout.write(result.response.endsWith('\n') ? result.response : `${result.response}\n`);
373
+ }
374
+ if (!result.ok && result.error) {
375
+ stderr.write(`${result.error}\n`);
376
+ }
377
+ }
378
+
379
+ process.exitCode = result.ok ? 0 : 1;
380
+ return result;
381
+ }
@@ -165,7 +165,7 @@ export function buildRecoverableDroppedSummary(dropped, baseSummary, maxPointers
165
165
  if (message.role === 'user' && typeof message.content === 'string'
166
166
  && message.content.startsWith('[COMPACTED CONTEXT SUMMARY — ')) {
167
167
  for (const line of message.content.split('\n')) {
168
- const prior = /^([^\n]+ \((?:reported success|reported failure|outcome unverified)\): (\/[^\n]+))$/.exec(line);
168
+ const prior = /^([^\n]+ \((?:reported success|reported failure|outcome unverified)\): ((?:\/|[A-Za-z]:[\\/]|\\\\)[^\n]+))$/.exec(line);
169
169
  if (prior?.[2])
170
170
  paths.set(prior[2], line);
171
171
  }
@@ -180,7 +180,8 @@ export function buildRecoverableDroppedSummary(dropped, baseSummary, maxPointers
180
180
  }
181
181
  if (paths.size === 0)
182
182
  return baseSummary;
183
- const recent = [...paths.values()].slice(-Math.max(0, maxPointers));
183
+ const limit = Number.isFinite(maxPointers) ? Math.max(0, Math.floor(maxPointers)) : 8;
184
+ const recent = limit === 0 ? [] : [...paths.values()].slice(-limit);
184
185
  const omitted = paths.size - recent.length;
185
186
  const index = `Recoverable prior tool output (${paths.size} saved; local files expire after retention):\n`
186
187
  + recent.join('\n')
@@ -170,7 +170,7 @@ export function buildRecoverableDroppedSummary(
170
170
  if (message.role === 'user' && typeof message.content === 'string'
171
171
  && message.content.startsWith('[COMPACTED CONTEXT SUMMARY — ')) {
172
172
  for (const line of message.content.split('\n')) {
173
- const prior = /^([^\n]+ \((?:reported success|reported failure|outcome unverified)\): (\/[^\n]+))$/.exec(line);
173
+ const prior = /^([^\n]+ \((?:reported success|reported failure|outcome unverified)\): ((?:\/|[A-Za-z]:[\\/]|\\\\)[^\n]+))$/.exec(line);
174
174
  if (prior?.[2]) paths.set(prior[2], line);
175
175
  }
176
176
  }
@@ -182,7 +182,8 @@ export function buildRecoverableDroppedSummary(
182
182
  paths.set(message.spillPath, `${message.name ?? 'tool'} (${verdict}): ${message.spillPath}`);
183
183
  }
184
184
  if (paths.size === 0) return baseSummary;
185
- const recent = [...paths.values()].slice(-Math.max(0, maxPointers));
185
+ const limit = Number.isFinite(maxPointers) ? Math.max(0, Math.floor(maxPointers)) : 8;
186
+ const recent = limit === 0 ? [] : [...paths.values()].slice(-limit);
186
187
  const omitted = paths.size - recent.length;
187
188
  const index = `Recoverable prior tool output (${paths.size} saved; local files expire after retention):\n`
188
189
  + recent.join('\n')
package/src/hooks.js CHANGED
@@ -78,6 +78,9 @@ function runOneHook(rule, payload, cwd) {
78
78
  child.stderr.on('data', (chunk) => { stderr = collect(stderr, chunk); });
79
79
  child.on('error', (error) => finish({ exitCode: null, spawnError: error.message, stdout, stderr }));
80
80
  child.on('close', (code) => finish({ exitCode: code, stdout, stderr }));
81
+ child.stdin.on('error', () => {
82
+ // Ignore EPIPE when a hook exits immediately without draining stdin
83
+ });
81
84
  child.stdin.end(JSON.stringify(payload));
82
85
  });
83
86
  }
package/src/hooks.ts CHANGED
@@ -113,6 +113,9 @@ function runOneHook(rule: NormalizedHookRule, payload: UnknownRecord, cwd: strin
113
113
  child.stderr.on('data', (chunk: Buffer | string) => { stderr = collect(stderr, chunk); });
114
114
  child.on('error', (error: Error) => finish({ exitCode: null, spawnError: error.message, stdout, stderr }));
115
115
  child.on('close', (code: number | null) => finish({ exitCode: code, stdout, stderr }));
116
+ child.stdin.on('error', () => {
117
+ // Ignore EPIPE when a hook exits immediately without draining stdin
118
+ });
116
119
  child.stdin.end(JSON.stringify(payload));
117
120
  });
118
121
  }
@@ -271,25 +271,35 @@ export function extractToolCallJsonObjects(text, allowUnclosedHealing = true) {
271
271
  }
272
272
  return results;
273
273
  }
274
- const TRAILING_PARTIAL_TOOL_TAG = /<\/?(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?|f(?:u(?:n(?:c(?:t(?:i(?:o(?:n(?:_(?:c(?:a(?:l(?:l(?:s)?)?)?)?)?)?)?)?)?)?)?)?)?|i(?:n(?:v(?:o(?:k(?:e)?)?)?)?)?|[||][^\n>]*)$/i;
274
+ const TRAILING_PARTIAL_TOOL_TAG = /<\/?(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?|f(?:u(?:n(?:c(?:t(?:i(?:o(?:n(?:_(?:c(?:a(?:l(?:l(?:s)?)?)?)?)?)?)?)?)?)?)?)?)?|i(?:n(?:v(?:o(?:k(?:e)?)?)?)?)?|[||][^\n><]*)$/i;
275
275
  const TRAILING_PARTIAL_THINK_TAG = /<\/?(?:t(?:h(?:i(?:n(?:k(?:i(?:n(?:g)?)?)?)?|o(?:u(?:g(?:h(?:t)?)?)?)?)?)?)?|r(?:e(?:a(?:s(?:o(?:n(?:i(?:n(?:g(?:_(?:s(?:c(?:r(?:a(?:t(?:c(?:h(?:p(?:a(?:d)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)$/i;
276
276
  export function stripToolCallMarkup(text) {
277
277
  if (!text || typeof text !== 'string')
278
278
  return '';
279
- return text
280
- .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
281
- .replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
282
- .replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
283
- .replace(TRAILING_PARTIAL_TOOL_TAG, '')
284
- .trim();
279
+ let out = text;
280
+ let prev;
281
+ do {
282
+ prev = out;
283
+ out = out
284
+ .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
285
+ .replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
286
+ .replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
287
+ .replace(TRAILING_PARTIAL_TOOL_TAG, '');
288
+ } while (out !== prev);
289
+ return out.trim();
285
290
  }
286
291
  export function stripThinkBlocks(text) {
287
292
  if (!text || typeof text !== 'string')
288
293
  return '';
289
- return text
290
- .replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
291
- .replace(TRAILING_PARTIAL_THINK_TAG, '')
292
- .trim();
294
+ let out = text;
295
+ let prev;
296
+ do {
297
+ prev = out;
298
+ out = out
299
+ .replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
300
+ .replace(TRAILING_PARTIAL_THINK_TAG, '');
301
+ } while (out !== prev);
302
+ return out.trim();
293
303
  }
294
304
  export function extractLivePlanFromText(text, allowTrailing = false) {
295
305
  if (!text || typeof text !== 'string')
@@ -272,25 +272,35 @@ export function extractToolCallJsonObjects(text: string, allowUnclosedHealing =
272
272
  return results;
273
273
  }
274
274
 
275
- const TRAILING_PARTIAL_TOOL_TAG = /<\/?(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?|f(?:u(?:n(?:c(?:t(?:i(?:o(?:n(?:_(?:c(?:a(?:l(?:l(?:s)?)?)?)?)?)?)?)?)?)?)?)?)?|i(?:n(?:v(?:o(?:k(?:e)?)?)?)?)?|[||][^\n>]*)$/i;
275
+ const TRAILING_PARTIAL_TOOL_TAG = /<\/?(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l(?:l)?)?)?)?)?)?)?)?|f(?:u(?:n(?:c(?:t(?:i(?:o(?:n(?:_(?:c(?:a(?:l(?:l(?:s)?)?)?)?)?)?)?)?)?)?)?)?)?|i(?:n(?:v(?:o(?:k(?:e)?)?)?)?)?|[||][^\n><]*)$/i;
276
276
  const TRAILING_PARTIAL_THINK_TAG = /<\/?(?:t(?:h(?:i(?:n(?:k(?:i(?:n(?:g)?)?)?)?|o(?:u(?:g(?:h(?:t)?)?)?)?)?)?)?|r(?:e(?:a(?:s(?:o(?:n(?:i(?:n(?:g(?:_(?:s(?:c(?:r(?:a(?:t(?:c(?:h(?:p(?:a(?:d)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)$/i;
277
277
 
278
278
  export function stripToolCallMarkup(text: string): string {
279
279
  if (!text || typeof text !== 'string') return '';
280
- return text
281
- .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
282
- .replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
283
- .replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
284
- .replace(TRAILING_PARTIAL_TOOL_TAG, '')
285
- .trim();
280
+ let out = text;
281
+ let prev: string;
282
+ do {
283
+ prev = out;
284
+ out = out
285
+ .replace(/<tool_call>[\s\S]*?(?:<\/tool_call>|(?:\s*<\/?[||]DSML[||][^>]*>)+|$)/gi, '')
286
+ .replace(/<[||]DSML[||][\s\S]*?(?:<\/[||]DSML[||]\s*calls>|$)/gi, '')
287
+ .replace(/(?:\s*<\/?[||]DSML[||][^>]*>)+/gi, '')
288
+ .replace(TRAILING_PARTIAL_TOOL_TAG, '');
289
+ } while (out !== prev);
290
+ return out.trim();
286
291
  }
287
292
 
288
293
  export function stripThinkBlocks(text: string): string {
289
294
  if (!text || typeof text !== 'string') return '';
290
- return text
291
- .replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
292
- .replace(TRAILING_PARTIAL_THINK_TAG, '')
293
- .trim();
295
+ let out = text;
296
+ let prev: string;
297
+ do {
298
+ prev = out;
299
+ out = out
300
+ .replace(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>[\s\S]*?(?:<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>|$)/gi, '')
301
+ .replace(TRAILING_PARTIAL_THINK_TAG, '');
302
+ } while (out !== prev);
303
+ return out.trim();
294
304
  }
295
305
 
296
306
  export function extractLivePlanFromText(text: string, allowTrailing = false): PlanUpdate | null {
@@ -14,7 +14,10 @@ import * as crypto from 'node:crypto';
14
14
  export function atomicWriteFileSync(targetPath, content, options = {}) {
15
15
  const resolved = path.resolve(targetPath);
16
16
  const dir = path.dirname(resolved);
17
- fs.mkdirSync(dir, { recursive: true, mode: options.mode ?? 0o755 });
17
+ const dirMode = options.mode !== undefined
18
+ ? (options.mode | ((options.mode & 0o444) >> 2))
19
+ : 0o755;
20
+ fs.mkdirSync(dir, { recursive: true, mode: dirMode });
18
21
  const randomSuffix = crypto.randomBytes(6).toString('hex');
19
22
  const tempPath = path.join(dir, `.${path.basename(resolved)}.${randomSuffix}.tmp`);
20
23
  try {
@@ -25,7 +25,10 @@ export function atomicWriteFileSync(
25
25
  ): void {
26
26
  const resolved = path.resolve(targetPath);
27
27
  const dir = path.dirname(resolved);
28
- fs.mkdirSync(dir, { recursive: true, mode: options.mode ?? 0o755 });
28
+ const dirMode = options.mode !== undefined
29
+ ? (options.mode | ((options.mode & 0o444) >> 2))
30
+ : 0o755;
31
+ fs.mkdirSync(dir, { recursive: true, mode: dirMode });
29
32
 
30
33
  const randomSuffix = crypto.randomBytes(6).toString('hex');
31
34
  const tempPath = path.join(dir, `.${path.basename(resolved)}.${randomSuffix}.tmp`);
@@ -83,7 +83,7 @@ export function readOnlyScopeError(tool, args, prompt) {
83
83
  }
84
84
  if (tool === 'sysRun' || tool === 'sysRunBg' || tool === 'terminal_persistent_shell') {
85
85
  const command = String(args.command ?? args.input ?? '').trim();
86
- if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command) && !/[;&|><`$()]/.test(command)) {
86
+ if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command) && !hasShellControlOperators(command)) {
87
87
  return null;
88
88
  }
89
89
  return 'A read-only inquiry authorizes only non-mutating status inspection commands (e.g. pwd, git status, cat), not arbitrary execution.';
@@ -88,7 +88,7 @@ export function readOnlyScopeError(
88
88
  }
89
89
  if (tool === 'sysRun' || tool === 'sysRunBg' || tool === 'terminal_persistent_shell') {
90
90
  const command = String(args.command ?? args.input ?? '').trim();
91
- if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command) && !/[;&|><`$()]/.test(command)) {
91
+ if (READ_ONLY_COMMAND.test(command) && !MUTATING_INSPECTION_OPTIONS.test(command) && !hasShellControlOperators(command)) {
92
92
  return null;
93
93
  }
94
94
  return 'A read-only inquiry authorizes only non-mutating status inspection commands (e.g. pwd, git status, cat), not arbitrary execution.';