@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
- package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
- package/bundled-assets/skill/LICENSE +21 -0
- package/bundled-assets/skill/README.md +61 -0
- package/bundled-assets/skill/SKILL.md +185 -0
- package/bundled-assets/skill/references/art-directions.md +99 -0
- package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
- package/bundled-assets/skill/references/design-baseline.txt +1 -0
- package/bundled-assets/skill/references/prompt-compiler.md +99 -0
- package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
- package/bundled-assets/skill/references/staged-pptx.md +71 -0
- package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
- package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
- package/bundled-assets/skill/scripts/brand_ref.py +776 -0
- package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
- package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
- package/bundled-assets/skill/scripts/export_images.py +280 -0
- package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
- package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
- package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
- package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
- package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
- package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
- package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
- package/bundled-assets/skill/scripts/render_gradient.py +258 -0
- package/bundled-assets/skill/scripts/slide_brand.py +111 -0
- package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
- package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
- package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
- package/bundled-assets/skill/vendor/README.md +4 -0
- package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
- package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
- package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
- package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
- package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
- package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +11282 -0
- package/lib/index.js +2638 -0
- package/package.json +140 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,2638 @@
|
|
|
1
|
+
import Schema from "@deepseek-ai/schemastery";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import path, { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { execFile, spawn } from "node:child_process";
|
|
7
|
+
import { homedir, tmpdir } from "node:os";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
+
import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
12
|
+
import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
|
|
13
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
14
|
+
// src/host/assets.ts
|
|
15
|
+
const MIME_BY_EXT$1 = {
|
|
16
|
+
".webp": "image/webp",
|
|
17
|
+
".png": "image/png",
|
|
18
|
+
".jpg": "image/jpeg",
|
|
19
|
+
".jpeg": "image/jpeg",
|
|
20
|
+
".svg": "image/svg+xml"
|
|
21
|
+
};
|
|
22
|
+
const brandCache = /* @__PURE__ */ new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Find the dsh-plugin package root starting from the executing module directory.
|
|
25
|
+
*/
|
|
26
|
+
function findPluginRoot(fromUrl = import.meta.url) {
|
|
27
|
+
let cursor = dirname(fileURLToPath(fromUrl));
|
|
28
|
+
for (let depth = 0; depth < 6; depth += 1) {
|
|
29
|
+
if (existsSync(join(cursor, "package.json"))) return cursor;
|
|
30
|
+
const parent = dirname(cursor);
|
|
31
|
+
if (parent === cursor) break;
|
|
32
|
+
cursor = parent;
|
|
33
|
+
}
|
|
34
|
+
return resolve(dirname(fileURLToPath(fromUrl)), "..");
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Single-source asset resolution:
|
|
38
|
+
* 1. Dev/monorepo mode: resolves directly from parent repo (`../oil-slide`, `./assets`).
|
|
39
|
+
* 2. Packed/installed mode: falls back to `bundled-assets/` produced by `scripts/sync-assets.mjs`.
|
|
40
|
+
*/
|
|
41
|
+
function resolvePluginAssets(options) {
|
|
42
|
+
const pluginRoot = resolve(options?.pluginRoot ?? findPluginRoot());
|
|
43
|
+
const parentRepo = resolve(pluginRoot, "..");
|
|
44
|
+
const monoSkillDir = join(parentRepo, "oil-slide");
|
|
45
|
+
const monoSkillFile = join(monoSkillDir, "SKILL.md");
|
|
46
|
+
const monoBrandDir = join(pluginRoot, "assets");
|
|
47
|
+
const bundledRoot = join(pluginRoot, "bundled-assets");
|
|
48
|
+
const bundledSkillDir = join(bundledRoot, "skill");
|
|
49
|
+
const bundledSkillFile = join(bundledSkillDir, "SKILL.md");
|
|
50
|
+
const bundledBrandDir = join(bundledRoot, "brand");
|
|
51
|
+
const hasMonorepo = existsSync(monoSkillFile) && existsSync(monoBrandDir);
|
|
52
|
+
const hasBundled = existsSync(bundledSkillFile) && existsSync(bundledBrandDir);
|
|
53
|
+
if (options?.preferBundled === true && hasBundled) return {
|
|
54
|
+
mode: "bundled",
|
|
55
|
+
pluginRoot,
|
|
56
|
+
repoRoot: hasMonorepo ? parentRepo : null,
|
|
57
|
+
skillDir: bundledSkillDir,
|
|
58
|
+
skillFile: bundledSkillFile,
|
|
59
|
+
scriptsDir: join(bundledSkillDir, "scripts"),
|
|
60
|
+
brandDir: bundledBrandDir
|
|
61
|
+
};
|
|
62
|
+
if (hasMonorepo) return {
|
|
63
|
+
mode: "monorepo",
|
|
64
|
+
pluginRoot,
|
|
65
|
+
repoRoot: parentRepo,
|
|
66
|
+
skillDir: monoSkillDir,
|
|
67
|
+
skillFile: monoSkillFile,
|
|
68
|
+
scriptsDir: join(monoSkillDir, "scripts"),
|
|
69
|
+
brandDir: monoBrandDir
|
|
70
|
+
};
|
|
71
|
+
if (hasBundled) return {
|
|
72
|
+
mode: "bundled",
|
|
73
|
+
pluginRoot,
|
|
74
|
+
repoRoot: null,
|
|
75
|
+
skillDir: bundledSkillDir,
|
|
76
|
+
skillFile: bundledSkillFile,
|
|
77
|
+
scriptsDir: join(bundledSkillDir, "scripts"),
|
|
78
|
+
brandDir: bundledBrandDir
|
|
79
|
+
};
|
|
80
|
+
throw new Error(`dsh-oil-slide assets not found. Checked monorepo (${monoSkillFile}) and bundled (${bundledSkillFile}). Run "pnpm sync:assets" before packaging.`);
|
|
81
|
+
}
|
|
82
|
+
async function readFileAsDataUrl(absPath) {
|
|
83
|
+
if (!existsSync(absPath)) return "";
|
|
84
|
+
const ext = extname(absPath).toLowerCase();
|
|
85
|
+
return `data:${MIME_BY_EXT$1[ext] ?? "application/octet-stream"};base64,${(await readFile(absPath)).toString("base64")}`;
|
|
86
|
+
}
|
|
87
|
+
async function loadBrandAssets(brandDir) {
|
|
88
|
+
const cached = brandCache.get(brandDir);
|
|
89
|
+
if (cached !== void 0) return cached;
|
|
90
|
+
const [markDataUrl, emptyDeckCobaltDataUrl] = await Promise.all([readFileAsDataUrl(join(brandDir, "oil-slide-mark-512.png")), readFileAsDataUrl(join(brandDir, "empty-deck-cobalt.webp"))]);
|
|
91
|
+
const result = {
|
|
92
|
+
markDataUrl,
|
|
93
|
+
emptyDeckCobaltDataUrl
|
|
94
|
+
};
|
|
95
|
+
brandCache.set(brandDir, result);
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
// src/shared/review.ts
|
|
99
|
+
const pageSchema = z.object({
|
|
100
|
+
title: z.string().trim().min(1).max(4e3),
|
|
101
|
+
content: z.string().trim().min(1).max(4e3),
|
|
102
|
+
takeaway: z.string().max(4e3).optional(),
|
|
103
|
+
notes: z.string().max(4e3).optional(),
|
|
104
|
+
layout: z.string().max(4e3).optional(),
|
|
105
|
+
assets: z.string().max(4e3).optional()
|
|
106
|
+
});
|
|
107
|
+
const key = z.string().regex(/^[a-f0-9]{32}$/);
|
|
108
|
+
const asset = z.union([z.object({ data: z.string().min(1).max(4194304) }), z.object({ path: z.string().min(1).max(2048) })]);
|
|
109
|
+
const fields$1 = {
|
|
110
|
+
name: z.string().trim().min(1).max(120),
|
|
111
|
+
colors: z.string().max(500),
|
|
112
|
+
font: z.string().max(500),
|
|
113
|
+
footer: z.string().max(500)
|
|
114
|
+
};
|
|
115
|
+
const brandSchema = z.object({
|
|
116
|
+
...fields$1,
|
|
117
|
+
id: key,
|
|
118
|
+
images: z.array(z.string()),
|
|
119
|
+
template: z.boolean().optional()
|
|
120
|
+
});
|
|
121
|
+
const regionSchema = z.object({
|
|
122
|
+
id: key,
|
|
123
|
+
number: z.number().int().positive(),
|
|
124
|
+
revision: z.number().int().positive(),
|
|
125
|
+
feedback: z.string(),
|
|
126
|
+
sha256: z.string(),
|
|
127
|
+
applying: z.boolean().optional()
|
|
128
|
+
});
|
|
129
|
+
const coord = z.number().int().min(0).max(1e3);
|
|
130
|
+
const operationSchema = z.discriminatedUnion("kind", [
|
|
131
|
+
z.object({
|
|
132
|
+
kind: z.literal("inspect-native"),
|
|
133
|
+
number: z.number().int().min(1).max(60)
|
|
134
|
+
}),
|
|
135
|
+
z.object({ kind: z.literal("brands") }),
|
|
136
|
+
z.object({
|
|
137
|
+
kind: z.literal("save-brand"),
|
|
138
|
+
...fields$1,
|
|
139
|
+
logo: asset.optional(),
|
|
140
|
+
template: asset.optional()
|
|
141
|
+
}),
|
|
142
|
+
z.object({
|
|
143
|
+
kind: z.literal("outline"),
|
|
144
|
+
revision: z.string(),
|
|
145
|
+
pages: z.array(pageSchema).min(1).max(60),
|
|
146
|
+
brandId: key.nullable()
|
|
147
|
+
}),
|
|
148
|
+
z.object({
|
|
149
|
+
kind: z.literal("region"),
|
|
150
|
+
revision: z.number().int().positive(),
|
|
151
|
+
number: z.number().int().min(1).max(60),
|
|
152
|
+
feedback: z.string().trim().min(1).max(4e3),
|
|
153
|
+
box: z.tuple([
|
|
154
|
+
coord,
|
|
155
|
+
coord,
|
|
156
|
+
coord,
|
|
157
|
+
coord
|
|
158
|
+
])
|
|
159
|
+
}),
|
|
160
|
+
z.object({ kind: z.literal("region-status") }),
|
|
161
|
+
z.object({
|
|
162
|
+
kind: z.literal("resolve"),
|
|
163
|
+
id: key,
|
|
164
|
+
choice: z.enum(["keep", "apply"])
|
|
165
|
+
})
|
|
166
|
+
]);
|
|
167
|
+
const reviewRequestSchema = z.object({
|
|
168
|
+
workspaceRoot: z.string().optional(),
|
|
169
|
+
deckRelPath: z.string().min(1),
|
|
170
|
+
operation: operationSchema
|
|
171
|
+
});
|
|
172
|
+
const nativePageSchema = z.object({
|
|
173
|
+
changed: z.array(z.number().int()),
|
|
174
|
+
file: z.string().optional(),
|
|
175
|
+
preview: z.string().optional(),
|
|
176
|
+
objects: z.array(z.object({
|
|
177
|
+
label: z.string(),
|
|
178
|
+
kind: z.enum([
|
|
179
|
+
"text",
|
|
180
|
+
"image",
|
|
181
|
+
"table",
|
|
182
|
+
"shape"
|
|
183
|
+
]),
|
|
184
|
+
box: z.tuple([
|
|
185
|
+
z.number(),
|
|
186
|
+
z.number(),
|
|
187
|
+
z.number(),
|
|
188
|
+
z.number()
|
|
189
|
+
])
|
|
190
|
+
}))
|
|
191
|
+
});
|
|
192
|
+
const reviewResultSchema = z.object({
|
|
193
|
+
brands: z.array(brandSchema).optional(),
|
|
194
|
+
brand: brandSchema.optional(),
|
|
195
|
+
busy: z.boolean().optional(),
|
|
196
|
+
error: z.string().optional(),
|
|
197
|
+
native: nativePageSchema.optional(),
|
|
198
|
+
revision: z.string().optional()
|
|
199
|
+
});
|
|
200
|
+
// src/shared/schemas.ts
|
|
201
|
+
const emptyRequestSchema = z.object({});
|
|
202
|
+
const brandAssetsResultSchema = z.object({
|
|
203
|
+
markDataUrl: z.string(),
|
|
204
|
+
emptyDeckCobaltDataUrl: z.string().default("")
|
|
205
|
+
});
|
|
206
|
+
const deckSlideInfoSchema = z.object({
|
|
207
|
+
name: z.string(),
|
|
208
|
+
relPath: z.string(),
|
|
209
|
+
label: z.string(),
|
|
210
|
+
slideNumber: z.number().nullable(),
|
|
211
|
+
kind: z.enum([
|
|
212
|
+
"slide",
|
|
213
|
+
"overview",
|
|
214
|
+
"verify",
|
|
215
|
+
"explore"
|
|
216
|
+
]),
|
|
217
|
+
sizeBytes: z.number(),
|
|
218
|
+
mtimeMs: z.number()
|
|
219
|
+
});
|
|
220
|
+
const workflowStageSchema = z.enum([
|
|
221
|
+
"outline_review",
|
|
222
|
+
"drafts",
|
|
223
|
+
"style_review",
|
|
224
|
+
"production",
|
|
225
|
+
"image_ready",
|
|
226
|
+
"converting",
|
|
227
|
+
"editable_ready"
|
|
228
|
+
]);
|
|
229
|
+
const workflowOutlineSchema = z.array(pageSchema).min(1).max(60);
|
|
230
|
+
const workflowCandidatesSchema = z.array(z.object({
|
|
231
|
+
number: z.number().int().min(1).max(3),
|
|
232
|
+
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
|
233
|
+
style: z.string().max(12e3),
|
|
234
|
+
history: z.array(z.string().regex(/^[a-f0-9]{64}$/)).optional()
|
|
235
|
+
})).max(3);
|
|
236
|
+
const workflowStateOnDiskSchema = z.object({
|
|
237
|
+
version: z.literal(1),
|
|
238
|
+
editablePreview: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
|
239
|
+
stage: workflowStageSchema,
|
|
240
|
+
deckRevision: z.number().int().positive().optional(),
|
|
241
|
+
outlineQuestionId: z.string().regex(/^oil_outline_[a-f0-9]{16}$/).optional(),
|
|
242
|
+
reviewId: z.string().regex(/^oil_style_[a-f0-9]{16}$/).optional(),
|
|
243
|
+
ratio: z.string().optional(),
|
|
244
|
+
outline: workflowOutlineSchema,
|
|
245
|
+
brand: brandSchema.optional(),
|
|
246
|
+
regionProposal: regionSchema.optional(),
|
|
247
|
+
outlineRevision: z.string().regex(/^[a-f0-9]{12}$/),
|
|
248
|
+
count: z.number().int().min(1).max(3).optional(),
|
|
249
|
+
samplePage: z.number().int().min(1).max(60).optional(),
|
|
250
|
+
candidates: workflowCandidatesSchema,
|
|
251
|
+
approved: z.object({ number: z.number().int().min(1).max(3) }).nullable(),
|
|
252
|
+
pages: z.record(z.string().regex(/^\d{1,2}$/), z.unknown())
|
|
253
|
+
});
|
|
254
|
+
const deckWorkflowSummarySchema = z.object({
|
|
255
|
+
stage: workflowStageSchema,
|
|
256
|
+
deckRevision: z.number().int().positive().optional(),
|
|
257
|
+
outlineQuestionId: z.string().regex(/^oil_outline_[a-f0-9]{16}$/).optional(),
|
|
258
|
+
reviewId: z.string().regex(/^oil_style_[a-f0-9]{16}$/).optional(),
|
|
259
|
+
ratio: z.string().optional(),
|
|
260
|
+
outline: workflowOutlineSchema,
|
|
261
|
+
brand: brandSchema.optional(),
|
|
262
|
+
regionProposal: regionSchema.optional(),
|
|
263
|
+
outlineRevision: z.string(),
|
|
264
|
+
candidateCount: z.number().optional(),
|
|
265
|
+
samplePage: z.number().optional(),
|
|
266
|
+
candidates: workflowCandidatesSchema,
|
|
267
|
+
selected: z.number().optional(),
|
|
268
|
+
editableSlides: z.array(deckSlideInfoSchema).optional(),
|
|
269
|
+
previousDownloads: z.array(z.object({
|
|
270
|
+
revision: z.number(),
|
|
271
|
+
image: z.string(),
|
|
272
|
+
editable: z.string().optional()
|
|
273
|
+
})).optional(),
|
|
274
|
+
produced: z.number().int().nonnegative(),
|
|
275
|
+
imagePptxRelPath: z.string().nullable(),
|
|
276
|
+
editablePptxRelPath: z.string().nullable()
|
|
277
|
+
});
|
|
278
|
+
const deckSummarySchema = z.object({
|
|
279
|
+
id: z.string(),
|
|
280
|
+
name: z.string(),
|
|
281
|
+
relPath: z.string(),
|
|
282
|
+
absPath: z.string(),
|
|
283
|
+
workflow: deckWorkflowSummarySchema.optional(),
|
|
284
|
+
slides: z.array(deckSlideInfoSchema),
|
|
285
|
+
exploreSlides: z.array(deckSlideInfoSchema).default([]),
|
|
286
|
+
overview: deckSlideInfoSchema.nullable(),
|
|
287
|
+
verifyImages: z.array(deckSlideInfoSchema),
|
|
288
|
+
htmlRelPath: z.string().nullable(),
|
|
289
|
+
pptxRelPath: z.string().nullable(),
|
|
290
|
+
htmlUpdatedAt: z.string().nullable(),
|
|
291
|
+
pptxUpdatedAt: z.string().nullable(),
|
|
292
|
+
pptxStale: z.boolean(),
|
|
293
|
+
updatedAt: z.string()
|
|
294
|
+
});
|
|
295
|
+
const scanDecksRequestSchema = z.object({ workspaceRoot: z.string().optional() });
|
|
296
|
+
const scanDecksResultSchema = z.object({
|
|
297
|
+
workspaceRoot: z.string().nullable(),
|
|
298
|
+
decks: z.array(deckSummarySchema)
|
|
299
|
+
});
|
|
300
|
+
const deckHtmlPreviewRequestSchema = z.object({
|
|
301
|
+
workspaceRoot: z.string().optional(),
|
|
302
|
+
deckRelPath: z.string()
|
|
303
|
+
});
|
|
304
|
+
const deckHtmlPreviewResultSchema = z.object({
|
|
305
|
+
found: z.boolean(),
|
|
306
|
+
deckRelPath: z.string(),
|
|
307
|
+
htmlRelPath: z.string(),
|
|
308
|
+
slideCount: z.number(),
|
|
309
|
+
html: z.string(),
|
|
310
|
+
error: z.string().optional()
|
|
311
|
+
});
|
|
312
|
+
const workspaceImageRequestSchema = z.object({
|
|
313
|
+
workspaceRoot: z.string().optional(),
|
|
314
|
+
relPath: z.string().min(1),
|
|
315
|
+
maxWidth: z.number().int().min(64).max(4096).optional(),
|
|
316
|
+
quality: z.number().int().min(40).max(100).optional()
|
|
317
|
+
});
|
|
318
|
+
const workspaceImageResultSchema = z.object({
|
|
319
|
+
found: z.boolean(),
|
|
320
|
+
relPath: z.string(),
|
|
321
|
+
mime: z.string(),
|
|
322
|
+
dataUrl: z.string(),
|
|
323
|
+
error: z.string().optional()
|
|
324
|
+
});
|
|
325
|
+
const compileDeckPptxRequestSchema = z.object({
|
|
326
|
+
workspaceRoot: z.string().optional(),
|
|
327
|
+
deckRelPath: z.string(),
|
|
328
|
+
outRelPath: z.string().optional()
|
|
329
|
+
});
|
|
330
|
+
const compileDeckPptxResultSchema = z.object({
|
|
331
|
+
ok: z.boolean(),
|
|
332
|
+
deckRelPath: z.string(),
|
|
333
|
+
htmlPath: z.string(),
|
|
334
|
+
outPath: z.string(),
|
|
335
|
+
pptxRelPath: z.string(),
|
|
336
|
+
durationMs: z.number(),
|
|
337
|
+
stdout: z.string(),
|
|
338
|
+
stderr: z.string(),
|
|
339
|
+
error: z.string().optional()
|
|
340
|
+
});
|
|
341
|
+
const doctorRequestSchema = z.object({ workspaceRoot: z.string().optional() });
|
|
342
|
+
const doctorCheckSchema = z.object({
|
|
343
|
+
id: z.string(),
|
|
344
|
+
label: z.string(),
|
|
345
|
+
status: z.enum([
|
|
346
|
+
"ok",
|
|
347
|
+
"warn",
|
|
348
|
+
"missing"
|
|
349
|
+
]),
|
|
350
|
+
detail: z.string(),
|
|
351
|
+
fixHint: z.string().optional()
|
|
352
|
+
});
|
|
353
|
+
const previewSignalSchema = z.object({
|
|
354
|
+
seq: z.number(),
|
|
355
|
+
deckRelPath: z.string().nullable(),
|
|
356
|
+
tab: z.enum([
|
|
357
|
+
"auto",
|
|
358
|
+
"canvas",
|
|
359
|
+
"reference"
|
|
360
|
+
]),
|
|
361
|
+
workspaceRoot: z.string().nullable(),
|
|
362
|
+
emittedAt: z.string()
|
|
363
|
+
});
|
|
364
|
+
const waitPreviewSignalRequestSchema = z.object({
|
|
365
|
+
afterSeq: z.number().int().min(-1),
|
|
366
|
+
timeoutMs: z.number().int().min(100).max(3e4).optional()
|
|
367
|
+
});
|
|
368
|
+
const waitPreviewSignalResultSchema = z.object({
|
|
369
|
+
changed: z.boolean(),
|
|
370
|
+
seq: z.number(),
|
|
371
|
+
signal: previewSignalSchema.nullable()
|
|
372
|
+
});
|
|
373
|
+
const doctorReportSchema = z.object({
|
|
374
|
+
ok: z.boolean(),
|
|
375
|
+
pythonBin: z.string().nullable(),
|
|
376
|
+
skillDir: z.string(),
|
|
377
|
+
checks: z.array(doctorCheckSchema)
|
|
378
|
+
});
|
|
379
|
+
const imageModelSchema = z.string().trim().min(1).max(256);
|
|
380
|
+
const channelIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
|
|
381
|
+
const imageChannelConnectionSchema = z.object({
|
|
382
|
+
id: channelIdSchema,
|
|
383
|
+
baseUrl: z.string().trim().min(1).max(2048),
|
|
384
|
+
apiKey: z.string().trim().max(8192).regex(/^[^\r\n]*$/).optional()
|
|
385
|
+
});
|
|
386
|
+
const channelUpdateSchema = imageChannelConnectionSchema.extend({
|
|
387
|
+
name: z.string().trim().min(1).max(80),
|
|
388
|
+
models: z.array(imageModelSchema).max(100)
|
|
389
|
+
});
|
|
390
|
+
const routesSchema = z.array(z.object({
|
|
391
|
+
channelId: channelIdSchema,
|
|
392
|
+
model: imageModelSchema
|
|
393
|
+
})).max(100);
|
|
394
|
+
const settingsRevisionSchema = z.string().min(1).max(64);
|
|
395
|
+
const imageChannelSettingsUpdateSchema = z.object({
|
|
396
|
+
revision: settingsRevisionSchema,
|
|
397
|
+
channels: z.array(channelUpdateSchema).max(50),
|
|
398
|
+
routes: routesSchema
|
|
399
|
+
});
|
|
400
|
+
const imageChannelSettingsSchema = z.object({
|
|
401
|
+
revision: settingsRevisionSchema,
|
|
402
|
+
channels: z.array(channelUpdateSchema.omit({ apiKey: true }).extend({ hasKey: z.boolean() })).max(50),
|
|
403
|
+
routes: routesSchema,
|
|
404
|
+
environmentModel: z.string().nullable()
|
|
405
|
+
});
|
|
406
|
+
const imageModelDiscoverySchema = z.object({ models: z.array(z.object({
|
|
407
|
+
id: imageModelSchema,
|
|
408
|
+
imageHint: z.boolean()
|
|
409
|
+
})) });
|
|
410
|
+
// src/host/modelDiscovery.ts
|
|
411
|
+
function fields(value) {
|
|
412
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
413
|
+
}
|
|
414
|
+
function strings(value) {
|
|
415
|
+
return (Array.isArray(value) ? value : [value]).filter((item) => typeof item === "string").map((item) => item.toLowerCase().trim());
|
|
416
|
+
}
|
|
417
|
+
const imageTasks = /\b(?:text[-_ ]?to[-_ ]?image|image[-_ ]?(?:gen(?:eration)?|edit(?:ing)?))\b/i;
|
|
418
|
+
function imageCapability(model) {
|
|
419
|
+
const endpoints = strings(model.supported_endpoint_types);
|
|
420
|
+
if (strings(model.kind).includes("image") || endpoints.some((value) => imageTasks.test(value) || /images\/(?:generations|edits)$/.test(value))) return true;
|
|
421
|
+
const outputs = [
|
|
422
|
+
fields(model.modalities).output,
|
|
423
|
+
fields(model.architecture).output_modalities,
|
|
424
|
+
model.output_modalities,
|
|
425
|
+
model.outputModalities,
|
|
426
|
+
model.supported_output_modalities
|
|
427
|
+
].flatMap(strings);
|
|
428
|
+
if (outputs.includes("image")) return true;
|
|
429
|
+
const caps = fields(model.capabilities);
|
|
430
|
+
const flags = [
|
|
431
|
+
caps.image_generation,
|
|
432
|
+
caps.imageGeneration,
|
|
433
|
+
caps.text_to_image,
|
|
434
|
+
caps.textToImage,
|
|
435
|
+
caps.image_gen
|
|
436
|
+
];
|
|
437
|
+
if (flags.includes(true)) return true;
|
|
438
|
+
if (flags.includes(false)) return false;
|
|
439
|
+
const tasks = [
|
|
440
|
+
model.type,
|
|
441
|
+
model.task,
|
|
442
|
+
model.task_type,
|
|
443
|
+
model.taskType,
|
|
444
|
+
model.tasks,
|
|
445
|
+
model.model_type,
|
|
446
|
+
model.modelType,
|
|
447
|
+
model.description,
|
|
448
|
+
model.capabilities,
|
|
449
|
+
Object.values(caps)
|
|
450
|
+
].flatMap(strings);
|
|
451
|
+
if (tasks.some((value) => value === "image" || imageTasks.test(value))) return true;
|
|
452
|
+
if (outputs.length || strings(model.kind).includes("chat") || tasks.some((value) => /embedding|rerank|moderation|transcription|speech|audio|video|chat[-_ ]?completion/.test(value))) return false;
|
|
453
|
+
}
|
|
454
|
+
function parseCatalog(body) {
|
|
455
|
+
const obj = fields(body);
|
|
456
|
+
const list = [
|
|
457
|
+
body,
|
|
458
|
+
obj.data,
|
|
459
|
+
obj.models,
|
|
460
|
+
fields(obj.output).models
|
|
461
|
+
].find(Array.isArray);
|
|
462
|
+
if (!list) throw new Error("渠道响应中没有可识别的模型列表 / No model list in the response.");
|
|
463
|
+
const entries = [];
|
|
464
|
+
for (const item of list) {
|
|
465
|
+
const record = fields(item);
|
|
466
|
+
const name = [
|
|
467
|
+
item,
|
|
468
|
+
record.id,
|
|
469
|
+
record.model
|
|
470
|
+
].find((value) => typeof value === "string" && value.trim());
|
|
471
|
+
if (typeof name !== "string") continue;
|
|
472
|
+
const id = name.trim();
|
|
473
|
+
if (id.length <= 256) entries.push({
|
|
474
|
+
id,
|
|
475
|
+
capability: imageCapability(record)
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
return entries;
|
|
479
|
+
}
|
|
480
|
+
function likelyImageName(id) {
|
|
481
|
+
const name = id.split("/").at(-1) ?? id;
|
|
482
|
+
return /(?:^|[.:_#-])(?:image|img|diffusion|flux|cogview|imagen|seedream|nano[-_]?banana|grok-imagine|dall-e|sdxl|pixart|kolors|ideogram|midjourney|recraft|hunyuan|jimeng|wanx|hidream|playground|sensenova-u\d*)(?=$|[.:_#-])/i.test(name) || /^(?:gpt-image|gemini[-\w.]*-image|qwen-image)/i.test(name);
|
|
483
|
+
}
|
|
484
|
+
async function readCatalog(url, headers, signal) {
|
|
485
|
+
let response;
|
|
486
|
+
try {
|
|
487
|
+
response = await fetch(url, {
|
|
488
|
+
headers,
|
|
489
|
+
signal,
|
|
490
|
+
redirect: "error"
|
|
491
|
+
});
|
|
492
|
+
} catch {
|
|
493
|
+
throw new Error("无法连接模型列表,请检查 API 地址和网络 / Could not reach the model list.");
|
|
494
|
+
}
|
|
495
|
+
if (!response.ok) {
|
|
496
|
+
await response.body?.cancel();
|
|
497
|
+
throw new Error(`模型列表请求失败 / Model list request failed (HTTP ${response.status})`);
|
|
498
|
+
}
|
|
499
|
+
return parseCatalog(await response.json().catch(() => null));
|
|
500
|
+
}
|
|
501
|
+
async function discoverCatalog(baseUrl, key, signal) {
|
|
502
|
+
const base = new URL(baseUrl);
|
|
503
|
+
const prefix = base.pathname.replace(/\/(?:chat\/completions|images\/(?:generations|edits)|models)$/i, "");
|
|
504
|
+
const root = base.origin + prefix.replace(/\/+$/, "");
|
|
505
|
+
const roots = [root];
|
|
506
|
+
if (!/\/v\d+[a-z\d._-]*$/i.test(prefix)) roots.push(root + "/v1");
|
|
507
|
+
const headers = { Accept: "application/json" };
|
|
508
|
+
if (key) headers.Authorization = "Bearer " + key;
|
|
509
|
+
const timeout = AbortSignal.timeout(1e4);
|
|
510
|
+
const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
511
|
+
const evidence = /* @__PURE__ */ new Map();
|
|
512
|
+
let answered = false;
|
|
513
|
+
let firstError;
|
|
514
|
+
const lists = await Promise.all(roots.map((apiRoot) => Promise.allSettled([readCatalog(apiRoot + "/models", headers, deadline), readCatalog(apiRoot + "/models?kind=image", headers, deadline)])));
|
|
515
|
+
signal?.throwIfAborted();
|
|
516
|
+
for (const [plain, filtered] of lists) {
|
|
517
|
+
const ordinaryIds = new Set(plain.status === "fulfilled" ? plain.value.map((entry) => entry.id) : []);
|
|
518
|
+
const filteredIds = new Set(filtered.status === "fulfilled" ? filtered.value.map((entry) => entry.id) : []);
|
|
519
|
+
const isNarrower = ordinaryIds.size > 0 && [...ordinaryIds].some((id) => !filteredIds.has(id));
|
|
520
|
+
for (const result of [plain, filtered]) {
|
|
521
|
+
if (result.status === "rejected") {
|
|
522
|
+
firstError ??= result.reason;
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
answered = true;
|
|
526
|
+
for (const { id, capability } of result.value) {
|
|
527
|
+
const fromImageList = result === filtered && plain.status === "fulfilled" && (isNarrower || !ordinaryIds.has(id));
|
|
528
|
+
const prior = evidence.get(id);
|
|
529
|
+
evidence.set(id, {
|
|
530
|
+
capability: prior?.capability === true ? true : capability ?? prior?.capability,
|
|
531
|
+
filtered: fromImageList || Boolean(prior?.filtered)
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (!answered) throw firstError ?? /* @__PURE__ */ new Error("模型列表不可用 / Model list unavailable.");
|
|
537
|
+
return { models: [...evidence].map(([id, info]) => ({
|
|
538
|
+
id,
|
|
539
|
+
imageHint: info.capability ?? (info.filtered || likelyImageName(id))
|
|
540
|
+
})).sort((a, b) => Number(b.imageHint) - Number(a.imageHint) || a.id.localeCompare(b.id)) };
|
|
541
|
+
}
|
|
542
|
+
// src/host/credentials.ts
|
|
543
|
+
function resolveOilSlideConfigPath(options = {}) {
|
|
544
|
+
const env = options.env ?? process.env;
|
|
545
|
+
const platform = options.platform ?? process.platform;
|
|
546
|
+
const home = options.homeDir ?? homedir();
|
|
547
|
+
const p = platform === "win32" ? path.win32 : path.posix;
|
|
548
|
+
const root = platform === "win32" ? env.APPDATA?.trim() || p.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME?.trim() || p.join(home, ".config");
|
|
549
|
+
return p.join(root, "oil-slide", "config.json");
|
|
550
|
+
}
|
|
551
|
+
// src/host/imageChannel.ts
|
|
552
|
+
const legacySchema = z.object({
|
|
553
|
+
baseUrl: z.string(),
|
|
554
|
+
model: z.string().trim().min(1),
|
|
555
|
+
apiKey: z.string().optional()
|
|
556
|
+
});
|
|
557
|
+
function filePath(options) {
|
|
558
|
+
const p = (options.platform ?? process.platform) === "win32" ? path.win32 : path.posix;
|
|
559
|
+
return p.join(p.dirname(resolveOilSlideConfigPath(options)), "image-channel.json");
|
|
560
|
+
}
|
|
561
|
+
function normalize(baseUrl) {
|
|
562
|
+
let url;
|
|
563
|
+
try {
|
|
564
|
+
url = new URL(baseUrl.trim());
|
|
565
|
+
} catch {}
|
|
566
|
+
if (!url || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("请填写不含密钥、查询参数或片段的 HTTP(S) API 根地址 / Enter an HTTP(S) API root without credentials or query parameters.");
|
|
567
|
+
return url.href.replace(/\/+$/, "");
|
|
568
|
+
}
|
|
569
|
+
async function readStored(options) {
|
|
570
|
+
try {
|
|
571
|
+
const data = JSON.parse(await readFile(filePath(options), "utf8"));
|
|
572
|
+
if (data?.version === 2) return {
|
|
573
|
+
version: 2,
|
|
574
|
+
...imageChannelSettingsUpdateSchema.parse(data)
|
|
575
|
+
};
|
|
576
|
+
const old = legacySchema.parse(data);
|
|
577
|
+
return {
|
|
578
|
+
version: 2,
|
|
579
|
+
revision: "legacy",
|
|
580
|
+
channels: [{
|
|
581
|
+
id: "legacy",
|
|
582
|
+
name: new URL(normalize(old.baseUrl)).host,
|
|
583
|
+
baseUrl: old.baseUrl,
|
|
584
|
+
models: [old.model],
|
|
585
|
+
apiKey: old.apiKey
|
|
586
|
+
}],
|
|
587
|
+
routes: [{
|
|
588
|
+
channelId: "legacy",
|
|
589
|
+
model: old.model
|
|
590
|
+
}]
|
|
591
|
+
};
|
|
592
|
+
} catch (err) {
|
|
593
|
+
if (err.code === "ENOENT") return null;
|
|
594
|
+
throw new Error("无法读取本机生图配置 / Could not read image-channel.json.");
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
async function getImageChannels(options = {}) {
|
|
598
|
+
const stored = await readStored(options);
|
|
599
|
+
const env = options.env ?? process.env;
|
|
600
|
+
let environmentModel = null;
|
|
601
|
+
if (!stored && env.OPENAI_BASE_URL) try {
|
|
602
|
+
normalize(env.OPENAI_BASE_URL);
|
|
603
|
+
environmentModel = env.CODEX_PPT_IMAGE_MODEL || env.IMAGE_TO_EDITABLE_PPT_IMAGE_MODEL || null;
|
|
604
|
+
} catch {}
|
|
605
|
+
return {
|
|
606
|
+
revision: stored?.revision ?? "empty",
|
|
607
|
+
channels: stored?.channels.map(({ apiKey, ...channel }) => ({
|
|
608
|
+
...channel,
|
|
609
|
+
hasKey: Boolean(apiKey)
|
|
610
|
+
})) ?? [],
|
|
611
|
+
routes: stored?.routes ?? [],
|
|
612
|
+
environmentModel
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function resolveKey(connection, previous) {
|
|
616
|
+
if (connection.apiKey !== void 0) return connection.apiKey.trim() || void 0;
|
|
617
|
+
const saved = previous?.channels.find((channel) => channel.id === connection.id);
|
|
618
|
+
return saved && normalize(saved.baseUrl) === normalize(connection.baseUrl) ? saved.apiKey : void 0;
|
|
619
|
+
}
|
|
620
|
+
let pendingSave = Promise.resolve();
|
|
621
|
+
function saveImageChannels(input, options = {}) {
|
|
622
|
+
const save = pendingSave.then(async () => {
|
|
623
|
+
const request = imageChannelSettingsUpdateSchema.parse(input);
|
|
624
|
+
const previous = await readStored(options);
|
|
625
|
+
if (request.revision !== (previous?.revision ?? "empty")) throw new Error("配置已在别处更新。请重新打开设置 / Settings changed elsewhere. Reopen the panel.");
|
|
626
|
+
const channels = request.channels.map((channel) => ({
|
|
627
|
+
...channel,
|
|
628
|
+
baseUrl: normalize(channel.baseUrl),
|
|
629
|
+
models: [...new Set(channel.models)],
|
|
630
|
+
apiKey: resolveKey(channel, previous)
|
|
631
|
+
}));
|
|
632
|
+
const byId = new Map(channels.map((channel) => [channel.id, channel]));
|
|
633
|
+
const routeKeys = request.routes.map((ref) => JSON.stringify([ref.channelId, ref.model]));
|
|
634
|
+
if (byId.size !== channels.length || new Set(routeKeys).size !== routeKeys.length || request.routes.some((ref) => !byId.get(ref.channelId)?.models.includes(ref.model))) throw new Error("模型顺序包含重复项或已移除的模型 / The model order contains duplicate or removed models.");
|
|
635
|
+
const stored = {
|
|
636
|
+
version: 2,
|
|
637
|
+
revision: randomUUID(),
|
|
638
|
+
channels,
|
|
639
|
+
routes: request.routes
|
|
640
|
+
};
|
|
641
|
+
const target = filePath(options);
|
|
642
|
+
const temp = target + "." + randomUUID() + ".tmp";
|
|
643
|
+
await mkdir(path.dirname(target), {
|
|
644
|
+
recursive: true,
|
|
645
|
+
mode: 448
|
|
646
|
+
});
|
|
647
|
+
try {
|
|
648
|
+
await writeFile(temp, JSON.stringify(stored), {
|
|
649
|
+
mode: 384,
|
|
650
|
+
flag: "wx"
|
|
651
|
+
});
|
|
652
|
+
await rename(temp, target);
|
|
653
|
+
} finally {
|
|
654
|
+
await rm(temp, { force: true });
|
|
655
|
+
}
|
|
656
|
+
return getImageChannels(options);
|
|
657
|
+
});
|
|
658
|
+
pendingSave = save.catch(() => void 0);
|
|
659
|
+
return save;
|
|
660
|
+
}
|
|
661
|
+
async function discoverImageModels(connection, options = {}, signal) {
|
|
662
|
+
return discoverCatalog(normalize(connection.baseUrl), resolveKey(connection, await readStored(options)), signal);
|
|
663
|
+
}
|
|
664
|
+
// src/host/doctor.ts
|
|
665
|
+
const execFileAsync$1 = promisify(execFile);
|
|
666
|
+
const REQUIRED_SCRIPTS = [
|
|
667
|
+
"html_to_pptx.py",
|
|
668
|
+
"deck_shell.py",
|
|
669
|
+
"measure_slide_layout.py",
|
|
670
|
+
"prepare_plate.py",
|
|
671
|
+
"verify_deck.py"
|
|
672
|
+
];
|
|
673
|
+
const PYTHON_PROBE_SCRIPT = `
|
|
674
|
+
import json, sys, os
|
|
675
|
+
out = {
|
|
676
|
+
"version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
|
677
|
+
"major": sys.version_info.major,
|
|
678
|
+
"minor": sys.version_info.minor,
|
|
679
|
+
"pillow": False,
|
|
680
|
+
"requests": False,
|
|
681
|
+
"pptx": False,
|
|
682
|
+
"playwright": False,
|
|
683
|
+
"chromiumPath": None,
|
|
684
|
+
}
|
|
685
|
+
try:
|
|
686
|
+
import PIL
|
|
687
|
+
out["pillow"] = True
|
|
688
|
+
except Exception:
|
|
689
|
+
pass
|
|
690
|
+
try:
|
|
691
|
+
import requests
|
|
692
|
+
out["requests"] = True
|
|
693
|
+
except Exception:
|
|
694
|
+
pass
|
|
695
|
+
try:
|
|
696
|
+
import pptx
|
|
697
|
+
out["pptx"] = True
|
|
698
|
+
except Exception:
|
|
699
|
+
pass
|
|
700
|
+
try:
|
|
701
|
+
import playwright
|
|
702
|
+
out["playwright"] = True
|
|
703
|
+
from playwright.sync_api import sync_playwright
|
|
704
|
+
try:
|
|
705
|
+
with sync_playwright() as p:
|
|
706
|
+
exe = p.chromium.executable_path
|
|
707
|
+
if exe and os.path.exists(exe):
|
|
708
|
+
out["chromiumPath"] = exe
|
|
709
|
+
except Exception:
|
|
710
|
+
pass
|
|
711
|
+
except Exception:
|
|
712
|
+
pass
|
|
713
|
+
print(json.dumps(out))
|
|
714
|
+
`.trim();
|
|
715
|
+
function candidatePythonBins(assets) {
|
|
716
|
+
const list = [];
|
|
717
|
+
const envPy = (process.env.OIL_SLIDE_PYTHON || process.env.OIL_PPT_PYTHON)?.trim();
|
|
718
|
+
if (envPy !== void 0 && envPy !== "") list.push(envPy);
|
|
719
|
+
if (assets.repoRoot !== null) {
|
|
720
|
+
const venvPy = join(assets.repoRoot, ".venv", "bin", "python");
|
|
721
|
+
if (existsSync(venvPy)) list.push(venvPy);
|
|
722
|
+
}
|
|
723
|
+
list.push("python3", "python");
|
|
724
|
+
return [...new Set(list)];
|
|
725
|
+
}
|
|
726
|
+
async function probePython(bin, signal) {
|
|
727
|
+
try {
|
|
728
|
+
const { stdout } = await execFileAsync$1(bin, ["-c", PYTHON_PROBE_SCRIPT], {
|
|
729
|
+
timeout: 8e3,
|
|
730
|
+
signal
|
|
731
|
+
});
|
|
732
|
+
const parsed = JSON.parse(stdout.trim());
|
|
733
|
+
if (typeof parsed.version === "string") return parsed;
|
|
734
|
+
return null;
|
|
735
|
+
} catch {
|
|
736
|
+
return null;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
let cachedBestPython = null;
|
|
740
|
+
let cachedFastPython = null;
|
|
741
|
+
function pythonCacheKey(assets) {
|
|
742
|
+
return `${assets.repoRoot ?? ""}|${process.env.OIL_SLIDE_PYTHON ?? ""}|${process.env.OIL_PPT_PYTHON ?? ""}`;
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Lightweight Python 3.10+ lookup for stdlib-only scripts (e.g. deck_shell.py)
|
|
746
|
+
* without importing Playwright or launching Chromium drivers.
|
|
747
|
+
*/
|
|
748
|
+
async function resolvePythonBinFast(assets, signal) {
|
|
749
|
+
const key = pythonCacheKey(assets);
|
|
750
|
+
const now = Date.now();
|
|
751
|
+
if (cachedFastPython !== null && cachedFastPython.key === key && cachedFastPython.expiresAt > now) return cachedFastPython.bin;
|
|
752
|
+
if (cachedBestPython !== null && cachedBestPython.key === key && cachedBestPython.expiresAt > now) return cachedBestPython.value?.bin ?? null;
|
|
753
|
+
for (const bin of candidatePythonBins(assets)) try {
|
|
754
|
+
const { stdout } = await execFileAsync$1(bin, ["-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"], {
|
|
755
|
+
timeout: 3e3,
|
|
756
|
+
signal
|
|
757
|
+
});
|
|
758
|
+
const [maj, min] = stdout.trim().split(".").map((s) => Number.parseInt(s, 10));
|
|
759
|
+
if (Number.isFinite(maj) && Number.isFinite(min) && (maj > 3 || maj === 3 && min >= 10)) {
|
|
760
|
+
cachedFastPython = {
|
|
761
|
+
key,
|
|
762
|
+
bin,
|
|
763
|
+
expiresAt: now + 6e4
|
|
764
|
+
};
|
|
765
|
+
return bin;
|
|
766
|
+
}
|
|
767
|
+
} catch {}
|
|
768
|
+
cachedFastPython = {
|
|
769
|
+
key,
|
|
770
|
+
bin: null,
|
|
771
|
+
expiresAt: now + 15e3
|
|
772
|
+
};
|
|
773
|
+
return null;
|
|
774
|
+
}
|
|
775
|
+
async function resolveBestPython(assets, signal, options) {
|
|
776
|
+
const key = pythonCacheKey(assets);
|
|
777
|
+
const now = Date.now();
|
|
778
|
+
if (!options?.forceRefresh && cachedBestPython !== null && cachedBestPython.key === key && cachedBestPython.expiresAt > now) return cachedBestPython.value;
|
|
779
|
+
let fallback = null;
|
|
780
|
+
for (const bin of candidatePythonBins(assets)) {
|
|
781
|
+
const probe = await probePython(bin, signal);
|
|
782
|
+
if (probe === null) continue;
|
|
783
|
+
if ((probe.major > 3 || probe.major === 3 && probe.minor >= 10) && probe.pillow && probe.requests && probe.pptx && probe.playwright) {
|
|
784
|
+
const result = {
|
|
785
|
+
bin,
|
|
786
|
+
probe
|
|
787
|
+
};
|
|
788
|
+
cachedBestPython = {
|
|
789
|
+
key,
|
|
790
|
+
value: result,
|
|
791
|
+
expiresAt: now + 6e4
|
|
792
|
+
};
|
|
793
|
+
return result;
|
|
794
|
+
}
|
|
795
|
+
if (fallback === null) fallback = {
|
|
796
|
+
bin,
|
|
797
|
+
probe
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
cachedBestPython = {
|
|
801
|
+
key,
|
|
802
|
+
value: fallback,
|
|
803
|
+
expiresAt: now + 3e4
|
|
804
|
+
};
|
|
805
|
+
return fallback;
|
|
806
|
+
}
|
|
807
|
+
async function runEnvironmentDoctor(options) {
|
|
808
|
+
const { assets, ctx, signal, env, platform, homeDir } = options;
|
|
809
|
+
const checks = [];
|
|
810
|
+
const missingScripts = REQUIRED_SCRIPTS.filter((name) => !existsSync(join(assets.scriptsDir, name)));
|
|
811
|
+
checks.push(missingScripts.length === 0 ? {
|
|
812
|
+
id: "scripts",
|
|
813
|
+
label: "oil-slide 脚本",
|
|
814
|
+
status: "ok",
|
|
815
|
+
detail: `已就绪(${assets.mode} 模式,${REQUIRED_SCRIPTS.length} 个核心脚本)`
|
|
816
|
+
} : {
|
|
817
|
+
id: "scripts",
|
|
818
|
+
label: "oil-slide 脚本",
|
|
819
|
+
status: "missing",
|
|
820
|
+
detail: `缺少脚本: ${missingScripts.join(", ")}`,
|
|
821
|
+
fixHint: "请检查 oil-slide/scripts/ 或重新执行 pnpm sync:assets"
|
|
822
|
+
});
|
|
823
|
+
const py = await resolveBestPython(assets, signal, { forceRefresh: true });
|
|
824
|
+
if (py === null) {
|
|
825
|
+
checks.push({
|
|
826
|
+
id: "python",
|
|
827
|
+
label: "Python 3.10+",
|
|
828
|
+
status: "missing",
|
|
829
|
+
detail: "未检测到可用 Python 3.10+ 运行时",
|
|
830
|
+
fixHint: "安装 Python 3.10+ 或设置环境变量 OIL_PPT_PYTHON"
|
|
831
|
+
});
|
|
832
|
+
checks.push({
|
|
833
|
+
id: "python-deps",
|
|
834
|
+
label: "Pillow / python-pptx / Playwright",
|
|
835
|
+
status: "missing",
|
|
836
|
+
detail: "因缺少 Python 运行时跳过依赖检查",
|
|
837
|
+
fixHint: "pip install pillow requests python-pptx playwright && playwright install chromium"
|
|
838
|
+
});
|
|
839
|
+
} else {
|
|
840
|
+
const pyOk = py.probe.major > 3 || py.probe.major === 3 && py.probe.minor >= 10;
|
|
841
|
+
checks.push({
|
|
842
|
+
id: "python",
|
|
843
|
+
label: "Python 3.10+",
|
|
844
|
+
status: pyOk ? "ok" : "warn",
|
|
845
|
+
detail: `Python ${py.probe.version} (${py.bin})`,
|
|
846
|
+
...pyOk ? {} : { fixHint: "建议升级至 Python 3.10+" }
|
|
847
|
+
});
|
|
848
|
+
const missingLibs = [];
|
|
849
|
+
if (!py.probe.pillow) missingLibs.push("Pillow");
|
|
850
|
+
if (!py.probe.requests) missingLibs.push("requests");
|
|
851
|
+
if (!py.probe.pptx) missingLibs.push("python-pptx");
|
|
852
|
+
if (!py.probe.playwright) missingLibs.push("playwright");
|
|
853
|
+
if (missingLibs.length > 0) checks.push({
|
|
854
|
+
id: "python-deps",
|
|
855
|
+
label: "渲染与 PPTX 依赖",
|
|
856
|
+
status: "missing",
|
|
857
|
+
detail: `缺少: ${missingLibs.join(", ")}`,
|
|
858
|
+
fixHint: `${py.bin} -m pip install pillow requests python-pptx playwright && ${py.bin} -m playwright install chromium`
|
|
859
|
+
});
|
|
860
|
+
else if (py.probe.chromiumPath === null) checks.push({
|
|
861
|
+
id: "python-deps",
|
|
862
|
+
label: "渲染与 PPTX 依赖",
|
|
863
|
+
status: "warn",
|
|
864
|
+
detail: "Pillow / python-pptx / playwright 已安装,但未找到 Chromium 浏览器",
|
|
865
|
+
fixHint: `${py.bin} -m playwright install chromium`
|
|
866
|
+
});
|
|
867
|
+
else checks.push({
|
|
868
|
+
id: "python-deps",
|
|
869
|
+
label: "渲染与 PPTX 依赖",
|
|
870
|
+
status: "ok",
|
|
871
|
+
detail: "Pillow、python-pptx、Playwright & Chromium 均已就绪"
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
const settings = await getImageChannels({
|
|
875
|
+
env,
|
|
876
|
+
platform,
|
|
877
|
+
homeDir
|
|
878
|
+
}).catch(() => null);
|
|
879
|
+
const model = settings?.routes[0]?.model ?? settings?.environmentModel;
|
|
880
|
+
checks.push({
|
|
881
|
+
id: "image-channel",
|
|
882
|
+
label: "自定义生图渠道",
|
|
883
|
+
status: model ? "ok" : "warn",
|
|
884
|
+
detail: model ? `已配置默认模型 ${model}` : "尚未配置可用的生图渠道",
|
|
885
|
+
...!model && { fixHint: "打开 Oil Slide → 生图设置,填写 Base URL 和模型名。" }
|
|
886
|
+
});
|
|
887
|
+
return {
|
|
888
|
+
ok: checks.every((c) => c.status !== "missing"),
|
|
889
|
+
pythonBin: py?.bin ?? null,
|
|
890
|
+
skillDir: assets.skillDir,
|
|
891
|
+
checks
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
// src/host/imageOptimizer.ts
|
|
895
|
+
const CACHE_DIR = join(tmpdir(), "dsh-oil-slide-img-cache-v1");
|
|
896
|
+
const MAX_MEM_ENTRIES = 128;
|
|
897
|
+
const MIN_CONVERT_BYTES = 36864;
|
|
898
|
+
const CONVERTIBLE_EXTS = /* @__PURE__ */ new Set([
|
|
899
|
+
".png",
|
|
900
|
+
".jpg",
|
|
901
|
+
".jpeg",
|
|
902
|
+
".webp"
|
|
903
|
+
]);
|
|
904
|
+
const memCache = /* @__PURE__ */ new Map();
|
|
905
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
906
|
+
let pillowAvailable = null;
|
|
907
|
+
function clampQuality(q) {
|
|
908
|
+
if (q === void 0 || !Number.isFinite(q)) return 85;
|
|
909
|
+
return Math.max(40, Math.min(96, Math.round(q)));
|
|
910
|
+
}
|
|
911
|
+
function clampMaxWidth(w) {
|
|
912
|
+
if (w === void 0 || !Number.isFinite(w) || w <= 0) return 0;
|
|
913
|
+
return Math.max(64, Math.min(4096, Math.round(w)));
|
|
914
|
+
}
|
|
915
|
+
function buildOptimizeKey(spec) {
|
|
916
|
+
const maxW = clampMaxWidth(spec.maxWidth);
|
|
917
|
+
const quality = clampQuality(spec.quality);
|
|
918
|
+
return createHash("sha1").update(`${spec.realPath}|${spec.mtimeMs}|${spec.size}|${maxW}|${quality}`).digest("hex");
|
|
919
|
+
}
|
|
920
|
+
function getMemCache(key) {
|
|
921
|
+
const hit = memCache.get(key);
|
|
922
|
+
if (hit !== void 0) {
|
|
923
|
+
memCache.delete(key);
|
|
924
|
+
memCache.set(key, hit);
|
|
925
|
+
}
|
|
926
|
+
return hit;
|
|
927
|
+
}
|
|
928
|
+
function setMemCache(key, value) {
|
|
929
|
+
memCache.delete(key);
|
|
930
|
+
memCache.set(key, value);
|
|
931
|
+
while (memCache.size > MAX_MEM_ENTRIES) {
|
|
932
|
+
const oldest = memCache.keys().next().value;
|
|
933
|
+
if (oldest === void 0) break;
|
|
934
|
+
memCache.delete(oldest);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
function shouldAttemptOptimize(spec) {
|
|
938
|
+
const ext = extname(spec.realPath).toLowerCase();
|
|
939
|
+
if (!CONVERTIBLE_EXTS.has(ext)) return false;
|
|
940
|
+
if (clampMaxWidth(spec.maxWidth) > 0) return true;
|
|
941
|
+
if (ext === ".webp") return false;
|
|
942
|
+
return spec.size >= MIN_CONVERT_BYTES;
|
|
943
|
+
}
|
|
944
|
+
const PY_BATCH_WEBP_SCRIPT = `
|
|
945
|
+
import io, json, os, sys
|
|
946
|
+
try:
|
|
947
|
+
from PIL import Image
|
|
948
|
+
except Exception:
|
|
949
|
+
print(json.dumps({"pillow": False, "ok": []}))
|
|
950
|
+
sys.exit(0)
|
|
951
|
+
|
|
952
|
+
payload = json.loads(sys.stdin.read() or "{}")
|
|
953
|
+
jobs = payload.get("jobs") or []
|
|
954
|
+
ok = []
|
|
955
|
+
for job in jobs:
|
|
956
|
+
src = job.get("src")
|
|
957
|
+
dst = job.get("dst")
|
|
958
|
+
max_w = int(job.get("maxWidth") or 0)
|
|
959
|
+
quality = int(job.get("quality") or 85)
|
|
960
|
+
orig_size = int(job.get("origSize") or 0)
|
|
961
|
+
if not src or not dst:
|
|
962
|
+
continue
|
|
963
|
+
try:
|
|
964
|
+
with Image.open(src) as im:
|
|
965
|
+
resized = False
|
|
966
|
+
if max_w > 0 and im.width > max_w:
|
|
967
|
+
new_h = max(1, round(im.height * max_w / im.width))
|
|
968
|
+
im = im.resize((max_w, new_h), Image.Resampling.LANCZOS)
|
|
969
|
+
resized = True
|
|
970
|
+
if im.mode in ("P", "LA"):
|
|
971
|
+
im = im.convert("RGBA")
|
|
972
|
+
elif im.mode not in ("RGB", "RGBA"):
|
|
973
|
+
im = im.convert("RGB")
|
|
974
|
+
buf = io.BytesIO()
|
|
975
|
+
im.save(buf, format="WEBP", quality=quality, method=4)
|
|
976
|
+
data = buf.getvalue()
|
|
977
|
+
if orig_size > 0 and len(data) >= orig_size:
|
|
978
|
+
continue
|
|
979
|
+
tmp = f"{dst}.{os.getpid()}.tmp"
|
|
980
|
+
with open(tmp, "wb") as fh:
|
|
981
|
+
fh.write(data)
|
|
982
|
+
os.replace(tmp, dst)
|
|
983
|
+
ok.append(job.get("key"))
|
|
984
|
+
except Exception:
|
|
985
|
+
continue
|
|
986
|
+
|
|
987
|
+
print(json.dumps({"pillow": True, "ok": ok}))
|
|
988
|
+
`.trim();
|
|
989
|
+
async function runPythonBatchWebp(pythonBin, jobs, signal) {
|
|
990
|
+
return new Promise((resolve) => {
|
|
991
|
+
let settled = false;
|
|
992
|
+
const finish = (val) => {
|
|
993
|
+
if (settled) return;
|
|
994
|
+
settled = true;
|
|
995
|
+
resolve(val);
|
|
996
|
+
};
|
|
997
|
+
const child = spawn(pythonBin, ["-c", PY_BATCH_WEBP_SCRIPT], {
|
|
998
|
+
stdio: [
|
|
999
|
+
"pipe",
|
|
1000
|
+
"pipe",
|
|
1001
|
+
"ignore"
|
|
1002
|
+
],
|
|
1003
|
+
signal
|
|
1004
|
+
});
|
|
1005
|
+
const timer = setTimeout(() => {
|
|
1006
|
+
child.kill("SIGKILL");
|
|
1007
|
+
finish({
|
|
1008
|
+
pillow: true,
|
|
1009
|
+
okKeys: /* @__PURE__ */ new Set()
|
|
1010
|
+
});
|
|
1011
|
+
}, 15e3);
|
|
1012
|
+
let out = "";
|
|
1013
|
+
child.stdout?.setEncoding("utf8");
|
|
1014
|
+
child.stdout?.on("data", (chunk) => {
|
|
1015
|
+
out += chunk;
|
|
1016
|
+
});
|
|
1017
|
+
child.on("error", () => {
|
|
1018
|
+
clearTimeout(timer);
|
|
1019
|
+
finish({
|
|
1020
|
+
pillow: true,
|
|
1021
|
+
okKeys: /* @__PURE__ */ new Set()
|
|
1022
|
+
});
|
|
1023
|
+
});
|
|
1024
|
+
child.on("close", () => {
|
|
1025
|
+
clearTimeout(timer);
|
|
1026
|
+
try {
|
|
1027
|
+
const parsed = JSON.parse(out.trim());
|
|
1028
|
+
finish({
|
|
1029
|
+
pillow: parsed.pillow !== false,
|
|
1030
|
+
okKeys: new Set(Array.isArray(parsed.ok) ? parsed.ok : [])
|
|
1031
|
+
});
|
|
1032
|
+
} catch {
|
|
1033
|
+
finish({
|
|
1034
|
+
pillow: true,
|
|
1035
|
+
okKeys: /* @__PURE__ */ new Set()
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
});
|
|
1039
|
+
child.stdin?.end(JSON.stringify({ jobs }));
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Batch-optimize workspace images to WebP (with persistent disk + in-memory LRU cache).
|
|
1044
|
+
* Returns a Map from `buildOptimizeKey(spec)` to `{ mime: "image/webp", bytes }`.
|
|
1045
|
+
* Missing keys simply fall back to reading the original file unchanged.
|
|
1046
|
+
*/
|
|
1047
|
+
async function optimizeImagesBatch(specs, assets, signal) {
|
|
1048
|
+
const results = /* @__PURE__ */ new Map();
|
|
1049
|
+
if (specs.length === 0 || pillowAvailable === false) return results;
|
|
1050
|
+
const uniqueSpecs = /* @__PURE__ */ new Map();
|
|
1051
|
+
for (const spec of specs) {
|
|
1052
|
+
if (!shouldAttemptOptimize(spec)) continue;
|
|
1053
|
+
const key = buildOptimizeKey(spec);
|
|
1054
|
+
if (!uniqueSpecs.has(key)) uniqueSpecs.set(key, spec);
|
|
1055
|
+
}
|
|
1056
|
+
if (uniqueSpecs.size === 0) return results;
|
|
1057
|
+
const missing = [];
|
|
1058
|
+
const awaitedPromises = [];
|
|
1059
|
+
for (const [key, spec] of uniqueSpecs) {
|
|
1060
|
+
const memHit = getMemCache(key);
|
|
1061
|
+
if (memHit !== void 0) {
|
|
1062
|
+
results.set(key, memHit);
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
const existingFlight = inFlight.get(key);
|
|
1066
|
+
if (existingFlight !== void 0) {
|
|
1067
|
+
awaitedPromises.push(existingFlight.then((res) => {
|
|
1068
|
+
if (res !== null) results.set(key, res);
|
|
1069
|
+
}));
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
const dst = join(CACHE_DIR, `${key}.webp`);
|
|
1073
|
+
const diskStat = await stat(dst).catch(() => null);
|
|
1074
|
+
if (diskStat !== null && diskStat.isFile() && diskStat.size > 0) {
|
|
1075
|
+
const bytes = await readFile(dst).catch(() => null);
|
|
1076
|
+
if (bytes !== null && bytes.length > 0) {
|
|
1077
|
+
const entry = {
|
|
1078
|
+
mime: "image/webp",
|
|
1079
|
+
bytes
|
|
1080
|
+
};
|
|
1081
|
+
setMemCache(key, entry);
|
|
1082
|
+
results.set(key, entry);
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
missing.push({
|
|
1087
|
+
key,
|
|
1088
|
+
spec,
|
|
1089
|
+
dst
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
if (missing.length > 0 && assets !== void 0) {
|
|
1093
|
+
const pythonBin = await resolvePythonBinFast(assets, signal);
|
|
1094
|
+
if (pythonBin !== null) {
|
|
1095
|
+
await mkdir(CACHE_DIR, { recursive: true }).catch(() => {});
|
|
1096
|
+
const batchPromise = (async () => {
|
|
1097
|
+
const { pillow, okKeys } = await runPythonBatchWebp(pythonBin, missing.map((m) => ({
|
|
1098
|
+
key: m.key,
|
|
1099
|
+
src: m.spec.realPath,
|
|
1100
|
+
dst: m.dst,
|
|
1101
|
+
maxWidth: clampMaxWidth(m.spec.maxWidth),
|
|
1102
|
+
quality: clampQuality(m.spec.quality),
|
|
1103
|
+
origSize: m.spec.size
|
|
1104
|
+
})), signal);
|
|
1105
|
+
if (!pillow) pillowAvailable = false;
|
|
1106
|
+
else pillowAvailable = true;
|
|
1107
|
+
const batchOut = /* @__PURE__ */ new Map();
|
|
1108
|
+
await Promise.all(missing.map(async (m) => {
|
|
1109
|
+
if (!okKeys.has(m.key)) return;
|
|
1110
|
+
const bytes = await readFile(m.dst).catch(() => null);
|
|
1111
|
+
if (bytes !== null && bytes.length > 0) {
|
|
1112
|
+
const entry = {
|
|
1113
|
+
mime: "image/webp",
|
|
1114
|
+
bytes
|
|
1115
|
+
};
|
|
1116
|
+
setMemCache(m.key, entry);
|
|
1117
|
+
batchOut.set(m.key, entry);
|
|
1118
|
+
}
|
|
1119
|
+
}));
|
|
1120
|
+
return batchOut;
|
|
1121
|
+
})();
|
|
1122
|
+
for (const m of missing) {
|
|
1123
|
+
const itemPromise = batchPromise.then((map) => map.get(m.key) ?? null).catch(() => null).finally(() => {
|
|
1124
|
+
inFlight.delete(m.key);
|
|
1125
|
+
});
|
|
1126
|
+
inFlight.set(m.key, itemPromise);
|
|
1127
|
+
}
|
|
1128
|
+
const produced = await batchPromise.catch(() => /* @__PURE__ */ new Map());
|
|
1129
|
+
for (const [key, val] of produced) results.set(key, val);
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
if (awaitedPromises.length > 0) await Promise.all(awaitedPromises);
|
|
1133
|
+
return results;
|
|
1134
|
+
}
|
|
1135
|
+
async function optimizeSingleImage(spec, assets, signal) {
|
|
1136
|
+
const key = buildOptimizeKey(spec);
|
|
1137
|
+
return (await optimizeImagesBatch([spec], assets, signal)).get(key) ?? null;
|
|
1138
|
+
}
|
|
1139
|
+
// src/host/decks.ts
|
|
1140
|
+
const IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
1141
|
+
".git",
|
|
1142
|
+
".next",
|
|
1143
|
+
".venv",
|
|
1144
|
+
".cache",
|
|
1145
|
+
".oil-ppt",
|
|
1146
|
+
"node_modules",
|
|
1147
|
+
"__pycache__",
|
|
1148
|
+
"oil-slide",
|
|
1149
|
+
"dsh-plugin",
|
|
1150
|
+
"bundled-assets",
|
|
1151
|
+
"landing",
|
|
1152
|
+
"research",
|
|
1153
|
+
"evals",
|
|
1154
|
+
"tests",
|
|
1155
|
+
"docs",
|
|
1156
|
+
"scripts"
|
|
1157
|
+
]);
|
|
1158
|
+
const IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1159
|
+
".png",
|
|
1160
|
+
".webp",
|
|
1161
|
+
".jpg",
|
|
1162
|
+
".jpeg",
|
|
1163
|
+
".svg",
|
|
1164
|
+
".gif"
|
|
1165
|
+
]);
|
|
1166
|
+
const MIME_BY_EXT = {
|
|
1167
|
+
".png": "image/png",
|
|
1168
|
+
".webp": "image/webp",
|
|
1169
|
+
".jpg": "image/jpeg",
|
|
1170
|
+
".jpeg": "image/jpeg",
|
|
1171
|
+
".svg": "image/svg+xml",
|
|
1172
|
+
".gif": "image/gif"
|
|
1173
|
+
};
|
|
1174
|
+
const MAX_IMAGE_BYTES = 15728640;
|
|
1175
|
+
const MAX_SCAN_DEPTH = 3;
|
|
1176
|
+
function toPosix$1(p) {
|
|
1177
|
+
return p.split(sep).join("/");
|
|
1178
|
+
}
|
|
1179
|
+
function assertAbsoluteWorkspace(workspaceRoot) {
|
|
1180
|
+
const trimmed = workspaceRoot.trim();
|
|
1181
|
+
if (trimmed === "" || !isAbsolute(trimmed)) throw new Error(`Invalid workspaceRoot (must be an absolute path): "${workspaceRoot}"`);
|
|
1182
|
+
if (trimmed.includes("\0")) throw new Error("Invalid workspaceRoot containing NUL byte");
|
|
1183
|
+
return resolve(trimmed);
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Resolve a workspace-relative path and guarantee containment inside `workspaceRoot`,
|
|
1187
|
+
* defending against `..` traversal and symlink escapes.
|
|
1188
|
+
*/
|
|
1189
|
+
async function resolveConfinedWorkspacePath(workspaceRoot, relPath) {
|
|
1190
|
+
const normalizedRoot = assertAbsoluteWorkspace(workspaceRoot);
|
|
1191
|
+
const cleaned = relPath.replace(/\\/g, "/").trim();
|
|
1192
|
+
if (cleaned === "" || cleaned.includes("\0") || cleaned.startsWith("/")) throw new Error(`Invalid workspace-relative path: "${relPath}"`);
|
|
1193
|
+
const realRoot = await realpath(normalizedRoot);
|
|
1194
|
+
const candidate = resolve(realRoot, cleaned);
|
|
1195
|
+
if (candidate !== realRoot && !candidate.startsWith(`${realRoot}${sep}`)) throw new Error(`Path escapes workspace: "${relPath}"`);
|
|
1196
|
+
const isInside = (target) => target === realRoot || target.startsWith(`${realRoot}${sep}`);
|
|
1197
|
+
const assertNearestExistingAncestorInside = async (target) => {
|
|
1198
|
+
let cur = dirname(target);
|
|
1199
|
+
while (true) {
|
|
1200
|
+
if (existsSync(cur)) {
|
|
1201
|
+
const realAnc = await realpath(cur);
|
|
1202
|
+
if (!isInside(realAnc)) throw new Error(`Symlink escapes workspace: "${relPath}"`);
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
const parent = dirname(cur);
|
|
1206
|
+
if (parent === cur) return;
|
|
1207
|
+
cur = parent;
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
if (existsSync(candidate)) {
|
|
1211
|
+
const realTarget = await realpath(candidate);
|
|
1212
|
+
if (!isInside(realTarget)) throw new Error(`Symlink escapes workspace: "${relPath}"`);
|
|
1213
|
+
return realTarget;
|
|
1214
|
+
}
|
|
1215
|
+
let current = candidate;
|
|
1216
|
+
for (let hop = 0; hop < 16; hop += 1) {
|
|
1217
|
+
let lst;
|
|
1218
|
+
try {
|
|
1219
|
+
lst = await lstat(current);
|
|
1220
|
+
} catch (err) {
|
|
1221
|
+
if (err?.code === "ENOENT") {
|
|
1222
|
+
await assertNearestExistingAncestorInside(current);
|
|
1223
|
+
return current;
|
|
1224
|
+
}
|
|
1225
|
+
throw err;
|
|
1226
|
+
}
|
|
1227
|
+
if (!lst.isSymbolicLink()) {
|
|
1228
|
+
const realTarget = await realpath(current);
|
|
1229
|
+
if (!isInside(realTarget)) throw new Error(`Symlink escapes workspace: "${relPath}"`);
|
|
1230
|
+
return realTarget;
|
|
1231
|
+
}
|
|
1232
|
+
const linkTarget = await readlink(current);
|
|
1233
|
+
const resolvedLink = resolve(dirname(current), linkTarget);
|
|
1234
|
+
if (!isInside(resolvedLink)) throw new Error(`Symlink escapes workspace: "${relPath}"`);
|
|
1235
|
+
await assertNearestExistingAncestorInside(resolvedLink);
|
|
1236
|
+
current = resolvedLink;
|
|
1237
|
+
}
|
|
1238
|
+
throw new Error(`Symlink loop or excessive indirection: "${relPath}"`);
|
|
1239
|
+
}
|
|
1240
|
+
function parseSlideNumber(filename) {
|
|
1241
|
+
const match = filename.match(/(?:^|[_-])(?:s|slide)[_-]?0*(\d+)/i);
|
|
1242
|
+
if (match?.[1] !== void 0) {
|
|
1243
|
+
const parsed = Number.parseInt(match[1], 10);
|
|
1244
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1245
|
+
}
|
|
1246
|
+
const leading = filename.match(/^0*(\d+)[_.-]/);
|
|
1247
|
+
if (leading?.[1] !== void 0) {
|
|
1248
|
+
const parsed = Number.parseInt(leading[1], 10);
|
|
1249
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1250
|
+
}
|
|
1251
|
+
return null;
|
|
1252
|
+
}
|
|
1253
|
+
function isOverviewFilename(filename) {
|
|
1254
|
+
const lower = filename.toLowerCase();
|
|
1255
|
+
return lower.includes("2x2") || lower.includes("overview") || lower.includes("contact-sheet") || lower.includes("grid");
|
|
1256
|
+
}
|
|
1257
|
+
function isIgnoredAuxImage(filename) {
|
|
1258
|
+
const lower = filename.toLowerCase();
|
|
1259
|
+
return lower.includes("style-swatch") || lower.includes("bg-plate") || lower.includes("brand-ref") || lower === "s1-ref.jpg" || lower.endsWith("-ref.jpg") || lower.endsWith("-ref.png");
|
|
1260
|
+
}
|
|
1261
|
+
function isIgnoredSlideRelPath(relPath) {
|
|
1262
|
+
const normalized = relPath.replace(/\\/g, "/").toLowerCase();
|
|
1263
|
+
return /(?:^|\/)assets\/media\/(?:research|derived)(?:\/|$)/.test(normalized);
|
|
1264
|
+
}
|
|
1265
|
+
function labelForSlide(filename, slideNumber, kind) {
|
|
1266
|
+
if (kind === "overview") return "2×2 总览";
|
|
1267
|
+
if (kind === "verify" || kind === "explore") return filename.replace(/\.[^.]+$/, "");
|
|
1268
|
+
if (slideNumber !== null) return `第 ${slideNumber} 页`;
|
|
1269
|
+
return filename.replace(/\.[^.]+$/, "");
|
|
1270
|
+
}
|
|
1271
|
+
async function listImagesInDir(workspaceRoot, dirPath, forceKind) {
|
|
1272
|
+
if (!existsSync(dirPath)) return [];
|
|
1273
|
+
const entries = await readdir(dirPath, { withFileTypes: true }).catch(() => []);
|
|
1274
|
+
const items = [];
|
|
1275
|
+
for (const entry of entries) {
|
|
1276
|
+
if (!entry.isFile()) continue;
|
|
1277
|
+
const ext = extname(entry.name).toLowerCase();
|
|
1278
|
+
if (!IMAGE_EXTENSIONS.has(ext) || ext === ".svg") continue;
|
|
1279
|
+
if (forceKind !== "verify" && isIgnoredAuxImage(entry.name)) continue;
|
|
1280
|
+
const abs = join(dirPath, entry.name);
|
|
1281
|
+
const relPath = toPosix$1(relative(workspaceRoot, abs));
|
|
1282
|
+
if (isIgnoredSlideRelPath(relPath)) continue;
|
|
1283
|
+
const info = await stat(abs).catch(() => null);
|
|
1284
|
+
if (info === null) continue;
|
|
1285
|
+
const kind = forceKind === "verify" ? "verify" : forceKind === "explore" ? "explore" : isOverviewFilename(entry.name) ? "overview" : "slide";
|
|
1286
|
+
const slideNumber = kind === "slide" ? parseSlideNumber(entry.name) : null;
|
|
1287
|
+
items.push({
|
|
1288
|
+
name: entry.name,
|
|
1289
|
+
relPath,
|
|
1290
|
+
label: labelForSlide(entry.name, slideNumber, kind),
|
|
1291
|
+
slideNumber,
|
|
1292
|
+
kind,
|
|
1293
|
+
sizeBytes: info.size,
|
|
1294
|
+
mtimeMs: info.mtimeMs
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
items.sort((a, b) => {
|
|
1298
|
+
if (a.slideNumber !== null && b.slideNumber !== null && a.slideNumber !== b.slideNumber) return a.slideNumber - b.slideNumber;
|
|
1299
|
+
if (a.slideNumber !== null && b.slideNumber === null) return -1;
|
|
1300
|
+
if (a.slideNumber === null && b.slideNumber !== null) return 1;
|
|
1301
|
+
return a.name.localeCompare(b.name, void 0, { numeric: true });
|
|
1302
|
+
});
|
|
1303
|
+
return items;
|
|
1304
|
+
}
|
|
1305
|
+
async function findPptxInDist(workspaceRoot, deckDir) {
|
|
1306
|
+
const distDir = join(deckDir, "dist");
|
|
1307
|
+
if (!existsSync(distDir)) return null;
|
|
1308
|
+
const entries = await readdir(distDir, { withFileTypes: true }).catch(() => []);
|
|
1309
|
+
const pptxFiles = [];
|
|
1310
|
+
for (const entry of entries) {
|
|
1311
|
+
if (!entry.isFile() || extname(entry.name).toLowerCase() !== ".pptx") continue;
|
|
1312
|
+
if (entry.name.startsWith("~$")) continue;
|
|
1313
|
+
const abs = join(distDir, entry.name);
|
|
1314
|
+
const info = await stat(abs).catch(() => null);
|
|
1315
|
+
if (info === null) continue;
|
|
1316
|
+
pptxFiles.push({
|
|
1317
|
+
relPath: toPosix$1(relative(workspaceRoot, abs)),
|
|
1318
|
+
mtimeMs: info.mtimeMs,
|
|
1319
|
+
preferred: entry.name === "deck.pptx"
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
if (pptxFiles.length === 0) return null;
|
|
1323
|
+
pptxFiles.sort((a, b) => {
|
|
1324
|
+
if (a.mtimeMs !== b.mtimeMs) return b.mtimeMs - a.mtimeMs;
|
|
1325
|
+
if (a.preferred !== b.preferred) return a.preferred ? -1 : 1;
|
|
1326
|
+
return a.relPath.localeCompare(b.relPath);
|
|
1327
|
+
});
|
|
1328
|
+
const top = pptxFiles[0];
|
|
1329
|
+
return top !== void 0 ? {
|
|
1330
|
+
relPath: top.relPath,
|
|
1331
|
+
mtimeMs: top.mtimeMs
|
|
1332
|
+
} : null;
|
|
1333
|
+
}
|
|
1334
|
+
async function inspectWorkflow(workspaceRoot, deckDir) {
|
|
1335
|
+
const rootRel = toPosix$1(relative(workspaceRoot, deckDir));
|
|
1336
|
+
const read = async (path) => {
|
|
1337
|
+
const relPath = rootRel ? `${rootRel}/${path}` : path;
|
|
1338
|
+
const abs = await resolveConfinedWorkspacePath(workspaceRoot, relPath);
|
|
1339
|
+
const info = await stat(abs).catch(() => null);
|
|
1340
|
+
return info?.isFile() ? {
|
|
1341
|
+
abs,
|
|
1342
|
+
relPath,
|
|
1343
|
+
info
|
|
1344
|
+
} : null;
|
|
1345
|
+
};
|
|
1346
|
+
try {
|
|
1347
|
+
const file = await read("slide-workflow.json");
|
|
1348
|
+
if (file === null || file.info.size > 1048576) return null;
|
|
1349
|
+
const parsed = workflowStateOnDiskSchema.safeParse(JSON.parse(await readFile(file.abs, "utf8")));
|
|
1350
|
+
if (!parsed.success) return null;
|
|
1351
|
+
const state = parsed.data;
|
|
1352
|
+
const image = [
|
|
1353
|
+
"image_ready",
|
|
1354
|
+
"converting",
|
|
1355
|
+
"editable_ready"
|
|
1356
|
+
].includes(state.stage) ? await read("dist/deck-images.pptx") : null;
|
|
1357
|
+
const editable = state.stage === "editable_ready" ? await read("dist/deck-editable.pptx") : null;
|
|
1358
|
+
const deckRevision = state.deckRevision ?? 1;
|
|
1359
|
+
const archiveRoot = join(deckDir, "dist", "revisions");
|
|
1360
|
+
const archives = deckRevision > 1 ? await readdir(archiveRoot).catch(() => []) : [];
|
|
1361
|
+
const previousDownloads = [];
|
|
1362
|
+
for (const dir of archives) {
|
|
1363
|
+
if (!/^r[1-9]\d*$/.test(dir)) continue;
|
|
1364
|
+
const revision = Number(dir.slice(1));
|
|
1365
|
+
if (revision >= deckRevision) continue;
|
|
1366
|
+
const image = await read(`dist/revisions/${dir}/deck-images.pptx`);
|
|
1367
|
+
const native = await read(`dist/revisions/${dir}/deck-editable.pptx`);
|
|
1368
|
+
if (image) previousDownloads.push({
|
|
1369
|
+
revision,
|
|
1370
|
+
image: image.relPath,
|
|
1371
|
+
editable: native?.relPath
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
previousDownloads.sort((a, b) => b.revision - a.revision);
|
|
1375
|
+
const editableSlides = editable && state.editablePreview ? await listImagesInDir(workspaceRoot, join(deckDir, "dist", "preview", state.editablePreview)) : [];
|
|
1376
|
+
return {
|
|
1377
|
+
mtimeMs: file.info.mtimeMs,
|
|
1378
|
+
pageNumbers: new Set(Object.keys(state.pages).map(Number)),
|
|
1379
|
+
workflow: {
|
|
1380
|
+
stage: state.stage,
|
|
1381
|
+
ratio: state.ratio,
|
|
1382
|
+
brand: state.brand,
|
|
1383
|
+
regionProposal: state.regionProposal,
|
|
1384
|
+
outline: state.outline,
|
|
1385
|
+
outlineRevision: state.outlineRevision,
|
|
1386
|
+
...state.count !== void 0 ? { candidateCount: state.count } : {},
|
|
1387
|
+
...state.samplePage !== void 0 ? { samplePage: state.samplePage } : {},
|
|
1388
|
+
outlineQuestionId: state.outlineQuestionId,
|
|
1389
|
+
candidates: state.candidates,
|
|
1390
|
+
reviewId: state.reviewId,
|
|
1391
|
+
deckRevision,
|
|
1392
|
+
previousDownloads,
|
|
1393
|
+
editableSlides,
|
|
1394
|
+
...state.approved !== null ? { selected: state.approved.number } : {},
|
|
1395
|
+
produced: Object.keys(state.pages).length,
|
|
1396
|
+
imagePptxRelPath: image?.relPath ?? null,
|
|
1397
|
+
editablePptxRelPath: editable?.relPath ?? null
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
} catch {
|
|
1401
|
+
return null;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
async function inspectDeckDir(workspaceRoot, deckDir) {
|
|
1405
|
+
const refDirs = [join(deckDir, "assets", "reference"), join(deckDir, "reference")];
|
|
1406
|
+
let rawRefImages = [];
|
|
1407
|
+
for (const refDir of refDirs) {
|
|
1408
|
+
const found = await listImagesInDir(workspaceRoot, refDir);
|
|
1409
|
+
if (found.length > 0) {
|
|
1410
|
+
rawRefImages = found;
|
|
1411
|
+
break;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
const exploreSlides = await listImagesInDir(workspaceRoot, join(deckDir, "assets", "explore"), "explore");
|
|
1415
|
+
const htmlAbs = join(deckDir, "web", "index.html");
|
|
1416
|
+
const htmlInfo = existsSync(htmlAbs) ? await stat(htmlAbs).catch(() => null) : null;
|
|
1417
|
+
const workflow = await inspectWorkflow(workspaceRoot, deckDir);
|
|
1418
|
+
const pptx = workflow === null ? await findPptxInDist(workspaceRoot, deckDir) : null;
|
|
1419
|
+
if (rawRefImages.length === 0 && exploreSlides.length === 0 && htmlInfo === null && pptx === null && workflow === null) return null;
|
|
1420
|
+
const overview = rawRefImages.find((img) => img.kind === "overview") ?? null;
|
|
1421
|
+
const slides = rawRefImages.filter((img) => img.kind === "slide" && (!workflow || img.slideNumber !== null && workflow.pageNumbers.has(img.slideNumber)));
|
|
1422
|
+
const verifyImages = await listImagesInDir(workspaceRoot, join(deckDir, "verify"), "verify");
|
|
1423
|
+
const rel = toPosix$1(relative(workspaceRoot, deckDir));
|
|
1424
|
+
const relPath = rel === "" ? "." : rel;
|
|
1425
|
+
const name = relPath === "." ? basename(workspaceRoot) : basename(deckDir);
|
|
1426
|
+
const mtimes = [];
|
|
1427
|
+
for (const img of rawRefImages) mtimes.push(img.mtimeMs);
|
|
1428
|
+
for (const img of exploreSlides) mtimes.push(img.mtimeMs);
|
|
1429
|
+
for (const img of verifyImages) mtimes.push(img.mtimeMs);
|
|
1430
|
+
if (htmlInfo !== null) mtimes.push(htmlInfo.mtimeMs);
|
|
1431
|
+
if (pptx !== null) mtimes.push(pptx.mtimeMs);
|
|
1432
|
+
if (workflow !== null) mtimes.push(workflow.mtimeMs);
|
|
1433
|
+
const latestMs = mtimes.length > 0 ? Math.max(...mtimes) : Date.now();
|
|
1434
|
+
const htmlRelPath = htmlInfo !== null ? toPosix$1(relative(workspaceRoot, htmlAbs)) : null;
|
|
1435
|
+
const pptxRelPath = pptx?.relPath ?? null;
|
|
1436
|
+
const pptxStale = htmlInfo !== null && pptx !== null ? htmlInfo.mtimeMs > pptx.mtimeMs + 1e3 : false;
|
|
1437
|
+
return {
|
|
1438
|
+
id: relPath,
|
|
1439
|
+
...workflow !== null ? { workflow: workflow.workflow } : {},
|
|
1440
|
+
name,
|
|
1441
|
+
relPath,
|
|
1442
|
+
absPath: deckDir,
|
|
1443
|
+
slides,
|
|
1444
|
+
exploreSlides,
|
|
1445
|
+
overview,
|
|
1446
|
+
verifyImages,
|
|
1447
|
+
htmlRelPath,
|
|
1448
|
+
pptxRelPath,
|
|
1449
|
+
htmlUpdatedAt: htmlInfo !== null ? new Date(htmlInfo.mtimeMs).toISOString() : null,
|
|
1450
|
+
pptxUpdatedAt: pptx !== null ? new Date(pptx.mtimeMs).toISOString() : null,
|
|
1451
|
+
pptxStale,
|
|
1452
|
+
updatedAt: new Date(latestMs).toISOString()
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Scan workspace root and nested folders (up to depth 3) for Oil Slide decks.
|
|
1457
|
+
*/
|
|
1458
|
+
async function scanWorkspaceDecks(workspaceRoot) {
|
|
1459
|
+
const root = assertAbsoluteWorkspace(workspaceRoot);
|
|
1460
|
+
if (!existsSync(root)) return [];
|
|
1461
|
+
const found = [];
|
|
1462
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1463
|
+
async function walk(dir, depth) {
|
|
1464
|
+
if (visited.has(dir)) return;
|
|
1465
|
+
visited.add(dir);
|
|
1466
|
+
const deck = await inspectDeckDir(root, dir);
|
|
1467
|
+
if (deck !== null) {
|
|
1468
|
+
found.push(deck);
|
|
1469
|
+
if (dir !== root) return;
|
|
1470
|
+
}
|
|
1471
|
+
if (depth >= MAX_SCAN_DEPTH) return;
|
|
1472
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
1473
|
+
for (const entry of entries) {
|
|
1474
|
+
if (!entry.isDirectory()) continue;
|
|
1475
|
+
if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name)) continue;
|
|
1476
|
+
if (entry.name === "assets" || entry.name === "reference" || entry.name === "media" || entry.name === "derived" || entry.name === "web" || entry.name === "dist" || entry.name === "verify" || entry.name === "editable-run" || entry.name === "brand" || entry.name === "plates" || entry.name === "spec") continue;
|
|
1477
|
+
await walk(join(dir, entry.name), depth + 1);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
await walk(root, 0);
|
|
1481
|
+
found.sort((a, b) => {
|
|
1482
|
+
const tDiff = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
|
|
1483
|
+
if (tDiff !== 0) return tDiff;
|
|
1484
|
+
return a.relPath.localeCompare(b.relPath);
|
|
1485
|
+
});
|
|
1486
|
+
return found;
|
|
1487
|
+
}
|
|
1488
|
+
async function readWorkspaceImageDataUrl(workspaceRoot, relPath, options) {
|
|
1489
|
+
try {
|
|
1490
|
+
const absPath = await resolveConfinedWorkspacePath(workspaceRoot, relPath);
|
|
1491
|
+
if (!existsSync(absPath)) return {
|
|
1492
|
+
found: false,
|
|
1493
|
+
relPath,
|
|
1494
|
+
mime: "",
|
|
1495
|
+
dataUrl: "",
|
|
1496
|
+
error: "File not found"
|
|
1497
|
+
};
|
|
1498
|
+
const ext = extname(absPath).toLowerCase();
|
|
1499
|
+
const mime = MIME_BY_EXT[ext];
|
|
1500
|
+
if (mime === void 0) return {
|
|
1501
|
+
found: false,
|
|
1502
|
+
relPath,
|
|
1503
|
+
mime: "",
|
|
1504
|
+
dataUrl: "",
|
|
1505
|
+
error: "Unsupported image extension"
|
|
1506
|
+
};
|
|
1507
|
+
const info = await stat(absPath);
|
|
1508
|
+
if (!info.isFile() || info.size > MAX_IMAGE_BYTES) return {
|
|
1509
|
+
found: false,
|
|
1510
|
+
relPath,
|
|
1511
|
+
mime: "",
|
|
1512
|
+
dataUrl: "",
|
|
1513
|
+
error: "File is not a readable image under 15MB"
|
|
1514
|
+
};
|
|
1515
|
+
if (options?.assets !== void 0) {
|
|
1516
|
+
const optimized = await optimizeSingleImage({
|
|
1517
|
+
realPath: absPath,
|
|
1518
|
+
mtimeMs: info.mtimeMs,
|
|
1519
|
+
size: info.size,
|
|
1520
|
+
maxWidth: options.maxWidth,
|
|
1521
|
+
quality: options.quality ?? 85
|
|
1522
|
+
}, options.assets, options.signal);
|
|
1523
|
+
if (optimized !== null) return {
|
|
1524
|
+
found: true,
|
|
1525
|
+
relPath,
|
|
1526
|
+
mime: optimized.mime,
|
|
1527
|
+
dataUrl: `data:${optimized.mime};base64,${optimized.bytes.toString("base64")}`
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
return {
|
|
1531
|
+
found: true,
|
|
1532
|
+
relPath,
|
|
1533
|
+
mime,
|
|
1534
|
+
dataUrl: `data:${mime};base64,${(await readFile(absPath)).toString("base64")}`
|
|
1535
|
+
};
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
return {
|
|
1538
|
+
found: false,
|
|
1539
|
+
relPath,
|
|
1540
|
+
mime: "",
|
|
1541
|
+
dataUrl: "",
|
|
1542
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
function isExternalOrSpecialUrl(raw) {
|
|
1547
|
+
const s = raw.trim();
|
|
1548
|
+
return s === "" || s.startsWith("#") || s.startsWith("data:") || s.startsWith("blob:") || s.startsWith("http://") || s.startsWith("https://") || s.startsWith("//");
|
|
1549
|
+
}
|
|
1550
|
+
async function resolveConfinedDeckAsset(deckRealRoot, baseDir, rawRef) {
|
|
1551
|
+
const cleaned = rawRef.split(/[?#]/)[0]?.trim() ?? "";
|
|
1552
|
+
if (cleaned === "" || cleaned.includes("\0") || isExternalOrSpecialUrl(cleaned)) return null;
|
|
1553
|
+
const candidate = resolve(baseDir, cleaned);
|
|
1554
|
+
if (candidate !== deckRealRoot && !candidate.startsWith(`${deckRealRoot}${sep}`)) return null;
|
|
1555
|
+
if (!existsSync(candidate)) return null;
|
|
1556
|
+
const realTarget = await realpath(candidate).catch(() => null);
|
|
1557
|
+
if (realTarget === null) return null;
|
|
1558
|
+
if (realTarget !== deckRealRoot && !realTarget.startsWith(`${deckRealRoot}${sep}`)) return null;
|
|
1559
|
+
return realTarget;
|
|
1560
|
+
}
|
|
1561
|
+
const MAX_INLINED_HTML_CACHE = 6;
|
|
1562
|
+
const inlinedHtmlCache = /* @__PURE__ */ new Map();
|
|
1563
|
+
async function isCacheEntryFresh(entry) {
|
|
1564
|
+
for (const dep of entry.deps) {
|
|
1565
|
+
const info = await stat(dep.path).catch(() => null);
|
|
1566
|
+
if (info === null || !info.isFile() || info.mtimeMs !== dep.mtimeMs || info.size !== dep.size) return false;
|
|
1567
|
+
}
|
|
1568
|
+
return true;
|
|
1569
|
+
}
|
|
1570
|
+
function setInlinedHtmlCache(key, entry) {
|
|
1571
|
+
inlinedHtmlCache.delete(key);
|
|
1572
|
+
inlinedHtmlCache.set(key, entry);
|
|
1573
|
+
while (inlinedHtmlCache.size > MAX_INLINED_HTML_CACHE) {
|
|
1574
|
+
const oldest = inlinedHtmlCache.keys().next().value;
|
|
1575
|
+
if (oldest === void 0) break;
|
|
1576
|
+
inlinedHtmlCache.delete(oldest);
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
const INLINE_WEBP_QUALITY = 86;
|
|
1580
|
+
async function inlineAssetUrl(deckRealRoot, baseDir, rawRef, cache, depMap, preOptimized) {
|
|
1581
|
+
const realTarget = await resolveConfinedDeckAsset(deckRealRoot, baseDir, rawRef);
|
|
1582
|
+
if (realTarget === null) return null;
|
|
1583
|
+
const cached = cache.get(realTarget);
|
|
1584
|
+
if (cached !== void 0) return cached;
|
|
1585
|
+
const ext = extname(realTarget).toLowerCase();
|
|
1586
|
+
const mime = MIME_BY_EXT[ext];
|
|
1587
|
+
if (mime === void 0) return null;
|
|
1588
|
+
const info = await stat(realTarget).catch(() => null);
|
|
1589
|
+
if (info === null || !info.isFile() || info.size > MAX_IMAGE_BYTES) return null;
|
|
1590
|
+
depMap.set(realTarget, {
|
|
1591
|
+
mtimeMs: info.mtimeMs,
|
|
1592
|
+
size: info.size
|
|
1593
|
+
});
|
|
1594
|
+
if (preOptimized !== void 0) {
|
|
1595
|
+
const optKey = buildOptimizeKey({
|
|
1596
|
+
realPath: realTarget,
|
|
1597
|
+
mtimeMs: info.mtimeMs,
|
|
1598
|
+
size: info.size,
|
|
1599
|
+
quality: INLINE_WEBP_QUALITY
|
|
1600
|
+
});
|
|
1601
|
+
const hit = preOptimized.get(optKey);
|
|
1602
|
+
if (hit !== void 0) {
|
|
1603
|
+
const dataUrl = `data:${hit.mime};base64,${hit.bytes.toString("base64")}`;
|
|
1604
|
+
cache.set(realTarget, dataUrl);
|
|
1605
|
+
return dataUrl;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
const dataUrl = `data:${mime};base64,${(await readFile(realTarget)).toString("base64")}`;
|
|
1609
|
+
cache.set(realTarget, dataUrl);
|
|
1610
|
+
return dataUrl;
|
|
1611
|
+
}
|
|
1612
|
+
async function collectCssAssetSpecs(cssText, deckRealRoot, cssDir, specsByPath) {
|
|
1613
|
+
const matches = [...cssText.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi)];
|
|
1614
|
+
for (const m of matches) {
|
|
1615
|
+
const realTarget = await resolveConfinedDeckAsset(deckRealRoot, cssDir, m[2] ?? "");
|
|
1616
|
+
if (realTarget === null || specsByPath.has(realTarget)) continue;
|
|
1617
|
+
const ext = extname(realTarget).toLowerCase();
|
|
1618
|
+
if (MIME_BY_EXT[ext] === void 0) continue;
|
|
1619
|
+
const info = await stat(realTarget).catch(() => null);
|
|
1620
|
+
if (info === null || !info.isFile() || info.size > MAX_IMAGE_BYTES) continue;
|
|
1621
|
+
specsByPath.set(realTarget, {
|
|
1622
|
+
realPath: realTarget,
|
|
1623
|
+
mtimeMs: info.mtimeMs,
|
|
1624
|
+
size: info.size,
|
|
1625
|
+
quality: INLINE_WEBP_QUALITY
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
async function rewriteCssAssetUrls(cssText, deckRealRoot, cssDir, cache, depMap, preOptimized) {
|
|
1630
|
+
const matches = [...cssText.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi)];
|
|
1631
|
+
if (matches.length === 0) return cssText;
|
|
1632
|
+
let out = "";
|
|
1633
|
+
let cursor = 0;
|
|
1634
|
+
for (const m of matches) {
|
|
1635
|
+
const start = m.index ?? 0;
|
|
1636
|
+
const full = m[0];
|
|
1637
|
+
const quote = m[1] || "\"";
|
|
1638
|
+
const rawUrl = m[2] ?? "";
|
|
1639
|
+
out += cssText.slice(cursor, start);
|
|
1640
|
+
const inlined = await inlineAssetUrl(deckRealRoot, cssDir, rawUrl, cache, depMap, preOptimized);
|
|
1641
|
+
out += inlined !== null ? `url(${quote}${inlined}${quote})` : full;
|
|
1642
|
+
cursor = start + full.length;
|
|
1643
|
+
}
|
|
1644
|
+
out += cssText.slice(cursor);
|
|
1645
|
+
return out;
|
|
1646
|
+
}
|
|
1647
|
+
async function buildInlinedDeckHtml(workspaceRoot, deckRelPath, options) {
|
|
1648
|
+
const normalizedDeck = deckRelPath.trim() === "" ? "." : deckRelPath.trim();
|
|
1649
|
+
const root = assertAbsoluteWorkspace(workspaceRoot);
|
|
1650
|
+
const deckAbs = normalizedDeck === "." ? root : await resolveConfinedWorkspacePath(root, normalizedDeck);
|
|
1651
|
+
const deckRealRoot = await realpath(deckAbs);
|
|
1652
|
+
const htmlAbs = join(deckRealRoot, "web", "index.html");
|
|
1653
|
+
const htmlRelPath = toPosix$1(relative(root, htmlAbs));
|
|
1654
|
+
const htmlStat = await stat(htmlAbs).catch(() => null);
|
|
1655
|
+
if (htmlStat === null || !htmlStat.isFile()) return {
|
|
1656
|
+
found: false,
|
|
1657
|
+
deckRelPath: normalizedDeck,
|
|
1658
|
+
htmlRelPath,
|
|
1659
|
+
slideCount: 0,
|
|
1660
|
+
html: "",
|
|
1661
|
+
error: `Missing HTML deck entry: ${htmlRelPath}`
|
|
1662
|
+
};
|
|
1663
|
+
const optMode = options.assets !== void 0 ? "webp" : "raw";
|
|
1664
|
+
const cacheKey = `${htmlAbs}:${options.stripScripts ? "preview" : "standalone"}:${optMode}`;
|
|
1665
|
+
const existing = inlinedHtmlCache.get(cacheKey);
|
|
1666
|
+
if (existing !== void 0 && await isCacheEntryFresh(existing)) {
|
|
1667
|
+
setInlinedHtmlCache(cacheKey, existing);
|
|
1668
|
+
return {
|
|
1669
|
+
...existing.result,
|
|
1670
|
+
deckRelPath: normalizedDeck,
|
|
1671
|
+
htmlRelPath
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
const htmlDir = dirname(htmlAbs);
|
|
1675
|
+
const assetCache = /* @__PURE__ */ new Map();
|
|
1676
|
+
const depMap = /* @__PURE__ */ new Map([[htmlAbs, {
|
|
1677
|
+
mtimeMs: htmlStat.mtimeMs,
|
|
1678
|
+
size: htmlStat.size
|
|
1679
|
+
}]]);
|
|
1680
|
+
let html = await readFile(htmlAbs, "utf8");
|
|
1681
|
+
const linkMatches = [...html.matchAll(/<link\b[^>]*rel=["']stylesheet["'][^>]*>/gi)];
|
|
1682
|
+
const resolvedLinks = [];
|
|
1683
|
+
for (const m of linkMatches) {
|
|
1684
|
+
const tag = m[0];
|
|
1685
|
+
const href = tag.match(/\bhref=(["'])([^"']+)\1/i)?.[2];
|
|
1686
|
+
if (href === void 0 || isExternalOrSpecialUrl(href)) continue;
|
|
1687
|
+
const cssAbs = await resolveConfinedDeckAsset(deckRealRoot, htmlDir, href);
|
|
1688
|
+
if (cssAbs === null || extname(cssAbs).toLowerCase() !== ".css") continue;
|
|
1689
|
+
const cssInfo = await stat(cssAbs).catch(() => null);
|
|
1690
|
+
if (cssInfo === null || !cssInfo.isFile()) continue;
|
|
1691
|
+
const cssRaw = await readFile(cssAbs, "utf8").catch(() => null);
|
|
1692
|
+
if (cssRaw === null) continue;
|
|
1693
|
+
depMap.set(cssAbs, {
|
|
1694
|
+
mtimeMs: cssInfo.mtimeMs,
|
|
1695
|
+
size: cssInfo.size
|
|
1696
|
+
});
|
|
1697
|
+
resolvedLinks.push({
|
|
1698
|
+
tag,
|
|
1699
|
+
href,
|
|
1700
|
+
cssAbs,
|
|
1701
|
+
cssRaw
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
let preOptimized;
|
|
1705
|
+
if (options.assets !== void 0) {
|
|
1706
|
+
const specsByPath = /* @__PURE__ */ new Map();
|
|
1707
|
+
for (const link of resolvedLinks) await collectCssAssetSpecs(link.cssRaw, deckRealRoot, dirname(link.cssAbs), specsByPath);
|
|
1708
|
+
await collectCssAssetSpecs(html, deckRealRoot, htmlDir, specsByPath);
|
|
1709
|
+
const attrScan = [...html.matchAll(/\b(src|poster|xlink:href|href)=(["'])([^"']+)\2/gi)];
|
|
1710
|
+
for (const m of attrScan) {
|
|
1711
|
+
const rawUrl = m[3] ?? "";
|
|
1712
|
+
const ext = extname((rawUrl.split(/[?#]/)[0] ?? "").trim()).toLowerCase();
|
|
1713
|
+
if (!IMAGE_EXTENSIONS.has(ext) || isExternalOrSpecialUrl(rawUrl)) continue;
|
|
1714
|
+
const realTarget = await resolveConfinedDeckAsset(deckRealRoot, htmlDir, rawUrl);
|
|
1715
|
+
if (realTarget === null || specsByPath.has(realTarget)) continue;
|
|
1716
|
+
const info = await stat(realTarget).catch(() => null);
|
|
1717
|
+
if (info === null || !info.isFile() || info.size > MAX_IMAGE_BYTES) continue;
|
|
1718
|
+
specsByPath.set(realTarget, {
|
|
1719
|
+
realPath: realTarget,
|
|
1720
|
+
mtimeMs: info.mtimeMs,
|
|
1721
|
+
size: info.size,
|
|
1722
|
+
quality: INLINE_WEBP_QUALITY
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
if (specsByPath.size > 0) preOptimized = await optimizeImagesBatch([...specsByPath.values()], options.assets, options.signal);
|
|
1726
|
+
}
|
|
1727
|
+
for (const link of resolvedLinks) {
|
|
1728
|
+
const cssRewritten = await rewriteCssAssetUrls(link.cssRaw, deckRealRoot, dirname(link.cssAbs), assetCache, depMap, preOptimized);
|
|
1729
|
+
html = html.replace(link.tag, `<style data-inlined-href="${link.href}">${cssRewritten}</style>`);
|
|
1730
|
+
}
|
|
1731
|
+
html = await rewriteCssAssetUrls(html, deckRealRoot, htmlDir, assetCache, depMap, preOptimized);
|
|
1732
|
+
const attrMatches = [...html.matchAll(/\b(src|poster|xlink:href|href)=(["'])([^"']+)\2/gi)];
|
|
1733
|
+
if (attrMatches.length > 0) {
|
|
1734
|
+
let rebuilt = "";
|
|
1735
|
+
let cursor = 0;
|
|
1736
|
+
for (const m of attrMatches) {
|
|
1737
|
+
const start = m.index ?? 0;
|
|
1738
|
+
const full = m[0];
|
|
1739
|
+
const attrName = m[1] ?? "src";
|
|
1740
|
+
const quote = m[2] ?? "\"";
|
|
1741
|
+
const rawUrl = m[3] ?? "";
|
|
1742
|
+
rebuilt += html.slice(cursor, start);
|
|
1743
|
+
const ext = extname((rawUrl.split(/[?#]/)[0] ?? "").trim()).toLowerCase();
|
|
1744
|
+
if (IMAGE_EXTENSIONS.has(ext) && !isExternalOrSpecialUrl(rawUrl)) {
|
|
1745
|
+
const inlined = await inlineAssetUrl(deckRealRoot, htmlDir, rawUrl, assetCache, depMap, preOptimized);
|
|
1746
|
+
rebuilt += inlined !== null ? `${attrName}=${quote}${inlined}${quote}` : full;
|
|
1747
|
+
} else rebuilt += full;
|
|
1748
|
+
cursor = start + full.length;
|
|
1749
|
+
}
|
|
1750
|
+
rebuilt += html.slice(cursor);
|
|
1751
|
+
html = rebuilt;
|
|
1752
|
+
}
|
|
1753
|
+
if (options.stripScripts) html = html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "");
|
|
1754
|
+
const result = {
|
|
1755
|
+
found: true,
|
|
1756
|
+
deckRelPath: normalizedDeck,
|
|
1757
|
+
htmlRelPath,
|
|
1758
|
+
slideCount: html.match(/class=(["'])[^"']*\bslide\b[^"']*\1/gi)?.length ?? 0,
|
|
1759
|
+
html
|
|
1760
|
+
};
|
|
1761
|
+
setInlinedHtmlCache(cacheKey, {
|
|
1762
|
+
deps: [...depMap.entries()].map(([path, meta]) => ({
|
|
1763
|
+
path,
|
|
1764
|
+
...meta
|
|
1765
|
+
})),
|
|
1766
|
+
result
|
|
1767
|
+
});
|
|
1768
|
+
return result;
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* Read a deck's `web/index.html` and inline all local stylesheets and images
|
|
1772
|
+
* (confined strictly within the deck directory) into self-contained `data:` URIs
|
|
1773
|
+
* so live HTML slides render identically in both `dsh web` and `DSH Desktop`.
|
|
1774
|
+
*/
|
|
1775
|
+
async function readDeckHtmlPreview(workspaceRoot, deckRelPath, options) {
|
|
1776
|
+
return buildInlinedDeckHtml(workspaceRoot, deckRelPath, {
|
|
1777
|
+
stripScripts: true,
|
|
1778
|
+
assets: options?.assets,
|
|
1779
|
+
signal: options?.signal
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* Build a standalone, offline-ready single-file HTML deck with all local stylesheets
|
|
1784
|
+
* and images inlined as `data:` URIs while preserving interactive keyboard/navigation scripts.
|
|
1785
|
+
*/
|
|
1786
|
+
async function readStandaloneDeckHtml(workspaceRoot, deckRelPath, options) {
|
|
1787
|
+
return buildInlinedDeckHtml(workspaceRoot, deckRelPath, {
|
|
1788
|
+
stripScripts: false,
|
|
1789
|
+
assets: options?.assets,
|
|
1790
|
+
signal: options?.signal
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
// src/host/review.ts
|
|
1794
|
+
const exec = promisify(execFile);
|
|
1795
|
+
async function runReview(assets, workspace, deck, op) {
|
|
1796
|
+
const py = await resolveBestPython(assets);
|
|
1797
|
+
if (!py) throw new Error("Python 3.10+ is required");
|
|
1798
|
+
const tmp = await mkdtemp(join(tmpdir(), "oil-slide-review-"));
|
|
1799
|
+
try {
|
|
1800
|
+
const args = [
|
|
1801
|
+
join(assets.scriptsDir, "slide_workflow.py"),
|
|
1802
|
+
"--deck",
|
|
1803
|
+
deck
|
|
1804
|
+
];
|
|
1805
|
+
const file = join(tmp, "input.json");
|
|
1806
|
+
switch (op.kind) {
|
|
1807
|
+
case "inspect-native":
|
|
1808
|
+
args.push("inspect-native", "--number", String(op.number));
|
|
1809
|
+
break;
|
|
1810
|
+
case "brands":
|
|
1811
|
+
args.push("brand-list");
|
|
1812
|
+
break;
|
|
1813
|
+
case "save-brand":
|
|
1814
|
+
await writeFile(file, JSON.stringify(op), { mode: 384 });
|
|
1815
|
+
args.push("brand-create", "--workspace", workspace, "--file", file);
|
|
1816
|
+
break;
|
|
1817
|
+
case "outline":
|
|
1818
|
+
await writeFile(file, JSON.stringify(op), { mode: 384 });
|
|
1819
|
+
args.push("edit-outline", "--file", file);
|
|
1820
|
+
break;
|
|
1821
|
+
case "region":
|
|
1822
|
+
args.push("propose-region", "--number", String(op.number), "--revision", String(op.revision), "--box", ...op.box.map(String), "--feedback=" + op.feedback);
|
|
1823
|
+
break;
|
|
1824
|
+
case "resolve":
|
|
1825
|
+
args.push("resolve-region", "--proposal", op.id, "--choice", op.choice);
|
|
1826
|
+
break;
|
|
1827
|
+
default: throw new Error("Invalid deck operation");
|
|
1828
|
+
}
|
|
1829
|
+
const { stdout } = await exec(py.bin, args, {
|
|
1830
|
+
cwd: deck,
|
|
1831
|
+
env: {
|
|
1832
|
+
...process.env,
|
|
1833
|
+
PYTHONIOENCODING: "utf-8"
|
|
1834
|
+
},
|
|
1835
|
+
maxBuffer: 8 << 20,
|
|
1836
|
+
windowsHide: true
|
|
1837
|
+
});
|
|
1838
|
+
const state = JSON.parse(stdout);
|
|
1839
|
+
if (op.kind === "inspect-native") return { native: state };
|
|
1840
|
+
if (op.kind === "brands") return { brands: state };
|
|
1841
|
+
if (op.kind === "save-brand") return { brand: state };
|
|
1842
|
+
return { revision: state.outlineRevision };
|
|
1843
|
+
} catch (cause) {
|
|
1844
|
+
const stderr = cause.stderr;
|
|
1845
|
+
if (stderr) throw new Error(stderr.trim().split("\n").at(-1)?.slice(0, 800));
|
|
1846
|
+
throw cause;
|
|
1847
|
+
} finally {
|
|
1848
|
+
await rm(tmp, {
|
|
1849
|
+
recursive: true,
|
|
1850
|
+
force: true
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
var DeckReviewService = class {
|
|
1855
|
+
jobs = /* @__PURE__ */ new Map();
|
|
1856
|
+
async handle(assets, workspace, req, refresh) {
|
|
1857
|
+
const deck = await resolveConfinedWorkspacePath(workspace, req.deckRelPath);
|
|
1858
|
+
const op = req.operation;
|
|
1859
|
+
if (op.kind === "region-status") return this.jobs.get(deck) ?? { busy: false };
|
|
1860
|
+
if (op.kind === "region") {
|
|
1861
|
+
if (this.jobs.get(deck)?.busy) throw new Error("A region edit is already running");
|
|
1862
|
+
this.jobs.set(deck, { busy: true });
|
|
1863
|
+
runReview(assets, workspace, deck, op).then(() => {
|
|
1864
|
+
this.jobs.delete(deck);
|
|
1865
|
+
refresh();
|
|
1866
|
+
}, (err) => this.jobs.set(deck, {
|
|
1867
|
+
busy: false,
|
|
1868
|
+
error: String(err.message)
|
|
1869
|
+
}));
|
|
1870
|
+
return { busy: true };
|
|
1871
|
+
}
|
|
1872
|
+
const result = await runReview(assets, workspace, deck, op);
|
|
1873
|
+
if (op.kind === "resolve") {
|
|
1874
|
+
this.jobs.delete(deck);
|
|
1875
|
+
refresh();
|
|
1876
|
+
}
|
|
1877
|
+
return result;
|
|
1878
|
+
}
|
|
1879
|
+
};
|
|
1880
|
+
// src/host/compiler.ts
|
|
1881
|
+
const execFileAsync = promisify(execFile);
|
|
1882
|
+
function isSlideFragmentFilename(name) {
|
|
1883
|
+
return !name.startsWith(".") && name.toLowerCase() !== "index.html" && /\.(?:html|htm|json)$/i.test(name);
|
|
1884
|
+
}
|
|
1885
|
+
async function maybeRebuildIndexFromSlides(options) {
|
|
1886
|
+
const rawRoot = options.workspaceRoot ?? options.deckAbs;
|
|
1887
|
+
const realRoot = await realpath(rawRoot);
|
|
1888
|
+
const realDeckAbs = await realpath(options.deckAbs);
|
|
1889
|
+
const deckRel = relative(realRoot, realDeckAbs);
|
|
1890
|
+
if (deckRel.startsWith("..") || deckRel.includes(`..${sep}`)) throw new Error(`Deck path escapes workspace: "${options.deckAbs}"`);
|
|
1891
|
+
const relJoin = (...parts) => deckRel === "" ? join(...parts) : join(deckRel, ...parts);
|
|
1892
|
+
const htmlRel = options.htmlAbs === realRoot || options.htmlAbs.startsWith(`${realRoot}${sep}`) ? relative(realRoot, options.htmlAbs) : relative(rawRoot, options.htmlAbs);
|
|
1893
|
+
const slidesDir = await resolveConfinedWorkspacePath(realRoot, relJoin("web", "slides"));
|
|
1894
|
+
const themePath = await resolveConfinedWorkspacePath(realRoot, relJoin("web", "theme.json"));
|
|
1895
|
+
const confinedHtmlAbs = await resolveConfinedWorkspacePath(realRoot, htmlRel);
|
|
1896
|
+
const shellScript = join(options.scriptsDir, "deck_shell.py");
|
|
1897
|
+
if (!existsSync(slidesDir) || !existsSync(shellScript)) return;
|
|
1898
|
+
let entries;
|
|
1899
|
+
try {
|
|
1900
|
+
entries = (await readdir(slidesDir)).filter(isSlideFragmentFilename);
|
|
1901
|
+
} catch {
|
|
1902
|
+
return;
|
|
1903
|
+
}
|
|
1904
|
+
if (entries.length === 0) return;
|
|
1905
|
+
let htmlMtimeMs = 0;
|
|
1906
|
+
if (existsSync(confinedHtmlAbs)) try {
|
|
1907
|
+
htmlMtimeMs = (await stat(confinedHtmlAbs)).mtimeMs;
|
|
1908
|
+
} catch {
|
|
1909
|
+
htmlMtimeMs = 0;
|
|
1910
|
+
}
|
|
1911
|
+
let newestSrcMs = 0;
|
|
1912
|
+
try {
|
|
1913
|
+
newestSrcMs = (await stat(slidesDir)).mtimeMs;
|
|
1914
|
+
} catch {}
|
|
1915
|
+
for (const name of entries) try {
|
|
1916
|
+
const m = (await stat(join(slidesDir, name))).mtimeMs;
|
|
1917
|
+
if (m > newestSrcMs) newestSrcMs = m;
|
|
1918
|
+
} catch {}
|
|
1919
|
+
if (existsSync(themePath)) try {
|
|
1920
|
+
const m = (await stat(themePath)).mtimeMs;
|
|
1921
|
+
if (m > newestSrcMs) newestSrcMs = m;
|
|
1922
|
+
} catch {}
|
|
1923
|
+
if (htmlMtimeMs > 0 && newestSrcMs <= htmlMtimeMs) return;
|
|
1924
|
+
const resolvedBin = typeof options.pythonBin === "function" ? await options.pythonBin() : options.pythonBin;
|
|
1925
|
+
if (resolvedBin === null || resolvedBin === "") return;
|
|
1926
|
+
const args = [
|
|
1927
|
+
shellScript,
|
|
1928
|
+
"--slides-dir",
|
|
1929
|
+
slidesDir,
|
|
1930
|
+
"--out",
|
|
1931
|
+
confinedHtmlAbs,
|
|
1932
|
+
"--json"
|
|
1933
|
+
];
|
|
1934
|
+
if (existsSync(themePath)) args.push("--theme", themePath);
|
|
1935
|
+
await execFileAsync(resolvedBin, args, {
|
|
1936
|
+
cwd: options.deckAbs,
|
|
1937
|
+
timeout: 6e4,
|
|
1938
|
+
maxBuffer: 4194304,
|
|
1939
|
+
signal: options.signal
|
|
1940
|
+
});
|
|
1941
|
+
}
|
|
1942
|
+
function toPosix(p) {
|
|
1943
|
+
return p.split(sep).join("/");
|
|
1944
|
+
}
|
|
1945
|
+
function trimLog(text, maxChars = 4e3) {
|
|
1946
|
+
if (text.length <= maxChars) return text;
|
|
1947
|
+
return `…(truncated)\n${text.slice(-maxChars)}`;
|
|
1948
|
+
}
|
|
1949
|
+
async function compileDeckToPptx(options) {
|
|
1950
|
+
const started = Date.now();
|
|
1951
|
+
const root = assertAbsoluteWorkspace(options.workspaceRoot);
|
|
1952
|
+
const realRoot = await realpath(root);
|
|
1953
|
+
const normalizedDeckRel = options.deckRelPath.trim() === "" ? "." : options.deckRelPath.trim();
|
|
1954
|
+
const deckAbs = normalizedDeckRel === "." ? realRoot : await resolveConfinedWorkspacePath(realRoot, normalizedDeckRel);
|
|
1955
|
+
const htmlAbs = await resolveConfinedWorkspacePath(realRoot, normalizedDeckRel === "." ? "web/index.html" : `${normalizedDeckRel.replace(/\/+$/, "")}/web/index.html`);
|
|
1956
|
+
const defaultOutRel = normalizedDeckRel === "." ? "dist/deck.pptx" : `${normalizedDeckRel.replace(/\/+$/, "")}/dist/deck.pptx`;
|
|
1957
|
+
const outAbs = await resolveConfinedWorkspacePath(realRoot, options.outRelPath !== void 0 && options.outRelPath.trim() !== "" ? options.outRelPath.trim() : defaultOutRel);
|
|
1958
|
+
const pptxRelPath = toPosix(relative(realRoot, outAbs));
|
|
1959
|
+
const scriptPath = join(options.assets.scriptsDir, "html_to_pptx.py");
|
|
1960
|
+
if (!existsSync(scriptPath)) return {
|
|
1961
|
+
ok: false,
|
|
1962
|
+
deckRelPath: normalizedDeckRel,
|
|
1963
|
+
htmlPath: htmlAbs,
|
|
1964
|
+
outPath: outAbs,
|
|
1965
|
+
pptxRelPath,
|
|
1966
|
+
durationMs: Date.now() - started,
|
|
1967
|
+
stdout: "",
|
|
1968
|
+
stderr: "",
|
|
1969
|
+
error: `Missing compiler script: ${scriptPath}`
|
|
1970
|
+
};
|
|
1971
|
+
const py = await resolveBestPython(options.assets, options.signal);
|
|
1972
|
+
if (py === null) return {
|
|
1973
|
+
ok: false,
|
|
1974
|
+
deckRelPath: normalizedDeckRel,
|
|
1975
|
+
htmlPath: htmlAbs,
|
|
1976
|
+
outPath: outAbs,
|
|
1977
|
+
pptxRelPath,
|
|
1978
|
+
durationMs: Date.now() - started,
|
|
1979
|
+
stdout: "",
|
|
1980
|
+
stderr: "",
|
|
1981
|
+
error: "Python 3.10+ runtime not found. Run oil_slide_doctor for details."
|
|
1982
|
+
};
|
|
1983
|
+
try {
|
|
1984
|
+
await maybeRebuildIndexFromSlides({
|
|
1985
|
+
pythonBin: py.bin,
|
|
1986
|
+
scriptsDir: options.assets.scriptsDir,
|
|
1987
|
+
deckAbs,
|
|
1988
|
+
htmlAbs,
|
|
1989
|
+
workspaceRoot: realRoot,
|
|
1990
|
+
signal: options.signal
|
|
1991
|
+
});
|
|
1992
|
+
} catch (error) {
|
|
1993
|
+
const err = error;
|
|
1994
|
+
return {
|
|
1995
|
+
ok: false,
|
|
1996
|
+
deckRelPath: normalizedDeckRel,
|
|
1997
|
+
htmlPath: htmlAbs,
|
|
1998
|
+
outPath: outAbs,
|
|
1999
|
+
pptxRelPath,
|
|
2000
|
+
durationMs: Date.now() - started,
|
|
2001
|
+
stdout: trimLog(err.stdout ?? ""),
|
|
2002
|
+
stderr: trimLog(err.stderr ?? ""),
|
|
2003
|
+
error: `Failed to rebuild web/index.html from web/slides/: ${err.message}`
|
|
2004
|
+
};
|
|
2005
|
+
}
|
|
2006
|
+
if (!existsSync(htmlAbs)) return {
|
|
2007
|
+
ok: false,
|
|
2008
|
+
deckRelPath: normalizedDeckRel,
|
|
2009
|
+
htmlPath: htmlAbs,
|
|
2010
|
+
outPath: outAbs,
|
|
2011
|
+
pptxRelPath,
|
|
2012
|
+
durationMs: Date.now() - started,
|
|
2013
|
+
stdout: "",
|
|
2014
|
+
stderr: "",
|
|
2015
|
+
error: `Missing HTML deck entry: ${htmlAbs}`
|
|
2016
|
+
};
|
|
2017
|
+
await mkdir(dirname(outAbs), { recursive: true });
|
|
2018
|
+
try {
|
|
2019
|
+
const { stdout, stderr } = await execFileAsync(py.bin, [
|
|
2020
|
+
scriptPath,
|
|
2021
|
+
"--html",
|
|
2022
|
+
htmlAbs,
|
|
2023
|
+
"--out",
|
|
2024
|
+
outAbs,
|
|
2025
|
+
"--audit"
|
|
2026
|
+
], {
|
|
2027
|
+
cwd: deckAbs,
|
|
2028
|
+
timeout: 18e4,
|
|
2029
|
+
maxBuffer: 8388608,
|
|
2030
|
+
signal: options.signal
|
|
2031
|
+
});
|
|
2032
|
+
return {
|
|
2033
|
+
ok: true,
|
|
2034
|
+
deckRelPath: normalizedDeckRel,
|
|
2035
|
+
htmlPath: htmlAbs,
|
|
2036
|
+
outPath: outAbs,
|
|
2037
|
+
pptxRelPath,
|
|
2038
|
+
durationMs: Date.now() - started,
|
|
2039
|
+
stdout: trimLog(stdout),
|
|
2040
|
+
stderr: trimLog(stderr)
|
|
2041
|
+
};
|
|
2042
|
+
} catch (error) {
|
|
2043
|
+
const err = error;
|
|
2044
|
+
return {
|
|
2045
|
+
ok: false,
|
|
2046
|
+
deckRelPath: normalizedDeckRel,
|
|
2047
|
+
htmlPath: htmlAbs,
|
|
2048
|
+
outPath: outAbs,
|
|
2049
|
+
pptxRelPath,
|
|
2050
|
+
durationMs: Date.now() - started,
|
|
2051
|
+
stdout: trimLog(err.stdout ?? ""),
|
|
2052
|
+
stderr: trimLog(err.stderr ?? ""),
|
|
2053
|
+
error: err.message
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
// src/shared/remote-contract.ts
|
|
2058
|
+
const PACKAGE_NAME = "@dickpy/dsh-oil-slide";
|
|
2059
|
+
const REMOTE_NAMESPACE = "oilSlide";
|
|
2060
|
+
function codec(typeSymbol, schema) {
|
|
2061
|
+
return {
|
|
2062
|
+
mode: "strict",
|
|
2063
|
+
typeSymbol,
|
|
2064
|
+
create: () => schema
|
|
2065
|
+
};
|
|
2066
|
+
}
|
|
2067
|
+
function jsonParam(name, typeSymbol, schema) {
|
|
2068
|
+
return {
|
|
2069
|
+
name,
|
|
2070
|
+
wire: name,
|
|
2071
|
+
source: "json",
|
|
2072
|
+
codec: codec(typeSymbol, schema)
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
function invocation(method, request, result) {
|
|
2076
|
+
return {
|
|
2077
|
+
id: `${PACKAGE_NAME}#${REMOTE_NAMESPACE}/${method}`,
|
|
2078
|
+
service: REMOTE_NAMESPACE,
|
|
2079
|
+
namespace: REMOTE_NAMESPACE,
|
|
2080
|
+
method,
|
|
2081
|
+
invocation: { kind: "direct" },
|
|
2082
|
+
parameters: [jsonParam("request", `${PACKAGE_NAME}#${method}Request`, request)],
|
|
2083
|
+
cancellation: { parameter: "signal" },
|
|
2084
|
+
result: codec(`${PACKAGE_NAME}#${method}Result`, result),
|
|
2085
|
+
sourceLocation: {
|
|
2086
|
+
file: "src/host/service.ts",
|
|
2087
|
+
line: 1,
|
|
2088
|
+
column: 1
|
|
2089
|
+
}
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
const OIL_SLIDE_INVOCATIONS = [
|
|
2093
|
+
invocation("reviewDeck", reviewRequestSchema, reviewResultSchema),
|
|
2094
|
+
invocation("getImageChannels", emptyRequestSchema, imageChannelSettingsSchema),
|
|
2095
|
+
invocation("saveImageChannels", imageChannelSettingsUpdateSchema, imageChannelSettingsSchema),
|
|
2096
|
+
invocation("discoverImageModels", imageChannelConnectionSchema, imageModelDiscoverySchema),
|
|
2097
|
+
invocation("getBrandAssets", emptyRequestSchema, brandAssetsResultSchema),
|
|
2098
|
+
invocation("scanDecks", scanDecksRequestSchema, scanDecksResultSchema),
|
|
2099
|
+
invocation("getDeckHtmlPreview", deckHtmlPreviewRequestSchema, deckHtmlPreviewResultSchema),
|
|
2100
|
+
invocation("getStandaloneDeckHtml", deckHtmlPreviewRequestSchema, deckHtmlPreviewResultSchema),
|
|
2101
|
+
invocation("getWorkspaceImageDataUrl", workspaceImageRequestSchema, workspaceImageResultSchema),
|
|
2102
|
+
invocation("compileDeckPptx", compileDeckPptxRequestSchema, compileDeckPptxResultSchema),
|
|
2103
|
+
invocation("runDoctor", doctorRequestSchema, doctorReportSchema),
|
|
2104
|
+
invocation("waitForPreviewSignal", waitPreviewSignalRequestSchema, waitPreviewSignalResultSchema)
|
|
2105
|
+
];
|
|
2106
|
+
// src/host/service.ts
|
|
2107
|
+
var OilSlideService = class extends TypertRemoteService {
|
|
2108
|
+
hostCtx;
|
|
2109
|
+
assets;
|
|
2110
|
+
defaultWorkspaceRoot;
|
|
2111
|
+
previewSeq = 0;
|
|
2112
|
+
latestPreviewSignal = null;
|
|
2113
|
+
previewWaiters = /* @__PURE__ */ new Set();
|
|
2114
|
+
constructor(ctx, config = {}, assets) {
|
|
2115
|
+
super(ctx, REMOTE_NAMESPACE);
|
|
2116
|
+
this.hostCtx = ctx;
|
|
2117
|
+
this.assets = assets ?? resolvePluginAssets();
|
|
2118
|
+
this.defaultWorkspaceRoot = config.defaultWorkspaceRoot;
|
|
2119
|
+
}
|
|
2120
|
+
deckReview = new DeckReviewService();
|
|
2121
|
+
reviewDeck(request) {
|
|
2122
|
+
const workspace = this.resolveWorkspaceRoot(request.workspaceRoot);
|
|
2123
|
+
if (!workspace) throw new Error("No active workspace");
|
|
2124
|
+
return this.deckReview.handle(this.assets, workspace, request, () => {
|
|
2125
|
+
this.notifyPreview({
|
|
2126
|
+
workspaceRoot: workspace,
|
|
2127
|
+
deckRelPath: request.deckRelPath,
|
|
2128
|
+
tab: "canvas"
|
|
2129
|
+
});
|
|
2130
|
+
});
|
|
2131
|
+
}
|
|
2132
|
+
getImageChannels() {
|
|
2133
|
+
return getImageChannels();
|
|
2134
|
+
}
|
|
2135
|
+
saveImageChannels(request) {
|
|
2136
|
+
return saveImageChannels(request);
|
|
2137
|
+
}
|
|
2138
|
+
discoverImageModels(request, signal) {
|
|
2139
|
+
return discoverImageModels(request, {}, signal);
|
|
2140
|
+
}
|
|
2141
|
+
notifyPreview(options) {
|
|
2142
|
+
this.previewSeq += 1;
|
|
2143
|
+
const resolvedWs = options?.workspaceRoot !== void 0 && options.workspaceRoot !== null ? this.resolveWorkspaceRoot(options.workspaceRoot) : this.resolveWorkspaceRoot();
|
|
2144
|
+
const signal = {
|
|
2145
|
+
seq: this.previewSeq,
|
|
2146
|
+
deckRelPath: typeof options?.deckRelPath === "string" && options.deckRelPath.trim() !== "" ? options.deckRelPath.trim() : null,
|
|
2147
|
+
tab: options?.tab ?? "auto",
|
|
2148
|
+
workspaceRoot: resolvedWs,
|
|
2149
|
+
emittedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2150
|
+
};
|
|
2151
|
+
this.latestPreviewSignal = signal;
|
|
2152
|
+
for (const wake of Array.from(this.previewWaiters)) wake();
|
|
2153
|
+
return signal;
|
|
2154
|
+
}
|
|
2155
|
+
async waitForPreviewSignal(request, abortSignal) {
|
|
2156
|
+
const afterSeq = Number.isFinite(request.afterSeq) ? request.afterSeq : 0;
|
|
2157
|
+
if (afterSeq < 0) return {
|
|
2158
|
+
changed: false,
|
|
2159
|
+
seq: this.previewSeq,
|
|
2160
|
+
signal: null
|
|
2161
|
+
};
|
|
2162
|
+
if (this.previewSeq > afterSeq && this.latestPreviewSignal !== null) return {
|
|
2163
|
+
changed: true,
|
|
2164
|
+
seq: this.previewSeq,
|
|
2165
|
+
signal: this.latestPreviewSignal
|
|
2166
|
+
};
|
|
2167
|
+
const timeoutMs = Math.min(Math.max(request.timeoutMs ?? 2e4, 100), 25e3);
|
|
2168
|
+
return new Promise((resolve) => {
|
|
2169
|
+
let settled = false;
|
|
2170
|
+
const finish = () => {
|
|
2171
|
+
if (settled) return;
|
|
2172
|
+
settled = true;
|
|
2173
|
+
clearTimeout(timer);
|
|
2174
|
+
this.previewWaiters.delete(finish);
|
|
2175
|
+
abortSignal?.removeEventListener("abort", finish);
|
|
2176
|
+
const changed = this.previewSeq > afterSeq && this.latestPreviewSignal !== null;
|
|
2177
|
+
resolve({
|
|
2178
|
+
changed,
|
|
2179
|
+
seq: this.previewSeq,
|
|
2180
|
+
signal: changed ? this.latestPreviewSignal : null
|
|
2181
|
+
});
|
|
2182
|
+
};
|
|
2183
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
2184
|
+
this.previewWaiters.add(finish);
|
|
2185
|
+
if (abortSignal?.aborted) finish();
|
|
2186
|
+
else abortSignal?.addEventListener("abort", finish, { once: true });
|
|
2187
|
+
});
|
|
2188
|
+
}
|
|
2189
|
+
resolveWorkspaceRoot(requested) {
|
|
2190
|
+
const candidate = requested?.trim();
|
|
2191
|
+
if (candidate !== void 0 && candidate !== "") return assertAbsoluteWorkspace(candidate);
|
|
2192
|
+
const configured = this.defaultWorkspaceRoot?.trim();
|
|
2193
|
+
if (configured !== void 0 && configured !== "") return assertAbsoluteWorkspace(configured);
|
|
2194
|
+
const wd = this.hostCtx.get("workingDirectory");
|
|
2195
|
+
if (typeof wd?.defaultDirectory === "string" && wd.defaultDirectory.trim() !== "") return assertAbsoluteWorkspace(wd.defaultDirectory);
|
|
2196
|
+
const cwd = process.cwd();
|
|
2197
|
+
return existsSync(cwd) ? assertAbsoluteWorkspace(cwd) : null;
|
|
2198
|
+
}
|
|
2199
|
+
async getBrandAssets(_request = {}, _signal) {
|
|
2200
|
+
return loadBrandAssets(this.assets.brandDir);
|
|
2201
|
+
}
|
|
2202
|
+
async scanDecks(request = {}, _signal) {
|
|
2203
|
+
const workspaceRoot = this.resolveWorkspaceRoot(request.workspaceRoot);
|
|
2204
|
+
if (workspaceRoot === null) return {
|
|
2205
|
+
workspaceRoot: null,
|
|
2206
|
+
decks: []
|
|
2207
|
+
};
|
|
2208
|
+
return {
|
|
2209
|
+
workspaceRoot,
|
|
2210
|
+
decks: await scanWorkspaceDecks(workspaceRoot)
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
async ensureFreshDeckIndex(workspaceRoot, deckRelPath, signal) {
|
|
2214
|
+
try {
|
|
2215
|
+
const root = assertAbsoluteWorkspace(workspaceRoot);
|
|
2216
|
+
const realRoot = await realpath(root);
|
|
2217
|
+
const normalizedDeckRel = deckRelPath.trim() === "" ? "." : deckRelPath.trim();
|
|
2218
|
+
const deckAbs = normalizedDeckRel === "." ? realRoot : await resolveConfinedWorkspacePath(realRoot, normalizedDeckRel);
|
|
2219
|
+
const htmlAbs = await resolveConfinedWorkspacePath(realRoot, normalizedDeckRel === "." ? "web/index.html" : `${normalizedDeckRel.replace(/\/+$/, "")}/web/index.html`);
|
|
2220
|
+
await maybeRebuildIndexFromSlides({
|
|
2221
|
+
pythonBin: () => resolvePythonBinFast(this.assets, signal),
|
|
2222
|
+
scriptsDir: this.assets.scriptsDir,
|
|
2223
|
+
deckAbs,
|
|
2224
|
+
htmlAbs,
|
|
2225
|
+
workspaceRoot: realRoot,
|
|
2226
|
+
signal
|
|
2227
|
+
});
|
|
2228
|
+
} catch {}
|
|
2229
|
+
}
|
|
2230
|
+
async getDeckHtmlPreview(request, signal) {
|
|
2231
|
+
const workspaceRoot = this.resolveWorkspaceRoot(request.workspaceRoot);
|
|
2232
|
+
if (workspaceRoot === null) return {
|
|
2233
|
+
found: false,
|
|
2234
|
+
deckRelPath: request.deckRelPath,
|
|
2235
|
+
htmlRelPath: "",
|
|
2236
|
+
slideCount: 0,
|
|
2237
|
+
html: "",
|
|
2238
|
+
error: "No workspaceRoot available"
|
|
2239
|
+
};
|
|
2240
|
+
await this.ensureFreshDeckIndex(workspaceRoot, request.deckRelPath, signal);
|
|
2241
|
+
return readDeckHtmlPreview(workspaceRoot, request.deckRelPath, {
|
|
2242
|
+
assets: this.assets,
|
|
2243
|
+
signal
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
async getStandaloneDeckHtml(request, signal) {
|
|
2247
|
+
const workspaceRoot = this.resolveWorkspaceRoot(request.workspaceRoot);
|
|
2248
|
+
if (workspaceRoot === null) return {
|
|
2249
|
+
found: false,
|
|
2250
|
+
deckRelPath: request.deckRelPath,
|
|
2251
|
+
htmlRelPath: "",
|
|
2252
|
+
slideCount: 0,
|
|
2253
|
+
html: "",
|
|
2254
|
+
error: "No workspaceRoot available"
|
|
2255
|
+
};
|
|
2256
|
+
await this.ensureFreshDeckIndex(workspaceRoot, request.deckRelPath, signal);
|
|
2257
|
+
return readStandaloneDeckHtml(workspaceRoot, request.deckRelPath, {
|
|
2258
|
+
assets: this.assets,
|
|
2259
|
+
signal
|
|
2260
|
+
});
|
|
2261
|
+
}
|
|
2262
|
+
async getWorkspaceImageDataUrl(request, signal) {
|
|
2263
|
+
const workspaceRoot = this.resolveWorkspaceRoot(request.workspaceRoot);
|
|
2264
|
+
if (workspaceRoot === null) return {
|
|
2265
|
+
found: false,
|
|
2266
|
+
relPath: request.relPath,
|
|
2267
|
+
mime: "",
|
|
2268
|
+
dataUrl: "",
|
|
2269
|
+
error: "No workspaceRoot available"
|
|
2270
|
+
};
|
|
2271
|
+
return readWorkspaceImageDataUrl(workspaceRoot, request.relPath, {
|
|
2272
|
+
maxWidth: request.maxWidth,
|
|
2273
|
+
quality: request.quality,
|
|
2274
|
+
assets: this.assets,
|
|
2275
|
+
signal
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
async compileDeckPptx(request, signal) {
|
|
2279
|
+
const workspaceRoot = this.resolveWorkspaceRoot(request.workspaceRoot);
|
|
2280
|
+
if (workspaceRoot === null) throw new Error("No workspaceRoot available for compiling PPTX.");
|
|
2281
|
+
return compileDeckToPptx({
|
|
2282
|
+
assets: this.assets,
|
|
2283
|
+
workspaceRoot,
|
|
2284
|
+
deckRelPath: request.deckRelPath,
|
|
2285
|
+
outRelPath: request.outRelPath,
|
|
2286
|
+
signal
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
async runDoctor(_request = {}, signal) {
|
|
2290
|
+
return runEnvironmentDoctor({
|
|
2291
|
+
assets: this.assets,
|
|
2292
|
+
ctx: this.hostCtx,
|
|
2293
|
+
signal
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
};
|
|
2297
|
+
// src/host/skillProvider.ts
|
|
2298
|
+
const OIL_SLIDE_PROVIDER_NAME = "oil-slide";
|
|
2299
|
+
const DEFAULT_DESCRIPTION = "创建有设计感的演示文稿与图文卡片(16:9/3:4/9:16/1:1),覆盖品牌调研、视觉生图、可编辑 HTML 核验、旧 PPT 翻新与按需原生 PPTX 交付。";
|
|
2300
|
+
function parseSkillMarkdown(raw) {
|
|
2301
|
+
const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
|
|
2302
|
+
if (match === null) return {
|
|
2303
|
+
name: "oil-slide",
|
|
2304
|
+
description: DEFAULT_DESCRIPTION,
|
|
2305
|
+
body: raw.trim(),
|
|
2306
|
+
metadata: {}
|
|
2307
|
+
};
|
|
2308
|
+
const header = match[1] ?? "";
|
|
2309
|
+
const body = (match[2] ?? "").trim();
|
|
2310
|
+
const metadata = {};
|
|
2311
|
+
let name = "oil-slide";
|
|
2312
|
+
let description = DEFAULT_DESCRIPTION;
|
|
2313
|
+
for (const line of header.split(/\r?\n/)) {
|
|
2314
|
+
const kv = line.match(/^([a-zA-Z0-9_-]+):\s*(.*)$/);
|
|
2315
|
+
if (kv === null) continue;
|
|
2316
|
+
const key = kv[1]?.trim() ?? "";
|
|
2317
|
+
let value = (kv[2] ?? "").trim();
|
|
2318
|
+
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
2319
|
+
if (key === "name" && value !== "") name = value;
|
|
2320
|
+
else if (key === "description" && value !== "") description = value;
|
|
2321
|
+
else if (key !== "" && value !== "") metadata[key] = value;
|
|
2322
|
+
}
|
|
2323
|
+
return {
|
|
2324
|
+
name,
|
|
2325
|
+
description,
|
|
2326
|
+
body,
|
|
2327
|
+
metadata
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
const DSH_PLUGIN_APPENDIX = `
|
|
2331
|
+
|
|
2332
|
+
## DeepSeek Harness 插件工具与宿主适配(dsh-oil-slide)
|
|
2333
|
+
|
|
2334
|
+
- **反问工具映射**:需要前期澄清少量关键前提时,使用宿主原生 \`ask_user_question\` 工具结构化提问,无需长段文字追问。
|
|
2335
|
+
- **生图执行路径**:PPT 样稿与成稿通过 slide_workflow.py render-draft / render-page 请求「生图设置」中的模型顺序,转换素材使用同一配置的 editppt image。发生自动切换时,向用户说明实际使用的备用模型。未配置或全部模型失败时,保留当前进度并提示检查渠道。
|
|
2336
|
+
- 大纲阶段让用户在右侧编辑、选择品牌资料及样稿数量。需要对话确认时只发一道单选题,使用当前状态的 outlineQuestionId 作为 id,接受面板提交的最新版本、页码和数量。生成前重新读取状态。
|
|
2337
|
+
- 圈选修改在幻灯片预览中直接生成候选并由用户决定是否采用。更新可编辑版时按 editable-prepare 返回的 changed 页码映射重建,若没有变化则直接 editable-finalize。
|
|
2338
|
+
- **风格选择题与右侧设计图共用一个回答**:每轮样稿齐全后读取 slide-workflow.json 的 reviewId。使用宿主的结构化提问工具发一道单选题,id 必须逐字使用 reviewId,选项以“设计稿 1 · …”“设计稿 2 · …”(英文 “Design 1 · …”)标明对应候选编号。接受自由填写的改稿、换组或恢复历史版本要求;完成后刷新面板,用新的 reviewId 重新提问。用户采用后只执行一次 approve-style,使用选中候选的当前 SHA。成稿和可编辑结果使用 canvas 预览,设计稿使用 reference。
|
|
2339
|
+
- **自动展开右侧预览栏(重要)**:每当生成或更新参考设计稿(如 \`s1.png\` / \`deck-2x2.png\`)、组装或更新 \`web/index.html\`、或导出 \`.pptx\` 后,**必须立即调用 \`oil_slide_open_preview\`**(传入 \`deckRelPath\` 和 \`tab: "reference"\` 或 \`"canvas"\`),自动展开并刷新右侧 Oil Slide 预览面板给用户查看。
|
|
2340
|
+
- 执行脚本前若不确定本机依赖,可调用 \`oil_slide_doctor\` 检查 Python 3.10+、Pillow、python-pptx、Playwright/Chromium 与生图凭据状态。
|
|
2341
|
+
- 需要将 \`web/index.html\` 编译为原生可编辑 \`.pptx\` 时,可直接调用 \`oil_slide_compile_pptx\`(支持 \`background: true\` 托管至后台任务,完成后会自动刷新右侧预览)。
|
|
2342
|
+
`;
|
|
2343
|
+
function createOilSlideSkillProvider(assets) {
|
|
2344
|
+
const resourceBase = {
|
|
2345
|
+
kind: "directory",
|
|
2346
|
+
path: assets.skillDir
|
|
2347
|
+
};
|
|
2348
|
+
return {
|
|
2349
|
+
name: OIL_SLIDE_PROVIDER_NAME,
|
|
2350
|
+
async list() {
|
|
2351
|
+
const parsed = parseSkillMarkdown(await readFile(assets.skillFile, "utf8"));
|
|
2352
|
+
return [{
|
|
2353
|
+
name: parsed.name,
|
|
2354
|
+
description: parsed.description,
|
|
2355
|
+
path: assets.skillFile,
|
|
2356
|
+
invocation: {
|
|
2357
|
+
modelInvocable: true,
|
|
2358
|
+
userInvocable: true
|
|
2359
|
+
},
|
|
2360
|
+
provider: OIL_SLIDE_PROVIDER_NAME,
|
|
2361
|
+
source: "bundled",
|
|
2362
|
+
resourceBase,
|
|
2363
|
+
rank: BUNDLED_SKILL_RANK,
|
|
2364
|
+
locator: pathToFileURL(assets.skillFile),
|
|
2365
|
+
metadata: parsed.metadata
|
|
2366
|
+
}];
|
|
2367
|
+
},
|
|
2368
|
+
async get(candidate) {
|
|
2369
|
+
const parsed = parseSkillMarkdown(await readFile(assets.skillFile, "utf8"));
|
|
2370
|
+
return {
|
|
2371
|
+
name: candidate.name,
|
|
2372
|
+
description: candidate.description,
|
|
2373
|
+
path: assets.skillFile,
|
|
2374
|
+
invocation: candidate.invocation,
|
|
2375
|
+
provider: candidate.provider,
|
|
2376
|
+
source: candidate.source,
|
|
2377
|
+
resourceBase,
|
|
2378
|
+
content: `${parsed.body}${DSH_PLUGIN_APPENDIX}`,
|
|
2379
|
+
metadata: parsed.metadata
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
function registerOilSlideSkill(ctx, assets) {
|
|
2385
|
+
const provider = createOilSlideSkillProvider(assets);
|
|
2386
|
+
return ctx.skills.registerProvider(() => provider);
|
|
2387
|
+
}
|
|
2388
|
+
// src/host/tools.ts
|
|
2389
|
+
const JSON_VALUE = { type: "json" };
|
|
2390
|
+
function asJson(value) {
|
|
2391
|
+
return JSON.parse(JSON.stringify(value));
|
|
2392
|
+
}
|
|
2393
|
+
function resolveSessionWorkspace(ctx, exec, explicit) {
|
|
2394
|
+
if (typeof explicit === "string" && explicit.trim() !== "") return explicit.trim();
|
|
2395
|
+
const session = exec.agent?.session;
|
|
2396
|
+
const wd = ctx.get?.("workingDirectory");
|
|
2397
|
+
if (session !== void 0 && typeof wd?.get === "function") try {
|
|
2398
|
+
const cwd = wd.get(session);
|
|
2399
|
+
if (typeof cwd === "string" && cwd.trim() !== "") return cwd;
|
|
2400
|
+
} catch {}
|
|
2401
|
+
if (typeof wd?.defaultDirectory === "string" && wd.defaultDirectory.trim() !== "") return wd.defaultDirectory;
|
|
2402
|
+
}
|
|
2403
|
+
function presentCall(title, kind, rawInput) {
|
|
2404
|
+
return {
|
|
2405
|
+
card: "generic",
|
|
2406
|
+
title,
|
|
2407
|
+
kind,
|
|
2408
|
+
rawInput
|
|
2409
|
+
};
|
|
2410
|
+
}
|
|
2411
|
+
function registerOilSlideTools(ctx, service) {
|
|
2412
|
+
const disposers = [];
|
|
2413
|
+
disposers.push(ctx.tools.register(defineTool({
|
|
2414
|
+
name: "oil_slide_doctor",
|
|
2415
|
+
description: "Check local Oil Slide (oil-slide) environment readiness: Python 3.10+, Pillow, python-pptx, Playwright/Chromium, oil-slide scripts, and the custom image channel configuration.",
|
|
2416
|
+
parameters: {},
|
|
2417
|
+
isConcurrencySafe: () => true,
|
|
2418
|
+
output: {
|
|
2419
|
+
schema: JSON_VALUE,
|
|
2420
|
+
render: (_args, value) => {
|
|
2421
|
+
const report = value;
|
|
2422
|
+
const lines = (report.checks ?? []).map((c) => {
|
|
2423
|
+
const tag = c.status === "ok" ? "[OK]" : c.status === "warn" ? "[WARN]" : "[MISSING]";
|
|
2424
|
+
const fix = c.fixHint ? ` -> ${c.fixHint}` : "";
|
|
2425
|
+
return `${tag} ${c.label}: ${c.detail}${fix}`;
|
|
2426
|
+
});
|
|
2427
|
+
return [{
|
|
2428
|
+
type: "text",
|
|
2429
|
+
text: `Oil Slide Doctor (${report.ok ? "ready" : "missing dependencies"}):\n${lines.join("\n")}`
|
|
2430
|
+
}];
|
|
2431
|
+
}
|
|
2432
|
+
},
|
|
2433
|
+
presentCall: (args) => presentCall("Oil Slide 环境体检", "other", args),
|
|
2434
|
+
execute: (_args, exec) => service.runDoctor({}, exec.signal).then(asJson)
|
|
2435
|
+
})));
|
|
2436
|
+
disposers.push(ctx.tools.register(defineTool({
|
|
2437
|
+
name: "oil_slide_compile_pptx",
|
|
2438
|
+
description: "Compile a deck's web/index.html into an editable native PowerPoint (.pptx) using oil-slide/scripts/html_to_pptx.py --audit. Supports optional background execution via DSH jobs.",
|
|
2439
|
+
parameters: {
|
|
2440
|
+
deckRelPath: {
|
|
2441
|
+
type: "string",
|
|
2442
|
+
description: "Deck directory path relative to the workspace root (e.g. '.' or 'decks/my-deck'). Defaults to '.'."
|
|
2443
|
+
},
|
|
2444
|
+
outRelPath: {
|
|
2445
|
+
type: "string",
|
|
2446
|
+
description: "Optional output .pptx path relative to the workspace root. Defaults to '<deckRelPath>/dist/deck.pptx'."
|
|
2447
|
+
},
|
|
2448
|
+
workspaceRoot: {
|
|
2449
|
+
type: "string",
|
|
2450
|
+
description: "Optional absolute workspace directory override."
|
|
2451
|
+
},
|
|
2452
|
+
background: {
|
|
2453
|
+
type: "boolean",
|
|
2454
|
+
description: "When true and DSH jobs service is available, run compilation as a background job and return a jobId."
|
|
2455
|
+
}
|
|
2456
|
+
},
|
|
2457
|
+
output: {
|
|
2458
|
+
schema: JSON_VALUE,
|
|
2459
|
+
render: (_args, value) => {
|
|
2460
|
+
const res = value;
|
|
2461
|
+
if (res.kind === "background" && typeof res.jobId === "string") return [{
|
|
2462
|
+
type: "text",
|
|
2463
|
+
text: `Started background PPTX compile job ${res.jobId}. Use job_output(wait=true) to await completion.`
|
|
2464
|
+
}];
|
|
2465
|
+
if (res.ok) return [{
|
|
2466
|
+
type: "text",
|
|
2467
|
+
text: `Compiled PPTX successfully: ${res.pptxRelPath ?? "dist/deck.pptx"} (${res.durationMs ?? 0}ms). You can deliver it to the user with present.`
|
|
2468
|
+
}];
|
|
2469
|
+
return [{
|
|
2470
|
+
type: "text",
|
|
2471
|
+
text: `PPTX compile failed: ${res.error ?? "unknown error"}`
|
|
2472
|
+
}];
|
|
2473
|
+
}
|
|
2474
|
+
},
|
|
2475
|
+
presentCall: (args) => presentCall("编译原生 PPTX", "execute", args),
|
|
2476
|
+
async execute(args, exec) {
|
|
2477
|
+
const workspaceRoot = resolveSessionWorkspace(ctx, exec, typeof args.workspaceRoot === "string" ? args.workspaceRoot : void 0);
|
|
2478
|
+
const deckRelPath = typeof args.deckRelPath === "string" && args.deckRelPath.trim() !== "" ? args.deckRelPath.trim() : ".";
|
|
2479
|
+
const outRelPath = typeof args.outRelPath === "string" && args.outRelPath.trim() !== "" ? args.outRelPath.trim() : void 0;
|
|
2480
|
+
if (args.background === true) {
|
|
2481
|
+
const jobs = ctx.get?.("jobs");
|
|
2482
|
+
if (jobs !== void 0 && typeof jobs.start === "function") return asJson({
|
|
2483
|
+
kind: "background",
|
|
2484
|
+
jobId: jobs.start({
|
|
2485
|
+
kind: "oil-slide",
|
|
2486
|
+
label: `Compile PPTX (${deckRelPath})`,
|
|
2487
|
+
run: () => {
|
|
2488
|
+
const controller = new AbortController();
|
|
2489
|
+
return {
|
|
2490
|
+
done: (async () => {
|
|
2491
|
+
try {
|
|
2492
|
+
const compiled = await service.compileDeckPptx({
|
|
2493
|
+
...workspaceRoot !== void 0 ? { workspaceRoot } : {},
|
|
2494
|
+
deckRelPath,
|
|
2495
|
+
...outRelPath !== void 0 ? { outRelPath } : {}
|
|
2496
|
+
}, controller.signal);
|
|
2497
|
+
if (compiled.ok) {
|
|
2498
|
+
service.notifyPreview({
|
|
2499
|
+
deckRelPath,
|
|
2500
|
+
tab: "canvas",
|
|
2501
|
+
workspaceRoot
|
|
2502
|
+
});
|
|
2503
|
+
return {
|
|
2504
|
+
status: "completed",
|
|
2505
|
+
detail: compiled.pptxRelPath,
|
|
2506
|
+
result: `Compiled ${compiled.pptxRelPath} in ${compiled.durationMs}ms`
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
return {
|
|
2510
|
+
status: "failed",
|
|
2511
|
+
detail: deckRelPath,
|
|
2512
|
+
result: compiled.error ?? compiled.stderr ?? "PPTX compile failed"
|
|
2513
|
+
};
|
|
2514
|
+
} catch (cause) {
|
|
2515
|
+
if (controller.signal.aborted) return {
|
|
2516
|
+
status: "killed",
|
|
2517
|
+
detail: deckRelPath,
|
|
2518
|
+
result: "Cancelled"
|
|
2519
|
+
};
|
|
2520
|
+
return {
|
|
2521
|
+
status: "failed",
|
|
2522
|
+
detail: deckRelPath,
|
|
2523
|
+
result: cause instanceof Error ? cause.message : String(cause)
|
|
2524
|
+
};
|
|
2525
|
+
}
|
|
2526
|
+
})(),
|
|
2527
|
+
cancel: (reason) => {
|
|
2528
|
+
if (!controller.signal.aborted) controller.abort(new Error(reason ?? "cancelled"));
|
|
2529
|
+
}
|
|
2530
|
+
};
|
|
2531
|
+
}
|
|
2532
|
+
}),
|
|
2533
|
+
deckRelPath
|
|
2534
|
+
});
|
|
2535
|
+
}
|
|
2536
|
+
const compiled = await service.compileDeckPptx({
|
|
2537
|
+
...workspaceRoot !== void 0 ? { workspaceRoot } : {},
|
|
2538
|
+
deckRelPath,
|
|
2539
|
+
...outRelPath !== void 0 ? { outRelPath } : {}
|
|
2540
|
+
}, exec.signal);
|
|
2541
|
+
if (compiled.ok) service.notifyPreview({
|
|
2542
|
+
deckRelPath,
|
|
2543
|
+
tab: "canvas",
|
|
2544
|
+
workspaceRoot
|
|
2545
|
+
});
|
|
2546
|
+
return asJson(compiled);
|
|
2547
|
+
}
|
|
2548
|
+
})));
|
|
2549
|
+
disposers.push(ctx.tools.register(defineTool({
|
|
2550
|
+
name: "oil_slide_open_preview",
|
|
2551
|
+
description: "Expand the right-sidebar Oil Slide preview panel in DeepSeek Harness and refresh the deck view (switching to 'reference' for Stage-1 design drafts or 'canvas' for the live 16:9 HTML deck). Call this immediately after generating or updating reference images, HTML slides, or PPTX.",
|
|
2552
|
+
parameters: {
|
|
2553
|
+
deckRelPath: {
|
|
2554
|
+
type: "string",
|
|
2555
|
+
description: "Deck directory path relative to the workspace root (e.g. 'decks/my-deck' or '.'). Optional."
|
|
2556
|
+
},
|
|
2557
|
+
tab: {
|
|
2558
|
+
type: "string",
|
|
2559
|
+
enum: [
|
|
2560
|
+
"auto",
|
|
2561
|
+
"reference",
|
|
2562
|
+
"canvas"
|
|
2563
|
+
],
|
|
2564
|
+
description: "Preferred view tab: 'reference' for design draft images, 'canvas' for live HTML slides, or 'auto'. Defaults to 'auto'."
|
|
2565
|
+
},
|
|
2566
|
+
workspaceRoot: {
|
|
2567
|
+
type: "string",
|
|
2568
|
+
description: "Optional absolute workspace directory override."
|
|
2569
|
+
}
|
|
2570
|
+
},
|
|
2571
|
+
isConcurrencySafe: () => true,
|
|
2572
|
+
output: {
|
|
2573
|
+
schema: JSON_VALUE,
|
|
2574
|
+
render: (_args, value) => {
|
|
2575
|
+
const sig = value;
|
|
2576
|
+
return [{
|
|
2577
|
+
type: "text",
|
|
2578
|
+
text: `Opened Oil Slide right-sidebar preview${sig.deckRelPath ? ` (${sig.deckRelPath})` : ""} on tab=${sig.tab ?? "auto"}.`
|
|
2579
|
+
}];
|
|
2580
|
+
}
|
|
2581
|
+
},
|
|
2582
|
+
presentCall: (args) => presentCall("展开 Oil Slide 预览栏", "other", args),
|
|
2583
|
+
async execute(args, exec) {
|
|
2584
|
+
const workspaceRoot = resolveSessionWorkspace(ctx, exec, typeof args.workspaceRoot === "string" ? args.workspaceRoot : void 0);
|
|
2585
|
+
const deckRelPath = typeof args.deckRelPath === "string" && args.deckRelPath.trim() !== "" ? args.deckRelPath.trim() : null;
|
|
2586
|
+
const rawTab = typeof args.tab === "string" ? args.tab : "auto";
|
|
2587
|
+
const tab = rawTab === "reference" || rawTab === "canvas" ? rawTab : "auto";
|
|
2588
|
+
return asJson({
|
|
2589
|
+
ok: true,
|
|
2590
|
+
...service.notifyPreview({
|
|
2591
|
+
deckRelPath,
|
|
2592
|
+
tab,
|
|
2593
|
+
workspaceRoot
|
|
2594
|
+
})
|
|
2595
|
+
});
|
|
2596
|
+
}
|
|
2597
|
+
})));
|
|
2598
|
+
return disposers;
|
|
2599
|
+
}
|
|
2600
|
+
// src/host/typert.host.ts
|
|
2601
|
+
const TYPERT = {
|
|
2602
|
+
package: PACKAGE_NAME,
|
|
2603
|
+
face: "host",
|
|
2604
|
+
schemas: [],
|
|
2605
|
+
model: {
|
|
2606
|
+
services: [],
|
|
2607
|
+
events: [],
|
|
2608
|
+
objects: []
|
|
2609
|
+
},
|
|
2610
|
+
invocations: OIL_SLIDE_INVOCATIONS
|
|
2611
|
+
};
|
|
2612
|
+
function registerOilSlideRoutes(registry) {
|
|
2613
|
+
if (!registry.getPackage("@dickpy/dsh-oil-slide", "host")) return registry.register(TYPERT);
|
|
2614
|
+
const invocations = TYPERT.invocations.filter(({ namespace, method }) => registry.local.get(`${namespace}/${method}`) === void 0);
|
|
2615
|
+
if (invocations.length === 0) return () => {};
|
|
2616
|
+
return registry.register({
|
|
2617
|
+
...TYPERT,
|
|
2618
|
+
package: `${PACKAGE_NAME}-additional-routes`,
|
|
2619
|
+
invocations
|
|
2620
|
+
});
|
|
2621
|
+
}
|
|
2622
|
+
// src/host/index.ts
|
|
2623
|
+
const name = PACKAGE_NAME;
|
|
2624
|
+
const Config = Schema.object({ defaultWorkspaceRoot: Schema.string().description("Optional fallback workspace directory when no session cwd is provided.") });
|
|
2625
|
+
function apply(ctx, config = {}) {
|
|
2626
|
+
const assets = resolvePluginAssets();
|
|
2627
|
+
const service = new OilSlideService(ctx, config, assets);
|
|
2628
|
+
ctx.inject(["typert"], (typertCtx) => {
|
|
2629
|
+
typertCtx.effect(() => registerOilSlideRoutes(typertCtx.typert), "oil-slide: host remote routes");
|
|
2630
|
+
});
|
|
2631
|
+
ctx.inject(["skills"], (skillsCtx) => {
|
|
2632
|
+
registerOilSlideSkill(skillsCtx, assets);
|
|
2633
|
+
});
|
|
2634
|
+
ctx.inject(["tools"], (toolsCtx) => {
|
|
2635
|
+
registerOilSlideTools(toolsCtx, service);
|
|
2636
|
+
});
|
|
2637
|
+
}
|
|
2638
|
+
export { Config, apply, name };
|