pi-suite 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/README.zh-CN.md +101 -0
- package/package.json +63 -4
- package/skills/pi-suite-jobs/SKILL.md +76 -0
- package/skills/pi-suite-workflow/SKILL.md +114 -0
- package/src/agents/catalog.ts +80 -0
- package/src/agents/child.ts +79 -0
- package/src/agents/commands.ts +17 -0
- package/src/agents/defaults.ts +78 -0
- package/src/agents/history.ts +112 -0
- package/src/agents/index.ts +211 -0
- package/src/agents/manager.ts +438 -0
- package/src/agents/mentions/clone.ts +51 -0
- package/src/agents/mentions/grammar.ts +64 -0
- package/src/agents/mentions/index.ts +76 -0
- package/src/agents/mentions/provider.ts +79 -0
- package/src/agents/model-editor.ts +95 -0
- package/src/agents/models.ts +43 -0
- package/src/agents/output/schema.ts +101 -0
- package/src/agents/output/tool.ts +98 -0
- package/src/agents/parent.ts +13 -0
- package/src/agents/questions.ts +63 -0
- package/src/agents/records.ts +90 -0
- package/src/agents/registry.ts +20 -0
- package/src/agents/render.ts +85 -0
- package/src/agents/resources/context.ts +48 -0
- package/src/agents/resources/loader.ts +86 -0
- package/src/agents/resources/memory.ts +67 -0
- package/src/agents/resources/packages.ts +96 -0
- package/src/agents/resources/paths.ts +8 -0
- package/src/agents/resources/prompts.ts +11 -0
- package/src/agents/resources/scope.ts +147 -0
- package/src/agents/resources/selectors.ts +186 -0
- package/src/agents/retry.ts +20 -0
- package/src/agents/rpc/handlers.ts +62 -0
- package/src/agents/rpc/index.ts +73 -0
- package/src/agents/rpc/options.ts +44 -0
- package/src/agents/run-groups.ts +16 -0
- package/src/agents/runner.ts +131 -0
- package/src/agents/runtime.ts +40 -0
- package/src/agents/schedules/index.ts +136 -0
- package/src/agents/schedules/menu.ts +38 -0
- package/src/agents/schedules/parse.ts +42 -0
- package/src/agents/schedules/store.ts +78 -0
- package/src/agents/schema.ts +5 -0
- package/src/agents/session.ts +29 -0
- package/src/agents/tools.ts +177 -0
- package/src/agents/types.ts +87 -0
- package/src/agents/ui/index.ts +42 -0
- package/src/agents/ui/runs.ts +122 -0
- package/src/agents/ui/types.ts +91 -0
- package/src/agents/viewer-info.ts +36 -0
- package/src/agents/viewer.ts +160 -0
- package/src/agents/workflow/collisions.ts +124 -0
- package/src/agents/workflow/entry.ts +93 -0
- package/src/agents/workflow/host.ts +119 -0
- package/src/agents/workflow/index.ts +100 -0
- package/src/agents/workflow/journal.ts +147 -0
- package/src/agents/workflow/literal.ts +57 -0
- package/src/agents/workflow/manager.ts +169 -0
- package/src/agents/workflow/meta.ts +323 -0
- package/src/agents/workflow/progress/format.ts +184 -0
- package/src/agents/workflow/progress/index.ts +3 -0
- package/src/agents/workflow/progress/model.ts +224 -0
- package/src/agents/workflow/progress/types.ts +144 -0
- package/src/agents/workflow/render.ts +46 -0
- package/src/agents/workflow/runtime/helpers.ts +236 -0
- package/src/agents/workflow/runtime/index.ts +3 -0
- package/src/agents/workflow/runtime/run.ts +646 -0
- package/src/agents/workflow/runtime/types.ts +273 -0
- package/src/agents/workflow/saved.ts +74 -0
- package/src/agents/workflow/store.ts +23 -0
- package/src/agents/workflow/task.ts +277 -0
- package/src/agents/workflow/tool-description.ts +32 -0
- package/src/agents/workflow/tools.ts +66 -0
- package/src/agents/workflow/ui/menu.ts +144 -0
- package/src/agents/workflow/ui/progress.ts +91 -0
- package/src/agents/workflow/worker/bootstrap.ts +316 -0
- package/src/agents/workflow/worker/flow.ts +218 -0
- package/src/agents/workflow/worker/index.ts +7 -0
- package/src/agents/workflow/worker/scope.ts +215 -0
- package/src/ask/.gitkeep +0 -0
- package/src/ask/form.ts +67 -0
- package/src/ask/index.ts +73 -0
- package/src/ask/keys.ts +32 -0
- package/src/ask/layout.ts +78 -0
- package/src/ask/queue.ts +40 -0
- package/src/ask/render.ts +62 -0
- package/src/ask/result.ts +56 -0
- package/src/ask/schema.ts +67 -0
- package/src/ask/tool-render.ts +49 -0
- package/src/ask/view.ts +406 -0
- package/src/goal/.gitkeep +0 -0
- package/src/goal/activity.ts +50 -0
- package/src/goal/commands.ts +75 -0
- package/src/goal/context.ts +36 -0
- package/src/goal/index.ts +38 -0
- package/src/goal/manager.ts +386 -0
- package/src/goal/presentation.ts +15 -0
- package/src/goal/render.ts +36 -0
- package/src/goal/snapshot.ts +78 -0
- package/src/goal/state.ts +39 -0
- package/src/goal/store.ts +59 -0
- package/src/goal/tools.ts +59 -0
- package/src/goal/wait.ts +39 -0
- package/src/index.ts +20 -0
- package/src/jobs/backends/linux-tree.ts +87 -0
- package/src/jobs/backends/pipe.ts +74 -0
- package/src/jobs/backends/process.ts +79 -0
- package/src/jobs/backends/pty-job.ts +45 -0
- package/src/jobs/backends/pty.ts +502 -0
- package/src/jobs/backends/windows-tree.ts +289 -0
- package/src/jobs/commands.ts +7 -0
- package/src/jobs/control.ts +13 -0
- package/src/jobs/index.ts +331 -0
- package/src/jobs/launch/config.ts +26 -0
- package/src/jobs/launch/name.ts +16 -0
- package/src/jobs/launch/presets.ts +61 -0
- package/src/jobs/log-viewer.ts +147 -0
- package/src/jobs/manager.ts +507 -0
- package/src/jobs/monitors/compile.ts +101 -0
- package/src/jobs/monitors/hands-free.ts +108 -0
- package/src/jobs/monitors/runtime.ts +165 -0
- package/src/jobs/output.ts +54 -0
- package/src/jobs/query.ts +62 -0
- package/src/jobs/render.ts +103 -0
- package/src/jobs/runtime.ts +89 -0
- package/src/jobs/state.ts +25 -0
- package/src/jobs/store.ts +168 -0
- package/src/jobs/terminal/keys.ts +292 -0
- package/src/jobs/terminal/protocol.ts +37 -0
- package/src/jobs/terminal/read.ts +131 -0
- package/src/jobs/terminal/render.ts +70 -0
- package/src/jobs/terminal/screen.ts +92 -0
- package/src/jobs/terminal/session.ts +100 -0
- package/src/jobs/terminal/shell.ts +22 -0
- package/src/jobs/terminal/snapshot.ts +8 -0
- package/src/jobs/terminal/visible-text.ts +53 -0
- package/src/jobs/tools.ts +203 -0
- package/src/jobs/types.ts +60 -0
- package/src/jobs/viewer/component.ts +209 -0
- package/src/jobs/viewer/metadata.ts +9 -0
- package/src/jobs/viewer.ts +149 -0
- package/src/jobs/workspace.ts +31 -0
- package/src/runtime/.gitkeep +0 -0
- package/src/runtime/binding.ts +26 -0
- package/src/runtime/cli-prompt.ts +24 -0
- package/src/runtime/clipboard.ts +16 -0
- package/src/runtime/config-edit.ts +31 -0
- package/src/runtime/config-fields.ts +65 -0
- package/src/runtime/config.ts +111 -0
- package/src/runtime/errors.ts +11 -0
- package/src/runtime/json-store.ts +156 -0
- package/src/runtime/notification-render.ts +35 -0
- package/src/runtime/notifications.ts +98 -0
- package/src/runtime/owner.ts +54 -0
- package/src/runtime/read.ts +200 -0
- package/src/runtime/renderers.ts +50 -0
- package/src/runtime/responses/index.ts +108 -0
- package/src/runtime/responses/payload.ts +78 -0
- package/src/runtime/settings/index.ts +24 -0
- package/src/runtime/settings/view.ts +84 -0
- package/src/runtime/suite.ts +192 -0
- package/src/runtime/text.ts +6 -0
- package/src/runtime/tools.ts +131 -0
- package/src/runtime/wait-render.ts +33 -0
- package/src/runtime/wait.ts +134 -0
- package/src/tasks/commands.ts +41 -0
- package/src/tasks/index.ts +305 -0
- package/src/tasks/model.ts +152 -0
- package/src/tasks/presentation.ts +40 -0
- package/src/tasks/query.ts +38 -0
- package/src/tasks/render.ts +54 -0
- package/src/tasks/schema.ts +25 -0
- package/src/tasks/store.ts +164 -0
- package/src/tasks/tools.ts +69 -0
- package/src/tasks/types.ts +61 -0
- package/src/tasks/viewer.ts +68 -0
- package/src/ui/.gitkeep +0 -0
- package/src/ui/actions.ts +50 -0
- package/src/ui/browser-chrome.ts +175 -0
- package/src/ui/browser.ts +292 -0
- package/src/ui/details.ts +111 -0
- package/src/ui/dock/line.ts +14 -0
- package/src/ui/dock/rows.ts +78 -0
- package/src/ui/dock.ts +224 -0
- package/src/ui/format.ts +25 -0
- package/src/ui/frame.ts +8 -0
- package/src/ui/inline-input.ts +98 -0
- package/src/ui/reading.ts +105 -0
- package/src/ui/rendering/builtin-command.ts +34 -0
- package/src/ui/rendering/command.ts +60 -0
- package/src/ui/rendering/read-page.ts +15 -0
- package/src/ui/rendering/shell/bash.ts +281 -0
- package/src/ui/rendering/shell/index.ts +24 -0
- package/src/ui/rendering/shell/powershell.ts +155 -0
- package/src/ui/rendering/shell/spans.ts +28 -0
- package/src/ui/scroll.ts +111 -0
- package/src/ui/select.ts +67 -0
- package/src/ui/status.ts +67 -0
- package/src/ui/structured-details.ts +41 -0
- package/src/ui/terminal.ts +137 -0
- package/src/ui/ticker.ts +18 -0
- package/src/ui/tool-render.ts +152 -0
- package/src/ui/transcript.ts +140 -0
- package/src/ui/viewer/agent-information.ts +34 -0
- package/src/ui/viewer/editor.ts +18 -0
- package/src/ui/viewer/navigation.ts +25 -0
- package/themes/oh-my-pi.json +95 -0
- package/third-party/UPSTREAM.md +88 -0
- package/third-party/licenses/.gitkeep +0 -0
- package/third-party/licenses/oh-my-pi.txt +23 -0
- package/third-party/licenses/pi-ask-user.txt +21 -0
- package/third-party/licenses/pi-background-jobs.txt +21 -0
- package/third-party/licenses/pi-goal.txt +21 -0
- package/third-party/licenses/pi-interactive-shell.txt +25 -0
- package/third-party/licenses/pi-subagents.txt +21 -0
- package/third-party/licenses/pi-tasks.txt +21 -0
- package/third-party/sources.json +111 -0
package/src/ui/dock.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import type { Component, TUI } from "@earendil-works/pi-tui";
|
|
2
|
+
import { isKeyRelease, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { dockWindow } from './dock/rows.ts';
|
|
5
|
+
import { executionRow } from './dock/line.ts';
|
|
6
|
+
import { displayText, selectedRow, type DisplayText } from './browser-chrome.ts';
|
|
7
|
+
|
|
8
|
+
const sourceOrder = ['goal', 'tasks', 'agents', 'jobs', 'workflows'];
|
|
9
|
+
|
|
10
|
+
export interface DockRow {
|
|
11
|
+
id: string; text: string; priority: number; suffix?: DisplayText; parentId?: string; selectable?: boolean;
|
|
12
|
+
/** Less detailed suffixes, in domain-defined omission order; never change the object's identity. */
|
|
13
|
+
compactSuffixes?: DisplayText[];
|
|
14
|
+
/**
|
|
15
|
+
* Marks the source's root tail row: the number of root objects the source already left out.
|
|
16
|
+
* The Dock window adds the roots it trims, renders `… N more <unit>` and drops the row at zero.
|
|
17
|
+
* Its priority sets which rows outrank the reservation; rows below it share the remaining height.
|
|
18
|
+
* Only for sources without generated gap hints, which would count trimmed roots twice.
|
|
19
|
+
*/
|
|
20
|
+
omitted?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface DockSource {
|
|
23
|
+
title: string;
|
|
24
|
+
/** Active selected row in this source, if any; sources can expand around it. */
|
|
25
|
+
rows: (selectedId?: string) => DockRow[];
|
|
26
|
+
/** Sources with their own overflow rows can opt out of generated gap hints. */
|
|
27
|
+
gapHints?: boolean;
|
|
28
|
+
summary?: () => string;
|
|
29
|
+
subtitle?: () => string;
|
|
30
|
+
aside?: () => DisplayText;
|
|
31
|
+
footer?: () => string;
|
|
32
|
+
progress?: () => number;
|
|
33
|
+
open?: (rowId: string, ctx: ExtensionContext) => void | Promise<void>;
|
|
34
|
+
/** Rows stay selectable, but Enter only views them; the hint says `Enter view`. */
|
|
35
|
+
readOnly?: boolean;
|
|
36
|
+
}
|
|
37
|
+
type Section = { id: string; source: DockSource; rows: DockRow[] };
|
|
38
|
+
type Choice = { section: Section; row: DockRow };
|
|
39
|
+
export function heightBudget(rows: number, maxRows = 12, statusRow = false): number {
|
|
40
|
+
// Native layout adds a blank widget row, a three-row editor and a 2–3 row footer.
|
|
41
|
+
return Math.max(0, Math.min(maxRows, Math.floor(rows / 2) - 1 - 3 - 2 - Number(statusRow)));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class Dock implements Component {
|
|
45
|
+
private sources = new Map<string, DockSource>();
|
|
46
|
+
private tui?: TUI;
|
|
47
|
+
private theme?: Theme;
|
|
48
|
+
private maxRows = 12;
|
|
49
|
+
private statusRow = false;
|
|
50
|
+
private ask = false;
|
|
51
|
+
private detail = false;
|
|
52
|
+
private context?: ExtensionContext;
|
|
53
|
+
private unsubscribe?: () => void;
|
|
54
|
+
private active = false;
|
|
55
|
+
private selection?: { sourceId: string; rowId: string; index: number };
|
|
56
|
+
|
|
57
|
+
bind(ctx: ExtensionContext, maxRows: number): void {
|
|
58
|
+
this.detach();
|
|
59
|
+
this.maxRows = maxRows;
|
|
60
|
+
if (ctx.mode !== "tui") return;
|
|
61
|
+
this.context = ctx;
|
|
62
|
+
ctx.ui.setWidget("pi-suite:dock", (tui, theme) => { this.tui = tui; this.theme = theme; return this; });
|
|
63
|
+
this.unsubscribe = ctx.ui.onTerminalInput(data => this.handleKey(data, ctx));
|
|
64
|
+
}
|
|
65
|
+
detach(ctx = this.context): void {
|
|
66
|
+
this.unsubscribe?.(); this.unsubscribe = undefined;
|
|
67
|
+
this.context = undefined; this.tui = undefined; this.theme = undefined;
|
|
68
|
+
this.active = false; this.selection = undefined;
|
|
69
|
+
ctx?.ui.setWidget("pi-suite:dock", undefined);
|
|
70
|
+
}
|
|
71
|
+
register(id: string, source: DockSource): void { this.sources.set(id, source); this.invalidate(); }
|
|
72
|
+
setOpen(id: string, open: NonNullable<DockSource['open']>): void { this.sources.get(id)!.open = open; this.invalidate(); }
|
|
73
|
+
setStatusRow(value: boolean): void { this.statusRow = value; this.invalidate(); }
|
|
74
|
+
setAsk(value: boolean): void { this.ask = value; if (value) this.active = false; this.invalidate(); }
|
|
75
|
+
setDetail(value: boolean): void { this.detail = value; if (value) this.active = false; this.invalidate(); }
|
|
76
|
+
budget(rows = this.tui?.terminal.rows ?? 24): number { return heightBudget(rows, this.maxRows, this.statusRow); }
|
|
77
|
+
askBudget(rows: number): number { return Math.max(1, Math.floor(rows * 0.7) - 1 - 2 - Number(this.statusRow)); }
|
|
78
|
+
|
|
79
|
+
private sections(): Section[] {
|
|
80
|
+
const selection = this.active ? this.selection : undefined;
|
|
81
|
+
return [...this.sources].map(([id, source]) => ({ id, source, rows: source.rows(selection?.sourceId === id ? selection.rowId : undefined) }))
|
|
82
|
+
.filter(item => item.rows.length)
|
|
83
|
+
.sort((a, b) => (sourceOrder.indexOf(a.id) < 0 ? sourceOrder.length : sourceOrder.indexOf(a.id))
|
|
84
|
+
- (sourceOrder.indexOf(b.id) < 0 ? sourceOrder.length : sourceOrder.indexOf(b.id)));
|
|
85
|
+
}
|
|
86
|
+
private choices(sections: Section[]): Choice[] {
|
|
87
|
+
return sections.flatMap(section => section.source.open ? section.rows.filter(row => row.selectable !== false)
|
|
88
|
+
.map(row => ({ section, row })) : []);
|
|
89
|
+
}
|
|
90
|
+
private reconcile(choices: Choice[]): Choice | undefined {
|
|
91
|
+
if (!choices.length) { this.active = false; return; }
|
|
92
|
+
const found = choices.findIndex(item => item.section.id === this.selection?.sourceId && item.row.id === this.selection?.rowId);
|
|
93
|
+
const index = found < 0 ? Math.min(this.selection?.index ?? 0, choices.length - 1) : found;
|
|
94
|
+
const choice = choices[index];
|
|
95
|
+
// Keep identity through reordering; if it disappears, its next neighbour takes the slot.
|
|
96
|
+
this.selection = { sourceId: choice.section.id, rowId: choice.row.id, index };
|
|
97
|
+
return choice;
|
|
98
|
+
}
|
|
99
|
+
private layout(): { sections: Section[]; choices: Choice[]; choice?: Choice } {
|
|
100
|
+
let sections = this.sections();
|
|
101
|
+
if (!this.active) return { sections, choices: [] };
|
|
102
|
+
const previous = this.selection;
|
|
103
|
+
let choices = this.choices(sections), choice = this.reconcile(choices);
|
|
104
|
+
if (choice && (choice.section.id !== previous?.sourceId || choice.row.id !== previous.rowId)) {
|
|
105
|
+
// A removed row can move selection to a collapsed group. Use the new
|
|
106
|
+
// group's expanded rows before drawing or computing the next key step.
|
|
107
|
+
sections = this.sections(); choices = this.choices(sections); choice = this.reconcile(choices);
|
|
108
|
+
}
|
|
109
|
+
return { sections, choices, choice };
|
|
110
|
+
}
|
|
111
|
+
private deactivate(): void { if (this.active) { this.active = false; this.invalidate(); } }
|
|
112
|
+
private editorHasFocus(): boolean {
|
|
113
|
+
// The broad injected TUI interface omits the concrete host's public focus getter.
|
|
114
|
+
// Pluggable editors need not inherit Editor, so narrow that public structural API.
|
|
115
|
+
const focused = (this.tui as unknown as { getFocusedComponent(): { getText?: unknown; setText?: unknown; capturesViewportInput?: boolean } | null })?.getFocusedComponent();
|
|
116
|
+
// The native editor exposes this flag while autocomplete owns its navigation.
|
|
117
|
+
return focused == null || typeof focused.getText === 'function' && typeof focused.setText === 'function' && !focused.capturesViewportInput;
|
|
118
|
+
}
|
|
119
|
+
private handleKey(data: string, ctx: ExtensionContext): { consume: true } | undefined {
|
|
120
|
+
if (this.context !== ctx) return;
|
|
121
|
+
if (this.ask || this.detail || !this.editorHasFocus() || ctx.ui.getEditorText() !== '' || this.budget() === 0) {
|
|
122
|
+
this.deactivate(); return;
|
|
123
|
+
}
|
|
124
|
+
// Kitty releases also match matchesKey; held-key repeats remain useful navigation.
|
|
125
|
+
if (isKeyRelease(data)) return;
|
|
126
|
+
const entering = !this.active;
|
|
127
|
+
if (entering && !matchesKey(data, 'left')) return;
|
|
128
|
+
this.active = true;
|
|
129
|
+
const { choices, choice } = this.layout();
|
|
130
|
+
if (!choice) return;
|
|
131
|
+
if (entering) { this.invalidate(); return { consume: true }; }
|
|
132
|
+
if (matchesKey(data, 'up') || matchesKey(data, 'down')) {
|
|
133
|
+
const index = Math.max(0, Math.min(choices.length - 1, this.selection!.index + (matchesKey(data, 'up') ? -1 : 1)));
|
|
134
|
+
const next = choices[index]; this.selection = { sourceId: next.section.id, rowId: next.row.id, index };
|
|
135
|
+
this.invalidate(); return { consume: true };
|
|
136
|
+
}
|
|
137
|
+
if (matchesKey(data, '[') || matchesKey(data, ']')) {
|
|
138
|
+
const sections = [...new Set(choices.map(item => item.section.id))];
|
|
139
|
+
const sectionId = sections[(sections.indexOf(choice.section.id) + (matchesKey(data, '[') ? -1 : 1) + sections.length) % sections.length];
|
|
140
|
+
const index = choices.findIndex(item => item.section.id === sectionId), next = choices[index];
|
|
141
|
+
this.selection = {sourceId: sectionId, rowId: next.row.id, index};
|
|
142
|
+
this.invalidate(); return {consume: true};
|
|
143
|
+
}
|
|
144
|
+
if (matchesKey(data, 'enter')) {
|
|
145
|
+
this.deactivate();
|
|
146
|
+
// Input listeners cannot await a reader. Report failures at this user boundary,
|
|
147
|
+
// and fence late imports/readers against a replaced SessionBinding context.
|
|
148
|
+
void Promise.resolve().then(() => this.context === ctx ? choice.section.source.open!(choice.row.id, ctx) : undefined)
|
|
149
|
+
.catch(error => { if (this.context === ctx) ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error'); });
|
|
150
|
+
return { consume: true };
|
|
151
|
+
}
|
|
152
|
+
const back = matchesKey(data, 'escape') || matchesKey(data, 'right');
|
|
153
|
+
this.deactivate();
|
|
154
|
+
return back ? { consume: true } : undefined;
|
|
155
|
+
}
|
|
156
|
+
private header(source: DockSource, width: number, selecting = false, compactHint = ''): string {
|
|
157
|
+
const aside = [compactHint ? this.color('dim', compactHint) : '', displayText(source.aside?.() ?? '', this.theme, 'dim')].filter(Boolean).join(' · '), space = Math.max(0, width - visibleWidth(aside) - Number(!!aside));
|
|
158
|
+
const fullHint = `↑↓ select · [ ] section · Enter ${source.readOnly ? 'view' : 'open'} · Esc back`;
|
|
159
|
+
const label = this.title(source);
|
|
160
|
+
const hint = selecting ? (visibleWidth(label) + 2 + visibleWidth(fullHint) <= space ? fullHint : '[ ] Enter Esc') : '';
|
|
161
|
+
const title = hint ? truncateToWidth(label, Math.max(0, space - visibleWidth(hint) - 2), '…') : label;
|
|
162
|
+
return this.row({id: 'header', priority: 0, text: title + (hint ? ' ' + this.color('dim', hint)
|
|
163
|
+
: source.subtitle ? ' ' + this.color('dim', source.subtitle()) : ''), suffix: aside || undefined}, width);
|
|
164
|
+
}
|
|
165
|
+
private color(kind: 'accent' | 'dim' | 'muted' | 'borderMuted', text: string): string { return this.theme?.fg(kind, text) ?? text; }
|
|
166
|
+
private title(source: DockSource): string { return this.theme?.bold(this.color('accent', source.title)) ?? source.title; }
|
|
167
|
+
private row(row: DockRow, width: number): string {
|
|
168
|
+
return executionRow(row.text, row.suffix ?? '', row.compactSuffixes, width, this.theme);
|
|
169
|
+
}
|
|
170
|
+
private summary(source: DockSource, rows: DockRow[], width: number): string {
|
|
171
|
+
const first = [...rows].sort((a, b) => b.priority - a.priority)[0];
|
|
172
|
+
const prefix = this.title(source) + ' · ';
|
|
173
|
+
const aside = displayText(source.aside?.() ?? '', this.theme, 'dim');
|
|
174
|
+
const space = Math.max(0, width - visibleWidth(prefix) - (aside ? visibleWidth(aside) + 1 : 0));
|
|
175
|
+
const text = prefix + (source.summary ? truncateToWidth(source.summary(), space, '…') : this.row(first, space));
|
|
176
|
+
return aside ? this.row({id: 'summary', text, priority: 0, suffix: aside}, width) : text;
|
|
177
|
+
}
|
|
178
|
+
private section(source: DockSource, rows: DockRow[], limit: number, width: number, selectedId?: string): string[] {
|
|
179
|
+
const focus = rows.find(row => row.id === selectedId);
|
|
180
|
+
if (focus && limit === 1) {
|
|
181
|
+
const index = rows.indexOf(focus);
|
|
182
|
+
const counts = [index ? `↑${index}` : '', rows.length - index - 1 ? `↓${rows.length - index - 1}` : ''].filter(Boolean).join(' ');
|
|
183
|
+
const title = this.title(source), room = width;
|
|
184
|
+
const full = title + ` [ ] Enter/Esc${counts ? ` ${counts}` : ''} · `;
|
|
185
|
+
const prefix = visibleWidth(full) <= room - Math.min(8, visibleWidth(focus.text)) ? full
|
|
186
|
+
: truncateToWidth(title, Math.max(0, room - visibleWidth(` [ ] ${counts} · `) - 8)) + ` [ ] ${counts} · `;
|
|
187
|
+
return [selectedRow(truncateToWidth(prefix + this.row(focus, Math.max(0, room - visibleWidth(prefix))), width), width, this.theme, true, '')];
|
|
188
|
+
}
|
|
189
|
+
if (!focus && rows.length === 1 && source.aside?.() && limit >= 2) return [this.header(source, width), this.row(rows[0], width)];
|
|
190
|
+
if (!focus && (rows.length === 1 || limit <= 3)) return [this.summary(source, rows, width)];
|
|
191
|
+
const tail = limit >= 4 ? 1 : 0;
|
|
192
|
+
const window = dockWindow(rows, limit - 1 - tail, selectedId, source.title === 'Tasks' ? 'groups' : 'items', source.gapHints);
|
|
193
|
+
const shown = window.rows.length ? window.rows : [{id: 'summary', priority: 0, text: source.summary?.() ?? this.row(rows[0], width)}];
|
|
194
|
+
const tree = width >= 40, ratio = source.progress?.() ?? 0;
|
|
195
|
+
const branch = (text: string, index: number): string => this.color(index < Math.round((shown.length + 1) * ratio) ? 'accent' : 'borderMuted', text);
|
|
196
|
+
return [this.header(source, width, !!focus, window.compactHint),
|
|
197
|
+
...shown.map((row, index) => {
|
|
198
|
+
const selected = row.id === selectedId;
|
|
199
|
+
// Selection decorates the laid-out row; ancestry and suffix budgets never depend on focus.
|
|
200
|
+
const prefix = tree ? branch(row.parentId ? '│ ' : '├─ ', index) : '';
|
|
201
|
+
const text = row.id.startsWith('overflow:') ? this.color('muted', this.row(row, Math.max(0, width - visibleWidth(prefix))))
|
|
202
|
+
: this.row(row, Math.max(0, width - visibleWidth(prefix)));
|
|
203
|
+
return selected ? selectedRow(prefix + text, width, this.theme, true, '') : prefix + text;
|
|
204
|
+
}), ...tail ? [truncateToWidth((tree ? branch('└─────', shown.length) : '')
|
|
205
|
+
+ (source.footer?.() ? ' ' + this.color('dim', source.footer!()) : ''), width)] : []];
|
|
206
|
+
}
|
|
207
|
+
render(width: number): string[] {
|
|
208
|
+
if (this.ask || this.detail) return [];
|
|
209
|
+
const limit = this.budget();
|
|
210
|
+
if (!limit) return [];
|
|
211
|
+
const { sections: sources, choice } = this.layout();
|
|
212
|
+
// A visible Tasks section owns the idle expansion budget. Domain urgency still
|
|
213
|
+
// ranks its rows and other sections; active selection always overrides this default.
|
|
214
|
+
const preferred = choice?.section.id ?? sources.find(section => section.id === 'tasks')?.id;
|
|
215
|
+
const ranked = [...sources].sort((a, b) => Number(b.id === preferred) - Number(a.id === preferred)
|
|
216
|
+
|| Math.max(...b.rows.map(row => row.priority)) - Math.max(...a.rows.map(row => row.priority)));
|
|
217
|
+
const allowances = new Map(ranked.slice(0, limit).map(section => [section.id, 1]));
|
|
218
|
+
const recipient = ranked[0]?.id;
|
|
219
|
+
if (recipient) allowances.set(recipient, allowances.get(recipient)! + Math.max(0, limit - allowances.size));
|
|
220
|
+
return sources.flatMap(({id, source, rows}) => allowances.has(id) ? this.section(source, rows, allowances.get(id)!, width,
|
|
221
|
+
choice?.section.id === id ? choice.row.id : undefined) : []);
|
|
222
|
+
}
|
|
223
|
+
invalidate(): void { this.tui?.requestRender(); }
|
|
224
|
+
}
|
package/src/ui/format.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const pad = (value: number): string => String(value).padStart(2, '0');
|
|
2
|
+
|
|
3
|
+
/** Show only completed units so a live timer never advances early. */
|
|
4
|
+
export function elapsedText(ms: number): string {
|
|
5
|
+
const seconds = Math.floor(Math.max(0, ms) / 1000);
|
|
6
|
+
if (seconds < 60) return `${seconds}s`;
|
|
7
|
+
|
|
8
|
+
const minutes = Math.floor(seconds / 60);
|
|
9
|
+
if (minutes < 60) return `${minutes}m${pad(seconds % 60)}s`;
|
|
10
|
+
|
|
11
|
+
const hours = Math.floor(minutes / 60);
|
|
12
|
+
if (hours < 24) return `${hours}h${pad(minutes % 60)}m`;
|
|
13
|
+
|
|
14
|
+
return `${Math.floor(hours / 24)}d${pad(hours % 24)}h`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const countUnits = [[1e9, 'B'], [1e6, 'M'], [1e3, 'k']] as const;
|
|
18
|
+
|
|
19
|
+
/** Truncate to tenths so a compact count never shows tokens not yet used. */
|
|
20
|
+
export function countText(n: number): string {
|
|
21
|
+
for (const [unit, suffix] of countUnits) {
|
|
22
|
+
if (n >= unit) return `${Math.floor(n / (unit / 10)) / 10}${suffix}`;
|
|
23
|
+
}
|
|
24
|
+
return String(n);
|
|
25
|
+
}
|
package/src/ui/frame.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { DynamicBorder, type Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
|
|
3
|
+
/** Callers reserve two rows in their viewport budget and offset mouse rows by one. */
|
|
4
|
+
export function commandFrame(width: number, content: string[], theme?: Theme): string[] {
|
|
5
|
+
// Extensions supply their theme explicitly because Pi's module cache may differ.
|
|
6
|
+
const border = new DynamicBorder(text => theme ? theme.fg('border', text) : text).render(width);
|
|
7
|
+
return [...border, ...content, ...border];
|
|
8
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { getSelectListTheme, type Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Editor, Input, Key, getKeybindings, matchesKey, truncateToWidth, visibleWidth, type TUI, type TuiMouseEvent } from '@earendil-works/pi-tui';
|
|
3
|
+
import { sanitizeText } from '../runtime/text.ts';
|
|
4
|
+
import { feedback, focusLabel, keyHint } from './browser-chrome.ts';
|
|
5
|
+
import { ViewerEditor } from './viewer/editor.ts';
|
|
6
|
+
|
|
7
|
+
export interface InlineRequest { prompt: string; submit: (message: string) => Promise<string>; multiline?: boolean }
|
|
8
|
+
/** One composer owns editing and the in-flight draft for both browser and reading frames. */
|
|
9
|
+
export class InlineInput {
|
|
10
|
+
private input?: Input | ViewerEditor;
|
|
11
|
+
private request?: InlineRequest;
|
|
12
|
+
private sending = false;
|
|
13
|
+
private hidden = false;
|
|
14
|
+
private notice?: {text: string; error: boolean};
|
|
15
|
+
private disposed = false;
|
|
16
|
+
private editorRows = 0;
|
|
17
|
+
constructor(private refresh: () => void, private theme?: Theme, private tui?: TUI, private keys = getKeybindings()) {}
|
|
18
|
+
get active(): boolean { return !this.hidden && (Boolean(this.input) || this.sending); }
|
|
19
|
+
get multiline(): boolean { return this.input instanceof Editor; }
|
|
20
|
+
set focused(value: boolean) { if (this.input) this.input.focused = value && !this.sending; }
|
|
21
|
+
open(request: InlineRequest): void {
|
|
22
|
+
this.hidden = false;
|
|
23
|
+
// Reopening during an already submitted request only shows that request; it cannot send twice.
|
|
24
|
+
if (this.sending) { this.refresh(); return; }
|
|
25
|
+
this.notice = undefined; this.request = request;
|
|
26
|
+
if (request.multiline) {
|
|
27
|
+
const editor = new ViewerEditor(this.tui!, {borderColor: text => this.theme?.fg(this.input?.focused ? 'accent' : 'borderMuted', text) ?? text, selectList: getSelectListTheme()});
|
|
28
|
+
editor.disableSubmit = true;
|
|
29
|
+
this.input = editor;
|
|
30
|
+
} else {
|
|
31
|
+
const input = new Input({prompt: sanitizeText(request.prompt).replace(/[\r\n\t]/g, ' ')});
|
|
32
|
+
input.onSubmit = value => this.submit(value);
|
|
33
|
+
this.input = input;
|
|
34
|
+
}
|
|
35
|
+
this.input.focused = true; this.refresh();
|
|
36
|
+
}
|
|
37
|
+
private submit(value: string): void {
|
|
38
|
+
const message = this.request?.multiline ? value : value.trim();
|
|
39
|
+
if (!message.trim()) { this.input = undefined; this.refresh(); return; }
|
|
40
|
+
this.sending = true; this.focused = false;
|
|
41
|
+
// Keep the native editor, its cursor and undo stack until success. A rejected run/IO
|
|
42
|
+
// request is a user-visible retry path, not permission to silently discard the draft.
|
|
43
|
+
void this.request!.submit(message).then(text => {
|
|
44
|
+
this.input = undefined; this.notice = {text, error: false};
|
|
45
|
+
}, error => {
|
|
46
|
+
this.notice = {text: error instanceof Error ? error.message : String(error), error: true};
|
|
47
|
+
}).finally(() => {
|
|
48
|
+
this.sending = false; this.focused = true;
|
|
49
|
+
if (!this.disposed) this.refresh();
|
|
50
|
+
});
|
|
51
|
+
this.refresh();
|
|
52
|
+
}
|
|
53
|
+
handleInput(data: string): boolean {
|
|
54
|
+
this.notice = undefined;
|
|
55
|
+
if (!this.active) return false;
|
|
56
|
+
if (matchesKey(data, Key.escape)) {
|
|
57
|
+
this.hidden = true; this.input = undefined;
|
|
58
|
+
} else if (!this.sending && this.input instanceof Editor) {
|
|
59
|
+
if (this.keys.matches(data, 'tui.input.newLine')) this.input.insertTextAtCursor('\n');
|
|
60
|
+
else if (this.keys.matches(data, 'tui.input.submit')) this.submit(this.input.getExpandedText());
|
|
61
|
+
else this.input.handleInput(data);
|
|
62
|
+
} else if (!this.sending) this.input?.handleInput(data);
|
|
63
|
+
this.refresh(); return true;
|
|
64
|
+
}
|
|
65
|
+
renderRows(width: number, maxRows: number): string[] {
|
|
66
|
+
if (this.input instanceof ViewerEditor) {
|
|
67
|
+
const prompt = truncateToWidth(`${focusLabel('Input', Boolean(this.input.focused), this.theme)} ${sanitizeText(this.request!.prompt).replace(/[\r\n\t]/g, ' ')}`, width);
|
|
68
|
+
const rows = maxRows > 1 ? [prompt, ...this.input.renderWithin(width, maxRows - 1)] : this.input.renderWithin(width, 1);
|
|
69
|
+
this.editorRows = rows.length;
|
|
70
|
+
return rows;
|
|
71
|
+
}
|
|
72
|
+
return [this.render(width) ?? ''];
|
|
73
|
+
}
|
|
74
|
+
render(width: number): string | undefined {
|
|
75
|
+
if (this.input instanceof Input) return this.input.render(width)[0] ?? '';
|
|
76
|
+
const notice = this.sending ? {text: 'Sending…', error: false} : this.notice;
|
|
77
|
+
return notice && truncateToWidth(feedback(sanitizeText(notice.text).replace(/[\r\n\t]/g, ' '), notice.error, this.theme), width);
|
|
78
|
+
}
|
|
79
|
+
handleMouse(event: TuiMouseEvent): void {
|
|
80
|
+
if (this.sending) return;
|
|
81
|
+
if (this.input instanceof ViewerEditor) {
|
|
82
|
+
const promptRows = Number(this.editorRows > 1);
|
|
83
|
+
if (event.y < promptRows || event.y >= this.editorRows) return;
|
|
84
|
+
this.input.handleMouse({...event, y: event.y - promptRows + this.input.viewportStart});
|
|
85
|
+
} else if (this.input) {
|
|
86
|
+
// Native Input's mouse offset is two columns even with a custom prompt.
|
|
87
|
+
const prompt = sanitizeText(this.request!.prompt).replace(/[\r\n\t]/g, ' ');
|
|
88
|
+
this.input.handleMouse({...event, x: event.x - visibleWidth(prompt) + 2});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
help(): string {
|
|
92
|
+
const keys = (action: Parameters<typeof this.keys.getKeys>[0]) => this.keys.getKeys(action).join('/');
|
|
93
|
+
const help = [!this.sending ? keyHint(keys('tui.input.submit'), 'send', this.theme) : 'Sending…',
|
|
94
|
+
...this.multiline ? [keyHint(keys('tui.input.newLine'), 'newline', this.theme)] : [], keyHint('Esc', 'cancel', this.theme)].join(' · ');
|
|
95
|
+
return this.notice?.error ? `${feedback(sanitizeText(this.notice.text).replace(/[\r\n\t]/g, ' '), true, this.theme)} · ${help}` : help;
|
|
96
|
+
}
|
|
97
|
+
dispose(): void { this.disposed = true; }
|
|
98
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { ExtensionContext, KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { CURSOR_MARKER, truncateToWidth, type Component, type OverlayHandle, type OverlayOptions, type TUI } from '@earendil-works/pi-tui';
|
|
3
|
+
|
|
4
|
+
type ReadingComponent = Component & { dispose?(): void };
|
|
5
|
+
export type ReadingFactory<T> = (tui: TUI, theme: Theme, keys: KeybindingsManager, done: (value: T) => void) => ReadingComponent | Promise<ReadingComponent>;
|
|
6
|
+
|
|
7
|
+
type ReadingSession = { depth: number; frame?: OverlayHandle };
|
|
8
|
+
const sessions = new WeakMap<ExtensionContext, ReadingSession>();
|
|
9
|
+
const fullScreens = new WeakMap<object, number>();
|
|
10
|
+
function fullScreenLease(owner: object): () => void {
|
|
11
|
+
fullScreens.set(owner, (fullScreens.get(owner) ?? 0) + 1);
|
|
12
|
+
return () => {
|
|
13
|
+
const remaining = fullScreens.get(owner)! - 1;
|
|
14
|
+
if (remaining) fullScreens.set(owner, remaining); else fullScreens.delete(owner);
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A command owns the handoff scope, not its size: ordinary browser pages stay 90%/70%. */
|
|
19
|
+
export async function withReadingSession<T>(ctx: ExtensionContext, action: () => Promise<T>): Promise<T> {
|
|
20
|
+
let session = sessions.get(ctx);
|
|
21
|
+
if (!session) { session = {depth: 0}; sessions.set(ctx, session); }
|
|
22
|
+
session.depth++;
|
|
23
|
+
try { return await action(); }
|
|
24
|
+
finally {
|
|
25
|
+
if (--session.depth === 0) { session.frame?.hide(); sessions.delete(ctx); }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function withReadingScreen<T>(ctx: ExtensionContext, action: () => Promise<T>): Promise<T> {
|
|
29
|
+
const release = fullScreenLease(ctx);
|
|
30
|
+
try { return await withReadingSession(ctx, action); }
|
|
31
|
+
finally { release(); }
|
|
32
|
+
}
|
|
33
|
+
export const isReadingSession = (ctx: ExtensionContext): boolean => sessions.has(ctx);
|
|
34
|
+
export const isReadingScreen = (ctx: ExtensionContext): boolean => fullScreens.has(ctx);
|
|
35
|
+
const fullScreen = (tui: TUI) => tui.mode === 'fullscreen' || fullScreens.has(tui);
|
|
36
|
+
|
|
37
|
+
/** One ceiling for both the overlay and its reader prevents Pi from clipping the footer after rendering. */
|
|
38
|
+
export const readingRows = (tui: TUI): number => fullScreen(tui) ? tui.terminal.rows : Math.max(1, Math.floor(tui.terminal.rows * 0.7));
|
|
39
|
+
export function readingOverlayOptions(tui: TUI): OverlayOptions {
|
|
40
|
+
return fullScreen(tui)
|
|
41
|
+
? {anchor: 'top-left', width: '100%', maxHeight: '100%', margin: 0}
|
|
42
|
+
// Pi evaluates the custom-view options factory only on opening. Percentage values
|
|
43
|
+
// are resolved by TUI on every render, keeping the ceiling aligned after resize.
|
|
44
|
+
: {anchor: 'center', width: '90%', maxHeight: '70%', margin: 0};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Shared explicit window budget: short views must still occupy the whole cover. */
|
|
48
|
+
export function readingWindow(lines: readonly string[], height: number): string[] {
|
|
49
|
+
const rows = Math.max(0, Math.floor(height));
|
|
50
|
+
return [...lines.slice(0, rows), ...Array(Math.max(0, rows - lines.length)).fill('')];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function readingText(render: (width: number) => readonly string[]): Component {
|
|
54
|
+
return {render: width => render(width).map(line => truncateToWidth(line, width)), invalidate() {}};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Stock custom owns each live page; only Suite's already-rendered frame survives between pages. */
|
|
58
|
+
export async function openReading<T>(ctx: ExtensionContext, factory: ReadingFactory<T>): Promise<T> {
|
|
59
|
+
const session = sessions.get(ctx), previous = session?.frame;
|
|
60
|
+
let terminal: TUI, release: (() => void) | undefined;
|
|
61
|
+
try {
|
|
62
|
+
return await ctx.ui.custom<T>(async (tui, theme, keys, done) => {
|
|
63
|
+
terminal = tui;
|
|
64
|
+
if (fullScreens.has(ctx)) release = fullScreenLease(tui);
|
|
65
|
+
const options = readingOverlayOptions(tui), coversScreen = fullScreen(tui);
|
|
66
|
+
let completed = false, frame: string[] | undefined;
|
|
67
|
+
const complete = (value: T) => {
|
|
68
|
+
if (completed) return;
|
|
69
|
+
completed = true;
|
|
70
|
+
if (session && frame) {
|
|
71
|
+
const retained = frame.map(line => line.replaceAll(CURSOR_MARKER, ''));
|
|
72
|
+
const old = session.frame;
|
|
73
|
+
// Install the frozen, capturing frame BEFORE done: stock custom hides/disposes
|
|
74
|
+
// immediately and its keyboard nextTick render can precede the next factory.
|
|
75
|
+
// No component resources/callbacks survive here, only our own rendered lines.
|
|
76
|
+
session.frame = tui.showOverlay({
|
|
77
|
+
// Size belongs to the completed page, not the next page's lease. In
|
|
78
|
+
// particular, a full-screen history still covers resize while loading a list.
|
|
79
|
+
render: width => readingWindow(retained.map(line => truncateToWidth(line, width)),
|
|
80
|
+
coversScreen ? tui.terminal.rows : Math.max(1, Math.floor(tui.terminal.rows * 0.7))),
|
|
81
|
+
invalidate() {}, capturesViewportInput: true, handleInput() {},
|
|
82
|
+
}, options);
|
|
83
|
+
old?.hide();
|
|
84
|
+
}
|
|
85
|
+
done(value);
|
|
86
|
+
};
|
|
87
|
+
const component = await factory(tui, theme, keys, complete);
|
|
88
|
+
// A factory may finish before returning its component. Stock custom cannot dispose
|
|
89
|
+
// an instance it never mounted; release that instance here rather than leaking it.
|
|
90
|
+
if (completed) { component.dispose?.(); return component; }
|
|
91
|
+
const render = component.render.bind(component);
|
|
92
|
+
component.render = width => {
|
|
93
|
+
const lines = render(width);
|
|
94
|
+
frame = (fullScreen(tui) ? readingWindow(lines, readingRows(tui)) : lines).slice();
|
|
95
|
+
return frame;
|
|
96
|
+
};
|
|
97
|
+
return component;
|
|
98
|
+
}, {overlay: true, overlayOptions: () => readingOverlayOptions(terminal), onHandle: () => {
|
|
99
|
+
// onHandle runs only after the new page is constructed and mounted. Removing our
|
|
100
|
+
// raw overlay now leaves the new capturing page in place, never the primary UI.
|
|
101
|
+
previous?.hide();
|
|
102
|
+
if (session?.frame === previous && session) session.frame = undefined;
|
|
103
|
+
}});
|
|
104
|
+
} finally { release?.(); }
|
|
105
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Theme, ToolRenderers } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { Component } from '@earendil-works/pi-tui';
|
|
3
|
+
import { CodeComponent, type CodeSource, type CommandShell } from './command.ts';
|
|
4
|
+
|
|
5
|
+
type CallArgs = { command?: unknown; timeout?: number } | undefined;
|
|
6
|
+
/** The native slot is still invoked: it owns the live timer and argument diagnostics. */
|
|
7
|
+
class CommandCall implements Component {
|
|
8
|
+
native?: Component;
|
|
9
|
+
private highlighted?: CodeComponent;
|
|
10
|
+
update(args: CallArgs, shell: CommandShell, theme: Theme): void {
|
|
11
|
+
if (typeof args?.command !== 'string' || !args.command) { this.highlighted = undefined; return; }
|
|
12
|
+
const source: CodeSource = { code: args.command, language: shell, mode: 'command', theme,
|
|
13
|
+
prefix: theme.fg('toolTitle', theme.bold(shell === 'powershell' ? 'PS> ' : '$ ')),
|
|
14
|
+
suffix: args.timeout ? theme.fg('muted', ` (timeout ${args.timeout}s)`) : '' };
|
|
15
|
+
this.highlighted ??= new CodeComponent(source);
|
|
16
|
+
this.highlighted.setSource(source);
|
|
17
|
+
}
|
|
18
|
+
invalidate(): void { this.native?.invalidate(); this.highlighted?.invalidate(); }
|
|
19
|
+
render(width: number): readonly string[] { return (this.highlighted ?? this.native!).render(width); }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Decorates display only. Default shell, result slot, images, timeout/output and expansion stay native. */
|
|
23
|
+
export function builtinCommandRenderers(base: ToolRenderers, shell: CommandShell,
|
|
24
|
+
enabled: (cwd: string) => boolean): ToolRenderers {
|
|
25
|
+
// Third-party execution shells must not acquire a second frame or lose their own call composition.
|
|
26
|
+
if (base.renderShell === 'self' || !base.renderCall) return base;
|
|
27
|
+
return { ...base, renderCall(args, theme, ctx) {
|
|
28
|
+
if (!enabled(ctx.cwd)) return base.renderCall!(args, theme, ctx);
|
|
29
|
+
const component = ctx.lastComponent instanceof CommandCall ? ctx.lastComponent : new CommandCall();
|
|
30
|
+
component.native = base.renderCall!(args, theme, { ...ctx, lastComponent: component.native });
|
|
31
|
+
component.update(args as CallArgs, shell, theme);
|
|
32
|
+
return component;
|
|
33
|
+
} };
|
|
34
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { highlightCode, type Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Text, type Component } from '@earendil-works/pi-tui';
|
|
3
|
+
import { sanitizeText } from '../../runtime/text.ts';
|
|
4
|
+
import { colorCommand, commandSpans, type CommandShell } from './shell/index.ts';
|
|
5
|
+
import type { CommandSpan } from './shell/spans.ts';
|
|
6
|
+
|
|
7
|
+
export type { CommandShell } from './shell/index.ts';
|
|
8
|
+
export type CodeSource = {
|
|
9
|
+
code: string; theme: Theme;
|
|
10
|
+
/** Trusted UI chrome, not part of the source passed to the grammar. */
|
|
11
|
+
prefix?: string; suffix?: string;
|
|
12
|
+
} & ({mode?: 'code'; language: string} | {mode: 'command'; language: CommandShell});
|
|
13
|
+
|
|
14
|
+
/** One owner keeps one source/layout cache; invalidate rebuilds ANSI after a theme change. */
|
|
15
|
+
export class CodeComponent implements Component {
|
|
16
|
+
private source?: CodeSource;
|
|
17
|
+
private text?: Text;
|
|
18
|
+
private width?: number;
|
|
19
|
+
private lines?: readonly string[];
|
|
20
|
+
private palette?: string;
|
|
21
|
+
private tokens?: CommandSpan[];
|
|
22
|
+
constructor(source: CodeSource) { this.setSource(source); }
|
|
23
|
+
setSource(source: CodeSource): void {
|
|
24
|
+
const old = this.source;
|
|
25
|
+
if (old?.code === source.code && old.language === source.language && old.mode === source.mode && old.theme === source.theme &&
|
|
26
|
+
old.prefix === source.prefix && old.suffix === source.suffix) return;
|
|
27
|
+
if (old?.code !== source.code || old.language !== source.language || old.mode !== source.mode) this.tokens = undefined;
|
|
28
|
+
this.source = source;
|
|
29
|
+
this.invalidate();
|
|
30
|
+
}
|
|
31
|
+
invalidate(): void { this.text = undefined; this.lines = undefined; this.width = undefined; }
|
|
32
|
+
render(width: number): readonly string[] {
|
|
33
|
+
const source = this.source!;
|
|
34
|
+
// Pi supplies a live Theme proxy: identity alone cannot detect palette changes.
|
|
35
|
+
const palette = ['syntaxKeyword', 'syntaxString', 'syntaxVariable', 'syntaxComment', 'syntaxNumber',
|
|
36
|
+
'syntaxFunction', 'syntaxType', 'syntaxOperator', 'syntaxPunctuation', 'mdCodeBlock', 'text', 'muted']
|
|
37
|
+
.map(token => source.theme.fg(token as Parameters<Theme['fg']>[0], '')).join('');
|
|
38
|
+
if (palette !== this.palette) { this.invalidate(); this.palette = palette; }
|
|
39
|
+
if (!this.text) {
|
|
40
|
+
const code = sanitizeText(source.code);
|
|
41
|
+
let highlighted: string;
|
|
42
|
+
if (source.mode === 'command') {
|
|
43
|
+
// Keep lexical offsets independent of the theme/layout. In particular <<- needs real tabs.
|
|
44
|
+
this.tokens ??= commandSpans(code, source.language);
|
|
45
|
+
highlighted = colorCommand(code, this.tokens, source.theme);
|
|
46
|
+
} else highlighted = highlightCode(code.replace(/\t/g, ' '), source.language).join('\n');
|
|
47
|
+
this.text = new Text((source.prefix ?? '') + highlighted.replace(/\t/g, ' ') + (source.suffix ?? ''), 0, 0);
|
|
48
|
+
}
|
|
49
|
+
if (!this.lines || this.width !== width) { this.width = width; this.lines = this.text.render(width); }
|
|
50
|
+
return this.lines;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Jobs and Suite command fields always highlight; only model-tool callers apply the config switch.
|
|
55
|
+
* Keep the returned component for unchanged commands; invalidate it on theme/layout invalidation.
|
|
56
|
+
* Shell is the execution language, never guessed from command contents. No command is executed.
|
|
57
|
+
*/
|
|
58
|
+
export function commandComponent(command: string, shell: CommandShell, theme: Theme): Component {
|
|
59
|
+
return new CodeComponent({ code: command, language: shell, mode: 'command', theme });
|
|
60
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ReadPage } from '../../runtime/read.ts';
|
|
2
|
+
import type { ToolField } from '../tool-render.ts';
|
|
3
|
+
|
|
4
|
+
/** Page offsets describe the raw byte source, not the length of the rendered text. */
|
|
5
|
+
export function readPageFields(page: ReadPage & { stream: string }): ToolField[] {
|
|
6
|
+
return [
|
|
7
|
+
{ label: 'stream', value: page.stream },
|
|
8
|
+
{ label: 'offset', value: String(page.offset) },
|
|
9
|
+
{ label: 'nextOffset', value: String(page.nextOffset) },
|
|
10
|
+
{ label: 'totalBytes', value: String(page.totalBytes) },
|
|
11
|
+
{ label: 'endOfStream', value: String(page.endOfStream) },
|
|
12
|
+
...page.matches !== undefined ? [{ label: 'matches', value: String(page.matches) }] : [],
|
|
13
|
+
...page.truncated ? [{ label: 'omittedBytes', value: String(page.truncated.omittedBytes) }] : [],
|
|
14
|
+
];
|
|
15
|
+
}
|