@thready-web/dsh-bot-plugin 0.1.0-beta.10 → 0.1.0-beta.12
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/README.md +19 -2
- package/dist/approvals.js +19 -1
- package/dist/canvas-compose.js +73 -0
- package/dist/canvas-http.js +379 -0
- package/dist/canvas-skills.js +56 -0
- package/dist/canvas-store.js +1015 -0
- package/dist/canvas-tools.js +380 -0
- package/dist/card-log.js +216 -0
- package/dist/context.js +6 -3
- package/dist/deleting.js +54 -0
- package/dist/desk-ledger.js +18 -0
- package/dist/desk.js +30 -5
- package/dist/http-plugin.js +2 -1
- package/dist/http.js +218 -3
- package/dist/inbox.js +24 -2
- package/dist/index.js +75 -12
- package/dist/questions.js +10 -0
- package/dist/runtime-registry.js +20 -0
- package/dist/session-delete-job.js +77 -0
- package/dist/session-files.js +33 -1
- package/dist/session-wipe.js +204 -0
- package/dist/store.js +46 -3
- package/dist/triggers.js +8 -0
- package/dist/work-admit.js +9 -20
- package/dist/work-child.js +27 -10
- package/dist/work-http.js +19 -0
- package/dist/work-ledger.js +5 -1
- package/dist/work-mock.js +10 -0
- package/dist/work-tickets.js +5 -3
- package/dist/work-tools.js +11 -9
- package/dist/work-worker.js +245 -6
- package/dist/worker-handles.js +33 -0
- package/dist/workspace-files.js +98 -17
- package/package.json +2 -1
- package/public/assets/{SourceEditor-BEQaScgR.js → SourceEditor-BjtoMvcX.js} +3 -3
- package/public/assets/{cssMode-gpcjCFFS.js → cssMode--96PQtWh.js} +1 -1
- package/public/assets/{freemarker2-C1qemGIt.js → freemarker2-Bz-HlISL.js} +1 -1
- package/public/assets/{handlebars-sZqIfAlP.js → handlebars-D9ScJ8AM.js} +1 -1
- package/public/assets/{html-Bn1WXB8L.js → html-Czc0jojJ.js} +1 -1
- package/public/assets/{htmlMode-CvQyXnaW.js → htmlMode-CCww5Z1w.js} +1 -1
- package/public/assets/index-DRCgKxWk.css +1 -0
- package/public/assets/index-ztUdW074.js +72 -0
- package/public/assets/{javascript-Ox4Jg12j.js → javascript-B-yRZSiz.js} +1 -1
- package/public/assets/{jsonMode-DMR7R2dQ.js → jsonMode-ASWsY833.js} +1 -1
- package/public/assets/{liquid-B6HxtpBd.js → liquid-BGoox2vJ.js} +1 -1
- package/public/assets/{mdx--jDhmrXq.js → mdx-DHgvnl_U.js} +1 -1
- package/public/assets/{python-YjG50skX.js → python-BJvVD30_.js} +1 -1
- package/public/assets/{razor-CEcFE3UK.js → razor-0PwR35mu.js} +1 -1
- package/public/assets/{tsMode-g4kTQl09.js → tsMode-3ETp8Gdh.js} +1 -1
- package/public/assets/{typescript-CnHeFmPW.js → typescript-BT0iTK6K.js} +1 -1
- package/public/assets/{xml-BFXMY9nb.js → xml-BTaNc_uT.js} +1 -1
- package/public/assets/{yaml-DNm87nSf.js → yaml-Dr7LW3tK.js} +1 -1
- package/public/index.html +2 -2
- package/skills/ui/baseline-ui/SKILL.md +85 -0
- package/skills/ui/bencium-innovative-ux-designer/SKILL.md +227 -0
- package/skills/ui/better-ui/SKILL.md +133 -0
- package/skills/ui/design-lab/SKILL.md +920 -0
- package/skills/ui/frontend-design/SKILL.md +71 -0
- package/skills/ui/impeccable/SKILL.md +93 -0
- package/skills/ui/interface-design/SKILL.md +320 -0
- package/skills/ui/sources.json +66 -0
- package/skills/ui/ui-design/SKILL.md +41 -0
- package/skills/ui/ui-skills-root/SKILL.md +59 -0
- package/skills/ui/visual-design-foundations/SKILL.md +318 -0
- package/skills/ui/web-design-guidelines/SKILL.md +39 -0
- package/public/assets/index-DRNkUrer.css +0 -1
- package/public/assets/index-DhL5Kdlz.js +0 -63
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ Parked `needs_user` tickets still count toward the combined unfinished cap (`slo
|
|
|
83
83
|
|
|
84
84
|
Workers share the owner's workspace. There is no filesystem isolation; briefings should state file boundaries, or dependent work should stay serial.
|
|
85
85
|
|
|
86
|
-
Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. The host sandbox stays `workspace-write` with the existing approval policy. This does not mount the web preset, add writable roots, or switch the sandbox to `danger-full-access`. A reserved start that does not create a worker within `min(ticket wallMs, 10m)` fails with `reserve-wall` and frees the slot; a late `createChild` is cancelled instead of attached.
|
|
86
|
+
Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. A canvas worker uses `foundations-canvas` instead, which mounts the file tools with `write` and `edit` disabled and does not mount bash or jobs. Preview bytes go through `canvas_write`, not the workspace. The host sandbox stays `workspace-write` with the existing approval policy. This does not mount the web preset, add writable roots, or switch the sandbox to `danger-full-access`. A reserved start that does not create a worker within `min(ticket wallMs, 10m)` fails with `reserve-wall` and frees the slot; a late `createChild` is cancelled instead of attached.
|
|
87
87
|
|
|
88
88
|
Runnable examples (any one of these is enough; `config.work` wins over the environment):
|
|
89
89
|
|
|
@@ -117,7 +117,7 @@ A granted worker token/runtime cap pauses admission at the official asynchronous
|
|
|
117
117
|
|
|
118
118
|
The ticket retains its attempt, fencing token and child session. `budget_json.quota` durably records cumulative committed `usage.totalTokens`, deduplication sequence, active elapsed time, and requested/waiting phase. Active time includes finishing in-flight work until the safe boundary; suspended-boundary waiting time is excluded. Waiting is exempt from lease/enqueue expiry and has no hard-wall failure timer. It retains a worker slot to preserve capacity accounting; the main bot is not in this worker gate or slot pool and can always grant, deny or cancel. Explicit cancellation releases the slot normally.
|
|
119
119
|
|
|
120
|
-
A grant adds amounts, never resets usage, and must exceed both current token usage and active time. An insufficient grant leaves the gate closed without another noisy extension event; its response includes usage, required totals, and the minimum additional amounts. One slice is
|
|
120
|
+
A grant adds amounts, never resets usage, and must exceed both current token usage and active time. An insufficient grant leaves the gate closed without another noisy extension event; its response includes usage, required totals, and the minimum additional amounts. One slice is 2,000,000 tokens and 60 minutes. Every dispatch starts on that slice. A budget passed with the dispatch is ignored. Every later grant adds at least another slice. There is no cumulative ceiling and no limit on how many times a ticket can be extended. A refusal from the main session is ignored: another full slice is granted instead.
|
|
121
121
|
|
|
122
122
|
Budget requests are urgent next-turn inbox notices, bypassing stale notice/user/delivery admission barriers without steering or interrupting the main turn. Admission is single-flight per owner and rechecks grant/cancellation races before persisting a notice. Ordinary progress retains its existing admission policy. The workbench labels suspended workers “Waiting for budget”.
|
|
123
123
|
|
|
@@ -127,6 +127,23 @@ A process restart cannot preserve an in-memory DSH turn: the durable wait surviv
|
|
|
127
127
|
|
|
128
128
|
Workbench sessions start in `THREADY_SESSION_CWD` when set, otherwise in `<DSH_HOME>/workspace` (created on first use), never in `DSH_HOME` itself, which holds the owner token and profiles.
|
|
129
129
|
|
|
130
|
+
The file drawer's Home root is a directory you choose, separate from process `HOME`. Set an existing directory with the http plugin's `files.home` or with `THREADY_FILES_HOME` (config wins). Leave `HOME` and `DSH_HOME` unchanged. The home directory is rejected when it is missing, not a directory, `DSH_HOME`, anything inside `DSH_HOME`, `/`, or `/etc`. Symlinks are judged by their real path. An invalid explicit value is not replaced with process `HOME`. When neither value is set, process `HOME` is used only if it passes those checks.
|
|
131
|
+
|
|
132
|
+
A workspace that is a subdirectory of `DSH_HOME` stays readable. A workspace that is `DSH_HOME`, or that contains it, stays closed. The one exception is a session whose stored cwd is exactly `DSH_HOME`: the drawer shows the configured session workspace instead, and only when that path is itself a safe directory. The stored cwd, session id, and history are not rewritten. Any other overlapping cwd stays closed.
|
|
133
|
+
|
|
134
|
+
```yaml
|
|
135
|
+
- insert:
|
|
136
|
+
- id: session-foundations-http
|
|
137
|
+
name: "@thready-web/dsh-bot-plugin/http"
|
|
138
|
+
config:
|
|
139
|
+
files:
|
|
140
|
+
home: /opt/dsh-bot/files
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
THREADY_FILES_HOME=/opt/dsh-bot/files
|
|
145
|
+
```
|
|
146
|
+
|
|
130
147
|
Generated raster previews can be embedded at `/dsh-bot/<project>/preview/<image>` or `/dsh-bot/<project>/artifacts/<image>`. These are deliberate artifact directories under that configured workspace, not a general file server or a per-session sharing boundary: authenticated workbench users can view their images. Only JPEG, PNG, GIF and WebP with matching signatures are served, with private/no-store caching. Dotfiles, traversal, symlink escapes, other workspace locations and active HTML/SVG are rejected. With no configured workspace this fallback is disabled. Relative Markdown image paths resolve under `/dsh-bot/`; existing absolute URLs remain unchanged.
|
|
131
148
|
|
|
132
149
|
Markdown images use bounded, aspect-preserving thumbnails. Click to open a viewport-fit dialog, then choose Original size to scroll through screenshot details. Escape, the close button or the backdrop dismisses it, restoring focus and body scrolling. Linked images expose their link separately from the preview control. Preview and unavailable-state labels follow the English/Chinese UI catalog.
|
package/dist/approvals.js
CHANGED
|
@@ -42,7 +42,7 @@ function displayReasonOf(value) {
|
|
|
42
42
|
}
|
|
43
43
|
return display;
|
|
44
44
|
}
|
|
45
|
-
export function createApprovalAnswerer() {
|
|
45
|
+
export function createApprovalAnswerer(record) {
|
|
46
46
|
const pending = new Set();
|
|
47
47
|
const settled = [];
|
|
48
48
|
let nextId = 1;
|
|
@@ -91,6 +91,13 @@ export function createApprovalAnswerer() {
|
|
|
91
91
|
};
|
|
92
92
|
entry.onAbort = onAbort;
|
|
93
93
|
pending.add(entry);
|
|
94
|
+
record?.({
|
|
95
|
+
sessionId,
|
|
96
|
+
requestId: entry.requestId,
|
|
97
|
+
toolName,
|
|
98
|
+
reason: textOf(request.reason),
|
|
99
|
+
...(callId === '' ? {} : { callId }),
|
|
100
|
+
});
|
|
94
101
|
if (request.signal?.aborted) {
|
|
95
102
|
onAbort();
|
|
96
103
|
return;
|
|
@@ -120,6 +127,16 @@ export function createApprovalAnswerer() {
|
|
|
120
127
|
entry.resolve(input.outcome);
|
|
121
128
|
return { ok: true, path: 'approval', outcome: input.outcome, requestId: entry.requestId };
|
|
122
129
|
}
|
|
130
|
+
function abandonSession(sessionId) {
|
|
131
|
+
for (const entry of [...pending]) {
|
|
132
|
+
if (entry.sessionId !== sessionId)
|
|
133
|
+
continue;
|
|
134
|
+
if (!detach(entry))
|
|
135
|
+
continue;
|
|
136
|
+
remember(entry, 'unavailable');
|
|
137
|
+
entry.resolve('unavailable');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
123
140
|
function snapshot(sessionId) {
|
|
124
141
|
const open = [...pending]
|
|
125
142
|
.filter(entry => !sessionId || entry.sessionId === sessionId)
|
|
@@ -152,6 +169,7 @@ export function createApprovalAnswerer() {
|
|
|
152
169
|
listen,
|
|
153
170
|
handle,
|
|
154
171
|
submit,
|
|
172
|
+
abandonSession,
|
|
155
173
|
snapshot,
|
|
156
174
|
pendingCount() {
|
|
157
175
|
return pending.size;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { parseHTML } from 'linkedom';
|
|
2
|
+
const DROP = new Set(['script', 'iframe', 'object', 'embed', 'base', 'meta', 'svg', 'foreignobject']);
|
|
3
|
+
function isRelativeAsset(href) {
|
|
4
|
+
if (href === '' || href.length > 200)
|
|
5
|
+
return false;
|
|
6
|
+
if (/[\s\\]/.test(href) || href.includes('..'))
|
|
7
|
+
return false;
|
|
8
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//') || href.startsWith('/'))
|
|
9
|
+
return false;
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
function escapeAttr(value) {
|
|
13
|
+
return value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
14
|
+
}
|
|
15
|
+
/** Keep a head <style> from closing itself and becoming markup. */
|
|
16
|
+
function escapeStyle(css) {
|
|
17
|
+
return css.replace(/<\/(style)/gi, '<\\/$1');
|
|
18
|
+
}
|
|
19
|
+
function scrub(el) {
|
|
20
|
+
for (const child of Array.from(el.children)) {
|
|
21
|
+
const tag = child.tagName.toLowerCase();
|
|
22
|
+
if (DROP.has(tag)) {
|
|
23
|
+
child.remove();
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
for (const attr of Array.from(child.attributes)) {
|
|
27
|
+
const name = attr.name.toLowerCase();
|
|
28
|
+
const value = attr.value.trim();
|
|
29
|
+
if (name.startsWith('on') || name === 'srcdoc')
|
|
30
|
+
child.removeAttribute(attr.name);
|
|
31
|
+
else if ((name === 'href' || name === 'src' || name === 'action' || name === 'formaction') &&
|
|
32
|
+
/^(javascript:|data:|https?:|\/\/)/i.test(value))
|
|
33
|
+
child.removeAttribute(attr.name);
|
|
34
|
+
}
|
|
35
|
+
scrub(child);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Scriptless design plus the host inspector. CSP stays with the caller. */
|
|
39
|
+
export function composeInspect(html, options) {
|
|
40
|
+
const { document } = parseHTML(html);
|
|
41
|
+
const sheets = [];
|
|
42
|
+
for (const node of Array.from(document.querySelectorAll('link, style'))) {
|
|
43
|
+
if (document.body.contains(node))
|
|
44
|
+
continue;
|
|
45
|
+
if (node.tagName === 'STYLE') {
|
|
46
|
+
const media = node.getAttribute('media');
|
|
47
|
+
const mediaAttr = media && media.length <= 200 && !/[\r\n<>]/.test(media) ? ` media="${escapeAttr(media)}"` : '';
|
|
48
|
+
sheets.push(`<style${mediaAttr}>${escapeStyle(node.textContent ?? '')}</style>`);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const rel = (node.getAttribute('rel') ?? '').toLowerCase();
|
|
52
|
+
const href = (node.getAttribute('href') ?? '').trim();
|
|
53
|
+
if (!rel.split(/\s+/).includes('stylesheet') || !isRelativeAsset(href))
|
|
54
|
+
continue;
|
|
55
|
+
sheets.push(`<link rel="stylesheet" href="${escapeAttr(href)}">`);
|
|
56
|
+
}
|
|
57
|
+
scrub(document.body);
|
|
58
|
+
return `<!doctype html>
|
|
59
|
+
<html>
|
|
60
|
+
<head>
|
|
61
|
+
<meta charset="utf-8">
|
|
62
|
+
<base href="${escapeAttr(options.baseHref)}">
|
|
63
|
+
<meta name="dsh-inspect-nonce" content="${escapeAttr(options.nonce)}">
|
|
64
|
+
<meta name="dsh-parent-origin" content="${escapeAttr(options.parentOrigin)}">
|
|
65
|
+
${options.page ? `<meta name="dsh-inspect-page" content="${escapeAttr(options.page)}">` : ''}
|
|
66
|
+
${sheets.join('\n')}
|
|
67
|
+
</head>
|
|
68
|
+
<body>
|
|
69
|
+
${document.body.innerHTML}
|
|
70
|
+
<script src="${escapeAttr(options.inspectorSrc)}"></script>
|
|
71
|
+
</body>
|
|
72
|
+
</html>`;
|
|
73
|
+
}
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { buildSync } from 'esbuild';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { composeInspect } from "./canvas-compose.js";
|
|
5
|
+
import { asStoreFailure, toolError } from "./errors.js";
|
|
6
|
+
import { CANVAS_MAX_JSON_BYTES, normalizeCanvasPath } from "./canvas-store.js";
|
|
7
|
+
const API = '/session-foundations/api/canvas';
|
|
8
|
+
const MEDIA = '/dsh-bot/canvas-media/';
|
|
9
|
+
const INSPECT = '/dsh-bot/canvas-inspect/';
|
|
10
|
+
const INSPECTOR = '/dsh-bot/canvas-inspector.js';
|
|
11
|
+
const CANVAS_ID = /^cnv_[A-Za-z0-9_-]{16}$/;
|
|
12
|
+
/**
|
|
13
|
+
* Manual and test publish routes. They require the existing login gate.
|
|
14
|
+
* Model tools do not call them. Media routes are dispatched before that gate
|
|
15
|
+
* and accept only the capability token.
|
|
16
|
+
*/
|
|
17
|
+
export async function handleCanvasApi(req, path, url, canvas) {
|
|
18
|
+
try {
|
|
19
|
+
const method = req.method ?? 'GET';
|
|
20
|
+
if (method === 'POST' && path === API) {
|
|
21
|
+
const body = await readBody(req);
|
|
22
|
+
return outcome(canvas.create({ sessionId: body.sessionId, title: body.title, ticketId: body.ticketId, createdBy: 'user' }));
|
|
23
|
+
}
|
|
24
|
+
if (method === 'GET' && path === API)
|
|
25
|
+
return outcome(canvas.list(url.searchParams.get('sessionId') ?? ''));
|
|
26
|
+
const parts = path.slice(API.length + 1).split('/');
|
|
27
|
+
const id = parts[0] ?? '';
|
|
28
|
+
if (!CANVAS_ID.test(id))
|
|
29
|
+
return { status: 404, body: toolError('NOT_FOUND', 'No such canvas.') };
|
|
30
|
+
if (method === 'GET' && parts.length === 1)
|
|
31
|
+
return outcome(canvas.get(id));
|
|
32
|
+
if (method === 'GET' && parts[1] === 'revisions' && parts.length === 3) {
|
|
33
|
+
const revision = Number(parts[2]);
|
|
34
|
+
if (!/^[1-9]\d{0,8}$/.test(parts[2] ?? ''))
|
|
35
|
+
return { status: 404, body: toolError('NOT_FOUND', 'No such revision.') };
|
|
36
|
+
return outcome(canvas.manifest(id, revision));
|
|
37
|
+
}
|
|
38
|
+
if (method !== 'POST' || parts.length !== 2)
|
|
39
|
+
return { status: 404, body: toolError('NOT_FOUND', 'No such canvas route.') };
|
|
40
|
+
const body = await readBody(req);
|
|
41
|
+
if (parts[1] === 'snapshot' || parts[1] === 'delta') {
|
|
42
|
+
const files = decodeFiles(body.files);
|
|
43
|
+
if (!Array.isArray(files))
|
|
44
|
+
return { status: 400, body: files };
|
|
45
|
+
return outcome(await canvas.publish({
|
|
46
|
+
canvasId: id,
|
|
47
|
+
kind: parts[1],
|
|
48
|
+
baseRevision: typeof body.baseRevision === 'number' ? body.baseRevision : null,
|
|
49
|
+
entry: typeof body.entry === 'string' ? body.entry : '',
|
|
50
|
+
expectedFence: typeof body.expectedFence === 'number' ? body.expectedFence : -1,
|
|
51
|
+
files,
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
if (parts[1] === 'token') {
|
|
55
|
+
const revision = typeof body.revision === 'number' ? body.revision : null;
|
|
56
|
+
const minRevision = typeof body.minRevision === 'number' ? body.minRevision : revision;
|
|
57
|
+
const maxRevision = typeof body.maxRevision === 'number' ? body.maxRevision : revision;
|
|
58
|
+
if (minRevision == null || maxRevision == null)
|
|
59
|
+
return { status: 400, body: toolError('VALIDATION', 'revision is required.') };
|
|
60
|
+
return outcome(canvas.mint({ canvasId: id, minRevision, maxRevision }));
|
|
61
|
+
}
|
|
62
|
+
if (parts[1] === 'adopt')
|
|
63
|
+
return outcome(await canvas.adopt({ canvasId: id, revision: typeof body.revision === 'number' ? body.revision : 0 }));
|
|
64
|
+
if (parts[1] === 'revoke')
|
|
65
|
+
return outcome(canvas.revoke({ canvasId: id, tokenId: typeof body.tokenId === 'string' ? body.tokenId : '' }));
|
|
66
|
+
if (parts[1] === 'fail') {
|
|
67
|
+
return outcome(await canvas.fail({
|
|
68
|
+
canvasId: id,
|
|
69
|
+
expectedFence: typeof body.expectedFence === 'number' ? body.expectedFence : -1,
|
|
70
|
+
message: typeof body.message === 'string' ? body.message : '',
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
return { status: 404, body: toolError('NOT_FOUND', 'No such canvas route.') };
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
|
|
77
|
+
if (code === 'VALIDATION')
|
|
78
|
+
return {
|
|
79
|
+
status: 400,
|
|
80
|
+
body: toolError('VALIDATION', error instanceof Error ? error.message : 'invalid canvas request'),
|
|
81
|
+
};
|
|
82
|
+
return { status: 500, body: asStoreFailure(error) };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Token-only media. A login cookie or Authorization header does not grant access.
|
|
87
|
+
* @param {string} requestUrl raw request target, before URL normalization
|
|
88
|
+
*/
|
|
89
|
+
export function serveCanvasMedia(req, res, requestUrl, canvas) {
|
|
90
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
91
|
+
json(res, 405, toolError('VALIDATION', 'canvas media is read-only.'));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const parsed = parseCanvasMedia(requestUrl);
|
|
95
|
+
if (!parsed) {
|
|
96
|
+
json(res, 400, toolError('VALIDATION', 'canvas media path is not allowed.'));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (!canvas) {
|
|
100
|
+
json(res, 404, toolError('NOT_FOUND', 'No such canvas file.'));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const found = canvas.readMedia(parsed);
|
|
104
|
+
if (found.ok === false) {
|
|
105
|
+
json(res, found.code === 'NOT_FOUND' ? 404 : found.code === 'VALIDATION' ? 400 : 401, found);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const origin = requestOrigin(req);
|
|
109
|
+
if (origin === '') {
|
|
110
|
+
json(res, 400, toolError('VALIDATION', 'canvas media needs a host.'));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const headers = {
|
|
114
|
+
'content-type': found.type === 'text/html' || found.type === 'text/css' ? `${found.type}; charset=utf-8` : found.type,
|
|
115
|
+
'content-length': String(found.bytes.length),
|
|
116
|
+
'cache-control': 'private, no-store',
|
|
117
|
+
'x-content-type-options': 'nosniff',
|
|
118
|
+
'referrer-policy': 'no-referrer',
|
|
119
|
+
'content-security-policy': mediaPolicy(found.type, origin, parsed),
|
|
120
|
+
};
|
|
121
|
+
res.writeHead(200, headers);
|
|
122
|
+
res.end(req.method === 'HEAD' ? undefined : found.bytes);
|
|
123
|
+
}
|
|
124
|
+
/** Raw media target. Dot segments and any percent-encoding are rejected before resolution. */
|
|
125
|
+
export function parseCanvasMedia(requestUrl) {
|
|
126
|
+
const pathname = (requestUrl.split('?')[0] ?? '').replace(/\/+$/, '');
|
|
127
|
+
if (!pathname.startsWith(MEDIA))
|
|
128
|
+
return null;
|
|
129
|
+
if (pathname.includes('\\') || pathname.includes('%') || pathname.includes('\0'))
|
|
130
|
+
return null;
|
|
131
|
+
if (pathname.split('/').includes('..') || pathname.split('/').includes('.'))
|
|
132
|
+
return null;
|
|
133
|
+
const parts = pathname.slice(MEDIA.length).split('/');
|
|
134
|
+
if (parts.length < 3)
|
|
135
|
+
return null;
|
|
136
|
+
const [token, revision, ...rest] = parts;
|
|
137
|
+
if (!token || !/^[A-Za-z0-9_-]{20,128}$/.test(token))
|
|
138
|
+
return null;
|
|
139
|
+
if (!revision || !/^[1-9]\d{0,8}$/.test(revision))
|
|
140
|
+
return null;
|
|
141
|
+
const path = normalizeCanvasPath(rest.join('/'));
|
|
142
|
+
if (!path)
|
|
143
|
+
return null;
|
|
144
|
+
return { token, revision: Number(revision), path };
|
|
145
|
+
}
|
|
146
|
+
function mediaPolicy(type, origin, parsed) {
|
|
147
|
+
const sandbox = "sandbox; base-uri 'none'; form-action 'none'";
|
|
148
|
+
if (type !== 'text/html')
|
|
149
|
+
return `default-src 'none'; ${sandbox}`;
|
|
150
|
+
const prefix = `${origin}${MEDIA}${parsed.token}/${parsed.revision}/`;
|
|
151
|
+
// A design draft usually keeps CSS in a <style> block. External sheets still have to come from this prefix.
|
|
152
|
+
return [
|
|
153
|
+
"default-src 'none'",
|
|
154
|
+
`img-src ${prefix}`,
|
|
155
|
+
`style-src ${prefix} 'unsafe-inline'`,
|
|
156
|
+
`font-src ${prefix}`,
|
|
157
|
+
`frame-ancestors ${origin}`,
|
|
158
|
+
sandbox,
|
|
159
|
+
].join('; ');
|
|
160
|
+
}
|
|
161
|
+
function requestOrigin(req) {
|
|
162
|
+
const host = header(req, 'host');
|
|
163
|
+
if (!host || /[\s/\\]/.test(host))
|
|
164
|
+
return '';
|
|
165
|
+
const forwarded = header(req, 'x-forwarded-proto');
|
|
166
|
+
const proto = forwarded === 'https' || forwarded === 'http' ? forwarded : 'http';
|
|
167
|
+
return `${proto}://${host}`;
|
|
168
|
+
}
|
|
169
|
+
function header(req, name) {
|
|
170
|
+
const value = req.headers[name];
|
|
171
|
+
return Array.isArray(value) ? (value[0] ?? '') : (value ?? '');
|
|
172
|
+
}
|
|
173
|
+
function outcome(result) {
|
|
174
|
+
if (result.ok !== false)
|
|
175
|
+
return { status: 200, body: result };
|
|
176
|
+
const status = result.code === 'NOT_FOUND' ? 404 : result.code === 'CAS_CONFLICT' ? 409 : result.code === 'FORBIDDEN' ? 401 : 400;
|
|
177
|
+
return { status, body: result };
|
|
178
|
+
}
|
|
179
|
+
function decodeFiles(value) {
|
|
180
|
+
if (!Array.isArray(value))
|
|
181
|
+
return toolError('VALIDATION', 'files are required.');
|
|
182
|
+
const files = [];
|
|
183
|
+
for (const item of value) {
|
|
184
|
+
if (!item || typeof item !== 'object')
|
|
185
|
+
return toolError('VALIDATION', 'files are required.');
|
|
186
|
+
const record = item;
|
|
187
|
+
if (typeof record.path !== 'string' || typeof record.type !== 'string' || typeof record.body !== 'string')
|
|
188
|
+
return toolError('VALIDATION', 'each file needs path, type, and body.');
|
|
189
|
+
if (record.body.length > CANVAS_MAX_JSON_BYTES)
|
|
190
|
+
return toolError('VALIDATION', 'A canvas file is too large.');
|
|
191
|
+
const bytes = decodeBase64(record.body);
|
|
192
|
+
if (!bytes)
|
|
193
|
+
return toolError('VALIDATION', `body for ${record.path} is not base64.`);
|
|
194
|
+
files.push({ path: record.path, type: record.type, bytes });
|
|
195
|
+
}
|
|
196
|
+
return files;
|
|
197
|
+
}
|
|
198
|
+
function decodeBase64(value) {
|
|
199
|
+
if (value.length % 4 === 1 || /[^A-Za-z0-9+/=]/.test(value))
|
|
200
|
+
return null;
|
|
201
|
+
const bytes = Buffer.from(value, 'base64');
|
|
202
|
+
const canonical = bytes.toString('base64').replace(/=+$/u, '');
|
|
203
|
+
if (canonical !== value.replace(/=+$/u, ''))
|
|
204
|
+
return null;
|
|
205
|
+
return bytes;
|
|
206
|
+
}
|
|
207
|
+
function readBody(req) {
|
|
208
|
+
return new Promise((resolve, reject) => {
|
|
209
|
+
const chunks = [];
|
|
210
|
+
let total = 0;
|
|
211
|
+
let failed = false;
|
|
212
|
+
const fail = (error) => {
|
|
213
|
+
if (failed)
|
|
214
|
+
return;
|
|
215
|
+
failed = true;
|
|
216
|
+
reject(error);
|
|
217
|
+
};
|
|
218
|
+
req.on('data', (chunk) => {
|
|
219
|
+
total += chunk.length;
|
|
220
|
+
if (total > CANVAS_MAX_JSON_BYTES) {
|
|
221
|
+
fail(Object.assign(new Error('Canvas package is too large.'), { code: 'VALIDATION' }));
|
|
222
|
+
req.destroy();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
chunks.push(chunk);
|
|
226
|
+
});
|
|
227
|
+
req.on('end', () => {
|
|
228
|
+
if (failed)
|
|
229
|
+
return;
|
|
230
|
+
try {
|
|
231
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
232
|
+
const parsed = text === '' ? {} : JSON.parse(text);
|
|
233
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
234
|
+
fail(Object.assign(new Error('canvas body must be an object.'), { code: 'VALIDATION' }));
|
|
235
|
+
else
|
|
236
|
+
resolve(parsed);
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
fail(Object.assign(new Error('invalid json'), { code: 'VALIDATION', cause: error }));
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
req.on('error', fail);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
function json(res, status, body) {
|
|
246
|
+
const text = JSON.stringify(body);
|
|
247
|
+
res.writeHead(status, {
|
|
248
|
+
'content-type': 'application/json; charset=utf-8',
|
|
249
|
+
'content-length': Buffer.byteLength(text),
|
|
250
|
+
'cache-control': 'no-store',
|
|
251
|
+
'x-content-type-options': 'nosniff',
|
|
252
|
+
});
|
|
253
|
+
res.end(text);
|
|
254
|
+
}
|
|
255
|
+
const NONCE = /^[A-Za-z0-9_-]{16,80}$/;
|
|
256
|
+
let inspectorCode = null;
|
|
257
|
+
/** Token-only inspect document. The design stays scriptless; only the host inspector runs. */
|
|
258
|
+
export async function serveCanvasInspect(req, res, requestUrl, canvas) {
|
|
259
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
260
|
+
json(res, 405, toolError('VALIDATION', 'canvas inspect is read-only.'));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const path = (requestUrl.split('?')[0] ?? '').replace(/\/+$/, '');
|
|
264
|
+
if (path === INSPECTOR) {
|
|
265
|
+
try {
|
|
266
|
+
const code = inspectorSource();
|
|
267
|
+
writeBody(res, req.method, 200, 'text/javascript; charset=utf-8', code, "default-src 'none'");
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
json(res, 500, toolError('STORE_FAILURE', error instanceof Error ? error.message : 'inspector failed'));
|
|
271
|
+
}
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const parsed = parseCanvasInspect(requestUrl);
|
|
275
|
+
if (!parsed) {
|
|
276
|
+
json(res, 400, toolError('VALIDATION', 'canvas inspect path is not allowed.'));
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const nonce = new URL(requestUrl, 'http://127.0.0.1').searchParams.get('nonce');
|
|
280
|
+
if (!nonce || !NONCE.test(nonce)) {
|
|
281
|
+
json(res, 400, toolError('VALIDATION', 'canvas inspect nonce is required.'));
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
if (!canvas) {
|
|
285
|
+
json(res, 404, toolError('NOT_FOUND', 'No such canvas file.'));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const found = canvas.readMedia({ token: parsed.token, revision: parsed.revision, path: parsed.path });
|
|
289
|
+
if (found.ok === false) {
|
|
290
|
+
json(res, found.code === 'NOT_FOUND' ? 404 : found.code === 'VALIDATION' ? 400 : 401, found);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (found.type !== 'text/html') {
|
|
294
|
+
json(res, 404, toolError('NOT_FOUND', 'No such canvas file.'));
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const origin = requestOrigin(req);
|
|
298
|
+
if (origin === '') {
|
|
299
|
+
json(res, 400, toolError('VALIDATION', 'canvas inspect needs a host.'));
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const prefix = `${origin}${MEDIA}${parsed.token}/${parsed.revision}/`;
|
|
303
|
+
const html = composeInspect(found.bytes.toString('utf8'), {
|
|
304
|
+
baseHref: prefix,
|
|
305
|
+
nonce,
|
|
306
|
+
parentOrigin: origin,
|
|
307
|
+
inspectorSrc: INSPECTOR,
|
|
308
|
+
page: parsed.path,
|
|
309
|
+
});
|
|
310
|
+
writeBody(res, req.method, 200, 'text/html; charset=utf-8', html, inspectPolicy(origin, prefix));
|
|
311
|
+
}
|
|
312
|
+
export function parseCanvasInspect(requestUrl) {
|
|
313
|
+
const pathname = (requestUrl.split('?')[0] ?? '').replace(/\/+$/, '');
|
|
314
|
+
if (!pathname.startsWith(INSPECT))
|
|
315
|
+
return null;
|
|
316
|
+
if (pathname.includes('\\') || pathname.includes('%') || pathname.includes('\0'))
|
|
317
|
+
return null;
|
|
318
|
+
if (pathname.split('/').includes('..') || pathname.split('/').includes('.'))
|
|
319
|
+
return null;
|
|
320
|
+
const parts = pathname.slice(INSPECT.length).split('/');
|
|
321
|
+
if (parts.length < 2)
|
|
322
|
+
return null;
|
|
323
|
+
const [token, revision, ...rest] = parts;
|
|
324
|
+
if (!token || !/^[A-Za-z0-9_-]{20,128}$/.test(token))
|
|
325
|
+
return null;
|
|
326
|
+
if (!revision || !/^[1-9]\d{0,8}$/.test(revision))
|
|
327
|
+
return null;
|
|
328
|
+
const path = normalizeCanvasPath(rest.length === 0 ? 'index.html' : rest.join('/'));
|
|
329
|
+
if (!path || !path.endsWith('.html'))
|
|
330
|
+
return null;
|
|
331
|
+
return { token, revision: Number(revision), path };
|
|
332
|
+
}
|
|
333
|
+
function inspectPolicy(origin, prefix) {
|
|
334
|
+
return [
|
|
335
|
+
"default-src 'none'",
|
|
336
|
+
`img-src ${prefix}`,
|
|
337
|
+
`style-src ${prefix} 'unsafe-inline'`,
|
|
338
|
+
`font-src ${prefix}`,
|
|
339
|
+
`script-src ${origin}${INSPECTOR}`,
|
|
340
|
+
`base-uri ${prefix}`,
|
|
341
|
+
`frame-ancestors ${origin}`,
|
|
342
|
+
"form-action 'none'",
|
|
343
|
+
'sandbox allow-scripts',
|
|
344
|
+
].join('; ');
|
|
345
|
+
}
|
|
346
|
+
function writeBody(res, method, status, type, body, policy) {
|
|
347
|
+
res.writeHead(status, {
|
|
348
|
+
'content-type': type,
|
|
349
|
+
'content-length': Buffer.byteLength(body),
|
|
350
|
+
'cache-control': 'private, no-store',
|
|
351
|
+
'x-content-type-options': 'nosniff',
|
|
352
|
+
'referrer-policy': 'no-referrer',
|
|
353
|
+
'content-security-policy': policy,
|
|
354
|
+
});
|
|
355
|
+
res.end(method === 'HEAD' ? undefined : body);
|
|
356
|
+
}
|
|
357
|
+
function inspectorSource() {
|
|
358
|
+
if (inspectorCode != null)
|
|
359
|
+
return inspectorCode;
|
|
360
|
+
// Same relative path from src/ (tests) and dist/ (built server): both sit next to ui/.
|
|
361
|
+
const entry = fileURLToPath(new URL('../ui/src/canvas-inspector.ts', import.meta.url));
|
|
362
|
+
if (!existsSync(entry))
|
|
363
|
+
throw new Error('canvas inspector source is missing');
|
|
364
|
+
const result = buildSync({
|
|
365
|
+
absWorkingDir: fileURLToPath(new URL('../ui/', import.meta.url)),
|
|
366
|
+
entryPoints: [entry],
|
|
367
|
+
bundle: true,
|
|
368
|
+
format: 'iife',
|
|
369
|
+
platform: 'browser',
|
|
370
|
+
target: 'es2022',
|
|
371
|
+
write: false,
|
|
372
|
+
minify: false,
|
|
373
|
+
logLevel: 'silent',
|
|
374
|
+
});
|
|
375
|
+
inspectorCode = result.outputFiles[0]?.text ?? '';
|
|
376
|
+
if (inspectorCode === '')
|
|
377
|
+
throw new Error('inspector bundle was empty');
|
|
378
|
+
return inspectorCode;
|
|
379
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
const SKILL_ID = /^[a-z0-9][a-z0-9-]{0,64}$/;
|
|
5
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', 'skills', 'ui');
|
|
6
|
+
/**
|
|
7
|
+
* Bundled canvas skills. `ui-design` is this plugin's contract.
|
|
8
|
+
* The other directories are a starter catalog from ui-skills.com.
|
|
9
|
+
*/
|
|
10
|
+
export function canvasSkillFiles() {
|
|
11
|
+
const entries = readdirSync(ROOT, { withFileTypes: true });
|
|
12
|
+
const skills = [];
|
|
13
|
+
for (const entry of entries) {
|
|
14
|
+
if (!entry.isDirectory() || !SKILL_ID.test(entry.name))
|
|
15
|
+
continue;
|
|
16
|
+
const bytes = readFileSync(join(ROOT, entry.name, 'SKILL.md'));
|
|
17
|
+
const summary = skillSummary(bytes.toString('utf8'), entry.name);
|
|
18
|
+
skills.push({
|
|
19
|
+
id: entry.name,
|
|
20
|
+
version: entry.name === 'ui-design' ? '1' : 'catalog',
|
|
21
|
+
summary,
|
|
22
|
+
bytes,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
skills.sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
|
|
26
|
+
return skills;
|
|
27
|
+
}
|
|
28
|
+
export function bindCanvasSkills(engine, sessionId) {
|
|
29
|
+
const bound = [];
|
|
30
|
+
const skipped = [];
|
|
31
|
+
for (const skill of canvasSkillFiles()) {
|
|
32
|
+
try {
|
|
33
|
+
engine.registerSkill(sessionId, 'public', skill.id, skill.version, skill.summary, skill.bytes);
|
|
34
|
+
bound.push(skill.id);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
skipped.push(skill.id);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { bound, skipped };
|
|
41
|
+
}
|
|
42
|
+
function skillSummary(text, fallback) {
|
|
43
|
+
const fence = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
44
|
+
const block = fence?.[1] ?? '';
|
|
45
|
+
const line = block.match(/^description:\s*(.*)$/m)?.[1]?.trim() ?? '';
|
|
46
|
+
const description = unquote(line).replace(/\s+/g, ' ').trim();
|
|
47
|
+
const summary = description || fallback;
|
|
48
|
+
return summary.slice(0, fallback === 'ui-design' ? 180 : 100);
|
|
49
|
+
}
|
|
50
|
+
function unquote(value) {
|
|
51
|
+
if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
|
|
52
|
+
(value.startsWith("'") && value.endsWith("'") && value.length >= 2)) {
|
|
53
|
+
return value.slice(1, -1);
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|