@open-artifact/server-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Types shared by frame-host's server (index.ts), the inner shell
3
+ * (client/shell.ts) and the Frame Runtime injected into the page
4
+ * (client/runtime.ts). Types only: the client scripts are plain scripts with
5
+ * no imports at run time.
6
+ *
7
+ * Page ⇄ inner shell messages follow the frame protocol (the
8
+ * `__frame_*` envelope). Inner shell ⇄ server is this host's own HTTP API.
9
+ */
10
+ /** The Frame Runtime contract this host reports in `__frame_init`. */
11
+ export type Contract = string;
12
+ /** What the server writes into the page as `window.__OPEN_ARTIFACT_FRAME`, before the runtime loads. */
13
+ export interface FrameBoot {
14
+ /** The inner shell's origin: the only window the runtime talks to. */
15
+ shellOrigin: string;
16
+ /** The artifact id. */
17
+ id: string;
18
+ /** The type key from the declaration. */
19
+ key: string | null;
20
+ /** Capabilities the page may use (backed here). */
21
+ grants: string[];
22
+ /** Declared capabilities this host cannot serve: they answer with an error code. */
23
+ stubs: string[];
24
+ contract: Contract;
25
+ /** Relay the page's console errors to the inner shell (OPEN_ARTIFACT_FRAME_DEBUG). */
26
+ debug?: boolean;
27
+ }
28
+ /** What `window.__FRAME_PREAMBLE` carries. */
29
+ export interface FramePreamble {
30
+ origins: string[];
31
+ }
32
+ /** A capability's config, as `__frame_init.capabilities[cap]` or a grant carries it. */
33
+ export interface CapGrant {
34
+ config?: Record<string, unknown>;
35
+ }
36
+ /** `GET /api/frame/session`: what the inner shell needs to start. */
37
+ export interface FrameSession {
38
+ id: string;
39
+ title: string;
40
+ key: string | null;
41
+ /** The artifact files' manifest version (the `/_f/<ver>/` segment). */
42
+ ver: string;
43
+ contract: Contract;
44
+ contentOrigin: string;
45
+ shellOrigin: string;
46
+ /** The broker generation: calls stamped with another one are not run. */
47
+ brokerGen: number;
48
+ grants: string[];
49
+ /** cap → error code. */
50
+ stubs: Record<string, string>;
51
+ /** cap → config, for `__frame_init.capabilities` and grants. */
52
+ configs: Record<string, Record<string, unknown>>;
53
+ /** The declaration's capabilities block, as written. */
54
+ capabilities: Record<string, unknown>;
55
+ flags: Record<string, boolean>;
56
+ readyTimeoutS: number;
57
+ me: LocalUser;
58
+ comments: {
59
+ available: boolean;
60
+ count: number;
61
+ };
62
+ agent: {
63
+ available: boolean;
64
+ name: string | null;
65
+ };
66
+ }
67
+ export interface LocalUser {
68
+ id: string;
69
+ name: string;
70
+ avatarUrl: string | null;
71
+ color: string;
72
+ email: string | null;
73
+ isOwner: boolean;
74
+ canEdit: boolean;
75
+ }
76
+ export interface CapRequest {
77
+ cap: string;
78
+ method: string;
79
+ args: unknown[];
80
+ /** The inner shell's client id (room sender, own-publish echo). */
81
+ client: string;
82
+ brokerGen?: number;
83
+ }
84
+ export interface CapErrorBody {
85
+ code: string;
86
+ message: string;
87
+ [extra: string]: unknown;
88
+ }
89
+ /** `POST /api/frame/cap` answer (always HTTP 200 once the request was understood). */
90
+ export type CapReply = {
91
+ result: unknown;
92
+ error?: undefined;
93
+ } | {
94
+ error: CapErrorBody;
95
+ result?: undefined;
96
+ };
97
+ /** Events of the inner shell's stream (`/api/frame/events`). */
98
+ export type FrameEvent = {
99
+ t: 'hello';
100
+ ver: string;
101
+ brokerGen: number;
102
+ peers: Peer[];
103
+ count: number;
104
+ } | {
105
+ t: 'db';
106
+ paths: string[];
107
+ } | {
108
+ t: 'room';
109
+ topic: string;
110
+ data: unknown;
111
+ from: string;
112
+ by: string;
113
+ } | {
114
+ t: 'peers';
115
+ peers: Peer[];
116
+ } | {
117
+ t: 'files';
118
+ ver: string;
119
+ paths: string[];
120
+ from?: string;
121
+ } | {
122
+ t: 'comments';
123
+ count: number;
124
+ }
125
+ /** The broker was rewired: a new generation, and the caps it now serves. */
126
+ | {
127
+ t: 'rewired';
128
+ brokerGen: number;
129
+ caps: string[];
130
+ reason: 'type' | 'files';
131
+ };
132
+ export interface Peer {
133
+ peer: string;
134
+ by: string;
135
+ name: string;
136
+ presence: Record<string, unknown>;
137
+ kind: 'user';
138
+ }
139
+ export interface CapCall {
140
+ __frame_cap: true;
141
+ cap: string;
142
+ id: string;
143
+ method: string;
144
+ args: unknown[];
145
+ brokerGen?: number;
146
+ holds?: boolean;
147
+ }
148
+ export interface CapResult {
149
+ __frame_cap_r: true;
150
+ id: string;
151
+ result?: unknown;
152
+ error?: CapErrorBody;
153
+ }
154
+ export interface FrameInit {
155
+ contract: Contract;
156
+ changes: string[];
157
+ flags: Record<string, boolean>;
158
+ capabilities: Record<string, CapGrant>;
159
+ usable: string[];
160
+ theme: 'light' | 'dark' | 'system';
161
+ hostVisible: boolean;
162
+ hostOverlays: unknown[];
163
+ hostSides: Record<string, unknown>;
164
+ hostKeys: unknown[];
165
+ hot: {
166
+ gen: number;
167
+ phase: 'final' | 'pending';
168
+ from: string | null;
169
+ };
170
+ capBudgets: Record<string, Record<string, number>>;
171
+ capWants: true;
172
+ brokerGen: number;
173
+ /** This host's: the inner shell's client id, so room events can tell "me". */
174
+ client: string;
175
+ }
176
+ export declare const DEFAULT_CAP_BUDGETS: Record<string, Record<string, number>>;
177
+ /** Message of a call refused because it was stamped with an older broker generation. */
178
+ export declare const STALE_GEN_MESSAGE = "not run: the artifact was updated";
179
+ /** Message of a pending call cut by `__frame_cap_rewired`. */
180
+ export declare const REWIRED_CUT_MESSAGE = "may not have run: the artifact was updated before this call was answered";
181
+ /** Message of a call to a capability the running version does not declare. */
182
+ export declare const UNDECLARED_MESSAGE = "the version this view runs does not declare it";
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Types shared by frame-host's server (index.ts), the inner shell
3
+ * (client/shell.ts) and the Frame Runtime injected into the page
4
+ * (client/runtime.ts). Types only: the client scripts are plain scripts with
5
+ * no imports at run time.
6
+ *
7
+ * Page ⇄ inner shell messages follow the frame protocol (the
8
+ * `__frame_*` envelope). Inner shell ⇄ server is this host's own HTTP API.
9
+ */
10
+ export const DEFAULT_CAP_BUDGETS = {
11
+ mcp: { callTool: 130_000 },
12
+ sample: { sample: 330_000 },
13
+ endpoints: { fetch: 130_000 },
14
+ assets: { upload: 270_000 },
15
+ };
16
+ /** Message of a call refused because it was stamped with an older broker generation. */
17
+ export const STALE_GEN_MESSAGE = 'not run: the artifact was updated';
18
+ /** Message of a pending call cut by `__frame_cap_rewired`. */
19
+ export const REWIRED_CUT_MESSAGE = 'may not have run: the artifact was updated before this call was answered';
20
+ /** Message of a call to a capability the running version does not declare. */
21
+ export const UNDECLARED_MESSAGE = 'the version this view runs does not declare it';
package/src/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@open-artifact/server-sdk`: shared code for type servers.
3
+ *
4
+ * - `serve.ts`: the server skeleton (`serve`, `TypeServer`), the Site contract and `libraryActions`.
5
+ * - `daemon.ts`: the Type API client (`TypeApi`) and the `OPEN_ARTIFACT_*` environment.
6
+ * - `lan.ts`: LAN listeners for sharing.
7
+ * - `ws.ts`: a minimal WebSocket server side.
8
+ *
9
+ * The daemon cannot tell a server built with it from one that speaks the
10
+ * protocol by itself.
11
+ */
12
+ export * from './serve.ts';
13
+ export * from './daemon.ts';
14
+ export * from './lan.ts';
15
+ export * from './ws.ts';
package/src/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@open-artifact/server-sdk`: shared code for type servers.
3
+ *
4
+ * - `serve.ts`: the server skeleton (`serve`, `TypeServer`), the Site contract and `libraryActions`.
5
+ * - `daemon.ts`: the Type API client (`TypeApi`) and the `OPEN_ARTIFACT_*` environment.
6
+ * - `lan.ts`: LAN listeners for sharing.
7
+ * - `ws.ts`: a minimal WebSocket server side.
8
+ *
9
+ * The daemon cannot tell a server built with it from one that speaks the
10
+ * protocol by itself.
11
+ */
12
+ export * from "./serve.js";
13
+ export * from "./daemon.js";
14
+ export * from "./lan.js";
15
+ export * from "./ws.js";
package/src/lan.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The network side of LAN sharing: listeners on this computer's local
3
+ * network addresses, opened when the first artifact is shared and closed
4
+ * when the last one stops, and the Host names they answer to. A site reaches
5
+ * it as {@link SiteNetwork} (`SiteContext.network`).
6
+ */
7
+ import type { Server } from 'node:http';
8
+ import { type NetworkInterfaceInfo } from 'node:os';
9
+ /** The file in an artifact folder that records its sharing state. */
10
+ export declare const SHARING_FILE = ".sharing.json";
11
+ /**
12
+ * True for 100.64.0.0/10: Tailscale's addresses (a carrier NAT's too),
13
+ * reachable from anywhere on the same tailnet.
14
+ */
15
+ export declare function isTailnet(address: string): boolean;
16
+ /**
17
+ * This computer's IPv4 addresses others may reach: the local network's
18
+ * first, then tunnels and its own networks, then Tailscale.
19
+ */
20
+ export declare function lanAddresses(interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>): string[];
21
+ /** Whether an artifact folder's {@link SHARING_FILE} says it is shared on the network (without mounting anything). */
22
+ export declare function sharedOnLan(root: string): boolean;
23
+ /** What a site sees of the LAN listeners (`SiteContext.network`). */
24
+ export interface SiteNetwork {
25
+ /** The port every listener uses: the server's own. */
26
+ readonly port: number;
27
+ /** Addresses listened on now. */
28
+ addresses(): string[];
29
+ /** Starts listening on the LAN addresses (once for all sites); resolves with them. */
30
+ open(): Promise<string[]>;
31
+ /** This site stopped sharing: the listeners close when no other site shares. */
32
+ release(): void;
33
+ /** Whether a link may use `name` as its Host (an address listened on, this machine's name, or a name resolving to them). */
34
+ allowName(name: string): Promise<boolean>;
35
+ }
36
+ /** Options of {@link LanNetwork}. */
37
+ export interface LanNetworkOptions {
38
+ /** The server's port; LAN listeners use the same one. */
39
+ port: () => number;
40
+ /** A new HTTP server with the same handlers as the loopback one. */
41
+ createServer: () => Server;
42
+ /** Whether any site still shares (listeners stay open while one does). */
43
+ stillShared: () => boolean;
44
+ /** Diagnostic log. */
45
+ log: (line: string) => void;
46
+ /** The addresses to listen on (default {@link lanAddresses}). */
47
+ addresses?: () => string[];
48
+ }
49
+ /** The LAN listeners of one type server. */
50
+ export declare class LanNetwork {
51
+ /** The contract handed to sites. */
52
+ readonly network: SiteNetwork;
53
+ private readonly options;
54
+ /** Address → its HTTP server. */
55
+ private readonly servers;
56
+ /** Names a remote owner link came by that resolve to an address listened on. */
57
+ private readonly names;
58
+ private opening;
59
+ /** Creates the (closed) listeners. */
60
+ constructor(options: LanNetworkOptions);
61
+ /** True while at least one LAN listener is open. */
62
+ get listening(): boolean;
63
+ /** Opens listeners on every LAN address not listened on yet; resolves with all addresses listened on. */
64
+ open(): Promise<string[]>;
65
+ private openNow;
66
+ /** A site stopped sharing: the listeners stay while another one still shares. */
67
+ release(): void;
68
+ /** Closes every LAN listener. */
69
+ close(): void;
70
+ /** Whether the owner's other-device link may use `name`: an address listened on, this machine's name, or one resolving to them. */
71
+ allowName(name: string): Promise<boolean>;
72
+ /** While listening: whether a Host header names an address listened on, this machine, or a name {@link allowName} took. */
73
+ hostAllowed(host: string): boolean;
74
+ }
package/src/lan.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The network side of LAN sharing: listeners on this computer's local
3
+ * network addresses, opened when the first artifact is shared and closed
4
+ * when the last one stops, and the Host names they answer to. A site reaches
5
+ * it as {@link SiteNetwork} (`SiteContext.network`).
6
+ */
7
+ import { lookup } from 'node:dns/promises';
8
+ import { readFileSync } from 'node:fs';
9
+ import { connect, createServer } from 'node:net';
10
+ import { hostname, networkInterfaces } from 'node:os';
11
+ import { join } from 'node:path';
12
+ /** The file in an artifact folder that records its sharing state. */
13
+ export const SHARING_FILE = '.sharing.json';
14
+ /** 198.18.0.0/15 (RFC 2544): TUN-mode proxies put their own interface there; nobody else reaches it. */
15
+ const isBenchmarkRange = (address) => /^198\.1[89]\./.test(address);
16
+ /**
17
+ * True for 100.64.0.0/10: Tailscale's addresses (a carrier NAT's too),
18
+ * reachable from anywhere on the same tailnet.
19
+ */
20
+ export function isTailnet(address) {
21
+ const m = /^100\.(\d{1,3})\./.exec(address);
22
+ return !!m && Number(m[1]) >= 64 && Number(m[1]) <= 127;
23
+ }
24
+ /** A VPN's or proxy's interface, by name: nobody on the same Wi-Fi reaches its address. */
25
+ const isTunnel = (name) => /(^|[^a-z0-9])(utun|tun|tap|wg|ppp|ipsec)\d*($|[^a-z0-9])/i.test(name) || /vpn|wintun|tunnel/i.test(name);
26
+ const ipv4Number = (address) => address.split('.').reduce((n, part) => n * 256 + Number(part), 0);
27
+ /** A network this computer makes for itself (point-to-point, or it holds the gateway's address), not one it joined. */
28
+ function isOwnNetwork(entry) {
29
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(entry.netmask))
30
+ return false;
31
+ const mask = ipv4Number(entry.netmask);
32
+ if (mask >= ipv4Number('255.255.255.252'))
33
+ return true;
34
+ const address = ipv4Number(entry.address);
35
+ return ((address & mask) >>> 0) + 1 === address;
36
+ }
37
+ /**
38
+ * This computer's IPv4 addresses others may reach: the local network's
39
+ * first, then tunnels and its own networks, then Tailscale.
40
+ */
41
+ export function lanAddresses(interfaces = networkInterfaces()) {
42
+ const rank = new Map();
43
+ for (const [name, list] of Object.entries(interfaces)) {
44
+ for (const entry of list ?? []) {
45
+ if (entry.family !== 'IPv4' || entry.internal || entry.address.startsWith('169.254.') || isBenchmarkRange(entry.address))
46
+ continue;
47
+ const r = isTailnet(entry.address) ? 2 : isTunnel(name) || isOwnNetwork(entry) ? 1 : 0;
48
+ rank.set(entry.address, Math.min(r, rank.get(entry.address) ?? r));
49
+ }
50
+ }
51
+ return [...rank.keys()].sort((a, b) => rank.get(a) - rank.get(b));
52
+ }
53
+ /** Errors that mean "nobody answers there". */
54
+ const NO_ANSWER = new Set(['ECONNREFUSED', 'EADDRNOTAVAIL', 'EAFNOSUPPORT', 'ENETUNREACH', 'EHOSTUNREACH', 'EACCES', 'EPERM']);
55
+ /** Whether something answers at host:port (refused, unreachable or 300 ms of silence: no). */
56
+ function answers(host, port) {
57
+ return new Promise((resolve) => {
58
+ const socket = connect({ host, port });
59
+ const done = (taken) => {
60
+ socket.destroy();
61
+ resolve(taken);
62
+ };
63
+ socket.setTimeout(300, () => done(false));
64
+ socket.once('connect', () => done(true));
65
+ socket.once('error', (error) => done(!NO_ANSWER.has(error.code ?? '')));
66
+ });
67
+ }
68
+ /** An address that accepts a connection even at a port nobody listens on is a proxy's: a link at it reaches nobody. */
69
+ async function answersAnyPort(address) {
70
+ const server = createServer();
71
+ let port = 0;
72
+ try {
73
+ port = await new Promise((resolve, reject) => {
74
+ server.once('error', reject);
75
+ server.listen(0, address, () => resolve(server.address()?.port ?? 0));
76
+ });
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ finally {
82
+ await new Promise((resolve) => server.close(() => resolve()));
83
+ }
84
+ return port > 0 && answers(address, port);
85
+ }
86
+ function listen(server, port, host) {
87
+ return new Promise((resolve, reject) => {
88
+ server.once('error', reject);
89
+ server.listen(port, host, () => {
90
+ server.off('error', reject);
91
+ resolve();
92
+ });
93
+ });
94
+ }
95
+ /** This machine's own name, with or without `.local`. */
96
+ function isMachineName(name) {
97
+ const machine = hostname().toLowerCase();
98
+ return name === machine || name === `${machine.replace(/\.local$/, '')}.local`;
99
+ }
100
+ /** Whether an artifact folder's {@link SHARING_FILE} says it is shared on the network (without mounting anything). */
101
+ export function sharedOnLan(root) {
102
+ try {
103
+ return JSON.parse(readFileSync(join(root, SHARING_FILE), 'utf8'))?.lan === true;
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ /** The LAN listeners of one type server. */
110
+ export class LanNetwork {
111
+ /** The contract handed to sites. */
112
+ network;
113
+ options;
114
+ /** Address → its HTTP server. */
115
+ servers = new Map();
116
+ /** Names a remote owner link came by that resolve to an address listened on. */
117
+ names = new Set();
118
+ opening = null;
119
+ /** Creates the (closed) listeners. */
120
+ constructor(options) {
121
+ this.options = options;
122
+ const self = this;
123
+ this.network = Object.freeze({
124
+ get port() {
125
+ return self.options.port();
126
+ },
127
+ addresses: () => [...self.servers.keys()],
128
+ open: () => self.open(),
129
+ release: () => self.release(),
130
+ allowName: (name) => self.allowName(name),
131
+ });
132
+ }
133
+ /** True while at least one LAN listener is open. */
134
+ get listening() {
135
+ return this.servers.size > 0;
136
+ }
137
+ /** Opens listeners on every LAN address not listened on yet; resolves with all addresses listened on. */
138
+ open() {
139
+ // Two sites opening at once share one pass over the interfaces.
140
+ this.opening ??= this.openNow().finally(() => {
141
+ this.opening = null;
142
+ });
143
+ return this.opening;
144
+ }
145
+ async openNow() {
146
+ const want = (this.options.addresses ?? lanAddresses)().filter((a) => !this.servers.has(a));
147
+ const proxied = await Promise.all(want.map(answersAnyPort));
148
+ for (const address of want.filter((_, i) => !proxied[i])) {
149
+ const server = this.options.createServer();
150
+ try {
151
+ await listen(server, this.options.port(), address);
152
+ this.servers.set(address, server);
153
+ this.options.log(`sharing: listening at ${address}:${this.options.port()}`);
154
+ }
155
+ catch (error) {
156
+ server.close();
157
+ this.options.log(`sharing: not listening at ${address}:${this.options.port()}: ${error instanceof Error ? error.message : String(error)}`);
158
+ }
159
+ }
160
+ return [...this.servers.keys()];
161
+ }
162
+ /** A site stopped sharing: the listeners stay while another one still shares. */
163
+ release() {
164
+ if (!this.options.stillShared())
165
+ this.close();
166
+ }
167
+ /** Closes every LAN listener. */
168
+ close() {
169
+ for (const server of this.servers.values()) {
170
+ server.close();
171
+ server.closeAllConnections();
172
+ }
173
+ if (this.servers.size)
174
+ this.options.log('sharing: stopped listening on the network');
175
+ this.servers.clear();
176
+ this.names.clear();
177
+ }
178
+ /** Whether the owner's other-device link may use `name`: an address listened on, this machine's name, or one resolving to them. */
179
+ async allowName(name) {
180
+ const lower = String(name ?? '').toLowerCase();
181
+ if (!lower || !this.servers.size)
182
+ return false;
183
+ if (this.servers.has(lower) || isMachineName(lower) || this.names.has(lower))
184
+ return true;
185
+ const found = await lookup(lower, { all: true, family: 4 }).catch(() => []);
186
+ if (!found.some((e) => this.servers.has(e.address)))
187
+ return false;
188
+ this.names.add(lower);
189
+ return true;
190
+ }
191
+ /** While listening: whether a Host header names an address listened on, this machine, or a name {@link allowName} took. */
192
+ hostAllowed(host) {
193
+ if (!this.servers.size)
194
+ return false;
195
+ const suffix = `:${this.options.port()}`;
196
+ if (!host.endsWith(suffix))
197
+ return false;
198
+ const name = host.slice(0, -suffix.length).toLowerCase();
199
+ return this.servers.has(name) || isMachineName(name) || this.names.has(name);
200
+ }
201
+ }