@causyne/agent 1.10.21 → 1.12.0

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 (82) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +12 -0
  2. package/native-skills/media/professional-document-publishing/SKILL.md +44 -0
  3. package/native-skills/media/screenplay-and-shotlist-forge/SKILL.md +42 -0
  4. package/package.json +1 -1
  5. package/src/acp/client.js +235 -0
  6. package/src/acp/client.ts +282 -0
  7. package/src/acp/peerProfiles.js +122 -0
  8. package/src/acp/peerProfiles.ts +128 -0
  9. package/src/acp/protocol.js +55 -0
  10. package/src/acp/protocol.ts +456 -0
  11. package/src/acp/server.js +746 -0
  12. package/src/acp/server.ts +822 -0
  13. package/src/agentLoop.d.ts +64 -0
  14. package/src/agentLoop.js +156 -12
  15. package/src/approvalGrants.js +33 -0
  16. package/src/approvalGrants.ts +50 -0
  17. package/src/commands.js +203 -0
  18. package/src/compiledSkills.js +10 -0
  19. package/src/decisionPolicy.js +2 -0
  20. package/src/decisionPolicy.ts +1 -0
  21. package/src/documentEngine/antiSlopAuditor.js +156 -0
  22. package/src/documentEngine/antiSlopAuditor.ts +221 -0
  23. package/src/documentEngine/documentForge.js +443 -0
  24. package/src/documentEngine/documentForge.ts +519 -0
  25. package/src/documentEngine/screenplayFormatter.js +336 -0
  26. package/src/documentEngine/screenplayFormatter.ts +407 -0
  27. package/src/engines/cad.js +113 -0
  28. package/src/engines/cad.ts +128 -0
  29. package/src/engines/film.js +108 -0
  30. package/src/engines/film.ts +104 -0
  31. package/src/engines/installer.js +226 -0
  32. package/src/engines/installer.ts +248 -0
  33. package/src/engines/photo.js +126 -0
  34. package/src/engines/photo.ts +137 -0
  35. package/src/engines/registry.js +186 -0
  36. package/src/engines/registry.ts +185 -0
  37. package/src/engines/sound.js +117 -0
  38. package/src/engines/sound.ts +130 -0
  39. package/src/engines/types.js +1 -0
  40. package/src/engines/types.ts +73 -0
  41. package/src/entrypoint.js +13 -0
  42. package/src/execSafe.js +10 -13
  43. package/src/execSafe.ts +25 -0
  44. package/src/memoryManager.js +9 -3
  45. package/src/modelRouter.js +56 -123
  46. package/src/modelRouter.ts +134 -0
  47. package/src/observer/advisory.js +164 -0
  48. package/src/observer/advisory.ts +171 -0
  49. package/src/observer/coldObserver.js +462 -0
  50. package/src/observer/coldObserver.ts +540 -0
  51. package/src/observer/evidence.js +435 -0
  52. package/src/observer/evidence.ts +499 -0
  53. package/src/perception.js +303 -118
  54. package/src/perception.ts +387 -0
  55. package/src/procSignal.js +15 -16
  56. package/src/procSignal.ts +31 -0
  57. package/src/promptMentions.js +170 -0
  58. package/src/promptMentions.ts +212 -0
  59. package/src/sandbox.js +9 -1
  60. package/src/sessionJournal.js +12 -2
  61. package/src/sessionJournal.ts +12 -2
  62. package/src/textDiff.js +117 -109
  63. package/src/textDiff.ts +169 -0
  64. package/src/toolPacks.js +19 -8
  65. package/src/tools/documentForge.js +215 -0
  66. package/src/tools/documentForge.ts +265 -0
  67. package/src/tools/generateMediaViaApi.js +1 -1
  68. package/src/tools/nativeEngine.js +464 -0
  69. package/src/tools/nativeEngine.ts +433 -0
  70. package/src/tools/openSourceToolProvisioner.js +510 -0
  71. package/src/tools/openSourceToolProvisioner.ts +590 -0
  72. package/src/tools/peerAgent.js +102 -0
  73. package/src/tools/peerAgent.ts +116 -0
  74. package/src/tools/registry.js +6 -1
  75. package/src/tui/completion.js +98 -42
  76. package/src/tui/prompt.js +17 -17
  77. package/src/uncertainty.js +93 -205
  78. package/src/uncertainty.ts +255 -0
  79. package/src/utils/paths.js +15 -18
  80. package/src/utils/paths.ts +36 -0
  81. package/src/vfeTracker.js +122 -181
  82. package/src/vfeTracker.ts +242 -0
