pi-subagent-manager 0.8.0 → 0.10.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.
@@ -16,6 +16,9 @@ import { dirname, join, resolve } from "node:path";
16
16
  export const SUBAGENT_MODES = ["off", "opportunistic", "orchestration"] as const;
17
17
  export type SubagentMode = (typeof SUBAGENT_MODES)[number];
18
18
 
19
+ export const WIDGET_MODES = ["full", "minimal"] as const;
20
+ export type WidgetMode = (typeof WIDGET_MODES)[number];
21
+
19
22
  export const TOOL_FILTERING_MODES = ["allowed", "all-except-blocked", "all"] as const;
20
23
  export type ToolFilteringMode = (typeof TOOL_FILTERING_MODES)[number];
21
24
 
@@ -29,6 +32,7 @@ export type ModelSelectionMode = (typeof MODEL_SELECTION_MODES)[number];
29
32
  export interface ManagerSettings {
30
33
  subagentMode: SubagentMode;
31
34
  toolFiltering: ToolFilteringMode;
35
+ widgetMode: WidgetMode;
32
36
  maxLevels: number;
33
37
  maxConcurrent: number;
34
38
  maxThreads: number;
@@ -42,10 +46,11 @@ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
42
46
  modelSelection: "pick-first-scoped",
43
47
  subagentMode: "opportunistic",
44
48
  toolFiltering: "allowed",
49
+ widgetMode: "full",
45
50
  };
46
51
 
47
52
  const KEYS = [
48
- "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering",
53
+ "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode",
49
54
  ] as const;
50
55
  const MAX_LEVELS = 32;
51
56
 
