@mrclrchtr/supi-review 7.3.0 → 7.4.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.
Files changed (58) hide show
  1. package/README.md +4 -0
  2. package/node_modules/@mrclrchtr/supi-agent-runtime/README.md +10 -0
  3. package/node_modules/@mrclrchtr/supi-agent-runtime/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-agent-runtime/package.json +7 -3
  5. package/node_modules/@mrclrchtr/supi-agent-runtime/src/api.ts +37 -1
  6. package/node_modules/@mrclrchtr/supi-agent-runtime/src/run.ts +151 -21
  7. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/agent-run-registry-types.ts +95 -0
  8. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/agent-run-registry.ts +372 -0
  9. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/transcript-format.ts +184 -0
  10. package/node_modules/@mrclrchtr/supi-agent-runtime/src/session/transcript-store.ts +284 -0
  11. package/node_modules/@mrclrchtr/supi-agent-runtime/src/types.ts +22 -0
  12. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-command.ts +206 -0
  13. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-overlay-data.ts +78 -0
  14. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-overlay-render.ts +167 -0
  15. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-overlay.ts +400 -0
  16. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-list.ts +95 -0
  17. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-switcher.ts +29 -0
  18. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewer-input.ts +69 -0
  19. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewer-render.ts +246 -0
  20. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewer.ts +400 -0
  21. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-run-viewport.ts +112 -0
  22. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-steering-input.ts +50 -0
  23. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript-context.ts +56 -0
  24. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript-pane.ts +386 -0
  25. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript-payload.ts +66 -0
  26. package/node_modules/@mrclrchtr/supi-agent-runtime/src/ui/agents-transcript.ts +380 -0
  27. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  28. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  29. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  30. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  31. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/ignore/index.js +25 -6
  32. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/ignore/legacy.js +22 -6
  33. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/ignore/package.json +1 -1
  34. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/common/connection.js +2 -2
  35. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.d.ts +1 -0
  36. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/lib/node/main.js +7 -0
  37. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-jsonrpc/package.json +2 -2
  38. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.d.ts +2 -2
  39. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.d.ts +2 -2
  40. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.d.ts +2 -2
  41. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-protocol/package.json +4 -4
  42. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/node_modules/vscode-languageserver-types/package.json +2 -2
  43. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  44. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  45. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  46. package/node_modules/@mrclrchtr/supi-code-intelligence/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  47. package/node_modules/@mrclrchtr/supi-code-intelligence/package.json +5 -5
  48. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  49. package/package.json +4 -4
  50. package/src/review.ts +5 -2
  51. package/src/tool/review_run/child-session.ts +29 -7
  52. package/src/tool/review_run/execute.ts +6 -1
  53. package/src/tool/review_run/execution.ts +6 -0
  54. package/src/tool/review_run/register.ts +3 -1
  55. package/src/tool/review_run/runner.ts +40 -0
  56. package/src/tool/review_run/workflow.ts +7 -1
  57. package/src/tui/review-command.ts +74 -3
  58. package/src/types.ts +5 -0
