@sortlist/cli 0.30.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 +0 -1
- 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 +0 -11
- 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,63 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,54 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,111 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -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
|
-
}
|