pi-legion 0.16.0 → 2.0.0
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/CONTRIBUTING.md +58 -0
- package/README.md +313 -640
- package/agents/advisor.md +7 -5
- package/agents/centurion.md +53 -0
- package/agents/designer.md +33 -33
- package/agents/planner.md +1 -2
- package/agents/prototype.md +2 -2
- package/agents/reviewer.md +67 -31
- package/agents/scout.md +6 -2
- package/agents/worker.md +12 -3
- package/docs/contracts/esc-abort-v1.md +131 -0
- package/docs/contracts/esc-cascade-v2.md +100 -0
- package/docs/design.md +44 -25
- package/docs/legion-v2-contract.md +461 -0
- package/docs/legion-v2-delivery.md +62 -0
- package/docs/retire-hardening-contract.md +125 -0
- package/docs/subagents-teams.md +76 -0
- package/docs/tui-viewer-contract.md +276 -0
- package/docs/vexillatio-contract.md +162 -0
- package/index.ts +1462 -286
- package/package.json +12 -9
- package/skills/pi-legion/SKILL.md +74 -96
- package/src/agents/agents.ts +6 -11
- package/src/agents/overrides.ts +2 -1
- package/src/agents/paths.ts +1 -1
- package/src/agents/settings.ts +268 -20
- package/src/api.ts +47 -48
- package/src/{herdr → backends/legacy}/client.ts +14 -69
- package/src/{shared → backends/legacy}/cursor-chat.ts +2 -2
- package/src/{herdr → backends/legacy}/runner.ts +22 -9
- package/src/backends/legacy/types.ts +138 -0
- package/src/extension/auto-doctor.ts +144 -0
- package/src/extension/budget.ts +2 -2
- package/src/extension/child-guard.ts +214 -201
- package/src/extension/event-bus.ts +263 -0
- package/src/extension/legion-commands.ts +719 -0
- package/src/extension/legion-doctor.ts +888 -0
- package/src/extension/legion-stop.ts +150 -0
- package/src/extension/legion-tools.ts +816 -0
- package/src/extension/notify.ts +24 -19
- package/src/extension/playbook.ts +20 -89
- package/src/extension/recycle.ts +2 -7
- package/src/extension/runtime.ts +655 -105
- package/src/extension/scout-guard.ts +483 -0
- package/src/extension/slash.ts +89 -438
- package/src/extension/spawn-hints.ts +79 -0
- package/src/extension/summary.ts +17 -58
- package/src/legion/budget.ts +165 -0
- package/src/legion/db.ts +242 -0
- package/src/legion/events.ts +150 -0
- package/src/legion/mail.ts +412 -0
- package/src/legion/nodes.ts +461 -0
- package/src/legion/rebuild.ts +533 -0
- package/src/legion/state-machine.ts +313 -0
- package/src/legion/usage.ts +101 -0
- package/src/runs/acceptance.ts +82 -25
- package/src/runs/args.ts +51 -5
- package/src/runs/hygiene.ts +335 -0
- package/src/runs/orchestrator.ts +790 -1683
- package/src/runs/owner.ts +61 -0
- package/src/runs/provision.ts +135 -0
- package/src/runs/store.ts +44 -17
- package/src/runs/verify-queue.ts +195 -0
- package/src/shared/name.ts +29 -0
- package/src/shared/output-cap.ts +57 -0
- package/src/shared/progress.ts +57 -135
- package/src/shared/session.ts +243 -171
- package/src/shared/types.ts +107 -208
- package/src/supervisor/child-memory.ts +140 -0
- package/src/supervisor/proc-tree.ts +103 -0
- package/src/supervisor/rpc-supervisor.ts +1033 -0
- package/src/supervisor/types.ts +153 -0
- package/src/supervisor/ui-proxy.ts +226 -0
- package/src/tui/chat-items.ts +330 -0
- package/src/tui/live-overlay.ts +874 -0
- package/src/tui/status.ts +553 -27
- package/src/tui/tree-view.ts +808 -0
- package/src/tui/viz/canvas.ts +119 -0
- package/src/tui/viz/layout.ts +111 -0
- package/src/tui/viz/model.ts +123 -0
- package/src/tui/viz/palette.ts +188 -0
- package/src/tui/viz/panels.ts +530 -0
- package/src/tui/viz/railway.ts +313 -0
- package/src/tui/viz/rate.ts +211 -0
- package/src/tui/viz/view.ts +228 -0
- package/src/extension/parent-label.ts +0 -115
- package/src/profiles/classify.ts +0 -375
- package/src/profiles/profiles.ts +0 -730
- package/src/runs/layout.ts +0 -258
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* M1 RPC supervisor contracts and the narrow client adapter seam used by tests.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { RpcClientOptions as PiRpcClientOptions } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { Writable } from "node:stream";
|
|
7
|
+
import type { BuildArgsInput } from "../runs/args.ts";
|
|
8
|
+
import type { UIProxy } from "./ui-proxy.ts";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Input to one child launch. `name` is the registry key supplied by the caller
|
|
12
|
+
* (the tree node id in v2); this layer does not sanitize or expand it.
|
|
13
|
+
*/
|
|
14
|
+
export interface SpawnInput extends Omit<BuildArgsInput, "cwd" | "includeTask"> {
|
|
15
|
+
name: string;
|
|
16
|
+
/** Working directory for the child Pi process. */
|
|
17
|
+
cwd: string;
|
|
18
|
+
/** Environment overlay passed to RpcClient. */
|
|
19
|
+
env?: Record<string, string>;
|
|
20
|
+
/** Whether to remove Legion lineage identity from the inherited environment. */
|
|
21
|
+
stripLegionIdentity?: boolean;
|
|
22
|
+
/** Optional Pi CLI entry point override. */
|
|
23
|
+
cliPath?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Handle returned after the RPC process accepts its first prompt. */
|
|
27
|
+
export interface ChildHandle {
|
|
28
|
+
name: string;
|
|
29
|
+
sessionFile: string;
|
|
30
|
+
pid?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Process id and process group id for one descendant of a supervised child. */
|
|
34
|
+
export interface DescendantInfo {
|
|
35
|
+
pid: number;
|
|
36
|
+
pgid: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Injectable options for process lifecycle handling in RpcSupervisor. */
|
|
40
|
+
export interface RpcSupervisorOptions {
|
|
41
|
+
/** Called with the refusal text when the memory gate blocks a spawn (UI notify hook). */
|
|
42
|
+
onSpawnRefused?: (message: string) => void;
|
|
43
|
+
/** Override the available-memory probe (MB) in tests. */
|
|
44
|
+
memoryAvailable?: () => number;
|
|
45
|
+
/** Replace the Pi client constructor in unit tests. */
|
|
46
|
+
clientFactory?: RpcClientFactory;
|
|
47
|
+
/** In-memory by default; M1-integration supplies a real TUI consumer. */
|
|
48
|
+
uiProxy?: UIProxy;
|
|
49
|
+
/** Grace period after stdin close before SIGTERM. */
|
|
50
|
+
retireTimeoutMs?: number;
|
|
51
|
+
/** Grace period for a child to exit after SIGTERM. */
|
|
52
|
+
signalTimeoutMs?: number;
|
|
53
|
+
/** Grace period for a child to exit after SIGKILL. */
|
|
54
|
+
killTimeoutMs?: number;
|
|
55
|
+
/** Enumerate process descendants before retiring a child. */
|
|
56
|
+
enumerateDescendants?: (rootPid: number) => DescendantInfo[];
|
|
57
|
+
/** Signal a PID or process group while sweeping descendants. */
|
|
58
|
+
signalProcess?: (target: number, signal: NodeJS.Signals) => boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Result of waiting for a child turn to settle or for its process to exit. */
|
|
62
|
+
export interface SettleResult {
|
|
63
|
+
/** True only when Pi emitted `agent_settled`. */
|
|
64
|
+
settled: boolean;
|
|
65
|
+
/** True when the process exited before a settle event was observed. */
|
|
66
|
+
abnormal: boolean;
|
|
67
|
+
aborted?: boolean;
|
|
68
|
+
exitCode?: number | null;
|
|
69
|
+
signal?: NodeJS.Signals | null;
|
|
70
|
+
reason?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Cumulative usage reported by the Pi RPC `get_session_stats` command. */
|
|
74
|
+
export interface UsageSnapshot {
|
|
75
|
+
tokensIn: number;
|
|
76
|
+
tokensOut: number;
|
|
77
|
+
costUsd: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The orchestrator's frozen backend seam (legion-v2-contract.md §3.1). */
|
|
81
|
+
export interface LegionSupervisor {
|
|
82
|
+
spawnChild(input: SpawnInput): Promise<ChildHandle>;
|
|
83
|
+
prompt(name: string, text: string): Promise<void>;
|
|
84
|
+
steer(name: string, text: string): Promise<void>;
|
|
85
|
+
followUp(name: string, text: string): Promise<void>;
|
|
86
|
+
abort(name: string): Promise<void>;
|
|
87
|
+
waitSettled(name: string, timeoutMs?: number, signal?: AbortSignal): Promise<SettleResult>;
|
|
88
|
+
isAlive(name: string): boolean;
|
|
89
|
+
stats(name: string): Promise<UsageSnapshot | null>;
|
|
90
|
+
retire(name: string, opts?: { graceful?: boolean }): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* RpcClient's public constructor options. Kept as an alias so the adapter tracks
|
|
95
|
+
* the installed Pi SDK without widening the supervisor contract.
|
|
96
|
+
*/
|
|
97
|
+
export type RpcClientOptions = PiRpcClientOptions;
|
|
98
|
+
|
|
99
|
+
/** Runtime process controls used by the host for exit and stdin lifecycle. */
|
|
100
|
+
export interface RpcProcessHandle {
|
|
101
|
+
pid?: number;
|
|
102
|
+
stdin:
|
|
103
|
+
| Pick<Writable, "destroyed" | "writableEnded" | "write" | "end">
|
|
104
|
+
| null;
|
|
105
|
+
exitCode: number | null;
|
|
106
|
+
signalCode: NodeJS.Signals | null;
|
|
107
|
+
once(
|
|
108
|
+
event: "exit",
|
|
109
|
+
listener: (code: number | null, signal: NodeJS.Signals | null) => void,
|
|
110
|
+
): this;
|
|
111
|
+
once(event: "error", listener: (error: Error) => void): this;
|
|
112
|
+
on(
|
|
113
|
+
event: "exit" | "close",
|
|
114
|
+
listener: (code: number | null, signal: NodeJS.Signals | null) => void,
|
|
115
|
+
): this;
|
|
116
|
+
off(
|
|
117
|
+
event: "exit" | "close",
|
|
118
|
+
listener: (code: number | null, signal: NodeJS.Signals | null) => void,
|
|
119
|
+
): this;
|
|
120
|
+
kill(signal?: NodeJS.Signals): boolean;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Only the RpcClient operations owned by the M1 host layer. */
|
|
124
|
+
export interface RpcClientLike {
|
|
125
|
+
/** Runtime process handle; RpcClient currently keeps it TS-private. */
|
|
126
|
+
process?: RpcProcessHandle | null;
|
|
127
|
+
start(): Promise<void>;
|
|
128
|
+
stop(): Promise<void>;
|
|
129
|
+
onEvent(listener: (event: unknown) => void): () => void;
|
|
130
|
+
getStderr?(): string;
|
|
131
|
+
prompt(message: string): Promise<unknown>;
|
|
132
|
+
steer(message: string): Promise<unknown>;
|
|
133
|
+
followUp(message: string): Promise<unknown>;
|
|
134
|
+
abort(): Promise<void>;
|
|
135
|
+
getSessionStats(): Promise<unknown>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Injectable RpcClient constructor used by unit tests. */
|
|
139
|
+
export type RpcClientFactory = (options: RpcClientOptions) => RpcClientLike;
|
|
140
|
+
|
|
141
|
+
/** Coarse lifecycle/tool event delivered by RpcSupervisor.onEvent(). */
|
|
142
|
+
export interface SupervisorEvent {
|
|
143
|
+
name: string;
|
|
144
|
+
type: string;
|
|
145
|
+
[key: string]: unknown;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** text_delta payloads are opt-in to keep default event traffic coarse. */
|
|
149
|
+
export interface EventSubscriptionOptions {
|
|
150
|
+
includeTextDelta?: boolean;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export type SupervisorEventListener = (event: SupervisorEvent) => void;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-side extension_ui_request types and in-memory forwarding queue.
|
|
3
|
+
* M1-integration supplies the real TUI consumer; this module owns no UI.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type ExtensionUIRequest =
|
|
7
|
+
| {
|
|
8
|
+
type: "extension_ui_request";
|
|
9
|
+
id: string;
|
|
10
|
+
method: "select";
|
|
11
|
+
title: string;
|
|
12
|
+
options: string[];
|
|
13
|
+
timeout?: number;
|
|
14
|
+
}
|
|
15
|
+
| {
|
|
16
|
+
type: "extension_ui_request";
|
|
17
|
+
id: string;
|
|
18
|
+
method: "confirm";
|
|
19
|
+
title: string;
|
|
20
|
+
message: string;
|
|
21
|
+
timeout?: number;
|
|
22
|
+
}
|
|
23
|
+
| {
|
|
24
|
+
type: "extension_ui_request";
|
|
25
|
+
id: string;
|
|
26
|
+
method: "input";
|
|
27
|
+
title: string;
|
|
28
|
+
placeholder?: string;
|
|
29
|
+
timeout?: number;
|
|
30
|
+
}
|
|
31
|
+
| {
|
|
32
|
+
type: "extension_ui_request";
|
|
33
|
+
id: string;
|
|
34
|
+
method: "editor";
|
|
35
|
+
title: string;
|
|
36
|
+
prefill?: string;
|
|
37
|
+
}
|
|
38
|
+
| {
|
|
39
|
+
type: "extension_ui_request";
|
|
40
|
+
id: string;
|
|
41
|
+
method: "notify";
|
|
42
|
+
message: string;
|
|
43
|
+
notifyType?: "info" | "warning" | "error";
|
|
44
|
+
}
|
|
45
|
+
| {
|
|
46
|
+
type: "extension_ui_request";
|
|
47
|
+
id: string;
|
|
48
|
+
method: "setStatus";
|
|
49
|
+
statusKey: string;
|
|
50
|
+
statusText?: string;
|
|
51
|
+
}
|
|
52
|
+
| {
|
|
53
|
+
type: "extension_ui_request";
|
|
54
|
+
id: string;
|
|
55
|
+
method: "setWidget";
|
|
56
|
+
widgetKey: string;
|
|
57
|
+
widgetLines?: string[];
|
|
58
|
+
widgetPlacement?: "aboveEditor" | "belowEditor";
|
|
59
|
+
}
|
|
60
|
+
| {
|
|
61
|
+
type: "extension_ui_request";
|
|
62
|
+
id: string;
|
|
63
|
+
method: "setTitle";
|
|
64
|
+
title: string;
|
|
65
|
+
}
|
|
66
|
+
| {
|
|
67
|
+
type: "extension_ui_request";
|
|
68
|
+
id: string;
|
|
69
|
+
method: "set_editor_text";
|
|
70
|
+
text: string;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** Response payload; UIProxy adds the RPC envelope and request id. */
|
|
74
|
+
export type ExtensionUIResponse =
|
|
75
|
+
| { value: string }
|
|
76
|
+
| { confirmed: boolean }
|
|
77
|
+
| { cancelled: true };
|
|
78
|
+
|
|
79
|
+
export interface PendingUIRequest {
|
|
80
|
+
/** Supervisor-local id; unique even when children reuse RPC request ids. */
|
|
81
|
+
id: string;
|
|
82
|
+
childName: string;
|
|
83
|
+
rpcRequestId: string;
|
|
84
|
+
request: ExtensionUIRequest;
|
|
85
|
+
receivedAt: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface UIProxyEnqueueInput {
|
|
89
|
+
childName: string;
|
|
90
|
+
request: ExtensionUIRequest;
|
|
91
|
+
respond?: (response: ExtensionUIResponse) => void;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Adapter surface for forwarding requests to a future TUI consumer. */
|
|
95
|
+
export interface UIProxy {
|
|
96
|
+
enqueue(input: UIProxyEnqueueInput): PendingUIRequest;
|
|
97
|
+
pending(): readonly PendingUIRequest[];
|
|
98
|
+
take(): PendingUIRequest | undefined;
|
|
99
|
+
respond(id: string, response: ExtensionUIResponse): boolean;
|
|
100
|
+
forgetChild(childName: string): void;
|
|
101
|
+
onRequest(listener: (request: PendingUIRequest) => void): () => void;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface StoredResponse {
|
|
105
|
+
childName: string;
|
|
106
|
+
respond: (response: ExtensionUIResponse) => void;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Type guard for the JSON event delivered by RpcClient's extension UI path. */
|
|
110
|
+
export function isExtensionUIRequest(value: unknown): value is ExtensionUIRequest {
|
|
111
|
+
if (!value || typeof value !== "object") return false;
|
|
112
|
+
// SAFETY: the object check above guarantees the value has an object record shape;
|
|
113
|
+
// all properties below are still validated before they narrow the request.
|
|
114
|
+
const record = value as Record<string, unknown>;
|
|
115
|
+
if (
|
|
116
|
+
record.type !== "extension_ui_request" ||
|
|
117
|
+
typeof record.id !== "string" ||
|
|
118
|
+
typeof record.method !== "string"
|
|
119
|
+
) {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
switch (record.method) {
|
|
124
|
+
case "select":
|
|
125
|
+
return (
|
|
126
|
+
typeof record.title === "string" &&
|
|
127
|
+
Array.isArray(record.options) &&
|
|
128
|
+
record.options.every((option) => typeof option === "string")
|
|
129
|
+
);
|
|
130
|
+
case "confirm":
|
|
131
|
+
return typeof record.title === "string" && typeof record.message === "string";
|
|
132
|
+
case "input":
|
|
133
|
+
return typeof record.title === "string";
|
|
134
|
+
case "editor":
|
|
135
|
+
return typeof record.title === "string";
|
|
136
|
+
case "notify":
|
|
137
|
+
return typeof record.message === "string";
|
|
138
|
+
case "setStatus":
|
|
139
|
+
return typeof record.statusKey === "string";
|
|
140
|
+
case "setWidget":
|
|
141
|
+
return typeof record.widgetKey === "string";
|
|
142
|
+
case "setTitle":
|
|
143
|
+
return typeof record.title === "string";
|
|
144
|
+
case "set_editor_text":
|
|
145
|
+
return typeof record.text === "string";
|
|
146
|
+
default:
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isDialogRequest(request: ExtensionUIRequest): boolean {
|
|
152
|
+
return (
|
|
153
|
+
request.method === "select" ||
|
|
154
|
+
request.method === "confirm" ||
|
|
155
|
+
request.method === "input" ||
|
|
156
|
+
request.method === "editor"
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* In-memory queue plus request-id routing. Dialog replies are kept separately
|
|
162
|
+
* from the drainable queue so a TUI may dequeue a request before answering it.
|
|
163
|
+
*/
|
|
164
|
+
export class InMemoryUIProxy implements UIProxy {
|
|
165
|
+
private readonly queue: PendingUIRequest[] = [];
|
|
166
|
+
private readonly responders = new Map<string, StoredResponse>();
|
|
167
|
+
private readonly listeners = new Set<(request: PendingUIRequest) => void>();
|
|
168
|
+
private nextId = 1;
|
|
169
|
+
|
|
170
|
+
enqueue(input: UIProxyEnqueueInput): PendingUIRequest {
|
|
171
|
+
const request: PendingUIRequest = {
|
|
172
|
+
id: `ui-${this.nextId++}`,
|
|
173
|
+
childName: input.childName,
|
|
174
|
+
rpcRequestId: input.request.id,
|
|
175
|
+
request: input.request,
|
|
176
|
+
receivedAt: Date.now(),
|
|
177
|
+
};
|
|
178
|
+
this.queue.push(request);
|
|
179
|
+
if (input.respond && isDialogRequest(input.request)) {
|
|
180
|
+
this.responders.set(request.id, {
|
|
181
|
+
childName: input.childName,
|
|
182
|
+
respond: input.respond,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
for (const listener of [...this.listeners]) {
|
|
186
|
+
try {
|
|
187
|
+
listener(request);
|
|
188
|
+
} catch {
|
|
189
|
+
// One UI adapter must not prevent delivery to another subscriber.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return request;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
pending(): readonly PendingUIRequest[] {
|
|
196
|
+
return this.queue.slice();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
take(): PendingUIRequest | undefined {
|
|
200
|
+
return this.queue.shift();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
respond(id: string, response: ExtensionUIResponse): boolean {
|
|
204
|
+
const stored = this.responders.get(id);
|
|
205
|
+
if (!stored) return false;
|
|
206
|
+
this.responders.delete(id);
|
|
207
|
+
const queuedAt = this.queue.findIndex((request) => request.id === id);
|
|
208
|
+
if (queuedAt >= 0) this.queue.splice(queuedAt, 1);
|
|
209
|
+
stored.respond(response);
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
forgetChild(childName: string): void {
|
|
214
|
+
for (let index = this.queue.length - 1; index >= 0; index -= 1) {
|
|
215
|
+
if (this.queue[index]?.childName === childName) this.queue.splice(index, 1);
|
|
216
|
+
}
|
|
217
|
+
for (const [id, stored] of this.responders) {
|
|
218
|
+
if (stored.childName === childName) this.responders.delete(id);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
onRequest(listener: (request: PendingUIRequest) => void): () => void {
|
|
223
|
+
this.listeners.add(listener);
|
|
224
|
+
return () => this.listeners.delete(listener);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AssistantMessageComponent,
|
|
3
|
+
ToolExecutionComponent,
|
|
4
|
+
UserMessageComponent,
|
|
5
|
+
getMarkdownTheme,
|
|
6
|
+
migrateSessionEntries,
|
|
7
|
+
parseSessionEntries,
|
|
8
|
+
sessionEntryToContextMessages,
|
|
9
|
+
} from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import type {
|
|
11
|
+
AssistantMessage,
|
|
12
|
+
ThinkingContent,
|
|
13
|
+
TextContent,
|
|
14
|
+
ToolResultMessage,
|
|
15
|
+
} from "@earendil-works/pi-ai";
|
|
16
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
17
|
+
import type { MarkdownTheme, TUI } from "@earendil-works/pi-tui";
|
|
18
|
+
|
|
19
|
+
export type ChatItem =
|
|
20
|
+
| { kind: "user"; component: UserMessageComponent; revoked?: boolean }
|
|
21
|
+
| { kind: "assistant"; component: AssistantMessageComponent; revoked?: boolean }
|
|
22
|
+
| { kind: "tool"; component: ToolExecutionComponent; toolCallId: string; revoked?: boolean };
|
|
23
|
+
|
|
24
|
+
export interface ChatItemSettings {
|
|
25
|
+
outputPad?: number;
|
|
26
|
+
hideThinkingBlock?: boolean;
|
|
27
|
+
codeBlockIndent?: string;
|
|
28
|
+
showImages?: boolean;
|
|
29
|
+
imageWidthCells?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ChatItemFactoryOptions {
|
|
33
|
+
tui?: TUI;
|
|
34
|
+
cwd: string;
|
|
35
|
+
settings?: ChatItemSettings;
|
|
36
|
+
markdownTheme?: MarkdownTheme;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ChatItemFactory {
|
|
40
|
+
/** All components created so far, in transcript order; revoked items preserve mount indices. */
|
|
41
|
+
readonly items: readonly ChatItem[];
|
|
42
|
+
/** Append parsed session messages. Returns the new items and whether the view changed. */
|
|
43
|
+
appendMessages(messages: readonly AgentMessage[]): {
|
|
44
|
+
added: readonly ChatItem[];
|
|
45
|
+
changed: boolean;
|
|
46
|
+
};
|
|
47
|
+
/** Create/update the one currently streaming assistant component. */
|
|
48
|
+
updateStreamingText(text: string, model?: string): AssistantMessageComponent;
|
|
49
|
+
/** Revoke the streaming assistant without finalizing it; return its accumulated text. */
|
|
50
|
+
retractStreamingItem(): string;
|
|
51
|
+
/** Mark the current streaming assistant message complete, if one exists. */
|
|
52
|
+
finishStreaming(): void;
|
|
53
|
+
/** Change every tool component's expanded state. */
|
|
54
|
+
setToolsExpanded(expanded: boolean): void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const fallbackTui = { requestRender() {} } as TUI;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Parse a session JSONL file using Pi's public session APIs. Invalid/torn JSON
|
|
61
|
+
* lines are skipped by parseSessionEntries; non-object rows and unsupported
|
|
62
|
+
* entry kinds are ignored before they can reach the message components.
|
|
63
|
+
*/
|
|
64
|
+
export function parseSessionMessages(content: string): AgentMessage[] {
|
|
65
|
+
const entries = parseSessionEntries(content).filter(isRecord) as ReturnType<typeof parseSessionEntries>;
|
|
66
|
+
try {
|
|
67
|
+
migrateSessionEntries(entries);
|
|
68
|
+
} catch {
|
|
69
|
+
// A damaged legacy record must not prevent valid messages around it from rendering.
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const messages: AgentMessage[] = [];
|
|
73
|
+
for (const entry of entries) {
|
|
74
|
+
if (!entry || typeof entry !== "object" || entry.type !== "message") continue;
|
|
75
|
+
try {
|
|
76
|
+
messages.push(...sessionEntryToContextMessages(entry).map(sanitizeMessageContent));
|
|
77
|
+
} catch {
|
|
78
|
+
// Session JSONL is external input; skip a malformed row and keep going.
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return messages;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Create persistent message-to-component state for one viewer instance. */
|
|
85
|
+
export function createChatItemFactory(options: ChatItemFactoryOptions): ChatItemFactory {
|
|
86
|
+
const settings = options.settings ?? {};
|
|
87
|
+
const outputPad = settings.outputPad ?? 1;
|
|
88
|
+
const hideThinkingBlock = settings.hideThinkingBlock ?? false;
|
|
89
|
+
const baseMarkdownTheme = options.markdownTheme ?? getMarkdownTheme();
|
|
90
|
+
const markdownTheme = settings.codeBlockIndent === undefined
|
|
91
|
+
? baseMarkdownTheme
|
|
92
|
+
: { ...baseMarkdownTheme, codeBlockIndent: settings.codeBlockIndent };
|
|
93
|
+
const tui = options.tui ?? fallbackTui;
|
|
94
|
+
const items: ChatItem[] = [];
|
|
95
|
+
const toolsByCallId = new Map<string, ToolExecutionComponent>();
|
|
96
|
+
const pendingResults = new Map<string, ToolResultMessage>();
|
|
97
|
+
let anonymousToolId = 0;
|
|
98
|
+
let streamingComponent: AssistantMessageComponent | undefined;
|
|
99
|
+
let streamingItem: Extract<ChatItem, { kind: "assistant" }> | undefined;
|
|
100
|
+
let streamingText = "";
|
|
101
|
+
|
|
102
|
+
const addToolCall = (
|
|
103
|
+
name: string,
|
|
104
|
+
toolCallId: string,
|
|
105
|
+
args: unknown,
|
|
106
|
+
): ToolExecutionComponent => {
|
|
107
|
+
const component = new ToolExecutionComponent(
|
|
108
|
+
name,
|
|
109
|
+
toolCallId,
|
|
110
|
+
args,
|
|
111
|
+
{
|
|
112
|
+
showImages: settings.showImages,
|
|
113
|
+
imageWidthCells: settings.imageWidthCells,
|
|
114
|
+
outputPad,
|
|
115
|
+
},
|
|
116
|
+
undefined,
|
|
117
|
+
tui,
|
|
118
|
+
options.cwd,
|
|
119
|
+
);
|
|
120
|
+
component.setExpanded(false);
|
|
121
|
+
items.push({ kind: "tool", component, toolCallId });
|
|
122
|
+
toolsByCallId.set(toolCallId, component);
|
|
123
|
+
const pending = pendingResults.get(toolCallId);
|
|
124
|
+
if (pending) {
|
|
125
|
+
component.updateResult({
|
|
126
|
+
content: pending.content,
|
|
127
|
+
details: pending.details,
|
|
128
|
+
isError: pending.isError,
|
|
129
|
+
durationMs: pending.durationMs,
|
|
130
|
+
});
|
|
131
|
+
pendingResults.delete(toolCallId);
|
|
132
|
+
}
|
|
133
|
+
return component;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const appendMessages = (messages: readonly AgentMessage[]) => {
|
|
137
|
+
const start = items.length;
|
|
138
|
+
let changed = false;
|
|
139
|
+
for (const message of messages) {
|
|
140
|
+
if (!message || typeof message !== "object") continue;
|
|
141
|
+
switch (message.role) {
|
|
142
|
+
case "user": {
|
|
143
|
+
const text = userMessageText(message.content);
|
|
144
|
+
if (!text) break;
|
|
145
|
+
items.push({
|
|
146
|
+
kind: "user",
|
|
147
|
+
component: new UserMessageComponent(text, markdownTheme, outputPad),
|
|
148
|
+
});
|
|
149
|
+
changed = true;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
case "assistant": {
|
|
153
|
+
const content = Array.isArray(message.content)
|
|
154
|
+
? message.content.filter(isTextOrThinking)
|
|
155
|
+
: [];
|
|
156
|
+
const hasToolCall = Array.isArray(message.content) &&
|
|
157
|
+
message.content.some((part) => part?.type === "toolCall");
|
|
158
|
+
if (content.length === 0 && !hasToolCall) break;
|
|
159
|
+
const renderableMessage: AssistantMessage = { ...message, content };
|
|
160
|
+
items.push({
|
|
161
|
+
kind: "assistant",
|
|
162
|
+
component: new AssistantMessageComponent(
|
|
163
|
+
renderableMessage,
|
|
164
|
+
hideThinkingBlock,
|
|
165
|
+
markdownTheme,
|
|
166
|
+
"Thinking...",
|
|
167
|
+
outputPad,
|
|
168
|
+
),
|
|
169
|
+
});
|
|
170
|
+
changed = true;
|
|
171
|
+
if (!Array.isArray(message.content)) break;
|
|
172
|
+
for (const part of message.content) {
|
|
173
|
+
if (!part || part.type !== "toolCall") continue;
|
|
174
|
+
const toolCallId = typeof part.id === "string" && part.id.length > 0
|
|
175
|
+
? part.id
|
|
176
|
+
: `legion-tool-${anonymousToolId++}`;
|
|
177
|
+
const tool = addToolCall(
|
|
178
|
+
typeof part.name === "string" && part.name.length > 0 ? part.name : "tool",
|
|
179
|
+
toolCallId,
|
|
180
|
+
part.arguments ?? {},
|
|
181
|
+
);
|
|
182
|
+
if (message.stopReason === "aborted" || message.stopReason === "error") {
|
|
183
|
+
const errorText = message.stopReason === "aborted"
|
|
184
|
+
? "Operation aborted"
|
|
185
|
+
: message.errorMessage || "Error";
|
|
186
|
+
tool.updateResult({
|
|
187
|
+
content: [{ type: "text", text: errorText }],
|
|
188
|
+
isError: true,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case "toolResult": {
|
|
195
|
+
const result = message as ToolResultMessage;
|
|
196
|
+
if (typeof result.toolCallId !== "string" || !Array.isArray(result.content)) break;
|
|
197
|
+
const safeResult = {
|
|
198
|
+
...result,
|
|
199
|
+
content: filterObjectContentParts(result.content),
|
|
200
|
+
};
|
|
201
|
+
const component = toolsByCallId.get(safeResult.toolCallId);
|
|
202
|
+
if (component) {
|
|
203
|
+
component.updateResult({
|
|
204
|
+
content: safeResult.content,
|
|
205
|
+
details: safeResult.details,
|
|
206
|
+
isError: safeResult.isError,
|
|
207
|
+
durationMs: safeResult.durationMs,
|
|
208
|
+
});
|
|
209
|
+
changed = true;
|
|
210
|
+
} else {
|
|
211
|
+
pendingResults.set(safeResult.toolCallId, safeResult);
|
|
212
|
+
}
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
default:
|
|
216
|
+
// system/custom/other message roles do not belong in the viewer.
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return { added: items.slice(start), changed };
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
const makeStreamingMessage = (text: string, model?: string): AssistantMessage => ({
|
|
224
|
+
role: "assistant",
|
|
225
|
+
content: text ? [{ type: "text", text }] : [],
|
|
226
|
+
api: "openai-completions",
|
|
227
|
+
provider: "openai",
|
|
228
|
+
model: model || "unknown",
|
|
229
|
+
usage: {
|
|
230
|
+
input: 0,
|
|
231
|
+
output: 0,
|
|
232
|
+
cacheRead: 0,
|
|
233
|
+
cacheWrite: 0,
|
|
234
|
+
totalTokens: 0,
|
|
235
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
236
|
+
},
|
|
237
|
+
stopReason: "pending",
|
|
238
|
+
timestamp: Date.now(),
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
get items() {
|
|
243
|
+
return items;
|
|
244
|
+
},
|
|
245
|
+
appendMessages,
|
|
246
|
+
updateStreamingText(text, model) {
|
|
247
|
+
if (!streamingComponent) {
|
|
248
|
+
streamingComponent = new AssistantMessageComponent(
|
|
249
|
+
undefined,
|
|
250
|
+
hideThinkingBlock,
|
|
251
|
+
markdownTheme,
|
|
252
|
+
"Thinking...",
|
|
253
|
+
outputPad,
|
|
254
|
+
);
|
|
255
|
+
streamingItem = { kind: "assistant", component: streamingComponent };
|
|
256
|
+
items.push(streamingItem);
|
|
257
|
+
}
|
|
258
|
+
streamingText = text;
|
|
259
|
+
streamingComponent.updateContent(makeStreamingMessage(streamingText, model), true);
|
|
260
|
+
return streamingComponent;
|
|
261
|
+
},
|
|
262
|
+
retractStreamingItem() {
|
|
263
|
+
if (!streamingComponent) return "";
|
|
264
|
+
const text = streamingText;
|
|
265
|
+
if (streamingItem) streamingItem.revoked = true;
|
|
266
|
+
streamingComponent = undefined;
|
|
267
|
+
streamingItem = undefined;
|
|
268
|
+
streamingText = "";
|
|
269
|
+
return text;
|
|
270
|
+
},
|
|
271
|
+
finishStreaming() {
|
|
272
|
+
if (!streamingComponent) return;
|
|
273
|
+
streamingComponent.updateContent(makeStreamingMessage(streamingText), false);
|
|
274
|
+
streamingComponent = undefined;
|
|
275
|
+
streamingItem = undefined;
|
|
276
|
+
streamingText = "";
|
|
277
|
+
},
|
|
278
|
+
setToolsExpanded(expanded) {
|
|
279
|
+
for (const item of items) {
|
|
280
|
+
if (item.kind === "tool") item.component.setExpanded(expanded);
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function sanitizeMessageContent(message: AgentMessage): AgentMessage {
|
|
287
|
+
switch (message.role) {
|
|
288
|
+
case "user":
|
|
289
|
+
return Array.isArray(message.content)
|
|
290
|
+
? { ...message, content: filterObjectContentParts(message.content) }
|
|
291
|
+
: message;
|
|
292
|
+
case "assistant":
|
|
293
|
+
return Array.isArray(message.content)
|
|
294
|
+
? { ...message, content: filterObjectContentParts(message.content) }
|
|
295
|
+
: message;
|
|
296
|
+
case "toolResult":
|
|
297
|
+
return Array.isArray(message.content)
|
|
298
|
+
? { ...message, content: filterObjectContentParts(message.content) }
|
|
299
|
+
: message;
|
|
300
|
+
default:
|
|
301
|
+
return message;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function filterObjectContentParts<T>(content: readonly T[]): T[] {
|
|
306
|
+
return content.filter((part) =>
|
|
307
|
+
part !== null && typeof part === "object" && !Array.isArray(part),
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function userMessageText(content: unknown): string {
|
|
312
|
+
if (typeof content === "string") return content;
|
|
313
|
+
if (!Array.isArray(content)) return "";
|
|
314
|
+
return content
|
|
315
|
+
.filter((part): part is TextContent =>
|
|
316
|
+
Boolean(part && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string"),
|
|
317
|
+
)
|
|
318
|
+
.map((part) => part.text)
|
|
319
|
+
.join("");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function isTextOrThinking(
|
|
323
|
+
part: AssistantMessage["content"][number],
|
|
324
|
+
): part is TextContent | ThinkingContent {
|
|
325
|
+
return Boolean(part && typeof part === "object" && (part.type === "text" || part.type === "thinking"));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
329
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
330
|
+
}
|