@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
|
@@ -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,27 @@
|
|
|
1
|
+
import type { PiRunEvent } from "./run.ts";
|
|
2
|
+
import type { RunListener } from "./registry.ts";
|
|
3
|
+
/** What `sseResponse` needs: anything with agent-paseo's / the registry's `listen` (so it serves either part). */
|
|
4
|
+
export interface Listenable {
|
|
5
|
+
listen(threadId: string, fn: RunListener): () => void;
|
|
6
|
+
}
|
|
7
|
+
export interface SseOptions {
|
|
8
|
+
/** The request's signal (Hono: `c.req.raw.signal`): the stream ends when the client goes. The run goes on. */
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
/** A `: ping` comment this often, so proxies keep the stream open. Default 15 000; 0 for none. */
|
|
11
|
+
pingMs?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Close the stream after the run's terminal event (a POST that streams its own answer), or at once when `READY`
|
|
14
|
+
* says no run is in progress (it ended before the response was made). Default false: follow the thread.
|
|
15
|
+
*/
|
|
16
|
+
endAfterRun?: boolean;
|
|
17
|
+
/** Extra response headers. */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
/** One event as SSE: `event: <type, or a CUSTOM event's name>` and `data: <json>` (JSON has no raw newline). */
|
|
21
|
+
export declare function sseFrame(e: PiRunEvent): string;
|
|
22
|
+
/**
|
|
23
|
+
* A thread's events as a web `Response` (`text/event-stream`), for any Fetch-API server (Hono: `return
|
|
24
|
+
* sseResponse(registry, id, { signal: c.req.raw.signal })`). The first events are the follower contract's `READY` and
|
|
25
|
+
* replay. Ends when `signal` aborts or the client cancels the body; the run is never stopped by it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function sseResponse(source: Listenable, threadId: string, o?: SseOptions): Response;
|