@chronosdb/forkbase 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +25 -2
  3. package/index.d.ts +127 -0
  4. package/index.mjs +293 -0
  5. package/package.json +16 -4
package/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-ALv2
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Abhishek DG
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
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,127 @@
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
+ export class ForkbaseClient {
92
+ url: string;
93
+ key: string;
94
+ agents: Agents;
95
+ jobs: Jobs;
96
+ constructor(url: string, key: string, options?: ClientOptions);
97
+ request(method: string, path: string, body?: unknown): Promise<any>;
98
+ /** A supabase-js client for tables, auth, storage and realtime (needs `@supabase/supabase-js`). */
99
+ supabase(options?: unknown): Promise<any>;
100
+ }
101
+
102
+ export interface ClientOptions {
103
+ fetch?: typeof fetch;
104
+ headers?: Record<string, string>;
105
+ }
106
+
107
+ export function createClient(url: string, key: string, options?: ClientOptions): ForkbaseClient;
108
+
109
+ // ---- inside a job ----
110
+
111
+ /** Thrown by `sleep` to end this attempt until the sleep is over. */
112
+ export class Suspend extends Error {
113
+ until: number;
114
+ }
115
+ export function step<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
116
+ export function sleep(name: string, seconds: number): Promise<void>;
117
+ export function sql(query: string, params?: unknown[]): Promise<SqlResult>;
118
+ export interface Context<P = any> {
119
+ payload: P;
120
+ job: { id: string; attempt: number; function: string };
121
+ run: { id: string; database_url: string; token: string } | null;
122
+ url: string;
123
+ step: typeof step;
124
+ sleep: typeof sleep;
125
+ sql: typeof sql;
126
+ }
127
+ export function context<P = any>(payload?: P): Context<P>;
package/index.mjs ADDED
@@ -0,0 +1,293 @@
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
+ // - Inside a job (a function Forkbase runs), `step`, `sleep`, `sql` and `context` are the job's own helpers.
8
+
9
+ export class ForkbaseError extends Error {
10
+ constructor(status, code, message, body) {
11
+ super(message);
12
+ this.name = "ForkbaseError";
13
+ this.status = status;
14
+ this.code = code;
15
+ this.body = body;
16
+ }
17
+ }
18
+
19
+ const enc = encodeURIComponent;
20
+
21
+ async function request(base, token, method, path, body, fetchImpl = globalThis.fetch, extra = {}) {
22
+ const headers = { authorization: `Bearer ${token}`, ...extra };
23
+ if (token && !String(token).startsWith("fb")) headers.apikey = token;
24
+ if (body !== undefined) headers["content-type"] = "application/json";
25
+ const res = await fetchImpl(base + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
26
+ const text = await res.text();
27
+ let data = text;
28
+ try {
29
+ data = text ? JSON.parse(text) : null;
30
+ } catch {}
31
+ return { status: res.status, ok: res.ok, data };
32
+ }
33
+
34
+ function fail(method, path, r) {
35
+ const d = r.data && typeof r.data === "object" ? r.data : {};
36
+ return new ForkbaseError(r.status, d.code || d.error || "error", `${method} ${path}: ${r.status} ${d.message || d.error_description || r.data || ""}`.trim(), r.data);
37
+ }
38
+
39
+ /** A run: a world of its own where an agent reads and writes; nothing reaches the data until `propose()`. */
40
+ export class Run {
41
+ constructor(client, data) {
42
+ this._client = client;
43
+ this._set(data);
44
+ }
45
+ _set(data) {
46
+ this.data = data;
47
+ this.id = data.id;
48
+ this.status = data.status;
49
+ if (data.token) this.token = data.token;
50
+ if (data.database_url) this.databaseUrl = data.database_url;
51
+ }
52
+ async _call(method, path, body) {
53
+ return this._client._do(method, `/agents/v1/runs/${enc(this.id)}${path}`, body, this.token);
54
+ }
55
+ /** One SQL statement in this run's world: `{ columns, rows, ... }`. */
56
+ sql(query, params = []) {
57
+ return this._call("POST", "/sql", { sql: query, params });
58
+ }
59
+ /** The rows this run inserted, updated and deleted. */
60
+ changes({ limit } = {}) {
61
+ return this._call("GET", `/changes${limit ? `?limit=${limit}` : ""}`);
62
+ }
63
+ /**
64
+ * Asks to merge: `{ status: "merged" }`, `{ status: "held", reasons }` (a person reviews it) or
65
+ * `{ status: "conflict" }` (the data changed underneath; start a new run). Never throws for those three.
66
+ */
67
+ async propose() {
68
+ const r = await this._client._raw("POST", `/agents/v1/runs/${enc(this.id)}/propose`, undefined, this.token);
69
+ if (r.status === 409) return { status: "conflict", ...(r.data || {}) };
70
+ if (!r.ok) throw fail("POST", "propose", r);
71
+ this.status = r.data.status;
72
+ return r.data;
73
+ }
74
+ /** Drops the world and everything in it. */
75
+ discard() {
76
+ return this._call("POST", "/discard");
77
+ }
78
+ /** The run as it is now (status, outcome). */
79
+ async refresh() {
80
+ this._set({ ...(await this._client._do("GET", `/agents/v1/runs/${enc(this.id)}`, undefined, this.token)), token: this.token, database_url: this.databaseUrl });
81
+ return this;
82
+ }
83
+ }
84
+
85
+ class Agents {
86
+ constructor(c) {
87
+ this._c = c;
88
+ }
89
+ /** Makes an agent (service key): `{ name, token, ... }`, its `fba_` token shown once. */
90
+ create(name, { policy } = {}) {
91
+ return this._c._do("POST", "/agents/v1/agents", { name, policy });
92
+ }
93
+ list() {
94
+ return this._c._do("GET", "/agents/v1/agents");
95
+ }
96
+ /** Starts a run. With the service key, `agent` names whose run it is. */
97
+ async run(intent, { agent, ttlSeconds, meta, actAs, policy } = {}) {
98
+ const body = { intent };
99
+ if (agent) body.agent = agent;
100
+ if (ttlSeconds) body.ttl_seconds = ttlSeconds;
101
+ if (meta) body.meta = meta;
102
+ if (actAs) body.act_as = typeof actAs === "string" ? { user_token: actAs } : actAs;
103
+ if (policy) body.policy = policy;
104
+ return new Run(this._c, await this._c._do("POST", "/agents/v1/runs", body));
105
+ }
106
+ /**
107
+ * Runs `fn(run)` in a new run, then proposes it; if `fn` throws, discards the run and throws again.
108
+ * Returns `{ run, result, outcome }`, `outcome` being what `propose()` answered.
109
+ */
110
+ async withRun(intent, fn, opts = {}) {
111
+ const run = await this.run(intent, opts);
112
+ let result;
113
+ try {
114
+ result = await fn(run);
115
+ } catch (e) {
116
+ await run.discard().catch(() => {});
117
+ throw e;
118
+ }
119
+ const outcome = await run.propose();
120
+ return { run, result, outcome };
121
+ }
122
+ async get(id) {
123
+ return new Run(this._c, await this._c._do("GET", `/agents/v1/runs/${enc(id)}`));
124
+ }
125
+ listRuns({ status, limit } = {}) {
126
+ const q = new URLSearchParams();
127
+ if (status) q.set("status", status);
128
+ if (limit) q.set("limit", String(limit));
129
+ return this._c._do("GET", `/agents/v1/runs${q.size ? `?${q}` : ""}`);
130
+ }
131
+ /** Approves a held run (service key: a person's decision, not an agent's). */
132
+ approve(id) {
133
+ return this._c._do("POST", `/agents/v1/runs/${enc(id)}/approve`);
134
+ }
135
+ reject(id, reason) {
136
+ return this._c._do("POST", `/agents/v1/runs/${enc(id)}/reject`, { reason });
137
+ }
138
+ /** Undoes a merged run's changes, row by row. */
139
+ undo(id, { skipChanged } = {}) {
140
+ return this._c._do("POST", `/agents/v1/runs/${enc(id)}/undo`, { skip_changed: !!skipChanged });
141
+ }
142
+ }
143
+
144
+ class Jobs {
145
+ constructor(c) {
146
+ this._c = c;
147
+ }
148
+ /** Deploys a function: `{ name, files: { "index.ts": "..." } | source, entry, env, timeout_s, memory_mb, max_attempts, concurrency, agent }`. */
149
+ deploy(fn) {
150
+ return this._c._do("POST", "/jobs/v1/functions", fn);
151
+ }
152
+ functions() {
153
+ return this._c._do("GET", "/jobs/v1/functions");
154
+ }
155
+ /** Starts a job: `{ delayS, runAt, idempotencyKey, wait }` (`wait`: seconds, up to 60, to wait for it to end). */
156
+ invoke(name, payload = null, { delayS, runAt, idempotencyKey, wait } = {}) {
157
+ const body = { payload };
158
+ if (delayS !== undefined) body.delay_s = delayS;
159
+ if (runAt !== undefined) body.run_at = runAt instanceof Date ? runAt.getTime() : runAt;
160
+ if (idempotencyKey) body.idempotency_key = idempotencyKey;
161
+ return this._c._do("POST", `/jobs/v1/functions/${enc(name)}/invoke${wait ? `?wait=${wait}` : ""}`, body);
162
+ }
163
+ get(id) {
164
+ return this._c._do("GET", `/jobs/v1/jobs/${enc(id)}`);
165
+ }
166
+ list({ fn, status, before, limit } = {}) {
167
+ const q = new URLSearchParams();
168
+ if (fn) q.set("function", fn);
169
+ if (status) q.set("status", status);
170
+ if (before) q.set("before", String(before));
171
+ if (limit) q.set("limit", String(limit));
172
+ return this._c._do("GET", `/jobs/v1/jobs${q.size ? `?${q}` : ""}`);
173
+ }
174
+ cancel(id) {
175
+ return this._c._do("POST", `/jobs/v1/jobs/${enc(id)}/cancel`);
176
+ }
177
+ retry(id) {
178
+ return this._c._do("POST", `/jobs/v1/jobs/${enc(id)}/retry`);
179
+ }
180
+ /** A cron schedule (UTC) for a function. */
181
+ schedule(fn, cron, payload = null) {
182
+ return this._c._do("POST", "/jobs/v1/schedules", { function: fn, cron, payload });
183
+ }
184
+ }
185
+
186
+ export class ForkbaseClient {
187
+ constructor(url, key, { fetch: fetchImpl, headers } = {}) {
188
+ if (!url) throw new Error("createClient: the server's URL");
189
+ if (!key) throw new Error("createClient: a key (service_role, or an agent's fba_ token)");
190
+ this.url = String(url).replace(/\/+$/, "");
191
+ this.key = key;
192
+ this._fetch = fetchImpl || globalThis.fetch.bind(globalThis);
193
+ this._headers = headers || {};
194
+ this.agents = new Agents(this);
195
+ this.jobs = new Jobs(this);
196
+ }
197
+ _raw(method, path, body, token) {
198
+ return request(this.url, token || this.key, method, path, body, this._fetch, this._headers);
199
+ }
200
+ async _do(method, path, body, token) {
201
+ const r = await this._raw(method, path, body, token);
202
+ if (!r.ok) throw fail(method, path, r);
203
+ return r.data;
204
+ }
205
+ /** Any route: `request("GET", "/platform/v1/project")`. */
206
+ request(method, path, body) {
207
+ return this._do(method, path, body);
208
+ }
209
+ /** A supabase-js client for tables, auth, storage and realtime (needs `@supabase/supabase-js`). */
210
+ async supabase(options) {
211
+ const { createClient } = await import("@supabase/supabase-js");
212
+ return createClient(this.url, this.key, options);
213
+ }
214
+ }
215
+
216
+ /** A client for a Forkbase server. */
217
+ export function createClient(url, key, options) {
218
+ return new ForkbaseClient(url, key, options);
219
+ }
220
+
221
+ // ---- inside a job ----------------------------------------------------------------------------------------------
222
+
223
+ const env = (typeof process !== "undefined" && process.env) || {};
224
+
225
+ /** Thrown by `sleep` to end this attempt until the sleep is over; Forkbase starts the job again then. */
226
+ export class Suspend extends Error {
227
+ constructor(until) {
228
+ super(`sleeping until ${new Date(until).toISOString()}`);
229
+ this.until = until;
230
+ }
231
+ }
232
+
233
+ function inJob(what) {
234
+ if (!env.FORKBASE_JOB_TOKEN) throw new Error(`${what}() works inside a Forkbase job`);
235
+ }
236
+
237
+ async function self(method, path, body) {
238
+ const r = await request(env.FORKBASE_URL, env.FORKBASE_JOB_TOKEN, method, path, body);
239
+ if (!r.ok && r.status !== 404) throw fail(method, path, r);
240
+ return r;
241
+ }
242
+
243
+ /** Runs `fn` once per job: on a retry, a step that finished returns what it returned then. Results must be JSON. */
244
+ export async function step(name, fn) {
245
+ inJob("step");
246
+ const path = `/jobs/v1/self/steps/${enc(name)}`;
247
+ const got = await self("GET", path);
248
+ if (got.status === 200) return got.data.result;
249
+ const result = await fn();
250
+ await self("PUT", path, { result: result === undefined ? null : result });
251
+ return result;
252
+ }
253
+
254
+ /** Ends this attempt and starts the job again after `seconds` (no process waits meanwhile). Steps before it stay done. */
255
+ export async function sleep(name, seconds) {
256
+ inJob("sleep");
257
+ const path = `/jobs/v1/self/steps/${enc(`sleep:${name}`)}`;
258
+ const got = await self("GET", path);
259
+ let until;
260
+ if (got.status === 200) until = got.data.result.until;
261
+ else {
262
+ until = Date.now() + Math.max(0, seconds) * 1000;
263
+ await self("PUT", path, { result: { until } });
264
+ }
265
+ if (Date.now() < until) throw new Suspend(until);
266
+ }
267
+
268
+ /** SQL in the job's world (functions deployed with an agent): `{ columns, rows, ... }`. */
269
+ export async function sql(query, params = []) {
270
+ const run = env.FORKBASE_RUN_ID;
271
+ if (!run) throw new Error("sql() needs a function deployed with an agent: its jobs work in a world");
272
+ const r = await request(env.FORKBASE_URL, env.FORKBASE_RUN_TOKEN, "POST", `/agents/v1/runs/${enc(run)}/sql`, { sql: query, params });
273
+ if (!r.ok) throw fail("POST", "sql", r);
274
+ return r.data;
275
+ }
276
+
277
+ /** The job: its payload (the runner passes it), ids, attempt, its world (or null), and the helpers above. */
278
+ let jobPayload = null;
279
+
280
+ export function context(payload) {
281
+ inJob("context");
282
+ if (payload !== undefined) jobPayload = payload;
283
+ const run = env.FORKBASE_RUN_ID ? { id: env.FORKBASE_RUN_ID, database_url: env.DATABASE_URL, token: env.FORKBASE_RUN_TOKEN } : null;
284
+ return {
285
+ payload: jobPayload,
286
+ job: { id: env.FORKBASE_JOB_ID, attempt: Number(env.FORKBASE_ATTEMPT), function: env.FORKBASE_FUNCTION },
287
+ run,
288
+ url: env.FORKBASE_URL,
289
+ step,
290
+ sleep,
291
+ sql,
292
+ };
293
+ }
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.1.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
+ }