pi-subagent-manager 1.10.0 → 1.12.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 (95) hide show
  1. package/README.md +9 -9
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +790 -0
  4. package/dist/orch/checklist-integration.js +176 -0
  5. package/dist/orch/context-entries.js +6 -0
  6. package/dist/orch/cost-ledger.js +38 -0
  7. package/dist/orch/diagnostics.js +86 -0
  8. package/dist/orch/extensions.js +66 -0
  9. package/dist/orch/housekeeping-usage.js +22 -0
  10. package/dist/orch/housekeeping.js +248 -0
  11. package/dist/orch/inherited-tools.js +57 -0
  12. package/dist/orch/mailbox.js +195 -0
  13. package/dist/orch/manager.js +970 -0
  14. package/dist/orch/paths.js +69 -0
  15. package/dist/orch/prompt.js +30 -0
  16. package/dist/orch/registry.js +115 -0
  17. package/dist/orch/runtime.js +835 -0
  18. package/dist/orch/tools.js +112 -0
  19. package/dist/orch/transcript.js +165 -0
  20. package/dist/prefs/agent-import.js +188 -0
  21. package/dist/prefs/config.js +878 -0
  22. package/dist/prefs/import-discovery.js +547 -0
  23. package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +0 -1
  24. package/dist/prefs/models.js +56 -0
  25. package/dist/prefs/settings.js +491 -0
  26. package/dist/types.js +1 -0
  27. package/dist/ui/agent-loader.js +63 -0
  28. package/dist/ui/agent-navigation-editor.js +168 -0
  29. package/dist/ui/cost-footer.js +209 -0
  30. package/dist/ui/dialog.js +505 -0
  31. package/dist/ui/import-picker.js +191 -0
  32. package/dist/ui/live-agent-view.js +527 -0
  33. package/dist/ui/model-picker.js +529 -0
  34. package/dist/ui/settings-ui.js +671 -0
  35. package/dist/ui/status-ui.js +470 -0
  36. package/dist/ui/thread-tree.js +142 -0
  37. package/dist/ui/tool-picker.js +331 -0
  38. package/dist/ui/transcript-tool.js +91 -0
  39. package/dist/ui/ui.js +1019 -0
  40. package/package.json +17 -5
  41. package/docs/assets/subagent-manager-demo.gif +0 -0
  42. package/docs/async-lifecycle.md +0 -153
  43. package/docs/custom-agents.md +0 -154
  44. package/docs/default-agents.md +0 -95
  45. package/docs/demo.md +0 -63
  46. package/docs/development.md +0 -74
  47. package/docs/importing-agents.md +0 -41
  48. package/docs/pi-footer.md +0 -128
  49. package/docs/research-claude.md +0 -258
  50. package/docs/research-codex.md +0 -143
  51. package/docs/research-default-agent-models.md +0 -121
  52. package/docs/research-model-audit-2026-10.md +0 -154
  53. package/docs/research-model-roles-coding.md +0 -99
  54. package/docs/research-model-roles-writing.md +0 -78
  55. package/docs/research-researcher-workflow.md +0 -97
  56. package/docs/settings.md +0 -293
  57. package/docs/subagent-extension-limitations.md +0 -98
  58. package/docs/threads.md +0 -73
  59. package/docs/tools-and-ui.md +0 -129
  60. package/src/index.ts +0 -920
  61. package/src/orch/checklist-integration.ts +0 -230
  62. package/src/orch/context-entries.ts +0 -15
  63. package/src/orch/cost-ledger.ts +0 -56
  64. package/src/orch/diagnostics.ts +0 -95
  65. package/src/orch/extensions.ts +0 -83
  66. package/src/orch/housekeeping-usage.ts +0 -47
  67. package/src/orch/housekeeping.ts +0 -348
  68. package/src/orch/inherited-tools.ts +0 -84
  69. package/src/orch/mailbox.ts +0 -261
  70. package/src/orch/manager.ts +0 -1084
  71. package/src/orch/paths.ts +0 -73
  72. package/src/orch/prompt.ts +0 -39
  73. package/src/orch/registry.ts +0 -168
  74. package/src/orch/runtime.ts +0 -1041
  75. package/src/orch/tools.ts +0 -190
  76. package/src/orch/transcript.ts +0 -186
  77. package/src/prefs/agent-import.ts +0 -245
  78. package/src/prefs/config.ts +0 -1017
  79. package/src/prefs/import-discovery.ts +0 -643
  80. package/src/prefs/models.ts +0 -74
  81. package/src/prefs/settings.ts +0 -614
  82. package/src/types.ts +0 -271
  83. package/src/ui/agent-loader.ts +0 -98
  84. package/src/ui/agent-navigation-editor.ts +0 -233
  85. package/src/ui/cost-footer.ts +0 -230
  86. package/src/ui/dialog.ts +0 -678
  87. package/src/ui/import-picker.ts +0 -231
  88. package/src/ui/live-agent-view.ts +0 -600
  89. package/src/ui/model-picker.ts +0 -701
  90. package/src/ui/settings-ui.ts +0 -830
  91. package/src/ui/status-ui.ts +0 -628
  92. package/src/ui/thread-tree.ts +0 -173
  93. package/src/ui/tool-picker.ts +0 -398
  94. package/src/ui/transcript-tool.ts +0 -142
  95. package/src/ui/ui.ts +0 -1407
