hanseol-dev 5.0.2-dev.15 → 5.0.2-dev.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/agents/common/sub-agent.d.ts +14 -0
  2. package/dist/agents/common/sub-agent.d.ts.map +1 -1
  3. package/dist/agents/common/sub-agent.js +98 -4
  4. package/dist/agents/common/sub-agent.js.map +1 -1
  5. package/dist/agents/index.d.ts +1 -1
  6. package/dist/agents/index.d.ts.map +1 -1
  7. package/dist/agents/index.js +1 -1
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/agents/office/excel-agent.d.ts +1 -1
  10. package/dist/agents/office/excel-agent.d.ts.map +1 -1
  11. package/dist/agents/office/excel-agent.js +6 -6
  12. package/dist/agents/office/excel-agent.js.map +1 -1
  13. package/dist/agents/office/excel-create-agent.d.ts +3 -0
  14. package/dist/agents/office/excel-create-agent.d.ts.map +1 -0
  15. package/dist/agents/office/excel-create-agent.js +38 -0
  16. package/dist/agents/office/excel-create-agent.js.map +1 -0
  17. package/dist/agents/office/excel-create-prompts.d.ts +4 -0
  18. package/dist/agents/office/excel-create-prompts.d.ts.map +1 -0
  19. package/dist/agents/office/excel-create-prompts.js +154 -0
  20. package/dist/agents/office/excel-create-prompts.js.map +1 -0
  21. package/dist/agents/office/index.d.ts +6 -3
  22. package/dist/agents/office/index.d.ts.map +1 -1
  23. package/dist/agents/office/index.js +6 -3
  24. package/dist/agents/office/index.js.map +1 -1
  25. package/dist/agents/office/powerpoint-agent.d.ts +1 -1
  26. package/dist/agents/office/powerpoint-agent.d.ts.map +1 -1
  27. package/dist/agents/office/powerpoint-agent.js +6 -6
  28. package/dist/agents/office/powerpoint-agent.js.map +1 -1
  29. package/dist/agents/office/powerpoint-create-agent.d.ts +3 -0
  30. package/dist/agents/office/powerpoint-create-agent.d.ts.map +1 -0
  31. package/dist/agents/office/powerpoint-create-agent.js +1431 -0
  32. package/dist/agents/office/powerpoint-create-agent.js.map +1 -0
  33. package/dist/agents/office/powerpoint-create-prompts.d.ts +42 -0
  34. package/dist/agents/office/powerpoint-create-prompts.d.ts.map +1 -0
  35. package/dist/agents/office/powerpoint-create-prompts.js +980 -0
  36. package/dist/agents/office/powerpoint-create-prompts.js.map +1 -0
  37. package/dist/agents/office/prompts.d.ts +8 -4
  38. package/dist/agents/office/prompts.d.ts.map +1 -1
  39. package/dist/agents/office/prompts.js +306 -67
  40. package/dist/agents/office/prompts.js.map +1 -1
  41. package/dist/agents/office/word-agent.d.ts +1 -1
  42. package/dist/agents/office/word-agent.d.ts.map +1 -1
  43. package/dist/agents/office/word-agent.js +6 -6
  44. package/dist/agents/office/word-agent.js.map +1 -1
  45. package/dist/agents/office/word-create-agent.d.ts +3 -0
  46. package/dist/agents/office/word-create-agent.d.ts.map +1 -0
  47. package/dist/agents/office/word-create-agent.js +38 -0
  48. package/dist/agents/office/word-create-agent.js.map +1 -0
  49. package/dist/agents/office/word-create-prompts.d.ts +4 -0
  50. package/dist/agents/office/word-create-prompts.d.ts.map +1 -0
  51. package/dist/agents/office/word-create-prompts.js +164 -0
  52. package/dist/agents/office/word-create-prompts.js.map +1 -0
  53. package/dist/cli.js +3 -0
  54. package/dist/cli.js.map +1 -1
  55. package/dist/constants.d.ts +1 -1
  56. package/dist/constants.d.ts.map +1 -1
  57. package/dist/constants.js +1 -1
  58. package/dist/constants.js.map +1 -1
  59. package/dist/pipe/pipe-runner.d.ts.map +1 -1
  60. package/dist/pipe/pipe-runner.js +20 -0
  61. package/dist/pipe/pipe-runner.js.map +1 -1
  62. package/dist/prompts/agents/planning.d.ts.map +1 -1
  63. package/dist/prompts/agents/planning.js +20 -11
  64. package/dist/prompts/agents/planning.js.map +1 -1
  65. package/dist/prompts/shared/tool-usage.d.ts.map +1 -1
  66. package/dist/prompts/shared/tool-usage.js +6 -3
  67. package/dist/prompts/shared/tool-usage.js.map +1 -1
  68. package/dist/prompts/system/plan-execute.js +1 -1
  69. package/dist/tools/office/excel-client.js +4 -4
  70. package/dist/tools/office/excel-tools/index.d.ts +2 -0
  71. package/dist/tools/office/excel-tools/index.d.ts.map +1 -1
  72. package/dist/tools/office/excel-tools/index.js +12 -0
  73. package/dist/tools/office/excel-tools/index.js.map +1 -1
  74. package/dist/tools/office/excel-tools/sheet-builders.d.ts +8 -0
  75. package/dist/tools/office/excel-tools/sheet-builders.d.ts.map +1 -0
  76. package/dist/tools/office/excel-tools/sheet-builders.js +414 -0
  77. package/dist/tools/office/excel-tools/sheet-builders.js.map +1 -0
  78. package/dist/tools/office/excel-tools.d.ts +1 -1
  79. package/dist/tools/office/excel-tools.d.ts.map +1 -1
  80. package/dist/tools/office/excel-tools.js +1 -1
  81. package/dist/tools/office/excel-tools.js.map +1 -1
  82. package/dist/tools/office/powerpoint-client.d.ts +3 -0
  83. package/dist/tools/office/powerpoint-client.d.ts.map +1 -1
  84. package/dist/tools/office/powerpoint-client.js +143 -10
  85. package/dist/tools/office/powerpoint-client.js.map +1 -1
  86. package/dist/tools/office/powerpoint-tools/export.d.ts.map +1 -1
  87. package/dist/tools/office/powerpoint-tools/export.js +16 -1
  88. package/dist/tools/office/powerpoint-tools/export.js.map +1 -1
  89. package/dist/tools/office/powerpoint-tools/index.d.ts +2 -0
  90. package/dist/tools/office/powerpoint-tools/index.d.ts.map +1 -1
  91. package/dist/tools/office/powerpoint-tools/index.js +7 -0
  92. package/dist/tools/office/powerpoint-tools/index.js.map +1 -1
  93. package/dist/tools/office/powerpoint-tools/launch.d.ts.map +1 -1
  94. package/dist/tools/office/powerpoint-tools/launch.js +2 -0
  95. package/dist/tools/office/powerpoint-tools/launch.js.map +1 -1
  96. package/dist/tools/office/powerpoint-tools/layout-builders.d.ts +12 -0
  97. package/dist/tools/office/powerpoint-tools/layout-builders.d.ts.map +1 -0
  98. package/dist/tools/office/powerpoint-tools/layout-builders.js +785 -0
  99. package/dist/tools/office/powerpoint-tools/layout-builders.js.map +1 -0
  100. package/dist/tools/office/powerpoint-tools/slides.js +1 -1
  101. package/dist/tools/office/powerpoint-tools/slides.js.map +1 -1
  102. package/dist/tools/office/powerpoint-tools.d.ts +1 -1
  103. package/dist/tools/office/powerpoint-tools.d.ts.map +1 -1
  104. package/dist/tools/office/powerpoint-tools.js +1 -1
  105. package/dist/tools/office/powerpoint-tools.js.map +1 -1
  106. package/dist/tools/office/word-client.js +4 -4
  107. package/dist/tools/office/word-tools/index.d.ts +4 -1
  108. package/dist/tools/office/word-tools/index.d.ts.map +1 -1
  109. package/dist/tools/office/word-tools/index.js +15 -0
  110. package/dist/tools/office/word-tools/index.js.map +1 -1
  111. package/dist/tools/office/word-tools/section-builders.d.ts +10 -0
  112. package/dist/tools/office/word-tools/section-builders.d.ts.map +1 -0
  113. package/dist/tools/office/word-tools/section-builders.js +421 -0
  114. package/dist/tools/office/word-tools/section-builders.js.map +1 -0
  115. package/dist/tools/office/word-tools.d.ts +1 -1
  116. package/dist/tools/office/word-tools.d.ts.map +1 -1
  117. package/dist/tools/office/word-tools.js +1 -1
  118. package/dist/tools/office/word-tools.js.map +1 -1
  119. package/dist/tools/registry.d.ts.map +1 -1
  120. package/dist/tools/registry.js +7 -4
  121. package/dist/tools/registry.js.map +1 -1
  122. package/package.json +1 -1
