fatedb 0.0.0-stage → 0.10.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +3 -0
  5. package/dist/cli.d.ts +15 -0
  6. package/dist/cli.js +256 -0
  7. package/dist/client.d.ts +152 -0
  8. package/dist/client.js +416 -0
  9. package/dist/cloudflare.d.ts +197 -0
  10. package/dist/cloudflare.js +159 -0
  11. package/dist/datalog/ast.d.ts +35 -0
  12. package/dist/datalog/ast.js +40 -0
  13. package/dist/datalog/evaluator.d.ts +14 -0
  14. package/dist/datalog/evaluator.js +395 -0
  15. package/dist/datalog/fact-source.d.ts +30 -0
  16. package/dist/datalog/fact-source.js +1 -0
  17. package/dist/datalog/fingerprint.d.ts +12 -0
  18. package/dist/datalog/fingerprint.js +50 -0
  19. package/dist/datalog/parser.d.ts +3 -0
  20. package/dist/datalog/parser.js +302 -0
  21. package/dist/datalog/value.d.ts +34 -0
  22. package/dist/datalog/value.js +104 -0
  23. package/dist/domain/date-validation.d.ts +2 -0
  24. package/dist/domain/date-validation.js +32 -0
  25. package/dist/domain/fact-value.d.ts +91 -0
  26. package/dist/domain/fact-value.js +167 -0
  27. package/dist/domain/fact.d.ts +14 -0
  28. package/dist/domain/fact.js +47 -0
  29. package/dist/domain/failure.d.ts +44 -0
  30. package/dist/domain/failure.js +30 -0
  31. package/dist/domain/graph-id.d.ts +7 -0
  32. package/dist/domain/graph-id.js +10 -0
  33. package/dist/domain/histogram.d.ts +29 -0
  34. package/dist/domain/histogram.js +48 -0
  35. package/dist/domain/identifiers.d.ts +26 -0
  36. package/dist/domain/identifiers.js +75 -0
  37. package/dist/domain/numbers.d.ts +12 -0
  38. package/dist/domain/numbers.js +77 -0
  39. package/dist/domain/projection.d.ts +252 -0
  40. package/dist/domain/projection.js +51 -0
  41. package/dist/domain/query-metrics.d.ts +31 -0
  42. package/dist/domain/query-metrics.js +35 -0
  43. package/dist/domain/read-token.d.ts +37 -0
  44. package/dist/domain/read-token.js +93 -0
  45. package/dist/domain/result.d.ts +22 -0
  46. package/dist/domain/result.js +16 -0
  47. package/dist/domain/schema-observation.d.ts +20 -0
  48. package/dist/domain/schema-observation.js +61 -0
  49. package/dist/domain/string-order.d.ts +2 -0
  50. package/dist/domain/string-order.js +15 -0
  51. package/dist/domain/vocabulary.d.ts +101 -0
  52. package/dist/domain/vocabulary.js +276 -0
  53. package/dist/index.d.ts +15 -0
  54. package/dist/index.js +14 -0
  55. package/dist/projection-config.d.ts +3 -0
  56. package/dist/projection-config.js +212 -0
  57. package/dist/server/access.d.ts +32 -0
  58. package/dist/server/access.js +117 -0
  59. package/dist/server/admin.d.ts +233 -0
  60. package/dist/server/admin.js +483 -0
  61. package/dist/server/authorization.d.ts +35 -0
  62. package/dist/server/authorization.js +76 -0
  63. package/dist/server/console-assets.d.ts +6 -0
  64. package/dist/server/console-assets.js +2 -0
  65. package/dist/server/console.d.ts +8 -0
  66. package/dist/server/console.js +301 -0
  67. package/dist/server/index.d.ts +122 -0
  68. package/dist/server/index.js +487 -0
  69. package/dist/server/mcp.d.ts +31 -0
  70. package/dist/server/mcp.js +169 -0
  71. package/dist/server/telemetry-do.d.ts +31 -0
  72. package/dist/server/telemetry-do.js +342 -0
  73. package/dist/server/telemetry.d.ts +27 -0
  74. package/dist/server/telemetry.js +191 -0
  75. package/dist/storage/constants.d.ts +20 -0
  76. package/dist/storage/constants.js +21 -0
  77. package/dist/storage/environment.d.ts +438 -0
  78. package/dist/storage/environment.js +145 -0
  79. package/dist/storage/facts.d.ts +41 -0
  80. package/dist/storage/facts.js +73 -0
  81. package/dist/storage/http.d.ts +55 -0
  82. package/dist/storage/http.js +169 -0
  83. package/dist/storage/keys.d.ts +50 -0
  84. package/dist/storage/keys.js +84 -0
  85. package/dist/storage/layout.d.ts +67 -0
  86. package/dist/storage/layout.js +134 -0
  87. package/dist/storage/log.d.ts +41 -0
  88. package/dist/storage/log.js +137 -0
  89. package/dist/storage/manifest.d.ts +26 -0
  90. package/dist/storage/manifest.js +206 -0
  91. package/dist/storage/operations.d.ts +303 -0
  92. package/dist/storage/operations.js +719 -0
  93. package/dist/storage/partition.d.ts +125 -0
  94. package/dist/storage/partition.js +816 -0
  95. package/dist/storage/projection.d.ts +72 -0
  96. package/dist/storage/projection.js +1349 -0
  97. package/dist/storage/root.d.ts +120 -0
  98. package/dist/storage/root.js +596 -0
  99. package/dist/storage/segment.d.ts +145 -0
  100. package/dist/storage/segment.js +451 -0
  101. package/dist/storage/shard.d.ts +82 -0
  102. package/dist/storage/shard.js +710 -0
  103. package/dist/storage/source.d.ts +60 -0
  104. package/dist/storage/source.js +199 -0
  105. package/dist/telemetry/model.d.ts +123 -0
  106. package/dist/telemetry/model.js +292 -0
  107. package/dist/version.d.ts +4 -0
  108. package/dist/version.js +6 -0
  109. package/package.json +82 -4
