@office-kit/pptx-dev 0.7.0 → 0.8.2
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.
- package/README.md +46 -17
- package/dist/cli.mjs +324 -88
- package/dist/cli.mjs.map +1 -1
- package/dist/terminal-client.js +16 -16
- package/package.json +4 -4
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/text-edit.ts","../src/visual-review.ts","../src/styles.ts","../src/page.ts","../src/agent-page.ts","../src/authoring-guidance.ts","../src/terminal.ts","../src/chat.ts","../src/server.ts","../src/cli.ts"],"sourcesContent":["import ts from 'typescript';\nimport { readFile, writeFile, realpath } from 'node:fs/promises';\nimport { dirname, relative, isAbsolute, extname } from 'node:path';\n\ninterface Preview {\n revision: number;\n slides: string[];\n slideTexts: string[];\n dependencies: string[];\n}\ninterface Change {\n file: string;\n before: string;\n after: string;\n}\n\n/** Literal edits are deliberately conservative: computed and ambiguous text goes to the agent. */\nexport function createTextEditor(\n entry: string,\n preview: () => Preview,\n verify: () => Promise<string | null>,\n) {\n let busy = false;\n let undo: Change | undefined;\n async function restore(change: Change) {\n if (\n (await realpath(change.file)) !== change.file ||\n (await readFile(change.file, 'utf8')) !== change.after\n )\n throw new Error('Source changed during editing. Your newer changes were preserved.');\n await writeFile(change.file, change.before);\n }\n return {\n async edit(value: { revision: number; slide: number; before: string; after: string }) {\n if (busy) throw new Error('A text edit is already running.');\n busy = true;\n try {\n const current = preview();\n if (value.revision !== current.revision)\n throw new Error('Preview changed. Select the text again.');\n if (\n !Number.isInteger(value.slide) ||\n !current.slides[value.slide] ||\n typeof value.before !== 'string' ||\n !value.before.trim() ||\n value.before.length > 12000 ||\n typeof value.after !== 'string' ||\n value.after.length > 12000 ||\n value.after === value.before\n )\n throw new Error('Invalid text edit.');\n if (current.slideTexts[value.slide]!.split(value.before).length !== 2)\n throw new Error('Text cannot be located uniquely on this slide. Use Apply with AI.');\n const root = await realpath(dirname(entry));\n const files = await Promise.all(\n [...new Set(current.dependencies)]\n .filter((file) => /\\.[cm]?[jt]sx?$/.test(file))\n .map(async (file) => {\n const path = await realpath(file),\n local = relative(root, path);\n if (\n local.startsWith('..') ||\n isAbsolute(local) ||\n local.split(/[\\\\/]/).includes('node_modules')\n )\n return null;\n return { file: path, before: await readFile(path, 'utf8') };\n }),\n );\n const candidates: Change[] = [];\n for (const item of files) {\n if (!item) continue;\n const source = ts.createSourceFile(\n item.file,\n item.before,\n ts.ScriptTarget.Latest,\n true,\n /[jt]sx$/.test(extname(item.file)) ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n const visit = (node: ts.Node) => {\n const text = ts.isJsxText(node)\n ? node.text\n .split(/\\r\\n|\\n|\\r/)\n .map((line, index, lines) => {\n let value = line.replaceAll('\\t', ' ');\n if (index) value = value.trimStart();\n if (index < lines.length - 1) value = value.trimEnd();\n return value;\n })\n .filter(Boolean)\n .join(' ')\n : ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)\n ? node.text\n : undefined;\n if (text === value.before) {\n // Attribute strings use JSX entity rules, not JavaScript string escapes.\n const jsx = ts.isJsxText(node) || ts.isJsxAttribute(node.parent);\n const replacement = jsx\n ? '{' + JSON.stringify(value.after) + '}'\n : JSON.stringify(value.after);\n const start = ts.isJsxText(node) ? node.pos : node.getStart(source);\n candidates.push({\n ...item,\n after: item.before.slice(0, start) + replacement + item.before.slice(node.end),\n });\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n }\n if (candidates.length !== 1)\n throw new Error('Text is computed or has multiple source matches. Use Apply with AI.');\n const change = candidates[0]!;\n if (\n preview().revision !== current.revision ||\n (await realpath(change.file)) !== change.file ||\n (await readFile(change.file, 'utf8')) !== change.before\n )\n throw new Error('Source changed. Select the text again.');\n await writeFile(change.file, change.after);\n try {\n const error = await verify();\n if (error) throw new Error('The text change did not build.');\n const next = preview();\n if (\n next.slides.length !== current.slides.length ||\n next.slides.some(\n (svg, index) => index !== value.slide && svg !== current.slides[index],\n ) ||\n next.slideTexts[value.slide] !==\n current.slideTexts[value.slide]!.replace(value.before, value.after)\n )\n throw new Error(\n 'This source affects other text or slides. Use Apply with AI for a local edit.',\n );\n if (\n (await realpath(change.file)) !== change.file ||\n (await readFile(change.file, 'utf8')) !== change.after\n )\n throw new Error('Source changed during editing.');\n undo = change;\n } catch (error) {\n await restore(change);\n await verify();\n throw error;\n }\n } finally {\n busy = false;\n }\n },\n async undo() {\n if (busy) throw new Error('A text edit is already running.');\n if (!undo) throw new Error('No direct text edit to undo.');\n busy = true;\n try {\n await restore(undo);\n undo = undefined;\n const error = await verify();\n if (error) throw new Error('Text restored, but the project has build errors.');\n } finally {\n busy = false;\n }\n },\n };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { chromium, type Browser } from 'playwright';\n\nexport interface VisualReview {\n prompt: string;\n images: string[];\n}\n/** Each session compares against its own turn's preview, including offscreen slides. */\nexport function createVisualReviewer(entry: string, slides: () => string[]) {\n let before: string[] = [];\n let rounds = 0;\n return {\n begin() {\n before = slides().slice();\n rounds = 0;\n },\n async next(): Promise<VisualReview | undefined> {\n const current = slides().slice();\n const changed = current.flatMap((svg, index) =>\n svg !== before[index] ? [{ svg, index }] : [],\n );\n if (!changed.length) return;\n if (rounds >= 3)\n throw new Error(\n 'Visual review reached its correction limit. Review the latest slide manually before continuing.',\n );\n const round = rounds + 1;\n let browser: Browser;\n try {\n browser = await chromium.launch({\n channel: process.env.PLAYWRIGHT_CHANNEL || 'chrome',\n headless: true,\n });\n } catch {\n try {\n browser = await chromium.launch({ headless: true });\n } catch {\n throw new Error(\n 'Visual review needs Chrome or a Playwright Chromium installation. Install Chrome and retry. The source edit was saved; visual review was not completed.',\n );\n }\n }\n try {\n const directory = join(dirname(entry), '.office-kit', 'reviews', randomUUID());\n await mkdir(directory, { recursive: true });\n const page = await browser.newPage({\n viewport: { width: 1600, height: 1000 },\n deviceScaleFactor: 1,\n });\n // Decks may reference remote assets. Review must not make network requests or execute SVG scripts.\n await page.route('**/*', (route) => route.abort());\n const images: string[] = [];\n for (const { svg, index } of changed) {\n await page.setContent(\n '<meta http-equiv=\"Content-Security-Policy\" content=\"default-src \\'none\\'; style-src \\'unsafe-inline\\'; img-src data: blob:; font-src data:\"><style>html,body{margin:0}svg{display:block;width:1600px;height:auto}</style>' +\n svg,\n );\n await page.evaluate(() => document.fonts.ready.then(() => undefined));\n const file = join(directory, `slide-${index + 1}.png`);\n await page.locator('svg').first().screenshot({ path: file, timeout: 15000 });\n images.push(file);\n }\n const prompt = `Visual review after the edit (round ${round}/3). Open every attached screenshot (or read each local PNG path below) before finishing. Check clipping, overlap, alignment, spacing, legibility and foreground/background contrast. ${round === 3 ? 'This is the final review: do not edit further; report any remaining defects to the user.' : 'Fix concrete design defects only on these affected slides;'} preserve the user's exact text and unrelated work. Do not claim visual verification unless you inspected the images. If there are no defects, finish without edits. Screenshots: ${JSON.stringify(images)}`;\n await writeFile(join(directory, 'review.txt'), prompt);\n before = current;\n rounds = round;\n return { prompt, images };\n } finally {\n await browser.close();\n }\n },\n };\n}\n","export const previewStyles = `*{box-sizing:border-box}\nbody{margin:0;height:100dvh;overflow:hidden;background:#e9eaf4;color:#dce1f1;font:13px system-ui;display:grid;grid-template-rows:60px minmax(0,1fr) 42px}\nbutton,a,select{font:inherit;color:inherit}button,select,.download{border:1px solid #30364d;border-radius:9px;background:#191e30;padding:7px 12px;text-decoration:none;cursor:pointer}\nbutton:hover:not(:disabled),.download:hover{background:#292f48}button:disabled{opacity:.4;cursor:default}\n:focus-visible{outline:2px solid #9b87ff;outline-offset:3px}\nheader{display:flex;align-items:center;gap:16px;padding:0 20px;background:linear-gradient(110deg,#171b2f,#211c38 60%,#171b2f);border-bottom:1px solid #38304d;min-width:0}\n.brand{font-weight:700;font-size:17px;white-space:nowrap}.badge{font-size:11px;color:#b2a4fb;background:#342c54;border-radius:4px;padding:3px 6px}\n#status{flex:1;color:#9ba5be;min-width:0}#present{background:#7154e8;color:#191e30;border-color:#7154e8}\n.workspace{--filmstrip-width:190px;--chat-width:38vw;display:grid;grid-template-columns:var(--filmstrip-width) minmax(0,1fr) clamp(280px,var(--chat-width),calc(100vw - var(--filmstrip-width) - 240px));min-height:0}\n.filmstrip{background:#111625;border-right:1px solid #30364d;overflow:auto;overscroll-behavior:contain;padding:16px 12px}\n.filmstrip h2{margin:0 0 12px 26px;text-transform:uppercase;letter-spacing:.1em;font-size:10px;color:#8490ac;font-weight:600}\n#thumbnails{display:flex;flex-direction:column;gap:12px;margin:0;padding:0;list-style:none}\n.thumbnail{display:flex;align-items:flex-start;gap:8px;width:100%;padding:4px 3px;border:0;background:transparent;border-radius:5px;text-align:left}\n.slide-number{width:18px;flex:none;text-align:right;font-size:11px;color:#8995b0;padding-top:5px}\n.thumbnail img{display:block;min-width:0;width:calc(100% - 26px);background:white;box-shadow:0 1px 4px #080b1933;border:2px solid transparent;border-radius:3px;aspect-ratio:var(--slide-ratio,16/9);object-fit:contain}\n.thumbnail[aria-current=\"true\"]{background:#31274e}.thumbnail[aria-current=\"true\"] img{border-color:#9b87ff}.thumbnail[aria-current=\"true\"] .slide-number{color:#b6a5ff;font-weight:700}\nmain{min-width:0;min-height:0;display:flex;flex-direction:column}\n#error{flex:none;max-height:30%;overflow:auto;background:#fff0ef;color:#922e25;margin:0;padding:16px 20px;white-space:pre-wrap;border-bottom:1px solid #e8bbb7}\n#error[hidden]{display:none}\n#stage{background:radial-gradient(ellipse at 20% 15%,#ddd8f6aa,transparent 65%),radial-gradient(#a0a4bf33 1px,transparent 1px),#edeef6;background-size:auto,18px 18px,auto;flex:1;min-height:0;overflow:auto;display:flex;padding:32px;overscroll-behavior:contain}\n#slide{position:relative;flex:none;margin:auto;background:white;box-shadow:0 20px 70px #28234825,0 2px 8px #28234815;overflow:hidden}\n#slide{user-select:text;-webkit-user-select:text}\n#empty{margin:auto;color:#8995b0}\nfooter{display:flex;align-items:center;gap:14px;padding:0 16px;background:#191e30;border-top:1px solid #30364d;font-size:12px}\n#count{min-width:90px}footer .hint{flex:1;color:#8995b0}footer button{padding:3px 10px}footer select{padding:3px 8px}\n#presentation-controls{display:none}\nbody.presenting{grid-template-rows:minmax(0,1fr);background:#111}\n.presenting header,.presenting footer,.presenting .filmstrip,.presenting #chat{display:none}\n.presenting .workspace{grid-template-columns:minmax(0,1fr)}.presenting #stage{padding:0;background:#111}.presenting #slide{box-shadow:none}\n.presenting #presentation-controls{display:flex;position:fixed;bottom:16px;left:50%;transform:translateX(-50%);align-items:center;gap:12px;background:#202735e8;color:white;padding:6px;border-radius:8px;opacity:0;transition:opacity .15s}\n.presenting #presentation-controls:hover,.presenting #presentation-controls:focus-within{opacity:1}\n#presentation-controls button{background:transparent;color:white;border-color:#5d6575}\n@media(max-width:700px){.workspace{grid-template-columns:140px minmax(0,1fr)}.filmstrip{padding:12px 5px}header{padding:0 12px;gap:10px}.badge,footer .hint{display:none}#stage{padding:16px}footer{gap:8px}#status{font-size:11px}.download{padding:7px 8px}}\n#chat{position:relative;min-width:0;min-height:0;display:flex;flex-direction:column;background:#191e30;border-left:1px solid #30364d}\n#chat-resizer{position:absolute;left:-5px;top:0;bottom:0;width:10px;z-index:3;cursor:col-resize;touch-action:none}#chat-resizer::after{content:\"\";position:absolute;left:4px;top:0;bottom:0;width:2px}#chat-resizer:hover::after,#chat-resizer:focus-visible::after,.resizing-chat #chat-resizer::after{background:#9b87ff}body.resizing-chat,body.resizing-chat *{cursor:col-resize!important;user-select:none!important}\n.chat-heading{display:flex;align-items:center;gap:8px;padding:16px;border-bottom:1px solid #2a3046}.chat-heading strong{flex:1}.chat-heading button{padding:5px 8px}\n#messages{flex:1;overflow:auto;padding:16px;display:flex;flex-direction:column;gap:16px;overscroll-behavior:contain}\n.chat-message{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}.chat-message.user{background:#302752;border-radius:8px;padding:10px 12px}.chat-message small{display:block;color:#a4afc6;font-size:11px;margin-bottom:4px}.chat-intro{color:#8995b0;line-height:1.7}\n#chat-form{padding:14px;border-top:1px solid #2a3046}#chat-context{font-size:11px;color:#9b87ff;margin-bottom:8px}#chat-input{font:inherit;resize:vertical;min-height:90px;max-height:200px;width:100%;padding:10px;border:1px solid #30364d;border-radius:8px} .chat-actions{display:flex;gap:8px;margin-top:8px;align-items:center}.chat-actions select{min-width:0;flex:1}#chat-send{background:#7154e8;color:white}#chat-status{padding:0 14px 12px;color:#9ba5be;font-size:11px;white-space:pre-wrap;max-height:90px;overflow:auto}\nbody.chat-hidden .workspace{grid-template-columns:190px minmax(0,1fr)}body.chat-hidden #chat{display:none}\nbody.presenting .workspace{grid-template-columns:minmax(0,1fr)}\n@media(max-width:1000px){.workspace{--filmstrip-width:120px;--chat-width:380px}.filmstrip{padding:12px 5px}#stage{padding:16px}}\n@media(max-width:700px){#chat-resizer{display:none}.workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(160px,1fr) minmax(200px,1fr)}.filmstrip{display:none}#chat{border-top:1px solid #30364d}.chat-heading{padding:8px 12px}#chat-form{padding:8px 12px}#chat-input{min-height:50px}body.chat-hidden .workspace,.presenting .workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}.brand{font-size:14px}header{gap:6px}.download{font-size:11px}}\n@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}\n\n[hidden]{display:none!important}\n.chat-heading{padding:10px 14px}.chat-heading select{flex:1;min-width:0;font-weight:600;border:0;padding-left:0}\n#chat-context{margin:0;padding:8px 14px;border-bottom:1px solid #2a3046;color:#9ba5be;font-size:11px}\n#claude-panel,#codex-panel{display:flex;flex-direction:column;flex:1;min-height:0}\n#claude-panel{background:#171b24;color:#e4e8f0}\n.terminal-toolbar{display:flex;align-items:center;gap:8px;padding:8px 12px;font-size:11px;min-height:40px}.terminal-toolbar span{flex:1;overflow-wrap:anywhere}.terminal-toolbar button{font-size:11px;padding:5px 8px;background:#262d3b;border-color:#45516a;color:#e4e8f0}\n.terminal-toolbar button:hover:not(:disabled){background:#35415a}\n#terminal{flex:1;min-height:0;overflow:hidden;padding:0}.xterm{height:100%}\n#chat-input{min-height:70px;resize:vertical}.chat-shortcut{flex:1;color:#9098a7;font-size:10px}\n.markdown{white-space:normal;line-height:1.65}.markdown>:first-child{margin-top:0}.markdown>:last-child{margin-bottom:0}.markdown p{margin:0 0 .8em}.markdown pre{overflow:auto;padding:10px;background:#22283b;border:1px solid #2a3046;border-radius:6px;white-space:pre}.markdown code{font-size:.9em;background:#22283b;border-radius:3px;padding:1px 4px}.markdown pre code{padding:0}.markdown ul,.markdown ol{padding-left:22px}.markdown blockquote{margin-left:0;padding-left:12px;border-left:3px solid #30364d;color:#9ba5be}.markdown table{display:block;overflow:auto;border-collapse:collapse}.markdown th,.markdown td{padding:6px 8px;border:1px solid #30364d}.markdown h1,.markdown h2,.markdown h3{font-size:1.1em}.markdown a{color:#b6a5ff;text-decoration:underline}\n\n.brand{display:flex;align-items:center;gap:10px;letter-spacing:-.5px}.brand svg{width:32px;height:32px;flex:none}.brand em{font-style:normal;font-weight:400;color:#aca4ce}.badge{text-transform:uppercase;letter-spacing:.14em;font-size:9px;border:1px solid #61508866;border-radius:5px}#status{font-size:11px}#present,#chat-send{color:#fff;background:linear-gradient(120deg,#8061ed,#634de0);border-color:#a38aef55;box-shadow:0 3px 15px #7455e82a}#toggle-chat[aria-expanded=\"true\"]{background:#35294f;border-color:#6f528b;color:#d6c5ff}.download{background:transparent;color:#bcc5dc}header button,header .download{font-size:12px}.filmstrip{background:linear-gradient(180deg,#161b2c,#111625)}.thumbnail{transition:background .15s}.thumbnail[aria-current=\"true\"]{box-shadow:inset 0 0 0 1px #9980ef33}.thumbnail[aria-current=\"true\"] img{box-shadow:0 0 16px #9567ed22}footer{background:#141929;color:#b9c2d8}footer .hint{font-size:10px}#count{font-size:11px;font-weight:600}#chat{background:#101422}.workspace-heading{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;color:#c7bee5;font-size:10px;font-weight:600;letter-spacing:.12em}.workspace-heading b{font-size:9px;color:#89cdbc;font-weight:500;letter-spacing:.08em}.workspace-heading b::before{content:\"\";display:inline-block;width:5px;height:5px;background:#86d5bb;border-radius:50%;margin-right:6px;box-shadow:0 0 8px #86d5bb66}.chat-heading{background:#191e30}.chat-heading select{background:transparent;color:#e4e5f3;font-size:12px}.chat-heading option{background:#191e30}#chat-context{background:#1a1e30;color:#a59abb;font-size:10px}.terminal-toolbar{gap:6px;padding:8px;font-size:10px}.terminal-toolbar button{white-space:nowrap}#terminal-start{background:#6c52c9;border-color:#9678e9}.terminal-frame{display:flex;flex:1;min-height:0;min-width:0;padding:4px 8px 8px;overflow:hidden}#terminal{width:100%;min-width:0}#chat-input{color:#e2e5f3;background:#131827;border-color:#3b3f58}#chat-input:focus{outline:none;border-color:#9b87ff;box-shadow:0 0 0 3px #9b87ff18}.chat-message.user{border:1px solid #67509655}.chat-intro{font-size:12px}.markdown pre{border-color:#3a4059}.markdown code{color:#d2c6fa}#error{background:#38242b;color:#ffb8b0}\n@media(max-width:700px){.brand svg{width:26px;height:26px}.brand{gap:6px}.workspace-heading{padding:7px 12px}header .download{font-size:10px;padding:7px}.badge{display:none}}\n`;\n","import { previewStyles } from './styles.ts';\nexport const page = `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\">\n<title>Office Kit — PowerPoint preview</title>\n<link rel=\"stylesheet\" href=\"/terminal.css\">\n<style>\n${previewStyles}\n.slide-edit-tools{display:flex;gap:6px;padding:8px 14px;flex-shrink:0}.slide-edit-tools button[aria-pressed=true]{background:#6850b8;border-color:#b8a1ff}.slide-selection{position:fixed;border:2px solid #b094ff;background:#a080ff18;pointer-events:none;z-index:20;box-shadow:0 0 0 1px #201632}.slide-edit-panel{position:fixed;z-index:21;width:min(380px,calc(100vw - 16px));padding:14px;background:#202438;border:1px solid #776591;border-radius:14px;box-shadow:0 16px 50px #0008;display:flex;flex-direction:column;gap:12px}.slide-edit-panel[hidden],.slide-selection[hidden]{display:none}.selection-heading,.selection-actions{display:flex;align-items:center;gap:8px}.selection-heading strong{flex:1}.slide-edit-panel textarea{width:100%;min-height:90px;max-height:35vh;resize:vertical;background:#141a2b;color:#f4efff;border:1px solid #514969;border-radius:8px;padding:10px;font:inherit}.selection-actions{flex-wrap:wrap}.selection-actions select{min-width:80px;flex:1}.slide-edit-panel small{color:#d1c9e3;line-height:1.5}.presenting .slide-edit-tools{display:none}\n\n#agent-workspace{position:relative;flex:1;min-height:0;min-width:0;display:flex;overflow:auto}.agent-pane{position:absolute;padding:3px 5px;display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}.agent-pane iframe{border:0;width:100%;flex:1;min-height:0;border-radius:0 0 9px 9px}.agent-tools{display:flex;gap:4px;align-items:center;flex-wrap:wrap;padding:6px;background:#20253a;border:1px solid #34334e;border-radius:9px 9px 0 0}.agent-tools span{flex:1;font-size:10px;letter-spacing:.04em;color:#b3abc9}.agent-tools svg{width:14px;height:14px}.agent-pane:focus-within .agent-tools{border-color:#8b6ed577;background:#29243e}.agent-tools button{font-size:11px;padding:5px;background:transparent;border:0;display:grid;place-items:center}.agent-divider{position:absolute;z-index:2;background:#101422;cursor:col-resize;touch-action:none}.agent-divider.vertical{cursor:row-resize}.agent-divider:hover,.agent-divider:focus-visible{background:#9b87ff}.splitting-agents iframe,.resizing-chat iframe{pointer-events:none}\n</style>\n<header><span class=\"brand\"><svg viewBox=\"0 0 36 36\" aria-hidden=\"true\"><defs><linearGradient id=\"brand-gradient\" x2=\"1\" y2=\"1\"><stop stop-color=\"#c39aff\"/><stop offset=\"1\" stop-color=\"#7165f4\"/></linearGradient></defs><rect x=\"2\" y=\"2\" width=\"32\" height=\"32\" rx=\"10\" fill=\"url(#brand-gradient)\"/><path d=\"M11 10h9l6 6v10H11z\" fill=\"none\" stroke=\"white\" stroke-width=\"1.8\" stroke-linejoin=\"round\"/><path d=\"M20 10v7h6M15 21h7M15 25h4\" fill=\"none\" stroke=\"white\" stroke-width=\"1.8\" stroke-linecap=\"round\"/><path d=\"m28 3 1.2 3.8L33 8l-3.8 1.2L28 13l-1.2-3.8L23 8l3.8-1.2z\" fill=\"#e7dbff\"/></svg>Office <em>Kit</em></span><span class=\"badge\">Studio</span><span id=\"status\" role=\"status\">Building…</span><button id=\"toggle-chat\" aria-expanded=\"true\" aria-controls=\"chat\">✦ Agents</button><button id=\"present\" disabled>Present</button><a class=\"download\" href=\"/deck.pptx\">Download PPTX</a></header>\n<div class=\"workspace\">\n<nav class=\"filmstrip\" aria-label=\"Slides\"><h2>Slides</h2><ol id=\"thumbnails\"></ol></nav>\n<main aria-label=\"Slide viewer\"><pre id=\"error\" role=\"alert\" hidden></pre><div id=\"stage\" tabindex=\"-1\"><div id=\"empty\">Waiting for slides…</div><div id=\"slide\" hidden></div></div></main>\n<aside id=\"chat\" aria-label=\"Slide chat\">\n<div id=\"chat-resizer\" role=\"separator\" tabindex=\"0\" aria-label=\"Chat width\" aria-orientation=\"vertical\" aria-controls=\"chat\" title=\"Drag to resize · Double-click to reset\"></div>\n<div class=\"workspace-heading\"><span>✦ AI WORKSPACE</span><b>LOCAL</b></div><div id=\"agent-workspace\"></div><div id=\"chat-context\" hidden></div></aside>\n</div>\n<footer><span id=\"count\" aria-live=\"polite\">No slides</span><span class=\"hint\">Select an area to ask AI · Edit text directly</span><button id=\"prev\" aria-label=\"Previous slide\" disabled>‹</button><button id=\"next\" aria-label=\"Next slide\" disabled>›</button><label for=\"zoom\">Zoom</label><select id=\"zoom\"><option value=\"fit\">Fit</option><option value=\"0.5\">50%</option><option value=\"0.75\">75%</option><option value=\"1\">100%</option><option value=\"1.25\">125%</option><option value=\"1.5\">150%</option><option value=\"2\">200%</option></select></footer>\n<div id=\"presentation-controls\"><button id=\"present-prev\" aria-label=\"Previous slide\">‹</button><span id=\"present-count\"></span><button id=\"present-next\" aria-label=\"Next slide\">›</button><button id=\"exit-present\">Exit · Esc</button></div>\n<script>\nlet state={slides:[],error:null,aspectRatio:16/9},index=0,urls=[],presenting=false;\nlet displayedSvg;\nconst byId=id=>document.getElementById(id);\nconst stage=byId('stage'),slide=byId('slide'),thumbnails=byId('thumbnails');\nconst workspace=document.querySelector('.workspace'),chatResizer=byId('chat-resizer');\nconst chatWidthKey='office-kit-chat-width',minChatWidth=280,minStageWidth=240;\nfunction chatWidthLimits(){return {min:minChatWidth,max:Math.max(minChatWidth,workspace.clientWidth-document.querySelector('.filmstrip').getBoundingClientRect().width-minStageWidth)};}\nfunction updateChatWidthAria(){\n const {min,max}=chatWidthLimits();\n chatResizer.setAttribute('aria-valuemin',String(min));chatResizer.setAttribute('aria-valuemax',String(Math.round(max)));\n const width=Math.round(byId('chat').getBoundingClientRect().width);\n chatResizer.setAttribute('aria-valuenow',String(width));chatResizer.setAttribute('aria-valuetext',width+' pixels');\n}\nfunction setChatWidth(width){const {min,max}=chatWidthLimits();workspace.style.setProperty('--chat-width',Math.min(max,Math.max(min,width))+'px');}\nfunction saveChatWidth(){try{const width=workspace.style.getPropertyValue('--chat-width');if(width)localStorage.setItem(chatWidthKey,String(parseFloat(width)));else localStorage.removeItem(chatWidthKey);}catch(error){console.warn('Could not save chat width',error);}}\ntry{const saved=Number(localStorage.getItem(chatWidthKey));if(Number.isFinite(saved)&&saved>=minChatWidth)workspace.style.setProperty('--chat-width',saved+'px');}catch(error){console.warn('Could not restore chat width',error);}\nlet chatDrag=null;\nchatResizer.onpointerdown=event=>{\n if(event.button!==0||!event.isPrimary)return;\n event.preventDefault();chatResizer.focus();chatDrag={id:event.pointerId,x:event.clientX,width:byId('chat').getBoundingClientRect().width};\n chatResizer.setPointerCapture(event.pointerId);document.body.classList.add('resizing-chat');\n};\nchatResizer.onpointermove=event=>{if(chatDrag?.id===event.pointerId)setChatWidth(chatDrag.width+chatDrag.x-event.clientX);};\nfunction finishChatResize(){if(!chatDrag)return;chatDrag=null;document.body.classList.remove('resizing-chat');saveChatWidth();}\nchatResizer.onpointerup=finishChatResize;chatResizer.onpointercancel=finishChatResize;chatResizer.onlostpointercapture=finishChatResize;\nchatResizer.ondblclick=()=>{workspace.style.removeProperty('--chat-width');saveChatWidth();};\nchatResizer.onkeydown=event=>{\n const {min,max}=chatWidthLimits(),width=byId('chat').getBoundingClientRect().width,step=event.shiftKey?50:10;\n let next;\n if(event.key==='ArrowLeft')next=width+step;else if(event.key==='ArrowRight')next=width-step;else if(event.key==='Home')next=min;else if(event.key==='End')next=max;else return;\n event.preventDefault();event.stopPropagation();setChatWidth(next);saveChatWidth();\n};\nnew ResizeObserver(updateChatWidthAria).observe(byId('chat'));\n\n// The slide lives in a shadow root rather than a sandboxed iframe so its text\n// (XHTML inside <foreignObject>) can be selected and copied while the deck's\n// SVG stays out of the viewer's own DOM and CSS. Keyboard events still reach the\n// document, so arrow-key navigation keeps working after clicking into a slide.\nconst canvas=slide.attachShadow({mode:'open'});\nfunction resize(){\n if(!state.slides.length)return;\n const style=getComputedStyle(stage);\n const width=Math.max(1,stage.clientWidth-parseFloat(style.paddingLeft)-parseFloat(style.paddingRight));\n const height=Math.max(1,stage.clientHeight-parseFloat(style.paddingTop)-parseFloat(style.paddingBottom));\n const ratio=state.aspectRatio;\n const zoom=byId('zoom').value;\n const slideWidth=presenting||zoom==='fit'?Math.min(width,height*ratio):1280*Number(zoom);\n slide.style.width=slideWidth+'px';slide.style.height=slideWidth/ratio+'px';\n}\nfunction selectSlide(next,focusThumbnail=false,reveal=true){\n index=Math.max(0,Math.min(next,state.slides.length-1));\n const count=state.slides.length?'Slide '+(index+1)+' of '+state.slides.length:'No slides';\n byId('chat-context').textContent=state.slides.length?count:'Whole project';\n byId('chat-context').dataset.focus=JSON.stringify({slide:state.slides.length?index:null,revision:state.revision??0});\n window.dispatchEvent(new Event('agent-focus'));\n byId('count').textContent=count;byId('present-count').textContent=count;\n for(const id of ['prev','present-prev'])byId(id).disabled=index===0;\n for(const id of ['next','present-next'])byId(id).disabled=index>=state.slides.length-1;\n byId('present').disabled=!state.slides.length;\n byId('zoom').disabled=!state.slides.length;\n slide.hidden=!state.slides.length;byId('empty').hidden=!!state.slides.length;\n const svg=state.slides[index];\n if(svg!==displayedSvg){\n displayedSvg=svg;\n canvas.innerHTML=svg?'<style>svg{display:block;width:100%;height:100%}</style>'+svg:'';\n }\n slide.setAttribute('aria-label','Slide '+(index+1));\n for(const [position,item] of Array.from(thumbnails.children).entries()){\n const button=item.firstElementChild,selected=position===index;\n button.setAttribute('aria-current',String(selected));button.tabIndex=selected?0:-1;\n if(selected){if(reveal)button.scrollIntoView({block:'nearest'});if(focusThumbnail)button.focus({preventScroll:true});}\n }\n resize();\n}\nfunction update(updated){\n const focusedThumbnail=thumbnails.contains(document.activeElement);\n const previous=state;\n state=updated;\n byId('status').textContent=state.error?'Build failed · showing last successful output':state.building?'Updating…':state.slides.length+' slides · Live';\n byId('error').textContent=state.error||'';byId('error').hidden=!state.error;\n document.documentElement.style.setProperty('--slide-ratio',String(state.aspectRatio));\n for(let i=state.slides.length;i<urls.length;i++){\n URL.revokeObjectURL(urls[i]);thumbnails.lastElementChild.remove();\n }\n urls.length=state.slides.length;\n state.slides.forEach((svg,i)=>{\n if(svg===previous.slides[i])return;\n const oldUrl=urls[i];\n urls[i]=URL.createObjectURL(new Blob([svg],{type:'image/svg+xml'}));\n let item=thumbnails.children[i];\n if(!item){\n item=document.createElement('li');\n const button=document.createElement('button'),number=document.createElement('span'),image=document.createElement('img');\n button.className='thumbnail';button.setAttribute('aria-label','Slide '+(i+1));button.onclick=()=>selectSlide(i,true);\n number.className='slide-number';number.textContent=String(i+1);\n image.alt='';image.draggable=false;image.loading='lazy';\n button.append(number,image);item.append(button);thumbnails.append(item);\n }\n item.querySelector('img').src=urls[i];\n if(oldUrl)URL.revokeObjectURL(oldUrl);\n });\n selectSlide(index,focusedThumbnail,false);\n if(!state.slides.length&&presenting)void exitPresentation();\n}\nfunction setPresenting(value){\n presenting=value;document.body.classList.toggle('presenting',value);resize();\n if(value)stage.focus();else{\n byId('present').focus();\n thumbnails.children[index]?.firstElementChild.scrollIntoView({block:'nearest'});\n }\n}\nasync function exitPresentation(){\n setPresenting(false);\n if(document.fullscreenElement)await document.exitFullscreen();\n}\nbyId('present').onclick=async()=>{\n setPresenting(true);\n try{await document.documentElement.requestFullscreen();}\n catch{byId('exit-present').textContent='Exit view · Esc';}\n};\nbyId('exit-present').onclick=exitPresentation;\ndocument.addEventListener('fullscreenchange',()=>{if(!document.fullscreenElement&&presenting)setPresenting(false);});\nfor(const id of ['prev','present-prev'])byId(id).onclick=()=>selectSlide(index-1);\nfor(const id of ['next','present-next'])byId(id).onclick=()=>selectSlide(index+1);\nbyId('zoom').onchange=resize;\nstage.onclick=()=>{if(presenting&&!getSelection().toString())selectSlide(index+1);};\ndocument.addEventListener('keydown',event=>{\n if(event.key==='Escape'&&presenting){event.preventDefault();void exitPresentation();return;}\n if(event.altKey||event.ctrlKey||event.metaKey||event.target.closest('select,input,textarea,[contenteditable]'))return;\n let next=index;\n if(['ArrowLeft','ArrowUp','PageUp'].includes(event.key))next--;\n else if(['ArrowRight','ArrowDown','PageDown'].includes(event.key))next++;\n else if(event.key==='Home')next=0;\n else if(event.key==='End')next=state.slides.length-1;\n else if(event.key===' '&&presenting&&!event.target.closest('button,a'))next+=event.shiftKey?-1:1;\n else return;\n event.preventDefault();selectSlide(next,thumbnails.contains(document.activeElement));\n});\nnew ResizeObserver(resize).observe(stage);\nlet refreshId=0;\nasync function refresh(){\n const id=++refreshId;\n try{const response=await fetch('/state'+(state.revision===undefined?'':'?since='+state.revision));if(!response.ok)throw new Error('Preview unavailable');const updated=await response.json();if(id===refreshId){if(updated.changes){updated.slides=state.slides.slice(0,updated.count);updated.slides.length=updated.count;for(const [position,svg] of Object.entries(updated.changes))updated.slides[Number(position)]=svg;}update(updated);}}\n catch{if(id===refreshId)byId('status').textContent='Reconnecting…';}\n}\nbyId('toggle-chat').onclick=()=>{const hidden=document.body.classList.toggle('chat-hidden');byId('toggle-chat').setAttribute('aria-expanded',String(!hidden));resize();};\nconst events=new EventSource('/events');events.onmessage=event=>{if(event.data==='chat'){window.dispatchEvent(new Event('agent-chat'));return;}if(event.data==='ready'){delete state.revision;}void refresh();};events.onerror=()=>{byId('status').textContent='Reconnecting…'};refresh();\n</script><script type=\"module\" src=\"/terminal.js\"></script></html>`;\n","import { previewStyles } from './styles.ts';\nexport const agentPage = `<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><link rel=\"stylesheet\" href=\"/terminal.css\"><style>${previewStyles}\nbody{display:flex;flex-direction:column;background:#191e30;height:100dvh;min-width:0;overflow:auto;overflow-x:hidden} .chat-heading{flex-wrap:wrap} .chat-heading select{min-width:100px}.chat-heading,#chat-context{flex-shrink:0}#claude-panel{min-height:100px}#codex-panel{min-height:240px}\n</style><div class=\"chat-heading\"><select id=\"chat-provider\" aria-label=\"AI provider\"><option value=\"claude\">Claude Code</option><option value=\"codex\">Codex</option></select><button id=\"chat-reset\" hidden>New chat</button></div>\n<div id=\"chat-context\">No slide selected</div>\n<section id=\"claude-panel\" aria-label=\"Claude Code terminal\"><div class=\"terminal-toolbar\"><span id=\"terminal-status\" role=\"status\">Start Claude Code to edit your slides.</span><button id=\"terminal-start\">Start</button><button id=\"terminal-stop\" hidden>End session</button></div><div class=\"terminal-frame\"><div id=\"terminal\"></div></div></section>\n<div id=\"codex-panel\" hidden>\n<div id=\"messages\" role=\"log\" aria-label=\"Conversation\"><p class=\"chat-intro\">Describe what you want to change. The current slide is included automatically. You can also ask about other slides or the whole deck.<br><br>Uses your locally installed Codex. Sign in through its CLI first. Sending a message allows it to edit this project.</p></div>\n<form id=\"chat-form\"><textarea id=\"chat-input\" aria-label=\"Message\" maxlength=\"16000\" placeholder=\"Ask for a change…\" required></textarea><div class=\"chat-actions\"><span class=\"chat-shortcut\">⌘ / Ctrl + Enter</span><button id=\"chat-stop\" type=\"button\" hidden>Stop</button><button id=\"chat-send\" type=\"submit\">Send</button></div></form>\n<div id=\"chat-status\" role=\"status\">Ready</div>\n</div>\n<script>\nconst byId=id=>document.getElementById(id),base=location.pathname;\nlet focus={slide:null,revision:0};\nwindow.addEventListener('message',event=>{\n if(event.origin!==location.origin||event.source!==parent)return;\n if(event.data?.type==='focus'){focus=event.data.focus;byId('chat-context').dataset.focus=JSON.stringify(focus);byId('chat-context').textContent=event.data.label;}\n if(event.data?.type==='chat')void refreshChat();\n if(event.data?.type==='inline-edit'&&byId('chat-provider').value==='codex'){\n void (async()=>{try{if(chatBusy)throw new Error('This agent is working. Wait for it to finish.');await chatAction('/chat',{message:event.data.message,provider:'codex',...event.data.focus});parent.postMessage({type:'inline-result',id:event.data.id},location.origin);}catch(error){parent.postMessage({type:'inline-result',id:event.data.id,error:error.message},location.origin);}})();\n }\n\n});\nparent.postMessage({type:'agent-ready'},location.origin);\nlet chatRequest=0,chatBusy=false,lastMessages='';\nfunction renderChat(chat){\n chatBusy=chat.running;\n byId('chat-send').disabled=chat.running;\n byId('chat-reset').disabled=chat.running;\n if(byId('chat-provider').value==='codex')byId('chat-provider').disabled=chat.running;\n byId('chat-stop').hidden=!chat.running;\n byId('chat-status').textContent=chat.status;\n\n const serialized=JSON.stringify(chat.messages);\n if(serialized===lastMessages)return;\n lastMessages=serialized;\n const log=byId('messages'),atBottom=log.scrollHeight-log.scrollTop-log.clientHeight<60;\n log.replaceChildren();\n if(!chat.messages.length){const intro=document.createElement('p');intro.className='chat-intro';intro.textContent='Ask for a focused slide edit or a change across the deck. Uses your locally installed CLI and its login. Sending allows edits to this project.';log.append(intro);}\n for(const message of chat.messages){\n const item=document.createElement('div'),label=document.createElement('small'),body=document.createElement('div');\n item.className='chat-message '+message.role;\n label.textContent=message.role==='user'?'You · '+(message.context?.slide?'Slide '+message.context.slide:'Whole project'):'Assistant';\n if(message.role==='assistant'&&message.html){body.className='markdown';body.innerHTML=message.html;}else body.textContent=message.text||(chat.running?'Working…':'No response');item.append(label,body);log.append(item);\n }\n if(atBottom)log.scrollTop=log.scrollHeight;\n}\nasync function refreshChat(){\n const id=++chatRequest;\n try{const response=await fetch(base+'/chat');if(!response.ok)throw new Error('Chat unavailable');const chat=await response.json();if(id===chatRequest)renderChat(chat);}\n catch(error){if(id===chatRequest)byId('chat-status').textContent=error.message;}\n}\nasync function chatAction(path,payload){\n ++chatRequest;\n const response=await fetch(base+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});\n const result=await response.json();if(!response.ok)throw new Error(result.error||'Chat request failed');\n await refreshChat();\n}\nbyId('chat-form').onsubmit=async event=>{\n event.preventDefault();if(chatBusy)return;\n const input=byId('chat-input'),message=input.value.trim();if(!message)return;\n chatBusy=true;byId('chat-send').disabled=true;\n try{await chatAction('/chat',{message,provider:byId('chat-provider').value,...focus});if(input.value.trim()===message)input.value='';}\n catch(error){byId('chat-status').textContent=error.message;chatBusy=false;byId('chat-send').disabled=false;}\n};\nbyId('chat-input').onkeydown=event=>{if(event.key==='Enter'&&(event.metaKey||event.ctrlKey)&&!event.isComposing){event.preventDefault();byId('chat-form').requestSubmit();}};\nfor(const action of ['stop','reset'])byId('chat-'+action).onclick=()=>chatAction('/chat/'+action,{}).catch(error=>{byId('chat-status').textContent=error.message;});\nbyId('chat-provider').onchange=()=>{try{sessionStorage.setItem('office-kit-provider'+base,byId('chat-provider').value);}catch{}const claude=byId('chat-provider').value==='claude';byId('claude-panel').hidden=!claude;byId('codex-panel').hidden=claude;byId('chat-reset').hidden=claude;};\ntry{byId('chat-provider').value=sessionStorage.getItem('office-kit-provider'+base)||'claude';}catch{}\nbyId('chat-provider').onchange();\nvoid refreshChat();\n</script><script type=\"module\" src=\"/terminal.js\"></script></html>`;\n","/** Shared guidance for agents editing a deck through the preview. */\nexport const authoringGuidance = `For lists and tables of contents, use Text paragraphs/bullets or mapped Text rows. Bullets and TableOfContents are not built-in DSL components: inspect installed exports, import existing local helpers or define them. Do not use Raw for these layouts.\nChoose foreground and actual background colors together. Explicitly set readable text colors on slides, cards, tables, chart labels and footnotes; check inherited theme styles. Aim for 4.5:1 contrast for normal text and 3:1 for large text (18pt or 14pt bold). Use a solid backing over images or gradients if needed. Inspect rendered slides; compilation alone cannot verify contrast.`;\n","import type { VisualReview } from './visual-review.ts';\nimport { authoringGuidance } from './authoring-guidance.ts';\nimport { randomBytes } from 'node:crypto';\nimport { dirname, resolve, join } from 'node:path';\nimport { createRequire } from 'node:module';\nimport { stat, chmod } from 'node:fs/promises';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { IPty } from 'node-pty';\nimport type { FocusContext } from './chat.ts';\n\nconst OUTPUT_LIMIT = 2_000_000;\nconst REQUEST_LIMIT = 128_000;\n\n/** A real interactive Claude session, shared across reloads of its owning tab. */\nexport function createTerminal(\n entry: string,\n busy = () => false,\n base = '',\n verify: () => Promise<string | null> = async () => null,\n review?: { begin(): void; next(): Promise<VisualReview | undefined> },\n) {\n let repairs = 0;\n let working = false;\n let process: IPty | undefined;\n let owner = '';\n let output = '';\n let context: FocusContext | undefined;\n let status = 'Start Claude Code to edit your slides.';\n let completion = Promise.resolve();\n let closing = false;\n let stopping = false;\n let starting = false;\n const token = randomBytes(32).toString('hex');\n const clients = new Set<ServerResponse>();\n const snapshot = () => ({ running: !!process, owner, status });\n const emit = (event: string, value: unknown) => {\n for (const client of clients) {\n if (!client.write(`event: ${event}\\ndata: ${JSON.stringify(value)}\\n\\n`)) {\n clients.delete(client);\n client.end();\n }\n }\n };\n async function stop() {\n if (!process || stopping) return completion;\n stopping = true;\n status = 'Stopping…';\n emit('state', snapshot());\n const running = process;\n running.kill();\n const timer = setTimeout(() => {\n if (process === running) running.kill('SIGKILL');\n }, 2000);\n await completion;\n clearTimeout(timer);\n }\n async function handle(\n request: IncomingMessage,\n response: ServerResponse,\n focus: (index: number | null, revision: number) => FocusContext,\n ) {\n const json = (code: number, value: unknown) => {\n response.writeHead(code, { 'Content-Type': 'application/json' });\n response.end(JSON.stringify(value));\n };\n if (request.url === '/terminal/context' || request.url === '/terminal/verify') {\n if (request.method !== 'POST' || request.headers.authorization !== `Bearer ${token}`) {\n json(403, { error: 'Invalid hook credentials' });\n return;\n }\n request.resume();\n if (request.url === '/terminal/verify') {\n if (closing || stopping || !process) {\n json(200, {});\n return;\n }\n let error: string | null;\n try {\n error = await verify();\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n }\n if (closing || stopping || !process) {\n json(200, {});\n return;\n }\n if (error && repairs < 3) {\n repairs++;\n status = `Repairing preview (${repairs}/3)…`;\n json(200, {\n decision: 'block',\n reason: `The actual preview build failed. Repair the source before finishing (attempt ${repairs}/3). Preserve unrelated edits, inspect the installed DSL exports and local components before changing imports. Do not hide the error or remove requested content. No Raw is needed for lists or an agenda: use Text paragraphs/bullets or mapped Text rows. Build error:\\n${error.slice(0, 16000)}`,\n });\n } else {\n if (!error && review) {\n try {\n const visual = await review.next();\n if (closing || stopping || !process) {\n json(200, {});\n return;\n }\n if (visual) {\n status = 'Reviewing slide screenshots…';\n json(200, { decision: 'block', reason: visual.prompt });\n emit('state', snapshot());\n return;\n }\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n }\n }\n working = false;\n status = error ? 'Preview verification incomplete: ' + error : 'Preview build verified';\n json(200, {});\n }\n emit('state', snapshot());\n return;\n }\n repairs = 0;\n working = true;\n review?.begin();\n json(200, {\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: `You are editing the local PowerPoint TSX project at ${resolve(entry)}.\nRead the project's authoring instructions. Make focused source patches and preserve unrelated work.\nThe preview rebuilds on save; do not start another dev server. A Stop hook checks the actual build and returns errors for repair.\n${authoringGuidance}\nThe focused slide is context, NOT a restriction. For \"this slide\", edit only its relevant source. For other slides or deck-wide requests, locate the relevant source or shared theme.\nSlide numbers are 1-based. Verify source before editing; dependency paths are candidates, not an exact slide-to-file mapping.\nPreview context captured with the latest terminal input: ${JSON.stringify(context)}`,\n },\n });\n return;\n }\n const origin = `http://${request.headers.host}`;\n if (\n request.headers['sec-fetch-site'] === 'cross-site' ||\n (request.headers.origin && request.headers.origin !== origin)\n ) {\n json(403, { error: 'Same-origin requests only' });\n return;\n }\n if (request.method === 'GET' && request.url === '/terminal/events') {\n response.writeHead(200, { 'Content-Type': 'text/event-stream' });\n response.write(`event: replay\\ndata: ${JSON.stringify(output)}\\n\\n`);\n response.write(`event: state\\ndata: ${JSON.stringify(snapshot())}\\n\\n`);\n clients.add(response);\n request.on('close', () => clients.delete(response));\n return;\n }\n if (\n request.method !== 'POST' ||\n request.headers.origin !== origin ||\n request.headers['content-type'] !== 'application/json'\n ) {\n json(403, { error: 'Same-origin JSON requests only' });\n return;\n }\n try {\n let body = '';\n request.setEncoding('utf8');\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > REQUEST_LIMIT) throw new Error('Request too large');\n }\n const value = JSON.parse(body);\n if (!value || typeof value.client !== 'string' || !/^[\\w-]{1,64}$/.test(value.client))\n throw new Error('Invalid terminal client');\n if (closing || starting || stopping || (process && owner !== value.client)) {\n json(409, {\n error: stopping\n ? 'Claude Code is stopping'\n : 'Claude Code is open in another tab. Use that tab to control it.',\n });\n return;\n }\n const size = () => {\n if (\n !Number.isInteger(value.cols) ||\n value.cols < 2 ||\n value.cols > 500 ||\n !Number.isInteger(value.rows) ||\n value.rows < 1 ||\n value.rows > 300\n )\n throw new Error('Invalid terminal dimensions');\n };\n const updateFocus = () => {\n if (\n !(value.slide === null || (Number.isInteger(value.slide) && value.slide >= 0)) ||\n !Number.isInteger(value.revision)\n )\n throw new Error('Invalid preview context');\n context = focus(value.slide, value.revision);\n };\n if (request.url === '/terminal/start') {\n if (busy()) throw new Error('A Codex edit is already running');\n size();\n updateFocus();\n if (!process) {\n starting = true;\n try {\n // Lazy loading leaves preview/export usable if a native PTY cannot load.\n // node-pty 1.1.0 ships its macOS spawn helper without executable bits.\n // Restore the packaged helper's mode before its first launch.\n if (globalThis.process.platform === 'darwin') {\n const root = dirname(createRequire(import.meta.url).resolve('node-pty/package.json'));\n const helper = join(\n root,\n 'prebuilds',\n `darwin-${globalThis.process.arch}`,\n 'spawn-helper',\n );\n const info = await stat(helper).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (info && !(info.mode & 0o100)) await chmod(helper, info.mode | 0o100);\n }\n const pty = await import('node-pty');\n if (process || closing) throw new Error('Terminal state changed. Try again.');\n const settings = {\n hooks: {\n Stop: [\n {\n hooks: [\n {\n type: 'http',\n url: `${origin}${base}/terminal/verify`,\n headers: { Authorization: `Bearer ${token}` },\n timeout: 120,\n },\n ],\n },\n ],\n UserPromptSubmit: [\n {\n hooks: [\n {\n type: 'http',\n url: `${origin}${base}/terminal/context`,\n headers: { Authorization: `Bearer ${token}` },\n timeout: 5,\n },\n ],\n },\n ],\n },\n };\n const env = { ...globalThis.process.env };\n // This is an independent interactive session, even if the preview was started by Claude.\n delete env.CLAUDECODE;\n process = pty.spawn('claude', ['--settings', JSON.stringify(settings)], {\n cwd: dirname(resolve(entry)),\n name: 'xterm-256color',\n env,\n cols: value.cols,\n rows: value.rows,\n });\n } finally {\n starting = false;\n }\n owner = value.client;\n output = '';\n status = 'Claude Code';\n emit('replay', '');\n process.onData((data) => {\n output = (output + data).slice(-OUTPUT_LIMIT);\n emit('output', data);\n });\n completion = new Promise<void>((done) =>\n process!.onExit(({ exitCode }) => {\n process = undefined;\n working = false;\n stopping = false;\n status = `Claude Code exited (${exitCode}). Start to open a new session.`;\n emit('state', snapshot());\n done();\n }),\n );\n }\n } else if (request.url === '/terminal/prompt') {\n if (!process) throw new Error('Start Claude Code in the selected agent pane first.');\n if (working)\n throw new Error('Claude Code is working. Wait for the current turn to finish.');\n if (\n typeof value.message !== 'string' ||\n !value.message.trim() ||\n value.message.length > 16000 ||\n [...value.message].some((character: string) => {\n const code = character.charCodeAt(0);\n return (code < 32 && code !== 9 && code !== 10) || code === 127;\n })\n )\n throw new Error('Invalid inline prompt');\n updateFocus();\n working = true;\n process.write('\\x1b[200~' + value.message + '\\x1b[201~');\n await new Promise((done) => setTimeout(done, 100));\n if (!process || stopping) throw new Error('Claude Code stopped before submitting.');\n process.write('\\r');\n } else if (request.url === '/terminal/input') {\n if (!process) throw new Error('Start Claude Code first');\n if (typeof value.data !== 'string' || value.data.length > 32000)\n throw new Error('Invalid terminal input');\n updateFocus();\n if (value.data.includes('\\x03')) working = false;\n process.write(value.data);\n } else if (request.url === '/terminal/resize') {\n size();\n process?.resize(value.cols, value.rows);\n } else if (request.url === '/terminal/stop') {\n await stop();\n } else {\n json(404, { error: 'Not found' });\n return;\n }\n emit('state', snapshot());\n json(200, snapshot());\n } catch (cause) {\n json(400, { error: cause instanceof Error ? cause.message : 'Invalid terminal request' });\n }\n }\n return {\n handle,\n isRunning: () => starting || !!process,\n async close() {\n closing = true;\n await stop();\n for (const client of clients) client.end();\n clients.clear();\n },\n };\n}\n","import type { VisualReview } from './visual-review.ts';\nimport { authoringGuidance } from './authoring-guidance.ts';\nimport MarkdownIt from 'markdown-it';\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { dirname, resolve } from 'node:path';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nexport type Provider = 'codex';\nconst markdown = new MarkdownIt({ html: false, linkify: false });\n// Do not fetch remote images from model output.\nmarkdown.renderer.rules.image = (tokens, index) =>\n markdown.utils.escapeHtml(tokens[index]?.content ?? '');\nexport interface FocusContext {\n slide: number | null;\n count: number;\n revision: number;\n text: string;\n entry: string;\n files: string[];\n buildError: string | null;\n}\ninterface Message {\n role: 'user' | 'assistant';\n text: string;\n context?: FocusContext;\n}\n\n/** One shared conversation and one editing process per dev server. */\nexport function createChat(\n entry: string,\n notify: () => void,\n busy = () => false,\n verify: () => Promise<string | null> = async () => null,\n review?: { begin(): void; next(): Promise<VisualReview | undefined> },\n reviewImages: (prompt: string) => string[] = () => [],\n) {\n let messages: Message[] = [];\n let provider: Provider = 'codex';\n let child: ChildProcess | undefined;\n let status = 'Ready';\n let stopping = false;\n let killTimer: ReturnType<typeof setTimeout> | undefined;\n let completion: Promise<void> = Promise.resolve();\n const snapshot = () => ({\n messages: messages.map((message) => ({\n ...message,\n ...(message.role === 'assistant' ? { html: markdown.render(message.text) } : {}),\n })),\n provider,\n running: !!child,\n status,\n });\n function stop() {\n if (!child || stopping) return;\n stopping = true;\n status = 'Stopping…';\n const processToStop = child;\n // During verification the child has exited, but the turn still owns the\n // conversation. Cancel repair without signalling a potentially reused PID.\n if (processToStop.exitCode !== null || processToStop.signalCode !== null) {\n notify();\n return;\n }\n const kill = (signal: NodeJS.Signals) => {\n try {\n if (process.platform !== 'win32' && processToStop.pid)\n process.kill(-processToStop.pid, signal);\n else processToStop.kill(signal);\n } catch {\n /* Already exited. */\n }\n };\n kill('SIGTERM');\n killTimer = setTimeout(() => kill('SIGKILL'), 2000);\n notify();\n }\n function start(\n text: string,\n selected: Provider,\n context: FocusContext,\n repairs = 0,\n images: string[] = [],\n reviewing = false,\n ) {\n if (!repairs && !reviewing) review?.begin();\n provider = selected;\n const user: Message = { role: 'user', text, context };\n // Keep recent conversational intent, including each turn's original focus.\n const history = messages.slice(-12).map((message) => ({\n ...message,\n text: message.text.slice(-12000),\n }));\n const prompt = `You are editing a local PowerPoint TSX project in ${dirname(resolve(entry))}.\nRead the project's authoring instructions. Make focused patches to the TSX source, preserving unrelated work.\nThe preview rebuilds automatically on save; do not start another dev server.\n${authoringGuidance}\nThe attached focus is context, NOT a restriction: use it for references such as \"this slide\". For other slides or deck-wide requests, find the relevant source or shared theme instead. Do not rewrite the whole deck for a local edit.\nSlide numbers are 1-based and refer to the last successful preview at send time. Source may have changed since then; verify it before editing. Files are dependency candidates, not an exact slide-to-source mapping.\nRespond in the user's language, briefly describing edits or answering their question. If permissions prevent an action, explain that instead of claiming success.\nRecent conversation (JSON): ${JSON.stringify(history)}\nCurrent request and preview context (JSON): ${JSON.stringify(user)}`;\n messages.push(user);\n const answer: Message = { role: 'assistant', text: '' };\n messages.push(answer);\n if (messages.length > 100) messages = messages.slice(-100);\n status = 'Working…';\n stopping = false;\n const args = ['exec', '--json', '--sandbox', 'workspace-write', '--skip-git-repo-check', '-'];\n for (const image of images) args.splice(args.length - 1, 0, '--image', image);\n child = spawn(selected, args, {\n cwd: dirname(resolve(entry)),\n stdio: ['pipe', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n shell: false,\n });\n const running = child;\n let buffer = '',\n stderr = '',\n failure = '',\n sawResult = false;\n function append(value: string) {\n answer.text = (answer.text + (answer.text ? '\\n\\n' : '') + value).slice(-100000);\n notify();\n }\n function consume(line: string) {\n if (!line.trim()) return;\n try {\n const event = JSON.parse(line);\n if (event.type === 'item.completed' && event.item?.type === 'agent_message')\n append(event.item.text ?? '');\n if (event.type === 'item.started') {\n status = 'Editing / inspecting…';\n notify();\n }\n if (event.type === 'turn.completed') sawResult = true;\n if (event.type === 'turn.failed' || event.type === 'error')\n failure = event.error?.message ?? event.message ?? 'Agent failed';\n } catch {\n failure = 'Unexpected CLI output. Update your CLI and try again.';\n }\n }\n running.stdout!.setEncoding('utf8');\n running.stdout!.on('data', (chunk: string) => {\n buffer += chunk;\n let end: number;\n while ((end = buffer.indexOf('\\n')) !== -1) {\n consume(buffer.slice(0, end));\n buffer = buffer.slice(end + 1);\n }\n if (buffer.length > 2_000_000) {\n failure = 'CLI output exceeded the limit.';\n stop();\n }\n });\n running.stderr!.setEncoding('utf8');\n running.stderr!.on('data', (chunk: string) => {\n stderr = (stderr + chunk).slice(-8000);\n });\n running.stdin!.on('error', () => {\n /* Early process exit is handled below. */\n });\n running.stdin!.end(prompt);\n completion = new Promise<void>((done) => {\n running.on('error', (error) => {\n failure = `Could not run ${selected}. Install it and log in from your terminal first. ${error.message}`;\n });\n running.on('close', async (code) => {\n if (buffer.trim()) consume(buffer);\n clearTimeout(killTimer);\n status = stopping\n ? 'Stopped. Saved edits remain in the preview.'\n : failure ||\n (code !== 0\n ? stderr || `${selected} exited with code ${code}`\n : !sawResult\n ? 'CLI exited without a completed result.'\n : 'Done');\n if (status === 'Done') {\n status = 'Verifying preview…';\n notify();\n let buildError: string | null;\n try {\n buildError = await verify();\n } catch (cause) {\n buildError = cause instanceof Error ? cause.message : String(cause);\n }\n if (!stopping && buildError && repairs < 3) {\n child = undefined;\n start(\n `The actual preview build failed. Repair the source and preserve unrelated work (attempt ${repairs + 1}/3). Do not remove requested content or hide the error.\\n${buildError.slice(0, 16000)}`,\n selected,\n { ...context, buildError },\n repairs + 1,\n [],\n reviewing,\n );\n await completion;\n done();\n return;\n }\n let reviewFailure = '';\n if (!stopping && !buildError && review) {\n try {\n const visual = await review.next();\n if (!stopping && visual) {\n child = undefined;\n start(visual.prompt, selected, context, 0, visual.images, true);\n await completion;\n done();\n return;\n }\n } catch (error) {\n reviewFailure = error instanceof Error ? error.message : String(error);\n }\n }\n status = stopping\n ? 'Stopped. Saved edits remain in the preview.'\n : buildError\n ? 'Preview still has errors after 3 repair attempts.\\n' + buildError.slice(0, 16000)\n : reviewFailure || 'Done';\n }\n if (status !== 'Done') append(status);\n child = undefined;\n notify();\n done();\n });\n });\n notify();\n }\n async function handle(\n request: IncomingMessage,\n response: ServerResponse,\n focus: (index: number | null, revision: number) => FocusContext,\n ) {\n const json = (code: number, value: unknown) => {\n response.writeHead(code, { 'Content-Type': 'application/json' });\n response.end(JSON.stringify(value));\n };\n if (request.method === 'GET' && request.url === '/chat') {\n json(200, snapshot());\n return;\n }\n if (request.method !== 'POST') {\n json(405, { error: 'Method not allowed' });\n return;\n }\n // Same-origin JSON prevents other sites from invoking local editing tools.\n if (\n request.headers.origin !== `http://${request.headers.host}` ||\n request.headers['content-type']?.split(';')[0] !== 'application/json'\n ) {\n json(403, { error: 'Same-origin JSON required' });\n return;\n }\n try {\n let body = '';\n request.setEncoding('utf8');\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > 32000) {\n json(413, { error: 'Message too large' });\n return;\n }\n }\n const value = JSON.parse(body);\n if (request.url === '/chat/stop') {\n stop();\n json(200, snapshot());\n return;\n }\n if (child) {\n json(409, { error: 'An edit is already running' });\n return;\n }\n if (request.url === '/chat/reset') {\n messages = [];\n status = 'Ready';\n notify();\n json(200, snapshot());\n return;\n }\n if (request.url !== '/chat') {\n json(404, { error: 'Not found' });\n return;\n }\n if (\n typeof value.message !== 'string' ||\n !value.message.trim() ||\n value.message.length > 16000 ||\n value.provider !== 'codex' ||\n !(value.slide === null || (Number.isInteger(value.slide) && value.slide >= 0)) ||\n !Number.isInteger(value.revision)\n ) {\n json(400, { error: 'Invalid chat request' });\n return;\n }\n if (busy()) {\n json(409, { error: 'End the Claude Code session before starting a Codex edit' });\n return;\n }\n const context = focus(value.slide, value.revision);\n start(value.message.trim(), value.provider, context, 0, reviewImages(value.message.trim()));\n json(202, snapshot());\n } catch (cause) {\n json(400, { error: cause instanceof Error ? cause.message : 'Invalid request' });\n }\n }\n return {\n handle,\n isRunning: () => !!child,\n async close() {\n stop();\n await completion;\n },\n };\n}\n","import { createTextEditor } from './text-edit.ts';\nimport { createVisualReviewer } from './visual-review.ts';\nimport { createServer, type ServerResponse } from 'node:http';\nimport { watch } from 'node:fs';\nimport { dirname, resolve, sep } from 'node:path';\nimport type { BuildResult } from './build.ts';\nimport { createDeckBuilder } from './build-runner.ts';\nimport { page } from './page.ts';\nimport { agentPage } from './agent-page.ts';\nimport { readFile } from 'node:fs/promises';\nimport { createTerminal } from './terminal.ts';\nimport { createChat } from './chat.ts';\n\nexport async function serveDeck(entry: string, port = 4173) {\n let latest: BuildResult | undefined;\n let error: string | null = null;\n let building = false;\n let revision = 0;\n let generation = 0;\n let patch: Record<number, string> = {};\n let pending = false;\n let closed = false;\n const clients = new Set<ServerResponse>();\n const sessions = new Map<\n string,\n {\n chat: ReturnType<typeof createChat>;\n terminal: ReturnType<typeof createTerminal>;\n closing: boolean;\n }\n >();\n const capturedReviews = new Map<string, string[]>();\n function session(id: string) {\n let result = sessions.get(id);\n if (!result) {\n const review = createVisualReviewer(resolve(entry), () => latest?.slides ?? []);\n const chat = createChat(\n entry,\n () => {\n for (const client of clients) client.write('data: chat\\n\\n');\n },\n () => terminal.isRunning(),\n verify,\n review,\n (prompt) => capturedReviews.get(prompt) ?? [],\n );\n const terminal = createTerminal(\n entry,\n () => chat.isRunning(),\n id ? '/agents/' + id : '',\n verify,\n review,\n );\n result = { chat, terminal, closing: false };\n sessions.set(id, result);\n }\n return result;\n }\n const textEditor = createTextEditor(\n resolve(entry),\n () => {\n if (!latest || building || pending || timer || error)\n throw new Error('Wait for a successful preview build.');\n return { ...latest, revision };\n },\n verify,\n );\n const server = createServer((request, response) => {\n const host = request.headers.host;\n if (host !== `127.0.0.1:${actualPort}` && host !== `localhost:${actualPort}`) {\n response.writeHead(403).end();\n return;\n }\n response.setHeader('Cache-Control', 'no-store');\n const match = request.url?.match(\n /^\\/agents\\/([\\w-]{1,64})(\\/(?:chat(?:\\/(?:stop|reset))?|terminal\\/(?:start|input|prompt|resize|stop|events|context|verify)|close))?$/,\n );\n if (request.url?.startsWith('/agents/') && !match) {\n response.writeHead(404).end();\n return;\n }\n if (request.url === '/text-edit' || request.url === '/text-edit/undo') {\n if (\n request.method !== 'POST' ||\n request.headers.origin !== `http://${host}` ||\n request.headers['content-type'] !== 'application/json'\n ) {\n response.writeHead(403).end();\n return;\n }\n void (async () => {\n let body = '';\n request.setEncoding('utf8');\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > 100000) throw new Error('Request too large');\n }\n const manualReview = createVisualReviewer(resolve(entry), () => latest?.slides ?? []);\n manualReview.begin();\n if (request.url === '/text-edit/undo') await textEditor.undo();\n else await textEditor.edit(JSON.parse(body));\n let review;\n let reviewError;\n try {\n review = await manualReview.next();\n if (review) {\n capturedReviews.set(review.prompt, review.images);\n if (capturedReviews.size > 64)\n capturedReviews.delete(capturedReviews.keys().next().value!);\n }\n } catch (cause) {\n reviewError = cause instanceof Error ? cause.message : String(cause);\n }\n response\n .writeHead(200, { 'Content-Type': 'application/json' })\n .end(JSON.stringify({ review, reviewError }));\n })().catch((cause) =>\n response\n .writeHead(400, { 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: cause instanceof Error ? cause.message : String(cause) })),\n );\n return;\n }\n const id = match?.[1] ?? '';\n if (match) {\n if (\n request.headers['sec-fetch-site'] === 'cross-site' ||\n (request.headers.origin && request.headers.origin !== `http://${host}`)\n ) {\n response.writeHead(403).end();\n return;\n }\n if (sessions.get(id)?.closing) {\n response.writeHead(409).end('{\"error\":\"Agent is closing\"}');\n return;\n }\n if (match[2] === '/close') {\n if (\n request.method !== 'POST' ||\n request.headers.origin !== `http://${host}` ||\n request.headers['content-type'] !== 'application/json'\n ) {\n response.writeHead(403).end();\n return;\n }\n request.resume();\n const current = sessions.get(id);\n void (async () => {\n if (current) {\n current.closing = true;\n await Promise.all([current.terminal.close(), current.chat.close()]);\n sessions.delete(id);\n }\n response.writeHead(200).end('{}');\n })().catch(() => response.writeHead(500).end());\n return;\n }\n if (!sessions.has(id) && sessions.size >= 8) {\n response.writeHead(429).end('Too many agent sessions. Close an existing pane.');\n return;\n }\n if (!match[2]) {\n if (request.method !== 'GET') {\n response.writeHead(405).end();\n return;\n }\n session(id);\n response.writeHead(200, { 'Content-Type': 'text/html' }).end(agentPage);\n return;\n }\n if (!sessions.has(id)) {\n response.writeHead(404).end();\n return;\n }\n request.url = match[2];\n }\n\n if (\n request.url === '/chat' ||\n request.url?.startsWith('/chat/') ||\n request.url?.startsWith('/terminal/')\n ) {\n const current = session(id);\n const handler = request.url.startsWith('/terminal/') ? current.terminal : current.chat;\n void handler.handle(request, response, (index, viewedRevision) => {\n if (viewedRevision !== revision)\n throw new Error('Preview changed. Review the current slide and send again.');\n if (index !== null && (!latest || index >= latest.slides.length))\n throw new Error('Slide no longer exists.');\n return {\n slide: index === null ? null : index + 1,\n count: latest?.slides.length ?? 0,\n revision,\n text: index === null ? '' : (latest?.slideTexts[index] ?? '').slice(0, 12000),\n entry: resolve(entry),\n files: latest?.dependencies ?? [resolve(entry)],\n buildError: error,\n };\n });\n } else if (\n request.method === 'GET' &&\n ['/terminal.js', '/terminal.css'].includes(request.url ?? '')\n ) {\n const asset = request.url === '/terminal.js' ? 'terminal-client.js' : 'terminal-client.css';\n void readFile(new URL(asset, import.meta.url)).then(\n (bytes) => {\n response.writeHead(200, {\n 'Content-Type': asset.endsWith('.css') ? 'text/css' : 'text/javascript',\n });\n response.end(bytes);\n },\n () => response.writeHead(500).end('Terminal assets unavailable. Rebuild pptx-dev.'),\n );\n } else if (request.method !== 'GET') {\n response.writeHead(405).end();\n } else if (request.url === '/events') {\n response.writeHead(200, { 'Content-Type': 'text/event-stream' });\n response.write('data: ready\\n\\n');\n clients.add(response);\n request.on('close', () => clients.delete(response));\n } else if (request.url === '/state' || request.url?.startsWith('/state?')) {\n const since = new URL(request.url, 'http://localhost').searchParams.get('since');\n const incremental =\n since !== null && (since === String(revision) || since === String(revision - 1));\n response.writeHead(200, { 'Content-Type': 'application/json' });\n response.end(\n JSON.stringify({\n revision,\n building,\n ...(incremental\n ? {\n changes: since === String(revision) ? {} : patch,\n count: latest?.slides.length ?? 0,\n }\n : { slides: latest?.slides ?? [] }),\n aspectRatio: latest?.aspectRatio ?? 16 / 9,\n error,\n diagnostics: latest?.diagnostics ?? [],\n }),\n );\n } else if (request.url === '/deck.pptx' && latest) {\n response.writeHead(200, {\n 'Content-Type': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'Content-Disposition': 'attachment; filename=\"deck.pptx\"',\n });\n response.end(latest.bytes);\n } else if (request.url === '/') {\n response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page);\n } else {\n response.writeHead(404).end();\n }\n });\n async function verify() {\n // A fresh build also covers writes whose watcher notification has not arrived yet.\n void rebuild();\n const deadline = Date.now() + 30000;\n while (!closed && (building || timer || pending)) {\n if (Date.now() >= deadline)\n return 'Preview verification timed out. Inspect the build before claiming success.';\n await new Promise((done) => setTimeout(done, 50));\n }\n return closed ? 'Preview server closed.' : error;\n }\n async function rebuild() {\n if (closed) return;\n if (building) {\n pending = true;\n return;\n }\n building = true;\n const started = generation;\n for (const client of clients) client.write('data: building\\n\\n');\n try {\n const result = await builder.build();\n if (started === generation && !closed) {\n patch = {};\n result.slides.forEach((svg, index) => {\n if (svg !== latest?.slides[index]) patch[index] = svg;\n });\n latest = result;\n revision++;\n error = null;\n }\n } catch (cause) {\n if (started === generation)\n error = cause instanceof Error ? (cause.stack ?? cause.message) : String(cause);\n } finally {\n building = false;\n for (const client of clients) client.write('data: updated\\n\\n');\n if (pending && !timer) {\n pending = false;\n void rebuild();\n }\n }\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const root = dirname(resolve(entry));\n const watcher = watch(root, { recursive: true }, (_, filename) => {\n if (\n !filename ||\n filename\n .split(sep)\n .some((part) => ['node_modules', '.git', 'dist', '.office-kit'].includes(part))\n )\n return;\n if (!/\\.([cm]?[jt]sx?|json|pptx|png|jpe?g|gif|bmp|tiff?|emf|wmf|svg)$/i.test(filename)) return;\n generation++;\n void builder.cancel();\n clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n pending = false;\n void rebuild();\n }, 30);\n });\n const builder = createDeckBuilder(entry);\n let actualPort = port;\n try {\n await new Promise<void>((resolveListen, reject) => {\n server.once('error', reject);\n server.listen(port, '127.0.0.1', () => {\n server.off('error', reject);\n resolveListen();\n });\n });\n } catch (cause) {\n watcher.close();\n await builder.close();\n throw cause;\n }\n const address = server.address();\n if (address && typeof address !== 'string') actualPort = address.port;\n await rebuild();\n return {\n url: `http://127.0.0.1:${actualPort}`,\n async close() {\n closed = true;\n clearTimeout(timer);\n watcher.close();\n await Promise.all(\n [...sessions.values()].flatMap(({ terminal, chat }) => [terminal.close(), chat.close()]),\n );\n await builder.close();\n for (const client of clients) client.end();\n await new Promise<void>((done, reject) =>\n server.close((cause) => (cause ? reject(cause) : done())),\n );\n },\n };\n}\n","#!/usr/bin/env node\nimport { resolve } from 'node:path';\nimport { exportDeck } from './index.ts';\nimport { serveDeck } from './server.ts';\nimport { initProject } from './init.ts';\nimport { inspectTemplate } from './inspect.ts';\n\nconst usage = `Usage: office-pptx init <new-directory>\n office-pptx dev <deck.tsx> [--port 4173]\n office-pptx build <deck.tsx> [--out deck.pptx]\n office-pptx inspect <template.pptx>`;\nconst [command, entry, ...args] = process.argv.slice(2);\ntry {\n if (command === '--help' || command === '-h') {\n console.log(usage);\n } else {\n if (!entry) throw new Error(usage);\n const option = command === 'build' ? '--out' : command === 'dev' ? '--port' : undefined;\n if (args.length && (args.length !== 2 || !option || args[0] !== option || !args[1])) {\n throw new Error(`Unexpected arguments: ${args.join(' ')}\\n${usage}`);\n }\n if (command === 'init') {\n const directory = await initProject(entry);\n console.log(\n `Created ${directory}\\nInside that directory, run npm install once.\\nStart development: npm run dev (or npx office-pptx dev deck.tsx).`,\n );\n } else if (command === 'inspect') {\n console.log(JSON.stringify(await inspectTemplate(entry), null, 2));\n } else if (command === 'build') {\n const output = resolve(args[1] ?? 'deck.pptx');\n const result = await exportDeck(entry, output);\n console.log(`Wrote ${output} (${result.slides.length} slides)`);\n } else if (command === 'dev') {\n const port = args[1] === undefined ? 4173 : Number(args[1]);\n if (!Number.isInteger(port) || port < 0 || port > 65535)\n throw new Error('Port must be an integer between 0 and 65535.');\n const server = await serveDeck(entry, port);\n console.log(`Preview: ${server.url}`);\n const stop = () => {\n void server.close().then(() => process.exit(0));\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n } else {\n throw new Error(usage);\n }\n }\n} catch (cause) {\n console.error(cause instanceof Error ? cause.message : cause);\n process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,SAAgB,iBACd,OACA,SACA,QACA;CACA,IAAI,OAAO;CACX,IAAI;CACJ,eAAe,QAAQ,QAAgB;EACrC,IACG,MAAM,SAAS,OAAO,IAAI,MAAO,OAAO,QACxC,MAAM,SAA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CAAC,CAAC;OAC5D,IAAI,YAAY,SAAS;GAC9B,MAAM,SAAS,QAAQ,KAAK,MAAM,WAAW;GAC7C,MAAM,SAAS,MAAM,WAAW,OAAO,MAAM;GAC7C,QAAQ,IAAI,SAAS,OAAO,IAAI,OAAO,OAAO,OAAO,SAAS;EAChE,OAAO,IAAI,YAAY,OAAO;GAC5B,MAAM,OAAO,KAAK,OAAO,KAAA,IAAY,OAAO,OAAO,KAAK,EAAE;GAC1D,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MAAM,8CAA8C;GAChE,MAAM,SAAS,MAAM,UAAU,OAAO,IAAI;GAC1C,QAAQ,IAAI,YAAY,OAAO,KAAK;GACpC,MAAM,aAAa;IACjB,OAAY,MAAM,CAAC,CAAC,WAAW,QAAQ,KAAK,CAAC,CAAC;GAChD;GACA,QAAQ,KAAK,UAAU,IAAI;GAC3B,QAAQ,KAAK,WAAW,IAAI;EAC9B,OACE,MAAM,IAAI,MAAM,KAAK;CAEzB;AACF,SAAS,OAAO;CACd,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,KAAK;CAC5D,QAAQ,WAAW;AACrB"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../src/history.ts","../src/text-edit.ts","../src/visual-review.ts","../src/styles.ts","../src/page.ts","../src/agent-page.ts","../src/authoring-guidance.ts","../src/terminal.ts","../src/chat.ts","../src/server.ts","../src/cli.ts"],"sourcesContent":["import { lstat, mkdir, readFile, readdir, realpath, unlink, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\n\nconst SNAPSHOT_LIMIT = 64 * 1024 * 1024;\nconst HISTORY_LIMIT = 128 * 1024 * 1024;\nconst ENTRY_LIMIT = 50;\nconst ignored = new Set(['node_modules', '.git', 'dist', '.office-kit']);\nexport const historyFile = (name: string) =>\n !name.split(sep).some((part) => ignored.has(part)) &&\n /\\.([cm]?[jt]sx?|json|css|md|ya?ml|pptx|png|jpe?g|gif|bmp|tiff?|emf|wmf|svg)$/i.test(name);\ntype Snapshot = Map<string, Buffer>;\ntype Change = { file: string; before: Buffer | undefined; after: Buffer | undefined };\ntype Entry = { label: string; changes: Change[] };\nconst equal = (a?: Buffer, b?: Buffer) => a === b || (!!a && !!b && a.equals(b));\n\n/** Session-local project history. Overlapping agent turns form one transaction. */\nexport async function createHistory(directory: string, notify: () => void = () => {}) {\n const root = await realpath(directory);\n let baseline: Snapshot = new Map();\n let initialized = false;\n const past: Entry[] = [],\n future: Entry[] = [];\n const active = new Set<string>();\n let label = '';\n let error: string | null = null;\n let queue = Promise.resolve();\n let restoring = false;\n function serial<T>(action: () => Promise<T>): Promise<T> {\n const result = queue.then(action);\n queue = result.then(\n () => {},\n () => {},\n );\n return result\n .catch((cause) => {\n error = cause instanceof Error ? cause.message : String(cause);\n throw cause;\n })\n .finally(notify);\n }\n async function snapshot(): Promise<Snapshot> {\n const files = new Map<string, Buffer>();\n let bytes = 0;\n async function visit(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true });\n await Promise.all(\n entries.map(async (item) => {\n if (ignored.has(item.name) || item.isSymbolicLink()) return;\n const file = join(dir, item.name);\n if (item.isDirectory()) return visit(file);\n if (!item.isFile() || !historyFile(file)) return;\n const info = await lstat(file);\n bytes += info.size;\n if (bytes > SNAPSHOT_LIMIT)\n throw new Error(\n 'Undo history exceeds 64 MiB of project source/assets. Move unused assets outside the deck folder.',\n );\n if (info.isSymbolicLink() || (await realpath(file)) !== file)\n throw new Error('Project paths changed while recording history. Try again.');\n const content = await readFile(file);\n files.set(relative(root, file), content);\n }),\n );\n }\n await visit(root);\n return files;\n }\n function record(next: Snapshot, description: string) {\n if (!initialized) {\n baseline = next;\n initialized = true;\n error = null;\n return;\n }\n const changes: Change[] = [];\n for (const file of new Set([...baseline.keys(), ...next.keys()])) {\n const before = baseline.get(file),\n after = next.get(file);\n if (!equal(before, after)) changes.push({ file, before, after });\n }\n if (changes.length) {\n past.push({ label: description, changes });\n future.length = 0;\n const size = () =>\n past.reduce(\n (sum, item) =>\n sum +\n item.changes.reduce(\n (n, change) => n + (change.before?.length ?? 0) + (change.after?.length ?? 0),\n 0,\n ),\n 0,\n );\n while (past.length > ENTRY_LIMIT || (past.length > 1 && size() > HISTORY_LIMIT)) past.shift();\n }\n baseline = next;\n error = null;\n }\n async function contents(file: string): Promise<Buffer | undefined> {\n const path = join(root, file);\n let parent = dirname(path);\n while (true) {\n try {\n if ((await realpath(parent)) !== parent)\n throw new Error('Undo refused: a project directory is now a symbolic link.');\n break;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== 'ENOENT') throw cause;\n parent = dirname(parent);\n }\n }\n try {\n const info = await lstat(path);\n if (!info.isFile() || info.isSymbolicLink())\n throw new Error('Undo refused: a project file changed type.');\n return await readFile(path);\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw cause;\n }\n }\n async function replace(change: Change, expected?: Buffer, next?: Buffer) {\n if (!equal(await contents(change.file), expected))\n throw new Error(`History conflict in ${change.file}. Newer changes were preserved.`);\n const file = join(root, change.file);\n if (next) {\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, next);\n } else await unlink(file);\n }\n try {\n record(await snapshot(), 'Initial state');\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n }\n return {\n state: () => ({\n undo: past.at(-1)?.label ?? null,\n redo: future.at(-1)?.label ?? null,\n busy: active.size > 0 || restoring,\n error,\n }),\n capture: () =>\n serial(async () => {\n if (!active.size && !restoring) record(await snapshot(), 'Source edit');\n }),\n begin: (id: string, description: string) =>\n serial(async () => {\n if (active.has(id)) return;\n if (!active.size) {\n record(await snapshot(), 'Source edit');\n label = description;\n } else label = 'Concurrent edits';\n active.add(id);\n }),\n end: (id: string) =>\n serial(async () => {\n if (!active.delete(id) || active.size) return;\n record(await snapshot(), label);\n }),\n move: (direction: 'undo' | 'redo') =>\n serial(async () => {\n if (active.size)\n throw new Error(\n 'Wait for all agents and text edits to finish before using Undo or Redo.',\n );\n // A save made outside the preview is also an edit; never silently overwrite it.\n record(await snapshot(), 'Source edit');\n const from = direction === 'undo' ? past : future;\n const to = direction === 'undo' ? future : past;\n const item = from.at(-1);\n if (!item) throw new Error(`Nothing to ${direction}.`);\n const before = (c: Change) => (direction === 'undo' ? c.after : c.before);\n const after = (c: Change) => (direction === 'undo' ? c.before : c.after);\n const applied: Change[] = [];\n restoring = true;\n try {\n await Promise.all(\n item.changes.map(async (change) => {\n if (!equal(await contents(change.file), before(change)))\n throw new Error(\n `History conflict in ${change.file}. Newer changes were preserved.`,\n );\n }),\n );\n // Ordered writes let a failed transaction restore only the files it wrote.\n for (const change of item.changes) {\n await replace(change, before(change), after(change));\n applied.push(change);\n }\n for (const change of item.changes) {\n const content = after(change);\n if (content) baseline.set(change.file, content);\n else baseline.delete(change.file);\n }\n from.pop();\n to.push(item);\n error = null;\n } catch (cause) {\n const failures = [];\n for (const change of applied.reverse()) {\n try {\n await replace(change, after(change), before(change));\n } catch (rollback) {\n failures.push(String(rollback));\n }\n }\n if (failures.length)\n throw new Error(`${String(cause)}; rollback incomplete: ${failures.join('; ')}`);\n throw cause;\n } finally {\n restoring = false;\n }\n }),\n };\n}\n","import ts from 'typescript';\nimport { readFile, writeFile, realpath } from 'node:fs/promises';\nimport { dirname, relative, isAbsolute, extname } from 'node:path';\n\ninterface Preview {\n revision: number;\n slides: string[];\n slideTexts: string[];\n dependencies: string[];\n}\ninterface Change {\n file: string;\n before: string;\n after: string;\n}\n\n/** Literal edits are deliberately conservative: computed and ambiguous text goes to the agent. */\nexport function createTextEditor(\n entry: string,\n preview: () => Preview,\n verify: () => Promise<string | null>,\n) {\n let busy = false;\n async function restore(change: Change) {\n if (\n (await realpath(change.file)) !== change.file ||\n (await readFile(change.file, 'utf8')) !== change.after\n )\n throw new Error('Source changed during editing. Your newer changes were preserved.');\n await writeFile(change.file, change.before);\n }\n return {\n async edit(value: { revision: number; slide: number; before: string; after: string }) {\n if (busy) throw new Error('A text edit is already running.');\n busy = true;\n try {\n const current = preview();\n if (value.revision !== current.revision)\n throw new Error('Preview changed. Select the text again.');\n if (\n !Number.isInteger(value.slide) ||\n !current.slides[value.slide] ||\n typeof value.before !== 'string' ||\n !value.before.trim() ||\n value.before.length > 12000 ||\n typeof value.after !== 'string' ||\n value.after.length > 12000 ||\n value.after === value.before\n )\n throw new Error('Invalid text edit.');\n if (current.slideTexts[value.slide]!.split(value.before).length !== 2)\n throw new Error('Text cannot be located uniquely on this slide. Use Apply with AI.');\n const root = await realpath(dirname(entry));\n const files = await Promise.all(\n [...new Set(current.dependencies)]\n .filter((file) => /\\.[cm]?[jt]sx?$/.test(file))\n .map(async (file) => {\n const path = await realpath(file),\n local = relative(root, path);\n if (\n local.startsWith('..') ||\n isAbsolute(local) ||\n local.split(/[\\\\/]/).includes('node_modules')\n )\n return null;\n return { file: path, before: await readFile(path, 'utf8') };\n }),\n );\n const candidates: Change[] = [];\n for (const item of files) {\n if (!item) continue;\n const source = ts.createSourceFile(\n item.file,\n item.before,\n ts.ScriptTarget.Latest,\n true,\n /[jt]sx$/.test(extname(item.file)) ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n const visit = (node: ts.Node) => {\n const text = ts.isJsxText(node)\n ? node.text\n .split(/\\r\\n|\\n|\\r/)\n .map((line, index, lines) => {\n let value = line.replaceAll('\\t', ' ');\n if (index) value = value.trimStart();\n if (index < lines.length - 1) value = value.trimEnd();\n return value;\n })\n .filter(Boolean)\n .join(' ')\n : ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)\n ? node.text\n : undefined;\n if (text === value.before) {\n // Attribute strings use JSX entity rules, not JavaScript string escapes.\n const jsx = ts.isJsxText(node) || ts.isJsxAttribute(node.parent);\n const replacement = jsx\n ? '{' + JSON.stringify(value.after) + '}'\n : JSON.stringify(value.after);\n const start = ts.isJsxText(node) ? node.pos : node.getStart(source);\n candidates.push({\n ...item,\n after: item.before.slice(0, start) + replacement + item.before.slice(node.end),\n });\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n }\n if (candidates.length !== 1)\n throw new Error('Text is computed or has multiple source matches. Use Apply with AI.');\n const change = candidates[0]!;\n if (\n preview().revision !== current.revision ||\n (await realpath(change.file)) !== change.file ||\n (await readFile(change.file, 'utf8')) !== change.before\n )\n throw new Error('Source changed. Select the text again.');\n await writeFile(change.file, change.after);\n try {\n const error = await verify();\n if (error) throw new Error('The text change did not build.');\n const next = preview();\n if (\n next.slides.length !== current.slides.length ||\n next.slides.some(\n (svg, index) => index !== value.slide && svg !== current.slides[index],\n ) ||\n next.slideTexts[value.slide] !==\n current.slideTexts[value.slide]!.replace(value.before, value.after)\n )\n throw new Error(\n 'This source affects other text or slides. Use Apply with AI for a local edit.',\n );\n if (\n (await realpath(change.file)) !== change.file ||\n (await readFile(change.file, 'utf8')) !== change.after\n )\n throw new Error('Source changed during editing.');\n } catch (error) {\n await restore(change);\n await verify();\n throw error;\n }\n } finally {\n busy = false;\n }\n },\n };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { chromium, type Browser } from 'playwright';\n\nexport interface VisualReview {\n prompt: string;\n images: string[];\n}\n/** Each session compares against its own turn's preview, including offscreen slides. */\nexport function createVisualReviewer(entry: string, slides: () => string[]) {\n let before: string[] = [];\n let rounds = 0;\n return {\n begin() {\n before = slides().slice();\n rounds = 0;\n },\n async next(): Promise<VisualReview | undefined> {\n const current = slides().slice();\n const changed = current.flatMap((svg, index) =>\n svg !== before[index] ? [{ svg, index }] : [],\n );\n if (!changed.length) return;\n if (rounds >= 3)\n throw new Error(\n 'Visual review reached its correction limit. Review the latest slide manually before continuing.',\n );\n const round = rounds + 1;\n let browser: Browser;\n try {\n browser = await chromium.launch({\n channel: process.env.PLAYWRIGHT_CHANNEL || 'chrome',\n headless: true,\n });\n } catch {\n try {\n browser = await chromium.launch({ headless: true });\n } catch {\n throw new Error(\n 'Visual review needs Chrome or a Playwright Chromium installation. Install Chrome and retry. The source edit was saved; visual review was not completed.',\n );\n }\n }\n try {\n const directory = join(dirname(entry), '.office-kit', 'reviews', randomUUID());\n await mkdir(directory, { recursive: true });\n const page = await browser.newPage({\n viewport: { width: 1600, height: 1000 },\n deviceScaleFactor: 1,\n });\n // Decks may reference remote assets. Review must not make network requests or execute SVG scripts.\n await page.route('**/*', (route) => route.abort());\n const images: string[] = [];\n for (const { svg, index } of changed) {\n await page.setContent(\n '<meta http-equiv=\"Content-Security-Policy\" content=\"default-src \\'none\\'; style-src \\'unsafe-inline\\'; img-src data: blob:; font-src data:\"><style>html,body{margin:0}svg{display:block;width:1600px;height:auto}</style>' +\n svg,\n );\n await page.evaluate(() => document.fonts.ready.then(() => undefined));\n const file = join(directory, `slide-${index + 1}.png`);\n await page.locator('svg').first().screenshot({ path: file, timeout: 15000 });\n images.push(file);\n }\n const prompt = `Visual review after the edit (round ${round}/3). Open every attached screenshot (or read each local PNG path below) before finishing. Check clipping, overlap, alignment, spacing, legibility and foreground/background contrast. ${round === 3 ? 'This is the final review: do not edit further; report any remaining defects to the user.' : 'Fix concrete design defects only on these affected slides;'} preserve the user's exact text and unrelated work. Do not claim visual verification unless you inspected the images. If there are no defects, finish without edits. Screenshots: ${JSON.stringify(images)}`;\n await writeFile(join(directory, 'review.txt'), prompt);\n before = current;\n rounds = round;\n return { prompt, images };\n } finally {\n await browser.close();\n }\n },\n };\n}\n","export const previewStyles = `*{box-sizing:border-box}\nbody{margin:0;height:100dvh;overflow:hidden;background:#e9eaf4;color:#dce1f1;font:13px system-ui;display:grid;grid-template-rows:60px minmax(0,1fr) 42px}\nbutton,a,select{font:inherit;color:inherit}button,select,.download{border:1px solid #30364d;border-radius:9px;background:#191e30;padding:7px 12px;text-decoration:none;cursor:pointer}\nbutton:hover:not(:disabled),.download:hover{background:#292f48}button:disabled{opacity:.4;cursor:default}\n:focus-visible{outline:2px solid #9b87ff;outline-offset:3px}\nheader{display:flex;align-items:center;gap:16px;padding:0 20px;background:linear-gradient(110deg,#171b2f,#211c38 60%,#171b2f);border-bottom:1px solid #38304d;min-width:0}\n.brand{font-weight:700;font-size:17px;white-space:nowrap}.badge{font-size:11px;color:#b2a4fb;background:#342c54;border-radius:4px;padding:3px 6px}\n#status{flex:1;color:#9ba5be;min-width:0}#present{background:#7154e8;color:#191e30;border-color:#7154e8}\n.workspace{--filmstrip-width:190px;--chat-width:38vw;display:grid;grid-template-columns:var(--filmstrip-width) minmax(0,1fr) clamp(280px,var(--chat-width),calc(100vw - var(--filmstrip-width) - 240px));min-height:0}\n.filmstrip{background:#111625;border-right:1px solid #30364d;overflow:auto;overscroll-behavior:contain;padding:16px 12px}\n.filmstrip h2{margin:0 0 12px 26px;text-transform:uppercase;letter-spacing:.1em;font-size:10px;color:#8490ac;font-weight:600}\n#thumbnails{display:flex;flex-direction:column;gap:12px;margin:0;padding:0;list-style:none}\n.thumbnail{display:flex;align-items:flex-start;gap:8px;width:100%;padding:4px 3px;border:0;background:transparent;border-radius:5px;text-align:left}\n.slide-number{width:18px;flex:none;text-align:right;font-size:11px;color:#8995b0;padding-top:5px}\n.thumbnail img{display:block;min-width:0;width:calc(100% - 26px);background:white;box-shadow:0 1px 4px #080b1933;border:2px solid transparent;border-radius:3px;aspect-ratio:var(--slide-ratio,16/9);object-fit:contain}\n.thumbnail[aria-current=\"true\"]{background:#31274e}.thumbnail[aria-current=\"true\"] img{border-color:#9b87ff}.thumbnail[aria-current=\"true\"] .slide-number{color:#b6a5ff;font-weight:700}\nmain{min-width:0;min-height:0;display:flex;flex-direction:column}\n#error{flex:none;max-height:30%;overflow:auto;background:#fff0ef;color:#922e25;margin:0;padding:16px 20px;white-space:pre-wrap;border-bottom:1px solid #e8bbb7}\n#error[hidden]{display:none}\n#stage{background:radial-gradient(ellipse at 20% 15%,#ddd8f6aa,transparent 65%),radial-gradient(#a0a4bf33 1px,transparent 1px),#edeef6;background-size:auto,18px 18px,auto;flex:1;min-height:0;overflow:auto;display:flex;padding:32px;overscroll-behavior:contain}\n#slide{position:relative;flex:none;margin:auto;background:white;box-shadow:0 20px 70px #28234825,0 2px 8px #28234815;overflow:hidden}\n#slide{user-select:text;-webkit-user-select:text}\n#empty{margin:auto;color:#8995b0}\nfooter{display:flex;align-items:center;gap:14px;padding:0 16px;background:#191e30;border-top:1px solid #30364d;font-size:12px}\n#count{min-width:90px}footer .hint{flex:1;color:#8995b0}footer button{padding:3px 10px}footer select{padding:3px 8px}\n#presentation-controls{display:none}\nbody.presenting{grid-template-rows:minmax(0,1fr);background:#111}\n.presenting header,.presenting footer,.presenting .filmstrip,.presenting #chat{display:none}\n.presenting .workspace{grid-template-columns:minmax(0,1fr)}.presenting #stage{padding:0;background:#111}.presenting #slide{box-shadow:none}\n.presenting #presentation-controls{display:flex;position:fixed;bottom:16px;left:50%;transform:translateX(-50%);align-items:center;gap:12px;background:#202735e8;color:white;padding:6px;border-radius:8px;opacity:0;transition:opacity .15s}\n.presenting #presentation-controls:hover,.presenting #presentation-controls:focus-within{opacity:1}\n#presentation-controls button{background:transparent;color:white;border-color:#5d6575}\n@media(max-width:700px){.workspace{grid-template-columns:140px minmax(0,1fr)}.filmstrip{padding:12px 5px}header{padding:0 12px;gap:10px}.badge,footer .hint{display:none}#stage{padding:16px}footer{gap:8px}#status{font-size:11px}.download{padding:7px 8px}}\n#chat{position:relative;min-width:0;min-height:0;display:flex;flex-direction:column;background:#191e30;border-left:1px solid #30364d}\n#chat-resizer{position:absolute;left:-5px;top:0;bottom:0;width:10px;z-index:3;cursor:col-resize;touch-action:none}#chat-resizer::after{content:\"\";position:absolute;left:4px;top:0;bottom:0;width:2px}#chat-resizer:hover::after,#chat-resizer:focus-visible::after,.resizing-chat #chat-resizer::after{background:#9b87ff}body.resizing-chat,body.resizing-chat *{cursor:col-resize!important;user-select:none!important}\n.chat-heading{display:flex;align-items:center;gap:8px;padding:16px;border-bottom:1px solid #2a3046}.chat-heading strong{flex:1}.chat-heading button{padding:5px 8px}\n#messages{flex:1;overflow:auto;padding:16px;display:flex;flex-direction:column;gap:16px;overscroll-behavior:contain}\n.chat-message{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}.chat-message.user{background:#302752;border-radius:8px;padding:10px 12px}.chat-message small{display:block;color:#a4afc6;font-size:11px;margin-bottom:4px}.chat-intro{color:#8995b0;line-height:1.7}\n#chat-form{padding:14px;border-top:1px solid #2a3046}#chat-context{font-size:11px;color:#9b87ff;margin-bottom:8px}#chat-input{font:inherit;resize:vertical;min-height:90px;max-height:200px;width:100%;padding:10px;border:1px solid #30364d;border-radius:8px} .chat-actions{display:flex;gap:8px;margin-top:8px;align-items:center}.chat-actions select{min-width:0;flex:1}#chat-send{background:#7154e8;color:white}#chat-status{padding:0 14px 12px;color:#9ba5be;font-size:11px;white-space:pre-wrap;max-height:90px;overflow:auto}\nbody.chat-hidden .workspace{grid-template-columns:190px minmax(0,1fr)}body.chat-hidden #chat{display:none}\nbody.presenting .workspace{grid-template-columns:minmax(0,1fr)}\n@media(max-width:1000px){.workspace{--filmstrip-width:120px;--chat-width:380px}.filmstrip{padding:12px 5px}#stage{padding:16px}}\n@media(max-width:700px){#chat-resizer{display:none}.workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(160px,1fr) minmax(200px,1fr)}.filmstrip{display:none}#chat{border-top:1px solid #30364d}.chat-heading{padding:8px 12px}#chat-form{padding:8px 12px}#chat-input{min-height:50px}body.chat-hidden .workspace,.presenting .workspace{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}.brand{font-size:14px}header{gap:6px}.download{font-size:11px}}\n@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}\n\n[hidden]{display:none!important}\n.chat-heading{padding:10px 14px}.chat-heading select{flex:1;min-width:0;font-weight:600;border:0;padding-left:0}\n#chat-context{margin:0;padding:8px 14px;border-bottom:1px solid #2a3046;color:#9ba5be;font-size:11px}\n#claude-panel,#codex-panel{display:flex;flex-direction:column;flex:1;min-height:0}\n#claude-panel{background:#171b24;color:#e4e8f0}\n.terminal-toolbar{display:flex;align-items:center;gap:8px;padding:8px 12px;font-size:11px;min-height:40px}.terminal-toolbar span{flex:1;overflow-wrap:anywhere}.terminal-toolbar button{font-size:11px;padding:5px 8px;background:#262d3b;border-color:#45516a;color:#e4e8f0}\n.terminal-toolbar button:hover:not(:disabled){background:#35415a}\n#terminal{flex:1;min-height:0;overflow:hidden;padding:0}.xterm{height:100%}\n#chat-input{min-height:70px;resize:vertical}.chat-shortcut{flex:1;color:#9098a7;font-size:10px}\n.markdown{white-space:normal;line-height:1.65}.markdown>:first-child{margin-top:0}.markdown>:last-child{margin-bottom:0}.markdown p{margin:0 0 .8em}.markdown pre{overflow:auto;padding:10px;background:#22283b;border:1px solid #2a3046;border-radius:6px;white-space:pre}.markdown code{font-size:.9em;background:#22283b;border-radius:3px;padding:1px 4px}.markdown pre code{padding:0}.markdown ul,.markdown ol{padding-left:22px}.markdown blockquote{margin-left:0;padding-left:12px;border-left:3px solid #30364d;color:#9ba5be}.markdown table{display:block;overflow:auto;border-collapse:collapse}.markdown th,.markdown td{padding:6px 8px;border:1px solid #30364d}.markdown h1,.markdown h2,.markdown h3{font-size:1.1em}.markdown a{color:#b6a5ff;text-decoration:underline}\n\n.brand{display:flex;align-items:center;gap:10px;letter-spacing:-.5px}.brand svg{width:32px;height:32px;flex:none}.brand em{font-style:normal;font-weight:400;color:#aca4ce}.badge{text-transform:uppercase;letter-spacing:.14em;font-size:9px;border:1px solid #61508866;border-radius:5px}#status{font-size:11px}#present,#chat-send{color:#fff;background:linear-gradient(120deg,#8061ed,#634de0);border-color:#a38aef55;box-shadow:0 3px 15px #7455e82a}#toggle-chat[aria-expanded=\"true\"]{background:#35294f;border-color:#6f528b;color:#d6c5ff}.download{background:transparent;color:#bcc5dc}header button,header .download{font-size:12px}.filmstrip{background:linear-gradient(180deg,#161b2c,#111625)}.thumbnail{transition:background .15s}.thumbnail[aria-current=\"true\"]{box-shadow:inset 0 0 0 1px #9980ef33}.thumbnail[aria-current=\"true\"] img{box-shadow:0 0 16px #9567ed22}footer{background:#141929;color:#b9c2d8}footer .hint{font-size:10px}#count{font-size:11px;font-weight:600}#chat{background:#101422}.workspace-heading{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;color:#c7bee5;font-size:10px;font-weight:600;letter-spacing:.12em}.workspace-heading b{font-size:9px;color:#89cdbc;font-weight:500;letter-spacing:.08em}.workspace-heading b::before{content:\"\";display:inline-block;width:5px;height:5px;background:#86d5bb;border-radius:50%;margin-right:6px;box-shadow:0 0 8px #86d5bb66}.chat-heading{background:#191e30}.chat-heading select{background:transparent;color:#e4e5f3;font-size:12px}.chat-heading option{background:#191e30}#chat-context{background:#1a1e30;color:#a59abb;font-size:10px}.terminal-toolbar{gap:6px;padding:8px;font-size:10px}.terminal-toolbar button{white-space:nowrap}#terminal-start{background:#6c52c9;border-color:#9678e9}.terminal-frame{display:flex;flex:1;min-height:0;min-width:0;padding:4px 8px 8px;overflow:hidden}#terminal{width:100%;min-width:0}#chat-input{color:#e2e5f3;background:#131827;border-color:#3b3f58}#chat-input:focus{outline:none;border-color:#9b87ff;box-shadow:0 0 0 3px #9b87ff18}.chat-message.user{border:1px solid #67509655}.chat-intro{font-size:12px}.markdown pre{border-color:#3a4059}.markdown code{color:#d2c6fa}#error{background:#38242b;color:#ffb8b0}\n@media(max-width:700px){.brand svg{width:26px;height:26px}.brand{gap:6px}.workspace-heading{padding:7px 12px}header .download{font-size:10px;padding:7px}.badge{display:none}}\n`;\n","import { previewStyles } from './styles.ts';\nexport const page = `<!doctype html>\n<html lang=\"en\">\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\">\n<title>Office Kit — PowerPoint preview</title>\n<link rel=\"stylesheet\" href=\"/terminal.css\">\n<style>\n${previewStyles}\n.slide-edit-tools{display:flex;gap:6px;padding:8px 14px;flex-shrink:0}.slide-edit-tools{align-items:center;flex-wrap:wrap}.slide-edit-tools span{font-size:11px;color:#625873;flex:1}.slide-edit-tools small{font-size:11px;color:#634396}.slide-hover{position:fixed;border:1px solid #b094ff;pointer-events:none;z-index:19;border-radius:2px}.slide-text-input{position:fixed;z-index:22;resize:none;background:#202438;color:#fff;border:2px solid #b094ff;border-radius:3px;padding:0;box-shadow:0 0 0 3px #b094ff30;line-height:1.15}.slide-text-input[hidden],.slide-hover[hidden]{display:none}.slide-selection{position:fixed;border:2px solid #b094ff;background:#a080ff18;pointer-events:none;z-index:20;box-shadow:0 0 0 1px #201632}.slide-edit-panel{position:fixed;z-index:21;width:min(380px,calc(100vw - 16px));padding:14px;background:#202438;border:1px solid #776591;border-radius:14px;box-shadow:0 16px 50px #0008;display:flex;flex-direction:column;gap:12px}.slide-edit-panel[hidden],.slide-selection[hidden]{display:none}.selection-heading,.selection-actions{display:flex;align-items:center;gap:8px}.selection-heading strong{flex:1}.slide-edit-panel textarea{width:100%;min-height:90px;max-height:35vh;resize:vertical;background:#141a2b;color:#f4efff;border:1px solid #514969;border-radius:8px;padding:10px;font:inherit}.selection-actions{flex-wrap:wrap}.selection-actions select{min-width:80px;flex:1}.slide-edit-panel small{color:#d1c9e3;line-height:1.5}.presenting .slide-edit-tools{display:none}\n\n#agent-workspace{position:relative;flex:1;min-height:0;min-width:0;display:flex;overflow:auto}.agent-pane{position:absolute;padding:3px 5px;display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}.agent-pane iframe{border:0;width:100%;flex:1;min-height:0;border-radius:0 0 9px 9px}.agent-tools{display:flex;gap:4px;align-items:center;flex-wrap:wrap;padding:6px;background:#20253a;border:1px solid #34334e;border-radius:9px 9px 0 0}.agent-tools span{flex:1;font-size:10px;letter-spacing:.04em;color:#b3abc9}.agent-tools svg{width:14px;height:14px}.agent-pane:focus-within .agent-tools{border-color:#8b6ed577;background:#29243e}.agent-tools button{font-size:11px;padding:5px;background:transparent;border:0;display:grid;place-items:center}.agent-divider{position:absolute;z-index:2;background:#101422;cursor:col-resize;touch-action:none}.agent-divider.vertical{cursor:row-resize}.agent-divider:hover,.agent-divider:focus-visible{background:#9b87ff}.splitting-agents iframe,.resizing-chat iframe{pointer-events:none}\n</style>\n<header><span class=\"brand\"><svg viewBox=\"0 0 36 36\" aria-hidden=\"true\"><defs><linearGradient id=\"brand-gradient\" x2=\"1\" y2=\"1\"><stop stop-color=\"#c39aff\"/><stop offset=\"1\" stop-color=\"#7165f4\"/></linearGradient></defs><rect x=\"2\" y=\"2\" width=\"32\" height=\"32\" rx=\"10\" fill=\"url(#brand-gradient)\"/><path d=\"M11 10h9l6 6v10H11z\" fill=\"none\" stroke=\"white\" stroke-width=\"1.8\" stroke-linejoin=\"round\"/><path d=\"M20 10v7h6M15 21h7M15 25h4\" fill=\"none\" stroke=\"white\" stroke-width=\"1.8\" stroke-linecap=\"round\"/><path d=\"m28 3 1.2 3.8L33 8l-3.8 1.2L28 13l-1.2-3.8L23 8l3.8-1.2z\" fill=\"#e7dbff\"/></svg>Office <em>Kit</em></span><span class=\"badge\">Studio</span><span id=\"status\" role=\"status\">Building…</span><button id=\"toggle-chat\" aria-expanded=\"true\" aria-controls=\"chat\">✦ Agents</button><button id=\"present\" disabled>Present</button><a class=\"download\" href=\"/deck.pptx\">Download PPTX</a></header>\n<div class=\"workspace\">\n<nav class=\"filmstrip\" aria-label=\"Slides\"><h2>Slides</h2><ol id=\"thumbnails\"></ol></nav>\n<main aria-label=\"Slide viewer\"><pre id=\"error\" role=\"alert\" hidden></pre><div id=\"stage\" tabindex=\"-1\"><div id=\"empty\">Waiting for slides…</div><div id=\"slide\" hidden></div></div></main>\n<aside id=\"chat\" aria-label=\"Slide chat\">\n<div id=\"chat-resizer\" role=\"separator\" tabindex=\"0\" aria-label=\"Chat width\" aria-orientation=\"vertical\" aria-controls=\"chat\" title=\"Drag to resize · Double-click to reset\"></div>\n<div class=\"workspace-heading\"><span>✦ AI WORKSPACE</span><b>LOCAL</b></div><div id=\"agent-workspace\"></div><div id=\"chat-context\" hidden></div></aside>\n</div>\n<footer><span id=\"count\" aria-live=\"polite\">No slides</span><span class=\"hint\">Select an area to ask AI · Edit text directly</span><button id=\"prev\" aria-label=\"Previous slide\" disabled>‹</button><button id=\"next\" aria-label=\"Next slide\" disabled>›</button><label for=\"zoom\">Zoom</label><select id=\"zoom\"><option value=\"fit\">Fit</option><option value=\"0.5\">50%</option><option value=\"0.75\">75%</option><option value=\"1\">100%</option><option value=\"1.25\">125%</option><option value=\"1.5\">150%</option><option value=\"2\">200%</option></select></footer>\n<div id=\"presentation-controls\"><button id=\"present-prev\" aria-label=\"Previous slide\">‹</button><span id=\"present-count\"></span><button id=\"present-next\" aria-label=\"Next slide\">›</button><button id=\"exit-present\">Exit · Esc</button></div>\n<script>\nlet state={slides:[],error:null,aspectRatio:16/9},index=0,urls=[],presenting=false;\nlet displayedSvg;\nconst byId=id=>document.getElementById(id);\nconst stage=byId('stage'),slide=byId('slide'),thumbnails=byId('thumbnails');\nconst workspace=document.querySelector('.workspace'),chatResizer=byId('chat-resizer');\nconst chatWidthKey='office-kit-chat-width',minChatWidth=280,minStageWidth=240;\nfunction chatWidthLimits(){return {min:minChatWidth,max:Math.max(minChatWidth,workspace.clientWidth-document.querySelector('.filmstrip').getBoundingClientRect().width-minStageWidth)};}\nfunction updateChatWidthAria(){\n const {min,max}=chatWidthLimits();\n chatResizer.setAttribute('aria-valuemin',String(min));chatResizer.setAttribute('aria-valuemax',String(Math.round(max)));\n const width=Math.round(byId('chat').getBoundingClientRect().width);\n chatResizer.setAttribute('aria-valuenow',String(width));chatResizer.setAttribute('aria-valuetext',width+' pixels');\n}\nfunction setChatWidth(width){const {min,max}=chatWidthLimits();workspace.style.setProperty('--chat-width',Math.min(max,Math.max(min,width))+'px');}\nfunction saveChatWidth(){try{const width=workspace.style.getPropertyValue('--chat-width');if(width)localStorage.setItem(chatWidthKey,String(parseFloat(width)));else localStorage.removeItem(chatWidthKey);}catch(error){console.warn('Could not save chat width',error);}}\ntry{const saved=Number(localStorage.getItem(chatWidthKey));if(Number.isFinite(saved)&&saved>=minChatWidth)workspace.style.setProperty('--chat-width',saved+'px');}catch(error){console.warn('Could not restore chat width',error);}\nlet chatDrag=null;\nchatResizer.onpointerdown=event=>{\n if(event.button!==0||!event.isPrimary)return;\n event.preventDefault();chatResizer.focus();chatDrag={id:event.pointerId,x:event.clientX,width:byId('chat').getBoundingClientRect().width};\n chatResizer.setPointerCapture(event.pointerId);document.body.classList.add('resizing-chat');\n};\nchatResizer.onpointermove=event=>{if(chatDrag?.id===event.pointerId)setChatWidth(chatDrag.width+chatDrag.x-event.clientX);};\nfunction finishChatResize(){if(!chatDrag)return;chatDrag=null;document.body.classList.remove('resizing-chat');saveChatWidth();}\nchatResizer.onpointerup=finishChatResize;chatResizer.onpointercancel=finishChatResize;chatResizer.onlostpointercapture=finishChatResize;\nchatResizer.ondblclick=()=>{workspace.style.removeProperty('--chat-width');saveChatWidth();};\nchatResizer.onkeydown=event=>{\n const {min,max}=chatWidthLimits(),width=byId('chat').getBoundingClientRect().width,step=event.shiftKey?50:10;\n let next;\n if(event.key==='ArrowLeft')next=width+step;else if(event.key==='ArrowRight')next=width-step;else if(event.key==='Home')next=min;else if(event.key==='End')next=max;else return;\n event.preventDefault();event.stopPropagation();setChatWidth(next);saveChatWidth();\n};\nnew ResizeObserver(updateChatWidthAria).observe(byId('chat'));\n\n// The slide lives in a shadow root rather than a sandboxed iframe so its text\n// (XHTML inside <foreignObject>) can be selected and copied while the deck's\n// SVG stays out of the viewer's own DOM and CSS. Keyboard events still reach the\n// document, so arrow-key navigation keeps working after clicking into a slide.\nconst canvas=slide.attachShadow({mode:'open'});\nfunction resize(){\n if(!state.slides.length)return;\n const style=getComputedStyle(stage);\n const width=Math.max(1,stage.clientWidth-parseFloat(style.paddingLeft)-parseFloat(style.paddingRight));\n const height=Math.max(1,stage.clientHeight-parseFloat(style.paddingTop)-parseFloat(style.paddingBottom));\n const ratio=state.aspectRatio;\n const zoom=byId('zoom').value;\n const slideWidth=presenting||zoom==='fit'?Math.min(width,height*ratio):1280*Number(zoom);\n slide.style.width=slideWidth+'px';slide.style.height=slideWidth/ratio+'px';\n}\nfunction selectSlide(next,focusThumbnail=false,reveal=true){\n index=Math.max(0,Math.min(next,state.slides.length-1));\n const count=state.slides.length?'Slide '+(index+1)+' of '+state.slides.length:'No slides';\n byId('chat-context').textContent=state.slides.length?count:'Whole project';\n byId('chat-context').dataset.focus=JSON.stringify({slide:state.slides.length?index:null,revision:state.revision??0});\n window.dispatchEvent(new Event('agent-focus'));\n byId('count').textContent=count;byId('present-count').textContent=count;\n for(const id of ['prev','present-prev'])byId(id).disabled=index===0;\n for(const id of ['next','present-next'])byId(id).disabled=index>=state.slides.length-1;\n byId('present').disabled=!state.slides.length;\n byId('zoom').disabled=!state.slides.length;\n slide.hidden=!state.slides.length;byId('empty').hidden=!!state.slides.length;\n const svg=state.slides[index];\n if(svg!==displayedSvg){\n displayedSvg=svg;\n canvas.innerHTML=svg?'<style>svg{display:block;width:100%;height:100%}</style>'+svg:'';\n }\n slide.setAttribute('aria-label','Slide '+(index+1));\n for(const [position,item] of Array.from(thumbnails.children).entries()){\n const button=item.firstElementChild,selected=position===index;\n button.setAttribute('aria-current',String(selected));button.tabIndex=selected?0:-1;\n if(selected){if(reveal)button.scrollIntoView({block:'nearest'});if(focusThumbnail)button.focus({preventScroll:true});}\n }\n resize();\n}\nfunction update(updated){\n const focusedThumbnail=thumbnails.contains(document.activeElement);\n const previous=state;\n state=updated;\n byId('status').textContent=state.error?'Build failed · showing last successful output':state.building?'Updating…':state.slides.length+' slides · Live';\n byId('error').textContent=state.error||'';byId('error').hidden=!state.error;\n document.documentElement.style.setProperty('--slide-ratio',String(state.aspectRatio));\n for(let i=state.slides.length;i<urls.length;i++){\n URL.revokeObjectURL(urls[i]);thumbnails.lastElementChild.remove();\n }\n urls.length=state.slides.length;\n state.slides.forEach((svg,i)=>{\n if(svg===previous.slides[i])return;\n const oldUrl=urls[i];\n urls[i]=URL.createObjectURL(new Blob([svg],{type:'image/svg+xml'}));\n let item=thumbnails.children[i];\n if(!item){\n item=document.createElement('li');\n const button=document.createElement('button'),number=document.createElement('span'),image=document.createElement('img');\n button.className='thumbnail';button.setAttribute('aria-label','Slide '+(i+1));button.onclick=()=>selectSlide(i,true);\n number.className='slide-number';number.textContent=String(i+1);\n image.alt='';image.draggable=false;image.loading='lazy';\n button.append(number,image);item.append(button);thumbnails.append(item);\n }\n item.querySelector('img').src=urls[i];\n if(oldUrl)URL.revokeObjectURL(oldUrl);\n });\n selectSlide(index,focusedThumbnail,false);\n if(!state.slides.length&&presenting)void exitPresentation();\n}\nfunction setPresenting(value){\n presenting=value;document.body.classList.toggle('presenting',value);resize();\n if(value)stage.focus();else{\n byId('present').focus();\n thumbnails.children[index]?.firstElementChild.scrollIntoView({block:'nearest'});\n }\n}\nasync function exitPresentation(){\n setPresenting(false);\n if(document.fullscreenElement)await document.exitFullscreen();\n}\nbyId('present').onclick=async()=>{\n setPresenting(true);\n try{await document.documentElement.requestFullscreen();}\n catch{byId('exit-present').textContent='Exit view · Esc';}\n};\nbyId('exit-present').onclick=exitPresentation;\ndocument.addEventListener('fullscreenchange',()=>{if(!document.fullscreenElement&&presenting)setPresenting(false);});\nfor(const id of ['prev','present-prev'])byId(id).onclick=()=>selectSlide(index-1);\nfor(const id of ['next','present-next'])byId(id).onclick=()=>selectSlide(index+1);\nbyId('zoom').onchange=resize;\nstage.onclick=()=>{if(presenting&&!getSelection().toString())selectSlide(index+1);};\ndocument.addEventListener('keydown',event=>{\n if(event.key==='Escape'&&presenting){event.preventDefault();void exitPresentation();return;}\n if(event.altKey||event.ctrlKey||event.metaKey||event.target.closest('select,input,textarea,[contenteditable]'))return;\n let next=index;\n if(['ArrowLeft','ArrowUp','PageUp'].includes(event.key))next--;\n else if(['ArrowRight','ArrowDown','PageDown'].includes(event.key))next++;\n else if(event.key==='Home')next=0;\n else if(event.key==='End')next=state.slides.length-1;\n else if(event.key===' '&&presenting&&!event.target.closest('button,a'))next+=event.shiftKey?-1:1;\n else return;\n event.preventDefault();selectSlide(next,thumbnails.contains(document.activeElement));\n});\nnew ResizeObserver(resize).observe(stage);\nlet refreshId=0;\nasync function refresh(){\n const id=++refreshId;\n try{const response=await fetch('/state'+(state.revision===undefined?'':'?since='+state.revision));if(!response.ok)throw new Error('Preview unavailable');const updated=await response.json();if(id===refreshId){if(updated.changes){updated.slides=state.slides.slice(0,updated.count);updated.slides.length=updated.count;for(const [position,svg] of Object.entries(updated.changes))updated.slides[Number(position)]=svg;}update(updated);}}\n catch{if(id===refreshId)byId('status').textContent='Reconnecting…';}\n}\nbyId('toggle-chat').onclick=()=>{const hidden=document.body.classList.toggle('chat-hidden');byId('toggle-chat').setAttribute('aria-expanded',String(!hidden));resize();};\nconst events=new EventSource('/events');events.onmessage=event=>{if(event.data==='history'){window.dispatchEvent(new Event('agent-history'));return;}if(event.data==='chat'){window.dispatchEvent(new Event('agent-chat'));return;}if(event.data==='ready'){delete state.revision;}void refresh();};events.onerror=()=>{byId('status').textContent='Reconnecting…'};refresh();\n</script><script type=\"module\" src=\"/terminal.js\"></script></html>`;\n","import { previewStyles } from './styles.ts';\nexport const agentPage = `<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><link rel=\"stylesheet\" href=\"/terminal.css\"><style>${previewStyles}\nbody{display:flex;flex-direction:column;background:#191e30;height:100dvh;min-width:0;overflow:auto;overflow-x:hidden} .chat-heading{flex-wrap:wrap} .chat-heading select{min-width:100px}.chat-heading,#chat-context{flex-shrink:0}#claude-panel{min-height:100px}#codex-panel{min-height:240px}\n</style><div class=\"chat-heading\"><select id=\"chat-provider\" aria-label=\"AI provider\"><option value=\"claude\">Claude Code</option><option value=\"codex\">Codex</option></select><button id=\"chat-reset\" hidden>New chat</button></div>\n<div id=\"chat-context\">No slide selected</div>\n<section id=\"claude-panel\" aria-label=\"Claude Code terminal\"><div class=\"terminal-toolbar\"><span id=\"terminal-status\" role=\"status\">Start Claude Code to edit your slides.</span><button id=\"terminal-start\">Start</button><button id=\"terminal-stop\" hidden>End session</button></div><div class=\"terminal-frame\"><div id=\"terminal\"></div></div></section>\n<div id=\"codex-panel\" hidden>\n<div id=\"messages\" role=\"log\" aria-label=\"Conversation\"><p class=\"chat-intro\">Describe what you want to change. The current slide is included automatically. You can also ask about other slides or the whole deck.<br><br>Uses your locally installed Codex. Sign in through its CLI first. Sending a message allows it to edit this project.</p></div>\n<form id=\"chat-form\"><textarea id=\"chat-input\" aria-label=\"Message\" maxlength=\"16000\" placeholder=\"Ask for a change…\" required></textarea><div class=\"chat-actions\"><span class=\"chat-shortcut\">⌘ / Ctrl + Enter</span><button id=\"chat-stop\" type=\"button\" hidden>Stop</button><button id=\"chat-send\" type=\"submit\">Send</button></div></form>\n<div id=\"chat-status\" role=\"status\">Ready</div>\n</div>\n<script>\nconst byId=id=>document.getElementById(id),base=location.pathname;\nlet focus={slide:null,revision:0};\nwindow.addEventListener('message',event=>{\n if(event.origin!==location.origin||event.source!==parent)return;\n if(event.data?.type==='focus'){focus=event.data.focus;byId('chat-context').dataset.focus=JSON.stringify(focus);byId('chat-context').textContent=event.data.label;}\n if(event.data?.type==='chat')void refreshChat();\n if(event.data?.type==='inline-edit'&&byId('chat-provider').value==='codex'){\n void (async()=>{try{if(chatBusy)throw new Error('This agent is working. Wait for it to finish.');await chatAction('/chat',{message:event.data.message,provider:'codex',...event.data.focus});parent.postMessage({type:'inline-result',id:event.data.id},location.origin);}catch(error){parent.postMessage({type:'inline-result',id:event.data.id,error:error.message},location.origin);}})();\n }\n\n});\nparent.postMessage({type:'agent-ready'},location.origin);\nlet chatRequest=0,chatBusy=false,lastMessages='';\nfunction renderChat(chat){\n chatBusy=chat.running;\n byId('chat-send').disabled=chat.running;\n byId('chat-reset').disabled=chat.running;\n if(byId('chat-provider').value==='codex')byId('chat-provider').disabled=chat.running;\n byId('chat-stop').hidden=!chat.running;\n byId('chat-status').textContent=chat.status;\n\n const serialized=JSON.stringify(chat.messages);\n if(serialized===lastMessages)return;\n lastMessages=serialized;\n const log=byId('messages'),atBottom=log.scrollHeight-log.scrollTop-log.clientHeight<60;\n log.replaceChildren();\n if(!chat.messages.length){const intro=document.createElement('p');intro.className='chat-intro';intro.textContent='Ask for a focused slide edit or a change across the deck. Uses your locally installed CLI and its login. Sending allows edits to this project.';log.append(intro);}\n for(const message of chat.messages){\n const item=document.createElement('div'),label=document.createElement('small'),body=document.createElement('div');\n item.className='chat-message '+message.role;\n label.textContent=message.role==='user'?'You · '+(message.context?.slide?'Slide '+message.context.slide:'Whole project'):'Assistant';\n if(message.role==='assistant'&&message.html){body.className='markdown';body.innerHTML=message.html;}else body.textContent=message.text||(chat.running?'Working…':'No response');item.append(label,body);log.append(item);\n }\n if(atBottom)log.scrollTop=log.scrollHeight;\n}\nasync function refreshChat(){\n const id=++chatRequest;\n try{const response=await fetch(base+'/chat');if(!response.ok)throw new Error('Chat unavailable');const chat=await response.json();if(id===chatRequest)renderChat(chat);}\n catch(error){if(id===chatRequest)byId('chat-status').textContent=error.message;}\n}\nasync function chatAction(path,payload){\n ++chatRequest;\n const response=await fetch(base+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});\n const result=await response.json();if(!response.ok)throw new Error(result.error||'Chat request failed');\n await refreshChat();\n}\nbyId('chat-form').onsubmit=async event=>{\n event.preventDefault();if(chatBusy)return;\n const input=byId('chat-input'),message=input.value.trim();if(!message)return;\n chatBusy=true;byId('chat-send').disabled=true;\n try{await chatAction('/chat',{message,provider:byId('chat-provider').value,...focus});if(input.value.trim()===message)input.value='';}\n catch(error){byId('chat-status').textContent=error.message;chatBusy=false;byId('chat-send').disabled=false;}\n};\nbyId('chat-input').onkeydown=event=>{if(event.key==='Enter'&&(event.metaKey||event.ctrlKey)&&!event.isComposing){event.preventDefault();byId('chat-form').requestSubmit();}};\nfor(const action of ['stop','reset'])byId('chat-'+action).onclick=()=>chatAction('/chat/'+action,{}).catch(error=>{byId('chat-status').textContent=error.message;});\nbyId('chat-provider').onchange=()=>{try{sessionStorage.setItem('office-kit-provider'+base,byId('chat-provider').value);}catch{}const claude=byId('chat-provider').value==='claude';byId('claude-panel').hidden=!claude;byId('codex-panel').hidden=claude;byId('chat-reset').hidden=claude;};\ntry{byId('chat-provider').value=sessionStorage.getItem('office-kit-provider'+base)||'claude';}catch{}\nbyId('chat-provider').onchange();\nvoid refreshChat();\n</script><script type=\"module\" src=\"/terminal.js\"></script></html>`;\n","/** Shared guidance for agents editing a deck through the preview. */\nexport const authoringGuidance = `For lists and tables of contents, use Text paragraphs/bullets or mapped Text rows. Bullets and TableOfContents are not built-in DSL components: inspect installed exports, import existing local helpers or define them. Do not use Raw for these layouts.\nChoose foreground and actual background colors together. Explicitly set readable text colors on slides, cards, tables, chart labels and footnotes; check inherited theme styles. Aim for 4.5:1 contrast for normal text and 3:1 for large text (18pt or 14pt bold). Use a solid backing over images or gradients if needed. Inspect rendered slides; compilation alone cannot verify contrast.`;\n","import type { VisualReview } from './visual-review.ts';\nimport { authoringGuidance } from './authoring-guidance.ts';\nimport { randomBytes } from 'node:crypto';\nimport { dirname, resolve, join } from 'node:path';\nimport { createRequire } from 'node:module';\nimport { stat, chmod } from 'node:fs/promises';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { IPty } from 'node-pty';\nimport type { FocusContext } from './chat.ts';\n\nconst OUTPUT_LIMIT = 2_000_000;\nconst REQUEST_LIMIT = 128_000;\n\n/** A real interactive Claude session, shared across reloads of its owning tab. */\nexport function createTerminal(\n entry: string,\n busy = () => false,\n base = '',\n verify: () => Promise<string | null> = async () => null,\n review?: { begin(): void; next(): Promise<VisualReview | undefined> },\n history?: { begin(): Promise<void>; end(): Promise<void> },\n) {\n let repairs = 0;\n let working = false;\n let process: IPty | undefined;\n let owner = '';\n let output = '';\n let context: FocusContext | undefined;\n let status = 'Start Claude Code to edit your slides.';\n let completion = Promise.resolve();\n let closing = false;\n let stopping = false;\n let starting = false;\n const token = randomBytes(32).toString('hex');\n const clients = new Set<ServerResponse>();\n const snapshot = () => ({ running: !!process, owner, status });\n const emit = (event: string, value: unknown) => {\n for (const client of clients) {\n if (!client.write(`event: ${event}\\ndata: ${JSON.stringify(value)}\\n\\n`)) {\n clients.delete(client);\n client.end();\n }\n }\n };\n async function stop() {\n if (!process || stopping) return completion;\n stopping = true;\n status = 'Stopping…';\n emit('state', snapshot());\n const running = process;\n running.kill();\n const timer = setTimeout(() => {\n if (process === running) running.kill('SIGKILL');\n }, 2000);\n await completion;\n clearTimeout(timer);\n }\n async function handle(\n request: IncomingMessage,\n response: ServerResponse,\n focus: (index: number | null, revision: number) => FocusContext,\n ) {\n const json = (code: number, value: unknown) => {\n response.writeHead(code, { 'Content-Type': 'application/json' });\n response.end(JSON.stringify(value));\n };\n if (request.url === '/terminal/context' || request.url === '/terminal/verify') {\n if (request.method !== 'POST' || request.headers.authorization !== `Bearer ${token}`) {\n json(403, { error: 'Invalid hook credentials' });\n return;\n }\n request.resume();\n if (request.url === '/terminal/verify') {\n if (closing || stopping || !process) {\n json(200, {});\n return;\n }\n let error: string | null;\n try {\n error = await verify();\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n }\n if (closing || stopping || !process) {\n json(200, {});\n return;\n }\n if (error && repairs < 3) {\n repairs++;\n status = `Repairing preview (${repairs}/3)…`;\n json(200, {\n decision: 'block',\n reason: `The actual preview build failed. Repair the source before finishing (attempt ${repairs}/3). Preserve unrelated edits, inspect the installed DSL exports and local components before changing imports. Do not hide the error or remove requested content. No Raw is needed for lists or an agenda: use Text paragraphs/bullets or mapped Text rows. Build error:\\n${error.slice(0, 16000)}`,\n });\n } else {\n if (!error && review) {\n try {\n const visual = await review.next();\n if (closing || stopping || !process) {\n json(200, {});\n return;\n }\n if (visual) {\n status = 'Reviewing slide screenshots…';\n json(200, { decision: 'block', reason: visual.prompt });\n emit('state', snapshot());\n return;\n }\n } catch (cause) {\n error = cause instanceof Error ? cause.message : String(cause);\n }\n }\n try {\n await history?.end();\n } catch (cause) {\n error = 'History: ' + String(cause);\n }\n working = false;\n status = error ? 'Preview verification incomplete: ' + error : 'Preview build verified';\n json(200, {});\n }\n emit('state', snapshot());\n return;\n }\n try {\n await history?.begin();\n } catch (cause) {\n json(409, { error: String(cause) });\n return;\n }\n repairs = 0;\n working = true;\n review?.begin();\n json(200, {\n hookSpecificOutput: {\n hookEventName: 'UserPromptSubmit',\n additionalContext: `You are editing the local PowerPoint TSX project at ${resolve(entry)}.\nRead the project's authoring instructions. Make focused source patches and preserve unrelated work.\nThe preview rebuilds on save; do not start another dev server. A Stop hook checks the actual build and returns errors for repair.\n${authoringGuidance}\nThe focused slide is context, NOT a restriction. For \"this slide\", edit only its relevant source. For other slides or deck-wide requests, locate the relevant source or shared theme.\nSlide numbers are 1-based. Verify source before editing; dependency paths are candidates, not an exact slide-to-file mapping.\nPreview context captured with the latest terminal input: ${JSON.stringify(context)}`,\n },\n });\n return;\n }\n const origin = `http://${request.headers.host}`;\n if (\n request.headers['sec-fetch-site'] === 'cross-site' ||\n (request.headers.origin && request.headers.origin !== origin)\n ) {\n json(403, { error: 'Same-origin requests only' });\n return;\n }\n if (request.method === 'GET' && request.url === '/terminal/events') {\n response.writeHead(200, { 'Content-Type': 'text/event-stream' });\n response.write(`event: replay\\ndata: ${JSON.stringify(output)}\\n\\n`);\n response.write(`event: state\\ndata: ${JSON.stringify(snapshot())}\\n\\n`);\n clients.add(response);\n request.on('close', () => clients.delete(response));\n return;\n }\n if (\n request.method !== 'POST' ||\n request.headers.origin !== origin ||\n request.headers['content-type'] !== 'application/json'\n ) {\n json(403, { error: 'Same-origin JSON requests only' });\n return;\n }\n try {\n let body = '';\n request.setEncoding('utf8');\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > REQUEST_LIMIT) throw new Error('Request too large');\n }\n const value = JSON.parse(body);\n if (!value || typeof value.client !== 'string' || !/^[\\w-]{1,64}$/.test(value.client))\n throw new Error('Invalid terminal client');\n if (closing || starting || stopping || (process && owner !== value.client)) {\n json(409, {\n error: stopping\n ? 'Claude Code is stopping'\n : 'Claude Code is open in another tab. Use that tab to control it.',\n });\n return;\n }\n const size = () => {\n if (\n !Number.isInteger(value.cols) ||\n value.cols < 2 ||\n value.cols > 500 ||\n !Number.isInteger(value.rows) ||\n value.rows < 1 ||\n value.rows > 300\n )\n throw new Error('Invalid terminal dimensions');\n };\n const updateFocus = () => {\n if (\n !(value.slide === null || (Number.isInteger(value.slide) && value.slide >= 0)) ||\n !Number.isInteger(value.revision)\n )\n throw new Error('Invalid preview context');\n context = focus(value.slide, value.revision);\n };\n if (request.url === '/terminal/start') {\n if (busy()) throw new Error('A Codex edit is already running');\n size();\n updateFocus();\n if (!process) {\n starting = true;\n try {\n // Lazy loading leaves preview/export usable if a native PTY cannot load.\n // node-pty 1.1.0 ships its macOS spawn helper without executable bits.\n // Restore the packaged helper's mode before its first launch.\n if (globalThis.process.platform === 'darwin') {\n const root = dirname(createRequire(import.meta.url).resolve('node-pty/package.json'));\n const helper = join(\n root,\n 'prebuilds',\n `darwin-${globalThis.process.arch}`,\n 'spawn-helper',\n );\n const info = await stat(helper).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (info && !(info.mode & 0o100)) await chmod(helper, info.mode | 0o100);\n }\n const pty = await import('node-pty');\n if (process || closing) throw new Error('Terminal state changed. Try again.');\n const settings = {\n hooks: {\n Stop: [\n {\n hooks: [\n {\n type: 'http',\n url: `${origin}${base}/terminal/verify`,\n headers: { Authorization: `Bearer ${token}` },\n timeout: 120,\n },\n ],\n },\n ],\n UserPromptSubmit: [\n {\n hooks: [\n {\n type: 'http',\n url: `${origin}${base}/terminal/context`,\n headers: { Authorization: `Bearer ${token}` },\n timeout: 5,\n },\n ],\n },\n ],\n },\n };\n const env = { ...globalThis.process.env };\n // This is an independent interactive session, even if the preview was started by Claude.\n delete env.CLAUDECODE;\n process = pty.spawn('claude', ['--settings', JSON.stringify(settings)], {\n cwd: dirname(resolve(entry)),\n name: 'xterm-256color',\n env,\n cols: value.cols,\n rows: value.rows,\n });\n } finally {\n starting = false;\n }\n owner = value.client;\n output = '';\n status = 'Claude Code';\n emit('replay', '');\n process.onData((data) => {\n output = (output + data).slice(-OUTPUT_LIMIT);\n emit('output', data);\n });\n completion = new Promise<void>((done) =>\n process!.onExit(async ({ exitCode }) => {\n process = undefined;\n working = false;\n stopping = false;\n status = `Claude Code exited (${exitCode}). Start to open a new session.`;\n try {\n await history?.end();\n } catch (cause) {\n status += ' History: ' + String(cause);\n }\n emit('state', snapshot());\n done();\n }),\n );\n }\n } else if (request.url === '/terminal/prompt') {\n if (!process) throw new Error('Start Claude Code in the selected agent pane first.');\n if (working)\n throw new Error('Claude Code is working. Wait for the current turn to finish.');\n if (\n typeof value.message !== 'string' ||\n !value.message.trim() ||\n value.message.length > 16000 ||\n [...value.message].some((character: string) => {\n const code = character.charCodeAt(0);\n return (code < 32 && code !== 9 && code !== 10) || code === 127;\n })\n )\n throw new Error('Invalid inline prompt');\n updateFocus();\n working = true;\n try {\n await history?.begin();\n } catch (cause) {\n working = false;\n throw cause;\n }\n if (!process || closing || stopping) {\n await history?.end();\n working = false;\n throw new Error('Claude Code stopped before submitting.');\n }\n process.write('\\x1b[200~' + value.message + '\\x1b[201~');\n await new Promise((done) => setTimeout(done, 100));\n if (!process || stopping) throw new Error('Claude Code stopped before submitting.');\n process.write('\\r');\n } else if (request.url === '/terminal/input') {\n if (!process) throw new Error('Start Claude Code first');\n if (typeof value.data !== 'string' || value.data.length > 32000)\n throw new Error('Invalid terminal input');\n updateFocus();\n process.write(value.data);\n if (value.data.includes('\\x03')) {\n working = false;\n await history?.end();\n }\n } else if (request.url === '/terminal/resize') {\n size();\n process?.resize(value.cols, value.rows);\n } else if (request.url === '/terminal/stop') {\n await stop();\n } else {\n json(404, { error: 'Not found' });\n return;\n }\n emit('state', snapshot());\n json(200, snapshot());\n } catch (cause) {\n json(400, { error: cause instanceof Error ? cause.message : 'Invalid terminal request' });\n }\n }\n return {\n handle,\n isRunning: () => starting || !!process,\n async close() {\n closing = true;\n await stop();\n for (const client of clients) client.end();\n clients.clear();\n },\n };\n}\n","import type { VisualReview } from './visual-review.ts';\nimport { authoringGuidance } from './authoring-guidance.ts';\nimport MarkdownIt from 'markdown-it';\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { dirname, resolve } from 'node:path';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nexport type Provider = 'codex';\nconst markdown = new MarkdownIt({ html: false, linkify: false });\n// Do not fetch remote images from model output.\nmarkdown.renderer.rules.image = (tokens, index) =>\n markdown.utils.escapeHtml(tokens[index]?.content ?? '');\nexport interface FocusContext {\n slide: number | null;\n count: number;\n revision: number;\n text: string;\n entry: string;\n files: string[];\n buildError: string | null;\n}\ninterface Message {\n role: 'user' | 'assistant';\n text: string;\n context?: FocusContext;\n}\n\n/** One shared conversation and one editing process per dev server. */\nexport function createChat(\n entry: string,\n notify: () => void,\n busy = () => false,\n verify: () => Promise<string | null> = async () => null,\n review?: { begin(): void; next(): Promise<VisualReview | undefined> },\n reviewImages: (prompt: string) => string[] = () => [],\n history?: { begin(): Promise<void>; end(): Promise<void> },\n) {\n let starting = false;\n let closing = false;\n let messages: Message[] = [];\n let provider: Provider = 'codex';\n let child: ChildProcess | undefined;\n let status = 'Ready';\n let stopping = false;\n let killTimer: ReturnType<typeof setTimeout> | undefined;\n let completion: Promise<void> = Promise.resolve();\n const snapshot = () => ({\n messages: messages.map((message) => ({\n ...message,\n ...(message.role === 'assistant' ? { html: markdown.render(message.text) } : {}),\n })),\n provider,\n running: starting || !!child,\n status,\n });\n function stop() {\n if (!child || stopping) return;\n stopping = true;\n status = 'Stopping…';\n const processToStop = child;\n // During verification the child has exited, but the turn still owns the\n // conversation. Cancel repair without signalling a potentially reused PID.\n if (processToStop.exitCode !== null || processToStop.signalCode !== null) {\n notify();\n return;\n }\n const kill = (signal: NodeJS.Signals) => {\n try {\n if (process.platform !== 'win32' && processToStop.pid)\n process.kill(-processToStop.pid, signal);\n else processToStop.kill(signal);\n } catch {\n /* Already exited. */\n }\n };\n kill('SIGTERM');\n killTimer = setTimeout(() => kill('SIGKILL'), 2000);\n notify();\n }\n function start(\n text: string,\n selected: Provider,\n context: FocusContext,\n repairs = 0,\n images: string[] = [],\n reviewing = false,\n ) {\n if (!repairs && !reviewing) review?.begin();\n provider = selected;\n const user: Message = { role: 'user', text, context };\n // Keep recent conversational intent, including each turn's original focus.\n const conversation = messages.slice(-12).map((message) => ({\n ...message,\n text: message.text.slice(-12000),\n }));\n const prompt = `You are editing a local PowerPoint TSX project in ${dirname(resolve(entry))}.\nRead the project's authoring instructions. Make focused patches to the TSX source, preserving unrelated work.\nThe preview rebuilds automatically on save; do not start another dev server.\n${authoringGuidance}\nThe attached focus is context, NOT a restriction: use it for references such as \"this slide\". For other slides or deck-wide requests, find the relevant source or shared theme instead. Do not rewrite the whole deck for a local edit.\nSlide numbers are 1-based and refer to the last successful preview at send time. Source may have changed since then; verify it before editing. Files are dependency candidates, not an exact slide-to-source mapping.\nRespond in the user's language, briefly describing edits or answering their question. If permissions prevent an action, explain that instead of claiming success.\nRecent conversation (JSON): ${JSON.stringify(conversation)}\nCurrent request and preview context (JSON): ${JSON.stringify(user)}`;\n messages.push(user);\n const answer: Message = { role: 'assistant', text: '' };\n messages.push(answer);\n if (messages.length > 100) messages = messages.slice(-100);\n status = 'Working…';\n stopping = false;\n const args = ['exec', '--json', '--sandbox', 'workspace-write', '--skip-git-repo-check', '-'];\n for (const image of images) args.splice(args.length - 1, 0, '--image', image);\n child = spawn(selected, args, {\n cwd: dirname(resolve(entry)),\n stdio: ['pipe', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n shell: false,\n });\n const running = child;\n let buffer = '',\n stderr = '',\n failure = '',\n sawResult = false;\n function append(value: string) {\n answer.text = (answer.text + (answer.text ? '\\n\\n' : '') + value).slice(-100000);\n notify();\n }\n function consume(line: string) {\n if (!line.trim()) return;\n try {\n const event = JSON.parse(line);\n if (event.type === 'item.completed' && event.item?.type === 'agent_message')\n append(event.item.text ?? '');\n if (event.type === 'item.started') {\n status = 'Editing / inspecting…';\n notify();\n }\n if (event.type === 'turn.completed') sawResult = true;\n if (event.type === 'turn.failed' || event.type === 'error')\n failure = event.error?.message ?? event.message ?? 'Agent failed';\n } catch {\n failure = 'Unexpected CLI output. Update your CLI and try again.';\n }\n }\n running.stdout!.setEncoding('utf8');\n running.stdout!.on('data', (chunk: string) => {\n buffer += chunk;\n let end: number;\n while ((end = buffer.indexOf('\\n')) !== -1) {\n consume(buffer.slice(0, end));\n buffer = buffer.slice(end + 1);\n }\n if (buffer.length > 2_000_000) {\n failure = 'CLI output exceeded the limit.';\n stop();\n }\n });\n running.stderr!.setEncoding('utf8');\n running.stderr!.on('data', (chunk: string) => {\n stderr = (stderr + chunk).slice(-8000);\n });\n running.stdin!.on('error', () => {\n /* Early process exit is handled below. */\n });\n running.stdin!.end(prompt);\n completion = new Promise<void>((done) => {\n running.on('error', (error) => {\n failure = `Could not run ${selected}. Install it and log in from your terminal first. ${error.message}`;\n });\n running.on('close', async (code) => {\n if (buffer.trim()) consume(buffer);\n clearTimeout(killTimer);\n status = stopping\n ? 'Stopped. Saved edits remain in the preview.'\n : failure ||\n (code !== 0\n ? stderr || `${selected} exited with code ${code}`\n : !sawResult\n ? 'CLI exited without a completed result.'\n : 'Done');\n if (status === 'Done') {\n status = 'Verifying preview…';\n notify();\n let buildError: string | null;\n try {\n buildError = await verify();\n } catch (cause) {\n buildError = cause instanceof Error ? cause.message : String(cause);\n }\n if (!stopping && buildError && repairs < 3) {\n child = undefined;\n start(\n `The actual preview build failed. Repair the source and preserve unrelated work (attempt ${repairs + 1}/3). Do not remove requested content or hide the error.\\n${buildError.slice(0, 16000)}`,\n selected,\n { ...context, buildError },\n repairs + 1,\n [],\n reviewing,\n );\n await completion;\n done();\n return;\n }\n let reviewFailure = '';\n if (!stopping && !buildError && review) {\n try {\n const visual = await review.next();\n if (!stopping && visual) {\n child = undefined;\n start(visual.prompt, selected, context, 0, visual.images, true);\n await completion;\n done();\n return;\n }\n } catch (error) {\n reviewFailure = error instanceof Error ? error.message : String(error);\n }\n }\n status = stopping\n ? 'Stopped. Saved edits remain in the preview.'\n : buildError\n ? 'Preview still has errors after 3 repair attempts.\\n' + buildError.slice(0, 16000)\n : reviewFailure || 'Done';\n }\n try {\n await history?.end();\n } catch (cause) {\n status = 'History: ' + String(cause);\n }\n if (status !== 'Done') append(status);\n child = undefined;\n notify();\n done();\n });\n });\n notify();\n }\n async function handle(\n request: IncomingMessage,\n response: ServerResponse,\n focus: (index: number | null, revision: number) => FocusContext,\n ) {\n const json = (code: number, value: unknown) => {\n response.writeHead(code, { 'Content-Type': 'application/json' });\n response.end(JSON.stringify(value));\n };\n if (request.method === 'GET' && request.url === '/chat') {\n json(200, snapshot());\n return;\n }\n if (request.method !== 'POST') {\n json(405, { error: 'Method not allowed' });\n return;\n }\n // Same-origin JSON prevents other sites from invoking local editing tools.\n if (\n request.headers.origin !== `http://${request.headers.host}` ||\n request.headers['content-type']?.split(';')[0] !== 'application/json'\n ) {\n json(403, { error: 'Same-origin JSON required' });\n return;\n }\n try {\n let body = '';\n request.setEncoding('utf8');\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > 32000) {\n json(413, { error: 'Message too large' });\n return;\n }\n }\n const value = JSON.parse(body);\n if (request.url === '/chat/stop') {\n stop();\n json(200, snapshot());\n return;\n }\n if (child || starting || closing) {\n json(409, { error: 'An edit is already running' });\n return;\n }\n if (request.url === '/chat/reset') {\n messages = [];\n status = 'Ready';\n notify();\n json(200, snapshot());\n return;\n }\n if (request.url !== '/chat') {\n json(404, { error: 'Not found' });\n return;\n }\n if (\n typeof value.message !== 'string' ||\n !value.message.trim() ||\n value.message.length > 16000 ||\n value.provider !== 'codex' ||\n !(value.slide === null || (Number.isInteger(value.slide) && value.slide >= 0)) ||\n !Number.isInteger(value.revision)\n ) {\n json(400, { error: 'Invalid chat request' });\n return;\n }\n if (busy()) {\n json(409, { error: 'End the Claude Code session before starting a Codex edit' });\n return;\n }\n const context = focus(value.slide, value.revision);\n starting = true;\n try {\n await history?.begin();\n if (closing) {\n await history?.end();\n throw new Error('Agent is closing');\n }\n start(value.message.trim(), value.provider, context, 0, reviewImages(value.message.trim()));\n } finally {\n starting = false;\n }\n json(202, snapshot());\n } catch (cause) {\n json(400, { error: cause instanceof Error ? cause.message : 'Invalid request' });\n }\n }\n return {\n handle,\n isRunning: () => starting || !!child,\n async close() {\n closing = true;\n stop();\n await completion;\n },\n };\n}\n","import { createHistory, historyFile } from './history.ts';\nimport { createTextEditor } from './text-edit.ts';\nimport { createVisualReviewer } from './visual-review.ts';\nimport { createServer, type ServerResponse } from 'node:http';\nimport { watch } from 'node:fs';\nimport { dirname, resolve, sep } from 'node:path';\nimport type { BuildResult } from './build.ts';\nimport { createDeckBuilder } from './build-runner.ts';\nimport { page } from './page.ts';\nimport { agentPage } from './agent-page.ts';\nimport { readFile } from 'node:fs/promises';\nimport { createTerminal } from './terminal.ts';\nimport { createChat } from './chat.ts';\n\nexport async function serveDeck(entry: string, port = 4173) {\n let latest: BuildResult | undefined;\n let error: string | null = null;\n let building = false;\n let revision = 0;\n let generation = 0;\n let patch: Record<number, string> = {};\n let pending = false;\n let closed = false;\n const clients = new Set<ServerResponse>();\n const sessions = new Map<\n string,\n {\n chat: ReturnType<typeof createChat>;\n terminal: ReturnType<typeof createTerminal>;\n closing: boolean;\n }\n >();\n const history = await createHistory(dirname(resolve(entry)), () => {\n for (const client of clients) client.write('data: history\\n\\n');\n });\n let textEdits = 0;\n const capturedReviews = new Map<string, string[]>();\n function session(id: string) {\n let result = sessions.get(id);\n if (!result) {\n const review = createVisualReviewer(resolve(entry), () => latest?.slides ?? []);\n const turnHistory = {\n begin: () => history.begin('agent:' + id, 'AI edit'),\n end: () => history.end('agent:' + id),\n };\n const chat = createChat(\n entry,\n () => {\n for (const client of clients) client.write('data: chat\\n\\n');\n },\n () => terminal.isRunning(),\n verify,\n review,\n (prompt) => capturedReviews.get(prompt) ?? [],\n turnHistory,\n );\n const terminal = createTerminal(\n entry,\n () => chat.isRunning(),\n id ? '/agents/' + id : '',\n verify,\n review,\n turnHistory,\n );\n result = { chat, terminal, closing: false };\n sessions.set(id, result);\n }\n return result;\n }\n const textEditor = createTextEditor(\n resolve(entry),\n () => {\n if (!latest || building || pending || timer || error)\n throw new Error('Wait for a successful preview build.');\n return { ...latest, revision };\n },\n verify,\n );\n const server = createServer((request, response) => {\n const host = request.headers.host;\n if (host !== `127.0.0.1:${actualPort}` && host !== `localhost:${actualPort}`) {\n response.writeHead(403).end();\n return;\n }\n response.setHeader('Cache-Control', 'no-store');\n const match = request.url?.match(\n /^\\/agents\\/([\\w-]{1,64})(\\/(?:chat(?:\\/(?:stop|reset))?|terminal\\/(?:start|input|prompt|resize|stop|events|context|verify)|close))?$/,\n );\n if (request.url?.startsWith('/agents/') && !match) {\n response.writeHead(404).end();\n return;\n }\n if (request.url === '/history' && request.method === 'GET') {\n response\n .writeHead(200, { 'Content-Type': 'application/json' })\n .end(JSON.stringify(history.state()));\n return;\n }\n if (\n request.url === '/text-edit' ||\n request.url === '/history/undo' ||\n request.url === '/history/redo'\n ) {\n if (\n request.method !== 'POST' ||\n request.headers.origin !== `http://${host}` ||\n request.headers['content-type'] !== 'application/json'\n ) {\n response.writeHead(403).end();\n return;\n }\n void (async () => {\n let body = '';\n request.setEncoding('utf8');\n for await (const chunk of request) {\n body += chunk;\n if (Buffer.byteLength(body) > 100000) throw new Error('Request too large');\n }\n if (request.url !== '/text-edit') {\n await history.move(request.url === '/history/undo' ? 'undo' : 'redo');\n const buildError = await verify();\n response\n .writeHead(200, { 'Content-Type': 'application/json' })\n .end(JSON.stringify({ ...history.state(), buildError }));\n return;\n }\n const manualReview = createVisualReviewer(resolve(entry), () => latest?.slides ?? []);\n manualReview.begin();\n const editId = 'text:' + ++textEdits;\n await history.begin(editId, 'Text edit');\n try {\n await textEditor.edit(JSON.parse(body));\n } finally {\n await history.end(editId);\n }\n let review;\n let reviewError;\n try {\n review = await manualReview.next();\n if (review) {\n capturedReviews.set(review.prompt, review.images);\n if (capturedReviews.size > 64)\n capturedReviews.delete(capturedReviews.keys().next().value!);\n }\n } catch (cause) {\n reviewError = cause instanceof Error ? cause.message : String(cause);\n }\n response\n .writeHead(200, { 'Content-Type': 'application/json' })\n .end(JSON.stringify({ review, reviewError }));\n })().catch((cause) =>\n response\n .writeHead(400, { 'Content-Type': 'application/json' })\n .end(JSON.stringify({ error: cause instanceof Error ? cause.message : String(cause) })),\n );\n return;\n }\n const id = match?.[1] ?? '';\n if (match) {\n if (\n request.headers['sec-fetch-site'] === 'cross-site' ||\n (request.headers.origin && request.headers.origin !== `http://${host}`)\n ) {\n response.writeHead(403).end();\n return;\n }\n if (sessions.get(id)?.closing) {\n response.writeHead(409).end('{\"error\":\"Agent is closing\"}');\n return;\n }\n if (match[2] === '/close') {\n if (\n request.method !== 'POST' ||\n request.headers.origin !== `http://${host}` ||\n request.headers['content-type'] !== 'application/json'\n ) {\n response.writeHead(403).end();\n return;\n }\n request.resume();\n const current = sessions.get(id);\n void (async () => {\n if (current) {\n current.closing = true;\n await Promise.all([current.terminal.close(), current.chat.close()]);\n sessions.delete(id);\n }\n response.writeHead(200).end('{}');\n })().catch(() => response.writeHead(500).end());\n return;\n }\n if (!sessions.has(id) && sessions.size >= 8) {\n response.writeHead(429).end('Too many agent sessions. Close an existing pane.');\n return;\n }\n if (!match[2]) {\n if (request.method !== 'GET') {\n response.writeHead(405).end();\n return;\n }\n session(id);\n response.writeHead(200, { 'Content-Type': 'text/html' }).end(agentPage);\n return;\n }\n if (!sessions.has(id)) {\n response.writeHead(404).end();\n return;\n }\n request.url = match[2];\n }\n\n if (\n request.url === '/chat' ||\n request.url?.startsWith('/chat/') ||\n request.url?.startsWith('/terminal/')\n ) {\n const current = session(id);\n const handler = request.url.startsWith('/terminal/') ? current.terminal : current.chat;\n void handler.handle(request, response, (index, viewedRevision) => {\n if (viewedRevision !== revision)\n throw new Error('Preview changed. Review the current slide and send again.');\n if (index !== null && (!latest || index >= latest.slides.length))\n throw new Error('Slide no longer exists.');\n return {\n slide: index === null ? null : index + 1,\n count: latest?.slides.length ?? 0,\n revision,\n text: index === null ? '' : (latest?.slideTexts[index] ?? '').slice(0, 12000),\n entry: resolve(entry),\n files: latest?.dependencies ?? [resolve(entry)],\n buildError: error,\n };\n });\n } else if (\n request.method === 'GET' &&\n ['/terminal.js', '/terminal.css'].includes(request.url ?? '')\n ) {\n const asset = request.url === '/terminal.js' ? 'terminal-client.js' : 'terminal-client.css';\n void readFile(new URL(asset, import.meta.url)).then(\n (bytes) => {\n response.writeHead(200, {\n 'Content-Type': asset.endsWith('.css') ? 'text/css' : 'text/javascript',\n });\n response.end(bytes);\n },\n () => response.writeHead(500).end('Terminal assets unavailable. Rebuild pptx-dev.'),\n );\n } else if (request.method !== 'GET') {\n response.writeHead(405).end();\n } else if (request.url === '/events') {\n response.writeHead(200, { 'Content-Type': 'text/event-stream' });\n response.write('data: ready\\n\\n');\n clients.add(response);\n request.on('close', () => clients.delete(response));\n } else if (request.url === '/state' || request.url?.startsWith('/state?')) {\n const since = new URL(request.url, 'http://localhost').searchParams.get('since');\n const incremental =\n since !== null && (since === String(revision) || since === String(revision - 1));\n response.writeHead(200, { 'Content-Type': 'application/json' });\n response.end(\n JSON.stringify({\n revision,\n building,\n ...(incremental\n ? {\n changes: since === String(revision) ? {} : patch,\n count: latest?.slides.length ?? 0,\n }\n : { slides: latest?.slides ?? [] }),\n aspectRatio: latest?.aspectRatio ?? 16 / 9,\n error,\n diagnostics: latest?.diagnostics ?? [],\n }),\n );\n } else if (request.url === '/deck.pptx' && latest) {\n response.writeHead(200, {\n 'Content-Type': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'Content-Disposition': 'attachment; filename=\"deck.pptx\"',\n });\n response.end(latest.bytes);\n } else if (request.url === '/') {\n response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page);\n } else {\n response.writeHead(404).end();\n }\n });\n async function verify() {\n // A fresh build also covers writes whose watcher notification has not arrived yet.\n void rebuild();\n const deadline = Date.now() + 30000;\n while (!closed && (building || timer || pending)) {\n if (Date.now() >= deadline)\n return 'Preview verification timed out. Inspect the build before claiming success.';\n await new Promise((done) => setTimeout(done, 50));\n }\n return closed ? 'Preview server closed.' : error;\n }\n async function rebuild() {\n if (closed) return;\n if (building) {\n pending = true;\n return;\n }\n building = true;\n const started = generation;\n for (const client of clients) client.write('data: building\\n\\n');\n try {\n const result = await builder.build();\n if (started === generation && !closed) {\n patch = {};\n result.slides.forEach((svg, index) => {\n if (svg !== latest?.slides[index]) patch[index] = svg;\n });\n latest = result;\n revision++;\n error = null;\n }\n } catch (cause) {\n if (started === generation)\n error = cause instanceof Error ? (cause.stack ?? cause.message) : String(cause);\n } finally {\n building = false;\n void history.capture().catch(() => {\n /* The history endpoint exposes capture failures. */\n });\n for (const client of clients) client.write('data: updated\\n\\n');\n if (pending && !timer) {\n pending = false;\n void rebuild();\n }\n }\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const root = dirname(resolve(entry));\n const watcher = watch(root, { recursive: true }, (_, filename) => {\n if (\n !filename ||\n filename\n .split(sep)\n .some((part) => ['node_modules', '.git', 'dist', '.office-kit'].includes(part))\n )\n return;\n if (!historyFile(filename)) return;\n generation++;\n void builder.cancel();\n clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n pending = false;\n void rebuild();\n }, 30);\n });\n const builder = createDeckBuilder(entry);\n let actualPort = port;\n try {\n await new Promise<void>((resolveListen, reject) => {\n server.once('error', reject);\n server.listen(port, '127.0.0.1', () => {\n server.off('error', reject);\n resolveListen();\n });\n });\n } catch (cause) {\n watcher.close();\n await builder.close();\n throw cause;\n }\n const address = server.address();\n if (address && typeof address !== 'string') actualPort = address.port;\n await rebuild();\n return {\n url: `http://127.0.0.1:${actualPort}`,\n async close() {\n closed = true;\n clearTimeout(timer);\n watcher.close();\n await Promise.all(\n [...sessions.values()].flatMap(({ terminal, chat }) => [terminal.close(), chat.close()]),\n );\n await builder.close();\n for (const client of clients) client.end();\n await new Promise<void>((done, reject) =>\n server.close((cause) => (cause ? reject(cause) : done())),\n );\n },\n };\n}\n","#!/usr/bin/env node\nimport { resolve } from 'node:path';\nimport { exportDeck } from './index.ts';\nimport { serveDeck } from './server.ts';\nimport { initProject } from './init.ts';\nimport { inspectTemplate } from './inspect.ts';\n\nconst usage = `Usage: office-pptx init <new-directory>\n office-pptx dev <deck.tsx> [--port 4173]\n office-pptx build <deck.tsx> [--out deck.pptx]\n office-pptx inspect <template.pptx>`;\nconst [command, entry, ...args] = process.argv.slice(2);\ntry {\n if (command === '--help' || command === '-h') {\n console.log(usage);\n } else {\n if (!entry) throw new Error(usage);\n const option = command === 'build' ? '--out' : command === 'dev' ? '--port' : undefined;\n if (args.length && (args.length !== 2 || !option || args[0] !== option || !args[1])) {\n throw new Error(`Unexpected arguments: ${args.join(' ')}\\n${usage}`);\n }\n if (command === 'init') {\n const directory = await initProject(entry);\n console.log(\n `Created ${directory}\\nInside that directory, run npm install once.\\nStart development: npm run dev (or npx office-pptx dev deck.tsx).`,\n );\n } else if (command === 'inspect') {\n console.log(JSON.stringify(await inspectTemplate(entry), null, 2));\n } else if (command === 'build') {\n const output = resolve(args[1] ?? 'deck.pptx');\n const result = await exportDeck(entry, output);\n console.log(`Wrote ${output} (${result.slides.length} slides)`);\n } else if (command === 'dev') {\n const port = args[1] === undefined ? 4173 : Number(args[1]);\n if (!Number.isInteger(port) || port < 0 || port > 65535)\n throw new Error('Port must be an integer between 0 and 65535.');\n const server = await serveDeck(entry, port);\n console.log(`Preview: ${server.url}`);\n const stop = () => {\n void server.close().then(() => process.exit(0));\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n } else {\n throw new Error(usage);\n }\n }\n} catch (cause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