@langchain/macaw-components 1.7.18 → 1.7.20
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/dist/catalog.json +798 -775
- package/dist/components/Banner/Banner.js +1 -1
- package/dist/components/Banner/Banner.js.map +1 -1
- package/dist/components/ChatPlan/ChatPlan.js +1 -1
- package/dist/components/ChatPlan/ChatPlan.js.map +1 -1
- package/dist/components/ChatThread/ChatThread.d.ts +59 -0
- package/dist/components/ChatThread/ChatThread.js +338 -0
- package/dist/components/ChatThread/ChatThread.js.map +1 -0
- package/dist/components/ChatThread/ChatThread.types.d.ts +284 -0
- package/dist/components/ChatThread/ChatThread.types.js +0 -0
- package/dist/components/ChatThread/ChatThreadContext.d.ts +34 -0
- package/dist/components/ChatThread/ChatThreadContext.js +53 -0
- package/dist/components/ChatThread/ChatThreadContext.js.map +1 -0
- package/dist/components/ChatThread/ChatThreadRequests.d.ts +1 -0
- package/dist/components/ChatThread/ChatThreadRequests.js +233 -0
- package/dist/components/ChatThread/ChatThreadRequests.js.map +1 -0
- package/dist/components/ChatThread/ChatThreadWork.d.ts +13 -0
- package/dist/components/ChatThread/ChatThreadWork.js +174 -0
- package/dist/components/ChatThread/ChatThreadWork.js.map +1 -0
- package/dist/components/ChatThread/deepAgentTools.d.ts +9 -0
- package/dist/components/ChatThread/deepAgentTools.js +215 -0
- package/dist/components/ChatThread/deepAgentTools.js.map +1 -0
- package/dist/components/ChatThread/index.d.ts +8 -0
- package/dist/components/ChatThread/index.js +6 -0
- package/dist/components/ChatThread/interrupts.d.ts +43 -0
- package/dist/components/ChatThread/interrupts.js +96 -0
- package/dist/components/ChatThread/interrupts.js.map +1 -0
- package/dist/components/ChatThread/messages.d.ts +29 -0
- package/dist/components/ChatThread/messages.js +137 -0
- package/dist/components/ChatThread/messages.js.map +1 -0
- package/dist/components/ChatThread/toChatThread.d.ts +12 -0
- package/dist/components/ChatThread/toChatThread.js +275 -0
- package/dist/components/ChatThread/toChatThread.js.map +1 -0
- package/dist/components/ChatThread/useLangGraphChatThread.d.ts +36 -0
- package/dist/components/ChatThread/useLangGraphChatThread.js +240 -0
- package/dist/components/ChatThread/useLangGraphChatThread.js.map +1 -0
- package/dist/components/ChatToolCall/ChatToolCallAccordion.js +1 -1
- package/dist/components/ChatToolCall/ChatToolCallAccordion.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallDetails.js +1 -1
- package/dist/components/ChatToolCall/ChatToolCallGroup.js +1 -1
- package/dist/components/ChatToolCall/ChatToolCallGroup.js.map +1 -1
- package/dist/components/MarkdownDisplay/MarkdownDisplay.js +1 -1
- package/dist/docs/phosphor-icon-catalog.js +2 -2
- package/dist/icons/LongTailPhosphorIcons.js +1 -1
- package/dist/utilities.css +1 -1
- package/docs/CHAT.md +109 -3
- package/docs/DESIGN.md +4 -1
- package/package.json +6 -2
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import type { ReactElement } from 'react';
|
|
2
|
+
import type { ChatMessageModel, ChatMessageStatus } from '../ChatMessage/index.js';
|
|
3
|
+
import type { ChatPlanItem } from '../ChatPlan/index.js';
|
|
4
|
+
import type { ChatToolCallModel, ChatToolCallProps, ChatToolCallStatus } from '../ChatToolCall/index.js';
|
|
5
|
+
/**
|
|
6
|
+
* The parts of a LangGraph `useStream` handle the chat reads. Every
|
|
7
|
+
* `@langchain/react` 1.x and 2.0 handle fits, and so does the 0.3.x handle
|
|
8
|
+
* from `@langchain/langgraph-sdk/react`. Macaw never imports the SDK, so the
|
|
9
|
+
* same code works whichever version or package alias an app installs.
|
|
10
|
+
*/
|
|
11
|
+
export interface ChatThreadStream {
|
|
12
|
+
readonly messages: readonly unknown[];
|
|
13
|
+
readonly values?: unknown;
|
|
14
|
+
/** 1.x: live tool calls with `running`, `finished`, or `error` status. */
|
|
15
|
+
readonly toolCalls?: readonly unknown[];
|
|
16
|
+
readonly interrupts?: readonly unknown[];
|
|
17
|
+
readonly interrupt?: unknown;
|
|
18
|
+
/** 1.x: subagents keyed by the ID of the tool call that started them. */
|
|
19
|
+
readonly subagents?: ReadonlyMap<string, unknown>;
|
|
20
|
+
readonly isLoading: boolean;
|
|
21
|
+
readonly isThreadLoading?: boolean;
|
|
22
|
+
readonly error?: unknown;
|
|
23
|
+
submit(input: unknown, options?: never): unknown;
|
|
24
|
+
stop(options?: never): unknown;
|
|
25
|
+
/** 1.x: resumes an interrupt by ID. 0.3.x resumes through `submit`. */
|
|
26
|
+
respond?(response: unknown, options?: never): unknown;
|
|
27
|
+
respondAll?(responsesById: Record<string, unknown>, options?: never): unknown;
|
|
28
|
+
/** 0.3.x: checkpoint metadata used to edit and retry. */
|
|
29
|
+
getMessagesMetadata?(message: never, index?: number): unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Selector hooks from `@langchain/react` 1.x or 2.0, passed in from the app's
|
|
33
|
+
* own import so Macaw never depends on a version or alias. Each is optional
|
|
34
|
+
* and turns on one feature. Pass a module-level object; it must not change
|
|
35
|
+
* between renders.
|
|
36
|
+
*/
|
|
37
|
+
export interface ChatThreadSelectors {
|
|
38
|
+
/** Queued messages and cancel. */
|
|
39
|
+
useSubmissionQueue?: (stream: never) => {
|
|
40
|
+
readonly entries: readonly unknown[];
|
|
41
|
+
cancel(id: string): Promise<boolean> | unknown;
|
|
42
|
+
};
|
|
43
|
+
/** Edit and retry, by forking from a message's checkpoint. */
|
|
44
|
+
useMessageMetadata?: (stream: never, messageId: string | undefined) => {
|
|
45
|
+
readonly parentCheckpointId?: string;
|
|
46
|
+
} | undefined;
|
|
47
|
+
/** A subagent's own messages, shown when its card is expanded. */
|
|
48
|
+
useMessages?: (stream: never, target?: never) => readonly unknown[];
|
|
49
|
+
/** A subagent's current step and tool calls. */
|
|
50
|
+
useToolCalls?: (stream: never, target?: never) => readonly unknown[];
|
|
51
|
+
}
|
|
52
|
+
/** What `toChatThread` reads; the field names match `useStream`. */
|
|
53
|
+
export interface ChatThreadSnapshot {
|
|
54
|
+
messages: readonly unknown[];
|
|
55
|
+
toolCalls?: readonly unknown[];
|
|
56
|
+
interrupts?: readonly unknown[];
|
|
57
|
+
values?: unknown;
|
|
58
|
+
subagents?: ReadonlyMap<string, unknown>;
|
|
59
|
+
/** Submission queue entries, such as `useSubmissionQueue(stream).entries`. */
|
|
60
|
+
queue?: readonly unknown[];
|
|
61
|
+
isLoading?: boolean;
|
|
62
|
+
error?: unknown;
|
|
63
|
+
}
|
|
64
|
+
export interface ToChatThreadOptions {
|
|
65
|
+
/** Message state key, matching `useStream`. Defaults to `messages`. */
|
|
66
|
+
messagesKey?: string;
|
|
67
|
+
/** Hide internal messages, such as ones with a reserved ID prefix. */
|
|
68
|
+
hideMessage?: (message: unknown) => boolean;
|
|
69
|
+
/** Tool calls that start a subagent. Defaults to deep agents' `task`. */
|
|
70
|
+
subagentTools?: readonly string[];
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The original messages behind a part, for renderers that need fields Macaw
|
|
74
|
+
* doesn't map, such as provider-specific content blocks or artifacts.
|
|
75
|
+
*/
|
|
76
|
+
export interface ChatThreadPartSource {
|
|
77
|
+
/** The AI message the part came from. */
|
|
78
|
+
message: unknown;
|
|
79
|
+
/** The tool result message, once the call returns. */
|
|
80
|
+
result?: unknown;
|
|
81
|
+
}
|
|
82
|
+
/** A delegated subagent run, such as a deep agent's `task` call. */
|
|
83
|
+
export interface ChatThreadSubagent {
|
|
84
|
+
/** The ID of the tool call that started it. */
|
|
85
|
+
id: string;
|
|
86
|
+
/** The subagent's type or name, such as "researcher". */
|
|
87
|
+
name: string;
|
|
88
|
+
/** The task it was given. */
|
|
89
|
+
task?: string;
|
|
90
|
+
status: ChatToolCallStatus;
|
|
91
|
+
elapsedMs?: number;
|
|
92
|
+
/** Wall-clock start, when the stream reports one. */
|
|
93
|
+
startedAt?: Date | number;
|
|
94
|
+
}
|
|
95
|
+
export type ChatThreadPart = ({
|
|
96
|
+
type: 'text';
|
|
97
|
+
id: string;
|
|
98
|
+
text: string;
|
|
99
|
+
streaming: boolean;
|
|
100
|
+
} | {
|
|
101
|
+
type: 'reasoning';
|
|
102
|
+
id: string;
|
|
103
|
+
text: string;
|
|
104
|
+
streaming: boolean;
|
|
105
|
+
} | {
|
|
106
|
+
type: 'tool-call';
|
|
107
|
+
id: string;
|
|
108
|
+
toolCall: ChatToolCallModel;
|
|
109
|
+
/** The pending interrupt that gates this call. */
|
|
110
|
+
interruptId?: string;
|
|
111
|
+
} | {
|
|
112
|
+
type: 'subagent';
|
|
113
|
+
id: string;
|
|
114
|
+
subagent: ChatThreadSubagent;
|
|
115
|
+
/** The subagent's final answer, once it returns. */
|
|
116
|
+
result?: string;
|
|
117
|
+
/**
|
|
118
|
+
* The adapter's handle for the run, passed to the controller's subagent
|
|
119
|
+
* hooks; `useLangGraphChatThread` uses the stream's subagent handle.
|
|
120
|
+
*/
|
|
121
|
+
handle?: unknown;
|
|
122
|
+
interruptId?: string;
|
|
123
|
+
} | {
|
|
124
|
+
type: 'image';
|
|
125
|
+
id: string;
|
|
126
|
+
url: string;
|
|
127
|
+
}) & {
|
|
128
|
+
source: ChatThreadPartSource;
|
|
129
|
+
};
|
|
130
|
+
/** A human message and everything the agent did in response. */
|
|
131
|
+
export interface ChatThreadTurn {
|
|
132
|
+
id: string;
|
|
133
|
+
/** Missing when the agent spoke first. */
|
|
134
|
+
user?: {
|
|
135
|
+
message: ChatMessageModel;
|
|
136
|
+
text: string;
|
|
137
|
+
/** The original message, for checkpoint metadata. */
|
|
138
|
+
raw: unknown;
|
|
139
|
+
};
|
|
140
|
+
/** The agent's reasoning, tool calls, subagents, and text, in order. */
|
|
141
|
+
parts: ChatThreadPart[];
|
|
142
|
+
status: ChatMessageStatus;
|
|
143
|
+
/** Tool calls and subagents in the turn. */
|
|
144
|
+
actionCount: number;
|
|
145
|
+
/** Set on a failed turn. */
|
|
146
|
+
error?: string;
|
|
147
|
+
}
|
|
148
|
+
export type ChatThreadDecisionType = 'approve' | 'edit' | 'reject' | 'respond';
|
|
149
|
+
export interface ChatThreadActionRequest {
|
|
150
|
+
name: string;
|
|
151
|
+
args: Record<string, unknown>;
|
|
152
|
+
description?: string;
|
|
153
|
+
allowedDecisions: readonly ChatThreadDecisionType[];
|
|
154
|
+
/** The tool call this request gates, when it is in the thread. */
|
|
155
|
+
toolCallId?: string;
|
|
156
|
+
}
|
|
157
|
+
export type ChatThreadInterrupt = {
|
|
158
|
+
/** A human-in-the-loop middleware request: one decision per action. */
|
|
159
|
+
kind: 'approval';
|
|
160
|
+
id: string;
|
|
161
|
+
requests: ChatThreadActionRequest[];
|
|
162
|
+
/** Python graphs use snake_case payloads; JavaScript, camelCase. */
|
|
163
|
+
casing: 'snake' | 'camel';
|
|
164
|
+
raw: unknown;
|
|
165
|
+
} | {
|
|
166
|
+
kind: 'other';
|
|
167
|
+
id: string;
|
|
168
|
+
value: unknown;
|
|
169
|
+
raw: unknown;
|
|
170
|
+
};
|
|
171
|
+
export type ChatThreadDecision = {
|
|
172
|
+
type: 'approve';
|
|
173
|
+
} | {
|
|
174
|
+
type: 'edit';
|
|
175
|
+
args: Record<string, unknown>;
|
|
176
|
+
} | {
|
|
177
|
+
type: 'reject';
|
|
178
|
+
message?: string;
|
|
179
|
+
} | {
|
|
180
|
+
type: 'respond';
|
|
181
|
+
message: string;
|
|
182
|
+
};
|
|
183
|
+
export interface ChatThreadQueuedMessage {
|
|
184
|
+
id: string;
|
|
185
|
+
text: string;
|
|
186
|
+
}
|
|
187
|
+
export interface ChatThreadFile {
|
|
188
|
+
path: string;
|
|
189
|
+
modifiedAt?: string;
|
|
190
|
+
}
|
|
191
|
+
export interface ChatThreadModel {
|
|
192
|
+
turns: ChatThreadTurn[];
|
|
193
|
+
/** Pending interrupts, oldest first. */
|
|
194
|
+
interrupts: ChatThreadInterrupt[];
|
|
195
|
+
queued: ChatThreadQueuedMessage[];
|
|
196
|
+
/** A deep agent's todos, from `values.todos`. */
|
|
197
|
+
plan?: ChatPlanItem[];
|
|
198
|
+
/** A deep agent's files, from `values.files`. */
|
|
199
|
+
files?: ChatThreadFile[];
|
|
200
|
+
status: 'idle' | 'running' | 'interrupted' | 'failed';
|
|
201
|
+
error?: string;
|
|
202
|
+
}
|
|
203
|
+
export type ChatThreadToolPresentation = Pick<ChatToolCallProps, 'label' | 'icon' | 'summary' | 'meta' | 'children'>;
|
|
204
|
+
/**
|
|
205
|
+
* Presents one tool by name. Return row props to keep the shared tool row,
|
|
206
|
+
* your own element to replace it, or null to hide the call. `source` holds
|
|
207
|
+
* the original messages for calls in the thread; approval cards and live
|
|
208
|
+
* status lines render before a call has one.
|
|
209
|
+
*/
|
|
210
|
+
export type ChatThreadToolRenderer = (toolCall: ChatToolCallModel, source?: ChatThreadPartSource) => ChatThreadToolPresentation | ReactElement | null;
|
|
211
|
+
/**
|
|
212
|
+
* What `ChatThread` can do on the reader's behalf. `useLangGraphChatThread`
|
|
213
|
+
* provides all of them.
|
|
214
|
+
*/
|
|
215
|
+
export interface ChatThreadActions {
|
|
216
|
+
/** Sends a message, or queues it while a run is active. */
|
|
217
|
+
send: (text: string) => Promise<void>;
|
|
218
|
+
/** Stops the active run; `stopping` is true until it settles. */
|
|
219
|
+
stop: () => Promise<void>;
|
|
220
|
+
/** Answers a human-in-the-loop request: one decision per action. */
|
|
221
|
+
respond: (interruptId: string, decisions: readonly ChatThreadDecision[]) => Promise<void>;
|
|
222
|
+
/** Resumes interrupts with raw values, together, keyed by interrupt ID. */
|
|
223
|
+
resume: (valuesById: Record<string, unknown>) => Promise<void>;
|
|
224
|
+
/** Removes a queued message before it sends. */
|
|
225
|
+
cancelQueued: (id: string) => Promise<void>;
|
|
226
|
+
/**
|
|
227
|
+
* Sends `text` from an earlier checkpoint, replacing what followed it: an
|
|
228
|
+
* edit, or a retry with the original text.
|
|
229
|
+
*/
|
|
230
|
+
fork: (text: string, forkPoint: unknown) => Promise<void>;
|
|
231
|
+
}
|
|
232
|
+
export interface ChatThreadTiming {
|
|
233
|
+
/**
|
|
234
|
+
* When the turn started working, moved later by any time it spent paused
|
|
235
|
+
* on an interrupt, so `endedAt - startedAt` is the time spent working.
|
|
236
|
+
*/
|
|
237
|
+
startedAt: number;
|
|
238
|
+
endedAt?: number;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Everything `ChatThread` renders from and calls. `useLangGraphChatThread`
|
|
242
|
+
* builds one from a LangGraph `useStream` handle; an app with its own stream
|
|
243
|
+
* or data builds one itself. Only `model` and `actions.send` are required:
|
|
244
|
+
* leave out an action or hook and the control or detail that needs it is
|
|
245
|
+
* hidden.
|
|
246
|
+
*/
|
|
247
|
+
export interface ChatThreadController {
|
|
248
|
+
/** Render-ready turns, interrupts, queue, plan, and run status. */
|
|
249
|
+
model: ChatThreadModel;
|
|
250
|
+
/**
|
|
251
|
+
* `send` is required. Without `stop` there's no Stop button, without
|
|
252
|
+
* `cancelQueued` queued messages can't be cancelled, and without `fork`
|
|
253
|
+
* there's no edit or retry. The built-in request cards answer through
|
|
254
|
+
* `resume`.
|
|
255
|
+
*/
|
|
256
|
+
actions: Pick<ChatThreadActions, 'send'> & Partial<ChatThreadActions>;
|
|
257
|
+
/** Shows a loading placeholder in place of the conversation. */
|
|
258
|
+
isThreadLoading?: boolean;
|
|
259
|
+
/** A stop is pending. */
|
|
260
|
+
stopping?: boolean;
|
|
261
|
+
/** When each turn's work started and ended, for "Worked for 12s". */
|
|
262
|
+
timings?: Readonly<Record<string, ChatThreadTiming>>;
|
|
263
|
+
/** The message the reader sent most recently; it pins to the top. */
|
|
264
|
+
sentMessageId?: string;
|
|
265
|
+
/**
|
|
266
|
+
* Hook returning the fork point for a turn's user message, or undefined
|
|
267
|
+
* when it can't be edited or retried. Called once per user message, so
|
|
268
|
+
* keep it present or absent for the life of the thread.
|
|
269
|
+
*/
|
|
270
|
+
useForkPoint?: (turn: ChatThreadTurn) => unknown;
|
|
271
|
+
/**
|
|
272
|
+
* Hook returning a subagent's own parts, shown when its row is expanded.
|
|
273
|
+
* Without it, subagent rows don't expand.
|
|
274
|
+
*/
|
|
275
|
+
useSubagentTranscript?: (handle: unknown, running: boolean) => ChatThreadPart[];
|
|
276
|
+
/**
|
|
277
|
+
* Hook returning the tool call a running subagent is on, for its row's
|
|
278
|
+
* summary. Receives undefined once the subagent stops.
|
|
279
|
+
*/
|
|
280
|
+
useSubagentStep?: (handle: unknown) => {
|
|
281
|
+
name: string;
|
|
282
|
+
args?: unknown;
|
|
283
|
+
} | undefined;
|
|
284
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
2
|
+
import type { ChatToolCallModel } from '../ChatToolCall/index.js';
|
|
3
|
+
import type { ChatThreadController, ChatThreadInterrupt, ChatThreadPart, ChatThreadPartSource, ChatThreadSubagent, ChatThreadToolPresentation, ChatThreadToolRenderer } from './ChatThread.types.js';
|
|
4
|
+
export interface ThreadContextValue {
|
|
5
|
+
thread: ChatThreadController;
|
|
6
|
+
tools: Record<string, ChatThreadToolRenderer>;
|
|
7
|
+
agentName?: string;
|
|
8
|
+
renderInterrupt?: (interrupt: ChatThreadInterrupt, thread: ChatThreadController) => ReactNode | undefined;
|
|
9
|
+
onOpenSubagent?: (subagent: ChatThreadSubagent) => void;
|
|
10
|
+
}
|
|
11
|
+
export declare const ThreadContext: import("react").Context<ThreadContextValue | null>;
|
|
12
|
+
export declare function useThread(): ThreadContextValue;
|
|
13
|
+
export type ToolPresentation = {
|
|
14
|
+
kind: 'row';
|
|
15
|
+
props: ChatThreadToolPresentation;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'element';
|
|
18
|
+
element: ReactElement;
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'hidden';
|
|
21
|
+
};
|
|
22
|
+
export declare function present(tools: Record<string, ChatThreadToolRenderer>, toolCall: ChatToolCallModel, source?: ChatThreadPartSource): ToolPresentation;
|
|
23
|
+
export declare function plainText(text: string): string;
|
|
24
|
+
/** Answers interrupts through the controller, which may not support it. */
|
|
25
|
+
export declare function resume(thread: ChatThreadController, valuesById: Record<string, unknown>): Promise<void>;
|
|
26
|
+
export declare function errorText(error: unknown): string;
|
|
27
|
+
/**
|
|
28
|
+
* Work comes before the answer: everything up to the agent's last step. Text
|
|
29
|
+
* and images after it are the answer.
|
|
30
|
+
*/
|
|
31
|
+
export declare function splitParts(parts: ChatThreadPart[]): {
|
|
32
|
+
work: ChatThreadPart[];
|
|
33
|
+
answer: ChatThreadPart[];
|
|
34
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createContext, isValidElement, useContext } from "react";
|
|
2
|
+
//#region packages/components/src/components/ChatThread/ChatThreadContext.ts
|
|
3
|
+
var ThreadContext = createContext(null);
|
|
4
|
+
function useThread() {
|
|
5
|
+
const context = useContext(ThreadContext);
|
|
6
|
+
if (!context) throw new Error("Chat thread parts must be inside ChatThread.");
|
|
7
|
+
return context;
|
|
8
|
+
}
|
|
9
|
+
function present(tools, toolCall, source) {
|
|
10
|
+
const output = tools[toolCall.name]?.(toolCall, source);
|
|
11
|
+
if (output === void 0) return {
|
|
12
|
+
kind: "row",
|
|
13
|
+
props: {}
|
|
14
|
+
};
|
|
15
|
+
if (output === null) return { kind: "hidden" };
|
|
16
|
+
if (isValidElement(output)) return {
|
|
17
|
+
kind: "element",
|
|
18
|
+
element: output
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
kind: "row",
|
|
22
|
+
props: output
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function plainText(text) {
|
|
26
|
+
return text.replace(/```[\s\S]*?```/g, " ").replace(/^#{1,6}\s+/gm, "").replace(/[*_`>]/g, "").replace(/\s+/g, " ").trim();
|
|
27
|
+
}
|
|
28
|
+
/** Answers interrupts through the controller, which may not support it. */
|
|
29
|
+
function resume(thread, valuesById) {
|
|
30
|
+
if (!thread.actions.resume) return Promise.reject(/* @__PURE__ */ new Error("This chat can’t answer requests."));
|
|
31
|
+
return thread.actions.resume(valuesById);
|
|
32
|
+
}
|
|
33
|
+
function errorText(error) {
|
|
34
|
+
return error instanceof Error && error.message ? error.message : "Could not send your response.";
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Work comes before the answer: everything up to the agent's last step. Text
|
|
38
|
+
* and images after it are the answer.
|
|
39
|
+
*/
|
|
40
|
+
function splitParts(parts) {
|
|
41
|
+
let lastWork = -1;
|
|
42
|
+
parts.forEach((part, index) => {
|
|
43
|
+
if (part.type !== "text" && part.type !== "image") lastWork = index;
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
work: parts.slice(0, lastWork + 1),
|
|
47
|
+
answer: parts.slice(lastWork + 1)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { ThreadContext, errorText, plainText, present, resume, splitParts, useThread };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=ChatThreadContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatThreadContext.js","names":[],"sources":["../../../src/components/ChatThread/ChatThreadContext.ts"],"sourcesContent":["import {\n createContext,\n isValidElement,\n type ReactElement,\n type ReactNode,\n useContext,\n} from 'react';\n\nimport type { ChatToolCallModel } from '../ChatToolCall';\nimport type {\n ChatThreadController,\n ChatThreadInterrupt,\n ChatThreadPart,\n ChatThreadPartSource,\n ChatThreadSubagent,\n ChatThreadToolPresentation,\n ChatThreadToolRenderer,\n} from './ChatThread.types';\n\nexport interface ThreadContextValue {\n thread: ChatThreadController;\n tools: Record<string, ChatThreadToolRenderer>;\n agentName?: string;\n renderInterrupt?: (\n interrupt: ChatThreadInterrupt,\n thread: ChatThreadController\n ) => ReactNode | undefined;\n onOpenSubagent?: (subagent: ChatThreadSubagent) => void;\n}\n\nexport const ThreadContext = createContext<ThreadContextValue | null>(null);\n\nexport function useThread() {\n const context = useContext(ThreadContext);\n if (!context) throw new Error('Chat thread parts must be inside ChatThread.');\n return context;\n}\n\nexport type ToolPresentation =\n | { kind: 'row'; props: ChatThreadToolPresentation }\n | { kind: 'element'; element: ReactElement }\n | { kind: 'hidden' };\n\nexport function present(\n tools: Record<string, ChatThreadToolRenderer>,\n toolCall: ChatToolCallModel,\n source?: ChatThreadPartSource\n): ToolPresentation {\n const output = tools[toolCall.name]?.(toolCall, source);\n if (output === undefined) return { kind: 'row', props: {} };\n if (output === null) return { kind: 'hidden' };\n if (isValidElement(output)) return { kind: 'element', element: output };\n return { kind: 'row', props: output };\n}\n\nexport function plainText(text: string) {\n // Results preview in a few lines, so drop Markdown syntax that would show.\n return text\n .replace(/```[\\s\\S]*?```/g, ' ')\n .replace(/^#{1,6}\\s+/gm, '')\n .replace(/[*_`>]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/** Answers interrupts through the controller, which may not support it. */\nexport function resume(\n thread: ChatThreadController,\n valuesById: Record<string, unknown>\n) {\n if (!thread.actions.resume) {\n return Promise.reject(new Error('This chat can’t answer requests.'));\n }\n return thread.actions.resume(valuesById);\n}\n\nexport function errorText(error: unknown) {\n return error instanceof Error && error.message\n ? error.message\n : 'Could not send your response.';\n}\n\n/**\n * Work comes before the answer: everything up to the agent's last step. Text\n * and images after it are the answer.\n */\nexport function splitParts(parts: ChatThreadPart[]) {\n let lastWork = -1;\n parts.forEach((part, index) => {\n if (part.type !== 'text' && part.type !== 'image') lastWork = index;\n });\n return {\n work: parts.slice(0, lastWork + 1),\n answer: parts.slice(lastWork + 1),\n };\n}\n"],"mappings":";;AA8BA,IAAa,gBAAgB,cAAyC,IAAI;AAE1E,SAAgB,YAAY;CAC1B,MAAM,UAAU,WAAW,aAAa;CACxC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,8CAA8C;CAC5E,OAAO;AACT;AAOA,SAAgB,QACd,OACA,UACA,QACkB;CAClB,MAAM,SAAS,MAAM,SAAS,KAAK,GAAG,UAAU,MAAM;CACtD,IAAI,WAAW,KAAA,GAAW,OAAO;EAAE,MAAM;EAAO,OAAO,CAAC;CAAE;CAC1D,IAAI,WAAW,MAAM,OAAO,EAAE,MAAM,SAAS;CAC7C,IAAI,eAAe,MAAM,GAAG,OAAO;EAAE,MAAM;EAAW,SAAS;CAAO;CACtE,OAAO;EAAE,MAAM;EAAO,OAAO;CAAO;AACtC;AAEA,SAAgB,UAAU,MAAc;CAEtC,OAAO,KACJ,QAAQ,mBAAmB,GAAG,CAAC,CAC/B,QAAQ,gBAAgB,EAAE,CAAC,CAC3B,QAAQ,WAAW,EAAE,CAAC,CACtB,QAAQ,QAAQ,GAAG,CAAC,CACpB,KAAK;AACV;;AAGA,SAAgB,OACd,QACA,YACA;CACA,IAAI,CAAC,OAAO,QAAQ,QAClB,OAAO,QAAQ,uBAAO,IAAI,MAAM,kCAAkC,CAAC;CAErE,OAAO,OAAO,QAAQ,OAAO,UAAU;AACzC;AAEA,SAAgB,UAAU,OAAgB;CACxC,OAAO,iBAAiB,SAAS,MAAM,UACnC,MAAM,UACN;AACN;;;;;AAMA,SAAgB,WAAW,OAAyB;CAClD,IAAI,WAAW;CACf,MAAM,SAAS,MAAM,UAAU;EAC7B,IAAI,KAAK,SAAS,UAAU,KAAK,SAAS,SAAS,WAAW;CAChE,CAAC;CACD,OAAO;EACL,MAAM,MAAM,MAAM,GAAG,WAAW,CAAC;EACjC,QAAQ,MAAM,MAAM,WAAW,CAAC;CAClC;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function InterruptRequests(): import("react").JSX.Element;
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { Textarea } from "../Textarea/Textarea.js";
|
|
2
|
+
import { ChatRichContent } from "../ChatRichContent/ChatRichContent.js";
|
|
3
|
+
import { CodeLite } from "../Code/CodeLite.js";
|
|
4
|
+
import { errorText, present, resume, useThread } from "./ChatThreadContext.js";
|
|
5
|
+
import { toHumanInTheLoopResponse } from "./interrupts.js";
|
|
6
|
+
import { Fragment, useState } from "react";
|
|
7
|
+
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
8
|
+
//#region packages/components/src/components/ChatThread/ChatThreadRequests.tsx
|
|
9
|
+
function argsText(args) {
|
|
10
|
+
return JSON.stringify(args, null, 2);
|
|
11
|
+
}
|
|
12
|
+
function shortDescription(description) {
|
|
13
|
+
return description && description.length <= 140 && !description.includes("\n") ? description : void 0;
|
|
14
|
+
}
|
|
15
|
+
function ApprovalRequest({ request, fallbackId, state, onDecide, onUndo }) {
|
|
16
|
+
const { tools } = useThread();
|
|
17
|
+
const [reason, setReason] = useState("");
|
|
18
|
+
const [reply, setReply] = useState("");
|
|
19
|
+
const [draftArgs, setDraftArgs] = useState(() => argsText(request.args));
|
|
20
|
+
const [argsError, setArgsError] = useState();
|
|
21
|
+
const toolCall = {
|
|
22
|
+
id: request.toolCallId ?? fallbackId,
|
|
23
|
+
name: request.name,
|
|
24
|
+
status: "input-required",
|
|
25
|
+
args: request.args
|
|
26
|
+
};
|
|
27
|
+
const presentation = present(tools, toolCall);
|
|
28
|
+
const props = presentation.kind === "row" ? presentation.props : {};
|
|
29
|
+
const label = props.label ?? request.name;
|
|
30
|
+
const title = typeof props.summary === "string" ? `${label}: ${props.summary}` : label;
|
|
31
|
+
const allowed = new Set(request.allowedDecisions);
|
|
32
|
+
const description = shortDescription(request.description) ?? "The agent is waiting for your approval to run this.";
|
|
33
|
+
let cardState = "unanswered";
|
|
34
|
+
let message;
|
|
35
|
+
if (state.submitting) cardState = "submitting";
|
|
36
|
+
else if (state.failure) {
|
|
37
|
+
cardState = "submission-failed";
|
|
38
|
+
message = state.failure;
|
|
39
|
+
} else if (argsError) {
|
|
40
|
+
cardState = "validation-error";
|
|
41
|
+
message = argsError;
|
|
42
|
+
} else if (state.decision) {
|
|
43
|
+
cardState = state.decision.type === "reject" ? "rejected" : "approved";
|
|
44
|
+
if (state.remaining > 0) message = `${cardState === "rejected" ? "Rejected" : "Approved"} · waiting for ${state.remaining} more ${state.remaining === 1 ? "decision" : "decisions"}`;
|
|
45
|
+
}
|
|
46
|
+
if (allowed.has("respond") && !allowed.has("approve")) return /* @__PURE__ */ jsx(ChatRichContent, {
|
|
47
|
+
title,
|
|
48
|
+
description: shortDescription(request.description) ?? "The agent asked for your reply.",
|
|
49
|
+
state: state.submitting ? "submitting" : state.failure ? "submission-failed" : state.decision ? "submitted" : "unanswered",
|
|
50
|
+
message: state.failure,
|
|
51
|
+
submitLabel: "Send reply",
|
|
52
|
+
onSubmit: () => onDecide({
|
|
53
|
+
type: "respond",
|
|
54
|
+
message: reply.trim()
|
|
55
|
+
}),
|
|
56
|
+
children: ({ disabled, isError, errorId }) => /* @__PURE__ */ jsx(Textarea, {
|
|
57
|
+
label: "Reply",
|
|
58
|
+
value: reply,
|
|
59
|
+
onChange: setReply,
|
|
60
|
+
rows: 3,
|
|
61
|
+
resize: "vertical",
|
|
62
|
+
disabled,
|
|
63
|
+
isError,
|
|
64
|
+
"aria-describedby": errorId
|
|
65
|
+
})
|
|
66
|
+
});
|
|
67
|
+
return /* @__PURE__ */ jsx(ChatRichContent, {
|
|
68
|
+
variant: "approval",
|
|
69
|
+
title,
|
|
70
|
+
description,
|
|
71
|
+
state: cardState,
|
|
72
|
+
message,
|
|
73
|
+
onApprove: allowed.has("approve") ? () => onDecide({ type: "approve" }) : void 0,
|
|
74
|
+
onReject: allowed.has("reject") ? (text) => onDecide({
|
|
75
|
+
type: "reject",
|
|
76
|
+
message: text.trim() || void 0
|
|
77
|
+
}) : void 0,
|
|
78
|
+
rejectionReason: allowed.has("reject") ? {
|
|
79
|
+
value: reason,
|
|
80
|
+
onChange: setReason
|
|
81
|
+
} : void 0,
|
|
82
|
+
onUndo: state.submitting ? void 0 : onUndo,
|
|
83
|
+
edit: allowed.has("edit") ? {
|
|
84
|
+
label: "Edit",
|
|
85
|
+
submitLabel: "Approve with edits",
|
|
86
|
+
content: ({ disabled, isError, errorId }) => /* @__PURE__ */ jsx(Textarea, {
|
|
87
|
+
label: "Arguments",
|
|
88
|
+
value: draftArgs,
|
|
89
|
+
onChange: (value) => {
|
|
90
|
+
setDraftArgs(value);
|
|
91
|
+
setArgsError(void 0);
|
|
92
|
+
},
|
|
93
|
+
rows: 6,
|
|
94
|
+
resize: "vertical",
|
|
95
|
+
className: "font-mono",
|
|
96
|
+
disabled,
|
|
97
|
+
isError,
|
|
98
|
+
"aria-describedby": errorId
|
|
99
|
+
}),
|
|
100
|
+
onSubmit: async () => {
|
|
101
|
+
let parsed;
|
|
102
|
+
try {
|
|
103
|
+
parsed = JSON.parse(draftArgs);
|
|
104
|
+
} catch {
|
|
105
|
+
parsed = void 0;
|
|
106
|
+
}
|
|
107
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
108
|
+
setArgsError("Enter the arguments as a JSON object.");
|
|
109
|
+
throw new Error("Invalid arguments");
|
|
110
|
+
}
|
|
111
|
+
await onDecide({
|
|
112
|
+
type: "edit",
|
|
113
|
+
args: parsed
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
} : void 0,
|
|
117
|
+
children: props.children ?? /* @__PURE__ */ jsx(CodeLite, {
|
|
118
|
+
value: argsText(request.args),
|
|
119
|
+
language: "json",
|
|
120
|
+
variant: "block",
|
|
121
|
+
label: "Arguments"
|
|
122
|
+
})
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
function OtherInterrupt({ interrupt }) {
|
|
126
|
+
const { thread } = useThread();
|
|
127
|
+
const [response, setResponse] = useState("");
|
|
128
|
+
const [state, setState] = useState("unanswered");
|
|
129
|
+
const [failure, setFailure] = useState();
|
|
130
|
+
const question = typeof interrupt.value === "string" ? interrupt.value : void 0;
|
|
131
|
+
return /* @__PURE__ */ jsx(ChatRichContent, {
|
|
132
|
+
title: question && question.length <= 140 ? question : "The agent needs your input",
|
|
133
|
+
description: "Your response resumes the run.",
|
|
134
|
+
state,
|
|
135
|
+
message: failure,
|
|
136
|
+
submitLabel: "Send",
|
|
137
|
+
onSubmit: async () => {
|
|
138
|
+
setState("submitting");
|
|
139
|
+
try {
|
|
140
|
+
await resume(thread, { [interrupt.id]: response });
|
|
141
|
+
setState("submitted");
|
|
142
|
+
} catch (error) {
|
|
143
|
+
setFailure(errorText(error));
|
|
144
|
+
setState("submission-failed");
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
children: ({ disabled, isError, errorId }) => /* @__PURE__ */ jsxs(Fragment$1, { children: [question === void 0 && interrupt.value !== void 0 && /* @__PURE__ */ jsx(CodeLite, {
|
|
149
|
+
value: JSON.stringify(interrupt.value, null, 2),
|
|
150
|
+
language: "json",
|
|
151
|
+
variant: "block",
|
|
152
|
+
label: "Request"
|
|
153
|
+
}), /* @__PURE__ */ jsx(Textarea, {
|
|
154
|
+
label: "Response",
|
|
155
|
+
value: response,
|
|
156
|
+
onChange: setResponse,
|
|
157
|
+
rows: 3,
|
|
158
|
+
resize: "vertical",
|
|
159
|
+
disabled,
|
|
160
|
+
isError,
|
|
161
|
+
"aria-describedby": errorId
|
|
162
|
+
})] })
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
function InterruptRequests() {
|
|
166
|
+
const { thread, renderInterrupt } = useThread();
|
|
167
|
+
const { interrupts } = thread.model;
|
|
168
|
+
const [decisions, setDecisions] = useState({});
|
|
169
|
+
const [submitting, setSubmitting] = useState(false);
|
|
170
|
+
const [failure, setFailure] = useState();
|
|
171
|
+
const key = interrupts.map((interrupt) => interrupt.id).join("|");
|
|
172
|
+
const [decisionsFor, setDecisionsFor] = useState(key);
|
|
173
|
+
if (decisionsFor !== key) {
|
|
174
|
+
setDecisionsFor(key);
|
|
175
|
+
setDecisions({});
|
|
176
|
+
setSubmitting(false);
|
|
177
|
+
setFailure(void 0);
|
|
178
|
+
}
|
|
179
|
+
const custom = new Map(interrupts.map((interrupt) => [interrupt.id, renderInterrupt?.(interrupt, thread)]));
|
|
180
|
+
const approvals = interrupts.filter((interrupt) => interrupt.kind === "approval" && custom.get(interrupt.id) === void 0);
|
|
181
|
+
const total = approvals.reduce((sum, interrupt) => sum + interrupt.requests.length, 0);
|
|
182
|
+
const decided = approvals.reduce((sum, interrupt) => sum + interrupt.requests.filter((_, index) => decisions[interrupt.id]?.[index]).length, 0);
|
|
183
|
+
async function decide(interruptId, index, decision) {
|
|
184
|
+
const current = [...decisions[interruptId] ?? []];
|
|
185
|
+
current[index] = decision;
|
|
186
|
+
const next = {
|
|
187
|
+
...decisions,
|
|
188
|
+
[interruptId]: current
|
|
189
|
+
};
|
|
190
|
+
setDecisions(next);
|
|
191
|
+
setFailure(void 0);
|
|
192
|
+
if (!approvals.every((interrupt) => interrupt.requests.every((_, requestIndex) => next[interrupt.id]?.[requestIndex]))) return;
|
|
193
|
+
setSubmitting(true);
|
|
194
|
+
try {
|
|
195
|
+
await resume(thread, Object.fromEntries(approvals.map((interrupt) => [interrupt.id, toHumanInTheLoopResponse(interrupt, next[interrupt.id])])));
|
|
196
|
+
} catch (error) {
|
|
197
|
+
setFailure(errorText(error));
|
|
198
|
+
setSubmitting(false);
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return /* @__PURE__ */ jsx("div", {
|
|
203
|
+
className: "flex min-w-0 flex-col gap-space-3",
|
|
204
|
+
children: interrupts.map((interrupt) => {
|
|
205
|
+
const rendered = custom.get(interrupt.id);
|
|
206
|
+
if (rendered !== void 0) return /* @__PURE__ */ jsx(Fragment, { children: rendered }, interrupt.id);
|
|
207
|
+
if (interrupt.kind === "other") return /* @__PURE__ */ jsx(OtherInterrupt, { interrupt }, interrupt.id);
|
|
208
|
+
return interrupt.requests.map((request, index) => /* @__PURE__ */ jsx(ApprovalRequest, {
|
|
209
|
+
request,
|
|
210
|
+
fallbackId: `${interrupt.id}:${index}`,
|
|
211
|
+
state: {
|
|
212
|
+
decision: decisions[interrupt.id]?.[index],
|
|
213
|
+
submitting,
|
|
214
|
+
failure,
|
|
215
|
+
remaining: total - decided
|
|
216
|
+
},
|
|
217
|
+
onDecide: (decision) => decide(interrupt.id, index, decision),
|
|
218
|
+
onUndo: () => setDecisions((current) => {
|
|
219
|
+
const list = [...current[interrupt.id] ?? []];
|
|
220
|
+
list[index] = void 0;
|
|
221
|
+
return {
|
|
222
|
+
...current,
|
|
223
|
+
[interrupt.id]: list
|
|
224
|
+
};
|
|
225
|
+
})
|
|
226
|
+
}, `${interrupt.id}:${index}`));
|
|
227
|
+
})
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
//#endregion
|
|
231
|
+
export { InterruptRequests };
|
|
232
|
+
|
|
233
|
+
//# sourceMappingURL=ChatThreadRequests.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatThreadRequests.js","names":[],"sources":["../../../src/components/ChatThread/ChatThreadRequests.tsx"],"sourcesContent":["import { Fragment, useState } from 'react';\n\nimport { ChatRichContent, type ChatRichContentState } from '../ChatRichContent';\nimport type { ChatToolCallModel } from '../ChatToolCall';\nimport { CodeLite } from '../Code/CodeLite';\nimport { Textarea } from '../Textarea';\nimport type {\n ChatThreadActionRequest,\n ChatThreadDecision,\n ChatThreadInterrupt,\n} from './ChatThread.types';\nimport { errorText, present, resume, useThread } from './ChatThreadContext';\nimport { toHumanInTheLoopResponse } from './interrupts';\n\nfunction argsText(args: Record<string, unknown>) {\n return JSON.stringify(args, null, 2);\n}\n\nfunction shortDescription(description: string | undefined) {\n return description && description.length <= 140 && !description.includes('\\n')\n ? description\n : undefined;\n}\n\ninterface DecisionState {\n decision?: ChatThreadDecision;\n submitting: boolean;\n failure?: string;\n remaining: number;\n}\n\nfunction ApprovalRequest({\n request,\n fallbackId,\n state,\n onDecide,\n onUndo,\n}: {\n request: ChatThreadActionRequest;\n fallbackId: string;\n state: DecisionState;\n onDecide: (decision: ChatThreadDecision) => Promise<void>;\n onUndo: () => void;\n}) {\n const { tools } = useThread();\n const [reason, setReason] = useState('');\n const [reply, setReply] = useState('');\n const [draftArgs, setDraftArgs] = useState(() => argsText(request.args));\n const [argsError, setArgsError] = useState<string>();\n const toolCall: ChatToolCallModel = {\n id: request.toolCallId ?? fallbackId,\n name: request.name,\n status: 'input-required',\n args: request.args,\n };\n const presentation = present(tools, toolCall);\n const props = presentation.kind === 'row' ? presentation.props : {};\n const label = props.label ?? request.name;\n const title =\n typeof props.summary === 'string' ? `${label}: ${props.summary}` : label;\n const allowed = new Set(request.allowedDecisions);\n const description =\n shortDescription(request.description) ??\n 'The agent is waiting for your approval to run this.';\n\n let cardState: ChatRichContentState = 'unanswered';\n let message: string | undefined;\n if (state.submitting) cardState = 'submitting';\n else if (state.failure) {\n cardState = 'submission-failed';\n message = state.failure;\n } else if (argsError) {\n cardState = 'validation-error';\n message = argsError;\n } else if (state.decision) {\n cardState = state.decision.type === 'reject' ? 'rejected' : 'approved';\n if (state.remaining > 0) {\n message = `${cardState === 'rejected' ? 'Rejected' : 'Approved'} · waiting for ${state.remaining} more ${state.remaining === 1 ? 'decision' : 'decisions'}`;\n }\n }\n\n if (allowed.has('respond') && !allowed.has('approve')) {\n return (\n <ChatRichContent\n title={title}\n description={\n shortDescription(request.description) ??\n 'The agent asked for your reply.'\n }\n state={\n state.submitting\n ? 'submitting'\n : state.failure\n ? 'submission-failed'\n : state.decision\n ? 'submitted'\n : 'unanswered'\n }\n message={state.failure}\n submitLabel=\"Send reply\"\n onSubmit={() => onDecide({ type: 'respond', message: reply.trim() })}\n >\n {({ disabled, isError, errorId }) => (\n <Textarea\n label=\"Reply\"\n value={reply}\n onChange={setReply}\n rows={3}\n resize=\"vertical\"\n disabled={disabled}\n isError={isError}\n aria-describedby={errorId}\n />\n )}\n </ChatRichContent>\n );\n }\n\n return (\n <ChatRichContent\n variant=\"approval\"\n title={title}\n description={description}\n state={cardState}\n message={message}\n onApprove={\n allowed.has('approve') ? () => onDecide({ type: 'approve' }) : undefined\n }\n onReject={\n allowed.has('reject')\n ? (text) =>\n onDecide({ type: 'reject', message: text.trim() || undefined })\n : undefined\n }\n rejectionReason={\n allowed.has('reject')\n ? { value: reason, onChange: setReason }\n : undefined\n }\n onUndo={state.submitting ? undefined : onUndo}\n edit={\n allowed.has('edit')\n ? {\n label: 'Edit',\n submitLabel: 'Approve with edits',\n content: ({ disabled, isError, errorId }) => (\n <Textarea\n label=\"Arguments\"\n value={draftArgs}\n onChange={(value) => {\n setDraftArgs(value);\n setArgsError(undefined);\n }}\n rows={6}\n resize=\"vertical\"\n className=\"font-mono\"\n disabled={disabled}\n isError={isError}\n aria-describedby={errorId}\n />\n ),\n onSubmit: async () => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(draftArgs);\n } catch {\n parsed = undefined;\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n setArgsError('Enter the arguments as a JSON object.');\n throw new Error('Invalid arguments');\n }\n await onDecide({\n type: 'edit',\n args: parsed as Record<string, unknown>,\n });\n },\n }\n : undefined\n }\n >\n {props.children ?? (\n <CodeLite\n value={argsText(request.args)}\n language=\"json\"\n variant=\"block\"\n label=\"Arguments\"\n />\n )}\n </ChatRichContent>\n );\n}\n\nfunction OtherInterrupt({\n interrupt,\n}: {\n interrupt: Extract<ChatThreadInterrupt, { kind: 'other' }>;\n}) {\n const { thread } = useThread();\n const [response, setResponse] = useState('');\n const [state, setState] = useState<ChatRichContentState>('unanswered');\n const [failure, setFailure] = useState<string>();\n const question =\n typeof interrupt.value === 'string' ? interrupt.value : undefined;\n return (\n <ChatRichContent\n title={\n question && question.length <= 140\n ? question\n : 'The agent needs your input'\n }\n description=\"Your response resumes the run.\"\n state={state}\n message={failure}\n submitLabel=\"Send\"\n onSubmit={async () => {\n setState('submitting');\n try {\n await resume(thread, { [interrupt.id]: response });\n setState('submitted');\n } catch (error) {\n setFailure(errorText(error));\n setState('submission-failed');\n throw error;\n }\n }}\n >\n {({ disabled, isError, errorId }) => (\n <>\n {question === undefined && interrupt.value !== undefined && (\n <CodeLite\n value={JSON.stringify(interrupt.value, null, 2)}\n language=\"json\"\n variant=\"block\"\n label=\"Request\"\n />\n )}\n <Textarea\n label=\"Response\"\n value={response}\n onChange={setResponse}\n rows={3}\n resize=\"vertical\"\n disabled={disabled}\n isError={isError}\n aria-describedby={errorId}\n />\n </>\n )}\n </ChatRichContent>\n );\n}\n\nexport function InterruptRequests() {\n const { thread, renderInterrupt } = useThread();\n const { interrupts } = thread.model;\n const [decisions, setDecisions] = useState<\n Record<string, (ChatThreadDecision | undefined)[]>\n >({});\n const [submitting, setSubmitting] = useState(false);\n const [failure, setFailure] = useState<string>();\n // A new set of interrupts starts with a clean slate.\n const key = interrupts.map((interrupt) => interrupt.id).join('|');\n const [decisionsFor, setDecisionsFor] = useState(key);\n if (decisionsFor !== key) {\n setDecisionsFor(key);\n setDecisions({});\n setSubmitting(false);\n setFailure(undefined);\n }\n const custom = new Map(\n interrupts.map((interrupt) => [\n interrupt.id,\n renderInterrupt?.(interrupt, thread),\n ])\n );\n // A host that renders an approval itself also resumes it, so the built-in\n // cards batch only the approvals they show.\n const approvals = interrupts.filter(\n (\n interrupt\n ): interrupt is Extract<ChatThreadInterrupt, { kind: 'approval' }> =>\n interrupt.kind === 'approval' && custom.get(interrupt.id) === undefined\n );\n const total = approvals.reduce(\n (sum, interrupt) => sum + interrupt.requests.length,\n 0\n );\n const decided = approvals.reduce(\n (sum, interrupt) =>\n sum +\n interrupt.requests.filter((_, index) => decisions[interrupt.id]?.[index])\n .length,\n 0\n );\n\n async function decide(\n interruptId: string,\n index: number,\n decision: ChatThreadDecision\n ) {\n const current = [...(decisions[interruptId] ?? [])];\n current[index] = decision;\n const next = { ...decisions, [interruptId]: current };\n setDecisions(next);\n setFailure(undefined);\n const complete = approvals.every((interrupt) =>\n interrupt.requests.every(\n (_, requestIndex) => next[interrupt.id]?.[requestIndex]\n )\n );\n // Requests paused together resume together, once each has a decision.\n if (!complete) return;\n setSubmitting(true);\n try {\n await resume(\n thread,\n Object.fromEntries(\n approvals.map((interrupt) => [\n interrupt.id,\n toHumanInTheLoopResponse(\n interrupt,\n next[interrupt.id] as ChatThreadDecision[]\n ),\n ])\n )\n );\n } catch (error) {\n setFailure(errorText(error));\n setSubmitting(false);\n throw error;\n }\n }\n\n return (\n <div className=\"flex min-w-0 flex-col gap-space-3\">\n {interrupts.map((interrupt) => {\n const rendered = custom.get(interrupt.id);\n if (rendered !== undefined)\n return <Fragment key={interrupt.id}>{rendered}</Fragment>;\n if (interrupt.kind === 'other') {\n return <OtherInterrupt key={interrupt.id} interrupt={interrupt} />;\n }\n return interrupt.requests.map((request, index) => (\n <ApprovalRequest\n key={`${interrupt.id}:${index}`}\n request={request}\n fallbackId={`${interrupt.id}:${index}`}\n state={{\n decision: decisions[interrupt.id]?.[index],\n submitting,\n failure,\n remaining: total - decided,\n }}\n onDecide={(decision) => decide(interrupt.id, index, decision)}\n onUndo={() =>\n setDecisions((current) => {\n const list = [...(current[interrupt.id] ?? [])];\n list[index] = undefined;\n return { ...current, [interrupt.id]: list };\n })\n }\n />\n ));\n })}\n </div>\n );\n}\n"],"mappings":";;;;;;;;AAcA,SAAS,SAAS,MAA+B;CAC/C,OAAO,KAAK,UAAU,MAAM,MAAM,CAAC;AACrC;AAEA,SAAS,iBAAiB,aAAiC;CACzD,OAAO,eAAe,YAAY,UAAU,OAAO,CAAC,YAAY,SAAS,IAAI,IACzE,cACA,KAAA;AACN;AASA,SAAS,gBAAgB,EACvB,SACA,YACA,OACA,UACA,UAOC;CACD,MAAM,EAAE,UAAU,UAAU;CAC5B,MAAM,CAAC,QAAQ,aAAa,SAAS,EAAE;CACvC,MAAM,CAAC,OAAO,YAAY,SAAS,EAAE;CACrC,MAAM,CAAC,WAAW,gBAAgB,eAAe,SAAS,QAAQ,IAAI,CAAC;CACvE,MAAM,CAAC,WAAW,gBAAgB,SAAiB;CACnD,MAAM,WAA8B;EAClC,IAAI,QAAQ,cAAc;EAC1B,MAAM,QAAQ;EACd,QAAQ;EACR,MAAM,QAAQ;CAChB;CACA,MAAM,eAAe,QAAQ,OAAO,QAAQ;CAC5C,MAAM,QAAQ,aAA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AAU,IAAI,OAAO,QAAQ;IAC5D,cACE,cAAc,YAAY;KACxB,MAAM,OAAO,CAAC,GAAI,QAAQ,UAAU,OAAO,CAAC,CAAE;KAC9C,KAAK,SAAS,KAAA;KACd,OAAO;MAAE,GAAG;OAAU,UAAU,KAAK;KAAK;IAC5C,CAAC;GAEJ,GAjBM,GAAG,UAAU,GAAG,GAAG,OAiBzB,CACF;EACH,CAAC;CACE,CAAA;AAET"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ChatThreadPart, ChatThreadToolRenderer, ChatThreadTurn } from './ChatThread.types.js';
|
|
2
|
+
export declare function WorkParts({ parts }: {
|
|
3
|
+
parts: ChatThreadPart[];
|
|
4
|
+
}): import("react").JSX.Element;
|
|
5
|
+
export declare function ImagePart({ url }: {
|
|
6
|
+
url: string;
|
|
7
|
+
}): import("react").JSX.Element | null;
|
|
8
|
+
export declare function visibleActionCount(parts: ChatThreadPart[], tools: Record<string, ChatThreadToolRenderer>): number;
|
|
9
|
+
export declare function WorkSummary({ turn, parts, count, }: {
|
|
10
|
+
turn: ChatThreadTurn;
|
|
11
|
+
parts: ChatThreadPart[];
|
|
12
|
+
count: number;
|
|
13
|
+
}): import("react").JSX.Element;
|