@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,1757 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The frame core: one open artifact of an original type (or a page artifact),
|
|
3
|
+
* served to any number of viewers. It answers plain-data requests
|
|
4
|
+
* ({@link FrameRequest} → {@link FrameReply}) and holds event connections
|
|
5
|
+
* ({@link FrameCore.connect}); everything it takes from where it runs comes
|
|
6
|
+
* through a {@link FrameEnv}. Nothing here imports a Node-only module (no
|
|
7
|
+
* `node:http`, `node:os`, `node:module`, `node:url`, `import.meta`, `fs.watch`
|
|
8
|
+
* or streams): local.ts adapts it to frame-host on this computer, and a hosted
|
|
9
|
+
* site can run it as is. Its storage (db/, comments.json, the published files,
|
|
10
|
+
* _blobs/) uses `node:fs` sync calls that a site's virtual file system also has.
|
|
11
|
+
*
|
|
12
|
+
* Every answer that depends on who asks takes the viewer from the request (or
|
|
13
|
+
* from the connection it belongs to), never from the instance: one core serves
|
|
14
|
+
* many viewers at once, and checks each call against that viewer's level and the
|
|
15
|
+
* declaration's access settings (access.ts). Nothing the page or the inner shell
|
|
16
|
+
* says about who it is counts: not a holder, not a client id, not an author.
|
|
17
|
+
*/
|
|
18
|
+
import { randomBytes } from 'node:crypto';
|
|
19
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
20
|
+
import { join, resolve } from 'node:path';
|
|
21
|
+
import { FRAME_BACKED_CAPABILITIES, FRAME_MCP_ROUTES, FRAME_SAMPLE_ROUTES, declaredMcpServers, FRAME_STUBBED_CAPABILITIES, LEGACY_CAPABILITY_IMPORT_PREFIX, adoptLegacyManifest, RESTRICTED_FRAME_SANDBOX, declaredCapabilities, titleInHtml, } from '@openartifactsai/protocol';
|
|
22
|
+
import { AGENT_AUTHOR, COMMENTS_FILE, CommentStore, agentView } from "./comments.js";
|
|
23
|
+
import { compileDbRules, dbAllows, meets, topicLevel, uploadLevel, userScopes } from "./access.js";
|
|
24
|
+
import { DbStore, checkSpec, docPathsOf, newDocId, splitPath } from "./db.js";
|
|
25
|
+
import { SAMPLE_BODY_MAX, SAMPLE_STREAM_HEADERS, checkSampleRequest, checkToolRequest, relaySample, sampleError, sampleErrorReply } from "./sample-relay.js";
|
|
26
|
+
import { FrameMcp, MCP_BODY_MAX, MCP_UNSERVED, mcpErrorReply, mcpServed } from "./mcp-relay.js";
|
|
27
|
+
import { BlobStore, FileStore, blobClaims, FrameError, cleanPath, contentTypeOf, reservedPath, typePath } from "./files.js";
|
|
28
|
+
import { STALE_GEN_MESSAGE, UNDECLARED_MESSAGE, } from "./wire.js";
|
|
29
|
+
/** The Frame Runtime contract reported to pages. */
|
|
30
|
+
export const CONTRACT = '0.2.92';
|
|
31
|
+
/** Capabilities with a local backend; a declared one is granted. `artifact` (self) and `permissions` always are. */
|
|
32
|
+
const BACKED = new Set(FRAME_BACKED_CAPABILITIES);
|
|
33
|
+
/** Declared capabilities that answer, but only with an error code: nothing here can serve them. */
|
|
34
|
+
const STUBBED = FRAME_STUBBED_CAPABILITIES;
|
|
35
|
+
/** A page artifact's marker: its declared capabilities are there (`capabilities`), put by the daemon. */
|
|
36
|
+
export const MARKER_FILE = '.artifact.json';
|
|
37
|
+
/** Caps whose stale-generation reply is `unavailable`; `user` answers null; others use the fallback error code. */
|
|
38
|
+
const STALE_UNAVAILABLE = new Set(['db', 'downloads', 'files', 'paste', 'reads']);
|
|
39
|
+
const BODY_MAX = 64 * 1024 * 1024;
|
|
40
|
+
const UPLOAD_MAX = 21 * 1024 * 1024;
|
|
41
|
+
const WATCH_DEBOUNCE_MS = 300;
|
|
42
|
+
/** An inner shell's client id (its event stream, its room sender). */
|
|
43
|
+
const CLIENT_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
44
|
+
/** `user.search` answers at most this many people. */
|
|
45
|
+
const SEARCH_MAX = 8;
|
|
46
|
+
const PALETTE = ['#785ee8', '#dc3c3d', '#019c7f', '#fbb315', '#ce447d', '#10a122', '#257de0'];
|
|
47
|
+
const ROOM_LIMITS = { maxBytes: 4096, presenceHz: 30, keepaliveMs: 20_000, silenceMs: 150_000, maxPeers: 256, maxRooms: 0 };
|
|
48
|
+
/** A colour of the palette, by id. */
|
|
49
|
+
export function colorOf(id) {
|
|
50
|
+
let h = 0;
|
|
51
|
+
for (let i = 0; i < id.length; i++)
|
|
52
|
+
h = (Math.imul(h, 31) + id.charCodeAt(i)) | 0;
|
|
53
|
+
return PALETTE[Math.abs(h) % PALETTE.length] ?? '#c7c9d1';
|
|
54
|
+
}
|
|
55
|
+
const atLeast = (level, min) => meets(level, min);
|
|
56
|
+
/**
|
|
57
|
+
* The viewer as the wire's `me` (`FrameSession.me`): its name and avatar only under the declaration's `profile` scope,
|
|
58
|
+
* its email only under `email` (without `scopes`, all that a page is told).
|
|
59
|
+
*/
|
|
60
|
+
export function wireUser(viewer, scopes = { profile: true, email: true }) {
|
|
61
|
+
return {
|
|
62
|
+
id: viewer.id,
|
|
63
|
+
name: scopes.profile ? viewer.name : '',
|
|
64
|
+
avatarUrl: scopes.profile ? viewer.avatarUrl : null,
|
|
65
|
+
color: viewer.color,
|
|
66
|
+
email: scopes.email ? viewer.email : null,
|
|
67
|
+
isOwner: viewer.level === 'owner',
|
|
68
|
+
canEdit: atLeast(viewer.level, 'admin'),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
72
|
+
/** A page artifact's declaration: the capabilities its `.artifact.json` declares (none when it has none). */
|
|
73
|
+
export function pageDeclaration(root) {
|
|
74
|
+
let marker = null;
|
|
75
|
+
try {
|
|
76
|
+
marker = JSON.parse(readFileSync(join(root, MARKER_FILE), 'utf8'));
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// none yet, or being written: no capabilities
|
|
80
|
+
}
|
|
81
|
+
return { key: 'page', capabilities: declaredCapabilities(isObject(marker) && isObject(marker.capabilities) ? marker.capabilities : null), monitoring: {} };
|
|
82
|
+
}
|
|
83
|
+
/** What a page artifact shows before it has an index.html: a quiet empty page, which reloads once one is written. */
|
|
84
|
+
const EMPTY_PAGE = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Empty page</title>' +
|
|
85
|
+
'<style>:root{color-scheme:light dark}html,body{height:100%;margin:0}body{display:grid;place-items:center;font:15px/1.5 system-ui,-apple-system,sans-serif;color:#6b6f76;background:Canvas}' +
|
|
86
|
+
'p{margin:0;text-align:center;max-width:28em;padding:0 16px}</style></head>' +
|
|
87
|
+
'<body data-open-artifacts-empty><p>This page is empty for now. It shows up here as soon as its index.html is written.</p></body></html>';
|
|
88
|
+
/**
|
|
89
|
+
* Mounts one artifact folder on an environment. Throws when the type carries no declaration, or when the page is
|
|
90
|
+
* restricted and its origin is one the inner shell runs on (see {@link FrameCore}).
|
|
91
|
+
*/
|
|
92
|
+
export function mountFrameCore(root, env) {
|
|
93
|
+
const declaration = env.page ? pageDeclaration(resolve(root)) : env.type.declaration();
|
|
94
|
+
if (!declaration)
|
|
95
|
+
throw new FrameError('not_frame_type', `${env.type.label}/index.html has no // artifact.json declaration.`, 500);
|
|
96
|
+
return new FrameCore(resolve(root), declaration, env);
|
|
97
|
+
}
|
|
98
|
+
/** Where a served page loads the Frame Runtime from (sendIndex puts it first in the page's <head>). */
|
|
99
|
+
const RUNTIME_SRC = '/_runtime/open-artifacts-frame.js';
|
|
100
|
+
/** {@link RUNTIME_SRC} before the rename: a page that saved its own document then may still hold it. */
|
|
101
|
+
const LEGACY_RUNTIME_SRC = '/_runtime/open-artifact-frame.js';
|
|
102
|
+
/** The page side of `sample`, which the runtime loads on the page's first `use("sample")` (client/sample.ts). */
|
|
103
|
+
const SAMPLE_SRC = '/_runtime/open-artifacts-sample.js';
|
|
104
|
+
/** The page side of `mcp`, loaded on the page's first `use("mcp")` (client/mcp.ts); its inner shell side, `/mcp-shell.js`. */
|
|
105
|
+
const MCP_SRC = '/_runtime/open-artifacts-mcp.js';
|
|
106
|
+
/** What a declared `sample` answers where nothing serves it ({@link FrameEnv.sample} absent). */
|
|
107
|
+
const SAMPLE_UNSERVED = 'tools_unavailable';
|
|
108
|
+
/**
|
|
109
|
+
* A document as the page wrote it, without the runtime sendIndex put in its <head>: what a page that publishes itself
|
|
110
|
+
* from `document.documentElement.outerHTML` sends back. Kept, the boot script would carry this run's shell origin and
|
|
111
|
+
* grants into the file, and run before the fresh one on every later load. (`safe()` escapes `<`, so the boot script's
|
|
112
|
+
* own text holds no `</script>`.)
|
|
113
|
+
*/
|
|
114
|
+
export function withoutFrameRuntime(html) {
|
|
115
|
+
return html
|
|
116
|
+
.replace(/<script>window\.__FRAME_PREAMBLE=[^<]*<\/script>/g, '')
|
|
117
|
+
.replace(new RegExp(`<script src="(?:${RUNTIME_SRC.replace(/[.]/g, '\\.')}|${LEGACY_RUNTIME_SRC.replace(/[.]/g, '\\.')})"></script>`, 'g'), '');
|
|
118
|
+
}
|
|
119
|
+
/** One open artifact of an original type. */
|
|
120
|
+
export class FrameCore {
|
|
121
|
+
root;
|
|
122
|
+
id;
|
|
123
|
+
page;
|
|
124
|
+
contentOrigin;
|
|
125
|
+
shellOrigin;
|
|
126
|
+
db;
|
|
127
|
+
comments;
|
|
128
|
+
files;
|
|
129
|
+
blobs;
|
|
130
|
+
/** The broker generation: bumped when the type or the files change under an open page. */
|
|
131
|
+
brokerGen = 1;
|
|
132
|
+
/** Page mode ({@link FrameEnv.page}). */
|
|
133
|
+
pageMode;
|
|
134
|
+
/** {@link FrameEnv.contentSecurityPolicy}. */
|
|
135
|
+
contentSecurityPolicy;
|
|
136
|
+
/** {@link FrameEnv.restricted}. */
|
|
137
|
+
restricted;
|
|
138
|
+
declaration;
|
|
139
|
+
title;
|
|
140
|
+
ver;
|
|
141
|
+
/** What the declaration grants (each viewer gets those of these its level allows: {@link grantsFor}). */
|
|
142
|
+
grants = [];
|
|
143
|
+
stubs = {};
|
|
144
|
+
/** The declaration's db rules, compiled. */
|
|
145
|
+
dbRules = compileDbRules(undefined);
|
|
146
|
+
env;
|
|
147
|
+
shellOrigins;
|
|
148
|
+
config;
|
|
149
|
+
flagKeys = [];
|
|
150
|
+
typeVer;
|
|
151
|
+
/** Open event connections, by viewer and client id. */
|
|
152
|
+
clients = new Map();
|
|
153
|
+
touchTimer = null;
|
|
154
|
+
/** Paths the page wrote, by the author the daemon records them under. */
|
|
155
|
+
touchPaths = new Map();
|
|
156
|
+
presenceCache = null;
|
|
157
|
+
watcher = null;
|
|
158
|
+
watchTimer = null;
|
|
159
|
+
typeTimer = null;
|
|
160
|
+
pending = new Set();
|
|
161
|
+
/** Page mode: the capabilities last read from the marker, to tell when they change. */
|
|
162
|
+
capsSeen = '';
|
|
163
|
+
/** The `mcp` routes (mcp-relay.ts). */
|
|
164
|
+
mcp = new FrameMcp({
|
|
165
|
+
id: () => this.id,
|
|
166
|
+
service: () => this.env.mcp,
|
|
167
|
+
capabilities: () => this.caps,
|
|
168
|
+
stub: () => this.stubs.mcp,
|
|
169
|
+
granted: (viewer) => this.grantsFor(viewer).includes('mcp'),
|
|
170
|
+
disabled: (viewer) => this.sampleDisabled(viewer),
|
|
171
|
+
brokerGen: () => this.brokerGen,
|
|
172
|
+
validClient: (client) => FrameCore.validClient(client),
|
|
173
|
+
log: (line) => this.log(line),
|
|
174
|
+
});
|
|
175
|
+
constructor(root, declaration, env) {
|
|
176
|
+
this.root = root;
|
|
177
|
+
this.declaration = declaration;
|
|
178
|
+
this.env = env;
|
|
179
|
+
this.pageMode = env.page;
|
|
180
|
+
this.contentSecurityPolicy = env.contentSecurityPolicy || null;
|
|
181
|
+
this.restricted = env.restricted;
|
|
182
|
+
this.id = env.id;
|
|
183
|
+
this.title = env.title ?? '';
|
|
184
|
+
this.page = `/f/${randomBytes(18).toString('base64url')}/`;
|
|
185
|
+
this.contentOrigin = env.origins.content;
|
|
186
|
+
this.shellOrigin = env.origins.shell;
|
|
187
|
+
this.shellOrigins = new Set([env.origins.shell, ...env.origins.shellOrigins]);
|
|
188
|
+
// A sandbox with allow-same-origin keeps the page from the inner shell only while the two origins differ.
|
|
189
|
+
if (this.restricted && [...this.shellOrigins].some((o) => originOf(o) === originOf(this.contentOrigin))) {
|
|
190
|
+
throw new FrameError('same_origin', `A restricted page needs an origin of its own: ${this.contentOrigin} is the inner shell's. Give the page a host name the shell does not use.`, 500);
|
|
191
|
+
}
|
|
192
|
+
const guard = { guard: env.guard };
|
|
193
|
+
this.db = new DbStore(root, { ...guard, imports: env.imports });
|
|
194
|
+
this.comments = new CommentStore(root, guard);
|
|
195
|
+
this.files = new FileStore(root, { ownIndex: this.pageMode, ...guard });
|
|
196
|
+
this.blobs = new BlobStore(root, guard);
|
|
197
|
+
this.ver = this.files.manifest().ver;
|
|
198
|
+
// A type written before the rename keeps its hints under `openArtifact`.
|
|
199
|
+
this.config = adoptLegacyManifest(env.type.manifest());
|
|
200
|
+
this.typeVer = env.type.fingerprint();
|
|
201
|
+
this.applyDeclaration(declaration);
|
|
202
|
+
this.db.on('change', (paths) => this.dbChanged(paths));
|
|
203
|
+
this.startWatching();
|
|
204
|
+
if (this.pageMode)
|
|
205
|
+
this.pageTitle();
|
|
206
|
+
}
|
|
207
|
+
applyDeclaration(declaration) {
|
|
208
|
+
this.declaration = declaration;
|
|
209
|
+
if (this.pageMode)
|
|
210
|
+
this.capsSeen = JSON.stringify(declaration.capabilities ?? {});
|
|
211
|
+
const caps = declaration.capabilities ?? {};
|
|
212
|
+
// `sample` is backed only where the environment serves it; elsewhere it answers as it did before it was.
|
|
213
|
+
const served = (c) => BACKED.has(c) && (c !== 'sample' || !!this.env.sample || this.env.sampleBy === 'shell') && (c !== 'mcp' || mcpServed(this.env.mcp, caps));
|
|
214
|
+
this.grants = [...new Set([...Object.keys(caps).filter(served), 'artifact', 'permissions'])];
|
|
215
|
+
this.stubs = Object.fromEntries(Object.keys(caps).flatMap((c) => (STUBBED[c] ? [[c, STUBBED[c]]] : c === 'sample' && !served(c) ? [[c, SAMPLE_UNSERVED]] : c === 'mcp' && !served(c) ? [[c, MCP_UNSERVED]] : [])));
|
|
216
|
+
const flags = caps.flags;
|
|
217
|
+
this.flagKeys = isObject(flags) && Array.isArray(flags.keys) ? flags.keys.filter((k) => typeof k === 'string') : [];
|
|
218
|
+
this.dbRules = compileDbRules(caps.db);
|
|
219
|
+
if (this.dbRules.problem)
|
|
220
|
+
this.log(`db rules refused (only the owner reads or writes): ${this.dbRules.problem}`);
|
|
221
|
+
}
|
|
222
|
+
// ---- who may do what (access.ts holds the rules) ------------------------------------------------------------------
|
|
223
|
+
get caps() {
|
|
224
|
+
return this.declaration.capabilities ?? {};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* What the page is told of people: the declaration's `user` scopes where the environment withholds identity (a
|
|
228
|
+
* site); else as before (names, no email).
|
|
229
|
+
*/
|
|
230
|
+
get scopes() {
|
|
231
|
+
return this.env.withholdIdentity ? userScopes(this.caps.user) : { profile: true, email: false };
|
|
232
|
+
}
|
|
233
|
+
/** Whether room senders carry their viewer's id (`by`): with `user` declared, or wherever identity is not withheld. */
|
|
234
|
+
get vouches() {
|
|
235
|
+
return !this.env.withholdIdentity || this.grants.includes('user');
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The capabilities one viewer is granted: the declaration's, less `comments` for a viewer who may not comment and
|
|
239
|
+
* `assets` below the upload level (`admin`, or `interact` when the declaration opens uploads to it).
|
|
240
|
+
*/
|
|
241
|
+
grantsFor(viewer) {
|
|
242
|
+
return this.grants.filter((cap) => {
|
|
243
|
+
if (cap === 'comments')
|
|
244
|
+
return viewer.canComment;
|
|
245
|
+
if (cap === 'assets')
|
|
246
|
+
return atLeast(viewer.level, uploadLevel(this.caps.assets));
|
|
247
|
+
return true;
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/** Whether a viewer may read / write a db path (`segs`): the declared rules, else the defaults. */
|
|
251
|
+
mayDb(viewer, segs, action) {
|
|
252
|
+
return dbAllows(this.dbRules, viewer, segs, action);
|
|
253
|
+
}
|
|
254
|
+
/** A db write the viewer may make, or `invalid_argument` (as the contract answers a refused write). */
|
|
255
|
+
mustWrite(viewer, segs) {
|
|
256
|
+
if (!this.mayDb(viewer, segs, 'write'))
|
|
257
|
+
throw new FrameError('invalid_argument', `This viewer may not write ${segs.join('/')}.`);
|
|
258
|
+
}
|
|
259
|
+
/** Whether the viewer edits the artifact (admin and above). */
|
|
260
|
+
static edits(viewer) {
|
|
261
|
+
return atLeast(viewer.level, 'admin');
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Whether the page may write itself. On a site, `{artifact: {publish: false}}` (or `self`) says no, for every viewer,
|
|
265
|
+
* writers included (the contract: `publish`, `edit` and `sync` reject `not_granted`; editors and the agent still
|
|
266
|
+
* publish the usual way, outside the page). On this computer, as before: the declaration is not read for it.
|
|
267
|
+
*/
|
|
268
|
+
get publishes() {
|
|
269
|
+
if (!this.env.withholdIdentity)
|
|
270
|
+
return true;
|
|
271
|
+
const own = isObject(this.caps.artifact) ? this.caps.artifact : isObject(this.caps.self) ? this.caps.self : {};
|
|
272
|
+
return own.publish !== false;
|
|
273
|
+
}
|
|
274
|
+
/** A write of the artifact's files: `not_granted` where the page declares `publish: false`, `not_writer` below admin. */
|
|
275
|
+
mustPublish(viewer) {
|
|
276
|
+
if (!this.publishes)
|
|
277
|
+
throw new FrameError('not_granted', 'This page declares publish: false.');
|
|
278
|
+
if (!FrameCore.edits(viewer))
|
|
279
|
+
throw new FrameError('not_writer', 'Only people who can edit this artifact publish its files.');
|
|
280
|
+
}
|
|
281
|
+
/** Whether a viewer may put text in front of the owner's agent: an editor who may comment. */
|
|
282
|
+
static reachesAgent(viewer) {
|
|
283
|
+
return FrameCore.edits(viewer) && viewer.canComment;
|
|
284
|
+
}
|
|
285
|
+
log(line) {
|
|
286
|
+
this.env.log?.(line);
|
|
287
|
+
}
|
|
288
|
+
/** The viewer of a request. */
|
|
289
|
+
viewerOf(req) {
|
|
290
|
+
return this.env.viewer(req);
|
|
291
|
+
}
|
|
292
|
+
close() {
|
|
293
|
+
if (this.watchTimer)
|
|
294
|
+
clearTimeout(this.watchTimer);
|
|
295
|
+
if (this.typeTimer)
|
|
296
|
+
clearTimeout(this.typeTimer);
|
|
297
|
+
if (this.touchTimer)
|
|
298
|
+
clearTimeout(this.touchTimer);
|
|
299
|
+
try {
|
|
300
|
+
this.watcher?.close();
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
// already closed
|
|
304
|
+
}
|
|
305
|
+
this.watcher = null;
|
|
306
|
+
for (const c of this.clients.values())
|
|
307
|
+
c.end();
|
|
308
|
+
this.clients.clear();
|
|
309
|
+
}
|
|
310
|
+
hasBlob(id) {
|
|
311
|
+
return !!this.blobs.meta(id);
|
|
312
|
+
}
|
|
313
|
+
// ---- changes -------------------------------------------------------------------------------------------------------
|
|
314
|
+
/** Starts the environment's watcher, when it has one; else every change comes through the core. */
|
|
315
|
+
startWatching() {
|
|
316
|
+
const start = this.env.watch;
|
|
317
|
+
if (!start)
|
|
318
|
+
return;
|
|
319
|
+
this.watcher = start({
|
|
320
|
+
artifact: (rel) => {
|
|
321
|
+
// Page mode: the marker carries the capabilities (the daemon writes it through a temporary file and a rename).
|
|
322
|
+
if (this.pageMode && (rel === MARKER_FILE || rel.startsWith(`${MARKER_FILE}.`) || rel.startsWith(`.${MARKER_FILE}`))) {
|
|
323
|
+
if (this.typeTimer)
|
|
324
|
+
clearTimeout(this.typeTimer);
|
|
325
|
+
this.typeTimer = setTimeout(() => this.capabilitiesChanged(), WATCH_DEBOUNCE_MS);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (ignoredChange(rel))
|
|
329
|
+
return;
|
|
330
|
+
this.pending.add(rel);
|
|
331
|
+
if (this.watchTimer)
|
|
332
|
+
clearTimeout(this.watchTimer);
|
|
333
|
+
this.watchTimer = setTimeout(() => this.flushWatch(), WATCH_DEBOUNCE_MS);
|
|
334
|
+
},
|
|
335
|
+
// The type folder: a new index.html or artifact-type/ under an open page rewires its broker.
|
|
336
|
+
type: (rel) => {
|
|
337
|
+
if (rel && rel.split('/').some((s) => s.startsWith('.')))
|
|
338
|
+
return;
|
|
339
|
+
if (this.typeTimer)
|
|
340
|
+
clearTimeout(this.typeTimer);
|
|
341
|
+
this.typeTimer = setTimeout(() => this.typeChanged(), WATCH_DEBOUNCE_MS);
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/** Re-reads the type; when what it serves changed, rewires. */
|
|
346
|
+
typeChanged() {
|
|
347
|
+
const next = this.env.type.fingerprint();
|
|
348
|
+
if (next === this.typeVer)
|
|
349
|
+
return false;
|
|
350
|
+
this.typeVer = next;
|
|
351
|
+
let declaration = null;
|
|
352
|
+
try {
|
|
353
|
+
declaration = this.env.type.declaration();
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
this.log(`type: ${error?.message ?? error}`);
|
|
357
|
+
}
|
|
358
|
+
if (declaration)
|
|
359
|
+
this.applyDeclaration(declaration);
|
|
360
|
+
this.rewire('type');
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Page mode: re-reads the capabilities `.artifact.json` declares; when they changed, rewires as for a new type, and
|
|
365
|
+
* open pages reload with the new set. Also run when a shell asks for its session, in case a watcher missed it.
|
|
366
|
+
*/
|
|
367
|
+
capabilitiesChanged() {
|
|
368
|
+
if (!this.pageMode)
|
|
369
|
+
return false;
|
|
370
|
+
const declaration = pageDeclaration(this.root);
|
|
371
|
+
if (JSON.stringify(declaration.capabilities) === this.capsSeen)
|
|
372
|
+
return false;
|
|
373
|
+
this.applyDeclaration(declaration);
|
|
374
|
+
this.rewire('type');
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
377
|
+
/** Page mode: the title of the page's index.html (its `<title>`) becomes the artifact's, when it says one. */
|
|
378
|
+
pageTitle() {
|
|
379
|
+
let html;
|
|
380
|
+
try {
|
|
381
|
+
html = readFileSync(join(this.root, 'index.html'), 'utf8');
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const title = titleInHtml(html)?.slice(0, 200);
|
|
387
|
+
if (!title || title === this.title)
|
|
388
|
+
return;
|
|
389
|
+
this.title = title;
|
|
390
|
+
const daemon = this.env.daemon;
|
|
391
|
+
// No author: the title follows the file, whoever wrote it (the page's own publish is recorded as the person's).
|
|
392
|
+
if (daemon?.available)
|
|
393
|
+
daemon.touch(this.id, { author: '', paths: [], title }).catch(() => { });
|
|
394
|
+
}
|
|
395
|
+
/** A new broker generation: calls stamped with the old one are not run, open shells cut theirs and reload. */
|
|
396
|
+
rewire(reason) {
|
|
397
|
+
this.brokerGen += 1;
|
|
398
|
+
this.broadcast((c) => ({ t: 'rewired', brokerGen: this.brokerGen, caps: this.grantsFor(c.viewer), reason }));
|
|
399
|
+
}
|
|
400
|
+
/** Applies what the folder watcher gathered (exposed for tests: watchers are slow to settle). */
|
|
401
|
+
flushWatch() {
|
|
402
|
+
const rels = [...this.pending];
|
|
403
|
+
this.pending.clear();
|
|
404
|
+
this.noteChanges(rels);
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Paths of the artifact folder that changed without the core writing them (relative, `/`-separated): the watcher's
|
|
408
|
+
* gatherings, or, where there is no watcher, what the host wrote itself (a site's sync). Open pages get the events.
|
|
409
|
+
*/
|
|
410
|
+
noteChanges(paths) {
|
|
411
|
+
if (this.pageMode && paths.includes(MARKER_FILE))
|
|
412
|
+
this.capabilitiesChanged();
|
|
413
|
+
const rels = paths.filter((r) => !ignoredChange(r));
|
|
414
|
+
if (!rels.length)
|
|
415
|
+
return;
|
|
416
|
+
const docs = docPathsOf(rels);
|
|
417
|
+
if (docs.length || rels.some((r) => r === 'db' || r.startsWith('db/')))
|
|
418
|
+
this.dbChanged(docs);
|
|
419
|
+
if (rels.includes(COMMENTS_FILE))
|
|
420
|
+
this.commentsChanged();
|
|
421
|
+
if (rels.some((r) => r !== COMMENTS_FILE && !r.startsWith('db/') && r !== 'db'))
|
|
422
|
+
this.filesChanged(rels.filter((r) => !reservedPath(r)));
|
|
423
|
+
if (this.pageMode && rels.includes('index.html'))
|
|
424
|
+
this.pageTitle();
|
|
425
|
+
}
|
|
426
|
+
/** Files changed on disk, not by this page's own publish: a new manifest rewires and reloads open pages. */
|
|
427
|
+
filesChanged(paths = []) {
|
|
428
|
+
const m = this.files.manifest();
|
|
429
|
+
if (m.ver === this.ver)
|
|
430
|
+
return false;
|
|
431
|
+
this.ver = m.ver;
|
|
432
|
+
this.rewire('files');
|
|
433
|
+
this.broadcast({ t: 'files', ver: m.ver, paths });
|
|
434
|
+
return true;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Sends an event to every open connection, or what `event` makes of it for that connection's viewer (null: nothing
|
|
438
|
+
* for this one).
|
|
439
|
+
*/
|
|
440
|
+
broadcast(event) {
|
|
441
|
+
for (const c of this.clients.values()) {
|
|
442
|
+
const out = typeof event === 'function' ? event(c) : event;
|
|
443
|
+
if (out)
|
|
444
|
+
c.send(out);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Documents changed: each connection hears of the ones its viewer may read, and of none it may not. No paths (a
|
|
449
|
+
* change the watcher could not place) reruns every listener, whose reads are each checked.
|
|
450
|
+
*/
|
|
451
|
+
dbChanged(paths) {
|
|
452
|
+
this.broadcast((c) => {
|
|
453
|
+
if (!paths.length)
|
|
454
|
+
return { t: 'db', paths: [] };
|
|
455
|
+
const mine = paths.filter((p) => {
|
|
456
|
+
try {
|
|
457
|
+
return this.mayDb(c.viewer, splitPath(p), 'read');
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
return false;
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
return mine.length ? { t: 'db', paths: mine } : null;
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
/** A write from the page: the daemon records it (best effort, gathered), under the viewer who made it. */
|
|
467
|
+
touched(paths, viewer) {
|
|
468
|
+
const author = touchAuthor(viewer);
|
|
469
|
+
let set = this.touchPaths.get(author);
|
|
470
|
+
if (!set)
|
|
471
|
+
this.touchPaths.set(author, (set = new Set()));
|
|
472
|
+
for (const p of paths)
|
|
473
|
+
set.add(p);
|
|
474
|
+
if (this.touchTimer)
|
|
475
|
+
return;
|
|
476
|
+
this.touchTimer = setTimeout(() => {
|
|
477
|
+
this.touchTimer = null;
|
|
478
|
+
const batches = [...this.touchPaths.entries()];
|
|
479
|
+
this.touchPaths.clear();
|
|
480
|
+
const daemon = this.env.daemon;
|
|
481
|
+
for (const [by, set] of batches) {
|
|
482
|
+
const list = [...set].slice(0, 100);
|
|
483
|
+
if (daemon?.available)
|
|
484
|
+
daemon.touch(this.id, { author: by, paths: list }).catch(() => { });
|
|
485
|
+
}
|
|
486
|
+
}, 1000);
|
|
487
|
+
this.touchTimer.unref?.();
|
|
488
|
+
}
|
|
489
|
+
// ---- requests on the inner shell's origin (under Site.page) ------------------------------------------------------
|
|
490
|
+
/**
|
|
491
|
+
* Whether a request may open the event stream over a WebSocket: admitted, from the inner shell's origin (a browser
|
|
492
|
+
* sends `Origin` on every WebSocket), and not the page's read-only token.
|
|
493
|
+
*/
|
|
494
|
+
acceptsStream(req) {
|
|
495
|
+
if (new URL(req.url || '/', 'http://local').pathname !== '/api/frame/events')
|
|
496
|
+
return false;
|
|
497
|
+
return this.env.admit(req) && this.sameOrigin(req) && this.readOnly(req) === false;
|
|
498
|
+
}
|
|
499
|
+
/** Whether the request's viewer is the page's read-only token; null when the environment places no viewer. */
|
|
500
|
+
readOnly(req) {
|
|
501
|
+
try {
|
|
502
|
+
return !!this.viewerOf(req).readOnly;
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* One request on the inner shell's origin. `{events: true}`: it asks for its event stream, which the adapter opens
|
|
510
|
+
* and hands to {@link connect}.
|
|
511
|
+
*/
|
|
512
|
+
async request(req) {
|
|
513
|
+
const reply = await this.shellReply(req);
|
|
514
|
+
// Neither origin tells anyone where it was: the page address and the shell's carry the site's tokens.
|
|
515
|
+
if ('status' in reply)
|
|
516
|
+
reply.headers['Referrer-Policy'] = 'no-referrer';
|
|
517
|
+
return reply;
|
|
518
|
+
}
|
|
519
|
+
async shellReply(req) {
|
|
520
|
+
const url = new URL(req.url || '/', 'http://local');
|
|
521
|
+
const p = url.pathname;
|
|
522
|
+
if (!this.env.admit(req))
|
|
523
|
+
return deny(403, 'Frame pages open on this computer only.');
|
|
524
|
+
// The page's read-only token opens the page's own origin, nothing here.
|
|
525
|
+
if (this.readOnly(req) !== false)
|
|
526
|
+
return deny(403, 'Not with this token.');
|
|
527
|
+
const blob = /^\/_blob\/([0-9a-f]{32})$/.exec(p);
|
|
528
|
+
if (blob)
|
|
529
|
+
return this.sendBlob(req, blob[1]);
|
|
530
|
+
if (p === '/' || p === '/index.html')
|
|
531
|
+
return this.sendClientFile(req, 'shell.html');
|
|
532
|
+
if (p === '/shell.js' || p === '/shell.css' || p === '/comments.js' || p === '/comments.css')
|
|
533
|
+
return this.sendClientFile(req, p.slice(1));
|
|
534
|
+
if (p === '/mcp-shell.js')
|
|
535
|
+
return this.sendScript(req, 'mcp-shell');
|
|
536
|
+
if (!p.startsWith('/api/frame/'))
|
|
537
|
+
return deny(404, 'Not found');
|
|
538
|
+
if (!this.sameOrigin(req))
|
|
539
|
+
return deny(403, 'Not from this page.');
|
|
540
|
+
const name = p.slice('/api/frame/'.length);
|
|
541
|
+
try {
|
|
542
|
+
if (name === 'events' && req.method === 'GET')
|
|
543
|
+
return { events: true };
|
|
544
|
+
const viewer = this.viewerOf(req);
|
|
545
|
+
if (name === 'session' && req.method === 'GET')
|
|
546
|
+
return json(200, this.session(viewer));
|
|
547
|
+
if (p === FRAME_SAMPLE_ROUTES.limits && req.method === 'GET')
|
|
548
|
+
return json(200, await this.sampleLimits(String(url.searchParams.get('client') ?? ''), viewer));
|
|
549
|
+
if (p === FRAME_SAMPLE_ROUTES.state && req.method === 'GET')
|
|
550
|
+
return json(200, await this.sampleState(viewer));
|
|
551
|
+
if (p === FRAME_MCP_ROUTES.state && req.method === 'GET')
|
|
552
|
+
return json(200, await this.mcp.answer(p, {}, url.searchParams, viewer));
|
|
553
|
+
if (req.method !== 'POST')
|
|
554
|
+
return deny(405, 'Method not allowed');
|
|
555
|
+
if (name === 'upload') {
|
|
556
|
+
const stale = this.gate('assets', numberOrUndefined(url.searchParams.get('gen')));
|
|
557
|
+
if (stale)
|
|
558
|
+
return json(200, stale);
|
|
559
|
+
// Checked before the body is read: a viewer who may not upload sends nothing in.
|
|
560
|
+
if (!this.grantsFor(viewer).includes('assets'))
|
|
561
|
+
return json(200, { error: { code: 'not_granted', message: `assets: ${UNDECLARED_MESSAGE}` } });
|
|
562
|
+
const data = bufferOf(await req.body(UPLOAD_MAX));
|
|
563
|
+
const out = this.blobs.upload(data, url.searchParams.get('type') ?? req.headers['content-type'], viewer.id);
|
|
564
|
+
this.touched(['_blobs'], viewer);
|
|
565
|
+
return json(200, { result: out });
|
|
566
|
+
}
|
|
567
|
+
if (!String(req.headers['content-type'] ?? '').startsWith('application/json'))
|
|
568
|
+
return deny(415, 'JSON only.');
|
|
569
|
+
if (p === FRAME_SAMPLE_ROUTES.call) {
|
|
570
|
+
// An adapter that streams answers this route with sampleStream(); through request() it can only say no.
|
|
571
|
+
const body = JSON.parse(bufferOf(await req.body(SAMPLE_BODY_MAX)).toString('utf8') || '{}');
|
|
572
|
+
const call = this.sampleCall(isObject(body) ? body : {}, viewer);
|
|
573
|
+
return sampleErrorReply('code' in call ? call : sampleError('upstream_error', 'This host does not stream sample calls.'));
|
|
574
|
+
}
|
|
575
|
+
if (p === FRAME_MCP_ROUTES.call) {
|
|
576
|
+
// As sample: an adapter that streams answers this route with mcpStream().
|
|
577
|
+
const body = JSON.parse(bufferOf(await req.body(MCP_BODY_MAX)).toString('utf8') || '{}');
|
|
578
|
+
const call = this.mcp.call(isObject(body) ? body : {}, viewer);
|
|
579
|
+
return mcpErrorReply('code' in call ? call : { code: 'upstream_error', message: 'This host does not stream connector calls.' });
|
|
580
|
+
}
|
|
581
|
+
if (p === FRAME_MCP_ROUTES.tools || p === FRAME_MCP_ROUTES.describe) {
|
|
582
|
+
const body = JSON.parse(bufferOf(await req.body(MCP_BODY_MAX)).toString('utf8') || '{}');
|
|
583
|
+
return json(200, await this.mcp.answer(p, isObject(body) ? body : {}, url.searchParams, viewer));
|
|
584
|
+
}
|
|
585
|
+
const body = JSON.parse(bufferOf(await req.body(BODY_MAX)).toString('utf8') || '{}');
|
|
586
|
+
if (name === 'cap')
|
|
587
|
+
return json(200, await this.call(body, viewer));
|
|
588
|
+
if (p === FRAME_SAMPLE_ROUTES.tool)
|
|
589
|
+
return json(200, await this.sampleTool(isObject(body) ? body : {}, viewer));
|
|
590
|
+
if (name === 'title')
|
|
591
|
+
return json(200, await this.proposeTitle(body, viewer));
|
|
592
|
+
if (name === 'agent')
|
|
593
|
+
return json(200, await this.askAgent(body, viewer));
|
|
594
|
+
if (name === 'activity')
|
|
595
|
+
return json(200, await this.activity(viewer));
|
|
596
|
+
return deny(404, 'Not found');
|
|
597
|
+
}
|
|
598
|
+
catch (error) {
|
|
599
|
+
return json(error?.status ?? 500, { error: errorOf(error) });
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* `POST /api/frame/mcp/call`, for an adapter that can stream (as {@link sampleStream}): the checks, then the call's
|
|
604
|
+
* NDJSON stream from the daemon (mcp-relay.ts), or one `error` line.
|
|
605
|
+
*/
|
|
606
|
+
async mcpStream(req, signal) {
|
|
607
|
+
if (!this.env.admit(req))
|
|
608
|
+
return deny(403, 'Frame pages open on this computer only.');
|
|
609
|
+
if (this.readOnly(req) !== false)
|
|
610
|
+
return deny(403, 'Not with this token.');
|
|
611
|
+
if (!this.sameOrigin(req))
|
|
612
|
+
return deny(403, 'Not from this page.');
|
|
613
|
+
if (req.method !== 'POST')
|
|
614
|
+
return deny(405, 'Method not allowed');
|
|
615
|
+
if (!String(req.headers['content-type'] ?? '').startsWith('application/json'))
|
|
616
|
+
return deny(415, 'JSON only.');
|
|
617
|
+
try {
|
|
618
|
+
const viewer = this.viewerOf(req);
|
|
619
|
+
const parsed = JSON.parse(bufferOf(await req.body(MCP_BODY_MAX)).toString('utf8') || '{}');
|
|
620
|
+
return this.mcp.stream(isObject(parsed) ? parsed : {}, viewer, signal);
|
|
621
|
+
}
|
|
622
|
+
catch (error) {
|
|
623
|
+
return json(error?.status ?? 500, { error: errorOf(error) });
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
// ---- sample (sample-relay.ts holds the checks and the relay) -----------------------------------------------------
|
|
627
|
+
/** Whether the declaration lets the page send images with `sample` (`{sample: {images: true}}`). */
|
|
628
|
+
get sampleImages() {
|
|
629
|
+
const declared = this.caps.sample;
|
|
630
|
+
return isObject(declared) && declared.images === true;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Whether `viewer` is granted `sample` but this view cannot use it (`capability_disabled`): the page's read-only
|
|
634
|
+
* token, and, in an adapter that has them, a snapshot's visit.
|
|
635
|
+
*/
|
|
636
|
+
sampleDisabled(viewer) {
|
|
637
|
+
return !!viewer.readOnly;
|
|
638
|
+
}
|
|
639
|
+
/** Why one view may not use `sample` at all, or null. */
|
|
640
|
+
sampleUnusable(viewer, forLimits = false) {
|
|
641
|
+
if (this.stubs.sample)
|
|
642
|
+
return sampleError(this.stubs.sample, 'sample is not available on this computer.');
|
|
643
|
+
if (!this.grantsFor(viewer).includes('sample'))
|
|
644
|
+
return sampleError('not_declared', `sample: ${UNDECLARED_MESSAGE}`);
|
|
645
|
+
if (!this.env.sample)
|
|
646
|
+
return sampleError(SAMPLE_UNSERVED, 'sample is not available on this computer.');
|
|
647
|
+
if (!forLimits && this.sampleDisabled(viewer))
|
|
648
|
+
return sampleError('capability_disabled', 'sample is not available in this view (a snapshot of the page).');
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
/** A `POST /api/frame/sample` body as the daemon is asked, or why it is refused before the daemon sees it. */
|
|
652
|
+
sampleCall(body, viewer) {
|
|
653
|
+
if (typeof body.brokerGen === 'number' && body.brokerGen !== this.brokerGen)
|
|
654
|
+
return sampleError('upstream_error', STALE_GEN_MESSAGE);
|
|
655
|
+
const unusable = this.sampleUnusable(viewer);
|
|
656
|
+
if (unusable)
|
|
657
|
+
return unusable;
|
|
658
|
+
const client = String(body.client ?? '');
|
|
659
|
+
if (!FrameCore.validClient(client))
|
|
660
|
+
return sampleError('invalid_request', 'Not a client id.');
|
|
661
|
+
const checked = checkSampleRequest(body, this.sampleImages);
|
|
662
|
+
if ('code' in checked)
|
|
663
|
+
return checked;
|
|
664
|
+
return { id: this.id, view: client, runtime: 'page', images: this.sampleImages, ...checked };
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* `POST /api/frame/sample`, for an adapter that can stream: the same checks as every inner shell route, then the
|
|
668
|
+
* call's NDJSON stream from the daemon (see sample-relay.ts), or a reply (a refusal is one `error` line). Aborting
|
|
669
|
+
* `signal` (the inner shell closed the request) cancels the call.
|
|
670
|
+
*/
|
|
671
|
+
async sampleStream(req, signal) {
|
|
672
|
+
const denied = () => {
|
|
673
|
+
if (!this.env.admit(req))
|
|
674
|
+
return deny(403, 'Frame pages open on this computer only.');
|
|
675
|
+
if (this.readOnly(req) !== false)
|
|
676
|
+
return deny(403, 'Not with this token.');
|
|
677
|
+
if (!this.sameOrigin(req))
|
|
678
|
+
return deny(403, 'Not from this page.');
|
|
679
|
+
if (req.method !== 'POST')
|
|
680
|
+
return deny(405, 'Method not allowed');
|
|
681
|
+
if (!String(req.headers['content-type'] ?? '').startsWith('application/json'))
|
|
682
|
+
return deny(415, 'JSON only.');
|
|
683
|
+
return null;
|
|
684
|
+
};
|
|
685
|
+
const no = denied();
|
|
686
|
+
if (no)
|
|
687
|
+
return { ...no, headers: { ...no.headers, 'Referrer-Policy': 'no-referrer' } };
|
|
688
|
+
try {
|
|
689
|
+
const viewer = this.viewerOf(req);
|
|
690
|
+
const parsed = JSON.parse(bufferOf(await req.body(SAMPLE_BODY_MAX)).toString('utf8') || '{}');
|
|
691
|
+
const body = isObject(parsed) ? parsed : {};
|
|
692
|
+
const call = this.sampleCall(body, viewer);
|
|
693
|
+
if ('code' in call)
|
|
694
|
+
return sampleErrorReply(call);
|
|
695
|
+
return { status: 200, headers: { ...SAMPLE_STREAM_HEADERS }, stream: relaySample(this.env.sample, call, signal, (line) => this.log(line)) };
|
|
696
|
+
}
|
|
697
|
+
catch (error) {
|
|
698
|
+
const reply = json(error?.status ?? 500, { error: errorOf(error) });
|
|
699
|
+
reply.headers['Referrer-Policy'] = 'no-referrer';
|
|
700
|
+
return reply;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
/** `POST /api/frame/sample/tool`: one round's tool results, handed on (`{ok: true}`, or `{error}`). */
|
|
704
|
+
async sampleTool(body, viewer) {
|
|
705
|
+
const unusable = this.sampleUnusable(viewer);
|
|
706
|
+
if (unusable)
|
|
707
|
+
return { error: unusable };
|
|
708
|
+
const checked = checkToolRequest(body);
|
|
709
|
+
if ('code' in checked)
|
|
710
|
+
return { error: checked };
|
|
711
|
+
try {
|
|
712
|
+
const answer = await this.env.sample.tool({ id: this.id, ...checked });
|
|
713
|
+
return isObject(answer) && isObject(answer.error) ? answer : { ok: true };
|
|
714
|
+
}
|
|
715
|
+
catch (error) {
|
|
716
|
+
return { error: errorOf(error) };
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
/** `GET /api/frame/sample/limits?client=`: the view's limits (a snapshot may read them too), or `{error}`. */
|
|
720
|
+
async sampleLimits(client, viewer) {
|
|
721
|
+
const unusable = this.sampleUnusable(viewer, true);
|
|
722
|
+
if (unusable)
|
|
723
|
+
return { error: unusable };
|
|
724
|
+
if (!FrameCore.validClient(client))
|
|
725
|
+
return { error: sampleError('invalid_request', 'Not a client id.') };
|
|
726
|
+
try {
|
|
727
|
+
const limits = await this.env.sample.limits({ id: this.id, view: client, ...(this.sampleImages ? { images: '1' } : {}) });
|
|
728
|
+
if (!isObject(limits))
|
|
729
|
+
return { error: sampleError('upstream_error', 'The limits could not be read.') };
|
|
730
|
+
// Never an images member for a page that does not declare them, whatever the daemon said.
|
|
731
|
+
const { images, ...rest } = limits;
|
|
732
|
+
return this.sampleImages && images ? { ...rest, images } : rest;
|
|
733
|
+
}
|
|
734
|
+
catch (error) {
|
|
735
|
+
return { error: errorOf(error) };
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* `GET /api/frame/sample/state`: whether the page's calls would be asked about (`permissions.state("sample")`), read
|
|
740
|
+
* from the person's permissions without asking, and the Shell page where they can change it. Or `{error}`.
|
|
741
|
+
*/
|
|
742
|
+
async sampleState(viewer) {
|
|
743
|
+
const unusable = this.sampleUnusable(viewer, true);
|
|
744
|
+
if (unusable)
|
|
745
|
+
return { error: unusable };
|
|
746
|
+
const service = this.env.sample;
|
|
747
|
+
try {
|
|
748
|
+
const found = service.state ? (await service.state(this.id)).state : 'none';
|
|
749
|
+
const state = found === 'granted' || found === 'denied' ? found : 'prompt';
|
|
750
|
+
const url = service.shellUrl ? await service.shellUrl(this.id).catch(() => null) : null;
|
|
751
|
+
return url ? { state, url } : { state };
|
|
752
|
+
}
|
|
753
|
+
catch (error) {
|
|
754
|
+
return { error: errorOf(error) };
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
/** The inner shell's own requests: from its origin, never from a page elsewhere. */
|
|
758
|
+
sameOrigin(req) {
|
|
759
|
+
const origin = req.headers.origin;
|
|
760
|
+
if (origin !== undefined)
|
|
761
|
+
return this.shellOrigins.has(origin);
|
|
762
|
+
const site = req.headers['sec-fetch-site'];
|
|
763
|
+
return site === undefined || site === 'same-origin' || site === 'none';
|
|
764
|
+
}
|
|
765
|
+
/** Per-capability config, as `__frame_init.capabilities[cap].config` or a grant carries it. */
|
|
766
|
+
configs(viewer) {
|
|
767
|
+
const out = {};
|
|
768
|
+
for (const cap of this.grantsFor(viewer)) {
|
|
769
|
+
if (cap === 'artifact')
|
|
770
|
+
out[cap] = { id: this.id, key: this.declaration.key, publish: this.publishes };
|
|
771
|
+
else if (cap === 'user') {
|
|
772
|
+
// For the viewer (see runtime.ts): its name only under the `profile` scope, its email only under `email`. The
|
|
773
|
+
// owner holds everything (no `can` list: runtime.ts answers true); anyone else is told what its level allows.
|
|
774
|
+
const { profile, email } = this.scopes;
|
|
775
|
+
const can = viewer.level === 'owner'
|
|
776
|
+
? {}
|
|
777
|
+
: {
|
|
778
|
+
can: [
|
|
779
|
+
...(this.mayDb(viewer, [], 'write') ? ['data.write'] : []),
|
|
780
|
+
...(FrameCore.edits(viewer) && this.publishes ? ['files.write'] : []),
|
|
781
|
+
...(FrameCore.edits(viewer) && this.grants.includes('assets') ? ['assets.write'] : []),
|
|
782
|
+
],
|
|
783
|
+
};
|
|
784
|
+
out[cap] = { id: viewer.id, color: viewer.color, owner: viewer.level === 'owner', canEdit: FrameCore.edits(viewer), profile, email, ...can };
|
|
785
|
+
}
|
|
786
|
+
else if (cap === 'room')
|
|
787
|
+
out[cap] = { limits: ROOM_LIMITS };
|
|
788
|
+
else if (cap === 'sample')
|
|
789
|
+
out[cap] = { images: this.sampleImages };
|
|
790
|
+
else if (cap === 'mcp')
|
|
791
|
+
out[cap] = { servers: declaredMcpServers(this.caps) };
|
|
792
|
+
else if (cap === 'network') {
|
|
793
|
+
const declaration = this.caps.network;
|
|
794
|
+
const optional = isObject(declaration) && declaration.optional === true;
|
|
795
|
+
out[cap] = { origins: optional ? [] : [...(this.env.allowedNetworkOrigins ?? [])] };
|
|
796
|
+
}
|
|
797
|
+
else
|
|
798
|
+
out[cap] = {};
|
|
799
|
+
}
|
|
800
|
+
return out;
|
|
801
|
+
}
|
|
802
|
+
/** What one viewer's inner shell needs to start. */
|
|
803
|
+
session(viewer) {
|
|
804
|
+
this.capabilitiesChanged();
|
|
805
|
+
const flags = {};
|
|
806
|
+
const openArtifacts = isObject(this.config.openArtifacts) ? this.config.openArtifacts : {};
|
|
807
|
+
const configured = (isObject(openArtifacts.flags) ? openArtifacts.flags : isObject(this.config.flags) ? this.config.flags : {});
|
|
808
|
+
for (const k of this.flagKeys)
|
|
809
|
+
flags[k] = configured[k] === true;
|
|
810
|
+
return {
|
|
811
|
+
id: this.id,
|
|
812
|
+
title: this.title,
|
|
813
|
+
key: this.declaration.key,
|
|
814
|
+
ver: this.ver,
|
|
815
|
+
contract: CONTRACT,
|
|
816
|
+
contentOrigin: this.pageOriginFor(viewer),
|
|
817
|
+
shellOrigin: this.shellOrigin,
|
|
818
|
+
...(this.env.origins.outer?.length ? { outerOrigins: [...this.env.origins.outer] } : {}),
|
|
819
|
+
...(this.env.sampleBy === 'shell' ? { sampleBy: 'shell' } : {}),
|
|
820
|
+
brokerGen: this.brokerGen,
|
|
821
|
+
grants: this.grantsFor(viewer),
|
|
822
|
+
stubs: this.stubs,
|
|
823
|
+
configs: this.configs(viewer),
|
|
824
|
+
capabilities: this.declaration.capabilities,
|
|
825
|
+
flags,
|
|
826
|
+
readyTimeoutS: Number(this.declaration.monitoring?.readyTimeoutS) || 60,
|
|
827
|
+
...(this.restricted ? { sandbox: RESTRICTED_FRAME_SANDBOX } : {}),
|
|
828
|
+
me: wireUser(viewer, this.scopes),
|
|
829
|
+
comments: { available: this.grantsFor(viewer).includes('comments'), count: viewer.canComment ? this.comments.openCount() : 0 },
|
|
830
|
+
agent: {
|
|
831
|
+
available: FrameCore.reachesAgent(viewer) && !!this.env.daemon?.available,
|
|
832
|
+
name: this.env.agentName ?? null,
|
|
833
|
+
...(this.env.agentWakesIdle === false ? { wakesIdle: false } : {}),
|
|
834
|
+
},
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* The page's origin for one viewer ({@link FrameEnv.pageOrigin}): an origin alone, and, for a restricted page, never
|
|
839
|
+
* one the inner shell runs on (as the mount checks for the instance's).
|
|
840
|
+
*/
|
|
841
|
+
pageOriginFor(viewer) {
|
|
842
|
+
const raw = this.env.pageOrigin(viewer);
|
|
843
|
+
let origin;
|
|
844
|
+
try {
|
|
845
|
+
origin = new URL(raw).origin;
|
|
846
|
+
}
|
|
847
|
+
catch {
|
|
848
|
+
throw new FrameError('same_origin', `The page origin ${JSON.stringify(raw)} is not one.`, 500);
|
|
849
|
+
}
|
|
850
|
+
if (origin !== raw.replace(/\/$/, ''))
|
|
851
|
+
throw new FrameError('same_origin', `The page origin is an origin alone, not ${JSON.stringify(raw)}.`, 500);
|
|
852
|
+
if (this.restricted && [...this.shellOrigins].some((o) => originOf(o) === origin)) {
|
|
853
|
+
throw new FrameError('same_origin', `A restricted page needs an origin of its own: ${origin} is the inner shell's.`, 500);
|
|
854
|
+
}
|
|
855
|
+
return origin;
|
|
856
|
+
}
|
|
857
|
+
/** Whether `client` is an inner shell's client id. */
|
|
858
|
+
static validClient(client) {
|
|
859
|
+
return CLIENT_ID.test(client);
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Opens one inner shell's event connection (`client`, its own id), for the viewer of `req`: a connection of the same
|
|
863
|
+
* viewer and id is ended first. `out` carries the events; the answer is to be called when the connection closes.
|
|
864
|
+
* Throws `invalid_request` (400) for a client id that is not one ({@link FrameCore.validClient}).
|
|
865
|
+
*/
|
|
866
|
+
connect(req, client, out) {
|
|
867
|
+
if (!FrameCore.validClient(client))
|
|
868
|
+
throw new FrameError('invalid_request', 'Not a client id.', 400);
|
|
869
|
+
const viewer = this.viewerOf(req);
|
|
870
|
+
if (viewer.readOnly)
|
|
871
|
+
throw new FrameError('forbidden', 'Not with this token.', 403);
|
|
872
|
+
const key = `${viewer.id}\u0000${client}`;
|
|
873
|
+
this.clients.get(key)?.end();
|
|
874
|
+
const entry = { id: client, viewer, send: out.send, presence: {}, end: out.end };
|
|
875
|
+
this.clients.set(key, entry);
|
|
876
|
+
out.send({ t: 'hello', ver: this.ver, brokerGen: this.brokerGen, peers: this.peers(), count: viewer.canComment ? this.comments.openCount() : 0 });
|
|
877
|
+
this.broadcast({ t: 'peers', peers: this.peers() });
|
|
878
|
+
return () => {
|
|
879
|
+
if (this.clients.get(key) === entry) {
|
|
880
|
+
this.clients.delete(key);
|
|
881
|
+
this.broadcast({ t: 'peers', peers: this.peers() });
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
/** The open connection of a viewer's client id. */
|
|
886
|
+
clientOf(viewer, client) {
|
|
887
|
+
return this.clients.get(`${viewer.id}\u0000${client}`);
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Who an event names as its sender (`from`): on a site, only a connection of the viewer's own (a page cannot speak
|
|
891
|
+
* as another client); on this computer, where one person is every viewer, the client id as given, as before.
|
|
892
|
+
*/
|
|
893
|
+
senderOf(viewer, client) {
|
|
894
|
+
if (!this.env.withholdIdentity)
|
|
895
|
+
return client || undefined;
|
|
896
|
+
return this.clientOf(viewer, client)?.id;
|
|
897
|
+
}
|
|
898
|
+
/** The connections as peers: `by` only when the declaration has `user`, a name only under its `profile` scope. */
|
|
899
|
+
peers() {
|
|
900
|
+
const by = this.vouches;
|
|
901
|
+
const named = by && this.scopes.profile;
|
|
902
|
+
return [...this.clients.values()].map((c) => ({ peer: c.id, by: by ? c.viewer.id : null, name: named ? c.viewer.name : '', presence: c.presence, kind: 'user' }));
|
|
903
|
+
}
|
|
904
|
+
// ---- capabilities ------------------------------------------------------------------------------------------------
|
|
905
|
+
gate(cap, gen) {
|
|
906
|
+
if (gen !== undefined && gen !== this.brokerGen) {
|
|
907
|
+
if (cap === 'user')
|
|
908
|
+
return { result: null };
|
|
909
|
+
const code = STALE_UNAVAILABLE.has(cap) ? 'unavailable' : 'upstream_error';
|
|
910
|
+
return { error: { code, message: STALE_GEN_MESSAGE, ...(cap === 'mcp' ? { retryable: true } : {}) } };
|
|
911
|
+
}
|
|
912
|
+
return null;
|
|
913
|
+
}
|
|
914
|
+
/** `POST /api/frame/cap`: one call of `viewer`'s, answered as `{result}` or `{error}`. */
|
|
915
|
+
async call(body, viewer) {
|
|
916
|
+
const cap = String(body.cap ?? '') === 'self' ? 'artifact' : String(body.cap ?? '');
|
|
917
|
+
const method = String(body.method ?? '');
|
|
918
|
+
const gen = typeof body.brokerGen === 'number' ? body.brokerGen : undefined;
|
|
919
|
+
const stale = this.gate(cap, gen);
|
|
920
|
+
if (stale)
|
|
921
|
+
return stale;
|
|
922
|
+
const args = Array.isArray(body.args) ? body.args : [body.args];
|
|
923
|
+
try {
|
|
924
|
+
// `shell: true`: the inner shell's own comments UI (its envelope, which a page's relayed call never sets).
|
|
925
|
+
const forShell = body.shell === true;
|
|
926
|
+
return { result: await this.capability(cap, method, isObject(args[0]) ? args[0] : {}, String(body.client ?? ''), viewer, forShell) };
|
|
927
|
+
}
|
|
928
|
+
catch (error) {
|
|
929
|
+
this.log(`${cap}.${method}: ${error?.code ?? 'error'} ${error?.message ?? error}`);
|
|
930
|
+
return { error: errorOf(error) };
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
author(viewer) {
|
|
934
|
+
return { kind: 'user', name: viewer.name, principal: viewer.id };
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* How a thread reaches the caller. The inner shell's own comments UI (`forShell`), and every caller on this computer:
|
|
938
|
+
* as stored. A page on a site: an author's name only under the `profile` scope, its principal only when `user` is
|
|
939
|
+
* declared, and `mine` on the viewer's own messages either way (so a page's moderation still knows them).
|
|
940
|
+
*/
|
|
941
|
+
threadView(viewer, forShell) {
|
|
942
|
+
if (forShell || !this.env.withholdIdentity)
|
|
943
|
+
return pageThread;
|
|
944
|
+
const named = this.scopes.profile;
|
|
945
|
+
const vouched = this.vouches;
|
|
946
|
+
return (t) => {
|
|
947
|
+
const out = pageThread(t);
|
|
948
|
+
out.messages = t.messages.map((m) => {
|
|
949
|
+
const author = m.author;
|
|
950
|
+
const mine = author.kind === 'user' && author.principal === viewer.id;
|
|
951
|
+
const shown = author.kind === 'user'
|
|
952
|
+
? { kind: author.kind, name: named ? author.name : '', ...(vouched && author.principal !== undefined ? { principal: author.principal } : {}), ...(mine ? { mine: true } : {}) }
|
|
953
|
+
: { kind: author.kind, name: author.name };
|
|
954
|
+
return { id: m.id, author: shown, text: m.text, at: m.at, ...(named && m.assignee !== undefined ? { assignee: m.assignee } : {}) };
|
|
955
|
+
});
|
|
956
|
+
return out;
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
async capability(cap, method, a, client, viewer, forShell = false) {
|
|
960
|
+
if (this.stubs[cap])
|
|
961
|
+
throw new FrameError(this.stubs[cap], `${cap} is not available on this computer.`);
|
|
962
|
+
if (!this.grantsFor(viewer).includes(cap))
|
|
963
|
+
throw new FrameError('not_granted', `${cap}: ${UNDECLARED_MESSAGE}`);
|
|
964
|
+
if (cap === 'sample')
|
|
965
|
+
throw new FrameError('invalid_request', `sample calls are streamed: POST ${FRAME_SAMPLE_ROUTES.call}.`);
|
|
966
|
+
if (cap === 'mcp')
|
|
967
|
+
throw new FrameError('invalid_request', `mcp calls go through ${FRAME_MCP_ROUTES.call}.`);
|
|
968
|
+
const path = () => String(a.path ?? '');
|
|
969
|
+
const doc = () => splitPath(path(), 'doc');
|
|
970
|
+
switch (`${cap}.${method}`) {
|
|
971
|
+
case 'db.get': {
|
|
972
|
+
// A document this viewer may not read looks like one that is not there.
|
|
973
|
+
if (!this.mayDb(viewer, doc(), 'read'))
|
|
974
|
+
return { exists: false };
|
|
975
|
+
const data = this.db.readDoc(path());
|
|
976
|
+
return data ? { exists: true, data } : { exists: false };
|
|
977
|
+
}
|
|
978
|
+
case 'db.set':
|
|
979
|
+
this.mustWrite(viewer, doc());
|
|
980
|
+
this.db.set(path(), a.data);
|
|
981
|
+
this.touched([`db/${path()}`], viewer);
|
|
982
|
+
return {};
|
|
983
|
+
case 'db.update':
|
|
984
|
+
this.mustWrite(viewer, doc());
|
|
985
|
+
this.db.update(path(), a.data);
|
|
986
|
+
this.touched([`db/${path()}`], viewer);
|
|
987
|
+
return {};
|
|
988
|
+
case 'db.delete':
|
|
989
|
+
this.mustWrite(viewer, doc());
|
|
990
|
+
this.db.delete(path());
|
|
991
|
+
this.touched([`db/${path()}`], viewer);
|
|
992
|
+
return {};
|
|
993
|
+
case 'db.add': {
|
|
994
|
+
const id = newDocId();
|
|
995
|
+
this.mustWrite(viewer, [...splitPath(path(), 'collection'), id]);
|
|
996
|
+
const out = this.db.add(path(), a.data, id);
|
|
997
|
+
this.touched([`db/${out.path}`], viewer);
|
|
998
|
+
return out;
|
|
999
|
+
}
|
|
1000
|
+
case 'db.query': {
|
|
1001
|
+
const coll = splitPath(path(), 'collection');
|
|
1002
|
+
const spec = checkSpec(a.spec ?? {});
|
|
1003
|
+
// Only the rows this viewer may read, and the limit counted among those.
|
|
1004
|
+
const docs = this.db.query(path(), { ...(isObject(a.spec) ? a.spec : {}), limit: null }).filter((d) => this.mayDb(viewer, [...coll, d.id], 'read'));
|
|
1005
|
+
return { docs: spec.limit ? docs.slice(0, spec.limit) : docs };
|
|
1006
|
+
}
|
|
1007
|
+
case 'db.acquire': {
|
|
1008
|
+
// The lease is the viewer's: the page's holder string tells only its own tabs apart, under the viewer's id.
|
|
1009
|
+
this.mustWrite(viewer, doc());
|
|
1010
|
+
const options = isObject(a.options) ? a.options : {};
|
|
1011
|
+
const holder = options.holder;
|
|
1012
|
+
if (typeof holder !== 'string' || !holder || holder.length > 128)
|
|
1013
|
+
throw new FrameError('invalid_argument', 'acquire() needs a holder.');
|
|
1014
|
+
const out = this.db.acquire(path(), { ...options, holder: leaseHolder(viewer, holder) });
|
|
1015
|
+
// Busy: when it frees up; who holds it only when it is the viewer itself (another tab: always, on this computer).
|
|
1016
|
+
if (out.acquired)
|
|
1017
|
+
return { ...out, holder };
|
|
1018
|
+
const mine = out.holder?.startsWith(leaseHolder(viewer, '')) ? out.holder.slice(leaseHolder(viewer, '').length) : undefined;
|
|
1019
|
+
return { acquired: false, ...(mine !== undefined ? { holder: mine } : {}), ...(out.expiresAt !== undefined ? { expiresAt: out.expiresAt } : {}) };
|
|
1020
|
+
}
|
|
1021
|
+
case 'db.release':
|
|
1022
|
+
this.mustWrite(viewer, doc());
|
|
1023
|
+
return this.db.release(path(), typeof a.holder === 'string' ? leaseHolder(viewer, a.holder) : null);
|
|
1024
|
+
case 'artifact.publish':
|
|
1025
|
+
this.mustPublish(viewer);
|
|
1026
|
+
if (typeof a.html === 'string') {
|
|
1027
|
+
if (!this.pageMode)
|
|
1028
|
+
throw new FrameError('read_only_path', "index.html belongs to this artifact's type; publish files instead.", 403);
|
|
1029
|
+
return this.publishPage(a.html, typeof a.ver === 'string' ? a.ver : undefined, viewer);
|
|
1030
|
+
}
|
|
1031
|
+
return this.publish(isObject(a.files) ? a.files : {}, client, viewer);
|
|
1032
|
+
case 'artifact.sync':
|
|
1033
|
+
this.mustPublish(viewer);
|
|
1034
|
+
return { version: this.ver, files: this.files.manifest().files };
|
|
1035
|
+
case 'artifact.metadata': {
|
|
1036
|
+
const refs = Array.isArray(a.refs) ? a.refs : [];
|
|
1037
|
+
const out = {};
|
|
1038
|
+
for (const ref of refs.slice(0, 100)) {
|
|
1039
|
+
if (ref === this.id || ref === 'self')
|
|
1040
|
+
out[String(ref)] = { id: this.id, title: this.title, type: this.declaration.key };
|
|
1041
|
+
}
|
|
1042
|
+
return out;
|
|
1043
|
+
}
|
|
1044
|
+
case 'artifact.search':
|
|
1045
|
+
return { results: [] };
|
|
1046
|
+
case 'artifact.edit':
|
|
1047
|
+
this.mustPublish(viewer);
|
|
1048
|
+
throw new FrameError('capability_disabled', 'edit() is for live documents; publish the files instead.');
|
|
1049
|
+
// Below admin (a viewer the declaration lets upload): only the assets it uploaded itself.
|
|
1050
|
+
case 'assets.list':
|
|
1051
|
+
return FrameCore.edits(viewer) ? this.blobs.list() : this.blobs.list((m) => this.uploadedBy(m, viewer));
|
|
1052
|
+
case 'assets.delete': {
|
|
1053
|
+
// An editor deletes the asset; anyone else, only its own claim (the bytes stay while another claims them).
|
|
1054
|
+
const out = this.blobs.delete(a.ref, FrameCore.edits(viewer) ? undefined : viewer.id);
|
|
1055
|
+
if (out.deleted)
|
|
1056
|
+
this.touched(['_blobs'], viewer);
|
|
1057
|
+
return out;
|
|
1058
|
+
}
|
|
1059
|
+
case 'user.me':
|
|
1060
|
+
case 'user.profile': {
|
|
1061
|
+
const { profile } = this.scopes;
|
|
1062
|
+
return { id: viewer.id, name: profile ? viewer.name : '', avatarUrl: profile ? viewer.avatarUrl : null, color: viewer.color };
|
|
1063
|
+
}
|
|
1064
|
+
case 'user.email':
|
|
1065
|
+
return this.scopes.email ? viewer.email : null;
|
|
1066
|
+
case 'user.profiles': {
|
|
1067
|
+
const ids = (Array.isArray(a.ids) ? a.ids : []).filter((i) => typeof i === 'string').slice(0, 100);
|
|
1068
|
+
const people = await this.reachable(viewer);
|
|
1069
|
+
return Object.fromEntries(ids.flatMap((i) => (people.has(i) ? [[i, this.profileOf(people.get(i), viewer)]] : [])));
|
|
1070
|
+
}
|
|
1071
|
+
case 'user.access': {
|
|
1072
|
+
// One's own level; anyone else's only for an editor, and only of people who can reach the artifact.
|
|
1073
|
+
const ids = (Array.isArray(a.ids) ? a.ids : []).slice(0, 100);
|
|
1074
|
+
const people = FrameCore.edits(viewer) ? await this.reachable(viewer) : new Map();
|
|
1075
|
+
return Object.fromEntries(ids.map((i) => [String(i), i === viewer.id ? viewer.level : (people.get(String(i))?.level ?? null)]));
|
|
1076
|
+
}
|
|
1077
|
+
case 'user.search': {
|
|
1078
|
+
// A site: under `profile`, for a viewer who edits or comments; names, and emails only under `email`.
|
|
1079
|
+
// This computer (identity not withheld): no one to search for, as before.
|
|
1080
|
+
if (!this.env.withholdIdentity)
|
|
1081
|
+
return [];
|
|
1082
|
+
const { profile, email } = userScopes(this.caps.user);
|
|
1083
|
+
if (!profile || !(FrameCore.edits(viewer) || viewer.canComment))
|
|
1084
|
+
return [];
|
|
1085
|
+
const q = String(a.q ?? a.query ?? '').trim().toLowerCase();
|
|
1086
|
+
const people = await this.reachable(viewer);
|
|
1087
|
+
const hits = [...people.values()].filter((p) => q === '' ? p.id === viewer.id : !!p.name && (p.name.toLowerCase().includes(q) || (email && !!p.email && p.email.toLowerCase().includes(q))));
|
|
1088
|
+
return hits
|
|
1089
|
+
.filter((p) => !!p.name)
|
|
1090
|
+
.slice(0, SEARCH_MAX)
|
|
1091
|
+
.map((p) => this.profileOf(p, viewer));
|
|
1092
|
+
}
|
|
1093
|
+
case 'permissions.state':
|
|
1094
|
+
case 'permissions.request': {
|
|
1095
|
+
// Answered from this viewer's grants (the page usually answers these itself; this is for a call that comes here).
|
|
1096
|
+
const mine = this.grantsFor(viewer);
|
|
1097
|
+
const state = (n) => (mine.includes(String(n) === 'self' ? 'artifact' : String(n)) ? 'granted' : 'unavailable');
|
|
1098
|
+
const named = method === 'state' ? (a.name !== undefined ? [a.name] : null) : Array.isArray(a.names) ? a.names : a.names !== undefined ? [a.names] : null;
|
|
1099
|
+
if (method === 'state' && named)
|
|
1100
|
+
return state(named[0]);
|
|
1101
|
+
return Object.fromEntries((named ?? mine).map((n) => [String(n), state(n)]));
|
|
1102
|
+
}
|
|
1103
|
+
case 'permissions.manage':
|
|
1104
|
+
throw new FrameError('unavailable', 'There is no permissions panel here.');
|
|
1105
|
+
case 'downloads.save':
|
|
1106
|
+
// Saved by the page itself; nothing on this side saves for it.
|
|
1107
|
+
throw new FrameError('unavailable', 'Downloads are saved by the page.');
|
|
1108
|
+
case 'comments.list':
|
|
1109
|
+
return { threads: this.comments.threads({ all: a.all !== false }).map(this.threadView(viewer, forShell)) };
|
|
1110
|
+
case 'comments.create': {
|
|
1111
|
+
const thread = this.comments.create({
|
|
1112
|
+
anchor: a.anchor,
|
|
1113
|
+
label: a.label,
|
|
1114
|
+
detail: a.detail,
|
|
1115
|
+
location: { custom: a.anchor ?? null, ...(typeof a.file === 'string' ? { file: a.file } : {}) },
|
|
1116
|
+
text: a.text,
|
|
1117
|
+
assignee: a.assignee,
|
|
1118
|
+
author: this.author(viewer),
|
|
1119
|
+
});
|
|
1120
|
+
this.commentsChanged();
|
|
1121
|
+
return { threadId: thread.id, commentId: thread.messages[0].id, thread: this.threadView(viewer, forShell)(thread) };
|
|
1122
|
+
}
|
|
1123
|
+
case 'comments.reply': {
|
|
1124
|
+
const { thread, message } = this.comments.addMessage(a.threadId, this.author(viewer), a.text, { assignee: a.assignee });
|
|
1125
|
+
this.commentsChanged();
|
|
1126
|
+
return { threadId: thread.id, commentId: message.id, thread: this.threadView(viewer, forShell)(thread) };
|
|
1127
|
+
}
|
|
1128
|
+
case 'comments.resolve': {
|
|
1129
|
+
this.mustModerate(viewer, a.threadId);
|
|
1130
|
+
const thread = this.comments.setResolved(a.threadId, a.resolved !== false, this.author(viewer));
|
|
1131
|
+
this.commentsChanged();
|
|
1132
|
+
return { thread: this.threadView(viewer, forShell)(thread) };
|
|
1133
|
+
}
|
|
1134
|
+
case 'comments.move': {
|
|
1135
|
+
this.mustModerate(viewer, a.threadId);
|
|
1136
|
+
const have = this.comments.load().threads.find((t) => t.id === a.threadId);
|
|
1137
|
+
const thread = this.comments.move(a.threadId, a.anchor, { ...(have?.location ?? {}), custom: a.anchor ?? null });
|
|
1138
|
+
this.commentsChanged();
|
|
1139
|
+
return { thread: this.threadView(viewer, forShell)(thread) };
|
|
1140
|
+
}
|
|
1141
|
+
case 'comments.delete': {
|
|
1142
|
+
this.mustModerate(viewer, a.threadId, a.commentId);
|
|
1143
|
+
const out = this.comments.remove(a.threadId, a.commentId);
|
|
1144
|
+
this.commentsChanged();
|
|
1145
|
+
return out;
|
|
1146
|
+
}
|
|
1147
|
+
case 'comments.sendToAgent':
|
|
1148
|
+
if (!FrameCore.reachesAgent(viewer))
|
|
1149
|
+
throw new FrameError('forbidden', 'Only people who can edit this artifact send comments to its agent.');
|
|
1150
|
+
return this.sendToAgent(a, viewer, forShell);
|
|
1151
|
+
case 'comments.canSendToAgent':
|
|
1152
|
+
return FrameCore.reachesAgent(viewer) ? this.canSendToAgent() : 'writers_only';
|
|
1153
|
+
case 'room.emit': {
|
|
1154
|
+
if (JSON.stringify(a.data ?? null).length > ROOM_LIMITS.maxBytes)
|
|
1155
|
+
throw new FrameError('too_large', `A room message is at most ${ROOM_LIMITS.maxBytes} bytes.`);
|
|
1156
|
+
const topic = String(a.topic ?? '');
|
|
1157
|
+
// A named room's topic arrives as `name/topic`: the declared level is the topic's own.
|
|
1158
|
+
if (!atLeast(viewer.level, topicLevel(this.caps.room, topic.slice(topic.lastIndexOf('/') + 1)))) {
|
|
1159
|
+
throw new FrameError('not_permitted', `This viewer may not send on ${JSON.stringify(topic)}.`);
|
|
1160
|
+
}
|
|
1161
|
+
// On a site the sender is a connection the viewer opened; a client id that is not one of its own sends nothing.
|
|
1162
|
+
const from = this.senderOf(viewer, client);
|
|
1163
|
+
if (from === undefined && this.env.withholdIdentity)
|
|
1164
|
+
return {};
|
|
1165
|
+
this.broadcast({ t: 'room', topic, data: a.data ?? null, from: from ?? client, by: this.vouches ? viewer.id : null });
|
|
1166
|
+
return {};
|
|
1167
|
+
}
|
|
1168
|
+
case 'room.presence': {
|
|
1169
|
+
const c = this.clientOf(viewer, client);
|
|
1170
|
+
if (c)
|
|
1171
|
+
c.presence = { ...c.presence, ...(isObject(a.patch) ? a.patch : {}) };
|
|
1172
|
+
this.broadcast({ t: 'peers', peers: this.peers() });
|
|
1173
|
+
return {};
|
|
1174
|
+
}
|
|
1175
|
+
case 'room.peers':
|
|
1176
|
+
return this.peers();
|
|
1177
|
+
case 'room.sendToAgentSession': {
|
|
1178
|
+
if (!FrameCore.reachesAgent(viewer))
|
|
1179
|
+
throw new FrameError('not_permitted', "Only people who can edit this artifact reach its owner's agent.");
|
|
1180
|
+
const text = typeof a.data === 'string' ? a.data : JSON.stringify(a.data ?? null);
|
|
1181
|
+
if (Buffer.byteLength(text) > ROOM_LIMITS.maxBytes)
|
|
1182
|
+
throw new FrameError('too_large', `sendToAgentSession() takes at most ${ROOM_LIMITS.maxBytes} bytes.`);
|
|
1183
|
+
const out = await this.env.agentHook.request({ label: this.declaration.key ?? 'page', text });
|
|
1184
|
+
return { to: out?.via ?? 'agent' };
|
|
1185
|
+
}
|
|
1186
|
+
case 'room.canSendToAgentSession':
|
|
1187
|
+
return FrameCore.reachesAgent(viewer) && (await this.canSendToAgent()) === 'available';
|
|
1188
|
+
default:
|
|
1189
|
+
throw new FrameError('invalid_request', `${cap}.${method} is not supported here.`);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
/** The page's publish: its wire form (`{text}` | `{b64}` | null | `{delete:true}`, each with an optional ifMatch). */
|
|
1193
|
+
publish(files, client, viewer) {
|
|
1194
|
+
const plan = {};
|
|
1195
|
+
for (const [p, raw] of Object.entries(files)) {
|
|
1196
|
+
const spec = isObject(raw) ? raw : null;
|
|
1197
|
+
const guard = spec && 'ifMatch' in spec ? { ifMatch: spec.ifMatch } : {};
|
|
1198
|
+
if (raw === null || spec?.delete === true) {
|
|
1199
|
+
plan[p] = { delete: true, ...guard };
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
let data;
|
|
1203
|
+
if (typeof spec?.b64 === 'string')
|
|
1204
|
+
data = Buffer.from(spec.b64, 'base64');
|
|
1205
|
+
else if (typeof spec?.text === 'string')
|
|
1206
|
+
data = Buffer.from(spec.text, 'utf8');
|
|
1207
|
+
else
|
|
1208
|
+
throw new FrameError('invalid_content', `${p}: no content.`);
|
|
1209
|
+
plan[p] = { data, ...(typeof spec.contentType === 'string' ? { contentType: spec.contentType } : {}), ...guard };
|
|
1210
|
+
}
|
|
1211
|
+
const out = this.files.publish(plan);
|
|
1212
|
+
if (out.version !== this.ver) {
|
|
1213
|
+
// The page's own write: no rewiring (its calls stay valid); other shells reload.
|
|
1214
|
+
this.ver = out.version;
|
|
1215
|
+
// `from` (the inner shell that published keeps its page): on a site, only a connection of this viewer's own.
|
|
1216
|
+
const own = this.senderOf(viewer, client);
|
|
1217
|
+
this.broadcast({ t: 'files', ver: out.version, paths: out.changed.map((c) => c.path), ...(own !== undefined ? { from: own } : {}) });
|
|
1218
|
+
}
|
|
1219
|
+
if (out.changed.length)
|
|
1220
|
+
this.touched(out.changed.map((c) => c.path), viewer);
|
|
1221
|
+
return out;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Page mode's `publish(html)`: the whole document replaces the root index.html, only while the files are still the
|
|
1225
|
+
* version this view was loaded from (`ver`; else `conflict`, nothing written). Every open view reloads, this one too.
|
|
1226
|
+
*/
|
|
1227
|
+
publishPage(html, ver, viewer) {
|
|
1228
|
+
if (ver !== undefined && ver !== this.files.manifest().ver) {
|
|
1229
|
+
throw new FrameError('conflict', 'The page changed since this view loaded it: nothing was written.', 409, { live: this.files.manifest().ver });
|
|
1230
|
+
}
|
|
1231
|
+
const out = this.files.publish({ 'index.html': { data: Buffer.from(withoutFrameRuntime(html), 'utf8'), contentType: 'text/html' } });
|
|
1232
|
+
if (out.version !== this.ver) {
|
|
1233
|
+
this.ver = out.version;
|
|
1234
|
+
this.rewire('files');
|
|
1235
|
+
this.broadcast({ t: 'files', ver: out.version, paths: ['index.html'] });
|
|
1236
|
+
}
|
|
1237
|
+
if (out.changed.length)
|
|
1238
|
+
this.touched(['index.html'], viewer);
|
|
1239
|
+
this.pageTitle();
|
|
1240
|
+
return out;
|
|
1241
|
+
}
|
|
1242
|
+
/** The comments changed: only viewers who may comment hear of it. */
|
|
1243
|
+
commentsChanged() {
|
|
1244
|
+
const count = this.comments.openCount();
|
|
1245
|
+
this.broadcast((c) => (c.viewer.canComment ? { t: 'comments', count } : null));
|
|
1246
|
+
}
|
|
1247
|
+
/** Resolving, moving or deleting a thread (or one message of it): its starter (that message's author) or an editor. */
|
|
1248
|
+
mustModerate(viewer, threadId, commentId) {
|
|
1249
|
+
if (FrameCore.edits(viewer))
|
|
1250
|
+
return;
|
|
1251
|
+
const thread = this.comments.load().threads.find((t) => t.id === threadId);
|
|
1252
|
+
if (!thread)
|
|
1253
|
+
return; // the store answers not_found
|
|
1254
|
+
const message = commentId === undefined || commentId === null ? thread.messages[0] : thread.messages.find((m) => m.id === commentId);
|
|
1255
|
+
const by = message?.author?.principal;
|
|
1256
|
+
if (by !== viewer.id)
|
|
1257
|
+
throw new FrameError('forbidden', 'Only who started this thread, or an editor, may do that.');
|
|
1258
|
+
}
|
|
1259
|
+
/** Whether a viewer uploaded an asset (`uploader`): one with none is the owner's. */
|
|
1260
|
+
uploadedBy(meta, viewer) {
|
|
1261
|
+
const claims = blobClaims(meta);
|
|
1262
|
+
return claims.length === 0 ? viewer.level === 'owner' : claims.includes(viewer.id);
|
|
1263
|
+
}
|
|
1264
|
+
/** The people `user` answers about: those who can reach the artifact, and the viewer. */
|
|
1265
|
+
async reachable(viewer) {
|
|
1266
|
+
const out = new Map();
|
|
1267
|
+
for (const p of await this.env.people())
|
|
1268
|
+
out.set(p.id, p);
|
|
1269
|
+
out.set(viewer.id, { id: viewer.id, name: viewer.name, email: viewer.email, avatarUrl: viewer.avatarUrl, color: viewer.color, level: viewer.level });
|
|
1270
|
+
return out;
|
|
1271
|
+
}
|
|
1272
|
+
/** A person as `user.profiles` / `user.search` give them: names under `profile`, emails under `email`. */
|
|
1273
|
+
profileOf(p, viewer) {
|
|
1274
|
+
const { profile, email } = this.scopes;
|
|
1275
|
+
return {
|
|
1276
|
+
id: p.id,
|
|
1277
|
+
name: profile ? p.name : '',
|
|
1278
|
+
avatarUrl: profile ? p.avatarUrl : null,
|
|
1279
|
+
color: p.color ?? colorOf(p.id),
|
|
1280
|
+
email: email ? p.email : null,
|
|
1281
|
+
isMe: p.id === viewer.id,
|
|
1282
|
+
guest: p.id === viewer.id ? viewer.guest : false,
|
|
1283
|
+
roles: null,
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
async presence() {
|
|
1287
|
+
const daemon = this.env.daemon;
|
|
1288
|
+
if (!daemon?.available)
|
|
1289
|
+
return null;
|
|
1290
|
+
if (this.presenceCache && Date.now() - this.presenceCache.at < 3000)
|
|
1291
|
+
return this.presenceCache.value;
|
|
1292
|
+
let value = null;
|
|
1293
|
+
try {
|
|
1294
|
+
value = await daemon.presence(this.id);
|
|
1295
|
+
}
|
|
1296
|
+
catch {
|
|
1297
|
+
value = null;
|
|
1298
|
+
}
|
|
1299
|
+
this.presenceCache = { at: Date.now(), value };
|
|
1300
|
+
return value;
|
|
1301
|
+
}
|
|
1302
|
+
async canSendToAgent() {
|
|
1303
|
+
if (!this.env.daemon?.available)
|
|
1304
|
+
return 'off';
|
|
1305
|
+
const p = await this.presence();
|
|
1306
|
+
if (!p)
|
|
1307
|
+
return 'no_session';
|
|
1308
|
+
return p.canSend === false ? 'no_session' : 'available';
|
|
1309
|
+
}
|
|
1310
|
+
async sendToAgent(a, viewer, forShell = false) {
|
|
1311
|
+
let threadId = typeof a.threadId === 'string' ? a.threadId : '';
|
|
1312
|
+
if (!threadId) {
|
|
1313
|
+
threadId = this.comments.create({ anchor: a.anchor, label: a.label, detail: a.detail, location: { custom: a.anchor ?? null }, text: a.text, author: this.author(viewer) }).id;
|
|
1314
|
+
}
|
|
1315
|
+
else if (typeof a.text === 'string' && a.text.trim()) {
|
|
1316
|
+
this.comments.addMessage(threadId, this.author(viewer), a.text);
|
|
1317
|
+
}
|
|
1318
|
+
this.comments.markSent(threadId);
|
|
1319
|
+
this.commentsChanged();
|
|
1320
|
+
const thread = this.comments.load().threads.find((t) => t.id === threadId);
|
|
1321
|
+
let out;
|
|
1322
|
+
try {
|
|
1323
|
+
const view = agentView(thread);
|
|
1324
|
+
const note = a.handoffNote;
|
|
1325
|
+
if (typeof note === 'string' && note.length <= 2000 && note.trim() && Buffer.byteLength(note) <= 2000)
|
|
1326
|
+
view.pageContext = note;
|
|
1327
|
+
out = await this.env.agentHook.thread(view);
|
|
1328
|
+
}
|
|
1329
|
+
catch (error) {
|
|
1330
|
+
throw new FrameError('agent_unavailable', error?.message ?? 'The agent could not be reached.', 409);
|
|
1331
|
+
}
|
|
1332
|
+
const marked = this.comments.markDelivered(threadId, out?.via === 'wait' ? 'wait' : 'hook');
|
|
1333
|
+
this.commentsChanged();
|
|
1334
|
+
return { threadId, status: out?.status ?? 'delivered', thread: this.threadView(viewer, forShell)(marked) };
|
|
1335
|
+
}
|
|
1336
|
+
async proposeTitle({ title, ifUnnamed }, viewer) {
|
|
1337
|
+
// The title is the artifact's: an editor's to change.
|
|
1338
|
+
if (!FrameCore.edits(viewer))
|
|
1339
|
+
return { applied: false };
|
|
1340
|
+
if (typeof title !== 'string' || !title.trim())
|
|
1341
|
+
return { applied: false };
|
|
1342
|
+
const clean = title.trim().slice(0, 200);
|
|
1343
|
+
if (ifUnnamed && this.title && !/^untitled\b/i.test(this.title))
|
|
1344
|
+
return { applied: false };
|
|
1345
|
+
const daemon = this.env.daemon;
|
|
1346
|
+
if (!daemon?.available)
|
|
1347
|
+
return { applied: false };
|
|
1348
|
+
try {
|
|
1349
|
+
await daemon.touch(this.id, { author: touchAuthor(viewer), paths: [], title: clean });
|
|
1350
|
+
this.title = clean;
|
|
1351
|
+
return { applied: true, title: clean };
|
|
1352
|
+
}
|
|
1353
|
+
catch {
|
|
1354
|
+
return { applied: false };
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
async askAgent({ text }, viewer) {
|
|
1358
|
+
if (!FrameCore.reachesAgent(viewer))
|
|
1359
|
+
throw new FrameError('forbidden', "Only people who can edit this artifact reach its owner's agent.", 403);
|
|
1360
|
+
const out = await this.env.agentHook.request({ label: this.declaration.key ?? 'page', text: String(text ?? '').slice(0, 20_000) });
|
|
1361
|
+
return { status: out?.status ?? 'delivered', via: out?.via ?? null };
|
|
1362
|
+
}
|
|
1363
|
+
async activity(viewer) {
|
|
1364
|
+
if (!FrameCore.reachesAgent(viewer))
|
|
1365
|
+
return { working: false, available: false };
|
|
1366
|
+
const p = await this.presence();
|
|
1367
|
+
return { working: !!p?.busy, available: !!p };
|
|
1368
|
+
}
|
|
1369
|
+
// ---- the page's own origin (Site.content) ------------------------------------------------------------------------
|
|
1370
|
+
/** One request on the page's own origin; every answer carries the page's CSP, when there is one. */
|
|
1371
|
+
async contentRequest(req) {
|
|
1372
|
+
let reader = null;
|
|
1373
|
+
try {
|
|
1374
|
+
reader = this.env.reader(req);
|
|
1375
|
+
}
|
|
1376
|
+
catch {
|
|
1377
|
+
// a token the environment cannot place: refused below
|
|
1378
|
+
}
|
|
1379
|
+
const reply = reader ? this.contentReply(req, { ...reader, readOnly: true }) : deny(403, 'Not with this address.');
|
|
1380
|
+
reply.headers['Referrer-Policy'] = 'no-referrer';
|
|
1381
|
+
if (reply.status >= 400 && !String(req.url).endsWith('/_files.json'))
|
|
1382
|
+
this.log(`content ${req.method} ${req.url} → ${reply.status}`);
|
|
1383
|
+
if (this.contentSecurityPolicy)
|
|
1384
|
+
reply.headers = { 'Content-Security-Policy': this.contentSecurityPolicy, ...reply.headers };
|
|
1385
|
+
return reply;
|
|
1386
|
+
}
|
|
1387
|
+
/** The page origin's answer, for its reader (read-only, whatever the environment said). */
|
|
1388
|
+
contentReply(req, reader) {
|
|
1389
|
+
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
1390
|
+
return deny(405, 'Method not allowed');
|
|
1391
|
+
const url = new URL(req.url || '/', 'http://local');
|
|
1392
|
+
const p = url.pathname;
|
|
1393
|
+
if (p === '/' || p === '/index.html')
|
|
1394
|
+
return { status: 302, headers: { Location: `/_f/${this.ver}/${url.search}`, 'Cache-Control': 'no-store' }, body: null };
|
|
1395
|
+
if (p === RUNTIME_SRC)
|
|
1396
|
+
return this.sendScript(req, 'runtime');
|
|
1397
|
+
if (p === SAMPLE_SRC)
|
|
1398
|
+
return this.sendScript(req, 'sample');
|
|
1399
|
+
if (p === MCP_SRC)
|
|
1400
|
+
return this.sendScript(req, 'mcp');
|
|
1401
|
+
if (p.startsWith('/_/openartifacts:'))
|
|
1402
|
+
return this.capabilityModule(req, p);
|
|
1403
|
+
// A page written before the rename imports `/_/openartifact:<name>`: the same module.
|
|
1404
|
+
if (p.startsWith(LEGACY_CAPABILITY_IMPORT_PREFIX))
|
|
1405
|
+
return this.capabilityModule(req, `/_/openartifacts:${p.slice(LEGACY_CAPABILITY_IMPORT_PREFIX.length)}`, true);
|
|
1406
|
+
const blob = /^\/_blob\/([0-9a-f]{32})$/.exec(p);
|
|
1407
|
+
if (blob)
|
|
1408
|
+
return this.sendBlob(req, blob[1]);
|
|
1409
|
+
const m = /^\/_f\/([A-Za-z0-9_-]{1,128})\/(.*)$/.exec(p);
|
|
1410
|
+
if (!m)
|
|
1411
|
+
return deny(404, 'Not found');
|
|
1412
|
+
let rel;
|
|
1413
|
+
try {
|
|
1414
|
+
rel = decodeURIComponent(m[2]);
|
|
1415
|
+
}
|
|
1416
|
+
catch {
|
|
1417
|
+
return deny(400, 'Bad path');
|
|
1418
|
+
}
|
|
1419
|
+
if (rel === '' || rel === 'index.html') {
|
|
1420
|
+
if (!this.loadedByShell(req))
|
|
1421
|
+
return deny(403, 'This page opens inside its Open Artifacts page.');
|
|
1422
|
+
return this.sendIndex(req, reader);
|
|
1423
|
+
}
|
|
1424
|
+
if (rel === '_files.json') {
|
|
1425
|
+
const manifest = this.files.manifest();
|
|
1426
|
+
// An artifact with no files yet has no listing: the original pages read that 404 as "start empty".
|
|
1427
|
+
if (Object.keys(manifest.files).length === 0)
|
|
1428
|
+
return json(404, { code: 'empty', message: 'No files yet.' }, req.method === 'HEAD');
|
|
1429
|
+
return json(200, { ver: manifest.ver, files: manifest.files }, req.method === 'HEAD');
|
|
1430
|
+
}
|
|
1431
|
+
const clean = cleanPath(rel);
|
|
1432
|
+
if (!clean || clean.split('/').some((s) => s.startsWith('.')))
|
|
1433
|
+
return deny(404, 'Not found');
|
|
1434
|
+
if (clean.startsWith('artifact-type/')) {
|
|
1435
|
+
const file = this.env.type.file(clean);
|
|
1436
|
+
if (!file)
|
|
1437
|
+
return deny(404, 'Not found');
|
|
1438
|
+
return sendFile(req, file, contentTypeOf(clean), true);
|
|
1439
|
+
}
|
|
1440
|
+
if (typePath(clean))
|
|
1441
|
+
return deny(404, 'Not found');
|
|
1442
|
+
const file = this.files.resolve(clean);
|
|
1443
|
+
if (!file)
|
|
1444
|
+
return deny(404, 'Not found');
|
|
1445
|
+
return this.sendStored(req, file, contentTypeOf(file));
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Who may load the page: the inner shell's frame (it sends its origin as the Referer), the page itself, a visit
|
|
1449
|
+
* typed into the address bar, or a client with no fetch metadata (a script, an old browser). A frame put up by
|
|
1450
|
+
* anyone else is refused here, not by CSP `frame-ancestors`: that directive checks every ancestor, and the app
|
|
1451
|
+
* around the Open Artifacts Shell may be a `file://` page or a scheme of its own (`app://`), which no source list
|
|
1452
|
+
* written on this computer can name.
|
|
1453
|
+
*/
|
|
1454
|
+
loadedByShell(req) {
|
|
1455
|
+
const dest = req.headers['sec-fetch-dest'];
|
|
1456
|
+
const site = req.headers['sec-fetch-site'];
|
|
1457
|
+
if (dest === 'document' || site === 'same-origin')
|
|
1458
|
+
return true;
|
|
1459
|
+
const referer = req.headers.referer;
|
|
1460
|
+
if (!referer)
|
|
1461
|
+
return dest === undefined && site === undefined;
|
|
1462
|
+
try {
|
|
1463
|
+
return this.shellOrigins.has(new URL(referer).origin);
|
|
1464
|
+
}
|
|
1465
|
+
catch {
|
|
1466
|
+
return false;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
/** The type's index.html (page mode: the artifact's, or an empty page) with the Frame Runtime first in its <head>. */
|
|
1470
|
+
sendIndex(req, reader) {
|
|
1471
|
+
let html;
|
|
1472
|
+
if (this.pageMode) {
|
|
1473
|
+
try {
|
|
1474
|
+
html = readFileSync(join(this.root, 'index.html'), 'utf8');
|
|
1475
|
+
}
|
|
1476
|
+
catch {
|
|
1477
|
+
html = EMPTY_PAGE;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
else {
|
|
1481
|
+
const own = this.env.type.indexHtml();
|
|
1482
|
+
if (own === null)
|
|
1483
|
+
return deny(500, 'The type has no index.html.');
|
|
1484
|
+
html = own;
|
|
1485
|
+
}
|
|
1486
|
+
// The page's origin knows its reader only by the read-only token: what it is given is that viewer's grants.
|
|
1487
|
+
const boot = {
|
|
1488
|
+
shellOrigin: this.shellOrigin,
|
|
1489
|
+
id: this.id,
|
|
1490
|
+
key: this.declaration.key,
|
|
1491
|
+
grants: this.grantsFor(reader),
|
|
1492
|
+
stubs: Object.keys(this.stubs),
|
|
1493
|
+
contract: CONTRACT,
|
|
1494
|
+
...(this.env.debug() ? { debug: true } : {}),
|
|
1495
|
+
};
|
|
1496
|
+
const safe = (v) => JSON.stringify(v).replace(/[<\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
1497
|
+
const inject = `<script>window.__FRAME_PREAMBLE=${safe({ origins: [this.shellOrigin] })};window.__OPEN_ARTIFACTS_FRAME=${safe(boot)};</script>` +
|
|
1498
|
+
`<script src="${RUNTIME_SRC}"></script>`;
|
|
1499
|
+
const head = /<head\b[^>]*>/i.exec(html);
|
|
1500
|
+
const out = head ? html.slice(0, head.index + head[0].length) + inject + html.slice(head.index + head[0].length) : inject + html;
|
|
1501
|
+
const body = Buffer.from(out, 'utf8');
|
|
1502
|
+
return {
|
|
1503
|
+
status: 200,
|
|
1504
|
+
headers: {
|
|
1505
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1506
|
+
'Content-Length': body.length,
|
|
1507
|
+
'Cache-Control': 'no-store',
|
|
1508
|
+
// No frame-ancestors: who framed it is checked when it is asked for (loadedByShell).
|
|
1509
|
+
'X-Content-Type-Options': 'nosniff',
|
|
1510
|
+
'Referrer-Policy': 'no-referrer',
|
|
1511
|
+
},
|
|
1512
|
+
body: req.method === 'HEAD' ? null : body,
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
sendClientFile(req, name) {
|
|
1516
|
+
if (name === 'shell.js')
|
|
1517
|
+
return this.sendScript(req, 'shell');
|
|
1518
|
+
if (name === 'comments.js' || name === 'comments.css') {
|
|
1519
|
+
return sendFile(req, this.env.client.file(name), name.endsWith('.js') ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8');
|
|
1520
|
+
}
|
|
1521
|
+
if (name === 'shell.html') {
|
|
1522
|
+
return sendFile(req, this.env.client.file(name), 'text/html; charset=utf-8', false, {
|
|
1523
|
+
'Content-Security-Policy': [
|
|
1524
|
+
"default-src 'none'",
|
|
1525
|
+
"script-src 'self'",
|
|
1526
|
+
"style-src 'self' 'unsafe-inline'",
|
|
1527
|
+
"img-src 'self' data: blob:",
|
|
1528
|
+
// The comment views' font (Inter) is inlined as data: URLs in comments.css.
|
|
1529
|
+
"font-src 'self' data:",
|
|
1530
|
+
["connect-src 'self'", ...this.env.origins.connectSrc].join(' '),
|
|
1531
|
+
// CSP host sources cannot spell an id with '_', so: any artifact origin on this server's port.
|
|
1532
|
+
`frame-src ${this.env.origins.frameSrc}`,
|
|
1533
|
+
"base-uri 'none'",
|
|
1534
|
+
"form-action 'none'",
|
|
1535
|
+
].join('; '),
|
|
1536
|
+
// The page frame sets its own `referrerpolicy="origin"`, so the page's origin still sees who framed it.
|
|
1537
|
+
'Referrer-Policy': 'no-referrer',
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
return sendFile(req, this.env.client.file(name), 'text/css; charset=utf-8');
|
|
1541
|
+
}
|
|
1542
|
+
/** ESM addresses contain only the capability name and the optional contract of this host. */
|
|
1543
|
+
capabilityModule(req, pathname, legacy = false) {
|
|
1544
|
+
const match = /^\/_\/openartifacts:([a-z][a-z0-9]{0,23})(?:@(\d+\.\d+\.\d+))?$/.exec(pathname);
|
|
1545
|
+
if (!match)
|
|
1546
|
+
return deny(404, 'Unknown capability module.');
|
|
1547
|
+
const [, name, version] = match;
|
|
1548
|
+
if (version !== undefined && version !== CONTRACT)
|
|
1549
|
+
return deny(404, 'Contract not served by this frame.');
|
|
1550
|
+
// The older `/_/openartifact:use` re-exports the one module, as the others do: a second copy of it at another
|
|
1551
|
+
// address would be a second module instance, with references of its own.
|
|
1552
|
+
if (name === 'use' && !version && !legacy)
|
|
1553
|
+
return this.sendScript(req, 'imports');
|
|
1554
|
+
if (name !== 'use' && name !== 'self' && name !== 'hot' && !BACKED.has(name) && !Object.hasOwn(STUBBED, name))
|
|
1555
|
+
return deny(404, 'Unknown capability module.');
|
|
1556
|
+
const body = Buffer.from(name === 'use'
|
|
1557
|
+
? 'export { at, default } from "/_/openartifacts:use";\n'
|
|
1558
|
+
: `import { at } from "/_/openartifacts:use"; export default at(${JSON.stringify(name)});\n`);
|
|
1559
|
+
return sendFile(req, { size: body.length, mtimeMs: null, body }, 'text/javascript; charset=utf-8');
|
|
1560
|
+
}
|
|
1561
|
+
/** A browser script: the built `<name>.js`, or one the environment makes (from source, locally). */
|
|
1562
|
+
sendScript(req, name) {
|
|
1563
|
+
let file;
|
|
1564
|
+
try {
|
|
1565
|
+
file = this.env.client.file(`${name}.js`);
|
|
1566
|
+
}
|
|
1567
|
+
catch (error) {
|
|
1568
|
+
this.log(`client ${name}: ${error?.message ?? error}`);
|
|
1569
|
+
return deny(500, `The frame ${name} script is missing.`);
|
|
1570
|
+
}
|
|
1571
|
+
return sendFile(req, file, 'text/javascript; charset=utf-8');
|
|
1572
|
+
}
|
|
1573
|
+
sendBlob(req, id) {
|
|
1574
|
+
const meta = this.blobs.meta(id);
|
|
1575
|
+
if (!meta)
|
|
1576
|
+
return deny(404, 'Not found');
|
|
1577
|
+
const extra = meta.contentType === 'image/svg+xml' ? { 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox" } : {};
|
|
1578
|
+
return this.sendStored(req, join(this.blobs.dir, id), meta.contentType, true, { ...extra, 'Cache-Control': 'public, max-age=31536000, immutable' });
|
|
1579
|
+
}
|
|
1580
|
+
/** A file of the artifact's storage. */
|
|
1581
|
+
sendStored(req, path, type, cacheable = false, extra = {}) {
|
|
1582
|
+
return sendFile(req, storedFile(path), type, cacheable, extra);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
// ---- helpers -----------------------------------------------------------------------------------------------------------
|
|
1586
|
+
/** A lease's holder as stored: the viewer's id, then the page's own string (which only tells its tabs apart). */
|
|
1587
|
+
function leaseHolder(viewer, holder) {
|
|
1588
|
+
return `${viewer.id}\u0000${holder}`;
|
|
1589
|
+
}
|
|
1590
|
+
/** What the daemon records a page's write under: the owner's is `owner` (as before); another viewer's, its id. */
|
|
1591
|
+
function touchAuthor(viewer) {
|
|
1592
|
+
return viewer.level === 'owner' ? 'owner' : viewer.id;
|
|
1593
|
+
}
|
|
1594
|
+
/** Changes no page hears of: hidden paths, the blobs, the history. */
|
|
1595
|
+
function ignoredChange(rel) {
|
|
1596
|
+
return rel.split('/').some((s) => s.startsWith('.')) || rel.startsWith('_blobs/') || rel.startsWith('history/');
|
|
1597
|
+
}
|
|
1598
|
+
function originOf(value) {
|
|
1599
|
+
try {
|
|
1600
|
+
return new URL(value).origin;
|
|
1601
|
+
}
|
|
1602
|
+
catch {
|
|
1603
|
+
return value;
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
/** A file of the artifact's storage, or null when it is not a file. */
|
|
1607
|
+
export function storedFile(path) {
|
|
1608
|
+
try {
|
|
1609
|
+
const st = statSync(path);
|
|
1610
|
+
if (!st.isFile())
|
|
1611
|
+
return null;
|
|
1612
|
+
return { size: st.size, mtimeMs: st.mtimeMs, body: { path } };
|
|
1613
|
+
}
|
|
1614
|
+
catch {
|
|
1615
|
+
return null;
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
/** The answer for a file: 404 without one; its ETag (when it has a time), 304, and no body for HEAD. */
|
|
1619
|
+
function sendFile(req, file, type, cacheable = false, extra = {}) {
|
|
1620
|
+
if (!file)
|
|
1621
|
+
return deny(404, 'Not found');
|
|
1622
|
+
const head = req.method === 'HEAD';
|
|
1623
|
+
if (file.mtimeMs === null) {
|
|
1624
|
+
// Made on the fly (a script from source): no ETag, never cached.
|
|
1625
|
+
return {
|
|
1626
|
+
status: 200,
|
|
1627
|
+
headers: { 'Content-Type': type, 'Content-Length': file.size, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', ...extra },
|
|
1628
|
+
body: head ? null : file.body,
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
const etag = `W/"${file.size.toString(16)}-${Math.floor(file.mtimeMs).toString(16)}"`;
|
|
1632
|
+
const headers = {
|
|
1633
|
+
'Content-Type': type,
|
|
1634
|
+
'Cache-Control': cacheable ? 'no-cache' : 'no-store',
|
|
1635
|
+
ETag: etag,
|
|
1636
|
+
'X-Content-Type-Options': 'nosniff',
|
|
1637
|
+
...extra,
|
|
1638
|
+
};
|
|
1639
|
+
if (req.headers['if-none-match'] === etag)
|
|
1640
|
+
return { status: 304, headers, body: null };
|
|
1641
|
+
return { status: 200, headers: { ...headers, 'Content-Length': file.size }, body: head ? null : file.body };
|
|
1642
|
+
}
|
|
1643
|
+
/** A body's bytes: a stored file read whole, for a host that cannot stream it (a Durable Object). */
|
|
1644
|
+
export function replyBytes(body) {
|
|
1645
|
+
if (body === null)
|
|
1646
|
+
return null;
|
|
1647
|
+
if (body instanceof Uint8Array)
|
|
1648
|
+
return body;
|
|
1649
|
+
return readFileSync(body.path);
|
|
1650
|
+
}
|
|
1651
|
+
const bufferOf = (bytes) => (Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
1652
|
+
const numberOrUndefined = (v) => (v === null || v === '' || !Number.isFinite(Number(v)) ? undefined : Number(v));
|
|
1653
|
+
/** A thread as a page sees it. */
|
|
1654
|
+
function pageThread(t) {
|
|
1655
|
+
let anchor = t.location?.custom;
|
|
1656
|
+
if (anchor === undefined) {
|
|
1657
|
+
try {
|
|
1658
|
+
anchor = JSON.parse(t.anchor);
|
|
1659
|
+
}
|
|
1660
|
+
catch {
|
|
1661
|
+
anchor = t.anchor;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
return {
|
|
1665
|
+
id: t.id,
|
|
1666
|
+
anchor,
|
|
1667
|
+
label: t.label,
|
|
1668
|
+
resolved: t.status === 'resolved',
|
|
1669
|
+
status: t.status,
|
|
1670
|
+
agent: t.agent ?? null,
|
|
1671
|
+
createdAt: t.createdAt,
|
|
1672
|
+
updatedAt: t.updatedAt,
|
|
1673
|
+
messages: t.messages.map((m) => ({ id: m.id, author: m.author, text: m.text, at: m.at, ...(m.assignee !== undefined ? { assignee: m.assignee } : {}) })),
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
function errorOf(error) {
|
|
1677
|
+
const e = error;
|
|
1678
|
+
return { code: typeof e?.code === 'string' ? e.code : 'upstream_error', message: e?.message ?? String(error), ...(e?.extra ?? {}) };
|
|
1679
|
+
}
|
|
1680
|
+
function json(status, body, headOnly = false) {
|
|
1681
|
+
const text = Buffer.from(JSON.stringify(body));
|
|
1682
|
+
return {
|
|
1683
|
+
status,
|
|
1684
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': text.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
|
|
1685
|
+
body: headOnly ? null : text,
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
function deny(status, message) {
|
|
1689
|
+
return { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }, body: Buffer.from(message, 'utf8') };
|
|
1690
|
+
}
|
|
1691
|
+
// ---- the agent's actions -------------------------------------------------------------------------------------------
|
|
1692
|
+
function frameOf(artifact) {
|
|
1693
|
+
const site = artifact.site;
|
|
1694
|
+
if (!(site instanceof FrameCore))
|
|
1695
|
+
throw new FrameError('not_found', `${artifact.id} is not open here.`, 404);
|
|
1696
|
+
return site;
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1699
|
+
* The type's actions (`/__open-artifacts/actions/<name>`): `info` for Artifact `call`,
|
|
1700
|
+
* and the hidden `open-artifacts.db.*` and `open-artifacts.comments.*` that ArtifactData and
|
|
1701
|
+
* ArtifactComments use, in the shapes `libraryActions` answers.
|
|
1702
|
+
*/
|
|
1703
|
+
export const frameActions = {
|
|
1704
|
+
info: {
|
|
1705
|
+
title: 'What the artifact holds',
|
|
1706
|
+
run: (artifact) => {
|
|
1707
|
+
const site = frameOf(artifact);
|
|
1708
|
+
const manifest = site.files.manifest();
|
|
1709
|
+
return {
|
|
1710
|
+
info: {
|
|
1711
|
+
type: site.declaration.key,
|
|
1712
|
+
contract: CONTRACT,
|
|
1713
|
+
capabilities: site.grants,
|
|
1714
|
+
ver: manifest.ver,
|
|
1715
|
+
brokerGen: site.brokerGen,
|
|
1716
|
+
files: Object.entries(manifest.files).map(([p, f]) => ({ path: p, size: f.size })),
|
|
1717
|
+
db: site.db.listAll().length,
|
|
1718
|
+
assets: site.blobs.list().usage,
|
|
1719
|
+
comments: { open: site.comments.openCount() },
|
|
1720
|
+
},
|
|
1721
|
+
};
|
|
1722
|
+
},
|
|
1723
|
+
},
|
|
1724
|
+
'open-artifacts.db.read': { hidden: true, run: (artifact, a) => frameOf(artifact).db.readDb(a.path || undefined, { query: a.query, limit: a.limit, cursor: a.cursor }) },
|
|
1725
|
+
'open-artifacts.db.write': {
|
|
1726
|
+
hidden: true,
|
|
1727
|
+
run: (artifact, a) => ({ writes: frameOf(artifact).db.writeDb(Array.isArray(a.writes) ? a.writes : [], { requireIfMatch: a.require_if_match === true }) }),
|
|
1728
|
+
},
|
|
1729
|
+
'open-artifacts.comments.read': {
|
|
1730
|
+
hidden: true,
|
|
1731
|
+
run: (artifact, a) => ({
|
|
1732
|
+
threads: frameOf(artifact)
|
|
1733
|
+
.comments.threads({ all: !!a.all })
|
|
1734
|
+
.map((t, i) => agentView(t, i + 1)),
|
|
1735
|
+
// A thread without `agent` was not sent to the agent: the daemon keeps the agent's replies off it.
|
|
1736
|
+
sent_tracked: true,
|
|
1737
|
+
}),
|
|
1738
|
+
},
|
|
1739
|
+
'open-artifacts.comments.reply': {
|
|
1740
|
+
hidden: true,
|
|
1741
|
+
run: (artifact, a) => {
|
|
1742
|
+
const site = frameOf(artifact);
|
|
1743
|
+
const { thread } = site.comments.addMessage(a.thread_id, { ...AGENT_AUTHOR }, a.text, { resolve: !!a.resolve });
|
|
1744
|
+
site.commentsChanged();
|
|
1745
|
+
return { thread: agentView(thread) };
|
|
1746
|
+
},
|
|
1747
|
+
},
|
|
1748
|
+
'open-artifacts.comments.resolve': {
|
|
1749
|
+
hidden: true,
|
|
1750
|
+
run: (artifact, a) => {
|
|
1751
|
+
const site = frameOf(artifact);
|
|
1752
|
+
const thread = site.comments.setResolved(a.thread_id, !a.reopen, { ...AGENT_AUTHOR });
|
|
1753
|
+
site.commentsChanged();
|
|
1754
|
+
return { thread: agentView(thread) };
|
|
1755
|
+
},
|
|
1756
|
+
},
|
|
1757
|
+
};
|