tandem-kit-core 0.0.0 → 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.
- package/LICENSE +21 -0
- package/README.md +7 -1
- package/dist/src/browser.d.ts +19 -0
- package/dist/src/browser.js +19 -0
- package/dist/src/client-tools.d.ts +31 -0
- package/dist/src/client-tools.js +82 -0
- package/dist/src/client.d.ts +179 -0
- package/dist/src/client.js +213 -0
- package/dist/src/delta.d.ts +16 -0
- package/dist/src/delta.js +99 -0
- package/dist/src/durable.d.ts +39 -0
- package/dist/src/durable.js +104 -0
- package/dist/src/errors.d.ts +5 -0
- package/dist/src/errors.js +10 -0
- package/dist/src/eventlog-file.d.ts +12 -0
- package/dist/src/eventlog-file.js +39 -0
- package/dist/src/eventlog.d.ts +31 -0
- package/dist/src/eventlog.js +63 -0
- package/dist/src/events.d.ts +15 -0
- package/dist/src/events.js +79 -0
- package/dist/src/events.json +80 -0
- package/dist/src/files.d.ts +34 -0
- package/dist/src/files.js +122 -0
- package/dist/src/fsutil.d.ts +8 -0
- package/dist/src/fsutil.js +68 -0
- package/dist/src/hash.d.ts +3 -0
- package/dist/src/hash.js +65 -0
- package/dist/src/images.d.ts +24 -0
- package/dist/src/images.js +70 -0
- package/dist/src/index.d.ts +25 -0
- package/dist/src/index.js +25 -0
- package/dist/src/json.d.ts +10 -0
- package/dist/src/json.js +68 -0
- package/dist/src/merge.d.ts +34 -0
- package/dist/src/merge.js +111 -0
- package/dist/src/persist.d.ts +49 -0
- package/dist/src/persist.js +29 -0
- package/dist/src/proposals-file.d.ts +12 -0
- package/dist/src/proposals-file.js +36 -0
- package/dist/src/proposals.d.ts +149 -0
- package/dist/src/proposals.js +296 -0
- package/dist/src/reconcile.d.ts +63 -0
- package/dist/src/reconcile.js +61 -0
- package/dist/src/replica.d.ts +147 -0
- package/dist/src/replica.js +320 -0
- package/dist/src/revisions-file.d.ts +14 -0
- package/dist/src/revisions-file.js +28 -0
- package/dist/src/revisions.d.ts +78 -0
- package/dist/src/revisions.js +152 -0
- package/dist/src/revisions.json +19 -0
- package/dist/src/schema.d.ts +12 -0
- package/dist/src/schema.js +49 -0
- package/dist/src/session-state.d.ts +36 -0
- package/dist/src/session-state.js +95 -0
- package/dist/src/sse.d.ts +17 -0
- package/dist/src/sse.js +59 -0
- package/dist/src/workcopy.d.ts +145 -0
- package/dist/src/workcopy.js +556 -0
- package/package.json +34 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ryan Xu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
1
|
# tandem-kit-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The engine of Tandem: the `tandem/0` event protocol, deltas, three-way merge, the `Workcopy` (a document an agent and a person both edit), revisions, proposals, the replica rules and an HTTP and server-sent-events client. No dependencies; it runs in Node and, through the `browser` export condition, in a page.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { Workcopy } from 'tandem-kit-core'
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Install it with `npm install tandem-kit-core` once published, or from a tarball or the private git repo (see `docs/adoption/installing.md` in the repository). The package ships compiled JavaScript with declaration files, so it runs from `node_modules` with no build step.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * from './client.js';
|
|
2
|
+
export * from './client-tools.js';
|
|
3
|
+
export * from './delta.js';
|
|
4
|
+
export * from './errors.js';
|
|
5
|
+
export * from './eventlog.js';
|
|
6
|
+
export * from './events.js';
|
|
7
|
+
export * from './files.js';
|
|
8
|
+
export * from './hash.js';
|
|
9
|
+
export * from './json.js';
|
|
10
|
+
export * from './merge.js';
|
|
11
|
+
export * from './persist.js';
|
|
12
|
+
export * from './proposals.js';
|
|
13
|
+
export * from './reconcile.js';
|
|
14
|
+
export * from './replica.js';
|
|
15
|
+
export * from './revisions.js';
|
|
16
|
+
export * from './schema.js';
|
|
17
|
+
export * from './sse.js';
|
|
18
|
+
export * from './workcopy.js';
|
|
19
|
+
export * from './session-state.js';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * from "./client.js";
|
|
2
|
+
export * from "./client-tools.js";
|
|
3
|
+
export * from "./delta.js";
|
|
4
|
+
export * from "./errors.js";
|
|
5
|
+
export * from "./eventlog.js";
|
|
6
|
+
export * from "./events.js";
|
|
7
|
+
export * from "./files.js";
|
|
8
|
+
export * from "./hash.js";
|
|
9
|
+
export * from "./json.js";
|
|
10
|
+
export * from "./merge.js";
|
|
11
|
+
export * from "./persist.js";
|
|
12
|
+
export * from "./proposals.js";
|
|
13
|
+
export * from "./reconcile.js";
|
|
14
|
+
export * from "./replica.js";
|
|
15
|
+
export * from "./revisions.js";
|
|
16
|
+
export * from "./schema.js";
|
|
17
|
+
export * from "./sse.js";
|
|
18
|
+
export * from "./workcopy.js";
|
|
19
|
+
export * from "./session-state.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ClientCallAnswer, TandemClient } from './client.js';
|
|
2
|
+
import type { Json } from './json.js';
|
|
3
|
+
export interface ClientCallContext {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
session: string;
|
|
7
|
+
signal: AbortSignal;
|
|
8
|
+
}
|
|
9
|
+
export type ClientToolResult = string | ClientCallAnswer;
|
|
10
|
+
export type ClientToolFn = (input: Record<string, Json>, call: ClientCallContext) => ClientToolResult | Promise<ClientToolResult>;
|
|
11
|
+
export interface ClientToolsOptions {
|
|
12
|
+
/** the seq to start from; calls already answered after it are never run again. Default 0 */
|
|
13
|
+
after?: number;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
/** run calls one at a time in the order they arrived (default `true`), or let them overlap */
|
|
16
|
+
serial?: boolean;
|
|
17
|
+
/** a call nothing here handles, an answer that could not be sent, or a stream that broke */
|
|
18
|
+
onError?: (error: Error, call?: {
|
|
19
|
+
id: string;
|
|
20
|
+
name: string;
|
|
21
|
+
}) => void;
|
|
22
|
+
/** wait before following the stream again after it broke, in milliseconds. Default 1000 */
|
|
23
|
+
retryMs?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface RunningClientTools {
|
|
26
|
+
stop(): void;
|
|
27
|
+
done: Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/** answers a session's `client_call` events with functions of the app's own page. It reads what is still unanswered first, so a page that
|
|
30
|
+
* reloads or reconnects never runs the same call twice, then follows the stream. A function that throws answers the agent with the error */
|
|
31
|
+
export declare function runClientTools(client: TandemClient, session: string, tools: Record<string, ClientToolFn>, options?: ClientToolsOptions): RunningClientTools;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
const asAnswer = (result) => (typeof result === 'string' ? { text: result } : result);
|
|
2
|
+
/** answers a session's `client_call` events with functions of the app's own page. It reads what is still unanswered first, so a page that
|
|
3
|
+
* reloads or reconnects never runs the same call twice, then follows the stream. A function that throws answers the agent with the error */
|
|
4
|
+
export function runClientTools(client, session, tools, options = {}) {
|
|
5
|
+
const abort = new AbortController();
|
|
6
|
+
options.signal?.addEventListener('abort', () => abort.abort());
|
|
7
|
+
const seen = new Set();
|
|
8
|
+
let chain = Promise.resolve();
|
|
9
|
+
const serial = options.serial !== false;
|
|
10
|
+
const report = (error, call) => options.onError?.(error instanceof Error ? error : new Error(String(error)), call);
|
|
11
|
+
const run = async (event) => {
|
|
12
|
+
const id = event.id;
|
|
13
|
+
const name = event.name;
|
|
14
|
+
let answer;
|
|
15
|
+
const tool = Object.hasOwn(tools, name) ? tools[name] : undefined;
|
|
16
|
+
if (!tool) {
|
|
17
|
+
answer = { text: `the app has no tool called ${name}`, is_error: true };
|
|
18
|
+
report(new Error(answer.text), { id, name });
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
try {
|
|
22
|
+
answer = asAnswer(await tool((event.input ?? {}), { id, name, session, signal: abort.signal }));
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
answer = { text: error instanceof Error ? error.message : String(error), is_error: true };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (abort.signal.aborted)
|
|
29
|
+
return;
|
|
30
|
+
try {
|
|
31
|
+
await client.answerClientCall(session, id, answer);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
const code = error.code;
|
|
35
|
+
if (code !== 'gone')
|
|
36
|
+
report(error, { id, name });
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const take = (event) => {
|
|
40
|
+
if (event.type !== 'client_call' || typeof event.id !== 'string' || seen.has(event.id))
|
|
41
|
+
return;
|
|
42
|
+
seen.add(event.id);
|
|
43
|
+
if (serial)
|
|
44
|
+
chain = chain.then(() => run(event));
|
|
45
|
+
else
|
|
46
|
+
void run(event);
|
|
47
|
+
};
|
|
48
|
+
const main = async () => {
|
|
49
|
+
let after = options.after ?? 0;
|
|
50
|
+
while (!abort.signal.aborted) {
|
|
51
|
+
try {
|
|
52
|
+
const replay = await client.events(session, after);
|
|
53
|
+
const answered = new Set(replay.events.filter((e) => e.type === 'client_call_done').map((e) => e.id));
|
|
54
|
+
for (const event of replay.events)
|
|
55
|
+
if (event.type === 'client_call' && !answered.has(event.id))
|
|
56
|
+
take(event);
|
|
57
|
+
for (const event of replay.events)
|
|
58
|
+
if (event.type === 'client_call')
|
|
59
|
+
seen.add(event.id);
|
|
60
|
+
after = replay.last_seq;
|
|
61
|
+
for await (const event of client.sessionEvents(session, after, abort.signal)) {
|
|
62
|
+
take(event);
|
|
63
|
+
if (event.seq !== undefined)
|
|
64
|
+
after = Math.max(after, event.seq);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (abort.signal.aborted)
|
|
69
|
+
break;
|
|
70
|
+
report(error);
|
|
71
|
+
}
|
|
72
|
+
if (abort.signal.aborted)
|
|
73
|
+
break;
|
|
74
|
+
await new Promise((resolve) => {
|
|
75
|
+
const timer = setTimeout(resolve, options.retryMs ?? 1000);
|
|
76
|
+
abort.signal.addEventListener('abort', () => (clearTimeout(timer), resolve(undefined)), { once: true });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
await chain;
|
|
80
|
+
};
|
|
81
|
+
return { stop: () => abort.abort(), done: main() };
|
|
82
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import type { TandemEvent } from './events.js';
|
|
2
|
+
import type { Delta } from './delta.js';
|
|
3
|
+
import type { ImagePart } from './images.js';
|
|
4
|
+
import type { Json } from './json.js';
|
|
5
|
+
import type { ApplyResult, Proposal, ProposalEdit, ProposalFilter, ProposeInput } from './proposals.js';
|
|
6
|
+
import type { Revision } from './revisions.js';
|
|
7
|
+
import type { ClashRecord, WriteResult } from './workcopy.js';
|
|
8
|
+
/** how a client in `poll` mode reads events: one request at a time, `GET .../events?after=<seq>&format=json&wait=<ms>`, instead of holding an event stream open */
|
|
9
|
+
export interface PollOptions {
|
|
10
|
+
/** how long the server may hold a read open while there is nothing new, in milliseconds; a server answers at once if it does not know `wait`. Default 20000 */
|
|
11
|
+
waitMs?: number;
|
|
12
|
+
/** the least time between two reads, so a server that answers at once (or `waitMs: 0`) is asked this often. Default 1000 */
|
|
13
|
+
intervalMs?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface ClientOptions {
|
|
16
|
+
baseUrl: string;
|
|
17
|
+
token?: string;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
/** how `sessionEvents`, `workcopyEvents` and `proposalEvents` read: `sse` (the default) holds a text/event-stream open, `poll` asks for what is new one request at a time, for a host behind a request/reply bridge that cannot stream. A poll read has the persisted events only: whole messages arrive, `text_delta` does not */
|
|
21
|
+
events?: 'sse' | 'poll';
|
|
22
|
+
/** the timing of `poll` mode */
|
|
23
|
+
poll?: PollOptions;
|
|
24
|
+
}
|
|
25
|
+
export interface SessionSummary {
|
|
26
|
+
id: string;
|
|
27
|
+
status: 'idle' | 'running' | 'ended';
|
|
28
|
+
harness: string;
|
|
29
|
+
doc?: string | null;
|
|
30
|
+
settings: {
|
|
31
|
+
model: string | null;
|
|
32
|
+
effort: string | null;
|
|
33
|
+
permission_mode: string;
|
|
34
|
+
};
|
|
35
|
+
last_seq: number;
|
|
36
|
+
turn: number;
|
|
37
|
+
pending: {
|
|
38
|
+
id: string;
|
|
39
|
+
kind: 'approval' | 'question';
|
|
40
|
+
}[];
|
|
41
|
+
}
|
|
42
|
+
export interface ClientCallAnswer {
|
|
43
|
+
text?: string;
|
|
44
|
+
is_error?: boolean;
|
|
45
|
+
images?: {
|
|
46
|
+
mime: string;
|
|
47
|
+
data: string;
|
|
48
|
+
alt?: string;
|
|
49
|
+
}[];
|
|
50
|
+
/** `app.` events to put into the session, for a card to draw */
|
|
51
|
+
events?: {
|
|
52
|
+
type: string;
|
|
53
|
+
[field: string]: unknown;
|
|
54
|
+
}[];
|
|
55
|
+
}
|
|
56
|
+
export declare class TandemClient {
|
|
57
|
+
private readonly baseUrl;
|
|
58
|
+
private readonly token;
|
|
59
|
+
private readonly extraHeaders;
|
|
60
|
+
private readonly doFetch;
|
|
61
|
+
private readonly mode;
|
|
62
|
+
private readonly pollOptions;
|
|
63
|
+
constructor(options: ClientOptions);
|
|
64
|
+
request<T = Json>(method: string, path: string, body?: unknown): Promise<{
|
|
65
|
+
status: number;
|
|
66
|
+
body: T;
|
|
67
|
+
}>;
|
|
68
|
+
private headers;
|
|
69
|
+
private ok;
|
|
70
|
+
info(): Promise<{
|
|
71
|
+
protocol: string;
|
|
72
|
+
harnesses: string[];
|
|
73
|
+
models?: {
|
|
74
|
+
id: string;
|
|
75
|
+
label: string;
|
|
76
|
+
note?: string;
|
|
77
|
+
}[];
|
|
78
|
+
efforts?: string[];
|
|
79
|
+
docs?: string[];
|
|
80
|
+
proposals?: boolean;
|
|
81
|
+
}>;
|
|
82
|
+
createSession(options?: Record<string, unknown>): Promise<SessionSummary>;
|
|
83
|
+
sessions(): Promise<{
|
|
84
|
+
sessions: SessionSummary[];
|
|
85
|
+
}>;
|
|
86
|
+
session(id: string): Promise<SessionSummary>;
|
|
87
|
+
send(id: string, text: string, images?: ImagePart[]): Promise<{
|
|
88
|
+
seq: number;
|
|
89
|
+
}>;
|
|
90
|
+
interrupt(id: string): Promise<{
|
|
91
|
+
ok: true;
|
|
92
|
+
}>;
|
|
93
|
+
compact(id: string, instructions?: string): Promise<{
|
|
94
|
+
ok: true;
|
|
95
|
+
}>;
|
|
96
|
+
settings(id: string, settings: Record<string, unknown>): Promise<{
|
|
97
|
+
model: string | null;
|
|
98
|
+
effort: string | null;
|
|
99
|
+
permission_mode: string;
|
|
100
|
+
}>;
|
|
101
|
+
approve(id: string, approvalId: string, reply: {
|
|
102
|
+
allow: boolean;
|
|
103
|
+
always?: boolean;
|
|
104
|
+
message?: string;
|
|
105
|
+
mode?: string;
|
|
106
|
+
}): Promise<{
|
|
107
|
+
ok: true;
|
|
108
|
+
}>;
|
|
109
|
+
answer(id: string, questionId: string, answers: Record<string, string> | null): Promise<{
|
|
110
|
+
ok: true;
|
|
111
|
+
}>;
|
|
112
|
+
answerClientCall(id: string, callId: string, answer: ClientCallAnswer): Promise<{
|
|
113
|
+
ok: true;
|
|
114
|
+
}>;
|
|
115
|
+
/** the persisted events after `after`, in one reply. With `waitMs` a server that has nothing yet holds the reply until something arrives or the time is up (it may shorten the wait) */
|
|
116
|
+
events(id: string, after?: number, options?: {
|
|
117
|
+
waitMs?: number;
|
|
118
|
+
signal?: AbortSignal;
|
|
119
|
+
}): Promise<{
|
|
120
|
+
events: TandemEvent[];
|
|
121
|
+
last_seq: number;
|
|
122
|
+
}>;
|
|
123
|
+
private read;
|
|
124
|
+
/** the same events as `stream`, read one request at a time: a reply is waited for up to `waitMs`, then asked again from the last `seq` seen. Ends when `signal` aborts; a failed request throws, as a dropped stream does */
|
|
125
|
+
poll(path: string, after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent>;
|
|
126
|
+
workcopy(name: string): Promise<{
|
|
127
|
+
name: string;
|
|
128
|
+
version: number;
|
|
129
|
+
state: Json;
|
|
130
|
+
clashes: ClashRecord[];
|
|
131
|
+
head: string;
|
|
132
|
+
}>;
|
|
133
|
+
write(name: string, write: {
|
|
134
|
+
version: number;
|
|
135
|
+
delta?: Delta;
|
|
136
|
+
state?: Json;
|
|
137
|
+
actor: string;
|
|
138
|
+
reason?: string;
|
|
139
|
+
commit?: boolean;
|
|
140
|
+
}): Promise<WriteResult & {
|
|
141
|
+
http: number;
|
|
142
|
+
}>;
|
|
143
|
+
commit(name: string): Promise<{
|
|
144
|
+
revision: Revision | null;
|
|
145
|
+
}>;
|
|
146
|
+
undo(name: string, actor?: string | {
|
|
147
|
+
actor?: string;
|
|
148
|
+
stack?: boolean;
|
|
149
|
+
scope?: 'state' | 'change';
|
|
150
|
+
onClash?: 'keep-current' | 'refuse';
|
|
151
|
+
}): Promise<WriteResult>;
|
|
152
|
+
revert(name: string, revision: string, options?: {
|
|
153
|
+
actor?: string;
|
|
154
|
+
reason?: string;
|
|
155
|
+
scope?: 'state' | 'change';
|
|
156
|
+
dryRun?: boolean;
|
|
157
|
+
onClash?: 'keep-current' | 'refuse';
|
|
158
|
+
}): Promise<WriteResult>;
|
|
159
|
+
resolveClash(name: string, clashId: string, choice: 'kept' | 'dropped', actor?: string): Promise<WriteResult>;
|
|
160
|
+
revisions(name: string): Promise<Revision[]>;
|
|
161
|
+
proposals(filter?: ProposalFilter): Promise<Proposal[]>;
|
|
162
|
+
proposal(id: string): Promise<Proposal>;
|
|
163
|
+
propose(input: ProposeInput): Promise<Proposal>;
|
|
164
|
+
editProposal(id: string, change: ProposalEdit, actor?: string): Promise<Proposal>;
|
|
165
|
+
applyProposal(id: string, options?: {
|
|
166
|
+
edit?: ProposalEdit;
|
|
167
|
+
actor?: string;
|
|
168
|
+
}): Promise<ApplyResult>;
|
|
169
|
+
discardProposal(id: string, actor?: string): Promise<Proposal>;
|
|
170
|
+
proposalEvents(after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent, any, any>;
|
|
171
|
+
deleteSession(id: string): Promise<{
|
|
172
|
+
ok: true;
|
|
173
|
+
}>;
|
|
174
|
+
stream(path: string, after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent>;
|
|
175
|
+
/** events as they come, over whichever read the client was made with (`events` option) */
|
|
176
|
+
follow(path: string, after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent>;
|
|
177
|
+
sessionEvents(id: string, after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent, any, any>;
|
|
178
|
+
workcopyEvents(name: string, after?: number, signal?: AbortSignal): AsyncGenerator<TandemEvent, any, any>;
|
|
179
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { TandemError } from "./errors.js";
|
|
2
|
+
import { SseParser } from "./sse.js";
|
|
3
|
+
export class TandemClient {
|
|
4
|
+
baseUrl;
|
|
5
|
+
token;
|
|
6
|
+
extraHeaders;
|
|
7
|
+
doFetch;
|
|
8
|
+
mode;
|
|
9
|
+
pollOptions;
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, '');
|
|
12
|
+
this.token = options.token;
|
|
13
|
+
this.extraHeaders = options.headers ?? {};
|
|
14
|
+
this.doFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
15
|
+
this.mode = options.events ?? 'sse';
|
|
16
|
+
this.pollOptions = { waitMs: options.poll?.waitMs ?? 20_000, intervalMs: options.poll?.intervalMs ?? 1000 };
|
|
17
|
+
}
|
|
18
|
+
async request(method, path, body) {
|
|
19
|
+
const response = await this.doFetch(`${this.baseUrl}${path}`, {
|
|
20
|
+
method,
|
|
21
|
+
headers: this.headers(body !== undefined),
|
|
22
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
23
|
+
});
|
|
24
|
+
const text = await response.text();
|
|
25
|
+
return { status: response.status, body: (text ? JSON.parse(text) : null) };
|
|
26
|
+
}
|
|
27
|
+
headers(json) {
|
|
28
|
+
return { ...this.extraHeaders, ...(json ? { 'content-type': 'application/json' } : {}), ...(this.token ? { authorization: `Bearer ${this.token}` } : {}) };
|
|
29
|
+
}
|
|
30
|
+
async ok(method, path, body) {
|
|
31
|
+
const { status, body: payload } = await this.request(method, path, body);
|
|
32
|
+
if (status >= 400) {
|
|
33
|
+
const error = payload?.error;
|
|
34
|
+
throw new TandemError(status, error?.code ?? 'http_error', error?.message ?? `HTTP ${status}`);
|
|
35
|
+
}
|
|
36
|
+
return payload;
|
|
37
|
+
}
|
|
38
|
+
info() {
|
|
39
|
+
return this.ok('GET', '/v1/info');
|
|
40
|
+
}
|
|
41
|
+
createSession(options = {}) {
|
|
42
|
+
return this.ok('POST', '/v1/sessions', options);
|
|
43
|
+
}
|
|
44
|
+
sessions() {
|
|
45
|
+
return this.ok('GET', '/v1/sessions');
|
|
46
|
+
}
|
|
47
|
+
session(id) {
|
|
48
|
+
return this.ok('GET', `/v1/sessions/${id}`);
|
|
49
|
+
}
|
|
50
|
+
send(id, text, images) {
|
|
51
|
+
return this.ok('POST', `/v1/sessions/${id}/messages`, images?.length ? { text, images } : { text });
|
|
52
|
+
}
|
|
53
|
+
interrupt(id) {
|
|
54
|
+
return this.ok('POST', `/v1/sessions/${id}/interrupt`);
|
|
55
|
+
}
|
|
56
|
+
compact(id, instructions) {
|
|
57
|
+
return this.ok('POST', `/v1/sessions/${id}/compact`, instructions ? { instructions } : {});
|
|
58
|
+
}
|
|
59
|
+
settings(id, settings) {
|
|
60
|
+
return this.ok('POST', `/v1/sessions/${id}/settings`, settings);
|
|
61
|
+
}
|
|
62
|
+
approve(id, approvalId, reply) {
|
|
63
|
+
return this.ok('POST', `/v1/sessions/${id}/approvals/${approvalId}`, reply);
|
|
64
|
+
}
|
|
65
|
+
answer(id, questionId, answers) {
|
|
66
|
+
return this.ok('POST', `/v1/sessions/${id}/questions/${questionId}`, { answers });
|
|
67
|
+
}
|
|
68
|
+
answerClientCall(id, callId, answer) {
|
|
69
|
+
return this.ok('POST', `/v1/sessions/${id}/client_calls/${callId}`, answer);
|
|
70
|
+
}
|
|
71
|
+
/** the persisted events after `after`, in one reply. With `waitMs` a server that has nothing yet holds the reply until something arrives or the time is up (it may shorten the wait) */
|
|
72
|
+
async events(id, after = 0, options = {}) {
|
|
73
|
+
return this.read(`/v1/sessions/${id}/events`, after, options.waitMs, options.signal);
|
|
74
|
+
}
|
|
75
|
+
async read(path, after, waitMs, signal) {
|
|
76
|
+
const wait = waitMs && waitMs > 0 ? `&wait=${Math.floor(waitMs)}` : '';
|
|
77
|
+
const response = await this.doFetch(`${this.baseUrl}${path}?after=${after}&format=json${wait}`, { headers: this.headers(false), signal });
|
|
78
|
+
const text = await response.text();
|
|
79
|
+
const payload = text ? JSON.parse(text) : null;
|
|
80
|
+
if (response.status >= 400)
|
|
81
|
+
throw new TandemError(response.status, payload?.error?.code ?? 'http_error', payload?.error?.message ?? `HTTP ${response.status}`);
|
|
82
|
+
return payload;
|
|
83
|
+
}
|
|
84
|
+
/** the same events as `stream`, read one request at a time: a reply is waited for up to `waitMs`, then asked again from the last `seq` seen. Ends when `signal` aborts; a failed request throws, as a dropped stream does */
|
|
85
|
+
async *poll(path, after = 0, signal) {
|
|
86
|
+
let cursor = after;
|
|
87
|
+
const { waitMs, intervalMs } = this.pollOptions;
|
|
88
|
+
while (!signal?.aborted) {
|
|
89
|
+
const started = Date.now();
|
|
90
|
+
let reply;
|
|
91
|
+
try {
|
|
92
|
+
reply = await this.read(path, cursor, waitMs, signal);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (signal?.aborted)
|
|
96
|
+
return;
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
for (const event of reply.events) {
|
|
100
|
+
if (event.seq !== undefined && event.seq > cursor)
|
|
101
|
+
cursor = event.seq;
|
|
102
|
+
yield event;
|
|
103
|
+
}
|
|
104
|
+
const spare = intervalMs - (Date.now() - started);
|
|
105
|
+
if (!reply.events.length && spare > 0)
|
|
106
|
+
await sleep(spare, signal);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
workcopy(name) {
|
|
110
|
+
return this.ok('GET', `/v1/workcopies/${name}`);
|
|
111
|
+
}
|
|
112
|
+
async write(name, write) {
|
|
113
|
+
const { status, body } = await this.request('POST', `/v1/workcopies/${name}/writes`, write);
|
|
114
|
+
if (status >= 400 && ![409, 422].includes(status))
|
|
115
|
+
throw new TandemError(status, 'http_error', `HTTP ${status}`);
|
|
116
|
+
return { ...body, http: status };
|
|
117
|
+
}
|
|
118
|
+
commit(name) {
|
|
119
|
+
return this.ok('POST', `/v1/workcopies/${name}/commit`);
|
|
120
|
+
}
|
|
121
|
+
undo(name, actor = 'human') {
|
|
122
|
+
const o = typeof actor === 'string' ? { actor } : actor;
|
|
123
|
+
return this.ok('POST', `/v1/workcopies/${name}/undo`, {
|
|
124
|
+
actor: o.actor ?? 'human',
|
|
125
|
+
...(o.stack !== undefined ? { stack: o.stack } : {}),
|
|
126
|
+
...(o.scope ? { scope: o.scope } : {}),
|
|
127
|
+
...(o.onClash ? { on_clash: o.onClash } : {}),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
revert(name, revision, options = {}) {
|
|
131
|
+
return this.ok('POST', `/v1/workcopies/${name}/revert`, { revision, actor: options.actor ?? 'human', ...(options.reason ? { reason: options.reason } : {}), ...(options.scope ? { scope: options.scope } : {}), ...(options.dryRun !== undefined ? { dry_run: options.dryRun } : {}), ...(options.onClash ? { on_clash: options.onClash } : {}) });
|
|
132
|
+
}
|
|
133
|
+
resolveClash(name, clashId, choice, actor = 'human') {
|
|
134
|
+
return this.ok('POST', `/v1/workcopies/${name}/clashes/${clashId}`, { choice, actor });
|
|
135
|
+
}
|
|
136
|
+
async revisions(name) {
|
|
137
|
+
return (await this.ok('GET', `/v1/workcopies/${name}/revisions`)).revisions;
|
|
138
|
+
}
|
|
139
|
+
async proposals(filter = {}) {
|
|
140
|
+
const query = new URLSearchParams();
|
|
141
|
+
for (const [key, value] of Object.entries(filter))
|
|
142
|
+
if (value !== undefined && value !== null)
|
|
143
|
+
query.set(key, String(value));
|
|
144
|
+
const suffix = query.size ? `?${query}` : '';
|
|
145
|
+
return (await this.ok('GET', `/v1/proposals${suffix}`)).proposals;
|
|
146
|
+
}
|
|
147
|
+
proposal(id) {
|
|
148
|
+
return this.ok('GET', `/v1/proposals/${encodeURIComponent(id)}`);
|
|
149
|
+
}
|
|
150
|
+
propose(input) {
|
|
151
|
+
return this.ok('POST', '/v1/proposals', input);
|
|
152
|
+
}
|
|
153
|
+
editProposal(id, change, actor = 'human') {
|
|
154
|
+
return this.ok('POST', `/v1/proposals/${encodeURIComponent(id)}/edit`, { ...change, actor });
|
|
155
|
+
}
|
|
156
|
+
applyProposal(id, options = {}) {
|
|
157
|
+
return this.ok('POST', `/v1/proposals/${encodeURIComponent(id)}/apply`, { actor: 'human', ...options });
|
|
158
|
+
}
|
|
159
|
+
discardProposal(id, actor = 'human') {
|
|
160
|
+
return this.ok('POST', `/v1/proposals/${encodeURIComponent(id)}/discard`, { actor });
|
|
161
|
+
}
|
|
162
|
+
proposalEvents(after = 0, signal) {
|
|
163
|
+
return this.follow('/v1/proposals/events', after, signal);
|
|
164
|
+
}
|
|
165
|
+
deleteSession(id) {
|
|
166
|
+
return this.ok('DELETE', `/v1/sessions/${id}`);
|
|
167
|
+
}
|
|
168
|
+
async *stream(path, after = 0, signal) {
|
|
169
|
+
const response = await this.doFetch(`${this.baseUrl}${path}${path.includes('?') ? '&' : '?'}after=${after}`, {
|
|
170
|
+
headers: { ...this.headers(false), accept: 'text/event-stream', 'last-event-id': String(after) },
|
|
171
|
+
signal,
|
|
172
|
+
});
|
|
173
|
+
if (!response.ok || !response.body)
|
|
174
|
+
throw new TandemError(response.status, 'http_error', `HTTP ${response.status}`);
|
|
175
|
+
const parser = new SseParser();
|
|
176
|
+
const decoder = new TextDecoder();
|
|
177
|
+
const reader = response.body.getReader();
|
|
178
|
+
try {
|
|
179
|
+
for (;;) {
|
|
180
|
+
const { done, value } = await reader.read();
|
|
181
|
+
if (done)
|
|
182
|
+
return;
|
|
183
|
+
for (const message of parser.feed(decoder.decode(value, { stream: true }))) {
|
|
184
|
+
yield JSON.parse(message.data);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
await reader.cancel().catch(() => undefined);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** events as they come, over whichever read the client was made with (`events` option) */
|
|
193
|
+
follow(path, after = 0, signal) {
|
|
194
|
+
return this.mode === 'poll' ? this.poll(path, after, signal) : this.stream(path, after, signal);
|
|
195
|
+
}
|
|
196
|
+
sessionEvents(id, after = 0, signal) {
|
|
197
|
+
return this.follow(`/v1/sessions/${id}/events`, after, signal);
|
|
198
|
+
}
|
|
199
|
+
workcopyEvents(name, after = 0, signal) {
|
|
200
|
+
return this.follow(`/v1/workcopies/${name}/events`, after, signal);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function sleep(ms, signal) {
|
|
204
|
+
return new Promise((resolve) => {
|
|
205
|
+
const done = () => {
|
|
206
|
+
clearTimeout(timer);
|
|
207
|
+
signal?.removeEventListener('abort', done);
|
|
208
|
+
resolve();
|
|
209
|
+
};
|
|
210
|
+
const timer = setTimeout(done, ms);
|
|
211
|
+
signal?.addEventListener('abort', done);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type Json } from './json.js';
|
|
2
|
+
export type Path = (string | number)[];
|
|
3
|
+
export type Op = {
|
|
4
|
+
op: 'set';
|
|
5
|
+
path: Path;
|
|
6
|
+
value: Json;
|
|
7
|
+
} | {
|
|
8
|
+
op: 'delete';
|
|
9
|
+
path: Path;
|
|
10
|
+
};
|
|
11
|
+
export type Delta = Op[];
|
|
12
|
+
export declare function applyOp(state: Json, op: Op): Json;
|
|
13
|
+
export declare function apply(state: Json, delta: Delta): Json;
|
|
14
|
+
export declare function diff(before: Json, after: Json, prefix?: Path): Delta;
|
|
15
|
+
export declare function formatPath(path: Path): string;
|
|
16
|
+
export declare function formatDelta(delta: Delta, maxChars?: number): string;
|