@@ -0,0 +1,169 @@
1
+ // A unified diff, in pure JavaScript / TypeScript.
2
+ //
3
+ // The git backend gets patches from git itself. This exists so the NATIVE
4
+ // backend — the fallback for a machine with no git, or a workspace that is not
5
+ // a repository — can answer the same question. Without it, REVIEW would show
6
+ // line counts on one machine and real changes on another, which is the kind of
7
+ // inconsistency that makes a feature feel broken rather than degraded.
8
+ //
9
+ // No dependency: this is a standard LCS over lines, which is what `diff -u`
10
+ // computes. Bounded, because a checkpoint diff is a UI affordance and must
11
+ // never become the reason a request times out.
12
+
13
+ /** Above this many lines on either side, fall back to counts without a patch. */
14
+ const MAX_DIFF_LINES = 4000;
15
+
16
+ /** Context lines around each change, matching `diff -u` and git's default. */
17
+ const CONTEXT = 3;
18
+
19
+ export interface UnifiedDiffResult {
20
+ patch: string;
21
+ additions: number;
22
+ deletions: number;
23
+ truncated: boolean;
24
+ }
25
+
26
+ /**
27
+ * Longest common subsequence over two line arrays.
28
+ *
29
+ * Classic dynamic programming. O(n*m) in time and memory, which is why
30
+ * MAX_DIFF_LINES exists — at the cap this is 16M cells, still well under a
31
+ * second, and anything larger is not something a human reads in a dialog.
32
+ */
33
+ function lcsTable(a: string[], b: string[]): Uint32Array[] {
34
+ const table: Uint32Array[] = [];
35
+ for (let i = 0; i <= a.length; i++) table.push(new Uint32Array(b.length + 1));
36
+ for (let i = a.length - 1; i >= 0; i--) {
37
+ const tableI = table[i]!;
38
+ const tableNext = table[i + 1]!;
39
+ for (let j = b.length - 1; j >= 0; j--) {
40
+ tableI[j] = a[i] === b[j]
41
+ ? tableNext[j + 1]! + 1
42
+ : Math.max(tableNext[j]!, tableI[j + 1]!);
43
+ }
44
+ }
45
+ return table;
46
+ }
47
+
48
+ type EditOp = [' ' | '-' | '+', string];
49
+
50
+ /** Walk the table into a flat edit script: ' ' keep, '-' remove, '+' add. */
51
+ function editScript(a: string[], b: string[]): EditOp[] {
52
+ const table = lcsTable(a, b);
53
+ const ops: EditOp[] = [];
54
+ let i = 0;
55
+ let j = 0;
56
+ while (i < a.length && j < b.length) {
57
+ if (a[i] === b[j]) {
58
+ ops.push([' ', a[i]!]);
59
+ i++;
60
+ j++;
61
+ } else if (table[i + 1]![j]! >= table[i]![j + 1]!) {
62
+ ops.push(['-', a[i]!]);
63
+ i++;
64
+ } else {
65
+ ops.push(['+', b[j]!]);
66
+ j++;
67
+ }
68
+ }
69
+ while (i < a.length) ops.push(['-', a[i++]!]);
70
+ while (j < b.length) ops.push(['+', b[j++]!]);
71
+ return ops;
72
+ }
73
+
74
+ function splitLines(text: string): string[] {
75
+ if (text === '') return [];
76
+ return text.replace(/\n$/, '').split('\n');
77
+ }
78
+
79
+ /**
80
+ * A unified diff of `before` → `after`.
81
+ */
82
+ export function unifiedDiff(before: string, after: string, pathLabel = 'file'): UnifiedDiffResult {
83
+ const a = splitLines(before);
84
+ const b = splitLines(after);
85
+
86
+ if (a.length > MAX_DIFF_LINES || b.length > MAX_DIFF_LINES) {
87
+ // Counting without the table keeps a huge file cheap: the exact per-line
88
+ // patch is not worth an O(n*m) allocation nobody will read.
89
+ return {
90
+ patch: '',
91
+ additions: b.length,
92
+ deletions: a.length,
93
+ truncated: true
94
+ };
95
+ }
96
+
97
+ const ops = editScript(a, b);
98
+ let additions = 0;
99
+ let deletions = 0;
100
+ for (const [kind] of ops) {
101
+ if (kind === '+') additions++;
102
+ else if (kind === '-') deletions++;
103
+ }
104
+ if (additions === 0 && deletions === 0) {
105
+ return { patch: '', additions: 0, deletions: 0, truncated: false };
106
+ }
107
+
108
+ // Group changes into hunks with CONTEXT lines of surrounding text, so the
109
+ // output is readable rather than the whole file with markers.
110
+ const lines = [`--- a/${pathLabel}`, `+++ b/${pathLabel}`];
111
+ let index = 0;
112
+ let oldLine = 1;
113
+ let newLine = 1;
114
+
115
+ while (index < ops.length) {
116
+ const opIndex = ops[index]!;
117
+ if (opIndex[0] === ' ') {
118
+ oldLine++;
119
+ newLine++;
120
+ index++;
121
+ continue;
122
+ }
123
+
124
+ // Walk back for leading context, then forward to the end of the change.
125
+ const start = Math.max(0, index - CONTEXT);
126
+ let end = index;
127
+ let quiet = 0;
128
+ while (end < ops.length && quiet <= CONTEXT * 2) {
129
+ quiet = ops[end]![0] === ' ' ? quiet + 1 : 0;
130
+ end++;
131
+ }
132
+ end = Math.min(ops.length, end);
133
+
134
+ let oldStart = oldLine;
135
+ let newStart = newLine;
136
+ for (let k = start; k < index; k++) {
137
+ if (ops[k]![0] !== '+') oldStart--;
138
+ if (ops[k]![0] !== '-') newStart--;
139
+ }
140
+
141
+ let oldCount = 0;
142
+ let newCount = 0;
143
+ const body: string[] = [];
144
+ for (let k = start; k < end; k++) {
145
+ const [kind, text] = ops[k]!;
146
+ if (kind !== '+') oldCount++;
147
+ if (kind !== '-') newCount++;
148
+ body.push(`${kind}${text}`);
149
+ }
150
+
151
+ lines.push(`@@ -${Math.max(1, oldStart)},${oldCount} +${Math.max(1, newStart)},${newCount} @@`);
152
+ lines.push(...body);
153
+
154
+ for (let k = index; k < end; k++) {
155
+ if (ops[k]![0] !== '+') oldLine++;
156
+ if (ops[k]![0] !== '-') newLine++;
157
+ }
158
+ index = end;
159
+ }
160
+
161
+ return { patch: lines.join('\n'), additions, deletions, truncated: false };
162
+ }
163
+
164
+ /** Binary content has no useful line diff — detected the way git detects it. */
165
+ export function looksBinary(buffer: Buffer | Uint8Array | null | undefined): boolean {
166
+ if (!buffer || buffer.length === 0) return false;
167
+ const sample = buffer.subarray(0, Math.min(8000, buffer.length));
168
+ return sample.includes(0);
169
+ }
package/src/toolPacks.js CHANGED
@@ -86,8 +86,11 @@ export const PACKS = {
86
86
  'manage_local_dependencies',
87
87
  'blender_act',
88
88
  'creative_apps',
89
+ 'native_engine',
89
90
  'resolve_act',
90
- 'palmier_act'
91
+ 'palmier_act',
92
+ 'document_forge',
93
+ 'open_source_tool_provisioner'
91
94
  ],
