@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.
Files changed (83) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/bin/frame-host.d.ts +2 -0
  5. package/bin/frame-host.js +47 -0
  6. package/package.json +124 -4
  7. package/src/child.d.ts +37 -0
  8. package/src/child.js +64 -0
  9. package/src/connectors/connectors.d.ts +101 -0
  10. package/src/connectors/connectors.js +256 -0
  11. package/src/connectors/daemon-connectors.d.ts +34 -0
  12. package/src/connectors/daemon-connectors.js +73 -0
  13. package/src/connectors/index.d.ts +7 -0
  14. package/src/connectors/index.js +7 -0
  15. package/src/connectors/mcp-client.d.ts +157 -0
  16. package/src/connectors/mcp-client.js +483 -0
  17. package/src/daemon.d.ts +119 -0
  18. package/src/daemon.js +301 -0
  19. package/src/frame/access.d.ts +69 -0
  20. package/src/frame/access.js +168 -0
  21. package/src/frame/client/comments.css +1 -0
  22. package/src/frame/client/comments.js +58 -0
  23. package/src/frame/client/imports.d.ts +6 -0
  24. package/src/frame/client/imports.js +112 -0
  25. package/src/frame/client/mcp-shell.js +345 -0
  26. package/src/frame/client/mcp.js +253 -0
  27. package/src/frame/client/runtime.js +1363 -0
  28. package/src/frame/client/sample.js +762 -0
  29. package/src/frame/client/shell.css +51 -0
  30. package/src/frame/client/shell.html +29 -0
  31. package/src/frame/client/shell.js +1417 -0
  32. package/src/frame/comments.d.ts +102 -0
  33. package/src/frame/comments.js +379 -0
  34. package/src/frame/core.d.ts +313 -0
  35. package/src/frame/core.js +1757 -0
  36. package/src/frame/db.d.ts +162 -0
  37. package/src/frame/db.js +604 -0
  38. package/src/frame/declaration.d.ts +30 -0
  39. package/src/frame/declaration.js +60 -0
  40. package/src/frame/env.d.ts +262 -0
  41. package/src/frame/env.js +13 -0
  42. package/src/frame/files.d.ts +130 -0
  43. package/src/frame/files.js +472 -0
  44. package/src/frame/index.d.ts +35 -0
  45. package/src/frame/index.js +33 -0
  46. package/src/frame/local.d.ts +126 -0
  47. package/src/frame/local.js +612 -0
  48. package/src/frame/mcp-relay.d.ts +79 -0
  49. package/src/frame/mcp-relay.js +191 -0
  50. package/src/frame/page-api.d.ts +48 -0
  51. package/src/frame/page-api.js +1 -0
  52. package/src/frame/page-comments.d.ts +109 -0
  53. package/src/frame/page-comments.js +1 -0
  54. package/src/frame/page-db.d.ts +88 -0
  55. package/src/frame/page-db.js +1 -0
  56. package/src/frame/page-imports.d.ts +2 -0
  57. package/src/frame/page-imports.js +2 -0
  58. package/src/frame/page-services.d.ts +124 -0
  59. package/src/frame/page-services.js +1 -0
  60. package/src/frame/page-values.d.ts +90 -0
  61. package/src/frame/page-values.js +1 -0
  62. package/src/frame/sample-relay.d.ts +42 -0
  63. package/src/frame/sample-relay.js +186 -0
  64. package/src/frame/snapshot-action.d.ts +18 -0
  65. package/src/frame/snapshot-action.js +82 -0
  66. package/src/frame/wire.d.ts +198 -0
  67. package/src/frame/wire.js +21 -0
  68. package/src/index.d.ts +17 -0
  69. package/src/index.js +17 -0
  70. package/src/lan.d.ts +75 -0
  71. package/src/lan.js +200 -0
  72. package/src/legacy-env.d.ts +7 -0
  73. package/src/legacy-env.js +14 -0
  74. package/src/serve.d.ts +375 -0
  75. package/src/serve.js +811 -0
  76. package/src/snapshot.d.ts +41 -0
  77. package/src/snapshot.js +224 -0
  78. package/src/type-package.d.ts +48 -0
  79. package/src/type-package.js +114 -0
  80. package/src/ws.d.ts +50 -0
  81. package/src/ws.js +203 -0
  82. package/src/zip.d.ts +197 -0
  83. package/src/zip.js +662 -0
