@penguinharness/multimodal-tools 0.0.0-stage → 0.2.19

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.
@@ -0,0 +1,112 @@
1
+ import type { WorkbenchPackage } from "@prismshadow/penguin-server/plugin";
2
+
3
+ type Job = {
4
+ id: string;
5
+ sessionId: string;
6
+ prompt: string;
7
+ ratio: string;
8
+ created: string;
9
+ failure?: string;
10
+ stopRequested?: boolean;
11
+ };
12
+ const ratios = new Set(["1:1", "16:9", "9:16", "4:3", "3:4"]);
13
+ const idPattern = /^[a-z\d-]{36}$/i;
14
+
15
+ export default {
16
+ modules: {
17
+ Workbench: {
18
+ create({ use }) {
19
+ const host = use.host;
20
+ const all = (): Job[] => {
21
+ const stored = host.getState() as { jobs?: Job[] } | null;
22
+ return Array.isArray(stored?.jobs) ? stored.jobs : [];
23
+ };
24
+ // Starting or retrying in two windows must never create a second Session
25
+ // for the same request, or overwrite another window's history.
26
+ let pending: Promise<unknown> = Promise.resolve();
27
+ function change<T>(operation: () => Promise<T>) {
28
+ const result = pending.then(operation, operation);
29
+ pending = result.catch(() => undefined);
30
+ return result;
31
+ }
32
+ return {
33
+ api: {
34
+ main: {
35
+ async handle(req) {
36
+ if (req.method === "GET" && req.path === "/jobs") return { body: { jobs: all() } };
37
+ if (req.method === "POST" && req.path === "/jobs") {
38
+ const body = (req.body ?? {}) as Partial<{
39
+ id: string;
40
+ prompt: string;
41
+ ratio: string;
42
+ lang: string;
43
+ }>;
44
+ const prompt = typeof body.prompt === "string" ? body.prompt.trim() : "";
45
+ const { id, ratio } = body;
46
+ if (
47
+ !id ||
48
+ !idPattern.test(id) ||
49
+ !prompt ||
50
+ prompt.length > 6000 ||
51
+ !ratio ||
52
+ !ratios.has(ratio)
53
+ ) {
54
+ return { status: 400, body: { error: "invalidBrief" } };
55
+ }
56
+ return change(async () => {
57
+ const existing = all().find((j) => j.id === id);
58
+ if (existing) return { body: { job: existing } };
59
+ const { sessionId } = await host.createSession();
60
+ const job: Job = {
61
+ id,
62
+ sessionId,
63
+ prompt,
64
+ ratio,
65
+ created: new Date().toISOString(),
66
+ };
67
+ await host.setState({ jobs: [job, ...all()] });
68
+ const language = body.lang === "zh" ? "Chinese" : "English";
69
+ // The run belongs to this Session: the CLI reads it from the Agent's environment,
70
+ // and Image Studio shows the images the Session's runs stored.
71
+ const instructions = [
72
+ "[use_skills]\nskills: multimodal-tools\n[/use_skills]\n",
73
+ "Generate one image with the Project's image model: run penguin tools t2i with the image brief as one literal argument, --aspect-ratio, --out image-studio and --json. Your response must describe the real tool result or its failure.",
74
+ `Aspect ratio: ${ratio}. Respond in ${language}.`,
75
+ "Image brief (JSON string): " + JSON.stringify(prompt),
76
+ ].join("\n");
77
+ try {
78
+ await host.run(sessionId, [{ text: instructions }]);
79
+ } catch (e) {
80
+ job.failure = e instanceof Error ? e.message : String(e);
81
+ await host.setState({ jobs: all().map((j) => (j.id === id ? job : j)) });
82
+ }
83
+ return { body: { job } };
84
+ });
85
+ }
86
+ const match = /^\/jobs\/([a-z\d-]{36})(\/stop-requested)?$/i.exec(req.path);
87
+ if (!match) return { status: 404, body: { error: "notFound" } };
88
+ const job = all().find((j) => j.id === match[1]);
89
+ if (!job) return { status: 404, body: { error: "notFound" } };
90
+ if (req.method === "GET" && !match[2]) {
91
+ const session = job.failure
92
+ ? { status: "failed", text: "", error: job.failure }
93
+ : await host.sessionResult(job.sessionId);
94
+ return { body: { job, session } };
95
+ }
96
+ if (req.method === "POST" && match[2])
97
+ return change(async () => {
98
+ const jobs = all().map((j) =>
99
+ j.id === job.id ? { ...j, stopRequested: true } : j,
100
+ );
101
+ await host.setState({ jobs });
102
+ return { body: { ok: true } };
103
+ });
104
+ return { status: 405, body: { error: "method" } };
105
+ },
106
+ },
107
+ },
108
+ };
109
+ },
110
+ },
111
+ },
112
+ } satisfies WorkbenchPackage;
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "image-studio-workbench",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "penguin": {
6
+ "version": "2026.11.19.2",
7
+ "appCenter": {
8
+ "show": true,
9
+ "icon": "ui/icon.svg",
10
+ "title": "Image Studio",
11
+ "titleZh": "\u56fe\u50cf\u5de5\u4f5c\u5ba4"
12
+ },
13
+ "modules": [
14
+ {
15
+ "name": "Workbench",
16
+ "requires": {
17
+ "host": {
18
+ "iface": "@prismshadow/penguin-server#WorkbenchHost",
19
+ "from": "Host"
20
+ }
21
+ },
22
+ "provides": {
23
+ "main": "@prismshadow/penguin-server#WorkbenchMain"
24
+ },
25
+ "contributes": {
26
+ "WebModule.sessionTabs": [
27
+ {
28
+ "id": "images.main",
29
+ "key": "main",
30
+ "title": "Image Studio",
31
+ "titleZh": "\u56fe\u50cf\u5de5\u4f5c\u5ba4",
32
+ "renderer": {
33
+ "iframe": {
34
+ "src": "ui/index.html"
35
+ }
36
+ }
37
+ }
38
+ ]
39
+ }
40
+ }
41
+ ]
42
+ }
43
+ }
@@ -0,0 +1,248 @@
1
+ import { lang, S } from "./strings.js";
2
+ const $ = (id) => document.getElementById(id);
3
+ document.documentElement.lang = lang;
4
+ document.title = S.title;
5
+ for (const el of document.querySelectorAll("[data-label]")) el.textContent = S[el.dataset.label];
6
+ $("prompt").placeholder = S.placeholder;
7
+ for (const [title, prompt] of S.ideas) {
8
+ const button = document.createElement("button");
9
+ button.type = "button";
10
+ button.textContent = title;
11
+ button.onclick = () => {
12
+ $("prompt").value = prompt;
13
+ $("prompt").focus();
14
+ };
15
+ $("ideas").append(button);
16
+ }
17
+ // The page SDK the server serves beside this workbench: `apiBase` is the API of the server this
18
+ // page came from ("/api", "/server/<machine>/api", or whatever a proxy put in front), and
19
+ // `abortSession` stops the driving Session. Imported by a name in a variable, so that no tool
20
+ // tries to resolve the served file ahead of time.
21
+ const SDK = "../sdk/workbench.js";
22
+ const PLUGIN = "@penguinharness/multimodal-tools";
23
+ let sdk = null,
24
+ tools = "",
25
+ bindingsUrl = "";
26
+ /** Loads the page SDK and names this Project's routes under its API. */
27
+ async function connect() {
28
+ if (sdk) return;
29
+ const loaded = await import(SDK);
30
+ // The page is served at <apiBase>/projects/<project>/agents/…: the Project is the segment
31
+ // after the runtime's API base.
32
+ const prefix = loaded.apiBase + "/projects/";
33
+ if (!location.pathname.startsWith(prefix)) throw new Error(S.unavailable);
34
+ const project = location.pathname.slice(prefix.length).split("/")[0];
35
+ tools = prefix + project + "/multimodal-tools";
36
+ bindingsUrl = prefix + project + "/models/tool-bindings";
37
+ sdk = loaded;
38
+ }
39
+ const sessionPath = (sessionId) => tools + "/sessions/" + encodeURIComponent(sessionId);
40
+ const placeholder = $("stage").firstElementChild;
41
+ let jobs = [],
42
+ current = null,
43
+ binding = null,
44
+ generation = 0,
45
+ timer,
46
+ stopping = false,
47
+ submitting = false,
48
+ retry = null;
49
+ async function request(url, method = "GET", body) {
50
+ const res = await fetch(url, {
51
+ method,
52
+ credentials: "same-origin",
53
+ ...(body
54
+ ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
55
+ : {}),
56
+ });
57
+ if (!res.ok) {
58
+ const payload = await res.json().catch(() => null);
59
+ throw new Error(payload?.error?.message || S.requestFailed);
60
+ }
61
+ return res.status === 204 ? null : res.json();
62
+ }
63
+ function problem(message) {
64
+ $("error").textContent = message;
65
+ $("error").hidden = !message;
66
+ }
67
+ function stage(message, detail = "") {
68
+ $("stage").replaceChildren(placeholder);
69
+ $("status").textContent = message;
70
+ $("downloads").replaceChildren();
71
+ $("detail").textContent = detail;
72
+ $("detail").hidden = !detail;
73
+ }
74
+ function showHistory() {
75
+ $("jobs").replaceChildren(
76
+ new Option(S.new, ""),
77
+ ...jobs.map((job) => new Option(job.prompt, job.id)),
78
+ );
79
+ $("jobs").value = current?.id || "";
80
+ }
81
+ function choose(job) {
82
+ current = job;
83
+ const serial = ++generation;
84
+ clearTimeout(timer);
85
+ stopping = false;
86
+ $("stop").hidden = true;
87
+ problem("");
88
+ showHistory();
89
+ if (!job) {
90
+ $("prompt").value = "";
91
+ $("ratio").value = "1:1";
92
+ stage(S.idle);
93
+ return;
94
+ }
95
+ $("prompt").value = job.prompt;
96
+ $("ratio").value = job.ratio;
97
+ stage(S.running);
98
+ void refresh(job, serial);
99
+ }
100
+ /** Where an image the Session's runs generated is downloaded; null for any other file. */
101
+ function linkedImage(file, sessionId) {
102
+ if (file.operation !== "t2i" || !/^image\/(?:png|jpe?g|webp|gif|avif)$/i.test(file.mimeType))
103
+ return null;
104
+ return sessionPath(sessionId) + "/files/" + encodeURIComponent(file.name);
105
+ }
106
+ function renderImages(images, job) {
107
+ const elements = [],
108
+ links = [];
109
+ for (const [index, { file, url }] of images.entries()) {
110
+ const img = new Image();
111
+ img.src = url;
112
+ img.alt = job.prompt;
113
+ if (index > 0) img.loading = "lazy";
114
+ const link = document.createElement("a");
115
+ link.className = "download";
116
+ link.href = url;
117
+ link.download = file.name;
118
+ link.textContent = S.download + " · " + file.name;
119
+ elements.push(img);
120
+ links.push(link);
121
+ }
122
+ $("stage").replaceChildren(...elements);
123
+ $("downloads").replaceChildren(...links);
124
+ $("detail").hidden = true;
125
+ }
126
+ async function refresh(job, serial) {
127
+ clearTimeout(timer);
128
+ try {
129
+ await connect();
130
+ const [{ session, job: serverJob }, { runs }, { files }] = await Promise.all([
131
+ request("../api/jobs/" + job.id),
132
+ request(sessionPath(job.sessionId) + "/runs"),
133
+ request(sessionPath(job.sessionId) + "/files"),
134
+ ]);
135
+ if (serial !== generation) return;
136
+ const imageRuns = runs.filter((r) => r.operation === "t2i");
137
+ const active = imageRuns.some((r) => r.status === "running");
138
+ const working = session.status === "running" || active;
139
+ const images = files
140
+ .map((file) => ({ file, url: linkedImage(file, job.sessionId) }))
141
+ .filter((x) => x.url);
142
+ const cancelled =
143
+ imageRuns.some((r) => r.status === "cancelled") || (serverJob.stopRequested && !working);
144
+ const failed = imageRuns.find((r) => r.status === "failed");
145
+ $("stop").hidden = !working;
146
+ $("stop").disabled = stopping || serverJob.stopRequested;
147
+ if (images.length) renderImages(images, job);
148
+ else if (working) stage(stopping || serverJob.stopRequested ? S.stopping : S.running);
149
+ else if (cancelled) stage(S.cancelled);
150
+ else stage(S.failed, failed?.error || session.error || session.text || "");
151
+ if (working) timer = setTimeout(() => void refresh(job, serial), 1400);
152
+ } catch (e) {
153
+ if (serial !== generation) return;
154
+ stage(S.retrieval, e.message);
155
+ timer = setTimeout(() => void refresh(job, serial), 4000);
156
+ }
157
+ }
158
+ $("jobs").onchange = () => choose(jobs.find((j) => j.id === $("jobs").value) || null);
159
+ $("brief").onsubmit = async (event) => {
160
+ event.preventDefault();
161
+ const prompt = $("prompt").value.trim(),
162
+ ratio = $("ratio").value;
163
+ if (submitting || !binding || !prompt) return;
164
+ const signature = JSON.stringify([prompt, ratio]);
165
+ if (retry?.signature !== signature) retry = { signature, id: crypto.randomUUID() };
166
+ submitting = true;
167
+ $("generate").disabled = true;
168
+ problem("");
169
+ try {
170
+ await refreshModel();
171
+ if (!binding) return;
172
+ const { job } = await request("../api/jobs", "POST", { id: retry.id, prompt, ratio, lang });
173
+ jobs = [job, ...jobs.filter((j) => j.id !== job.id)];
174
+ retry = null;
175
+ choose(job);
176
+ if (matchMedia("(max-width:720px)").matches)
177
+ document.querySelector(".preview").scrollIntoView({ block: "start" });
178
+ } catch (e) {
179
+ problem(e.message);
180
+ } finally {
181
+ submitting = false;
182
+ $("generate").disabled = !binding;
183
+ }
184
+ };
185
+ $("stop").onclick = async () => {
186
+ const job = current,
187
+ serial = generation;
188
+ if (!job || stopping) return;
189
+ stopping = true;
190
+ $("stop").disabled = true;
191
+ problem("");
192
+ try {
193
+ await connect();
194
+ // Stop the driving Session first so it cannot start another run while existing ones are cancelled.
195
+ const interrupted = await sdk.abortSession(job.sessionId).catch(() => {
196
+ throw new Error(S.requestFailed);
197
+ });
198
+ const { runs } = await request(sessionPath(job.sessionId) + "/runs");
199
+ const active = runs.filter((r) => r.operation === "t2i" && r.status === "running");
200
+ await Promise.all(
201
+ active.map((r) => request(tools + "/runs/" + encodeURIComponent(r.id), "DELETE")),
202
+ );
203
+ if (interrupted || active.length)
204
+ await request("../api/jobs/" + job.id + "/stop-requested", "POST", {});
205
+ if (serial === generation) await refresh(job, serial);
206
+ } catch (e) {
207
+ if (serial === generation) {
208
+ problem(e.message);
209
+ $("stop").disabled = false;
210
+ }
211
+ } finally {
212
+ if (serial === generation) stopping = false;
213
+ }
214
+ };
215
+ async function refreshModel() {
216
+ try {
217
+ await connect();
218
+ const { bindings } = await request(bindingsUrl);
219
+ // Listed only while the multimodal tools plugin is on in this Project.
220
+ const declared = bindings.find((b) => b.key === "t2i" && b.package === PLUGIN);
221
+ const active = declared !== undefined;
222
+ binding = declared?.model ?? null;
223
+ $("model").textContent = binding
224
+ ? binding.provider + " / " + binding.modelId
225
+ : active
226
+ ? S.unconfigured
227
+ : S.disabled;
228
+ } catch {
229
+ binding = null;
230
+ $("model").textContent = S.unavailable;
231
+ }
232
+ $("generate").disabled = submitting || !binding;
233
+ }
234
+
235
+ async function start() {
236
+ $("generate").disabled = true;
237
+ stage(S.idle);
238
+ const [, history] = await Promise.allSettled([refreshModel(), request("../api/jobs")]);
239
+ if (history.status === "fulfilled") {
240
+ jobs = history.value.jobs;
241
+ choose(jobs[0] || null);
242
+ } else {
243
+ showHistory();
244
+ problem(history.reason.message);
245
+ }
246
+ }
247
+ window.addEventListener("focus", () => void refreshModel());
248
+ void start();
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#4e5076"/><g transform="translate(4 4)" fill="none" stroke="#faf3e3" stroke-width="1.6" stroke-linejoin="round"><path d="M4.5 3.5h15a1.5 1.5 0 0 1 1.5 1.5v14a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 19V5a1.5 1.5 0 0 1 1.5-1.5z"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m3 16 5-4.5 4 3.5 3.5-5 5.5 7"/></g></svg>
@@ -0,0 +1,58 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
6
+ <title>Image Studio</title>
7
+ <link rel="stylesheet" href="style.css" />
8
+ </head>
9
+ <body>
10
+ <header>
11
+ <div class="identity">
12
+ <img src="icon.svg" alt="" width="32" height="32" />
13
+ <h1 data-label="title"></h1>
14
+ </div>
15
+ <div class="history">
16
+ <label for="jobs" data-label="history"></label
17
+ ><select id="jobs"></select>
18
+ </div>
19
+ </header>
20
+ <main>
21
+ <form id="brief">
22
+ <h2 data-label="brief"></h2>
23
+ <label for="prompt" data-label="prompt"></label
24
+ ><textarea id="prompt" rows="7" maxlength="6000" required></textarea>
25
+ <fieldset>
26
+ <legend data-label="try"></legend>
27
+ <div id="ideas"></div>
28
+ </fieldset>
29
+ <label for="ratio" data-label="ratio"></label
30
+ ><select id="ratio">
31
+ <option value="1:1">1:1</option>
32
+ <option value="16:9">16:9</option>
33
+ <option value="9:16">9:16</option>
34
+ <option value="4:3">4:3</option>
35
+ <option value="3:4">3:4</option>
36
+ </select>
37
+ <div class="binding"><span data-label="model"></span><span id="model"></span></div>
38
+ <button class="primary" id="generate" type="submit" data-label="generate"></button>
39
+ <p id="error" role="alert" hidden></p>
40
+ </form>
41
+ <section class="preview" aria-labelledby="preview-title">
42
+ <div class="topline">
43
+ <h2 id="preview-title" data-label="preview"></h2>
44
+ <button id="stop" type="button" hidden data-label="stop"></button>
45
+ </div>
46
+ <div id="stage">
47
+ <div class="placeholder">
48
+ <div class="frame" aria-hidden="true">▧</div>
49
+ <p id="status" role="status"></p>
50
+ </div>
51
+ </div>
52
+ <div id="downloads"></div>
53
+ <p id="detail" hidden></p>
54
+ </section>
55
+ </main>
56
+ <script type="module" src="app.js"></script>
57
+ </body>
58
+ </html>
@@ -0,0 +1,89 @@
1
+ const en = {
2
+ title: "Image Studio",
3
+ history: "History",
4
+ new: "New brief",
5
+ brief: "Image brief",
6
+ prompt: "Describe the image",
7
+ placeholder: "Subject, setting, style and any details to keep.",
8
+ try: "Starting points",
9
+ ratio: "Aspect ratio",
10
+ model: "Project image model",
11
+ generate: "Generate image",
12
+ preview: "Preview",
13
+ stop: "Cancel generation",
14
+ idle: "Your image will appear here.",
15
+ running: "Generating the image…",
16
+ stopping: "Cancellation requested…",
17
+ cancelled: "Generation cancelled.",
18
+ failed: "The Session finished without an image.",
19
+ disabled: "Turn on the multimodal tools plugin in this Project to start a new image.",
20
+ unconfigured: "Choose an image model in the project’s model settings.",
21
+ unavailable: "Cannot load the project’s image settings.",
22
+ requestFailed: "The request failed. Try again.",
23
+ download: "Download",
24
+ retrieval: "Cannot load the images from this Session.",
25
+ ideas: [
26
+ [
27
+ "Product photo",
28
+ "A studio photograph of a blue ceramic mug on warm linen, soft side light, uncluttered background.",
29
+ ],
30
+ [
31
+ "Nature illustration",
32
+ "A field-guide illustration of a puffin carrying fish, fine ink outlines and muted watercolors.",
33
+ ],
34
+ [
35
+ "Poster background",
36
+ "An abstract screen-printed poster background with overlapping circles, navy ink and terracotta paper. Leave space for a title.",
37
+ ],
38
+ ],
39
+ };
40
+ const zh = {
41
+ title: "图像工作室",
42
+ history: "历史记录",
43
+ new: "新建创作",
44
+ brief: "创作要求",
45
+ prompt: "描述想要的图像",
46
+ placeholder: "可以写主体、环境、风格和需要保留的细节。",
47
+ try: "试试这些主题",
48
+ ratio: "画幅比例",
49
+ model: "项目图像模型",
50
+ generate: "生成图像",
51
+ preview: "预览",
52
+ stop: "取消生成",
53
+ idle: "生成的图像会出现在这里。",
54
+ running: "正在生成图像…",
55
+ stopping: "已请求取消…",
56
+ cancelled: "已取消生成。",
57
+ failed: "会话已结束,没有生成图像。",
58
+ disabled: "请先在本项目启用多模态工具插件,再开始创作。",
59
+ unconfigured: "请先在项目模型设置中选择图像模型。",
60
+ unavailable: "无法读取项目的图像设置。",
61
+ requestFailed: "请求失败,请重试。",
62
+ download: "下载",
63
+ retrieval: "无法读取此次会话的图像。",
64
+ ideas: [
65
+ ["产品摄影", "一只蓝釉陶瓷杯放在暖色亚麻布上,柔和侧光,背景简洁,产品摄影。"],
66
+ ["自然插画", "一只嘴里叼着小鱼的海鹦,自然图鉴插画,细致墨线,柔和水彩。"],
67
+ ["海报背景", "丝网印刷风格的海报背景,用海军蓝墨和陶土色纸张叠印圆形,为标题留白。"],
68
+ ],
69
+ };
70
+ let parentRoot;
71
+ try {
72
+ if (window.parent !== window) parentRoot = window.parent.document.documentElement;
73
+ } catch {}
74
+ export const lang = (parentRoot?.lang || navigator.language).toLowerCase().startsWith("zh")
75
+ ? "zh"
76
+ : "en";
77
+ export const S = lang === "zh" ? zh : en;
78
+ function theme() {
79
+ const dark = parentRoot
80
+ ? parentRoot.classList.contains("dark") || parentRoot.dataset.theme === "dark"
81
+ : matchMedia("(prefers-color-scheme: dark)").matches;
82
+ document.documentElement.toggleAttribute("data-dark", dark);
83
+ }
84
+ theme();
85
+ if (parentRoot)
86
+ new MutationObserver(theme).observe(parentRoot, {
87
+ attributes: true,
88
+ attributeFilter: ["class", "data-theme"],
89
+ });