92
95
  system: [
93
96
  // Channel B of the Three-Channel Doctrine: reading the screen as structured
@@ -110,7 +113,9 @@ export const PACKS = {
110
113
  advanced: [
111
114
  'tool_forge',
112
115
  'plugin_manager',
116
+ 'document_forge',
113
117
  'agent_subagent_orchestrate',
118
+ 'peer_agent_delegate',
114
119
  'code_search_ast',
115
120
  'code_list_symbols',
116
121
  'pdf_read'
@@ -225,6 +230,10 @@ You MUST produce visually UNIQUE output on every project. Specifically:
225
230
  - **ENFORCED, NOT ADVISORY**: every HTML/CSS file you write is read back and scored by an automatic gate before the task can finish (src/slopDetector.js). It looks for the stock gradient hexes, purple-to-blue ramps, placeholder marketing copy, emoji used as icons, default-only typography, the centered-hero/3-cards/"Get Started" skeleton and the stock soft shadow. Score too high and you will be sent back to rebuild with a named design movement. Design it properly the first time; the gate is not fooled by swapping one gradient for another.`,
226
231
 
227
232
  media: `# Media Generation Protocol (Sovereign 5-Stage Hierarchy & Seamless Consent Routing)
233
+
234
+ ## Native engine-first for file media work
235
+ For editing or producing media from files in the workspace, check \`native_engine\` status first; engines are added one at a time, starting with film. If the engine is missing, explain the download and ask before calling \`install\` with \`confirm: true\`. When the needed engine is installed, use \`catalog\` -> \`execute\` or \`batch\`. Pass \`project\` to edit an existing document or \`saveAs\` for a new one, then \`render\` a preview and inspect it before exporting. Engines are headless: never use MCP servers, \`computer_use\`, or screenshots to drive them. The generation chain below applies only when no native engine capability exists or the user explicitly asks for generated media.
236
+
228
237
  When the user asks you to generate images, audio, music, video, or any creative media, you MUST navigate this exact 5-Stage priority chain:
229
238
 
230
239
  ## Stage 1: Specialized Paid APIs (Primary / Auto-Router)
@@ -235,12 +244,14 @@ Always attempt calling \`generate_media_via_api\` FIRST.
235
244
 
236
245
  ## Stage 2: Local AI Models / Binaries (Mode B & C — First Fallback)
237
246
  When Stage 1 is denied or unconfigured, you MUST evaluate local processing on the user's PC:
238
- 1. **Mandatory Gatekeeper**: Call \`check_system_specs\` FIRST right now to verify hardware.
239
- 2. **Eligibility & Action**: If RAM >= 8GB and Free Disk > 10GB, use \`manage_local_ai_dependencies\` (\`pipInst\` or \`fetchBin\`) + \`sysRun\` to run:
240
- - **Audio / Voice / Music**: Kokoro TTS, XTTS, MusicGen (\`pipInst\`), or Whisper (\`whisper.cpp\` / \`bark.cpp\`).
241
- - **Image / Art**: Stable Diffusion via \`diffusers\` or \`stable-diffusion.cpp\`.
242
- 3. **Download Consent**: Present exact model/binary size to the user before downloading multi-GB files.
243
- 4. **Seamless Denial Routing**: If \`check_system_specs\` shows RAM < 8GB OR the user denies multi-GB local downloads, immediately transition to Stage 3.
247
+ 1. **Mandatory Gatekeeper**: Call \`open_source_tool_provisioner\` (action: 'discover' or 'evaluate') or \`check_system_specs\` FIRST to verify hardware (RAM, CPU cores, GPU/Metal acceleration, disk space).
248
+ 2. **Eligibility & Action**: Use \`open_source_tool_provisioner\` to discover and inspect open-source tools matching user intent:
249
+ - **Voice Generation / Cloning**: F5-TTS, Kokoro-82M, XTTS-v2, Chatterbox (with exact RAM, compute, and disk size reported).
250
+ - **Audio / Transcription**: Whisper.cpp, Faster-Whisper.
251
+ - **Image / Restoration**: Real-ESRGAN, Rembg.
252
+ - **Local LLMs**: Ollama.
253
+ 3. **Mandatory HITL Consent**: \`open_source_tool_provisioner\` enforces Human-In-The-Loop approval (\`confirm: true\` or structured \`request_decision\`) before downloading or installing any model or package.
254
+ 4. **Seamless Denial Routing**: If hardware is insufficient OR the user denies local downloads, immediately transition to Stage 3.
244
255
 
245
256
  ## Stage 3: Free Cloud APIs / Pollinations.ai (Mode D — Second Fallback)
246
257
  When Stage 2 is impossible or denied, fall back to free cloud APIs via \`generate_media_via_api\` (\`provider: 'pollinations'\`).
@@ -370,7 +381,7 @@ const MEDIA_INTENT = /\b(image|images|picture|photo|gambar|render|3d model|blend
370
381
 
371
382
  const SYSTEM_INTENT = /\b(process|processes|pid|kill|port|zip|unzip|tar|archive|compress|extract|clipboard|copy to clipboard|print|printer|cetak|open in browser|launch app|computer use|vision grounding|desktop vision|gui agent|coordinate click|desktop control)\b/i;
372
383
 
373
- const ADVANCED_INTENT = /\b(pdf|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
384
+ const ADVANCED_INTENT = /\b(pdf|document|proposal|dokumen|screenplay|naskah|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
374
385
 
375
386
  const INTENT_MATCHERS = {
376
387
  game: GAME_INTENT,
@@ -0,0 +1,215 @@
1
+ /*
2
+ * Copyright (c) 2026 Causyne.
3
+ * SPDX-License-Identifier: BUSL-1.1
4
+ *
5
+ * Causyne Document Forge Tool Wrapper.
6
+ * Bridges HTML/CSS-first publishing, headless PDF compilation, visual page QA,
7
+ * anti-slop compliance auditing, and Hollywood screenplay & shot list generation.
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { compileDocumentHtml, renderHtmlToPdf, inspectPdfPages } from '../documentEngine/documentForge.js';
12
+ import { formatScreenplayHtml, formatShotListHtml, analyzeVoiceOverTiming } from '../documentEngine/screenplayFormatter.js';
13
+ import { auditTextContent, auditBudgetArithmetic } from '../documentEngine/antiSlopAuditor.js';
14
+ import { resolveUserPath } from '../utils/paths.js';
15
+ export const documentForgeTool = {
16
+ schema: {
17
+ name: 'document_forge',
18
+ description: 'Causyne Document Forge: Professional document & media production harness. Generates pixel-perfect A4/Letter publications via HTML/CSS-First Paged Media and Headless Chrome, renders vector PDFs (<2MB compliant), extracts page images for visual QA ("Lihat Hasilnya"), audits anti-slop and math integrity, formats Hollywood Courier 12pt screenplays, creates production shot lists, and times VO narration.',
19
+ parameters: {
20
+ type: 'object',
21
+ properties: {
22
+ action: {
23
+ type: 'string',
24
+ enum: [
25
+ 'compile_document',
26
+ 'render_pdf',
27
+ 'inspect_pages',
28
+ 'audit_text',
29
+ 'audit_budget',
30
+ 'format_screenplay',
31
+ 'format_shotlist',
32
+ 'analyze_vo'
33
+ ],
34
+ description: 'Action to execute.'
35
+ },
36
+ documentSpec: {
37
+ type: 'object',
38
+ properties: {
39
+ title: { type: 'string' },
40
+ subtitle: { type: 'string' },
41
+ categoryOrKicker: { type: 'string' },
42
+ authorOrProposer: { type: 'string' },
43
+ palette: { type: 'string', enum: ['corporate', 'editorial_dair', 'minimal_clean'] },
44
+ includeCover: { type: 'boolean' }
45
+ },
46
+ description: 'Formal publication spec with sections, tables, and palette (corporate, editorial_dair, minimal_clean).'
47
+ },
48
+ screenplaySpec: {
49
+ type: 'object',
50
+ properties: {
51
+ title: { type: 'string' },
52
+ author: { type: 'string' },
53
+ contact: { type: 'string' }
54
+ },
55
+ description: 'Hollywood screenplay spec with scene headings, action, characters, dialogue, and transitions.'
56
+ },
57
+ shotList: {
58
+ type: 'object',
59
+ properties: {
60
+ title: { type: 'string' },
61
+ shots: {
62
+ type: 'array',
63
+ items: {
64
+ type: 'object',
65
+ properties: {
66
+ shotNumber: { type: 'number' },
67
+ framing: { type: 'string' },
68
+ subject: { type: 'string' },
69
+ action: { type: 'string' },
70
+ durationSeconds: { type: 'number' }
71
+ }
72
+ }
73
+ }
74
+ },
75
+ description: 'Director production shot list with framing, lenses, camera movements, and audio cues.'
76
+ },
77
+ voBlocks: {
78
+ type: 'array',
79
+ items: {
80
+ type: 'object',
81
+ properties: {
82
+ id: { type: 'string' },
83
+ timecode: { type: 'string' },
84
+ text: { type: 'string' },
85
+ targetDurationSeconds: { type: 'number' }
86
+ }
87
+ },
88
+ description: 'Voiceover blocks with timecode and target durations for WPM pacing analysis.'
89
+ },
90
+ budgetSpec: {
91
+ type: 'object',
92
+ properties: {
93
+ grossUpTaxRate: { type: 'number' },
94
+ targetGross: { type: 'number' }
95
+ },
96
+ description: 'Budget specification for arithmetic validation and tax gross-up verification.'
97
+ },
98
+ textContent: {
99
+ type: 'string',
100
+ description: 'Raw text or HTML content to audit for AI tropes, long em-dashes, and placeholder brackets.'
101
+ },
102
+ sourceHtmlPath: {
103
+ type: 'string',
104
+ description: 'Path to HTML file to render into PDF via Headless Chrome.'
105
+ },
106
+ outputPdfPath: {
107
+ type: 'string',
108
+ description: 'Destination PDF file path.'
109
+ },
110
+ outputPath: {
111
+ type: 'string',
112
+ description: 'Destination HTML or JSON output file path.'
113
+ },
114
+ inspectImagesDir: {
115
+ type: 'string',
116
+ description: 'Directory to save extracted page images for visual inspection.'
117
+ }
118
+ }
119
+ }
120
+ },
121
+ async execute(args = {}, _context = {}) {
122
+ const action = args.action || 'compile_document';
123
+ switch (action) {
124
+ case 'compile_document': {
125
+ if (!args.documentSpec) {
126
+ return { success: false, error: 'compile_document requires documentSpec.' };
127
+ }
128
+ const compiled = compileDocumentHtml(args.documentSpec);
129
+ if (args.outputPath) {
130
+ const target = resolveUserPath(args.outputPath);
131
+ fs.mkdirSync(path.dirname(target), { recursive: true });
132
+ fs.writeFileSync(target, compiled.html, 'utf8');
133
+ }
134
+ return {
135
+ success: true,
136
+ html: compiled.html,
137
+ outputPath: args.outputPath ? resolveUserPath(args.outputPath) : undefined
138
+ };
139
+ }
140
+ case 'render_pdf': {
141
+ if (!args.sourceHtmlPath || !args.outputPdfPath) {
142
+ return { success: false, error: 'render_pdf requires sourceHtmlPath and outputPdfPath.' };
143
+ }
144
+ const src = resolveUserPath(args.sourceHtmlPath);
145
+ const out = resolveUserPath(args.outputPdfPath);
146
+ const res = await renderHtmlToPdf(src, out);
147
+ return res;
148
+ }
149
+ case 'inspect_pages': {
150
+ if (!args.outputPdfPath) {
151
+ return { success: false, error: 'inspect_pages requires outputPdfPath.' };
152
+ }
153
+ const pdf = resolveUserPath(args.outputPdfPath);
154
+ const imgDir = args.inspectImagesDir ? resolveUserPath(args.inspectImagesDir) : undefined;
155
+ const res = await inspectPdfPages(pdf, imgDir);
156
+ return res;
157
+ }
158
+ case 'audit_text': {
159
+ if (!args.textContent) {
160
+ return { success: false, error: 'audit_text requires textContent parameter.' };
161
+ }
162
+ const res = auditTextContent(args.textContent);
163
+ return { success: true, ...res };
164
+ }
165
+ case 'audit_budget': {
166
+ if (!args.budgetSpec) {
167
+ return { success: false, error: 'audit_budget requires budgetSpec parameter.' };
168
+ }
169
+ const res = auditBudgetArithmetic(args.budgetSpec);
170
+ return { success: true, ...res };
171
+ }
172
+ case 'format_screenplay': {
173
+ if (!args.screenplaySpec) {
174
+ return { success: false, error: 'format_screenplay requires screenplaySpec.' };
175
+ }
176
+ const formatted = formatScreenplayHtml(args.screenplaySpec);
177
+ if (args.outputPath) {
178
+ const target = resolveUserPath(args.outputPath);
179
+ fs.mkdirSync(path.dirname(target), { recursive: true });
180
+ fs.writeFileSync(target, formatted.html, 'utf8');
181
+ }
182
+ return {
183
+ success: true,
184
+ html: formatted.html,
185
+ outputPath: args.outputPath ? resolveUserPath(args.outputPath) : undefined
186
+ };
187
+ }
188
+ case 'format_shotlist': {
189
+ if (!args.shotList) {
190
+ return { success: false, error: 'format_shotlist requires shotList parameter.' };
191
+ }
192
+ const formatted = formatShotListHtml(args.shotList.title, args.shotList.shots);
193
+ if (args.outputPath) {
194
+ const target = resolveUserPath(args.outputPath);
195
+ fs.mkdirSync(path.dirname(target), { recursive: true });
196
+ fs.writeFileSync(target, formatted.html, 'utf8');
197
+ }
198
+ return {
199
+ success: true,
200
+ html: formatted.html,
201
+ outputPath: args.outputPath ? resolveUserPath(args.outputPath) : undefined
202
+ };
203
+ }
204
+ case 'analyze_vo': {
205
+ if (!args.voBlocks || !Array.isArray(args.voBlocks)) {
206
+ return { success: false, error: 'analyze_vo requires voBlocks array.' };
207
+ }
208
+ const res = analyzeVoiceOverTiming(args.voBlocks);
209
+ return { success: true, analysis: res };
210
+ }
211
+ default:
212
+ return { success: false, error: `Unsupported document_forge action: ${action}` };
213
+ }
214
+ }
215
+ };