@@ -0,0 +1,487 @@
1
+ // A FateDB instance: the Worker an app binds to, with the Durable Objects that hold its graphs.
2
+ // `fatedb create` makes a project whose entry module re-exports this one, and whose config
3
+ // (`fatedb/cloudflare`) binds the storage. Apps call it over RPC: getGraph, query.
4
+ //
5
+ // Over HTTP it serves two callers. An app's binding reaches /mcp, as the binding's client id. With
6
+ // a console configured, its hostname, behind Cloudflare Access, serves the console and /mcp as the
7
+ // console's client id (console.ts, mcp.ts). Nothing else has a URL.
8
+ import { RpcTarget, WorkerEntrypoint } from "cloudflare:workers";
9
+ import { createInProcessGraph, } from "../client.js";
10
+ import { denied, invalid, unavailable } from "../domain/failure.js";
11
+ import { toValue } from "../domain/fact-value.js";
12
+ import { parseGraphId } from "../domain/graph-id.js";
13
+ import { parseMaxStalenessMs } from "../domain/read-token.js";
14
+ import { err, isRecord, ok } from "../domain/result.js";
15
+ import { handleGraphRequest, jsonResponse, queryInProcess, queryManyInProcess } from "../storage/http.js";
16
+ import { GraphError } from "../storage/operations.js";
17
+ import { COMPATIBILITY_DATE, VERSION } from "../version.js";
18
+ import { authenticate, consoleConfig, isCrossSiteWrite, isRefusal } from "./access.js";
19
+ import { describeEntity, graphDetail, listGraphs, observedSchema, runQuery } from "./admin.js";
20
+ import { authorizeGraph, GraphAuthorizationError, parseIdentity, staticAuthorizer } from "./authorization.js";
21
+ import { outcomeOfError, outcomeOfFailure, recordCall } from "./telemetry.js";
22
+ /**
23
+ * /mcp and the console load on first use: the MCP SDK and the console's files are most of the
24
+ * bundle, and apps' calls over RPC, most of what an instance serves, use neither, so an isolate
25
+ * started for one does not run them.
26
+ */
27
+ const loadMcp = () => import("./mcp.js");
28
+ const loadConsole = () => import("./console.js");
29
+ export { PartitionDO } from "../storage/partition.js";
30
+ export { IndexShardDO } from "../storage/shard.js";
31
+ export { GraphRootDO } from "../storage/root.js";
32
+ export { ProjectionDO } from "../storage/projection.js";
33
+ export { TelemetryDO } from "./telemetry-do.js";
34
+ function bindGraph(env, graphId) {
35
+ // The public client over the graph routes, in process: one parser and one code path, never a
36
+ // network fetch, and no second database implementation. Its queries skip the routes' JSON: an
37
+ // answer is most of what a read costs, and it would be serialized and parsed back for nothing.
38
+ return createInProcessGraph({ graphId,
39
+ fetch: async (input, init) => (await handleGraphRequest(new Request(input, init), env)) ?? jsonResponse({ error: "not found", retryable: false }, 404),
40
+ inProcess: (id, request) => queryInProcess(env, id, request),
41
+ inProcessMany: (id, request) => queryManyInProcess(env, id, request),
42
+ });
43
+ }
44
+ /**
45
+ * Runs an operation of the in-process client, whose failures are results already. Anything it
46
+ * throws is a fault of ours: logged here, and answered as the graph being unavailable, so no
47
+ * backend cause crosses RPC.
48
+ */
49
+ async function guarded(operation, run) {
50
+ try {
51
+ return await run();
52
+ }
53
+ catch (error) {
54
+ console.error(JSON.stringify({ event: "graph.rpc_failed", operation, error: error instanceof Error ? error.message : String(error) }));
55
+ return err(unavailable(operation, "FateDB failed to answer"));
56
+ }
57
+ }
58
+ /** RPC options name only known keys: no AbortSignal, and nothing the caller could use to widen its authority. */
59
+ function parseOptions(input, keys, what) {
60
+ if (input === undefined)
61
+ return ok({});
62
+ if (!isRecord(input) || Object.keys(input).some((key) => !keys.includes(key))) {
63
+ return err(invalid({ path: "options", message: `RPC ${what} accept only ${keys.join(", ")}` }));
64
+ }
65
+ return ok(input);
66
+ }
67
+ function parseReadOptionFields(fields) {
68
+ const result = {};
69
+ if (fields["readToken"] !== undefined) {
70
+ if (typeof fields["readToken"] !== "string") {
71
+ return err(invalid({ path: "readToken", message: "expected a read token from an earlier answer" }));
72
+ }
73
+ result.readToken = fields["readToken"];
74
+ }
75
+ if (fields["consistency"] !== undefined) {
76
+ if (fields["consistency"] !== "own-writes" && fields["consistency"] !== "snapshot") {
77
+ return err(invalid({ path: "consistency", message: "expected own-writes or snapshot" }));
78
+ }
79
+ result.consistency = fields["consistency"];
80
+ }
81
+ if (fields["maxStalenessMs"] !== undefined) {
82
+ const parsed = parseMaxStalenessMs(fields["maxStalenessMs"], "maxStalenessMs");
83
+ if (!parsed.ok)
84
+ return err(invalid(parsed.error));
85
+ if (parsed.value !== undefined)
86
+ result.maxStalenessMs = parsed.value;
87
+ }
88
+ return ok(result);
89
+ }
90
+ function readOptions(input) {
91
+ const fields = parseOptions(input, ["readToken", "consistency", "maxStalenessMs"], "reads");
92
+ if (!fields.ok)
93
+ return fields;
94
+ return parseReadOptionFields(fields.value);
95
+ }
96
+ function writeOptions(input) {
97
+ const fields = parseOptions(input, ["clientRequestToken", "readToken"], "writes");
98
+ if (!fields.ok)
99
+ return fields;
100
+ const result = {};
101
+ if (fields.value["clientRequestToken"] !== undefined) {
102
+ if (typeof fields.value["clientRequestToken"] !== "string") {
103
+ return err(invalid({ path: "clientRequestToken", message: "expected a non-empty client request token" }));
104
+ }
105
+ result.clientRequestToken = fields.value["clientRequestToken"];
106
+ }
107
+ if (fields.value["readToken"] !== undefined) {
108
+ if (typeof fields.value["readToken"] !== "string") {
109
+ return err(invalid({ path: "readToken", message: "expected a read token from an earlier answer" }));
110
+ }
111
+ result.readToken = fields.value["readToken"];
112
+ }
113
+ return ok(result);
114
+ }
115
+ /**
116
+ * A graph, for an app (RFD0015). Its operations answer results, and never throw for what they are
117
+ * given: a handle for a graph id that is not one answers `invalid`, one for a graph the app has no
118
+ * grant for answers `denied`, and one without the write grant answers `denied` from `transact`.
119
+ */
120
+ export class Graph extends RpcTarget {
121
+ #id;
122
+ #access;
123
+ #telemetry;
124
+ constructor(id, access, telemetry) {
125
+ super();
126
+ this.#id = id;
127
+ this.#access = access;
128
+ this.#telemetry = telemetry;
129
+ }
130
+ get id() {
131
+ return this.#id;
132
+ }
133
+ async query(source, options) {
134
+ const started = performance.now();
135
+ const access = this.#access;
136
+ const record = (result) => {
137
+ if (this.#telemetry !== undefined && this.#id !== "") {
138
+ const client = access.ok ? access.value.clientId : this.#telemetry.clientId;
139
+ recordCall(this.#telemetry.env, this.#telemetry.ctx, {
140
+ graph: this.#id,
141
+ client,
142
+ operation: "query",
143
+ outcome: result.ok ? "ok" : outcomeOfFailure(result.error),
144
+ durationMs: performance.now() - started,
145
+ ...(typeof source === "string"
146
+ ? { query: { source, rows: result.ok ? result.value.rows.length : 0, tuples: result.ok ? result.value.metrics.source.tuplesRead : 0 } }
147
+ : {}),
148
+ });
149
+ }
150
+ return result;
151
+ };
152
+ if (!access.ok)
153
+ return record(access);
154
+ const read = readOptions(options);
155
+ if (!read.ok)
156
+ return record(read);
157
+ return record(await guarded("read", () => access.value.client.query(source, read.value)));
158
+ }
159
+ async queryMany(sources, options) {
160
+ const started = performance.now();
161
+ const access = this.#access;
162
+ const record = (result) => {
163
+ if (this.#telemetry !== undefined && this.#id !== "") {
164
+ const client = access.ok ? access.value.clientId : this.#telemetry.clientId;
165
+ recordCall(this.#telemetry.env, this.#telemetry.ctx, {
166
+ graph: this.#id,
167
+ client,
168
+ operation: "query",
169
+ outcome: result.ok ? "ok" : outcomeOfFailure(result.error),
170
+ durationMs: performance.now() - started,
171
+ });
172
+ }
173
+ return result;
174
+ };
175
+ if (!access.ok)
176
+ return record(access);
177
+ const read = readOptions(options);
178
+ if (!read.ok)
179
+ return record(read);
180
+ return record(await guarded("read", () => access.value.client.queryMany(sources, read.value)));
181
+ }
182
+ async getSchema(options) {
183
+ const started = performance.now();
184
+ const access = this.#access;
185
+ const record = (result) => {
186
+ if (this.#telemetry !== undefined && this.#id !== "") {
187
+ const client = access.ok ? access.value.clientId : this.#telemetry.clientId;
188
+ recordCall(this.#telemetry.env, this.#telemetry.ctx, {
189
+ graph: this.#id,
190
+ client,
191
+ operation: "getSchema",
192
+ outcome: result.ok ? "ok" : outcomeOfFailure(result.error),
193
+ durationMs: performance.now() - started,
194
+ });
195
+ }
196
+ return result;
197
+ };
198
+ if (!access.ok)
199
+ return record(access);
200
+ const read = readOptions(options);
201
+ if (!read.ok)
202
+ return record(read);
203
+ return record(await guarded("read", () => access.value.client.getSchema(read.value)));
204
+ }
205
+ async transact(facts, options) {
206
+ const started = performance.now();
207
+ const access = this.#access;
208
+ const factCount = Array.isArray(facts) ? facts.length : 0;
209
+ const record = (result) => {
210
+ if (this.#telemetry !== undefined && this.#id !== "") {
211
+ const client = access.ok ? access.value.clientId : this.#telemetry.clientId;
212
+ recordCall(this.#telemetry.env, this.#telemetry.ctx, {
213
+ graph: this.#id,
214
+ client,
215
+ operation: "transact",
216
+ outcome: result.ok ? "ok" : outcomeOfFailure(result.error),
217
+ durationMs: performance.now() - started,
218
+ ...(result.ok && !result.value.replayed ? { facts: factCount } : {}),
219
+ });
220
+ }
221
+ return result;
222
+ };
223
+ if (!access.ok)
224
+ return record(access);
225
+ if (!access.value.write)
226
+ return record(err(denied(`this app's grant for graph ${this.#id} is read only`)));
227
+ const write = writeOptions(options);
228
+ if (!write.ok)
229
+ return record(write);
230
+ return record(await guarded("write", () => access.value.client.transact(facts, write.value)));
231
+ }
232
+ }
233
+ export default class FateDBService extends WorkerEntrypoint {
234
+ // A top-level RPC returning only data has its own execution context. Calls on one long-lived
235
+ // RpcTarget instead share the getGraph invocation's budgets. Every one-shot call is authorized:
236
+ // it is not a caller-supplied capability.
237
+ async query(input) {
238
+ const fields = parseOptions(input, ["graphId", "query", "readToken", "consistency", "maxStalenessMs"], "queries");
239
+ if (!fields.ok)
240
+ return fields;
241
+ const { graphId, query, ...options } = fields.value;
242
+ if (typeof query !== "string")
243
+ return err(invalid({ path: "query", message: "expected a Datalog query string" }));
244
+ const parsed = parseReadOptionFields(options);
245
+ if (!parsed.ok)
246
+ return parsed;
247
+ const telemetry = { env: this.env, ctx: this.ctx, clientId: this.#clientId() };
248
+ return new Graph(typeof graphId === "string" ? graphId : "", await this.#access(graphId), telemetry).query(query, parsed.value);
249
+ }
250
+ async queryMany(input) {
251
+ const fields = parseOptions(input, ["graphId", "queries", "readToken", "consistency", "maxStalenessMs"], "batch queries");
252
+ if (!fields.ok)
253
+ return fields;
254
+ const { graphId, queries, ...options } = fields.value;
255
+ if (!Array.isArray(queries) || !queries.every((q) => typeof q === "string")) {
256
+ return err(invalid({ path: "queries", message: "expected an array of Datalog query strings" }));
257
+ }
258
+ const parsed = parseReadOptionFields(options);
259
+ if (!parsed.ok)
260
+ return parsed;
261
+ const telemetry = { env: this.env, ctx: this.ctx, clientId: this.#clientId() };
262
+ return new Graph(typeof graphId === "string" ? graphId : "", await this.#access(graphId), telemetry).queryMany(queries, parsed.value);
263
+ }
264
+ /** A handle for the graph, whatever it is given: its operations answer why they cannot run. */
265
+ async getGraph(input) {
266
+ const fields = parseOptions(input, ["graphId"], "graph handles");
267
+ const graphId = fields.ok ? fields.value["graphId"] : undefined;
268
+ const telemetry = { env: this.env, ctx: this.ctx, clientId: this.#clientId() };
269
+ return new Graph(typeof graphId === "string" ? graphId : "", fields.ok ? await this.#access(graphId) : fields, telemetry);
270
+ }
271
+ #clientId() {
272
+ try {
273
+ return parseIdentity(this.ctx.props).clientId;
274
+ }
275
+ catch {
276
+ return "unknown";
277
+ }
278
+ }
279
+ /** What this app may do with the graph, by its binding's client id and the instance's grants. Acquiring it creates no data. */
280
+ async #access(input) {
281
+ const graphId = parseGraphId(input);
282
+ if (!graphId.ok)
283
+ return err(invalid(graphId.error));
284
+ let identity;
285
+ try {
286
+ identity = parseIdentity(this.ctx.props);
287
+ }
288
+ catch {
289
+ return err(denied("this app's binding has no client id: bind the instance with props: { clientId }"));
290
+ }
291
+ let permissions;
292
+ try {
293
+ permissions = await authorizeGraph(staticAuthorizer(this.env.GRAPH_GRANTS), identity, { graphId: graphId.value });
294
+ }
295
+ catch (error) {
296
+ if (error instanceof GraphAuthorizationError)
297
+ return err(denied(`this app has no grant to read graph ${graphId.value}`));
298
+ throw error;
299
+ }
300
+ return ok({ client: bindGraph(this.env, graphId.value), write: permissions.includes("write"), clientId: identity.clientId });
301
+ }
302
+ async fetch(request) {
303
+ const url = new URL(request.url);
304
+ const props = this.ctx.props;
305
+ if (typeof props === "object" && props !== null && Object.keys(props).length > 0) {
306
+ let clientId;
307
+ try {
308
+ ({ clientId } = parseIdentity(props));
309
+ }
310
+ catch {
311
+ return plain("Graph access denied", 403);
312
+ }
313
+ if (url.pathname !== "/mcp")
314
+ return plain("Not found", 404);
315
+ return (await loadMcp()).handleMcp(request, this.env, this.ctx, (code) => this.#run(clientId, code), VERSION);
316
+ }
317
+ const config = consoleConfig(this.env.CONSOLE);
318
+ if (config === null || url.hostname !== config.hostname)
319
+ return plain("Not found", 404);
320
+ const viewer = await authenticate(request, config);
321
+ if (isRefusal(viewer))
322
+ return plain(viewer.reason, viewer.status);
323
+ if (isCrossSiteWrite(request))
324
+ return plain("Cross-site writes are refused", 403);
325
+ if (url.pathname === "/mcp")
326
+ return (await loadMcp()).handleMcp(request, this.env, this.ctx, (code) => this.#run(config.clientId, code), VERSION);
327
+ const routes = await loadConsole();
328
+ if (url.pathname.startsWith("/api/"))
329
+ return routes.handleConsoleApi(request, this.env, config, viewer, this.ctx);
330
+ return routes.serveConsole(request);
331
+ }
332
+ /** Runs an agent's code in a Dynamic Worker with no network, whose only binding is the read-only API as `clientId`. */
333
+ async #run(clientId, code) {
334
+ const started = performance.now();
335
+ const finish = (res) => {
336
+ recordCall(this.env, this.ctx, {
337
+ graph: "_instance",
338
+ client: clientId,
339
+ operation: "execute",
340
+ outcome: res.ok ? "ok" : "failed",
341
+ durationMs: performance.now() - started,
342
+ });
343
+ return res;
344
+ };
345
+ const { normalizeCode, sandboxModule } = await loadMcp();
346
+ const source = sandboxModule(normalizeCode(code));
347
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source)));
348
+ const id = `${clientId}:${[...digest.slice(0, 16)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
349
+ const codemodeApi = getCodemodeApiFactory(this.ctx.exports);
350
+ if (codemodeApi === null)
351
+ return finish({ ok: false, error: "the code did not run: CodemodeApi export is unavailable", logs: [] });
352
+ try {
353
+ const worker = this.env.LOADER.get(id, () => ({
354
+ compatibilityDate: COMPATIBILITY_DATE, mainModule: "run.js", modules: { "run.js": source },
355
+ env: { FATEDB: codemodeApi({ props: { clientId } }) },
356
+ globalOutbound: null,
357
+ }));
358
+ const entry = worker.getEntrypoint();
359
+ if (!isSandboxEntrypoint(entry))
360
+ return finish({ ok: false, error: "the code did not run: sandbox entrypoint missing run()", logs: [] });
361
+ let timer;
362
+ const timeout = new Promise((resolve) => {
363
+ timer = setTimeout(() => resolve({ ok: false, error: `the code ran for more than ${RUN_TIMEOUT_MS / 1000} s`, logs: [] }), RUN_TIMEOUT_MS);
364
+ });
365
+ try {
366
+ return finish(await Promise.race([entry.run(), timeout]));
367
+ }
368
+ finally {
369
+ clearTimeout(timer);
370
+ }
371
+ }
372
+ catch (error) {
373
+ return finish({ ok: false, error: `the code did not run: ${error instanceof Error ? error.message : String(error)}`, logs: [] });
374
+ }
375
+ }
376
+ }
377
+ const RUN_TIMEOUT_MS = 30_000;
378
+ function isCodemodeApiFactory(value) {
379
+ return typeof value === "function";
380
+ }
381
+ function getCodemodeApiFactory(exportsObj) {
382
+ if (typeof exportsObj !== "object" || exportsObj === null || !("CodemodeApi" in exportsObj))
383
+ return null;
384
+ const candidate = exportsObj.CodemodeApi;
385
+ return isCodemodeApiFactory(candidate) ? candidate : null;
386
+ }
387
+ function isSandboxEntrypoint(value) {
388
+ return typeof value === "object" && value !== null && "run" in value && typeof value.run === "function";
389
+ }
390
+ function plain(text, status) {
391
+ return new Response(`${text}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } });
392
+ }
393
+ /** The read-only API agents' code calls from its sandbox, as the client id in its props. */
394
+ export class CodemodeApi extends WorkerEntrypoint {
395
+ #client() {
396
+ return parseIdentity(this.ctx.props).clientId;
397
+ }
398
+ graphs() {
399
+ return forAgents(() => listGraphs(this.env, this.#client()));
400
+ }
401
+ query(graphId, datalog, options) {
402
+ const opt = isRecord(options) ? options : {};
403
+ const consistency = opt["consistency"];
404
+ const limit = opt["limit"];
405
+ return forAgents(async () => {
406
+ const started = performance.now();
407
+ const client = this.#client();
408
+ const graph = typeof graphId === "string" ? graphId : "";
409
+ const source = typeof datalog === "string" ? datalog : "";
410
+ try {
411
+ if (typeof graphId !== "string" || typeof datalog !== "string")
412
+ throw new GraphError(400, "query(datalog) takes a Datalog string");
413
+ if (consistency !== undefined && consistency !== "own-writes" && consistency !== "snapshot")
414
+ throw new GraphError(400, "consistency is own-writes or snapshot");
415
+ if (limit !== undefined && (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 10_000))
416
+ throw new GraphError(400, "limit is a whole number from 1 to 10,000");
417
+ const answer = await runQuery(this.env, client, graphId, datalog, { ...(consistency === undefined ? {} : { consistency }), ...(limit === undefined ? {} : { limit }) });
418
+ recordCall(this.env, this.ctx, {
419
+ graph: graphId, client, operation: "query", outcome: "ok", durationMs: performance.now() - started,
420
+ query: { source: datalog, rows: answer.rows.length, tuples: answer.metrics.tuplesRead },
421
+ });
422
+ return { ...answer, rows: answer.rows.map(values) };
423
+ }
424
+ catch (error) {
425
+ if (graph !== "") {
426
+ recordCall(this.env, this.ctx, {
427
+ graph, client, operation: "query", outcome: outcomeOfError(error), durationMs: performance.now() - started,
428
+ ...(source === "" ? {} : { query: { source, rows: 0, tuples: 0 } }),
429
+ });
430
+ }
431
+ throw error;
432
+ }
433
+ });
434
+ }
435
+ schema(graphId) {
436
+ return forAgents(async () => {
437
+ const started = performance.now();
438
+ const client = this.#client();
439
+ const graph = String(graphId);
440
+ try {
441
+ const answer = await observedSchema(this.env, client, graph);
442
+ recordCall(this.env, this.ctx, { graph, client, operation: "getSchema", outcome: "ok", durationMs: performance.now() - started });
443
+ return answer;
444
+ }
445
+ catch (error) {
446
+ recordCall(this.env, this.ctx, { graph, client, operation: "getSchema", outcome: outcomeOfError(error), durationMs: performance.now() - started });
447
+ throw error;
448
+ }
449
+ });
450
+ }
451
+ status(graphId) {
452
+ return forAgents(() => graphDetail(this.env, this.#client(), String(graphId)));
453
+ }
454
+ entity(graphId, entity) {
455
+ return forAgents(async () => {
456
+ const started = performance.now();
457
+ const client = this.#client();
458
+ const graph = String(graphId);
459
+ try {
460
+ if (typeof entity !== "string")
461
+ throw new GraphError(400, "entity(id) takes an entity id");
462
+ const described = await describeEntity(this.env, client, graph, entity);
463
+ recordCall(this.env, this.ctx, { graph, client, operation: "entity", outcome: "ok", durationMs: performance.now() - started });
464
+ return { ...described, facts: described.facts.map((fact) => ({ field: fact.field, value: toValue(fact.value) })) };
465
+ }
466
+ catch (error) {
467
+ recordCall(this.env, this.ctx, { graph, client, operation: "entity", outcome: outcomeOfError(error), durationMs: performance.now() - started });
468
+ throw error;
469
+ }
470
+ });
471
+ }
472
+ }
473
+ /** A row as agents' code reads it: each value as JavaScript holds it. */
474
+ const values = (row) => Object.fromEntries(Object.entries(row).map(([variable, value]) => [variable, toValue(value)]));
475
+ /** Errors an agent's code can read: what was refused and why, and nothing of storage's internals. */
476
+ async function forAgents(run) {
477
+ try {
478
+ return await run();
479
+ }
480
+ catch (error) {
481
+ if (error instanceof GraphError && error.status < 500)
482
+ throw new Error(error.message);
483
+ if (error instanceof GraphAuthorizationError || error instanceof RangeError)
484
+ throw new Error(error.message);
485
+ throw new Error("storage failed; try again");
486
+ }
487
+ }
@@ -0,0 +1,31 @@
1
+ export type RunResult = Readonly<{
2
+ ok: true;
3
+ result: unknown;
4
+ logs: readonly string[];
5
+ }> | Readonly<{
6
+ ok: false;
7
+ error: string;
8
+ logs: readonly string[];
9
+ }>;
10
+ /** Runs an agent's code in the sandbox, as one client. */
11
+ export type Runner = (code: string) => Promise<RunResult>;
12
+ /** The API the code sees, as TypeScript: the tool's description carries it. */
13
+ export declare const API_TYPES = "declare const fatedb: {\n /** The graphs this connection may read. */\n graphs(): Promise<GraphSummary[]>;\n graph(id: string): {\n /**\n * A Datalog query: atoms field(Entity, Value) joined by shared variables, as in\n * app:name(Task, Name), app:status(Task, \"open\"). A field with a / or # goes in single quotes;\n * strings are JSON strings; numbers are integers (42) or decimals (4.2); variables start\n * with a capital letter. Strings match text, references and dates alike. Comparisons: =, <,\n * <=, >, >=, startsWith, endsWith, contains; = and the rest compare integers and decimals\n * by value. No negation, OR, rules, aggregates or sorting: do those in code. The first\n * `limit` rows (1,000 by default, at most 10,000); truncated says there were more.\n */\n query(\n datalog: string,\n options?: { consistency?: \"own-writes\" | \"snapshot\"; limit?: number },\n ): Promise<{ rows: Row[]; truncated: boolean; watermark: number }>;\n /** Every field of the graph's active facts, and the value types it holds. */\n schema(): Promise<{ fields: { field: string; valueTags: string[] }[]; watermark: number }>;\n /** The graph's partitions, index shards, watermark and how far the index trails. */\n status(): Promise<GraphDetail>;\n /** An entity's facts, the facts whose values reference it, and the names of the entities on both ends. */\n entity(id: string): Promise<{\n id: string;\n facts: { field: string; value: Value }[];\n referencedBy: { field: string; entity: string }[];\n names: Record<string, string>;\n truncated: boolean;\n }>;\n };\n};\n/**\n * A value as JavaScript holds it: text, references (entity ids) and decimals are strings, a\n * decimal with every digit; numbers are bigints; booleans booleans; dates and date-times Dates;\n * bytes Uint8Arrays; lists arrays; maps objects; null is null.\n */\ntype Value = string | bigint | boolean | null | Date | Uint8Array | Value[] | { [key: string]: Value };\n/** Each variable's value: the value of the fact the first atom binding it matched. */\ntype Row = Record<string, Value>;\ntype GraphSummary = {\n id: string;\n partitions: number;\n shards: number;\n facts: number;\n segments: number;\n watermark: number;\n lagMs: number | null;\n updatedAt: number;\n permissions: (\"read\" | \"write\")[];\n};\ntype GraphDetail = GraphSummary & {\n layout: { version: number; eras: { from: number; count: number; since: number }[]; shards: { depth: number; prefix: number }[] } | null;\n};";
14
+ export declare const EXAMPLE = "const [g] = await fatedb.graphs();\nconst { fields } = await fatedb.graph(g.id).schema();\nreturn fields.map((f) => f.field);";
15
+ export declare const EXECUTE: {
16
+ readonly name: "execute";
17
+ readonly title: "Run code against this FateDB instance";
18
+ readonly description: "Runs JavaScript against this FateDB instance and returns what it returns, with anything it logged. Write the body of an async function: await the API below, filter and join in code, and return a small value. It comes back as JSON: bigints as numbers, or as strings of digits past 2^53; Dates as ISO strings; bytes as arrays. The code runs in a sandbox with no network, and the API is read-only.\n\ndeclare const fatedb: {\n /** The graphs this connection may read. */\n graphs(): Promise<GraphSummary[]>;\n graph(id: string): {\n /**\n * A Datalog query: atoms field(Entity, Value) joined by shared variables, as in\n * app:name(Task, Name), app:status(Task, \"open\"). A field with a / or # goes in single quotes;\n * strings are JSON strings; numbers are integers (42) or decimals (4.2); variables start\n * with a capital letter. Strings match text, references and dates alike. Comparisons: =, <,\n * <=, >, >=, startsWith, endsWith, contains; = and the rest compare integers and decimals\n * by value. No negation, OR, rules, aggregates or sorting: do those in code. The first\n * `limit` rows (1,000 by default, at most 10,000); truncated says there were more.\n */\n query(\n datalog: string,\n options?: { consistency?: \"own-writes\" | \"snapshot\"; limit?: number },\n ): Promise<{ rows: Row[]; truncated: boolean; watermark: number }>;\n /** Every field of the graph's active facts, and the value types it holds. */\n schema(): Promise<{ fields: { field: string; valueTags: string[] }[]; watermark: number }>;\n /** The graph's partitions, index shards, watermark and how far the index trails. */\n status(): Promise<GraphDetail>;\n /** An entity's facts, the facts whose values reference it, and the names of the entities on both ends. */\n entity(id: string): Promise<{\n id: string;\n facts: { field: string; value: Value }[];\n referencedBy: { field: string; entity: string }[];\n names: Record<string, string>;\n truncated: boolean;\n }>;\n };\n};\n/**\n * A value as JavaScript holds it: text, references (entity ids) and decimals are strings, a\n * decimal with every digit; numbers are bigints; booleans booleans; dates and date-times Dates;\n * bytes Uint8Arrays; lists arrays; maps objects; null is null.\n */\ntype Value = string | bigint | boolean | null | Date | Uint8Array | Value[] | { [key: string]: Value };\n/** Each variable's value: the value of the fact the first atom binding it matched. */\ntype Row = Record<string, Value>;\ntype GraphSummary = {\n id: string;\n partitions: number;\n shards: number;\n facts: number;\n segments: number;\n watermark: number;\n lagMs: number | null;\n updatedAt: number;\n permissions: (\"read\" | \"write\")[];\n};\ntype GraphDetail = GraphSummary & {\n layout: { version: number; eras: { from: number; count: number; since: number }[]; shards: { depth: number; prefix: number }[] } | null;\n};\n\nExample:\nconst [g] = await fatedb.graphs();\nconst { fields } = await fatedb.graph(g.id).schema();\nreturn fields.map((f) => f.field);";
19
+ readonly annotations: {
20
+ readonly readOnlyHint: true;
21
+ readonly destructiveHint: false;
22
+ readonly idempotentHint: true;
23
+ readonly openWorldHint: false;
24
+ };
25
+ };
26
+ /** Answers one MCP request via Cloudflare's Agents SDK stateless MCP handler. */
27
+ export declare function handleMcp(request: Request, env: unknown, ctx: ExecutionContext, run: Runner, version: string): Promise<Response>;
28
+ /** The agent's code as a function body: without Markdown fences, and an async arrow function called. */
29
+ export declare function normalizeCode(code: string): string;
30
+ /** The sandbox's module: the API over the binding, a console that keeps what is logged, and the code. */
31
+ export declare function sandboxModule(code: string): string;