@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The frame core on this computer: frame-host's environment
|
|
3
|
+
* ({@link localFrameEnv}) and its Node HTTP adapter ({@link FrameSite}).
|
|
4
|
+
*
|
|
5
|
+
* Everything a hosted site has no use for, or that a Worker lacks, is here
|
|
6
|
+
* and only here: the type folder and the client folder read from disk (with
|
|
7
|
+
* the link checks), `fs.watch` on both folders, `os.userInfo` for the owner's
|
|
8
|
+
* name, `stripTypeScriptTypes` for the client scripts run from source,
|
|
9
|
+
* `import.meta.url` for where they are, and `IncomingMessage` /
|
|
10
|
+
* `ServerResponse` / `createReadStream` for requests. Every viewer here is the
|
|
11
|
+
* owner, and a request comes in only from this computer, but for the visit of
|
|
12
|
+
* a `snapshot` (frame/snapshot-action.ts): its inner shell is loaded at
|
|
13
|
+
* `/snapshot/<credential>/`, which the site claims only while that visit lasts
|
|
14
|
+
* ({@link FrameSite.beginSnapshot}), and every request under it is a read-only
|
|
15
|
+
* viewer nobody else sees (no writes, no presence, no event but `hello`).
|
|
16
|
+
*/
|
|
17
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
18
|
+
import { createReadStream, existsSync, readFileSync, readdirSync, statSync, watch } from 'node:fs';
|
|
19
|
+
import * as nodeModule from 'node:module';
|
|
20
|
+
import { userInfo } from 'node:os';
|
|
21
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
22
|
+
import { fileURLToPath } from 'node:url';
|
|
23
|
+
import { FrameCore, colorOf, pageDeclaration, storedFile } from "./core.js";
|
|
24
|
+
import { readDeclaration } from "./declaration.js";
|
|
25
|
+
import { FRAME_MCP_ROUTES, FRAME_SAMPLE_ROUTES } from '@openartifactsai/protocol';
|
|
26
|
+
import { FrameError, LINK_GUARD, staysInside } from "./files.js";
|
|
27
|
+
/**
|
|
28
|
+
* Where the browser scripts and the shell page are: `$OPEN_ARTIFACTS_FRAME_CLIENT_DIR`,
|
|
29
|
+
* else `client/` beside this module (src/frame/client from source, or
|
|
30
|
+
* dist/daemon/frame-host/client beside the bundle).
|
|
31
|
+
*/
|
|
32
|
+
export const CLIENT_DIR = process.env.OPEN_ARTIFACTS_FRAME_CLIENT_DIR || join(dirname(fileURLToPath(import.meta.url)), 'client');
|
|
33
|
+
// ---- snapshot visits -----------------------------------------------------------------------------------------------
|
|
34
|
+
/** A snapshot visit's inner shell: `/snapshot/<credential>/…` on the shell's origin. */
|
|
35
|
+
const SNAPSHOT_PATH = /^\/snapshot\/([A-Za-z0-9_-]{32})(\/[^?]*)?(\?.*)?$/;
|
|
36
|
+
/** The viewers of snapshot visits, by identity: the owner's level and name, but every write refused. */
|
|
37
|
+
const snapshotViewers = new WeakSet();
|
|
38
|
+
/** The requests (`IncomingMessage`) of a snapshot visit, with its viewer: what {@link localFrameEnv} answers for them. */
|
|
39
|
+
const snapshotRequests = new WeakMap();
|
|
40
|
+
/**
|
|
41
|
+
* What a snapshot's viewer may call: reads only. Anything else is refused with the code a viewer who may not do it
|
|
42
|
+
* gets ({@link snapshotRefusal}); a capability the page was not granted answers as it always does.
|
|
43
|
+
*/
|
|
44
|
+
const SNAPSHOT_READS = new Set([
|
|
45
|
+
'db.get',
|
|
46
|
+
'db.query',
|
|
47
|
+
'artifact.metadata',
|
|
48
|
+
'artifact.search',
|
|
49
|
+
'artifact.sync',
|
|
50
|
+
'assets.list',
|
|
51
|
+
'user.me',
|
|
52
|
+
'user.profile',
|
|
53
|
+
'user.email',
|
|
54
|
+
'user.profiles',
|
|
55
|
+
'user.access',
|
|
56
|
+
'user.search',
|
|
57
|
+
'permissions.state',
|
|
58
|
+
'permissions.request',
|
|
59
|
+
'comments.list',
|
|
60
|
+
'comments.canSendToAgent',
|
|
61
|
+
'room.peers',
|
|
62
|
+
'room.canSendToAgentSession',
|
|
63
|
+
]);
|
|
64
|
+
const SNAPSHOT_REFUSED = 'This is a snapshot of the page: it only reads, and nothing is written.';
|
|
65
|
+
/** Whether `viewer` is a snapshot visit's. */
|
|
66
|
+
export function isSnapshotViewer(viewer) {
|
|
67
|
+
return snapshotViewers.has(viewer);
|
|
68
|
+
}
|
|
69
|
+
/** The error a snapshot's viewer gets for `cap.method`: the one the contract gives a viewer who may not. */
|
|
70
|
+
function snapshotRefusal(cap) {
|
|
71
|
+
if (cap === 'db')
|
|
72
|
+
return new FrameError('invalid_argument', SNAPSHOT_REFUSED);
|
|
73
|
+
if (cap === 'artifact' || cap === 'assets')
|
|
74
|
+
return new FrameError('not_writer', SNAPSHOT_REFUSED);
|
|
75
|
+
if (cap === 'comments')
|
|
76
|
+
return new FrameError('forbidden', SNAPSHOT_REFUSED);
|
|
77
|
+
return new FrameError('not_permitted', SNAPSHOT_REFUSED);
|
|
78
|
+
}
|
|
79
|
+
/** A JSON answer of the inner shell's API. */
|
|
80
|
+
function jsonReply(status, body) {
|
|
81
|
+
const text = Buffer.from(JSON.stringify(body));
|
|
82
|
+
return { status, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': text.length, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }, body: text };
|
|
83
|
+
}
|
|
84
|
+
/** The owner, as every request on this computer is. */
|
|
85
|
+
export function localUser() {
|
|
86
|
+
let name = 'You';
|
|
87
|
+
try {
|
|
88
|
+
name = userInfo().username || name;
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// no passwd entry
|
|
92
|
+
}
|
|
93
|
+
return { id: 'local', name, avatarUrl: null, color: colorOf('local'), email: null, level: 'owner', guest: false, canComment: true };
|
|
94
|
+
}
|
|
95
|
+
function typeConfig(typeDir) {
|
|
96
|
+
try {
|
|
97
|
+
return JSON.parse(readFileSync(join(typeDir, 'artifact-type.json'), 'utf8'));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return {};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** A fingerprint of what the type serves: index.html and artifact-type/ (names, sizes, times). */
|
|
104
|
+
function typeFingerprint(typeDir) {
|
|
105
|
+
const hash = createHash('sha256');
|
|
106
|
+
try {
|
|
107
|
+
hash.update(readFileSync(join(typeDir, 'index.html')));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
hash.update('-');
|
|
111
|
+
}
|
|
112
|
+
const walk = (dir, rel, depth) => {
|
|
113
|
+
if (depth > 8)
|
|
114
|
+
return;
|
|
115
|
+
let entries;
|
|
116
|
+
try {
|
|
117
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
123
|
+
if (e.name.startsWith('.'))
|
|
124
|
+
continue;
|
|
125
|
+
const path = join(dir, e.name);
|
|
126
|
+
if (e.isDirectory())
|
|
127
|
+
walk(path, `${rel}/${e.name}`, depth + 1);
|
|
128
|
+
else if (e.isFile()) {
|
|
129
|
+
try {
|
|
130
|
+
const st = statSync(path);
|
|
131
|
+
hash.update(`\n${rel}/${e.name}\0${st.size}\0${st.mtimeMs}`);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
// gone
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
walk(join(typeDir, 'artifact-type'), 'artifact-type', 0);
|
|
140
|
+
return hash.digest('hex').slice(0, 16);
|
|
141
|
+
}
|
|
142
|
+
/** The type folder on disk. */
|
|
143
|
+
export function localTypeSource(typeDir) {
|
|
144
|
+
const own = join(typeDir, 'artifact-type');
|
|
145
|
+
return {
|
|
146
|
+
label: typeDir,
|
|
147
|
+
fingerprint: () => typeFingerprint(typeDir),
|
|
148
|
+
declaration: () => readDeclaration(typeDir),
|
|
149
|
+
manifest: () => typeConfig(typeDir),
|
|
150
|
+
indexHtml: () => {
|
|
151
|
+
try {
|
|
152
|
+
return readFileSync(join(typeDir, 'index.html'), 'utf8');
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
file: (rel) => {
|
|
159
|
+
const file = join(typeDir, rel);
|
|
160
|
+
// A link in artifact-type/ to a file outside it is not served (a project's folder is anyone's).
|
|
161
|
+
if (!file.startsWith(own + sep) || !staysInside(own, file))
|
|
162
|
+
return null;
|
|
163
|
+
return storedFile(file);
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
const stripped = new Map();
|
|
168
|
+
/**
|
|
169
|
+
* A client file only a build makes (the comment views, comments.js and
|
|
170
|
+
* comments.css): beside the bundle, or, from source, in the repository's
|
|
171
|
+
* built frame-host client folder.
|
|
172
|
+
*/
|
|
173
|
+
function builtClientFile(name) {
|
|
174
|
+
const here = join(CLIENT_DIR, name);
|
|
175
|
+
if (existsSync(here))
|
|
176
|
+
return here;
|
|
177
|
+
return join(CLIENT_DIR, '..', '..', '..', '..', '..', 'dist', 'daemon', 'frame-host', 'client', name);
|
|
178
|
+
}
|
|
179
|
+
/** A client .ts as a browser script: types stripped by Node (no bundling: the client files import types only). */
|
|
180
|
+
function scriptFromSource(file) {
|
|
181
|
+
const st = statSync(file);
|
|
182
|
+
const have = stripped.get(file);
|
|
183
|
+
if (have && have.mtimeMs === st.mtimeMs)
|
|
184
|
+
return have.code;
|
|
185
|
+
const strip = nodeModule.stripTypeScriptTypes;
|
|
186
|
+
if (typeof strip !== 'function')
|
|
187
|
+
throw new Error('this Node cannot strip TypeScript; build the client scripts (node scripts/build.mjs --only frame).');
|
|
188
|
+
const code = strip(readFileSync(file, 'utf8'), { mode: 'strip' });
|
|
189
|
+
stripped.set(file, { mtimeMs: st.mtimeMs, code });
|
|
190
|
+
return code;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The page side of `sample` from source: client/sample.ts takes its checks and helpers from the protocol's
|
|
194
|
+
* sample.ts (a build bundles the two), so here both are stripped and joined in one script, the protocol's part first
|
|
195
|
+
* (its exports become plain declarations) and the client's import of it left out.
|
|
196
|
+
*/
|
|
197
|
+
export function sampleScriptFromSource(clientFile, protocolFile) {
|
|
198
|
+
const exports = /^export (?=(?:async function|const|function|let|class) )/gm;
|
|
199
|
+
const imports = /^import\s*\{[^}]*\}\s*from\s*'(?:@openartifactsai\/protocol\/sample|\.\/sample-images\.ts)';?[ \t]*$/gm;
|
|
200
|
+
const protocol = scriptFromSource(protocolFile).replace(exports, '');
|
|
201
|
+
// The image preparation sample.ts imports (client/sample-images.ts, beside it): joined after the protocol's part.
|
|
202
|
+
const images = scriptFromSource(join(dirname(clientFile), 'sample-images.ts')).replace(imports, '').replace(exports, '');
|
|
203
|
+
const client = scriptFromSource(clientFile).replace(imports, '');
|
|
204
|
+
return `(() => {\n'use strict';\n${protocol}\n${images}\n${client}\n})();\n`;
|
|
205
|
+
}
|
|
206
|
+
/** Where the protocol's sample.ts is, from source. */
|
|
207
|
+
function protocolSampleFile() {
|
|
208
|
+
return fileURLToPath(import.meta.resolve('@openartifactsai/protocol/sample'));
|
|
209
|
+
}
|
|
210
|
+
/** The client folder: the built scripts, or, from source, the .ts with its types stripped. */
|
|
211
|
+
function localClientFile(name) {
|
|
212
|
+
if (name === 'sample.js') {
|
|
213
|
+
const built = join(CLIENT_DIR, name);
|
|
214
|
+
try {
|
|
215
|
+
if (statSync(built).isFile())
|
|
216
|
+
return storedFile(built);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// not built: from source
|
|
220
|
+
}
|
|
221
|
+
const body = Buffer.from(sampleScriptFromSource(join(CLIENT_DIR, 'sample.ts'), protocolSampleFile()), 'utf8');
|
|
222
|
+
return { size: body.length, mtimeMs: null, body };
|
|
223
|
+
}
|
|
224
|
+
if (name === 'runtime.js' || name === 'shell.js' || name === 'imports.js' || name === 'mcp.js' || name === 'mcp-shell.js') {
|
|
225
|
+
const built = join(CLIENT_DIR, name);
|
|
226
|
+
try {
|
|
227
|
+
if (statSync(built).isFile())
|
|
228
|
+
return storedFile(built);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
// not built: from source
|
|
232
|
+
}
|
|
233
|
+
const body = Buffer.from(scriptFromSource(join(CLIENT_DIR, name.replace(/\.js$/, '.ts'))), 'utf8');
|
|
234
|
+
return { size: body.length, mtimeMs: null, body };
|
|
235
|
+
}
|
|
236
|
+
if (name === 'comments.js' || name === 'comments.css')
|
|
237
|
+
return storedFile(builtClientFile(name));
|
|
238
|
+
return storedFile(join(CLIENT_DIR, name));
|
|
239
|
+
}
|
|
240
|
+
/** A page's connector calls through the daemon's Type API, when there is a daemon to ask. */
|
|
241
|
+
function daemonMcp(daemon) {
|
|
242
|
+
if (!daemon?.available)
|
|
243
|
+
return undefined;
|
|
244
|
+
return {
|
|
245
|
+
start: (body, signal) => daemon.mcpPageStream(body, signal),
|
|
246
|
+
tools: (body) => daemon.mcpPageTools(body),
|
|
247
|
+
describe: (body) => daemon.mcpPageDescribe(body),
|
|
248
|
+
state: (id, view) => daemon.mcpPageState(id, view),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/** `sample` through the daemon's Type API, when there is a daemon to ask. */
|
|
252
|
+
function daemonSample(daemon) {
|
|
253
|
+
if (!daemon?.available)
|
|
254
|
+
return undefined;
|
|
255
|
+
return {
|
|
256
|
+
start: (body, signal) => daemon.sampleStream(body, signal),
|
|
257
|
+
tool: (body) => daemon.sampleTool(body),
|
|
258
|
+
limits: (query) => daemon.sampleLimits(query),
|
|
259
|
+
state: (id) => daemon.sampleState(id),
|
|
260
|
+
shellUrl: (id) => daemon.artifact(id).then((a) => (typeof a.view_url === 'string' && /^https?:\/\//i.test(a.view_url) ? a.view_url : null)),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/** frame-host's environment: this computer, its owner, the type folder, the client folder, `fs.watch`. */
|
|
264
|
+
export function localFrameEnv(root, ctx, options, type = localTypeSource(options.typeDir)) {
|
|
265
|
+
if (!ctx.contentOrigin)
|
|
266
|
+
throw new FrameError('no_content_origin', 'frame-host needs serve({contentHosts: true}) and an art_ artifact id.', 500);
|
|
267
|
+
const contentOrigin = ctx.contentOrigin;
|
|
268
|
+
const port = new URL(contentOrigin).port;
|
|
269
|
+
const owner = localUser();
|
|
270
|
+
const { typeDir, page } = options;
|
|
271
|
+
const log = (line) => ctx.log?.(line);
|
|
272
|
+
return {
|
|
273
|
+
id: ctx.id,
|
|
274
|
+
title: ctx.title,
|
|
275
|
+
log,
|
|
276
|
+
origins: {
|
|
277
|
+
shell: `http://127.0.0.1:${port}`,
|
|
278
|
+
shellOrigins: [`http://127.0.0.1:${port}`, `http://localhost:${port}`],
|
|
279
|
+
content: contentOrigin,
|
|
280
|
+
connectSrc: [`ws://127.0.0.1:${port}`, `ws://localhost:${port}`],
|
|
281
|
+
frameSrc: `http://*.frame.localhost:${port}`,
|
|
282
|
+
},
|
|
283
|
+
// A snapshot visit's request (marked by FrameSite.handle) is its own read-only viewer; every other is the owner.
|
|
284
|
+
viewer: (req) => (req.peer ? snapshotRequests.get(req.peer) : undefined) ?? owner,
|
|
285
|
+
// The page's address carries no token here: its reader is the owner too (read-only, as the core treats it: the
|
|
286
|
+
// page's origin answers GET and HEAD only, a snapshot's visit included).
|
|
287
|
+
reader: () => owner,
|
|
288
|
+
pageOrigin: () => contentOrigin,
|
|
289
|
+
withholdIdentity: false,
|
|
290
|
+
people: () => [{ id: owner.id, name: owner.name, email: owner.email, avatarUrl: owner.avatarUrl, color: owner.color, level: owner.level }],
|
|
291
|
+
admit: (req) => ctx.local(req.peer),
|
|
292
|
+
type,
|
|
293
|
+
client: { file: localClientFile },
|
|
294
|
+
watch: (on) => {
|
|
295
|
+
const watchers = [];
|
|
296
|
+
try {
|
|
297
|
+
const w = watch(root, { recursive: true }, (event, name) => {
|
|
298
|
+
if (!name)
|
|
299
|
+
return;
|
|
300
|
+
// A folder's own 'change' is its times or attributes (Windows reports one when the folder is only listed);
|
|
301
|
+
// what changed in it comes by its own name.
|
|
302
|
+
if (event === 'change' && isFolder(join(root, String(name))))
|
|
303
|
+
return;
|
|
304
|
+
on.artifact(String(name).split(sep).join('/'));
|
|
305
|
+
});
|
|
306
|
+
w.on('error', () => { });
|
|
307
|
+
watchers.push(w);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
log(`watch: ${error?.message ?? error}`);
|
|
311
|
+
}
|
|
312
|
+
// The type folder: a page type serves neither index.html nor artifact-type/ (its pages are the artifacts' own).
|
|
313
|
+
if (!page) {
|
|
314
|
+
try {
|
|
315
|
+
const w = watch(typeDir, { recursive: true }, (_event, name) => on.type(name ? String(name).split(sep).join('/') : null));
|
|
316
|
+
w.on('error', () => { });
|
|
317
|
+
watchers.push(w);
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
log(`watch type: ${error?.message ?? error}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
close: () => {
|
|
325
|
+
for (const w of watchers) {
|
|
326
|
+
try {
|
|
327
|
+
w.close();
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
// already closed
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
},
|
|
336
|
+
restricted: options.restricted,
|
|
337
|
+
contentSecurityPolicy: options.contentSecurityPolicy,
|
|
338
|
+
allowedNetworkOrigins: options.allowedNetworkOrigins,
|
|
339
|
+
page,
|
|
340
|
+
guard: LINK_GUARD,
|
|
341
|
+
imports: ctx.workspace,
|
|
342
|
+
debug: () => !!process.env.OPEN_ARTIFACTS_FRAME_DEBUG,
|
|
343
|
+
daemon: ctx.daemon,
|
|
344
|
+
sample: daemonSample(ctx.daemon),
|
|
345
|
+
mcp: daemonMcp(ctx.daemon),
|
|
346
|
+
agentHook: ctx.agentHook,
|
|
347
|
+
...(ctx.agentName !== undefined ? { agentName: ctx.agentName } : {}),
|
|
348
|
+
...(ctx.agentWakesIdle !== undefined ? { agentWakesIdle: ctx.agentWakesIdle } : {}),
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
/** Mounts one artifact folder. Throws when the type folder carries no declaration or the server has no content hosts. */
|
|
352
|
+
export async function mountFrameSite(root, ctx) {
|
|
353
|
+
const typeDir = resolve(ctx.typeDir ?? process.env.OPEN_ARTIFACTS_TYPE_DIR ?? process.cwd());
|
|
354
|
+
const page = ctx.page === true;
|
|
355
|
+
const type = localTypeSource(typeDir);
|
|
356
|
+
const declaration = page ? pageDeclaration(resolve(root)) : type.declaration();
|
|
357
|
+
if (!declaration)
|
|
358
|
+
throw new FrameError('not_frame_type', `${typeDir}/index.html has no // artifact.json declaration.`, 500);
|
|
359
|
+
const env = localFrameEnv(resolve(root), ctx, {
|
|
360
|
+
typeDir, page, restricted: ctx.restricted === true,
|
|
361
|
+
contentSecurityPolicy: ctx.contentSecurityPolicy || null,
|
|
362
|
+
allowedNetworkOrigins: ctx.allowedNetworkOrigins,
|
|
363
|
+
}, type);
|
|
364
|
+
return new FrameSite(resolve(root), typeDir, declaration, env);
|
|
365
|
+
}
|
|
366
|
+
/** Whether `path` is a folder now (false when it is gone). */
|
|
367
|
+
function isFolder(path) {
|
|
368
|
+
try {
|
|
369
|
+
return statSync(path).isDirectory();
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
// ---- the Node HTTP adapter -----------------------------------------------------------------------------------------
|
|
376
|
+
/** A request as plain data (the core's), keeping the `IncomingMessage` for the environment. */
|
|
377
|
+
function plainRequest(req) {
|
|
378
|
+
const headers = {};
|
|
379
|
+
for (const [k, v] of Object.entries(req.headers))
|
|
380
|
+
headers[k] = Array.isArray(v) ? v.join(', ') : v;
|
|
381
|
+
return { method: req.method ?? 'GET', url: req.url ?? '/', headers, body: (limit) => readBody(req, limit), peer: req };
|
|
382
|
+
}
|
|
383
|
+
function readBody(req, limit) {
|
|
384
|
+
return new Promise((resolvePromise, reject) => {
|
|
385
|
+
const chunks = [];
|
|
386
|
+
let size = 0;
|
|
387
|
+
req.on('data', (c) => {
|
|
388
|
+
size += c.length;
|
|
389
|
+
if (size > limit) {
|
|
390
|
+
reject(new FrameError('too_large', `The request is over ${limit} bytes.`, 413));
|
|
391
|
+
req.destroy();
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
chunks.push(c);
|
|
395
|
+
});
|
|
396
|
+
req.on('end', () => resolvePromise(Buffer.concat(chunks)));
|
|
397
|
+
req.on('error', reject);
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
/** Writes the core's answer; a stored file is streamed. */
|
|
401
|
+
function sendReply(req, res, reply) {
|
|
402
|
+
req.resume?.();
|
|
403
|
+
res.writeHead(reply.status, reply.headers);
|
|
404
|
+
const body = reply.body;
|
|
405
|
+
if (body === null)
|
|
406
|
+
return void res.end();
|
|
407
|
+
if (body instanceof Uint8Array)
|
|
408
|
+
return void res.end(body);
|
|
409
|
+
createReadStream(body.path)
|
|
410
|
+
.on('error', () => res.destroy())
|
|
411
|
+
.pipe(res);
|
|
412
|
+
}
|
|
413
|
+
/** A response carried over a WebSocket (serve()'s `StreamResponse`), not an HTTP one. */
|
|
414
|
+
const overSocket = (res) => 'ws' in res;
|
|
415
|
+
/** One open artifact of an original type, on this computer: the core, answering Node's requests. */
|
|
416
|
+
export class FrameSite extends FrameCore {
|
|
417
|
+
/** The type folder. */
|
|
418
|
+
typeDir;
|
|
419
|
+
/** Snapshot visits under way: credential → their viewer. */
|
|
420
|
+
visits = new Map();
|
|
421
|
+
constructor(root, typeDir, declaration, env) {
|
|
422
|
+
super(root, declaration, env);
|
|
423
|
+
this.typeDir = typeDir;
|
|
424
|
+
}
|
|
425
|
+
// ---- snapshot visits ---------------------------------------------------------------------------------------------
|
|
426
|
+
/**
|
|
427
|
+
* Starts a snapshot visit: a one-time credential (unguessable, this artifact's only) and the address of the inner
|
|
428
|
+
* shell under it, `<shell origin>/snapshot/<credential>/`. Until `end()`, every request under that address is a
|
|
429
|
+
* read-only viewer of its own (the owner's level and name, so the page draws as the person sees it): it reads, each
|
|
430
|
+
* write is refused, it is no peer of anyone, and its event stream says `hello` and nothing more. After `end()` the
|
|
431
|
+
* address is not this site's any more (404). The credential is never logged.
|
|
432
|
+
*/
|
|
433
|
+
beginSnapshot() {
|
|
434
|
+
const credential = randomBytes(24).toString('base64url');
|
|
435
|
+
const viewer = { ...localUser() };
|
|
436
|
+
snapshotViewers.add(viewer);
|
|
437
|
+
this.visits.set(credential, viewer);
|
|
438
|
+
return { url: `${this.shellOrigin}/snapshot/${credential}/`, end: () => void this.visits.delete(credential) };
|
|
439
|
+
}
|
|
440
|
+
/** Snapshot visits under way. */
|
|
441
|
+
get snapshotVisits() {
|
|
442
|
+
return this.visits.size;
|
|
443
|
+
}
|
|
444
|
+
/** A snapshot visit's address, while it lasts (serve() then routes it here: `Site.claims`). */
|
|
445
|
+
claims(pathname) {
|
|
446
|
+
const m = SNAPSHOT_PATH.exec(pathname);
|
|
447
|
+
return !!m && this.visits.has(m[1]);
|
|
448
|
+
}
|
|
449
|
+
/** The visit's own session: no comments UI or agent in the inner shell, and `snapshot` (it waits for no one). */
|
|
450
|
+
session(viewer) {
|
|
451
|
+
const session = super.session(viewer);
|
|
452
|
+
if (!isSnapshotViewer(viewer))
|
|
453
|
+
return session;
|
|
454
|
+
return { ...session, snapshot: true, comments: { available: false, count: 0 }, agent: { available: false, name: null } };
|
|
455
|
+
}
|
|
456
|
+
/** A snapshot's viewer reads only: every other call is refused before the core runs it. */
|
|
457
|
+
async capability(cap, method, a, client, viewer, forShell = false) {
|
|
458
|
+
if (isSnapshotViewer(viewer) && !SNAPSHOT_READS.has(`${cap}.${method}`) && !this.stubs[cap] && this.grantsFor(viewer).includes(cap)) {
|
|
459
|
+
throw snapshotRefusal(cap);
|
|
460
|
+
}
|
|
461
|
+
return super.capability(cap, method, a, client, viewer, forShell);
|
|
462
|
+
}
|
|
463
|
+
/** A snapshot's visit draws the page as it is: it asks no model. */
|
|
464
|
+
sampleDisabled(viewer) {
|
|
465
|
+
return isSnapshotViewer(viewer) || super.sampleDisabled(viewer);
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* The inner shell's own POSTs other than capability calls, for a snapshot's viewer: an upload, a title, the agent
|
|
469
|
+
* and its activity are answered here, as for a viewer who may not, and never reach the core (null: the core answers).
|
|
470
|
+
*/
|
|
471
|
+
snapshotShellReply(req) {
|
|
472
|
+
if (req.method !== 'POST')
|
|
473
|
+
return null;
|
|
474
|
+
const name = new URL(req.url || '/', 'http://local').pathname.replace(/^\/api\/frame\//, '');
|
|
475
|
+
if (name === 'cap')
|
|
476
|
+
return null;
|
|
477
|
+
if (name === 'upload')
|
|
478
|
+
return jsonReply(200, { error: { code: 'not_granted', message: SNAPSHOT_REFUSED } });
|
|
479
|
+
if (name === 'title')
|
|
480
|
+
return jsonReply(200, { applied: false });
|
|
481
|
+
if (name === 'activity')
|
|
482
|
+
return jsonReply(200, { working: false, available: false });
|
|
483
|
+
if (name === 'agent')
|
|
484
|
+
return jsonReply(403, { error: { code: 'forbidden', message: SNAPSHOT_REFUSED } });
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
// ---- requests on the inner shell's origin (under Site.page) ------------------------------------------------------
|
|
488
|
+
async handle(req, res) {
|
|
489
|
+
// A snapshot visit: its credential must be live, and the path below it is the inner shell's as usual.
|
|
490
|
+
const visit = SNAPSHOT_PATH.exec(req.url ?? '/');
|
|
491
|
+
let snapshot;
|
|
492
|
+
if (visit) {
|
|
493
|
+
snapshot = this.visits.get(visit[1]);
|
|
494
|
+
if (!snapshot) {
|
|
495
|
+
req.resume?.();
|
|
496
|
+
res.writeHead(404);
|
|
497
|
+
res.end();
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
req.url = `${visit[2] || '/'}${visit[3] ?? ''}`;
|
|
501
|
+
snapshotRequests.set(req, snapshot);
|
|
502
|
+
}
|
|
503
|
+
const plain = plainRequest(req);
|
|
504
|
+
if (overSocket(res)) {
|
|
505
|
+
if (this.acceptsStream(plain))
|
|
506
|
+
return snapshot ? this.quietEvents(req, plain, res) : this.events(req, plain, res);
|
|
507
|
+
res.writeHead(404);
|
|
508
|
+
res.end();
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const refused = snapshot ? this.snapshotShellReply(plain) : null;
|
|
512
|
+
if (refused)
|
|
513
|
+
return sendReply(req, res, refused);
|
|
514
|
+
if (new URL(plain.url || '/', 'http://local').pathname === FRAME_SAMPLE_ROUTES.call)
|
|
515
|
+
return this.sample(req, plain, res);
|
|
516
|
+
if (new URL(plain.url || '/', 'http://local').pathname === FRAME_MCP_ROUTES.call)
|
|
517
|
+
return this.sample(req, plain, res, true);
|
|
518
|
+
const reply = await this.request(plain);
|
|
519
|
+
if ('events' in reply)
|
|
520
|
+
return snapshot ? this.quietEvents(req, plain, res) : this.events(req, plain, res);
|
|
521
|
+
sendReply(req, res, reply);
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* `POST /api/frame/sample`: the call's NDJSON stream, written line by line as the daemon sends it. The inner shell
|
|
525
|
+
* closing its request (the page cancelled, or went away) aborts the daemon's.
|
|
526
|
+
*/
|
|
527
|
+
async sample(req, plain, res, mcp = false) {
|
|
528
|
+
const controller = new AbortController();
|
|
529
|
+
res.on('close', () => {
|
|
530
|
+
if (!res.writableEnded)
|
|
531
|
+
controller.abort();
|
|
532
|
+
});
|
|
533
|
+
// `mcp`: a connector call (`POST /api/frame/mcp/call`), streamed the same way.
|
|
534
|
+
const answer = mcp ? await this.mcpStream(plain, controller.signal) : await this.sampleStream(plain, controller.signal);
|
|
535
|
+
if (!('stream' in answer))
|
|
536
|
+
return sendReply(req, res, answer);
|
|
537
|
+
res.writeHead(answer.status, answer.headers);
|
|
538
|
+
res.flushHeaders();
|
|
539
|
+
try {
|
|
540
|
+
for await (const chunk of answer.stream) {
|
|
541
|
+
if (controller.signal.aborted)
|
|
542
|
+
break;
|
|
543
|
+
res.write(chunk);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
this.log(`sample: ${error?.message ?? error}`);
|
|
548
|
+
}
|
|
549
|
+
if (!res.writableEnded && !res.destroyed)
|
|
550
|
+
res.end();
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* A snapshot visit's event stream: `hello` (no peers), then nothing. It is not one of the core's connections, so no
|
|
554
|
+
* open view sees it among its peers, and nothing it would hear (a reload, a peer) changes the picture.
|
|
555
|
+
*/
|
|
556
|
+
quietEvents(req, plain, res) {
|
|
557
|
+
const client = String(new URL(plain.url || '/', 'http://local').searchParams.get('c') ?? '');
|
|
558
|
+
if (!FrameCore.validClient(client)) {
|
|
559
|
+
res.writeHead(400);
|
|
560
|
+
res.end();
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
const sse = !overSocket(res);
|
|
564
|
+
if (sse)
|
|
565
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
566
|
+
else
|
|
567
|
+
res.writeHead(200);
|
|
568
|
+
const hello = { t: 'hello', ver: this.ver, brokerGen: this.brokerGen, peers: [], count: 0 };
|
|
569
|
+
res.write(sse ? `data: ${JSON.stringify(hello)}\n\n` : JSON.stringify(hello));
|
|
570
|
+
const ping = sse ? setInterval(() => res.write(': ping\n\n'), 25_000) : null;
|
|
571
|
+
req.on('close', () => {
|
|
572
|
+
if (ping)
|
|
573
|
+
clearInterval(ping);
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
/** The event stream of one inner shell: JSON objects, over a `baoyu-sse` WebSocket or as SSE. */
|
|
577
|
+
events(req, plain, res) {
|
|
578
|
+
const client = String(new URL(plain.url || '/', 'http://local').searchParams.get('c') ?? '');
|
|
579
|
+
if (!FrameCore.validClient(client)) {
|
|
580
|
+
res.writeHead(400);
|
|
581
|
+
res.end();
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
const sse = !overSocket(res);
|
|
585
|
+
if (sse)
|
|
586
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
587
|
+
else
|
|
588
|
+
res.writeHead(200);
|
|
589
|
+
const send = (obj) => {
|
|
590
|
+
try {
|
|
591
|
+
res.write(sse ? `data: ${JSON.stringify(obj)}\n\n` : JSON.stringify(obj));
|
|
592
|
+
}
|
|
593
|
+
catch {
|
|
594
|
+
// closing
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
const closed = this.connect(plain, client, { send, end: () => res.end() });
|
|
598
|
+
const ping = sse ? setInterval(() => res.write(': ping\n\n'), 25_000) : null;
|
|
599
|
+
req.on('close', () => {
|
|
600
|
+
if (ping)
|
|
601
|
+
clearInterval(ping);
|
|
602
|
+
closed();
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
// ---- the page's own origin (Site.content) ------------------------------------------------------------------------
|
|
606
|
+
async content(req, res) {
|
|
607
|
+
sendReply(req, res, await this.contentRequest(plainRequest(req)));
|
|
608
|
+
}
|
|
609
|
+
contentUpgrade(_req, socket) {
|
|
610
|
+
socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
|
|
611
|
+
}
|
|
612
|
+
}
|