@sortlist/cli 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.published +1 -0
  2. package/README.md +145 -0
  3. package/bin/sl.mjs +73 -0
  4. package/codegen.ts +36 -0
  5. package/package.json +62 -0
  6. package/src/commands/chat/chat.ts +302 -0
  7. package/src/commands/chat/interactive/App.tsx +119 -0
  8. package/src/commands/chat/interactive/components/ChatInput.tsx +115 -0
  9. package/src/commands/chat/interactive/components/ChoicePrompt.tsx +35 -0
  10. package/src/commands/chat/interactive/components/MessageView.tsx +63 -0
  11. package/src/commands/chat/interactive/components/ThinkingBox.tsx +54 -0
  12. package/src/commands/chat/interactive/connection.ts +111 -0
  13. package/src/commands/chat/interactive/debug-log.ts +19 -0
  14. package/src/commands/chat/interactive/hooks/useChat.ts +440 -0
  15. package/src/commands/chat/interactive/hooks/useTerminalSize.ts +23 -0
  16. package/src/commands/chat/interactive/index.tsx +26 -0
  17. package/src/commands/chat/interactive/markdown.ts +29 -0
  18. package/src/commands/chat/interactive/types.ts +34 -0
  19. package/src/commands/config.ts +94 -0
  20. package/src/commands/dynamic.ts +396 -0
  21. package/src/commands/login.ts +191 -0
  22. package/src/commands/logout.ts +43 -0
  23. package/src/commands/offer.ts +96 -0
  24. package/src/commands/switch.ts +72 -0
  25. package/src/commands/token.ts +23 -0
  26. package/src/commands/whoami.ts +50 -0
  27. package/src/graphql/client.ts +257 -0
  28. package/src/graphql/generated/gql.ts +106 -0
  29. package/src/graphql/generated/graphql.ts +7732 -0
  30. package/src/graphql/generated/index.ts +1 -0
  31. package/src/graphql/introspection.ts +240 -0
  32. package/src/graphql/operations/common.ts +115 -0
  33. package/src/graphql/operations/hermes.ts +54 -0
  34. package/src/graphql/query-builder.ts +236 -0
  35. package/src/index.ts +176 -0
  36. package/src/lib/auth.ts +58 -0
  37. package/src/lib/browser.ts +6 -0
  38. package/src/lib/company.ts +35 -0
  39. package/src/lib/config.ts +73 -0
  40. package/src/lib/env.ts +10 -0
  41. package/src/lib/output.ts +84 -0
  42. package/src/lib/parse.ts +8 -0
  43. package/src/lib/sentry.ts +77 -0
  44. package/src/lib/sequence-buffer.ts +95 -0
  45. package/src/lib/version-check.ts +88 -0
  46. package/src/types/marked-terminal.d.ts +20 -0
