@open-artifact/server-sdk 0.0.0-stage → 0.2.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/src/serve.d.ts ADDED
@@ -0,0 +1,362 @@
1
+ /**
2
+ * `serve()`: the skeleton of a type server. One process per type, started by
3
+ * the daemon through `entry.start` (or by hand). It listens on `OPEN_ARTIFACT_PORT` (or
4
+ * a free port), prints the {@link ReadyLine}, answers the daemon's `/__open-artifact/*`
5
+ * routes behind `Bearer OPEN_ARTIFACT_SECRET`, and hands every request under
6
+ * `/<kind>/<token>/` to that artifact's {@link Site}.
7
+ *
8
+ * A type plugs in with `mountSite(root, context)`, which returns a
9
+ * {@link Site}: the object that serves one artifact's pages.
10
+ */
11
+ import { EventEmitter } from 'node:events';
12
+ import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
13
+ import type { Duplex } from 'node:stream';
14
+ import { type ArtifactTypeManifest, type ManifestHostHints, type OpenRequest, type ReadyLine, type ShareRequest, type ShareView, type SummaryResult, type TypeApiWakeResult, type WakeRequestItem, type WakeThread } from '@open-artifact/protocol';
15
+ import { TypeApi } from './daemon.ts';
16
+ import { LanNetwork, type SiteNetwork } from './lan.ts';
17
+ import { type WebSocketConnection } from './ws.ts';
18
+ /** Protocol version this SDK speaks. */
19
+ export declare const PROTOCOL = 1;
20
+ /** File a mounted artifact's folder gets, naming the server that serves it. */
21
+ export declare const STATE_FILE = ".artifact-server.json";
22
+ /** WebSocket subprotocol that carries a site's server-sent event stream. */
23
+ export declare const STREAM_PROTOCOL = "baoyu-sse";
24
+ /** The sharing side of a site, when its type supports LAN sharing. */
25
+ export interface SiteShare {
26
+ /** True while the site's LAN sharing is on (keeps it mounted when idle). */
27
+ readonly listening?: boolean;
28
+ /** Restores the saved sharing state after mounting; `open` is whether to open listeners right away. */
29
+ start?(open: boolean): unknown;
30
+ /** `GET /__open-artifact/share?id=`: the sharing state. */
31
+ shareView?(): ShareView | Promise<ShareView>;
32
+ /** `POST /__open-artifact/share`: changes sharing; answers the new state. */
33
+ share?(action: Omit<ShareRequest, 'id'> & Record<string, unknown>): ShareView | Promise<ShareView>;
34
+ /** The share links: `linkRole(token)` is truthy when `/s/<token>` is one of this site's links. */
35
+ sharing?: {
36
+ linkRole?(token: string): unknown;
37
+ };
38
+ }
39
+ /**
40
+ * What a type's `mountSite` returns: the server side of one open artifact.
41
+ * The skeleton routes every request under {@link page} to {@link handle},
42
+ * with `req.url` rewritten to the path below the page.
43
+ */
44
+ export interface Site {
45
+ /** The site's address, `/<kind>/<token>/`. Unique per server. */
46
+ readonly page: string;
47
+ /**
48
+ * Answers one request. For an event stream carried over WebSocket
49
+ * ({@link STREAM_PROTOCOL}), `res` is a {@link StreamResponse}, which offers
50
+ * the subset of `ServerResponse` an SSE handler uses.
51
+ */
52
+ handle(req: IncomingMessage, res: ServerResponse | StreamResponse): unknown;
53
+ /** Takes a WebSocket upgrade under the page (other than an event stream). */
54
+ upgrade?(req: IncomingMessage, socket: Duplex, head: Buffer): void;
55
+ /** Unmounts: stops watchers, closes connections. */
56
+ close(): void;
57
+ /** LAN sharing, when the type supports it. */
58
+ readonly share?: SiteShare;
59
+ /** Whether the site answers a path outside its page (e.g. its own top-level routes). */
60
+ claims?(pathname: string): boolean;
61
+ /** Whether the site serves a path shared by every site (e.g. common assets). */
62
+ common?(pathname: string): boolean;
63
+ /** Whether the site holds the upload `/_blob/<id>`. */
64
+ hasBlob?(id: string): boolean | Promise<boolean>;
65
+ /**
66
+ * Answers a request on the artifact's own origin, `http://<id>.frame.localhost:<port>`
67
+ * (servers started with {@link TypeServerOptions.contentHosts}). `req.url` is left as sent.
68
+ */
69
+ content?(req: IncomingMessage, res: ServerResponse): unknown;
70
+ /** Takes a WebSocket upgrade on the artifact's own origin. */
71
+ contentUpgrade?(req: IncomingMessage, socket: Duplex, head: Buffer): void;
72
+ }
73
+ /** Hands what a page sends for the agent to the daemon's wake router. */
74
+ export interface AgentHook {
75
+ /** A comment thread for the owner's session. */
76
+ thread(view: WakeThread): Promise<TypeApiWakeResult>;
77
+ /** A page request ("Ask agent to…") for the owner's session. */
78
+ request(request: Omit<WakeRequestItem, 'id'> & {
79
+ id?: string;
80
+ }): Promise<TypeApiWakeResult>;
81
+ }
82
+ /** What `mountSite` gets besides the artifact folder. */
83
+ export interface SiteContext {
84
+ /** Artifact id. */
85
+ id: string;
86
+ /** Artifact title, as the daemon knows it (may be empty). */
87
+ title: string;
88
+ /** The Type API client. */
89
+ daemon: TypeApi;
90
+ /** Appends a line to the artifact's log file. */
91
+ log(line: string): void;
92
+ /** The LAN listeners, for sharing. */
93
+ network: SiteNetwork;
94
+ /** Whether a request comes from this computer. */
95
+ local(req: IncomingMessage): boolean;
96
+ /** Wakes the owner's session; rejects when the agent could not be reached. */
97
+ agentHook: AgentHook;
98
+ /** The agent's display name, when the daemon knows it. */
99
+ agentName?: string;
100
+ /** false: the daemon cannot wake the agent while it idles; what is sent waits for its next turn. */
101
+ agentWakesIdle?: boolean;
102
+ /** Opening another folder from a page; this skeleton does not support it. */
103
+ open(): Promise<never>;
104
+ /**
105
+ * The artifact's own origin, `http://<id>.frame.localhost:<port>`, when the
106
+ * server routes content hosts ({@link TypeServerOptions.contentHosts}); else null.
107
+ */
108
+ contentOrigin?: string | null;
109
+ }
110
+ /** One open artifact, as actions see it. */
111
+ export interface ArtifactRef {
112
+ id: string;
113
+ /** Absolute path of the artifact folder. */
114
+ root: string;
115
+ title: string;
116
+ site: Site;
117
+ }
118
+ /** A named operation the agent can call (`POST /__open-artifact/actions/<name>`). */
119
+ export interface ServerAction {
120
+ /** Shown in the action list: one line, what it does. */
121
+ title?: string;
122
+ /** When to use it and what it returns (at most 1000 characters reach the agent). */
123
+ description?: string;
124
+ /** `read`: changes nothing. `write` (the default): changes the artifact. */
125
+ effect?: 'read' | 'write';
126
+ /** Left out of `GET /__open-artifact/actions` (reserved `open-artifact.*` actions). */
127
+ hidden?: boolean;
128
+ /** JSON schema of `args`, for the list. */
129
+ schema?: unknown;
130
+ /**
131
+ * A long action: the call answers `{task, pending: true}` at once, the
132
+ * action runs on, and its answer (or error) goes to the daemon through
133
+ * `open-artifact.type.task`, which hands it to the calling session. Without a daemon
134
+ * it runs like any other action.
135
+ */
136
+ long?: boolean;
137
+ /** Runs the action; the answer is sent as JSON. A long action may report `progress` (0 to 1). */
138
+ run(artifact: ArtifactRef, args: Record<string, unknown>, task?: ActionTask): unknown;
139
+ }
140
+ /** What a long action's `run` gets besides its arguments. */
141
+ export interface ActionTask {
142
+ /** The task id the call answered with. */
143
+ id: string;
144
+ /** Reports progress, 0 to 1 (logged by the daemon). */
145
+ progress(fraction: number): void;
146
+ }
147
+ /** One entry of `GET /__open-artifact/actions`. */
148
+ export interface ActionInfo {
149
+ name: string;
150
+ title: string;
151
+ description?: string;
152
+ effect?: 'read' | 'write';
153
+ schema?: unknown;
154
+ long?: boolean;
155
+ }
156
+ /** What a long action's call answers with, besides its task id. */
157
+ export declare const LONG_ACTION_NOTE = "This action runs in the background: its result comes to you as a message that starts with \"[Artifact task finished]\".";
158
+ /** The record {@link STATE_FILE} holds. */
159
+ export interface ServerStateRecord {
160
+ pid: number;
161
+ /** The site's page URL. */
162
+ url: string;
163
+ port: number;
164
+ root: string;
165
+ /** First segment of the page path. */
166
+ kind: string;
167
+ startedAt: string;
168
+ /** Artifact id. */
169
+ openArtifact: string;
170
+ }
171
+ /**
172
+ * The part of an HTTP response a site's event-stream handler uses, carried
173
+ * over one WebSocket: every `write` is one text message, `end` closes it
174
+ * (with `4000 + status` when the handler refused the stream). Emits `close`
175
+ * when the client goes away.
176
+ */
177
+ export declare class StreamResponse extends EventEmitter {
178
+ /** The WebSocket the stream goes out on. */
179
+ readonly ws: WebSocketConnection;
180
+ /** Status the handler set. */
181
+ statusCode: number;
182
+ /** Mirrors `ServerResponse.headersSent`. */
183
+ headersSent: boolean;
184
+ /** Mirrors `ServerResponse.writableEnded`. */
185
+ writableEnded: boolean;
186
+ /** Mirrors `ServerResponse.destroyed`. */
187
+ destroyed: boolean;
188
+ /** Wraps an accepted WebSocket. */
189
+ constructor(ws: WebSocketConnection);
190
+ /** Records the status; headers do not travel. */
191
+ writeHead(status: number, ..._rest: unknown[]): this;
192
+ /** Headers do not travel; a no-op. */
193
+ setHeader(..._args: unknown[]): this;
194
+ /** A no-op. */
195
+ flushHeaders(): void;
196
+ /** Sends `chunk` as one text message while the stream is open with status 200. */
197
+ write(chunk: unknown): boolean;
198
+ /** Ends the stream, closing the WebSocket. */
199
+ end(chunk?: unknown): this;
200
+ /** Ends the stream. */
201
+ destroy(): this;
202
+ /** The client went away. */
203
+ closed(): void;
204
+ }
205
+ /**
206
+ * What {@link libraryActions} looks for in a type library (the module that
207
+ * exports `mountSite`). Every function is optional.
208
+ */
209
+ export interface TypeLibrary {
210
+ /** Checks the artifact's files. */
211
+ check?(target: string): unknown;
212
+ /** Adds a file: bytes and a name (`project` style) or an absolute path (`root` style). */
213
+ upload?(target: string, file: Uint8Array | string, name: string, group?: unknown): unknown;
214
+ /** What the artifact holds. */
215
+ readInfo?(target: string): unknown;
216
+ /**
217
+ * `open-artifact.db.read`: the whole store, a collection or a document. `options`
218
+ * (`query`, `limit`, `cursor`) as the agent gave them; see DbStore.readDb.
219
+ */
220
+ readDb?(root: string, path?: string, options?: {
221
+ query?: unknown;
222
+ limit?: unknown;
223
+ cursor?: unknown;
224
+ }): unknown;
225
+ /** `open-artifact.db.write`: a batch of writes; `requireIfMatch` as DbStore.writeDb takes it. */
226
+ writeDb?(root: string, writes: unknown[], options?: {
227
+ requireIfMatch?: boolean;
228
+ }): unknown;
229
+ /** `open-artifact.comments.read`: open threads (`all`: resolved too). */
230
+ commentThreads?(root: string, all: boolean): unknown;
231
+ /** `open-artifact.comments.reply`. */
232
+ replyComment?(root: string, threadId: string, text: string, resolve: boolean): unknown;
233
+ /** `open-artifact.comments.resolve`. */
234
+ resolveComment?(root: string, threadId: string, reopen: boolean): unknown;
235
+ }
236
+ /**
237
+ * The agent's operations on an artifact through a type library: `check`,
238
+ * `upload` and `info` for the agent's `call`, and the reserved `open-artifact.db.*` and
239
+ * `open-artifact.comments.*` the ArtifactData and ArtifactComments tools use. `config`
240
+ * is the type's `open-artifact` block (`style`, `projectDir`).
241
+ */
242
+ export declare function libraryActions(lib: TypeLibrary, config?: ManifestHostHints): Record<string, ServerAction>;
243
+ /** The type's `artifact-type.json`, read from `dir` (default `OPEN_ARTIFACT_TYPE_DIR`); `{}` when there is none. */
244
+ export declare function typeManifest(dir?: string | undefined): ArtifactTypeManifest;
245
+ /** Options of {@link TypeServer} and {@link serve}. */
246
+ export interface TypeServerOptions {
247
+ /** Mounts one artifact folder; returns its site. */
248
+ mountSite(root: string, context: SiteContext): Site | Promise<Site>;
249
+ /** Named actions (`POST /__open-artifact/actions/<name>`). */
250
+ actions?: Record<string, ServerAction>;
251
+ /** `GET /__open-artifact/summary?id=`. */
252
+ summary?(artifact: {
253
+ id: string;
254
+ root: string;
255
+ }): SummaryResult | Promise<SummaryResult>;
256
+ /** Type id (default `OPEN_ARTIFACT_TYPE`, else `type`). */
257
+ type?: string;
258
+ /** Version reported by `/__open-artifact/health` (default `0`). */
259
+ version?: string;
260
+ /** Port to listen on (default `OPEN_ARTIFACT_PORT`, else any free one). */
261
+ port?: number;
262
+ /** Address to listen on (default `127.0.0.1`). */
263
+ host?: string;
264
+ /** Bearer secret of `/__open-artifact/*` (default `OPEN_ARTIFACT_SECRET`); `null` turns the check off. */
265
+ secret?: string | null;
266
+ /** Idle time after which unused sites unmount and the process exits, ms (default `OPEN_ARTIFACT_SERVER_IDLE_MS`, else 15 min; 0: never). */
267
+ idleMs?: number;
268
+ /** Called when the whole server has been idle for `idleMs` (default: close and exit). */
269
+ onIdle?: () => void;
270
+ /** The Type API client (default: from the environment). */
271
+ daemon?: TypeApi;
272
+ /** Diagnostic log (default: stderr with a timestamp). */
273
+ log?: (line: string) => void;
274
+ /**
275
+ * Gives each artifact its own origin: a request whose Host is
276
+ * `<artifact id>.frame.localhost:<port>` (from this computer) goes to that
277
+ * site's {@link Site.content} / {@link Site.contentUpgrade}. Browsers resolve
278
+ * `*.localhost` to loopback by themselves.
279
+ */
280
+ contentHosts?: boolean;
281
+ }
282
+ /** A type server built on the SDK: the `/__open-artifact/*` routes plus routing to each artifact's site. */
283
+ export declare class TypeServer {
284
+ /** Type id. */
285
+ readonly type: string;
286
+ /** Version reported by `/__open-artifact/health`. */
287
+ readonly version: string;
288
+ /** The Type API client. */
289
+ readonly daemon: TypeApi;
290
+ /** Diagnostic log. */
291
+ readonly log: (line: string) => void;
292
+ /** The loopback HTTP server. */
293
+ readonly server: Server;
294
+ /** The LAN listeners. */
295
+ readonly lan: LanNetwork;
296
+ /** Port once listening. */
297
+ port: number;
298
+ private readonly options;
299
+ private readonly secret;
300
+ private readonly idleMs;
301
+ private readonly byId;
302
+ private readonly byPage;
303
+ private readonly mounting;
304
+ private hosts;
305
+ private lastActivity;
306
+ private timer;
307
+ /** Creates the server; call {@link listen} next. */
308
+ constructor(options: TypeServerOptions);
309
+ /** `http://127.0.0.1:<port>`, without a trailing slash. */
310
+ get origin(): string;
311
+ /** Number of mounted artifacts. */
312
+ get openCount(): number;
313
+ private makeServer;
314
+ /** Listens on the configured port, or any free one when it is taken. */
315
+ listen(): Promise<this>;
316
+ /** The line the daemon waits for, with the protocol version and type for logs. */
317
+ readyLine(): ReadyLine & {
318
+ protocol: number;
319
+ type: string;
320
+ };
321
+ /** Prints the ready line to `out` (default stdout). */
322
+ ready(out?: {
323
+ write(text: string): unknown;
324
+ }): void;
325
+ private tick;
326
+ private sharing;
327
+ private anySharing;
328
+ private hostAllowed;
329
+ /** The artifact id of a request on an artifact's own origin, or null. */
330
+ private contentIdOf;
331
+ /** The mounted site whose own origin a request is on, or null when it is not on one. */
332
+ private contentEntry;
333
+ /** Mounts an artifact (or finds it mounted); idempotent. */
334
+ open(request: Partial<OpenRequest>): Promise<ArtifactRef & {
335
+ page: string;
336
+ }>;
337
+ private mount;
338
+ /** Unmounts an artifact; false when it was not mounted. */
339
+ unmount(id: string): boolean;
340
+ /** The site whose address `pathname` is under, with the path below it. */
341
+ private under;
342
+ /** The site of the page that referred this request (same host only). */
343
+ private referred;
344
+ /** The site that answers a path outside every site's address: share links, uploads, common paths, the referrer. */
345
+ private answering;
346
+ private onRequest;
347
+ private siteRequest;
348
+ /** The daemon's routes: from this computer, with the secret, never from a page. */
349
+ private openArtifactRoute;
350
+ /** Starts a long action and answers with its task; the end goes to the daemon (`open-artifact.type.task`). */
351
+ private runLong;
352
+ private onUpgrade;
353
+ /** A site's event stream (SSE) carried over a WebSocket ({@link STREAM_PROTOCOL}). */
354
+ private stream;
355
+ /** Unmounts everything and stops listening. */
356
+ close(): void;
357
+ }
358
+ /**
359
+ * Runs a type server: listens, prints the ready line, and closes everything
360
+ * on SIGTERM / SIGINT. Resolves with the {@link TypeServer}.
361
+ */
362
+ export declare function serve(options: TypeServerOptions): Promise<TypeServer>;