MCPcopy Create free account
hub / github.com/code-with-antonio/nightcode / useChat

Function useChat

packages/cli/src/hooks/use-chat.ts:31–107  ·  view source on GitHub ↗
(sessionId: string, initialMessages: Message[])

Source from the content-addressed store, hash-verified

29export type Message = UIMessage<ChatMessageMetadata, never, ChatTools>;
30
31export function useChat(sessionId: string, initialMessages: Message[]) {
32 const transport = useMemo(() => {
33 return new DefaultChatTransport<Message>({
34 api: apiClient.chat.$url().toString(),
35 headers() {
36 const auth = getAuth();
37 return auth ? { Authorization: `Bearer ${auth.token}` } : new Headers();
38 },
39 prepareSendMessagesRequest({ messages }) {
40 const message = messages[messages.length - 1];
41 if (!message) throw new Error("No message to send");
42
43 const metadata = messages.findLast(
44 (m) => m.metadata?.mode && m.metadata?.model,
45 )?.metadata;
46 const previousMessage = messages[messages.length - 2];
47 const requestMessages =
48 message.role === "assistant" && previousMessage?.role === "user"
49 ? [previousMessage, message]
50 : [message];
51
52 return {
53 body: {
54 id: sessionId,
55 messages: requestMessages,
56 mode: message.metadata?.mode ?? metadata?.mode,
57 model: message.metadata?.model ?? metadata?.model,
58 },
59 }
60 }
61 });
62 }, [sessionId]);
63
64 const chat = useAiChat<Message>({
65 id: sessionId,
66 messages: initialMessages,
67 transport,
68 onToolCall({ toolCall }) {
69 const mode = chat.messages.at(-1)?.metadata?.mode ?? "BUILD";
70
71 void executeLocalTool(toolCall.toolName, toolCall.input, mode)
72 .then((output) =>
73 chat.addToolOutput({
74 tool: toolCall.toolName as keyof ChatTools,
75 toolCallId: toolCall.toolCallId,
76 output,
77 }),
78 )
79 .catch((error) =>
80 chat.addToolOutput({
81 tool: toolCall.toolName as keyof ChatTools,
82 toolCallId: toolCall.toolCallId,
83 state: "output-error",
84 errorText: error instanceof Error ? error.message : String(error),
85 }),
86 );
87 },
88 sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,

Callers 1

SessionChatFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected