@causyne/agent 1.20.124 → 1.20.127

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 (235) hide show
  1. package/bin/causyne.js +1 -1
  2. package/package.json +4 -4
  3. package/src/acp/protocol.ts +19 -1
  4. package/src/acp/server.js +282 -8
  5. package/src/acp/server.ts +284 -8
  6. package/src/agent/abortableDelay.js +2 -2
  7. package/src/agent/abortableDelay.ts +2 -2
  8. package/src/agent/errorClassifier.js +9 -1
  9. package/src/agent/errorClassifier.ts +8 -1
  10. package/src/agentLoop.js +83 -27
  11. package/src/agentLoop.ts +92 -26
  12. package/src/approvalPolicy.js +34 -10
  13. package/src/approvalPolicy.ts +42 -11
  14. package/src/browser/causyneBrowser.js +30 -3
  15. package/src/browser/causyneBrowser.ts +33 -3
  16. package/src/browser/urlPolicy.js +14 -1
  17. package/src/browser/urlPolicy.ts +12 -1
  18. package/src/cliMode.js +21 -9
  19. package/src/cliMode.ts +20 -8
  20. package/src/commands.js +188 -32
  21. package/src/commands.ts +209 -32
  22. package/src/config.js +19 -4
  23. package/src/config.ts +18 -4
  24. package/src/core/contextCompactor.js +54 -7
  25. package/src/core/contextCompactor.ts +63 -7
  26. package/src/core/goalLoop.js +257 -0
  27. package/src/core/goalLoop.ts +310 -0
  28. package/src/entrypoint.js +135 -3
  29. package/src/entrypoint.ts +136 -3
  30. package/src/game/causyneCoreBridge.js +686 -0
  31. package/src/game/causyneCoreBridge.ts +702 -0
  32. package/src/game/gameLauncher.js +287 -0
  33. package/src/game/gameLauncher.ts +352 -0
  34. package/src/game/gameProvisioner.js +425 -0
  35. package/src/game/gameProvisioner.ts +488 -0
  36. package/src/headlessCli.js +19 -12
  37. package/src/headlessCli.ts +22 -8
  38. package/src/infra/atomicWriter.js +40 -4
  39. package/src/infra/atomicWriter.ts +36 -4
  40. package/src/launchIntent.js +73 -3
  41. package/src/launchIntent.ts +76 -3
  42. package/src/lsp/lspClient.js +83 -12
  43. package/src/lsp/lspClient.ts +75 -12
  44. package/src/mcp/mcpRegistry.js +75 -8
  45. package/src/mcp/mcpRegistry.ts +70 -7
  46. package/src/memory/contextBudget.js +2 -0
  47. package/src/memory/contextBudget.ts +1 -0
  48. package/src/modelVariants.js +45 -0
  49. package/src/modelVariants.ts +54 -0
  50. package/src/outputRecovery.js +3 -2
  51. package/src/outputRecovery.ts +4 -2
  52. package/src/permissionPresets.js +327 -0
  53. package/src/permissionPresets.ts +361 -0
  54. package/src/providers/antigravity.js +62 -9
  55. package/src/providers/antigravity.ts +73 -9
  56. package/src/providers/byokHttp.js +7 -1
  57. package/src/providers/byokHttp.ts +6 -1
  58. package/src/providers/byokStream.js +21 -8
  59. package/src/providers/byokStream.ts +17 -7
  60. package/src/providers/dashscope-byok.js +21 -5
  61. package/src/providers/dashscope-byok.ts +29 -11
  62. package/src/providers/moonshot.js +26 -7
  63. package/src/providers/moonshot.ts +34 -13
  64. package/src/providers/muse.js +6 -0
  65. package/src/providers/muse.ts +8 -0
  66. package/src/providers/ollama.js +39 -7
  67. package/src/providers/ollama.ts +36 -7
  68. package/src/providers/openai-compatible.js +16 -3
  69. package/src/providers/openai-compatible.ts +13 -3
  70. package/src/providers/openai.js +62 -4
  71. package/src/providers/openai.ts +50 -4
  72. package/src/providers/openrouter.js +19 -4
  73. package/src/providers/openrouter.ts +21 -4
  74. package/src/providers/qwen-byok.js +21 -5
  75. package/src/providers/qwen-byok.ts +29 -11
  76. package/src/providers/xai.js +26 -10
  77. package/src/providers/xai.ts +34 -16
  78. package/src/reporting.js +4 -2
  79. package/src/reporting.ts +4 -2
  80. package/src/sandbox.js +34 -0
  81. package/src/sandbox.ts +43 -0
  82. package/src/scheduler/scheduler.js +372 -0
  83. package/src/scheduler/scheduler.ts +433 -0
  84. package/src/sessionSearchIndex.js +267 -0
  85. package/src/sessionSearchIndex.ts +311 -0
  86. package/src/skillsManager.js +2 -3
  87. package/src/skillsManager.ts +2 -3
  88. package/src/toolPacks.js +6 -0
  89. package/src/toolPacks.ts +6 -0
  90. package/src/tools/applyPatch.js +1 -1
  91. package/src/tools/applyPatch.ts +1 -1
  92. package/src/tools/generateMediaViaApi.js +4 -3
  93. package/src/tools/generateMediaViaApi.ts +4 -3
  94. package/src/tools/nativeEngine.js +2 -2
  95. package/src/tools/nativeEngine.ts +2 -2
  96. package/src/tools/openSourceToolProvisioner.js +2 -2
  97. package/src/tools/openSourceToolProvisioner.ts +2 -2
  98. package/src/tools/payloadSanitizer.js +0 -1
  99. package/src/tools/payloadSanitizer.ts +0 -1
  100. package/src/tools/pdfReader.js +122 -20
  101. package/src/tools/pdfReader.ts +111 -20
  102. package/src/tools/presentDeliverable.js +103 -0
  103. package/src/tools/presentDeliverable.ts +127 -0
  104. package/src/tools/ptcRuntime.js +444 -0
  105. package/src/tools/ptcRuntime.ts +490 -0
  106. package/src/tools/ptyTerminal.js +1096 -0
  107. package/src/tools/ptyTerminal.ts +1231 -0
  108. package/src/tools/registry.js +21 -12
  109. package/src/tools/registry.ts +21 -12
  110. package/src/tools/toolOutputStore.js +26 -4
  111. package/src/tools/toolOutputStore.ts +22 -4
  112. package/src/tools/webFetch.js +158 -11
  113. package/src/tools/webFetch.ts +145 -11
  114. package/src/tools/webSearch.js +123 -36
  115. package/src/tools/webSearch.ts +124 -33
  116. package/src/tui/banner.js +5 -1
  117. package/src/tui/banner.ts +6 -1
  118. package/src/tui/chatRenderer.js +1 -2
  119. package/src/tui/chatRenderer.ts +1 -2
  120. package/src/tui/completion.js +1 -0
  121. package/src/tui/completion.ts +1 -0
  122. package/src/tui/composerControls.js +111 -27
  123. package/src/tui/composerControls.ts +124 -28
  124. package/src/tui/dialogs.js +3 -16
  125. package/src/tui/dialogs.ts +3 -16
  126. package/src/tui/home.js +1 -0
  127. package/src/tui/home.ts +1 -0
  128. package/src/tui/invocation.js +1 -2
  129. package/src/tui/invocation.ts +1 -2
  130. package/src/tui/modelPicker.js +22 -12
  131. package/src/tui/modelPicker.ts +22 -12
  132. package/src/tui/overlay.js +2 -5
  133. package/src/tui/overlay.ts +2 -5
  134. package/src/tui/prompt.js +6 -4
  135. package/src/tui/prompt.ts +6 -4
  136. package/src/tui/selectList.js +4 -12
  137. package/src/tui/selectList.ts +4 -12
  138. package/src/tui/setup.js +22 -9
  139. package/src/tui/setup.ts +26 -9
  140. package/src/tui/statusLine.ts +2 -0
  141. package/src/web/client/browserPanel.js +702 -0
  142. package/src/web/client/browserPanel.ts +663 -0
  143. package/src/web/client/chatStream.js +309 -0
  144. package/src/web/client/chatStream.ts +289 -0
  145. package/src/web/client/cliPanel.js +165 -0
  146. package/src/web/client/cliPanel.ts +171 -0
  147. package/src/web/client/composer.js +204 -0
  148. package/src/web/client/composer.ts +209 -0
  149. package/src/web/client/diffPanel.js +176 -0
  150. package/src/web/client/diffPanel.ts +203 -0
  151. package/src/web/client/dom.js +220 -0
  152. package/src/web/client/dom.ts +221 -0
  153. package/src/web/client/filesAndCanvas.js +231 -0
  154. package/src/web/client/filesAndCanvas.ts +238 -0
  155. package/src/web/client/gameLauncherUi.js +78 -0
  156. package/src/web/client/gameLauncherUi.ts +78 -0
  157. package/src/web/client/main.js +301 -0
  158. package/src/web/client/main.ts +368 -0
  159. package/src/web/client/markdown.js +364 -0
  160. package/src/web/client/markdown.ts +373 -0
  161. package/src/web/client/modelPicker.js +455 -0
  162. package/src/web/client/modelPicker.ts +451 -0
  163. package/src/web/client/permissionPresetsUi.js +307 -0
  164. package/src/web/client/permissionPresetsUi.ts +333 -0
  165. package/src/web/client/sessions.js +353 -0
  166. package/src/web/client/sessions.ts +372 -0
  167. package/src/web/client/settingsModal.js +191 -0
  168. package/src/web/client/settingsModal.ts +176 -0
  169. package/src/web/client/state.js +250 -0
  170. package/src/web/client/state.ts +233 -0
  171. package/src/web/client/streamSmoother.js +127 -0
  172. package/src/web/client/streamSmoother.ts +119 -0
  173. package/src/web/client/studioLayout.js +54 -0
  174. package/src/web/client/studioLayout.ts +60 -0
  175. package/src/web/client/studioShell.js +327 -0
  176. package/src/web/client/studioShell.ts +340 -0
  177. package/src/web/client/studioStart.js +77 -0
  178. package/src/web/client/studioStart.ts +89 -0
  179. package/src/web/client/terminalPanel.js +357 -0
  180. package/src/web/client/terminalPanel.ts +345 -0
  181. package/src/web/client/turnView.js +934 -0
  182. package/src/web/client/turnView.ts +981 -0
  183. package/src/web/client/types.js +1 -0
  184. package/src/web/client/types.ts +319 -0
  185. package/src/web/client/validators.js +106 -0
  186. package/src/web/client/validators.ts +96 -0
  187. package/src/web/server/activeRuns.js +152 -0
  188. package/src/web/server/activeRuns.ts +171 -0
  189. package/src/web/server/routesBrowser.js +355 -0
  190. package/src/web/server/routesBrowser.ts +386 -0
  191. package/src/web/server/routesChat.js +304 -0
  192. package/src/web/server/routesChat.ts +347 -0
  193. package/src/web/server/routesCore.js +472 -0
  194. package/src/web/server/routesCore.ts +522 -0
  195. package/src/web/server/routesTerminal.js +162 -0
  196. package/src/web/server/routesTerminal.ts +182 -0
  197. package/src/web/server/routesWorkspace.js +510 -0
  198. package/src/web/server/routesWorkspace.ts +546 -0
  199. package/src/web/server/security.js +98 -0
  200. package/src/web/server/security.ts +108 -0
  201. package/src/web/server/sessionTranscript.js +586 -0
  202. package/src/web/server/sessionTranscript.ts +566 -0
  203. package/src/web/server/staticAssets.js +80 -0
  204. package/src/web/server/staticAssets.ts +91 -0
  205. package/src/web/server/types.js +1 -0
  206. package/src/web/server/types.ts +135 -0
  207. package/src/web/server/workspaceFiles.js +368 -0
  208. package/src/web/server/workspaceFiles.ts +363 -0
  209. package/src/web/skybridgeServer.js +76 -2449
  210. package/src/web/skybridgeServer.ts +118 -2600
  211. package/src/web/skybridgeUi.js +16 -450
  212. package/src/web/skybridgeUi.ts +16 -454
  213. package/src/web/styles/agent.css +380 -0
  214. package/src/web/styles/composer.css +193 -0
  215. package/src/web/styles/overlays.css +436 -0
  216. package/src/web/styles/shell.css +387 -0
  217. package/src/web/styles/studio.css +723 -0
  218. package/src/web/styles/thread.css +221 -0
  219. package/src/web/styles/tokens.css +94 -0
  220. package/src/web/ui/brandMark.js +73 -0
  221. package/src/web/ui/brandMark.ts +82 -0
  222. package/src/web/ui/modalsTemplate.js +139 -0
  223. package/src/web/ui/modalsTemplate.ts +139 -0
  224. package/src/web/ui/sidebarTemplate.js +63 -0
  225. package/src/web/ui/sidebarTemplate.ts +64 -0
  226. package/src/web/ui/studioTemplate.js +258 -0
  227. package/src/web/ui/studioTemplate.ts +258 -0
  228. package/src/web/ui/workspaceTemplate.js +72 -0
  229. package/src/web/ui/workspaceTemplate.ts +73 -0
  230. package/src/worktreeManager.js +16 -1
  231. package/src/worktreeManager.ts +22 -1
  232. package/src/web/skybridgeClientScript.js +0 -3951
  233. package/src/web/skybridgeClientScript.ts +0 -3952
  234. package/src/web/skybridgeStyles.js +0 -827
  235. package/src/web/skybridgeStyles.ts +0 -828
