@lightblues/jig 0.0.8 → 0.0.10
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 -0
- package/dist/agent-chat/follow.d.ts +13 -1
- package/dist/agent-chat/follow.js +47 -6
- package/dist/agent-chat/index.d.ts +8 -4
- package/dist/agent-chat/index.js +4 -2
- package/dist/agent-chat/markdown.d.ts +22 -0
- package/dist/agent-chat/markdown.js +186 -0
- package/dist/agent-chat/react.d.ts +28 -5
- package/dist/agent-chat/react.js +43 -15
- package/dist/agent-chat/reduce.d.ts +29 -6
- package/dist/agent-chat/reduce.js +57 -17
- package/dist/agent-chat/timeline.d.ts +42 -0
- package/dist/agent-chat/timeline.js +46 -0
- package/dist/agent-paseo/follow.js +17 -5
- package/dist/agent-paseo/runner.d.ts +2 -0
- package/dist/agent-paseo/runner.js +17 -6
- package/dist/agent-pi/index.d.ts +4 -0
- package/dist/agent-pi/index.js +2 -0
- package/dist/agent-pi/models.d.ts +3 -1
- package/dist/agent-pi/models.js +18 -8
- package/dist/agent-pi/registry.d.ts +93 -0
- package/dist/agent-pi/registry.js +248 -0
- package/dist/agent-pi/run.d.ts +8 -1
- package/dist/agent-pi/run.js +24 -4
- package/dist/agent-pi/sse.d.ts +27 -0
- package/dist/agent-pi/sse.js +75 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/markdown/close.d.ts +1 -0
- package/dist/markdown/close.js +3 -0
- package/dist/markdown/index.d.ts +108 -0
- package/dist/markdown/index.js +169 -0
- package/package.json +34 -5
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export const initialState = { messages: [], live: null, error: null, connected: false, last: null, history: false };
|
|
2
2
|
/**
|
|
3
|
-
* Folds one AG-UI event into the thread state, without changing `state`.
|
|
3
|
+
* Folds one AG-UI event into the thread state, without changing `state`. Parts are stamped with the event's
|
|
4
|
+
* `timestamp`, or the clock when it has none (`PartTimes`). Follows the follower contract of
|
|
4
5
|
* agent-paseo and agent-pi: `CUSTOM READY` drops the run being drawn (the stream resyncs: `RUN_STARTED` and a replay
|
|
5
6
|
* follow when one is running), so a reconnect or a server-side gap never duplicates text. Unknown events return
|
|
6
7
|
* `state` unchanged.
|
|
@@ -8,6 +9,7 @@ export const initialState = { messages: [], live: null, error: null, connected:
|
|
|
8
9
|
export function reduce(state, event) {
|
|
9
10
|
const e = event;
|
|
10
11
|
const meta = (e.metadata ?? {});
|
|
12
|
+
const now = typeof e.timestamp === "number" ? e.timestamp : Date.now();
|
|
11
13
|
switch (e.type) {
|
|
12
14
|
case "CUSTOM": {
|
|
13
15
|
if (e.name !== "READY")
|
|
@@ -24,7 +26,7 @@ export function reduce(state, event) {
|
|
|
24
26
|
return {
|
|
25
27
|
...prev,
|
|
26
28
|
error: null,
|
|
27
|
-
live: { runId: String(e.runId), threadId: String(e.threadId), metadata: e.metadata ?? null, user: null, text: "", reasoning: "", tools: [], activities: [], parts: [] },
|
|
29
|
+
live: { runId: String(e.runId), threadId: String(e.threadId), metadata: e.metadata ?? null, user: null, text: "", reasoning: "", tools: [], activities: [], parts: [], startedAt: now },
|
|
28
30
|
};
|
|
29
31
|
}
|
|
30
32
|
case "RUN_FINISHED": {
|
|
@@ -35,13 +37,15 @@ export function reduce(state, event) {
|
|
|
35
37
|
const error = typeof meta.error === "string" ? meta.error : undefined;
|
|
36
38
|
const stopped = Boolean(meta.stopped) || e.outcome?.type === "cancelled";
|
|
37
39
|
const status = error ? "error" : stopped ? "stopped" : "done";
|
|
38
|
-
const
|
|
40
|
+
const timing = timingOf(meta.timing);
|
|
41
|
+
const last = { runId: String(e.runId), status, ...(e.result !== undefined ? { result: e.result } : {}), ...(error ? { error } : {}), ...(timing ? { timing } : {}) };
|
|
39
42
|
return other ? { ...state, last } : { ...settle(state), live: null, last, error: null };
|
|
40
43
|
}
|
|
41
44
|
case "RUN_ERROR": {
|
|
42
45
|
const message = String(e.message ?? "error");
|
|
43
46
|
const runId = String(meta.runId ?? state.live?.runId ?? "");
|
|
44
|
-
const
|
|
47
|
+
const timing = timingOf(meta.timing);
|
|
48
|
+
const last = { runId, status: "error", error: message, ...(timing ? { timing } : {}) };
|
|
45
49
|
if (state.live && meta.runId && state.live.runId !== runId)
|
|
46
50
|
return { ...state, last };
|
|
47
51
|
return { ...settle(state), live: null, error: message, last };
|
|
@@ -50,11 +54,11 @@ export function reduce(state, event) {
|
|
|
50
54
|
const live = state.live;
|
|
51
55
|
if (!live)
|
|
52
56
|
return activityOutside(state, e);
|
|
53
|
-
const next = run(live, e, meta);
|
|
57
|
+
const next = run(live, e, meta, now);
|
|
54
58
|
return next === live ? state : { ...state, live: next };
|
|
55
59
|
}
|
|
56
60
|
/** One event of the run in progress. Returns `live` itself when nothing changed. */
|
|
57
|
-
function run(live, e, meta) {
|
|
61
|
+
function run(live, e, meta, now) {
|
|
58
62
|
switch (e.type) {
|
|
59
63
|
case "TEXT_MESSAGE_START":
|
|
60
64
|
case "TEXT_MESSAGE_CHUNK":
|
|
@@ -67,22 +71,25 @@ function run(live, e, meta) {
|
|
|
67
71
|
}
|
|
68
72
|
if (e.type !== "TEXT_MESSAGE_START" && !delta)
|
|
69
73
|
return live;
|
|
70
|
-
return withText(live, "text", id, delta);
|
|
74
|
+
return withText(live, "text", id, delta, now);
|
|
71
75
|
}
|
|
76
|
+
case "TEXT_MESSAGE_END":
|
|
77
|
+
case "REASONING_MESSAGE_END":
|
|
78
|
+
return endPart(live, e.type === "TEXT_MESSAGE_END" ? "text" : "reasoning", String(e.messageId ?? ""), now);
|
|
72
79
|
case "REASONING_MESSAGE_START":
|
|
73
80
|
case "REASONING_MESSAGE_CHUNK":
|
|
74
81
|
case "REASONING_MESSAGE_CONTENT": {
|
|
75
82
|
const delta = typeof e.delta === "string" ? e.delta : "";
|
|
76
83
|
if (e.type !== "REASONING_MESSAGE_START" && !delta)
|
|
77
84
|
return live;
|
|
78
|
-
return withText(live, "reasoning", String(e.messageId ?? ""), delta);
|
|
85
|
+
return withText(live, "reasoning", String(e.messageId ?? ""), delta, now);
|
|
79
86
|
}
|
|
80
87
|
case "TOOL_CALL_START": {
|
|
81
88
|
const id = String(e.toolCallId);
|
|
82
89
|
if (live.tools.some((t) => t.id === id))
|
|
83
90
|
return live;
|
|
84
91
|
const tool = { id, name: String(e.toolCallName ?? ""), summary: str(meta.summary), args: "", status: "running", done: false };
|
|
85
|
-
return { ...live, tools: [...live.tools, tool], parts: [...live.parts, { kind: "tool", id }] };
|
|
92
|
+
return { ...live, tools: [...live.tools, tool], parts: [...closeTexts(live.parts, now), { kind: "tool", id, startedAt: now, endedAt: null }] };
|
|
86
93
|
}
|
|
87
94
|
case "TOOL_CALL_ARGS": {
|
|
88
95
|
const delta = typeof e.delta === "string" ? e.delta : "";
|
|
@@ -97,18 +104,21 @@ function run(live, e, meta) {
|
|
|
97
104
|
return { ...t, args: t.args + delta, summary };
|
|
98
105
|
});
|
|
99
106
|
}
|
|
100
|
-
case "TOOL_CALL_END":
|
|
101
|
-
|
|
107
|
+
case "TOOL_CALL_END": {
|
|
108
|
+
const id = String(e.toolCallId);
|
|
109
|
+
const next = tool(live, id, (t) => ({
|
|
102
110
|
...t,
|
|
103
111
|
done: true,
|
|
104
112
|
status: str(meta.status) ?? (meta.isError === true ? "failed" : "completed"),
|
|
105
113
|
}));
|
|
114
|
+
return next === live ? live : { ...next, parts: next.parts.map((p) => (p.kind === "tool" && p.id === id && p.endedAt === null ? { ...p, endedAt: now } : p)) };
|
|
115
|
+
}
|
|
106
116
|
case "ACTIVITY_SNAPSHOT": {
|
|
107
117
|
const id = String(e.messageId);
|
|
108
118
|
const at = live.activities.findIndex((a) => a.id === id);
|
|
109
119
|
const a = { id, activityType: String(e.activityType), content: (e.content ?? {}) };
|
|
110
120
|
if (at < 0)
|
|
111
|
-
return { ...live, activities: [...live.activities, a], parts: [...live.parts, { kind: "activity", id }] };
|
|
121
|
+
return { ...live, activities: [...live.activities, a], parts: [...closeTexts(live.parts, now), { kind: "activity", id, startedAt: now, endedAt: now }] };
|
|
112
122
|
if (e.replace === false)
|
|
113
123
|
return live;
|
|
114
124
|
return { ...live, activities: live.activities.map((x, i) => (i === at ? a : x)) };
|
|
@@ -116,13 +126,23 @@ function run(live, e, meta) {
|
|
|
116
126
|
}
|
|
117
127
|
return live;
|
|
118
128
|
}
|
|
119
|
-
function withText(live, kind, id, delta) {
|
|
129
|
+
function withText(live, kind, id, delta, now) {
|
|
120
130
|
const at = live.parts.findIndex((p) => p.kind === kind && p.id === id);
|
|
121
|
-
|
|
131
|
+
let parts;
|
|
122
132
|
if (at < 0)
|
|
123
|
-
parts.
|
|
124
|
-
else if (delta)
|
|
125
|
-
|
|
133
|
+
parts = [...closeTexts(live.parts, now), { kind, id, text: delta, startedAt: now, endedAt: null }];
|
|
134
|
+
else if (delta) {
|
|
135
|
+
const p = live.parts[at];
|
|
136
|
+
if (!p.text && at < live.parts.length - 1) {
|
|
137
|
+
// Opened empty, then other parts came first (agent-pi opens the step's text before its reasoning): the text
|
|
138
|
+
// starts where its first delta is.
|
|
139
|
+
parts = [...closeTexts(live.parts.filter((_, i) => i !== at), now), { ...p, kind, text: delta, startedAt: now, endedAt: null }];
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
parts = live.parts.slice();
|
|
143
|
+
parts[at] = { ...p, kind, text: p.text + delta };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
126
146
|
else
|
|
127
147
|
return live;
|
|
128
148
|
const joined = parts
|
|
@@ -132,6 +152,26 @@ function withText(live, kind, id, delta) {
|
|
|
132
152
|
.join("\n\n");
|
|
133
153
|
return { ...live, parts, [kind]: joined };
|
|
134
154
|
}
|
|
155
|
+
/** Ends the open text and reasoning parts: another part starts. */
|
|
156
|
+
function closeTexts(parts, now) {
|
|
157
|
+
return parts.some((p) => (p.kind === "text" || p.kind === "reasoning") && p.endedAt === null)
|
|
158
|
+
? parts.map((p) => ((p.kind === "text" || p.kind === "reasoning") && p.endedAt === null ? { ...p, endedAt: now } : p))
|
|
159
|
+
: parts;
|
|
160
|
+
}
|
|
161
|
+
function endPart(live, kind, id, now) {
|
|
162
|
+
const at = live.parts.findIndex((p) => p.kind === kind && p.id === id && p.endedAt === null);
|
|
163
|
+
if (at < 0)
|
|
164
|
+
return live;
|
|
165
|
+
return { ...live, parts: live.parts.map((p, i) => (i === at ? { ...p, endedAt: now } : p)) };
|
|
166
|
+
}
|
|
167
|
+
function timingOf(v) {
|
|
168
|
+
if (!v || typeof v !== "object")
|
|
169
|
+
return null;
|
|
170
|
+
const t = v;
|
|
171
|
+
if (typeof t.durationMs !== "number")
|
|
172
|
+
return null;
|
|
173
|
+
return { ttfbMs: typeof t.ttfbMs === "number" ? t.ttfbMs : null, durationMs: t.durationMs };
|
|
174
|
+
}
|
|
135
175
|
function tool(live, id, f) {
|
|
136
176
|
const at = live.tools.findIndex((t) => t.id === id);
|
|
137
177
|
if (at < 0)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { LiveActivity, LiveRun, LiveTool } from "./reduce.ts";
|
|
2
|
+
/** A reasoning text shown inside a tool group, before the tool at index `at` of the group (`at = tools.length`: after the last). */
|
|
3
|
+
export interface GroupThought {
|
|
4
|
+
at: number;
|
|
5
|
+
text: string;
|
|
6
|
+
}
|
|
7
|
+
/** One item of a run as a chat draws it. `startedAt` / `endedAt` as `PartTimes` (`endedAt` null while open). */
|
|
8
|
+
export type TimelineItem = {
|
|
9
|
+
kind: "reasoning";
|
|
10
|
+
id: string;
|
|
11
|
+
text: string;
|
|
12
|
+
startedAt: number;
|
|
13
|
+
endedAt: number | null;
|
|
14
|
+
} | {
|
|
15
|
+
kind: "tools";
|
|
16
|
+
id: string;
|
|
17
|
+
tools: LiveTool[];
|
|
18
|
+
thoughts: GroupThought[];
|
|
19
|
+
startedAt: number;
|
|
20
|
+
endedAt: number | null;
|
|
21
|
+
} | {
|
|
22
|
+
kind: "text";
|
|
23
|
+
id: string;
|
|
24
|
+
text: string;
|
|
25
|
+
startedAt: number;
|
|
26
|
+
endedAt: number | null;
|
|
27
|
+
} | {
|
|
28
|
+
kind: "activity";
|
|
29
|
+
id: string;
|
|
30
|
+
activity: LiveActivity;
|
|
31
|
+
startedAt: number;
|
|
32
|
+
endedAt: number | null;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The live run as an ordered list of items, grouped as baton's chat groups them: consecutive tool calls in one
|
|
36
|
+
* `tools` item, text segments split by tools (a text part is one item; blank ones are dropped), cards in place (a card ends the tool group before it).
|
|
37
|
+
* Reasoning before any tool of a segment is its own `reasoning` item (a run with no tools keeps all of it);
|
|
38
|
+
* reasoning that comes while a tool group is open joins that group's `thoughts`, so a model that thinks between
|
|
39
|
+
* calls still shows one "3 steps" line. A tool group ends (`endedAt`) when its last tool has; it has the id of its
|
|
40
|
+
* first tool. Pure: call it on each render.
|
|
41
|
+
*/
|
|
42
|
+
export declare function timeline(live: LiveRun): TimelineItem[];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live run as an ordered list of items, grouped as baton's chat groups them: consecutive tool calls in one
|
|
3
|
+
* `tools` item, text segments split by tools (a text part is one item; blank ones are dropped), cards in place (a card ends the tool group before it).
|
|
4
|
+
* Reasoning before any tool of a segment is its own `reasoning` item (a run with no tools keeps all of it);
|
|
5
|
+
* reasoning that comes while a tool group is open joins that group's `thoughts`, so a model that thinks between
|
|
6
|
+
* calls still shows one "3 steps" line. A tool group ends (`endedAt`) when its last tool has; it has the id of its
|
|
7
|
+
* first tool. Pure: call it on each render.
|
|
8
|
+
*/
|
|
9
|
+
export function timeline(live) {
|
|
10
|
+
const out = [];
|
|
11
|
+
const tools = new Map(live.tools.map((t) => [t.id, t]));
|
|
12
|
+
const activities = new Map(live.activities.map((a) => [a.id, a]));
|
|
13
|
+
let group = null;
|
|
14
|
+
for (const p of live.parts) {
|
|
15
|
+
if (p.kind === "text") {
|
|
16
|
+
group = null;
|
|
17
|
+
if (p.text.trim())
|
|
18
|
+
out.push({ kind: "text", id: p.id, text: p.text, startedAt: p.startedAt, endedAt: p.endedAt });
|
|
19
|
+
}
|
|
20
|
+
else if (p.kind === "reasoning") {
|
|
21
|
+
if (!p.text.trim())
|
|
22
|
+
continue;
|
|
23
|
+
if (group)
|
|
24
|
+
group.thoughts.push({ at: group.tools.length, text: p.text });
|
|
25
|
+
else
|
|
26
|
+
out.push({ kind: "reasoning", id: p.id, text: p.text, startedAt: p.startedAt, endedAt: p.endedAt });
|
|
27
|
+
}
|
|
28
|
+
else if (p.kind === "tool") {
|
|
29
|
+
const t = tools.get(p.id);
|
|
30
|
+
if (!t)
|
|
31
|
+
continue;
|
|
32
|
+
if (!group)
|
|
33
|
+
out.push((group = { kind: "tools", id: t.id, tools: [], thoughts: [], startedAt: p.startedAt, endedAt: p.endedAt }));
|
|
34
|
+
group.tools.push(t);
|
|
35
|
+
group.endedAt = group.endedAt === null || p.endedAt === null ? null : Math.max(group.endedAt, p.endedAt);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const a = activities.get(p.id);
|
|
39
|
+
if (!a)
|
|
40
|
+
continue;
|
|
41
|
+
group = null;
|
|
42
|
+
out.push({ kind: "activity", id: a.id, activity: a, startedAt: p.startedAt, endedAt: p.endedAt });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
@@ -96,6 +96,11 @@ export class AgentFollower {
|
|
|
96
96
|
const turns = group(tail.entries);
|
|
97
97
|
const runningNow = a?.status === "running";
|
|
98
98
|
const cur = runningNow ? turns.at(-1) ?? null : null;
|
|
99
|
+
// A gap inside a turn whose start we saw keeps its clock; text the tail shows first counts from now.
|
|
100
|
+
if (cur && this.turn?.turnId === cur.turnId && this.turn.startedAt != null) {
|
|
101
|
+
cur.startedAt = this.turn.startedAt;
|
|
102
|
+
cur.ttfbMs = this.turn.ttfbMs ?? (cur.folder.text() ? Date.now() - this.turn.startedAt : null);
|
|
103
|
+
}
|
|
99
104
|
this.history = [];
|
|
100
105
|
for (const t of turns)
|
|
101
106
|
if (t !== cur)
|
|
@@ -142,8 +147,11 @@ export class AgentFollower {
|
|
|
142
147
|
this.emit(x);
|
|
143
148
|
return;
|
|
144
149
|
}
|
|
145
|
-
for (const x of t.folder.push(it))
|
|
150
|
+
for (const x of t.folder.push(it)) {
|
|
151
|
+
if (t.ttfbMs == null && t.startedAt != null && x.type === EventType.TEXT_MESSAGE_CONTENT && x.delta)
|
|
152
|
+
t.ttfbMs = Date.now() - t.startedAt;
|
|
146
153
|
this.emit(x);
|
|
154
|
+
}
|
|
147
155
|
return;
|
|
148
156
|
}
|
|
149
157
|
if (e.type === "turn_started") {
|
|
@@ -162,7 +170,7 @@ export class AgentFollower {
|
|
|
162
170
|
begin(turnId) {
|
|
163
171
|
if (this.turn)
|
|
164
172
|
this.end(this.turn, "done");
|
|
165
|
-
this.turn = { turnId, user: null, folder: new TurnFolder() };
|
|
173
|
+
this.turn = { turnId, user: null, folder: new TurnFolder(), startedAt: Date.now(), ttfbMs: null };
|
|
166
174
|
this.emit(this.started(this.turn));
|
|
167
175
|
}
|
|
168
176
|
end(t, status, error) {
|
|
@@ -170,15 +178,19 @@ export class AgentFollower {
|
|
|
170
178
|
this.emit(x);
|
|
171
179
|
this.history.push(...messages(t));
|
|
172
180
|
this.turn = null;
|
|
181
|
+
const timing = t.startedAt != null ? { timing: { ttfbMs: t.ttfbMs ?? null, durationMs: Date.now() - t.startedAt } } : {};
|
|
173
182
|
if (status === "error")
|
|
174
|
-
this.emit({ type: EventType.RUN_ERROR, message: error ?? "the turn failed", metadata: { threadId: this.agentId, runId: t.turnId } });
|
|
175
|
-
else
|
|
183
|
+
this.emit({ type: EventType.RUN_ERROR, message: error ?? "the turn failed", metadata: { threadId: this.agentId, runId: t.turnId, ...timing } });
|
|
184
|
+
else {
|
|
185
|
+
const metadata = { ...timing, ...(status === "stopped" ? { stopped: true } : {}) };
|
|
176
186
|
this.emit({
|
|
177
187
|
type: EventType.RUN_FINISHED,
|
|
178
188
|
threadId: this.agentId,
|
|
179
189
|
runId: t.turnId,
|
|
180
|
-
...(status === "stopped" ? { outcome: { type: "cancelled" }
|
|
190
|
+
...(status === "stopped" ? { outcome: { type: "cancelled" } } : {}),
|
|
191
|
+
...(Object.keys(metadata).length ? { metadata } : {}),
|
|
181
192
|
});
|
|
193
|
+
}
|
|
182
194
|
}
|
|
183
195
|
async regap(why, resubscribe = false) {
|
|
184
196
|
if (this.closed || this.buffer)
|
|
@@ -153,6 +153,8 @@ export declare class PaseoThreadRunner<TResult = unknown> {
|
|
|
153
153
|
private drain;
|
|
154
154
|
/** A quiet or broken stream: the daemon says whether the turn ended while no event came. */
|
|
155
155
|
private check;
|
|
156
|
+
/** `{timing}` for the end event of a run whose start this runner saw; nothing for a recovered one. */
|
|
157
|
+
private timing;
|
|
156
158
|
private cleanup;
|
|
157
159
|
private fail;
|
|
158
160
|
/** Ends the run: stores the answer and emits `RUN_FINISHED`, or fails it. Resolves true when an answer was stored. */
|
|
@@ -57,6 +57,7 @@ export class PaseoThreadRunner {
|
|
|
57
57
|
if (this.runs.has(req.threadId))
|
|
58
58
|
throw new Error(`thread ${req.threadId} already has a run in progress`);
|
|
59
59
|
const run = this.newRun(req.threadId, req.runId ?? `jig-${randomUUID()}`, null, req.metadata, false);
|
|
60
|
+
run.startedAt = Date.now();
|
|
60
61
|
this.runs.set(run.threadId, run);
|
|
61
62
|
this.emit(run.threadId, this.started(run));
|
|
62
63
|
void this.deliver(req, run).catch((e) => this.fail(run, e.message));
|
|
@@ -126,7 +127,7 @@ export class PaseoThreadRunner {
|
|
|
126
127
|
}
|
|
127
128
|
// ---- internals
|
|
128
129
|
newRun(threadId, runId, agentId, metadata, ours) {
|
|
129
|
-
return { threadId, runId, agentId, metadata, turn: new TurnFolder(), ours, turnId: null, epoch: null, seq: -1, buffer: null, again: null, sentAt: null, waiting: null, stopping: false, unsub: null, last: Date.now(), watch: null, done: false };
|
|
130
|
+
return { threadId, runId, agentId, metadata, turn: new TurnFolder(), ours, turnId: null, epoch: null, seq: -1, buffer: null, again: null, sentAt: null, waiting: null, stopping: false, unsub: null, last: Date.now(), watch: null, done: false, startedAt: null, ttfbMs: null };
|
|
130
131
|
}
|
|
131
132
|
started(run) {
|
|
132
133
|
return { type: EventType.RUN_STARTED, threadId: run.threadId, runId: run.runId, ...(run.metadata ? { metadata: run.metadata } : {}) };
|
|
@@ -210,8 +211,11 @@ export class PaseoThreadRunner {
|
|
|
210
211
|
return;
|
|
211
212
|
if (run.turnId && e.turnId && e.turnId !== run.turnId)
|
|
212
213
|
return;
|
|
213
|
-
for (const x of run.turn.push(it))
|
|
214
|
+
for (const x of run.turn.push(it)) {
|
|
215
|
+
if (run.ttfbMs === null && run.startedAt !== null && x.type === EventType.TEXT_MESSAGE_CONTENT && x.delta)
|
|
216
|
+
run.ttfbMs = Date.now() - run.startedAt;
|
|
214
217
|
this.emit(run.threadId, x);
|
|
218
|
+
}
|
|
215
219
|
return;
|
|
216
220
|
}
|
|
217
221
|
// `turn_started` claims nothing: it may be someone else's turn. The daemon shows our message right after ours starts.
|
|
@@ -368,6 +372,10 @@ export class PaseoThreadRunner {
|
|
|
368
372
|
this.log(`agent-paseo thread ${run.threadId}: check: ${e.message}`);
|
|
369
373
|
}
|
|
370
374
|
}
|
|
375
|
+
/** `{timing}` for the end event of a run whose start this runner saw; nothing for a recovered one. */
|
|
376
|
+
timing(run) {
|
|
377
|
+
return run.startedAt === null ? {} : { timing: { ttfbMs: run.ttfbMs, durationMs: Date.now() - run.startedAt } };
|
|
378
|
+
}
|
|
371
379
|
cleanup(run) {
|
|
372
380
|
run.done = true;
|
|
373
381
|
run.waiting = null;
|
|
@@ -385,7 +393,7 @@ export class PaseoThreadRunner {
|
|
|
385
393
|
for (const e of run.turn.end())
|
|
386
394
|
this.emit(run.threadId, e);
|
|
387
395
|
void this.o.store.saveError(run.threadId, { runId: run.runId, agentId: run.agentId, error: error.slice(0, 2000) }).catch((e) => this.log(`agent-paseo thread ${run.threadId}: saveError: ${e.message}`));
|
|
388
|
-
this.emit(run.threadId, { type: EventType.RUN_ERROR, message: error, metadata: { threadId: run.threadId, runId: run.runId } });
|
|
396
|
+
this.emit(run.threadId, { type: EventType.RUN_ERROR, message: error, metadata: { threadId: run.threadId, runId: run.runId, ...this.timing(run) } });
|
|
389
397
|
}
|
|
390
398
|
/** Ends the run: stores the answer and emits `RUN_FINISHED`, or fails it. Resolves true when an answer was stored. */
|
|
391
399
|
async finish(run, status, error) {
|
|
@@ -403,20 +411,23 @@ export class PaseoThreadRunner {
|
|
|
403
411
|
this.cleanup(run);
|
|
404
412
|
for (const e of run.turn.end())
|
|
405
413
|
this.emit(run.threadId, e);
|
|
414
|
+
// Measured when the turn ended, not after the host stored the answer.
|
|
415
|
+
const timing = this.timing(run);
|
|
406
416
|
try {
|
|
407
417
|
const result = await this.o.store.saveAnswer(run.threadId, { runId: run.runId, agentId: run.agentId, text, tools: run.turn.toolList(), status, ...(error ? { error } : {}) });
|
|
418
|
+
const metadata = { ...timing, ...(status === "stopped" ? { stopped: true } : {}), ...(status === "error" ? { error: error ?? "the turn failed" } : {}) };
|
|
408
419
|
this.emit(run.threadId, {
|
|
409
420
|
type: EventType.RUN_FINISHED,
|
|
410
421
|
threadId: run.threadId,
|
|
411
422
|
runId: run.runId,
|
|
412
423
|
result,
|
|
413
|
-
...(status === "stopped" ? { outcome: { type: "cancelled" }
|
|
414
|
-
...(
|
|
424
|
+
...(status === "stopped" ? { outcome: { type: "cancelled" } } : {}),
|
|
425
|
+
...(Object.keys(metadata).length ? { metadata } : {}),
|
|
415
426
|
});
|
|
416
427
|
return true;
|
|
417
428
|
}
|
|
418
429
|
catch (e) {
|
|
419
|
-
this.emit(run.threadId, { type: EventType.RUN_ERROR, message: e.message, metadata: { threadId: run.threadId, runId: run.runId } });
|
|
430
|
+
this.emit(run.threadId, { type: EventType.RUN_ERROR, message: e.message, metadata: { threadId: run.threadId, runId: run.runId, ...timing } });
|
|
420
431
|
return false;
|
|
421
432
|
}
|
|
422
433
|
}
|
package/dist/agent-pi/index.d.ts
CHANGED
|
@@ -9,3 +9,7 @@ export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, wind
|
|
|
9
9
|
export type { Card, PiRunEvent, RunAgentOptions, RunLimits, RunResult, RunTool, Turn } from "./run.ts";
|
|
10
10
|
export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.ts";
|
|
11
11
|
export type { PgSessionStoreOptions, Query, RunStart, RunStatus, RunUsage, SessionStore } from "./store.ts";
|
|
12
|
+
export { Busy, failOrphans, RunFolder, RunRegistry, runRegistry } from "./registry.ts";
|
|
13
|
+
export type { ReadyValue, RegistryRun, RunListener, StartOptions } from "./registry.ts";
|
|
14
|
+
export { sseFrame, sseResponse } from "./sse.ts";
|
|
15
|
+
export type { Listenable, SseOptions } from "./sse.ts";
|
package/dist/agent-pi/index.js
CHANGED
|
@@ -6,3 +6,5 @@
|
|
|
6
6
|
export { costOf, modelCost, parsePrices, piModels, routerModel, singleModel } from "./models.js";
|
|
7
7
|
export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, windowEntries, withoutEmptyImages, withoutImages } from "./run.js";
|
|
8
8
|
export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.js";
|
|
9
|
+
export { Busy, failOrphans, RunFolder, RunRegistry, runRegistry } from "./registry.js";
|
|
10
|
+
export { sseFrame, sseResponse } from "./sse.js";
|
|
@@ -29,6 +29,8 @@ export interface PiModels {
|
|
|
29
29
|
tier: string;
|
|
30
30
|
thinking: Thinking;
|
|
31
31
|
};
|
|
32
|
+
/** The model of a tier, for a run that picks its own (`runAgent({ tier })`). Throws for an unknown tier. */
|
|
33
|
+
byTier?(tier: string): PiModel;
|
|
32
34
|
}
|
|
33
35
|
export interface PiModelsOptions<TTier extends string, TPurpose extends string> {
|
|
34
36
|
/** The OpenAI-compatible router (`…/v1`). */
|
|
@@ -84,7 +86,7 @@ export declare function piModels<TTier extends string, TPurpose extends string>(
|
|
|
84
86
|
};
|
|
85
87
|
/**
|
|
86
88
|
* 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.
|
|
89
|
+
* `purposes` runs as tier `default` without thinking. `byTier` knows `default` and the purposes' tiers.
|
|
88
90
|
*/
|
|
89
91
|
export declare function singleModel(model: PiModel, purposes?: Record<string, PurposeModel>): PiModels;
|
|
90
92
|
/** A reply's cost: what the provider worked out, else the model's rates over its usage (a faux stream prices nothing). */
|
package/dist/agent-pi/models.js
CHANGED
|
@@ -77,13 +77,15 @@ export function piModels(o) {
|
|
|
77
77
|
if (!byTier.has(pick.tier))
|
|
78
78
|
throw new Error(`purpose ${purpose} names tier ${pick.tier}, which has no model`);
|
|
79
79
|
}
|
|
80
|
+
const tier = (name) => {
|
|
81
|
+
const model = byTier.get(name);
|
|
82
|
+
if (!model)
|
|
83
|
+
throw new Error(`no model for tier ${name}`);
|
|
84
|
+
return model;
|
|
85
|
+
};
|
|
80
86
|
return {
|
|
81
|
-
tier
|
|
82
|
-
|
|
83
|
-
if (!model)
|
|
84
|
-
throw new Error(`no model for tier ${name}`);
|
|
85
|
-
return model;
|
|
86
|
-
},
|
|
87
|
+
tier,
|
|
88
|
+
byTier: tier,
|
|
87
89
|
pick: (purpose) => {
|
|
88
90
|
const pick = o.purposes[purpose];
|
|
89
91
|
if (!pick)
|
|
@@ -94,10 +96,18 @@ export function piModels(o) {
|
|
|
94
96
|
}
|
|
95
97
|
/**
|
|
96
98
|
* 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.
|
|
99
|
+
* `purposes` runs as tier `default` without thinking. `byTier` knows `default` and the purposes' tiers.
|
|
98
100
|
*/
|
|
99
101
|
export function singleModel(model, purposes = {}) {
|
|
100
|
-
|
|
102
|
+
const tiers = new Set(["default", ...Object.values(purposes).map((p) => p.tier)]);
|
|
103
|
+
return {
|
|
104
|
+
pick: (purpose) => ({ model, tier: purposes[purpose]?.tier ?? "default", thinking: purposes[purpose]?.thinking ?? "off" }),
|
|
105
|
+
byTier: (tier) => {
|
|
106
|
+
if (!tiers.has(tier))
|
|
107
|
+
throw new Error(`no model for tier ${tier}`);
|
|
108
|
+
return model;
|
|
109
|
+
},
|
|
110
|
+
};
|
|
101
111
|
}
|
|
102
112
|
/** A reply's cost: what the provider worked out, else the model's rates over its usage (a faux stream prices nothing). */
|
|
103
113
|
export function costOf(model, usage) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { PiRunEvent } from "./run.ts";
|
|
2
|
+
import type { SessionStore } from "./store.ts";
|
|
3
|
+
/** A thread already has a run in progress. Hosts answer it with 409. */
|
|
4
|
+
export declare class Busy extends Error {
|
|
5
|
+
readonly threadId: string;
|
|
6
|
+
readonly runId: string;
|
|
7
|
+
constructor(threadId: string, runId: string);
|
|
8
|
+
}
|
|
9
|
+
/** `value` of `CUSTOM READY`, the first event every listener gets: the same as agent-paseo's. */
|
|
10
|
+
export interface ReadyValue {
|
|
11
|
+
threadId: string;
|
|
12
|
+
runId: string | null;
|
|
13
|
+
running: boolean;
|
|
14
|
+
}
|
|
15
|
+
export type RunListener = (event: PiRunEvent) => void;
|
|
16
|
+
/**
|
|
17
|
+
* What a run gets from the registry. The field names are `runAgent`'s option names, so `runAgent({ ...options, ...run })`
|
|
18
|
+
* wires the run in: its id, the thread as AG-UI `threadId`, the stop signal and the event sink.
|
|
19
|
+
*/
|
|
20
|
+
export interface RegistryRun {
|
|
21
|
+
runId: string;
|
|
22
|
+
threadId: string;
|
|
23
|
+
signal: AbortSignal;
|
|
24
|
+
onEvent: (event: PiRunEvent) => void;
|
|
25
|
+
}
|
|
26
|
+
export interface StartOptions {
|
|
27
|
+
/** The run's id. Default `run_` + 12 random characters (as `runAgent` makes them). */
|
|
28
|
+
runId?: string;
|
|
29
|
+
/** Merged into `RUN_STARTED.metadata` (the host's stored user message id, an ask id). */
|
|
30
|
+
metadata?: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* What a listener needs to see the run so far: a replay of the text, reasoning, tool calls and cards, in the order
|
|
34
|
+
* they came. Folded from the run's own events, so it holds exactly what a listener from the start saw.
|
|
35
|
+
*/
|
|
36
|
+
export declare class RunFolder {
|
|
37
|
+
private order;
|
|
38
|
+
fold(e: PiRunEvent): void;
|
|
39
|
+
/** The run so far as events: one CONTENT per message (the text so far), each START with its END if it ended. */
|
|
40
|
+
replay(): PiRunEvent[];
|
|
41
|
+
private find;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* One run per thread in this process, which outlives the HTTP request that started it, and its events to any number
|
|
45
|
+
* of listeners. A listener that joins mid-run (a reload, a second tab, a reconnect) gets `READY`, `RUN_STARTED` and a
|
|
46
|
+
* replay of the run so far, then the live events: the follower contract agent-paseo's runner keeps
|
|
47
|
+
* (`.ea/docs/agent-chat.md`). Nothing is persisted here; the run's store has the session and the run row.
|
|
48
|
+
*/
|
|
49
|
+
export declare class RunRegistry {
|
|
50
|
+
private runs;
|
|
51
|
+
private listeners;
|
|
52
|
+
private warn;
|
|
53
|
+
constructor(o?: {
|
|
54
|
+
warn?: (message: string, detail?: unknown) => void;
|
|
55
|
+
});
|
|
56
|
+
running(threadId: string): boolean;
|
|
57
|
+
current(threadId: string): {
|
|
58
|
+
runId: string;
|
|
59
|
+
} | null;
|
|
60
|
+
/**
|
|
61
|
+
* Starts a run on a thread; throws `Busy` when the thread has one. `fn` gets the run's id, thread, stop signal and
|
|
62
|
+
* event sink (`runAgent({ ...options, ...run })`). The registry guarantees each run one terminal event: when `fn`
|
|
63
|
+
* throws or settles without one, it sends `RUN_ERROR` / `RUN_FINISHED` itself. The run leaves the registry with its
|
|
64
|
+
* terminal event; events after it are dropped. `result` is `fn`'s promise (already handled: not awaiting it is fine).
|
|
65
|
+
*/
|
|
66
|
+
start<T>(threadId: string, fn: (run: RegistryRun) => Promise<T>, o?: StartOptions): {
|
|
67
|
+
runId: string;
|
|
68
|
+
result: Promise<T>;
|
|
69
|
+
};
|
|
70
|
+
/** Aborts the thread's run (only `runId`'s, when given). False when there is no such run. */
|
|
71
|
+
stop(threadId: string, runId?: string): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Follows a thread: `CUSTOM READY {threadId, runId, running}` at once; when a run is in progress, `RUN_STARTED` and
|
|
74
|
+
* the replay of the run so far (once the run has started); then live events. Returns the unsubscribe.
|
|
75
|
+
*/
|
|
76
|
+
listen(threadId: string, fn: RunListener): () => void;
|
|
77
|
+
/** Aborts every run (shutdown). */
|
|
78
|
+
close(): void;
|
|
79
|
+
private onEvent;
|
|
80
|
+
private end;
|
|
81
|
+
/** Delivers to the listeners there are now: one that joins during delivery got this event in its replay already. */
|
|
82
|
+
private send;
|
|
83
|
+
private call;
|
|
84
|
+
}
|
|
85
|
+
export declare function runRegistry(o?: {
|
|
86
|
+
warn?: (message: string, detail?: unknown) => void;
|
|
87
|
+
}): RunRegistry;
|
|
88
|
+
/**
|
|
89
|
+
* At startup, before serving: runs the store still shows `running` were never finished (the process that ran them is
|
|
90
|
+
* gone, and with it their registry), so they are marked failed. Returns how many. Hosts with their own visible-thread
|
|
91
|
+
* rows (`rudi_messages`, a chat message `streaming`) fail those in the same place.
|
|
92
|
+
*/
|
|
93
|
+
export declare function failOrphans(store: Pick<SessionStore, "failStaleRuns">): Promise<number>;
|