package/src/index.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@openartifactsai/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_ARTIFACTS_*` environment.
6
+ * - `lan.ts`: LAN listeners for sharing.
7
+ * - `ws.ts`: a minimal WebSocket server side.
8
+ * - `child.ts`: stopping a child process (`stopChild`, `hasExited`) and ending this one (`endProcess`).
9
+ *
10
+ * The daemon cannot tell a server built with it from one that speaks the
11
+ * protocol by itself.
12
+ */
13
+ export * from "./serve.js";
14
+ export * from "./daemon.js";
15
+ export * from "./lan.js";
16
+ export * from "./ws.js";
17
+ export * from "./child.js";
package/src/lan.d.ts ADDED
@@ -0,0 +1,75 @@
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
+ import { SHARING_FILE } from '@openartifactsai/protocol/workspace-files';
10
+ /** The file in an artifact folder that records its sharing state. */
11
+ export { SHARING_FILE };
12
+ /**
13
+ * True for 100.64.0.0/10: Tailscale's addresses (a carrier NAT's too),
14
+ * reachable from anywhere on the same tailnet.
15
+ */
16
+ export declare function isTailnet(address: string): boolean;
17
+ /**
18
+ * This computer's IPv4 addresses others may reach: the local network's
19
+ * first, then tunnels and its own networks, then Tailscale.
20
+ */
21
+ export declare function lanAddresses(interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>): string[];
22
+ /** Whether an artifact folder's {@link SHARING_FILE} says it is shared on the network (without mounting anything). */
23
+ export declare function sharedOnLan(root: string): boolean;
24
+ /** What a site sees of the LAN listeners (`SiteContext.network`). */
25
+ export interface SiteNetwork {
26
+ /** The port every listener uses: the server's own. */
27
+ readonly port: number;
28
+ /** Addresses listened on now. */
29
+ addresses(): string[];
30
+ /** Starts listening on the LAN addresses (once for all sites); resolves with them. */
31
+ open(): Promise<string[]>;
32
+ /** This site stopped sharing: the listeners close when no other site shares. */
33
+ release(): void;
34
+ /** Whether a link may use `name` as its Host (an address listened on, this machine's name, or a name resolving to them). */
35
+ allowName(name: string): Promise<boolean>;
36
+ }
37
+ /** Options of {@link LanNetwork}. */
38
+ export interface LanNetworkOptions {
39
+ /** The server's port; LAN listeners use the same one. */
40
+ port: () => number;
41
+ /** A new HTTP server with the same handlers as the loopback one. */
42
+ createServer: () => Server;
43
+ /** Whether any site still shares (listeners stay open while one does). */
44
+ stillShared: () => boolean;
45
+ /** Diagnostic log. */
46
+ log: (line: string) => void;
47
+ /** The addresses to listen on (default {@link lanAddresses}). */
48
+ addresses?: () => string[];
49
+ }
50
+ /** The LAN listeners of one type server. */
51
+ export declare class LanNetwork {
52
+ /** The contract handed to sites. */
53
+ readonly network: SiteNetwork;
54
+ private readonly options;
55
+ /** Address → its HTTP server. */
56
+ private readonly servers;
57
+ /** Names a remote owner link came by that resolve to an address listened on. */
58
+ private readonly names;
59
+ private opening;
60
+ /** Creates the (closed) listeners. */
61
+ constructor(options: LanNetworkOptions);
62
+ /** True while at least one LAN listener is open. */
63
+ get listening(): boolean;
64
+ /** Opens listeners on every LAN address not listened on yet; resolves with all addresses listened on. */
65
+ open(): Promise<string[]>;
66
+ private openNow;
67
+ /** A site stopped sharing: the listeners stay while another one still shares. */
68
+ release(): void;
69
+ /** Closes every LAN listener. */
70
+ close(): void;
71
+ /** Whether the owner's other-device link may use `name`: an address listened on, this machine's name, or one resolving to them. */
72
+ allowName(name: string): Promise<boolean>;
73
+ /** While listening: whether a Host header names an address listened on, this machine, or a name {@link allowName} took. */
74
+ hostAllowed(host: string): boolean;
75
+ }
package/src/lan.js ADDED
@@ -0,0 +1,200 @@
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 { connect, createServer } from 'node:net';
9
+ import { hostname, networkInterfaces } from 'node:os';
10
+ import { SHARING_FILE, WorkspaceDirectory, readSharingState } from '@openartifactsai/protocol/workspace-files';
11
+ /** The file in an artifact folder that records its sharing state. */
12
+ export { SHARING_FILE };
13
+ /** 198.18.0.0/15 (RFC 2544): TUN-mode proxies put their own interface there; nobody else reaches it. */
14
+ const isBenchmarkRange = (address) => /^198\.1[89]\./.test(address);
15
+ /**
16
+ * True for 100.64.0.0/10: Tailscale's addresses (a carrier NAT's too),
17
+ * reachable from anywhere on the same tailnet.
18
+ */
19
+ export function isTailnet(address) {
20
+ const m = /^100\.(\d{1,3})\./.exec(address);
21
+ return !!m && Number(m[1]) >= 64 && Number(m[1]) <= 127;
22
+ }
23
+ /** A VPN's or proxy's interface, by name: nobody on the same Wi-Fi reaches its address. */
24
+ 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);
25
+ const ipv4Number = (address) => address.split('.').reduce((n, part) => n * 256 + Number(part), 0);
26
+ /** A network this computer makes for itself (point-to-point, or it holds the gateway's address), not one it joined. */
27
+ function isOwnNetwork(entry) {
28
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(entry.netmask))
29
+ return false;
30
+ const mask = ipv4Number(entry.netmask);
31
+ if (mask >= ipv4Number('255.255.255.252'))
32
+ return true;
33
+ const address = ipv4Number(entry.address);
34
+ return ((address & mask) >>> 0) + 1 === address;
35
+ }
36
+ /**
37
+ * This computer's IPv4 addresses others may reach: the local network's
38
+ * first, then tunnels and its own networks, then Tailscale.
39
+ */
40
+ export function lanAddresses(interfaces = networkInterfaces()) {
41
+ const rank = new Map();
42
+ for (const [name, list] of Object.entries(interfaces)) {
43
+ for (const entry of list ?? []) {
44
+ if (entry.family !== 'IPv4' || entry.internal || entry.address.startsWith('169.254.') || isBenchmarkRange(entry.address))
45
+ continue;
46
+ const r = isTailnet(entry.address) ? 2 : isTunnel(name) || isOwnNetwork(entry) ? 1 : 0;
47
+ rank.set(entry.address, Math.min(r, rank.get(entry.address) ?? r));
48
+ }
49
+ }
50
+ return [...rank.keys()].sort((a, b) => rank.get(a) - rank.get(b));
51
+ }
52
+ /** Errors that mean "nobody answers there". */
53
+ const NO_ANSWER = new Set(['ECONNREFUSED', 'EADDRNOTAVAIL', 'EAFNOSUPPORT', 'ENETUNREACH', 'EHOSTUNREACH', 'EACCES', 'EPERM']);
54
+ /** Whether something answers at host:port (refused, unreachable or 300 ms of silence: no). */
55
+ function answers(host, port) {
56
+ return new Promise((resolve) => {
57
+ const socket = connect({ host, port });
58
+ const done = (taken) => {
59
+ socket.destroy();
60
+ resolve(taken);
61
+ };
62
+ socket.setTimeout(300, () => done(false));
63
+ socket.once('connect', () => done(true));
64
+ socket.once('error', (error) => done(!NO_ANSWER.has(error.code ?? '')));
65
+ });
66
+ }
67
+ /** An address that accepts a connection even at a port nobody listens on is a proxy's: a link at it reaches nobody. */
68
+ async function answersAnyPort(address) {
69
+ const server = createServer();
70
+ let port = 0;
71
+ try {
72
+ port = await new Promise((resolve, reject) => {
73
+ server.once('error', reject);
74
+ server.listen(0, address, () => resolve(server.address()?.port ?? 0));
75
+ });
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ finally {
81
+ await new Promise((resolve) => server.close(() => resolve()));
82
+ }
83
+ return port > 0 && answers(address, port);
84
+ }
85
+ function listen(server, port, host) {
86
+ return new Promise((resolve, reject) => {
87
+ server.once('error', reject);
88
+ server.listen(port, host, () => {
89
+ server.off('error', reject);
90
+ resolve();
91
+ });
92
+ });
93
+ }
94
+ /** This machine's own name, with or without `.local`. */
95
+ function isMachineName(name) {
96
+ const machine = hostname().toLowerCase();
97
+ return name === machine || name === `${machine.replace(/\.local$/, '')}.local`;
98
+ }
99
+ /** Whether an artifact folder's {@link SHARING_FILE} says it is shared on the network (without mounting anything). */
100
+ export function sharedOnLan(root) {
101
+ try {
102
+ return readSharingState(new WorkspaceDirectory(root))?.lan === true;
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ /** The LAN listeners of one type server. */
109
+ export class LanNetwork {
110
+ /** The contract handed to sites. */
111
+ network;
112
+ options;
113
+ /** Address → its HTTP server. */
114
+ servers = new Map();
115
+ /** Names a remote owner link came by that resolve to an address listened on. */
116
+ names = new Set();
117
+ opening = null;
118
+ /** Creates the (closed) listeners. */
119
+ constructor(options) {
120
+ this.options = options;
121
+ const self = this;
122
+ this.network = Object.freeze({
123
+ get port() {
124
+ return self.options.port();
125
+ },
126
+ addresses: () => [...self.servers.keys()],
127
+ open: () => self.open(),
128
+ release: () => self.release(),
129
+ allowName: (name) => self.allowName(name),
130
+ });
131
+ }
132
+ /** True while at least one LAN listener is open. */
133
+ get listening() {
134
+ return this.servers.size > 0;
135
+ }
136
+ /** Opens listeners on every LAN address not listened on yet; resolves with all addresses listened on. */
137
+ open() {
138
+ // Two sites opening at once share one pass over the interfaces.
139
+ this.opening ??= this.openNow().finally(() => {
140
+ this.opening = null;
141
+ });
142
+ return this.opening;
143
+ }
144
+ async openNow() {
145
+ const want = (this.options.addresses ?? lanAddresses)().filter((a) => !this.servers.has(a));
146
+ const proxied = await Promise.all(want.map(answersAnyPort));
147
+ for (const address of want.filter((_, i) => !proxied[i])) {
148
+ const server = this.options.createServer();
149
+ try {
150
+ await listen(server, this.options.port(), address);
151
+ this.servers.set(address, server);
152
+ this.options.log(`sharing: listening at ${address}:${this.options.port()}`);
153
+ }
154
+ catch (error) {
155
+ server.close();
156
+ this.options.log(`sharing: not listening at ${address}:${this.options.port()}: ${error instanceof Error ? error.message : String(error)}`);
157
+ }
158
+ }
159
+ return [...this.servers.keys()];
160
+ }
161
+ /** A site stopped sharing: the listeners stay while another one still shares. */
162
+ release() {
163
+ if (!this.options.stillShared())
164
+ this.close();
165
+ }
166
+ /** Closes every LAN listener. */
167
+ close() {
168
+ for (const server of this.servers.values()) {
169
+ server.close();
170
+ server.closeAllConnections();
171
+ }
172
+ if (this.servers.size)
173
+ this.options.log('sharing: stopped listening on the network');
174
+ this.servers.clear();
175
+ this.names.clear();
176
+ }
177
+ /** Whether the owner's other-device link may use `name`: an address listened on, this machine's name, or one resolving to them. */
178
+ async allowName(name) {
179
+ const lower = String(name ?? '').toLowerCase();
180
+ if (!lower || !this.servers.size)
181
+ return false;
182
+ if (this.servers.has(lower) || isMachineName(lower) || this.names.has(lower))
183
+ return true;
184
+ const found = await lookup(lower, { all: true, family: 4 }).catch(() => []);
185
+ if (!found.some((e) => this.servers.has(e.address)))
186
+ return false;
187
+ this.names.add(lower);
188
+ return true;
189
+ }
190
+ /** While listening: whether a Host header names an address listened on, this machine, or a name {@link allowName} took. */
191
+ hostAllowed(host) {
192
+ if (!this.servers.size)
193
+ return false;
194
+ const suffix = `:${this.options.port()}`;
195
+ if (!host.endsWith(suffix))
196
+ return false;
197
+ const name = host.slice(0, -suffix.length).toLowerCase();
198
+ return this.servers.has(name) || isMachineName(name) || this.names.has(name);
199
+ }
200
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Our environment variables' names before 0.23 (`OPEN_ARTIFACT_*`, when Open Artifacts was "Open Artifact"): a daemon
3
+ * of 0.22 or older starts a type server with only those. A server built with this SDK reads the new name first, then
4
+ * the old one. No Node.js module is imported here: browser code shares the modules that use it.
5
+ */
6
+ /** The value of `name` (an `OPEN_ARTIFACTS_*` variable) in `env`, else of its old name (`OPEN_ARTIFACT_*`). */
7
+ export declare function envOrLegacy(env: Readonly<Record<string, string | undefined>>, name: string): string | undefined;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Our environment variables' names before 0.23 (`OPEN_ARTIFACT_*`, when Open Artifacts was "Open Artifact"): a daemon
3
+ * of 0.22 or older starts a type server with only those. A server built with this SDK reads the new name first, then
4
+ * the old one. No Node.js module is imported here: browser code shares the modules that use it.
5
+ */
6
+ const PREFIX = 'OPEN_ARTIFACTS_';
7
+ const LEGACY_PREFIX = 'OPEN_ARTIFACT_';
8
+ /** The value of `name` (an `OPEN_ARTIFACTS_*` variable) in `env`, else of its old name (`OPEN_ARTIFACT_*`). */
9
+ export function envOrLegacy(env, name) {
10
+ const value = env[name];
11
+ if (value || !name.startsWith(PREFIX))
12
+ return value;
13
+ return env[LEGACY_PREFIX + name.slice(PREFIX.length)] || value;
14
+ }