@@ -0,0 +1,284 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { appendFile, mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
6
+ import type { AgentRunMessage, AgentRunToolRenderer } from "../types.ts";
7
+ import type { TranscriptRecord } from "./transcript-format.ts";
8
+ import { parseTranscript, projectOperation, sanitizeMessage } from "./transcript-format.ts";
9
+
10
+ export type AgentRunTranscriptStatus = "capturing" | "complete" | "incomplete";
11
+
12
+ export interface AgentRunTranscriptMetadata {
13
+ readonly runKey: string;
14
+ readonly batchId: string;
15
+ readonly taskId: string;
16
+ readonly kind: string;
17
+ readonly label: string;
18
+ readonly cwd: string;
19
+ readonly modelId: string;
20
+ readonly thinkingLevel: string;
21
+ readonly tools: readonly string[];
22
+ readonly taskDescription?: string;
23
+ readonly sharedContext?: string;
24
+ readonly startedAt: number;
25
+ }
26
+
27
+ export interface AgentRunTranscriptOperation {
28
+ readonly type: string;
29
+ readonly occurredAt: number;
30
+ readonly [key: string]: unknown;
31
+ }
32
+
33
+ export interface AgentRunTranscriptDocument {
34
+ readonly metadata: AgentRunTranscriptMetadata;
35
+ readonly systemPrompt: string;
36
+ readonly systemPromptHistory: readonly { readonly occurredAt: number; readonly text: string }[];
37
+ readonly messages: readonly AgentRunMessage[];
38
+ readonly operations: readonly AgentRunTranscriptOperation[];
39
+ readonly status: AgentRunTranscriptStatus;
40
+ readonly messageCount: number;
41
+ }
42
+
43
+ export interface AgentRunTranscriptStatusSnapshot {
44
+ readonly status: AgentRunTranscriptStatus;
45
+ readonly revision: number;
46
+ readonly messageCount: number;
47
+ }
48
+
49
+ /** A temporary, human-only transcript source for one Agent Run. */
50
+ export interface AgentRunTranscriptSource {
51
+ readonly runKey: string;
52
+ readonly toolRenderers: readonly AgentRunToolRenderer[];
53
+ getStatus(): AgentRunTranscriptStatusSnapshot;
54
+ load(): Promise<AgentRunTranscriptDocument>;
55
+ }
56
+
57
+ /** Owns all temporary transcript files for one parent session. */
58
+ export class AgentRunTranscriptStore {
59
+ #directoryPromise: Promise<string> | undefined;
60
+ #captures = new Set<AgentRunTranscriptCapture>();
61
+
62
+ /** Start one temporary transcript capture. A storage error does not fail the Agent Run. */
63
+ createCapture(
64
+ metadata: AgentRunTranscriptMetadata,
65
+ systemPrompt: string,
66
+ toolRenderers: readonly AgentRunToolRenderer[],
67
+ onChange?: () => void,
68
+ ): AgentRunTranscriptCapture {
69
+ const capture = new AgentRunTranscriptCapture({
70
+ metadata,
71
+ systemPrompt,
72
+ toolRenderers,
73
+ getDirectory: () => this.#getDirectory(),
74
+ onChange,
75
+ });
76
+ this.#captures.add(capture);
77
+ return capture;
78
+ }
79
+
80
+ /** Remove the session's temporary transcript files. */
81
+ async dispose(): Promise<void> {
82
+ await Promise.all([...this.#captures].map((capture) => capture.finish()));
83
+ const directoryPromise = this.#directoryPromise;
84
+ this.#captures.clear();
85
+ if (!directoryPromise) return;
86
+ const directory = await directoryPromise.catch(() => undefined);
87
+ if (directory) await rm(directory, { recursive: true, force: true }).catch(() => undefined);
88
+ this.#directoryPromise = undefined;
89
+ }
90
+
91
+ #getDirectory(): Promise<string> {
92
+ this.#directoryPromise ??= mkdtemp(join(tmpdir(), "supi-agent-transcripts-"));
93
+ return this.#directoryPromise;
94
+ }
95
+ }
96
+
97
+ /** Captures finalized session messages and safe lifecycle metadata to one JSONL file. */
98
+ export class AgentRunTranscriptCapture implements AgentRunTranscriptSource {
99
+ #status: AgentRunTranscriptStatus = "capturing";
100
+ #revision = 0;
101
+ #messageCount = 0;
102
+ #initialSystemPrompt: string;
103
+ #systemPrompt: string;
104
+ #systemPromptHistory: Array<{ occurredAt: number; text: string }>;
105
+ #toolRenderers: AgentRunToolRenderer[];
106
+ #filePath: string | undefined;
107
+ #writeQueue: Promise<void>;
108
+ #finishPromise: Promise<void> | undefined;
109
+ readonly metadata: AgentRunTranscriptMetadata;
110
+ private readonly onChange?: () => void;
111
+
112
+ constructor(options: {
113
+ metadata: AgentRunTranscriptMetadata;
114
+ systemPrompt: string;
115
+ toolRenderers: readonly AgentRunToolRenderer[];
116
+ getDirectory: () => Promise<string>;
117
+ onChange?: () => void;
118
+ }) {
119
+ const { metadata, systemPrompt, toolRenderers, getDirectory, onChange } = options;
120
+ this.metadata = metadata;
121
+ this.onChange = onChange;
122
+ this.#initialSystemPrompt = systemPrompt;
123
+ this.#systemPrompt = systemPrompt;
124
+ this.#systemPromptHistory = [{ occurredAt: Date.now(), text: systemPrompt }];
125
+ this.#toolRenderers = toolRenderers.map(copyToolRenderer);
126
+ this.#writeQueue = this.#createFile(getDirectory);
127
+ }
128
+
129
+ get runKey(): string {
130
+ return this.metadata.runKey;
131
+ }
132
+
133
+ get toolRenderers(): readonly AgentRunToolRenderer[] {
134
+ return Object.freeze([...this.#toolRenderers]);
135
+ }
136
+
137
+ getStatus(): AgentRunTranscriptStatusSnapshot {
138
+ return Object.freeze({
139
+ status: this.#status,
140
+ revision: this.#revision,
141
+ messageCount: this.#messageCount,
142
+ });
143
+ }
144
+
145
+ /** Update the effective prompt and render-only tool definitions. */
146
+ updateSession(systemPrompt: string, toolRenderers: readonly AgentRunToolRenderer[]): void {
147
+ if (this.#status !== "capturing") return;
148
+ this.#updateToolRenderers(toolRenderers);
149
+ if (systemPrompt === this.#systemPrompt) return;
150
+ this.#systemPrompt = systemPrompt;
151
+ const occurredAt = Date.now();
152
+ this.#systemPromptHistory.push({ occurredAt, text: systemPrompt });
153
+ void this.#enqueue({ kind: "system-prompt", text: systemPrompt, occurredAt });
154
+ }
155
+
156
+ /** Record finalized messages and allowlisted lifecycle details only. */
157
+ observe(
158
+ event: AgentSessionEvent,
159
+ systemPrompt: string,
160
+ toolRenderers: readonly AgentRunToolRenderer[],
161
+ ): void {
162
+ if (this.#status !== "capturing") return;
163
+ this.updateSession(systemPrompt, toolRenderers);
164
+ if (event.type === "message_end") {
165
+ void this.#enqueue({ kind: "message", message: sanitizeMessage(event.message) });
166
+ }
167
+ const operation = projectOperation(event);
168
+ if (operation) void this.#enqueue({ kind: "operation", operation });
169
+ }
170
+
171
+ /** Mark the capture complete after the run settles and wait for queued writes. */
172
+ finish(): Promise<void> {
173
+ if (this.#finishPromise !== undefined) return this.#finishPromise;
174
+ if (this.#status !== "capturing") return Promise.resolve();
175
+ this.#finishPromise = (async () => {
176
+ await this.#enqueue({ kind: "status", status: "complete" });
177
+ await this.#writeQueue;
178
+ if (this.#status === "capturing") {
179
+ this.#status = "complete";
180
+ this.#revision++;
181
+ this.onChange?.();
182
+ }
183
+ })();
184
+ return this.#finishPromise;
185
+ }
186
+
187
+ /** Read the full transcript from temporary storage. */
188
+ load(): Promise<AgentRunTranscriptDocument> {
189
+ const read = this.#writeQueue.then(async () => {
190
+ const filePath = this.#filePath;
191
+ if (!filePath) return this.#document([], [], "incomplete");
192
+ try {
193
+ const content = await readFile(filePath, "utf8");
194
+ const document = parseTranscript(content, this.#document([], [], this.#status));
195
+ if (document.status === "incomplete") this.#markIncomplete();
196
+ return document;
197
+ } catch {
198
+ this.#markIncomplete();
199
+ return this.#document([], [], "incomplete");
200
+ }
201
+ });
202
+ this.#writeQueue = read.then(
203
+ () => undefined,
204
+ () => this.#markIncomplete(),
205
+ );
206
+ return read;
207
+ }
208
+
209
+ async #createFile(getDirectory: () => Promise<string>): Promise<void> {
210
+ try {
211
+ const directory = await getDirectory();
212
+ this.#filePath = join(directory, `${randomUUID()}.jsonl`);
213
+ await appendFile(
214
+ this.#filePath,
215
+ `${JSON.stringify({
216
+ kind: "header",
217
+ metadata: this.metadata,
218
+ systemPrompt: this.#initialSystemPrompt,
219
+ occurredAt: this.#systemPromptHistory[0]?.occurredAt ?? Date.now(),
220
+ })}\n`,
221
+ "utf8",
222
+ );
223
+ this.#revision++;
224
+ } catch {
225
+ this.#markIncomplete();
226
+ }
227
+ }
228
+
229
+ #enqueue(record: TranscriptRecord): Promise<void> {
230
+ this.#revision++;
231
+ this.#writeQueue = this.#writeQueue
232
+ .then(async () => {
233
+ if (this.#status === "incomplete" || !this.#filePath) return;
234
+ await appendFile(this.#filePath, `${JSON.stringify(record)}\n`, "utf8");
235
+ if (record.kind === "message") this.#messageCount++;
236
+ this.onChange?.();
237
+ })
238
+ .catch(() => this.#markIncomplete());
239
+ return this.#writeQueue;
240
+ }
241
+
242
+ #updateToolRenderers(toolRenderers: readonly AgentRunToolRenderer[]): void {
243
+ for (const value of toolRenderers) {
244
+ const renderer = copyToolRenderer(value);
245
+ const index = this.#toolRenderers.findIndex((entry) => entry.name === renderer.name);
246
+ if (index < 0) this.#toolRenderers.push(renderer);
247
+ else this.#toolRenderers[index] = renderer;
248
+ }
249
+ }
250
+
251
+ #markIncomplete(): void {
252
+ if (this.#status === "incomplete") return;
253
+ this.#status = "incomplete";
254
+ this.#revision++;
255
+ this.onChange?.();
256
+ }
257
+
258
+ #document(
259
+ messages: readonly AgentRunMessage[],
260
+ operations: readonly AgentRunTranscriptOperation[],
261
+ status: AgentRunTranscriptStatus,
262
+ systemPromptHistory: readonly { readonly occurredAt: number; readonly text: string }[] = this
263
+ .#systemPromptHistory,
264
+ ): AgentRunTranscriptDocument {
265
+ return {
266
+ metadata: this.metadata,
267
+ systemPrompt: this.#systemPrompt,
268
+ systemPromptHistory,
269
+ messages,
270
+ operations,
271
+ status,
272
+ messageCount: messages.length,
273
+ };
274
+ }
275
+ }
276
+
277
+ function copyToolRenderer(renderer: AgentRunToolRenderer): AgentRunToolRenderer {
278
+ return Object.freeze({
279
+ name: renderer.name,
280
+ ...(renderer.renderCall ? { renderCall: renderer.renderCall } : {}),
281
+ ...(renderer.renderResult ? { renderResult: renderer.renderResult } : {}),
282
+ ...(renderer.renderShell ? { renderShell: renderer.renderShell } : {}),
283
+ });
284
+ }
@@ -7,6 +7,8 @@ import type {
7
7
  ToolDefinition,
8
8
  } from "@earendil-works/pi-coding-agent";
9
9
  import type { AgentRunProviderAuthority } from "./provider-authority.ts";
10
+ import type { AgentRunRegistry } from "./session/agent-run-registry.ts";
11
+ import type { AgentRunRegistration } from "./session/agent-run-registry-types.ts";
10
12
 
11
13
  /** The host-owned failure stages of one Agent Run. */
12
14
  export type AgentRunFailureCode =
@@ -288,6 +290,8 @@ export interface StartAgentRunOptions<T> {
288
290
 
289
291
  /** Sole public control interface for one Agent Run. */
290
292
  export interface AgentRunHandle<T> {
293
+ /** True only while the initial user prompt accepts steering. */
294
+ readonly steeringAvailable: boolean;
291
295
  /** Terminal outcome, including all usage attributable to the owned Agent Run session. */
292
296
  readonly result: Promise<AgentRunOutcome<T>>;
293
297
  /** Subscribe to immutable progress snapshots; the current snapshot is immediate. */
@@ -297,3 +301,21 @@ export interface AgentRunHandle<T> {
297
301
  /** Stop the run; repeated calls share the same terminal cleanup. */
298
302
  stop(): Promise<void>;
299
303
  }
304
+
305
+ /** Options for `startRegisteredAgentRun()`. */
306
+ export interface StartRegisteredAgentRunOptions<T> extends StartAgentRunOptions<T> {
307
+ /** Optional containing-session registry. */
308
+ readonly registry?: AgentRunRegistry;
309
+ /** Viewer metadata and caller-owned conversation/activity views. */
310
+ readonly registration: Pick<
311
+ AgentRunRegistration,
312
+ "metadata" | "getConversation" | "getRecentActivity"
313
+ >;
314
+ /** System prompt to store before the child session starts. */
315
+ readonly transcriptSystemPrompt?: string;
316
+ }
317
+
318
+ /** Handle returned by `startRegisteredAgentRun()`, with its stable run key. */
319
+ export interface RegisteredAgentRunHandle<T> extends AgentRunHandle<T> {
320
+ readonly runKey: string;
321
+ }
@@ -0,0 +1,206 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
+ import { AgentRunRegistry } from "../session/agent-run-registry.ts";
4
+ import type { AgentRunRegistrySnapshot } from "../session/agent-run-registry-types.ts";
5
+ import type {
6
+ AgentsOverlayData,
7
+ AgentsOverlayRun,
8
+ AgentsProfilePages,
9
+ } from "./agents-overlay-data.ts";
10
+
11
+ interface SharedProcessState {
12
+ readonly runtimes: Map<string, SharedRuntimeState>;
13
+ }
14
+
15
+ interface SharedRuntimeState {
16
+ readonly id: string;
17
+ readonly registry: AgentRunRegistry;
18
+ commandRegistered: boolean;
19
+ removeDiscoveryListener?: () => void;
20
+ profilePages?: { readonly owner: object; readonly provider: AgentsProfilePages };
21
+ }
22
+
23
+ const sharedStateKey = Symbol.for("@mrclrchtr/supi-agent-runtime/agents-viewer");
24
+ const discoverChannel = "supi:agent-runtime:agents-viewer:discover";
25
+ const responseChannel = "supi:agent-runtime:agents-viewer:response";
26
+
27
+ function sharedProcessState(): SharedProcessState {
28
+ const global = globalThis as unknown as Record<symbol, unknown>;
29
+ const existing = global[sharedStateKey] as SharedProcessState | undefined;
30
+ if (existing) return existing;
31
+ const created: SharedProcessState = { runtimes: new Map() };
32
+ global[sharedStateKey] = created;
33
+ return created;
34
+ }
35
+
36
+ /** Find the shared state for the Pi runtime that owns this extension API. */
37
+ function runtimeState(pi: ExtensionAPI): SharedRuntimeState {
38
+ const processState = sharedProcessState();
39
+ const discovered = findRuntimeState(pi);
40
+ if (discovered) return discovered;
41
+
42
+ const state: SharedRuntimeState = {
43
+ id: randomUUID(),
44
+ registry: new AgentRunRegistry(),
45
+ commandRegistered: false,
46
+ };
47
+ processState.runtimes.set(state.id, state);
48
+ state.removeDiscoveryListener = pi.events.on(discoverChannel, (data) => {
49
+ if (!isRequest(data)) return;
50
+ pi.events.emit(responseChannel, { requestId: data.requestId, runtimeId: state.id });
51
+ });
52
+ pi.on("session_start", () => state.registry.openSession());
53
+ pi.on("session_shutdown", async () => {
54
+ state.profilePages = undefined;
55
+ await state.registry.clear();
56
+ state.removeDiscoveryListener?.();
57
+ state.removeDiscoveryListener = undefined;
58
+ processState.runtimes.delete(state.id);
59
+ });
60
+ return state;
61
+ }
62
+
63
+ function isRequest(data: unknown): data is { requestId: string } {
64
+ return (
65
+ typeof data === "object" &&
66
+ data !== null &&
67
+ "requestId" in data &&
68
+ typeof data.requestId === "string"
69
+ );
70
+ }
71
+
72
+ function isResponse(data: unknown): data is { requestId: string; runtimeId: string } {
73
+ return isRequest(data) && "runtimeId" in data && typeof data.runtimeId === "string";
74
+ }
75
+
76
+ /** Return the Agent Run registry for the containing Pi runtime. */
77
+ export function getAgentRunRegistry(pi: ExtensionAPI): AgentRunRegistry {
78
+ return runtimeState(pi).registry;
79
+ }
80
+
81
+ /** Optional Agent-owned data for the Profiles and Profile Diagnostics pages. */
82
+ export interface RegisterAgentsCommandOptions {
83
+ readonly profilePages?: AgentsProfilePages;
84
+ }
85
+
86
+ /** Register `/agents` once for a Pi runtime and return its shared run registry. */
87
+ export function registerAgentsCommand(
88
+ pi: ExtensionAPI,
89
+ options: RegisterAgentsCommandOptions = {},
90
+ ): AgentRunRegistry {
91
+ const state = runtimeState(pi);
92
+ if (options.profilePages) state.profilePages = { owner: pi, provider: options.profilePages };
93
+ if (state.commandRegistered) return state.registry;
94
+
95
+ pi.registerCommand("agents", {
96
+ description: "Inspect managed runs and, when available, Agent Profiles",
97
+ handler: async (_args, ctx) => showAgentsViewer(pi, state, ctx),
98
+ });
99
+ state.commandRegistered = true;
100
+ return state.registry;
101
+ }
102
+
103
+ /** Open the shared `/agents` viewer from another interactive extension flow. */
104
+ export function openAgentsViewer(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
105
+ return showAgentsViewer(pi, runtimeState(pi), ctx);
106
+ }
107
+
108
+ async function showAgentsViewer(
109
+ pi: ExtensionAPI,
110
+ state: SharedRuntimeState,
111
+ ctx: ExtensionCommandContext,
112
+ ): Promise<void> {
113
+ if (ctx.mode !== "tui") {
114
+ ctx.ui.notify("/agents is available only in TUI mode.", "warning");
115
+ return;
116
+ }
117
+ const [{ Key, matchesKey }, { AgentsDialog }] = await Promise.all([
118
+ import("@earendil-works/pi-tui"),
119
+ import("./agents-overlay.ts"),
120
+ ]);
121
+ let closeOverlay: (() => void) | undefined;
122
+ let askUserActive = false;
123
+ const removeAskUserStart = pi.events.on("supi:ask-user:start", () => {
124
+ askUserActive = true;
125
+ });
126
+ const removeAskUserEnd = pi.events.on("supi:ask-user:end", () => {
127
+ askUserActive = false;
128
+ });
129
+ const removeAskUserInput = ctx.ui.onTerminalInput?.((data) => {
130
+ if (!askUserActive || !closeOverlay || !matchesKey(data, Key.escape)) return;
131
+ closeOverlay();
132
+ return { consume: true };
133
+ });
134
+ try {
135
+ await ctx.ui.custom<void>(
136
+ (tui, theme, keybindings, done) => {
137
+ closeOverlay = () => done(undefined);
138
+ return new AgentsDialog(
139
+ buildOverlayData(state.registry.snapshot(), profilePagesFor(state)),
140
+ {
141
+ theme,
142
+ tui,
143
+ keybindings,
144
+ done: () => done(undefined),
145
+ onSteer: (runKey, message) => state.registry.steer(runKey, message),
146
+ onStop: (runKey) => state.registry.stop(runKey),
147
+ subscribe: (listener) =>
148
+ state.registry.subscribe((snapshot) =>
149
+ listener(buildOverlayData(snapshot, profilePagesFor(state))),
150
+ ),
151
+ },
152
+ );
153
+ },
154
+ {
155
+ overlay: true,
156
+ overlayOptions: {
157
+ anchor: "top-left",
158
+ width: "100%",
159
+ maxHeight: "100%",
160
+ margin: 0,
161
+ },
162
+ },
163
+ );
164
+ } finally {
165
+ removeAskUserInput?.();
166
+ removeAskUserStart();
167
+ removeAskUserEnd();
168
+ }
169
+ }
170
+
171
+ /** Remove the Agent-owned Profile pages when their provider extension shuts down. */
172
+ export function clearAgentsProfilePages(pi: ExtensionAPI): void {
173
+ const state = findRuntimeState(pi);
174
+ if (state?.profilePages?.owner === pi) state.profilePages = undefined;
175
+ }
176
+
177
+ function findRuntimeState(pi: ExtensionAPI): SharedRuntimeState | undefined {
178
+ const processState = sharedProcessState();
179
+ const requestId = randomUUID();
180
+ let discoveredId: string | undefined;
181
+ const removeResponseListener = pi.events.on(responseChannel, (data) => {
182
+ if (!isResponse(data) || data.requestId !== requestId) return;
183
+ discoveredId = data.runtimeId;
184
+ });
185
+ pi.events.emit(discoverChannel, { requestId });
186
+ removeResponseListener();
187
+ return discoveredId ? processState.runtimes.get(discoveredId) : undefined;
188
+ }
189
+
190
+ function profilePagesFor(state: SharedRuntimeState) {
191
+ return state.profilePages?.provider.getData();
192
+ }
193
+
194
+ function buildOverlayData(
195
+ snapshot: AgentRunRegistrySnapshot,
196
+ profilePages: AgentsOverlayData["profilePages"],
197
+ ): AgentsOverlayData {
198
+ const runs: AgentsOverlayRun[] = snapshot.runs.map((run) => ({
199
+ ...run,
200
+ key: `run:${run.runKey}`,
201
+ }));
202
+ return {
203
+ runs,
204
+ ...(profilePages ? { profilePages } : {}),
205
+ };
206
+ }
@@ -0,0 +1,78 @@
1
+ import type { ModelThinkingLevel, Usage } from "@earendil-works/pi-ai";
2
+ import type { KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
3
+ import type {
4
+ AgentRunDisplayConversation,
5
+ AgentRunRegistryRun,
6
+ } from "../session/agent-run-registry-types.ts";
7
+ import type { AgentRunTranscriptSource } from "../session/transcript-store.ts";
8
+
9
+ /** Shared height limit for the PI overlay and its rendered viewport. */
10
+ export const AGENTS_OVERLAY_MAX_HEIGHT_PERCENT = 100;
11
+
12
+ /** One Profile shown by the optional Agent Profiles pages. */
13
+ export interface AgentsProfilePageEntry {
14
+ readonly id: string;
15
+ readonly description: string;
16
+ readonly source?: string;
17
+ readonly directory?: string;
18
+ readonly model?: string;
19
+ readonly thinking?: string;
20
+ readonly timeoutMinutes?: number;
21
+ readonly tools?: readonly string[];
22
+ readonly systemPrompt?: string;
23
+ readonly instructionScopes?: readonly string[];
24
+ readonly fieldSources?: Readonly<Record<string, string>>;
25
+ readonly unavailable?: string;
26
+ }
27
+
28
+ /** One bounded diagnostic shown by the optional Agent Profile Diagnostics page. */
29
+ export interface AgentsProfileDiagnostic {
30
+ readonly profileId: string;
31
+ readonly source: string;
32
+ readonly code: string;
33
+ readonly message: string;
34
+ readonly directory?: string;
35
+ }
36
+
37
+ /** Optional Agent-owned data for the two Agent Profile pages. */
38
+ export interface AgentsProfilePagesData {
39
+ readonly profiles: readonly AgentsProfilePageEntry[];
40
+ readonly diagnostics: readonly AgentsProfileDiagnostic[];
41
+ readonly omittedProfileCount: number;
42
+ readonly omittedDiagnosticCount: number;
43
+ }
44
+
45
+ /** Read-only provider for Agent-owned profile pages. */
46
+ export interface AgentsProfilePages {
47
+ getData(): AgentsProfilePagesData | undefined;
48
+ }
49
+
50
+ /** One active or completed managed run shown in the shared viewer. */
51
+ export interface AgentsOverlayRun extends AgentRunRegistryRun {
52
+ readonly key: string;
53
+ readonly transcriptSource?: AgentRunTranscriptSource;
54
+ readonly conversation?: AgentRunDisplayConversation;
55
+ readonly usage?: Usage;
56
+ readonly thinkingLevel: ModelThinkingLevel;
57
+ readonly result?: AgentRunRegistryRun["result"];
58
+ }
59
+
60
+ /** Data shown by the session-scoped /agents overlay. */
61
+ export interface AgentsOverlayData {
62
+ readonly runs: readonly AgentsOverlayRun[];
63
+ readonly profilePages?: AgentsProfilePagesData;
64
+ }
65
+
66
+ /** Result of one interactive selected-run control. */
67
+ export type AgentOverlayControlResult = "accepted" | "not-running" | "canceled";
68
+
69
+ /** Runtime dependencies for the interactive overlay. */
70
+ export interface AgentsDialogDependencies {
71
+ readonly theme: Theme;
72
+ readonly done: () => void;
73
+ readonly tui: { requestRender: () => void; terminal: { rows: number } };
74
+ readonly keybindings?: Pick<KeybindingsManager, "getKeys" | "matches">;
75
+ readonly onSteer: (runKey: string, message: string) => Promise<AgentOverlayControlResult>;
76
+ readonly onStop: (runKey: string) => Promise<Exclude<AgentOverlayControlResult, "canceled">>;
77
+ readonly subscribe?: (listener: (data: AgentsOverlayData) => void) => () => void;
78
+ }