@@ -0,0 +1,119 @@
1
+ import { Spinner } from '@inkjs/ui';
2
+ import { Box, Text, useApp, useInput } from 'ink';
3
+ import React, { useCallback } from 'react';
4
+
5
+ import { ChatInput } from './components/ChatInput.tsx';
6
+ import { ChoicePrompt } from './components/ChoicePrompt.tsx';
7
+ import { MessageView } from './components/MessageView.tsx';
8
+ import { ThinkingBox } from './components/ThinkingBox.tsx';
9
+ import { useChat } from './hooks/useChat.ts';
10
+ import { useTerminalSize } from './hooks/useTerminalSize.ts';
11
+
12
+ interface AppProps {
13
+ companyId: string;
14
+ conversationId?: string;
15
+ conversationTitle?: string;
16
+ endpoint: string;
17
+ }
18
+
19
+ export function App({ companyId, conversationId: initialConversationId, conversationTitle, endpoint }: AppProps) {
20
+ const { exit } = useApp();
21
+ const { rows: termHeight } = useTerminalSize();
22
+
23
+ const chat = useChat({ companyId, conversationId: initialConversationId, conversationTitle, endpoint });
24
+
25
+ const isBusy = chat.streamContent !== null || chat.thinkingLog.length > 0;
26
+
27
+ useInput((_input, key) => {
28
+ if (key.ctrl && _input === 'c') {
29
+ chat.disconnect();
30
+ exit();
31
+ return;
32
+ }
33
+ // Esc (when no choice prompt is up) stops the chat mid-turn without quitting.
34
+ if (key.escape && !chat.pendingChoice && isBusy) {
35
+ chat.cancelStream();
36
+ }
37
+ });
38
+
39
+ const handleSubmit = useCallback(
40
+ (value: string) => {
41
+ const content = value.trim();
42
+ if (!content) return;
43
+
44
+ if (content === '/quit' || content === '/exit') {
45
+ chat.disconnect();
46
+ exit();
47
+ return;
48
+ }
49
+
50
+ chat.sendMessage(content);
51
+ },
52
+ [chat, exit],
53
+ );
54
+
55
+ // ── Early returns ──
56
+
57
+ if (chat.status === 'error' && !chat.connection) {
58
+ return (
59
+ <Box flexDirection="column" padding={1} minHeight={termHeight}>
60
+ <Text color="red">Error: {chat.errorMsg}</Text>
61
+ </Box>
62
+ );
63
+ }
64
+
65
+ if (chat.status === 'connecting') {
66
+ return (
67
+ <Box padding={1} minHeight={termHeight}>
68
+ <Text color="cyan">Connecting...</Text>
69
+ </Box>
70
+ );
71
+ }
72
+
73
+ // ── Layout ──
74
+
75
+ const streamingHeight = Math.max(6, Math.floor(termHeight / 4));
76
+
77
+ return (
78
+ <Box flexDirection="column" minHeight={termHeight}>
79
+ {/* Header */}
80
+ <Box marginBottom={1}>
81
+ <Text dimColor>Sortlist Chat</Text>
82
+ {chat.conversationId && <Text dimColor> · {chat.conversationId}</Text>}
83
+ <Text dimColor> · /quit to exit{isBusy ? ' · esc to stop' : ''}</Text>
84
+ </Box>
85
+
86
+ {/* Greeting loader */}
87
+ {chat.waitingForGreeting && chat.messages.length === 0 && chat.streamContent === null && (
88
+ <Box marginBottom={1}>
89
+ <Spinner label="Starting up..." />
90
+ </Box>
91
+ )}
92
+
93
+ {/* Messages — all rendered, terminal scrollback handles overflow */}
94
+ {chat.messages.map((msg, i) => (
95
+ // eslint-disable-next-line react/no-array-index-key -- append-only list, no reorder
96
+ <MessageView key={i} msg={msg} />
97
+ ))}
98
+
99
+ {/* Thinking/streaming box — hidden while the user is being prompted for a choice */}
100
+ {!chat.pendingChoice && (chat.streamContent !== null || chat.thinkingLog.length > 0) && (
101
+ <ThinkingBox thinkingLog={chat.thinkingLog} streamContent={chat.streamContent} height={streamingHeight} />
102
+ )}
103
+
104
+ {/* Error banner */}
105
+ {chat.errorMsg && chat.status !== 'error' && (
106
+ <Box>
107
+ <Text color="red">{chat.errorMsg}</Text>
108
+ </Box>
109
+ )}
110
+
111
+ {/* Input — choice prompt takes precedence when active */}
112
+ {chat.pendingChoice ? (
113
+ <ChoicePrompt choice={chat.pendingChoice} onSelect={chat.respondToChoice} onCancel={chat.cancelChoice} />
114
+ ) : (
115
+ <ChatInput inputKey={chat.inputKey} isDisabled={chat.inputDisabled} onSubmit={handleSubmit} />
116
+ )}
117
+ </Box>
118
+ );
119
+ }
@@ -0,0 +1,115 @@
1
+ import chalk from 'chalk';
2
+ import { Box, Text, useInput } from 'ink';
3
+ import React, { useState } from 'react';
4
+
5
+ interface ChatInputProps {
6
+ inputKey: number;
7
+ isDisabled: boolean;
8
+ onSubmit: (value: string) => void;
9
+ }
10
+
11
+ const CURSOR = chalk.inverse(' ');
12
+ const PLACEHOLDER = 'Type a message...';
13
+
14
+ // Delete the word to the left of the cursor. Strips a run of whitespace, then a run of
15
+ // non-whitespace — mirrors readline / most shells.
16
+ function deleteWordLeft(value: string, cursor: number): { value: string; cursor: number } {
17
+ if (cursor === 0) return { value, cursor };
18
+ let index = cursor;
19
+ while (index > 0 && /\s/.test(value[index - 1]!)) index--;
20
+ while (index > 0 && !/\s/.test(value[index - 1]!)) index--;
21
+ return { value: value.slice(0, index) + value.slice(cursor), cursor: index };
22
+ }
23
+
24
+ export function ChatInput({ inputKey, isDisabled, onSubmit }: ChatInputProps) {
25
+ const [value, setValue] = useState('');
26
+ const [cursor, setCursor] = useState(0);
27
+
28
+ // Reset internal state when inputKey changes (parent signals "new turn").
29
+ React.useEffect(() => {
30
+ setValue('');
31
+ setCursor(0);
32
+ }, [inputKey]);
33
+
34
+ useInput(
35
+ (input, key) => {
36
+ if (key.upArrow || key.downArrow || key.tab) return;
37
+ if (key.ctrl && input === 'c') return;
38
+
39
+ if (key.return) {
40
+ onSubmit(value);
41
+ return;
42
+ }
43
+
44
+ if (key.leftArrow) {
45
+ setCursor((c) => Math.max(0, c - 1));
46
+ return;
47
+ }
48
+ if (key.rightArrow) {
49
+ setCursor((c) => Math.min(value.length, c + 1));
50
+ return;
51
+ }
52
+
53
+ // Ctrl+W / Alt(Option)+Backspace / Ctrl+Backspace → delete word left
54
+ const isWordDelete =
55
+ (key.ctrl && input === 'w') ||
56
+ (key.meta && (key.backspace || key.delete)) ||
57
+ (key.ctrl && (key.backspace || key.delete));
58
+ if (isWordDelete) {
59
+ const next = deleteWordLeft(value, cursor);
60
+ setValue(next.value);
61
+ setCursor(next.cursor);
62
+ return;
63
+ }
64
+
65
+ if (key.backspace || key.delete) {
66
+ if (cursor === 0) return;
67
+ setValue((v) => v.slice(0, cursor - 1) + v.slice(cursor));
68
+ setCursor((c) => Math.max(0, c - 1));
69
+ return;
70
+ }
71
+
72
+ // Ctrl+U → delete to line start
73
+ if (key.ctrl && input === 'u') {
74
+ setValue((v) => v.slice(cursor));
75
+ setCursor(0);
76
+ return;
77
+ }
78
+
79
+ // Swallow any other ctrl/meta combos we don't recognize instead of inserting
80
+ // the raw letter (this was the source of the "ctrl+w inserted 'w'" bug).
81
+ if (key.ctrl || key.meta) return;
82
+
83
+ // Printable text: insert at cursor.
84
+ if (input && input.length > 0) {
85
+ setValue((v) => v.slice(0, cursor) + input + v.slice(cursor));
86
+ setCursor((c) => c + input.length);
87
+ }
88
+ },
89
+ { isActive: !isDisabled },
90
+ );
91
+
92
+ const rendered = React.useMemo(() => {
93
+ if (isDisabled) {
94
+ return value.length > 0 ? value : chalk.dim(PLACEHOLDER);
95
+ }
96
+ if (value.length === 0) {
97
+ return chalk.inverse(PLACEHOLDER[0]!) + chalk.dim(PLACEHOLDER.slice(1));
98
+ }
99
+ let result = '';
100
+ for (let index = 0; index < value.length; index++) {
101
+ result += index === cursor ? chalk.inverse(value[index]!) : value[index]!;
102
+ }
103
+ if (cursor === value.length) result += CURSOR;
104
+ return result;
105
+ }, [value, cursor, isDisabled]);
106
+
107
+ return (
108
+ <Box borderStyle="round" borderColor="green" paddingX={1} flexShrink={0}>
109
+ <Text color="green" bold>
110
+ {'❯ '}
111
+ </Text>
112
+ <Text>{rendered}</Text>
113
+ </Box>
114
+ );
115
+ }
@@ -0,0 +1,35 @@
1
+ import { Select } from '@inkjs/ui';
2
+ import { Box, Text, useInput } from 'ink';
3
+ import React from 'react';
4
+
5
+ import type { PendingChoice } from '../types.ts';
6
+
7
+ interface ChoicePromptProps {
8
+ choice: PendingChoice;
9
+ onSelect: (value: string) => void;
10
+ onCancel: () => void;
11
+ }
12
+
13
+ export function ChoicePrompt({ choice, onSelect, onCancel }: ChoicePromptProps) {
14
+ const options = choice.options.map((option) => ({ label: option, value: option }));
15
+
16
+ useInput((_input, key) => {
17
+ if (key.escape) {
18
+ onCancel();
19
+ }
20
+ });
21
+
22
+ return (
23
+ <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} flexShrink={0}>
24
+ <Box marginBottom={1}>
25
+ <Text color="yellow" bold>
26
+ ? {choice.question}
27
+ </Text>
28
+ </Box>
29
+ <Select options={options} onChange={onSelect} />
30
+ <Box marginTop={1}>
31
+ <Text dimColor>↑↓ move · ↵ select · esc cancel</Text>
32
+ </Box>
33
+ </Box>
34
+ );
35
+ }
@@ -0,0 +1,63 @@
1
+ import { Box, Text } from 'ink';
2
+ import React from 'react';
3
+
4
+ import { renderMarkdown } from '../markdown.ts';
5
+ import type { Message } from '../types.ts';
6
+
7
+ export function MessageView({ msg }: { msg: Message }) {
8
+ if (msg.role === 'user') {
9
+ return (
10
+ <Box marginBottom={1}>
11
+ <Text backgroundColor="#333333">
12
+ <Text color="green" bold>
13
+ {'❯ '}
14
+ </Text>
15
+ {msg.content}
16
+ </Text>
17
+ </Box>
18
+ );
19
+ }
20
+
21
+ return (
22
+ <Box flexDirection="column" marginBottom={1}>
23
+ <Text color="cyan" bold>
24
+ Chat
25
+ </Text>
26
+ <Box marginLeft={0}>
27
+ <Text>{renderMarkdown(msg.content)}</Text>
28
+ </Box>
29
+ </Box>
30
+ );
31
+ }
32
+
33
+ export function estimateMessageLines(msg: Message, width: number): number {
34
+ if (msg.role === 'user') {
35
+ return Math.ceil((msg.content.length + 2) / width) + 1;
36
+ }
37
+ const rendered = renderMarkdown(msg.content);
38
+ const lines = rendered.split('\n').reduce((sum, line) => {
39
+ return sum + Math.max(1, Math.ceil((line.length || 1) / width));
40
+ }, 0);
41
+ return 1 + lines + 1;
42
+ }
43
+
44
+ export function getVisibleMessages(
45
+ messages: Message[],
46
+ availableHeight: number,
47
+ width: number,
48
+ scrollOffset: number,
49
+ ): Message[] {
50
+ const endIdx = messages.length - scrollOffset;
51
+ if (endIdx <= 0) return messages.slice(0, 1);
52
+
53
+ let usedLines = 0;
54
+ let startIdx = endIdx;
55
+ for (let i = endIdx - 1; i >= 0; i--) {
56
+ const lines = estimateMessageLines(messages[i]!, width);
57
+ if (usedLines + lines > availableHeight && usedLines > 0) break;
58
+ // Always include at least the most recent message, even if it overflows
59
+ usedLines += lines;
60
+ startIdx = i;
61
+ }
62
+ return messages.slice(startIdx, endIdx);
63
+ }
@@ -0,0 +1,54 @@
1
+ import { Spinner } from '@inkjs/ui';
2
+ import { Box, Text } from 'ink';
3
+ import React from 'react';
4
+
5
+ import type { ThinkingEntry, ToolCallInfo } from '../types.ts';
6
+
7
+ interface ThinkingBoxProps {
8
+ thinkingLog: ThinkingEntry[];
9
+ streamContent: string | null;
10
+ height: number;
11
+ }
12
+
13
+ function ToolCallLine({ tool }: { tool: ToolCallInfo }) {
14
+ const pending = !tool.resultLabel;
15
+
16
+ if (pending) {
17
+ return (
18
+ <Box>
19
+ <Spinner label={tool.label} />
20
+ </Box>
21
+ );
22
+ }
23
+
24
+ return (
25
+ <Box>
26
+ <Text color={tool.isError ? 'red' : 'green'}>{tool.isError ? '✗' : '✓'} </Text>
27
+ <Text color="white">{tool.label}</Text>
28
+ </Box>
29
+ );
30
+ }
31
+
32
+ export function ThinkingBox({ thinkingLog, streamContent, height }: ThinkingBoxProps) {
33
+ const maxLines = height - 3;
34
+ const visible = thinkingLog.slice(-maxLines);
35
+
36
+ return (
37
+ <Box
38
+ flexDirection="column"
39
+ height={height}
40
+ flexShrink={0}
41
+ borderStyle="single"
42
+ borderColor="cyan"
43
+ paddingX={1}
44
+ overflow="hidden">
45
+ <Text color="cyan" bold dimColor>
46
+ {streamContent !== null ? 'Typing...' : 'Thinking...'}
47
+ </Text>
48
+ {visible.map((entry, i) => (
49
+ // eslint-disable-next-line react/no-array-index-key -- append-only log
50
+ <ToolCallLine key={i} tool={entry.tool} />
51
+ ))}
52
+ </Box>
53
+ );
54
+ }
@@ -0,0 +1,111 @@
1
+ import { print } from 'graphql';
2
+
3
+ import { ConversationEvent as ConversationEventSubscriptionDocument } from '../../../graphql/operations/common.ts';
4
+ import type { ChatConnection, ChatEvent } from './types.ts';
5
+
6
+ const EVENT_STREAM = 'text/event-stream';
7
+
8
+ // Subscribes to `conversationEvent` over GraphQL-SSE (distinct connection
9
+ // mode). hive-router negotiates the response format from the client's
10
+ // `Accept` header; we explicitly ask for text/event-stream. The router
11
+ // keeps the HTTP response open and pushes `event: next` frames as the
12
+ // chat subgraph POSTs them via the callback protocol.
13
+ export async function connectChatStream(
14
+ endpoint: string,
15
+ token: string,
16
+ conversationId: string,
17
+ onDebug?: (line: string) => void,
18
+ ): Promise<ChatConnection> {
19
+ const abort = new AbortController();
20
+ const response = await fetch(endpoint, {
21
+ method: 'POST',
22
+ signal: abort.signal,
23
+ headers: {
24
+ 'Content-Type': 'application/json',
25
+ Authorization: `Bearer ${token}`,
26
+ Accept: EVENT_STREAM,
27
+ },
28
+ body: JSON.stringify({
29
+ query: print(ConversationEventSubscriptionDocument),
30
+ variables: { conversationId },
31
+ }),
32
+ });
33
+
34
+ if (!response.ok || !response.body) {
35
+ throw new Error(`Chat stream failed: HTTP ${response.status} ${response.statusText}`);
36
+ }
37
+
38
+ const contentType = response.headers.get('content-type') ?? '';
39
+ if (!contentType.includes(EVENT_STREAM)) {
40
+ throw new Error(`Expected ${EVENT_STREAM}, got "${contentType}"`);
41
+ }
42
+
43
+ const messageHandlers: Array<(event: ChatEvent) => void> = [];
44
+ const closeHandlers: Array<() => void> = [];
45
+
46
+ void (async () => {
47
+ const reader = response.body!.getReader();
48
+ const decoder = new TextDecoder();
49
+ let buffer = '';
50
+ let currentEvent: string | null = null;
51
+ let currentData: string[] = [];
52
+
53
+ const dispatch = () => {
54
+ if (currentEvent === 'next' && currentData.length > 0) {
55
+ try {
56
+ const payload = JSON.parse(currentData.join('\n'));
57
+ const conversationEvent = payload?.data?.conversationEvent;
58
+ if (conversationEvent) {
59
+ for (const handler of messageHandlers) handler(conversationEvent);
60
+ }
61
+ } catch (err) {
62
+ onDebug?.(`[sse] parse error: ${err instanceof Error ? err.message : err}`);
63
+ }
64
+ }
65
+ currentEvent = null;
66
+ currentData = [];
67
+ };
68
+
69
+ try {
70
+ while (true) {
71
+ const { value, done } = await reader.read();
72
+ if (done) break;
73
+ buffer += decoder.decode(value, { stream: true });
74
+
75
+ let newlineIndex: number;
76
+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
77
+ const line = buffer.slice(0, newlineIndex).replace(/\r$/, '');
78
+ buffer = buffer.slice(newlineIndex + 1);
79
+
80
+ if (line === '') {
81
+ dispatch();
82
+ continue;
83
+ }
84
+ if (line.startsWith(':')) continue;
85
+ if (line.startsWith('event:')) {
86
+ currentEvent = line.slice(6).trim();
87
+ } else if (line.startsWith('data:')) {
88
+ currentData.push(line.slice(5).replace(/^ /, ''));
89
+ }
90
+ }
91
+ }
92
+ dispatch();
93
+ } catch (err) {
94
+ onDebug?.(`[sse] stream error: ${err instanceof Error ? err.message : err}`);
95
+ } finally {
96
+ for (const handler of closeHandlers) handler();
97
+ }
98
+ })();
99
+
100
+ return {
101
+ onMessage(fn) {
102
+ messageHandlers.push(fn);
103
+ },
104
+ onClose(fn) {
105
+ closeHandlers.push(fn);
106
+ },
107
+ close() {
108
+ abort.abort();
109
+ },
110
+ };
111
+ }
@@ -0,0 +1,19 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const LOG_DIR = path.resolve(import.meta.dirname, '../../../..');
5
+ const DEBUG_LOG_PATH = path.join(LOG_DIR, 'debug.log');
6
+ const TOOL_LOG_PATH = path.join(LOG_DIR, 'debug-tools.log');
7
+
8
+ export function clearDebugLogs() {
9
+ fs.writeFileSync(DEBUG_LOG_PATH, '');
10
+ fs.writeFileSync(TOOL_LOG_PATH, '');
11
+ }
12
+
13
+ export function appendDebugLog(line: string) {
14
+ fs.appendFileSync(DEBUG_LOG_PATH, `[${new Date().toISOString()}] ${line}\n`);
15
+ }
16
+
17
+ export function appendToolLog(line: string) {
18
+ fs.appendFileSync(TOOL_LOG_PATH, `[${new Date().toISOString()}] ${line}\n`);
19
+ }