@logictan/dsh-stitch-designer 0.0.0-stage → 1.0.0

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/lib/store.js ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Local asset store behind the preview panel: the screenshot/HTML cache, the
3
+ * "last used project" state, and the per-project screen registry.
4
+ *
5
+ * Stitch's `list_screens` index lags behind generation by up to a couple of
6
+ * minutes, and `generate_screen_from_text` returns the finished screen in its
7
+ * own payload long before that index catches up. The cache and registry here
8
+ * are what let the panel show a design the moment it exists instead of showing
9
+ * an empty project — the failure the reference implementation was written to
10
+ * fix, and the reason `state.json` is persisted rather than held in memory
11
+ * (an in-memory `lastScreenId` is lost on every restart, blanking the panel).
12
+ *
13
+ * Everything lives under `~/.stitch`, the same location the reference plugin
14
+ * used, so an existing cache keeps working. The API key is deliberately NOT
15
+ * here: it belongs to the credentials file (see `src/index.js`).
16
+ *
17
+ * @module @logictan/dsh-stitch-designer/store
18
+ */
19
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
20
+ import { homedir } from 'node:os';
21
+ import { dirname, join } from 'node:path';
22
+
23
+ /** Root of the local cache. */
24
+ export const STITCH_HOME = join(homedir(), '.stitch');
25
+ /** Cached screenshots, served at `/stitch/screens/<id>.png`. */
26
+ export const SCREENS_DIR = join(STITCH_HOME, 'screens');
27
+ /** Exported 1:1 HTML sources, served at `/stitch/html/<id>.html`. */
28
+ export const HTML_DIR = join(STITCH_HOME, 'html');
29
+ /** Persisted project/screen state. */
30
+ export const STATE_FILE = join(STITCH_HOME, 'state.json');
31
+ /** Cap on remembered screen ids per project. */
32
+ const MAX_REMEMBERED_SCREENS = 50;
33
+
34
+ /**
35
+ * Read `state.json`, tolerating absence and corruption.
36
+ *
37
+ * A missing or malformed file means "no memory yet", which is a normal first
38
+ * run — not a failure worth surfacing, and definitely not one worth letting
39
+ * abort a panel refresh.
40
+ *
41
+ * @returns the parsed state, or an empty object.
42
+ */
43
+ export async function loadState() {
44
+ try {
45
+ const parsed = JSON.parse(await readFile(STATE_FILE, 'utf8'));
46
+ return parsed !== null && typeof parsed === 'object' ? parsed : {};
47
+ } catch {
48
+ return {};
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Merge a patch into `state.json`.
54
+ *
55
+ * Empty values never overwrite a stored one: callers pass whatever they happen
56
+ * to have in hand, and an uninitialised variable would otherwise erase the
57
+ * project the panel is supposed to remember.
58
+ *
59
+ * @param patch - fields to merge.
60
+ * @returns the merged state.
61
+ */
62
+ export async function saveState(patch) {
63
+ const previous = await loadState();
64
+ const next = { ...previous, ...patch };
65
+ if (!patch.projectId && previous.projectId) next.projectId = previous.projectId;
66
+ if (!patch.lastScreenId && previous.lastScreenId) next.lastScreenId = previous.lastScreenId;
67
+ try {
68
+ await mkdir(dirname(STATE_FILE), { recursive: true });
69
+ await writeFile(STATE_FILE, JSON.stringify(next, null, 2));
70
+ } catch {
71
+ // The state file is an optimisation; losing it degrades the panel to
72
+ // "whatever Stitch's index reports" and must not fail the request.
73
+ }
74
+ return next;
75
+ }
76
+
77
+ /**
78
+ * Screen ids this machine has already seen for one project.
79
+ *
80
+ * @param state - a loaded state object.
81
+ * @param projectId - the project id.
82
+ * @returns the remembered ids, oldest first.
83
+ */
84
+ export function knownScreenIds(state, projectId) {
85
+ const registry = state?.screensByProject?.[projectId];
86
+ return Array.isArray(registry) ? registry : [];
87
+ }
88
+
89
+ /**
90
+ * Record one screen id against its project.
91
+ *
92
+ * @param projectId - the project id.
93
+ * @param screenId - the screen id to remember.
94
+ */
95
+ export async function rememberScreenId(projectId, screenId) {
96
+ if (!projectId || !screenId) return;
97
+ const state = await loadState();
98
+ const registry = { ...(state.screensByProject ?? {}) };
99
+ const list = Array.isArray(registry[projectId]) ? [...registry[projectId]] : [];
100
+ if (!list.includes(screenId)) list.push(screenId);
101
+ registry[projectId] = list.slice(-MAX_REMEMBERED_SCREENS);
102
+ try {
103
+ await mkdir(dirname(STATE_FILE), { recursive: true });
104
+ await writeFile(STATE_FILE, JSON.stringify({ ...state, screensByProject: registry }, null, 2));
105
+ } catch {
106
+ // See saveState: a lost registry only costs the index-lag fallback.
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Upgrade a Google image URL to full resolution.
112
+ *
113
+ * Stitch hands out thumbnail URLs; `=s0` asks the image service for the
114
+ * original. Applied only when no size directive is already present, so a URL
115
+ * that already carries one is left alone.
116
+ *
117
+ * @param url - the download URL.
118
+ * @returns the URL to fetch.
119
+ */
120
+ export function hdImageUrl(url) {
121
+ const value = String(url ?? '');
122
+ return value.includes('googleusercontent.com') && !/=[sw]\d+/.test(value) ? `${value}=s0` : value;
123
+ }
124
+
125
+ /**
126
+ * Download a URL to a local path, creating parent directories.
127
+ *
128
+ * @param url - source URL.
129
+ * @param dest - absolute destination path.
130
+ * @returns the destination path.
131
+ * @throws when the response is not OK or the write fails.
132
+ */
133
+ export async function downloadTo(url, dest) {
134
+ const response = await fetch(hdImageUrl(url));
135
+ if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`);
136
+ await mkdir(dirname(dest), { recursive: true });
137
+ await writeFile(dest, Buffer.from(await response.arrayBuffer()));
138
+ return dest;
139
+ }
140
+
141
+ /**
142
+ * Cache one screen's screenshot and HTML source, best effort.
143
+ *
144
+ * A failed download is not an error: the panel falls back to the remote
145
+ * `downloadUrl`, and the next refresh retries. Only the returned record's
146
+ * shape matters to callers.
147
+ *
148
+ * @param screen - a Stitch screen object.
149
+ * @returns the screen's id, or `undefined` when it carries none.
150
+ */
151
+ export async function cacheScreenAssets(screen) {
152
+ const screenId = String(screen?.name ?? '').split('/').pop();
153
+ if (!screenId) return undefined;
154
+ if (screen?.screenshot?.downloadUrl) {
155
+ await downloadTo(screen.screenshot.downloadUrl, join(SCREENS_DIR, `${screenId}.png`)).catch(() => {});
156
+ }
157
+ if (screen?.htmlCode?.downloadUrl) {
158
+ await downloadTo(screen.htmlCode.downloadUrl, join(HTML_DIR, `${screenId}.html`)).catch(() => {});
159
+ }
160
+ return screenId;
161
+ }
162
+
163
+ /**
164
+ * Project one Stitch screen into the panel's row shape.
165
+ *
166
+ * @param screen - a Stitch screen object.
167
+ * @returns the panel row, or `undefined` when the screen carries no id.
168
+ */
169
+ export function toPanelScreen(screen) {
170
+ const screenId = String(screen?.name ?? '').split('/').pop();
171
+ if (!screenId) return undefined;
172
+ return {
173
+ name: screen.name,
174
+ id: screenId,
175
+ title: screen.title ?? '',
176
+ deviceType: screen.deviceType ?? '',
177
+ width: screen.width ?? '',
178
+ height: screen.height ?? '',
179
+ preview: `/stitch/screens/${screenId}.png`,
180
+ screenshotUrl: screen.screenshot?.downloadUrl ?? '',
181
+ htmlUrl: screen.htmlCode?.downloadUrl ?? '',
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Pull the freshly generated screen out of a `generate`/`edit` result.
187
+ *
188
+ * Stitch returns the finished screen inside
189
+ * `structuredContent.outputComponents[].design.screens[]` immediately, which is
190
+ * strictly earlier than `list_screens` will report it.
191
+ *
192
+ * @param result - the MCP result of a generate/edit call.
193
+ * @returns the first screen found, or `undefined`.
194
+ */
195
+ export function extractScreenFromResult(result) {
196
+ const components = result?.structuredContent?.outputComponents;
197
+ if (!Array.isArray(components)) return undefined;
198
+ for (const component of components) {
199
+ const screens = component?.design?.screens;
200
+ if (Array.isArray(screens) && screens.length > 0) return screens[0];
201
+ }
202
+ return undefined;
203
+ }
204
+
205
+ /**
206
+ * Adopt a screen into the cache and the persisted state.
207
+ *
208
+ * @param projectId - the project the screen belongs to.
209
+ * @param screen - the Stitch screen object.
210
+ * @param source - provenance tag recorded for the panel (`list`, `generate`, ...).
211
+ * @returns the panel response, or `undefined` when the screen carries no id.
212
+ */
213
+ export async function adoptScreen(projectId, screen, source = 'list') {
214
+ const screenId = await cacheScreenAssets(screen);
215
+ if (screenId === undefined) return undefined;
216
+ await rememberScreenId(projectId, screenId);
217
+ await saveState({ projectId, lastScreenId: screenId });
218
+ return {
219
+ ok: true,
220
+ screenId,
221
+ title: screen.title ?? '',
222
+ deviceType: screen.deviceType ?? '',
223
+ width: screen.width ?? '',
224
+ height: screen.height ?? '',
225
+ preview: `/stitch/screens/${screenId}.png`,
226
+ html: `/stitch/html/${screenId}.html`,
227
+ source,
228
+ };
229
+ }
package/lib/tools.js ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Adaptation of Google Stitch's own MCP tool descriptors to DSH ToolRuntime
3
+ * definitions.
4
+ *
5
+ * This module is the whole reason the plugin exists as a host-side MCP host
6
+ * rather than a dependency on `@deepseek-ai/dsh-mcp-client`: Stitch's tool
7
+ * vocabulary is not the closed subset `dsh-tools` accepts, and the bridge has
8
+ * to decide field by field what to keep and what to drop.
9
+ *
10
+ * Two measured facts drive every choice here (probed against the live
11
+ * `tools/list` of 2026-10-08, all 15 tools):
12
+ *
13
+ * - `parameters` is passed through VERBATIM. `ToolRuntime.register` validates
14
+ * only `output.schema`; it never inspects `definition.parameters`. Stitch's
15
+ * input schemas carry `$defs` / `$ref` / `x-google-*` (11 of 15 fail
16
+ * `assertSupportedJsonSchema`), so routing them through `defineTool` — which
17
+ * validates its `parameters` at construction — would throw for 11 tools.
18
+ * Registering the raw schema is therefore not a shortcut, it is the only
19
+ * shape that keeps the upstream contract intact for the model.
20
+ * - `output.schema` IS validated, both at registration and again on every
21
+ * result (`createSuccessResult`). 13 of Stitch's 15 advertised
22
+ * `outputSchema`s are outside the accepted subset, so they must be dropped
23
+ * to the loose envelope below — the same fallback
24
+ * `@deepseek-ai/dsh-mcp-client`'s `supportedOutputSchema` performs.
25
+ *
26
+ * @module @logictan/dsh-stitch-designer/tools
27
+ */
28
+ import { createHash } from 'node:crypto';
29
+
30
+ import { assertSupportedJsonSchema } from '@deepseek-ai/dsh-tools';
31
+
32
+ /** DeepSeek function-name contract: at most 64 characters. */
33
+ const MAX_PUBLIC_NAME_LENGTH = 64;
34
+ /** DeepSeek function-name contract: only `[A-Za-z0-9_-]` is allowed. */
35
+ const INVALID_NAME_CHARS = /[^A-Za-z0-9_-]/g;
36
+ /** Hex chars of the SHA-256 identity hash appended on lossy normalization. */
37
+ const HASH_LENGTH = 12;
38
+
39
+ /**
40
+ * Derive the model-facing public name for one Stitch tool.
41
+ *
42
+ * Byte-for-byte the same rule `dsh-mcp-client` applies, because the names are
43
+ * the model's existing vocabulary: this plugin replaces the retired
44
+ * `mcp-stitch` row, and every prompt, note and habit that names
45
+ * `mcp__stitch__generate_screen_from_text` has to keep working. The clean case
46
+ * is `mcp__<serverName>__<rawName>` verbatim; when character replacement or
47
+ * truncation changes it, a 12-hex-char SHA-256 of the identity is appended so
48
+ * two distinct Stitch tools can never collapse onto one public name.
49
+ *
50
+ * @param serverName - stable local namespace; `stitch` reproduces the retired row.
51
+ * @param rawName - Stitch's own tool name.
52
+ * @returns the globally unique, model-facing ToolRuntime name.
53
+ */
54
+ export function publicToolName(serverName, rawName) {
55
+ const joined = `mcp__${serverName}__${rawName}`;
56
+ const normalized = joined.replace(INVALID_NAME_CHARS, '_');
57
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH) return normalized;
58
+ const hash = createHash('sha256').update(`${serverName}\0${rawName}`).digest('hex').slice(0, HASH_LENGTH);
59
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
60
+ }
61
+
62
+ /**
63
+ * Keep an advertised output schema only if the runtime accepts it.
64
+ *
65
+ * Stitch's richer schemas (`$defs`, `x-google-*`, `not`) are rejected by
66
+ * `assertSupportedJsonSchema`; the loose envelope in {@link createOutput} is
67
+ * what the tool falls back to. Dropping the schema loses no information the
68
+ * model can act on — the text projection carries the payload either way — but
69
+ * keeping an unsupported one would make registration throw.
70
+ *
71
+ * @param candidate - the upstream `outputSchema`, if any.
72
+ * @returns the schema when supported, otherwise `undefined`.
73
+ */
74
+ export function supportedOutputSchema(candidate) {
75
+ if (candidate === undefined) return undefined;
76
+ try {
77
+ assertSupportedJsonSchema(candidate);
78
+ return candidate;
79
+ } catch {
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Project ordered MCP content blocks into one plain-text string.
86
+ *
87
+ * Stitch returns only `text` blocks (measured across all 15 tools), so the
88
+ * text run is simply joined. A non-text block is reported positionally rather
89
+ * than silently dropped, which is what makes a future image-returning tool
90
+ * visible instead of empty.
91
+ *
92
+ * @param content - the MCP `content` array.
93
+ * @returns the joined text.
94
+ */
95
+ export function extractText(content) {
96
+ if (!Array.isArray(content)) return '';
97
+ return content
98
+ .map((block) => {
99
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
100
+ return block.text;
101
+ }
102
+ const type = block !== null && typeof block === 'object' && typeof block.type === 'string' ? block.type : 'unknown';
103
+ return `[${type} content is not projected to text]`;
104
+ })
105
+ .join('\n');
106
+ }
107
+
108
+ /**
109
+ * Build the canonical result schema and its text projection.
110
+ *
111
+ * The envelope is fixed because `createSuccessResult` validates every returned
112
+ * value against it: `content` is always present, and `structuredContent` is
113
+ * required exactly when a structured schema was kept. With no structured
114
+ * schema the value carries `content` alone and the text projection is the whole
115
+ * model-visible result.
116
+ *
117
+ * @param structuredSchema - an accepted upstream schema, or `undefined`.
118
+ * @returns the `output` field of a ToolRuntime definition.
119
+ */
120
+ export function createOutput(structuredSchema) {
121
+ return {
122
+ schema: {
123
+ type: 'object',
124
+ properties: {
125
+ content: { type: 'array', items: {} },
126
+ structuredContent: structuredSchema ?? {},
127
+ },
128
+ required: structuredSchema === undefined ? ['content'] : ['content', 'structuredContent'],
129
+ additionalProperties: false,
130
+ },
131
+ render(_args, value) {
132
+ return [{ type: 'text', text: extractText(value.content) }];
133
+ },
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Adapt one upstream Stitch tool descriptor to a ToolRuntime definition.
139
+ *
140
+ * `parameters` is the raw upstream `inputSchema` (see the module note). The
141
+ * result is unregistered; the caller owns registration lifetime.
142
+ *
143
+ * @param options - upstream descriptor fields plus the raw-result callback.
144
+ * @returns the ToolRuntime definition.
145
+ */
146
+ export function createToolDefinition(options) {
147
+ const { name, description, inputSchema, outputSchema, call, timeoutMs } = options;
148
+ return {
149
+ name,
150
+ description,
151
+ parameters: inputSchema,
152
+ output: createOutput(supportedOutputSchema(outputSchema)),
153
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
154
+ async execute(args, exec) {
155
+ const result = await call(typeof args === 'object' && args !== null ? args : {}, exec);
156
+ const content = Array.isArray(result?.content) ? result.content : [];
157
+ const text = extractText(content);
158
+ if (result?.isError === true) throw new Error(text);
159
+ return {
160
+ content,
161
+ ...(result?.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
162
+ };
163
+ },
164
+ };
165
+ }
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@logictan/dsh-stitch-designer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "DSH Stitch designer: Google Stitch AI UI generation as native mcp__stitch__* tools, plus an in-session preview panel with screenshot cache and 1:1 HTML export. DSH Stitch 界面设计子插件。",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "dsh": {
13
+ "bundle": {
14
+ "patch": "./cordis.patch.yml"
15
+ },
16
+ "client": {
17
+ "inject": [
18
+ "slots",
19
+ "remote",
20
+ "remote.credentials"
21
+ ],
22
+ "platform": "web"
23
+ }
24
+ },
25
+ "files": [
26
+ "lib",
27
+ "cordis.patch.yml",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "test": "node --test",
33
+ "build": "node build.mjs",
34
+ "prepare": "node build.mjs",
35
+ "prepack": "node build.mjs"
36
+ },
37
+ "keywords": [
38
+ "dsh",
39
+ "deepseek-harness",
40
+ "dsh-plugin",
41
+ "google-stitch",
42
+ "ai-design",
43
+ "ui-generation",
44
+ "generative-ui",
45
+ "mcp",
46
+ "preview"
47
+ ],
48
+ "license": "MIT",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/dale0525/dsh-plugins.git",
52
+ "directory": "packages/dsh-stitch-designer"
53
+ },
54
+ "engines": {
55
+ "node": "^22.19.0 || >=24.0.0"
56
+ },
57
+ "peerDependencies": {
58
+ "@deepseek-ai/cordis": "^4.0.2",
59
+ "@deepseek-ai/dsh-tools": "^0.1.5-alpha.1 || ^0.1.6-alpha.1 || ^0.1.7-alpha.1 || ^0.1.7-rc.1 || ^0.2.0-rc.1 || ^0.2.0-rc.2"
60
+ },
61
+ "peerDependenciesMeta": {
62
+ "@deepseek-ai/cordis": {
63
+ "optional": true
64
+ },
65
+ "@deepseek-ai/dsh-tools": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "devDependencies": {
70
+ "@deepseek-ai/cordis": "^4.0.2",
71
+ "@deepseek-ai/dsh-tools": "^0.2.0-rc.2"
72
+ }
73
+ }