pal-code 0.0.5
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 +169 -0
- package/SYSTEM.md +146 -0
- package/bin/pal-code.js +131 -0
- package/package.json +68 -0
- package/packages/cli/README.md +77 -0
- package/packages/cli/src/agent-panel.ts +94 -0
- package/packages/cli/src/commands/ext.ts +79 -0
- package/packages/cli/src/commands/mcp-registry.ts +136 -0
- package/packages/cli/src/commands/mcp.ts +186 -0
- package/packages/cli/src/commands.ts +153 -0
- package/packages/cli/src/components/message-box.ts +35 -0
- package/packages/cli/src/components/permission-prompt.ts +185 -0
- package/packages/cli/src/components/render-history.ts +143 -0
- package/packages/cli/src/components/run-view.ts +256 -0
- package/packages/cli/src/components/sidebar.ts +120 -0
- package/packages/cli/src/components/status-line.ts +26 -0
- package/packages/cli/src/config.ts +107 -0
- package/packages/cli/src/index.ts +1606 -0
- package/packages/cli/src/overlays/key-input.ts +167 -0
- package/packages/cli/src/overlays/model-picker.ts +106 -0
- package/packages/cli/src/overlays/session-picker.ts +168 -0
- package/packages/cli/src/overlays/wizard.ts +145 -0
- package/packages/cli/src/state.ts +133 -0
- package/packages/cli/src/theme.ts +88 -0
- package/packages/cli/src/turn.ts +266 -0
- package/packages/cli/src/utils/cost.ts +111 -0
- package/packages/cli/src/utils/format.test.ts +167 -0
- package/packages/cli/src/utils/format.ts +248 -0
- package/packages/cli/src/utils/highlight.ts +358 -0
- package/packages/cli/src/utils/permissions.ts +196 -0
- package/packages/core/src/agent/events.ts +36 -0
- package/packages/core/src/agent/fallback.test.ts +99 -0
- package/packages/core/src/agent/fallback.ts +344 -0
- package/packages/core/src/agent/index.ts +35 -0
- package/packages/core/src/agent/protocol.test.ts +136 -0
- package/packages/core/src/agent/resume-compaction.test.ts +116 -0
- package/packages/core/src/agent/roles.ts +188 -0
- package/packages/core/src/agent/run.test.ts +207 -0
- package/packages/core/src/agent/run.ts +713 -0
- package/packages/core/src/agent/scope.ts +34 -0
- package/packages/core/src/agent/todos.ts +66 -0
- package/packages/core/src/compaction.protocol.test.ts +90 -0
- package/packages/core/src/compaction.test.ts +101 -0
- package/packages/core/src/compaction.ts +243 -0
- package/packages/core/src/config.test.ts +40 -0
- package/packages/core/src/config.ts +387 -0
- package/packages/core/src/extensions.ts +178 -0
- package/packages/core/src/index.ts +157 -0
- package/packages/core/src/logger.ts +54 -0
- package/packages/core/src/provider/auth.ts +153 -0
- package/packages/core/src/provider/complete.ts +63 -0
- package/packages/core/src/provider/index.ts +6 -0
- package/packages/core/src/provider/openrouter.test.ts +59 -0
- package/packages/core/src/provider/openrouter.ts +304 -0
- package/packages/core/src/provider/pick-model.ts +43 -0
- package/packages/core/src/provider/registry.ts +222 -0
- package/packages/core/src/provider/types.ts +61 -0
- package/packages/core/src/repo-map.ts +177 -0
- package/packages/core/src/session/index.ts +2 -0
- package/packages/core/src/session/migration.test.ts +104 -0
- package/packages/core/src/session/store-v2-repair.test.ts +209 -0
- package/packages/core/src/session/store.test.ts +235 -0
- package/packages/core/src/session/store.ts +677 -0
- package/packages/core/src/session/types.ts +72 -0
- package/packages/core/src/snapshots.ts +107 -0
- package/packages/core/src/tools/definitions.ts +365 -0
- package/packages/core/src/tools/executor.test.ts +122 -0
- package/packages/core/src/tools/executor.ts +1363 -0
- package/packages/core/src/tools/index.ts +5 -0
- package/packages/core/src/tools/search.ts +201 -0
- package/scripts/postinstall.js +121 -0
- package/scripts/preinstall.js +51 -0
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PermissionPrompt — a centered modal box that appears when pal needs
|
|
3
|
+
* the user to approve a tool call.
|
|
4
|
+
*
|
|
5
|
+
* Replaces the old one-line status-bar prompt with a prominent overlay
|
|
6
|
+
* that takes up space in the main content area so the user cannot miss it.
|
|
7
|
+
*
|
|
8
|
+
* Rendering-only: reads `state.pendingPermission` live on each render.
|
|
9
|
+
* The global key handler in index.ts intercepts y/a/n/Esc and resolves
|
|
10
|
+
* the permission; this component is purely visual.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {visibleWidth} from '@earendil-works/pi-tui';
|
|
14
|
+
import type {Component} from '@earendil-works/pi-tui';
|
|
15
|
+
|
|
16
|
+
import {c} from '../theme.js';
|
|
17
|
+
import {state} from '../state.js';
|
|
18
|
+
|
|
19
|
+
/** Strip ANSI escape sequences for visible-width measurement. */
|
|
20
|
+
const ANSI_RE = /\x1b\[[0-9;]*m/g;
|
|
21
|
+
|
|
22
|
+
/** Repeat a character `n` times. */
|
|
23
|
+
const rep = (ch: string, n: number): string => ch.repeat(Math.max(0, n));
|
|
24
|
+
|
|
25
|
+
/** Visible width of a string (delegates to pi-tui's ANSI-aware helper). */
|
|
26
|
+
const vw = (s: string): number => visibleWidth(s);
|
|
27
|
+
|
|
28
|
+
export class PermissionPrompt implements Component {
|
|
29
|
+
/**
|
|
30
|
+
* Return the rendered lines, or an empty array when there is no pending
|
|
31
|
+
* permission (making the component invisible).
|
|
32
|
+
*/
|
|
33
|
+
render(width: number): string[] {
|
|
34
|
+
const perm = state.pendingPermission;
|
|
35
|
+
if (!perm) return [];
|
|
36
|
+
|
|
37
|
+
// ── Sizing ──
|
|
38
|
+
const maxBox = Math.min(60, Math.max(40, width));
|
|
39
|
+
const W = maxBox;
|
|
40
|
+
const inner = W - 2; // "│" content "│" — inner = total minus the two border chars
|
|
41
|
+
const boxColor = c.dim + c.yellow;
|
|
42
|
+
const paint = (s: string) => `${boxColor}${s}${c.reset}`;
|
|
43
|
+
|
|
44
|
+
// ── Content lines ──
|
|
45
|
+
const title = `${c.bold}${c.yellow}🔒 Permission Request${c.reset}`;
|
|
46
|
+
const summary = `${c.bold}${perm.summary}${c.reset}`;
|
|
47
|
+
const actions =
|
|
48
|
+
`${c.green}[y]${c.reset} Allow once ` +
|
|
49
|
+
`${c.cyan}[a]${c.reset} Always allow ` +
|
|
50
|
+
`${c.red}[n]${c.reset} Deny`;
|
|
51
|
+
const hint = `${c.dim}Press Esc to abort${c.reset}`;
|
|
52
|
+
|
|
53
|
+
// Wrap summary if it's wider than the inner area.
|
|
54
|
+
const summaryLines = wrapAnsi(summary, inner);
|
|
55
|
+
|
|
56
|
+
// ── Build box ──
|
|
57
|
+
const lines: string[] = [];
|
|
58
|
+
|
|
59
|
+
// Empty line above the box for breathing room
|
|
60
|
+
lines.push('');
|
|
61
|
+
|
|
62
|
+
// Top border: ┌─── 🔒 Permission Request ───────┐
|
|
63
|
+
const tagText = '🔒 Permission Request';
|
|
64
|
+
const tagVisW = vw(tagText.replace(ANSI_RE, ''));
|
|
65
|
+
const tagFull = `${c.bold}${c.yellow}${tagText}${c.reset}`;
|
|
66
|
+
const dashesBefore = Math.max(1, Math.floor((W - 2 - tagVisW) / 2));
|
|
67
|
+
const dashesAfter = Math.max(1, W - 2 - dashesBefore - tagVisW);
|
|
68
|
+
lines.push(
|
|
69
|
+
paint('┌') + rep('─', dashesBefore) + tagFull + rep('─', dashesAfter) + paint('┐'),
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
// Empty content row
|
|
73
|
+
lines.push(paint('│') + rep(' ', inner) + paint('│'));
|
|
74
|
+
|
|
75
|
+
// "pal wants to:" label
|
|
76
|
+
const label = ' pal wants to:';
|
|
77
|
+
lines.push(paint('│') + `${c.dim}${label}${c.reset}` + rep(' ', Math.max(0, inner - vw(label))) + paint('│'));
|
|
78
|
+
|
|
79
|
+
// Summary (possibly wrapped)
|
|
80
|
+
for (const sl of summaryLines) {
|
|
81
|
+
const visW = vw(sl);
|
|
82
|
+
lines.push(paint('│') + ' ' + sl + c.reset + rep(' ', Math.max(0, inner - 2 - visW)) + paint('│'));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Empty row
|
|
86
|
+
lines.push(paint('│') + rep(' ', inner) + paint('│'));
|
|
87
|
+
|
|
88
|
+
// Separator
|
|
89
|
+
lines.push(paint('│') + rep('─', inner) + paint('│'));
|
|
90
|
+
|
|
91
|
+
// Empty row
|
|
92
|
+
lines.push(paint('│') + rep(' ', inner) + paint('│'));
|
|
93
|
+
|
|
94
|
+
// Action keys
|
|
95
|
+
const actionsVisW = vw(actions.replace(ANSI_RE, ''));
|
|
96
|
+
if (actionsVisW <= inner) {
|
|
97
|
+
const leftPad = Math.floor((inner - actionsVisW) / 2);
|
|
98
|
+
const rightPad = inner - actionsVisW - leftPad;
|
|
99
|
+
lines.push(
|
|
100
|
+
paint('│') + rep(' ', leftPad) + actions + c.reset + rep(' ', rightPad) + paint('│'),
|
|
101
|
+
);
|
|
102
|
+
} else {
|
|
103
|
+
// Fallback: left-align if too wide
|
|
104
|
+
lines.push(paint('│') + ' ' + actions + c.reset + rep(' ', Math.max(0, inner - 1 - actionsVisW)) + paint('│'));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Empty row
|
|
108
|
+
lines.push(paint('│') + rep(' ', inner) + paint('│'));
|
|
109
|
+
|
|
110
|
+
// Hint
|
|
111
|
+
const hintVisW = vw(hint.replace(ANSI_RE, ''));
|
|
112
|
+
if (hintVisW <= inner) {
|
|
113
|
+
const leftPad = Math.floor((inner - hintVisW) / 2);
|
|
114
|
+
const rightPad = inner - hintVisW - leftPad;
|
|
115
|
+
lines.push(
|
|
116
|
+
paint('│') + rep(' ', leftPad) + hint + c.reset + rep(' ', rightPad) + paint('│'),
|
|
117
|
+
);
|
|
118
|
+
} else {
|
|
119
|
+
lines.push(paint('│') + ' ' + hint + c.reset + rep(' ', Math.max(0, inner - 1 - hintVisW)) + paint('│'));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Empty content row
|
|
123
|
+
lines.push(paint('│') + rep(' ', inner) + paint('│'));
|
|
124
|
+
|
|
125
|
+
// Bottom border
|
|
126
|
+
lines.push(paint('└') + rep('─', inner) + paint('┘'));
|
|
127
|
+
|
|
128
|
+
// Empty line below
|
|
129
|
+
lines.push('');
|
|
130
|
+
|
|
131
|
+
return lines;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
invalidate(): void {}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Wrap ANSI-styled text to `maxWidth` visible columns, preserving styles.
|
|
139
|
+
* Returns an array of lines.
|
|
140
|
+
*/
|
|
141
|
+
function wrapAnsi(text: string, maxWidth: number): string[] {
|
|
142
|
+
if (maxWidth <= 0) return [text];
|
|
143
|
+
|
|
144
|
+
const lines: string[] = [];
|
|
145
|
+
let current = '';
|
|
146
|
+
let currentW = 0;
|
|
147
|
+
|
|
148
|
+
// Tokenize: alternating plain text and ANSI escape sequences
|
|
149
|
+
const tokens = text.split(/(\x1b\[[0-9;]*m)/);
|
|
150
|
+
let activeStyle = '';
|
|
151
|
+
|
|
152
|
+
for (const token of tokens) {
|
|
153
|
+
if (token === '') continue;
|
|
154
|
+
|
|
155
|
+
if (ANSI_RE.test(token)) {
|
|
156
|
+
// It's an ANSI escape — update active style, append directly
|
|
157
|
+
token.replace(ANSI_RE, () => '');
|
|
158
|
+
activeStyle = token;
|
|
159
|
+
current += token;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Plain text — split on word boundaries to wrap
|
|
164
|
+
const words = token.split(/( +)/);
|
|
165
|
+
for (const word of words) {
|
|
166
|
+
if (word === '') continue;
|
|
167
|
+
const wordW = vw(word);
|
|
168
|
+
if (currentW + wordW > maxWidth && currentW > 0) {
|
|
169
|
+
// Reset style at end of line, push, start new line with style
|
|
170
|
+
lines.push(current + c.reset);
|
|
171
|
+
current = activeStyle + word;
|
|
172
|
+
currentW = wordW;
|
|
173
|
+
} else {
|
|
174
|
+
current += word;
|
|
175
|
+
currentW += wordW;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (current.length > 0) {
|
|
181
|
+
lines.push(current + c.reset);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return lines.length > 0 ? lines : [''];
|
|
185
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* renderHistory — replay a stored session transcript into the message area.
|
|
3
|
+
*
|
|
4
|
+
* Sessions are stored as an append-only, normalized log (see @pal/core's
|
|
5
|
+
* SessionStore), so resuming can show everything the user saw: user boxes,
|
|
6
|
+
* assistant answers, tool activity, and a seam marker at each compaction
|
|
7
|
+
* checkpoint. The model view is built separately; this is purely for the human.
|
|
8
|
+
*
|
|
9
|
+
* Large sessions are shown newest-first with a "show earlier" affordance rather
|
|
10
|
+
* than replaying hundreds of blocks at once.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {Container, Text, Markdown} from '@earendil-works/pi-tui';
|
|
14
|
+
import type {StoredMessage, CompactionRecord} from '@pal/core';
|
|
15
|
+
|
|
16
|
+
import {c, markdownTheme} from '../theme.js';
|
|
17
|
+
import {MessageBox} from './message-box.js';
|
|
18
|
+
import {formatMessageTimestamp} from '../utils/format.js';
|
|
19
|
+
import type {AgentRole} from '../state.js';
|
|
20
|
+
|
|
21
|
+
/** How many of the most recent messages to render initially. */
|
|
22
|
+
export const REPAINT_WINDOW = 200;
|
|
23
|
+
|
|
24
|
+
export interface RenderHistoryOptions {
|
|
25
|
+
/** Max messages to render before the "show earlier" seam. Defaults to REPAINT_WINDOW. */
|
|
26
|
+
window?: number;
|
|
27
|
+
/** Compaction checkpoints, used to draw seam markers. */
|
|
28
|
+
compactions?: CompactionRecord[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Render the transcript into `container`.
|
|
33
|
+
*
|
|
34
|
+
* The newest `window` messages are rendered. When the session is longer, a
|
|
35
|
+
* "show earlier" marker is placed at the top; `onShowEarlier` (if given) is
|
|
36
|
+
* invoked when the user activates it, and the full prefix is then rendered.
|
|
37
|
+
*/
|
|
38
|
+
export function renderHistory(
|
|
39
|
+
container: Container,
|
|
40
|
+
tui: {requestRender: () => void},
|
|
41
|
+
messages: StoredMessage[],
|
|
42
|
+
opts: RenderHistoryOptions = {},
|
|
43
|
+
): void {
|
|
44
|
+
const win = opts.window ?? REPAINT_WINDOW;
|
|
45
|
+
const hidden = Math.max(0, messages.length - win);
|
|
46
|
+
const compactions = opts.compactions ?? [];
|
|
47
|
+
|
|
48
|
+
if (hidden > 0) {
|
|
49
|
+
addShowEarlier(container, tui, messages, hidden, compactions);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
renderRange(container, messages.slice(hidden), hidden, compactions);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Render a contiguous slice of messages, drawing compaction seams. */
|
|
56
|
+
function renderRange(
|
|
57
|
+
container: Container,
|
|
58
|
+
messages: StoredMessage[],
|
|
59
|
+
seqOffset: number,
|
|
60
|
+
compactions: CompactionRecord[],
|
|
61
|
+
): void {
|
|
62
|
+
for (let i = 0; i < messages.length; i++) {
|
|
63
|
+
const seq = seqOffset + i + 1;
|
|
64
|
+
// Draw a seam before the first message that follows a checkpoint boundary.
|
|
65
|
+
for (const rec of compactions) {
|
|
66
|
+
if (rec.toSeq + 1 === seq) {
|
|
67
|
+
container.addChild(new Text(seamLine(rec), 1, 0));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
renderMessage(container, messages[i]);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Render one stored message as its static TUI representation. */
|
|
75
|
+
function renderMessage(container: Container, m: StoredMessage): void {
|
|
76
|
+
const ts = formatMessageTimestamp(m.createdAt);
|
|
77
|
+
|
|
78
|
+
if (m.role === 'user') {
|
|
79
|
+
container.addChild(new MessageBox(m.content, (m.meta.agentRole as AgentRole) ?? 'pal', ts));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (m.role === 'tool') {
|
|
84
|
+
const icon = m.meta.toolStatus === 'error' ? `${c.red}✗${c.reset}` : `${c.green}✓${c.reset}`;
|
|
85
|
+
const name = m.meta.toolName ?? 'tool';
|
|
86
|
+
const firstLine = (m.content || '').split('\n').find((l) => l.trim()) ?? '';
|
|
87
|
+
container.addChild(
|
|
88
|
+
new Text(
|
|
89
|
+
` ${icon} ${c.dim}${name}${c.reset} ${c.dim}→ ${truncate(firstLine.trim(), 80)}${c.reset}`,
|
|
90
|
+
1,
|
|
91
|
+
0,
|
|
92
|
+
),
|
|
93
|
+
);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// assistant (with or without tool calls) — render the prose it produced
|
|
98
|
+
if (m.content && m.content.trim()) {
|
|
99
|
+
container.addChild(new Markdown(m.content, 1, 0, markdownTheme));
|
|
100
|
+
}
|
|
101
|
+
if (m.toolCalls?.length) {
|
|
102
|
+
for (const tc of m.toolCalls) {
|
|
103
|
+
container.addChild(new Text(` ${c.cyan}⛭${c.reset} ${c.dim}${tc.name}${c.reset}`, 1, 0));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function seamLine(rec: CompactionRecord): string {
|
|
109
|
+
return `\n${c.dim}── context compacted · messages ${rec.fromSeq + 1}–${rec.toSeq} ──${c.reset}\n`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* A "show earlier" marker that reveals the hidden prefix when activated.
|
|
114
|
+
*
|
|
115
|
+
* pi-tui has no generic clickable Text, so the marker names the count and the
|
|
116
|
+
* caller binds a key that calls the returned reveal function.
|
|
117
|
+
*/
|
|
118
|
+
function addShowEarlier(
|
|
119
|
+
container: Container,
|
|
120
|
+
tui: {requestRender: () => void},
|
|
121
|
+
all: StoredMessage[],
|
|
122
|
+
hidden: number,
|
|
123
|
+
compactions: CompactionRecord[],
|
|
124
|
+
): void {
|
|
125
|
+
const marker = new Text(
|
|
126
|
+
`${c.cyan}↑ show earlier${c.reset} ${c.dim}(${hidden} older message${hidden === 1 ? '' : 's'}) — press ${c.reset}${c.cyan}ctrl+home${c.reset}${c.dim} to reveal${c.reset}`,
|
|
127
|
+
1,
|
|
128
|
+
0,
|
|
129
|
+
);
|
|
130
|
+
container.addChild(marker);
|
|
131
|
+
|
|
132
|
+
// Expose a reveal hook the CLI can trigger; it rebuilds the whole container
|
|
133
|
+
// with the full history so ordering stays correct.
|
|
134
|
+
(container as unknown as {revealEarlier?: () => void}).revealEarlier = () => {
|
|
135
|
+
container.clear();
|
|
136
|
+
renderRange(container, all, 0, compactions);
|
|
137
|
+
tui.requestRender();
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function truncate(s: string, n: number): string {
|
|
142
|
+
return s.length <= n ? s : `${s.slice(0, n - 1)}…`;
|
|
143
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RunView — the live, mutable block that represents one agent turn.
|
|
3
|
+
*
|
|
4
|
+
* Instead of appending a line per tool call (which buries the answer in a
|
|
5
|
+
* wall of scrollback), a RunView owns a single container: a header that ticks,
|
|
6
|
+
* one row per tool that flips spinner -> check/cross, and the streaming answer.
|
|
7
|
+
* `finish()` collapses it to a one-line summary; `expand()` re-inflates it.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {Container, Text, Markdown} from '@earendil-works/pi-tui';
|
|
11
|
+
import type {TUI} from '@earendil-works/pi-tui';
|
|
12
|
+
|
|
13
|
+
import {c, markdownTheme} from '../theme.js';
|
|
14
|
+
import {truncate} from '../utils/format.js';
|
|
15
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
16
|
+
// Live run view — one mutable block per turn instead of an append-only log
|
|
17
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
18
|
+
|
|
19
|
+
const SPIN_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
20
|
+
|
|
21
|
+
interface RunRow {
|
|
22
|
+
name: string;
|
|
23
|
+
argsSummary: string;
|
|
24
|
+
status: 'running' | 'ok' | 'error';
|
|
25
|
+
startedAt: number;
|
|
26
|
+
elapsedMs: number;
|
|
27
|
+
preview: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* UI for a single agent turn: a ticking header, one row per tool call that
|
|
32
|
+
* flips `⠋ → ✓/✗` in place, and the streaming answer. Collapses to a one-line
|
|
33
|
+
* summary when the turn ends; `ctrl+o` re-inflates it.
|
|
34
|
+
*/
|
|
35
|
+
export class RunView {
|
|
36
|
+
readonly container = new Container();
|
|
37
|
+
private readonly header = new Text('', 1, 0);
|
|
38
|
+
private readonly rows: RunRow[] = [];
|
|
39
|
+
private readonly rowIds: string[] = [];
|
|
40
|
+
private readonly rowTexts: Text[] = [];
|
|
41
|
+
private summaryText: Text | null = null;
|
|
42
|
+
/** All streaming answer blocks from every round — only the last is active. */
|
|
43
|
+
private responses: Markdown[] = [];
|
|
44
|
+
private response: Markdown | null = null;
|
|
45
|
+
/** True after finish() re-parented responses to `this.parent`. */
|
|
46
|
+
private reParented = false;
|
|
47
|
+
private roundNo = 0;
|
|
48
|
+
private maxRounds = 0;
|
|
49
|
+
private frame = 0;
|
|
50
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
51
|
+
private readonly startedAt = Date.now();
|
|
52
|
+
collapsed = false;
|
|
53
|
+
|
|
54
|
+
private streamBuffer = '';
|
|
55
|
+
|
|
56
|
+
constructor(
|
|
57
|
+
private readonly parent: Container,
|
|
58
|
+
private readonly tui: TUI,
|
|
59
|
+
private model: string,
|
|
60
|
+
) {
|
|
61
|
+
this.container.addChild(this.header);
|
|
62
|
+
this.parent.addChild(this.container);
|
|
63
|
+
this.renderHeader();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Update the displayed model (a fallback model may serve the turn). */
|
|
67
|
+
setModel(model: string): void {
|
|
68
|
+
this.model = model;
|
|
69
|
+
this.renderHeader();
|
|
70
|
+
this.tui.requestRender();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Append streamed assistant text to this round's answer block. */
|
|
74
|
+
streamText(chunk: string): void {
|
|
75
|
+
this.streamBuffer += chunk;
|
|
76
|
+
this.responseBlock().setText(this.streamBuffer);
|
|
77
|
+
this.tui.requestRender();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private renderHeader(): void {
|
|
81
|
+
const active = !this.collapsed;
|
|
82
|
+
const mark = active
|
|
83
|
+
? `${c.cyan}${SPIN_FRAMES[this.frame % SPIN_FRAMES.length]}${c.reset}`
|
|
84
|
+
: `${c.cyan}▸${c.reset}`;
|
|
85
|
+
const secs = ((Date.now() - this.startedAt) / 1000).toFixed(1);
|
|
86
|
+
const roundPart = this.maxRounds
|
|
87
|
+
? ` ${c.dim}· ${this.roundNo}/${this.maxRounds}${c.reset}`
|
|
88
|
+
: '';
|
|
89
|
+
const toolPart = this.rows.length
|
|
90
|
+
? ` ${c.dim}· ${this.rows.length} tool${this.rows.length === 1 ? '' : 's'}${c.reset}`
|
|
91
|
+
: '';
|
|
92
|
+
this.header.setText(
|
|
93
|
+
`${mark} ${c.bold}Run${c.reset} ${c.dim}${this.model} · ${secs}s${c.reset}${roundPart}${toolPart}`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private renderRow(i: number): void {
|
|
98
|
+
const r = this.rows[i];
|
|
99
|
+
const t = this.rowTexts[i];
|
|
100
|
+
if (!r || !t) return;
|
|
101
|
+
const icon =
|
|
102
|
+
r.status === 'running'
|
|
103
|
+
? `${c.cyan}${SPIN_FRAMES[this.frame % SPIN_FRAMES.length]}${c.reset}`
|
|
104
|
+
: r.status === 'ok'
|
|
105
|
+
? `${c.green}✓${c.reset}`
|
|
106
|
+
: `${c.red}✗${c.reset}`;
|
|
107
|
+
const ms =
|
|
108
|
+
r.status === 'running' ? '' : ` ${c.dim}${(r.elapsedMs / 1000).toFixed(2)}s${c.reset}`;
|
|
109
|
+
const tail = r.preview ? ` ${c.dim}→ ${r.preview}${c.reset}` : '';
|
|
110
|
+
t.setText(` ${icon} ${r.name}${c.dim}(${r.argsSummary})${c.reset}${ms}${tail}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private tick(): void {
|
|
114
|
+
this.frame++;
|
|
115
|
+
for (let i = 0; i < this.rows.length; i++) {
|
|
116
|
+
if (this.rows[i]!.status === 'running') this.renderRow(i);
|
|
117
|
+
}
|
|
118
|
+
this.renderHeader();
|
|
119
|
+
this.tui.requestRender();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
beginRound(round: number, max: number): void {
|
|
123
|
+
this.roundNo = round;
|
|
124
|
+
this.maxRounds = max;
|
|
125
|
+
// Archive the previous round's response so finish() can preserve it.
|
|
126
|
+
this.response = null;
|
|
127
|
+
this.streamBuffer = '';
|
|
128
|
+
if (!this.timer) this.timer = setInterval(() => this.tick(), 120);
|
|
129
|
+
this.renderHeader();
|
|
130
|
+
this.tui.requestRender();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The streaming answer block for the current round, created on first use. */
|
|
134
|
+
responseBlock(): Markdown {
|
|
135
|
+
if (!this.response) {
|
|
136
|
+
this.response = new Markdown('', 1, 0, markdownTheme);
|
|
137
|
+
this.responses.push(this.response);
|
|
138
|
+
this.container.addChild(this.response);
|
|
139
|
+
}
|
|
140
|
+
return this.response;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
body(): Container {
|
|
144
|
+
return this.container;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
addTool(id: string, name: string, argsSummary: string): void {
|
|
148
|
+
this.rows.push({
|
|
149
|
+
name,
|
|
150
|
+
argsSummary,
|
|
151
|
+
status: 'running',
|
|
152
|
+
startedAt: Date.now(),
|
|
153
|
+
elapsedMs: 0,
|
|
154
|
+
preview: '',
|
|
155
|
+
});
|
|
156
|
+
this.rowIds.push(id);
|
|
157
|
+
const t = new Text('', 1, 0);
|
|
158
|
+
this.rowTexts.push(t);
|
|
159
|
+
this.container.addChild(t);
|
|
160
|
+
this.renderRow(this.rows.length - 1);
|
|
161
|
+
this.renderHeader();
|
|
162
|
+
this.tui.requestRender();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
endTool(id: string, ok: boolean, content: string): void {
|
|
166
|
+
const i = this.rowIds.indexOf(id);
|
|
167
|
+
if (i < 0) return;
|
|
168
|
+
const r = this.rows[i]!;
|
|
169
|
+
if (r.status !== 'running') return;
|
|
170
|
+
r.status = ok ? 'ok' : 'error';
|
|
171
|
+
r.elapsedMs = Date.now() - r.startedAt;
|
|
172
|
+
const firstLine = (content || '').split('\n').find((l) => l.trim()) ?? '';
|
|
173
|
+
r.preview = truncate(firstLine.trim().replace(/^\s*\d+[:\s]+/, ''), 60);
|
|
174
|
+
this.renderRow(i);
|
|
175
|
+
this.renderHeader();
|
|
176
|
+
this.tui.requestRender();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Inline notice inside the run block (nudges, loop warnings). */
|
|
180
|
+
notice(text: string): void {
|
|
181
|
+
this.container.addChild(new Text(text, 1, 0));
|
|
182
|
+
this.tui.requestRender();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The user interrupted this turn — stop the spinner and mark it. */
|
|
186
|
+
aborted(): void {
|
|
187
|
+
if (this.timer) {
|
|
188
|
+
clearInterval(this.timer);
|
|
189
|
+
this.timer = null;
|
|
190
|
+
}
|
|
191
|
+
this.container.addChild(new Text(`${c.yellow} ! interrupted by user${c.reset}`, 1, 0));
|
|
192
|
+
this.tui.requestRender();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Collapse: drop the activity, keep ALL answers, leave a one-line summary. */
|
|
196
|
+
finish(keepAnswer: boolean): void {
|
|
197
|
+
if (this.timer) {
|
|
198
|
+
clearInterval(this.timer);
|
|
199
|
+
this.timer = null;
|
|
200
|
+
}
|
|
201
|
+
this.parent.removeChild(this.container);
|
|
202
|
+
this.parent.addChild(this.summary());
|
|
203
|
+
if (keepAnswer && this.responses.length > 0) {
|
|
204
|
+
// Re-parent every round's answer block so multi-round turns don't lose
|
|
205
|
+
// earlier assistant prose. They are kept in creation order (round 1, 2, …).
|
|
206
|
+
for (const resp of this.responses) {
|
|
207
|
+
this.container.removeChild(resp);
|
|
208
|
+
this.parent.addChild(resp);
|
|
209
|
+
}
|
|
210
|
+
this.reParented = true;
|
|
211
|
+
}
|
|
212
|
+
this.collapsed = true;
|
|
213
|
+
this.tui.requestRender();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private summary(): Text {
|
|
217
|
+
const secs = ((Date.now() - this.startedAt) / 1000).toFixed(1);
|
|
218
|
+
const tools = this.rows.length;
|
|
219
|
+
const failed = this.rows.filter((r) => r.status === 'error').length;
|
|
220
|
+
const bits = [`▸ Run · ${this.model} · ${secs}s`];
|
|
221
|
+
if (tools)
|
|
222
|
+
bits.push(`${tools} tool${tools === 1 ? '' : 's'}${failed ? `, ${failed} failed` : ''}`);
|
|
223
|
+
bits.push('ctrl+o to expand');
|
|
224
|
+
if (!this.summaryText) this.summaryText = new Text('', 1, 0);
|
|
225
|
+
this.summaryText.setText(` ${c.dim}${bits.join(' · ')}${c.reset}`);
|
|
226
|
+
return this.summaryText;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Re-inflate the full activity (ctrl+o), replacing the summary line. */
|
|
230
|
+
expand(): void {
|
|
231
|
+
if (!this.collapsed) return;
|
|
232
|
+
// Drop the summary — it's the collapsed stand-in for what we're restoring.
|
|
233
|
+
if (this.summaryText) {
|
|
234
|
+
this.parent.removeChild(this.summaryText);
|
|
235
|
+
this.summaryText = null;
|
|
236
|
+
}
|
|
237
|
+
// Re-insert the activity *before* the answers so the order reads
|
|
238
|
+
// activity → answers, not summary → answers → activity.
|
|
239
|
+
//
|
|
240
|
+
// Only responses that were re-parented by finish() live in `this.parent`;
|
|
241
|
+
// finish(false) left them inside `this.container`, so skip those to avoid
|
|
242
|
+
// removeChild throwing for a non-child.
|
|
243
|
+
if (this.reParented) {
|
|
244
|
+
for (const resp of this.responses) {
|
|
245
|
+
this.parent.removeChild(resp);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
this.parent.addChild(this.container);
|
|
249
|
+
for (const resp of this.responses) {
|
|
250
|
+
this.parent.addChild(resp);
|
|
251
|
+
}
|
|
252
|
+
this.reParented = false;
|
|
253
|
+
this.collapsed = false;
|
|
254
|
+
this.tui.requestRender();
|
|
255
|
+
}
|
|
256
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Right-hand sidebar: token/cost stats above the live todo list.
|
|
3
|
+
*
|
|
4
|
+
* Rendered as a pi-tui overlay anchored to the top-right of the screen.
|
|
5
|
+
* The overlay system composites it at a screen-relative position so it stays
|
|
6
|
+
* pinned while the main column scrolls underneath.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {Text} from '@earendil-works/pi-tui';
|
|
10
|
+
import type {Component} from '@earendil-works/pi-tui';
|
|
11
|
+
|
|
12
|
+
import {c} from '../theme.js';
|
|
13
|
+
import {formatTokens, formatCost, formatCacheHit} from '../utils/cost.js';
|
|
14
|
+
import {truncate} from '../utils/format.js';
|
|
15
|
+
import {state} from '../state.js';
|
|
16
|
+
|
|
17
|
+
export interface SidebarStats {
|
|
18
|
+
inputTokens: number;
|
|
19
|
+
outputTokens: number;
|
|
20
|
+
cachedTokens: number;
|
|
21
|
+
cost: number;
|
|
22
|
+
contextPct: number;
|
|
23
|
+
priced: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const TODO_ICON: Record<string, string> = {
|
|
27
|
+
completed: `${c.green}✓${c.reset}`,
|
|
28
|
+
in_progress: `${c.yellow}▸${c.reset}`,
|
|
29
|
+
cancelled: `${c.dim}✗${c.reset}`,
|
|
30
|
+
pending: `${c.dim}·${c.reset}`,
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export class Sidebar implements Component {
|
|
34
|
+
private readonly body = new Text('', 1, 0);
|
|
35
|
+
private stats: SidebarStats = {
|
|
36
|
+
inputTokens: 0,
|
|
37
|
+
outputTokens: 0,
|
|
38
|
+
cachedTokens: 0,
|
|
39
|
+
cost: 0,
|
|
40
|
+
contextPct: 0,
|
|
41
|
+
priced: false,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
setStats(stats: SidebarStats): void {
|
|
45
|
+
this.stats = stats;
|
|
46
|
+
this.refresh();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
refresh(): void {
|
|
50
|
+
const s = this.stats;
|
|
51
|
+
|
|
52
|
+
// Must match the overlay width passed to tui.showOverlay() in index.ts.
|
|
53
|
+
const w = 30;
|
|
54
|
+
|
|
55
|
+
// The same symbols the old status bar used — one stat per line, left-aligned.
|
|
56
|
+
const lines: string[] = [];
|
|
57
|
+
if (state.sessionTitle) {
|
|
58
|
+
lines.push(`${c.bold}${c.cyan}${truncate(state.sessionTitle, w - 4)}${c.reset}`, '');
|
|
59
|
+
}
|
|
60
|
+
lines.push(
|
|
61
|
+
`${c.bold}${c.green}Info${c.reset}`,
|
|
62
|
+
`↑${formatTokens(s.inputTokens)}${s.inputTokens > 0 && s.cachedTokens > 0 ? ` ${c.dim}${formatCacheHit(s.cachedTokens, s.inputTokens)}${c.reset}` : ''}`,
|
|
63
|
+
`↓${formatTokens(s.outputTokens)}`,
|
|
64
|
+
`${formatCost(s.cost)}${s.priced ? '' : `${c.dim} (unpriced)${c.reset}`}`,
|
|
65
|
+
`${s.contextPct}%`,
|
|
66
|
+
'',
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
// Extensions
|
|
70
|
+
lines.push(`${c.bold}${c.green}Extensions${c.reset}`);
|
|
71
|
+
if (state.extensions.length === 0) {
|
|
72
|
+
lines.push(`${c.dim}· none${c.reset}`);
|
|
73
|
+
} else {
|
|
74
|
+
const sorted = [...state.extensions].sort((a, b) => a.name.localeCompare(b.name));
|
|
75
|
+
for (const ext of sorted) {
|
|
76
|
+
const dot = ext.active ? `${c.green}●${c.reset}` : `${c.red}●${c.reset}`;
|
|
77
|
+
lines.push(`${dot} ${truncate(ext.name, w - 5)}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
lines.push('');
|
|
81
|
+
|
|
82
|
+
// MCP Servers
|
|
83
|
+
lines.push(`${c.bold}${c.green}MCP Servers${c.reset}`);
|
|
84
|
+
if (state.mcpServers.length === 0) {
|
|
85
|
+
lines.push(`${c.dim}· none${c.reset}`);
|
|
86
|
+
} else {
|
|
87
|
+
const sorted = [...state.mcpServers].sort((a, b) => a.name.localeCompare(b.name));
|
|
88
|
+
for (const srv of sorted) {
|
|
89
|
+
const dot = srv.status === 'connected' ? `${c.green}●${c.reset}`
|
|
90
|
+
: srv.status === 'starting' ? `${c.yellow}●${c.reset}`
|
|
91
|
+
: `${c.red}●${c.reset}`;
|
|
92
|
+
const tools = srv.toolCount > 0 ? ` ${c.dim}(${srv.toolCount} tools)${c.reset}` : '';
|
|
93
|
+
lines.push(`${dot} ${truncate(srv.name, w - 5)}${tools}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
lines.push('');
|
|
97
|
+
|
|
98
|
+
lines.push(`${c.bold}${c.green}Todos${c.reset}`);
|
|
99
|
+
|
|
100
|
+
const todos = state.currentTodos;
|
|
101
|
+
if (todos.length === 0) {
|
|
102
|
+
lines.push(`${c.dim}· none${c.reset}`);
|
|
103
|
+
} else {
|
|
104
|
+
for (const t of todos) {
|
|
105
|
+
const icon = TODO_ICON[t.status] ?? `${c.dim}·${c.reset}`;
|
|
106
|
+
lines.push(`${icon} ${truncate(t.content, w - 6)}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
this.body.setText(lines.join('\n'));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
invalidate(): void {
|
|
114
|
+
this.body.invalidate();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
render(width: number): string[] {
|
|
118
|
+
return this.body.render(width);
|
|
119
|
+
}
|
|
120
|
+
}
|