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
@@ -0,0 +1,505 @@
1
+ import { CURSOR_MARKER, Editor, getKeybindings, Input, Key, matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
2
+ export const DIALOG_OPTIONS = {
3
+ overlay: true,
4
+ overlayOptions: {
5
+ anchor: "center",
6
+ width: "90%",
7
+ maxHeight: "90%",
8
+ margin: 1,
9
+ },
10
+ };
11
+ export function dialogText(text) {
12
+ return stripTerminalSequences(text).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
13
+ }
14
+ export function dialogHeight(host) {
15
+ const rows = host.terminal?.rows ?? 24;
16
+ return Math.max(1, Math.min(rows - 2, Math.floor(rows * 0.9)));
17
+ }
18
+ export function frameDialog(theme, width, height, title, body, footer) {
19
+ if (width <= 0 || height <= 0)
20
+ return [];
21
+ const fit = (text, columns) => {
22
+ const clipped = truncateToWidth(text, Math.max(0, columns), "", true);
23
+ return clipped + " ".repeat(Math.max(0, columns - visibleWidth(clipped)));
24
+ };
25
+ if (width < 4 || height < 4)
26
+ return [fit(theme.fg("muted", dialogText(title)), width)];
27
+ const inner = width - 2;
28
+ const line = (text) => theme.fg("border", "│") + fit(text, inner) + theme.fg("border", "│");
29
+ const heading = truncateToWidth(` ${dialogText(title)} `, inner, "");
30
+ const top = theme.fg("border", "╭" + heading + "─".repeat(Math.max(0, inner - visibleWidth(heading))) + "╮");
31
+ const budget = height - 4;
32
+ const padded = body.slice(0, budget);
33
+ while (padded.length < budget)
34
+ padded.push("");
35
+ const content = padded.map(line);
36
+ return [
37
+ top,
38
+ ...content,
39
+ theme.fg("border", "├" + "─".repeat(inner) + "┤"),
40
+ line(theme.fg("dim", dialogText(footer))),
41
+ theme.fg("border", "╰" + "─".repeat(inner) + "╯"),
42
+ ];
43
+ }
44
+ export class DialogEditor {
45
+ host;
46
+ theme;
47
+ title;
48
+ prefill;
49
+ done;
50
+ editor;
51
+ initialText;
52
+ constructor(host, theme, title, prefill, done) {
53
+ this.host = host;
54
+ this.theme = theme;
55
+ this.title = title;
56
+ this.prefill = prefill;
57
+ this.done = done;
58
+ this.editor = new Editor(host, {
59
+ borderColor: (text) => theme.fg("border", text),
60
+ selectList: {
61
+ selectedPrefix: (text) => theme.fg("accent", text),
62
+ selectedText: (text) => theme.fg("accent", text),
63
+ description: (text) => theme.fg("muted", text),
64
+ scrollInfo: (text) => theme.fg("dim", text),
65
+ noMatch: (text) => theme.fg("warning", text),
66
+ },
67
+ }, { paddingX: 0 });
68
+ this.editor.setText(stripTerminalSequences(prefill)
69
+ .replace(/\r\n?/g, "\n")
70
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ""));
71
+ this.initialText = this.editor.getText();
72
+ this.editor.disableSubmit = true;
73
+ }
74
+ getEditor() {
75
+ return this.editor;
76
+ }
77
+ get focused() {
78
+ return this.editor.focused;
79
+ }
80
+ set focused(value) {
81
+ this.editor.focused = value;
82
+ }
83
+ handleInput(data) {
84
+ if (matchesKey(data, Key.escape))
85
+ return this.done(undefined);
86
+ if (matchesKey(data, Key.ctrl("s"))) {
87
+ const value = this.editor.getText();
88
+ return this.done(value === this.initialText ? this.prefill : value);
89
+ }
90
+ this.editor.handleInput(data);
91
+ this.host.requestRender();
92
+ }
93
+ invalidate() {
94
+ this.editor.invalidate();
95
+ }
96
+ render(width) {
97
+ const height = dialogHeight(this.host);
98
+ const rows = this.editor.render(Math.max(1, width - 4)).slice(1, -1);
99
+ const budget = Math.max(0, height - 4);
100
+ const cursor = rows.findIndex((line) => line.includes(CURSOR_MARKER));
101
+ const start = cursor >= budget ? cursor - budget + 1 : 0;
102
+ return frameDialog(this.theme, width, height, this.title, rows.slice(start, start + budget).map((line) => ` ${line}`), "Enter newline · Ctrl+S apply · Esc cancel");
103
+ }
104
+ }
105
+ export function dialogEditor(ctx, title, prefill) {
106
+ return ctx.ui.custom((host, theme, _keys, done) => new DialogEditor(host, theme, title, prefill, done), DIALOG_OPTIONS);
107
+ }
108
+ export class DialogMenu {
109
+ host;
110
+ theme;
111
+ title;
112
+ rows;
113
+ done;
114
+ footer;
115
+ saveId;
116
+ renderLegend;
117
+ spaceSelect;
118
+ selected = 0;
119
+ viewport = 1;
120
+ constructor(host, theme, title, rows, done, selectedId, footer = "↑↓ navigate · Enter select · Esc close", saveId, renderLegend, spaceSelect = false) {
121
+ this.host = host;
122
+ this.theme = theme;
123
+ this.title = title;
124
+ this.rows = rows;
125
+ this.done = done;
126
+ this.footer = footer;
127
+ this.saveId = saveId;
128
+ this.renderLegend = renderLegend;
129
+ this.spaceSelect = spaceSelect;
130
+ const index = rows.findIndex((row) => row.id === selectedId);
131
+ if (index >= 0)
132
+ this.selected = index;
133
+ }
134
+ getSelectedId() {
135
+ return this.rows[this.selected]?.id;
136
+ }
137
+ handleInput(data) {
138
+ const keys = getKeybindings();
139
+ if (keys.matches(data, "tui.select.cancel"))
140
+ return this.done(undefined);
141
+ if (keys.matches(data, "tui.select.confirm") ||
142
+ (this.spaceSelect && matchesKey(data, Key.space)))
143
+ return this.done(this.getSelectedId());
144
+ if (this.saveId && matchesKey(data, Key.ctrl("s")))
145
+ return this.done(this.saveId);
146
+ let offset = 0;
147
+ if (keys.matches(data, "tui.select.up"))
148
+ offset = -1;
149
+ else if (keys.matches(data, "tui.select.down") || matchesKey(data, Key.tab))
150
+ offset = 1;
151
+ else if (matchesKey(data, Key.pageUp))
152
+ offset = -this.viewport;
153
+ else if (matchesKey(data, Key.pageDown))
154
+ offset = this.viewport;
155
+ else if (matchesKey(data, Key.home))
156
+ this.selected = 0;
157
+ else if (matchesKey(data, Key.end))
158
+ this.selected = Math.max(0, this.rows.length - 1);
159
+ this.selected = Math.max(0, Math.min(this.rows.length - 1, this.selected + offset));
160
+ this.host.requestRender();
161
+ }
162
+ invalidate() { }
163
+ render(width) {
164
+ const height = dialogHeight(this.host);
165
+ const inner = Math.max(0, width - 4);
166
+ const legend = this.renderLegend
167
+ ? wrapTextWithAnsi(this.renderLegend(this.theme), Math.max(1, inner - 1))
168
+ .slice(0, Math.max(0, height - 8))
169
+ .map((line) => ` ${line}`)
170
+ : [];
171
+ const help = (this.rows[this.selected]?.help ?? "")
172
+ .split(/\r\n?|\n/)
173
+ .flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, inner - 1)))
174
+ .slice(0, Math.max(1, height - 7 - legend.length));
175
+ const rowHeight = this.rows.some((row) => row.valueDetail !== undefined) ? 2 : 1;
176
+ this.viewport = Math.max(1, Math.floor((height - 6 - help.length - legend.length) / rowHeight));
177
+ const start = Math.max(0, Math.min(this.selected - this.viewport + 1, this.rows.length - this.viewport));
178
+ const hasIndicators = this.rows.some((row) => row.renderIndicators);
179
+ const indicatorWidth = 3;
180
+ const labelWidth = Math.min(28, Math.max(8, Math.floor(inner * 0.35)), hasIndicators ? Math.max(0, inner - 2 - 6 - indicatorWidth - 1) : Infinity);
181
+ const body = [
182
+ this.theme.fg("dim", ` ${this.rows.length ? this.selected + 1 : 0}/${this.rows.length} · Field / ${hasIndicators ? "Saved / " : ""}Value`),
183
+ ...this.rows.slice(start, start + this.viewport).flatMap((row, i) => {
184
+ const selected = start + i === this.selected;
185
+ const color = (text) => (selected ? this.theme.fg("accent", text) : text);
186
+ const plainLabel = dialogText(row.label);
187
+ const label = truncateToWidth(row.renderLabel ? row.renderLabel(plainLabel, this.theme) : plainLabel, labelWidth, "", true);
188
+ const padding = " ".repeat(Math.max(0, labelWidth - visibleWidth(label)));
189
+ const indicators = truncateToWidth(row.renderIndicators?.(this.theme) ?? "", indicatorWidth, "", true);
190
+ const indicatorPadding = " ".repeat(Math.max(0, indicatorWidth - visibleWidth(indicators)));
191
+ const value = dialogText(row.value ?? "");
192
+ const primary = color(`${selected ? "›" : " "} `) +
193
+ (row.renderLabel ? label : color(label)) +
194
+ color(`${padding} │ `) +
195
+ (hasIndicators ? indicators + color(`${indicatorPadding} │ `) : "") +
196
+ (row.valueColor ? this.theme.fg(row.valueColor, value) : color(value));
197
+ if (rowHeight === 1)
198
+ return [primary];
199
+ const valueStart = 2 + labelWidth + 3 + (hasIndicators ? indicatorWidth + 3 : 0);
200
+ const detail = truncateToWidth(dialogText(row.valueDetail ?? ""), Math.max(0, inner - valueStart));
201
+ return [primary, " ".repeat(valueStart) + this.theme.fg("muted", detail)];
202
+ }),
203
+ "",
204
+ ...help.map((line) => this.theme.fg("muted", ` ${line}`)),
205
+ ];
206
+ if (legend.length) {
207
+ const budget = Math.max(0, height - 4 - legend.length);
208
+ body.length = Math.min(body.length, budget);
209
+ while (body.length < budget)
210
+ body.push("");
211
+ body.push(...legend);
212
+ }
213
+ return frameDialog(this.theme, width, height, this.title, body, this.footer);
214
+ }
215
+ }
216
+ export function canOpenDialog(ctx) {
217
+ if (!ctx.hasUI)
218
+ return false;
219
+ if (ctx.mode && ctx.mode !== "tui") {
220
+ ctx.ui.notify("Agents dialogs require interactive TUI mode.", "warning");
221
+ return false;
222
+ }
223
+ return true;
224
+ }
225
+ export async function dialogMenu(ctx, title, rows, options = {}) {
226
+ return ctx.ui.custom((host, theme, _keys, done) => new DialogMenu(host, theme, title, rows, done, options.selectedId, options.footer, options.saveId, options.renderLegend, options.spaceSelect), DIALOG_OPTIONS);
227
+ }
228
+ export async function dialogInput(ctx, title, initial, help) {
229
+ return ctx.ui.custom((host, theme, _keys, done) => {
230
+ const input = new Input();
231
+ input.setValue(dialogText(initial));
232
+ input.onSubmit = done;
233
+ input.onEscape = () => done(undefined);
234
+ return {
235
+ get focused() {
236
+ return input.focused;
237
+ },
238
+ set focused(value) {
239
+ input.focused = value;
240
+ },
241
+ handleInput: (data) => {
242
+ input.handleInput(data);
243
+ host.requestRender();
244
+ },
245
+ invalidate: () => input.invalidate(),
246
+ render: (width) => frameDialog(theme, width, dialogHeight(host), title, [
247
+ "",
248
+ ...input.render(Math.max(1, width - 4)).map((line) => ` ${line}`),
249
+ "",
250
+ ...help
251
+ .split(/\r\n?|\n/)
252
+ .flatMap((line) => wrapTextWithAnsi(dialogText(line), Math.max(1, width - 5)))
253
+ .map((line) => theme.fg("muted", ` ${line}`)),
254
+ ], "Enter apply · Esc cancel"),
255
+ };
256
+ }, DIALOG_OPTIONS);
257
+ }
258
+ const dialogScopes = new WeakSet();
259
+ function isPromise(value) {
260
+ return (typeof value === "object" && value !== null && typeof value.then === "function");
261
+ }
262
+ function safeDispose(component) {
263
+ if (!component?.dispose)
264
+ return;
265
+ try {
266
+ component.dispose();
267
+ }
268
+ catch {
269
+ }
270
+ }
271
+ export class DialogSession {
272
+ host;
273
+ theme;
274
+ keys;
275
+ child;
276
+ focusedState = false;
277
+ inputLocked = true;
278
+ closed = false;
279
+ disposed = false;
280
+ generation = 0;
281
+ pending;
282
+ outerDone;
283
+ constructor(host, theme, keys, done) {
284
+ this.host = host;
285
+ this.theme = theme;
286
+ this.keys = keys;
287
+ this.outerDone = done;
288
+ }
289
+ getComponent() {
290
+ return this.child;
291
+ }
292
+ restoreFocus() {
293
+ if (this.closed)
294
+ return;
295
+ this.host.setFocus(this);
296
+ this.host.requestRender();
297
+ }
298
+ get focused() {
299
+ return this.focusedState;
300
+ }
301
+ set focused(value) {
302
+ this.focusedState = value;
303
+ this.forwardFocus();
304
+ }
305
+ mount(factory) {
306
+ if (this.closed)
307
+ return Promise.resolve(undefined);
308
+ const generation = ++this.generation;
309
+ this.inputLocked = true;
310
+ this.resolvePending();
311
+ return new Promise((resolve, reject) => {
312
+ let settled = false;
313
+ const resolveOnce = (value) => {
314
+ if (settled)
315
+ return;
316
+ settled = true;
317
+ if (this.pending?.generation === generation)
318
+ this.pending.settled = true;
319
+ resolve(value);
320
+ };
321
+ const rejectOnce = (error) => {
322
+ if (settled)
323
+ return;
324
+ settled = true;
325
+ this.inputLocked = true;
326
+ if (this.pending?.generation === generation)
327
+ this.pending.settled = true;
328
+ reject(error);
329
+ };
330
+ this.pending = {
331
+ generation,
332
+ settled: false,
333
+ resolve: (value) => resolveOnce(value),
334
+ };
335
+ const finish = (value) => {
336
+ if (this.closed || generation !== this.generation)
337
+ return;
338
+ this.inputLocked = true;
339
+ resolveOnce(value);
340
+ };
341
+ const adopt = (component) => {
342
+ try {
343
+ this.install(generation, component);
344
+ }
345
+ catch (error) {
346
+ rejectOnce(error);
347
+ }
348
+ };
349
+ try {
350
+ const produced = factory(this.host, this.theme, this.keys, finish);
351
+ if (isPromise(produced)) {
352
+ void produced.then((component) => adopt(component), (error) => {
353
+ if (settled || this.closed || generation !== this.generation)
354
+ return;
355
+ rejectOnce(error);
356
+ });
357
+ }
358
+ else {
359
+ adopt(produced);
360
+ }
361
+ }
362
+ catch (error) {
363
+ rejectOnce(error);
364
+ }
365
+ });
366
+ }
367
+ handleInput(data) {
368
+ if (this.closed || this.inputLocked)
369
+ return;
370
+ this.child?.handleInput?.(data);
371
+ }
372
+ handleMouse(event) {
373
+ if (this.closed || this.inputLocked)
374
+ return undefined;
375
+ return this.child?.handleMouse?.(event);
376
+ }
377
+ invalidate() {
378
+ this.child?.invalidate();
379
+ }
380
+ render(width) {
381
+ return this.child?.render(width) ?? [];
382
+ }
383
+ dispose() {
384
+ if (this.disposed)
385
+ return;
386
+ this.disposed = true;
387
+ this.closed = true;
388
+ this.inputLocked = true;
389
+ this.resolvePending();
390
+ const child = this.child;
391
+ this.child = undefined;
392
+ safeDispose(child);
393
+ }
394
+ close() {
395
+ if (this.closed)
396
+ return;
397
+ this.closed = true;
398
+ this.inputLocked = true;
399
+ this.resolvePending();
400
+ const done = this.outerDone;
401
+ this.outerDone = undefined;
402
+ try {
403
+ done?.();
404
+ }
405
+ finally {
406
+ this.dispose();
407
+ }
408
+ }
409
+ install(generation, component) {
410
+ if (this.closed || generation !== this.generation) {
411
+ safeDispose(component);
412
+ return;
413
+ }
414
+ this.replaceChild(component);
415
+ this.inputLocked = this.pending?.generation === generation ? this.pending.settled : true;
416
+ this.host.requestRender();
417
+ }
418
+ replaceChild(next) {
419
+ const previous = this.child;
420
+ this.child = next;
421
+ this.forwardFocus();
422
+ if (!previous || previous === next)
423
+ return;
424
+ if ("focused" in previous)
425
+ previous.focused = false;
426
+ safeDispose(previous);
427
+ }
428
+ forwardFocus() {
429
+ const child = this.child;
430
+ if (!child || !("focused" in child))
431
+ return;
432
+ child.focused = this.focused;
433
+ }
434
+ resolvePending() {
435
+ const pending = this.pending;
436
+ if (!pending || pending.settled)
437
+ return;
438
+ pending.settled = true;
439
+ pending.resolve(undefined);
440
+ }
441
+ }
442
+ export function scopeDialogContext(ctx, session) {
443
+ const source = ctx.ui;
444
+ const originalCustom = source.custom.bind(source);
445
+ const ui = Object.create(source);
446
+ ui.custom = ((factory, options) => {
447
+ if (options?.overlay)
448
+ return session.mount(factory);
449
+ return originalCustom(factory, options).finally(() => session.restoreFocus());
450
+ });
451
+ return Object.create(ctx, {
452
+ ui: { value: ui, writable: true, enumerable: true, configurable: true },
453
+ });
454
+ }
455
+ export async function withDialogSession(ctx, run) {
456
+ if (dialogScopes.has(ctx)) {
457
+ await run(ctx);
458
+ return;
459
+ }
460
+ let failure;
461
+ let failed = false;
462
+ let session;
463
+ try {
464
+ await ctx.ui.custom((host, theme, keys, done) => {
465
+ session = new DialogSession(host, theme, keys, done);
466
+ const scoped = scopeDialogContext(ctx, session);
467
+ dialogScopes.add(scoped);
468
+ const task = Promise.resolve().then(() => run(scoped));
469
+ void task.then(() => {
470
+ try {
471
+ session?.close();
472
+ }
473
+ catch (error) {
474
+ if (!failed) {
475
+ failed = true;
476
+ failure = error;
477
+ }
478
+ }
479
+ }, (error) => {
480
+ failed = true;
481
+ failure = error;
482
+ try {
483
+ session?.close();
484
+ }
485
+ catch (closeError) {
486
+ failure ??= closeError;
487
+ }
488
+ });
489
+ return session;
490
+ }, DIALOG_OPTIONS);
491
+ }
492
+ catch (error) {
493
+ try {
494
+ session?.close();
495
+ }
496
+ catch {
497
+ }
498
+ if (!failed) {
499
+ failed = true;
500
+ failure = error;
501
+ }
502
+ }
503
+ if (failed)
504
+ throw failure;
505
+ }
@@ -0,0 +1,191 @@
1
+ import { CURSOR_MARKER, getKeybindings, Key, matchesKey, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui";
2
+ import { DIALOG_OPTIONS, dialogHeight, dialogText, frameDialog, } from "./dialog.js";
3
+ const TITLE = "Import agents";
4
+ const DETAIL_LINE_CAP = 3;
5
+ const FOOTER = "Space toggle · Enter import (empty skip) · Esc cancel · Ctrl+A all · ↑↓ navigate · PgUp/PgDn · Home/End";
6
+ function agentText(text) {
7
+ return dialogText(text).split(CURSOR_MARKER).join("").replaceAll("\x1b", " ");
8
+ }
9
+ function clipVisible(text, columns) {
10
+ if (columns <= 0 || !text)
11
+ return "";
12
+ if (visibleWidth(text) <= columns)
13
+ return text;
14
+ const clipped = truncateToWidth(text, columns, "").replaceAll("\x1b[0m", "");
15
+ return clipped && text.startsWith(clipped) ? clipped : "";
16
+ }
17
+ function wrapText(text, columns) {
18
+ const clean = agentText(text);
19
+ if (!clean || columns <= 0)
20
+ return [];
21
+ const lines = [];
22
+ let rest = clean;
23
+ while (rest.length > 0) {
24
+ const chunk = clipVisible(rest, columns);
25
+ if (!chunk) {
26
+ rest = rest.slice(1);
27
+ continue;
28
+ }
29
+ lines.push(chunk);
30
+ if (chunk.length >= rest.length)
31
+ break;
32
+ rest = rest.slice(chunk.length);
33
+ }
34
+ return lines;
35
+ }
36
+ export class ImportPicker {
37
+ host;
38
+ theme;
39
+ items;
40
+ done;
41
+ cursor = 0;
42
+ viewport = 1;
43
+ checked = new Set();
44
+ constructor(host, theme, items, done) {
45
+ this.host = host;
46
+ this.theme = theme;
47
+ this.items = items;
48
+ this.done = done;
49
+ }
50
+ getSelectedIds() {
51
+ const seen = new Set();
52
+ const ids = [];
53
+ for (const item of this.items) {
54
+ if (!this.checked.has(item.id) || seen.has(item.id))
55
+ continue;
56
+ seen.add(item.id);
57
+ ids.push(item.id);
58
+ }
59
+ return ids;
60
+ }
61
+ getCursorIndex() {
62
+ return this.cursor;
63
+ }
64
+ invalidate() { }
65
+ handleInput(data) {
66
+ const keys = getKeybindings();
67
+ if (keys.matches(data, "tui.select.cancel")) {
68
+ this.done(undefined);
69
+ return;
70
+ }
71
+ if (keys.matches(data, "tui.select.confirm")) {
72
+ this.done(this.getSelectedIds());
73
+ return;
74
+ }
75
+ if (matchesKey(data, Key.space)) {
76
+ this.toggleCursor();
77
+ this.host.requestRender();
78
+ return;
79
+ }
80
+ if (matchesKey(data, Key.ctrl("a"))) {
81
+ this.toggleAll();
82
+ this.host.requestRender();
83
+ return;
84
+ }
85
+ if (this.items.length === 0)
86
+ return;
87
+ if (keys.matches(data, "tui.select.up"))
88
+ this.move(this.cursor - 1);
89
+ else if (keys.matches(data, "tui.select.down"))
90
+ this.move(this.cursor + 1);
91
+ else if (keys.matches(data, "tui.select.pageUp") || matchesKey(data, Key.pageUp))
92
+ this.move(this.cursor - this.viewport);
93
+ else if (keys.matches(data, "tui.select.pageDown") || matchesKey(data, Key.pageDown))
94
+ this.move(this.cursor + this.viewport);
95
+ else if (matchesKey(data, Key.home))
96
+ this.move(0);
97
+ else if (matchesKey(data, Key.end))
98
+ this.move(this.items.length - 1);
99
+ }
100
+ render(width) {
101
+ const height = dialogHeight(this.host);
102
+ const budget = Math.max(0, height - 4);
103
+ const columns = Math.max(1, width - 4);
104
+ const current = this.items[this.cursor];
105
+ const detail = current ? wrapText(current.detail, columns) : [];
106
+ const headerCount = budget > 0 ? 1 : 0;
107
+ let detailCount = Math.min(detail.length, DETAIL_LINE_CAP, Math.floor(budget / 3));
108
+ if (this.items.length > 0)
109
+ detailCount = Math.min(detailCount, Math.max(0, budget - headerCount - 1));
110
+ const room = Math.max(0, budget - headerCount - detailCount);
111
+ const gap = detailCount > 0 && room >= 3 ? 1 : 0;
112
+ const listCount = Math.max(0, room - gap);
113
+ this.viewport = Math.max(1, listCount);
114
+ const start = this.windowStart(listCount);
115
+ const shown = Math.min(listCount, Math.max(0, this.items.length - start));
116
+ const body = [];
117
+ if (headerCount)
118
+ body.push(this.countLine(start, shown));
119
+ if (this.items.length === 0) {
120
+ if (listCount > 0)
121
+ body.push(this.theme.fg("muted", " No external agents to import"));
122
+ }
123
+ else {
124
+ const rows = this.items.slice(start, start + listCount);
125
+ for (let offset = 0; offset < rows.length; offset++)
126
+ body.push(this.row(rows[offset], start + offset === this.cursor));
127
+ }
128
+ if (gap)
129
+ body.push("");
130
+ for (const line of detail.slice(0, detailCount))
131
+ body.push(this.theme.fg("muted", ` ${line}`));
132
+ return frameDialog(this.theme, width, height, TITLE, body, FOOTER);
133
+ }
134
+ countLine(start, shown) {
135
+ const position = this.items.length ? this.cursor + 1 : 0;
136
+ return this.theme.fg("dim", ` ${this.scrollHint(start, shown)}${this.checked.size} selected · ${position}/${this.items.length}`);
137
+ }
138
+ scrollHint(start, shown) {
139
+ if (this.items.length === 0)
140
+ return "";
141
+ const above = shown > 0 ? start : this.cursor;
142
+ const below = shown > 0
143
+ ? Math.max(0, this.items.length - (start + shown))
144
+ : Math.max(0, this.items.length - this.cursor - 1);
145
+ if (above <= 0 && below <= 0)
146
+ return "";
147
+ const parts = [];
148
+ if (above > 0)
149
+ parts.push(`▲${above}`);
150
+ if (below > 0)
151
+ parts.push(`▼${below}`);
152
+ return `${parts.join(" ")} `;
153
+ }
154
+ row(item, active) {
155
+ const mark = this.checked.has(item.id) ? "x" : " ";
156
+ const text = `${active ? "›" : " "}[${mark}] ${agentText(item.label)}`;
157
+ return active ? this.theme.fg("accent", text) : text;
158
+ }
159
+ windowStart(listCount) {
160
+ if (listCount <= 0 || this.items.length === 0)
161
+ return 0;
162
+ return Math.max(0, Math.min(this.cursor - listCount + 1, this.items.length - listCount));
163
+ }
164
+ move(next) {
165
+ if (this.items.length === 0)
166
+ return;
167
+ this.cursor = Math.max(0, Math.min(this.items.length - 1, next));
168
+ this.host.requestRender();
169
+ }
170
+ toggleCursor() {
171
+ const item = this.items[this.cursor];
172
+ if (!item)
173
+ return;
174
+ if (this.checked.has(item.id))
175
+ this.checked.delete(item.id);
176
+ else
177
+ this.checked.add(item.id);
178
+ }
179
+ toggleAll() {
180
+ const all = this.items.length > 0 && this.items.every((item) => this.checked.has(item.id));
181
+ if (all) {
182
+ this.checked.clear();
183
+ return;
184
+ }
185
+ for (const item of this.items)
186
+ this.checked.add(item.id);
187
+ }
188
+ }
189
+ export function selectImportAgents(ctx, items) {
190
+ return ctx.ui.custom((host, theme, _keys, done) => new ImportPicker(host, theme, items, done), DIALOG_OPTIONS);
191
+ }