hanseol-dev 5.0.2-dev.16 → 5.0.2-dev.160

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 +1118 -0
  32. package/dist/agents/office/powerpoint-create-agent.js.map +1 -0
  33. package/dist/agents/office/powerpoint-create-prompts.d.ts +129 -0
  34. package/dist/agents/office/powerpoint-create-prompts.d.ts.map +1 -0
  35. package/dist/agents/office/powerpoint-create-prompts.js +1454 -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 +297 -96
  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,1118 @@
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, buildContentFillJsonPrompt, parseContentFillJson, buildContentSlideHtml, } from './powerpoint-create-prompts.js';
8
+ const DEFAULT_DESIGN = {
9
+ primary_color: '#1B2A4A',
10
+ accent_color: '#00D4AA',
11
+ background_color: '#FFFFFF',
12
+ text_color: '#1A1A2E',
13
+ accent_light: '#E8F5F0',
14
+ gradient_end: '#2D5F8A',
15
+ font_title: 'Segoe UI',
16
+ font_body: 'Malgun Gothic',
17
+ mood: 'modern-minimal',
18
+ design_notes: 'Clean gradients, card-based layouts',
19
+ };
20
+ function extractContent(msg) {
21
+ const content = msg['content'];
22
+ if (content && content.trim())
23
+ return content;
24
+ const reasoning = msg['reasoning_content'];
25
+ if (reasoning && reasoning.trim())
26
+ return reasoning;
27
+ return '';
28
+ }
29
+ function validateAndFixPlan(plan) {
30
+ if (!plan.design)
31
+ return 'Missing design object';
32
+ if (!plan.design.primary_color || !plan.design.accent_color) {
33
+ return 'Missing design colors (primary_color, accent_color)';
34
+ }
35
+ if (!Array.isArray(plan.slides) || plan.slides.length < 3) {
36
+ return 'slides array must have at least 3 entries';
37
+ }
38
+ if (plan.slides.length < 10) {
39
+ return `Only ${plan.slides.length} slides — minimum 10 required (aim for 12-15). Add more content slides with specific data.`;
40
+ }
41
+ if (plan.slides[0]?.type !== 'title') {
42
+ logger.info('Auto-fixing: first slide type changed to "title"');
43
+ plan.slides[0].type = 'title';
44
+ }
45
+ const lastSlide = plan.slides[plan.slides.length - 1];
46
+ if (lastSlide.type !== 'closing') {
47
+ logger.info('Auto-fixing: last slide type changed to "closing"');
48
+ lastSlide.type = 'closing';
49
+ }
50
+ for (let i = 0; i < plan.slides.length; i++) {
51
+ if (!plan.slides[i].title) {
52
+ plan.slides[i].title = `Slide ${i + 1}`;
53
+ logger.info(`Auto-fixing: slide ${i + 1} missing title, set placeholder`);
54
+ }
55
+ }
56
+ const layoutOnlyPatterns = [
57
+ /^(?:전체\s*배경|왼쪽에|오른쪽에|중앙에|상단에|하단에)/,
58
+ /#[0-9a-fA-F]{3,8}에서.*그라데이션/,
59
+ /(?:accent_light|primary|gradient_end)\s*(?:배경|글씨|색상)/,
60
+ /^(?:CSS|flexbox|grid|conic-gradient|linear-gradient)/i,
61
+ ];
62
+ for (let i = 0; i < plan.slides.length; i++) {
63
+ const slide = plan.slides[i];
64
+ if (slide.type === 'title' || slide.type === 'closing')
65
+ continue;
66
+ const cd = slide.content_direction || '';
67
+ const hasNumbers = /\d/.test(cd);
68
+ const isLayoutOnly = layoutOnlyPatterns.some(p => p.test(cd));
69
+ if (isLayoutOnly && !hasNumbers) {
70
+ return `Slide ${i + 1} "${slide.title}" content_direction contains layout instructions instead of actual data. content_direction must include REAL text/numbers to display.`;
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ function repairLlmJson(raw) {
76
+ let result = '';
77
+ let inString = false;
78
+ let i = 0;
79
+ while (i < raw.length) {
80
+ const ch = raw[i];
81
+ if (!inString) {
82
+ if (ch === ',') {
83
+ let j = i + 1;
84
+ while (j < raw.length && /\s/.test(raw[j]))
85
+ j++;
86
+ if (j < raw.length && (raw[j] === '}' || raw[j] === ']')) {
87
+ i++;
88
+ continue;
89
+ }
90
+ }
91
+ result += ch;
92
+ if (ch === '"')
93
+ inString = true;
94
+ i++;
95
+ continue;
96
+ }
97
+ if (ch === '\\') {
98
+ result += ch;
99
+ if (i + 1 < raw.length) {
100
+ result += raw[i + 1];
101
+ i += 2;
102
+ }
103
+ else {
104
+ i++;
105
+ }
106
+ continue;
107
+ }
108
+ if (ch === '"') {
109
+ let j = i + 1;
110
+ while (j < raw.length && /[ \t\r\n]/.test(raw[j]))
111
+ j++;
112
+ const next = j < raw.length ? raw[j] : '';
113
+ if (next === '' || /[,:}\]]/.test(next)) {
114
+ result += '"';
115
+ inString = false;
116
+ }
117
+ else {
118
+ result += '\\"';
119
+ }
120
+ i++;
121
+ continue;
122
+ }
123
+ if (ch === '\n') {
124
+ result += '\\n';
125
+ i++;
126
+ continue;
127
+ }
128
+ if (ch === '\r') {
129
+ result += '\\n';
130
+ i += (i + 1 < raw.length && raw[i + 1] === '\n') ? 2 : 1;
131
+ continue;
132
+ }
133
+ if (ch === '\t') {
134
+ result += '\\t';
135
+ i++;
136
+ continue;
137
+ }
138
+ if (ch.charCodeAt(0) < 0x20) {
139
+ i++;
140
+ continue;
141
+ }
142
+ result += ch;
143
+ i++;
144
+ }
145
+ return result;
146
+ }
147
+ function parseJsonPlan(raw) {
148
+ let cleaned = raw.trim();
149
+ if (cleaned.startsWith('```')) {
150
+ cleaned = cleaned.replace(/^```(?:json|JSON)?\s*\n?/, '').replace(/\n?```\s*$/, '');
151
+ }
152
+ const firstBrace = cleaned.indexOf('{');
153
+ if (firstBrace > 0) {
154
+ cleaned = cleaned.slice(firstBrace);
155
+ }
156
+ const lastBrace = cleaned.lastIndexOf('}');
157
+ if (lastBrace >= 0 && lastBrace < cleaned.length - 1) {
158
+ cleaned = cleaned.slice(0, lastBrace + 1);
159
+ }
160
+ try {
161
+ return JSON.parse(cleaned);
162
+ }
163
+ catch (e) {
164
+ logger.debug('parseJsonPlan: direct parse failed', { error: String(e), length: cleaned.length });
165
+ }
166
+ const match = cleaned.match(/\{[\s\S]*\}/);
167
+ if (!match)
168
+ return null;
169
+ try {
170
+ return JSON.parse(match[0]);
171
+ }
172
+ catch { }
173
+ const repaired = repairLlmJson(match[0]);
174
+ try {
175
+ return JSON.parse(repaired);
176
+ }
177
+ catch (e) {
178
+ logger.debug('parseJsonPlan: repaired parse failed', { error: String(e) });
179
+ }
180
+ try {
181
+ let final = repaired;
182
+ let braces = 0, brackets = 0;
183
+ let inStr = false, esc = false;
184
+ for (const ch of final) {
185
+ if (esc) {
186
+ esc = false;
187
+ continue;
188
+ }
189
+ if (ch === '\\') {
190
+ esc = true;
191
+ continue;
192
+ }
193
+ if (ch === '"') {
194
+ inStr = !inStr;
195
+ continue;
196
+ }
197
+ if (inStr)
198
+ continue;
199
+ if (ch === '{')
200
+ braces++;
201
+ else if (ch === '}')
202
+ braces--;
203
+ else if (ch === '[')
204
+ brackets++;
205
+ else if (ch === ']')
206
+ brackets--;
207
+ }
208
+ if (inStr)
209
+ final += '"';
210
+ for (let i = 0; i < brackets; i++)
211
+ final += ']';
212
+ for (let i = 0; i < braces; i++)
213
+ final += '}';
214
+ return JSON.parse(final);
215
+ }
216
+ catch {
217
+ return null;
218
+ }
219
+ }
220
+ function extractHtml(raw) {
221
+ const trimmed = raw.trim();
222
+ if (trimmed.startsWith('<!DOCTYPE') || trimmed.startsWith('<html')) {
223
+ return trimmed;
224
+ }
225
+ const fenceMatch = trimmed.match(/```(?:html)?\s*\n([\s\S]*?)\n```/);
226
+ if (fenceMatch?.[1]) {
227
+ return fenceMatch[1].trim();
228
+ }
229
+ const docMatch = trimmed.match(/(<!DOCTYPE[\s\S]*<\/html>)/i);
230
+ if (docMatch?.[1]) {
231
+ return docMatch[1].trim();
232
+ }
233
+ return null;
234
+ }
235
+ function injectEdgeSizing(html, backgroundColor) {
236
+ let result = html.replace(/<meta\s+name=["']viewport["'][^>]*>/gi, '');
237
+ const bgColor = backgroundColor || '#000000';
238
+ const sizingCss = `<style id="edge-sizing">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;zoom:1!important}</style>`;
239
+ if (result.includes('</head>')) {
240
+ result = result.replace('</head>', `${sizingCss}</head>`);
241
+ }
242
+ else if (result.includes('<head>')) {
243
+ result = result.replace('<head>', `<head>${sizingCss}`);
244
+ }
245
+ else if (result.includes('<html')) {
246
+ result = result.replace(/<html[^>]*>/, (match) => `${match}<head>${sizingCss}</head>`);
247
+ }
248
+ else {
249
+ result = sizingCss + result;
250
+ }
251
+ return result;
252
+ }
253
+ function injectViewportCss(html, backgroundColor) {
254
+ let result = html.replace(/<meta\s+name=["']viewport["'][^>]*>/gi, '');
255
+ const bgColor = backgroundColor || '#000000';
256
+ 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>`;
257
+ const injection = overrideCss;
258
+ if (result.includes('</head>')) {
259
+ result = result.replace('</head>', `${injection}</head>`);
260
+ }
261
+ else if (result.includes('<head>')) {
262
+ result = result.replace('<head>', `<head>${injection}`);
263
+ }
264
+ else if (result.includes('<html')) {
265
+ result = result.replace(/<html[^>]*>/, (match) => `${match}<head>${injection}</head>`);
266
+ }
267
+ else {
268
+ result = injection + result;
269
+ }
270
+ return result;
271
+ }
272
+ function injectTitleContrastFix(html, designTextColor) {
273
+ const safeColor = designTextColor.replace(/'/g, "\\'");
274
+ const script = `<script>(function(){` +
275
+ `var dc='${safeColor}';` +
276
+ `function lum(c){var m=c.match(/[\\d.]+/g);if(!m||m.length<3)return -1;` +
277
+ `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)});` +
278
+ `return 0.2126*s[0]+0.7152*s[1]+0.0722*s[2]}` +
279
+ `function getBg(el){while(el){var s=getComputedStyle(el);var bg=s.backgroundColor;` +
280
+ `var m=bg.match(/[\\d.]+/g);if(m&&m.length>=3){if(m.length<4||parseFloat(m[3])>0.1)return bg}` +
281
+ `el=el.parentElement}return'rgb(255,255,255)'}` +
282
+ `var els=document.querySelectorAll('h1,h2');` +
283
+ `for(var i=0;i<els.length;i++){var el=els[i];var cs=getComputedStyle(el);` +
284
+ `var tfc=cs.webkitTextFillColor||'';` +
285
+ `if(tfc==='transparent'||tfc==='rgba(0, 0, 0, 0)'){` +
286
+ `el.style.setProperty('-webkit-text-fill-color','initial','important')}` +
287
+ `if(parseFloat(cs.opacity)<0.6){el.style.setProperty('opacity','1','important')}` +
288
+ `var fg=cs.color;var bg=getBg(el);var fl=lum(fg),bl=lum(bg);` +
289
+ `if(fl>=0&&bl>=0){var r=(Math.max(fl,bl)+0.05)/(Math.min(fl,bl)+0.05);` +
290
+ `if(r<3){el.style.setProperty('color',dc,'important');` +
291
+ `el.style.setProperty('-webkit-text-fill-color',dc,'important')}}}` +
292
+ `})()<\/script>`;
293
+ if (html.includes('</body>')) {
294
+ return html.replace('</body>', `${script}</body>`);
295
+ }
296
+ return html + script;
297
+ }
298
+ function escapeHtml(text) {
299
+ return text
300
+ .replace(/&/g, '&amp;')
301
+ .replace(/</g, '&lt;')
302
+ .replace(/>/g, '&gt;')
303
+ .replace(/"/g, '&quot;');
304
+ }
305
+ function buildTitleSlideHtml(design, mainTitle, subtitle, date, _slideNum) {
306
+ return `<!DOCTYPE html>
307
+ <html lang="ko">
308
+ <head>
309
+ <meta charset="UTF-8">
310
+ <style>
311
+ * { margin: 0; padding: 0; box-sizing: border-box; }
312
+ html { background-color: ${design.primary_color}; }
313
+ html, body { width: 1920px; height: 1080px; overflow: hidden; }
314
+ body {
315
+ background: linear-gradient(135deg, ${design.primary_color} 0%, ${design.gradient_end} 60%, ${design.primary_color} 100%);
316
+ display: flex;
317
+ flex-direction: column;
318
+ align-items: center;
319
+ justify-content: center;
320
+ font-family: "${design.font_title}", "Segoe UI", sans-serif;
321
+ }
322
+ body::before {
323
+ content: '';
324
+ display: block;
325
+ width: 100%;
326
+ height: 6px;
327
+ background: linear-gradient(90deg, transparent, ${design.accent_color}, transparent);
328
+ flex-shrink: 0;
329
+ }
330
+ .slide-content {
331
+ text-align: center;
332
+ max-width: 1400px;
333
+ padding: 0 60px;
334
+ }
335
+ .main-title {
336
+ font-size: 96px;
337
+ font-weight: 800;
338
+ color: #ffffff;
339
+ letter-spacing: -2px;
340
+ text-shadow: 0 6px 40px rgba(0,0,0,0.25);
341
+ line-height: 1.1;
342
+ margin-bottom: 32px;
343
+ }
344
+ .accent-bar {
345
+ width: 120px; height: 5px;
346
+ background: ${design.accent_color};
347
+ margin: 0 auto 32px;
348
+ border-radius: 3px;
349
+ box-shadow: 0 0 20px ${design.accent_color}40;
350
+ }
351
+ .subtitle {
352
+ font-size: 32px;
353
+ font-weight: 400;
354
+ color: rgba(255,255,255,0.88);
355
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
356
+ line-height: 1.5;
357
+ margin-bottom: 16px;
358
+ }
359
+ .date-text {
360
+ font-size: 22px;
361
+ font-weight: 300;
362
+ color: rgba(255,255,255,0.55);
363
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
364
+ }
365
+ </style>
366
+ </head>
367
+ <body>
368
+ <div class="slide-content">
369
+ <div class="main-title">${escapeHtml(mainTitle)}</div>
370
+ <div class="accent-bar"></div>
371
+ ${subtitle ? `<div class="subtitle">${escapeHtml(subtitle)}</div>` : ''}
372
+ <div class="date-text">${escapeHtml(date)}</div>
373
+ </div>
374
+ <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>
375
+ </body>
376
+ </html>`;
377
+ }
378
+ function buildClosingSlideHtml(design, companyName, _slideNum, language, tagline) {
379
+ const thankYou = language === 'ko' ? '감사합니다' : 'Thank You';
380
+ const taglineHtml = tagline
381
+ ? `<div class="tagline">${escapeHtml(tagline)}</div>`
382
+ : '';
383
+ return `<!DOCTYPE html>
384
+ <html lang="${language}">
385
+ <head>
386
+ <meta charset="UTF-8">
387
+ <style>
388
+ * { margin: 0; padding: 0; box-sizing: border-box; }
389
+ html { background-color: ${design.primary_color}; }
390
+ html, body { width: 1920px; height: 1080px; overflow: hidden; }
391
+ body {
392
+ background: linear-gradient(135deg, ${design.primary_color} 0%, ${design.gradient_end} 60%, ${design.primary_color} 100%);
393
+ display: flex;
394
+ flex-direction: column;
395
+ align-items: center;
396
+ justify-content: center;
397
+ font-family: "${design.font_title}", "Segoe UI", sans-serif;
398
+ }
399
+ body::before {
400
+ content: '';
401
+ position: absolute;
402
+ top: 0; left: 0; right: 0;
403
+ height: 6px;
404
+ background: linear-gradient(90deg, transparent, ${design.accent_color}, transparent);
405
+ }
406
+ body::after {
407
+ content: '';
408
+ position: absolute;
409
+ bottom: 0; left: 0; right: 0;
410
+ height: 6px;
411
+ background: linear-gradient(90deg, transparent, ${design.accent_color}, transparent);
412
+ }
413
+ .slide-content {
414
+ text-align: center;
415
+ max-width: 1200px;
416
+ }
417
+ .thank-you {
418
+ font-size: 104px;
419
+ font-weight: 800;
420
+ color: #ffffff;
421
+ letter-spacing: -1px;
422
+ text-shadow: 0 6px 40px rgba(0,0,0,0.25);
423
+ margin-bottom: 36px;
424
+ }
425
+ .accent-bar {
426
+ width: 120px; height: 5px;
427
+ background: ${design.accent_color};
428
+ margin: 0 auto 36px;
429
+ border-radius: 3px;
430
+ box-shadow: 0 0 20px ${design.accent_color}40;
431
+ }
432
+ .company {
433
+ font-size: 44px;
434
+ font-weight: 600;
435
+ color: rgba(255,255,255,0.88);
436
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
437
+ margin-bottom: 20px;
438
+ }
439
+ .tagline {
440
+ font-size: 28px;
441
+ font-weight: 400;
442
+ color: rgba(255,255,255,0.60);
443
+ font-family: "${design.font_body}", "Malgun Gothic", sans-serif;
444
+ line-height: 1.6;
445
+ max-width: 900px;
446
+ margin: 0 auto;
447
+ }
448
+ </style>
449
+ </head>
450
+ <body>
451
+ <div class="slide-content">
452
+ <div class="thank-you">${escapeHtml(thankYou)}</div>
453
+ <div class="accent-bar"></div>
454
+ <div class="company">${escapeHtml(companyName)}</div>
455
+ ${taglineHtml}
456
+ </div>
457
+ <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>
458
+ </body>
459
+ </html>`;
460
+ }
461
+ function isOverviewSlide(title, slideIndex) {
462
+ if (slideIndex !== 1)
463
+ return false;
464
+ const overviewKeywords = /개요|목차|overview|agenda|outline|순서|발표\s*구성|contents|목록/i;
465
+ return overviewKeywords.test(title);
466
+ }
467
+ function parseOverviewItems(contentDirection) {
468
+ const items = [];
469
+ const lines = contentDirection.split(/\n/).filter(l => l.trim());
470
+ for (const line of lines) {
471
+ const match = line.match(/^\d+[\.\)]\s*(.+?)(?:\s*[-–—:]\s*(.+))?$/);
472
+ if (match) {
473
+ items.push({ title: match[1].trim(), desc: match[2]?.trim() || '' });
474
+ }
475
+ }
476
+ if (items.length === 0) {
477
+ const parts = contentDirection.split(/[,;·•]/).map(s => s.trim()).filter(Boolean);
478
+ for (const part of parts) {
479
+ const sepMatch = part.match(/^(.+?)(?:\s*[-–—:]\s*(.+))?$/);
480
+ if (sepMatch) {
481
+ items.push({ title: sepMatch[1].trim(), desc: sepMatch[2]?.trim() || '' });
482
+ }
483
+ }
484
+ }
485
+ return items.slice(0, 5);
486
+ }
487
+ function buildOverviewSlideHtml(design, title, subtitle, items, slideNum) {
488
+ const badgeColors = [
489
+ design.primary_color,
490
+ design.accent_color,
491
+ design.gradient_end,
492
+ design.primary_color,
493
+ design.accent_color,
494
+ ];
495
+ const itemCount = items.length;
496
+ const topRow = itemCount <= 3 ? items : items.slice(0, Math.ceil(itemCount / 2));
497
+ const bottomRow = itemCount <= 3 ? [] : items.slice(Math.ceil(itemCount / 2));
498
+ function renderCard(item, idx) {
499
+ const color = badgeColors[idx % badgeColors.length];
500
+ return `
501
+ <div class="card">
502
+ <div class="badge" style="background:${color}">${idx + 1}</div>
503
+ <div class="card-title">${escapeHtml(item.title)}</div>
504
+ ${item.desc ? `<div class="card-desc">${escapeHtml(item.desc)}</div>` : ''}
505
+ </div>`;
506
+ }
507
+ return `<!DOCTYPE html>
508
+ <html lang="ko">
509
+ <head>
510
+ <meta charset="UTF-8">
511
+ <style>
512
+ * { margin: 0; padding: 0; box-sizing: border-box; }
513
+ html, body { width: 1920px; height: 1080px; overflow: hidden; }
514
+ body {
515
+ background: ${design.background_color};
516
+ font-family: "${design.font_body}", "${design.font_title}", "Segoe UI", "Malgun Gothic", sans-serif;
517
+ display: flex; flex-direction: column;
518
+ word-break: keep-all; overflow-wrap: break-word;
519
+ }
520
+ .header {
521
+ background: linear-gradient(135deg, ${design.primary_color}, ${design.gradient_end});
522
+ padding: 48px 80px 40px;
523
+ flex-shrink: 0;
524
+ }
525
+ .header-title {
526
+ font-size: 52px; font-weight: 800; color: #ffffff;
527
+ font-family: "${design.font_title}", "Segoe UI", sans-serif;
528
+ margin-bottom: 8px;
529
+ }
530
+ .header-subtitle {
531
+ font-size: 24px; font-weight: 400; color: rgba(255,255,255,0.75);
532
+ }
533
+ .content {
534
+ flex: 1; display: flex; flex-direction: column;
535
+ padding: 48px 80px 40px;
536
+ gap: 24px;
537
+ justify-content: center;
538
+ }
539
+ .row {
540
+ display: flex; gap: 24px;
541
+ justify-content: center;
542
+ }
543
+ .card {
544
+ flex: 1;
545
+ max-width: 340px;
546
+ background: #ffffff;
547
+ border-radius: 16px;
548
+ padding: 36px 32px;
549
+ box-shadow: 0 4px 20px rgba(0,0,0,0.06);
550
+ display: flex; flex-direction: column;
551
+ align-items: center; text-align: center;
552
+ gap: 12px;
553
+ transition: none;
554
+ }
555
+ .badge {
556
+ width: 44px; height: 44px;
557
+ border-radius: 50%;
558
+ color: #ffffff;
559
+ font-size: 20px; font-weight: 700;
560
+ display: flex; align-items: center; justify-content: center;
561
+ flex-shrink: 0;
562
+ }
563
+ .card-title {
564
+ font-size: 26px; font-weight: 700; color: ${design.text_color};
565
+ line-height: 1.3;
566
+ }
567
+ .card-desc {
568
+ font-size: 22px; font-weight: 400; color: ${design.text_color}aa;
569
+ line-height: 1.5;
570
+ }
571
+ .page-num {
572
+ position: absolute;
573
+ bottom: 24px; right: 44px;
574
+ font-size: 13px;
575
+ color: ${design.text_color}55;
576
+ }
577
+ </style>
578
+ </head>
579
+ <body>
580
+ <div class="header">
581
+ <div class="header-title">${escapeHtml(title)}</div>
582
+ ${subtitle ? `<div class="header-subtitle">${escapeHtml(subtitle)}</div>` : ''}
583
+ </div>
584
+ <div class="content">
585
+ <div class="row">
586
+ ${topRow.map((item, idx) => renderCard(item, idx)).join('')}
587
+ </div>
588
+ ${bottomRow.length > 0 ? `<div class="row">
589
+ ${bottomRow.map((item, idx) => renderCard(item, topRow.length + idx)).join('')}
590
+ </div>` : ''}
591
+ </div>
592
+ <div class="page-num">${slideNum}</div>
593
+ </body>
594
+ </html>`;
595
+ }
596
+ function getTempDir() {
597
+ const platform = getPlatform();
598
+ if (platform === 'wsl') {
599
+ return { writePath: '/mnt/c/temp', winPath: 'C:\\temp' };
600
+ }
601
+ return { writePath: 'C:\\temp', winPath: 'C:\\temp' };
602
+ }
603
+ function ensureTempDir(writePath) {
604
+ if (!fs.existsSync(writePath)) {
605
+ fs.mkdirSync(writePath, { recursive: true });
606
+ }
607
+ }
608
+ function normalizeDesign(raw) {
609
+ return {
610
+ primary_color: raw['primary_color'] || DEFAULT_DESIGN.primary_color,
611
+ accent_color: raw['accent_color'] || DEFAULT_DESIGN.accent_color,
612
+ background_color: raw['background_color'] || DEFAULT_DESIGN.background_color,
613
+ text_color: raw['text_color'] || DEFAULT_DESIGN.text_color,
614
+ accent_light: raw['accent_light'] || DEFAULT_DESIGN.accent_light,
615
+ gradient_end: raw['gradient_end'] || DEFAULT_DESIGN.gradient_end,
616
+ font_title: raw['font_title'] || DEFAULT_DESIGN.font_title,
617
+ font_body: raw['font_body'] || DEFAULT_DESIGN.font_body,
618
+ mood: raw['mood'] || DEFAULT_DESIGN.mood,
619
+ design_notes: raw['design_notes'] || DEFAULT_DESIGN.design_notes,
620
+ };
621
+ }
622
+ async function runStructured(llmClient, instruction, explicitSavePath) {
623
+ const startTime = Date.now();
624
+ const phaseLogger = getSubAgentPhaseLogger();
625
+ const toolCallLogger = getSubAgentToolCallLogger();
626
+ let totalToolCalls = 0;
627
+ const timestamp = Date.now();
628
+ logger.enter('PPT-Create.runStructured');
629
+ const hasKorean = /[\uac00-\ud7af\u1100-\u11ff]/.test(instruction);
630
+ const language = hasKorean ? 'ko' : 'en';
631
+ if (phaseLogger)
632
+ phaseLogger('powerpoint-create', 'enhancement', 'Generating creative guidance...');
633
+ let guidance = '';
634
+ try {
635
+ const enhRes = await llmClient.chatCompletion({
636
+ messages: [
637
+ { role: 'system', content: PPT_CREATE_ENHANCEMENT_PROMPT },
638
+ { role: 'user', content: instruction },
639
+ ],
640
+ temperature: 0.7,
641
+ max_tokens: 2000,
642
+ });
643
+ const enhMsg = enhRes.choices[0]?.message;
644
+ guidance = enhMsg ? extractContent(enhMsg) : '';
645
+ if (guidance.length < 1500) {
646
+ logger.warn('PPT enhancement too short, retrying', { length: guidance.length });
647
+ const retryEnhRes = await llmClient.chatCompletion({
648
+ messages: [
649
+ { role: 'system', content: PPT_CREATE_ENHANCEMENT_PROMPT },
650
+ { 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.` },
651
+ ],
652
+ temperature: 0.7,
653
+ max_tokens: 2000,
654
+ });
655
+ const retryMsg = retryEnhRes.choices[0]?.message;
656
+ const retryGuidance = retryMsg ? extractContent(retryMsg) : '';
657
+ if (retryGuidance.length > guidance.length) {
658
+ guidance = retryGuidance;
659
+ }
660
+ }
661
+ if (phaseLogger)
662
+ phaseLogger('powerpoint-create', 'enhancement', `Done (${guidance.length} chars)`);
663
+ }
664
+ catch (e) {
665
+ logger.warn('PPT enhancement failed, proceeding without', { error: String(e) });
666
+ }
667
+ const enhancedInstruction = guidance
668
+ ? `${instruction}\n\n═══ CREATIVE GUIDANCE ═══\n${guidance}\n═══ END GUIDANCE ═══`
669
+ : instruction;
670
+ if (phaseLogger)
671
+ phaseLogger('powerpoint-create', 'planning', 'Generating JSON plan...');
672
+ let plan = null;
673
+ try {
674
+ const planRes = await llmClient.chatCompletion({
675
+ messages: [
676
+ { role: 'system', content: PPT_STRUCTURED_PLANNING_PROMPT },
677
+ { role: 'user', content: enhancedInstruction },
678
+ ],
679
+ temperature: 0.4,
680
+ max_tokens: 8000,
681
+ });
682
+ const planMsg = planRes.choices[0]?.message;
683
+ const finishReason = planRes.choices[0]?.finish_reason;
684
+ const rawPlan = planMsg ? extractContent(planMsg) : '';
685
+ if (finishReason === 'length') {
686
+ logger.warn('PPT planning response was truncated (finish_reason=length)');
687
+ }
688
+ logger.debug('PPT planning raw response', { length: rawPlan.length, finishReason, first200: rawPlan.slice(0, 200) });
689
+ plan = rawPlan ? parseJsonPlan(rawPlan) : null;
690
+ if (plan) {
691
+ plan.design = normalizeDesign(plan.design);
692
+ const validationError = validateAndFixPlan(plan);
693
+ if (validationError) {
694
+ logger.warn('PPT plan validation failed', { error: validationError });
695
+ if (phaseLogger)
696
+ phaseLogger('powerpoint-create', 'planning', `Validation failed: ${validationError}. Retrying...`);
697
+ const retryRes = await llmClient.chatCompletion({
698
+ messages: [
699
+ { role: 'system', content: PPT_STRUCTURED_PLANNING_PROMPT },
700
+ { role: 'user', content: enhancedInstruction },
701
+ { role: 'assistant', content: rawPlan },
702
+ { 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.` },
703
+ ],
704
+ temperature: 0.2,
705
+ max_tokens: 8000,
706
+ });
707
+ const retryMsg = retryRes.choices[0]?.message;
708
+ const retryRaw = retryMsg ? extractContent(retryMsg) : '';
709
+ const retryPlan = retryRaw ? parseJsonPlan(retryRaw) : null;
710
+ if (retryPlan) {
711
+ retryPlan.design = normalizeDesign(retryPlan.design);
712
+ const retryError = validateAndFixPlan(retryPlan);
713
+ if (!retryError) {
714
+ plan = retryPlan;
715
+ if (phaseLogger)
716
+ phaseLogger('powerpoint-create', 'planning', `Retry succeeded (${plan.slides.length} slides)`);
717
+ }
718
+ else {
719
+ plan = null;
720
+ }
721
+ }
722
+ else {
723
+ plan = null;
724
+ }
725
+ }
726
+ else {
727
+ if (phaseLogger)
728
+ phaseLogger('powerpoint-create', 'planning', `Done (${plan.slides.length} slides)`);
729
+ }
730
+ }
731
+ else {
732
+ logger.warn('PPT JSON plan parsing failed');
733
+ if (phaseLogger)
734
+ phaseLogger('powerpoint-create', 'planning', 'JSON parsing failed. Falling back.');
735
+ }
736
+ }
737
+ catch (e) {
738
+ logger.warn('PPT planning failed', { error: String(e) });
739
+ if (phaseLogger)
740
+ phaseLogger('powerpoint-create', 'planning', 'Planning error. Falling back.');
741
+ }
742
+ if (!plan) {
743
+ logger.error('PPT planning failed after retries — cannot create presentation');
744
+ return {
745
+ success: false,
746
+ error: 'Failed to generate presentation plan. Please try again.',
747
+ };
748
+ }
749
+ if (plan.slides.length > 20) {
750
+ logger.warn(`PPT plan has ${plan.slides.length} slides, capping to 20`);
751
+ const firstSlide = plan.slides[0];
752
+ const lastSlide = plan.slides[plan.slides.length - 1];
753
+ const contentSlides = plan.slides.slice(1, -1).slice(0, 18);
754
+ plan.slides = [firstSlide, ...contentSlides, lastSlide];
755
+ if (phaseLogger)
756
+ phaseLogger('powerpoint-create', 'planning', `Capped to ${plan.slides.length} slides`);
757
+ }
758
+ const userYearMatch = instruction.match(/(\d{4})년/);
759
+ if (userYearMatch) {
760
+ const userYear = userYearMatch[1];
761
+ for (const slide of plan.slides) {
762
+ if (slide.type === 'content' && slide.content_direction) {
763
+ if (!slide.content_direction.includes(`${userYear}년`)) {
764
+ slide.content_direction += ` (Note: This report covers ${userYear}년 data.)`;
765
+ }
766
+ }
767
+ }
768
+ }
769
+ const companyMatch = instruction.match(/회사명\s*[::]\s*([^\s,,、]+)/);
770
+ if (companyMatch && companyMatch[1]) {
771
+ const companyName_ = companyMatch[1];
772
+ const titleSlide = plan.slides.find(s => s.type === 'title');
773
+ if (titleSlide) {
774
+ if (titleSlide.title.trim() !== companyName_) {
775
+ const originalTitle = titleSlide.title;
776
+ titleSlide.title = companyName_;
777
+ if (!titleSlide.content_direction?.includes(originalTitle)) {
778
+ const stripped = originalTitle.replace(companyName_, '').replace(/^\s*[-–—:|\s]+/, '').trim();
779
+ const subtitle = stripped || originalTitle;
780
+ titleSlide.content_direction = subtitle + (titleSlide.content_direction ? '\n' + titleSlide.content_direction : '');
781
+ }
782
+ }
783
+ }
784
+ }
785
+ if (phaseLogger)
786
+ phaseLogger('powerpoint-create', 'execution', 'Starting HTML rendering pipeline...');
787
+ const { writePath: tempWritePath, winPath: tempWinPath } = getTempDir();
788
+ ensureTempDir(tempWritePath);
789
+ let savePath = explicitSavePath;
790
+ if (!savePath) {
791
+ const fullPathMatch = instruction.match(/([A-Za-z]:\\[^\s,]+\.pptx|\/[^\s,]+\.pptx)/i);
792
+ if (fullPathMatch) {
793
+ savePath = fullPathMatch[1];
794
+ }
795
+ else {
796
+ const nameMatch = instruction.match(/([\w][\w\-_.]*\.pptx)/i);
797
+ if (nameMatch) {
798
+ savePath = `C:\\temp\\${nameMatch[1]}`;
799
+ }
800
+ }
801
+ }
802
+ const titleSlidePlanForDate = plan.slides.find(s => s.type === 'title');
803
+ const dateSearchTexts = [
804
+ instruction,
805
+ titleSlidePlanForDate?.title || '',
806
+ titleSlidePlanForDate?.content_direction || '',
807
+ ];
808
+ let kstDate = '';
809
+ for (const text of dateSearchTexts) {
810
+ const dateMatch = text.match(/(\d{4})년\s*(\d{1,2})\s*(월|분기)/);
811
+ if (dateMatch) {
812
+ kstDate = `${dateMatch[1]}년 ${dateMatch[2]}${dateMatch[3]}`;
813
+ break;
814
+ }
815
+ }
816
+ if (!kstDate) {
817
+ const kstNow = new Date(Date.now() + 9 * 60 * 60 * 1000);
818
+ kstDate = `${kstNow.getUTCFullYear()}년 ${kstNow.getUTCMonth() + 1}월`;
819
+ }
820
+ const titleSlidePlan = plan.slides.find(s => s.type === 'title');
821
+ const rawTitleText = titleSlidePlan?.title || '';
822
+ const titleSeps = [' - ', ' – ', ' — ', ': ', ' | '];
823
+ let companyName = rawTitleText;
824
+ let titleSubtitle = '';
825
+ for (const sep of titleSeps) {
826
+ const idx = rawTitleText.indexOf(sep);
827
+ if (idx > 0) {
828
+ companyName = rawTitleText.slice(0, idx).trim();
829
+ titleSubtitle = rawTitleText.slice(idx + sep.length).trim();
830
+ break;
831
+ }
832
+ }
833
+ if (!titleSubtitle && titleSlidePlan) {
834
+ titleSubtitle = ((titleSlidePlan.content_direction || '').split('\n')[0] || '').trim().slice(0, 120);
835
+ }
836
+ if (/로고|슬로건|연락처|contact|logo|placeholder/i.test(titleSubtitle)) {
837
+ titleSubtitle = '';
838
+ }
839
+ const createResult = await powerpointClient.powerpointCreate();
840
+ totalToolCalls++;
841
+ if (toolCallLogger)
842
+ toolCallLogger('powerpoint-create', 'powerpoint_create', {}, createResult.success ? 'Created' : createResult['error'] || '', createResult.success, 0, totalToolCalls);
843
+ if (!createResult.success) {
844
+ return { success: false, error: `Failed to create presentation: ${createResult['error']}` };
845
+ }
846
+ const builtSlides = [];
847
+ let failCount = 0;
848
+ const tempFiles = [];
849
+ for (let i = 0; i < plan.slides.length; i++) {
850
+ const slidePlan = plan.slides[i];
851
+ const slideNum = i + 1;
852
+ if (failCount >= 3) {
853
+ logger.warn('Too many slide failures, stopping');
854
+ break;
855
+ }
856
+ if (phaseLogger)
857
+ phaseLogger('powerpoint-create', 'execution', `Rendering slide ${slideNum}/${plan.slides.length}: ${slidePlan.title}`);
858
+ let html = null;
859
+ let isCodeTemplate = true;
860
+ if (slidePlan.type === 'title') {
861
+ html = buildTitleSlideHtml(plan.design, companyName, titleSubtitle, kstDate, slideNum);
862
+ }
863
+ else if (slidePlan.type === 'closing') {
864
+ const closingTagline = (slidePlan.content_direction || '').replace(/감사합니다|thank\s*you/gi, '').trim() || undefined;
865
+ html = buildClosingSlideHtml(plan.design, companyName, slideNum, language, closingTagline);
866
+ }
867
+ else if (isOverviewSlide(slidePlan.title, i)) {
868
+ const overviewItems = parseOverviewItems(slidePlan.content_direction || '');
869
+ if (overviewItems.length >= 2) {
870
+ const firstLine = (slidePlan.content_direction || '').split('\n')[0] || '';
871
+ const overviewSubtitle = /^\d/.test(firstLine.trim()) ? '' : firstLine.trim();
872
+ html = buildOverviewSlideHtml(plan.design, slidePlan.title, overviewSubtitle, overviewItems, slideNum);
873
+ logger.info(`Slide ${slideNum}: Using code-generated overview template (${overviewItems.length} items)`);
874
+ }
875
+ }
876
+ if (!html && slidePlan.type !== 'title' && slidePlan.type !== 'closing') {
877
+ const cleanedDirection = (slidePlan.content_direction || '')
878
+ .replace(/\s*Layout\s*:\s*[^\n]*/gi, '')
879
+ .trim();
880
+ const slideLayoutType = extractLayoutHint(slidePlan.content_direction || '');
881
+ const jsonPrompt = buildContentFillJsonPrompt(slidePlan.title, cleanedDirection, slideLayoutType, language);
882
+ let slideData = null;
883
+ try {
884
+ const jsonRes = await llmClient.chatCompletion({
885
+ messages: [
886
+ { role: 'system', content: jsonPrompt },
887
+ { role: 'user', content: 'Output the JSON now.' },
888
+ ],
889
+ temperature: 0.3,
890
+ max_tokens: 2000,
891
+ });
892
+ const jsonMsg = jsonRes.choices[0]?.message;
893
+ const jsonRaw = jsonMsg ? extractContent(jsonMsg) : '';
894
+ slideData = parseContentFillJson(jsonRaw, slideLayoutType);
895
+ if (!slideData) {
896
+ logger.warn(`Slide ${slideNum}: JSON parse failed, retrying`);
897
+ const retryRes = await llmClient.chatCompletion({
898
+ messages: [
899
+ { role: 'system', content: jsonPrompt },
900
+ { role: 'user', content: 'Output ONLY valid JSON. No markdown fences, no explanation. Start with { and end with }.' },
901
+ ],
902
+ temperature: 0.2,
903
+ max_tokens: 2000,
904
+ });
905
+ const retryMsg = retryRes.choices[0]?.message;
906
+ const retryRaw = retryMsg ? extractContent(retryMsg) : '';
907
+ slideData = parseContentFillJson(retryRaw, slideLayoutType);
908
+ }
909
+ }
910
+ catch (e) {
911
+ logger.warn(`Slide ${slideNum}: JSON fill LLM call failed: ${e}`);
912
+ }
913
+ if (slideData) {
914
+ html = buildContentSlideHtml(plan.design, slidePlan.title, slideLayoutType, slideData, slideNum, i);
915
+ isCodeTemplate = true;
916
+ logger.info(`Slide ${slideNum}: Code template "${slideLayoutType}" generated`);
917
+ }
918
+ else {
919
+ isCodeTemplate = false;
920
+ logger.warn(`Slide ${slideNum}: JSON fill failed, falling back to LLM HTML generation`);
921
+ const fallbackPrompt = buildSlideHtmlPrompt(slidePlan.title, cleanedDirection, plan.design, i, plan.slides.length, language, slideLayoutType);
922
+ try {
923
+ const htmlRes = await llmClient.chatCompletion({
924
+ messages: [
925
+ { role: 'system', content: fallbackPrompt },
926
+ { role: 'user', content: 'Generate the HTML slide now.' },
927
+ ],
928
+ temperature: 0.3,
929
+ max_tokens: 8000,
930
+ });
931
+ const htmlMsg = htmlRes.choices[0]?.message;
932
+ const rawHtml = htmlMsg ? extractContent(htmlMsg) : '';
933
+ html = extractHtml(rawHtml);
934
+ }
935
+ catch (e) {
936
+ logger.warn(`Slide ${slideNum}: LLM HTML fallback failed: ${e}`);
937
+ }
938
+ }
939
+ }
940
+ if (!html) {
941
+ logger.warn(`Slide ${slideNum}: Failed to generate HTML, skipping`);
942
+ failCount++;
943
+ continue;
944
+ }
945
+ const htmlFileName = `hanseol_slide_${slideNum}_${timestamp}.html`;
946
+ const pngFileName = `hanseol_slide_${slideNum}_${timestamp}.png`;
947
+ const htmlWritePath = path.join(tempWritePath, htmlFileName);
948
+ const pngWritePath = path.join(tempWritePath, pngFileName);
949
+ const htmlWinPath = `${tempWinPath}\\${htmlFileName}`;
950
+ const pngWinPath = `${tempWinPath}\\${pngFileName}`;
951
+ try {
952
+ const viewportHtml = isCodeTemplate
953
+ ? injectEdgeSizing(html, plan.design.background_color)
954
+ : injectViewportCss(html, plan.design.background_color);
955
+ const processed = injectTitleContrastFix(viewportHtml, plan.design.text_color);
956
+ fs.writeFileSync(htmlWritePath, processed, 'utf-8');
957
+ tempFiles.push(htmlWritePath);
958
+ }
959
+ catch (e) {
960
+ logger.warn(`Slide ${slideNum}: Failed to write HTML file: ${e}`);
961
+ failCount++;
962
+ continue;
963
+ }
964
+ let renderSuccess = false;
965
+ try {
966
+ const renderResult = await powerpointClient.renderHtmlToImage(htmlWinPath, pngWinPath);
967
+ totalToolCalls++;
968
+ renderSuccess = renderResult.success;
969
+ if (!renderSuccess) {
970
+ await new Promise(r => setTimeout(r, 2000));
971
+ const retryRender = await powerpointClient.renderHtmlToImage(htmlWinPath, pngWinPath);
972
+ totalToolCalls++;
973
+ renderSuccess = retryRender.success;
974
+ }
975
+ }
976
+ catch (e) {
977
+ logger.warn(`Slide ${slideNum}: Edge screenshot failed: ${e}`);
978
+ try {
979
+ await new Promise(r => setTimeout(r, 2000));
980
+ const retryRender = await powerpointClient.renderHtmlToImage(htmlWinPath, pngWinPath);
981
+ totalToolCalls++;
982
+ renderSuccess = retryRender.success;
983
+ }
984
+ catch {
985
+ renderSuccess = false;
986
+ }
987
+ }
988
+ try {
989
+ fs.unlinkSync(htmlWritePath);
990
+ }
991
+ catch { }
992
+ if (!renderSuccess) {
993
+ logger.warn(`Slide ${slideNum}: Screenshot rendering failed, skipping`);
994
+ failCount++;
995
+ continue;
996
+ }
997
+ try {
998
+ const pngStats = fs.statSync(pngWritePath);
999
+ if (pngStats.size < 15000) {
1000
+ logger.warn(`Slide ${slideNum}: Screenshot too small (${pngStats.size} bytes), likely blank — skipping`);
1001
+ failCount++;
1002
+ try {
1003
+ fs.unlinkSync(pngWritePath);
1004
+ }
1005
+ catch { }
1006
+ continue;
1007
+ }
1008
+ }
1009
+ catch { }
1010
+ tempFiles.push(pngWritePath);
1011
+ const addResult = await powerpointClient.powerpointAddSlide(7);
1012
+ totalToolCalls++;
1013
+ if (!addResult.success) {
1014
+ logger.warn(`Slide ${slideNum}: Failed to add blank slide`);
1015
+ failCount++;
1016
+ continue;
1017
+ }
1018
+ const bgResult = await powerpointClient.powerpointAddFullSlideImage(slideNum, pngWinPath);
1019
+ totalToolCalls++;
1020
+ if (toolCallLogger)
1021
+ toolCallLogger('powerpoint-create', 'addFullSlideImage', { slideNum, imagePath: pngWinPath }, bgResult.success ? 'OK' : 'Failed', bgResult.success, slideNum, totalToolCalls);
1022
+ if (bgResult.success) {
1023
+ builtSlides.push(`Slide ${slideNum}: ${slidePlan.title} (${slidePlan.type})`);
1024
+ try {
1025
+ await powerpointClient.powerpointAddNote(slideNum, html);
1026
+ }
1027
+ catch { }
1028
+ }
1029
+ else {
1030
+ logger.warn(`Slide ${slideNum}: Failed to set background: ${JSON.stringify(bgResult)}`);
1031
+ failCount++;
1032
+ }
1033
+ }
1034
+ if (builtSlides.length > 0) {
1035
+ try {
1036
+ const slideCountResult = await powerpointClient.powerpointGetSlideCount();
1037
+ const totalSlidesInPpt = slideCountResult['slide_count'] || 0;
1038
+ if (totalSlidesInPpt > builtSlides.length) {
1039
+ logger.warn(`PPT has ${totalSlidesInPpt} slides but only ${builtSlides.length} were rendered — deleting ${totalSlidesInPpt - builtSlides.length} trailing blanks`);
1040
+ for (let d = totalSlidesInPpt; d > builtSlides.length; d--) {
1041
+ await powerpointClient.powerpointDeleteSlide(d);
1042
+ totalToolCalls++;
1043
+ }
1044
+ }
1045
+ }
1046
+ catch (e) {
1047
+ logger.warn(`Failed to clean up trailing slides: ${e}`);
1048
+ }
1049
+ }
1050
+ if (builtSlides.length > 0) {
1051
+ if (savePath) {
1052
+ const wslSavePath = savePath.replace(/\\/g, '/').replace(/^([A-Za-z]):/, (_m, d) => `/mnt/${d.toLowerCase()}`);
1053
+ try {
1054
+ fs.unlinkSync(wslSavePath);
1055
+ }
1056
+ catch { }
1057
+ }
1058
+ let saveResult = await powerpointClient.powerpointSave(savePath);
1059
+ totalToolCalls++;
1060
+ if (toolCallLogger)
1061
+ toolCallLogger('powerpoint-create', 'powerpoint_save', { path: savePath }, saveResult.success ? (saveResult['path'] || 'OK') : (saveResult.error || 'Failed'), saveResult.success, 0, totalToolCalls);
1062
+ if (!saveResult.success && savePath) {
1063
+ const fallbackPath = 'C:\\temp\\presentation.pptx';
1064
+ saveResult = await powerpointClient.powerpointSave(fallbackPath);
1065
+ totalToolCalls++;
1066
+ if (toolCallLogger)
1067
+ toolCallLogger('powerpoint-create', 'powerpoint_save', { path: fallbackPath }, saveResult.success ? (saveResult['path'] || 'OK') : (saveResult.error || 'Failed'), saveResult.success, 0, totalToolCalls);
1068
+ }
1069
+ }
1070
+ for (const tempFile of tempFiles) {
1071
+ try {
1072
+ fs.unlinkSync(tempFile);
1073
+ }
1074
+ catch { }
1075
+ }
1076
+ const duration = Date.now() - startTime;
1077
+ const slideList = builtSlides.join('\n');
1078
+ const summary = `Presentation COMPLETE — ${builtSlides.length} slides created and saved successfully.\nAll requested topics are covered across these slides. Do NOT add more slides or call powerpoint_modify_agent.\n\nSlides:\n${slideList}`;
1079
+ logger.exit('PPT-Create.runStructured', { slideCount: builtSlides.length, totalToolCalls, duration });
1080
+ return {
1081
+ success: builtSlides.length > 0,
1082
+ result: summary,
1083
+ metadata: { iterations: plan.slides.length, toolCalls: totalToolCalls, duration },
1084
+ };
1085
+ }
1086
+ export function createPowerPointCreateRequestTool() {
1087
+ return {
1088
+ definition: {
1089
+ type: 'function',
1090
+ function: {
1091
+ name: 'powerpoint_create_agent',
1092
+ 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.',
1093
+ parameters: {
1094
+ type: 'object',
1095
+ properties: {
1096
+ instruction: {
1097
+ type: 'string',
1098
+ 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.',
1099
+ },
1100
+ save_path: {
1101
+ type: 'string',
1102
+ description: 'Windows file path to save the presentation (e.g., "C:\\\\temp\\\\pitch.pptx"). MUST be provided if the user specified a save path.',
1103
+ },
1104
+ },
1105
+ required: ['instruction'],
1106
+ },
1107
+ },
1108
+ },
1109
+ execute: async (args, llmClient) => {
1110
+ const instruction = args['instruction'];
1111
+ const explicitSavePath = args['save_path'];
1112
+ return runStructured(llmClient, instruction, explicitSavePath);
1113
+ },
1114
+ categories: ['llm-agent'],
1115
+ requiresSubLLM: true,
1116
+ };
1117
+ }
1118
+ //# sourceMappingURL=powerpoint-create-agent.js.map