@@ -0,0 +1,1431 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { powerpointClient } from '../../tools/office/powerpoint-client.js';
4
+ import { getSubAgentPhaseLogger, getSubAgentToolCallLogger } from '../common/sub-agent.js';
5
+ import { logger } from '../../utils/logger.js';
6
+ import { getPlatform } from '../../utils/platform-utils.js';
7
+ import { PPT_CREATE_ENHANCEMENT_PROMPT, PPT_STRUCTURED_PLANNING_PROMPT, buildSlideHtmlPrompt, extractLayoutHint, checkLayoutCompliance, postProcessSlideHtml, buildLayoutSetPrompt, parseLayoutSet, buildAllSkeletonsPrompt, parseSkeletons, buildFillPrompt, } from './powerpoint-create-prompts.js';
8
+ function getUnderfillFixByLayout(layoutType) {
9
+ const fixes = {
10
+ cards: 'ADD MORE CONTENT to cards:\n- Each card needs 4-5 bullet points (not 2-3)\n- Add a 2-sentence descriptive paragraph under each heading\n- Add a metric/stat at the bottom of each card\n- Use generous padding: 40px inside cards, 20px between items',
11
+ progress_bars: 'ADD MORE BARS and detail:\n- Increase to 5-6 bars (not 3-4)\n- Add a 1-line detail text below each bar explaining context\n- Add an insight summary box at the very bottom\n- Use larger bar height (48px) and label font (28px)',
12
+ bar_chart: 'ADD MORE to the chart:\n- Add more bars (5-6 total)\n- Make bars taller (tallest 85%)\n- Add a 2-3 line insight section at the bottom\n- Increase font sizes: values 32px, labels 28px',
13
+ donut_chart: 'ADD MORE to donut and legend:\n- Add 4-5 segments with detailed labels\n- Each legend item: name + absolute value + percentage\n- Add a 2-sentence summary paragraph below the legend\n- Make donut larger (450px)',
14
+ table: 'ADD MORE ROWS and content:\n- Increase to 6-8 data rows\n- Fill ALL cells with real data\n- Add a summary bar below the table with key insight\n- Use larger padding on td (28-32px)',
15
+ timeline: 'ADD MORE DETAIL to milestones:\n- Each milestone: 3-4 sentence description (not 1 line)\n- Add a KPI metric at the bottom of each milestone card\n- Use 3-4 milestone cards (not 2)\n- Add date labels and context',
16
+ process_flow: 'ADD MORE DETAIL to steps:\n- Each step: 2-3 sentence description (not 1 line)\n- Add time/metric at the bottom of each step\n- Use step numbers + titles\n- Increase padding for readability',
17
+ big_numbers: 'ADD MORE CONTEXT:\n- Each metric: number + unit + label + 2-3 sentence context + trend indicator\n- Ensure 3 metric cards minimum\n- Add supporting text below each number\n- Make numbers larger (80px)',
18
+ two_col_split: 'ADD MORE CONTENT:\n- Left column: primary visual with supporting context\n- Right column: 4-5 detailed bullet points\n- Both columns must be content-rich\n- Use generous font sizes (28-30px)',
19
+ hero_stat: 'ADD MORE CONTEXT:\n- Central number must be 128px\n- Add 2-3 sentence context paragraph below\n- Add row of 2-3 supporting metrics\n- Include trend indicators and labels',
20
+ };
21
+ return fixes[layoutType] || fixes['cards'];
22
+ }
23
+ const DEFAULT_DESIGN = {
24
+ primary_color: '#1B2A4A',
25
+ accent_color: '#00D4AA',
26
+ background_color: '#FFFFFF',
27
+ text_color: '#1A1A2E',
28
+ accent_light: '#E8F5F0',
29
+ gradient_end: '#2D5F8A',
30
+ font_title: 'Segoe UI',
31
+ font_body: 'Malgun Gothic',
32
+ mood: 'modern-minimal',
33
+ design_notes: 'Clean gradients, card-based layouts',
34
+ };
35
+ function extractContent(msg) {
36
+ const content = msg['content'];
37
+ if (content && content.trim())
38
+ return content;
39
+ const reasoning = msg['reasoning_content'];
40
+ if (reasoning && reasoning.trim())
41
+ return reasoning;
42
+ return '';
43
+ }
44
+ function validateAndFixPlan(plan) {
45
+ if (!plan.design)
46
+ return 'Missing design object';
47
+ if (!plan.design.primary_color || !plan.design.accent_color) {
48
+ return 'Missing design colors (primary_color, accent_color)';
49
+ }
50
+ if (!Array.isArray(plan.slides) || plan.slides.length < 3) {
51
+ return 'slides array must have at least 3 entries';
52
+ }
53
+ if (plan.slides.length < 10) {
54
+ return `Only ${plan.slides.length} slides — minimum 10 required (aim for 12-15). Add more content slides with specific data.`;
55
+ }
56
+ if (plan.slides[0]?.type !== 'title') {
57
+ logger.info('Auto-fixing: first slide type changed to "title"');
58
+ plan.slides[0].type = 'title';
59
+ }
60
+ const lastSlide = plan.slides[plan.slides.length - 1];
61
+ if (lastSlide.type !== 'closing') {
62
+ logger.info('Auto-fixing: last slide type changed to "closing"');
63
+ lastSlide.type = 'closing';
64
+ }
65
+ for (let i = 0; i < plan.slides.length; i++) {
66
+ if (!plan.slides[i].title) {
67
+ plan.slides[i].title = `Slide ${i + 1}`;
68
+ logger.info(`Auto-fixing: slide ${i + 1} missing title, set placeholder`);
69
+ }
70
+ }
71
+ const layoutOnlyPatterns = [
72
+ /^(?:전체\s*배경|왼쪽에|오른쪽에|중앙에|상단에|하단에)/,
73
+ /#[0-9a-fA-F]{3,8}에서.*그라데이션/,
74
+ /(?:accent_light|primary|gradient_end)\s*(?:배경|글씨|색상)/,
75
+ /^(?:CSS|flexbox|grid|conic-gradient|linear-gradient)/i,
76
+ ];
77
+ for (let i = 0; i < plan.slides.length; i++) {
78
+ const slide = plan.slides[i];
79
+ if (slide.type === 'title' || slide.type === 'closing')
80
+ continue;
81
+ const cd = slide.content_direction || '';
82
+ const hasNumbers = /\d/.test(cd);
83
+ const isLayoutOnly = layoutOnlyPatterns.some(p => p.test(cd));
84
+ if (isLayoutOnly && !hasNumbers) {
85
+ return `Slide ${i + 1} "${slide.title}" content_direction contains layout instructions instead of actual data. content_direction must include REAL text/numbers to display.`;
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ function repairLlmJson(raw) {
91
+ let result = '';
92
+ let inString = false;
93
+ let i = 0;
94
+ while (i < raw.length) {
95
+ const ch = raw[i];
96
+ if (!inString) {
97
+ if (ch === ',') {
98
+ let j = i + 1;
99
+ while (j < raw.length && /\s/.test(raw[j]))
100
+ j++;
101
+ if (j < raw.length && (raw[j] === '}' || raw[j] === ']')) {
102
+ i++;
103
+ continue;
104
+ }
105
+ }
106
+ result += ch;
107
+ if (ch === '"')
108
+ inString = true;
109
+ i++;
110
+ continue;
111
+ }
112
+ if (ch === '\\') {
113
+ result += ch;
114
+ if (i + 1 < raw.length) {
115
+ result += raw[i + 1];
116
+ i += 2;
117
+ }
118
+ else {
119
+ i++;
120
+ }
121
+ continue;
122
+ }
123
+ if (ch === '"') {
124
+ let j = i + 1;
125
+ while (j < raw.length && /[ \t\r\n]/.test(raw[j]))
126
+ j++;
127
+ const next = j < raw.length ? raw[j] : '';
128
+ if (next === '' || /[,:}\]]/.test(next)) {
129
+ result += '"';
130
+ inString = false;
131
+ }
132
+ else {
133
+ result += '\\"';
134
+ }
135
+ i++;
136
+ continue;
137
+ }
138
+ if (ch === '\n') {
139
+ result += '\\n';
140
+ i++;
141
+ continue;
142
+ }
143
+ if (ch === '\r') {
144
+ result += '\\n';
145
+ i += (i + 1 < raw.length && raw[i + 1] === '\n') ? 2 : 1;
146
+ continue;
147
+ }
148
+ if (ch === '\t') {
149
+ result += '\\t';
150
+ i++;
151
+ continue;
152
+ }
153
+ if (ch.charCodeAt(0) < 0x20) {
154
+ i++;
155
+ continue;
156
+ }
157
+ result += ch;
158
+ i++;
159
+ }
160
+ return result;
161
+ }
162
+ function parseJsonPlan(raw) {
163
+ let cleaned = raw.trim();
164
+ if (cleaned.startsWith('```')) {
165
+ cleaned = cleaned.replace(/^```(?:json|JSON)?\s*\n?/, '').replace(/\n?```\s*$/, '');
166
+ }
167
+ const firstBrace = cleaned.indexOf('{');
168
+ if (firstBrace > 0) {
169
+ cleaned = cleaned.slice(firstBrace);
170
+ }
171
+ const lastBrace = cleaned.lastIndexOf('}');
172
+ if (lastBrace >= 0 && lastBrace < cleaned.length - 1) {
173
+ cleaned = cleaned.slice(0, lastBrace + 1);
174
+ }
175
+ try {
176
+ return JSON.parse(cleaned);
177
+ }
178
+ catch (e) {
179
+ logger.debug('parseJsonPlan: direct parse failed', { error: String(e), length: cleaned.length });
180
+ }
181
+ const match = cleaned.match(/\{[\s\S]*\}/);
182
+ if (!match)
183
+ return null;
184
+ try {
185
+ return JSON.parse(match[0]);
186
+ }
187
+ catch { }
188
+ const repaired = repairLlmJson(match[0]);
189
+ try {
190
+ return JSON.parse(repaired);
191
+ }
192
+ catch (e) {
193
+ logger.debug('parseJsonPlan: repaired parse failed', { error: String(e) });
194
+ }
195
+ try {
196
+ let final = repaired;
197
+ let braces = 0, brackets = 0;
198
+ let inStr = false, esc = false;
199
+ for (const ch of final) {
200
+ if (esc) {
201
+ esc = false;
202
+ continue;
203
+ }
204
+ if (ch === '\\') {
205
+ esc = true;
206
+ continue;
207
+ }
208
+ if (ch === '"') {
209
+ inStr = !inStr;
210
+ continue;
211
+ }
212
+ if (inStr)
213
+ continue;
214
+ if (ch === '{')
215
+ braces++;
216
+ else if (ch === '}')
217
+ braces--;
218
+ else if (ch === '[')
219
+ brackets++;
220
+ else if (ch === ']')
221
+ brackets--;
222
+ }
223
+ if (inStr)
224
+ final += '"';
225
+ for (let i = 0; i < brackets; i++)
226
+ final += ']';
227
+ for (let i = 0; i < braces; i++)
228
+ final += '}';
229
+ return JSON.parse(final);
230
+ }
231
+ catch {
232
+ return null;
233
+ }
234
+ }
235
+ function extractHtml(raw) {
236
+ const trimmed = raw.trim();
237
+ if (trimmed.startsWith('<!DOCTYPE') || trimmed.startsWith('<html')) {
238
+ return trimmed;
239
+ }
240
+ const fenceMatch = trimmed.match(/```(?:html)?\s*\n([\s\S]*?)\n```/);
241
+ if (fenceMatch?.[1]) {
242
+ return fenceMatch[1].trim();
243
+ }
244
+ const docMatch = trimmed.match(/(<!DOCTYPE[\s\S]*<\/html>)/i);
245
+ if (docMatch?.[1]) {
246
+ return docMatch[1].trim();
247
+ }
248
+ return null;
249
+ }
250
+ function injectViewportCss(html, backgroundColor) {
251
+ let result = html.replace(/<meta\s+name=["']viewport["'][^>]*>/gi, '');
252
+ const bgColor = backgroundColor || '#000000';
253
+ const overrideCss = `<style>*{box-sizing:border-box;word-break:keep-all;overflow-wrap:break-word}html{width:2040px!important;height:1200px!important;overflow:hidden!important;margin:0!important;background-color:${bgColor}!important;zoom:1!important}body{width:1920px!important;height:1080px!important;min-width:1920px!important;min-height:1080px!important;overflow:hidden!important;margin:0!important;display:flex!important;flex-direction:column!important;zoom:1!important;font-size:26px!important}body>div,body>main,body>section,body>article,body>header,body>footer{max-width:none!important;zoom:1!important}body>*>div,body>*>main,body>*>section,body>*>article{max-width:none!important;zoom:1!important}body>*:only-child{display:flex!important;flex-direction:column!important;flex:1!important;min-height:1080px!important}body>*:only-child>*:nth-child(2),body>*:only-child>*:nth-child(3),body>*:only-child>*:last-child:not(:first-child){flex:1!important;display:flex!important;align-items:stretch!important}body>.content,body>*:nth-child(2),body>*:nth-child(3),body *>.content,body [class*=content]{flex:1!important;align-items:stretch!important;align-content:stretch!important;grid-auto-rows:1fr!important}[class*=card],[class*=item],[class*=step],[class*=milestone],[class*=feature]{justify-content:flex-start!important;gap:20px!important}</style>`;
254
+ const injection = overrideCss;
255
+ if (result.includes('</head>')) {
256
+ result = result.replace('</head>', `${injection}</head>`);
257
+ }
258
+ else if (result.includes('<head>')) {
259
+ result = result.replace('<head>', `<head>${injection}`);
260
+ }
261
+ else if (result.includes('<html')) {
262
+ result = result.replace(/<html[^>]*>/, (match) => `${match}<head>${injection}</head>`);
263
+ }
264
+ else {
265
+ result = injection + result;
266
+ }
267
+ return result;
268
+ }
269
+ function enforceMinFontSize(html) {
270
+ const MIN_PX = 26;
271
+ let result = html.replace(/font-size:\s*(\d+(?:\.\d+)?)px/g, (_match, size) => {
272
+ const px = parseFloat(size);
273
+ return (px > 12 && px < MIN_PX) ? `font-size:${MIN_PX}px` : _match;
274
+ });
275
+ result = result.replace(/font-size:\s*(\d+(?:\.\d+)?)pt/g, (_match, size) => {
276
+ const pt = parseFloat(size);
277
+ const px = pt * 1.333;
278
+ return (px > 12 && px < MIN_PX) ? `font-size:${MIN_PX}px` : _match;
279
+ });
280
+ result = result.replace(/font-size:\s*(\d+(?:\.\d+)?)r?em/g, (_match, size) => {
281
+ const em = parseFloat(size);
282
+ const px = em * 16;
283
+ return (px > 12 && px < MIN_PX) ? `font-size:${MIN_PX}px` : _match;
284
+ });
285
+ result = result.replace(/font-size:\s*(\d+(?:\.\d+)?)%/g, (_match, size) => {
286
+ const pct = parseFloat(size);
287
+ const px = pct / 100 * 16;
288
+ return (px > 12 && px < MIN_PX) ? `font-size:${MIN_PX}px` : _match;
289
+ });
290
+ return result;
291
+ }
292
+ function ensureSafeBodyPadding(html) {
293
+ const safeStyle = `<style>body{padding-top:20px!important;padding-bottom:40px!important;min-height:auto!important}body>div:last-child,body>section:last-child{margin-bottom:0!important;padding-bottom:0!important}</style>`;
294
+ if (html.includes('</head>')) {
295
+ return html.replace('</head>', `${safeStyle}</head>`);
296
+ }
297
+ return html;
298
+ }
299
+ function stripGradientTextEffects(html) {
300
+ let result = html.replace(/-webkit-text-fill-color:\s*transparent/gi, '-webkit-text-fill-color:initial');
301
+ result = result.replace(/background-clip:\s*text/gi, 'background-clip:initial');
302
+ result = result.replace(/-webkit-background-clip:\s*text/gi, '-webkit-background-clip:initial');
303
+ return result;
304
+ }
305
+ function removeAbsolutePositioning(html) {
306
+ let result = html.replace(/style="([^"]*)position:\s*absolute([^"]*)"/gi, (match, before, after) => {
307
+ if (/(?:width|height):\s*[1-5]?\dpx/i.test(before + after) || /opacity:\s*0\.[0-4]/i.test(before + after)) {
308
+ return match;
309
+ }
310
+ let cleaned = `${before}position:static${after}`;
311
+ cleaned = cleaned.replace(/(?:^|;)\s*(?:top|left|right|bottom):\s*[^;]+/gi, '');
312
+ return `style="${cleaned}"`;
313
+ });
314
+ result = result.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/gi, (_m, open, css, close) => {
315
+ let fixed = css.replace(/position:\s*absolute/gi, 'position:static');
316
+ fixed = fixed.replace(/position:\s*static([^}]*)/gi, (ruleMatch) => {
317
+ return ruleMatch.replace(/(?:^|;)\s*(?:top|left|right|bottom):\s*[^;{}]+/gi, '');
318
+ });
319
+ return open + fixed + close;
320
+ });
321
+ result = result.replace(/transform:\s*translate[^;)]*\)/gi, 'transform:none');
322
+ result = result.replace(/transform:\s*scale\(\s*0\.\d+\s*\)/gi, 'transform:none');
323
+ result = result.replace(/transform:\s*scale\(\s*0\.\d+\s*,\s*0\.\d+\s*\)/gi, 'transform:none');
324
+ result = result.replace(/zoom:\s*0\.\d+/gi, 'zoom:1');
325
+ return result;
326
+ }
327
+ function injectTitleContrastFix(html, designTextColor) {
328
+ const safeColor = designTextColor.replace(/'/g, "\\'");
329
+ const script = `<script>(function(){` +
330
+ `var dc='${safeColor}';` +
331
+ `function lum(c){var m=c.match(/[\\d.]+/g);if(!m||m.length<3)return -1;` +
332
+ `var s=[m[0]/255,m[1]/255,m[2]/255].map(function(v){return v<=0.03928?v/12.92:Math.pow((v+0.055)/1.055,2.4)});` +
333
+ `return 0.2126*s[0]+0.7152*s[1]+0.0722*s[2]}` +
334
+ `function getBg(el){while(el){var s=getComputedStyle(el);var bg=s.backgroundColor;` +
335
+ `var m=bg.match(/[\\d.]+/g);if(m&&m.length>=3){if(m.length<4||parseFloat(m[3])>0.1)return bg}` +
336
+ `el=el.parentElement}return'rgb(255,255,255)'}` +
337
+ `var els=document.querySelectorAll('h1,h2');` +
338
+ `for(var i=0;i<els.length;i++){var el=els[i];var cs=getComputedStyle(el);` +
339
+ `var tfc=cs.webkitTextFillColor||'';` +
340
+ `if(tfc==='transparent'||tfc==='rgba(0, 0, 0, 0)'){` +
341
+ `el.style.setProperty('-webkit-text-fill-color','initial','important')}` +
342
+ `if(parseFloat(cs.opacity)<0.6){el.style.setProperty('opacity','1','important')}` +
343
+ `var fg=cs.color;var bg=getBg(el);var fl=lum(fg),bl=lum(bg);` +
344
+ `if(fl>=0&&bl>=0){var r=(Math.max(fl,bl)+0.05)/(Math.min(fl,bl)+0.05);` +
345
+ `if(r<3){el.style.setProperty('color',dc,'important');` +
346
+ `el.style.setProperty('-webkit-text-fill-color',dc,'important')}}}` +
347
+ `})()<\/script>`;
348
+ if (html.includes('</body>')) {
349
+ return html.replace('</body>', `${script}</body>`);
350
+ }
351
+ return html + script;
352
+ }
353
+ function injectMeasureCss(html) {
354
+ let result = html.replace(/<meta\s+name=["']viewport["'][^>]*>/gi, '');
355
+ const measureCss = `<style>*{box-sizing:border-box;word-break:keep-all;overflow-wrap:break-word;overflow:visible!important;max-height:none!important}html{width:2040px!important;height:auto!important;min-height:auto!important;margin:0!important}body{width:1920px!important;min-width:1920px!important;height:auto!important;min-height:auto!important;overflow:visible!important;margin:0!important}</style>`;
356
+ const injection = measureCss;
357
+ if (result.includes('</head>')) {
358
+ result = result.replace('</head>', `${injection}</head>`);
359
+ }
360
+ else if (result.includes('<head>')) {
361
+ result = result.replace('<head>', `<head>${injection}`);
362
+ }
363
+ else if (result.includes('<html')) {
364
+ result = result.replace(/<html[^>]*>/, (match) => `${match}<head>${injection}</head>`);
365
+ }
366
+ else {
367
+ result = injection + result;
368
+ }
369
+ const measureScript = `<script>document.title='SH:'+document.documentElement.scrollHeight</script>`;
370
+ if (result.includes('</body>')) {
371
+ result = result.replace('</body>', `${measureScript}</body>`);
372
+ }
373
+ else if (result.includes('</html>')) {
374
+ result = result.replace('</html>', `<body>${measureScript}</body></html>`);
375
+ }
376
+ else {
377
+ result += `</style></head><body>${measureScript}</body></html>`;
378
+ }
379
+ return result;
380
+ }
381
+ function injectFillMeasureCss(html) {
382
+ let result = html.replace(/<meta\s+name=["']viewport["'][^>]*>/gi, '');
383
+ const fillCss = `<style>*{box-sizing:border-box;word-break:keep-all;overflow-wrap:break-word;min-height:auto!important;height:auto!important}html{width:2040px!important;margin:0!important;height:auto!important}body{width:1920px!important;min-width:1920px!important;margin:0!important;display:block!important;height:auto!important;min-height:auto!important;overflow:visible!important}body>*{flex:none!important}body *{flex-grow:0!important;flex-shrink:1!important;flex-basis:auto!important}</style>`;
384
+ const measureScript = `<script>document.title='SH:'+document.documentElement.scrollHeight</script>`;
385
+ if (result.includes('</head>')) {
386
+ result = result.replace('</head>', `${fillCss}</head>`);
387
+ }
388
+ else if (result.includes('<head>')) {
389
+ result = result.replace('<head>', `<head>${fillCss}`);
390
+ }
391
+ else if (result.includes('<html')) {
392
+ result = result.replace(/<html[^>]*>/, (match) => `${match}<head>${fillCss}</head>`);
393
+ }
394
+ else {
395
+ result = fillCss + result;
396
+ }
397
+ if (result.includes('</body>')) {
398
+ result = result.replace('</body>', `${measureScript}</body>`);
399
+ }
400
+ else if (result.includes('</html>')) {
401
+ result = result.replace('</html>', `<body>${measureScript}</body></html>`);
402
+ }
403
+ else {
404
+ result += `</style></head><body>${measureScript}</body></html>`;
405
+ }
406
+ return result;
407
+ }
408
+ function escapeHtml(text) {
409
+ return text
410
+ .replace(/&/g, '&amp;')
411
+ .replace(/</g, '&lt;')
412
+ .replace(/>/g, '&gt;')
413
+ .replace(/"/g, '&quot;');
414
+ }
415
+ function buildTitleSlideHtml(design, mainTitle, subtitle, date, _slideNum) {
416
+ return `<!DOCTYPE html>
417
+ <html lang="ko">
418
+ <head>
419
+ <meta charset="UTF-8">
420
+ <style>
421
+ * { margin: 0; padding: 0; box-sizing: border-box; }
422
+ html { background-color: ${design.primary_color}; }
423
+ html, body { width: 1920px; height: 1080px; overflow: hidden; }
424
+ body {
425
+ background: linear-gradient(135deg, ${design.primary_color} 0%, ${design.gradient_end} 60%, ${design.primary_color} 100%);
426
+ display: flex;
427
+ flex-direction: column;
428
+ align-items: center;
429
+ justify-content: center;
430
+ font-family: "${design.font_title}", "Segoe UI", sans-serif;
431
+ }
432
+ body::before {
433
+ content: '';
434
+ display: block;
435
+ width: 100%;
436
+ height: 6px;
437
+ background: linear-gradient(90deg, transparent, ${design.accent_color}, transparent);
438
+ flex-shrink: 0;
439
+ }
440
+ .slide-content {
441
+ text-align: center;
442
+ max-width: 1400px;
443
+ padding: 0 60px;
444
+ }
445
+ .main-title {
446
+ font-size: 96px;
447
+ font-weight: 800;
448
+ color: #ffffff;
449
+ letter-spacing: -2px;
450
+ text-shadow: 0 6px 40px rgba(0,0,0,0.25);
451
+ line-height: 1.1;
452
+ margin-bottom: 32px;
453
+ }
454
+ .accent-bar {
455
+ width: 120px; height: 5px;
456
+ background: ${design.accent_color};
457
+ margin: 0 auto 32px;
458
+ border-radius: 3px;
459
+ box-shadow: 0 0 20px ${design.accent_color}40;
460
+ }
461
+ .subtitle {
462
+ font-size: 32px;
463
+ font-weight: 400;
464
+ color: rgba(255,255,255,0.88);
465
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
466
+ line-height: 1.5;
467
+ margin-bottom: 16px;
468
+ }
469
+ .date-text {
470
+ font-size: 22px;
471
+ font-weight: 300;
472
+ color: rgba(255,255,255,0.55);
473
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
474
+ }
475
+ </style>
476
+ </head>
477
+ <body>
478
+ <div class="slide-content">
479
+ <div class="main-title">${escapeHtml(mainTitle)}</div>
480
+ <div class="accent-bar"></div>
481
+ ${subtitle ? `<div class="subtitle">${escapeHtml(subtitle)}</div>` : ''}
482
+ <div class="date-text">${escapeHtml(date)}</div>
483
+ </div>
484
+ <style>body{align-items:center!important;justify-content:center!important}.slide-content{flex:unset!important;min-height:unset!important;display:flex!important;flex-direction:column!important;align-items:center!important;justify-content:center!important}.slide-content>*{flex:unset!important;min-height:unset!important}</style>
485
+ </body>
486
+ </html>`;
487
+ }
488
+ function buildClosingSlideHtml(design, companyName, _slideNum, language) {
489
+ const thankYou = language === 'ko' ? '감사합니다' : 'Thank You';
490
+ return `<!DOCTYPE html>
491
+ <html lang="${language}">
492
+ <head>
493
+ <meta charset="UTF-8">
494
+ <style>
495
+ * { margin: 0; padding: 0; box-sizing: border-box; }
496
+ html { background-color: ${design.primary_color}; }
497
+ html, body { width: 1920px; height: 1080px; overflow: hidden; }
498
+ body {
499
+ background: linear-gradient(135deg, ${design.primary_color} 0%, ${design.gradient_end} 60%, ${design.primary_color} 100%);
500
+ display: flex;
501
+ flex-direction: column;
502
+ align-items: center;
503
+ justify-content: center;
504
+ font-family: "${design.font_title}", "Segoe UI", sans-serif;
505
+ }
506
+ body::after {
507
+ content: '';
508
+ display: block;
509
+ width: 100%;
510
+ height: 6px;
511
+ background: linear-gradient(90deg, transparent, ${design.accent_color}, transparent);
512
+ flex-shrink: 0;
513
+ }
514
+ .slide-content {
515
+ text-align: center;
516
+ }
517
+ .thank-you {
518
+ font-size: 96px;
519
+ font-weight: 800;
520
+ color: #ffffff;
521
+ letter-spacing: -1px;
522
+ text-shadow: 0 6px 40px rgba(0,0,0,0.25);
523
+ margin-bottom: 32px;
524
+ }
525
+ .accent-bar {
526
+ width: 100px; height: 5px;
527
+ background: ${design.accent_color};
528
+ margin: 0 auto 32px;
529
+ border-radius: 3px;
530
+ box-shadow: 0 0 20px ${design.accent_color}40;
531
+ }
532
+ .company {
533
+ font-size: 36px;
534
+ font-weight: 500;
535
+ color: rgba(255,255,255,0.80);
536
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
537
+ }
538
+ </style>
539
+ </head>
540
+ <body>
541
+ <div class="slide-content">
542
+ <div class="thank-you">${escapeHtml(thankYou)}</div>
543
+ <div class="accent-bar"></div>
544
+ <div class="company">${escapeHtml(companyName)}</div>
545
+ </div>
546
+ <style>body{align-items:center!important;justify-content:center!important}.slide-content{flex:unset!important;min-height:unset!important;display:flex!important;flex-direction:column!important;align-items:center!important;justify-content:center!important}.slide-content>*{flex:unset!important;min-height:unset!important}</style>
547
+ </body>
548
+ </html>`;
549
+ }
550
+ function isOverviewSlide(title, slideIndex) {
551
+ if (slideIndex !== 1)
552
+ return false;
553
+ const overviewKeywords = /개요|목차|overview|agenda|outline|순서|발표\s*구성|contents|목록/i;
554
+ return overviewKeywords.test(title);
555
+ }
556
+ function parseOverviewItems(contentDirection) {
557
+ const items = [];
558
+ const lines = contentDirection.split(/\n/).filter(l => l.trim());
559
+ for (const line of lines) {
560
+ const match = line.match(/^\d+[\.\)]\s*(.+?)(?:\s*[-–—:]\s*(.+))?$/);
561
+ if (match) {
562
+ items.push({ title: match[1].trim(), desc: match[2]?.trim() || '' });
563
+ }
564
+ }
565
+ if (items.length === 0) {
566
+ const parts = contentDirection.split(/[,;·•]/).map(s => s.trim()).filter(Boolean);
567
+ for (const part of parts) {
568
+ const sepMatch = part.match(/^(.+?)(?:\s*[-–—:]\s*(.+))?$/);
569
+ if (sepMatch) {
570
+ items.push({ title: sepMatch[1].trim(), desc: sepMatch[2]?.trim() || '' });
571
+ }
572
+ }
573
+ }
574
+ return items.slice(0, 5);
575
+ }
576
+ function buildOverviewSlideHtml(design, title, subtitle, items, slideNum) {
577
+ const badgeColors = [
578
+ design.primary_color,
579
+ design.accent_color,
580
+ design.gradient_end,
581
+ design.primary_color,
582
+ design.accent_color,
583
+ ];
584
+ const itemCount = items.length;
585
+ const topRow = itemCount <= 3 ? items : items.slice(0, Math.ceil(itemCount / 2));
586
+ const bottomRow = itemCount <= 3 ? [] : items.slice(Math.ceil(itemCount / 2));
587
+ function renderCard(item, idx) {
588
+ const color = badgeColors[idx % badgeColors.length];
589
+ return `
590
+ <div class="card">
591
+ <div class="badge" style="background:${color}">${idx + 1}</div>
592
+ <div class="card-title">${escapeHtml(item.title)}</div>
593
+ ${item.desc ? `<div class="card-desc">${escapeHtml(item.desc)}</div>` : ''}
594
+ </div>`;
595
+ }
596
+ return `<!DOCTYPE html>
597
+ <html lang="ko">
598
+ <head>
599
+ <meta charset="UTF-8">
600
+ <style>
601
+ * { margin: 0; padding: 0; box-sizing: border-box; }
602
+ html, body { width: 1920px; height: 1080px; overflow: hidden; }
603
+ body {
604
+ background: ${design.background_color};
605
+ font-family: "${design.font_body}", "${design.font_title}", "Segoe UI", "Malgun Gothic", sans-serif;
606
+ display: flex; flex-direction: column;
607
+ word-break: keep-all; overflow-wrap: break-word;
608
+ }
609
+ .header {
610
+ background: linear-gradient(135deg, ${design.primary_color}, ${design.gradient_end});
611
+ padding: 48px 80px 40px;
612
+ flex-shrink: 0;
613
+ }
614
+ .header-title {
615
+ font-size: 52px; font-weight: 800; color: #ffffff;
616
+ font-family: "${design.font_title}", "Segoe UI", sans-serif;
617
+ margin-bottom: 8px;
618
+ }
619
+ .header-subtitle {
620
+ font-size: 24px; font-weight: 400; color: rgba(255,255,255,0.75);
621
+ }
622
+ .content {
623
+ flex: 1; display: flex; flex-direction: column;
624
+ padding: 48px 80px 40px;
625
+ gap: 24px;
626
+ justify-content: center;
627
+ }
628
+ .row {
629
+ display: flex; gap: 24px;
630
+ justify-content: center;
631
+ }
632
+ .card {
633
+ flex: 1;
634
+ max-width: 340px;
635
+ background: #ffffff;
636
+ border-radius: 16px;
637
+ padding: 36px 32px;
638
+ box-shadow: 0 4px 20px rgba(0,0,0,0.06);
639
+ display: flex; flex-direction: column;
640
+ align-items: center; text-align: center;
641
+ gap: 12px;
642
+ transition: none;
643
+ }
644
+ .badge {
645
+ width: 44px; height: 44px;
646
+ border-radius: 50%;
647
+ color: #ffffff;
648
+ font-size: 20px; font-weight: 700;
649
+ display: flex; align-items: center; justify-content: center;
650
+ flex-shrink: 0;
651
+ }
652
+ .card-title {
653
+ font-size: 26px; font-weight: 700; color: ${design.text_color};
654
+ line-height: 1.3;
655
+ }
656
+ .card-desc {
657
+ font-size: 22px; font-weight: 400; color: ${design.text_color}aa;
658
+ line-height: 1.5;
659
+ }
660
+ .page-num {
661
+ position: absolute;
662
+ bottom: 24px; right: 44px;
663
+ font-size: 13px;
664
+ color: ${design.text_color}55;
665
+ }
666
+ </style>
667
+ </head>
668
+ <body>
669
+ <div class="header">
670
+ <div class="header-title">${escapeHtml(title)}</div>
671
+ ${subtitle ? `<div class="header-subtitle">${escapeHtml(subtitle)}</div>` : ''}
672
+ </div>
673
+ <div class="content">
674
+ <div class="row">
675
+ ${topRow.map((item, idx) => renderCard(item, idx)).join('')}
676
+ </div>
677
+ ${bottomRow.length > 0 ? `<div class="row">
678
+ ${bottomRow.map((item, idx) => renderCard(item, topRow.length + idx)).join('')}
679
+ </div>` : ''}
680
+ </div>
681
+ <div class="page-num">${slideNum}</div>
682
+ </body>
683
+ </html>`;
684
+ }
685
+ function getTempDir() {
686
+ const platform = getPlatform();
687
+ if (platform === 'wsl') {
688
+ return { writePath: '/mnt/c/temp', winPath: 'C:\\temp' };
689
+ }
690
+ return { writePath: 'C:\\temp', winPath: 'C:\\temp' };
691
+ }
692
+ function ensureTempDir(writePath) {
693
+ if (!fs.existsSync(writePath)) {
694
+ fs.mkdirSync(writePath, { recursive: true });
695
+ }
696
+ }
697
+ function normalizeDesign(raw) {
698
+ return {
699
+ primary_color: raw['primary_color'] || DEFAULT_DESIGN.primary_color,
700
+ accent_color: raw['accent_color'] || DEFAULT_DESIGN.accent_color,
701
+ background_color: raw['background_color'] || DEFAULT_DESIGN.background_color,
702
+ text_color: raw['text_color'] || DEFAULT_DESIGN.text_color,
703
+ accent_light: raw['accent_light'] || DEFAULT_DESIGN.accent_light,
704
+ gradient_end: raw['gradient_end'] || DEFAULT_DESIGN.gradient_end,
705
+ font_title: raw['font_title'] || DEFAULT_DESIGN.font_title,
706
+ font_body: raw['font_body'] || DEFAULT_DESIGN.font_body,
707
+ mood: raw['mood'] || DEFAULT_DESIGN.mood,
708
+ design_notes: raw['design_notes'] || DEFAULT_DESIGN.design_notes,
709
+ };
710
+ }
711
+ async function runStructured(llmClient, instruction, explicitSavePath) {
712
+ const startTime = Date.now();
713
+ const phaseLogger = getSubAgentPhaseLogger();
714
+ const toolCallLogger = getSubAgentToolCallLogger();
715
+ let totalToolCalls = 0;
716
+ const timestamp = Date.now();
717
+ logger.enter('PPT-Create.runStructured');
718
+ const hasKorean = /[\uac00-\ud7af\u1100-\u11ff]/.test(instruction);
719
+ const language = hasKorean ? 'ko' : 'en';
720
+ if (phaseLogger)
721
+ phaseLogger('powerpoint-create', 'enhancement', 'Generating creative guidance...');
722
+ let guidance = '';
723
+ try {
724
+ const enhRes = await llmClient.chatCompletion({
725
+ messages: [
726
+ { role: 'system', content: PPT_CREATE_ENHANCEMENT_PROMPT },
727
+ { role: 'user', content: instruction },
728
+ ],
729
+ temperature: 0.7,
730
+ max_tokens: 2000,
731
+ });
732
+ const enhMsg = enhRes.choices[0]?.message;
733
+ guidance = enhMsg ? extractContent(enhMsg) : '';
734
+ if (guidance.length < 1500) {
735
+ logger.warn('PPT enhancement too short, retrying', { length: guidance.length });
736
+ const retryEnhRes = await llmClient.chatCompletion({
737
+ messages: [
738
+ { role: 'system', content: PPT_CREATE_ENHANCEMENT_PROMPT },
739
+ { role: 'user', content: `${instruction}\n\nIMPORTANT: Produce a COMPLETE, DETAILED design system and content plan. Include ALL 7 sections: DOCUMENT_TYPE, AUDIENCE, MOOD, COLOR PALETTE (6 hex values), FONTS, SLIDE PLAN (10-15 slides), DESIGN NOTES. Do NOT stop early.` },
740
+ ],
741
+ temperature: 0.7,
742
+ max_tokens: 2000,
743
+ });
744
+ const retryMsg = retryEnhRes.choices[0]?.message;
745
+ const retryGuidance = retryMsg ? extractContent(retryMsg) : '';
746
+ if (retryGuidance.length > guidance.length) {
747
+ guidance = retryGuidance;
748
+ }
749
+ }
750
+ if (phaseLogger)
751
+ phaseLogger('powerpoint-create', 'enhancement', `Done (${guidance.length} chars)`);
752
+ }
753
+ catch (e) {
754
+ logger.warn('PPT enhancement failed, proceeding without', { error: String(e) });
755
+ }
756
+ const enhancedInstruction = guidance
757
+ ? `${instruction}\n\n═══ CREATIVE GUIDANCE ═══\n${guidance}\n═══ END GUIDANCE ═══`
758
+ : instruction;
759
+ if (phaseLogger)
760
+ phaseLogger('powerpoint-create', 'planning', 'Generating JSON plan...');
761
+ let plan = null;
762
+ try {
763
+ const planRes = await llmClient.chatCompletion({
764
+ messages: [
765
+ { role: 'system', content: PPT_STRUCTURED_PLANNING_PROMPT },
766
+ { role: 'user', content: enhancedInstruction },
767
+ ],
768
+ temperature: 0.4,
769
+ max_tokens: 8000,
770
+ });
771
+ const planMsg = planRes.choices[0]?.message;
772
+ const finishReason = planRes.choices[0]?.finish_reason;
773
+ const rawPlan = planMsg ? extractContent(planMsg) : '';
774
+ if (finishReason === 'length') {
775
+ logger.warn('PPT planning response was truncated (finish_reason=length)');
776
+ }
777
+ logger.debug('PPT planning raw response', { length: rawPlan.length, finishReason, first200: rawPlan.slice(0, 200) });
778
+ plan = rawPlan ? parseJsonPlan(rawPlan) : null;
779
+ if (plan) {
780
+ plan.design = normalizeDesign(plan.design);
781
+ const validationError = validateAndFixPlan(plan);
782
+ if (validationError) {
783
+ logger.warn('PPT plan validation failed', { error: validationError });
784
+ if (phaseLogger)
785
+ phaseLogger('powerpoint-create', 'planning', `Validation failed: ${validationError}. Retrying...`);
786
+ const retryRes = await llmClient.chatCompletion({
787
+ messages: [
788
+ { role: 'system', content: PPT_STRUCTURED_PLANNING_PROMPT },
789
+ { role: 'user', content: enhancedInstruction },
790
+ { role: 'assistant', content: rawPlan },
791
+ { role: 'user', content: `ERROR: ${validationError}\n\nFix the issues and output the corrected JSON. Remember: aim for 10-12 slides with REAL content data in each content_direction.` },
792
+ ],
793
+ temperature: 0.2,
794
+ max_tokens: 8000,
795
+ });
796
+ const retryMsg = retryRes.choices[0]?.message;
797
+ const retryRaw = retryMsg ? extractContent(retryMsg) : '';
798
+ const retryPlan = retryRaw ? parseJsonPlan(retryRaw) : null;
799
+ if (retryPlan) {
800
+ retryPlan.design = normalizeDesign(retryPlan.design);
801
+ const retryError = validateAndFixPlan(retryPlan);
802
+ if (!retryError) {
803
+ plan = retryPlan;
804
+ if (phaseLogger)
805
+ phaseLogger('powerpoint-create', 'planning', `Retry succeeded (${plan.slides.length} slides)`);
806
+ }
807
+ else {
808
+ plan = null;
809
+ }
810
+ }
811
+ else {
812
+ plan = null;
813
+ }
814
+ }
815
+ else {
816
+ if (phaseLogger)
817
+ phaseLogger('powerpoint-create', 'planning', `Done (${plan.slides.length} slides)`);
818
+ }
819
+ }
820
+ else {
821
+ logger.warn('PPT JSON plan parsing failed');
822
+ if (phaseLogger)
823
+ phaseLogger('powerpoint-create', 'planning', 'JSON parsing failed. Falling back.');
824
+ }
825
+ }
826
+ catch (e) {
827
+ logger.warn('PPT planning failed', { error: String(e) });
828
+ if (phaseLogger)
829
+ phaseLogger('powerpoint-create', 'planning', 'Planning error. Falling back.');
830
+ }
831
+ if (!plan) {
832
+ logger.error('PPT planning failed after retries — cannot create presentation');
833
+ return {
834
+ success: false,
835
+ error: 'Failed to generate presentation plan. Please try again.',
836
+ };
837
+ }
838
+ if (plan.slides.length > 15) {
839
+ logger.warn(`PPT plan has ${plan.slides.length} slides, capping to 15`);
840
+ const firstSlide = plan.slides[0];
841
+ const lastSlide = plan.slides[plan.slides.length - 1];
842
+ const contentSlides = plan.slides.slice(1, -1).slice(0, 13);
843
+ plan.slides = [firstSlide, ...contentSlides, lastSlide];
844
+ if (phaseLogger)
845
+ phaseLogger('powerpoint-create', 'planning', `Capped to ${plan.slides.length} slides`);
846
+ }
847
+ const userYearMatch = instruction.match(/(\d{4})년/);
848
+ if (userYearMatch) {
849
+ const userYear = userYearMatch[1];
850
+ for (const slide of plan.slides) {
851
+ if (slide.type === 'content' && slide.content_direction) {
852
+ if (!slide.content_direction.includes(`${userYear}년`)) {
853
+ slide.content_direction += ` (Note: This report covers ${userYear}년 data.)`;
854
+ }
855
+ }
856
+ }
857
+ }
858
+ const companyMatch = instruction.match(/회사명\s*[::]\s*([^\s,,、]+)/);
859
+ if (companyMatch && companyMatch[1]) {
860
+ const companyName_ = companyMatch[1];
861
+ const titleSlide = plan.slides.find(s => s.type === 'title');
862
+ if (titleSlide) {
863
+ if (titleSlide.title.trim() !== companyName_) {
864
+ const originalTitle = titleSlide.title;
865
+ titleSlide.title = companyName_;
866
+ if (!titleSlide.content_direction?.includes(originalTitle)) {
867
+ const stripped = originalTitle.replace(companyName_, '').replace(/^\s*[-–—:|\s]+/, '').trim();
868
+ const subtitle = stripped || originalTitle;
869
+ titleSlide.content_direction = subtitle + (titleSlide.content_direction ? '\n' + titleSlide.content_direction : '');
870
+ }
871
+ }
872
+ }
873
+ }
874
+ let layoutTemplates = [];
875
+ let slideSkeletons = new Map();
876
+ if (plan.design) {
877
+ try {
878
+ if (phaseLogger)
879
+ phaseLogger('powerpoint-create', 'layout-set', 'Generating custom layout components...');
880
+ const layoutSetPrompt = buildLayoutSetPrompt(plan.design);
881
+ const layoutRes = await llmClient.chatCompletion({
882
+ messages: [
883
+ { role: 'system', content: layoutSetPrompt },
884
+ { role: 'user', content: 'Generate the layout components now. Start with ---LAYOUT: and end each with ---END---.' },
885
+ ],
886
+ temperature: 0.7,
887
+ max_tokens: 6000,
888
+ }, { maxRetries: 2 });
889
+ const layoutRaw = layoutRes.choices[0]?.message;
890
+ const layoutText = layoutRaw ? extractContent(layoutRaw) : '';
891
+ layoutTemplates = parseLayoutSet(layoutText);
892
+ logger.info(`Layout Set: generated ${layoutTemplates.length} templates: ${layoutTemplates.map(l => l.name).join(', ')}`);
893
+ if (phaseLogger)
894
+ phaseLogger('powerpoint-create', 'layout-set', `Generated ${layoutTemplates.length} layout templates`);
895
+ }
896
+ catch (e) {
897
+ logger.warn(`Layout Set generation failed, will use fallback: ${e}`);
898
+ }
899
+ }
900
+ if (layoutTemplates.length >= 4) {
901
+ try {
902
+ if (phaseLogger)
903
+ phaseLogger('powerpoint-create', 'skeleton', 'Generating slide skeletons...');
904
+ const skeletonPrompt = buildAllSkeletonsPrompt(plan.slides, layoutTemplates);
905
+ const skeletonRes = await llmClient.chatCompletion({
906
+ messages: [
907
+ { role: 'system', content: skeletonPrompt },
908
+ { role: 'user', content: 'Generate skeletons for all content slides. Use ===SLIDE:N=== format.' },
909
+ ],
910
+ temperature: 0.3,
911
+ max_tokens: 8000,
912
+ }, { maxRetries: 2 });
913
+ const skeletonRaw = skeletonRes.choices[0]?.message;
914
+ const skeletonText = skeletonRaw ? extractContent(skeletonRaw) : '';
915
+ slideSkeletons = parseSkeletons(skeletonText);
916
+ logger.info(`Skeletons: generated ${slideSkeletons.size} slide skeletons`);
917
+ if (phaseLogger)
918
+ phaseLogger('powerpoint-create', 'skeleton', `Generated ${slideSkeletons.size} slide skeletons`);
919
+ }
920
+ catch (e) {
921
+ logger.warn(`Skeleton generation failed, will use fallback: ${e}`);
922
+ }
923
+ }
924
+ if (phaseLogger)
925
+ phaseLogger('powerpoint-create', 'execution', 'Starting HTML rendering pipeline...');
926
+ const { writePath: tempWritePath, winPath: tempWinPath } = getTempDir();
927
+ ensureTempDir(tempWritePath);
928
+ let savePath = explicitSavePath;
929
+ if (!savePath) {
930
+ const fullPathMatch = instruction.match(/([A-Za-z]:\\[^\s,]+\.pptx|\/[^\s,]+\.pptx)/i);
931
+ if (fullPathMatch) {
932
+ savePath = fullPathMatch[1];
933
+ }
934
+ else {
935
+ const nameMatch = instruction.match(/([\w][\w\-_.]*\.pptx)/i);
936
+ if (nameMatch) {
937
+ savePath = `C:\\temp\\${nameMatch[1]}`;
938
+ }
939
+ }
940
+ }
941
+ const titleSlidePlanForDate = plan.slides.find(s => s.type === 'title');
942
+ const dateSearchTexts = [
943
+ instruction,
944
+ titleSlidePlanForDate?.title || '',
945
+ titleSlidePlanForDate?.content_direction || '',
946
+ ];
947
+ let kstDate = '';
948
+ for (const text of dateSearchTexts) {
949
+ const dateMatch = text.match(/(\d{4})년\s*(\d{1,2})\s*(월|분기)/);
950
+ if (dateMatch) {
951
+ kstDate = `${dateMatch[1]}년 ${dateMatch[2]}${dateMatch[3]}`;
952
+ break;
953
+ }
954
+ }
955
+ if (!kstDate) {
956
+ const kstNow = new Date(Date.now() + 9 * 60 * 60 * 1000);
957
+ kstDate = `${kstNow.getUTCFullYear()}년 ${kstNow.getUTCMonth() + 1}월`;
958
+ }
959
+ const titleSlidePlan = plan.slides.find(s => s.type === 'title');
960
+ const rawTitleText = titleSlidePlan?.title || '';
961
+ const titleSeps = [' - ', ' – ', ' — ', ': ', ' | '];
962
+ let companyName = rawTitleText;
963
+ let titleSubtitle = '';
964
+ for (const sep of titleSeps) {
965
+ const idx = rawTitleText.indexOf(sep);
966
+ if (idx > 0) {
967
+ companyName = rawTitleText.slice(0, idx).trim();
968
+ titleSubtitle = rawTitleText.slice(idx + sep.length).trim();
969
+ break;
970
+ }
971
+ }
972
+ if (!titleSubtitle && titleSlidePlan) {
973
+ titleSubtitle = ((titleSlidePlan.content_direction || '').split('\n')[0] || '').trim().slice(0, 120);
974
+ }
975
+ if (/로고|슬로건|연락처|contact|logo|placeholder/i.test(titleSubtitle)) {
976
+ titleSubtitle = '';
977
+ }
978
+ const createResult = await powerpointClient.powerpointCreate();
979
+ totalToolCalls++;
980
+ if (toolCallLogger)
981
+ toolCallLogger('powerpoint-create', 'powerpoint_create', {}, createResult.success ? 'Created' : createResult['error'] || '', createResult.success, 0, totalToolCalls);
982
+ if (!createResult.success) {
983
+ return { success: false, error: `Failed to create presentation: ${createResult['error']}` };
984
+ }
985
+ const builtSlides = [];
986
+ let failCount = 0;
987
+ const tempFiles = [];
988
+ for (let i = 0; i < plan.slides.length; i++) {
989
+ const slidePlan = plan.slides[i];
990
+ const slideNum = i + 1;
991
+ if (failCount >= 3) {
992
+ logger.warn('Too many slide failures, stopping');
993
+ break;
994
+ }
995
+ if (phaseLogger)
996
+ phaseLogger('powerpoint-create', 'execution', `Rendering slide ${slideNum}/${plan.slides.length}: ${slidePlan.title}`);
997
+ let html = null;
998
+ let htmlPrompt = null;
999
+ if (slidePlan.type === 'title') {
1000
+ html = buildTitleSlideHtml(plan.design, companyName, titleSubtitle, kstDate, slideNum);
1001
+ }
1002
+ else if (slidePlan.type === 'closing') {
1003
+ html = buildClosingSlideHtml(plan.design, companyName, slideNum, language);
1004
+ }
1005
+ else if (isOverviewSlide(slidePlan.title, i)) {
1006
+ const overviewItems = parseOverviewItems(slidePlan.content_direction || '');
1007
+ if (overviewItems.length >= 2) {
1008
+ const firstLine = (slidePlan.content_direction || '').split('\n')[0] || '';
1009
+ const overviewSubtitle = /^\d/.test(firstLine.trim()) ? '' : firstLine.trim();
1010
+ html = buildOverviewSlideHtml(plan.design, slidePlan.title, overviewSubtitle, overviewItems, slideNum);
1011
+ logger.info(`Slide ${slideNum}: Using code-generated overview template (${overviewItems.length} items)`);
1012
+ }
1013
+ }
1014
+ let slideLayoutType = 'cards';
1015
+ let usedSkeleton = false;
1016
+ if (!html && slidePlan.type !== 'title' && slidePlan.type !== 'closing') {
1017
+ const cleanedDirection = (slidePlan.content_direction || '')
1018
+ .replace(/\s*Layout\s*:\s*[^\n]*/gi, '')
1019
+ .trim();
1020
+ slideLayoutType = extractLayoutHint(slidePlan.content_direction || '');
1021
+ const skeletonInfo = slideSkeletons.get(slideNum);
1022
+ const matchedLayout = skeletonInfo
1023
+ ? layoutTemplates.find(l => l.name === skeletonInfo.layout)
1024
+ : null;
1025
+ if (skeletonInfo && matchedLayout) {
1026
+ usedSkeleton = true;
1027
+ logger.info(`Slide ${slideNum}: Using skeleton "${skeletonInfo.layout}" from Phase 4 (layoutType: ${slideLayoutType})`);
1028
+ htmlPrompt = buildFillPrompt(skeletonInfo.skeleton, matchedLayout.css, cleanedDirection, slidePlan.title, plan.design, i, plan.slides.length, language, slideLayoutType);
1029
+ }
1030
+ else {
1031
+ logger.info(`Slide ${slideNum}: Fallback to layout-specific prompt → "${slideLayoutType}"`);
1032
+ htmlPrompt = buildSlideHtmlPrompt(slidePlan.title, cleanedDirection, plan.design, i, plan.slides.length, language, slideLayoutType);
1033
+ }
1034
+ try {
1035
+ const htmlRes = await llmClient.chatCompletion({
1036
+ messages: [
1037
+ { role: 'system', content: htmlPrompt },
1038
+ { role: 'user', content: 'Generate the HTML slide now.' },
1039
+ ],
1040
+ temperature: 0.3,
1041
+ max_tokens: 8000,
1042
+ });
1043
+ const htmlMsg = htmlRes.choices[0]?.message;
1044
+ const rawHtml = htmlMsg ? extractContent(htmlMsg) : '';
1045
+ html = extractHtml(rawHtml);
1046
+ if (!html && rawHtml.length > 100) {
1047
+ logger.warn(`Slide ${slideNum}: HTML extraction failed, retrying`);
1048
+ const retryRes = await llmClient.chatCompletion({
1049
+ messages: [
1050
+ { role: 'system', content: htmlPrompt },
1051
+ { role: 'user', content: 'Generate the complete HTML document. Start with <!DOCTYPE html> and end with </html>. No markdown fences.' },
1052
+ ],
1053
+ temperature: 0.2,
1054
+ max_tokens: 4000,
1055
+ });
1056
+ const retryMsg = retryRes.choices[0]?.message;
1057
+ const retryRaw = retryMsg ? extractContent(retryMsg) : '';
1058
+ html = extractHtml(retryRaw);
1059
+ }
1060
+ }
1061
+ catch (e) {
1062
+ logger.warn(`Slide ${slideNum}: LLM call failed: ${e}`);
1063
+ }
1064
+ }
1065
+ if (!html) {
1066
+ logger.warn(`Slide ${slideNum}: Failed to generate HTML, skipping`);
1067
+ failCount++;
1068
+ continue;
1069
+ }
1070
+ const OVERFLOW_THRESHOLD = 1080;
1071
+ if (htmlPrompt) {
1072
+ const MAX_REGEN_ATTEMPTS = 2;
1073
+ for (let attempt = 0; attempt < MAX_REGEN_ATTEMPTS; attempt++) {
1074
+ const measureFileName = `hanseol_measure_${slideNum}_${timestamp}_${attempt}.html`;
1075
+ const measureWritePath = path.join(tempWritePath, measureFileName);
1076
+ const measureWinPath = `${tempWinPath}\\${measureFileName}`;
1077
+ try {
1078
+ fs.writeFileSync(measureWritePath, injectMeasureCss(html), 'utf-8');
1079
+ const contentHeight = await powerpointClient.measureHtmlHeight(measureWinPath);
1080
+ try {
1081
+ fs.unlinkSync(measureWritePath);
1082
+ }
1083
+ catch { }
1084
+ if (contentHeight <= OVERFLOW_THRESHOLD) {
1085
+ if (attempt > 0)
1086
+ logger.info(`Slide ${slideNum}: Fits after ${attempt} regeneration(s) (${contentHeight}px)`);
1087
+ break;
1088
+ }
1089
+ logger.warn(`Slide ${slideNum}: Content overflows (${contentHeight}px > ${OVERFLOW_THRESHOLD}), attempt ${attempt + 1}/${MAX_REGEN_ATTEMPTS}`);
1090
+ if (phaseLogger)
1091
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: overflow (${contentHeight}px), regen ${attempt + 1}/${MAX_REGEN_ATTEMPTS}...`);
1092
+ try {
1093
+ const regenRes = await llmClient.chatCompletion({
1094
+ messages: [
1095
+ { role: 'system', content: htmlPrompt },
1096
+ { role: 'user', content: `Generate the HTML slide now. Your previous version was ${contentHeight}px tall — it MUST fit in 1080px (with 60px top+bottom padding = 960px usable). Content was clipped by ${contentHeight - 1080}px.\n\nFix:\n- Reduce content: remove 2-3 least important bullets or rows from each section\n- Compact padding: cards 24px, gaps 12-16px\n- Keep fonts: title 40-48px, body 26px min\n- If 4+ cards/sections → reduce to 3\n- Target: 850-960px content height` },
1097
+ ],
1098
+ temperature: 0.2,
1099
+ max_tokens: 8000,
1100
+ });
1101
+ const regenMsg = regenRes.choices[0]?.message;
1102
+ const regenRaw = regenMsg ? extractContent(regenMsg) : '';
1103
+ const regenHtml = extractHtml(regenRaw);
1104
+ if (regenHtml) {
1105
+ html = regenHtml;
1106
+ logger.info(`Slide ${slideNum}: Regenerated HTML (attempt ${attempt + 1})`);
1107
+ }
1108
+ else {
1109
+ break;
1110
+ }
1111
+ }
1112
+ catch (e) {
1113
+ logger.warn(`Slide ${slideNum}: Overflow regeneration attempt ${attempt + 1} failed: ${e}`);
1114
+ break;
1115
+ }
1116
+ }
1117
+ catch {
1118
+ break;
1119
+ }
1120
+ }
1121
+ }
1122
+ const MIN_FILL_HEIGHT = 850;
1123
+ const MAX_FILL_ATTEMPTS = 3;
1124
+ if (htmlPrompt && slidePlan.type === 'content') {
1125
+ if (phaseLogger)
1126
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: starting fill measurement...`);
1127
+ for (let fillAttempt = 0; fillAttempt < MAX_FILL_ATTEMPTS; fillAttempt++) {
1128
+ const fillFileName = `hanseol_fill_${slideNum}_${timestamp}_${fillAttempt}.html`;
1129
+ const fillWritePath = path.join(tempWritePath, fillFileName);
1130
+ const fillWinPath = `${tempWinPath}\\${fillFileName}`;
1131
+ try {
1132
+ fs.writeFileSync(fillWritePath, injectFillMeasureCss(html), 'utf-8');
1133
+ const naturalHeight = await powerpointClient.measureHtmlHeight(fillWinPath);
1134
+ if (naturalHeight > 0) {
1135
+ try {
1136
+ fs.unlinkSync(fillWritePath);
1137
+ }
1138
+ catch { }
1139
+ }
1140
+ if (phaseLogger)
1141
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: fill=${naturalHeight}px (${Math.round(naturalHeight / 1080 * 100)}%), threshold=${MIN_FILL_HEIGHT}px`);
1142
+ if (naturalHeight > 0 && naturalHeight < MIN_FILL_HEIGHT) {
1143
+ const fillPct = Math.round(naturalHeight / 1080 * 100);
1144
+ logger.warn(`Slide ${slideNum}: Underfill — natural height ${naturalHeight}px (${fillPct}%). Attempt ${fillAttempt + 1}/${MAX_FILL_ATTEMPTS}...`);
1145
+ if (phaseLogger)
1146
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: underfill (${fillPct}%), regen attempt ${fillAttempt + 1}...`);
1147
+ try {
1148
+ const htmlExcerpt = html.length > 2000 ? html.slice(0, 2000) + '\n...(truncated)' : html;
1149
+ const fillRes = await llmClient.chatCompletion({
1150
+ messages: [
1151
+ { role: 'system', content: htmlPrompt },
1152
+ { role: 'assistant', content: htmlExcerpt },
1153
+ { role: 'user', content: `CRITICAL FEEDBACK: Your HTML above only fills ${fillPct}% of the slide vertically (natural height: ${naturalHeight}px, slide: 1080px). The slide looks EMPTY.\n\nFIX THESE ISSUES:\n1. Add MORE ACTUAL CONTENT — more bullet points, more data, more rows, more detail text\n2. ALL content elements MUST be DIRECT children of .content — NO wrapper divs\n3. Target: 85-95% fill (${Math.round(1080 * 0.85)}-${Math.round(1080 * 0.95)}px content height)\n\n${getUnderfillFixByLayout(slideLayoutType)}\n\nDo NOT use CSS tricks (flex:1, min-height) to stretch empty space — add real text content instead.\nRegenerate the COMPLETE HTML from <!DOCTYPE html> to </html>.` },
1154
+ ],
1155
+ temperature: 0.3,
1156
+ max_tokens: 8000,
1157
+ });
1158
+ const fillMsg = fillRes.choices[0]?.message;
1159
+ const fillRaw = fillMsg ? extractContent(fillMsg) : '';
1160
+ const fillHtml = extractHtml(fillRaw);
1161
+ if (fillHtml) {
1162
+ const overflowCheckFile = `hanseol_ocheck_${slideNum}_${timestamp}_${fillAttempt}.html`;
1163
+ const overflowCheckPath = path.join(tempWritePath, overflowCheckFile);
1164
+ const overflowCheckWin = `${tempWinPath}\\${overflowCheckFile}`;
1165
+ let overflowOk = true;
1166
+ try {
1167
+ fs.writeFileSync(overflowCheckPath, injectMeasureCss(fillHtml), 'utf-8');
1168
+ const regenHeight = await powerpointClient.measureHtmlHeight(overflowCheckWin);
1169
+ try {
1170
+ fs.unlinkSync(overflowCheckPath);
1171
+ }
1172
+ catch { }
1173
+ if (regenHeight > OVERFLOW_THRESHOLD) {
1174
+ logger.warn(`Slide ${slideNum}: Fill regen overflows (${regenHeight}px), keeping original`);
1175
+ overflowOk = false;
1176
+ }
1177
+ }
1178
+ catch {
1179
+ try {
1180
+ fs.unlinkSync(overflowCheckPath);
1181
+ }
1182
+ catch { }
1183
+ }
1184
+ if (!overflowOk)
1185
+ break;
1186
+ html = fillHtml;
1187
+ logger.info(`Slide ${slideNum}: Regenerated with more content (was ${fillPct}% fill, attempt ${fillAttempt + 1})`);
1188
+ continue;
1189
+ }
1190
+ }
1191
+ catch (e) {
1192
+ logger.warn(`Slide ${slideNum}: Fill regeneration failed: ${e}`);
1193
+ }
1194
+ break;
1195
+ }
1196
+ else if (naturalHeight > 0) {
1197
+ const fillPct = Math.round(naturalHeight / 1080 * 100);
1198
+ logger.info(`Slide ${slideNum}: Fill OK — ${naturalHeight}px (${fillPct}%)`);
1199
+ break;
1200
+ }
1201
+ else {
1202
+ if (phaseLogger)
1203
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: fill measure returned 0, skipping`);
1204
+ break;
1205
+ }
1206
+ }
1207
+ catch (fillErr) {
1208
+ if (phaseLogger)
1209
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: fill measure FAILED: ${fillErr}`);
1210
+ break;
1211
+ }
1212
+ }
1213
+ }
1214
+ if (html && slidePlan.type === 'content') {
1215
+ html = postProcessSlideHtml(html);
1216
+ if (slideNum <= 3) {
1217
+ try {
1218
+ fs.writeFileSync(path.join(tempWritePath, `hanseol_debug_slide_${slideNum}.html`), html, 'utf-8');
1219
+ }
1220
+ catch { }
1221
+ }
1222
+ }
1223
+ if (htmlPrompt && html && slidePlan.type === 'content' && !usedSkeleton) {
1224
+ const MAX_LAYOUT_REGEN = 2;
1225
+ for (let layoutAttempt = 0; layoutAttempt < MAX_LAYOUT_REGEN; layoutAttempt++) {
1226
+ const complianceError = checkLayoutCompliance(html, slideLayoutType);
1227
+ if (!complianceError) {
1228
+ if (layoutAttempt > 0) {
1229
+ logger.info(`Slide ${slideNum}: Layout compliance OK after ${layoutAttempt} regen(s)`);
1230
+ }
1231
+ break;
1232
+ }
1233
+ logger.warn(`Slide ${slideNum}: Layout compliance FAILED — ${complianceError}`);
1234
+ if (phaseLogger)
1235
+ phaseLogger('powerpoint-create', 'execution', `Slide ${slideNum}: wrong layout, regen ${layoutAttempt + 1}/${MAX_LAYOUT_REGEN}...`);
1236
+ try {
1237
+ const regenRes = await llmClient.chatCompletion({
1238
+ messages: [
1239
+ { role: 'system', content: htmlPrompt },
1240
+ { role: 'user', content: `Generate the HTML slide now.\n\n⚠⚠⚠ CRITICAL ERROR: ${complianceError}\n\nYou MUST use the "${slideLayoutType}" layout as specified in the REQUIRED LAYOUT section above. Re-read the CSS STRUCTURE section carefully and follow it EXACTLY. Do NOT use cards or any other layout.` },
1241
+ ],
1242
+ temperature: 0.2,
1243
+ max_tokens: 8000,
1244
+ });
1245
+ const regenMsg = regenRes.choices[0]?.message;
1246
+ const regenRaw = regenMsg ? extractContent(regenMsg) : '';
1247
+ const regenHtml = extractHtml(regenRaw);
1248
+ if (regenHtml) {
1249
+ html = regenHtml;
1250
+ logger.info(`Slide ${slideNum}: Regenerated for layout compliance (attempt ${layoutAttempt + 1})`);
1251
+ }
1252
+ else {
1253
+ break;
1254
+ }
1255
+ }
1256
+ catch (e) {
1257
+ logger.warn(`Slide ${slideNum}: Layout regen failed: ${e}`);
1258
+ break;
1259
+ }
1260
+ }
1261
+ }
1262
+ const htmlFileName = `hanseol_slide_${slideNum}_${timestamp}.html`;
1263
+ const pngFileName = `hanseol_slide_${slideNum}_${timestamp}.png`;
1264
+ const htmlWritePath = path.join(tempWritePath, htmlFileName);
1265
+ const pngWritePath = path.join(tempWritePath, pngFileName);
1266
+ const htmlWinPath = `${tempWinPath}\\${htmlFileName}`;
1267
+ const pngWinPath = `${tempWinPath}\\${pngFileName}`;
1268
+ try {
1269
+ const processed = injectTitleContrastFix(ensureSafeBodyPadding(removeAbsolutePositioning(stripGradientTextEffects(enforceMinFontSize(injectViewportCss(html, plan.design.background_color))))), plan.design.text_color);
1270
+ fs.writeFileSync(htmlWritePath, processed, 'utf-8');
1271
+ tempFiles.push(htmlWritePath);
1272
+ }
1273
+ catch (e) {
1274
+ logger.warn(`Slide ${slideNum}: Failed to write HTML file: ${e}`);
1275
+ failCount++;
1276
+ continue;
1277
+ }
1278
+ let renderSuccess = false;
1279
+ try {
1280
+ const renderResult = await powerpointClient.renderHtmlToImage(htmlWinPath, pngWinPath);
1281
+ totalToolCalls++;
1282
+ renderSuccess = renderResult.success;
1283
+ if (!renderSuccess) {
1284
+ await new Promise(r => setTimeout(r, 2000));
1285
+ const retryRender = await powerpointClient.renderHtmlToImage(htmlWinPath, pngWinPath);
1286
+ totalToolCalls++;
1287
+ renderSuccess = retryRender.success;
1288
+ }
1289
+ }
1290
+ catch (e) {
1291
+ logger.warn(`Slide ${slideNum}: Edge screenshot failed: ${e}`);
1292
+ try {
1293
+ await new Promise(r => setTimeout(r, 2000));
1294
+ const retryRender = await powerpointClient.renderHtmlToImage(htmlWinPath, pngWinPath);
1295
+ totalToolCalls++;
1296
+ renderSuccess = retryRender.success;
1297
+ }
1298
+ catch {
1299
+ renderSuccess = false;
1300
+ }
1301
+ }
1302
+ try {
1303
+ fs.unlinkSync(htmlWritePath);
1304
+ }
1305
+ catch { }
1306
+ if (!renderSuccess) {
1307
+ logger.warn(`Slide ${slideNum}: Screenshot rendering failed, skipping`);
1308
+ failCount++;
1309
+ continue;
1310
+ }
1311
+ try {
1312
+ const pngStats = fs.statSync(pngWritePath);
1313
+ if (pngStats.size < 15000) {
1314
+ logger.warn(`Slide ${slideNum}: Screenshot too small (${pngStats.size} bytes), likely blank — skipping`);
1315
+ failCount++;
1316
+ try {
1317
+ fs.unlinkSync(pngWritePath);
1318
+ }
1319
+ catch { }
1320
+ continue;
1321
+ }
1322
+ }
1323
+ catch { }
1324
+ tempFiles.push(pngWritePath);
1325
+ const addResult = await powerpointClient.powerpointAddSlide(7);
1326
+ totalToolCalls++;
1327
+ if (!addResult.success) {
1328
+ logger.warn(`Slide ${slideNum}: Failed to add blank slide`);
1329
+ failCount++;
1330
+ continue;
1331
+ }
1332
+ const bgResult = await powerpointClient.powerpointAddFullSlideImage(slideNum, pngWinPath);
1333
+ totalToolCalls++;
1334
+ if (toolCallLogger)
1335
+ toolCallLogger('powerpoint-create', 'addFullSlideImage', { slideNum, imagePath: pngWinPath }, bgResult.success ? 'OK' : 'Failed', bgResult.success, slideNum, totalToolCalls);
1336
+ if (bgResult.success) {
1337
+ builtSlides.push(`Slide ${slideNum}: ${slidePlan.title} (${slidePlan.type})`);
1338
+ try {
1339
+ await powerpointClient.powerpointAddNote(slideNum, html);
1340
+ }
1341
+ catch { }
1342
+ }
1343
+ else {
1344
+ logger.warn(`Slide ${slideNum}: Failed to set background: ${JSON.stringify(bgResult)}`);
1345
+ failCount++;
1346
+ }
1347
+ }
1348
+ if (builtSlides.length > 0) {
1349
+ try {
1350
+ const slideCountResult = await powerpointClient.powerpointGetSlideCount();
1351
+ const totalSlidesInPpt = slideCountResult['slide_count'] || 0;
1352
+ if (totalSlidesInPpt > builtSlides.length) {
1353
+ logger.warn(`PPT has ${totalSlidesInPpt} slides but only ${builtSlides.length} were rendered — deleting ${totalSlidesInPpt - builtSlides.length} trailing blanks`);
1354
+ for (let d = totalSlidesInPpt; d > builtSlides.length; d--) {
1355
+ await powerpointClient.powerpointDeleteSlide(d);
1356
+ totalToolCalls++;
1357
+ }
1358
+ }
1359
+ }
1360
+ catch (e) {
1361
+ logger.warn(`Failed to clean up trailing slides: ${e}`);
1362
+ }
1363
+ }
1364
+ if (builtSlides.length > 0) {
1365
+ if (savePath) {
1366
+ const wslSavePath = savePath.replace(/\\/g, '/').replace(/^([A-Za-z]):/, (_m, d) => `/mnt/${d.toLowerCase()}`);
1367
+ try {
1368
+ fs.unlinkSync(wslSavePath);
1369
+ }
1370
+ catch { }
1371
+ }
1372
+ let saveResult = await powerpointClient.powerpointSave(savePath);
1373
+ totalToolCalls++;
1374
+ if (toolCallLogger)
1375
+ toolCallLogger('powerpoint-create', 'powerpoint_save', { path: savePath }, saveResult.success ? (saveResult['path'] || 'OK') : (saveResult.error || 'Failed'), saveResult.success, 0, totalToolCalls);
1376
+ if (!saveResult.success && savePath) {
1377
+ const fallbackPath = 'C:\\temp\\presentation.pptx';
1378
+ saveResult = await powerpointClient.powerpointSave(fallbackPath);
1379
+ totalToolCalls++;
1380
+ if (toolCallLogger)
1381
+ toolCallLogger('powerpoint-create', 'powerpoint_save', { path: fallbackPath }, saveResult.success ? (saveResult['path'] || 'OK') : (saveResult.error || 'Failed'), saveResult.success, 0, totalToolCalls);
1382
+ }
1383
+ }
1384
+ for (const tempFile of tempFiles) {
1385
+ try {
1386
+ fs.unlinkSync(tempFile);
1387
+ }
1388
+ catch { }
1389
+ }
1390
+ const duration = Date.now() - startTime;
1391
+ const summary = `Presentation created with ${builtSlides.length} slides (HTML rendering, ${plan.design.mood}):\n${builtSlides.join('\n')}`;
1392
+ logger.exit('PPT-Create.runStructured', { slideCount: builtSlides.length, totalToolCalls, duration });
1393
+ return {
1394
+ success: builtSlides.length > 0,
1395
+ result: summary,
1396
+ metadata: { iterations: plan.slides.length, toolCalls: totalToolCalls, duration },
1397
+ };
1398
+ }
1399
+ export function createPowerPointCreateRequestTool() {
1400
+ return {
1401
+ definition: {
1402
+ type: 'function',
1403
+ function: {
1404
+ name: 'powerpoint_create_agent',
1405
+ description: 'Autonomous PowerPoint CREATION agent. Creates NEW presentations from scratch with professional slide designs, color schemes, and visual hierarchy. Uses HTML rendering pipeline for maximum design quality — each slide is rendered as a beautiful HTML page and captured as a high-quality image. Give it a topic or outline and it produces a polished, enterprise-grade presentation. For EDITING existing .pptx files, use powerpoint_modify_agent instead.',
1406
+ parameters: {
1407
+ type: 'object',
1408
+ properties: {
1409
+ instruction: {
1410
+ type: 'string',
1411
+ description: 'Detailed instruction for creating a new presentation. Include: topic/title, desired content, and design preferences. The agent autonomously creates a professional presentation with title, content, and closing slides.',
1412
+ },
1413
+ save_path: {
1414
+ type: 'string',
1415
+ description: 'Windows file path to save the presentation (e.g., "C:\\\\temp\\\\pitch.pptx"). MUST be provided if the user specified a save path.',
1416
+ },
1417
+ },
1418
+ required: ['instruction'],
1419
+ },
1420
+ },
1421
+ },
1422
+ execute: async (args, llmClient) => {
1423
+ const instruction = args['instruction'];
1424
+ const explicitSavePath = args['save_path'];
1425
+ return runStructured(llmClient, instruction, explicitSavePath);
1426
+ },
1427
+ categories: ['llm-agent'],
1428
+ requiresSubLLM: true,
1429
+ };
1430
+ }
1431
+ //# sourceMappingURL=powerpoint-create-agent.js.map