package/src/types.ts DELETED
@@ -1,271 +0,0 @@
1
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
- import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
3
-
4
- export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
5
- export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
6
- export interface ResolvedAgentSettings {
7
- model: string;
8
- thinkingLevel: ThinkingLevel;
9
- }
10
- export interface AgentType {
11
- name: string;
12
- description: string;
13
- models?: string[];
14
- /** @deprecated Use ordered models instead. */
15
- model?: string;
16
- /** Advisory display names. Not provider/model pins and never used for selection. */
17
- modelSuggestions?: string[];
18
- thinkingLevel?: ThinkingLevel;
19
- /** Pi semantic token for the type pill background and task path foreground. */
20
- color?: string;
21
- /** Optional literal Nerd Font glyph; displayed only when the labs setting is enabled. */
22
- icon?: string;
23
- tools?: { allow?: string[]; block?: string[] };
24
- systemPrompt: string;
25
- filePath?: string;
26
- source?: "bundled" | "user" | "project";
27
- /**
28
- * How this definition is customized relative to its base.
29
- * - fork: a full `<name>.md` copy (owns the system prompt).
30
- * - override: a settings-only `<name>.yml` merged on top of the base
31
- * (no Markdown body; unset fields follow the base).
32
- * Absent for pure bundled definitions and brand-new drafts.
33
- */
34
- customization?: {
35
- kind: "fork" | "override";
36
- scope: "user" | "project";
37
- filePath: string;
38
- };
39
- /** Source of the base definition under the customization, if any. */
40
- baseSource?: "bundled" | "user" | "project";
41
- /** File path of the base definition under the customization, if any. */
42
- baseFilePath?: string;
43
- }
44
- export type ThreadState = "starting" | "running" | "paused" | "completed" | "failed" | "stopped";
45
- export interface ChildDiagnostic {
46
- level: "info" | "warning" | "error";
47
- message: string;
48
- source?: string;
49
- }
50
- export interface ThreadView {
51
- /** Bounded explicit extension reports; live only, not transcript content. */
52
- diagnostics?: ChildDiagnostic[];
53
- path: string;
54
- parent: string | null;
55
- owner: string;
56
- type: string;
57
- color?: string;
58
- icon?: string;
59
- /** Actual runtime selection, not the type's model preferences. */
60
- model?: string;
61
- thinkingLevel?: ThinkingLevel;
62
- state: ThreadState;
63
- task: string;
64
- status: string;
65
- /**
66
- * [labs] One-line summary of current work written by the housekeeping model.
67
- * Live only: never persisted, cleared when the run settles or restarts.
68
- * Renderers prefer it over raw `status` while the agent is active.
69
- */
70
- summary?: string;
71
- output?: string;
72
- error?: string;
73
- createdAt: number;
74
- updatedAt: number;
75
- sessionFile?: string;
76
- /** Frozen active time. Renderer adds `Date.now() - startedAt` while a run is active. */
77
- elapsedMs?: number;
78
- /** Current run start. Live only; omitted from saved views so reloads do not count offline time. */
79
- startedAt?: number;
80
- /** Most recent run start (spawn or resume). Persisted; orders the agent tree newest-first. */
81
- lastStartedAt?: number;
82
- /** Cumulative input tokens, including cache read/write. Live views include the in-progress message. */
83
- inputTokens?: number;
84
- /** Cumulative output tokens. Live views include the in-progress message. */
85
- outputTokens?: number;
86
- /** Cumulative estimated USD cost for this agent's own messages. */
87
- costUsd?: number;
88
- /** Stable lifetime identity for cost accounting, retained across resumes/reloads. */
89
- costId?: string;
90
- }
91
- export type DriverEvent =
92
- | { kind: "diagnostic"; diagnostic: ChildDiagnostic }
93
- | { kind: "settings"; model: string; thinkingLevel: ThinkingLevel }
94
- | {
95
- kind: "activity" | "error";
96
- text: string;
97
- /** Short sanitized argument snippet (e.g. a command or path) used only as summary context. */
98
- detail?: string;
99
- }
100
- | {
101
- kind: "checkpoint";
102
- text: string;
103
- sessionFile?: string;
104
- sessionLeafId?: string | null;
105
- }
106
- | {
107
- kind: "usage";
108
- /** Cumulative own-assistant tokens for this driver instance, excluding inherited history. */
109
- inputTokens: number;
110
- outputTokens: number;
111
- /** Cumulative estimated USD cost, when reported by the runtime. */
112
- costUsd?: number;
113
- /** Streaming message_update snapshot. Omit for authoritative message_end. */
114
- partial?: boolean;
115
- };
116
- /** Ephemeral read-only transcript state; never part of registry/delivery events. */
117
- export interface TranscriptToolState {
118
- toolCallId: string;
119
- toolName: string;
120
- parentToolCallId?: string;
121
- args: unknown;
122
- result?: unknown;
123
- isError?: boolean;
124
- state: "running" | "completed";
125
- }
126
- export interface TranscriptSnapshot {
127
- revision: number;
128
- /** Changes when a driver is replaced; revisions remain monotonic within the manager. */
129
- generation: number;
130
- messages: readonly AgentMessage[];
131
- assistant: AgentMessage | null;
132
- tools: readonly TranscriptToolState[];
133
- inheritedCount: number;
134
- thread?: ThreadView;
135
- error?: string;
136
- }
137
- export interface TranscriptObservation {
138
- snapshot: TranscriptSnapshot;
139
- unsubscribe(): void;
140
- }
141
- export type TranscriptListener = (snapshot: TranscriptSnapshot) => void;
142
-
143
- /** Opaque session metadata needed to reproduce inherited context transformations. */
144
- export interface InheritedContextEntry {
145
- customType: string;
146
- data: unknown;
147
- }
148
-
149
- export interface AgentDriver {
150
- prompt(message: string): Promise<void>;
151
- steer(message: string): Promise<void>;
152
- snapshot(): AgentMessage[];
153
- contextEntries?(): InheritedContextEntry[];
154
- observeTranscript?(listener: TranscriptListener): TranscriptObservation;
155
- output(): string;
156
- abort(): Promise<void>;
157
- dispose(): void | Promise<void>;
158
- sendUpdate(content: string): Promise<void> | void;
159
- sessionFile?: string;
160
- sessionLeafId?: string | null;
161
- }
162
- export interface DriverOptions {
163
- path: string;
164
- /** Whether the configured depth limit permits another level of children. */
165
- canSpawnChildren?: boolean;
166
- type: AgentType;
167
- inherited: AgentMessage[];
168
- inheritedContextEntries?: InheritedContextEntry[];
169
- tools: ToolDefinition[];
170
- onEvent(event: DriverEvent): void;
171
- shouldPause(): boolean;
172
- parentPath: string | null;
173
- sessionFile?: string;
174
- /** Retained transcript of a nested lexical parent. Absent for /root and independent roots. */
175
- parentSessionFile?: string;
176
- sessionLeafId?: string | null;
177
- signal: AbortSignal;
178
- }
179
- export interface SavedThreadView {
180
- path: string;
181
- parent: string | null;
182
- owner: string;
183
- type: string;
184
- color?: string;
185
- icon?: string;
186
- model?: string;
187
- thinkingLevel?: ThinkingLevel;
188
- state: ThreadState;
189
- task: string;
190
- status: string;
191
- output?: string;
192
- error?: string;
193
- createdAt: number;
194
- sessionFile?: string;
195
- sessionLeafId?: string | null;
196
- /** Frozen cumulative active time. `startedAt` is intentionally not persisted. */
197
- elapsedMs?: number;
198
- lastStartedAt?: number;
199
- inputTokens?: number;
200
- outputTokens?: number;
201
- costUsd?: number;
202
- costId?: string;
203
- }
204
- export interface SavedThread {
205
- view: SavedThreadView;
206
- definition: AgentType;
207
- /** Reserved threads may not have a transcript yet; preserve their initial context. */
208
- inherited?: AgentMessage[];
209
- inheritedContextEntries?: InheritedContextEntry[];
210
- }
211
- export interface ThreadService {
212
- list(): ThreadView[];
213
- get(path: string): ThreadView;
214
- output(path: string): string;
215
- transcript(path: string): Promise<string>;
216
- /** Optional for portable adapters; the runtime manager always implements this. */
217
- observeTranscript?(path: string, listener: TranscriptListener): Promise<TranscriptObservation>;
218
- spawn(
219
- args: { path: string; type: string; task: string; wait?: boolean; timeoutMs?: number },
220
- signal?: AbortSignal,
221
- ): Promise<ThreadView>;
222
- /** message and/or timeoutMs (30s–5min). timeoutMs alone only re-arms a running child's report-only timeout. */
223
- steer(path: string, message?: string, timeoutMs?: number): Promise<ThreadView>;
224
- wait(path: string, timeoutMs?: number, signal?: AbortSignal): Promise<ThreadView>;
225
- update(message: string): ThreadView;
226
- pause(reason: string): ThreadView;
227
- stop(path: string): Promise<ThreadView>;
228
- }
229
- export type DriverFactory = (options: DriverOptions) => Promise<AgentDriver>;
230
- export type ThreadEvent =
231
- | { kind: "diagnostic"; thread: ThreadView; diagnostic: ChildDiagnostic; recipient: string }
232
- | { kind: "change"; thread: ThreadView }
233
- | { kind: "metrics"; thread: ThreadView }
234
- | { kind: "update"; thread: ThreadView; message: string; recipient: string }
235
- | { kind: "settled"; thread: ThreadView; recipient: string; async: boolean }
236
- /** A spawn timeout elapsed while the child is still running. The child is NOT stopped. */
237
- | {
238
- kind: "timeout";
239
- thread: ThreadView;
240
- recipient: string;
241
- timeoutMs: number;
242
- recentOutput: string;
243
- };
244
- /** Recent live activity of one running agent, offered to the optional housekeeping summarizer. */
245
- export interface ThreadActivity {
246
- path: string;
247
- type: string;
248
- task: string;
249
- /** Identifies one start/resume run; summaries for an older run are stale. */
250
- run: number;
251
- /** Oldest to newest, bounded. */
252
- recent: readonly string[];
253
- }
254
- export interface ManagerOptions {
255
- createDriver: DriverFactory;
256
- rootSnapshot(): AgentMessage[];
257
- rootContextEntries?(): InheritedContextEntry[];
258
- getType(name: string): AgentType;
259
- toolsFor(path: string): ToolDefinition[];
260
- onEvent?(event: ThreadEvent): void;
261
- /** Called after each live activity of an active agent. Failures are ignored. */
262
- onActivity?(activity: ThreadActivity): void;
263
- /** Notification failures are diagnostic only; they must never interrupt a runner. */
264
- onEventError?(error: unknown, event: ThreadEvent): void;
265
- /** Maximum levels including the main conversation as L1; defaults to 3. */
266
- maxLevels?: number;
267
- /** @deprecated Internal legacy path-depth override; prefer maxLevels. */
268
- maxDepth?: number;
269
- maxThreads?: number;
270
- maxConcurrent?: number;
271
- }
@@ -1,98 +0,0 @@
1
- import { LOADER_STYLES, type LoaderStyle } from "../prefs/settings.ts";
2
- import type { ThreadView } from "../types.ts";
3
-
4
- export const AGENT_PROGRESS_INTERVAL = 180;
5
-
6
- type SettledState = Exclude<ThreadView["state"], "starting" | "running">;
7
-
8
- /** Built-in glyphs only; role icons are validated separately and never replaced. */
9
- export const AGENT_LOADERS: Record<
10
- LoaderStyle,
11
- {
12
- label: string;
13
- requiresNerdFont: boolean;
14
- frames: readonly string[];
15
- states: Record<SettledState, string>;
16
- }
17
- > = {
18
- circle: {
19
- label: "Circle",
20
- requiresNerdFont: true,
21
- // Nerd Fonts md-circle-slice-1..8, check-circle, pause-circle, close-circle, stop-circle.
22
- frames: Array.from({ length: 8 }, (_, index) => String.fromCodePoint(0xf0a9e + index)),
23
- states: {
24
- completed: "\u{f05e0}",
25
- paused: "\u{f03e5}",
26
- failed: "\u{f0159}",
27
- stopped: "\u{f0666}",
28
- },
29
- },
30
- braille: {
31
- label: "Braille",
32
- requiresNerdFont: false,
33
- frames: Array.from("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"),
34
- states: { completed: "✓", paused: "Ⅱ", failed: "×", stopped: "■" },
35
- },
36
- hourglass: {
37
- label: "Hourglass",
38
- requiresNerdFont: true,
39
- // Nerd Fonts fa-hourglass-start/half/end, check-square, pause, times-circle, stop.
40
- frames: ["\uf251", "\uf252", "\uf253"],
41
- states: { completed: "\uf14a", paused: "\uf04c", failed: "\uf057", stopped: "\uf04d" },
42
- },
43
- // Compact ASCII palettes inspired by cli-spinners line, star2 and toggle13.
44
- // https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json
45
- ascii: {
46
- label: "ASCII",
47
- requiresNerdFont: false,
48
- frames: ["|", "/", "-", "\\"],
49
- states: { completed: "+", paused: "=", failed: "!", stopped: "#" },
50
- },
51
- "ascii-star": {
52
- label: "ASCII Star",
53
- requiresNerdFont: false,
54
- frames: ["+", "x", "*"],
55
- states: { completed: "+", paused: "=", failed: "!", stopped: "#" },
56
- },
57
- "ascii-pulse": {
58
- label: "ASCII Pulse",
59
- requiresNerdFont: false,
60
- frames: ["=", "*", "-"],
61
- states: { completed: "+", paused: "=", failed: "!", stopped: "#" },
62
- },
63
- };
64
-
65
- /** Filter the picker without exposing private-use glyphs to ordinary fonts. */
66
- export function availableLoaderStyles(nerdFontIcons: boolean): LoaderStyle[] {
67
- return LOADER_STYLES.filter((style) => nerdFontIcons || !AGENT_LOADERS[style].requiresNerdFont);
68
- }
69
-
70
- /** Preserve saved preferences, but render a portable fallback when Nerd Fonts are off. */
71
- export function effectiveLoaderStyle(style: LoaderStyle, nerdFontIcons: boolean): LoaderStyle {
72
- return !nerdFontIcons && AGENT_LOADERS[style].requiresNerdFont ? "ascii" : style;
73
- }
74
-
75
- /** RPC/non-animated hosts use the first running frame and all settled indicators. */
76
- export function agentProgressIcon(
77
- thread: Pick<ThreadView, "state">,
78
- nerdFontIcons: boolean,
79
- now = Date.now(),
80
- animate = true,
81
- loaderStyle: LoaderStyle = "circle",
82
- ): string | undefined {
83
- const loader = AGENT_LOADERS[effectiveLoaderStyle(loaderStyle, nerdFontIcons)];
84
- if (thread.state === "starting" || thread.state === "running") {
85
- const index = animate ? Math.floor(Math.max(0, now) / AGENT_PROGRESS_INTERVAL) : 0;
86
- return loader.frames[index % loader.frames.length];
87
- }
88
- return loader.states[thread.state];
89
- }
90
-
91
- /** Restrict the separate label prefix to trusted, single built-in loader glyphs. */
92
- export function isAgentLoaderGlyph(glyph: string, nerdFontIcons = true): boolean {
93
- return Object.values(AGENT_LOADERS).some(
94
- (loader) =>
95
- (nerdFontIcons || !loader.requiresNerdFont) &&
96
- (loader.frames.includes(glyph) || Object.values(loader.states).includes(glyph)),
97
- );
98
- }
@@ -1,233 +0,0 @@
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
- /** Session-local widget collapse (full → minimal); never saves the configured display mode. */
20
- collapseWidget?(): void | Promise<void>;
21
- canCollapse?(): boolean;
22
- /**
23
- * Session-local widget expansion (minimal → full). While it is available, Left
24
- * steps toward the full widget before the tree: tree ← full ← minimal.
25
- */
26
- expandWidget?(): void | Promise<void>;
27
- canExpand?(): boolean;
28
- /** Root ownership token; changing it invalidates queued transitions. */
29
- generation(): unknown;
30
- onError?(error: unknown): void;
31
- /**
32
- * Chronological user prompts for reload/new/resume/fork. Omit on startup:
33
- * Pi hydrates the installed editor after the startup session_start event.
34
- */
35
- initialHistory?: readonly string[];
36
- }
37
-
38
- /**
39
- * Physical arrow boundary adapter. It owns no session/history internals and never
40
- * changes the draft. Install once per root UI lifecycle, not for tree navigation.
41
- * Another custom editor occupies the same host slot; skip installation rather than stack.
42
- */
43
- export class AgentNavigationEditor extends CustomEditor {
44
- private pending: "left" | "right" | undefined;
45
- private disposed = false;
46
- private dispatchDepth = 0;
47
- private inputEpoch = 0;
48
- private pastePending = false;
49
- private jumpPending = false;
50
-
51
- constructor(
52
- tui: TUI,
53
- theme: EditorTheme,
54
- private navigationKeys: KeybindingsManager,
55
- private navigation: AgentNavigationEditorOptions,
56
- options?: CustomEditorOptions,
57
- ) {
58
- super(tui, theme, navigationKeys, options);
59
- // SessionStartEvent.reason distinguishes startup (host hydrates AFTER
60
- // installation) from reload/replacement (explicit public hydration needed).
61
- // Never infer replay from prompt text: intentional repetitions are valid.
62
- for (const text of navigation.initialHistory ?? []) this.addToHistory(text);
63
- }
64
-
65
- /** Invalidates queued work without resetting a competing extension's editor. */
66
- dispose(): void {
67
- this.disposed = true;
68
- this.inputEpoch++;
69
- }
70
-
71
- private ordinaryArrow(data: string, direction: "left" | "right"): boolean {
72
- if (!matchesKey(data, direction === "left" ? Key.left : Key.right)) return false;
73
- const action = direction === "left" ? "tui.editor.cursorLeft" : "tui.editor.cursorRight";
74
- // Editor uses the global TUI bindings; CustomEditor uses the injected app
75
- // manager. Both must agree, and a conflicting remap wins conservatively.
76
- for (const keys of [this.navigationKeys, getKeybindings()]) {
77
- if (!keys.matches(data, action)) return false;
78
- for (const other of Object.keys(keys.getResolvedBindings())) {
79
- if (
80
- other !== action &&
81
- (other.startsWith("tui.editor.") ||
82
- other.startsWith("tui.input.") ||
83
- other.startsWith("tui.altScreen.") ||
84
- other.startsWith("app.")) &&
85
- keys.matches(data, other as Keybinding)
86
- )
87
- return false;
88
- }
89
- }
90
- return true;
91
- }
92
-
93
- override handleInput(data: string): void {
94
- const outer = this.dispatchDepth === 0;
95
- const direction = this.ordinaryArrow(data, "left")
96
- ? "left"
97
- : this.ordinaryArrow(data, "right")
98
- ? "right"
99
- : undefined;
100
- if (outer && (!direction || (this.pending && this.pending !== direction))) this.inputEpoch++;
101
- const previousPaste = this.pastePending;
102
- const wasPaste = previousPaste || data.includes("\x1b[200~");
103
- // Update before dispatch: Pi recursively sends a suffix after the end
104
- // marker through this.handleInput, and that suffix is no longer paste.
105
- if (data.includes("\x1b[200~")) this.pastePending = true;
106
- if (wasPaste && data.includes("\x1b[201~")) this.pastePending = false;
107
- const wasJump = this.jumpPending;
108
- const cursor = this.getCursor();
109
- const text = this.getText();
110
- const lines = text.split("\n");
111
- const atBoundary =
112
- direction === "left"
113
- ? cursor.line === 0 && cursor.col === 0
114
- : direction === "right" &&
115
- cursor.line === lines.length - 1 &&
116
- cursor.col === lines.at(-1)!.length;
117
- const eligible =
118
- outer &&
119
- direction !== undefined &&
120
- this.focused &&
121
- !this.disposed &&
122
- !wasPaste &&
123
- !wasJump &&
124
- !this.isShowingAutocomplete() &&
125
- atBoundary;
126
- const generation = eligible ? this.navigation.generation() : undefined;
127
- let changed = false;
128
- let consumed = false;
129
- const originalChange = this.onChange;
130
- const originalShortcut = this.onExtensionShortcut;
131
- const observeChange = (value: string) => {
132
- changed = true;
133
- originalChange?.call(this, value);
134
- };
135
- const observeShortcut = (value: string) => {
136
- const handled = originalShortcut?.call(this, value) ?? false;
137
- consumed ||= handled && value === data;
138
- return handled;
139
- };
140
- this.onChange = observeChange;
141
- this.onExtensionShortcut = observeShortcut;
142
- this.dispatchDepth++;
143
- try {
144
- // Exactly one stock dispatch, preserving host-wired application controls.
145
- super.handleInput(data);
146
- } finally {
147
- this.dispatchDepth--;
148
- if (this.onChange === observeChange) this.onChange = originalChange;
149
- if (this.onExtensionShortcut === observeShortcut) this.onExtensionShortcut = originalShortcut;
150
- if (consumed) this.pastePending = previousPaste;
151
- if (!consumed) {
152
- // Track only public input; over-suppress when precedence is ambiguous.
153
- // Recursive paste suffix dispatch updates guards, but never opens UI.
154
- if (!wasPaste) {
155
- const keys = getKeybindings();
156
- const jump =
157
- keys.matches(data, "tui.editor.jumpForward") ||
158
- keys.matches(data, "tui.editor.jumpBackward");
159
- this.jumpPending = !wasJump && jump;
160
- }
161
- }
162
- }
163
- const after = this.getCursor();
164
- if (
165
- eligible &&
166
- !consumed &&
167
- !changed &&
168
- !this.isShowingAutocomplete() &&
169
- this.getText() === text &&
170
- after.line === cursor.line &&
171
- after.col === cursor.col
172
- ) {
173
- this.queueNavigation(text, cursor, generation, direction!);
174
- }
175
- }
176
-
177
- private queueNavigation(
178
- text: string,
179
- cursor: { line: number; col: number },
180
- generation: unknown,
181
- direction: "left" | "right",
182
- ): void {
183
- // Left walks one step toward the tree: minimal → full first, then full → tree.
184
- // Right walks one step toward minimal. The decision is rechecked in the microtask.
185
- const action = (): "expand" | "tree" | "collapse" | undefined => {
186
- if (direction === "right")
187
- return this.navigation.collapseWidget && (this.navigation.canCollapse?.() ?? false)
188
- ? "collapse"
189
- : undefined;
190
- if (this.navigation.expandWidget && (this.navigation.canExpand?.() ?? false)) return "expand";
191
- return this.navigation.canOpen() ? "tree" : undefined;
192
- };
193
- const chosen = action();
194
- if (this.pending || !chosen) return;
195
- this.pending = direction;
196
- const epoch = this.inputEpoch;
197
- queueMicrotask(() => {
198
- const after = this.getCursor();
199
- if (
200
- this.disposed ||
201
- !this.focused ||
202
- this.inputEpoch !== epoch ||
203
- this.navigation.generation() !== generation ||
204
- action() !== chosen ||
205
- this.isShowingAutocomplete() ||
206
- this.getText() !== text ||
207
- after.line !== cursor.line ||
208
- after.col !== cursor.col
209
- ) {
210
- this.pending = undefined;
211
- return;
212
- }
213
- try {
214
- // Call within the checked microtask: an extra Promise.then would leave
215
- // a gap in which root ownership could change after validation.
216
- void Promise.resolve(
217
- chosen === "tree"
218
- ? this.navigation.openTree()
219
- : chosen === "expand"
220
- ? this.navigation.expandWidget!()
221
- : this.navigation.collapseWidget!(),
222
- )
223
- .catch((error: unknown) => this.navigation.onError?.(error))
224
- .finally(() => {
225
- this.pending = undefined;
226
- });
227
- } catch (error) {
228
- this.pending = undefined;
229
- this.navigation.onError?.(error);
230
- }
231
- });
232
- }
233
- }