@@ -84,6 +89,7 @@ function positiveSafeInteger(value: unknown): value is number {
84
89
 
85
90
  function requirement(key: (typeof KEYS)[number]): string {
86
91
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
92
+ if (key === "widgetMode") return "widgetMode must be full or minimal";
87
93
  if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
88
94
  if (key === "modelSelection")
89
95
  return "modelSelection must be pick-first-available, pick-first-scoped or use-current";
@@ -127,6 +133,11 @@ function parseSettings(content: string): Partial<ManagerSettings> {
127
133
  layer.toolFiltering = value as ToolFilteringMode;
128
134
  continue;
129
135
  }
136
+ if (key === "widgetMode") {
137
+ if (!WIDGET_MODES.includes(value as WidgetMode)) throw new Error(requirement(key));
138
+ layer.widgetMode = value as WidgetMode;
139
+ continue;
140
+ }
130
141
  if (key === "modelSelection") {
131
142
  if (!MODEL_SELECTION_MODES.includes(value as ModelSelectionMode))
132
143
  throw new Error(requirement(key));
package/src/types.ts CHANGED
@@ -59,10 +59,38 @@ export type DriverEvent =
59
59
  /** Streaming message_update snapshot. Omit for authoritative message_end. */
60
60
  partial?: boolean;
61
61
  };
62
+ /** Ephemeral read-only transcript state; never part of registry/delivery events. */
63
+ export interface TranscriptToolState {
64
+ toolCallId: string;
65
+ toolName: string;
66
+ parentToolCallId?: string;
67
+ args: unknown;
68
+ result?: unknown;
69
+ isError?: boolean;
70
+ state: "running" | "completed";
71
+ }
72
+ export interface TranscriptSnapshot {
73
+ revision: number;
74
+ /** Changes when a driver is replaced; revisions remain monotonic within the manager. */
75
+ generation: number;
76
+ messages: readonly AgentMessage[];
77
+ assistant: AgentMessage | null;
78
+ tools: readonly TranscriptToolState[];
79
+ inheritedCount: number;
80
+ thread?: ThreadView;
81
+ error?: string;
82
+ }
83
+ export interface TranscriptObservation {
84
+ snapshot: TranscriptSnapshot;
85
+ unsubscribe(): void;
86
+ }
87
+ export type TranscriptListener = (snapshot: TranscriptSnapshot) => void;
88
+
62
89
  export interface AgentDriver {
63
90
  prompt(message: string): Promise<void>;
64
91
  steer(message: string): Promise<void>;
65
92
  snapshot(): AgentMessage[];
93
+ observeTranscript?(listener: TranscriptListener): TranscriptObservation;
66
94
  output(): string;
67
95
  abort(): Promise<void>;
68
96
  dispose(): void;
@@ -114,6 +142,8 @@ export interface ThreadService {
114
142
  get(path: string): ThreadView;
115
143
  output(path: string): string;
116
144
  transcript(path: string): Promise<string>;
145
+ /** Optional for portable adapters; the runtime manager always implements this. */
146
+ observeTranscript?(path: string, listener: TranscriptListener): Promise<TranscriptObservation>;
117
147
  spawn(
118
148
  args: { path: string; type: string; task: string; wait?: boolean },
119
149
  signal?: AbortSignal,
@@ -0,0 +1,195 @@
1
+ import {
2
+ CustomEditor,
3
+ type CustomEditorOptions,
4
+ type KeybindingsManager,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ getKeybindings,
8
+ Key,
9
+ matchesKey,
10
+ type EditorTheme,
11
+ type Keybinding,
12
+ type TUI,
13
+ } from "@earendil-works/pi-tui";
14
+
15
+ export interface AgentNavigationEditorOptions {
16
+ /** Must return the whole navigation interaction, so repeated Left cannot reopen it. */
17
+ openTree(): void | Promise<void>;
18
+ canOpen(): boolean;
19
+ /** Root ownership token; changing it invalidates queued transitions. */
20
+ generation(): unknown;
21
+ onError?(error: unknown): void;
22
+ /**
23
+ * Chronological user prompts for reload/new/resume/fork. Omit on startup:
24
+ * Pi hydrates the installed editor after the startup session_start event.
25
+ */
26
+ initialHistory?: readonly string[];
27
+ }
28
+
29
+ /**
30
+ * Physical Left boundary adapter. It owns no session/history internals and never
31
+ * changes the draft. Install once per root UI lifecycle, not for tree navigation.
32
+ * Another custom editor occupies the same host slot; skip installation rather than stack.
33
+ */
34
+ export class AgentNavigationEditor extends CustomEditor {
35
+ private pending = false;
36
+ private disposed = false;
37
+ private dispatchDepth = 0;
38
+ private inputEpoch = 0;
39
+ private pastePending = false;
40
+ private jumpPending = false;
41
+
42
+ constructor(
43
+ tui: TUI,
44
+ theme: EditorTheme,
45
+ private navigationKeys: KeybindingsManager,
46
+ private navigation: AgentNavigationEditorOptions,
47
+ options?: CustomEditorOptions,
48
+ ) {
49
+ super(tui, theme, navigationKeys, options);
50
+ // SessionStartEvent.reason distinguishes startup (host hydrates AFTER
51
+ // installation) from reload/replacement (explicit public hydration needed).
52
+ // Never infer replay from prompt text: intentional repetitions are valid.
53
+ for (const text of navigation.initialHistory ?? []) this.addToHistory(text);
54
+ }
55
+
56
+ /** Invalidates queued work without resetting a competing extension's editor. */
57
+ dispose(): void {
58
+ this.disposed = true;
59
+ this.inputEpoch++;
60
+ }
61
+
62
+ private ordinaryLeft(data: string): boolean {
63
+ if (!matchesKey(data, Key.left)) return false;
64
+ // Editor uses the global TUI bindings; CustomEditor uses the injected app
65
+ // manager. Both must agree, and a conflicting remap wins conservatively.
66
+ for (const keys of [this.navigationKeys, getKeybindings()]) {
67
+ if (!keys.matches(data, "tui.editor.cursorLeft")) return false;
68
+ for (const action of Object.keys(keys.getResolvedBindings())) {
69
+ if (
70
+ action !== "tui.editor.cursorLeft" &&
71
+ (action.startsWith("tui.editor.") ||
72
+ action.startsWith("tui.input.") ||
73
+ action.startsWith("tui.altScreen.") ||
74
+ action.startsWith("app.")) &&
75
+ keys.matches(data, action as Keybinding)
76
+ )
77
+ return false;
78
+ }
79
+ }
80
+ return true;
81
+ }
82
+
83
+ override handleInput(data: string): void {
84
+ const outer = this.dispatchDepth === 0;
85
+ const left = this.ordinaryLeft(data);
86
+ if (outer && !left) this.inputEpoch++;
87
+ const previousPaste = this.pastePending;
88
+ const wasPaste = previousPaste || data.includes("\x1b[200~");
89
+ // Update before dispatch: Pi recursively sends a suffix after the end
90
+ // marker through this.handleInput, and that suffix is no longer paste.
91
+ if (data.includes("\x1b[200~")) this.pastePending = true;
92
+ if (wasPaste && data.includes("\x1b[201~")) this.pastePending = false;
93
+ const wasJump = this.jumpPending;
94
+ const cursor = this.getCursor();
95
+ const text = this.getText();
96
+ const eligible =
97
+ outer &&
98
+ left &&
99
+ this.focused &&
100
+ !this.disposed &&
101
+ !wasPaste &&
102
+ !wasJump &&
103
+ !this.isShowingAutocomplete() &&
104
+ cursor.line === 0 &&
105
+ cursor.col === 0;
106
+ const generation = eligible ? this.navigation.generation() : undefined;
107
+ let changed = false;
108
+ let consumed = false;
109
+ const originalChange = this.onChange;
110
+ const originalShortcut = this.onExtensionShortcut;
111
+ const observeChange = (value: string) => {
112
+ changed = true;
113
+ originalChange?.call(this, value);
114
+ };
115
+ const observeShortcut = (value: string) => {
116
+ const handled = originalShortcut?.call(this, value) ?? false;
117
+ consumed ||= handled && value === data;
118
+ return handled;
119
+ };
120
+ this.onChange = observeChange;
121
+ this.onExtensionShortcut = observeShortcut;
122
+ this.dispatchDepth++;
123
+ try {
124
+ // Exactly one stock dispatch, preserving host-wired application controls.
125
+ super.handleInput(data);
126
+ } finally {
127
+ this.dispatchDepth--;
128
+ if (this.onChange === observeChange) this.onChange = originalChange;
129
+ if (this.onExtensionShortcut === observeShortcut) this.onExtensionShortcut = originalShortcut;
130
+ if (consumed) this.pastePending = previousPaste;
131
+ if (!consumed) {
132
+ // Track only public input; over-suppress when precedence is ambiguous.
133
+ // Recursive paste suffix dispatch updates guards, but never opens UI.
134
+ if (!wasPaste) {
135
+ const keys = getKeybindings();
136
+ const jump =
137
+ keys.matches(data, "tui.editor.jumpForward") ||
138
+ keys.matches(data, "tui.editor.jumpBackward");
139
+ this.jumpPending = !wasJump && jump;
140
+ }
141
+ }
142
+ }
143
+ const after = this.getCursor();
144
+ if (
145
+ eligible &&
146
+ !consumed &&
147
+ !changed &&
148
+ !this.isShowingAutocomplete() &&
149
+ this.getText() === text &&
150
+ after.line === cursor.line &&
151
+ after.col === cursor.col
152
+ ) {
153
+ this.queueOpen(text, cursor, generation);
154
+ }
155
+ }
156
+
157
+ private queueOpen(
158
+ text: string,
159
+ cursor: { line: number; col: number },
160
+ generation: unknown,
161
+ ): void {
162
+ if (this.pending || !this.navigation.canOpen()) return;
163
+ this.pending = true;
164
+ const epoch = this.inputEpoch;
165
+ queueMicrotask(() => {
166
+ const after = this.getCursor();
167
+ if (
168
+ this.disposed ||
169
+ !this.focused ||
170
+ this.inputEpoch !== epoch ||
171
+ this.navigation.generation() !== generation ||
172
+ !this.navigation.canOpen() ||
173
+ this.isShowingAutocomplete() ||
174
+ this.getText() !== text ||
175
+ after.line !== cursor.line ||
176
+ after.col !== cursor.col
177
+ ) {
178
+ this.pending = false;
179
+ return;
180
+ }
181
+ try {
182
+ // Call within the checked microtask: an extra Promise.then would leave
183
+ // a gap in which root ownership could change after validation.
184
+ void Promise.resolve(this.navigation.openTree())
185
+ .catch((error: unknown) => this.navigation.onError?.(error))
186
+ .finally(() => {
187
+ this.pending = false;
188
+ });
189
+ } catch (error) {
190
+ this.pending = false;
191
+ this.navigation.onError?.(error);
192
+ }
193
+ });
194
+ }
195
+ }
package/src/ui/dialog.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type {
2
- ExtensionCommandContext,
2
+ ExtensionContext,
3
3
  ExtensionUIContext,
4
4
  KeybindingsManager,
5
5
  Theme,
@@ -167,7 +167,7 @@ export class DialogEditor {
167
167
  }
168
168
 
169
169
  export function dialogEditor(
170
- ctx: ExtensionCommandContext,
170
+ ctx: ExtensionContext,
171
171
  title: string,
172
172
  prefill: string,
173
173
  ): Promise<string | undefined> {
@@ -273,7 +273,7 @@ export class DialogMenu {
273
273
  }
274
274
  }
275
275
 
276
- export function canOpenDialog(ctx: ExtensionCommandContext): boolean {
276
+ export function canOpenDialog(ctx: ExtensionContext): boolean {
277
277
  if (!ctx.hasUI) return false;
278
278
  if (ctx.mode && ctx.mode !== "tui") {
279
279
  ctx.ui.notify("Agents dialogs require interactive TUI mode.", "warning");
@@ -283,7 +283,7 @@ export function canOpenDialog(ctx: ExtensionCommandContext): boolean {
283
283
  }
284
284
 
285
285
  export async function dialogMenu(
286
- ctx: ExtensionCommandContext,
286
+ ctx: ExtensionContext,
287
287
  title: string,
288
288
  rows: DialogRow[],
289
289
  options: { selectedId?: string; footer?: string; saveId?: string } = {},
@@ -305,7 +305,7 @@ export async function dialogMenu(
305
305
  }
306
306
 
307
307
  export async function dialogInput(
308
- ctx: ExtensionCommandContext,
308
+ ctx: ExtensionContext,
309
309
  title: string,
310
310
  initial: string,
311
311
  help: string,
@@ -366,7 +366,7 @@ interface PendingView {
366
366
  resolve: (value: unknown) => void;
367
367
  }
368
368
 
369
- const dialogScopes = new WeakSet<ExtensionCommandContext>();
369
+ const dialogScopes = new WeakSet<ExtensionContext>();
370
370
 
371
371
  function isPromise<T>(value: T | Promise<T>): value is Promise<T> {
372
372
  return (
@@ -512,6 +512,7 @@ export class DialogSession {
512
512
  this.disposed = true;
513
513
  this.closed = true;
514
514
  this.inputLocked = true;
515
+ this.resolvePending();
515
516
  const child = this.child;
516
517
  this.child = undefined;
517
518
  safeDispose(child);
@@ -567,10 +568,10 @@ export class DialogSession {
567
568
  }
568
569
  }
569
570
 
570
- function scopeDialogContext(
571
- ctx: ExtensionCommandContext,
571
+ export function scopeDialogContext<T extends ExtensionContext>(
572
+ ctx: T,
572
573
  session: DialogSession,
573
- ): ExtensionCommandContext {
574
+ ): T {
574
575
  const source = ctx.ui;
575
576
  const originalCustom = source.custom.bind(source);
576
577
  const ui = Object.create(source) as ExtensionUIContext;
@@ -584,16 +585,16 @@ function scopeDialogContext(
584
585
  // Define an own property while keeping the remaining context getters live.
585
586
  return Object.create(ctx, {
586
587
  ui: { value: ui, writable: true, enumerable: true, configurable: true },
587
- }) as ExtensionCommandContext;
588
+ }) as T;
588
589
  }
589
590
 
590
591
  /**
591
592
  * Run a dialog workflow inside one ctx.ui.custom overlay.
592
593
  * Nested calls on the scoped context reuse that overlay instead of opening another.
593
594
  */
594
- export async function withDialogSession(
595
- ctx: ExtensionCommandContext,
596
- run: (ctx: ExtensionCommandContext) => Promise<void>,
595
+ export async function withDialogSession<T extends ExtensionContext>(
596
+ ctx: T,
597
+ run: (ctx: T) => Promise<void>,
597
598
  ): Promise<void> {
598
599
  if (dialogScopes.has(ctx)) {
599
600
  await run(ctx);