@optilogic/chat 1.0.0-beta.1 → 1.0.0-beta.10

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.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * HITLInteractionRecord — Displays a completed HITL Q&A interaction
3
+ * in the chat message history.
4
+ *
5
+ * Rendered below AgentResponse in the agent message block. Shows the full detail
6
+ * of each clarifying question the agent asked and the user's response.
7
+ */
8
+
9
+ import * as React from "react";
10
+ import { useMemo } from "react";
11
+ import { cn } from "@optilogic/core";
12
+ import type { HITLQuestion } from "./HITLQuestionPanel";
13
+
14
+ export interface HITLInteraction {
15
+ question: HITLQuestion;
16
+ response: string;
17
+ respondedAt: number;
18
+ }
19
+
20
+ export interface HITLInteractionRecordProps
21
+ extends React.HTMLAttributes<HTMLDivElement> {
22
+ interaction: HITLInteraction;
23
+ }
24
+
25
+ /**
26
+ * Parse the formatted response string (produced by buildResponseString) back
27
+ * into a per-question answer map and optional additional context.
28
+ */
29
+ function parseResponse(response: string): {
30
+ answers: Record<string, string>;
31
+ additionalContext: string | null;
32
+ } {
33
+ const answers: Record<string, string> = {};
34
+ let additionalContext: string | null = null;
35
+
36
+ const blocks = response.split("\n\n");
37
+ for (const block of blocks) {
38
+ const qaMatch = block.match(/^Q: (.+)\nA: (.+)$/s);
39
+ if (qaMatch) {
40
+ answers[qaMatch[1].trim()] = qaMatch[2].trim();
41
+ } else if (block.startsWith("Additional context: ")) {
42
+ additionalContext = block.slice("Additional context: ".length).trim();
43
+ }
44
+ }
45
+
46
+ return { answers, additionalContext };
47
+ }
48
+
49
+ const HITLInteractionRecord = React.forwardRef<
50
+ HTMLDivElement,
51
+ HITLInteractionRecordProps
52
+ >(({ interaction, className, ...props }, ref) => {
53
+ const { question, response, respondedAt } = interaction;
54
+ const timestamp = new Date(respondedAt).toLocaleTimeString([], {
55
+ hour: "2-digit",
56
+ minute: "2-digit",
57
+ });
58
+
59
+ const { answers, additionalContext } = useMemo(
60
+ () => parseResponse(response),
61
+ [response]
62
+ );
63
+
64
+ // Check if parsing found any structured answers; if not, fall back to
65
+ // showing the raw response string (for responses not built by buildResponseString).
66
+ const hasParsedAnswers = Object.keys(answers).length > 0;
67
+
68
+ return (
69
+ <div
70
+ ref={ref}
71
+ className={cn(
72
+ "rounded-lg border border-border bg-muted p-3 space-y-2 text-sm",
73
+ className
74
+ )}
75
+ {...props}
76
+ >
77
+ {/* Header */}
78
+ <div className="flex items-center justify-between">
79
+ <span className="font-medium text-muted-foreground">
80
+ Clarifying Question
81
+ </span>
82
+ <span className="text-xs text-muted-foreground">{timestamp}</span>
83
+ </div>
84
+
85
+ {/* Reason */}
86
+ <p className="text-foreground font-medium">{question.reason}</p>
87
+
88
+ {/* Context (if provided) */}
89
+ {question.context && (
90
+ <div className="text-xs text-muted-foreground bg-background rounded p-2 border border-border">
91
+ <pre className="whitespace-pre-wrap font-mono">
92
+ {question.context}
93
+ </pre>
94
+ </div>
95
+ )}
96
+
97
+ {/* Questions with inline answers */}
98
+ <div className="space-y-2">
99
+ {question.questions.map((q, i) => (
100
+ <div key={i}>
101
+ <p className="text-foreground">{q}</p>
102
+ {question.options?.[q] && (
103
+ <p className="text-xs text-muted-foreground ml-2">
104
+ Options: {question.options[q].join(", ")}
105
+ </p>
106
+ )}
107
+ {hasParsedAnswers && answers[q] && (
108
+ <p className="text-xs text-foreground ml-2 mt-0.5 bg-background rounded px-2 py-1 border border-border">
109
+ <span className="text-muted-foreground">Answer: </span>
110
+ {answers[q]}
111
+ </p>
112
+ )}
113
+ </div>
114
+ ))}
115
+ </div>
116
+
117
+ {/* Additional context from freeform text, or raw fallback */}
118
+ {hasParsedAnswers && additionalContext && (
119
+ <div className="border-t border-border pt-2">
120
+ <span className="text-muted-foreground text-xs">
121
+ Additional context:
122
+ </span>
123
+ <p className="text-foreground mt-0.5">{additionalContext}</p>
124
+ </div>
125
+ )}
126
+
127
+ {/* Fallback: show raw response if it wasn't in the parsed Q/A format */}
128
+ {!hasParsedAnswers && (
129
+ <div className="border-t border-border pt-2">
130
+ <span className="text-muted-foreground text-xs">Response:</span>
131
+ <p className="text-foreground mt-0.5">{response}</p>
132
+ </div>
133
+ )}
134
+ </div>
135
+ );
136
+ });
137
+ HITLInteractionRecord.displayName = "HITLInteractionRecord";
138
+
139
+ export { HITLInteractionRecord };
@@ -0,0 +1,263 @@
1
+ /**
2
+ * HITLQuestionPanel — Human-in-the-Loop clarifying question panel.
3
+ *
4
+ * Renders in the input area (replacing UserPromptInput) when the agent asks a
5
+ * clarifying question via the HumanInTheLoop tool. Shows the question details
6
+ * and lets the user respond via option buttons or free-form text.
7
+ *
8
+ * Option clicks select/toggle rather than immediately submitting. The "Send
9
+ * response" button enables once all questions have a selected option OR the
10
+ * textarea has text. On submit, selected options and free-form text are
11
+ * combined into a single formatted string for the backend.
12
+ */
13
+
14
+ import * as React from "react";
15
+ import { useState, useEffect, useRef, useCallback, useMemo } from "react";
16
+ import { cn, Button, Textarea } from "@optilogic/core";
17
+
18
+ export interface HITLQuestion {
19
+ reason: string;
20
+ questions: string[];
21
+ options: Record<string, string[]> | null;
22
+ context: string | null;
23
+ /** Timeout in seconds. When omitted, no countdown is shown and the panel never times out. */
24
+ timeoutSeconds?: number;
25
+ receivedAt: number;
26
+ }
27
+
28
+ export interface HITLQuestionPanelProps
29
+ extends Omit<React.HTMLAttributes<HTMLDivElement>, "onSubmit"> {
30
+ question: HITLQuestion;
31
+ onSubmit: (response: string) => void;
32
+ onStop: () => void;
33
+ }
34
+
35
+ /**
36
+ * Build a single response string from selected options and optional free-form text.
37
+ * Format is designed to be easily parsed by the LLM consuming the response.
38
+ */
39
+ export function buildResponseString(
40
+ questions: string[],
41
+ selectedOptions: Record<string, string>,
42
+ freeformText: string
43
+ ): string {
44
+ const parts: string[] = [];
45
+
46
+ for (const q of questions) {
47
+ const answer = selectedOptions[q];
48
+ if (answer) {
49
+ parts.push(`Q: ${q}\nA: ${answer}`);
50
+ }
51
+ }
52
+
53
+ const trimmed = freeformText.trim();
54
+ if (trimmed) {
55
+ parts.push(`Additional context: ${trimmed}`);
56
+ }
57
+
58
+ return parts.join("\n\n");
59
+ }
60
+
61
+ const HITLQuestionPanel = React.forwardRef<
62
+ HTMLDivElement,
63
+ HITLQuestionPanelProps
64
+ >(({ question, onSubmit, onStop, className, ...props }, ref) => {
65
+ const [freeformText, setFreeformText] = useState("");
66
+ const [selectedOptions, setSelectedOptions] = useState<
67
+ Record<string, string>
68
+ >({});
69
+ const hasTimeout = question.timeoutSeconds != null;
70
+ const [secondsLeft, setSecondsLeft] = useState(() =>
71
+ hasTimeout
72
+ ? Math.max(
73
+ 0,
74
+ Math.round(
75
+ question.timeoutSeconds! - (Date.now() - question.receivedAt) / 1000
76
+ )
77
+ )
78
+ : Infinity
79
+ );
80
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
81
+
82
+ // Focus the textarea on mount
83
+ useEffect(() => {
84
+ textareaRef.current?.focus();
85
+ }, []);
86
+
87
+ // Countdown timer (only when timeoutSeconds is provided)
88
+ useEffect(() => {
89
+ if (!hasTimeout) return;
90
+ const interval = setInterval(() => {
91
+ const remaining = Math.max(
92
+ 0,
93
+ Math.round(
94
+ question.timeoutSeconds! - (Date.now() - question.receivedAt) / 1000
95
+ )
96
+ );
97
+ setSecondsLeft(remaining);
98
+ if (remaining <= 0) clearInterval(interval);
99
+ }, 1000);
100
+ return () => clearInterval(interval);
101
+ }, [hasTimeout, question.timeoutSeconds, question.receivedAt]);
102
+
103
+ const timedOut = hasTimeout && secondsLeft <= 0;
104
+
105
+ // Which questions have options defined?
106
+ const questionsWithOptions = useMemo(
107
+ () => question.questions.filter((q) => question.options?.[q]?.length),
108
+ [question.questions, question.options]
109
+ );
110
+
111
+ const allOptionsSelected =
112
+ questionsWithOptions.length > 0 &&
113
+ questionsWithOptions.every((q) => selectedOptions[q]);
114
+
115
+ const hasFreeformText = freeformText.trim().length > 0;
116
+
117
+ const canSubmit = !timedOut && (allOptionsSelected || hasFreeformText);
118
+
119
+ const handleOptionClick = useCallback(
120
+ (questionText: string, option: string) => {
121
+ if (timedOut) return;
122
+ setSelectedOptions((prev) => {
123
+ // Toggle: deselect if already selected, otherwise select
124
+ if (prev[questionText] === option) {
125
+ const next = { ...prev };
126
+ delete next[questionText];
127
+ return next;
128
+ }
129
+ return { ...prev, [questionText]: option };
130
+ });
131
+ },
132
+ [timedOut]
133
+ );
134
+
135
+ const handleSubmit = useCallback(() => {
136
+ if (!canSubmit) return;
137
+ const combined = buildResponseString(
138
+ question.questions,
139
+ selectedOptions,
140
+ freeformText
141
+ );
142
+ onSubmit(combined);
143
+ }, [canSubmit, question.questions, selectedOptions, freeformText, onSubmit]);
144
+
145
+ const handleKeyDown = useCallback(
146
+ (e: React.KeyboardEvent) => {
147
+ if (e.key === "Enter" && !e.shiftKey) {
148
+ e.preventDefault();
149
+ handleSubmit();
150
+ }
151
+ },
152
+ [handleSubmit]
153
+ );
154
+
155
+ const formatTime = (s: number) => {
156
+ const m = Math.floor(s / 60);
157
+ const sec = s % 60;
158
+ return `${m}:${sec.toString().padStart(2, "0")}`;
159
+ };
160
+
161
+ return (
162
+ <div
163
+ ref={ref}
164
+ className={cn(
165
+ "rounded-lg border border-border bg-muted p-4 space-y-3",
166
+ className
167
+ )}
168
+ {...props}
169
+ >
170
+ {/* Header: reason + countdown */}
171
+ <div className="flex items-start justify-between gap-3">
172
+ <div className="flex-1">
173
+ <p className="text-sm font-medium text-foreground">
174
+ {question.reason}
175
+ </p>
176
+ </div>
177
+ {hasTimeout && (
178
+ <span
179
+ className={cn(
180
+ "text-xs font-mono whitespace-nowrap",
181
+ secondsLeft <= 30 ? "text-destructive" : "text-muted-foreground"
182
+ )}
183
+ >
184
+ {timedOut ? "Timed out" : formatTime(secondsLeft)}
185
+ </span>
186
+ )}
187
+ </div>
188
+
189
+ {/* Context (if provided) */}
190
+ {question.context && (
191
+ <div className="text-xs text-muted-foreground bg-background rounded p-2 border border-border max-h-24 overflow-y-auto">
192
+ <pre className="whitespace-pre-wrap font-mono">
193
+ {question.context}
194
+ </pre>
195
+ </div>
196
+ )}
197
+
198
+ {/* Questions */}
199
+ <div className="space-y-3">
200
+ {question.questions.map((q, i) => (
201
+ <div key={i}>
202
+ <p className="text-sm text-foreground">{q}</p>
203
+
204
+ {/* Options for this question (if provided) */}
205
+ {question.options?.[q] && (
206
+ <div className="flex flex-wrap gap-2 mt-1.5">
207
+ {question.options[q].map((option, j) => {
208
+ const isSelected = selectedOptions[q] === option;
209
+ return (
210
+ <Button
211
+ key={j}
212
+ variant={isSelected ? "primary" : "outline"}
213
+ size="sm"
214
+ onClick={() => handleOptionClick(q, option)}
215
+ disabled={timedOut}
216
+ >
217
+ {option}
218
+ </Button>
219
+ );
220
+ })}
221
+ </div>
222
+ )}
223
+ </div>
224
+ ))}
225
+ </div>
226
+
227
+ {/* Free-form input — always shown for additional context */}
228
+ <Textarea
229
+ ref={textareaRef}
230
+ value={freeformText}
231
+ onChange={(e) => setFreeformText(e.target.value)}
232
+ onKeyDown={handleKeyDown}
233
+ disabled={timedOut}
234
+ placeholder="Add additional context or type a full response..."
235
+ rows={2}
236
+ className="resize-none"
237
+ />
238
+
239
+ <div className="flex items-center justify-between">
240
+ <Button
241
+ variant="ghost"
242
+ size="sm"
243
+ onClick={onStop}
244
+ className="text-destructive hover:text-destructive hover:bg-destructive/10"
245
+ >
246
+ Stop agent
247
+ </Button>
248
+
249
+ <Button
250
+ variant="primary"
251
+ size="sm"
252
+ onClick={handleSubmit}
253
+ disabled={!canSubmit}
254
+ >
255
+ Send response
256
+ </Button>
257
+ </div>
258
+ </div>
259
+ );
260
+ });
261
+ HITLQuestionPanel.displayName = "HITLQuestionPanel";
262
+
263
+ export { HITLQuestionPanel };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * HITL (Human-in-the-Loop) Interaction Components
3
+ *
4
+ * Components for displaying and handling clarifying questions
5
+ * between the AI agent and the user during a conversation.
6
+ */
7
+
8
+ // Question panel (interactive input area)
9
+ export { HITLQuestionPanel } from "./HITLQuestionPanel";
10
+ export type { HITLQuestionPanelProps, HITLQuestion } from "./HITLQuestionPanel";
11
+ export { buildResponseString } from "./HITLQuestionPanel";
12
+
13
+ // Interaction record (read-only history display)
14
+ export { HITLInteractionRecord } from "./HITLInteractionRecord";
15
+ export type {
16
+ HITLInteractionRecordProps,
17
+ HITLInteraction,
18
+ } from "./HITLInteractionRecord";
@@ -0,0 +1,60 @@
1
+ import * as React from "react";
2
+ import { cn } from "@optilogic/core";
3
+
4
+ export interface UserPromptProps extends React.HTMLAttributes<HTMLDivElement> {
5
+ /** The text content of the user's message */
6
+ content: string;
7
+ /** Optional timestamp to display below the message */
8
+ timestamp?: Date;
9
+ }
10
+
11
+ /**
12
+ * UserPrompt component
13
+ *
14
+ * Displays a user's chat message in a styled bubble.
15
+ * Used alongside AgentResponse to create chat interfaces.
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * <UserPrompt
20
+ * content="What is the weather today?"
21
+ * timestamp={new Date()}
22
+ * />
23
+ * ```
24
+ *
25
+ * @example
26
+ * ```tsx
27
+ * // Custom styling
28
+ * <UserPrompt
29
+ * content="Hello world"
30
+ * className="max-w-full"
31
+ * />
32
+ * ```
33
+ */
34
+ export const UserPrompt = React.forwardRef<HTMLDivElement, UserPromptProps>(
35
+ ({ content, timestamp, className, ...props }, ref) => {
36
+ return (
37
+ <div
38
+ ref={ref}
39
+ className={cn(
40
+ "w-fit max-w-[80%] rounded-lg px-4 pt-3.5 pb-3",
41
+ "bg-secondary text-secondary-foreground",
42
+ className
43
+ )}
44
+ {...props}
45
+ >
46
+ <p className="whitespace-pre-wrap">{content}</p>
47
+ {timestamp && (
48
+ <p className="text-xs text-secondary-foreground/70 mt-1">
49
+ {timestamp.toLocaleTimeString([], {
50
+ hour: "2-digit",
51
+ minute: "2-digit",
52
+ })}
53
+ </p>
54
+ )}
55
+ </div>
56
+ );
57
+ }
58
+ );
59
+
60
+ UserPrompt.displayName = "UserPrompt";
@@ -0,0 +1 @@
1
+ export { UserPrompt, type UserPromptProps } from "./UserPrompt";