@chronosdb/forkbase 0.0.0-stage → 0.8.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 (4) hide show
  1. package/README.md +25 -2
  2. package/index.d.ts +192 -0
  3. package/index.mjs +407 -0
  4. package/package.json +16 -4
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # forkbase
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Forkbase for TypeScript and JavaScript: agents' runs (a world per run, propose, review) and jobs, with no
4
+ dependencies (Node 18+, browsers, Deno, Bun). Tables, auth, storage and realtime speak Supabase's APIs:
5
+ `client.supabase()` returns a supabase-js client for them (install `@supabase/supabase-js`).
6
+
7
+ ```ts
8
+ import { createClient } from "@chronosdb/forkbase";
9
+
10
+ const fb = createClient("https://api.example.com", process.env.FORKBASE_AGENT_TOKEN!);
11
+ const { outcome } = await fb.agents.withRun("close stale carts", async (run) => {
12
+ await run.sql("update carts set closed = true where updated_at < now() - interval '30 days'");
13
+ });
14
+ if (outcome.status === "held") console.log("a person reviews it:", outcome.reasons);
15
+ ```
16
+
17
+ - `fb.agents`: `run(intent)`, `withRun(intent, fn)` (proposes on success, discards on a throw), `get`, `listRuns`;
18
+ with the service key also `create`, `approve`, `reject`, `undo`.
19
+ - `run`: `sql(query, params)`, `changes()`, `propose()` (`merged`, `held` or `conflict`; never throws for those),
20
+ `discard()`, `refresh()`.
21
+ - `fb.jobs` (service key): `deploy`, `functions`, `invoke(name, payload, { wait, delayS, runAt, idempotencyKey })`,
22
+ `get`, `list`, `cancel`, `retry`, `schedule`.
23
+ - Inside a job: `step(name, fn)`, `sleep(name, seconds)`, `sql(query, params)`, `context()`. The job runtime ships
24
+ this module, so functions import it without installing it.
25
+
26
+ Errors are `ForkbaseError` with `status`, `code` and `body`.
package/index.d.ts ADDED
@@ -0,0 +1,192 @@
1
+ // Forkbase for TypeScript and JavaScript.
2
+
3
+ export class ForkbaseError extends Error {
4
+ status: number;
5
+ code: string;
6
+ body: unknown;
7
+ }
8
+
9
+ export interface SqlResult {
10
+ columns: string[];
11
+ rows: unknown[][];
12
+ [k: string]: unknown;
13
+ }
14
+
15
+ export interface ProposeOutcome {
16
+ status: "merged" | "held" | "conflict" | string;
17
+ reasons?: string[];
18
+ [k: string]: unknown;
19
+ }
20
+
21
+ export interface RunData {
22
+ id: string;
23
+ status: string;
24
+ agent?: string;
25
+ intent?: string;
26
+ token?: string;
27
+ database_url?: string;
28
+ [k: string]: unknown;
29
+ }
30
+
31
+ export interface RunOptions {
32
+ /** With the service key: whose run it is. */
33
+ agent?: string;
34
+ ttlSeconds?: number;
35
+ meta?: Record<string, unknown>;
36
+ /** A signed-in user's access token (or `{ user_token }`): the run sees what that user may see. */
37
+ actAs?: string | { user_token: string };
38
+ /** A merge policy's name. */
39
+ policy?: string;
40
+ }
41
+
42
+ /** A run: a world of its own where an agent reads and writes; nothing reaches the data until `propose()`. */
43
+ export class Run {
44
+ id: string;
45
+ status: string;
46
+ token?: string;
47
+ databaseUrl?: string;
48
+ data: RunData;
49
+ sql(query: string, params?: unknown[]): Promise<SqlResult>;
50
+ changes(opts?: { limit?: number }): Promise<any>;
51
+ propose(): Promise<ProposeOutcome>;
52
+ discard(): Promise<any>;
53
+ refresh(): Promise<this>;
54
+ }
55
+
56
+ export interface Agents {
57
+ create(name: string, opts?: { policy?: string }): Promise<any>;
58
+ list(): Promise<any>;
59
+ run(intent: string, opts?: RunOptions): Promise<Run>;
60
+ withRun<T>(intent: string, fn: (run: Run) => Promise<T> | T, opts?: RunOptions): Promise<{ run: Run; result: T; outcome: ProposeOutcome }>;
61
+ get(id: string): Promise<Run>;
62
+ listRuns(opts?: { status?: string; limit?: number }): Promise<any>;
63
+ approve(id: string): Promise<any>;
64
+ reject(id: string, reason?: string): Promise<any>;
65
+ undo(id: string, opts?: { skipChanged?: boolean }): Promise<any>;
66
+ }
67
+
68
+ export interface Jobs {
69
+ deploy(fn: {
70
+ name: string;
71
+ files?: Record<string, string>;
72
+ source?: string;
73
+ entry?: string;
74
+ env?: Record<string, string>;
75
+ timeout_s?: number;
76
+ memory_mb?: number;
77
+ max_attempts?: number;
78
+ concurrency?: number;
79
+ agent?: string;
80
+ [k: string]: unknown;
81
+ }): Promise<any>;
82
+ functions(): Promise<any>;
83
+ invoke(name: string, payload?: unknown, opts?: { delayS?: number; runAt?: number | Date; idempotencyKey?: string; wait?: number }): Promise<any>;
84
+ get(id: string): Promise<any>;
85
+ list(opts?: { fn?: string; status?: string; before?: number; limit?: number }): Promise<any>;
86
+ cancel(id: string): Promise<any>;
87
+ retry(id: string): Promise<any>;
88
+ schedule(fn: string, cron: string, payload?: unknown): Promise<any>;
89
+ }
90
+
91
+ /** Whom a chat call is for: a person's access token (with the anon key), or their id (with the service key). */
92
+ export interface ChatWho {
93
+ token?: string;
94
+ userId?: string;
95
+ }
96
+
97
+ export interface ChatMessage {
98
+ id: string;
99
+ thread_id: string;
100
+ seq: number;
101
+ role: "user" | "assistant";
102
+ content: string;
103
+ /** An assistant message's: working, done, held (its changes wait for review), rejected, failed, expired. */
104
+ status: string;
105
+ job_id: string | null;
106
+ run_id: string | null;
107
+ error: string | null;
108
+ created_at: number;
109
+ updated_at: number;
110
+ }
111
+
112
+ export interface ChatThread {
113
+ id: string;
114
+ agent: string;
115
+ user_id: string;
116
+ title: string | null;
117
+ created_at: number;
118
+ updated_at: number;
119
+ messages?: ChatMessage[];
120
+ }
121
+
122
+ export interface Chat {
123
+ createThread(agent: string, opts?: ChatWho & { title?: string }): Promise<ChatThread>;
124
+ threads(opts?: ChatWho & { agent?: string }): Promise<{ threads: ChatThread[] }>;
125
+ thread(id: string, who?: ChatWho): Promise<ChatThread>;
126
+ deleteThread(id: string, who?: ChatWho): Promise<null>;
127
+ /** Without `onEvent`, `{message, reply}` at once; with it, the turn streams and this resolves with the reply. */
128
+ send(threadId: string, content: string, opts?: ChatWho): Promise<{ message: ChatMessage; reply: ChatMessage }>;
129
+ send(threadId: string, content: string, opts: ChatWho & { onEvent: (name: "message" | "text" | "tool" | "done" | "error", data: any) => void }): Promise<ChatMessage>;
130
+ }
131
+
132
+ export class ForkbaseClient {
133
+ url: string;
134
+ key: string;
135
+ agents: Agents;
136
+ jobs: Jobs;
137
+ chat: Chat;
138
+ constructor(url: string, key: string, options?: ClientOptions);
139
+ request(method: string, path: string, body?: unknown): Promise<any>;
140
+ /** A supabase-js client for tables, auth, storage and realtime (needs `@supabase/supabase-js`). */
141
+ supabase(options?: unknown): Promise<any>;
142
+ }
143
+
144
+ export interface ClientOptions {
145
+ fetch?: typeof fetch;
146
+ headers?: Record<string, string>;
147
+ }
148
+
149
+ export function createClient(url: string, key: string, options?: ClientOptions): ForkbaseClient;
150
+
151
+ // ---- inside a job ----
152
+
153
+ /** Thrown by `sleep` to end this attempt until the sleep is over. */
154
+ export class Suspend extends Error {
155
+ until: number;
156
+ }
157
+ export function step<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
158
+ export function sleep(name: string, seconds: number): Promise<void>;
159
+ export function sql(query: string, params?: unknown[]): Promise<SqlResult>;
160
+ /** Who called a function over HTTP. */
161
+ export interface Caller {
162
+ role: "anon" | "authenticated" | "service_role";
163
+ user_id: string | null;
164
+ email: string | null;
165
+ claims: Record<string, unknown> | null;
166
+ }
167
+ /** The request of a call over HTTP (the caller's keys and cookies left out). */
168
+ export interface FunctionRequest {
169
+ method: string;
170
+ /** after `/functions/v1/<name>`: "/" or "/a/b" */
171
+ path: string;
172
+ query: Record<string, string>;
173
+ headers: Record<string, string>;
174
+ }
175
+ /** The answer of a function called over HTTP, with a status and headers. */
176
+ export function respond(body: unknown, init?: { status?: number; headers?: Record<string, string> }): { $forkbase_response: unknown };
177
+ export interface Context<P = any> {
178
+ payload: P;
179
+ job: { id: string; attempt: number; function: string };
180
+ run: { id: string; database_url: string; token: string } | null;
181
+ /** A call over HTTP's request; null for other jobs. */
182
+ request: FunctionRequest | null;
183
+ /** A call over HTTP's caller; null for other jobs. */
184
+ caller: Caller | null;
185
+ /** Calls this server as the caller: `ctx.call("GET", "/rest/v1/todos?select=*")`, under their row-level security. */
186
+ call<T = any>(method: string, path: string, body?: unknown): Promise<T>;
187
+ url: string;
188
+ step: typeof step;
189
+ sleep: typeof sleep;
190
+ sql: typeof sql;
191
+ }
192
+ export function context<P = any>(payload?: P, request?: unknown): Context<P>;
package/index.mjs ADDED
@@ -0,0 +1,407 @@
1
+ // Forkbase for TypeScript and JavaScript, with no dependencies (fetch is built in from Node 18, and in browsers,
2
+ // Deno and Bun).
3
+ //
4
+ // - `createClient(url, key)`: agents' runs (each a world of its own; propose; review) and jobs. The key is the
5
+ // service_role key (servers only) or an agent's `fba_` token. Tables, auth, storage and realtime speak Supabase's
6
+ // APIs: `client.supabase()` gives a supabase-js client for them (install `@supabase/supabase-js`).
7
+ // - `client.chat`: threads with a declared agent, as a person (their access token, with the anon key) or for one
8
+ // (`userId`, with the service key).
9
+ // - Inside a job (a function Forkbase runs), `step`, `sleep`, `sql` and `context` are the job's own helpers.
10
+
11
+ export class ForkbaseError extends Error {
12
+ constructor(status, code, message, body) {
13
+ super(message);
14
+ this.name = "ForkbaseError";
15
+ this.status = status;
16
+ this.code = code;
17
+ this.body = body;
18
+ }
19
+ }
20
+
21
+ const enc = encodeURIComponent;
22
+
23
+ async function request(base, token, method, path, body, fetchImpl = globalThis.fetch, extra = {}) {
24
+ const headers = { authorization: `Bearer ${token}`, ...extra };
25
+ if (token && !String(token).startsWith("fb")) headers.apikey = token;
26
+ if (body !== undefined) headers["content-type"] = "application/json";
27
+ const res = await fetchImpl(base + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
28
+ const text = await res.text();
29
+ let data = text;
30
+ try {
31
+ data = text ? JSON.parse(text) : null;
32
+ } catch {}
33
+ return { status: res.status, ok: res.ok, data };
34
+ }
35
+
36
+ function fail(method, path, r) {
37
+ const d = r.data && typeof r.data === "object" ? r.data : {};
38
+ return new ForkbaseError(r.status, d.code || d.error || "error", `${method} ${path}: ${r.status} ${d.message || d.error_description || r.data || ""}`.trim(), r.data);
39
+ }
40
+
41
+ /** A run: a world of its own where an agent reads and writes; nothing reaches the data until `propose()`. */
42
+ export class Run {
43
+ constructor(client, data) {
44
+ this._client = client;
45
+ this._set(data);
46
+ }
47
+ _set(data) {
48
+ this.data = data;
49
+ this.id = data.id;
50
+ this.status = data.status;
51
+ if (data.token) this.token = data.token;
52
+ if (data.database_url) this.databaseUrl = data.database_url;
53
+ }
54
+ async _call(method, path, body) {
55
+ return this._client._do(method, `/agents/v1/runs/${enc(this.id)}${path}`, body, this.token);
56
+ }
57
+ /** One SQL statement in this run's world: `{ columns, rows, ... }`. */
58
+ sql(query, params = []) {
59
+ return this._call("POST", "/sql", { sql: query, params });
60
+ }
61
+ /** The rows this run inserted, updated and deleted. */
62
+ changes({ limit } = {}) {
63
+ return this._call("GET", `/changes${limit ? `?limit=${limit}` : ""}`);
64
+ }
65
+ /**
66
+ * Asks to merge: `{ status: "merged" }`, `{ status: "held", reasons }` (a person reviews it) or
67
+ * `{ status: "conflict" }` (the data changed underneath; start a new run). Never throws for those three.
68
+ */
69
+ async propose() {
70
+ const r = await this._client._raw("POST", `/agents/v1/runs/${enc(this.id)}/propose`, undefined, this.token);
71
+ if (r.status === 409) return { status: "conflict", ...(r.data || {}) };
72
+ if (!r.ok) throw fail("POST", "propose", r);
73
+ this.status = r.data.status;
74
+ return r.data;
75
+ }
76
+ /** Drops the world and everything in it. */
77
+ discard() {
78
+ return this._call("POST", "/discard");
79
+ }
80
+ /** The run as it is now (status, outcome). */
81
+ async refresh() {
82
+ this._set({ ...(await this._client._do("GET", `/agents/v1/runs/${enc(this.id)}`, undefined, this.token)), token: this.token, database_url: this.databaseUrl });
83
+ return this;
84
+ }
85
+ }
86
+
87
+ class Agents {
88
+ constructor(c) {
89
+ this._c = c;
90
+ }
91
+ /** Makes an agent (service key): `{ name, token, ... }`, its `fba_` token shown once. */
92
+ create(name, { policy } = {}) {
93
+ return this._c._do("POST", "/agents/v1/agents", { name, policy });
94
+ }
95
+ list() {
96
+ return this._c._do("GET", "/agents/v1/agents");
97
+ }
98
+ /** Starts a run. With the service key, `agent` names whose run it is. */
99
+ async run(intent, { agent, ttlSeconds, meta, actAs, policy } = {}) {
100
+ const body = { intent };
101
+ if (agent) body.agent = agent;
102
+ if (ttlSeconds) body.ttl_seconds = ttlSeconds;
103
+ if (meta) body.meta = meta;
104
+ if (actAs) body.act_as = typeof actAs === "string" ? { user_token: actAs } : actAs;
105
+ if (policy) body.policy = policy;
106
+ return new Run(this._c, await this._c._do("POST", "/agents/v1/runs", body));
107
+ }
108
+ /**
109
+ * Runs `fn(run)` in a new run, then proposes it; if `fn` throws, discards the run and throws again.
110
+ * Returns `{ run, result, outcome }`, `outcome` being what `propose()` answered.
111
+ */
112
+ async withRun(intent, fn, opts = {}) {
113
+ const run = await this.run(intent, opts);
114
+ let result;
115
+ try {
116
+ result = await fn(run);
117
+ } catch (e) {
118
+ await run.discard().catch(() => {});
119
+ throw e;
120
+ }
121
+ const outcome = await run.propose();
122
+ return { run, result, outcome };
123
+ }
124
+ async get(id) {
125
+ return new Run(this._c, await this._c._do("GET", `/agents/v1/runs/${enc(id)}`));
126
+ }
127
+ listRuns({ status, limit } = {}) {
128
+ const q = new URLSearchParams();
129
+ if (status) q.set("status", status);
130
+ if (limit) q.set("limit", String(limit));
131
+ return this._c._do("GET", `/agents/v1/runs${q.size ? `?${q}` : ""}`);
132
+ }
133
+ /** Approves a held run (service key: a person's decision, not an agent's). */
134
+ approve(id) {
135
+ return this._c._do("POST", `/agents/v1/runs/${enc(id)}/approve`);
136
+ }
137
+ reject(id, reason) {
138
+ return this._c._do("POST", `/agents/v1/runs/${enc(id)}/reject`, { reason });
139
+ }
140
+ /** Undoes a merged run's changes, row by row. */
141
+ undo(id, { skipChanged } = {}) {
142
+ return this._c._do("POST", `/agents/v1/runs/${enc(id)}/undo`, { skip_changed: !!skipChanged });
143
+ }
144
+ }
145
+
146
+ class Jobs {
147
+ constructor(c) {
148
+ this._c = c;
149
+ }
150
+ /** Deploys a function: `{ name, files: { "index.ts": "..." } | source, entry, env, timeout_s, memory_mb, max_attempts, concurrency, agent }`. */
151
+ deploy(fn) {
152
+ return this._c._do("POST", "/jobs/v1/functions", fn);
153
+ }
154
+ functions() {
155
+ return this._c._do("GET", "/jobs/v1/functions");
156
+ }
157
+ /** Starts a job: `{ delayS, runAt, idempotencyKey, wait }` (`wait`: seconds, up to 60, to wait for it to end). */
158
+ invoke(name, payload = null, { delayS, runAt, idempotencyKey, wait } = {}) {
159
+ const body = { payload };
160
+ if (delayS !== undefined) body.delay_s = delayS;
161
+ if (runAt !== undefined) body.run_at = runAt instanceof Date ? runAt.getTime() : runAt;
162
+ if (idempotencyKey) body.idempotency_key = idempotencyKey;
163
+ return this._c._do("POST", `/jobs/v1/functions/${enc(name)}/invoke${wait ? `?wait=${wait}` : ""}`, body);
164
+ }
165
+ get(id) {
166
+ return this._c._do("GET", `/jobs/v1/jobs/${enc(id)}`);
167
+ }
168
+ list({ fn, status, before, limit } = {}) {
169
+ const q = new URLSearchParams();
170
+ if (fn) q.set("function", fn);
171
+ if (status) q.set("status", status);
172
+ if (before) q.set("before", String(before));
173
+ if (limit) q.set("limit", String(limit));
174
+ return this._c._do("GET", `/jobs/v1/jobs${q.size ? `?${q}` : ""}`);
175
+ }
176
+ cancel(id) {
177
+ return this._c._do("POST", `/jobs/v1/jobs/${enc(id)}/cancel`);
178
+ }
179
+ retry(id) {
180
+ return this._c._do("POST", `/jobs/v1/jobs/${enc(id)}/retry`);
181
+ }
182
+ /** A cron schedule (UTC) for a function. */
183
+ schedule(fn, cron, payload = null) {
184
+ return this._c._do("POST", "/jobs/v1/schedules", { function: fn, cron, payload });
185
+ }
186
+ }
187
+
188
+ class Chat {
189
+ constructor(c) {
190
+ this._c = c;
191
+ }
192
+ // as a person (`token`: their access token, with the client's anon key) or for one (`userId`, with the service key)
193
+ async _call(method, path, body, who = {}, accept) {
194
+ const { token, userId } = who;
195
+ const headers = { apikey: this._c.key, authorization: `Bearer ${token || this._c.key}`, ...this._c._headers };
196
+ if (accept) headers.accept = accept;
197
+ let p = path;
198
+ if (userId && method === "GET") p += `${p.includes("?") ? "&" : "?"}user_id=${enc(userId)}`;
199
+ if (userId && method === "DELETE") p += `${p.includes("?") ? "&" : "?"}user_id=${enc(userId)}`;
200
+ if (userId && body && typeof body === "object") body = { ...body, user_id: userId };
201
+ if (body !== undefined) headers["content-type"] = "application/json";
202
+ const res = await this._c._fetch(this._c.url + p, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
203
+ if (accept && res.ok) return res;
204
+ const text = await res.text();
205
+ let data = text;
206
+ try {
207
+ data = text ? JSON.parse(text) : null;
208
+ } catch {}
209
+ if (!res.ok) throw fail(method, p, { status: res.status, data });
210
+ return data;
211
+ }
212
+ /** Starts a thread with a declared agent whose file says `chat:`. */
213
+ createThread(agent, { title, ...who } = {}) {
214
+ return this._call("POST", "/chat/v1/threads", { agent, title }, who);
215
+ }
216
+ threads({ agent, ...who } = {}) {
217
+ return this._call("GET", `/chat/v1/threads${agent ? `?agent=${enc(agent)}` : ""}`, undefined, who);
218
+ }
219
+ /** A thread with its messages. */
220
+ thread(id, who = {}) {
221
+ return this._call("GET", `/chat/v1/threads/${enc(id)}`, undefined, who);
222
+ }
223
+ deleteThread(id, who = {}) {
224
+ return this._call("DELETE", `/chat/v1/threads/${enc(id)}`, undefined, who);
225
+ }
226
+ /**
227
+ * Sends a message. Without `onEvent`: `{ message, reply }` at once (the reply is `working`; read it from the thread).
228
+ * With `onEvent(name, data)`: the turn streams (`message`, `text`, `tool`, `done`) and this resolves with the reply
229
+ * as `done` gave it (`done`, `held`, `failed`, ...).
230
+ */
231
+ async send(threadId, content, { onEvent, ...who } = {}) {
232
+ const path = `/chat/v1/threads/${enc(threadId)}/messages`;
233
+ if (!onEvent) return this._call("POST", path, { content }, who);
234
+ const res = await this._call("POST", path, { content }, who, "text/event-stream");
235
+ return readEvents(res, onEvent);
236
+ }
237
+ }
238
+
239
+ /** Reads an SSE body, calling `onEvent(name, data)`; resolves with the `done` event's data. */
240
+ async function readEvents(res, onEvent) {
241
+ const reader = res.body.getReader();
242
+ const dec = new TextDecoder();
243
+ let buf = "";
244
+ let last = null;
245
+ for (;;) {
246
+ const { value, done } = await reader.read();
247
+ if (value) buf += dec.decode(value, { stream: true });
248
+ let i;
249
+ while ((i = buf.indexOf("\n\n")) >= 0) {
250
+ const block = buf.slice(0, i);
251
+ buf = buf.slice(i + 2);
252
+ let name = "message";
253
+ let data = "";
254
+ for (const line of block.split("\n")) {
255
+ if (line.startsWith("event:")) name = line.slice(6).trim();
256
+ else if (line.startsWith("data:")) data += line.slice(5).trimStart();
257
+ }
258
+ if (!data) continue;
259
+ let v = data;
260
+ try {
261
+ v = JSON.parse(data);
262
+ } catch {}
263
+ onEvent(name, v);
264
+ if (name === "done") last = v;
265
+ if (name === "error") throw new ForkbaseError(500, "stream", v && v.message ? v.message : String(v), v);
266
+ }
267
+ if (done) return last;
268
+ }
269
+ }
270
+
271
+ export class ForkbaseClient {
272
+ constructor(url, key, { fetch: fetchImpl, headers } = {}) {
273
+ if (!url) throw new Error("createClient: the server's URL");
274
+ if (!key) throw new Error("createClient: a key (service_role, an agent's fba_ token, or anon for chat)");
275
+ this.url = String(url).replace(/\/+$/, "");
276
+ this.key = key;
277
+ this._fetch = fetchImpl || globalThis.fetch.bind(globalThis);
278
+ this._headers = headers || {};
279
+ this.agents = new Agents(this);
280
+ this.jobs = new Jobs(this);
281
+ this.chat = new Chat(this);
282
+ }
283
+ _raw(method, path, body, token) {
284
+ return request(this.url, token || this.key, method, path, body, this._fetch, this._headers);
285
+ }
286
+ async _do(method, path, body, token) {
287
+ const r = await this._raw(method, path, body, token);
288
+ if (!r.ok) throw fail(method, path, r);
289
+ return r.data;
290
+ }
291
+ /** Any route: `request("GET", "/platform/v1/project")`. */
292
+ request(method, path, body) {
293
+ return this._do(method, path, body);
294
+ }
295
+ /** A supabase-js client for tables, auth, storage and realtime (needs `@supabase/supabase-js`). */
296
+ async supabase(options) {
297
+ const { createClient } = await import("@supabase/supabase-js");
298
+ return createClient(this.url, this.key, options);
299
+ }
300
+ }
301
+
302
+ /** A client for a Forkbase server. */
303
+ export function createClient(url, key, options) {
304
+ return new ForkbaseClient(url, key, options);
305
+ }
306
+
307
+ // ---- inside a job ----------------------------------------------------------------------------------------------
308
+
309
+ const env = (typeof process !== "undefined" && process.env) || {};
310
+
311
+ /** Thrown by `sleep` to end this attempt until the sleep is over; Forkbase starts the job again then. */
312
+ export class Suspend extends Error {
313
+ constructor(until) {
314
+ super(`sleeping until ${new Date(until).toISOString()}`);
315
+ this.until = until;
316
+ }
317
+ }
318
+
319
+ function inJob(what) {
320
+ if (!env.FORKBASE_JOB_TOKEN) throw new Error(`${what}() works inside a Forkbase job`);
321
+ }
322
+
323
+ async function self(method, path, body) {
324
+ const r = await request(env.FORKBASE_URL, env.FORKBASE_JOB_TOKEN, method, path, body);
325
+ if (!r.ok && r.status !== 404) throw fail(method, path, r);
326
+ return r;
327
+ }
328
+
329
+ /** Runs `fn` once per job: on a retry, a step that finished returns what it returned then. Results must be JSON. */
330
+ export async function step(name, fn) {
331
+ inJob("step");
332
+ const path = `/jobs/v1/self/steps/${enc(name)}`;
333
+ const got = await self("GET", path);
334
+ if (got.status === 200) return got.data.result;
335
+ const result = await fn();
336
+ await self("PUT", path, { result: result === undefined ? null : result });
337
+ return result;
338
+ }
339
+
340
+ /** Ends this attempt and starts the job again after `seconds` (no process waits meanwhile). Steps before it stay done. */
341
+ export async function sleep(name, seconds) {
342
+ inJob("sleep");
343
+ const path = `/jobs/v1/self/steps/${enc(`sleep:${name}`)}`;
344
+ const got = await self("GET", path);
345
+ let until;
346
+ if (got.status === 200) until = got.data.result.until;
347
+ else {
348
+ until = Date.now() + Math.max(0, seconds) * 1000;
349
+ await self("PUT", path, { result: { until } });
350
+ }
351
+ if (Date.now() < until) throw new Suspend(until);
352
+ }
353
+
354
+ /** SQL in the job's world (functions deployed with an agent): `{ columns, rows, ... }`. */
355
+ export async function sql(query, params = []) {
356
+ const run = env.FORKBASE_RUN_ID;
357
+ if (!run) throw new Error("sql() needs a function deployed with an agent: its jobs work in a world");
358
+ const r = await request(env.FORKBASE_URL, env.FORKBASE_RUN_TOKEN, "POST", `/agents/v1/runs/${enc(run)}/sql`, { sql: query, params });
359
+ if (!r.ok) throw fail("POST", "sql", r);
360
+ return r.data;
361
+ }
362
+
363
+ /** The job: its payload (the runner passes it), ids, attempt, its world (or null), and the helpers above. */
364
+ let jobPayload = null;
365
+
366
+ /** A function called over HTTP answers with this to set the status and headers: `return respond({ made: 1 }, { status: 201 })`. */
367
+ export function respond(body, { status = 200, headers = {} } = {}) {
368
+ return { $forkbase_response: { status, headers, body: body === undefined ? null : body } };
369
+ }
370
+
371
+ /** Calls this server as the app's caller (a call over HTTP): their key and token, their grants and row-level security. */
372
+ async function callAsCaller(method, path, body) {
373
+ const key = env.FORKBASE_CALLER_APIKEY;
374
+ if (!key) throw new Error("ctx.call() works in a call over HTTP from an app (the service key's calls have no caller to act as)");
375
+ const headers = { apikey: key, authorization: `Bearer ${env.FORKBASE_CALLER_TOKEN || key}` };
376
+ if (body !== undefined) headers["content-type"] = "application/json";
377
+ const res = await fetch(env.FORKBASE_URL + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
378
+ const text = await res.text();
379
+ let data = text;
380
+ try {
381
+ data = text ? JSON.parse(text) : null;
382
+ } catch {}
383
+ const r = { status: res.status, ok: res.ok, data };
384
+ if (!r.ok) throw fail(method, path, r);
385
+ return r.data;
386
+ }
387
+
388
+ let jobRequest = null;
389
+
390
+ export function context(payload, request) {
391
+ inJob("context");
392
+ if (payload !== undefined) jobPayload = payload;
393
+ if (request !== undefined) jobRequest = request;
394
+ const run = env.FORKBASE_RUN_ID ? { id: env.FORKBASE_RUN_ID, database_url: env.DATABASE_URL, token: env.FORKBASE_RUN_TOKEN } : null;
395
+ return {
396
+ payload: jobPayload,
397
+ job: { id: env.FORKBASE_JOB_ID, attempt: Number(env.FORKBASE_ATTEMPT), function: env.FORKBASE_FUNCTION },
398
+ run,
399
+ request: jobRequest ? { method: jobRequest.method, path: jobRequest.path, query: jobRequest.query, headers: jobRequest.headers } : null,
400
+ caller: jobRequest ? jobRequest.caller : null,
401
+ call: callAsCaller,
402
+ url: env.FORKBASE_URL,
403
+ step,
404
+ sleep,
405
+ sql,
406
+ };
407
+ }
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@chronosdb/forkbase",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "description": "Forkbase for TypeScript and JavaScript: agents' runs (worlds, propose, review), jobs, and the job runtime's helpers. Tables, auth, storage and realtime work with supabase-js.",
5
+ "type": "module",
6
+ "main": "./index.mjs",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": { "types": "./index.d.ts", "default": "./index.mjs" }
10
+ },
11
+ "files": ["index.mjs", "index.d.ts", "README.md"],
12
+ "engines": { "node": ">=18" },
13
+ "peerDependencies": { "@supabase/supabase-js": "^2" },
14
+ "peerDependenciesMeta": { "@supabase/supabase-js": { "optional": true } },
15
+ "license": "FSL-1.1-ALv2",
16
+ "homepage": "https://chronos.2090.tech/forkbase",
17
+ "keywords": ["forkbase", "agents", "database", "mcp", "supabase"]
18
+ }