@sortlist/cli 0.29.0 → 0.31.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.
- package/README.md +1 -48
- package/package.json +2 -10
- package/src/commands/dynamic.ts +95 -7
- package/src/graphql/generated/gql.ts +3 -33
- package/src/graphql/generated/graphql.ts +420 -559
- package/src/graphql/operations/common.ts +0 -82
- package/src/index.ts +23 -12
- package/src/commands/chat/chat.ts +0 -302
- package/src/commands/chat/interactive/App.tsx +0 -119
- package/src/commands/chat/interactive/components/ChatInput.tsx +0 -115
- package/src/commands/chat/interactive/components/ChoicePrompt.tsx +0 -35
- package/src/commands/chat/interactive/components/MessageView.tsx +0 -63
- package/src/commands/chat/interactive/components/ThinkingBox.tsx +0 -54
- package/src/commands/chat/interactive/connection.ts +0 -111
- package/src/commands/chat/interactive/debug-log.ts +0 -19
- package/src/commands/chat/interactive/hooks/useChat.ts +0 -440
- package/src/commands/chat/interactive/hooks/useTerminalSize.ts +0 -23
- package/src/commands/chat/interactive/index.tsx +0 -26
- package/src/commands/chat/interactive/markdown.ts +0 -29
- package/src/commands/chat/interactive/types.ts +0 -34
- package/src/types/marked-terminal.d.ts +0 -20
|
@@ -1,440 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,26 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
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 };
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
declare module 'marked-terminal' {
|
|
2
|
-
import type { MarkedExtension } from 'marked';
|
|
3
|
-
|
|
4
|
-
interface MarkedTerminalOptions {
|
|
5
|
-
reflowText?: boolean;
|
|
6
|
-
width?: number;
|
|
7
|
-
tab?: number;
|
|
8
|
-
showSectionPrefix?: boolean;
|
|
9
|
-
unescape?: boolean;
|
|
10
|
-
emoji?: boolean;
|
|
11
|
-
tableOptions?: Record<string, unknown>;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function markedTerminal(
|
|
15
|
-
options?: MarkedTerminalOptions,
|
|
16
|
-
highlightOptions?: Record<string, unknown>,
|
|
17
|
-
): MarkedExtension;
|
|
18
|
-
|
|
19
|
-
export default class Renderer {}
|
|
20
|
-
}
|