@zseven-w/qoder-openpencil 0.0.0-stage → 0.1.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/INSTALL.md +77 -0
- package/LICENSE +21 -0
- package/NOTICE +10 -0
- package/README.md +46 -2
- package/README.zh.md +38 -0
- package/THIRD_PARTY_NOTICES.md +69 -0
- package/bin/qoder-openpencil.mjs +90 -0
- package/package.json +71 -4
- package/platforms.json +65 -0
- package/plugins/openpencil/.mcp.json +10 -0
- package/plugins/openpencil/.qoder-plugin/plugin.json +19 -0
- package/plugins/openpencil/CONNECTORS.md +9 -0
- package/plugins/openpencil/LICENSE +21 -0
- package/plugins/openpencil/NOTICE +10 -0
- package/plugins/openpencil/assets/icon.png +0 -0
- package/plugins/openpencil/assets/logo.png +0 -0
- package/plugins/openpencil/mcp.json +11 -0
- package/plugins/openpencil/plugin.json +19 -0
- package/plugins/openpencil/scripts/browser-launch.mjs +37 -0
- package/plugins/openpencil/scripts/canvas-codegen.mjs +141 -0
- package/plugins/openpencil/scripts/canvas-controller.mjs +293 -0
- package/plugins/openpencil/scripts/canvas-images.mjs +93 -0
- package/plugins/openpencil/scripts/canvas-panel.mjs +82 -0
- package/plugins/openpencil/scripts/canvas-selection.mjs +61 -0
- package/plugins/openpencil/scripts/document-format.mjs +48 -0
- package/plugins/openpencil/scripts/editor-runtime.mjs +453 -0
- package/plugins/openpencil/scripts/editor-session.mjs +230 -0
- package/plugins/openpencil/scripts/launch-mcp +22 -0
- package/plugins/openpencil/scripts/launch-mcp.cmd +21 -0
- package/plugins/openpencil/scripts/mcp-bridge.mjs +70 -0
- package/plugins/openpencil/scripts/runtime-install.mjs +128 -0
- package/plugins/openpencil/scripts/transport.mjs +138 -0
- package/plugins/openpencil/skills/openpencil-design/SKILL.md +125 -0
- package/plugins/openpencil/skills/openpencil-design/references/codegen.md +34 -0
- package/plugins/openpencil/skills/openpencil-design/references/images.md +54 -0
- package/plugins/openpencil/skills/openpencil-design/references/node-schema.md +208 -0
- package/plugins/openpencil/skills/openpencil-setup/SKILL.md +59 -0
- package/plugins/openpencil/ui/app.html +226 -0
- package/plugins/openpencil/ui/codegen.js +80 -0
- package/plugins/openpencil/ui/panel.css +311 -0
- package/plugins/openpencil/ui/panel.html +11 -0
- package/plugins/openpencil/ui/panel.js +219 -0
- package/plugins/openpencil/ui/selection.js +19 -0
- package/scripts/build-editor-runtime.mjs +35 -0
- package/scripts/canvas.mjs +75 -0
- package/scripts/check-package.mjs +81 -0
- package/scripts/check-release-version.mjs +53 -0
- package/scripts/collab-bootstrap-config.mjs +66 -0
- package/scripts/configure-runtime.mjs +15 -0
- package/scripts/host-config.mjs +352 -0
- package/scripts/managed-handshake.mjs +23 -0
- package/scripts/node-registration.mjs +17 -0
- package/scripts/pack-package.mjs +41 -0
- package/scripts/pack-plugin.mjs +166 -0
- package/scripts/platforms.mjs +84 -0
- package/scripts/plugin-host-check.mjs +174 -0
- package/scripts/publish-release.mjs +294 -0
- package/scripts/registry-convergence.mjs +40 -0
- package/scripts/setup.mjs +147 -0
- package/scripts/stage-editor-runtime.mjs +189 -0
- package/scripts/sync-platform-versions.mjs +63 -0
- package/scripts/verify-platform-packages.mjs +270 -0
- package/scripts/verify-selective-install.mjs +219 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
3
|
+
import { extname, isAbsolute } from 'node:path';
|
|
4
|
+
import { readCanvasSelection } from './canvas-selection.mjs';
|
|
5
|
+
import { snapshotMatches } from './document-format.mjs';
|
|
6
|
+
|
|
7
|
+
export const frameworks = ['react', 'react-tailwind', 'vue', 'svelte', 'html', 'flutter', 'swiftui', 'compose', 'react-native'];
|
|
8
|
+
const fail = message => { throw new Error(message); };
|
|
9
|
+
const equalIds = (a, b) => {
|
|
10
|
+
const sorted = [...b].sort();
|
|
11
|
+
return Array.isArray(a) && a.length === b.length && [...a].sort().every((id, i) => id === sorted[i]);
|
|
12
|
+
};
|
|
13
|
+
const summary = job => job && ({
|
|
14
|
+
requestId: job.requestId,
|
|
15
|
+
uiRequestId: job.uiRequestId,
|
|
16
|
+
framework: job.framework,
|
|
17
|
+
pageId: job.pageId,
|
|
18
|
+
nodeIds: job.nodeIds,
|
|
19
|
+
expectedVersion: job.expectedVersion,
|
|
20
|
+
status: job.status,
|
|
21
|
+
revision: job.revision,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export function codegenSummary(controller) { return summary(controller.codegenJob); }
|
|
25
|
+
|
|
26
|
+
export async function prepareCodegen(controller, args) {
|
|
27
|
+
if (!frameworks.includes(args.framework) || typeof args.uiRequestId !== 'string' || !/^host-\d+-\d+$/.test(args.uiRequestId)) {
|
|
28
|
+
fail('Invalid code-generation request.');
|
|
29
|
+
}
|
|
30
|
+
// A repeated browser event cannot create another chat request.
|
|
31
|
+
if (controller.codegenJob?.uiRequestId === args.uiRequestId) return controller.codegenJob;
|
|
32
|
+
const session = controller.session;
|
|
33
|
+
const { live, selection } = await readCanvasSelection(session, { fresh: true });
|
|
34
|
+
const page = live.document.pages?.length ? live.document.pages[selection.pageIndex] : live.document;
|
|
35
|
+
const nodeIds = selection.count ? selection.nodeIds : (page.children || []).map(node => node.id);
|
|
36
|
+
if (!nodeIds.length) fail('Select a frame or add content before generating code.');
|
|
37
|
+
if (selection.pageId !== args.pageId || !equalIds(args.nodeIds, nodeIds)) {
|
|
38
|
+
fail('The code-generation target changed. Select the intended page or elements and try again.');
|
|
39
|
+
}
|
|
40
|
+
let snapshot;
|
|
41
|
+
try { snapshot = JSON.parse(args.docJson); } catch { fail('A flushed canvas snapshot is required.'); }
|
|
42
|
+
if (!snapshotMatches(snapshot, live)) fail('Canvas edits are still syncing. No code-generation request was sent.');
|
|
43
|
+
const exported = await session.forward({
|
|
44
|
+
jsonrpc: '2.0',
|
|
45
|
+
id: 'canvas-codegen-export',
|
|
46
|
+
method: 'tools/call',
|
|
47
|
+
params: { name: 'codegen_export', arguments: { framework: args.framework, pageId: selection.pageId, nodeIds: JSON.stringify(nodeIds) } },
|
|
48
|
+
});
|
|
49
|
+
if (exported.error || exported.result?.isError) {
|
|
50
|
+
fail(exported.error?.message || exported.result?.content?.[0]?.text || 'Code export failed.');
|
|
51
|
+
}
|
|
52
|
+
const output = exported.result.structuredContent || JSON.parse(exported.result.content.find(item => item.type === 'text').text);
|
|
53
|
+
if (!output.code || typeof output.code !== 'string' || Buffer.byteLength(output.code) > 2 * 1024 * 1024) {
|
|
54
|
+
fail('The runtime returned no source code.');
|
|
55
|
+
}
|
|
56
|
+
// Recheck after exporting: a concurrent MCP edit must not acquire an older brief.
|
|
57
|
+
const after = await session.document();
|
|
58
|
+
if (after.version !== live.version) fail('The design changed during code export. No request was sent.');
|
|
59
|
+
const requestId = randomUUID();
|
|
60
|
+
const context = {
|
|
61
|
+
requestId,
|
|
62
|
+
framework: args.framework,
|
|
63
|
+
pageId: selection.pageId,
|
|
64
|
+
nodeIds,
|
|
65
|
+
expectedVersion: live.version,
|
|
66
|
+
canvasFile: session.source,
|
|
67
|
+
recoveryPath: session.draft,
|
|
68
|
+
};
|
|
69
|
+
const prompt = `Use the OpenPencil code-generation workflow for this request: ${JSON.stringify(context)}. `
|
|
70
|
+
+ `Read canvas_codegen_status and require its requestId to equal ${requestId}; a mismatch or cancelled status means this request must stop. Inspect the captured nodes and their native screenshot, then implement them in the current project using its existing conventions. `
|
|
71
|
+
+ 'Use codegen_export as a starting point; preserve text, layout, images and design tokens. Finish a runnable implementation and relevant checks. '
|
|
72
|
+
+ 'Read the openpencil-design code-generation reference. Return the primary source to the Code panel with canvas_codegen_complete(requestId, codePath). '
|
|
73
|
+
+ 'Do not modify the design or silently follow later selection changes. If the design version changed, stop and explain.';
|
|
74
|
+
const job = {
|
|
75
|
+
...context,
|
|
76
|
+
uiRequestId: args.uiRequestId,
|
|
77
|
+
code: output.files?.['component.tsx'] || output.code,
|
|
78
|
+
files: output.files,
|
|
79
|
+
prompt,
|
|
80
|
+
status: 'prepared',
|
|
81
|
+
revision: (controller.codegenJob?.revision || 0) + 1,
|
|
82
|
+
};
|
|
83
|
+
controller.codegenJob = job;
|
|
84
|
+
return job;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function completeCodegen(controller, { requestId, codePath }) {
|
|
88
|
+
const job = controller.codegenJob;
|
|
89
|
+
if (!job || job.requestId !== requestId || job.status === 'cancelled') {
|
|
90
|
+
fail('This code-generation request is no longer active.');
|
|
91
|
+
}
|
|
92
|
+
if (!isAbsolute(codePath || '')) fail('Use the absolute path of the primary generated source file.');
|
|
93
|
+
const extensions = {
|
|
94
|
+
react: ['.tsx', '.jsx'],
|
|
95
|
+
'react-tailwind': ['.tsx', '.jsx'],
|
|
96
|
+
vue: ['.vue'],
|
|
97
|
+
svelte: ['.svelte'],
|
|
98
|
+
html: ['.html'],
|
|
99
|
+
flutter: ['.dart'],
|
|
100
|
+
swiftui: ['.swift'],
|
|
101
|
+
compose: ['.kt'],
|
|
102
|
+
'react-native': ['.tsx', '.jsx'],
|
|
103
|
+
};
|
|
104
|
+
if (!extensions[job.framework].includes(extname(codePath).toLowerCase())) {
|
|
105
|
+
fail('The primary source extension must match the requested framework.');
|
|
106
|
+
}
|
|
107
|
+
const stat = await lstat(codePath);
|
|
108
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 2 * 1024 * 1024) {
|
|
109
|
+
fail('Generated source must be a regular file of at most 2 MiB.');
|
|
110
|
+
}
|
|
111
|
+
const bytes = await readFile(codePath);
|
|
112
|
+
if (bytes.length > 2 * 1024 * 1024) fail('Generated source exceeds 2 MiB.');
|
|
113
|
+
let code;
|
|
114
|
+
try { code = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
|
|
115
|
+
catch { fail('Generated source must be UTF-8 text.'); }
|
|
116
|
+
if (!code.trim() || code.includes('\u0000')) fail('Generated source must be non-empty UTF-8 text.');
|
|
117
|
+
const live = await controller.session.document();
|
|
118
|
+
if (live.version !== job.expectedVersion) {
|
|
119
|
+
fail('The design changed after this request. The previous preview was retained.');
|
|
120
|
+
}
|
|
121
|
+
job.code = code;
|
|
122
|
+
job.codePath = codePath;
|
|
123
|
+
job.status = 'complete';
|
|
124
|
+
job.revision++;
|
|
125
|
+
return { ...summary(job), codePath };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function pollCodegen(controller, { afterRevision } = {}) {
|
|
129
|
+
const job = controller.codegenJob;
|
|
130
|
+
if (!job || job.revision === afterRevision) return null;
|
|
131
|
+
return { ...summary(job), code: job.code, codePath: job.codePath };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function cancelCodegen(controller, { uiRequestId }) {
|
|
135
|
+
const job = controller.codegenJob;
|
|
136
|
+
if (job?.uiRequestId === uiRequestId && job.status !== 'cancelled') {
|
|
137
|
+
job.status = 'cancelled';
|
|
138
|
+
job.revision++;
|
|
139
|
+
}
|
|
140
|
+
return summary(job);
|
|
141
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { EditorSession } from './editor-session.mjs';
|
|
3
|
+
import { startPanel } from './canvas-panel.mjs';
|
|
4
|
+
import { forward, errorReply } from './transport.mjs';
|
|
5
|
+
import { readCanvasSelection } from './canvas-selection.mjs';
|
|
6
|
+
import { importCanvasImage } from './canvas-images.mjs';
|
|
7
|
+
import { prepareCanvasBrowser, browserLaunchStatus } from './browser-launch.mjs';
|
|
8
|
+
import { prepareCodegen, completeCodegen, pollCodegen, cancelCodegen, codegenSummary, frameworks } from './canvas-codegen.mjs';
|
|
9
|
+
|
|
10
|
+
export const CANVAS_URI = 'ui://openpencil/canvas/v0.1.0.html';
|
|
11
|
+
const schema = properties => ({ type: 'object', properties, additionalProperties: false });
|
|
12
|
+
const filePath = { type: 'string', description: 'Absolute .op path; omit to create or reopen this session’s canvas.' };
|
|
13
|
+
|
|
14
|
+
export const canvasTools = [
|
|
15
|
+
{
|
|
16
|
+
name: 'open_canvas',
|
|
17
|
+
title: 'OpenPencil Canvas',
|
|
18
|
+
description: 'Open the editable Rust OpenPencil canvas directly inside Qoder (Global workspace tab, Session Sidebar app tab, or inline card). Optional filePath loads an existing .op into an isolated managed session. All subsequent OpenPencil tools target this canvas until the bridge closes. Omit filePath for a new document.',
|
|
19
|
+
inputSchema: schema({ filePath }),
|
|
20
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
21
|
+
_meta: {
|
|
22
|
+
ui: { resourceUri: CANVAS_URI },
|
|
23
|
+
'ui/resourceUri': CANVAS_URI,
|
|
24
|
+
'qoder/ui': {
|
|
25
|
+
entrypoints: [{ type: 'global' }, { type: 'thread' }],
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: 'canvas_open_browser',
|
|
31
|
+
description: 'Open or reconnect this chat’s managed editable canvas and return its local panelUrl. Open the returned URL in Qoder’s built-in browser or the user’s browser while preserving its theme/launch fragment. All subsequent OpenPencil tools target this same canvas.',
|
|
32
|
+
inputSchema: schema({ filePath }),
|
|
33
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: 'canvas_prepare_browser',
|
|
37
|
+
description: 'Prepare this conversation’s existing canvas URL and short-lived ready receipt for host-mediated browser opening. Does not launch a browser or send a message.',
|
|
38
|
+
inputSchema: { ...schema({ theme: { type: 'string', enum: ['light', 'dark'] } }), required: ['theme'] },
|
|
39
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
40
|
+
_meta: { ui: { visibility: ['app'] } },
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: 'canvas_launch_status',
|
|
44
|
+
description: 'Read whether the browser canvas for this launch has actually connected.',
|
|
45
|
+
inputSchema: { ...schema({ launchId: { type: 'string' } }), required: ['launchId'] },
|
|
46
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
47
|
+
_meta: { ui: { visibility: ['app'] } },
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: 'canvas_status',
|
|
51
|
+
description: 'Read managed canvas file, recovery path, document version and selection.',
|
|
52
|
+
inputSchema: schema({}),
|
|
53
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'canvas_selection',
|
|
57
|
+
description: 'Read the current managed canvas selection: exact node IDs, names, types, parents, active page and document version. Call before modifying selected elements from a chat prompt; read these nodes with batch_get, then edit only their subtrees. Empty selection means no target, never the entire page.',
|
|
58
|
+
inputSchema: schema({}),
|
|
59
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: 'canvas_import_image',
|
|
63
|
+
description: 'Embed a local PNG/JPEG/WebP (at most 8 MiB) into an existing image node in the managed canvas. Reads file bytes directly without putting base64 in chat. Requires the current document version and active page; preserves node ID, geometry and unrelated nodes. Clears acquisition hints after import. Does not generate images, call a provider, or save the source .op. After import inspect the native preview, canvas_save and verify reopen; never automatically retry an uncertain write.',
|
|
64
|
+
inputSchema: {
|
|
65
|
+
...schema({
|
|
66
|
+
filePath: { type: 'string', description: 'Absolute path to a local image asset.' },
|
|
67
|
+
nodeId: { type: 'string', minLength: 1 },
|
|
68
|
+
pageId: { type: 'string', minLength: 1 },
|
|
69
|
+
expectedVersion: { type: 'integer', minimum: 0 },
|
|
70
|
+
}),
|
|
71
|
+
required: ['filePath', 'nodeId', 'pageId', 'expectedVersion'],
|
|
72
|
+
},
|
|
73
|
+
annotations: { destructiveHint: true, openWorldHint: false },
|
|
74
|
+
_meta: { ui: { visibility: ['model'] } },
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: 'canvas_save',
|
|
78
|
+
description: 'Save the managed canvas to its original path or a new absolute .op path. Refuses external changes or an existing Save As destination. UI must flush its snapshot first; never automatically retry.',
|
|
79
|
+
inputSchema: schema({ filePath, docJson: { type: 'string', description: 'UI-only flushed document snapshot, used to reject stale saves.' } }),
|
|
80
|
+
annotations: { destructiveHint: true, openWorldHint: false },
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
name: 'canvas_checkpoint',
|
|
84
|
+
description: 'Persist a recovery draft of the managed canvas without overwriting its source.',
|
|
85
|
+
inputSchema: schema({}),
|
|
86
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
87
|
+
_meta: { ui: { visibility: ['app'] } },
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
name: 'canvas_codegen_prepare',
|
|
91
|
+
description: 'Capture the Code panel target after flushing browser edits and export baseline source. Does not call a model or write project files.',
|
|
92
|
+
inputSchema: {
|
|
93
|
+
...schema({
|
|
94
|
+
uiRequestId: { type: 'string' },
|
|
95
|
+
framework: { type: 'string', enum: frameworks },
|
|
96
|
+
pageId: { type: 'string' },
|
|
97
|
+
nodeIds: { type: 'array', items: { type: 'string' } },
|
|
98
|
+
docJson: { type: 'string' },
|
|
99
|
+
}),
|
|
100
|
+
required: ['uiRequestId', 'framework', 'pageId', 'nodeIds', 'docJson'],
|
|
101
|
+
},
|
|
102
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
103
|
+
_meta: { ui: { visibility: ['app'] } },
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
name: 'canvas_codegen_status',
|
|
107
|
+
description: 'Read the latest Code panel conversion request, its fixed page/node IDs, design version, baseline source and handoff prompt. Use this before implementing a Code panel request; later selection changes do not change its target.',
|
|
108
|
+
inputSchema: schema({}),
|
|
109
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
name: 'canvas_codegen_complete',
|
|
113
|
+
description: 'Return the primary implemented source file to the Code panel preview, copy and download actions. Pass the requestId from canvas_codegen_status and an absolute codePath after implementing and verifying the project. Reads the file; never writes it or changes the design. Rejects superseded requests and changed design versions.',
|
|
114
|
+
inputSchema: { ...schema({ requestId: { type: 'string' }, codePath: { type: 'string' } }), required: ['requestId', 'codePath'] },
|
|
115
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
name: 'canvas_codegen_cancel',
|
|
119
|
+
description: 'Cancel the matching panel request without replaying a host message.',
|
|
120
|
+
inputSchema: { ...schema({ uiRequestId: { type: 'string' } }), required: ['uiRequestId'] },
|
|
121
|
+
annotations: { destructiveHint: false, openWorldHint: false },
|
|
122
|
+
_meta: { ui: { visibility: ['app'] } },
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
name: 'canvas_codegen_poll',
|
|
126
|
+
description: 'Read a changed Code panel result.',
|
|
127
|
+
inputSchema: schema({ afterRevision: { type: 'integer' } }),
|
|
128
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
129
|
+
_meta: { ui: { visibility: ['app'] } },
|
|
130
|
+
},
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
const toolResult = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value });
|
|
134
|
+
|
|
135
|
+
export class CanvasController {
|
|
136
|
+
constructor(options = {}) {
|
|
137
|
+
this.options = options;
|
|
138
|
+
this.queue = Promise.resolve();
|
|
139
|
+
this.session = null;
|
|
140
|
+
this.panel = null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
enqueue(work) {
|
|
144
|
+
const result = this.queue.then(work);
|
|
145
|
+
this.queue = result.catch(() => {});
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async ensurePanel() {
|
|
150
|
+
if (!this.panel) this.panel = await startPanel(this);
|
|
151
|
+
return this.panel;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async open({ filePath } = {}) {
|
|
155
|
+
const panel = await this.ensurePanel();
|
|
156
|
+
if (this.session && filePath && filePath !== this.session.source && filePath !== this.session.draft) {
|
|
157
|
+
throw new Error('This conversation already has a canvas. Save it, then open the other document in a new conversation.');
|
|
158
|
+
}
|
|
159
|
+
if (!this.session) {
|
|
160
|
+
this.session = await EditorSession.start({ filePath, allowOrigin: panel.origin, runtimeRoot: this.options.runtimeRoot });
|
|
161
|
+
await this.options.onToolsChanged?.();
|
|
162
|
+
}
|
|
163
|
+
this.session.assertLive();
|
|
164
|
+
const value = { filePath: this.session.source, recoveryPath: this.session.draft, panelUrl: panel.url, version: this.session.version };
|
|
165
|
+
return {
|
|
166
|
+
...toolResult(value),
|
|
167
|
+
_meta: {
|
|
168
|
+
canvas: {
|
|
169
|
+
editorOrigin: `http://127.0.0.1:${this.session.port}`,
|
|
170
|
+
token: this.session.token,
|
|
171
|
+
panelUrl: panel.url,
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async call(name, args) {
|
|
178
|
+
if (name === 'open_canvas' || name === 'canvas_open_browser') return this.open(args);
|
|
179
|
+
if (!this.session) throw new Error('Open a managed canvas with open_canvas or canvas_open_browser first.');
|
|
180
|
+
if (name === 'canvas_prepare_browser') return toolResult(prepareCanvasBrowser(this, args));
|
|
181
|
+
if (name === 'canvas_launch_status') return toolResult(browserLaunchStatus(this, args));
|
|
182
|
+
if (name === 'canvas_launch_ready') return toolResult(browserLaunchStatus(this, args, true));
|
|
183
|
+
if (name === 'canvas_import_image') return toolResult(await importCanvasImage(this.session, args));
|
|
184
|
+
if (name === 'canvas_save') return toolResult(await this.session.save(args));
|
|
185
|
+
if (name === 'canvas_checkpoint') return toolResult(await this.session.checkpoint());
|
|
186
|
+
if (name === 'canvas_codegen_prepare') return toolResult(await prepareCodegen(this, args));
|
|
187
|
+
if (name === 'canvas_codegen_status') return toolResult(this.codegenJob || null);
|
|
188
|
+
if (name === 'canvas_codegen_complete') return toolResult(await completeCodegen(this, args));
|
|
189
|
+
if (name === 'canvas_codegen_cancel') return toolResult(cancelCodegen(this, args));
|
|
190
|
+
if (name === 'canvas_codegen_poll') return toolResult(pollCodegen(this, args));
|
|
191
|
+
const current = await readCanvasSelection(this.session);
|
|
192
|
+
return toolResult({
|
|
193
|
+
filePath: this.session.source,
|
|
194
|
+
recoveryPath: this.session.draft,
|
|
195
|
+
version: current.live.version,
|
|
196
|
+
selection: current.selection,
|
|
197
|
+
codegen: codegenSummary(this),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async resource() {
|
|
202
|
+
const panel = await this.ensurePanel();
|
|
203
|
+
const template = await readFile(new URL('../ui/app.html', import.meta.url), 'utf8');
|
|
204
|
+
// Qoder's MCP Apps host reads _meta.ui.csp (permitting loopback http://127.0.0.1
|
|
205
|
+
// in frameDomains) and _meta['qoder/ui'] for inline card vs fullscreen webview tabs.
|
|
206
|
+
return {
|
|
207
|
+
contents: [{
|
|
208
|
+
uri: CANVAS_URI,
|
|
209
|
+
mimeType: 'text/html;profile=mcp-app',
|
|
210
|
+
text: template,
|
|
211
|
+
_meta: {
|
|
212
|
+
ui: {
|
|
213
|
+
prefersBorder: false,
|
|
214
|
+
permissions: { clipboardWrite: {} },
|
|
215
|
+
csp: {
|
|
216
|
+
frameDomains: [panel.origin],
|
|
217
|
+
connectDomains: [],
|
|
218
|
+
resourceDomains: [],
|
|
219
|
+
},
|
|
220
|
+
},
|
|
221
|
+
'qoder/ui': {
|
|
222
|
+
availableDisplayModes: ['inline', 'fullscreen'],
|
|
223
|
+
preferredDisplayMode: 'fullscreen',
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
}],
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async dispatch(message) {
|
|
231
|
+
if (
|
|
232
|
+
!message
|
|
233
|
+
|| Array.isArray(message)
|
|
234
|
+
|| message.jsonrpc !== '2.0'
|
|
235
|
+
|| typeof message.method !== 'string'
|
|
236
|
+
|| (Object.hasOwn(message, 'id') && message.id !== null && !['string', 'number'].includes(typeof message.id))
|
|
237
|
+
) {
|
|
238
|
+
return errorReply(null, -32600, 'Expected a JSON-RPC 2.0 request or notification.');
|
|
239
|
+
}
|
|
240
|
+
const reply = result => ({ jsonrpc: '2.0', id: message.id, result });
|
|
241
|
+
try {
|
|
242
|
+
if (message.method === 'resources/read' && message.params?.uri === CANVAS_URI) return reply(await this.resource());
|
|
243
|
+
if (message.method === 'resources/list') {
|
|
244
|
+
return reply({
|
|
245
|
+
resources: [{
|
|
246
|
+
uri: CANVAS_URI,
|
|
247
|
+
name: 'OpenPencil Canvas',
|
|
248
|
+
mimeType: 'text/html;profile=mcp-app',
|
|
249
|
+
}],
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
if (message.method === 'tools/call' && canvasTools.some(tool => tool.name === message.params?.name)) {
|
|
253
|
+
return reply(await this.call(message.params.name, message.params.arguments || {}));
|
|
254
|
+
}
|
|
255
|
+
if (this.session && message.method === 'tools/call' && message.params?.name === 'save_document') {
|
|
256
|
+
if (message.params.arguments?.sourceFilePath) {
|
|
257
|
+
throw new Error('Source-copy save is unavailable while a managed canvas is active.');
|
|
258
|
+
}
|
|
259
|
+
return reply(await this.call('canvas_save', message.params.arguments || {}));
|
|
260
|
+
}
|
|
261
|
+
const upstream = this.session ? await this.session.forward(message) : await forward(message, this.options);
|
|
262
|
+
if (!Object.hasOwn(message, 'id')) return null;
|
|
263
|
+
if (message.method === 'initialize') {
|
|
264
|
+
const result = upstream?.result || {
|
|
265
|
+
protocolVersion: message.params?.protocolVersion || '2025-11-25',
|
|
266
|
+
serverInfo: { name: 'qoder-openpencil', version: '0.1.0' },
|
|
267
|
+
};
|
|
268
|
+
result.capabilities = { ...result.capabilities, tools: { listChanged: true }, resources: {} };
|
|
269
|
+
return reply(result);
|
|
270
|
+
}
|
|
271
|
+
if (message.method === 'tools/list') {
|
|
272
|
+
return reply({ ...upstream?.result, tools: [...(upstream?.result?.tools || []), ...canvasTools] });
|
|
273
|
+
}
|
|
274
|
+
return upstream;
|
|
275
|
+
} catch (error) {
|
|
276
|
+
if (!Object.hasOwn(message, 'id')) return null;
|
|
277
|
+
if (message.method === 'tools/call') {
|
|
278
|
+
return reply({
|
|
279
|
+
content: [{ type: 'text', text: error.message }],
|
|
280
|
+
isError: true,
|
|
281
|
+
...(error.code ? { structuredContent: { code: error.code } } : {}),
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
return errorReply(message.id, -32000, error.message);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async close() {
|
|
289
|
+
await this.queue;
|
|
290
|
+
try { if (this.session) await this.session.close(); }
|
|
291
|
+
finally { if (this.panel) await this.panel.close(); }
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { liveDocument } from './document-format.mjs';
|
|
5
|
+
|
|
6
|
+
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
7
|
+
const MAX_DOCUMENT_BYTES = 32 * 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
function mimeType(bytes) {
|
|
10
|
+
if (bytes.length >= 33 && bytes.subarray(0, 8).toString('hex') === '89504e470d0a1a0a'
|
|
11
|
+
&& bytes.toString('ascii', 12, 16) === 'IHDR') return 'image/png';
|
|
12
|
+
if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
|
|
13
|
+
if (bytes.length >= 16 && bytes.toString('ascii', 0, 4) === 'RIFF'
|
|
14
|
+
&& bytes.toString('ascii', 8, 12) === 'WEBP') return 'image/webp';
|
|
15
|
+
throw new Error('Use a PNG, JPEG or WebP image file. SVG and non-image files are not imported.');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function target(live, pageId, nodeId) {
|
|
19
|
+
const document = liveDocument(live.document);
|
|
20
|
+
const page = document.pages?.length ? document.pages[live.activePageIndex] : document;
|
|
21
|
+
if (!page || (document.pages?.length ? page.id : '0') !== pageId) {
|
|
22
|
+
throw new Error('The active page changed. Read the canvas and confirm the image target again.');
|
|
23
|
+
}
|
|
24
|
+
const stack = [...(page.children || [])];
|
|
25
|
+
while (stack.length) {
|
|
26
|
+
const node = stack.pop();
|
|
27
|
+
if (node.id === nodeId) {
|
|
28
|
+
if (node.type !== 'image') throw new Error('The target must be an existing image node; other node types are preserved.');
|
|
29
|
+
return { document, node };
|
|
30
|
+
}
|
|
31
|
+
stack.push(...(node.children || []));
|
|
32
|
+
}
|
|
33
|
+
throw new Error('The image target no longer exists on this page. No image was imported.');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Import bytes, not file URLs: WASM and reopened documents cannot rely on a
|
|
37
|
+
// generated asset remaining in the host's cache or temporary directory.
|
|
38
|
+
export async function importCanvasImage(session, { filePath, nodeId, pageId, expectedVersion } = {}) {
|
|
39
|
+
if (typeof filePath !== 'string' || !isAbsolute(filePath)) throw new Error('Use an absolute local image file path.');
|
|
40
|
+
if (
|
|
41
|
+
typeof nodeId !== 'string'
|
|
42
|
+
|| !nodeId.trim()
|
|
43
|
+
|| typeof pageId !== 'string'
|
|
44
|
+
|| !pageId.trim()
|
|
45
|
+
|| !Number.isSafeInteger(expectedVersion)
|
|
46
|
+
|| expectedVersion < 0
|
|
47
|
+
) {
|
|
48
|
+
throw new Error('Provide the exact image nodeId, pageId and expectedVersion from the current canvas.');
|
|
49
|
+
}
|
|
50
|
+
const info = await lstat(filePath);
|
|
51
|
+
if (!info.isFile() || info.isSymbolicLink() || !info.size || info.size > MAX_IMAGE_BYTES) {
|
|
52
|
+
throw new Error('Use a regular image file of at most 8 MiB.');
|
|
53
|
+
}
|
|
54
|
+
const bytes = await readFile(filePath);
|
|
55
|
+
if (!bytes.length || bytes.length > MAX_IMAGE_BYTES) throw new Error('Use an image file of at most 8 MiB.');
|
|
56
|
+
const mime = mimeType(bytes);
|
|
57
|
+
const src = `data:${mime};base64,${bytes.toString('base64')}`;
|
|
58
|
+
const live = await session.document();
|
|
59
|
+
if (live.version !== expectedVersion) throw new Error('The canvas changed. Read it and confirm the image target before importing.');
|
|
60
|
+
const current = target(live, pageId, nodeId);
|
|
61
|
+
current.node.src = src;
|
|
62
|
+
current.node.imagePrompt = null;
|
|
63
|
+
current.node.imageSearchQuery = null;
|
|
64
|
+
if (Buffer.byteLength(JSON.stringify(current.document)) > MAX_DOCUMENT_BYTES) {
|
|
65
|
+
throw new Error('Embedding this image would exceed the 32 MiB document limit. Use a smaller asset.');
|
|
66
|
+
}
|
|
67
|
+
const reply = await session.forward({
|
|
68
|
+
jsonrpc: '2.0',
|
|
69
|
+
id: 'canvas-import-image',
|
|
70
|
+
method: 'tools/call',
|
|
71
|
+
params: {
|
|
72
|
+
name: 'update_node',
|
|
73
|
+
arguments: { nodeId, pageId, data: { src, imagePrompt: null, imageSearchQuery: null } },
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
if (reply?.error || !reply?.result || reply.result.isError) {
|
|
77
|
+
throw new Error('Image import was not confirmed. Inspect the canvas before repeating it; the write was not retried.');
|
|
78
|
+
}
|
|
79
|
+
const after = await session.document();
|
|
80
|
+
if (target(after, pageId, nodeId).node.src !== src) {
|
|
81
|
+
throw new Error('Image import readback did not match. Inspect the target before making another change.');
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
nodeId,
|
|
85
|
+
pageId,
|
|
86
|
+
version: after.version,
|
|
87
|
+
bytes: bytes.length,
|
|
88
|
+
mimeType: mime,
|
|
89
|
+
sha256: createHash('sha256').update(bytes).digest('hex'),
|
|
90
|
+
embedded: true,
|
|
91
|
+
saved: false,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { MAX_BYTES } from './transport.mjs';
|
|
5
|
+
|
|
6
|
+
export async function panelHtml(grant) {
|
|
7
|
+
const root = new URL('../ui/', import.meta.url);
|
|
8
|
+
const [html, css, panelJs, selectionJs, codegenJs] = await Promise.all(
|
|
9
|
+
['panel.html', 'panel.css', 'panel.js', 'selection.js', 'codegen.js'].map(name => readFile(new URL(name, root), 'utf8')),
|
|
10
|
+
);
|
|
11
|
+
const js = panelJs + '\n' + selectionJs + '\n' + codegenJs;
|
|
12
|
+
const json = JSON.stringify(grant).replace(/</g, '\\u003c');
|
|
13
|
+
return html.replace('/* PANEL_CSS */', css).replace('/* PANEL_GRANT */', json).replace('/* PANEL_JS */', js);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function startPanel(controller) {
|
|
17
|
+
const capability = randomBytes(32).toString('base64url');
|
|
18
|
+
let origin;
|
|
19
|
+
const route = `/canvas/${capability}`;
|
|
20
|
+
const server = http.createServer(async (req, res) => {
|
|
21
|
+
const reply = (status, value) => {
|
|
22
|
+
if (res.destroyed || res.headersSent) return;
|
|
23
|
+
res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
24
|
+
res.end(JSON.stringify(value));
|
|
25
|
+
};
|
|
26
|
+
try {
|
|
27
|
+
if (req.headers.host !== new URL(origin).host || (req.headers.origin && req.headers.origin !== origin)) {
|
|
28
|
+
req.resume();
|
|
29
|
+
reply(403, { error: 'Canvas origin is not authorized.' });
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (req.url === route && req.method === 'GET') {
|
|
33
|
+
const session = await controller.enqueue(() => controller.open({}));
|
|
34
|
+
const html = await panelHtml({ ...session._meta.canvas, rpcPath: `${route}/rpc`, source: session.structuredContent.filePath });
|
|
35
|
+
res.writeHead(200, {
|
|
36
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
37
|
+
'Cache-Control': 'no-store',
|
|
38
|
+
'Referrer-Policy': 'no-referrer',
|
|
39
|
+
'X-Content-Type-Options': 'nosniff',
|
|
40
|
+
'Content-Security-Policy': `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; frame-src ${session._meta.canvas.editorOrigin}; connect-src 'self'; img-src data:`,
|
|
41
|
+
});
|
|
42
|
+
res.end(html);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (req.url === `${route}/rpc` && req.method === 'POST') {
|
|
46
|
+
const chunks = [];
|
|
47
|
+
let size = 0;
|
|
48
|
+
for await (const chunk of req) {
|
|
49
|
+
size += chunk.length;
|
|
50
|
+
if (size > MAX_BYTES) {
|
|
51
|
+
reply(413, { error: 'Canvas request exceeds 32 MiB.' });
|
|
52
|
+
req.destroy();
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
chunks.push(chunk);
|
|
56
|
+
}
|
|
57
|
+
const message = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
58
|
+
if (!['canvas_status', 'canvas_selection', 'canvas_save', 'canvas_checkpoint', 'canvas_codegen_prepare', 'canvas_codegen_poll', 'canvas_codegen_cancel', 'canvas_launch_ready'].includes(message.name)) {
|
|
59
|
+
reply(403, { error: 'Unsupported canvas control.' });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const result = await controller.enqueue(() => controller.call(message.name, message.arguments || {}));
|
|
63
|
+
reply(200, result);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
req.resume();
|
|
67
|
+
reply(404, { error: 'Canvas route not found.' });
|
|
68
|
+
} catch (error) {
|
|
69
|
+
reply(400, { error: error.message, code: error.code });
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
73
|
+
origin = `http://127.0.0.1:${server.address().port}`;
|
|
74
|
+
return {
|
|
75
|
+
origin,
|
|
76
|
+
url: origin + route,
|
|
77
|
+
close: async () => {
|
|
78
|
+
server.closeAllConnections();
|
|
79
|
+
await new Promise(resolve => server.close(resolve));
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const selectionError = (message, code) => Object.assign(new Error(message), { code });
|
|
2
|
+
|
|
3
|
+
function editorState(reply) {
|
|
4
|
+
if (reply?.error || reply?.result?.isError) throw new Error('Cannot read the canvas selection.');
|
|
5
|
+
const result = reply?.result;
|
|
6
|
+
let state = result?.structuredContent;
|
|
7
|
+
if (!state) {
|
|
8
|
+
const text = result?.content?.find(item => item.type === 'text')?.text;
|
|
9
|
+
try { state = JSON.parse(text); } catch { throw new Error('Invalid canvas selection response.'); }
|
|
10
|
+
}
|
|
11
|
+
const pageIndex = Number(state.active_page_index);
|
|
12
|
+
if (!Number.isSafeInteger(pageIndex) || pageIndex < 0 || typeof state.active_page_id !== 'string' || typeof state.selection_ids !== 'string') {
|
|
13
|
+
throw new Error('Invalid canvas selection state.');
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
pageId: state.active_page_id,
|
|
17
|
+
pageIndex,
|
|
18
|
+
nodeIds: [...new Set(state.selection_ids.split(',').filter(id => id && id !== '0'))].sort(),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function sameSelection(a, b) {
|
|
23
|
+
const right = Array.isArray(b?.nodeIds) ? [...b.nodeIds].sort() : [];
|
|
24
|
+
return a?.pageId === b?.pageId
|
|
25
|
+
&& Array.isArray(a?.nodeIds)
|
|
26
|
+
&& Array.isArray(b?.nodeIds)
|
|
27
|
+
&& a.nodeIds.length === b.nodeIds.length
|
|
28
|
+
&& [...a.nodeIds].sort().every((id, index) => id === right[index]);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function readCanvasSelection(session, { fresh = false } = {}) {
|
|
32
|
+
const state = async () => editorState(await session.forward({
|
|
33
|
+
jsonrpc: '2.0',
|
|
34
|
+
id: 'canvas-selection',
|
|
35
|
+
method: 'tools/call',
|
|
36
|
+
params: { name: 'get_editor_state', arguments: {} },
|
|
37
|
+
}));
|
|
38
|
+
const before = await state();
|
|
39
|
+
const live = !fresh && session.selectionDocument ? await session.selectionDocument(before.pageIndex) : await session.document();
|
|
40
|
+
const after = await state();
|
|
41
|
+
if (!sameSelection(before, after) || before.pageIndex !== after.pageIndex || after.pageIndex !== live.activePageIndex) {
|
|
42
|
+
throw selectionError('选区或页面正在切换,请确认选中的元素后重试。', 'SELECTION_TRANSITION');
|
|
43
|
+
}
|
|
44
|
+
const document = live.document;
|
|
45
|
+
const page = document.pages?.length ? document.pages[after.pageIndex] : document;
|
|
46
|
+
if (!page || (document.pages?.length && page.id !== after.pageId)) {
|
|
47
|
+
throw selectionError('页面尚在同步,请稍后重试。', 'SELECTION_TRANSITION');
|
|
48
|
+
}
|
|
49
|
+
const nodes = new Map();
|
|
50
|
+
const visit = (children, parentId = null) => {
|
|
51
|
+
for (const node of children || []) {
|
|
52
|
+
nodes.set(node.id, { id: node.id, name: node.name || node.type, type: node.type, parentId });
|
|
53
|
+
visit(node.children, node.id);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
visit(page.children);
|
|
57
|
+
if (after.nodeIds.some(id => !nodes.has(id))) {
|
|
58
|
+
throw selectionError('选中的元素已不存在,请重新选择。', 'SELECTION_STALE');
|
|
59
|
+
}
|
|
60
|
+
return { live, selection: { ...after, count: after.nodeIds.length, nodes: after.nodeIds.map(id => nodes.get(id)) } };
|
|
61
|
+
}
|