@@ -1,6 +1,9 @@
1
1
  import fs from 'node:fs/promises';
2
- import { getErrorMessage, assertSafeWorkspaceInput, boundedInteger, sanitizeToolError, sanitizeToolText } from './toolPathSafety.js';
2
+ import zlib from 'node:zlib';
3
+ import { assertSafeWorkspaceInput, boundedInteger, sanitizeToolError, sanitizeToolText } from './toolPathSafety.js';
3
4
  const MAX_PDF_FILE_BYTES = 10 * 1024 * 1024;
5
+ const MAX_DECOMPRESSED_STREAM_BYTES = 4 * 1024 * 1024;
6
+ const MAX_TOTAL_DECOMPRESSED_BYTES = 16 * 1024 * 1024;
4
7
  function decodePdfLiteral(raw) {
5
8
  return raw.replace(/\\([nrt()\\]|[0-7]{1,3})/g, (_match, token) => {
6
9
  if (token === 'n')
@@ -14,31 +17,130 @@ function decodePdfLiteral(raw) {
14
17
  return String.fromCharCode(parseInt(token, 8));
15
18
  });
16
19
  }
17
- function extractTextFromPdfBuffer(buffer) {
18
- const textChunks = [];
19
- const content = buffer.toString('binary');
20
+ function decodePdfHexString(hex) {
21
+ const cleaned = hex.replace(/[^0-9a-fA-F]/g, '');
22
+ if (cleaned.length < 2)
23
+ return '';
24
+ const padded = cleaned.length % 2 === 1 ? `${cleaned}0` : cleaned;
25
+ const bytes = Buffer.from(padded, 'hex');
26
+ if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
27
+ // UTF-16BE BOM
28
+ let out = '';
29
+ for (let i = 2; i + 1 < bytes.length; i += 2) {
30
+ out += String.fromCharCode((bytes[i] << 8) | bytes[i + 1]);
31
+ }
32
+ return out;
33
+ }
34
+ return bytes.toString('latin1');
35
+ }
36
+ function extractTextBlocksFromStream(streamContent, out) {
20
37
  let pos = 0;
21
- while (pos < content.length) {
22
- const start = content.indexOf('BT', pos);
38
+ while (pos < streamContent.length) {
39
+ const start = streamContent.indexOf('BT', pos);
23
40
  if (start === -1)
24
41
  break;
25
- const end = content.indexOf('ET', start + 2);
42
+ const end = streamContent.indexOf('ET', start + 2);
26
43
  if (end === -1)
27
44
  break;
28
- const block = content.slice(start, end + 2);
45
+ const block = streamContent.slice(start + 2, end);
29
46
  pos = end + 2;
30
- const strRegex = /\(([^)]{1,4096})\)/g;
31
- let strMatch;
32
- while ((strMatch = strRegex.exec(block)) !== null) {
33
- const rawText = decodePdfLiteral(strMatch[1] ?? '');
34
- if (rawText && rawText.trim().length > 0 && !rawText.startsWith('F') && !rawText.includes('\x00')) {
35
- textChunks.push(rawText);
47
+ let i = 0;
48
+ while (i < block.length) {
49
+ const ch = block[i];
50
+ if (ch === '(') {
51
+ let depth = 1;
52
+ let j = i + 1;
53
+ while (j < block.length && depth > 0) {
54
+ if (block[j] === '\\') {
55
+ j += 2;
56
+ continue;
57
+ }
58
+ if (block[j] === '(')
59
+ depth++;
60
+ else if (block[j] === ')')
61
+ depth--;
62
+ j++;
63
+ }
64
+ const raw = block.slice(i + 1, Math.max(i + 1, j - 1)).slice(0, 4096);
65
+ const decoded = decodePdfLiteral(raw);
66
+ if (decoded && decoded.trim().length > 0 && !decoded.includes('\x00')) {
67
+ out.push(decoded);
68
+ }
69
+ i = j;
70
+ continue;
71
+ }
72
+ if (ch === '<' && block[i + 1] !== '<') {
73
+ const close = block.indexOf('>', i + 1);
74
+ if (close !== -1) {
75
+ const decoded = decodePdfHexString(block.slice(i + 1, close).slice(0, 4096));
76
+ if (decoded && decoded.trim().length > 0 && !decoded.includes('\x00')) {
77
+ out.push(decoded);
78
+ }
79
+ i = close + 1;
80
+ continue;
81
+ }
82
+ }
83
+ i++;
84
+ }
85
+ }
86
+ }
87
+ function tryInflatePdfStream(rawSlice) {
88
+ if (rawSlice.length === 0 || rawSlice.length > MAX_DECOMPRESSED_STREAM_BYTES)
89
+ return null;
90
+ try {
91
+ return zlib.inflateSync(rawSlice, { maxOutputLength: MAX_DECOMPRESSED_STREAM_BYTES });
92
+ }
93
+ catch {
94
+ try {
95
+ return zlib.inflateRawSync(rawSlice, { maxOutputLength: MAX_DECOMPRESSED_STREAM_BYTES });
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ }
102
+ export function extractTextFromPdfBuffer(buffer) {
103
+ const textChunks = [];
104
+ const rawBinary = buffer.toString('binary');
105
+ // 1. Decompress FlateDecode / zlib PDF streams using built-in node:zlib
106
+ let totalDecompressed = 0;
107
+ let searchPos = 0;
108
+ while (searchPos < rawBinary.length && totalDecompressed < MAX_TOTAL_DECOMPRESSED_BYTES) {
109
+ const streamToken = rawBinary.indexOf('stream', searchPos);
110
+ if (streamToken === -1)
111
+ break;
112
+ let dataStart = streamToken + 6;
113
+ if (rawBinary[dataStart] === '\r' && rawBinary[dataStart + 1] === '\n')
114
+ dataStart += 2;
115
+ else if (rawBinary[dataStart] === '\n' || rawBinary[dataStart] === '\r')
116
+ dataStart += 1;
117
+ const endToken = rawBinary.indexOf('endstream', dataStart);
118
+ if (endToken === -1)
119
+ break;
120
+ searchPos = endToken + 9;
121
+ // Trim trailing line break before `endstream`
122
+ let dataEnd = endToken;
123
+ if (dataEnd > dataStart && rawBinary[dataEnd - 1] === '\n')
124
+ dataEnd--;
125
+ if (dataEnd > dataStart && rawBinary[dataEnd - 1] === '\r')
126
+ dataEnd--;
127
+ if (dataEnd <= dataStart)
128
+ continue;
129
+ const dictWindow = rawBinary.slice(Math.max(0, streamToken - 320), streamToken);
130
+ if (dictWindow.includes('FlateDecode')) {
131
+ const inflated = tryInflatePdfStream(buffer.subarray(dataStart, dataEnd));
132
+ if (inflated && inflated.length > 0) {
133
+ totalDecompressed += inflated.length;
134
+ extractTextBlocksFromStream(inflated.toString('latin1'), textChunks);
36
135
  }
37
136
  }
38
137
  }
39
- if (textChunks.length < 5) {
138
+ // 2. Also scan uncompressed streams directly
139
+ extractTextBlocksFromStream(rawBinary, textChunks);
140
+ const combined = textChunks.join(' ').trim();
141
+ if (combined.length < 10) {
40
142
  const printableRegex = /[\x20-\x7E\r\n\t]{5,}/g;
41
- const matches = content.match(printableRegex) || [];
143
+ const matches = rawBinary.match(printableRegex) || [];
42
144
  const keywords = ['obj', 'endobj', 'stream', 'endstream', 'xref', 'trailer', 'startxref', 'Catalog', 'Pages', 'Font', 'XObject', 'ProcSet', 'MediaBox'];
43
145
  const filtered = matches.filter((s) => {
44
146
  const trimmed = s.trim();
@@ -52,18 +154,18 @@ function extractTextFromPdfBuffer(buffer) {
52
154
  return filtered.join('\n');
53
155
  }
54
156
  }
55
- return textChunks.join(' ');
157
+ return combined;
56
158
  }
57
159
  export const pdfRead = {
58
160
  schema: {
59
161
  name: 'pdf_read',
60
- description: 'Extract text content from a local PDF document file. Ideal for reading attached PDFs, reports, scripts, and theses.',
162
+ description: 'Extract text content from a local PDF document file (supports both uncompressed and FlateDecode-compressed streams). Ideal for reading attached PDFs, reports, scripts, and papers.',
61
163
  parameters: {
62
164
  type: 'object',
63
165
  properties: {
64
166
  path: {
65
167
  type: 'string',
66
- description: 'Absolute path to the .pdf file.'
168
+ description: 'Absolute or workspace-relative path to the .pdf file.'
67
169
  },
68
170
  maxChars: {
69
171
  type: 'number',
@@ -85,7 +187,7 @@ export const pdfRead = {
85
187
  if (!extractedText || extractedText.length < 20) {
86
188
  return {
87
189
  success: true,
88
- output: `[NOTICE: Only minimal text extracted (${extractedText.length} chars). The PDF might be scanned/image-based or heavily FlateDecode-compressed. For image-based PDFs, try converting pages to images or using OCR.]`,
190
+ output: `[NOTICE: Only minimal text extracted (${extractedText.length} chars). The PDF might be scanned/image-based. For scanned PDFs, convert pages to images and inspect visually.]`,
89
191
  rawExtracted: extractedText
90
192
  };
91
193
  }
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
+ import zlib from 'node:zlib';
2
3
  import {
3
- getErrorMessage,
4
4
  assertSafeWorkspaceInput,
5
5
  boundedInteger,
6
6
  sanitizeToolError,
@@ -9,6 +9,8 @@ import {
9
9
  } from './toolPathSafety.js';
10
10
 
11
11
  const MAX_PDF_FILE_BYTES = 10 * 1024 * 1024;
12
+ const MAX_DECOMPRESSED_STREAM_BYTES = 4 * 1024 * 1024;
13
+ const MAX_TOTAL_DECOMPRESSED_BYTES = 16 * 1024 * 1024;
12
14
 
13
15
  function decodePdfLiteral(raw: string): string {
14
16
  return raw.replace(/\\([nrt()\\]|[0-7]{1,3})/g, (_match, token: string) => {
@@ -20,32 +22,121 @@ function decodePdfLiteral(raw: string): string {
20
22
  });
21
23
  }
22
24
 
23
- function extractTextFromPdfBuffer(buffer: Buffer): string {
24
- const textChunks: string[] = [];
25
- const content = buffer.toString('binary');
25
+ function decodePdfHexString(hex: string): string {
26
+ const cleaned = hex.replace(/[^0-9a-fA-F]/g, '');
27
+ if (cleaned.length < 2) return '';
28
+ const padded = cleaned.length % 2 === 1 ? `${cleaned}0` : cleaned;
29
+ const bytes = Buffer.from(padded, 'hex');
30
+ if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
31
+ // UTF-16BE BOM
32
+ let out = '';
33
+ for (let i = 2; i + 1 < bytes.length; i += 2) {
34
+ out += String.fromCharCode((bytes[i]! << 8) | bytes[i + 1]!);
35
+ }
36
+ return out;
37
+ }
38
+ return bytes.toString('latin1');
39
+ }
26
40
 
41
+ function extractTextBlocksFromStream(streamContent: string, out: string[]): void {
27
42
  let pos = 0;
28
- while (pos < content.length) {
29
- const start = content.indexOf('BT', pos);
43
+ while (pos < streamContent.length) {
44
+ const start = streamContent.indexOf('BT', pos);
30
45
  if (start === -1) break;
31
- const end = content.indexOf('ET', start + 2);
46
+ const end = streamContent.indexOf('ET', start + 2);
32
47
  if (end === -1) break;
33
- const block = content.slice(start, end + 2);
48
+ const block = streamContent.slice(start + 2, end);
34
49
  pos = end + 2;
35
50
 
36
- const strRegex = /\(([^)]{1,4096})\)/g;
37
- let strMatch: RegExpExecArray | null;
38
- while ((strMatch = strRegex.exec(block)) !== null) {
39
- const rawText = decodePdfLiteral(strMatch[1] ?? '');
40
- if (rawText && rawText.trim().length > 0 && !rawText.startsWith('F') && !rawText.includes('\x00')) {
41
- textChunks.push(rawText);
51
+ let i = 0;
52
+ while (i < block.length) {
53
+ const ch = block[i]!;
54
+ if (ch === '(') {
55
+ let depth = 1;
56
+ let j = i + 1;
57
+ while (j < block.length && depth > 0) {
58
+ if (block[j] === '\\') { j += 2; continue; }
59
+ if (block[j] === '(') depth++;
60
+ else if (block[j] === ')') depth--;
61
+ j++;
62
+ }
63
+ const raw = block.slice(i + 1, Math.max(i + 1, j - 1)).slice(0, 4096);
64
+ const decoded = decodePdfLiteral(raw);
65
+ if (decoded && decoded.trim().length > 0 && !decoded.includes('\x00')) {
66
+ out.push(decoded);
67
+ }
68
+ i = j;
69
+ continue;
42
70
  }
71
+ if (ch === '<' && block[i + 1] !== '<') {
72
+ const close = block.indexOf('>', i + 1);
73
+ if (close !== -1) {
74
+ const decoded = decodePdfHexString(block.slice(i + 1, close).slice(0, 4096));
75
+ if (decoded && decoded.trim().length > 0 && !decoded.includes('\x00')) {
76
+ out.push(decoded);
77
+ }
78
+ i = close + 1;
79
+ continue;
80
+ }
81
+ }
82
+ i++;
43
83
  }
44
84
  }
85
+ }
86
+
87
+ function tryInflatePdfStream(rawSlice: Buffer): Buffer | null {
88
+ if (rawSlice.length === 0 || rawSlice.length > MAX_DECOMPRESSED_STREAM_BYTES) return null;
89
+ try {
90
+ return zlib.inflateSync(rawSlice, { maxOutputLength: MAX_DECOMPRESSED_STREAM_BYTES });
91
+ } catch {
92
+ try {
93
+ return zlib.inflateRawSync(rawSlice, { maxOutputLength: MAX_DECOMPRESSED_STREAM_BYTES });
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ }
99
+
100
+ export function extractTextFromPdfBuffer(buffer: Buffer): string {
101
+ const textChunks: string[] = [];
102
+ const rawBinary = buffer.toString('binary');
103
+
104
+ // 1. Decompress FlateDecode / zlib PDF streams using built-in node:zlib
105
+ let totalDecompressed = 0;
106
+ let searchPos = 0;
107
+ while (searchPos < rawBinary.length && totalDecompressed < MAX_TOTAL_DECOMPRESSED_BYTES) {
108
+ const streamToken = rawBinary.indexOf('stream', searchPos);
109
+ if (streamToken === -1) break;
110
+ let dataStart = streamToken + 6;
111
+ if (rawBinary[dataStart] === '\r' && rawBinary[dataStart + 1] === '\n') dataStart += 2;
112
+ else if (rawBinary[dataStart] === '\n' || rawBinary[dataStart] === '\r') dataStart += 1;
113
+ const endToken = rawBinary.indexOf('endstream', dataStart);
114
+ if (endToken === -1) break;
115
+ searchPos = endToken + 9;
116
+
117
+ // Trim trailing line break before `endstream`
118
+ let dataEnd = endToken;
119
+ if (dataEnd > dataStart && rawBinary[dataEnd - 1] === '\n') dataEnd--;
120
+ if (dataEnd > dataStart && rawBinary[dataEnd - 1] === '\r') dataEnd--;
121
+ if (dataEnd <= dataStart) continue;
122
+
123
+ const dictWindow = rawBinary.slice(Math.max(0, streamToken - 320), streamToken);
124
+ if (dictWindow.includes('FlateDecode')) {
125
+ const inflated = tryInflatePdfStream(buffer.subarray(dataStart, dataEnd));
126
+ if (inflated && inflated.length > 0) {
127
+ totalDecompressed += inflated.length;
128
+ extractTextBlocksFromStream(inflated.toString('latin1'), textChunks);
129
+ }
130
+ }
131
+ }
132
+
133
+ // 2. Also scan uncompressed streams directly
134
+ extractTextBlocksFromStream(rawBinary, textChunks);
45
135
 
46
- if (textChunks.length < 5) {
136
+ const combined = textChunks.join(' ').trim();
137
+ if (combined.length < 10) {
47
138
  const printableRegex = /[\x20-\x7E\r\n\t]{5,}/g;
48
- const matches = content.match(printableRegex) || [];
139
+ const matches = rawBinary.match(printableRegex) || [];
49
140
  const keywords = ['obj', 'endobj', 'stream', 'endstream', 'xref', 'trailer', 'startxref', 'Catalog', 'Pages', 'Font', 'XObject', 'ProcSet', 'MediaBox'];
50
141
  const filtered = matches.filter((s) => {
51
142
  const trimmed = s.trim();
@@ -58,7 +149,7 @@ function extractTextFromPdfBuffer(buffer: Buffer): string {
58
149
  }
59
150
  }
60
151
 
61
- return textChunks.join(' ');
152
+ return combined;
62
153
  }
63
154
 
64
155
  export interface PdfReadArgs {
@@ -77,13 +168,13 @@ export interface PdfReadResult {
77
168
  export const pdfRead = {
78
169
  schema: {
79
170
  name: 'pdf_read',
80
- description: 'Extract text content from a local PDF document file. Ideal for reading attached PDFs, reports, scripts, and theses.',
171
+ description: 'Extract text content from a local PDF document file (supports both uncompressed and FlateDecode-compressed streams). Ideal for reading attached PDFs, reports, scripts, and papers.',
81
172
  parameters: {
82
173
  type: 'object',
83
174
  properties: {
84
175
  path: {
85
176
  type: 'string',
86
- description: 'Absolute path to the .pdf file.'
177
+ description: 'Absolute or workspace-relative path to the .pdf file.'
87
178
  },
88
179
  maxChars: {
89
180
  type: 'number',
@@ -106,7 +197,7 @@ export const pdfRead = {
106
197
  if (!extractedText || extractedText.length < 20) {
107
198
  return {
108
199
  success: true,
109
- output: `[NOTICE: Only minimal text extracted (${extractedText.length} chars). The PDF might be scanned/image-based or heavily FlateDecode-compressed. For image-based PDFs, try converting pages to images or using OCR.]`,
200
+ output: `[NOTICE: Only minimal text extracted (${extractedText.length} chars). The PDF might be scanned/image-based. For scanned PDFs, convert pages to images and inspect visually.]`,
110
201
  rawExtracted: extractedText
111
202
  };
112
203
  }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Causyne Agent — Explicit Deliverable Presentation Tool (`present`)
3
+ *
4
+ * Allows the agent to formally surface up to 8 verified workspace deliverable
5
+ * files (reports, PDFs, images, HTML demos, documents, charts) with descriptions
6
+ * for rich presentation in TUI and Skybridge Web Studio.
7
+ */
8
+ import fs from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { isIgnoredByCausyneIgnore } from '../ignoreRules.js';
11
+ import { resolveScopedPath, resolveToolWorkspaceRoots, sanitizeToolError } from './toolPathSafety.js';
12
+ const MAX_DELIVERABLES = 8;
13
+ function classifyDeliverableKind(filePath) {
14
+ const ext = path.extname(filePath).toLowerCase();
15
+ if (ext === '.html' || ext === '.htm' || ext === '.svg')
16
+ return 'html';
17
+ if (ext === '.md' || ext === '.markdown' || ext === '.idoc')
18
+ return 'markdown';
19
+ if (ext === '.pdf')
20
+ return 'pdf';
21
+ if (['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif'].includes(ext))
22
+ return 'image';
23
+ if (['.docx', '.xlsx', '.pptx', '.csv', '.txt', '.rtf'].includes(ext))
24
+ return 'document';
25
+ if (['.ts', '.tsx', '.js', '.jsx', '.py', '.rs', '.go', '.java', '.css', '.json', '.yaml', '.yml'].includes(ext))
26
+ return 'code';
27
+ return 'file';
28
+ }
29
+ export const presentDeliverableTool = {
30
+ schema: {
31
+ name: 'present',
32
+ description: 'Present up to 8 verified workspace deliverable files (PDFs, images, HTML previews, reports, documents) cleanly to the user with concise descriptions. Use for finished user-facing artifacts rather than routine source edits.',
33
+ parameters: {
34
+ type: 'object',
35
+ properties: {
36
+ files: {
37
+ type: 'array',
38
+ minItems: 1,
39
+ maxItems: MAX_DELIVERABLES,
40
+ items: {
41
+ type: 'object',
42
+ properties: {
43
+ path: { type: 'string', description: 'Workspace-relative or scoped absolute path to an existing regular file.' },
44
+ description: { type: 'string', description: 'Short one-line description of what this deliverable contains.' }
45
+ },
46
+ required: ['path'],
47
+ additionalProperties: false
48
+ }
49
+ }
50
+ },
51
+ required: ['files'],
52
+ additionalProperties: false
53
+ }
54
+ },
55
+ async execute(args, context = {}) {
56
+ try {
57
+ if (!Array.isArray(args?.files) || args.files.length === 0) {
58
+ return { success: false, error: 'files must be a non-empty array of 1-8 workspace files.' };
59
+ }
60
+ if (args.files.length > MAX_DELIVERABLES) {
61
+ return { success: false, error: `At most ${MAX_DELIVERABLES} deliverables can be presented in one call.` };
62
+ }
63
+ const scope = resolveToolWorkspaceRoots(context);
64
+ const primaryRoot = scope.primaryRoot || process.cwd();
65
+ const presented = [];
66
+ const seen = new Set();
67
+ for (const item of args.files) {
68
+ if (!item || typeof item.path !== 'string' || !item.path.trim()) {
69
+ return { success: false, error: 'Every deliverable entry requires a non-empty path string.' };
70
+ }
71
+ const resolved = resolveScopedPath(item.path, context);
72
+ if (isIgnoredByCausyneIgnore(resolved, primaryRoot, false)) {
73
+ return { success: false, error: `Deliverable path is blocked by .causyneignore: ${item.path}` };
74
+ }
75
+ const lstat = await fs.lstat(resolved);
76
+ if (lstat.isSymbolicLink() || !lstat.isFile()) {
77
+ return { success: false, error: `Deliverable must be a regular workspace file: ${item.path}` };
78
+ }
79
+ const rel = path.relative(primaryRoot, resolved).split(path.sep).join('/');
80
+ if (seen.has(rel))
81
+ continue;
82
+ seen.add(rel);
83
+ presented.push({
84
+ path: rel,
85
+ absolutePath: resolved,
86
+ name: path.basename(resolved),
87
+ sizeBytes: lstat.size,
88
+ kind: classifyDeliverableKind(resolved),
89
+ description: typeof item.description === 'string' ? item.description.trim().slice(0, 240) : ''
90
+ });
91
+ }
92
+ const lines = presented.map((d, idx) => `${idx + 1}. ${d.path} (${d.kind}, ${d.sizeBytes} B)${d.description ? ` — ${d.description}` : ''}`);
93
+ return {
94
+ success: true,
95
+ deliverables: presented,
96
+ output: `Presented ${presented.length} deliverable(s):\n${lines.join('\n')}`
97
+ };
98
+ }
99
+ catch (error) {
100
+ return { success: false, error: sanitizeToolError(error) };
101
+ }
102
+ }
103
+ };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Causyne Agent — Explicit Deliverable Presentation Tool (`present`)
3
+ *
4
+ * Allows the agent to formally surface up to 8 verified workspace deliverable
5
+ * files (reports, PDFs, images, HTML demos, documents, charts) with descriptions
6
+ * for rich presentation in TUI and Skybridge Web Studio.
7
+ */
8
+
9
+ import fs from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { isIgnoredByCausyneIgnore } from '../ignoreRules.js';
12
+ import {
13
+ resolveScopedPath,
14
+ resolveToolWorkspaceRoots,
15
+ sanitizeToolError,
16
+ type ToolWorkspaceContext
17
+ } from './toolPathSafety.js';
18
+
19
+ const MAX_DELIVERABLES = 8;
20
+
21
+ export interface DeliverableItemInput {
22
+ path: string;
23
+ description?: string | undefined;
24
+ }
25
+
26
+ export interface PresentedDeliverable {
27
+ path: string;
28
+ absolutePath: string;
29
+ name: string;
30
+ sizeBytes: number;
31
+ kind: 'html' | 'markdown' | 'pdf' | 'image' | 'document' | 'code' | 'file';
32
+ description: string;
33
+ }
34
+
35
+ function classifyDeliverableKind(filePath: string): PresentedDeliverable['kind'] {
36
+ const ext = path.extname(filePath).toLowerCase();
37
+ if (ext === '.html' || ext === '.htm' || ext === '.svg') return 'html';
38
+ if (ext === '.md' || ext === '.markdown' || ext === '.idoc') return 'markdown';
39
+ if (ext === '.pdf') return 'pdf';
40
+ if (['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif'].includes(ext)) return 'image';
41
+ if (['.docx', '.xlsx', '.pptx', '.csv', '.txt', '.rtf'].includes(ext)) return 'document';
42
+ if (['.ts', '.tsx', '.js', '.jsx', '.py', '.rs', '.go', '.java', '.css', '.json', '.yaml', '.yml'].includes(ext)) return 'code';
43
+ return 'file';
44
+ }
45
+
46
+ export const presentDeliverableTool = {
47
+ schema: {
48
+ name: 'present',
49
+ description:
50
+ 'Present up to 8 verified workspace deliverable files (PDFs, images, HTML previews, reports, documents) cleanly to the user with concise descriptions. Use for finished user-facing artifacts rather than routine source edits.',
51
+ parameters: {
52
+ type: 'object',
53
+ properties: {
54
+ files: {
55
+ type: 'array',
56
+ minItems: 1,
57
+ maxItems: MAX_DELIVERABLES,
58
+ items: {
59
+ type: 'object',
60
+ properties: {
61
+ path: { type: 'string', description: 'Workspace-relative or scoped absolute path to an existing regular file.' },
62
+ description: { type: 'string', description: 'Short one-line description of what this deliverable contains.' }
63
+ },
64
+ required: ['path'],
65
+ additionalProperties: false
66
+ }
67
+ }
68
+ },
69
+ required: ['files'],
70
+ additionalProperties: false
71
+ }
72
+ },
73
+
74
+ async execute(
75
+ args: { files?: DeliverableItemInput[] },
76
+ context: ToolWorkspaceContext = {}
77
+ ) {
78
+ try {
79
+ if (!Array.isArray(args?.files) || args.files.length === 0) {
80
+ return { success: false, error: 'files must be a non-empty array of 1-8 workspace files.' };
81
+ }
82
+ if (args.files.length > MAX_DELIVERABLES) {
83
+ return { success: false, error: `At most ${MAX_DELIVERABLES} deliverables can be presented in one call.` };
84
+ }
85
+ const scope = resolveToolWorkspaceRoots(context);
86
+ const primaryRoot = scope.primaryRoot || process.cwd();
87
+ const presented: PresentedDeliverable[] = [];
88
+ const seen = new Set<string>();
89
+
90
+ for (const item of args.files) {
91
+ if (!item || typeof item.path !== 'string' || !item.path.trim()) {
92
+ return { success: false, error: 'Every deliverable entry requires a non-empty path string.' };
93
+ }
94
+ const resolved = resolveScopedPath(item.path, context);
95
+ if (isIgnoredByCausyneIgnore(resolved, primaryRoot, false)) {
96
+ return { success: false, error: `Deliverable path is blocked by .causyneignore: ${item.path}` };
97
+ }
98
+ const lstat = await fs.lstat(resolved);
99
+ if (lstat.isSymbolicLink() || !lstat.isFile()) {
100
+ return { success: false, error: `Deliverable must be a regular workspace file: ${item.path}` };
101
+ }
102
+ const rel = path.relative(primaryRoot, resolved).split(path.sep).join('/');
103
+ if (seen.has(rel)) continue;
104
+ seen.add(rel);
105
+ presented.push({
106
+ path: rel,
107
+ absolutePath: resolved,
108
+ name: path.basename(resolved),
109
+ sizeBytes: lstat.size,
110
+ kind: classifyDeliverableKind(resolved),
111
+ description: typeof item.description === 'string' ? item.description.trim().slice(0, 240) : ''
112
+ });
113
+ }
114
+
115
+ const lines = presented.map(
116
+ (d, idx) => `${idx + 1}. ${d.path} (${d.kind}, ${d.sizeBytes} B)${d.description ? ` — ${d.description}` : ''}`
117
+ );
118
+ return {
119
+ success: true,
120
+ deliverables: presented,
121
+ output: `Presented ${presented.length} deliverable(s):\n${lines.join('\n')}`
122
+ };
123
+ } catch (error) {
124
+ return { success: false, error: sanitizeToolError(error) };
125
+ }
126
+ }
127
+ };