@ptkl/toolkit 0.11.0 → 0.14.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.
@@ -0,0 +1,455 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState, useEffect, useCallback, useRef } from 'react';
3
+ import { Box, Text, useApp, useInput, useStdout } from 'ink';
4
+ import TextInput from 'ink-text-input';
5
+ import { Marked } from 'marked';
6
+ import { markedTerminal } from 'marked-terminal';
7
+ // ---------------------------------------------------------------------------
8
+ // Markdown renderer
9
+ // ---------------------------------------------------------------------------
10
+ let _md = null;
11
+ function getMd() {
12
+ if (!_md) {
13
+ _md = new Marked(markedTerminal({
14
+ reflowText: true,
15
+ tab: 2,
16
+ width: Math.min(process.stdout.columns || 80, 100),
17
+ }));
18
+ }
19
+ return _md;
20
+ }
21
+ function renderMarkdown(content) {
22
+ try {
23
+ return getMd().parse(content).replace(/\n+$/, '');
24
+ }
25
+ catch {
26
+ return content;
27
+ }
28
+ }
29
+ const EMPTY_STREAM = {
30
+ active: false,
31
+ content: '',
32
+ thinking: false,
33
+ thinkingElapsed: '',
34
+ agentLabel: '',
35
+ };
36
+ const COMMAND_DEFS = [
37
+ { command: '/agent', description: 'Switch active agent' },
38
+ { command: '/thoughts', description: 'Expand last thinking output' },
39
+ { command: '/clear', description: 'Start a new conversation' },
40
+ { command: '/compact', description: 'Summarize and compress context' },
41
+ { command: '/undo', description: 'Undo last file edit' },
42
+ { command: '/cost', description: 'Show token usage' },
43
+ { command: '/files', description: 'List accessed files' },
44
+ { command: '/history', description: 'Show conversation info' },
45
+ { command: '/conversations', description: 'Browse and resume past conversations' },
46
+ { command: '/agents', description: 'List conversation participants' },
47
+ { command: '/add', description: 'Add agent to conversation', hasArgs: true },
48
+ { command: '/remove', description: 'Remove agent from conversation', hasArgs: true },
49
+ { command: '/profile', description: 'Show current profile info' },
50
+ { command: '/help', description: 'Show all commands' },
51
+ { command: '/quit', description: 'Exit the session' },
52
+ ];
53
+ // ---------------------------------------------------------------------------
54
+ // Line-count estimator
55
+ // ---------------------------------------------------------------------------
56
+ function estimateLines(msg) {
57
+ switch (msg.kind) {
58
+ case 'user': return 3;
59
+ case 'assistant': {
60
+ const lines = (msg.rendered ?? msg.content).split('\n').length;
61
+ return Math.min(lines + 3, 40);
62
+ }
63
+ case 'thinking': return 1;
64
+ case 'tool_call': return 1;
65
+ case 'tool_result': return msg.meta?.success ? 1 : 2;
66
+ case 'error': return 2;
67
+ case 'system': {
68
+ const lines = msg.content.split('\n').length;
69
+ return Math.min(lines + 1, 20);
70
+ }
71
+ default: return 2;
72
+ }
73
+ }
74
+ // Select the window of messages visible given a scroll offset (lines from bottom).
75
+ // Returns visible messages plus whether there's more content above or below.
76
+ function selectVisible(msgs, budget, skipLines) {
77
+ // Walk from the bottom, skipping `skipLines` worth of messages first
78
+ let skipped = 0;
79
+ let i = msgs.length - 1;
80
+ while (i >= 0 && skipped < skipLines) {
81
+ skipped += estimateLines(msgs[i]);
82
+ i--;
83
+ }
84
+ const canScrollDown = skipLines > 0;
85
+ // Now fill the viewport upward from position i
86
+ let used = 0;
87
+ const result = [];
88
+ while (i >= 0) {
89
+ const est = estimateLines(msgs[i]);
90
+ if (used + est > budget)
91
+ break;
92
+ result.unshift(msgs[i]);
93
+ used += est;
94
+ i--;
95
+ }
96
+ const canScrollUp = i >= 0;
97
+ return { visible: result, canScrollUp, canScrollDown };
98
+ }
99
+ // ---------------------------------------------------------------------------
100
+ // Message row components
101
+ // ---------------------------------------------------------------------------
102
+ function UserMessage({ content }) {
103
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Box, { children: [_jsx(Text, { color: "#3b82f6", children: " \u23F5 " }), _jsx(Text, { color: "#3b82f6", bold: true, children: "You" })] }), _jsxs(Text, { children: [" ", content] })] }));
104
+ }
105
+ function AssistantMessage({ rendered, agentLabel }) {
106
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Box, { children: [_jsx(Text, { color: "#f97316", children: " \u25C6 " }), _jsx(Text, { color: "#f97316", bold: true, children: agentLabel })] }), _jsxs(Text, { children: [" ", rendered] })] }));
107
+ }
108
+ function ThinkingMessage({ elapsed }) {
109
+ return (_jsxs(Box, { children: [_jsxs(Text, { dimColor: true, italic: true, children: [" \u25C7 Thought for ", elapsed, "s "] }), _jsx(Text, { dimColor: true, children: "/thoughts to expand" })] }));
110
+ }
111
+ function ToolCallMessage({ name, summary }) {
112
+ return (_jsxs(Box, { children: [_jsxs(Text, { color: "#a855f7", children: [" \u25B8 ", name] }), _jsxs(Text, { dimColor: true, children: [" ", summary] })] }));
113
+ }
114
+ function ToolResultMessage({ name, success, error }) {
115
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsx(Text, { dimColor: true, children: " " }), _jsx(Text, { color: success ? 'green' : 'red', children: success ? '✓' : '✗' }), _jsxs(Text, { dimColor: true, children: [" ", name] })] }), !success && error && _jsxs(Text, { color: "red", children: [" ", error] })] }));
116
+ }
117
+ function MessageRow({ msg }) {
118
+ switch (msg.kind) {
119
+ case 'user':
120
+ return _jsx(UserMessage, { content: msg.content });
121
+ case 'assistant':
122
+ return _jsx(AssistantMessage, { rendered: msg.rendered ?? msg.content, agentLabel: msg.meta?.name ?? 'Assistant' });
123
+ case 'thinking':
124
+ return _jsx(ThinkingMessage, { elapsed: msg.meta?.elapsed ?? '?' });
125
+ case 'tool_call':
126
+ return _jsx(ToolCallMessage, { name: msg.meta?.name ?? '', summary: msg.content });
127
+ case 'tool_result':
128
+ return _jsx(ToolResultMessage, { name: msg.meta?.name ?? '', success: msg.meta?.success ?? true, error: msg.content || undefined });
129
+ case 'error':
130
+ return _jsx(Box, { marginTop: 1, children: _jsxs(Text, { color: "red", children: [" \u2717 ", msg.content] }) });
131
+ case 'system':
132
+ return _jsx(Box, { marginTop: 1, children: _jsxs(Text, { dimColor: true, children: [" ", msg.content] }) });
133
+ default:
134
+ return null;
135
+ }
136
+ }
137
+ // ---------------------------------------------------------------------------
138
+ // Scroll indicators
139
+ // ---------------------------------------------------------------------------
140
+ function ScrollHint({ above, below }) {
141
+ if (!above && !below)
142
+ return null;
143
+ return (_jsxs(Box, { children: [above && _jsx(Text, { dimColor: true, children: " \u2191 PgUp " }), below && _jsx(Text, { dimColor: true, children: " \u2193 PgDn " }), (above || below) && _jsx(Text, { dimColor: true, children: "to scroll" })] }));
144
+ }
145
+ // ---------------------------------------------------------------------------
146
+ // Command palette
147
+ // ---------------------------------------------------------------------------
148
+ function CommandPalette({ commands, cursor }) {
149
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "#3b82f6", paddingX: 1, children: [_jsx(Text, { dimColor: true, children: " \u2191\u2193 navigate \u00B7 Tab complete \u00B7 Enter run \u00B7 Esc cancel" }), commands.map((cmd, i) => (_jsxs(Box, { children: [_jsx(Text, { color: i === cursor ? '#3b82f6' : undefined, children: i === cursor ? '❯ ' : ' ' }), _jsx(Text, { bold: i === cursor, color: i === cursor ? '#3b82f6' : undefined, children: cmd.command.padEnd(12) }), _jsxs(Text, { dimColor: true, children: [" ", cmd.description] })] }, cmd.command)))] }));
150
+ }
151
+ // ---------------------------------------------------------------------------
152
+ // Live section: streaming response
153
+ // ---------------------------------------------------------------------------
154
+ function StreamingRow({ stream, maxLines }) {
155
+ if (!stream.active)
156
+ return null;
157
+ let displayContent = stream.content;
158
+ if (displayContent) {
159
+ const lines = displayContent.split('\n');
160
+ if (lines.length > maxLines) {
161
+ displayContent = '…\n' + lines.slice(-maxLines).join('\n');
162
+ }
163
+ }
164
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Box, { children: [_jsx(Text, { color: "#f97316", children: " \u25C6 " }), _jsx(Text, { color: "#f97316", bold: true, children: stream.agentLabel || '…' })] }), stream.thinking && _jsx(Text, { dimColor: true, italic: true, children: " \u25C7 Thinking..." }), stream.thinkingElapsed && !stream.thinking && (_jsxs(Text, { dimColor: true, italic: true, children: [" \u25C7 Thought for ", stream.thinkingElapsed, "s"] })), displayContent
165
+ ? _jsxs(Text, { children: [" ", displayContent] })
166
+ : _jsx(Text, { dimColor: true, children: " \u25CF" })] }));
167
+ }
168
+ // ---------------------------------------------------------------------------
169
+ // Status bar
170
+ // ---------------------------------------------------------------------------
171
+ function StatusBar({ prompt: promptTokens, completion, agentName, isLocal, profileName, contextUsed, contextLimit }) {
172
+ const total = promptTokens + completion;
173
+ const ctxPercent = contextLimit > 0 ? Math.min(100, Math.round((contextUsed / contextLimit) * 100)) : 0;
174
+ const ctxColor = ctxPercent < 50 ? '#22c55e' : ctxPercent < 80 ? '#eab308' : '#ef4444';
175
+ const barW = 8;
176
+ const filled = Math.round(barW * ctxPercent / 100);
177
+ return (_jsxs(Box, { paddingX: 2, marginTop: 1, children: [_jsx(Text, { bold: true, color: "#f97316", children: agentName }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), contextUsed > 0 && _jsx(Text, { color: ctxColor, children: '█'.repeat(filled) }), contextUsed > 0 && _jsx(Text, { dimColor: true, children: '░'.repeat(barW - filled) }), contextUsed > 0 && _jsxs(Text, { color: ctxColor, children: [" ", ctxPercent, "%"] }), contextUsed > 0 && _jsx(Text, { dimColor: true, children: " \u00B7 " }), total > 0
178
+ ? _jsxs(Text, { dimColor: true, children: [promptTokens.toLocaleString(), " in \u00B7 ", completion.toLocaleString(), " out"] })
179
+ : _jsx(Text, { dimColor: true, children: "ready" }), _jsx(Box, { flexGrow: 1 }), _jsxs(Text, { dimColor: true, children: [profileName, " \u00B7 ", isLocal ? 'local' : 'cloud'] })] }));
180
+ }
181
+ // ---------------------------------------------------------------------------
182
+ // Input area
183
+ // ---------------------------------------------------------------------------
184
+ function InputArea({ value, onChange, onSubmit, processing, consent }) {
185
+ if (consent) {
186
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "#a855f7", paddingX: 1, children: [_jsxs(Box, { children: [_jsxs(Text, { color: "#a855f7", children: [" \u26A1 ", consent.name] }), _jsxs(Text, { dimColor: true, children: [" ", consent.summary] })] }), _jsxs(Box, { children: [_jsx(Text, { dimColor: true, children: " Run? " }), _jsx(TextInput, { value: value, onChange: onChange, onSubmit: onSubmit, placeholder: "y / n / a(lways)" })] })] }));
187
+ }
188
+ if (processing) {
189
+ return (_jsx(Box, { borderStyle: "single", borderColor: "gray", paddingX: 1, children: _jsx(Text, { dimColor: true, children: " \u00B7 processing..." }) }));
190
+ }
191
+ return (_jsxs(Box, { borderStyle: "single", borderColor: "#3b82f6", paddingX: 1, children: [_jsx(Text, { color: "#3b82f6", children: " \u276F " }), _jsx(TextInput, { value: value, onChange: onChange, onSubmit: onSubmit, placeholder: "Ask anything \u00B7 / commands \u00B7 Tab switch agent" })] }));
192
+ }
193
+ // ---------------------------------------------------------------------------
194
+ // Agent picker overlay
195
+ // ---------------------------------------------------------------------------
196
+ function AgentPickerOverlay({ agents, onSelect, onCancel }) {
197
+ const [cursor, setCursor] = useState(0);
198
+ useInput((_, key) => {
199
+ if (key.upArrow)
200
+ setCursor(i => (i - 1 + agents.length) % agents.length);
201
+ else if (key.downArrow)
202
+ setCursor(i => (i + 1) % agents.length);
203
+ else if (key.return)
204
+ onSelect(agents[cursor]);
205
+ else if (key.escape)
206
+ onCancel();
207
+ });
208
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "#f97316", paddingX: 1, paddingY: 1, marginTop: 1, children: [_jsxs(Box, { marginBottom: 1, children: [_jsx(Text, { bold: true, color: "#f97316", children: "Switch agent" }), _jsx(Text, { dimColor: true, children: " \u2191\u2193 \u00B7 Enter \u00B7 Esc" })] }), agents.map((a, i) => (_jsxs(Box, { children: [_jsx(Text, { color: i === cursor ? '#f97316' : undefined, children: i === cursor ? '❯ ' : ' ' }), _jsx(Text, { bold: i === cursor, children: a.name }), a.description && _jsxs(Text, { dimColor: true, children: [" \u2014 ", a.description] })] }, a.uuid)))] }));
209
+ }
210
+ // ---------------------------------------------------------------------------
211
+ // Conversation picker overlay
212
+ // ---------------------------------------------------------------------------
213
+ function formatRelativeTime(iso) {
214
+ const diff = Date.now() - new Date(iso).getTime();
215
+ const mins = Math.floor(diff / 60_000);
216
+ if (mins < 1)
217
+ return 'just now';
218
+ if (mins < 60)
219
+ return `${mins}m ago`;
220
+ const hrs = Math.floor(mins / 60);
221
+ if (hrs < 24)
222
+ return `${hrs}h ago`;
223
+ const days = Math.floor(hrs / 24);
224
+ return `${days}d ago`;
225
+ }
226
+ function ConversationPickerOverlay({ conversations, onSelect, onCancel }) {
227
+ const [cursor, setCursor] = useState(0);
228
+ const maxVisible = 10;
229
+ let startIdx = 0;
230
+ if (conversations.length > maxVisible) {
231
+ startIdx = Math.max(0, Math.min(cursor - Math.floor(maxVisible / 2), conversations.length - maxVisible));
232
+ }
233
+ const visible = conversations.slice(startIdx, startIdx + maxVisible);
234
+ useInput((_, key) => {
235
+ if (key.upArrow)
236
+ setCursor(i => (i - 1 + conversations.length) % conversations.length);
237
+ else if (key.downArrow)
238
+ setCursor(i => (i + 1) % conversations.length);
239
+ else if (key.return)
240
+ onSelect(conversations[cursor]);
241
+ else if (key.escape)
242
+ onCancel();
243
+ });
244
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "#3b82f6", paddingX: 1, paddingY: 1, marginTop: 1, children: [_jsxs(Box, { marginBottom: 1, children: [_jsx(Text, { bold: true, color: "#3b82f6", children: "Conversations" }), _jsx(Text, { dimColor: true, children: " \u2191\u2193 \u00B7 Enter \u00B7 Esc" })] }), visible.map((c, i) => {
245
+ const gi = startIdx + i;
246
+ return (_jsxs(Box, { children: [_jsx(Text, { color: gi === cursor ? '#3b82f6' : undefined, children: gi === cursor ? '❯ ' : ' ' }), _jsx(Text, { bold: gi === cursor, children: c.title.length > 45 ? c.title.slice(0, 42) + '...' : c.title }), _jsxs(Text, { dimColor: true, children: [" ", c.agentName, " \u00B7 ", c.messageCount, " msgs \u00B7 ", formatRelativeTime(c.updatedAt)] })] }, c.uuid));
247
+ }), conversations.length > maxVisible && (_jsxs(Text, { dimColor: true, children: [" ", conversations.length, " total \u00B7 scroll for more"] }))] }));
248
+ }
249
+ // ---------------------------------------------------------------------------
250
+ // Root app
251
+ // ---------------------------------------------------------------------------
252
+ let _msgId = 0;
253
+ function nextId() { return String(++_msgId); }
254
+ export function App({ bridge }) {
255
+ const { exit } = useApp();
256
+ const { stdout } = useStdout();
257
+ const [termHeight, setTermHeight] = useState(stdout.rows || 24);
258
+ const [messages, setMessages] = useState([]);
259
+ const [stream, setStream] = useState(EMPTY_STREAM);
260
+ const [inputValue, setInputValue] = useState('');
261
+ const [processing, setProcessing] = useState(false);
262
+ const [consent, setConsent] = useState(null);
263
+ const [tokenUsage, setTokenUsage] = useState({ prompt: 0, completion: 0 });
264
+ const [activeAgentName, setActiveAgentName] = useState(bridge.agentName);
265
+ const [agentPickerAgents, setAgentPickerAgents] = useState(null);
266
+ const [convPickerConvs, setConvPickerConvs] = useState(null);
267
+ // Lines scrolled up from the bottom (0 = at bottom)
268
+ const [scrollOffset, setScrollOffset] = useState(0);
269
+ const [cmdCursor, setCmdCursor] = useState(0);
270
+ const [contextUsage, setContextUsage] = useState({ used: 0, limit: 128_000 });
271
+ const agentLabelRef = useRef('');
272
+ const paletteSelectionRef = useRef(null);
273
+ useEffect(() => {
274
+ const handleResize = () => setTermHeight(stdout.rows || 24);
275
+ stdout.on('resize', handleResize);
276
+ return () => { stdout.off('resize', handleResize); };
277
+ }, [stdout]);
278
+ const addMsg = useCallback((msg) => {
279
+ setMessages(prev => [...prev, { ...msg, id: nextId() }]);
280
+ }, []);
281
+ // Scroll to bottom when new messages arrive (unless user has scrolled up)
282
+ const scrollOffsetRef = useRef(scrollOffset);
283
+ scrollOffsetRef.current = scrollOffset;
284
+ const prevMsgLenRef = useRef(0);
285
+ useEffect(() => {
286
+ if (messages.length > prevMsgLenRef.current) {
287
+ prevMsgLenRef.current = messages.length;
288
+ // Auto-scroll to bottom only if already at bottom
289
+ if (scrollOffsetRef.current === 0) {
290
+ setScrollOffset(0);
291
+ }
292
+ }
293
+ }, [messages.length]);
294
+ // PageUp / PageDown scrolling (active when picker is not open)
295
+ const streamMaxLines = Math.max(3, Math.min(8, termHeight - 14));
296
+ const streamRows = stream.active ? streamMaxLines + 3 : 0;
297
+ const msgBudget = Math.max(4, termHeight - 7 - streamRows);
298
+ const pageSize = Math.max(3, Math.floor(msgBudget * 0.7));
299
+ // Command palette
300
+ const showCommandPalette = /^\/\S*$/.test(inputValue) && !processing && !consent && !agentPickerAgents;
301
+ const filteredCommands = showCommandPalette
302
+ ? COMMAND_DEFS.filter(c => c.command.startsWith(inputValue))
303
+ : [];
304
+ const effectiveCmdCursor = filteredCommands.length > 0
305
+ ? Math.min(cmdCursor, filteredCommands.length - 1)
306
+ : 0;
307
+ paletteSelectionRef.current = filteredCommands.length > 0 ? filteredCommands[effectiveCmdCursor] : null;
308
+ useInput((_, key) => {
309
+ if (key.pageUp) {
310
+ setScrollOffset(prev => prev + pageSize);
311
+ }
312
+ else if (key.pageDown) {
313
+ setScrollOffset(prev => Math.max(0, prev - pageSize));
314
+ }
315
+ else if (key.tab && !showCommandPalette && !inputValue && !processing && !consent) {
316
+ bridge.submitInput('/agent');
317
+ }
318
+ }, { isActive: !agentPickerAgents });
319
+ // Command palette navigation
320
+ useInput((_, key) => {
321
+ if (key.upArrow) {
322
+ setCmdCursor(i => (i - 1 + filteredCommands.length) % filteredCommands.length);
323
+ }
324
+ else if (key.downArrow) {
325
+ setCmdCursor(i => (i + 1) % filteredCommands.length);
326
+ }
327
+ else if (key.tab) {
328
+ const selected = paletteSelectionRef.current;
329
+ if (selected) {
330
+ setInputValue(selected.hasArgs ? selected.command + ' ' : selected.command);
331
+ setCmdCursor(0);
332
+ }
333
+ }
334
+ else if (key.escape) {
335
+ setInputValue('');
336
+ setCmdCursor(0);
337
+ }
338
+ }, { isActive: showCommandPalette && filteredCommands.length > 0 });
339
+ useEffect(() => {
340
+ bridge.on('user_message', (content) => {
341
+ addMsg({ kind: 'user', content });
342
+ setScrollOffset(0);
343
+ });
344
+ bridge.on('processing', (active) => setProcessing(active));
345
+ bridge.on('stream_start', () => {
346
+ agentLabelRef.current = bridge.agentName;
347
+ setStream({ active: true, content: '', thinking: false, thinkingElapsed: '', agentLabel: bridge.agentName });
348
+ });
349
+ bridge.on('agent_label', (name) => {
350
+ agentLabelRef.current = name;
351
+ setStream(s => ({ ...s, agentLabel: name }));
352
+ });
353
+ bridge.on('delta', (text) => {
354
+ setStream(s => ({ ...s, content: s.content + text }));
355
+ });
356
+ bridge.on('thinking_start', () => {
357
+ setStream(s => ({ ...s, thinking: true, thinkingElapsed: '' }));
358
+ });
359
+ bridge.on('thinking_end', (elapsed) => {
360
+ setStream(s => ({ ...s, thinking: false, thinkingElapsed: elapsed }));
361
+ });
362
+ bridge.on('stream_end', (content) => {
363
+ const label = agentLabelRef.current || bridge.agentName;
364
+ setStream(EMPTY_STREAM);
365
+ if (content.trim()) {
366
+ addMsg({
367
+ kind: 'assistant',
368
+ content,
369
+ rendered: renderMarkdown(content),
370
+ meta: { name: label },
371
+ });
372
+ }
373
+ setScrollOffset(0);
374
+ });
375
+ bridge.on('tool_call', ({ name, summary }) => {
376
+ addMsg({ kind: 'tool_call', content: summary, meta: { name } });
377
+ });
378
+ bridge.on('tool_result', ({ name, success, error }) => {
379
+ addMsg({ kind: 'tool_result', content: error ?? '', meta: { name, success } });
380
+ });
381
+ bridge.on('token_usage', ({ prompt, completion }) => {
382
+ setTokenUsage({ prompt, completion });
383
+ });
384
+ bridge.on('context_usage', ({ used, limit }) => {
385
+ setContextUsage({ used, limit });
386
+ });
387
+ bridge.on('error', (message) => addMsg({ kind: 'error', content: message }));
388
+ bridge.on('system', (content) => addMsg({ kind: 'system', content }));
389
+ bridge.on('mcp_status', (servers) => {
390
+ addMsg({ kind: 'system', content: `MCP: ${servers.join(', ')}` });
391
+ });
392
+ bridge.on('clear', () => {
393
+ setMessages([{ id: nextId(), kind: 'system', content: '─── conversation cleared ───' }]);
394
+ setStream(EMPTY_STREAM);
395
+ setTokenUsage({ prompt: 0, completion: 0 });
396
+ setScrollOffset(0);
397
+ });
398
+ bridge.on('consent_request', (req) => setConsent(req));
399
+ bridge.on('show_agent_picker', (agents) => setAgentPickerAgents(agents));
400
+ bridge.on('show_conv_picker', (convs) => setConvPickerConvs(convs));
401
+ bridge.on('active_agent_changed', ({ name }) => {
402
+ setActiveAgentName(name);
403
+ setAgentPickerAgents(null);
404
+ });
405
+ bridge.on('replay_messages', (msgs) => {
406
+ const rendered = msgs.map(m => ({
407
+ id: nextId(),
408
+ kind: m.kind,
409
+ content: m.content,
410
+ rendered: m.kind === 'assistant' ? renderMarkdown(m.content) : undefined,
411
+ meta: m.meta,
412
+ }));
413
+ setMessages(prev => [...prev, ...rendered]);
414
+ setScrollOffset(0);
415
+ });
416
+ bridge.on('quit', () => exit());
417
+ return () => { bridge.removeAllListeners(); };
418
+ }, [bridge, exit, addMsg]);
419
+ const handleInputChange = useCallback((v) => {
420
+ setInputValue(v.replace(/\t/g, ''));
421
+ setCmdCursor(0);
422
+ }, []);
423
+ const handleSubmit = useCallback((value) => {
424
+ const trimmed = value.trim();
425
+ if (!trimmed)
426
+ return;
427
+ if (consent) {
428
+ const v = trimmed.toLowerCase();
429
+ const answer = (v === 'n' || v === 'no') ? 'no'
430
+ : (v === 'a' || v === 'always') ? 'always'
431
+ : 'yes';
432
+ bridge.resolveConsent(answer);
433
+ setConsent(null);
434
+ setInputValue('');
435
+ return;
436
+ }
437
+ const paletteSelection = paletteSelectionRef.current;
438
+ if (paletteSelection) {
439
+ if (paletteSelection.hasArgs) {
440
+ setInputValue(paletteSelection.command + ' ');
441
+ setCmdCursor(0);
442
+ return;
443
+ }
444
+ bridge.submitInput(paletteSelection.command);
445
+ setInputValue('');
446
+ setCmdCursor(0);
447
+ return;
448
+ }
449
+ bridge.submitInput(trimmed);
450
+ setInputValue('');
451
+ setCmdCursor(0);
452
+ }, [bridge, consent]);
453
+ const { visible: visibleMessages, canScrollUp, canScrollDown } = selectVisible(messages, msgBudget, scrollOffset);
454
+ return (_jsxs(Box, { flexDirection: "column", height: termHeight, children: [canScrollUp && (_jsxs(Box, { children: [_jsx(Text, { dimColor: true, children: " \u2191 more " }), _jsx(Text, { dimColor: true, color: "#555", children: "(PgUp/PgDn to scroll)" })] })), _jsx(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden", children: visibleMessages.map(msg => _jsx(MessageRow, { msg: msg }, msg.id)) }), canScrollDown && (_jsx(Box, { children: _jsx(Text, { dimColor: true, children: " \u2193 more recent messages" }) })), convPickerConvs ? (_jsx(ConversationPickerOverlay, { conversations: convPickerConvs, onSelect: (conv) => { bridge.resolveConversationPicker(conv); setConvPickerConvs(null); }, onCancel: () => { bridge.resolveConversationPicker(null); setConvPickerConvs(null); } })) : agentPickerAgents ? (_jsx(AgentPickerOverlay, { agents: agentPickerAgents, onSelect: (agent) => bridge.resolveAgentPicker(agent), onCancel: () => bridge.resolveAgentPicker(null) })) : (_jsx(StreamingRow, { stream: stream, maxLines: streamMaxLines })), _jsx(StatusBar, { prompt: tokenUsage.prompt, completion: tokenUsage.completion, agentName: activeAgentName, isLocal: bridge.isLocal, profileName: bridge.profileName, contextUsed: contextUsage.used, contextLimit: contextUsage.limit }), _jsx(Box, { borderStyle: "single", borderColor: "gray" }), showCommandPalette && filteredCommands.length > 0 && (_jsx(CommandPalette, { commands: filteredCommands, cursor: effectiveCmdCursor })), _jsx(InputArea, { value: inputValue, onChange: handleInputChange, onSubmit: handleSubmit, processing: (processing && !consent) || agentPickerAgents !== null || convPickerConvs !== null, consent: consent })] }));
455
+ }
@@ -0,0 +1,23 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from 'react';
3
+ import { Box, Text, useInput, useApp } from 'ink';
4
+ export function SelectAgent({ agents, onSelect }) {
5
+ const { exit } = useApp();
6
+ const [cursor, setCursor] = useState(0);
7
+ useInput((_, key) => {
8
+ if (key.upArrow) {
9
+ setCursor(i => (i - 1 + agents.length) % agents.length);
10
+ }
11
+ else if (key.downArrow) {
12
+ setCursor(i => (i + 1) % agents.length);
13
+ }
14
+ else if (key.return) {
15
+ onSelect(agents[cursor]);
16
+ exit();
17
+ }
18
+ else if (key.ctrl && key.name === 'c') {
19
+ process.exit(0);
20
+ }
21
+ });
22
+ return (_jsxs(Box, { flexDirection: "column", paddingY: 1, paddingX: 2, children: [_jsx(Text, { bold: true, children: "Select agent" }), _jsx(Text, { dimColor: true, children: "\u2191\u2193 to move \u00B7 Enter to select" }), _jsx(Box, { flexDirection: "column", marginTop: 1, children: agents.map((a, i) => (_jsxs(Box, { children: [_jsx(Text, { color: i === cursor ? '#f97316' : undefined, children: i === cursor ? '❯ ' : ' ' }), _jsx(Text, { bold: i === cursor, children: a.name }), a.description && (_jsxs(Text, { dimColor: true, children: [" \u2014 ", a.description] }))] }, a.uuid))) })] }));
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "0.11.0",
3
+ "version": "0.14.0",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",
@@ -24,6 +24,7 @@
24
24
  "scripts": {
25
25
  "test": "echo \"Error: no test specified\" && exit 1",
26
26
  "build": "npx tsc",
27
+ "postbuild": "chmod +x dist/bin/toolkit.js",
27
28
  "toolkit": "tsc --build && node dist/bin/toolkit",
28
29
  "prepublishOnly": "npm run build"
29
30
  },
@@ -35,7 +36,8 @@
35
36
  "@babel/preset-typescript": "^7.28.5",
36
37
  "@babel/standalone": "^7.26.10",
37
38
  "@inquirer/password": "^4.0.21",
38
- "@ptkl/sdk": "^1.9.2",
39
+ "@ptkl/sdk": "^1.14.0",
40
+ "@ptkl/toolkit": "file:",
39
41
  "@rollup/plugin-babel": "^6.1.0",
40
42
  "@rollup/plugin-commonjs": "^29.0.0",
41
43
  "@rollup/plugin-node-resolve": "^16.0.3",
@@ -48,11 +50,16 @@
48
50
  "chokidar": "^4.0.1",
49
51
  "circular-json": "^0.5.9",
50
52
  "commander": "^12.1.0",
53
+ "ink": "^5.2.1",
54
+ "ink-text-input": "^6.0.0",
51
55
  "js-yaml": "^4.1.0",
52
56
  "jsonpath-plus": "^10.4.0",
53
57
  "less": "^4.1.1",
54
58
  "lodash": "^4.17.21",
59
+ "marked": "^15.0.12",
60
+ "marked-terminal": "^7.3.0",
55
61
  "open": "^10.1.2",
62
+ "react": "^18.3.1",
56
63
  "rollup": "^4.34.6",
57
64
  "sass": "^1.95.1",
58
65
  "tar": "^7.4.3",
@@ -62,7 +69,9 @@
62
69
  "yaml": "^2.5.0"
63
70
  },
64
71
  "devDependencies": {
72
+ "@types/marked-terminal": "^6.1.1",
65
73
  "@types/node": "^22.3.0",
74
+ "@types/react": "^18.3.29",
66
75
  "@types/ws": "^8.5.12",
67
76
  "typescript": "^5.5.4"
68
77
  },