@lightblues/jig 0.0.8 → 0.0.9
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/dist/agent-pi/index.d.ts +4 -0
- package/dist/agent-pi/index.js +2 -0
- package/dist/agent-pi/registry.d.ts +93 -0
- package/dist/agent-pi/registry.js +248 -0
- package/dist/agent-pi/sse.d.ts +27 -0
- package/dist/agent-pi/sse.js +75 -0
- package/package.json +1 -1
package/dist/agent-pi/index.d.ts
CHANGED
|
@@ -9,3 +9,7 @@ export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, wind
|
|
|
9
9
|
export type { Card, PiRunEvent, RunAgentOptions, RunLimits, RunResult, RunTool, Turn } from "./run.ts";
|
|
10
10
|
export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.ts";
|
|
11
11
|
export type { PgSessionStoreOptions, Query, RunStart, RunStatus, RunUsage, SessionStore } from "./store.ts";
|
|
12
|
+
export { Busy, failOrphans, RunFolder, RunRegistry, runRegistry } from "./registry.ts";
|
|
13
|
+
export type { ReadyValue, RegistryRun, RunListener, StartOptions } from "./registry.ts";
|
|
14
|
+
export { sseFrame, sseResponse } from "./sse.ts";
|
|
15
|
+
export type { Listenable, SseOptions } from "./sse.ts";
|
package/dist/agent-pi/index.js
CHANGED
|
@@ -6,3 +6,5 @@
|
|
|
6
6
|
export { costOf, modelCost, parsePrices, piModels, routerModel, singleModel } from "./models.js";
|
|
7
7
|
export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, windowEntries, withoutEmptyImages, withoutImages } from "./run.js";
|
|
8
8
|
export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.js";
|
|
9
|
+
export { Busy, failOrphans, RunFolder, RunRegistry, runRegistry } from "./registry.js";
|
|
10
|
+
export { sseFrame, sseResponse } from "./sse.js";
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { PiRunEvent } from "./run.ts";
|
|
2
|
+
import type { SessionStore } from "./store.ts";
|
|
3
|
+
/** A thread already has a run in progress. Hosts answer it with 409. */
|
|
4
|
+
export declare class Busy extends Error {
|
|
5
|
+
readonly threadId: string;
|
|
6
|
+
readonly runId: string;
|
|
7
|
+
constructor(threadId: string, runId: string);
|
|
8
|
+
}
|
|
9
|
+
/** `value` of `CUSTOM READY`, the first event every listener gets: the same as agent-paseo's. */
|
|
10
|
+
export interface ReadyValue {
|
|
11
|
+
threadId: string;
|
|
12
|
+
runId: string | null;
|
|
13
|
+
running: boolean;
|
|
14
|
+
}
|
|
15
|
+
export type RunListener = (event: PiRunEvent) => void;
|
|
16
|
+
/**
|
|
17
|
+
* What a run gets from the registry. The field names are `runAgent`'s option names, so `runAgent({ ...options, ...run })`
|
|
18
|
+
* wires the run in: its id, the thread as AG-UI `threadId`, the stop signal and the event sink.
|
|
19
|
+
*/
|
|
20
|
+
export interface RegistryRun {
|
|
21
|
+
runId: string;
|
|
22
|
+
threadId: string;
|
|
23
|
+
signal: AbortSignal;
|
|
24
|
+
onEvent: (event: PiRunEvent) => void;
|
|
25
|
+
}
|
|
26
|
+
export interface StartOptions {
|
|
27
|
+
/** The run's id. Default `run_` + 12 random characters (as `runAgent` makes them). */
|
|
28
|
+
runId?: string;
|
|
29
|
+
/** Merged into `RUN_STARTED.metadata` (the host's stored user message id, an ask id). */
|
|
30
|
+
metadata?: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* What a listener needs to see the run so far: a replay of the text, reasoning, tool calls and cards, in the order
|
|
34
|
+
* they came. Folded from the run's own events, so it holds exactly what a listener from the start saw.
|
|
35
|
+
*/
|
|
36
|
+
export declare class RunFolder {
|
|
37
|
+
private order;
|
|
38
|
+
fold(e: PiRunEvent): void;
|
|
39
|
+
/** The run so far as events: one CONTENT per message (the text so far), each START with its END if it ended. */
|
|
40
|
+
replay(): PiRunEvent[];
|
|
41
|
+
private find;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* One run per thread in this process, which outlives the HTTP request that started it, and its events to any number
|
|
45
|
+
* of listeners. A listener that joins mid-run (a reload, a second tab, a reconnect) gets `READY`, `RUN_STARTED` and a
|
|
46
|
+
* replay of the run so far, then the live events: the follower contract agent-paseo's runner keeps
|
|
47
|
+
* (`.ea/docs/agent-chat.md`). Nothing is persisted here; the run's store has the session and the run row.
|
|
48
|
+
*/
|
|
49
|
+
export declare class RunRegistry {
|
|
50
|
+
private runs;
|
|
51
|
+
private listeners;
|
|
52
|
+
private warn;
|
|
53
|
+
constructor(o?: {
|
|
54
|
+
warn?: (message: string, detail?: unknown) => void;
|
|
55
|
+
});
|
|
56
|
+
running(threadId: string): boolean;
|
|
57
|
+
current(threadId: string): {
|
|
58
|
+
runId: string;
|
|
59
|
+
} | null;
|
|
60
|
+
/**
|
|
61
|
+
* Starts a run on a thread; throws `Busy` when the thread has one. `fn` gets the run's id, thread, stop signal and
|
|
62
|
+
* event sink (`runAgent({ ...options, ...run })`). The registry guarantees each run one terminal event: when `fn`
|
|
63
|
+
* throws or settles without one, it sends `RUN_ERROR` / `RUN_FINISHED` itself. The run leaves the registry with its
|
|
64
|
+
* terminal event; events after it are dropped. `result` is `fn`'s promise (already handled: not awaiting it is fine).
|
|
65
|
+
*/
|
|
66
|
+
start<T>(threadId: string, fn: (run: RegistryRun) => Promise<T>, o?: StartOptions): {
|
|
67
|
+
runId: string;
|
|
68
|
+
result: Promise<T>;
|
|
69
|
+
};
|
|
70
|
+
/** Aborts the thread's run (only `runId`'s, when given). False when there is no such run. */
|
|
71
|
+
stop(threadId: string, runId?: string): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Follows a thread: `CUSTOM READY {threadId, runId, running}` at once; when a run is in progress, `RUN_STARTED` and
|
|
74
|
+
* the replay of the run so far (once the run has started); then live events. Returns the unsubscribe.
|
|
75
|
+
*/
|
|
76
|
+
listen(threadId: string, fn: RunListener): () => void;
|
|
77
|
+
/** Aborts every run (shutdown). */
|
|
78
|
+
close(): void;
|
|
79
|
+
private onEvent;
|
|
80
|
+
private end;
|
|
81
|
+
/** Delivers to the listeners there are now: one that joins during delivery got this event in its replay already. */
|
|
82
|
+
private send;
|
|
83
|
+
private call;
|
|
84
|
+
}
|
|
85
|
+
export declare function runRegistry(o?: {
|
|
86
|
+
warn?: (message: string, detail?: unknown) => void;
|
|
87
|
+
}): RunRegistry;
|
|
88
|
+
/**
|
|
89
|
+
* At startup, before serving: runs the store still shows `running` were never finished (the process that ran them is
|
|
90
|
+
* gone, and with it their registry), so they are marked failed. Returns how many. Hosts with their own visible-thread
|
|
91
|
+
* rows (`rudi_messages`, a chat message `streaming`) fail those in the same place.
|
|
92
|
+
*/
|
|
93
|
+
export declare function failOrphans(store: Pick<SessionStore, "failStaleRuns">): Promise<number>;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { EventType } from "@ag-ui/core";
|
|
3
|
+
/** A thread already has a run in progress. Hosts answer it with 409. */
|
|
4
|
+
export class Busy extends Error {
|
|
5
|
+
threadId;
|
|
6
|
+
runId;
|
|
7
|
+
constructor(threadId, runId) {
|
|
8
|
+
super(`thread ${threadId} already has a run in progress (${runId})`);
|
|
9
|
+
this.name = "Busy";
|
|
10
|
+
this.threadId = threadId;
|
|
11
|
+
this.runId = runId;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* What a listener needs to see the run so far: a replay of the text, reasoning, tool calls and cards, in the order
|
|
16
|
+
* they came. Folded from the run's own events, so it holds exactly what a listener from the start saw.
|
|
17
|
+
*/
|
|
18
|
+
export class RunFolder {
|
|
19
|
+
order = [];
|
|
20
|
+
fold(e) {
|
|
21
|
+
const id = String(e.messageId ?? e.toolCallId ?? "");
|
|
22
|
+
switch (e.type) {
|
|
23
|
+
case EventType.TEXT_MESSAGE_START:
|
|
24
|
+
if (!this.find("text", id))
|
|
25
|
+
this.order.push({ kind: "text", id, text: "", open: true });
|
|
26
|
+
return;
|
|
27
|
+
case EventType.TEXT_MESSAGE_CONTENT: {
|
|
28
|
+
const x = this.find("text", id);
|
|
29
|
+
if (x)
|
|
30
|
+
x.text += String(e.delta ?? "");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
case EventType.TEXT_MESSAGE_END: {
|
|
34
|
+
const x = this.find("text", id);
|
|
35
|
+
if (x)
|
|
36
|
+
x.open = false;
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
case EventType.REASONING_MESSAGE_START:
|
|
40
|
+
if (!this.find("reasoning", id))
|
|
41
|
+
this.order.push({ kind: "reasoning", id, text: "", open: true });
|
|
42
|
+
return;
|
|
43
|
+
case EventType.REASONING_MESSAGE_CONTENT: {
|
|
44
|
+
const x = this.find("reasoning", id);
|
|
45
|
+
if (x)
|
|
46
|
+
x.text += String(e.delta ?? "");
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
case EventType.REASONING_MESSAGE_END: {
|
|
50
|
+
const x = this.find("reasoning", id);
|
|
51
|
+
if (x)
|
|
52
|
+
x.open = false;
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
case EventType.TOOL_CALL_START:
|
|
56
|
+
if (!this.find("tool", id))
|
|
57
|
+
this.order.push({ kind: "tool", id, name: String(e.toolCallName ?? ""), ...(e.parentMessageId ? { parent: String(e.parentMessageId) } : {}), args: "", end: null });
|
|
58
|
+
return;
|
|
59
|
+
case EventType.TOOL_CALL_ARGS: {
|
|
60
|
+
const x = this.find("tool", id);
|
|
61
|
+
if (x)
|
|
62
|
+
x.args += String(e.delta ?? "");
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
case EventType.TOOL_CALL_END: {
|
|
66
|
+
const x = this.find("tool", id);
|
|
67
|
+
if (x)
|
|
68
|
+
x.end = e;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
case EventType.ACTIVITY_SNAPSHOT: {
|
|
72
|
+
const x = this.find("activity", id);
|
|
73
|
+
if (x) {
|
|
74
|
+
if (e.replace !== false)
|
|
75
|
+
x.event = e;
|
|
76
|
+
}
|
|
77
|
+
else
|
|
78
|
+
this.order.push({ kind: "activity", id, event: e });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** The run so far as events: one CONTENT per message (the text so far), each START with its END if it ended. */
|
|
84
|
+
replay() {
|
|
85
|
+
const out = [];
|
|
86
|
+
for (const x of this.order) {
|
|
87
|
+
if (x.kind === "text") {
|
|
88
|
+
out.push({ type: EventType.TEXT_MESSAGE_START, messageId: x.id, role: "assistant" });
|
|
89
|
+
if (x.text)
|
|
90
|
+
out.push({ type: EventType.TEXT_MESSAGE_CONTENT, messageId: x.id, delta: x.text });
|
|
91
|
+
if (!x.open)
|
|
92
|
+
out.push({ type: EventType.TEXT_MESSAGE_END, messageId: x.id });
|
|
93
|
+
}
|
|
94
|
+
else if (x.kind === "reasoning") {
|
|
95
|
+
out.push({ type: EventType.REASONING_START, messageId: x.id });
|
|
96
|
+
out.push({ type: EventType.REASONING_MESSAGE_START, messageId: x.id, role: "reasoning" });
|
|
97
|
+
if (x.text)
|
|
98
|
+
out.push({ type: EventType.REASONING_MESSAGE_CONTENT, messageId: x.id, delta: x.text });
|
|
99
|
+
if (!x.open)
|
|
100
|
+
out.push({ type: EventType.REASONING_MESSAGE_END, messageId: x.id }, { type: EventType.REASONING_END, messageId: x.id });
|
|
101
|
+
}
|
|
102
|
+
else if (x.kind === "tool") {
|
|
103
|
+
out.push({ type: EventType.TOOL_CALL_START, toolCallId: x.id, toolCallName: x.name, ...(x.parent ? { parentMessageId: x.parent } : {}) });
|
|
104
|
+
if (x.args)
|
|
105
|
+
out.push({ type: EventType.TOOL_CALL_ARGS, toolCallId: x.id, delta: x.args });
|
|
106
|
+
if (x.end)
|
|
107
|
+
out.push(x.end);
|
|
108
|
+
}
|
|
109
|
+
else
|
|
110
|
+
out.push(x.event);
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
find(kind, id) {
|
|
115
|
+
return this.order.find((x) => x.kind === kind && x.id === id);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const isEnd = (e) => e.type === EventType.RUN_FINISHED || e.type === EventType.RUN_ERROR;
|
|
119
|
+
/**
|
|
120
|
+
* One run per thread in this process, which outlives the HTTP request that started it, and its events to any number
|
|
121
|
+
* of listeners. A listener that joins mid-run (a reload, a second tab, a reconnect) gets `READY`, `RUN_STARTED` and a
|
|
122
|
+
* replay of the run so far, then the live events: the follower contract agent-paseo's runner keeps
|
|
123
|
+
* (`.ea/docs/agent-chat.md`). Nothing is persisted here; the run's store has the session and the run row.
|
|
124
|
+
*/
|
|
125
|
+
export class RunRegistry {
|
|
126
|
+
runs = new Map();
|
|
127
|
+
listeners = new Map();
|
|
128
|
+
warn;
|
|
129
|
+
constructor(o = {}) {
|
|
130
|
+
this.warn = o.warn ?? ((m, d) => console.warn(`agent-pi: ${m}`, d ?? ""));
|
|
131
|
+
}
|
|
132
|
+
running(threadId) {
|
|
133
|
+
return this.runs.has(threadId);
|
|
134
|
+
}
|
|
135
|
+
current(threadId) {
|
|
136
|
+
const r = this.runs.get(threadId);
|
|
137
|
+
return r ? { runId: r.runId } : null;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Starts a run on a thread; throws `Busy` when the thread has one. `fn` gets the run's id, thread, stop signal and
|
|
141
|
+
* event sink (`runAgent({ ...options, ...run })`). The registry guarantees each run one terminal event: when `fn`
|
|
142
|
+
* throws or settles without one, it sends `RUN_ERROR` / `RUN_FINISHED` itself. The run leaves the registry with its
|
|
143
|
+
* terminal event; events after it are dropped. `result` is `fn`'s promise (already handled: not awaiting it is fine).
|
|
144
|
+
*/
|
|
145
|
+
start(threadId, fn, o = {}) {
|
|
146
|
+
const cur = this.runs.get(threadId);
|
|
147
|
+
if (cur)
|
|
148
|
+
throw new Busy(threadId, cur.runId);
|
|
149
|
+
const run = { runId: o.runId ?? `run_${randomBytes(9).toString("base64url")}`, threadId, metadata: o.metadata, abort: new AbortController(), folder: new RunFolder(), started: null, ended: false };
|
|
150
|
+
this.runs.set(threadId, run);
|
|
151
|
+
let result;
|
|
152
|
+
try {
|
|
153
|
+
result = Promise.resolve(fn({ runId: run.runId, threadId, signal: run.abort.signal, onEvent: (e) => this.onEvent(run, e) }));
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
result = Promise.reject(err);
|
|
157
|
+
}
|
|
158
|
+
result.then(() => this.end(run, { type: EventType.RUN_FINISHED, threadId, runId: run.runId }), (err) => this.end(run, { type: EventType.RUN_ERROR, message: err instanceof Error ? err.message : String(err), metadata: { threadId, runId: run.runId } }));
|
|
159
|
+
return { runId: run.runId, result };
|
|
160
|
+
}
|
|
161
|
+
/** Aborts the thread's run (only `runId`'s, when given). False when there is no such run. */
|
|
162
|
+
stop(threadId, runId) {
|
|
163
|
+
const r = this.runs.get(threadId);
|
|
164
|
+
if (!r || (runId && r.runId !== runId))
|
|
165
|
+
return false;
|
|
166
|
+
r.abort.abort();
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Follows a thread: `CUSTOM READY {threadId, runId, running}` at once; when a run is in progress, `RUN_STARTED` and
|
|
171
|
+
* the replay of the run so far (once the run has started); then live events. Returns the unsubscribe.
|
|
172
|
+
*/
|
|
173
|
+
listen(threadId, fn) {
|
|
174
|
+
let set = this.listeners.get(threadId);
|
|
175
|
+
if (!set)
|
|
176
|
+
this.listeners.set(threadId, (set = new Set()));
|
|
177
|
+
const r = this.runs.get(threadId);
|
|
178
|
+
const value = { threadId, runId: r?.runId ?? null, running: Boolean(r) };
|
|
179
|
+
this.call(fn, { type: EventType.CUSTOM, name: "READY", value });
|
|
180
|
+
if (r?.started) {
|
|
181
|
+
this.call(fn, r.started);
|
|
182
|
+
for (const e of r.folder.replay())
|
|
183
|
+
this.call(fn, e);
|
|
184
|
+
}
|
|
185
|
+
set.add(fn);
|
|
186
|
+
return () => {
|
|
187
|
+
set.delete(fn);
|
|
188
|
+
if (!set.size && this.listeners.get(threadId) === set)
|
|
189
|
+
this.listeners.delete(threadId);
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/** Aborts every run (shutdown). */
|
|
193
|
+
close() {
|
|
194
|
+
for (const r of this.runs.values())
|
|
195
|
+
r.abort.abort();
|
|
196
|
+
}
|
|
197
|
+
onEvent(run, e) {
|
|
198
|
+
if (run.ended)
|
|
199
|
+
return;
|
|
200
|
+
if (e.type === EventType.RUN_STARTED) {
|
|
201
|
+
if (run.started)
|
|
202
|
+
return;
|
|
203
|
+
e = run.metadata ? { ...e, metadata: { ...(e.metadata ?? {}), ...run.metadata } } : e;
|
|
204
|
+
run.started = e;
|
|
205
|
+
}
|
|
206
|
+
else if (isEnd(e))
|
|
207
|
+
return this.end(run, e);
|
|
208
|
+
else if (!run.started) {
|
|
209
|
+
// A run that skipped RUN_STARTED (a host fn, not runAgent) gets one before its first event.
|
|
210
|
+
run.started = { type: EventType.RUN_STARTED, threadId: run.threadId, runId: run.runId, ...(run.metadata ? { metadata: run.metadata } : {}) };
|
|
211
|
+
this.send(run, run.started);
|
|
212
|
+
}
|
|
213
|
+
run.folder.fold(e);
|
|
214
|
+
this.send(run, e);
|
|
215
|
+
}
|
|
216
|
+
end(run, e) {
|
|
217
|
+
if (run.ended)
|
|
218
|
+
return;
|
|
219
|
+
run.ended = true;
|
|
220
|
+
if (this.runs.get(run.threadId) === run)
|
|
221
|
+
this.runs.delete(run.threadId);
|
|
222
|
+
this.send(run, e);
|
|
223
|
+
}
|
|
224
|
+
/** Delivers to the listeners there are now: one that joins during delivery got this event in its replay already. */
|
|
225
|
+
send(run, e) {
|
|
226
|
+
for (const fn of [...(this.listeners.get(run.threadId) ?? [])])
|
|
227
|
+
this.call(fn, e);
|
|
228
|
+
}
|
|
229
|
+
call(fn, e) {
|
|
230
|
+
try {
|
|
231
|
+
fn(e);
|
|
232
|
+
}
|
|
233
|
+
catch (err) {
|
|
234
|
+
this.warn("listener failed", err);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
export function runRegistry(o) {
|
|
239
|
+
return new RunRegistry(o);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* At startup, before serving: runs the store still shows `running` were never finished (the process that ran them is
|
|
243
|
+
* gone, and with it their registry), so they are marked failed. Returns how many. Hosts with their own visible-thread
|
|
244
|
+
* rows (`rudi_messages`, a chat message `streaming`) fail those in the same place.
|
|
245
|
+
*/
|
|
246
|
+
export function failOrphans(store) {
|
|
247
|
+
return store.failStaleRuns();
|
|
248
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PiRunEvent } from "./run.ts";
|
|
2
|
+
import type { RunListener } from "./registry.ts";
|
|
3
|
+
/** What `sseResponse` needs: anything with agent-paseo's / the registry's `listen` (so it serves either part). */
|
|
4
|
+
export interface Listenable {
|
|
5
|
+
listen(threadId: string, fn: RunListener): () => void;
|
|
6
|
+
}
|
|
7
|
+
export interface SseOptions {
|
|
8
|
+
/** The request's signal (Hono: `c.req.raw.signal`): the stream ends when the client goes. The run goes on. */
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
/** A `: ping` comment this often, so proxies keep the stream open. Default 15 000; 0 for none. */
|
|
11
|
+
pingMs?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Close the stream after the run's terminal event (a POST that streams its own answer), or at once when `READY`
|
|
14
|
+
* says no run is in progress (it ended before the response was made). Default false: follow the thread.
|
|
15
|
+
*/
|
|
16
|
+
endAfterRun?: boolean;
|
|
17
|
+
/** Extra response headers. */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
/** One event as SSE: `event: <type, or a CUSTOM event's name>` and `data: <json>` (JSON has no raw newline). */
|
|
21
|
+
export declare function sseFrame(e: PiRunEvent): string;
|
|
22
|
+
/**
|
|
23
|
+
* A thread's events as a web `Response` (`text/event-stream`), for any Fetch-API server (Hono: `return
|
|
24
|
+
* sseResponse(registry, id, { signal: c.req.raw.signal })`). The first events are the follower contract's `READY` and
|
|
25
|
+
* replay. Ends when `signal` aborts or the client cancels the body; the run is never stopped by it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function sseResponse(source: Listenable, threadId: string, o?: SseOptions): Response;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** One event as SSE: `event: <type, or a CUSTOM event's name>` and `data: <json>` (JSON has no raw newline). */
|
|
2
|
+
export function sseFrame(e) {
|
|
3
|
+
const name = String(e.type === "CUSTOM" && typeof e.name === "string" ? e.name : e.type).replace(/[\r\n]/g, " ");
|
|
4
|
+
return `event: ${name}\ndata: ${JSON.stringify(e)}\n\n`;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* A thread's events as a web `Response` (`text/event-stream`), for any Fetch-API server (Hono: `return
|
|
8
|
+
* sseResponse(registry, id, { signal: c.req.raw.signal })`). The first events are the follower contract's `READY` and
|
|
9
|
+
* replay. Ends when `signal` aborts or the client cancels the body; the run is never stopped by it.
|
|
10
|
+
*/
|
|
11
|
+
export function sseResponse(source, threadId, o = {}) {
|
|
12
|
+
const encoder = new TextEncoder();
|
|
13
|
+
let finish = () => { };
|
|
14
|
+
const body = new ReadableStream({
|
|
15
|
+
start(controller) {
|
|
16
|
+
let done = false;
|
|
17
|
+
let off = null;
|
|
18
|
+
let ping = null;
|
|
19
|
+
const write = (text) => {
|
|
20
|
+
if (done)
|
|
21
|
+
return;
|
|
22
|
+
try {
|
|
23
|
+
controller.enqueue(encoder.encode(text));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
finish();
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
finish = () => {
|
|
30
|
+
if (done)
|
|
31
|
+
return;
|
|
32
|
+
done = true;
|
|
33
|
+
off?.();
|
|
34
|
+
if (ping)
|
|
35
|
+
clearInterval(ping);
|
|
36
|
+
o.signal?.removeEventListener("abort", finish);
|
|
37
|
+
try {
|
|
38
|
+
controller.close();
|
|
39
|
+
}
|
|
40
|
+
catch { }
|
|
41
|
+
};
|
|
42
|
+
if (o.signal?.aborted)
|
|
43
|
+
return finish();
|
|
44
|
+
o.signal?.addEventListener("abort", finish);
|
|
45
|
+
write(": connected\n\n");
|
|
46
|
+
let ended = false;
|
|
47
|
+
off = source.listen(threadId, (e) => {
|
|
48
|
+
write(sseFrame(e));
|
|
49
|
+
if (o.endAfterRun && (e.type === "RUN_FINISHED" || e.type === "RUN_ERROR"))
|
|
50
|
+
ended = true;
|
|
51
|
+
if (o.endAfterRun && e.type === "CUSTOM" && e.name === "READY" && !e.value?.running)
|
|
52
|
+
ended = true;
|
|
53
|
+
if (ended)
|
|
54
|
+
queueMicrotask(finish);
|
|
55
|
+
});
|
|
56
|
+
if (done)
|
|
57
|
+
off();
|
|
58
|
+
const every = o.pingMs ?? 15_000;
|
|
59
|
+
if (every > 0 && !done)
|
|
60
|
+
ping = setInterval(() => write(": ping\n\n"), every);
|
|
61
|
+
},
|
|
62
|
+
cancel() {
|
|
63
|
+
finish();
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
return new Response(body, {
|
|
67
|
+
headers: {
|
|
68
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
69
|
+
"cache-control": "no-store",
|
|
70
|
+
connection: "keep-alive",
|
|
71
|
+
"x-accel-buffering": "no",
|
|
72
|
+
...o.headers,
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lightblues/jig",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.9",
|
|
4
4
|
"description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, and more as they prove reusable.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|