@ptkl/toolkit 0.11.0 → 1.0.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
+ }
@@ -0,0 +1,51 @@
1
+ import Util from "./util.js";
2
+ import OutputFormatCommand from "../commands/outputCommand.js";
3
+ // Re-exported so new commands only need to import from this one module.
4
+ export { OutputFormatCommand };
5
+ /** Attach the global `--env <dev|live>` option to a command. Mirrors the existing `--profile`
6
+ * handling in src/bin/toolkit.ts (a flag whose resolved value is stashed on `process.env` so
7
+ * downstream lib code — src/lib/sdk.ts's `resolveEnv()` — can read it without threading it
8
+ * through every function call). */
9
+ export function withEnvOption(command) {
10
+ return command.option("--env <env>", "Environment to target: dev | live", "dev");
11
+ }
12
+ /** Build an `OutputFormatCommand`-wrapped command that also carries the global `--env` option.
13
+ * This is the uniform shape new command groups should use:
14
+ *
15
+ * ```ts
16
+ * registerCommand(new Command("list").description("List things"))
17
+ * .action(withProfile(async (profile, opts) => {
18
+ * const client = sdk.platform(profile);
19
+ * return (await client.project().list()).data;
20
+ * }))
21
+ * ```
22
+ */
23
+ export function registerCommand(command) {
24
+ withEnvOption(command);
25
+ return new OutputFormatCommand(command);
26
+ }
27
+ /** Wrap a command action with profile resolution + error normalization. The active profile is
28
+ * resolved once (throwing the existing friendly "run `profile use`" error if none is set) and
29
+ * handed to `fn` as the first argument; the resolved `--env` (if the wrapped command carries the
30
+ * option from `withEnvOption`/`registerCommand`) is stashed on `process.env.PTKL_ACTIVE_ENV` for
31
+ * `src/lib/sdk.ts` to pick up. Errors are normalized the same way as the top-level handler in
32
+ * src/bin/toolkit.ts (prefer the API's error message over a raw stack). */
33
+ export function withProfile(fn) {
34
+ return async (...args) => {
35
+ try {
36
+ const last = args[args.length - 1];
37
+ const opts = last && typeof last.opts === "function" ? last.opts() : undefined;
38
+ if (opts?.env) {
39
+ process.env.PTKL_ACTIVE_ENV = opts.env;
40
+ }
41
+ const profile = Util.getCurrentProfile();
42
+ return await fn(profile, ...args);
43
+ }
44
+ catch (err) {
45
+ const response = err?.response;
46
+ const message = response?.data?.message ?? err?.message ?? String(err);
47
+ console.error(message);
48
+ process.exit(1);
49
+ }
50
+ };
51
+ }
@@ -0,0 +1,88 @@
1
+ // Central factory for v0.10 SDK clients, built from the active profile.
2
+ //
3
+ // Two gateways exist on the platform (see TOOLKIT_API_COVERAGE_RFC.md §2):
4
+ // - PlatformBaseClient -> baseURL = profile.host (native /v1/... + proxied services)
5
+ // - IntegrationsBaseClient -> baseURL = profile.host + /luma/integrations (integration interfaces + satellites)
6
+ // Every accessor below builds its client against the correct gateway base URL so
7
+ // commands never have to think about which host to hit.
8
+ import { Platform, Integrations, Kortex, Workflow, Sandbox, Ratchet, Thunder, Project, Config, Payments, Mail, DMS, Timber, SerbiaMinFin, } from "@ptkl/sdk/beta";
9
+ import Util from "./util.js";
10
+ /** Resolve the active `--env` (dev|live), defaulting to `dev`. Commands surface `--env` through
11
+ * the scaffold (see src/lib/scaffold.ts), which stores the resolved value in this env var —
12
+ * mirroring how the existing `--profile` flag is threaded via PTKL_ACTIVE_PROFILE. */
13
+ export function resolveEnv() {
14
+ return process.env.PTKL_ACTIVE_ENV || "dev";
15
+ }
16
+ function stripTrailingSlashes(url) {
17
+ return url.replace(/\/+$/, "");
18
+ }
19
+ function resolveProfile(profile) {
20
+ return profile ?? Util.getCurrentProfile();
21
+ }
22
+ /** Options for the native platform gateway (`profile.host`). */
23
+ export function platformOptions(profile) {
24
+ const p = resolveProfile(profile);
25
+ return {
26
+ host: p.host,
27
+ token: p.token,
28
+ env: resolveEnv(),
29
+ project: p.project,
30
+ };
31
+ }
32
+ /** Options for the integrations gateway (`profile.host/luma/integrations`). */
33
+ export function integrationsOptions(profile) {
34
+ const p = resolveProfile(profile);
35
+ return {
36
+ host: `${stripTrailingSlashes(p.host)}/luma/integrations`,
37
+ token: p.token,
38
+ env: resolveEnv(),
39
+ project: p.project,
40
+ };
41
+ }
42
+ // -- Native platform-gateway clients -----------------------------------------------------------
43
+ export function platform(profile) {
44
+ return new Platform(platformOptions(profile));
45
+ }
46
+ export function workflow(profile) {
47
+ return new Workflow(platformOptions(profile));
48
+ }
49
+ export function sandbox(profile) {
50
+ return new Sandbox(platformOptions(profile));
51
+ }
52
+ export function ratchet(profile) {
53
+ return new Ratchet(platformOptions(profile));
54
+ }
55
+ export function thunder(profile) {
56
+ return new Thunder(platformOptions(profile));
57
+ }
58
+ export function project(profile) {
59
+ return new Project(platformOptions(profile));
60
+ }
61
+ export function config(profile) {
62
+ return new Config(platformOptions(profile));
63
+ }
64
+ /** Kortex is proxied through the platform gateway (`/luma/kortex/v1/...`), not the integrations
65
+ * gateway — despite the name, it is not an "integration". */
66
+ export function kortex(profile) {
67
+ return new Kortex(platformOptions(profile));
68
+ }
69
+ // -- Integrations-gateway clients --------------------------------------------------------------
70
+ export function integrations(profile) {
71
+ return new Integrations(integrationsOptions(profile));
72
+ }
73
+ export function payments(profile) {
74
+ return new Payments(integrationsOptions(profile));
75
+ }
76
+ export function mail(profile) {
77
+ return new Mail(integrationsOptions(profile));
78
+ }
79
+ export function dms(profile) {
80
+ return new DMS(integrationsOptions(profile));
81
+ }
82
+ export function timber(profile) {
83
+ return new Timber(integrationsOptions(profile));
84
+ }
85
+ /** Serbia MinFin (fiscalization/VPFR/NBS umbrella client — see SerbiaMinFin in the SDK). */
86
+ export function serbia(profile) {
87
+ return new SerbiaMinFin(integrationsOptions(profile));
88
+ }