@lightblues/jig 0.0.7 → 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/README.md +1 -1
- package/dist/agent-pi/index.d.ts +15 -0
- package/dist/agent-pi/index.js +10 -0
- package/dist/agent-pi/models.d.ts +91 -0
- package/dist/agent-pi/models.js +107 -0
- package/dist/agent-pi/registry.d.ts +93 -0
- package/dist/agent-pi/registry.js +248 -0
- package/dist/agent-pi/run.d.ts +160 -0
- package/dist/agent-pi/run.js +471 -0
- package/dist/agent-pi/sse.d.ts +27 -0
- package/dist/agent-pi/sse.js +75 -0
- package/dist/agent-pi/store.d.ts +112 -0
- package/dist/agent-pi/store.js +161 -0
- package/package.json +23 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Planned parts (design: baton `.ea/log/2026-11-24-shared-agent-ui.md`, item #274)
|
|
|
7
7
|
| Subpath | What |
|
|
8
8
|
|---|---|
|
|
9
9
|
| `@lightblues/jig/agent-paseo` | server adapter: a Paseo agent's timeline as AG-UI events, with replay and recovery |
|
|
10
|
-
| `@lightblues/jig/agent-pi` | server runtime for in-app pi agents: models
|
|
10
|
+
| `@lightblues/jig/agent-pi` | server runtime for in-app pi agents: router models with tiers, sessions and runs in the host's own Postgres tables, one run as AG-UI events (run registry and SSE route: next) |
|
|
11
11
|
| `@lightblues/jig/agent-chat` | a thin headless client: follow a thread over SSE, reconnect, fold events into messages |
|
|
12
12
|
|
|
13
13
|
The protocol is AG-UI (`@ag-ui/core`), used as is.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lightblues/jig/agent-pi`: the server runtime for in-app pi agents (vibeU, erudite, lemma): router models with
|
|
3
|
+
* tiers, sessions and run rows in the host's own tables, and one `AgentSession` run that emits `@ag-ui/core` events.
|
|
4
|
+
* The host keeps auth, tool binding, prompts, tools, budgets and rendering. See `.ea/docs/agent-pi.md`.
|
|
5
|
+
*/
|
|
6
|
+
export { costOf, modelCost, parsePrices, piModels, routerModel, singleModel } from "./models.ts";
|
|
7
|
+
export type { ModelPrice, ModelStream, PiModel, PiModels, PiModelsOptions, PurposeModel, Thinking } from "./models.ts";
|
|
8
|
+
export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, windowEntries, withoutEmptyImages, withoutImages } from "./run.ts";
|
|
9
|
+
export type { Card, PiRunEvent, RunAgentOptions, RunLimits, RunResult, RunTool, Turn } from "./run.ts";
|
|
10
|
+
export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.ts";
|
|
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";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lightblues/jig/agent-pi`: the server runtime for in-app pi agents (vibeU, erudite, lemma): router models with
|
|
3
|
+
* tiers, sessions and run rows in the host's own tables, and one `AgentSession` run that emits `@ag-ui/core` events.
|
|
4
|
+
* The host keeps auth, tool binding, prompts, tools, budgets and rendering. See `.ea/docs/agent-pi.md`.
|
|
5
|
+
*/
|
|
6
|
+
export { costOf, modelCost, parsePrices, piModels, routerModel, singleModel } from "./models.js";
|
|
7
|
+
export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, windowEntries, withoutEmptyImages, withoutImages } from "./run.js";
|
|
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,91 @@
|
|
|
1
|
+
import type { StreamFn } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { type Model, type Usage } from "@earendil-works/pi-ai";
|
|
3
|
+
/** A model stream that returns at once, the form pi takes for a registered provider. */
|
|
4
|
+
export type ModelStream = (...args: Parameters<StreamFn>) => Awaited<ReturnType<StreamFn>>;
|
|
5
|
+
/** pi's thinking levels a purpose may ask for; a model without reasoning always runs `off`. */
|
|
6
|
+
export type Thinking = "off" | "minimal" | "low" | "medium" | "high";
|
|
7
|
+
/** One model and how to stream from it. Tests build one from pi-ai's faux provider (`fauxModel`). */
|
|
8
|
+
export interface PiModel {
|
|
9
|
+
id: string;
|
|
10
|
+
model: Model<any>;
|
|
11
|
+
streamFn: ModelStream;
|
|
12
|
+
}
|
|
13
|
+
/** Which tier and how much thinking a kind of run gets. */
|
|
14
|
+
export interface PurposeModel {
|
|
15
|
+
tier: string;
|
|
16
|
+
thinking: Thinking;
|
|
17
|
+
}
|
|
18
|
+
/** US dollars per million tokens; a missing `cacheWrite` is 0. */
|
|
19
|
+
export interface ModelPrice {
|
|
20
|
+
input: number;
|
|
21
|
+
output: number;
|
|
22
|
+
cacheRead: number;
|
|
23
|
+
cacheWrite?: number;
|
|
24
|
+
}
|
|
25
|
+
/** What `runAgent` asks of the models: the model, tier name and thinking level of a purpose. */
|
|
26
|
+
export interface PiModels {
|
|
27
|
+
pick(purpose: string): {
|
|
28
|
+
model: PiModel;
|
|
29
|
+
tier: string;
|
|
30
|
+
thinking: Thinking;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export interface PiModelsOptions<TTier extends string, TPurpose extends string> {
|
|
34
|
+
/** The OpenAI-compatible router (`…/v1`). */
|
|
35
|
+
baseUrl: string;
|
|
36
|
+
/** The router key. It only lives in `streamFn`; pi's runtime is registered with a dummy key. */
|
|
37
|
+
apiKey: string;
|
|
38
|
+
/** The model id behind each tier (`{ haiku: 'cbi/deepseek-v4.1-flash', … }`). */
|
|
39
|
+
tiers: Record<TTier, string>;
|
|
40
|
+
/** The tier and thinking of each purpose. An unknown purpose throws in `pick`. */
|
|
41
|
+
purposes: Record<TPurpose, {
|
|
42
|
+
tier: TTier;
|
|
43
|
+
thinking: Thinking;
|
|
44
|
+
}>;
|
|
45
|
+
/** Prices by model id; an unpriced model costs 0 (`warn` says so once). */
|
|
46
|
+
prices?: Record<string, ModelPrice>;
|
|
47
|
+
/** The provider name pi registers the models under (the host's name: `erudite`, `vibeu`, `lemma`). Default `jig`. */
|
|
48
|
+
provider?: string;
|
|
49
|
+
/** What the models take. Default `['text', 'image']`. */
|
|
50
|
+
input?: ("text" | "image")[];
|
|
51
|
+
/** Default 128 000. */
|
|
52
|
+
contextWindow?: number;
|
|
53
|
+
/** pi's default output cap; `runAgent` sets its own from `limits`. Default 4 000. */
|
|
54
|
+
maxTokens?: number;
|
|
55
|
+
/** Default `console.warn`. */
|
|
56
|
+
warn?: (message: string) => void;
|
|
57
|
+
}
|
|
58
|
+
/** A model's rates as pi takes them; an unpriced model costs 0. */
|
|
59
|
+
export declare const modelCost: (price: ModelPrice | undefined) => Model<any>["cost"];
|
|
60
|
+
/**
|
|
61
|
+
* `base` with the prices in `json` (an env value, JSON keyed by model id) over them. Malformed JSON keeps `base`;
|
|
62
|
+
* a malformed entry is skipped. `warn` says which.
|
|
63
|
+
*/
|
|
64
|
+
export declare function parsePrices(json: string | undefined, base?: Record<string, ModelPrice>, warn?: (message: string) => void): Record<string, ModelPrice>;
|
|
65
|
+
/**
|
|
66
|
+
* One router model. DeepSeek takes `thinking: {type}` and wants its reasoning sent back on later turns; pi detects
|
|
67
|
+
* that only for its own provider, so the compat flags are set here by id.
|
|
68
|
+
*/
|
|
69
|
+
export declare function routerModel(id: string, o: {
|
|
70
|
+
baseUrl: string;
|
|
71
|
+
apiKey: string;
|
|
72
|
+
provider?: string;
|
|
73
|
+
price?: ModelPrice;
|
|
74
|
+
input?: ("text" | "image")[];
|
|
75
|
+
contextWindow?: number;
|
|
76
|
+
maxTokens?: number;
|
|
77
|
+
}): PiModel;
|
|
78
|
+
/**
|
|
79
|
+
* The tiers behind an OpenAI-compatible router, and which tier and thinking each purpose gets. The key is injected
|
|
80
|
+
* in each model's `streamFn`, never registered with pi.
|
|
81
|
+
*/
|
|
82
|
+
export declare function piModels<TTier extends string, TPurpose extends string>(o: PiModelsOptions<TTier, TPurpose>): PiModels & {
|
|
83
|
+
tier(name: TTier): PiModel;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* One model for every purpose, with the purposes' tier names and thinking (tests: a faux model). A purpose not in
|
|
87
|
+
* `purposes` runs as tier `default` without thinking.
|
|
88
|
+
*/
|
|
89
|
+
export declare function singleModel(model: PiModel, purposes?: Record<string, PurposeModel>): PiModels;
|
|
90
|
+
/** A reply's cost: what the provider worked out, else the model's rates over its usage (a faux stream prices nothing). */
|
|
91
|
+
export declare function costOf(model: PiModel, usage: Usage): number;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { calculateCost } from "@earendil-works/pi-ai";
|
|
2
|
+
import { streamSimple } from "@earendil-works/pi-ai/api/openai-completions";
|
|
3
|
+
/** A model's rates as pi takes them; an unpriced model costs 0. */
|
|
4
|
+
export const modelCost = (price) => price ? { input: price.input, output: price.output, cacheRead: price.cacheRead, cacheWrite: price.cacheWrite ?? 0 } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
5
|
+
const isPrice = (value) => {
|
|
6
|
+
const p = value;
|
|
7
|
+
return (!!p &&
|
|
8
|
+
typeof p === "object" &&
|
|
9
|
+
["input", "output", "cacheRead"].every((k) => typeof p[k] === "number" && p[k] >= 0) &&
|
|
10
|
+
(p.cacheWrite === undefined || (typeof p.cacheWrite === "number" && p.cacheWrite >= 0)));
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* `base` with the prices in `json` (an env value, JSON keyed by model id) over them. Malformed JSON keeps `base`;
|
|
14
|
+
* a malformed entry is skipped. `warn` says which.
|
|
15
|
+
*/
|
|
16
|
+
export function parsePrices(json, base = {}, warn = console.warn) {
|
|
17
|
+
const prices = { ...base };
|
|
18
|
+
if (!json)
|
|
19
|
+
return prices;
|
|
20
|
+
let given;
|
|
21
|
+
try {
|
|
22
|
+
given = JSON.parse(json);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
warn("model prices are not JSON; using the built-in prices");
|
|
26
|
+
return prices;
|
|
27
|
+
}
|
|
28
|
+
for (const [id, price] of Object.entries((given && typeof given === "object" ? given : {}))) {
|
|
29
|
+
if (isPrice(price))
|
|
30
|
+
prices[id] = price;
|
|
31
|
+
else
|
|
32
|
+
warn(`model price skipped: ${id}`);
|
|
33
|
+
}
|
|
34
|
+
return prices;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One router model. DeepSeek takes `thinking: {type}` and wants its reasoning sent back on later turns; pi detects
|
|
38
|
+
* that only for its own provider, so the compat flags are set here by id.
|
|
39
|
+
*/
|
|
40
|
+
export function routerModel(id, o) {
|
|
41
|
+
const deepseek = /deepseek/i.test(id);
|
|
42
|
+
const model = {
|
|
43
|
+
id,
|
|
44
|
+
name: id,
|
|
45
|
+
api: "openai-completions",
|
|
46
|
+
provider: o.provider ?? "jig",
|
|
47
|
+
baseUrl: o.baseUrl,
|
|
48
|
+
reasoning: true,
|
|
49
|
+
input: o.input ?? ["text", "image"],
|
|
50
|
+
cost: modelCost(o.price),
|
|
51
|
+
contextWindow: o.contextWindow ?? 128_000,
|
|
52
|
+
maxTokens: o.maxTokens ?? 4_000,
|
|
53
|
+
compat: {
|
|
54
|
+
supportsStore: false,
|
|
55
|
+
supportsDeveloperRole: false,
|
|
56
|
+
maxTokensField: "max_tokens",
|
|
57
|
+
...(deepseek ? { thinkingFormat: "deepseek", requiresReasoningContentOnAssistantMessages: true, supportsReasoningEffort: false } : {}),
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
const apiKey = o.apiKey;
|
|
61
|
+
return { id, model, streamFn: (m, context, options) => streamSimple(m, context, { ...options, apiKey }) };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The tiers behind an OpenAI-compatible router, and which tier and thinking each purpose gets. The key is injected
|
|
65
|
+
* in each model's `streamFn`, never registered with pi.
|
|
66
|
+
*/
|
|
67
|
+
export function piModels(o) {
|
|
68
|
+
const warn = o.warn ?? console.warn;
|
|
69
|
+
const byTier = new Map();
|
|
70
|
+
for (const [tier, id] of Object.entries(o.tiers)) {
|
|
71
|
+
const price = o.prices?.[id];
|
|
72
|
+
if (o.prices && !price)
|
|
73
|
+
warn(`model ${id} has no price; its runs cost 0`);
|
|
74
|
+
byTier.set(tier, routerModel(id, { ...o, price }));
|
|
75
|
+
}
|
|
76
|
+
for (const [purpose, pick] of Object.entries(o.purposes)) {
|
|
77
|
+
if (!byTier.has(pick.tier))
|
|
78
|
+
throw new Error(`purpose ${purpose} names tier ${pick.tier}, which has no model`);
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
tier: (name) => {
|
|
82
|
+
const model = byTier.get(name);
|
|
83
|
+
if (!model)
|
|
84
|
+
throw new Error(`no model for tier ${name}`);
|
|
85
|
+
return model;
|
|
86
|
+
},
|
|
87
|
+
pick: (purpose) => {
|
|
88
|
+
const pick = o.purposes[purpose];
|
|
89
|
+
if (!pick)
|
|
90
|
+
throw new Error(`unknown purpose ${purpose}`);
|
|
91
|
+
return { model: byTier.get(pick.tier), tier: pick.tier, thinking: pick.thinking };
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* One model for every purpose, with the purposes' tier names and thinking (tests: a faux model). A purpose not in
|
|
97
|
+
* `purposes` runs as tier `default` without thinking.
|
|
98
|
+
*/
|
|
99
|
+
export function singleModel(model, purposes = {}) {
|
|
100
|
+
return { pick: (purpose) => ({ model, tier: purposes[purpose]?.tier ?? "default", thinking: purposes[purpose]?.thinking ?? "off" }) };
|
|
101
|
+
}
|
|
102
|
+
/** A reply's cost: what the provider worked out, else the model's rates over its usage (a faux stream prices nothing). */
|
|
103
|
+
export function costOf(model, usage) {
|
|
104
|
+
if (usage.cost?.total)
|
|
105
|
+
return usage.cost.total;
|
|
106
|
+
return calculateCost(model.model, { ...usage, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }).total;
|
|
107
|
+
}
|
|
@@ -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
|
+
}
|