@chronosdb/forkbase 0.1.0 → 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.
- package/index.d.ts +66 -1
- package/index.mjs +116 -2
- package/package.json +1 -1
- package/LICENSE +0 -105
package/index.d.ts
CHANGED
|
@@ -88,11 +88,53 @@ export interface Jobs {
|
|
|
88
88
|
schedule(fn: string, cron: string, payload?: unknown): Promise<any>;
|
|
89
89
|
}
|
|
90
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
|
+
|
|
91
132
|
export class ForkbaseClient {
|
|
92
133
|
url: string;
|
|
93
134
|
key: string;
|
|
94
135
|
agents: Agents;
|
|
95
136
|
jobs: Jobs;
|
|
137
|
+
chat: Chat;
|
|
96
138
|
constructor(url: string, key: string, options?: ClientOptions);
|
|
97
139
|
request(method: string, path: string, body?: unknown): Promise<any>;
|
|
98
140
|
/** A supabase-js client for tables, auth, storage and realtime (needs `@supabase/supabase-js`). */
|
|
@@ -115,13 +157,36 @@ export class Suspend extends Error {
|
|
|
115
157
|
export function step<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
|
|
116
158
|
export function sleep(name: string, seconds: number): Promise<void>;
|
|
117
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 };
|
|
118
177
|
export interface Context<P = any> {
|
|
119
178
|
payload: P;
|
|
120
179
|
job: { id: string; attempt: number; function: string };
|
|
121
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>;
|
|
122
187
|
url: string;
|
|
123
188
|
step: typeof step;
|
|
124
189
|
sleep: typeof sleep;
|
|
125
190
|
sql: typeof sql;
|
|
126
191
|
}
|
|
127
|
-
export function context<P = any>(payload?: P): Context<P>;
|
|
192
|
+
export function context<P = any>(payload?: P, request?: unknown): Context<P>;
|
package/index.mjs
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// - `createClient(url, key)`: agents' runs (each a world of its own; propose; review) and jobs. The key is the
|
|
5
5
|
// service_role key (servers only) or an agent's `fba_` token. Tables, auth, storage and realtime speak Supabase's
|
|
6
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).
|
|
7
9
|
// - Inside a job (a function Forkbase runs), `step`, `sleep`, `sql` and `context` are the job's own helpers.
|
|
8
10
|
|
|
9
11
|
export class ForkbaseError extends Error {
|
|
@@ -183,16 +185,100 @@ class Jobs {
|
|
|
183
185
|
}
|
|
184
186
|
}
|
|
185
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
|
+
|
|
186
271
|
export class ForkbaseClient {
|
|
187
272
|
constructor(url, key, { fetch: fetchImpl, headers } = {}) {
|
|
188
273
|
if (!url) throw new Error("createClient: the server's URL");
|
|
189
|
-
if (!key) throw new Error("createClient: a key (service_role,
|
|
274
|
+
if (!key) throw new Error("createClient: a key (service_role, an agent's fba_ token, or anon for chat)");
|
|
190
275
|
this.url = String(url).replace(/\/+$/, "");
|
|
191
276
|
this.key = key;
|
|
192
277
|
this._fetch = fetchImpl || globalThis.fetch.bind(globalThis);
|
|
193
278
|
this._headers = headers || {};
|
|
194
279
|
this.agents = new Agents(this);
|
|
195
280
|
this.jobs = new Jobs(this);
|
|
281
|
+
this.chat = new Chat(this);
|
|
196
282
|
}
|
|
197
283
|
_raw(method, path, body, token) {
|
|
198
284
|
return request(this.url, token || this.key, method, path, body, this._fetch, this._headers);
|
|
@@ -277,14 +363,42 @@ export async function sql(query, params = []) {
|
|
|
277
363
|
/** The job: its payload (the runner passes it), ids, attempt, its world (or null), and the helpers above. */
|
|
278
364
|
let jobPayload = null;
|
|
279
365
|
|
|
280
|
-
|
|
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) {
|
|
281
391
|
inJob("context");
|
|
282
392
|
if (payload !== undefined) jobPayload = payload;
|
|
393
|
+
if (request !== undefined) jobRequest = request;
|
|
283
394
|
const run = env.FORKBASE_RUN_ID ? { id: env.FORKBASE_RUN_ID, database_url: env.DATABASE_URL, token: env.FORKBASE_RUN_TOKEN } : null;
|
|
284
395
|
return {
|
|
285
396
|
payload: jobPayload,
|
|
286
397
|
job: { id: env.FORKBASE_JOB_ID, attempt: Number(env.FORKBASE_ATTEMPT), function: env.FORKBASE_FUNCTION },
|
|
287
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,
|
|
288
402
|
url: env.FORKBASE_URL,
|
|
289
403
|
step,
|
|
290
404
|
sleep,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chronosdb/forkbase",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
package/LICENSE
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
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.
|