@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,6 @@
|
|
|
1
|
+
/** ES module served on the page origin. All grants and operations belong to the injected frame runtime. */
|
|
2
|
+
import type { PageImportOptions, PageReference } from '../page-api.js';
|
|
3
|
+
/** A stable capability reference, usable synchronously for granted builders and listeners. */
|
|
4
|
+
export declare function at<Name extends string>(name: Name, options?: PageImportOptions): PageReference<Name>;
|
|
5
|
+
/** Wait for the frame handshake and return the same reference that at() provides. */
|
|
6
|
+
export default function use<Name extends string>(name: Name, options?: PageImportOptions): Promise<PageReference<Name>>;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// packages/server-sdk/src/frame/client/imports.ts
|
|
2
|
+
var references = /* @__PURE__ */ new Map();
|
|
3
|
+
var reserved = /* @__PURE__ */ new Set(["then", "toJSON", "constructor", "__proto__", "prototype"]);
|
|
4
|
+
var reservedNames = /* @__PURE__ */ new Set(["constructor", "prototype", "use", "contract"]);
|
|
5
|
+
var listenerErrorArgument = {
|
|
6
|
+
"room.on": 2,
|
|
7
|
+
"room.onPeers": 1,
|
|
8
|
+
"room.onConnection": 1,
|
|
9
|
+
"room.onFollow": 1,
|
|
10
|
+
"comments.onSendToAgent": 1
|
|
11
|
+
};
|
|
12
|
+
var namePattern = /^[a-z][a-z0-9]{0,23}$/;
|
|
13
|
+
var blocked = (name) => Object.assign(new Error(`This page does not have the ${name} capability.`), { code: "not_granted" });
|
|
14
|
+
function reference(name, options) {
|
|
15
|
+
if (typeof name !== "string" || !namePattern.test(name) || reservedNames.has(name)) throw new TypeError("A capability name must be a lowercase identifier.");
|
|
16
|
+
const frame = globalThis.openArtifacts;
|
|
17
|
+
if (options?.contract !== void 0 && options.contract !== frame?.contract) {
|
|
18
|
+
throw new RangeError(`This frame does not serve contract ${options.contract}.`);
|
|
19
|
+
}
|
|
20
|
+
const key = name === "self" ? "artifact" : name;
|
|
21
|
+
const existing = references.get(key);
|
|
22
|
+
if (existing) return existing;
|
|
23
|
+
const initial = frame && Object.hasOwn(frame, key) ? Reflect.get(frame, key) : null;
|
|
24
|
+
let current = typeof initial === "object" && initial !== null ? initial : null;
|
|
25
|
+
const ready = frame ? frame.use(key).then((granted) => {
|
|
26
|
+
current = granted;
|
|
27
|
+
}) : Promise.resolve();
|
|
28
|
+
let pending = 0;
|
|
29
|
+
const invoke = async (member, args, enabled = () => true) => {
|
|
30
|
+
if (pending >= 256) throw Object.assign(new Error("Too many capability calls are waiting for the frame."), { code: "queue_overflow" });
|
|
31
|
+
pending++;
|
|
32
|
+
try {
|
|
33
|
+
const captured = args.map((value) => {
|
|
34
|
+
try {
|
|
35
|
+
return structuredClone(value);
|
|
36
|
+
} catch {
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
await ready;
|
|
41
|
+
if (!enabled()) return;
|
|
42
|
+
if (!current) throw blocked(key);
|
|
43
|
+
const method = current[member];
|
|
44
|
+
if (typeof method !== "function") throw new TypeError(`${key}.${member} is not a method.`);
|
|
45
|
+
return Reflect.apply(method, current, captured);
|
|
46
|
+
} finally {
|
|
47
|
+
pending--;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const target = /* @__PURE__ */ Object.create(null);
|
|
51
|
+
const namespace = new Proxy(target, {
|
|
52
|
+
get(_target, member) {
|
|
53
|
+
if (typeof member !== "string" || reserved.has(member)) return void 0;
|
|
54
|
+
if (member === "available") return current !== null;
|
|
55
|
+
if (current) return current[member];
|
|
56
|
+
const listener = `${key}.${member}`;
|
|
57
|
+
if (Object.hasOwn(listenerErrorArgument, listener)) {
|
|
58
|
+
return (...args) => {
|
|
59
|
+
let cancelled = false;
|
|
60
|
+
let stop;
|
|
61
|
+
void invoke(member, args, () => !cancelled).then((result) => {
|
|
62
|
+
if (typeof result !== "function") return;
|
|
63
|
+
if (cancelled) result();
|
|
64
|
+
else stop = () => result();
|
|
65
|
+
}, (error) => {
|
|
66
|
+
if (cancelled) return;
|
|
67
|
+
const handler = args[listenerErrorArgument[listener]];
|
|
68
|
+
if (typeof handler === "function") handler(error);
|
|
69
|
+
else globalThis.reportError(error);
|
|
70
|
+
});
|
|
71
|
+
return () => {
|
|
72
|
+
cancelled = true;
|
|
73
|
+
stop?.();
|
|
74
|
+
stop = void 0;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
return (...args) => invoke(member, args);
|
|
79
|
+
},
|
|
80
|
+
has(_target, member) {
|
|
81
|
+
return member === "available" || typeof member === "string" && !reserved.has(member) && !!current && Object.hasOwn(current, member);
|
|
82
|
+
},
|
|
83
|
+
ownKeys() {
|
|
84
|
+
return ["available", ...Object.keys(current ?? {}).filter((key2) => key2 !== "available" && !reserved.has(key2))];
|
|
85
|
+
},
|
|
86
|
+
getOwnPropertyDescriptor(_target, member) {
|
|
87
|
+
if (member === "available") return { configurable: true, enumerable: false, writable: false, value: current !== null };
|
|
88
|
+
if (!current || typeof member !== "string" || reserved.has(member) || !Object.hasOwn(current, member)) return void 0;
|
|
89
|
+
return { configurable: true, enumerable: true, writable: false, value: current[member] };
|
|
90
|
+
},
|
|
91
|
+
set: () => false,
|
|
92
|
+
defineProperty: () => false,
|
|
93
|
+
deleteProperty: () => false,
|
|
94
|
+
setPrototypeOf: () => false,
|
|
95
|
+
preventExtensions: () => false
|
|
96
|
+
});
|
|
97
|
+
const slot = { namespace, ready };
|
|
98
|
+
references.set(key, slot);
|
|
99
|
+
return slot;
|
|
100
|
+
}
|
|
101
|
+
function at(name, options) {
|
|
102
|
+
return reference(name, options).namespace;
|
|
103
|
+
}
|
|
104
|
+
async function use(name, options) {
|
|
105
|
+
const slot = reference(name, options);
|
|
106
|
+
await slot.ready;
|
|
107
|
+
return slot.namespace;
|
|
108
|
+
}
|
|
109
|
+
export {
|
|
110
|
+
at,
|
|
111
|
+
use as default
|
|
112
|
+
};
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// packages/server-sdk/src/frame/client/mcp-shell.ts
|
|
4
|
+
(() => {
|
|
5
|
+
"use strict";
|
|
6
|
+
const register = window.__openArtifactsMcpShell;
|
|
7
|
+
if (typeof register !== "function") return;
|
|
8
|
+
const WATCH_MIN_MS = 3e4;
|
|
9
|
+
const WATCH_MAX_MS = 864e5;
|
|
10
|
+
const WATCH_MAX = 64;
|
|
11
|
+
const GC_DEFAULT_MS = 3e5;
|
|
12
|
+
const GC_MAX_MS = 7 * 864e5;
|
|
13
|
+
const FINAL = /* @__PURE__ */ new Set(["not_in_manifest", "bad_request", "server_not_found", "capability_disabled", "capability_removed"]);
|
|
14
|
+
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
15
|
+
const err = (code, message, extra = {}) => ({ code, message, ...extra });
|
|
16
|
+
function stable(value) {
|
|
17
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
|
|
18
|
+
if (isRecord(value)) return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stable(value[k])}`).join(",")}}`;
|
|
19
|
+
return JSON.stringify(value) ?? "null";
|
|
20
|
+
}
|
|
21
|
+
const keyOf = (server, tool, input) => `${server}
|
|
22
|
+
${tool}
|
|
23
|
+
${stable(input ?? {})}`;
|
|
24
|
+
register((host) => {
|
|
25
|
+
const flights = /* @__PURE__ */ new Map();
|
|
26
|
+
const callers = /* @__PURE__ */ new Map();
|
|
27
|
+
const live = /* @__PURE__ */ new Set();
|
|
28
|
+
const cache = /* @__PURE__ */ new Map();
|
|
29
|
+
const writes = /* @__PURE__ */ new Set();
|
|
30
|
+
const reads = /* @__PURE__ */ new Set();
|
|
31
|
+
const learn = (server, tool, readOnly) => {
|
|
32
|
+
const name = `${server}
|
|
33
|
+
${tool}`;
|
|
34
|
+
if (readOnly) {
|
|
35
|
+
reads.add(name);
|
|
36
|
+
writes.delete(name);
|
|
37
|
+
} else {
|
|
38
|
+
writes.add(name);
|
|
39
|
+
reads.delete(name);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const watches = /* @__PURE__ */ new Map();
|
|
43
|
+
const learnFrom = (server, tools) => {
|
|
44
|
+
if (typeof server !== "string" || !Array.isArray(tools)) return;
|
|
45
|
+
for (const tool of tools) if (isRecord(tool) && typeof tool.name === "string") learn(server, tool.name, isRecord(tool.annotations) && tool.annotations.readOnlyHint === true);
|
|
46
|
+
};
|
|
47
|
+
async function run(server, tool, input, watch2, signal, onWait) {
|
|
48
|
+
let r;
|
|
49
|
+
try {
|
|
50
|
+
r = await fetch(host.api("mcp/call"), {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: { "Content-Type": "application/json" },
|
|
53
|
+
body: JSON.stringify({ server, tool, input, client: host.client, brokerGen: host.gen(), ...watch2 ? { watch: true } : {} }),
|
|
54
|
+
credentials: "same-origin",
|
|
55
|
+
signal
|
|
56
|
+
});
|
|
57
|
+
} catch (e) {
|
|
58
|
+
if (signal.aborted) throw err("cancelled", "The call was cancelled.", { server, tool });
|
|
59
|
+
throw err("upstream_error", `The connector call could not be sent: ${String(e?.message ?? e)}`, { server, tool, retryable: true });
|
|
60
|
+
}
|
|
61
|
+
if (!r.ok || !r.body) {
|
|
62
|
+
const out = await r.json().catch(() => null);
|
|
63
|
+
throw isRecord(out?.error) ? out.error : err("upstream_error", `HTTP ${r.status}`, { server, tool, retryable: true });
|
|
64
|
+
}
|
|
65
|
+
const reader = r.body.getReader();
|
|
66
|
+
const decoder = new TextDecoder();
|
|
67
|
+
let buffered = "";
|
|
68
|
+
const line = (text) => {
|
|
69
|
+
let ev;
|
|
70
|
+
try {
|
|
71
|
+
ev = JSON.parse(text);
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
if (!isRecord(ev)) return null;
|
|
76
|
+
if (ev.t === "wait") onWait(null);
|
|
77
|
+
else if (ev.t === "ask" && typeof ev.url === "string" && /^https?:\/\//i.test(ev.url)) onWait(ev.url);
|
|
78
|
+
else if (ev.t === "done") return { result: ev.result, payload: ev.payload, readOnly: ev.readOnly === true };
|
|
79
|
+
else if (ev.t === "error") {
|
|
80
|
+
const { t: _t, ...rest } = ev;
|
|
81
|
+
throw { ...rest, code: typeof ev.code === "string" ? ev.code : "upstream_error", message: typeof ev.message === "string" ? ev.message : "The connector call failed." };
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
};
|
|
85
|
+
try {
|
|
86
|
+
for (; ; ) {
|
|
87
|
+
const { value, done } = await reader.read();
|
|
88
|
+
if (done) break;
|
|
89
|
+
buffered += decoder.decode(value, { stream: true });
|
|
90
|
+
let at;
|
|
91
|
+
while ((at = buffered.indexOf("\n")) >= 0) {
|
|
92
|
+
const text = buffered.slice(0, at).trim();
|
|
93
|
+
buffered = buffered.slice(at + 1);
|
|
94
|
+
const out2 = text ? line(text) : null;
|
|
95
|
+
if (out2) return out2;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
buffered += decoder.decode();
|
|
99
|
+
const out = buffered.trim() ? line(buffered.trim()) : null;
|
|
100
|
+
if (out) return out;
|
|
101
|
+
} catch (e) {
|
|
102
|
+
if (signal.aborted) throw err("cancelled", "The call was cancelled.", { server, tool });
|
|
103
|
+
if (isRecord(e) && typeof e.code === "string") throw e;
|
|
104
|
+
throw err("upstream_error", `The connector call broke: ${String(e?.message ?? e)}`, { server, tool, retryable: true });
|
|
105
|
+
} finally {
|
|
106
|
+
reader.cancel().catch(() => {
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
throw err("upstream_error", "The connector call ended without an answer.", { server, tool, retryable: true });
|
|
110
|
+
}
|
|
111
|
+
const gcOf = (opts) => {
|
|
112
|
+
const ms = isRecord(opts) && typeof opts.gcTime === "number" ? opts.gcTime : GC_DEFAULT_MS;
|
|
113
|
+
return Math.max(0, Math.min(ms, GC_MAX_MS));
|
|
114
|
+
};
|
|
115
|
+
function store(key, done, opts) {
|
|
116
|
+
const old = cache.get(key);
|
|
117
|
+
if (old?.gc) clearTimeout(old.gc);
|
|
118
|
+
const entry = { done, storedAt: Date.now(), gc: null };
|
|
119
|
+
cache.set(key, entry);
|
|
120
|
+
touch(key, entry, opts);
|
|
121
|
+
}
|
|
122
|
+
function touch(key, entry, opts) {
|
|
123
|
+
if (entry.gc) clearTimeout(entry.gc);
|
|
124
|
+
entry.gc = setTimeout(() => {
|
|
125
|
+
if (cache.get(key) === entry) cache.delete(key);
|
|
126
|
+
}, gcOf(opts));
|
|
127
|
+
}
|
|
128
|
+
const answerOf = (done, from) => ({ ...done.result, payload: done.payload, ...from ? { cache: from } : {} });
|
|
129
|
+
function flight(key, server, tool, input, watch2, share) {
|
|
130
|
+
const have = share ? flights.get(key) : void 0;
|
|
131
|
+
if (have) return have;
|
|
132
|
+
const controller = new AbortController();
|
|
133
|
+
const f = {
|
|
134
|
+
controller,
|
|
135
|
+
waiters: /* @__PURE__ */ new Set(),
|
|
136
|
+
waiting: false,
|
|
137
|
+
promise: run(server, tool, input, watch2, controller.signal, (url) => {
|
|
138
|
+
f.waiting = true;
|
|
139
|
+
for (const id of f.waiters) {
|
|
140
|
+
host.toPage({ __frame_cap_ack: true, id });
|
|
141
|
+
host.ask(id, url);
|
|
142
|
+
}
|
|
143
|
+
})
|
|
144
|
+
};
|
|
145
|
+
if (share) flights.set(key, f);
|
|
146
|
+
live.add(f);
|
|
147
|
+
const clear = () => {
|
|
148
|
+
live.delete(f);
|
|
149
|
+
if (flights.get(key) === f) flights.delete(key);
|
|
150
|
+
for (const id of f.waiters) host.ask(id, null);
|
|
151
|
+
};
|
|
152
|
+
f.promise.then(clear, clear);
|
|
153
|
+
return f;
|
|
154
|
+
}
|
|
155
|
+
function callTool(id, args, reply) {
|
|
156
|
+
const [server, tool, input, rawCache] = args;
|
|
157
|
+
const opts = rawCache === false ? false : isRecord(rawCache) ? rawCache : void 0;
|
|
158
|
+
const key = keyOf(server, tool, input);
|
|
159
|
+
const write = writes.has(`${server}
|
|
160
|
+
${tool}`);
|
|
161
|
+
if (opts !== false && !write) {
|
|
162
|
+
const stored = cache.get(key);
|
|
163
|
+
const stale = isRecord(opts) && typeof opts.staleTime === "number" ? opts.staleTime : 0;
|
|
164
|
+
if (stored && !(isRecord(opts) && opts.refresh) && Date.now() - stored.storedAt < stale) {
|
|
165
|
+
touch(key, stored, opts);
|
|
166
|
+
return reply({ result: answerOf(stored.done, { storedAt: stored.storedAt, revalidating: false }) });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const f = flight(`call
|
|
170
|
+
${key}`, server, tool, input, false, reads.has(`${server}
|
|
171
|
+
${tool}`));
|
|
172
|
+
f.waiters.add(id);
|
|
173
|
+
callers.set(id, f);
|
|
174
|
+
if (f.waiting) host.toPage({ __frame_cap_ack: true, id });
|
|
175
|
+
f.promise.then(
|
|
176
|
+
(done) => {
|
|
177
|
+
if (!callers.delete(id)) return;
|
|
178
|
+
learn(server, tool, done.readOnly);
|
|
179
|
+
if (done.readOnly && opts !== false && done.result?.isError !== true) store(key, done, opts);
|
|
180
|
+
reply({ result: answerOf(done) });
|
|
181
|
+
},
|
|
182
|
+
(error) => {
|
|
183
|
+
if (!callers.delete(id)) return;
|
|
184
|
+
reply({ error });
|
|
185
|
+
}
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
function cancel(id) {
|
|
189
|
+
const f = callers.get(id);
|
|
190
|
+
if (!f) return;
|
|
191
|
+
callers.delete(id);
|
|
192
|
+
host.ask(id, null);
|
|
193
|
+
f.waiters.delete(id);
|
|
194
|
+
if (!f.waiters.size) f.controller.abort();
|
|
195
|
+
}
|
|
196
|
+
const hidden = () => document.visibilityState === "hidden";
|
|
197
|
+
const tell = (id, ev) => host.toPage({ __frame_mcp_watch: true, watch: id, ev });
|
|
198
|
+
function schedule(id, w, ms) {
|
|
199
|
+
if (w.timer) clearTimeout(w.timer);
|
|
200
|
+
w.timer = setTimeout(() => void poll(id, w), Math.max(0, ms));
|
|
201
|
+
}
|
|
202
|
+
async function poll(id, w, forced = false) {
|
|
203
|
+
if (watches.get(id) !== w) return;
|
|
204
|
+
w.timer = null;
|
|
205
|
+
if (hidden() && !forced) return;
|
|
206
|
+
if (w.busy) return;
|
|
207
|
+
w.busy = true;
|
|
208
|
+
const first = w.last === 0;
|
|
209
|
+
w.last = Date.now();
|
|
210
|
+
const key = keyOf(w.server, w.tool, w.input);
|
|
211
|
+
const stored = w.cache !== false ? cache.get(key) : void 0;
|
|
212
|
+
const stale = isRecord(w.cache) && typeof w.cache.staleTime === "number" ? w.cache.staleTime : 0;
|
|
213
|
+
try {
|
|
214
|
+
if (stored && Date.now() - stored.storedAt < stale && !forced) {
|
|
215
|
+
touch(key, stored, w.cache);
|
|
216
|
+
tell(id, { type: "data", result: answerOf(stored.done, { storedAt: stored.storedAt, revalidating: false }) });
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (stored && first) tell(id, { type: "data", result: answerOf(stored.done, { storedAt: stored.storedAt, revalidating: true }) });
|
|
220
|
+
const done = await flight(`watch
|
|
221
|
+
${key}`, w.server, w.tool, w.input, true, true).promise;
|
|
222
|
+
if (watches.get(id) !== w) return;
|
|
223
|
+
learn(w.server, w.tool, done.readOnly);
|
|
224
|
+
if (done.readOnly && w.cache !== false && done.result?.isError !== true) store(key, done, w.cache);
|
|
225
|
+
tell(id, { type: "data", result: answerOf(done) });
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (watches.get(id) !== w) return;
|
|
228
|
+
const code = isRecord(error) ? String(error.code) : "";
|
|
229
|
+
if (code === "cancelled") return;
|
|
230
|
+
const final = FINAL.has(code);
|
|
231
|
+
tell(id, { type: "error", error, ...final ? { final: true } : {} });
|
|
232
|
+
if (final) return void watches.delete(id);
|
|
233
|
+
} finally {
|
|
234
|
+
w.busy = false;
|
|
235
|
+
if (watches.get(id) === w && w.again) {
|
|
236
|
+
w.again = false;
|
|
237
|
+
if (w.timer) clearTimeout(w.timer);
|
|
238
|
+
w.timer = null;
|
|
239
|
+
void poll(id, w, true);
|
|
240
|
+
} else if (watches.get(id) === w && !w.timer) schedule(id, w, w.every);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function watch(args, reply) {
|
|
244
|
+
const [id, server, tool, input, raw] = args;
|
|
245
|
+
if (typeof id !== "string" || !id) return reply({ error: err("bad_request", "watch: an id.") });
|
|
246
|
+
if (watches.has(id)) return reply({ result: null });
|
|
247
|
+
if (watches.size >= WATCH_MAX) return reply({ error: err("bad_request", `At most ${WATCH_MAX} watches per view: stop one before starting another.`, { server, tool }) });
|
|
248
|
+
const o = isRecord(raw) ? raw : {};
|
|
249
|
+
const every = Math.min(WATCH_MAX_MS, Math.max(WATCH_MIN_MS, typeof o.refetchInterval === "number" ? o.refetchInterval : WATCH_MIN_MS));
|
|
250
|
+
const w = { server, tool, input: isRecord(input) ? input : {}, cache: o.cache === false ? false : isRecord(o.cache) ? o.cache : void 0, every, last: 0, timer: null, busy: false, again: false };
|
|
251
|
+
watches.set(id, w);
|
|
252
|
+
reply({ result: null });
|
|
253
|
+
void poll(id, w);
|
|
254
|
+
}
|
|
255
|
+
function unwatch(id) {
|
|
256
|
+
const w = watches.get(id);
|
|
257
|
+
if (!w) return;
|
|
258
|
+
if (w.timer) clearTimeout(w.timer);
|
|
259
|
+
watches.delete(id);
|
|
260
|
+
}
|
|
261
|
+
document.addEventListener("visibilitychange", () => {
|
|
262
|
+
if (hidden()) return;
|
|
263
|
+
for (const [id, w] of watches) {
|
|
264
|
+
if (w.busy) continue;
|
|
265
|
+
const due = w.last + w.every - Date.now();
|
|
266
|
+
if (due <= 0) void poll(id, w);
|
|
267
|
+
else schedule(id, w, due);
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
function invalidate(server, tool, input) {
|
|
271
|
+
const match = (s, t, i) => (typeof server !== "string" || s === server) && (typeof tool !== "string" || t === tool) && (!isRecord(input) || stable(i) === stable(input));
|
|
272
|
+
for (const [key, entry] of [...cache]) {
|
|
273
|
+
const [s, t, i] = key.split("\n");
|
|
274
|
+
if (match(s, t, JSON.parse(i))) {
|
|
275
|
+
if (entry.gc) clearTimeout(entry.gc);
|
|
276
|
+
cache.delete(key);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
for (const [id, w] of watches) {
|
|
280
|
+
if (!match(w.server, w.tool, w.input)) continue;
|
|
281
|
+
if (w.busy) w.again = true;
|
|
282
|
+
else void poll(id, w, true);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
async function read(path, body) {
|
|
286
|
+
try {
|
|
287
|
+
const r = body ? await fetch(host.api(path), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, client: host.client }), credentials: "same-origin" }) : await fetch(host.api(`${path}?client=${encodeURIComponent(host.client)}`), { credentials: "same-origin" });
|
|
288
|
+
const out = await r.json().catch(() => null);
|
|
289
|
+
if (isRecord(out) && out.error) return { error: out.error };
|
|
290
|
+
if (isRecord(out) && "result" in out) return { result: out.result };
|
|
291
|
+
return { error: err("upstream_error", `HTTP ${r.status}`, { retryable: true }) };
|
|
292
|
+
} catch (e) {
|
|
293
|
+
return { error: err("upstream_error", String(e?.message ?? e), { retryable: true }) };
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
answer: (m, reply) => {
|
|
298
|
+
const args = Array.isArray(m.args) ? m.args : [];
|
|
299
|
+
const id = String(m.id ?? "");
|
|
300
|
+
switch (m.method) {
|
|
301
|
+
case "callTool":
|
|
302
|
+
return callTool(id, args, reply);
|
|
303
|
+
case "cancelCall":
|
|
304
|
+
cancel(String(args[0] ?? ""));
|
|
305
|
+
return reply({ result: null });
|
|
306
|
+
case "listTools":
|
|
307
|
+
return void read("mcp/tools", typeof args[0] === "string" ? { server: args[0] } : {}).then((out) => {
|
|
308
|
+
const servers = isRecord(out.result) && Array.isArray(out.result.servers) ? out.result.servers : [];
|
|
309
|
+
for (const s of servers) if (isRecord(s) && s.authStatus === "connected") learnFrom(s.server, s.tools);
|
|
310
|
+
reply(out);
|
|
311
|
+
});
|
|
312
|
+
case "describeTool":
|
|
313
|
+
return void read("mcp/describe", { server: args[0], tool: args[1] }).then((out) => {
|
|
314
|
+
if (isRecord(out.result)) learnFrom(args[0], [out.result]);
|
|
315
|
+
reply(out);
|
|
316
|
+
});
|
|
317
|
+
case "state":
|
|
318
|
+
return void read("mcp/state", null).then(reply);
|
|
319
|
+
case "watch":
|
|
320
|
+
return watch(args, reply);
|
|
321
|
+
case "unwatch":
|
|
322
|
+
unwatch(String(args[0] ?? ""));
|
|
323
|
+
return reply({ result: null });
|
|
324
|
+
case "invalidate":
|
|
325
|
+
invalidate(args[0], args[1], args[2]);
|
|
326
|
+
return reply({ result: null });
|
|
327
|
+
default:
|
|
328
|
+
return reply({ error: err("capability_removed", `mcp.${String(m.method)} is not served here.`) });
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
drop: () => {
|
|
332
|
+
for (const f of live) f.controller.abort();
|
|
333
|
+
live.clear();
|
|
334
|
+
flights.clear();
|
|
335
|
+
for (const id of callers.keys()) host.ask(id, null);
|
|
336
|
+
callers.clear();
|
|
337
|
+
for (const w of watches.values()) if (w.timer) clearTimeout(w.timer);
|
|
338
|
+
watches.clear();
|
|
339
|
+
for (const entry of cache.values()) if (entry.gc) clearTimeout(entry.gc);
|
|
340
|
+
cache.clear();
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
});
|
|
344
|
+
})();
|
|
345
|
+
})();
|