@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,363 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { isPhysicalPathAllowed, physicalPath } from '../../agent/workspaceBoundary.js';
5
+ import { isIgnoredByCausyneIgnore } from '../../ignoreRules.js';
6
+ import { parseUnifiedDiff } from '../../diffReview.js';
7
+
8
+ export const MAX_FILE_READ_BYTES = 512 * 1024;
9
+ export const MAX_FILE_WRITE_BYTES = 2 * 1024 * 1024;
10
+ export const MAX_ATTACHMENT_BYTES = 32 * 1024;
11
+ export const MAX_ATTACHMENTS = 6;
12
+ const MAX_LIST_ENTRIES = 250;
13
+ const SKIPPED_DIRS = new Set(['.git', 'node_modules', '.next', 'dist', 'build', '.venv']);
14
+
15
+ export function formatByteSize(bytes: number): string {
16
+ if (!Number.isFinite(bytes) || bytes < 0) return '0 B';
17
+ if (bytes < 1024) return `${Math.round(bytes)} B`;
18
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
19
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
20
+ }
21
+
22
+ export function resolveWorkspaceRelativePath(workspaceRoot: string, rawRel: string): string | null {
23
+ if (typeof rawRel !== 'string' || rawRel.includes('\0')) return null;
24
+ const cleaned = rawRel.trim();
25
+ if (!cleaned) return null;
26
+ if (path.isAbsolute(cleaned)) return null;
27
+ const candidate = path.resolve(workspaceRoot, cleaned);
28
+ if (!isPhysicalPathAllowed(candidate, [workspaceRoot], false)) return null;
29
+ return candidate;
30
+ }
31
+
32
+ export function workspaceMatchesSession(sessionWorkspace: string, workspaceRoot: string): boolean {
33
+ if (!sessionWorkspace) return false;
34
+ const resolvedSession = physicalPath(sessionWorkspace);
35
+ return resolvedSession === workspaceRoot || sessionWorkspace === workspaceRoot;
36
+ }
37
+
38
+ export function listWorkspaceEntries(
39
+ workspaceRoot: string,
40
+ relDir: string,
41
+ query = ''
42
+ ): Array<{ path: string; name: string; type: 'dir' | 'file'; size: number }> {
43
+ const targetDir = relDir ? resolveWorkspaceRelativePath(workspaceRoot, relDir) : workspaceRoot;
44
+ if (!targetDir) throw new Error('Requested directory is outside the locked workspace.');
45
+ const q = query.trim().toLowerCase();
46
+ const entries: Array<{ path: string; name: string; type: 'dir' | 'file'; size: number }> = [];
47
+
48
+ const scan = (dir: string, depth: number): void => {
49
+ if (entries.length >= MAX_LIST_ENTRIES) return;
50
+ let dirents: fs.Dirent[];
51
+ try {
52
+ dirents = fs.readdirSync(dir, { withFileTypes: true });
53
+ } catch {
54
+ return;
55
+ }
56
+ for (const d of dirents) {
57
+ if (entries.length >= MAX_LIST_ENTRIES) break;
58
+ if (d.isSymbolicLink()) continue;
59
+ if (d.isDirectory() && SKIPPED_DIRS.has(d.name)) continue;
60
+ const abs = path.join(dir, d.name);
61
+ if (!isPhysicalPathAllowed(abs, [workspaceRoot], false)) continue;
62
+ if (isIgnoredByCausyneIgnore(abs, workspaceRoot, d.isDirectory())) continue;
63
+ const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
64
+ const isDir = d.isDirectory();
65
+ let size = 0;
66
+ if (!isDir) {
67
+ try { size = fs.statSync(abs).size; } catch { size = 0; }
68
+ }
69
+ if (!q || rel.toLowerCase().includes(q)) {
70
+ entries.push({ path: rel, name: d.name, type: isDir ? 'dir' : 'file', size });
71
+ }
72
+ if (q && isDir && depth < 3) {
73
+ scan(abs, depth + 1);
74
+ }
75
+ }
76
+ };
77
+
78
+ scan(targetDir, 0);
79
+ entries.sort((a, b) => (a.type === b.type ? a.path.localeCompare(b.path) : a.type === 'dir' ? -1 : 1));
80
+ return entries;
81
+ }
82
+
83
+ export function buildWorkspacePromptWithAttachments(
84
+ workspaceRoot: string,
85
+ prompt: string,
86
+ rawAttachments: unknown
87
+ ): { effectivePrompt: string; attachedPaths: string[] } {
88
+ if (!Array.isArray(rawAttachments) || rawAttachments.length === 0) {
89
+ return { effectivePrompt: prompt, attachedPaths: [] };
90
+ }
91
+ const attachedPaths: string[] = [];
92
+ const sections: string[] = [];
93
+ for (const raw of rawAttachments.slice(0, MAX_ATTACHMENTS)) {
94
+ if (typeof raw !== 'string') continue;
95
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, raw);
96
+ if (!abs) continue;
97
+ if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) continue;
98
+ try {
99
+ const stat = fs.lstatSync(abs);
100
+ if (stat.isSymbolicLink() || !stat.isFile()) continue;
101
+ const buf = fs.readFileSync(abs);
102
+ if (buf.includes(0)) continue;
103
+ const sliced = buf.length > MAX_ATTACHMENT_BYTES ? buf.subarray(0, MAX_ATTACHMENT_BYTES) : buf;
104
+ const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
105
+ const truncatedNote = buf.length > MAX_ATTACHMENT_BYTES ? '\n[truncated]' : '';
106
+ attachedPaths.push(rel);
107
+ sections.push(`--- Attached workspace file: ${rel} ---\n${sliced.toString('utf8')}${truncatedNote}`);
108
+ } catch {
109
+ // skip unreadable attachment
110
+ }
111
+ }
112
+ if (sections.length === 0) {
113
+ return { effectivePrompt: prompt, attachedPaths: [] };
114
+ }
115
+ return {
116
+ effectivePrompt: `${sections.join('\n\n')}\n\n${prompt}`,
117
+ attachedPaths
118
+ };
119
+ }
120
+
121
+ export function buildSynthesizedWriteHunk(content: string): {
122
+ additions: number;
123
+ hunks: Array<{ header: string; lines: string[] }>;
124
+ } {
125
+ const lines = content.split(/\r?\n/);
126
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
127
+ const capped = lines.slice(0, 140).map((ln) => `+${ln}`);
128
+ if (lines.length > 140) capped.push(`+... (${lines.length - 140} more lines)`);
129
+ return {
130
+ additions: lines.length,
131
+ hunks: capped.length > 0
132
+ ? [{ header: `@@ -0,0 +1,${lines.length} @@`, lines: capped }]
133
+ : []
134
+ };
135
+ }
136
+
137
+ export function readLastGitCommitDiffForFile(
138
+ workspaceRoot: string,
139
+ relPath: string
140
+ ): { additions: number; deletions: number; hunks: Array<{ header: string; lines: string[] }> } | null {
141
+ if (!relPath || relPath.startsWith('-') || relPath.includes('\0')) return null;
142
+ try {
143
+ const raw = execFileSync(
144
+ 'git',
145
+ ['log', '-n', '1', '--format=', '--unified=3', '--no-color', '-p', '--', relPath],
146
+ {
147
+ cwd: workspaceRoot,
148
+ encoding: 'utf8',
149
+ stdio: ['ignore', 'pipe', 'ignore'],
150
+ maxBuffer: 256 * 1024,
151
+ timeout: 3000,
152
+ windowsHide: true
153
+ }
154
+ );
155
+ if (!raw || !raw.trim()) return null;
156
+ const parsed = parseUnifiedDiff(raw);
157
+ const first = parsed[0];
158
+ if (!first || first.hunks.length === 0) return null;
159
+ return {
160
+ additions: first.additions,
161
+ deletions: first.deletions,
162
+ hunks: first.hunks.slice(0, 12).map((h) => ({
163
+ header: h.header,
164
+ lines: h.lines.slice(0, 140)
165
+ }))
166
+ };
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+
172
+ const MAX_PACK_ASSET_BYTES = 4 * 1024 * 1024;
173
+ const MAX_PACK_TOTAL_BYTES = 32 * 1024 * 1024;
174
+ const MAX_PACK_ASSETS = 64;
175
+
176
+ function extractAttributeValue(rawAttrs: string, attrName: string): string | null {
177
+ const lower = rawAttrs.toLowerCase();
178
+ const target = attrName.toLowerCase();
179
+ let idx = 0;
180
+ while (idx < lower.length) {
181
+ const pos = lower.indexOf(target, idx);
182
+ if (pos === -1) return null;
183
+ const prevCh = pos > 0 ? lower[pos - 1]! : ' ';
184
+ const validPrev = prevCh === ' ' || prevCh === '\t' || prevCh === '\n' || prevCh === '\r' || prevCh === '/';
185
+ let after = pos + target.length;
186
+ while (after < rawAttrs.length && (rawAttrs[after] === ' ' || rawAttrs[after] === '\t')) after++;
187
+ if (validPrev && rawAttrs[after] === '=') {
188
+ after++;
189
+ while (after < rawAttrs.length && (rawAttrs[after] === ' ' || rawAttrs[after] === '\t')) after++;
190
+ if (after >= rawAttrs.length) return null;
191
+ const quote = rawAttrs[after]!;
192
+ if (quote === '"' || quote === "'") {
193
+ const end = rawAttrs.indexOf(quote, after + 1);
194
+ return end === -1 ? null : rawAttrs.slice(after + 1, end).trim();
195
+ }
196
+ let end = after;
197
+ while (end < rawAttrs.length && rawAttrs[end] !== ' ' && rawAttrs[end] !== '\t' && rawAttrs[end] !== '\n' && rawAttrs[end] !== '\r') {
198
+ end++;
199
+ }
200
+ return rawAttrs.slice(after, end).trim();
201
+ }
202
+ idx = pos + target.length;
203
+ }
204
+ return null;
205
+ }
206
+
207
+ function isSafeRelativeAssetRef(ref: string): boolean {
208
+ if (!ref || ref.includes('\0')) return false;
209
+ const trimmed = ref.trim();
210
+ if (!trimmed || trimmed.startsWith('/') || trimmed.startsWith('//') || trimmed.startsWith('#')) return false;
211
+ // Reject any URI scheme (http:, https:, data:, javascript:, vbscript:, blob:, file:, etc.)
212
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
213
+ return false;
214
+ }
215
+ return true;
216
+ }
217
+
218
+ function escapeInlineTagClose(content: string, tagName: 'script' | 'style'): string {
219
+ const needle = `</${tagName}`;
220
+ let out = '';
221
+ let i = 0;
222
+ const lower = content.toLowerCase();
223
+ while (i < content.length) {
224
+ const found = lower.indexOf(needle, i);
225
+ if (found === -1) {
226
+ out += content.slice(i);
227
+ break;
228
+ }
229
+ out += content.slice(i, found) + `<\\/${tagName}`;
230
+ i = found + needle.length;
231
+ }
232
+ return out;
233
+ }
234
+
235
+ /**
236
+ * Bounded zero-dependency static HTML preview bundler.
237
+ * Inlines relative local `<link rel="stylesheet" href="...">` and `<script src="...">`
238
+ * files strictly inside the workspace boundary so multi-file HTML projects preview cleanly
239
+ * inside sandboxed iframes without spawning a local HTTP server.
240
+ */
241
+ export function packLocalHtmlPreview(
242
+ workspaceRoot: string,
243
+ relHtmlPath: string
244
+ ): { html: string; packedAssets: number; totalBytes: number } {
245
+ const absHtml = resolveWorkspaceRelativePath(workspaceRoot, relHtmlPath);
246
+ if (!absHtml) throw new Error('HTML preview path is outside the locked workspace.');
247
+ const htmlStat = fs.lstatSync(absHtml);
248
+ if (htmlStat.isSymbolicLink() || !htmlStat.isFile()) {
249
+ throw new Error('Only regular HTML workspace files can be previewed.');
250
+ }
251
+ if (htmlStat.size > MAX_PACK_ASSET_BYTES) {
252
+ throw new Error('HTML file exceeds preview size cap.');
253
+ }
254
+ const rawHtml = fs.readFileSync(absHtml, 'utf8');
255
+ if (rawHtml.includes('\0')) {
256
+ throw new Error('Binary content cannot be previewed as HTML.');
257
+ }
258
+
259
+ const baseDir = path.dirname(absHtml);
260
+ let packedAssets = 0;
261
+ let totalBytes = Buffer.byteLength(rawHtml, 'utf8');
262
+ const outParts: string[] = [];
263
+ let cursor = 0;
264
+
265
+ while (cursor < rawHtml.length) {
266
+ const lt = rawHtml.indexOf('<', cursor);
267
+ if (lt === -1) {
268
+ outParts.push(rawHtml.slice(cursor));
269
+ break;
270
+ }
271
+ if (lt > cursor) outParts.push(rawHtml.slice(cursor, lt));
272
+
273
+ if (rawHtml.startsWith('<!--', lt)) {
274
+ const endComment = rawHtml.indexOf('-->', lt + 4);
275
+ const next = endComment === -1 ? rawHtml.length : endComment + 3;
276
+ outParts.push(rawHtml.slice(lt, next));
277
+ cursor = next;
278
+ continue;
279
+ }
280
+
281
+ let gt = lt + 1;
282
+ let quote: string | null = null;
283
+ while (gt < rawHtml.length) {
284
+ const ch = rawHtml[gt]!;
285
+ if (quote) {
286
+ if (ch === quote) quote = null;
287
+ } else if (ch === '"' || ch === "'") {
288
+ quote = ch;
289
+ } else if (ch === '>') {
290
+ break;
291
+ }
292
+ gt++;
293
+ }
294
+ if (gt >= rawHtml.length) {
295
+ outParts.push(rawHtml.slice(lt));
296
+ break;
297
+ }
298
+
299
+ const tagContent = rawHtml.slice(lt + 1, gt);
300
+ const trimmedTag = tagContent.trim();
301
+ const spaceIdx = trimmedTag.search(/[\s/>]/);
302
+ const tagName = (spaceIdx === -1 ? trimmedTag : trimmedTag.slice(0, spaceIdx)).toLowerCase();
303
+ const rawAttrs = spaceIdx === -1 ? '' : trimmedTag.slice(spaceIdx);
304
+
305
+ if (tagName === 'base' && extractAttributeValue(rawAttrs, 'href')) {
306
+ throw new Error('HTML preview refuses <base href> overrides.');
307
+ }
308
+
309
+ const readBundledAsset = (ref: string): string | null => {
310
+ if (packedAssets >= MAX_PACK_ASSETS || !isSafeRelativeAssetRef(ref)) return null;
311
+ const cleanRef = ref.split(/[?#]/, 1)[0] ?? '';
312
+ if (!cleanRef) return null;
313
+ const candidate = path.resolve(baseDir, cleanRef);
314
+ if (!isPhysicalPathAllowed(candidate, [workspaceRoot], false)) return null;
315
+ if (isIgnoredByCausyneIgnore(candidate, workspaceRoot, false)) return null;
316
+ try {
317
+ const stat = fs.lstatSync(candidate);
318
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_PACK_ASSET_BYTES) return null;
319
+ if (totalBytes + stat.size > MAX_PACK_TOTAL_BYTES) return null;
320
+ const buf = fs.readFileSync(candidate);
321
+ if (buf.includes(0)) return null;
322
+ packedAssets++;
323
+ totalBytes += buf.length;
324
+ return buf.toString('utf8');
325
+ } catch {
326
+ return null;
327
+ }
328
+ };
329
+
330
+ if (tagName === 'link') {
331
+ const rel = (extractAttributeValue(rawAttrs, 'rel') || '').toLowerCase();
332
+ const href = extractAttributeValue(rawAttrs, 'href');
333
+ if (rel.split(/\s+/).includes('stylesheet') && href) {
334
+ const css = readBundledAsset(href);
335
+ if (css !== null) {
336
+ outParts.push(`<style>${escapeInlineTagClose(css, 'style')}</style>`);
337
+ cursor = gt + 1;
338
+ continue;
339
+ }
340
+ }
341
+ }
342
+
343
+ if (tagName === 'script') {
344
+ const src = extractAttributeValue(rawAttrs, 'src');
345
+ if (src) {
346
+ const js = readBundledAsset(src);
347
+ if (js !== null) {
348
+ const closePos = rawHtml.toLowerCase().indexOf('</script>', gt + 1);
349
+ const scriptType = extractAttributeValue(rawAttrs, 'type');
350
+ const typeAttr = scriptType && scriptType.toLowerCase() === 'module' ? ' type="module"' : '';
351
+ outParts.push(`<script${typeAttr}>${escapeInlineTagClose(js, 'script')}</script>`);
352
+ cursor = closePos === -1 ? gt + 1 : closePos + '</script>'.length;
353
+ continue;
354
+ }
355
+ }
356
+ }
357
+
358
+ outParts.push(rawHtml.slice(lt, gt + 1));
359
+ cursor = gt + 1;
360
+ }
361
+
362
+ return { html: outParts.join(''), packedAssets, totalBytes };
363
+ }