@causyne/agent 1.20.121 → 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 (256) 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 +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -85,7 +85,7 @@ function splitCommandSegments(command: string): string[] {
85
85
  continue;
86
86
  }
87
87
  if (!inSingle && !inDouble) {
88
- if (ch === ';') {
88
+ if (ch === ';' || ch === '\n' || ch === '\r') {
89
89
  if (current.trim()) segments.push(current.trim());
90
90
  current = '';
91
91
  continue;
@@ -96,12 +96,22 @@ function splitCommandSegments(command: string): string[] {
96
96
  i++;
97
97
  continue;
98
98
  }
99
- if (ch === '|' && command[i + 1] === '|') {
99
+ if (ch === '&' && command[i - 1] !== '>' && command[i + 1] !== '>') {
100
+ if (current.trim()) segments.push(current.trim());
101
+ current = '';
102
+ continue;
103
+ }
104
+ if (ch === '|' && (command[i + 1] === '|' || command[i + 1] === '&')) {
100
105
  if (current.trim()) segments.push(current.trim());
101
106
  current = '';
102
107
  i++;
103
108
  continue;
104
109
  }
110
+ if (ch === '|') {
111
+ if (current.trim()) segments.push(current.trim());
112
+ current = '';
113
+ continue;
114
+ }
105
115
  }
106
116
  current += ch;
107
117
  }
@@ -110,7 +120,7 @@ function splitCommandSegments(command: string): string[] {
110
120
  }
111
121
 
112
122
  const READ_ONLY_CMD_PATTERNS = [
113
- String.raw`^\s*(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
123
+ String.raw`(?:pwd|ls|find|rg|grep|cat|sed|awk|head|tail|wc|diff|file|stat|which|whereis|type|du|df|pdfinfo|pdftotext|identify|mediainfo|ffprobe|otool|readelf|nm|ps|lsof|top|uptime|whoami|id|uname|env|printenv|echo|printf|pytest)\b`,
114
124
  String.raw`(?:\.\/)?gradlew?\s+(?:test\S*|check\S*|lint\S*)\b`,
115
125
  String.raw`mvn\s+(?:test\S*|verify\S*)\b`,
116
126
  String.raw`git\s+(?:status|diff|log|show|branch|tag|remote|rev-parse|describe)\b`,
@@ -126,7 +136,7 @@ const READ_ONLY_CMD_PATTERNS = [
126
136
  String.raw`go\s+test\b`,
127
137
  String.raw`curl\s+(?:-I|-sI|-s\b|--head)\b`
128
138
  ];
129
- const READ_ONLY_CMD_REGEX = new RegExp(READ_ONLY_CMD_PATTERNS.join('|'), 'i');
139
+ const READ_ONLY_CMD_REGEX = new RegExp(`^\\s*(?:${READ_ONLY_CMD_PATTERNS.join('|')})`, 'i');
130
140
 
131
141
  export function isReadOnlyShellCommand(command: string): boolean {
132
142
  const trimmed = command.trim();
@@ -106,11 +106,16 @@ export function auditBudgetArithmetic(spec) {
106
106
  let taxCalculated;
107
107
  let differenceFromTarget;
108
108
  if (spec.grossUpTaxRate !== undefined) {
109
- const divisor = 1 - spec.grossUpTaxRate;
110
- grossCalculated = Math.round(grandTotal / divisor);
111
- taxCalculated = grossCalculated - grandTotal;
112
- if (spec.targetGross !== undefined) {
113
- differenceFromTarget = grossCalculated - spec.targetGross;
109
+ if (!Number.isFinite(spec.grossUpTaxRate) || spec.grossUpTaxRate < 0 || spec.grossUpTaxRate >= 1) {
110
+ categoryErrors.push(`Invalid grossUpTaxRate "${spec.grossUpTaxRate}": must be a finite fraction in [0, 1)`);
111
+ }
112
+ else {
113
+ const divisor = 1 - spec.grossUpTaxRate;
114
+ grossCalculated = Math.round(grandTotal / divisor);
115
+ taxCalculated = grossCalculated - grandTotal;
116
+ if (spec.targetGross !== undefined) {
117
+ differenceFromTarget = grossCalculated - spec.targetGross;
118
+ }
114
119
  }
115
120
  }
116
121
  const valid = itemErrors.length === 0 && categoryErrors.length === 0 && (differenceFromTarget === undefined || differenceFromTarget === 0);
@@ -166,12 +166,18 @@ export function auditBudgetArithmetic(spec: ArithmeticBudgetSpec): {
166
166
  let differenceFromTarget: number | undefined;
167
167
 
168
168
  if (spec.grossUpTaxRate !== undefined) {
169
- const divisor = 1 - spec.grossUpTaxRate;
170
- grossCalculated = Math.round(grandTotal / divisor);
171
- taxCalculated = grossCalculated - grandTotal;
169
+ if (!Number.isFinite(spec.grossUpTaxRate) || spec.grossUpTaxRate < 0 || spec.grossUpTaxRate >= 1) {
170
+ categoryErrors.push(
171
+ `Invalid grossUpTaxRate "${spec.grossUpTaxRate}": must be a finite fraction in [0, 1)`
172
+ );
173
+ } else {
174
+ const divisor = 1 - spec.grossUpTaxRate;
175
+ grossCalculated = Math.round(grandTotal / divisor);
176
+ taxCalculated = grossCalculated - grandTotal;
172
177
 
173
- if (spec.targetGross !== undefined) {
174
- differenceFromTarget = grossCalculated - spec.targetGross;
178
+ if (spec.targetGross !== undefined) {
179
+ differenceFromTarget = grossCalculated - spec.targetGross;
180
+ }
175
181
  }
176
182
  }
177
183
 
@@ -7,6 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import os from 'node:os';
10
+ import { pathToFileURL } from 'node:url';
10
11
  import { spawn } from 'node:child_process';
11
12
  const PALETTES = {
12
13
  corporate: {
@@ -38,7 +39,8 @@ const PALETTES = {
38
39
  * Compile formal publication document to pixel-perfect HTML + CSS Paged Media.
39
40
  */
40
41
  export function compileDocumentHtml(spec) {
41
- const p = PALETTES[spec.palette || 'corporate'];
42
+ const paletteKey = spec.palette && Object.hasOwn(PALETTES, spec.palette) ? spec.palette : 'corporate';
43
+ const p = PALETTES[paletteKey];
42
44
  const css = `
43
45
  :root {
44
46
  --primary: ${p.primary};
@@ -302,6 +304,7 @@ export async function renderHtmlToPdf(htmlFilePath, outputPdfPath, timeoutMs = 2
302
304
  }
303
305
  const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-pdf-profile-'));
304
306
  return new Promise((resolve) => {
307
+ let settled = false;
305
308
  const proc = spawn(chromePath, [
306
309
  '--headless',
307
310
  '--disable-gpu',
@@ -309,7 +312,7 @@ export async function renderHtmlToPdf(htmlFilePath, outputPdfPath, timeoutMs = 2
309
312
  '--no-pdf-header-footer',
310
313
  `--user-data-dir=${profileDir}`,
311
314
  `--print-to-pdf=${absOut}`,
312
- `file://${absHtml}`
315
+ pathToFileURL(absHtml).href
313
316
  ], { stdio: 'ignore' });
314
317
  let prevSize = -1;
315
318
  let stableCount = 0;
@@ -317,25 +320,36 @@ export async function renderHtmlToPdf(htmlFilePath, outputPdfPath, timeoutMs = 2
317
320
  let elapsed = 0;
318
321
  const timer = setInterval(() => {
319
322
  elapsed += interval;
320
- if (fs.existsSync(absOut)) {
321
- const stat = fs.statSync(absOut);
322
- if (stat.size === prevSize && stat.size > 0) {
323
- stableCount++;
324
- if (stableCount >= 3) {
325
- cleanupAndResolve(true);
326
- return;
323
+ try {
324
+ if (fs.existsSync(absOut)) {
325
+ const stat = fs.statSync(absOut);
326
+ if (stat.size === prevSize && stat.size > 0) {
327
+ stableCount++;
328
+ if (stableCount >= 3) {
329
+ cleanupAndResolve(true);
330
+ return;
331
+ }
332
+ }
333
+ else {
334
+ stableCount = 0;
335
+ prevSize = stat.size;
327
336
  }
328
337
  }
329
- else {
330
- stableCount = 0;
331
- prevSize = stat.size;
332
- }
338
+ }
339
+ catch {
340
+ // Ignore transient stat race while PDF is being written
333
341
  }
334
342
  if (elapsed >= timeoutMs) {
335
343
  cleanupAndResolve(false, 'Render timed out waiting for PDF file stabilization.');
336
344
  }
337
345
  }, interval);
346
+ proc.on('error', (err) => {
347
+ cleanupAndResolve(false, `Failed to launch Chrome: ${err.message}`);
348
+ });
338
349
  function cleanupAndResolve(success, error) {
350
+ if (settled)
351
+ return;
352
+ settled = true;
339
353
  clearInterval(timer);
340
354
  try {
341
355
  proc.kill();
@@ -349,7 +363,14 @@ export async function renderHtmlToPdf(htmlFilePath, outputPdfPath, timeoutMs = 2
349
363
  resolve({ success: false, error: error || 'Failed to generate PDF.' });
350
364
  return;
351
365
  }
352
- const stat = fs.statSync(absOut);
366
+ let stat;
367
+ try {
368
+ stat = fs.statSync(absOut);
369
+ }
370
+ catch {
371
+ resolve({ success: false, error: 'Failed to stat generated PDF.' });
372
+ return;
373
+ }
353
374
  const sizeKb = Math.round(stat.size / 1024);
354
375
  const exceeds2Mb = sizeKb > 2048;
355
376
  resolve({
@@ -410,9 +431,17 @@ except Exception as e:
410
431
  print(json.dumps({"success": False, "error": str(e)}))
411
432
  `;
412
433
  return new Promise((resolve) => {
413
- const py = spawn('python3', ['-c', script, absPdf, outputImagesDir || '']);
434
+ let settled = false;
435
+ const pyBin = process.platform === 'win32' ? 'python' : 'python3';
436
+ const py = spawn(pyBin, ['-c', script, absPdf, outputImagesDir || '']);
414
437
  let stdout = '';
415
438
  let stderr = '';
439
+ py.on('error', (err) => {
440
+ if (settled)
441
+ return;
442
+ settled = true;
443
+ resolve({ success: false, error: `Failed to spawn ${pyBin}: ${err.message}` });
444
+ });
416
445
  py.stdout.on('data', (d) => {
417
446
  stdout += d.toString();
418
447
  });
@@ -420,6 +449,9 @@ except Exception as e:
420
449
  stderr += d.toString();
421
450
  });
422
451
  py.on('close', (code) => {
452
+ if (settled)
453
+ return;
454
+ settled = true;
423
455
  if (code !== 0) {
424
456
  resolve({ success: false, error: stderr.trim() || `Python process exited with code ${code}` });
425
457
  return;
@@ -8,6 +8,7 @@
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import os from 'node:os';
11
+ import { pathToFileURL } from 'node:url';
11
12
  import { spawn } from 'node:child_process';
12
13
 
13
14
  export type DocumentPalette = 'corporate' | 'editorial_dair' | 'minimal_clean';
@@ -88,7 +89,8 @@ const PALETTES: Record<DocumentPalette, { primary: string; primaryDark: string;
88
89
  * Compile formal publication document to pixel-perfect HTML + CSS Paged Media.
89
90
  */
90
91
  export function compileDocumentHtml(spec: FormalDocumentSpec): { html: string; css: string } {
91
- const p = PALETTES[spec.palette || 'corporate'];
92
+ const paletteKey = spec.palette && Object.hasOwn(PALETTES, spec.palette) ? spec.palette : 'corporate';
93
+ const p = PALETTES[paletteKey];
92
94
 
93
95
  const css = `
94
96
  :root {
@@ -365,6 +367,7 @@ export async function renderHtmlToPdf(htmlFilePath: string, outputPdfPath: strin
365
367
  const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-pdf-profile-'));
366
368
 
367
369
  return new Promise((resolve) => {
370
+ let settled = false;
368
371
  const proc = spawn(
369
372
  chromePath,
370
373
  [
@@ -374,7 +377,7 @@ export async function renderHtmlToPdf(htmlFilePath: string, outputPdfPath: strin
374
377
  '--no-pdf-header-footer',
375
378
  `--user-data-dir=${profileDir}`,
376
379
  `--print-to-pdf=${absOut}`,
377
- `file://${absHtml}`
380
+ pathToFileURL(absHtml).href
378
381
  ],
379
382
  { stdio: 'ignore' }
380
383
  );
@@ -386,18 +389,22 @@ export async function renderHtmlToPdf(htmlFilePath: string, outputPdfPath: strin
386
389
 
387
390
  const timer = setInterval(() => {
388
391
  elapsed += interval;
389
- if (fs.existsSync(absOut)) {
390
- const stat = fs.statSync(absOut);
391
- if (stat.size === prevSize && stat.size > 0) {
392
- stableCount++;
393
- if (stableCount >= 3) {
394
- cleanupAndResolve(true);
395
- return;
392
+ try {
393
+ if (fs.existsSync(absOut)) {
394
+ const stat = fs.statSync(absOut);
395
+ if (stat.size === prevSize && stat.size > 0) {
396
+ stableCount++;
397
+ if (stableCount >= 3) {
398
+ cleanupAndResolve(true);
399
+ return;
400
+ }
401
+ } else {
402
+ stableCount = 0;
403
+ prevSize = stat.size;
396
404
  }
397
- } else {
398
- stableCount = 0;
399
- prevSize = stat.size;
400
405
  }
406
+ } catch {
407
+ // Ignore transient stat race while PDF is being written
401
408
  }
402
409
 
403
410
  if (elapsed >= timeoutMs) {
@@ -405,7 +412,13 @@ export async function renderHtmlToPdf(htmlFilePath: string, outputPdfPath: strin
405
412
  }
406
413
  }, interval);
407
414
 
415
+ proc.on('error', (err) => {
416
+ cleanupAndResolve(false, `Failed to launch Chrome: ${err.message}`);
417
+ });
418
+
408
419
  function cleanupAndResolve(success: boolean, error?: string) {
420
+ if (settled) return;
421
+ settled = true;
409
422
  clearInterval(timer);
410
423
  try {
411
424
  proc.kill();
@@ -419,7 +432,13 @@ export async function renderHtmlToPdf(htmlFilePath: string, outputPdfPath: strin
419
432
  return;
420
433
  }
421
434
 
422
- const stat = fs.statSync(absOut);
435
+ let stat: fs.Stats;
436
+ try {
437
+ stat = fs.statSync(absOut);
438
+ } catch {
439
+ resolve({ success: false, error: 'Failed to stat generated PDF.' });
440
+ return;
441
+ }
423
442
  const sizeKb = Math.round(stat.size / 1024);
424
443
  const exceeds2Mb = sizeKb > 2048;
425
444
 
@@ -484,10 +503,18 @@ except Exception as e:
484
503
  `;
485
504
 
486
505
  return new Promise((resolve) => {
487
- const py = spawn('python3', ['-c', script, absPdf, outputImagesDir || '']);
506
+ let settled = false;
507
+ const pyBin = process.platform === 'win32' ? 'python' : 'python3';
508
+ const py = spawn(pyBin, ['-c', script, absPdf, outputImagesDir || '']);
488
509
  let stdout = '';
489
510
  let stderr = '';
490
511
 
512
+ py.on('error', (err) => {
513
+ if (settled) return;
514
+ settled = true;
515
+ resolve({ success: false, error: `Failed to spawn ${pyBin}: ${err.message}` });
516
+ });
517
+
491
518
  py.stdout.on('data', (d) => {
492
519
  stdout += d.toString();
493
520
  });
@@ -496,6 +523,8 @@ except Exception as e:
496
523
  });
497
524
 
498
525
  py.on('close', (code) => {
526
+ if (settled) return;
527
+ settled = true;
499
528
  if (code !== 0) {
500
529
  resolve({ success: false, error: stderr.trim() || `Python process exited with code ${code}` });
501
530
  return;
@@ -1,3 +1,4 @@
1
+ import os from 'node:os';
1
2
  import path from 'node:path';
2
3
  // Multi-page layout, vector illustration, and publication engine for Causyne Agent.
3
4
  // Headless document composer, IDML/ePub/PDF/SVG/PNG renderer, and batch pipeline.
@@ -56,7 +57,7 @@ export const designEngine = {
56
57
  case 'inspect':
57
58
  case 'probe': {
58
59
  const file = request.action === 'inspect' ? requireProject(context, 'inspect') : positional(request.query ?? '');
59
- args = ['run', '--in', file, '--export', '/dev/null'];
60
+ args = ['run', '--in', file, '--export', os.devNull];
60
61
  break;
61
62
  }
62
63
  case 'execute':
@@ -1,3 +1,4 @@
1
+ import os from 'node:os';
1
2
  import path from 'node:path';
2
3
  import type {
3
4
  NativeEngineAction,
@@ -69,7 +70,7 @@ export const designEngine: NativeEngineAdapter = {
69
70
  case 'inspect':
70
71
  case 'probe': {
71
72
  const file = request.action === 'inspect' ? requireProject(context, 'inspect') : positional(request.query ?? '');
72
- args = ['run', '--in', file, '--export', '/dev/null'];
73
+ args = ['run', '--in', file, '--export', os.devNull];
73
74
  break;
74
75
  }
75
76
  case 'execute':
@@ -94,10 +94,10 @@ export const filmEngine = {
94
94
  break;
95
95
  }
96
96
  args.push('--compact');
97
- if (request.saveAs)
98
- artifacts = [request.saveAs];
99
- else if (request.save && context.project)
100
- artifacts = [context.project];
97
+ if (context.saveAs)
98
+ artifacts.push(context.saveAs);
99
+ else if (context.save && context.project)
100
+ artifacts.push(context.project);
101
101
  return {
102
102
  args,
103
103
  ...(stdin === undefined ? {} : { stdin }),
@@ -91,8 +91,8 @@ export const filmEngine: NativeEngineAdapter = {
91
91
  }
92
92
 
93
93
  args.push('--compact');
94
- if (request.saveAs) artifacts = [request.saveAs];
95
- else if (request.save && context.project) artifacts = [context.project];
94
+ if (context.saveAs) artifacts.push(context.saveAs);
95
+ else if (context.save && context.project) artifacts.push(context.project);
96
96
 
97
97
  return {
98
98
  args,
@@ -1,3 +1,4 @@
1
+ import os from 'node:os';
1
2
  import path from 'node:path';
2
3
  // RAW photo development, color grading, HDR merge, and tone-mapping engine for Causyne Agent.
3
4
  // Headless RAW pipeline, non-destructive develop adjustments, and photo library automation.
@@ -56,7 +57,7 @@ export const lightEngine = {
56
57
  case 'inspect':
57
58
  case 'probe': {
58
59
  const file = request.action === 'inspect' ? requireProject(context, 'inspect') : positional(request.query ?? '');
59
- args = ['render', file, '-o', '/dev/null'];
60
+ args = ['render', file, '-o', os.devNull];
60
61
  break;
61
62
  }
62
63
  case 'execute':
@@ -1,3 +1,4 @@
1
+ import os from 'node:os';
1
2
  import path from 'node:path';
2
3
  import type {
3
4
  NativeEngineAction,
@@ -69,7 +70,7 @@ export const lightEngine: NativeEngineAdapter = {
69
70
  case 'inspect':
70
71
  case 'probe': {
71
72
  const file = request.action === 'inspect' ? requireProject(context, 'inspect') : positional(request.query ?? '');
72
- args = ['render', file, '-o', '/dev/null'];
73
+ args = ['render', file, '-o', os.devNull];
73
74
  break;
74
75
  }
75
76
  case 'execute':
@@ -29,7 +29,7 @@ export const NATIVE_ENGINES = {
29
29
  [effectEngine.id]: effectEngine
30
30
  };
31
31
  export function nativeEngine(id) {
32
- return NATIVE_ENGINES[id] ?? null;
32
+ return Object.hasOwn(NATIVE_ENGINES, id) ? NATIVE_ENGINES[id] : null;
33
33
  }
34
34
  export function engineInstallDir(adapter) {
35
35
  return path.join(causyneHome(), 'engines', adapter.id);
@@ -33,7 +33,7 @@ export const NATIVE_ENGINES: Record<string, NativeEngineAdapter> = {
33
33
  };
34
34
 
35
35
  export function nativeEngine(id: string): NativeEngineAdapter | null {
36
- return NATIVE_ENGINES[id] ?? null;
36
+ return Object.hasOwn(NATIVE_ENGINES, id) ? NATIVE_ENGINES[id]! : null;
37
37
  }
38
38
 
39
39
  export function engineInstallDir(adapter: NativeEngineAdapter): string {
@@ -6,6 +6,7 @@
6
6
  // Encapsulates on-demand process lifecycle, error containment, execution timeouts,
7
7
  // and graceful fallback mechanisms to guarantee zero crashes on Causyne host processes.
8
8
  import fs from 'node:fs';
9
+ import os from 'node:os';
9
10
  import path from 'node:path';
10
11
  import { McpClient } from '../mcp/mcpClient.js';
11
12
  import { resolveUserPath } from '../utils/paths.js';
@@ -51,8 +52,9 @@ export class SovereignReverseHarness {
51
52
  // 1. Locate local rea binary if installed (sub-second launch, zero network lag)
52
53
  let command = 'npx';
53
54
  let args = ['--yes', 'rea-agents@6.8.0', '--mcp'];
55
+ const homeDir = os.homedir();
54
56
  const candidatePaths = [
55
- path.join(process.env.HOME || '', '.local', 'bin', 'rea'),
57
+ path.join(homeDir, '.local', 'bin', 'rea'),
56
58
  '/usr/local/bin/rea',
57
59
  '/opt/homebrew/bin/rea'
58
60
  ];
@@ -64,7 +66,6 @@ export class SovereignReverseHarness {
64
66
  }
65
67
  }
66
68
  const nodeDir = path.dirname(process.execPath);
67
- const homeDir = process.env.HOME || '';
68
69
  const buildToolsDirs = [
69
70
  path.join(homeDir, 'Library/Android/sdk/build-tools/36.1.0'),
70
71
  path.join(homeDir, 'Library/Android/sdk/build-tools/35.0.0'),
@@ -72,7 +73,7 @@ export class SovereignReverseHarness {
72
73
  '/opt/homebrew/bin',
73
74
  '/usr/local/bin'
74
75
  ].filter(d => fs.existsSync(d));
75
- const augmentedPath = [nodeDir, ...buildToolsDirs, process.env.PATH || ''].join(':');
76
+ const augmentedPath = [nodeDir, ...buildToolsDirs, process.env.PATH || ''].filter(Boolean).join(path.delimiter);
76
77
  const mcpClient = new McpClient({
77
78
  name: 'causyne_reverse_engineering',
78
79
  command,
@@ -7,6 +7,7 @@
7
7
  // and graceful fallback mechanisms to guarantee zero crashes on Causyne host processes.
8
8
 
9
9
  import fs from 'node:fs';
10
+ import os from 'node:os';
10
11
  import path from 'node:path';
11
12
  import { McpClient, type McpToolCallResult } from '../mcp/mcpClient.js';
12
13
  import { resolveUserPath } from '../utils/paths.js';
@@ -66,8 +67,9 @@ export class SovereignReverseHarness {
66
67
  let command = 'npx';
67
68
  let args = ['--yes', 'rea-agents@6.8.0', '--mcp'];
68
69
 
70
+ const homeDir = os.homedir();
69
71
  const candidatePaths = [
70
- path.join(process.env.HOME || '', '.local', 'bin', 'rea'),
72
+ path.join(homeDir, '.local', 'bin', 'rea'),
71
73
  '/usr/local/bin/rea',
72
74
  '/opt/homebrew/bin/rea'
73
75
  ];
@@ -81,7 +83,6 @@ export class SovereignReverseHarness {
81
83
  }
82
84
 
83
85
  const nodeDir = path.dirname(process.execPath);
84
- const homeDir = process.env.HOME || '';
85
86
  const buildToolsDirs = [
86
87
  path.join(homeDir, 'Library/Android/sdk/build-tools/36.1.0'),
87
88
  path.join(homeDir, 'Library/Android/sdk/build-tools/35.0.0'),
@@ -90,7 +91,7 @@ export class SovereignReverseHarness {
90
91
  '/usr/local/bin'
91
92
  ].filter(d => fs.existsSync(d));
92
93
 
93
- const augmentedPath = [nodeDir, ...buildToolsDirs, process.env.PATH || ''].join(':');
94
+ const augmentedPath = [nodeDir, ...buildToolsDirs, process.env.PATH || ''].filter(Boolean).join(path.delimiter);
94
95
 
95
96
  const mcpClient = new McpClient({
96
97
  name: 'causyne_reverse_engineering',
@@ -34,7 +34,8 @@ export function parsePermissionMode(raw) {
34
34
  export function parseMaxTurns(raw) {
35
35
  if (raw === undefined || raw === null || raw === '')
36
36
  return undefined;
37
- const parsed = typeof raw === 'number' ? raw : Number.parseInt(String(raw).trim(), 10);
37
+ const trimmed = String(raw).trim();
38
+ const parsed = typeof raw === 'number' ? raw : (/^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN);
38
39
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_HEADLESS_TURNS) {
39
40
  throw new Error(`Invalid --max-turns "${raw}". Expected an integer between 1 and ${MAX_HEADLESS_TURNS}.`);
40
41
  }
@@ -90,7 +90,8 @@ export function parsePermissionMode(raw?: unknown): AutonomyModeCode | undefined
90
90
 
91
91
  export function parseMaxTurns(raw?: unknown): number | undefined {
92
92
  if (raw === undefined || raw === null || raw === '') return undefined;
93
- const parsed = typeof raw === 'number' ? raw : Number.parseInt(String(raw).trim(), 10);
93
+ const trimmed = String(raw).trim();
94
+ const parsed = typeof raw === 'number' ? raw : (/^\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN);
94
95
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_HEADLESS_TURNS) {
95
96
  throw new Error(`Invalid --max-turns "${raw}". Expected an integer between 1 and ${MAX_HEADLESS_TURNS}.`);
96
97
  }
@@ -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
  }