@lightblues/jig 0.0.7 → 0.0.8
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 +11 -0
- package/dist/agent-pi/index.js +8 -0
- package/dist/agent-pi/models.d.ts +91 -0
- package/dist/agent-pi/models.js +107 -0
- package/dist/agent-pi/run.d.ts +160 -0
- package/dist/agent-pi/run.js +471 -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,11 @@
|
|
|
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";
|
|
@@ -0,0 +1,8 @@
|
|
|
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";
|
|
@@ -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,160 @@
|
|
|
1
|
+
import { type BaseEvent } from "@ag-ui/core";
|
|
2
|
+
import type { ImageContent, TSchema } from "@earendil-works/pi-ai";
|
|
3
|
+
import { type FileEntry, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { type PiModels } from "./models.ts";
|
|
5
|
+
import { type RunStatus, type RunUsage, type SessionStore } from "./store.ts";
|
|
6
|
+
/**
|
|
7
|
+
* Limits per run. `toolCalls` and `ms` stop a run that went wrong (a loop, a hung tool), not a normal one;
|
|
8
|
+
* `outputTokens` is the most one model reply may write, `thinkingTokens` what a thinking run may write on top;
|
|
9
|
+
* `toolResultChars` cuts one tool's result so it cannot fill the context.
|
|
10
|
+
*/
|
|
11
|
+
export interface RunLimits {
|
|
12
|
+
toolCalls: number;
|
|
13
|
+
ms: number;
|
|
14
|
+
outputTokens: number;
|
|
15
|
+
thinkingTokens: number;
|
|
16
|
+
toolResultChars: number;
|
|
17
|
+
}
|
|
18
|
+
/** erudite's and lemma's limits (vibeU's chat raises `toolCalls` to 40 and `ms` to 600 000). */
|
|
19
|
+
export declare const DEFAULT_LIMITS: RunLimits;
|
|
20
|
+
/** A tool already bound to the run's owner by the host: the model supplies `args` and nothing else. */
|
|
21
|
+
export interface RunTool {
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
parameters: TSchema;
|
|
25
|
+
/** `data` is what the model reads (JSON, cut at `toolResultChars`); each card becomes an `ACTIVITY_SNAPSHOT`. */
|
|
26
|
+
execute: (args: any, ctx: {
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
}) => Promise<{
|
|
29
|
+
data: unknown;
|
|
30
|
+
cards?: Card[];
|
|
31
|
+
}>;
|
|
32
|
+
}
|
|
33
|
+
/** A card a tool shows the user: the host's JSON, drawn by the host's component for `kind`. */
|
|
34
|
+
export type Card = {
|
|
35
|
+
kind: string;
|
|
36
|
+
} & Record<string, unknown>;
|
|
37
|
+
/** History by plain turns, for a session that does not exist yet (vibeU's chats from before sessions). */
|
|
38
|
+
export type Turn = {
|
|
39
|
+
role: "user" | "assistant";
|
|
40
|
+
text: string;
|
|
41
|
+
};
|
|
42
|
+
export interface RunAgentOptions {
|
|
43
|
+
store: SessionStore;
|
|
44
|
+
models: PiModels;
|
|
45
|
+
/** The thread this run continues: its session is loaded and grows. Null: a one-off session (a batch, a decision). */
|
|
46
|
+
scope: string | null;
|
|
47
|
+
/** Whose run this is: the host's id from its auth, never from the request. Stored on the session and the run. */
|
|
48
|
+
ownerId: string;
|
|
49
|
+
/** Which kind of run: picks the tier and thinking (`models`), recorded on the run. */
|
|
50
|
+
purpose: string;
|
|
51
|
+
system: string;
|
|
52
|
+
tools?: RunTool[];
|
|
53
|
+
/** pi tool definitions used as they are (lemma's read-only file tools); counted against `toolCalls` like the others. */
|
|
54
|
+
piTools?: ToolDefinition<any, any>[];
|
|
55
|
+
/** The user turn. Images go to this run only; the stored session keeps `imagePlaceholder` instead of their bytes. */
|
|
56
|
+
input: {
|
|
57
|
+
text: string;
|
|
58
|
+
images?: ImageContent[];
|
|
59
|
+
};
|
|
60
|
+
limits?: Partial<RunLimits>;
|
|
61
|
+
/** Aborting it stops the run: status `stopped`, the text so far kept. */
|
|
62
|
+
signal?: AbortSignal;
|
|
63
|
+
/** Ids that say what the run was about, in the session's etho entry (a batch: also its title). */
|
|
64
|
+
labels?: Record<string, string>;
|
|
65
|
+
/** AG-UI events of the run, in order. A throwing listener is logged, never stops the run. */
|
|
66
|
+
onEvent?: (event: PiRunEvent) => void;
|
|
67
|
+
/** The etho entry written into a new session: `app` (`erudite`), and the label that names the owner (`user`, `space`). False: none. */
|
|
68
|
+
etho?: {
|
|
69
|
+
app: string;
|
|
70
|
+
ownerLabel?: string;
|
|
71
|
+
} | false;
|
|
72
|
+
/** AG-UI `threadId`. Default the scope, else the session id. */
|
|
73
|
+
threadId?: string;
|
|
74
|
+
/** The run's id. Default `run_` + 12 random characters. */
|
|
75
|
+
runId?: string;
|
|
76
|
+
/** pi's working directory, named in the system prompt. Default `/`. */
|
|
77
|
+
cwd?: string;
|
|
78
|
+
/** Read only the last this many user messages of the thread; what the run writes still goes after the thread's last entry. */
|
|
79
|
+
window?: number;
|
|
80
|
+
/** Answer the session's last user message again: the new answer branches off before it; `input` is the message re-sent. */
|
|
81
|
+
retry?: boolean;
|
|
82
|
+
/** Turns to start a new session with; ignored when the scope has a session. */
|
|
83
|
+
history?: Turn[];
|
|
84
|
+
/** False: keep no session at all (no row, no entries); the run row has no session id. Default true. */
|
|
85
|
+
persist?: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* When pi compacts the thread: past `historyTokens` of history (besides the system prompt and tools) it keeps a
|
|
88
|
+
* summary and the last `keep` share. False: never. Default: pi's own setting.
|
|
89
|
+
*/
|
|
90
|
+
compaction?: {
|
|
91
|
+
historyTokens: number;
|
|
92
|
+
keep?: number;
|
|
93
|
+
} | false;
|
|
94
|
+
/** What a stored image becomes for the model on later runs. Default `[an image shown earlier]`. */
|
|
95
|
+
imagePlaceholder?: string;
|
|
96
|
+
/** What the model reads when a tool throws (erudite: the API error's message). Default `the tool failed` (an error's message can hold internals). */
|
|
97
|
+
toolError?: (err: unknown, tool: string) => string | Promise<string>;
|
|
98
|
+
/** The args of a call the user may see (a summary); undefined shows none. Default: none. Never the result. */
|
|
99
|
+
showArgs?: (tool: string, args: unknown) => unknown;
|
|
100
|
+
/** Host columns of the run row (vibeU `{ user_id }`). */
|
|
101
|
+
runColumns?: Record<string, string | number | boolean | null>;
|
|
102
|
+
/** How often pi retries a failed model call (with backoff from 2 s). Default 2, as the hosts have it. */
|
|
103
|
+
retries?: number;
|
|
104
|
+
/** Default `console.warn`. */
|
|
105
|
+
warn?: (message: string, detail?: unknown) => void;
|
|
106
|
+
}
|
|
107
|
+
export interface RunResult {
|
|
108
|
+
runId: string;
|
|
109
|
+
status: RunStatus;
|
|
110
|
+
/** Every assistant text of the run, joined by a blank line. */
|
|
111
|
+
text: string;
|
|
112
|
+
/** The last step's text: the answer without what the model said before its tool calls. */
|
|
113
|
+
final: string;
|
|
114
|
+
cards: Card[];
|
|
115
|
+
usage: RunUsage;
|
|
116
|
+
/** Null for `ok`; else why (the model's error, `tool call limit`, `time limit`, `stopped`). */
|
|
117
|
+
error: string | null;
|
|
118
|
+
sessionId: string | null;
|
|
119
|
+
}
|
|
120
|
+
/** The events `runAgent` emits: `@ag-ui/core` events (design §4.2, `.ea/docs/agent-pi.md`). */
|
|
121
|
+
export type PiRunEvent = BaseEvent & Record<string, unknown>;
|
|
122
|
+
/** Text cut at `max` characters, marked. */
|
|
123
|
+
export declare function cutText(text: string, max: number): string;
|
|
124
|
+
/** Tokens of a text, roughly: a CJK character is about one, other text about four characters a token. */
|
|
125
|
+
export declare function estimateTokens(text: string): number;
|
|
126
|
+
/**
|
|
127
|
+
* The stored entries from the `turns`-th last user message on, the first one cut loose from its parent: the
|
|
128
|
+
* session a windowed run reads. The last entry stays the thread's last, so what the run appends follows it.
|
|
129
|
+
*/
|
|
130
|
+
export declare function windowEntries(entries: FileEntry[], turns: number): FileEntry[];
|
|
131
|
+
/** An entry as stored: an image part of a message becomes `placeholder` text, so the store never holds the bytes. */
|
|
132
|
+
export declare function withoutImages<T>(entry: T, placeholder: string): T;
|
|
133
|
+
/** A stored entry loaded again: an image without bytes (vibeU kept the part with empty data) becomes `placeholder` text. */
|
|
134
|
+
export declare function withoutEmptyImages<T>(entry: T, placeholder: string): T;
|
|
135
|
+
/**
|
|
136
|
+
* One run of a pi `AgentSession` with only the given tools, its session in the `store`: loaded before the run (or
|
|
137
|
+
* its last turns, `window`), each new entry stored as the run goes (images replaced by a placeholder), compacted by pi
|
|
138
|
+
* past the history budget. The run row exists from the start, so a run the server never finished is visible.
|
|
139
|
+
*
|
|
140
|
+
* Emits `@ag-ui/core` events through `onEvent` (design §4.2). Never throws once the run row exists: a model or store
|
|
141
|
+
* failure ends as a status. It throws only when the store cannot load, insert, or start the run (nothing ran yet).
|
|
142
|
+
*/
|
|
143
|
+
export declare function runAgent(o: RunAgentOptions): Promise<RunResult>;
|
|
144
|
+
/**
|
|
145
|
+
* Adds a user message to a thread's session without a run (an event the app recorded): the next run reads it in
|
|
146
|
+
* order. Makes the session, with its etho entry, when the scope has none yet.
|
|
147
|
+
*/
|
|
148
|
+
export declare function appendToThread(o: {
|
|
149
|
+
store: SessionStore;
|
|
150
|
+
scope: string;
|
|
151
|
+
ownerId: string;
|
|
152
|
+
purpose: string;
|
|
153
|
+
text: string;
|
|
154
|
+
at?: Date;
|
|
155
|
+
cwd?: string;
|
|
156
|
+
etho?: {
|
|
157
|
+
app: string;
|
|
158
|
+
ownerLabel?: string;
|
|
159
|
+
} | false;
|
|
160
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
import { tmpdir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { EventType } from "@ag-ui/core";
|
|
4
|
+
import { createAgentSession, createExtensionRuntime, defineTool, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { costOf } from "./models.js";
|
|
6
|
+
import { newRunId } from "./store.js";
|
|
7
|
+
/** erudite's and lemma's limits (vibeU's chat raises `toolCalls` to 40 and `ms` to 600 000). */
|
|
8
|
+
export const DEFAULT_LIMITS = { toolCalls: 20, ms: 180_000, outputTokens: 4_000, thinkingTokens: 8_000, toolResultChars: 20_000 };
|
|
9
|
+
const textOf = (message) => message.content
|
|
10
|
+
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
|
11
|
+
.join("")
|
|
12
|
+
.trim();
|
|
13
|
+
/** Text cut at `max` characters, marked. */
|
|
14
|
+
export function cutText(text, max) {
|
|
15
|
+
return text.length > max ? `${text.slice(0, max)}…(cut)` : text;
|
|
16
|
+
}
|
|
17
|
+
/** Tokens of a text, roughly: a CJK character is about one, other text about four characters a token. */
|
|
18
|
+
export function estimateTokens(text) {
|
|
19
|
+
const cjk = text.match(/[ -鿿-]/g)?.length ?? 0;
|
|
20
|
+
return Math.ceil(cjk + (text.length - cjk) / 4);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The stored entries from the `turns`-th last user message on, the first one cut loose from its parent: the
|
|
24
|
+
* session a windowed run reads. The last entry stays the thread's last, so what the run appends follows it.
|
|
25
|
+
*/
|
|
26
|
+
export function windowEntries(entries, turns) {
|
|
27
|
+
const [header, ...rest] = entries;
|
|
28
|
+
let starts = 0;
|
|
29
|
+
let from = rest.length;
|
|
30
|
+
for (let i = rest.length - 1; i >= 0 && starts < turns; i--) {
|
|
31
|
+
const entry = rest[i];
|
|
32
|
+
if (entry.type === "message" && entry.message?.role === "user") {
|
|
33
|
+
starts++;
|
|
34
|
+
from = i;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (from === 0 || from === rest.length)
|
|
38
|
+
return entries;
|
|
39
|
+
const [first, ...after] = rest.slice(from);
|
|
40
|
+
return [header, { ...first, parentId: null }, ...after];
|
|
41
|
+
}
|
|
42
|
+
const messageOf = (entry) => entry?.type === "message" ? entry.message : null;
|
|
43
|
+
/** An entry as stored: an image part of a message becomes `placeholder` text, so the store never holds the bytes. */
|
|
44
|
+
export function withoutImages(entry, placeholder) {
|
|
45
|
+
const message = messageOf(entry);
|
|
46
|
+
if (!message || !Array.isArray(message.content) || !message.content.some((p) => p?.type === "image"))
|
|
47
|
+
return entry;
|
|
48
|
+
const content = message.content.map((p) => (p?.type === "image" ? { type: "text", text: placeholder } : p));
|
|
49
|
+
return { ...entry, message: { ...message, content } };
|
|
50
|
+
}
|
|
51
|
+
/** A stored entry loaded again: an image without bytes (vibeU kept the part with empty data) becomes `placeholder` text. */
|
|
52
|
+
export function withoutEmptyImages(entry, placeholder) {
|
|
53
|
+
const message = messageOf(entry);
|
|
54
|
+
if (!message || !Array.isArray(message.content) || !message.content.some((p) => p?.type === "image" && !p.data))
|
|
55
|
+
return entry;
|
|
56
|
+
const content = message.content.map((p) => (p?.type === "image" && !p.data ? { type: "text", text: placeholder } : p));
|
|
57
|
+
return { ...entry, message: { ...message, content } };
|
|
58
|
+
}
|
|
59
|
+
/** pi's model runtime with the one model registered under its provider; it streams through `model.streamFn`. */
|
|
60
|
+
const runtimes = new WeakMap();
|
|
61
|
+
function runtimeFor(model) {
|
|
62
|
+
let runtime = runtimes.get(model);
|
|
63
|
+
if (!runtime) {
|
|
64
|
+
runtime = ModelRuntime.create({ authPath: join(tmpdir(), "jig-pi-auth.json"), modelsPath: null, refreshOnCreate: false }).then((created) => {
|
|
65
|
+
const { id, name, reasoning, input, cost, contextWindow, maxTokens } = model.model;
|
|
66
|
+
created.registerProvider(model.model.provider, {
|
|
67
|
+
api: model.model.api,
|
|
68
|
+
baseUrl: model.model.baseUrl || "http://model.invalid",
|
|
69
|
+
// pi wants a key before it streams; the real one lives in `streamFn`.
|
|
70
|
+
apiKey: "in-stream-fn",
|
|
71
|
+
streamSimple: model.streamFn,
|
|
72
|
+
models: [{ id, name, reasoning, input, cost, contextWindow, maxTokens, compat: model.model.compat }],
|
|
73
|
+
});
|
|
74
|
+
return created;
|
|
75
|
+
});
|
|
76
|
+
runtimes.set(model, runtime);
|
|
77
|
+
}
|
|
78
|
+
return runtime;
|
|
79
|
+
}
|
|
80
|
+
function loaderFor(system) {
|
|
81
|
+
return {
|
|
82
|
+
getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),
|
|
83
|
+
getSkills: () => ({ skills: [], diagnostics: [] }),
|
|
84
|
+
getPrompts: () => ({ prompts: [], diagnostics: [] }),
|
|
85
|
+
getThemes: () => ({ themes: [], diagnostics: [] }),
|
|
86
|
+
getAgentsFiles: () => ({ agentsFiles: [] }),
|
|
87
|
+
getSystemPrompt: () => system,
|
|
88
|
+
getSystemPromptSource: () => undefined,
|
|
89
|
+
getAppendSystemPrompt: () => [],
|
|
90
|
+
getAppendSystemPromptSources: () => [],
|
|
91
|
+
extendResources: () => { },
|
|
92
|
+
reload: async () => { },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function historyMessages(model, history) {
|
|
96
|
+
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
|
|
97
|
+
return history
|
|
98
|
+
.filter((turn) => turn.text.trim())
|
|
99
|
+
.map((turn) => turn.role === "user"
|
|
100
|
+
? { role: "user", content: turn.text, timestamp: 0 }
|
|
101
|
+
: { role: "assistant", content: [{ type: "text", text: turn.text }], api: model.model.api, provider: model.model.provider, model: model.id, usage, stopReason: "stop", timestamp: 0 });
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Runs and appends on one scope of one store, one at a time in this process: two at once would both start from the
|
|
105
|
+
* same stored seq, and the second one's entries would be dropped as conflicts. Across processes it is the host's (one
|
|
106
|
+
* server per database). A tool must not start a run on its own run's scope: it would wait for itself.
|
|
107
|
+
*/
|
|
108
|
+
const locks = new WeakMap();
|
|
109
|
+
async function inScope(store, scope, fn) {
|
|
110
|
+
if (scope === null)
|
|
111
|
+
return fn();
|
|
112
|
+
let scopes = locks.get(store);
|
|
113
|
+
if (!scopes)
|
|
114
|
+
locks.set(store, (scopes = new Map()));
|
|
115
|
+
const before = scopes.get(scope) ?? Promise.resolve();
|
|
116
|
+
const mine = before.catch(() => { }).then(fn);
|
|
117
|
+
const tail = mine.catch(() => { });
|
|
118
|
+
scopes.set(scope, tail);
|
|
119
|
+
try {
|
|
120
|
+
return await mine;
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
if (scopes.get(scope) === tail)
|
|
124
|
+
scopes.delete(scope);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const errorResult = (text) => ({ content: [{ type: "text", text }], details: undefined, isError: true });
|
|
128
|
+
const DEFAULT_PLACEHOLDER = "[an image shown earlier]";
|
|
129
|
+
/**
|
|
130
|
+
* One run of a pi `AgentSession` with only the given tools, its session in the `store`: loaded before the run (or
|
|
131
|
+
* its last turns, `window`), each new entry stored as the run goes (images replaced by a placeholder), compacted by pi
|
|
132
|
+
* past the history budget. The run row exists from the start, so a run the server never finished is visible.
|
|
133
|
+
*
|
|
134
|
+
* Emits `@ag-ui/core` events through `onEvent` (design §4.2). Never throws once the run row exists: a model or store
|
|
135
|
+
* failure ends as a status. It throws only when the store cannot load, insert, or start the run (nothing ran yet).
|
|
136
|
+
*/
|
|
137
|
+
export function runAgent(o) {
|
|
138
|
+
return inScope(o.store, o.persist === false ? null : o.scope, () => run(o));
|
|
139
|
+
}
|
|
140
|
+
async function run(o) {
|
|
141
|
+
const warn = o.warn ?? ((message, detail) => console.warn(`agent-pi: ${message}`, detail ?? ""));
|
|
142
|
+
const placeholder = o.imagePlaceholder ?? DEFAULT_PLACEHOLDER;
|
|
143
|
+
const pick = o.models.pick(o.purpose);
|
|
144
|
+
const model = pick.model;
|
|
145
|
+
const thinking = model.model.reasoning ? pick.thinking : "off";
|
|
146
|
+
const base = { ...DEFAULT_LIMITS, ...o.limits };
|
|
147
|
+
const limits = { ...base, outputTokens: thinking === "off" ? base.outputTokens : base.outputTokens + base.thinkingTokens };
|
|
148
|
+
const keep = o.persist !== false;
|
|
149
|
+
const cwd = o.cwd ?? "/";
|
|
150
|
+
const scope = o.scope;
|
|
151
|
+
// Load. The whole thread is the base of the seqs; a windowed run reads a slice of it.
|
|
152
|
+
const stored = keep && scope ? await o.store.load(scope) : null;
|
|
153
|
+
const loaded = stored ? stored.entries.map((e) => withoutEmptyImages(e, placeholder)) : [];
|
|
154
|
+
const read = o.window && loaded.length ? windowEntries(loaded, o.window) : loaded;
|
|
155
|
+
const sessionManager = read.length ? SessionManager.inMemory(cwd, undefined, read) : SessionManager.inMemory(cwd, stored ? { id: stored.id } : undefined);
|
|
156
|
+
const sessionId = sessionManager.getSessionId();
|
|
157
|
+
if (!read.length) {
|
|
158
|
+
if (o.etho) {
|
|
159
|
+
const ownerLabel = o.etho.ownerLabel ?? "owner";
|
|
160
|
+
sessionManager.appendCustomEntry("etho", { app: o.etho.app, kind: o.purpose, labels: { ...o.labels, [ownerLabel]: o.ownerId, ...(scope ? { scope } : {}) } });
|
|
161
|
+
}
|
|
162
|
+
// etho titles a session by its pi name; a one-off run's first message is often data, unreadable as a title.
|
|
163
|
+
if (!scope)
|
|
164
|
+
sessionManager.appendSessionInfo([o.purpose, ...Object.values(o.labels ?? {})].join(" · "));
|
|
165
|
+
for (const message of historyMessages(model, o.history ?? []))
|
|
166
|
+
sessionManager.appendMessage(message);
|
|
167
|
+
}
|
|
168
|
+
if (o.retry && read.length) {
|
|
169
|
+
const asked = sessionManager.getBranch().findLast((entry) => entry.type === "message" && entry.message.role === "user");
|
|
170
|
+
if (asked?.parentId)
|
|
171
|
+
sessionManager.branch(asked.parentId);
|
|
172
|
+
else if (asked)
|
|
173
|
+
sessionManager.resetLeaf();
|
|
174
|
+
}
|
|
175
|
+
if (keep && !stored)
|
|
176
|
+
await o.store.insert({ id: sessionId, ownerId: o.ownerId, scope, purpose: o.purpose });
|
|
177
|
+
const runId = o.runId ?? newRunId();
|
|
178
|
+
const threadId = o.threadId ?? scope ?? sessionId;
|
|
179
|
+
await o.store.startRun({ runId, ownerId: o.ownerId, purpose: o.purpose, model: model.id, tier: pick.tier, thinking, sessionId: keep ? sessionId : null, columns: o.runColumns });
|
|
180
|
+
const startedAt = Date.now();
|
|
181
|
+
// From here on nothing throws: every failure ends the run with a status.
|
|
182
|
+
let ended = false;
|
|
183
|
+
const emit = (event) => {
|
|
184
|
+
if (ended || !o.onEvent)
|
|
185
|
+
return;
|
|
186
|
+
try {
|
|
187
|
+
o.onEvent(event);
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
warn("onEvent failed", err);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
emit({ type: EventType.RUN_STARTED, threadId, runId });
|
|
194
|
+
// Persist: one chain, so appends never overlap; a failed append leaves `saved` where it was and the next one
|
|
195
|
+
// retries the range (seqs already stored are skipped).
|
|
196
|
+
const skipped = loaded.length - read.length;
|
|
197
|
+
let saved = read.length;
|
|
198
|
+
let saving = Promise.resolve();
|
|
199
|
+
const persist = () => {
|
|
200
|
+
if (!keep)
|
|
201
|
+
return saving;
|
|
202
|
+
saving = saving
|
|
203
|
+
.then(async () => {
|
|
204
|
+
const all = [sessionManager.getHeader(), ...sessionManager.getEntries()];
|
|
205
|
+
if (all.length <= saved)
|
|
206
|
+
return;
|
|
207
|
+
await o.store.append(sessionId, saved + skipped, all.slice(saved).map((e) => withoutImages(e, placeholder)));
|
|
208
|
+
saved = all.length;
|
|
209
|
+
})
|
|
210
|
+
.catch((err) => warn(`session ${sessionId} not saved`, err));
|
|
211
|
+
return saving;
|
|
212
|
+
};
|
|
213
|
+
const usage = { inputTokens: 0, cachedTokens: 0, outputTokens: 0, toolCalls: 0, costUsd: 0 };
|
|
214
|
+
const cards = [];
|
|
215
|
+
const parts = [];
|
|
216
|
+
let cut = null;
|
|
217
|
+
let error = null;
|
|
218
|
+
let final = "";
|
|
219
|
+
let stopped = false;
|
|
220
|
+
/** The last reply's stop reason: a stop after a whole final reply (`stop`, `length`) cut nothing. */
|
|
221
|
+
let lastStop = null;
|
|
222
|
+
// False once pi settled (its last event) or `prompt()` returned: a stop or the timer from then on changes nothing.
|
|
223
|
+
let running = true;
|
|
224
|
+
const count = async (name, run) => {
|
|
225
|
+
usage.toolCalls += 1;
|
|
226
|
+
if (usage.toolCalls > limits.toolCalls) {
|
|
227
|
+
cut ??= "tool call limit";
|
|
228
|
+
return errorResult("Tool call limit reached for this answer. Answer now with what you have.");
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
return await run();
|
|
232
|
+
}
|
|
233
|
+
catch (err) {
|
|
234
|
+
const message = o.toolError ? await Promise.resolve(o.toolError(err, name)).catch(() => "the tool failed") : "the tool failed";
|
|
235
|
+
if (!o.toolError)
|
|
236
|
+
warn(`tool ${name} failed`, err);
|
|
237
|
+
return errorResult(JSON.stringify({ error: message }));
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
const tools = [
|
|
241
|
+
...(o.tools ?? []).map((tool) => defineTool({
|
|
242
|
+
name: tool.name,
|
|
243
|
+
label: tool.name,
|
|
244
|
+
description: tool.description,
|
|
245
|
+
parameters: tool.parameters,
|
|
246
|
+
execute: (_id, args, signal) => count(tool.name, async () => {
|
|
247
|
+
const result = await tool.execute(args, { signal });
|
|
248
|
+
return { content: [{ type: "text", text: cutText(typeof result.data === "string" ? result.data : JSON.stringify(result.data) ?? "null", limits.toolResultChars) }], details: { cards: result.cards ?? [] } };
|
|
249
|
+
}),
|
|
250
|
+
})),
|
|
251
|
+
...(o.piTools ?? []).map((tool) => ({ ...tool, execute: (...args) => count(tool.name, () => tool.execute(...args)) })),
|
|
252
|
+
];
|
|
253
|
+
// AG-UI state of the run.
|
|
254
|
+
let messageNo = 0;
|
|
255
|
+
let messageId = null;
|
|
256
|
+
let lastTextId = null;
|
|
257
|
+
let reasoningId = null;
|
|
258
|
+
let streaming = "";
|
|
259
|
+
const closeReasoning = () => {
|
|
260
|
+
if (!reasoningId)
|
|
261
|
+
return;
|
|
262
|
+
emit({ type: EventType.REASONING_MESSAGE_END, messageId: reasoningId });
|
|
263
|
+
emit({ type: EventType.REASONING_END, messageId: reasoningId });
|
|
264
|
+
reasoningId = null;
|
|
265
|
+
};
|
|
266
|
+
const closeMessage = (stopReason) => {
|
|
267
|
+
if (!messageId)
|
|
268
|
+
return;
|
|
269
|
+
closeReasoning();
|
|
270
|
+
emit({ type: EventType.TEXT_MESSAGE_END, messageId });
|
|
271
|
+
emit({ type: EventType.STEP_FINISHED, stepName: `step-${messageNo}`, ...(stopReason ? { metadata: { stopReason } } : {}) });
|
|
272
|
+
messageId = null;
|
|
273
|
+
};
|
|
274
|
+
let session = null;
|
|
275
|
+
// pi 1.4 ignores an abort that lands while `prompt()` is still preparing (before its agent run is active), so an
|
|
276
|
+
// abort is wanted until the session takes it: every event of a run asked to abort aborts it again.
|
|
277
|
+
let abortWanted = false;
|
|
278
|
+
const abort = () => {
|
|
279
|
+
abortWanted = true;
|
|
280
|
+
void session?.abort().catch((err) => warn("abort failed", err));
|
|
281
|
+
};
|
|
282
|
+
const stop = () => {
|
|
283
|
+
if (!running)
|
|
284
|
+
return;
|
|
285
|
+
stopped = true;
|
|
286
|
+
abort();
|
|
287
|
+
};
|
|
288
|
+
const timer = setTimeout(() => {
|
|
289
|
+
if (!running)
|
|
290
|
+
return;
|
|
291
|
+
cut ??= "time limit";
|
|
292
|
+
abort();
|
|
293
|
+
}, limits.ms);
|
|
294
|
+
o.signal?.addEventListener("abort", stop);
|
|
295
|
+
if (o.signal?.aborted)
|
|
296
|
+
stopped = true;
|
|
297
|
+
try {
|
|
298
|
+
if (!stopped) {
|
|
299
|
+
const compaction = o.compaction === false
|
|
300
|
+
? { enabled: false }
|
|
301
|
+
: o.compaction
|
|
302
|
+
? (() => {
|
|
303
|
+
const fixed = estimateTokens(o.system + JSON.stringify(tools.map(({ name, description, parameters }) => ({ name, description, parameters }))));
|
|
304
|
+
const history = o.compaction.historyTokens;
|
|
305
|
+
return { enabled: true, reserveTokens: Math.max(1, model.model.contextWindow - fixed - history), keepRecentTokens: Math.round(history * (o.compaction.keep ?? 0.25)) };
|
|
306
|
+
})()
|
|
307
|
+
: undefined;
|
|
308
|
+
({ session } = await createAgentSession({
|
|
309
|
+
cwd,
|
|
310
|
+
model: { ...model.model, maxTokens: limits.outputTokens },
|
|
311
|
+
thinkingLevel: thinking,
|
|
312
|
+
modelRuntime: await runtimeFor(model),
|
|
313
|
+
resourceLoader: loaderFor(o.system),
|
|
314
|
+
tools: tools.map((tool) => tool.name),
|
|
315
|
+
customTools: tools,
|
|
316
|
+
sessionManager,
|
|
317
|
+
settingsManager: SettingsManager.inMemory({ retry: { enabled: (o.retries ?? 2) > 0, maxRetries: o.retries ?? 2 }, ...(compaction ? { compaction } : {}) }),
|
|
318
|
+
}));
|
|
319
|
+
session.subscribe((event) => {
|
|
320
|
+
if (ended)
|
|
321
|
+
return;
|
|
322
|
+
if (abortWanted && (event.type === "agent_start" || event.type === "turn_start" || event.type === "message_start"))
|
|
323
|
+
void session?.abort().catch(() => { });
|
|
324
|
+
if (event.type === "message_start" && event.message.role === "assistant") {
|
|
325
|
+
closeMessage();
|
|
326
|
+
streaming = "";
|
|
327
|
+
messageId = lastTextId = `${runId}:${++messageNo}`;
|
|
328
|
+
emit({ type: EventType.STEP_STARTED, stepName: `step-${messageNo}` });
|
|
329
|
+
emit({ type: EventType.TEXT_MESSAGE_START, messageId, role: "assistant" });
|
|
330
|
+
}
|
|
331
|
+
if (event.type === "message_update" && messageId) {
|
|
332
|
+
const e = event.assistantMessageEvent;
|
|
333
|
+
if (e.type === "text_delta") {
|
|
334
|
+
closeReasoning();
|
|
335
|
+
streaming += e.delta;
|
|
336
|
+
emit({ type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta: e.delta });
|
|
337
|
+
}
|
|
338
|
+
if (e.type === "thinking_delta" && e.delta) {
|
|
339
|
+
if (!reasoningId) {
|
|
340
|
+
reasoningId = `${messageId}:reasoning`;
|
|
341
|
+
emit({ type: EventType.REASONING_START, messageId: reasoningId });
|
|
342
|
+
emit({ type: EventType.REASONING_MESSAGE_START, messageId: reasoningId, role: "reasoning" });
|
|
343
|
+
}
|
|
344
|
+
emit({ type: EventType.REASONING_MESSAGE_CONTENT, messageId: reasoningId, delta: e.delta });
|
|
345
|
+
}
|
|
346
|
+
if (e.type === "thinking_end")
|
|
347
|
+
closeReasoning();
|
|
348
|
+
}
|
|
349
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
350
|
+
const message = event.message;
|
|
351
|
+
usage.inputTokens += message.usage.input + message.usage.cacheRead;
|
|
352
|
+
usage.cachedTokens += message.usage.cacheRead;
|
|
353
|
+
usage.outputTokens += message.usage.output;
|
|
354
|
+
usage.costUsd += costOf(model, message.usage);
|
|
355
|
+
// A stopped reply may end without its text: keep what was streamed.
|
|
356
|
+
const text = textOf(message) || (message.stopReason === "aborted" ? streaming.trim() : "");
|
|
357
|
+
streaming = "";
|
|
358
|
+
if (text)
|
|
359
|
+
parts.push(text);
|
|
360
|
+
final = message.stopReason === "toolUse" ? "" : text;
|
|
361
|
+
error = message.stopReason === "error" ? (message.errorMessage ?? "model error") : null;
|
|
362
|
+
lastStop = message.stopReason;
|
|
363
|
+
closeMessage(message.stopReason);
|
|
364
|
+
}
|
|
365
|
+
if (event.type === "tool_execution_start") {
|
|
366
|
+
emit({ type: EventType.TOOL_CALL_START, toolCallId: event.toolCallId, toolCallName: event.toolName, ...(lastTextId ? { parentMessageId: lastTextId } : {}) });
|
|
367
|
+
const shown = o.showArgs?.(event.toolName, event.args);
|
|
368
|
+
if (shown !== undefined)
|
|
369
|
+
emit({ type: EventType.TOOL_CALL_ARGS, toolCallId: event.toolCallId, delta: cutText(JSON.stringify(shown) ?? "null", 2_000) });
|
|
370
|
+
}
|
|
371
|
+
if (event.type === "tool_execution_end") {
|
|
372
|
+
emit({ type: EventType.TOOL_CALL_END, toolCallId: event.toolCallId, metadata: { isError: event.isError } });
|
|
373
|
+
const given = event.result?.details?.cards;
|
|
374
|
+
if (Array.isArray(given)) {
|
|
375
|
+
given.forEach((card, i) => {
|
|
376
|
+
if (!card || typeof card !== "object")
|
|
377
|
+
return;
|
|
378
|
+
cards.push(card);
|
|
379
|
+
emit({ type: EventType.ACTIVITY_SNAPSHOT, messageId: `${event.toolCallId}:card:${i}`, activityType: `card.${typeof card.kind === "string" ? card.kind : "unknown"}`, content: card });
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (event.type === "compaction_end" && event.result) {
|
|
384
|
+
const spent = event.result.usage;
|
|
385
|
+
if (spent) {
|
|
386
|
+
usage.inputTokens += spent.input + spent.cacheRead;
|
|
387
|
+
usage.cachedTokens += spent.cacheRead;
|
|
388
|
+
usage.outputTokens += spent.output;
|
|
389
|
+
usage.costUsd += costOf(model, spent);
|
|
390
|
+
}
|
|
391
|
+
emit({ type: EventType.CUSTOM, name: "compaction", value: { reason: event.reason, tokensBefore: event.result.tokensBefore, tokensAfter: event.result.estimatedTokensAfter } });
|
|
392
|
+
void persist();
|
|
393
|
+
}
|
|
394
|
+
if (event.type === "agent_settled" && !event.aborted)
|
|
395
|
+
running = false;
|
|
396
|
+
if (event.type === "message_end" || event.type === "agent_settled")
|
|
397
|
+
void persist();
|
|
398
|
+
});
|
|
399
|
+
// The signal or the timer may have fired while the session was made: then do not start.
|
|
400
|
+
if (!stopped && !abortWanted)
|
|
401
|
+
await session.prompt(o.input.text, o.input.images?.length ? { images: o.input.images } : undefined);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
catch (err) {
|
|
405
|
+
error = err instanceof Error ? err.message : String(err);
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
running = false;
|
|
409
|
+
clearTimeout(timer);
|
|
410
|
+
o.signal?.removeEventListener("abort", stop);
|
|
411
|
+
}
|
|
412
|
+
// A stop that came after the whole answer (pi was wrapping up) cut nothing: the run is ok.
|
|
413
|
+
if (stopped && (lastStop === "stop" || lastStop === "length") && !error)
|
|
414
|
+
stopped = false;
|
|
415
|
+
if (stopped && streaming.trim())
|
|
416
|
+
parts.push(streaming.trim()), (final = streaming.trim());
|
|
417
|
+
await persist();
|
|
418
|
+
try {
|
|
419
|
+
session?.dispose();
|
|
420
|
+
}
|
|
421
|
+
catch (err) {
|
|
422
|
+
warn("session dispose failed", err);
|
|
423
|
+
}
|
|
424
|
+
const status = stopped ? "stopped" : cut ? "cut" : error ? "failed" : "ok";
|
|
425
|
+
const why = status === "ok" ? null : status === "stopped" ? "stopped" : status === "cut" ? cut : error;
|
|
426
|
+
if (status === "failed")
|
|
427
|
+
warn(`run ${runId} (${o.purpose}) failed`, error);
|
|
428
|
+
try {
|
|
429
|
+
await o.store.endRun(runId, status, usage, why);
|
|
430
|
+
}
|
|
431
|
+
catch (err) {
|
|
432
|
+
// The row stays `running` until `failStaleRuns`; the run itself is over and its result stands.
|
|
433
|
+
warn(`run ${runId} not ended in the store`, err);
|
|
434
|
+
}
|
|
435
|
+
closeMessage(stopped ? "aborted" : undefined);
|
|
436
|
+
const durationMs = Date.now() - startedAt;
|
|
437
|
+
if (status === "failed")
|
|
438
|
+
emit({ type: EventType.RUN_ERROR, message: why ?? "the run failed", metadata: { threadId, runId } });
|
|
439
|
+
else
|
|
440
|
+
emit({
|
|
441
|
+
type: EventType.RUN_FINISHED,
|
|
442
|
+
threadId,
|
|
443
|
+
runId,
|
|
444
|
+
result: { messageId: final ? lastTextId : null, text: final, costUsd: usage.costUsd, durationMs },
|
|
445
|
+
...(status === "stopped" ? { outcome: { type: "cancelled" }, metadata: { stopped: true } } : status === "cut" ? { metadata: { stopped: "cut", reason: cut } } : {}),
|
|
446
|
+
});
|
|
447
|
+
ended = true;
|
|
448
|
+
return { runId, status, text: parts.join("\n\n"), final, cards, usage, error: why, sessionId: keep ? sessionId : null };
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Adds a user message to a thread's session without a run (an event the app recorded): the next run reads it in
|
|
452
|
+
* order. Makes the session, with its etho entry, when the scope has none yet.
|
|
453
|
+
*/
|
|
454
|
+
export async function appendToThread(o) {
|
|
455
|
+
return inScope(o.store, o.scope, () => appendNow(o));
|
|
456
|
+
}
|
|
457
|
+
async function appendNow(o) {
|
|
458
|
+
const stored = await o.store.load(o.scope);
|
|
459
|
+
const loaded = (stored?.entries ?? []);
|
|
460
|
+
const saved = loaded.length;
|
|
461
|
+
const cwd = o.cwd ?? "/";
|
|
462
|
+
const sessionManager = saved ? SessionManager.inMemory(cwd, undefined, loaded) : SessionManager.inMemory(cwd, stored ? { id: stored.id } : undefined);
|
|
463
|
+
const sessionId = sessionManager.getSessionId();
|
|
464
|
+
if (!saved && o.etho)
|
|
465
|
+
sessionManager.appendCustomEntry("etho", { app: o.etho.app, kind: o.purpose, labels: { [o.etho.ownerLabel ?? "owner"]: o.ownerId, scope: o.scope } });
|
|
466
|
+
if (!stored)
|
|
467
|
+
await o.store.insert({ id: sessionId, ownerId: o.ownerId, scope: o.scope, purpose: o.purpose });
|
|
468
|
+
sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: o.text }], timestamp: (o.at ?? new Date()).getTime() });
|
|
469
|
+
const all = [sessionManager.getHeader(), ...sessionManager.getEntries()];
|
|
470
|
+
await o.store.append(sessionId, saved, all.slice(saved));
|
|
471
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** How a run ended. `stopped`: the host's signal aborted it; `cut`: a limit (tool calls, time) ended it. */
|
|
2
|
+
export type RunStatus = "ok" | "failed" | "cut" | "stopped";
|
|
3
|
+
export interface RunUsage {
|
|
4
|
+
/** Input tokens including cache reads. */
|
|
5
|
+
inputTokens: number;
|
|
6
|
+
cachedTokens: number;
|
|
7
|
+
outputTokens: number;
|
|
8
|
+
toolCalls: number;
|
|
9
|
+
/** At the model's price, in US dollars; 0 for an unpriced model. */
|
|
10
|
+
costUsd: number;
|
|
11
|
+
}
|
|
12
|
+
/** A run as `startRun` records it, `running` until `endRun`. */
|
|
13
|
+
export interface RunStart {
|
|
14
|
+
runId: string;
|
|
15
|
+
ownerId: string;
|
|
16
|
+
purpose: string;
|
|
17
|
+
/** The model id. */
|
|
18
|
+
model: string;
|
|
19
|
+
tier: string;
|
|
20
|
+
thinking: string;
|
|
21
|
+
/** Null for a run that keeps no session (`persist: false`). */
|
|
22
|
+
sessionId: string | null;
|
|
23
|
+
/** Host columns of the run row (vibeU: `{ user_id }`), from `runAgent({ runColumns })`. */
|
|
24
|
+
columns?: Record<string, string | number | boolean | null>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Where `runAgent` keeps pi sessions and run rows. `pgSessionStore` implements it over the hosts' Postgres tables; a
|
|
28
|
+
* host that stores sessions another way (intake's JSONL) supplies its own. Entries are pi's `FileEntry` objects, the
|
|
29
|
+
* header first, in the order pi wrote them; a store keeps them as they are.
|
|
30
|
+
*/
|
|
31
|
+
export interface SessionStore {
|
|
32
|
+
/** The session of `scope` with all its entries (header first), or null when the scope has none yet. */
|
|
33
|
+
load(scope: string): Promise<{
|
|
34
|
+
id: string;
|
|
35
|
+
entries: unknown[];
|
|
36
|
+
} | null>;
|
|
37
|
+
/** A new session under the id pi gave it. `scope` is null for a one-off run (a batch), which no later run continues. */
|
|
38
|
+
insert(session: {
|
|
39
|
+
id: string;
|
|
40
|
+
ownerId: string;
|
|
41
|
+
scope: string | null;
|
|
42
|
+
purpose: string;
|
|
43
|
+
}): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Stores `entries` as seq `from`, `from + 1`, …, leaving a seq already stored as it is (the runner retries a range
|
|
46
|
+
* after a failed append), and touches the session's `updated_at`.
|
|
47
|
+
*/
|
|
48
|
+
append(sessionId: string, from: number, entries: unknown[]): Promise<void>;
|
|
49
|
+
startRun(run: RunStart): Promise<void>;
|
|
50
|
+
/** `error` is null for `ok`, otherwise why (the model's error, `tool call limit`, `time limit`, `stopped`). */
|
|
51
|
+
endRun(runId: string, status: RunStatus, usage: RunUsage, error: string | null): Promise<void>;
|
|
52
|
+
/** At startup: runs still `running` were never finished (the server restarted); marks them failed. Returns how many. */
|
|
53
|
+
failStaleRuns(): Promise<number>;
|
|
54
|
+
}
|
|
55
|
+
/** A driver's query, as `pg` has it. postgres.js: `(text, params) => sql.unsafe(text, params).then((rows) => ({ rows }))`. */
|
|
56
|
+
export type Query = (text: string, params?: unknown[]) => Promise<{
|
|
57
|
+
rows: any[];
|
|
58
|
+
}>;
|
|
59
|
+
export interface PgSessionStoreOptions {
|
|
60
|
+
query: Query;
|
|
61
|
+
/** Table names. Default `agent_sessions`, `agent_entries`, `ai_runs`. */
|
|
62
|
+
tables?: {
|
|
63
|
+
sessions?: string;
|
|
64
|
+
entries?: string;
|
|
65
|
+
runs?: string;
|
|
66
|
+
};
|
|
67
|
+
/** The owner column of the sessions and runs tables (erudite `user_id`, vibeU `space_id`, lemma `learner`). */
|
|
68
|
+
ownerColumn: string;
|
|
69
|
+
/** `agent_entries.entry`'s type: `jsonb` (erudite, lemma) or `text` (vibeU, new hosts: model output can hold NUL, which jsonb rejects). Default `text`. */
|
|
70
|
+
entryType?: "jsonb" | "text";
|
|
71
|
+
/** A sessions column that takes the run's purpose (vibeU `purpose`); none by default. */
|
|
72
|
+
sessionPurposeColumn?: string;
|
|
73
|
+
/**
|
|
74
|
+
* Run-row columns a host's table may lack: null leaves it out. Defaults `thinking`, `cost_usd`, `duration_ms`
|
|
75
|
+
* (vibeU has no `cost_usd` or `duration_ms`, lemma no `thinking`).
|
|
76
|
+
*/
|
|
77
|
+
runColumns?: {
|
|
78
|
+
thinking?: string | null;
|
|
79
|
+
costUsd?: string | null;
|
|
80
|
+
durationMs?: string | null;
|
|
81
|
+
};
|
|
82
|
+
/** The status written for each `RunStatus` (lemma's CHECK has no `stopped`: `{ stopped: 'cut' }`). */
|
|
83
|
+
statuses?: Partial<Record<RunStatus, string>>;
|
|
84
|
+
}
|
|
85
|
+
/** `run_` and 12 random base64url characters, as erudite and vibeU make them. */
|
|
86
|
+
export declare const newRunId: () => string;
|
|
87
|
+
/**
|
|
88
|
+
* `SessionStore` over the host's existing tables. It runs no migration; `PI_SESSION_DDL` is the reference schema for a
|
|
89
|
+
* new host. Every write is one statement, so it needs no transaction and works with any driver's `query`.
|
|
90
|
+
*/
|
|
91
|
+
export declare function pgSessionStore(o: PgSessionStoreOptions): SessionStore;
|
|
92
|
+
/**
|
|
93
|
+
* The reference schema, for a new host's own migration (the part runs none). The host adds its FK on `owner_id`, or
|
|
94
|
+
* names the column its own way and passes `ownerColumn`. Entries are `text`: model output can hold NUL, which jsonb rejects.
|
|
95
|
+
*/
|
|
96
|
+
export declare const PI_SESSION_DDL = "CREATE TABLE agent_sessions (\n id text PRIMARY KEY,\n owner_id text NOT NULL,\n scope text UNIQUE,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX agent_sessions_oneoff ON agent_sessions (updated_at) WHERE scope IS NULL;\n\nCREATE TABLE agent_entries (\n session_id text NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,\n seq integer NOT NULL,\n entry text NOT NULL,\n PRIMARY KEY (session_id, seq)\n);\n\nCREATE TABLE ai_runs (\n id text PRIMARY KEY,\n owner_id text NOT NULL,\n purpose text NOT NULL,\n model text NOT NULL,\n tier text NOT NULL,\n thinking text NOT NULL,\n session_id text REFERENCES agent_sessions(id) ON DELETE SET NULL,\n status text NOT NULL CHECK (status IN ('running', 'ok', 'failed', 'cut', 'stopped')),\n error text,\n input_tokens integer NOT NULL DEFAULT 0,\n cached_tokens integer NOT NULL DEFAULT 0,\n output_tokens integer NOT NULL DEFAULT 0,\n tool_calls integer NOT NULL DEFAULT 0,\n cost_usd double precision NOT NULL DEFAULT 0,\n duration_ms integer,\n started_at timestamptz NOT NULL DEFAULT now(),\n ended_at timestamptz\n);\nCREATE INDEX ai_runs_owner ON ai_runs (owner_id, purpose, started_at);\n";
|
|
97
|
+
/** A `SessionStore` in memory, for tests and for runs that keep nothing. `runs` and `sessions` are readable. */
|
|
98
|
+
export declare function memorySessionStore(): SessionStore & {
|
|
99
|
+
sessions: Map<string, {
|
|
100
|
+
id: string;
|
|
101
|
+
ownerId: string;
|
|
102
|
+
scope: string | null;
|
|
103
|
+
purpose: string;
|
|
104
|
+
entries: Map<number, string>;
|
|
105
|
+
}>;
|
|
106
|
+
runs: Map<string, RunStart & {
|
|
107
|
+
status: RunStatus | "running";
|
|
108
|
+
usage?: RunUsage;
|
|
109
|
+
error?: string | null;
|
|
110
|
+
}>;
|
|
111
|
+
entriesOf(sessionId: string): unknown[];
|
|
112
|
+
};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
const IDENT = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/;
|
|
3
|
+
function ident(name) {
|
|
4
|
+
if (!IDENT.test(name))
|
|
5
|
+
throw new Error(`not a plain SQL identifier: ${name}`);
|
|
6
|
+
return name;
|
|
7
|
+
}
|
|
8
|
+
/** `run_` and 12 random base64url characters, as erudite and vibeU make them. */
|
|
9
|
+
export const newRunId = () => `run_${randomBytes(9).toString("base64url")}`;
|
|
10
|
+
/**
|
|
11
|
+
* `SessionStore` over the host's existing tables. It runs no migration; `PI_SESSION_DDL` is the reference schema for a
|
|
12
|
+
* new host. Every write is one statement, so it needs no transaction and works with any driver's `query`.
|
|
13
|
+
*/
|
|
14
|
+
export function pgSessionStore(o) {
|
|
15
|
+
const sessions = ident(o.tables?.sessions ?? "agent_sessions");
|
|
16
|
+
const entries = ident(o.tables?.entries ?? "agent_entries");
|
|
17
|
+
const runs = ident(o.tables?.runs ?? "ai_runs");
|
|
18
|
+
const owner = ident(o.ownerColumn);
|
|
19
|
+
const entryType = o.entryType ?? "text";
|
|
20
|
+
const purposeColumn = o.sessionPurposeColumn ? ident(o.sessionPurposeColumn) : null;
|
|
21
|
+
const col = (given, fallback) => (given === null ? null : ident(given ?? fallback));
|
|
22
|
+
const thinkingColumn = col(o.runColumns?.thinking, "thinking");
|
|
23
|
+
const costColumn = col(o.runColumns?.costUsd, "cost_usd");
|
|
24
|
+
const durationColumn = col(o.runColumns?.durationMs, "duration_ms");
|
|
25
|
+
const status = (s) => o.statuses?.[s] ?? s;
|
|
26
|
+
const q = o.query;
|
|
27
|
+
return {
|
|
28
|
+
async load(scope) {
|
|
29
|
+
const { rows } = await q(`SELECT id FROM ${sessions} WHERE scope = $1`, [scope]);
|
|
30
|
+
if (!rows[0])
|
|
31
|
+
return null;
|
|
32
|
+
const id = String(rows[0].id);
|
|
33
|
+
const stored = await q(`SELECT entry FROM ${entries} WHERE session_id = $1 ORDER BY seq`, [id]);
|
|
34
|
+
return { id, entries: stored.rows.map((row) => (typeof row.entry === "string" ? JSON.parse(row.entry) : row.entry)) };
|
|
35
|
+
},
|
|
36
|
+
async insert(s) {
|
|
37
|
+
const columns = ["id", owner, "scope", ...(purposeColumn ? [purposeColumn] : [])];
|
|
38
|
+
const values = [s.id, s.ownerId, s.scope, ...(purposeColumn ? [s.purpose] : [])];
|
|
39
|
+
await q(`INSERT INTO ${sessions} (${columns.join(", ")}) VALUES (${values.map((_, i) => `$${i + 1}`).join(", ")})`, values);
|
|
40
|
+
},
|
|
41
|
+
async append(sessionId, from, list) {
|
|
42
|
+
if (!list.length)
|
|
43
|
+
return;
|
|
44
|
+
// The entries go as one text parameter, read back as json: `json` keeps each element's text as written (a NUL
|
|
45
|
+
// escape included), and a text parameter is never re-encoded by a driver's json serializer (postgres.js).
|
|
46
|
+
await q(`WITH added AS (
|
|
47
|
+
INSERT INTO ${entries} (session_id, seq, entry)
|
|
48
|
+
SELECT $1, $2::integer + e.n::integer - 1, e.entry::${entryType} FROM json_array_elements($3::text::json) WITH ORDINALITY AS e(entry, n)
|
|
49
|
+
ON CONFLICT DO NOTHING
|
|
50
|
+
)
|
|
51
|
+
UPDATE ${sessions} SET updated_at = now() WHERE id = $1`, [sessionId, from, JSON.stringify(list)]);
|
|
52
|
+
},
|
|
53
|
+
async startRun(r) {
|
|
54
|
+
const columns = ["id", owner, "purpose", "model", "tier", "session_id", "status"];
|
|
55
|
+
const values = [r.runId, r.ownerId, r.purpose, r.model, r.tier, r.sessionId, "running"];
|
|
56
|
+
if (thinkingColumn)
|
|
57
|
+
columns.push(thinkingColumn), values.push(r.thinking);
|
|
58
|
+
for (const [name, value] of Object.entries(r.columns ?? {}))
|
|
59
|
+
columns.push(ident(name)), values.push(value);
|
|
60
|
+
await q(`INSERT INTO ${runs} (${columns.join(", ")}) VALUES (${values.map((_, i) => `$${i + 1}`).join(", ")})`, values);
|
|
61
|
+
},
|
|
62
|
+
async endRun(runId, s, usage, error) {
|
|
63
|
+
const sets = ["status = $2", "input_tokens = $3", "cached_tokens = $4", "output_tokens = $5", "tool_calls = $6", "error = $7", "ended_at = now()"];
|
|
64
|
+
const values = [runId, status(s), usage.inputTokens, usage.cachedTokens, usage.outputTokens, usage.toolCalls, error];
|
|
65
|
+
if (costColumn)
|
|
66
|
+
sets.push(`${costColumn} = $8`), values.push(usage.costUsd);
|
|
67
|
+
if (durationColumn)
|
|
68
|
+
sets.push(`${durationColumn} = (extract(epoch FROM now() - started_at) * 1000)::integer`);
|
|
69
|
+
await q(`UPDATE ${runs} SET ${sets.join(", ")} WHERE id = $1`, values);
|
|
70
|
+
},
|
|
71
|
+
async failStaleRuns() {
|
|
72
|
+
const { rows } = await q(`UPDATE ${runs} SET status = $1, error = 'server restarted', ended_at = now() WHERE status = 'running' RETURNING id`, [status("failed")]);
|
|
73
|
+
return rows.length;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The reference schema, for a new host's own migration (the part runs none). The host adds its FK on `owner_id`, or
|
|
79
|
+
* names the column its own way and passes `ownerColumn`. Entries are `text`: model output can hold NUL, which jsonb rejects.
|
|
80
|
+
*/
|
|
81
|
+
export const PI_SESSION_DDL = `CREATE TABLE agent_sessions (
|
|
82
|
+
id text PRIMARY KEY,
|
|
83
|
+
owner_id text NOT NULL,
|
|
84
|
+
scope text UNIQUE,
|
|
85
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
86
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
87
|
+
);
|
|
88
|
+
CREATE INDEX agent_sessions_oneoff ON agent_sessions (updated_at) WHERE scope IS NULL;
|
|
89
|
+
|
|
90
|
+
CREATE TABLE agent_entries (
|
|
91
|
+
session_id text NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,
|
|
92
|
+
seq integer NOT NULL,
|
|
93
|
+
entry text NOT NULL,
|
|
94
|
+
PRIMARY KEY (session_id, seq)
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
CREATE TABLE ai_runs (
|
|
98
|
+
id text PRIMARY KEY,
|
|
99
|
+
owner_id text NOT NULL,
|
|
100
|
+
purpose text NOT NULL,
|
|
101
|
+
model text NOT NULL,
|
|
102
|
+
tier text NOT NULL,
|
|
103
|
+
thinking text NOT NULL,
|
|
104
|
+
session_id text REFERENCES agent_sessions(id) ON DELETE SET NULL,
|
|
105
|
+
status text NOT NULL CHECK (status IN ('running', 'ok', 'failed', 'cut', 'stopped')),
|
|
106
|
+
error text,
|
|
107
|
+
input_tokens integer NOT NULL DEFAULT 0,
|
|
108
|
+
cached_tokens integer NOT NULL DEFAULT 0,
|
|
109
|
+
output_tokens integer NOT NULL DEFAULT 0,
|
|
110
|
+
tool_calls integer NOT NULL DEFAULT 0,
|
|
111
|
+
cost_usd double precision NOT NULL DEFAULT 0,
|
|
112
|
+
duration_ms integer,
|
|
113
|
+
started_at timestamptz NOT NULL DEFAULT now(),
|
|
114
|
+
ended_at timestamptz
|
|
115
|
+
);
|
|
116
|
+
CREATE INDEX ai_runs_owner ON ai_runs (owner_id, purpose, started_at);
|
|
117
|
+
`;
|
|
118
|
+
/** A `SessionStore` in memory, for tests and for runs that keep nothing. `runs` and `sessions` are readable. */
|
|
119
|
+
export function memorySessionStore() {
|
|
120
|
+
const sessions = new Map();
|
|
121
|
+
const runs = new Map();
|
|
122
|
+
const entriesOf = (id) => [...(sessions.get(id)?.entries ?? new Map()).entries()].sort(([a], [b]) => a - b).map(([, e]) => JSON.parse(e));
|
|
123
|
+
return {
|
|
124
|
+
sessions,
|
|
125
|
+
runs,
|
|
126
|
+
entriesOf,
|
|
127
|
+
async load(scope) {
|
|
128
|
+
const s = [...sessions.values()].find((x) => x.scope === scope);
|
|
129
|
+
return s ? { id: s.id, entries: entriesOf(s.id) } : null;
|
|
130
|
+
},
|
|
131
|
+
async insert(s) {
|
|
132
|
+
if (sessions.has(s.id) || (s.scope !== null && [...sessions.values()].some((x) => x.scope === s.scope)))
|
|
133
|
+
throw new Error(`session exists: ${s.scope ?? s.id}`);
|
|
134
|
+
sessions.set(s.id, { ...s, entries: new Map() });
|
|
135
|
+
},
|
|
136
|
+
async append(id, from, list) {
|
|
137
|
+
const s = sessions.get(id);
|
|
138
|
+
if (!s)
|
|
139
|
+
throw new Error(`no session ${id}`);
|
|
140
|
+
list.forEach((e, i) => {
|
|
141
|
+
if (!s.entries.has(from + i))
|
|
142
|
+
s.entries.set(from + i, JSON.stringify(e));
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
async startRun(r) {
|
|
146
|
+
runs.set(r.runId, { ...r, status: "running" });
|
|
147
|
+
},
|
|
148
|
+
async endRun(id, status, usage, error) {
|
|
149
|
+
const r = runs.get(id);
|
|
150
|
+
if (r)
|
|
151
|
+
Object.assign(r, { status, usage, error });
|
|
152
|
+
},
|
|
153
|
+
async failStaleRuns() {
|
|
154
|
+
let n = 0;
|
|
155
|
+
for (const r of runs.values())
|
|
156
|
+
if (r.status === "running")
|
|
157
|
+
Object.assign(r, { status: "failed", error: "server restarted" }), n++;
|
|
158
|
+
return n;
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lightblues/jig",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.8",
|
|
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",
|
|
@@ -36,6 +36,10 @@
|
|
|
36
36
|
"types": "./dist/agent-chat/react.d.ts",
|
|
37
37
|
"default": "./dist/agent-chat/react.js"
|
|
38
38
|
},
|
|
39
|
+
"./agent-pi": {
|
|
40
|
+
"types": "./dist/agent-pi/index.d.ts",
|
|
41
|
+
"default": "./dist/agent-pi/index.js"
|
|
42
|
+
},
|
|
39
43
|
"./package.json": "./package.json"
|
|
40
44
|
},
|
|
41
45
|
"scripts": {
|
|
@@ -47,6 +51,9 @@
|
|
|
47
51
|
},
|
|
48
52
|
"devDependencies": {
|
|
49
53
|
"@ag-ui/core": "1.0.5",
|
|
54
|
+
"@earendil-works/pi-agent-core": "1.4.0",
|
|
55
|
+
"@earendil-works/pi-ai": "1.4.0",
|
|
56
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
50
57
|
"@getpaseo/client": "0.16.1",
|
|
51
58
|
"@types/node": "^24.0.0",
|
|
52
59
|
"@types/react": "19.3.0",
|
|
@@ -54,10 +61,16 @@
|
|
|
54
61
|
"esbuild": "0.28.2",
|
|
55
62
|
"react": "19.3.1",
|
|
56
63
|
"react-test-renderer": "19.3.1",
|
|
64
|
+
"@types/pg": "8.23.1",
|
|
65
|
+
"pg": "8.23.1",
|
|
66
|
+
"postgres": "3.4.9",
|
|
57
67
|
"typescript": "^5.9.0"
|
|
58
68
|
},
|
|
59
69
|
"peerDependencies": {
|
|
60
70
|
"@ag-ui/core": "^1.0.5",
|
|
71
|
+
"@earendil-works/pi-agent-core": "~1.4.0",
|
|
72
|
+
"@earendil-works/pi-ai": "~1.4.0",
|
|
73
|
+
"@earendil-works/pi-coding-agent": "~1.4.0",
|
|
61
74
|
"@getpaseo/client": "0.16.1",
|
|
62
75
|
"react": ">=18"
|
|
63
76
|
},
|
|
@@ -65,6 +78,15 @@
|
|
|
65
78
|
"@ag-ui/core": {
|
|
66
79
|
"optional": true
|
|
67
80
|
},
|
|
81
|
+
"@earendil-works/pi-agent-core": {
|
|
82
|
+
"optional": true
|
|
83
|
+
},
|
|
84
|
+
"@earendil-works/pi-ai": {
|
|
85
|
+
"optional": true
|
|
86
|
+
},
|
|
87
|
+
"@earendil-works/pi-coding-agent": {
|
|
88
|
+
"optional": true
|
|
89
|
+
},
|
|
68
90
|
"@getpaseo/client": {
|
|
69
91
|
"optional": true
|
|
70
92
|
},
|