@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,230 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdir, mkdtemp, readFile, writeFile, rename, lstat, rm } from 'node:fs/promises';
|
|
4
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
5
|
+
import { stateRoot, sha256 } from './editor-runtime.mjs';
|
|
6
|
+
import { ensureRuntime } from './runtime-install.mjs';
|
|
7
|
+
import { post } from './transport.mjs';
|
|
8
|
+
import { snapshotMatches, diskDocument } from './document-format.mjs';
|
|
9
|
+
|
|
10
|
+
export function validateDocument(bytes) {
|
|
11
|
+
const document = JSON.parse(bytes.toString());
|
|
12
|
+
if (
|
|
13
|
+
!document
|
|
14
|
+
|| typeof document !== 'object'
|
|
15
|
+
|| Array.isArray(document)
|
|
16
|
+
|| (!Array.isArray(document.children) && !Array.isArray(document.pages))
|
|
17
|
+
) {
|
|
18
|
+
throw new Error('Expected an OpenPencil document with children or pages.');
|
|
19
|
+
}
|
|
20
|
+
return document;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function sourceBytes(path) {
|
|
24
|
+
if (!isAbsolute(path) || !path.toLowerCase().endsWith('.op')) throw new Error('Use an absolute .op file path.');
|
|
25
|
+
const stat = await lstat(path);
|
|
26
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 32 * 1024 * 1024) {
|
|
27
|
+
throw new Error('The .op source must be a regular file smaller than 32 MiB.');
|
|
28
|
+
}
|
|
29
|
+
const bytes = await readFile(path);
|
|
30
|
+
validateDocument(bytes);
|
|
31
|
+
return bytes;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function atomicSave(path, bytes, baseline) {
|
|
35
|
+
if (Buffer.byteLength(bytes) > 32 * 1024 * 1024) throw new Error('Saved document exceeds 32 MiB.');
|
|
36
|
+
validateDocument(bytes);
|
|
37
|
+
if (baseline === null) {
|
|
38
|
+
// Save As never silently replaces a different existing document.
|
|
39
|
+
await writeFile(path, bytes, { flag: 'wx', mode: 0o600 });
|
|
40
|
+
return sha256(bytes);
|
|
41
|
+
}
|
|
42
|
+
if (sha256(await sourceBytes(path)) !== baseline) {
|
|
43
|
+
throw new Error('Source changed outside this canvas. Save was stopped; keep the recovery draft.');
|
|
44
|
+
}
|
|
45
|
+
const temp = join(dirname(path), `.${basename(path)}.qoder-${randomUUID()}.tmp`);
|
|
46
|
+
try {
|
|
47
|
+
await writeFile(temp, bytes, { flag: 'wx', mode: 0o600 });
|
|
48
|
+
// Check again after staging, before replacing the source.
|
|
49
|
+
if (sha256(await sourceBytes(path)) !== baseline) throw new Error('Source changed while saving; save was stopped.');
|
|
50
|
+
await rename(temp, path);
|
|
51
|
+
return sha256(bytes);
|
|
52
|
+
} finally {
|
|
53
|
+
await rm(temp, { force: true });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function handshake(child) {
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
let buffer = '';
|
|
60
|
+
const timer = setTimeout(() => finish(new Error('Rust editor startup timed out.')), 20_000);
|
|
61
|
+
const onExit = code => finish(new Error(process.platform === 'win32' && [0xc0000135, 0xc000007b].includes(code >>> 0)
|
|
62
|
+
? 'Rust editor needs the matching Microsoft Visual C++ v14 Redistributable. Install it from Microsoft, then run setup again.'
|
|
63
|
+
: 'Rust editor exited before its handshake.'));
|
|
64
|
+
const onData = (bytes) => {
|
|
65
|
+
buffer += bytes.toString('utf8');
|
|
66
|
+
if (buffer.length > 16_384) return finish(new Error('Rust editor handshake exceeded its limit.'));
|
|
67
|
+
const newline = buffer.indexOf('\n');
|
|
68
|
+
if (newline < 0) return;
|
|
69
|
+
try {
|
|
70
|
+
const value = JSON.parse(buffer.slice(0, newline));
|
|
71
|
+
if (
|
|
72
|
+
!value.ok
|
|
73
|
+
|| !Number.isInteger(value.port)
|
|
74
|
+
|| value.port < 1
|
|
75
|
+
|| value.port > 65535
|
|
76
|
+
|| typeof value.token !== 'string'
|
|
77
|
+
|| value.token.length < 8
|
|
78
|
+
) {
|
|
79
|
+
throw new Error();
|
|
80
|
+
}
|
|
81
|
+
finish(null, value);
|
|
82
|
+
} catch {
|
|
83
|
+
finish(new Error('Invalid Rust editor startup handshake.'));
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const finish = (error, value) => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
child.stdout.off('data', onData);
|
|
89
|
+
child.off('exit', onExit);
|
|
90
|
+
child.off('error', finish);
|
|
91
|
+
if (error) reject(error); else resolve(value);
|
|
92
|
+
};
|
|
93
|
+
child.stdout.on('data', onData);
|
|
94
|
+
child.once('exit', onExit);
|
|
95
|
+
child.once('error', finish);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class EditorSession {
|
|
100
|
+
static async start({ filePath, allowOrigin, runtimeRoot }) {
|
|
101
|
+
const runtime = await ensureRuntime(runtimeRoot);
|
|
102
|
+
await mkdir(join(stateRoot(), 'sessions'), { recursive: true, mode: 0o700 });
|
|
103
|
+
const dir = await mkdtemp(join(stateRoot(), 'sessions', 'canvas-'));
|
|
104
|
+
const draft = join(dir, 'recovery.op');
|
|
105
|
+
const initial = filePath ? await sourceBytes(filePath) : Buffer.from(`{"version":"${runtime.version}","children":[]}\n`);
|
|
106
|
+
await writeFile(draft, initial, { mode: 0o600 });
|
|
107
|
+
const config = join(stateRoot(), 'settings', `${runtime.version}-${sha256(runtime.root).slice(0, 12)}`);
|
|
108
|
+
await mkdir(config, { recursive: true, mode: 0o700 });
|
|
109
|
+
const child = spawn(runtime.binary, [
|
|
110
|
+
'--serve-web',
|
|
111
|
+
'--managed',
|
|
112
|
+
'--port',
|
|
113
|
+
'0',
|
|
114
|
+
'--file',
|
|
115
|
+
draft,
|
|
116
|
+
'--allow-origin',
|
|
117
|
+
allowOrigin,
|
|
118
|
+
'--config-root',
|
|
119
|
+
config,
|
|
120
|
+
], {
|
|
121
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
122
|
+
env: {
|
|
123
|
+
...process.env,
|
|
124
|
+
OPENPENCIL_WEB_BUNDLE_DIR: runtime.webBundle,
|
|
125
|
+
OPENPENCIL_CANVASKIT_DIR: runtime.canvasKit,
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
child.stderr.on('data', () => {}); // Never relay runtime credentials or private document diagnostics.
|
|
129
|
+
try {
|
|
130
|
+
const info = await handshake(child);
|
|
131
|
+
if (String(info.version) !== runtime.version) throw new Error('Rust editor and bundle versions disagree.');
|
|
132
|
+
const session = new EditorSession();
|
|
133
|
+
Object.assign(session, {
|
|
134
|
+
child,
|
|
135
|
+
draft,
|
|
136
|
+
dir,
|
|
137
|
+
source: filePath || null,
|
|
138
|
+
baseline: filePath ? sha256(initial) : null,
|
|
139
|
+
port: info.port,
|
|
140
|
+
token: info.token,
|
|
141
|
+
version: runtime.version,
|
|
142
|
+
closed: false,
|
|
143
|
+
});
|
|
144
|
+
child.once('exit', () => { session.closed = true; });
|
|
145
|
+
await session.document();
|
|
146
|
+
return session;
|
|
147
|
+
} catch (error) {
|
|
148
|
+
child.kill();
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
assertLive() {
|
|
154
|
+
if (this.closed) throw new Error('Canvas runtime ended. Reopen the recovery draft in a new canvas.');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async document() {
|
|
158
|
+
this.assertLive();
|
|
159
|
+
const response = await fetch(`http://127.0.0.1:${this.port}/api/mcp/document`, { signal: AbortSignal.timeout(5_000) });
|
|
160
|
+
if (!response.ok) throw new Error(`Canvas document read failed (${response.status}).`);
|
|
161
|
+
const chunks = [];
|
|
162
|
+
let size = 0;
|
|
163
|
+
for await (const chunk of response.body) {
|
|
164
|
+
size += chunk.length;
|
|
165
|
+
if (size > 32 * 1024 * 1024) throw new Error('Canvas document exceeds 32 MiB.');
|
|
166
|
+
chunks.push(chunk);
|
|
167
|
+
}
|
|
168
|
+
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
169
|
+
validateDocument(JSON.stringify(value.document));
|
|
170
|
+
if (!Number.isSafeInteger(value.version)) throw new Error('Canvas document version is invalid.');
|
|
171
|
+
return value;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async forward(message) {
|
|
175
|
+
this.assertLive();
|
|
176
|
+
return post(this.port, message);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async selectionDocument(pageIndex) {
|
|
180
|
+
this.assertLive();
|
|
181
|
+
const response = await fetch(`http://127.0.0.1:${this.port}/api/mcp/version`, { signal: AbortSignal.timeout(5_000) });
|
|
182
|
+
if (!response.ok) throw new Error('Canvas version read failed.');
|
|
183
|
+
const value = await response.json();
|
|
184
|
+
if (!Number.isSafeInteger(value.version)) throw new Error('Canvas version is invalid.');
|
|
185
|
+
// Selection polling must not repeatedly transfer embedded document images.
|
|
186
|
+
if (this.selectionSnapshot?.version !== value.version || this.selectionSnapshot.activePageIndex !== pageIndex) {
|
|
187
|
+
this.selectionSnapshot = await this.document();
|
|
188
|
+
}
|
|
189
|
+
return this.selectionSnapshot;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async checkpoint() {
|
|
193
|
+
const value = await this.document();
|
|
194
|
+
const bytes = JSON.stringify(diskDocument(value)) + '\n';
|
|
195
|
+
const temp = join(this.dir, 'checkpoint.tmp');
|
|
196
|
+
await writeFile(temp, bytes, { mode: 0o600 });
|
|
197
|
+
await rename(temp, this.draft);
|
|
198
|
+
return { recoveryPath: this.draft, version: value.version };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async save({ filePath = this.source, docJson } = {}) {
|
|
202
|
+
if (!filePath || !isAbsolute(filePath) || !filePath.toLowerCase().endsWith('.op')) {
|
|
203
|
+
throw new Error('Choose an absolute .op path to save this canvas.');
|
|
204
|
+
}
|
|
205
|
+
const value = await this.document();
|
|
206
|
+
// The editor flushes its sync gate before requesting Save. Refuse a stale UI snapshot.
|
|
207
|
+
const snapshot = docJson === undefined ? diskDocument(value) : validateDocument(docJson);
|
|
208
|
+
if (docJson !== undefined && !snapshotMatches(snapshot, value)) {
|
|
209
|
+
throw new Error('The canvas changed while saving. Refresh and save again; no file was overwritten.');
|
|
210
|
+
}
|
|
211
|
+
const bytes = Buffer.from(JSON.stringify(snapshot, null, 2) + '\n');
|
|
212
|
+
const hash = await atomicSave(filePath, bytes, filePath === this.source ? this.baseline : null);
|
|
213
|
+
this.source = filePath;
|
|
214
|
+
this.baseline = hash;
|
|
215
|
+
await this.checkpoint();
|
|
216
|
+
this.lastSave = { filePath, sha256: hash, version: value.version };
|
|
217
|
+
return this.lastSave;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async close() {
|
|
221
|
+
if (this.closed) return;
|
|
222
|
+
try {
|
|
223
|
+
await this.checkpoint();
|
|
224
|
+
} finally {
|
|
225
|
+
this.closed = true;
|
|
226
|
+
this.child.stdin.end(); // Release only this daemon's supervisor lease.
|
|
227
|
+
this.child.kill();
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# GUI hosts may not inherit the terminal's Node version-manager PATH.
|
|
3
|
+
set -eu
|
|
4
|
+
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
|
5
|
+
state_dir="${OPENPENCIL_QODER_STATE_DIR:-$HOME/.qoder-openpencil}"
|
|
6
|
+
node_bin=
|
|
7
|
+
if [ -f "$state_dir/node-path" ]; then
|
|
8
|
+
IFS= read -r node_bin < "$state_dir/node-path" || true
|
|
9
|
+
fi
|
|
10
|
+
usable_node() {
|
|
11
|
+
[ -n "$1" ] && "$1" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' >/dev/null 2>&1
|
|
12
|
+
}
|
|
13
|
+
if usable_node "$node_bin"; then
|
|
14
|
+
exec "$node_bin" "$script_dir/mcp-bridge.mjs" "$@"
|
|
15
|
+
fi
|
|
16
|
+
for candidate in "$(command -v node || true)" /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do
|
|
17
|
+
if usable_node "$candidate"; then
|
|
18
|
+
exec "$candidate" "$script_dir/mcp-bridge.mjs" "$@"
|
|
19
|
+
fi
|
|
20
|
+
done
|
|
21
|
+
printf '%s\n' 'OpenPencil requires Node.js 22+. Run qoder-openpencil setup (or npm run setup from a checkout) to register your current Node executable, then reconnect the plugin.' >&2
|
|
22
|
+
exit 1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
setlocal DisableDelayedExpansion
|
|
3
|
+
rem Resolve the same private Node registration as the POSIX launcher.
|
|
4
|
+
set "state_dir=%OPENPENCIL_QODER_STATE_DIR%"
|
|
5
|
+
if not defined state_dir set "state_dir=%USERPROFILE%\.qoder-openpencil"
|
|
6
|
+
set "node_bin="
|
|
7
|
+
if exist "%state_dir%\node-path" set /p "node_bin=" < "%state_dir%\node-path"
|
|
8
|
+
if not defined node_bin goto path_node
|
|
9
|
+
if not exist "%node_bin%" goto path_node
|
|
10
|
+
"%node_bin%" -e "process.exit(Number(process.versions.node.split('.')[0]) >= 22 ? 0 : 1)" >nul 2>&1
|
|
11
|
+
if errorlevel 1 goto path_node
|
|
12
|
+
"%node_bin%" "%~dp0mcp-bridge.mjs" %*
|
|
13
|
+
exit /b %errorlevel%
|
|
14
|
+
:path_node
|
|
15
|
+
node -e "process.exit(Number(process.versions.node.split('.')[0]) >= 22 ? 0 : 1)" >nul 2>&1
|
|
16
|
+
if errorlevel 1 goto missing_node
|
|
17
|
+
node "%~dp0mcp-bridge.mjs" %*
|
|
18
|
+
exit /b %errorlevel%
|
|
19
|
+
:missing_node
|
|
20
|
+
echo OpenPencil requires Node.js 22+. Run qoder-openpencil setup (or npm run setup from a checkout) to register your current Node executable, then reconnect the plugin. >&2
|
|
21
|
+
exit /b 1
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
|
+
import { discover, errorReply, MAX_BYTES, parsePort } from './transport.mjs';
|
|
5
|
+
import { CanvasController } from './canvas-controller.mjs';
|
|
6
|
+
|
|
7
|
+
function optionsFromArgs(args) {
|
|
8
|
+
const options = { port: process.env.OPENPENCIL_MCP_PORT };
|
|
9
|
+
let doctor = false;
|
|
10
|
+
for (let i = 0; i < args.length; i++) {
|
|
11
|
+
if (args[i] === '--doctor') doctor = true;
|
|
12
|
+
else if (args[i] === '--port' && args[i + 1]) options.port = parsePort(args[++i]);
|
|
13
|
+
else throw new Error('Usage: node mcp-bridge.mjs [--doctor] [--port PORT]');
|
|
14
|
+
}
|
|
15
|
+
if (options.port !== undefined) options.port = parsePort(options.port);
|
|
16
|
+
return { options, doctor };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function write(reply) {
|
|
20
|
+
if (reply && !process.stdout.write(`${JSON.stringify(reply)}\n`)) await once(process.stdout, 'drain');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function serve(options) {
|
|
24
|
+
const canvas = new CanvasController({
|
|
25
|
+
...options,
|
|
26
|
+
onToolsChanged: () => write({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' }),
|
|
27
|
+
});
|
|
28
|
+
const shutdown = () => { process.stdin.destroy(); };
|
|
29
|
+
process.once('SIGTERM', shutdown);
|
|
30
|
+
process.once('SIGINT', shutdown);
|
|
31
|
+
const decoder = new StringDecoder('utf8');
|
|
32
|
+
let buffer = '';
|
|
33
|
+
// Serialize messages to preserve the ordering of canvas edits and notifications.
|
|
34
|
+
try {
|
|
35
|
+
for await (const chunk of process.stdin) {
|
|
36
|
+
buffer += decoder.write(chunk);
|
|
37
|
+
let newline;
|
|
38
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
39
|
+
const line = buffer.slice(0, newline);
|
|
40
|
+
buffer = buffer.slice(newline + 1);
|
|
41
|
+
if (Buffer.byteLength(line) > MAX_BYTES) throw new Error('MCP input exceeds the size limit.');
|
|
42
|
+
if (!line.trim()) continue;
|
|
43
|
+
let message;
|
|
44
|
+
try { message = JSON.parse(line); }
|
|
45
|
+
catch { await write(errorReply(null, -32700, 'Invalid JSON.')); continue; }
|
|
46
|
+
await write(await canvas.enqueue(() => canvas.dispatch(message)));
|
|
47
|
+
}
|
|
48
|
+
if (Buffer.byteLength(buffer) > MAX_BYTES) throw new Error('MCP input exceeds the size limit.');
|
|
49
|
+
}
|
|
50
|
+
buffer += decoder.end();
|
|
51
|
+
if (buffer.trim()) await write(errorReply(null, -32700, 'MCP messages must end with a newline.'));
|
|
52
|
+
} finally {
|
|
53
|
+
process.off('SIGTERM', shutdown);
|
|
54
|
+
process.off('SIGINT', shutdown);
|
|
55
|
+
await canvas.close();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const { options, doctor } = optionsFromArgs(process.argv.slice(2));
|
|
61
|
+
if (doctor) {
|
|
62
|
+
const endpoint = await discover(options);
|
|
63
|
+
process.stdout.write(`${JSON.stringify({ ok: true, ...endpoint, transport: 'json-rpc' })}\n`);
|
|
64
|
+
} else {
|
|
65
|
+
await serve(options);
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
process.stderr.write(`OpenPencil: ${error.message}\n`);
|
|
69
|
+
process.exitCode = 1;
|
|
70
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import {
|
|
6
|
+
assertSupportedLibc,
|
|
7
|
+
defaultPackageRoot,
|
|
8
|
+
hasPackageCatalog,
|
|
9
|
+
resolveEditorRuntime,
|
|
10
|
+
resolveRuntime,
|
|
11
|
+
stateRoot,
|
|
12
|
+
} from './editor-runtime.mjs';
|
|
13
|
+
|
|
14
|
+
export { assertSupportedLibc };
|
|
15
|
+
|
|
16
|
+
const MANAGED_SOURCES = new Set(['optional-package', 'development-package', 'release']);
|
|
17
|
+
|
|
18
|
+
export async function configureRuntime(root, state = stateRoot(), metadata = {}) {
|
|
19
|
+
const runtime = await resolveRuntime(root);
|
|
20
|
+
await mkdir(state, { recursive: true, mode: 0o700 });
|
|
21
|
+
const temporary = join(state, `.runtime-${randomUUID()}.json`);
|
|
22
|
+
try {
|
|
23
|
+
await writeFile(temporary, JSON.stringify({ ...metadata, root: runtime.root }) + '\n', { flag: 'wx', mode: 0o600 });
|
|
24
|
+
await rename(temporary, join(state, 'runtime.json'));
|
|
25
|
+
} finally {
|
|
26
|
+
await rm(temporary, { force: true });
|
|
27
|
+
}
|
|
28
|
+
return runtime;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Resolve the installed npm platform package (or staged dev package) and record it in private state. */
|
|
32
|
+
export async function activatePackageRuntime(options = {}) {
|
|
33
|
+
const state = resolve(options.state ?? stateRoot());
|
|
34
|
+
const [parsedOs, parsedArch] = typeof options.platform === 'string' && options.platform.includes('-')
|
|
35
|
+
? options.platform.split('-', 2)
|
|
36
|
+
: [];
|
|
37
|
+
const platformName = options.platformName ?? parsedOs ?? process.platform;
|
|
38
|
+
const arch = options.arch ?? parsedArch ?? process.arch;
|
|
39
|
+
const platform = options.platform ?? `${platformName}-${arch}`;
|
|
40
|
+
if (platformName === 'linux') {
|
|
41
|
+
const glibc = options.glibc !== undefined ? options.glibc : process.report?.getReport?.().header?.glibcVersionRuntime;
|
|
42
|
+
assertSupportedLibc(platform, glibc);
|
|
43
|
+
}
|
|
44
|
+
const projectRoot = options.projectRoot ?? defaultPackageRoot();
|
|
45
|
+
const resolved = resolveEditorRuntime({
|
|
46
|
+
platform: platformName,
|
|
47
|
+
arch,
|
|
48
|
+
env: options.env ?? {},
|
|
49
|
+
projectRoot,
|
|
50
|
+
catalog: options.catalog,
|
|
51
|
+
resolvePackageJson: options.resolvePackageJson,
|
|
52
|
+
readFile: options.readFile,
|
|
53
|
+
stat: options.stat,
|
|
54
|
+
lstat: options.lstat,
|
|
55
|
+
realpath: options.realpath,
|
|
56
|
+
chmod: options.chmod,
|
|
57
|
+
});
|
|
58
|
+
const root = dirname(dirname(resolved.binary));
|
|
59
|
+
const packageName = `@zseven-w/qoder-openpencil-${platform}`;
|
|
60
|
+
const metadata = {
|
|
61
|
+
source: resolved.source,
|
|
62
|
+
packageName,
|
|
63
|
+
openPencilVersion: resolved.openPencilVersion,
|
|
64
|
+
openPencilRevision: resolved.revision,
|
|
65
|
+
platform,
|
|
66
|
+
};
|
|
67
|
+
if (options.stat || options.readFile) {
|
|
68
|
+
return {
|
|
69
|
+
root,
|
|
70
|
+
version: resolved.openPencilVersion,
|
|
71
|
+
revision: resolved.revision,
|
|
72
|
+
packageName,
|
|
73
|
+
binary: resolved.binary,
|
|
74
|
+
webBundle: resolved.webBundleDir,
|
|
75
|
+
canvasKit: resolved.canvasKitDir,
|
|
76
|
+
source: resolved.source,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const runtime = await configureRuntime(root, state, metadata);
|
|
80
|
+
return { ...runtime, source: resolved.source };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export const installRuntime = activatePackageRuntime;
|
|
84
|
+
|
|
85
|
+
export async function ensureRuntime(root, options = {}) {
|
|
86
|
+
if (root || process.env.OPENPENCIL_EDITOR_RUNTIME_DIR) return resolveRuntime(root);
|
|
87
|
+
const state = resolve(options.state ?? stateRoot());
|
|
88
|
+
const projectRoot = options.projectRoot ?? defaultPackageRoot();
|
|
89
|
+
const catalogAvailable = options.catalog !== undefined || hasPackageCatalog(projectRoot);
|
|
90
|
+
|
|
91
|
+
let config;
|
|
92
|
+
try {
|
|
93
|
+
config = JSON.parse(await readFile(join(state, 'runtime.json'), 'utf8'));
|
|
94
|
+
} catch (error) {
|
|
95
|
+
if (error.code !== 'ENOENT') throw new Error(`Invalid runtime configuration: ${error.message}`);
|
|
96
|
+
if (catalogAvailable) return activatePackageRuntime({ ...options, state, projectRoot });
|
|
97
|
+
throw new Error(
|
|
98
|
+
'OpenPencil editor runtime is not configured. Install @zseven-w/qoder-openpencil via npm (without --omit=optional) and run qoder-openpencil setup, or set OPENPENCIL_EDITOR_RUNTIME_DIR.',
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
if (!config || typeof config !== 'object' || Array.isArray(config) || typeof config.root !== 'string' || !isAbsolute(config.root)) {
|
|
102
|
+
throw new Error('Invalid runtime configuration: expected an absolute runtime root.');
|
|
103
|
+
}
|
|
104
|
+
if (MANAGED_SOURCES.has(config.source)) {
|
|
105
|
+
if (catalogAvailable) return activatePackageRuntime({ ...options, state, projectRoot });
|
|
106
|
+
const expected = config.source === 'release'
|
|
107
|
+
? {}
|
|
108
|
+
: {
|
|
109
|
+
packageName: config.packageName,
|
|
110
|
+
openPencilVersion: config.openPencilVersion,
|
|
111
|
+
openPencilRevision: config.openPencilRevision,
|
|
112
|
+
};
|
|
113
|
+
const runtime = await resolveRuntime(config.root, expected);
|
|
114
|
+
return { ...runtime, source: config.source };
|
|
115
|
+
}
|
|
116
|
+
const runtime = await resolveRuntime(config.root);
|
|
117
|
+
return { ...runtime, source: config.source || 'custom' };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
121
|
+
try {
|
|
122
|
+
const runtime = await activatePackageRuntime();
|
|
123
|
+
console.log(JSON.stringify({ ok: true, version: runtime.version, root: runtime.root, source: runtime.source }));
|
|
124
|
+
} catch (error) {
|
|
125
|
+
console.error(`OpenPencil runtime setup failed: ${error.message}`);
|
|
126
|
+
process.exitCode = 1;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export const MAX_BYTES = 32 * 1024 * 1024;
|
|
7
|
+
|
|
8
|
+
export function parsePort(value) {
|
|
9
|
+
const port = Number(value);
|
|
10
|
+
if (!/^\d+$/.test(String(value)) || !Number.isInteger(port) || port < 1 || port > 65535) {
|
|
11
|
+
throw new Error('OpenPencil port must be an integer from 1 to 65535.');
|
|
12
|
+
}
|
|
13
|
+
return port;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Direct loopback HTTP: no proxy, remote URL, redirect, or shell execution.
|
|
17
|
+
export function post(port, message, { timeout = 120_000, maxBytes = MAX_BYTES } = {}) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
const body = JSON.stringify(message);
|
|
20
|
+
const request = http.request({
|
|
21
|
+
host: '127.0.0.1',
|
|
22
|
+
port,
|
|
23
|
+
path: '/mcp',
|
|
24
|
+
method: 'POST',
|
|
25
|
+
headers: {
|
|
26
|
+
'Content-Type': 'application/json',
|
|
27
|
+
Accept: 'application/json, text/event-stream',
|
|
28
|
+
'Content-Length': Buffer.byteLength(body),
|
|
29
|
+
},
|
|
30
|
+
}, (response) => {
|
|
31
|
+
const chunks = [];
|
|
32
|
+
let size = 0;
|
|
33
|
+
response.on('data', (chunk) => {
|
|
34
|
+
size += chunk.length;
|
|
35
|
+
if (size > maxBytes) {
|
|
36
|
+
response.destroy(new Error('OpenPencil response exceeds the size limit.'));
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
chunks.push(chunk);
|
|
40
|
+
});
|
|
41
|
+
response.on('error', reject);
|
|
42
|
+
response.on('end', () => {
|
|
43
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
44
|
+
reject(new Error(`OpenPencil returned HTTP ${response.statusCode}; the request was not retried.`));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
48
|
+
if (!text.trim()) {
|
|
49
|
+
if (!Object.hasOwn(message, 'id')) resolve(null);
|
|
50
|
+
else reject(new Error('OpenPencil returned an empty response to a request.'));
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const reply = JSON.parse(text);
|
|
55
|
+
if (!Object.hasOwn(message, 'id')) { resolve(null); return; }
|
|
56
|
+
if (
|
|
57
|
+
reply.jsonrpc !== '2.0'
|
|
58
|
+
|| reply.id !== message.id
|
|
59
|
+
|| (!Object.hasOwn(reply, 'result') && !Object.hasOwn(reply, 'error'))
|
|
60
|
+
) {
|
|
61
|
+
throw new Error();
|
|
62
|
+
}
|
|
63
|
+
resolve(reply);
|
|
64
|
+
} catch {
|
|
65
|
+
reject(new Error('OpenPencil returned an invalid JSON-RPC response.'));
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
const timer = setTimeout(() => request.destroy(new Error(
|
|
70
|
+
'OpenPencil request timed out; it was not retried. Inspect the canvas before repeating an edit.',
|
|
71
|
+
)), timeout);
|
|
72
|
+
request.on('close', () => clearTimeout(timer));
|
|
73
|
+
request.on('error', (error) => reject(error.code
|
|
74
|
+
? new Error(`Cannot reach local OpenPencil (${error.code}). Start its MCP server, then reconnect.`)
|
|
75
|
+
: error));
|
|
76
|
+
request.end(body);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function identityOf(reply) {
|
|
81
|
+
const result = reply?.result;
|
|
82
|
+
const identity = result?._meta ?? result;
|
|
83
|
+
if (identity?.server !== 'openpencil-mcp') {
|
|
84
|
+
throw new Error('The local endpoint is not a Rust OpenPencil MCP server.');
|
|
85
|
+
}
|
|
86
|
+
return identity;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function discover({ port, discoveryFile = join(homedir(), '.openpencil', '.op-mcp-port') } = {}) {
|
|
90
|
+
let expectedToken;
|
|
91
|
+
if (port !== undefined) {
|
|
92
|
+
port = parsePort(port);
|
|
93
|
+
} else {
|
|
94
|
+
let record;
|
|
95
|
+
try { record = JSON.parse(await readFile(discoveryFile, 'utf8')); }
|
|
96
|
+
catch {
|
|
97
|
+
throw new Error('No valid OpenPencil discovery record. Start the Rust editor and enable MCP, or set OPENPENCIL_MCP_PORT.');
|
|
98
|
+
}
|
|
99
|
+
if (record.transport !== 'json-rpc' || typeof record.token !== 'string' || !record.token) {
|
|
100
|
+
throw new Error('Invalid OpenPencil discovery record: expected json-rpc transport and an instance token.');
|
|
101
|
+
}
|
|
102
|
+
port = parsePort(record.port);
|
|
103
|
+
expectedToken = record.token;
|
|
104
|
+
}
|
|
105
|
+
const identity = identityOf(await post(port, { jsonrpc: '2.0', id: 'identity', method: 'ping' }, { timeout: 3_000 }));
|
|
106
|
+
if (expectedToken !== undefined && (identity.mode !== 'live' || identity.token !== expectedToken)) {
|
|
107
|
+
throw new Error('OpenPencil discovery record is stale: instance identity does not match. Reopen the editor.');
|
|
108
|
+
}
|
|
109
|
+
return { port, mode: identity.mode ?? 'unknown' };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function errorReply(id, code, message) {
|
|
113
|
+
return { jsonrpc: '2.0', id, error: { code, message } };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function forward(message, options) {
|
|
117
|
+
if (
|
|
118
|
+
!message
|
|
119
|
+
|| typeof message !== 'object'
|
|
120
|
+
|| Array.isArray(message)
|
|
121
|
+
|| message.jsonrpc !== '2.0'
|
|
122
|
+
|| typeof message.method !== 'string'
|
|
123
|
+
|| (Object.hasOwn(message, 'id')
|
|
124
|
+
&& message.id !== null
|
|
125
|
+
&& typeof message.id !== 'string'
|
|
126
|
+
&& typeof message.id !== 'number')
|
|
127
|
+
) {
|
|
128
|
+
return errorReply(null, -32600, 'Expected a JSON-RPC 2.0 request or notification.');
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
const endpoint = await discover(options);
|
|
132
|
+
return await post(endpoint.port, message);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
// Never include raw server bodies or the discovery token in a diagnostic.
|
|
135
|
+
if (!Object.hasOwn(message, 'id')) return null;
|
|
136
|
+
return errorReply(message.id, -32000, error.message);
|
|
137
|
+
}
|
|
138
|
+
}
|