@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,440 @@
1
+ import React, { useCallback, useState } from 'react';
2
+
3
+ import { graphql } from '../../../../graphql/client.ts';
4
+ import {
5
+ CancelConversation,
6
+ Conversation,
7
+ Me,
8
+ RespondToToolCall,
9
+ SendMessage,
10
+ } from '../../../../graphql/operations/common.ts';
11
+ import { ensureAuthenticated, isExpired } from '../../../../lib/auth.ts';
12
+ import { captureException } from '../../../../lib/sentry.ts';
13
+ import { SequenceBuffer } from '../../../../lib/sequence-buffer.ts';
14
+ import { connectChatStream } from '../connection.ts';
15
+ import { appendDebugLog, appendToolLog, clearDebugLogs } from '../debug-log.ts';
16
+ import type { ChatConnection, ChatEvent, Message, PendingChoice, ThinkingEntry, ToolCallInfo } from '../types.ts';
17
+
18
+ /**
19
+ * Available tool calls
20
+ * ┌─────────────────────┬────────────────────────────────┬───────────────────────┐
21
+ │ Tool │ When model uses it │ Ink component │
22
+ ├─────────────────────┼────────────────────────────────┼───────────────────────┤
23
+ │ ask_multiple_choice │ discrete choice ≤6 options │ @inkjs/ui SelectInput │
24
+ ├─────────────────────┼────────────────────────────────┼───────────────────────┤
25
+ │ ask_confirm │ yes/no before action │ ConfirmInput │
26
+ ├─────────────────────┼────────────────────────────────┼───────────────────────┤
27
+ │ ask_text │ structured free-text input │ TextInput │
28
+ ├─────────────────────┼────────────────────────────────┼───────────────────────┤
29
+ │ render_table │ list results (agencies, leads) │ Ink Table │
30
+ ├─────────────────────┼────────────────────────────────┼───────────────────────┤
31
+ │ render_card │ single entity summary │ custom Box │
32
+ └─────────────────────┴────────────────────────────────┴───────────────────────┘
33
+ */
34
+
35
+ // Must match AskChoiceTool::CANCEL_SENTINEL in the chat backend.
36
+ const CHOICE_CANCEL_SENTINEL = '__cancelled__';
37
+
38
+ function parseToolCall(toolName: string, toolCallId: string, args: unknown): ToolCallInfo {
39
+ const argsObj = (typeof args === 'object' && args !== null ? args : {}) as Record<string, unknown>;
40
+
41
+ let label: string;
42
+
43
+ if (toolName === 'mcp_execute') {
44
+ const query = String(argsObj.query ?? '');
45
+ // Extract operation name: "query GetCurrentUser { ..." → "query GetCurrentUser"
46
+ const match = query.match(/^\s*(query|mutation|subscription)\s+(\w+)/);
47
+ if (match) {
48
+ label = `${match[1]} ${match[2]}`;
49
+ } else {
50
+ label = 'execute GraphQL';
51
+ }
52
+ } else if (toolName === 'mcp_introspect') {
53
+ const typeName = String(argsObj.type_name ?? argsObj.typeName ?? 'schema');
54
+ label = `introspect ${typeName}`;
55
+ } else if (toolName === 'ask_choice') {
56
+ const question = String(argsObj.question ?? 'choice');
57
+ label = `ask: ${question}`.slice(0, 80);
58
+ } else {
59
+ label = `${toolName}(${JSON.stringify(args)})`.slice(0, 80);
60
+ }
61
+
62
+ return { toolName, toolCallId, label, isError: false };
63
+ }
64
+
65
+ interface UseChatOptions {
66
+ companyId: string;
67
+ conversationId?: string;
68
+ conversationTitle?: string;
69
+ endpoint: string;
70
+ }
71
+
72
+ export interface ChatState {
73
+ messages: Message[];
74
+ streamContent: string | null;
75
+ thinkingLog: string[];
76
+ status: 'connecting' | 'ready' | 'waiting' | 'error';
77
+ errorMsg: string | null;
78
+ conversationId: string | null;
79
+ connection: ChatConnection | null;
80
+ inputDisabled: boolean;
81
+ }
82
+
83
+ export function useChat({
84
+ companyId,
85
+ conversationId: initialConversationId,
86
+ conversationTitle: _conversationTitle,
87
+ endpoint,
88
+ }: UseChatOptions) {
89
+ const [messages, setMessages] = useState<Message[]>([]);
90
+ const [streamContent, setStreamContent] = useState<string | null>(null);
91
+ const streamContentRef = React.useRef<string | null>(null);
92
+ const [thinkingLog, setThinkingLog] = useState<ThinkingEntry[]>([]);
93
+ const [status, setStatus] = useState<ChatState['status']>('connecting');
94
+ const [errorMsg, setErrorMsg] = useState<string | null>(null);
95
+ const [conversationId, setConversationId] = useState<string | null>(initialConversationId ?? null);
96
+ const [connection, setConnection] = useState<ChatConnection | null>(null);
97
+ const [inputDisabled, setInputDisabled] = useState(true);
98
+ const [inputKey, setInputKey] = useState(0);
99
+ const [waitingForGreeting, setWaitingForGreeting] = useState(false);
100
+ const [pendingChoice, setPendingChoice] = useState<PendingChoice | null>(null);
101
+
102
+ // Initialize connection
103
+ const initRef = React.useRef(false);
104
+ React.useEffect(() => {
105
+ if (initRef.current) return;
106
+ initRef.current = true;
107
+
108
+ clearDebugLogs();
109
+
110
+ (async () => {
111
+ try {
112
+ const creds = ensureAuthenticated();
113
+ if (isExpired(creds)) {
114
+ setStatus('error');
115
+ setErrorMsg('Session expired. Run `sl login` to re-authenticate.');
116
+ return;
117
+ }
118
+
119
+ let activeConversationId = initialConversationId;
120
+
121
+ if (!activeConversationId) {
122
+ const userData = await graphql(Me, undefined, { endpoint, throwOnError: true });
123
+ const membership = (userData.me?.memberships?.nodes ?? []).find((m) => m?.company?.id === companyId);
124
+ activeConversationId = membership?.conversation?.id ?? undefined;
125
+ if (!activeConversationId) {
126
+ setStatus('error');
127
+ setErrorMsg('Could not resolve a conversation for this company.');
128
+ return;
129
+ }
130
+ setConversationId(activeConversationId);
131
+ } else {
132
+ const data = await graphql(Conversation, { id: activeConversationId }, { endpoint, throwOnError: true });
133
+ const conversation = data.node?.__typename === 'Conversation' ? data.node : null;
134
+ if (!conversation) {
135
+ setStatus('error');
136
+ setErrorMsg(`Conversation not found: ${activeConversationId}`);
137
+ return;
138
+ }
139
+ const existing: Message[] = [];
140
+ for (const msg of (conversation.messages?.nodes ?? []).filter((m): m is NonNullable<typeof m> => m != null)) {
141
+ if ((msg.role === 'user' || msg.role === 'assistant') && msg.content) {
142
+ existing.push({ role: msg.role, content: msg.content });
143
+ }
144
+ }
145
+ setMessages(existing);
146
+ setConversationId(activeConversationId);
147
+ }
148
+
149
+ const onDebug = (line: string) => {
150
+ appendDebugLog(line);
151
+ };
152
+
153
+ const conn = await connectChatStream(endpoint, creds.accessToken, activeConversationId!, onDebug);
154
+
155
+ const completedSegments: string[] = [];
156
+ let finalizedAgentLoopId: string | null = null;
157
+
158
+ const saveSegment = () => {
159
+ const current = streamContentRef.current;
160
+ if (current) {
161
+ completedSegments.push(current);
162
+ }
163
+ streamContentRef.current = null;
164
+ setStreamContent(null);
165
+ };
166
+
167
+ const finalizeSegments = () => {
168
+ saveSegment();
169
+ const segments = completedSegments.splice(0);
170
+ onDebug(
171
+ `finalizeSegments: ${segments.length} segments, last=${segments[segments.length - 1]?.slice(0, 80) ?? '(none)'}`,
172
+ );
173
+ if (segments.length === 0) return;
174
+ const final_ = segments[segments.length - 1]!;
175
+ setMessages((prev) => {
176
+ onDebug(`setMessages: prev=${prev.length} messages, adding assistant (${final_.length} chars)`);
177
+ return [...prev, { role: 'assistant' as const, content: final_ }];
178
+ });
179
+ };
180
+
181
+ // Safety timer: if no event arrives within 3s of the last MessageEndedEvent,
182
+ // treat it as a missed AgentLoopCompletedEvent and finalize anyway.
183
+ const DONE_SAFETY_MS = 3000;
184
+ let doneTimer: ReturnType<typeof setTimeout> | null = null;
185
+ let lastSeenAgentLoopId: string | null = null;
186
+
187
+ const startDoneTimer = () => {
188
+ cancelDoneTimer();
189
+ const agentLoopIdAtStart = lastSeenAgentLoopId;
190
+ doneTimer = setTimeout(() => {
191
+ doneTimer = null;
192
+ finalizedAgentLoopId = agentLoopIdAtStart;
193
+ onDebug('⚠ AgentLoopCompletedEvent not received — finalizing via safety timer');
194
+ finalizeSegments();
195
+ setThinkingLog([]);
196
+ sequenceBuffer.reset();
197
+ }, DONE_SAFETY_MS);
198
+ };
199
+
200
+ const cancelDoneTimer = () => {
201
+ if (doneTimer) {
202
+ clearTimeout(doneTimer);
203
+ doneTimer = null;
204
+ }
205
+ };
206
+
207
+ const sequenceBuffer = new SequenceBuffer<ChatEvent>({
208
+ onEvent: processEvent,
209
+ onGap(from, to) {
210
+ const count = to - from + 1;
211
+ const range = to > from ? `→${to}` : '';
212
+ onDebug(`⚠ ${count} event(s) lost (#${from}${range})`);
213
+ },
214
+ });
215
+
216
+ function processEvent(event: ChatEvent) {
217
+ // Ignore straggling events from an agent loop that's already finalized
218
+ if (event.agentLoopId && event.agentLoopId === finalizedAgentLoopId) {
219
+ onDebug(`⚠ ignoring late ${event.__typename} for finalized loop ${event.agentLoopId}`);
220
+ return;
221
+ }
222
+ // A new agentLoopId means a new turn — clear the finalized guard
223
+ if (event.agentLoopId && event.agentLoopId !== finalizedAgentLoopId) {
224
+ finalizedAgentLoopId = null;
225
+ }
226
+ if (event.agentLoopId) {
227
+ lastSeenAgentLoopId = event.agentLoopId;
228
+ }
229
+
230
+ // Any event arriving cancels the safety timer
231
+ cancelDoneTimer();
232
+
233
+ switch (event.__typename) {
234
+ case 'AgentLoopStartedEvent':
235
+ // New outer-loop run — reset per-turn state
236
+ break;
237
+ case 'AgentPickedEvent':
238
+ // Orchestrator picked a specialist for this turn. Currently not
239
+ // surfaced in the UI; logged for debug.
240
+ onDebug(`agent_picked turn=${event.turn ?? '?'} agent=${event.agent ?? '?'}`);
241
+ break;
242
+ case 'MessageStartedEvent':
243
+ saveSegment();
244
+ break;
245
+ case 'MessageChunkEvent': {
246
+ const chunk = event.content ?? '';
247
+ streamContentRef.current = (streamContentRef.current ?? '') + chunk;
248
+ setStreamContent(streamContentRef.current);
249
+ setWaitingForGreeting(false);
250
+ break;
251
+ }
252
+ case 'MessageEndedEvent':
253
+ saveSegment();
254
+ // Start safety timer in case AgentLoopCompletedEvent never arrives
255
+ startDoneTimer();
256
+ break;
257
+ case 'ToolCallEvent': {
258
+ const tool = parseToolCall(event.toolName ?? '', event.toolCallId ?? '', event.arguments);
259
+ appendToolLog(`CALL ${tool.label} [${event.toolCallId}]\n args: ${JSON.stringify(event.arguments)}`);
260
+ setThinkingLog((prev) => [...prev, { kind: 'tool_call', tool }]);
261
+ if (event.toolName === 'ask_choice' && event.toolCallId) {
262
+ const argsObj = (
263
+ typeof event.arguments === 'object' && event.arguments !== null ? event.arguments : {}
264
+ ) as Record<string, unknown>;
265
+ const rawOptions = Array.isArray(argsObj.options) ? argsObj.options : [];
266
+ const options = rawOptions.map((option) => String(option)).filter((option) => option.length > 0);
267
+ const question = String(argsObj.question ?? '');
268
+ if (options.length > 0 && question) {
269
+ setPendingChoice({ toolCallId: event.toolCallId, question, options });
270
+ }
271
+ }
272
+ break;
273
+ }
274
+ case 'ToolResultEvent': {
275
+ const resultContent = event.content ?? '';
276
+ appendToolLog(`RESULT [${event.toolCallId}]\n ${resultContent}`);
277
+ const isError = resultContent.includes('"errors"') || resultContent.includes('"error"');
278
+ setPendingChoice((prev) => (prev && prev.toolCallId === event.toolCallId ? null : prev));
279
+ setThinkingLog((prev) => {
280
+ // Find the matching tool_call and update it with the result
281
+ const updated = [...prev];
282
+ for (let i = updated.length - 1; i >= 0; i--) {
283
+ const entry = updated[i]!;
284
+ if (
285
+ entry.kind === 'tool_call' &&
286
+ entry.tool.toolCallId === event.toolCallId &&
287
+ !entry.tool.resultLabel
288
+ ) {
289
+ updated[i] = {
290
+ ...entry,
291
+ tool: {
292
+ ...entry.tool,
293
+ isError,
294
+ resultLabel: isError ? `✗ error` : `✓ done`,
295
+ },
296
+ };
297
+ break;
298
+ }
299
+ }
300
+ return updated;
301
+ });
302
+ break;
303
+ }
304
+ case 'SupervisorVerdictEvent':
305
+ // Supervisor decided whether the outer loop should continue. Logged
306
+ // for debug; no UI surface yet.
307
+ onDebug(`supervisor turn=${event.turn ?? '?'} verdict=${event.verdict ?? '?'}`);
308
+ break;
309
+ case 'AgentLoopCompletedEvent':
310
+ finalizedAgentLoopId = event.agentLoopId ?? null;
311
+ finalizeSegments();
312
+ setThinkingLog([]);
313
+ sequenceBuffer.reset();
314
+ break;
315
+ case 'AgentLoopCancelledEvent':
316
+ finalizedAgentLoopId = event.agentLoopId ?? null;
317
+ finalizeSegments();
318
+ setThinkingLog([]);
319
+ setPendingChoice(null);
320
+ sequenceBuffer.reset();
321
+ break;
322
+ case 'AgentLoopFailedEvent':
323
+ captureException(new Error(`Chat stream error: ${event.message}`), {
324
+ conversationId: activeConversationId,
325
+ event,
326
+ });
327
+ finalizedAgentLoopId = event.agentLoopId ?? null;
328
+ finalizeSegments();
329
+ setThinkingLog([]);
330
+ setErrorMsg(event.message ?? 'Unknown error');
331
+ sequenceBuffer.reset();
332
+ break;
333
+ }
334
+ }
335
+
336
+ // Reset per-stream state whenever the backend starts a new outer loop
337
+ // (e.g. a resume after ask_choice). Without this, events #1..#N from
338
+ // the new stream are dropped as duplicates because the buffer's
339
+ // `expected` counter is still pointing at the previous stream's tail.
340
+ let lastAgentLoopId: string | null = null;
341
+ conn.onMessage((event) => {
342
+ if (event.agentLoopId && event.agentLoopId !== lastAgentLoopId) {
343
+ sequenceBuffer.reset();
344
+ finalizedAgentLoopId = null;
345
+ lastAgentLoopId = event.agentLoopId;
346
+ }
347
+ sequenceBuffer.push(event);
348
+ });
349
+
350
+ conn.onClose(() => {
351
+ cancelDoneTimer();
352
+ finalizeSegments();
353
+ setStatus('error');
354
+ setErrorMsg('Connection closed.');
355
+ });
356
+
357
+ setConnection(conn);
358
+ setStatus('ready');
359
+ setInputDisabled(false);
360
+ } catch (err) {
361
+ captureException(err, { context: 'chat_init', conversationId: initialConversationId });
362
+ setStatus('error');
363
+ setErrorMsg(err instanceof Error ? err.message : String(err));
364
+ }
365
+ })();
366
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only init, inputs stable for session
367
+ }, []);
368
+
369
+ const sendMessage = useCallback(
370
+ async (content: string) => {
371
+ if (!conversationId) return;
372
+ setMessages((prev) => [...prev, { role: 'user', content }]);
373
+ setThinkingLog([]);
374
+ setInputKey((prev) => prev + 1);
375
+
376
+ try {
377
+ await graphql(SendMessage, { input: { conversationId, content } }, { endpoint, throwOnError: true });
378
+ } catch (err) {
379
+ captureException(err, { context: 'send_message', conversationId });
380
+ setErrorMsg('Failed to send message.');
381
+ }
382
+ },
383
+ [conversationId, endpoint],
384
+ );
385
+
386
+ const submitToolCallResponse = useCallback(
387
+ async (value: string) => {
388
+ if (!pendingChoice) return;
389
+ const toolCallId = pendingChoice.toolCallId;
390
+ setPendingChoice(null);
391
+ try {
392
+ await graphql(RespondToToolCall, { input: { toolCallId, value } }, { endpoint, throwOnError: true });
393
+ } catch (err) {
394
+ captureException(err, { context: 'respond_to_tool_call', toolCallId, value });
395
+ setErrorMsg('Failed to submit choice.');
396
+ }
397
+ },
398
+ [pendingChoice, endpoint],
399
+ );
400
+
401
+ const respondToChoice = useCallback(async (value: string) => submitToolCallResponse(value), [submitToolCallResponse]);
402
+
403
+ const cancelChoice = useCallback(
404
+ async () => submitToolCallResponse(CHOICE_CANCEL_SENTINEL),
405
+ [submitToolCallResponse],
406
+ );
407
+
408
+ const cancelStream = useCallback(async () => {
409
+ if (!conversationId) return;
410
+ try {
411
+ await graphql(CancelConversation, { input: { conversationId } }, { endpoint, throwOnError: true });
412
+ } catch (err) {
413
+ captureException(err, { context: 'cancel_conversation', conversationId });
414
+ setErrorMsg('Failed to stop chat.');
415
+ }
416
+ }, [conversationId, endpoint]);
417
+
418
+ const disconnect = useCallback(() => {
419
+ connection?.close();
420
+ }, [connection]);
421
+
422
+ return {
423
+ messages,
424
+ streamContent,
425
+ thinkingLog,
426
+ status,
427
+ errorMsg,
428
+ conversationId,
429
+ connection,
430
+ inputDisabled,
431
+ inputKey,
432
+ waitingForGreeting,
433
+ pendingChoice,
434
+ sendMessage,
435
+ respondToChoice,
436
+ cancelChoice,
437
+ cancelStream,
438
+ disconnect,
439
+ };
440
+ }
@@ -0,0 +1,23 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ export function useTerminalSize() {
4
+ const [size, setSize] = useState({
5
+ columns: process.stdout.columns ?? 80,
6
+ rows: process.stdout.rows ?? 24,
7
+ });
8
+
9
+ useEffect(() => {
10
+ const onResize = () => {
11
+ setSize({
12
+ columns: process.stdout.columns ?? 80,
13
+ rows: process.stdout.rows ?? 24,
14
+ });
15
+ };
16
+ process.stdout.on('resize', onResize);
17
+ return () => {
18
+ process.stdout.off('resize', onResize);
19
+ };
20
+ }, []);
21
+
22
+ return size;
23
+ }
@@ -0,0 +1,26 @@
1
+ import { render } from 'ink';
2
+ import React from 'react';
3
+
4
+ import { App } from './App.tsx';
5
+
6
+ interface LaunchOptions {
7
+ companyId: string;
8
+ conversationId?: string;
9
+ conversationTitle?: string;
10
+ endpoint: string;
11
+ }
12
+
13
+ export function launchInteractive(opts: LaunchOptions): void {
14
+ const instance = render(
15
+ <App
16
+ companyId={opts.companyId}
17
+ conversationId={opts.conversationId}
18
+ conversationTitle={opts.conversationTitle}
19
+ endpoint={opts.endpoint}
20
+ />,
21
+ );
22
+
23
+ instance.waitUntilExit().then(() => {
24
+ process.exit(0);
25
+ });
26
+ }
@@ -0,0 +1,29 @@
1
+ import { Marked, type Tokens } from 'marked';
2
+ import { markedTerminal } from 'marked-terminal';
3
+
4
+ const terminalExt = markedTerminal({
5
+ reflowText: true,
6
+ width: Math.min(process.stdout.columns ?? 80, 100) - 4,
7
+ tab: 2,
8
+ }) as Parameters<typeof Marked.prototype.use>[0];
9
+
10
+ const marked = new Marked(terminalExt, {
11
+ renderer: {
12
+ // Override link rendering to avoid "(mailto:...)" noise on email addresses.
13
+ // For mailto links, just show the email text. For URLs, show "text (url)".
14
+ link({ href, text }: Tokens.Link) {
15
+ if (href.startsWith('mailto:')) return text;
16
+ if (text === href) return href;
17
+ return `${text} (${href})`;
18
+ },
19
+ },
20
+ });
21
+
22
+ /**
23
+ * Render markdown string to terminal-formatted text.
24
+ * Strips trailing newlines to avoid extra spacing in Ink.
25
+ */
26
+ export function renderMarkdown(input: string): string {
27
+ const result = marked.parse(input, { async: false });
28
+ return result.replace(/\n+$/, '');
29
+ }
@@ -0,0 +1,34 @@
1
+ import type { ConversationEventSubscription } from '../../../graphql/generated/graphql.ts';
2
+
3
+ export interface Message {
4
+ role: 'user' | 'assistant';
5
+ content: string;
6
+ }
7
+
8
+ /**
9
+ * One event from the `conversationEvent` subscription — a discriminated union keyed
10
+ * by `__typename`. The union matches the inline fragments in `ConversationEvent`.
11
+ */
12
+ export type ChatEvent = ConversationEventSubscription['conversationEvent'];
13
+
14
+ export interface ChatConnection {
15
+ onMessage: (fn: (event: ChatEvent) => void) => void;
16
+ onClose: (fn: () => void) => void;
17
+ close: () => void;
18
+ }
19
+
20
+ export interface ToolCallInfo {
21
+ toolName: string;
22
+ toolCallId: string;
23
+ label: string; // e.g. "query GetCurrentUser" or "introspect Conversation"
24
+ isError: boolean;
25
+ resultLabel?: string; // e.g. "✓ done" or "✗ error: ..."
26
+ }
27
+
28
+ export interface PendingChoice {
29
+ toolCallId: string;
30
+ question: string;
31
+ options: string[];
32
+ }
33
+
34
+ export type ThinkingEntry = { kind: 'tool_call'; tool: ToolCallInfo };
@@ -0,0 +1,94 @@
1
+ import { Command } from 'commander';
2
+
3
+ import { clearCredentials } from '../lib/auth.ts';
4
+ import { loadConfig, resetConfig, saveConfig } from '../lib/config.ts';
5
+ import { isLocalDev } from '../lib/env.ts';
6
+ import { error, hint, info, isJsonMode, printJson, success } from '../lib/output.ts';
7
+
8
+ const PRODUCTION_ENDPOINT = 'https://federation.sortlist.com/graphql';
9
+ const STAGING_ENDPOINT = 'https://federation.sortlist-test.com/graphql';
10
+ const LOCAL_ENDPOINT = 'http://localhost:4020/graphql';
11
+
12
+ export const configCommand = new Command('config')
13
+ .summary('View or update CLI configuration')
14
+ .description(
15
+ 'View or update CLI configuration\n\n' +
16
+ 'Manage your endpoint, company context, and credentials.\n\n' +
17
+ 'Examples:\n' +
18
+ ' sl config show See current endpoint and company\n' +
19
+ ' sl config set endpoint <url> Point to a custom endpoint\n' +
20
+ ' sl config reset Clear all config and credentials',
21
+ );
22
+
23
+ configCommand
24
+ .command('show')
25
+ .description('Show current configuration')
26
+ .action(function (this: Command) {
27
+ const opts = this.optsWithGlobals();
28
+ const config = loadConfig();
29
+ if (isJsonMode(opts)) {
30
+ printJson(config);
31
+ } else {
32
+ info(`Endpoint: ${config.endpoint}`);
33
+ if (config.oauthId) info(`User: ${config.oauthId}`);
34
+ if (config.companyName) info(`Company: ${config.companyName} (${config.companySlug})`);
35
+ else if (config.companyId) info(`Company ID: ${config.companyId}`);
36
+ }
37
+ });
38
+
39
+ configCommand
40
+ .command('set <key> <value>')
41
+ .description('Set a config value (endpoint, companyId, companySlug)')
42
+ .action((key: string, value: string) => {
43
+ const allowed = ['endpoint', 'companyId', 'companySlug', 'companyName', 'oauthId'];
44
+ if (!allowed.includes(key)) {
45
+ error(`Unknown config key: "${key}".`);
46
+ info('');
47
+ info(' Allowed keys:');
48
+ for (const k of allowed) {
49
+ info(` ${k}`);
50
+ }
51
+ hint('Usage: sl config set <key> <value>');
52
+ process.exit(1);
53
+ }
54
+ saveConfig({ [key]: value });
55
+ success(`Set ${key} = ${value}`);
56
+ });
57
+
58
+ if (isLocalDev) {
59
+ configCommand
60
+ .command('use-production')
61
+ .description('Point CLI to production (federation.sortlist.com)')
62
+ .action(() => {
63
+ saveConfig({ endpoint: PRODUCTION_ENDPOINT });
64
+ success(`Endpoint set to ${PRODUCTION_ENDPOINT}`);
65
+ hint('Run `sl login` to authenticate against production.');
66
+ });
67
+
68
+ configCommand
69
+ .command('use-staging')
70
+ .description('Point CLI to staging (federation.sortlist-test.com)')
71
+ .action(() => {
72
+ saveConfig({ endpoint: STAGING_ENDPOINT });
73
+ success(`Endpoint set to ${STAGING_ENDPOINT}`);
74
+ hint('Run `sl login` to authenticate against staging.');
75
+ });
76
+
77
+ configCommand
78
+ .command('use-local')
79
+ .description('Point CLI to local development (localhost:4020)')
80
+ .action(() => {
81
+ saveConfig({ endpoint: LOCAL_ENDPOINT });
82
+ success(`Endpoint set to ${LOCAL_ENDPOINT}`);
83
+ });
84
+ }
85
+
86
+ configCommand
87
+ .command('reset')
88
+ .description('Reset all config and credentials')
89
+ .action(() => {
90
+ resetConfig();
91
+ clearCredentials();
92
+ success('Config and credentials cleared.');
93
+ hint('Run `sl login` to re-authenticate.');
94
+ });