@agentskit/chat-ink 0.1.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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AgentsKit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @agentskit/chat-ink
2
+
3
+ Opinionated Ink shell for a framework-neutral AgentsKit Chat definition. Chat state, streaming, keyboard history, cancellation, and terminal primitives come directly from `@agentskit/ink`.
4
+
5
+ Unsupported visual components should be validated through `parseSemanticFallback` from `@agentskit/chat` and rendered through `SemanticFallback`, preserving the shared kind and human-readable summary in plain terminal text.
6
+
7
+ The native `ChoiceList` supports Up/Down or a number followed by Enter and emits the shared selection event.
8
+
9
+ Use `theme` for semantic colors and `slots` for native Ink composition. `toChatInkTheme` returns the complete upstream `InkTheme`; terminal-unsupported spatial tokens are intentionally ignored. See [theming and composition](../../docs/theming-and-composition.md).
@@ -0,0 +1,48 @@
1
+ import { ComponentManifest, ChatDefinition, ChatSession, ChatThemeInput } from '@agentskit/chat';
2
+ export { ChatDefinition, SemanticFallback as SemanticFallbackContent } from '@agentskit/chat';
3
+ import { ComponentRenderFrame, ComponentInteractionEvent, ComponentSelectionEvent } from '@agentskit/chat-protocol';
4
+ import { ChatContainer, Message, InputBar, ThinkingIndicator, ToolConfirmation, InkTheme } from '@agentskit/ink';
5
+ import { ReactElement, ComponentType, ComponentProps } from 'react';
6
+
7
+ interface StandardComponentProps {
8
+ readonly frame: ComponentRenderFrame;
9
+ readonly manifest: ComponentManifest;
10
+ readonly onInteract: (event: ComponentInteractionEvent) => void;
11
+ readonly isActive?: boolean;
12
+ }
13
+ declare const StandardComponent: ({ frame, manifest, onInteract, isActive }: StandardComponentProps) => ReactElement | null;
14
+
15
+ declare const toChatInkTheme: (input?: ChatThemeInput) => InkTheme;
16
+ interface AgentChatSlots {
17
+ readonly Container?: ComponentType<ComponentProps<typeof ChatContainer>>;
18
+ readonly Message?: ComponentType<ComponentProps<typeof Message>>;
19
+ readonly Input?: ComponentType<ComponentProps<typeof InputBar>>;
20
+ readonly Thinking?: ComponentType<ComponentProps<typeof ThinkingIndicator>>;
21
+ readonly Confirmation?: ComponentType<ComponentProps<typeof ToolConfirmation>>;
22
+ readonly ChoiceList?: ComponentType<ChoiceListProps>;
23
+ readonly StandardComponent?: ComponentType<StandardComponentProps>;
24
+ }
25
+ interface SemanticFallbackProps {
26
+ readonly fallback: unknown;
27
+ }
28
+ declare const SemanticFallback: ({ fallback }: SemanticFallbackProps) => ReactElement;
29
+ interface AgentChatProps {
30
+ readonly definition: ChatDefinition;
31
+ readonly placeholder?: string;
32
+ readonly onComponentSelect?: (event: ComponentSelectionEvent) => void;
33
+ readonly onComponentInteract?: (event: ComponentInteractionEvent) => void;
34
+ readonly actionConfirmationTtlMs?: number;
35
+ readonly session?: ChatSession;
36
+ readonly theme?: ChatThemeInput;
37
+ readonly slots?: AgentChatSlots;
38
+ }
39
+ interface ChoiceListProps {
40
+ readonly frame: unknown;
41
+ readonly manifest: ComponentManifest;
42
+ readonly onSelect: (event: ComponentSelectionEvent) => void;
43
+ readonly isActive?: boolean;
44
+ }
45
+ declare const ChoiceList: ({ frame, manifest, onSelect, isActive }: ChoiceListProps) => ReactElement | null;
46
+ declare const AgentChat: (props: AgentChatProps) => ReactElement;
47
+
48
+ export { AgentChat, type AgentChatProps, type AgentChatSlots, ChoiceList, type ChoiceListProps, SemanticFallback, type SemanticFallbackProps, StandardComponent, type StandardComponentProps, toChatInkTheme };
package/dist/index.js ADDED
@@ -0,0 +1,344 @@
1
+ // src/index.tsx
2
+ import { STANDARD_COMPONENT_KEYS, formatSemanticFallback, getLifecycleTargets, parseSemanticFallback, presentChatMessage, resolveChatSession, resolveChatTheme, resolveChoiceAction, resolveChoiceListFrame, resolveComponentFrame as resolveComponentFrame2, selectChoice } from "@agentskit/chat";
3
+ import { ChatContainer, defaultInkTheme, InkThemeProvider, InputBar, Message, ThinkingIndicator, ToolConfirmation, useChat, useInkTheme } from "@agentskit/ink";
4
+ import { Box as Box2, Text as Text2, useInput as useInput2 } from "ink";
5
+ import { useMemo, useRef as useRef2, useState as useState2 } from "react";
6
+
7
+ // src/StandardComponent.tsx
8
+ import { ApprovalRequestPropsSchema, ButtonGroupPropsSchema, ConfirmationPropsSchema, ErrorNoticePropsSchema, FileAttachmentPropsSchema, FormPropsSchema, LinkCardPropsSchema, ProgressPropsSchema, SourceListPropsSchema, TablePropsSchema, ToolCallPropsSchema, createComponentInteraction, resolveComponentFrame, resolveComponentFallback } from "@agentskit/chat";
9
+ import { Box, Text, useInput } from "ink";
10
+ import { useRef, useState } from "react";
11
+ import { jsx, jsxs } from "react/jsx-runtime";
12
+ var presentation = (frame, manifest) => {
13
+ const key = frame.componentKey;
14
+ if (key === "button-group") {
15
+ const item = ButtonGroupPropsSchema.parse(frame.props);
16
+ return { title: item.label, lines: [], actions: item.buttons.filter((button) => !button.disabled).map((button) => ({ label: button.label, event: "select", value: button.id })) };
17
+ }
18
+ if (key === "form") {
19
+ const item = FormPropsSchema.parse(frame.props);
20
+ return { title: item.title ?? "Form", lines: item.fields.map((field) => `${field.label}${field.required ? " *" : ""}`), actions: [] };
21
+ }
22
+ if (key === "confirmation") {
23
+ const item = ConfirmationPropsSchema.parse(frame.props);
24
+ return { title: item.title, lines: [item.message], actions: [{ label: item.confirmLabel, event: "confirm" }, { label: item.cancelLabel, event: "cancel" }] };
25
+ }
26
+ if (key === "progress") {
27
+ const item = ProgressPropsSchema.parse(frame.props);
28
+ return { title: item.label, lines: [`${item.value}%${item.status ? ` \u2014 ${item.status}` : ""}`], actions: [] };
29
+ }
30
+ if (key === "source-list") {
31
+ const item = SourceListPropsSchema.parse(frame.props);
32
+ return { title: item.label, lines: item.sources.map((source) => `${source.title}${source.snippet ? ` \u2014 ${source.snippet}` : ""}`), actions: item.sources.filter((source) => source.url).map((source) => ({ label: `Open ${source.title}`, event: "open", value: source.id })) };
33
+ }
34
+ if (key === "link-card") {
35
+ const item = LinkCardPropsSchema.parse(frame.props);
36
+ return { title: item.title, lines: [item.description ?? item.href], actions: [{ label: item.label ?? "Open", event: "open", value: item.href }] };
37
+ }
38
+ if (key === "error-notice") {
39
+ const item = ErrorNoticePropsSchema.parse(frame.props);
40
+ return { title: item.title, lines: [item.message, item.code ?? ""], actions: item.retryLabel ? [{ label: item.retryLabel, event: "retry" }] : [] };
41
+ }
42
+ if (key === "tool-call") {
43
+ const item = ToolCallPropsSchema.parse(frame.props);
44
+ return { title: item.name, lines: [item.status, item.arguments ? JSON.stringify(item.arguments) : "", item.result === void 0 ? "" : JSON.stringify(item.result)], actions: [] };
45
+ }
46
+ if (key === "approval-request") {
47
+ const item = ApprovalRequestPropsSchema.parse(frame.props);
48
+ return { title: item.title, lines: [item.description], actions: [{ label: item.approveLabel, event: "approve" }, { label: item.denyLabel, event: "deny" }] };
49
+ }
50
+ if (key === "table") {
51
+ const item = TablePropsSchema.parse(frame.props);
52
+ return { title: item.caption, lines: [item.columns.map((column) => column.label).join(" | "), ...item.rows.map((row) => item.columns.map((column) => String(row[column.key] ?? "")).join(" | "))], actions: [] };
53
+ }
54
+ if (key === "file-attachment") {
55
+ const item = FileAttachmentPropsSchema.parse(frame.props);
56
+ return { title: item.name, lines: [item.mimeType, item.sizeBytes === void 0 ? "" : `${item.sizeBytes} bytes`], actions: item.url ? [{ label: "Open", event: "open", value: item.url }] : [] };
57
+ }
58
+ return { title: resolveComponentFallback(frame, manifest) ?? key, lines: [], actions: [] };
59
+ };
60
+ var StandardComponent = ({ frame, manifest, onInteract, isActive = true }) => {
61
+ const resolved = resolveComponentFrame(frame, manifest);
62
+ if (!resolved.ok || frame.componentKey === "choice-list") return null;
63
+ if (frame.componentKey === "form") return /* @__PURE__ */ jsx(TerminalForm, { frame, manifest, onInteract, isActive });
64
+ const item = presentation(frame, manifest);
65
+ const [active, setActive] = useState(0);
66
+ const activeRef = useRef(0);
67
+ useInput((_input, key) => {
68
+ if (!isActive || item.actions.length === 0) return;
69
+ if (key.upArrow) activeRef.current = Math.max(0, activeRef.current - 1);
70
+ if (key.downArrow) activeRef.current = Math.min(item.actions.length - 1, activeRef.current + 1);
71
+ if (key.upArrow || key.downArrow) setActive(activeRef.current);
72
+ if (key.return) {
73
+ const action = item.actions[activeRef.current];
74
+ onInteract(createComponentInteraction(frame, manifest, action.event, action.value));
75
+ }
76
+ });
77
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
78
+ /* @__PURE__ */ jsx(Text, { bold: true, children: item.title }),
79
+ item.lines.filter(Boolean).map((line, index) => /* @__PURE__ */ jsx(Text, { children: line }, index)),
80
+ item.actions.map((action, index) => /* @__PURE__ */ jsxs(Text, { inverse: index === active, children: [
81
+ index + 1,
82
+ ". ",
83
+ action.label
84
+ ] }, action.label))
85
+ ] });
86
+ };
87
+ var TerminalForm = ({ frame, manifest, onInteract, isActive = true }) => {
88
+ const item = FormPropsSchema.parse(frame.props);
89
+ const [fieldIndex, setFieldIndex] = useState(0);
90
+ const [draft, setDraft] = useState("");
91
+ const [values, setValues] = useState({});
92
+ const field = item.fields[fieldIndex];
93
+ useInput((input, key) => {
94
+ if (!isActive || field === void 0) return;
95
+ if (field.type === "checkbox" && input === " ") setDraft((current) => current === "true" ? "false" : "true");
96
+ else if (field.type === "select" && (key.upArrow || key.downArrow)) {
97
+ const options = field.options ?? [];
98
+ const current = Math.max(0, options.findIndex((option) => option.id === draft));
99
+ setDraft(options[Math.max(0, Math.min(options.length - 1, current + (key.downArrow ? 1 : -1)))]?.id ?? "");
100
+ } else if (key.backspace || key.delete) setDraft((current) => current.slice(0, -1));
101
+ else if (!key.return && !key.ctrl && !key.meta && field.type !== "checkbox" && field.type !== "select") setDraft((current) => current + input);
102
+ if (!key.return) return;
103
+ const value = field.type === "checkbox" ? draft === "true" : field.type === "select" ? draft || field.options?.[0]?.id || "" : draft;
104
+ if (field.required && value === "") return;
105
+ const next = { ...values, [field.id]: value };
106
+ setValues(next);
107
+ if (fieldIndex === item.fields.length - 1) onInteract(createComponentInteraction(frame, manifest, "submit", next));
108
+ else {
109
+ setFieldIndex((index) => index + 1);
110
+ setDraft("");
111
+ }
112
+ });
113
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
114
+ /* @__PURE__ */ jsx(Text, { bold: true, children: item.title ?? "Form" }),
115
+ item.fields.map((candidate, index) => /* @__PURE__ */ jsxs(Text, { inverse: index === fieldIndex, children: [
116
+ candidate.label,
117
+ candidate.required ? " *" : "",
118
+ ": ",
119
+ index === fieldIndex ? candidate.type === "checkbox" ? draft === "true" ? "[x]" : "[ ]" : candidate.type === "select" ? candidate.options?.find((option) => option.id === draft)?.label ?? candidate.options?.[0]?.label ?? "" : draft : String(values[candidate.id] ?? "")
120
+ ] }, candidate.id)),
121
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: fieldIndex === item.fields.length - 1 ? item.submitLabel : "Enter to continue" })
122
+ ] });
123
+ };
124
+
125
+ // src/index.tsx
126
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
127
+ var toChatInkTheme = (input) => {
128
+ const theme = resolveChatTheme(input);
129
+ return {
130
+ roles: {
131
+ ...defaultInkTheme.roles,
132
+ user: { ...defaultInkTheme.roles.user, color: theme.colors.accent },
133
+ assistant: { ...defaultInkTheme.roles.assistant, color: theme.colors.accent },
134
+ system: { ...defaultInkTheme.roles.system, color: theme.colors.muted },
135
+ tool: { ...defaultInkTheme.roles.tool, color: theme.colors.accent }
136
+ },
137
+ toolStatus: {
138
+ ...defaultInkTheme.toolStatus,
139
+ pending: { ...defaultInkTheme.toolStatus.pending, color: theme.colors.muted },
140
+ running: { ...defaultInkTheme.toolStatus.running, color: theme.colors.accent },
141
+ complete: { ...defaultInkTheme.toolStatus.complete, color: theme.colors.accent },
142
+ error: { ...defaultInkTheme.toolStatus.error, color: theme.colors.danger },
143
+ requires_confirmation: { ...defaultInkTheme.toolStatus.requires_confirmation, color: theme.colors.accent }
144
+ },
145
+ prompt: { active: theme.colors.accent, busy: theme.colors.muted },
146
+ inputText: { active: theme.colors.text, busy: theme.colors.muted },
147
+ header: { border: theme.colors.border, title: theme.colors.accent },
148
+ usage: { prompt: theme.colors.accent, completion: theme.colors.muted },
149
+ segment: { ...defaultInkTheme.segment, provider: theme.colors.accent, model: theme.colors.accent, modeLive: theme.colors.accent, modeDemo: theme.colors.muted, tools: theme.colors.accent, muted: theme.colors.muted }
150
+ };
151
+ };
152
+ var SemanticFallback = ({ fallback }) => {
153
+ const validated = parseSemanticFallback(fallback);
154
+ return /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: formatSemanticFallback(validated) });
155
+ };
156
+ var ResolvedChoiceList = ({ resolved, onSelect, isActive }) => {
157
+ const theme = useInkTheme();
158
+ const [activeIndex, setActiveIndex] = useState2(0);
159
+ const activeIndexRef = useRef2(0);
160
+ const numericBufferRef = useRef2("");
161
+ const activate = (index) => {
162
+ activeIndexRef.current = index;
163
+ setActiveIndex(index);
164
+ };
165
+ useInput2((input, key) => {
166
+ if (!isActive) return;
167
+ if (key.upArrow) activate(Math.max(0, activeIndexRef.current - 1));
168
+ if (key.downArrow) activate(Math.min(resolved.props.choices.length - 1, activeIndexRef.current + 1));
169
+ if (key.upArrow || key.downArrow) numericBufferRef.current = "";
170
+ if (/^[0-9]$/.test(input)) numericBufferRef.current = `${numericBufferRef.current}${input}`.slice(-2);
171
+ if (key.return) {
172
+ const numericIndex = Number(numericBufferRef.current) - 1;
173
+ const selectedIndex = numericBufferRef.current !== "" && resolved.props.choices[numericIndex] !== void 0 ? numericIndex : activeIndexRef.current;
174
+ numericBufferRef.current = "";
175
+ onSelect(selectChoice(resolved.frame, resolved.props.choices[selectedIndex].id));
176
+ }
177
+ });
178
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
179
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: resolved.props.prompt }),
180
+ resolved.props.choices.map((choice, index) => /* @__PURE__ */ jsxs2(Text2, { inverse: index === activeIndex, children: [
181
+ /* @__PURE__ */ jsxs2(Text2, { color: theme.prompt.active, children: [
182
+ index + 1,
183
+ "."
184
+ ] }),
185
+ " ",
186
+ /* @__PURE__ */ jsx2(Text2, { children: choice.label }),
187
+ choice.description === void 0 ? null : /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
188
+ " \u2014 ",
189
+ choice.description
190
+ ] })
191
+ ] }, choice.id)),
192
+ /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "Use \u2191/\u2193 or a number, then Enter." })
193
+ ] });
194
+ };
195
+ var ChoiceList = ({ frame, manifest, onSelect, isActive = true }) => {
196
+ const resolved = resolveChoiceListFrame(frame, manifest);
197
+ return resolved.ok ? /* @__PURE__ */ jsx2(ResolvedChoiceList, { resolved, onSelect, isActive }) : null;
198
+ };
199
+ var AgentChatSession = ({ definition, placeholder, onComponentSelect = () => void 0, onComponentInteract = () => void 0, actionConfirmationTtlMs, session: preparedSession, slots = {} }) => {
200
+ const theme = useInkTheme();
201
+ const ContainerSlot = slots.Container ?? ChatContainer;
202
+ const MessageSlot = slots.Message ?? Message;
203
+ const InputSlot = slots.Input ?? InputBar;
204
+ const ThinkingSlot = slots.Thinking ?? ThinkingIndicator;
205
+ const ConfirmationSlot = slots.Confirmation ?? ToolConfirmation;
206
+ const ChoiceListSlot = slots.ChoiceList ?? ChoiceList;
207
+ const StandardComponentSlot = slots.StandardComponent ?? StandardComponent;
208
+ const [session] = useState2(() => resolveChatSession(definition, preparedSession));
209
+ const sessionId = session.sessionId;
210
+ const [actionError, setActionError] = useState2();
211
+ const [resolvedInstances, setResolvedInstances] = useState2(() => /* @__PURE__ */ new Set());
212
+ const resolvedInstancesRef = useRef2(/* @__PURE__ */ new Set());
213
+ const config = useMemo(() => session.updateChat(definition.chat), [definition.chat, session]);
214
+ const chat = useChat(config);
215
+ const chatRef = useRef2(chat);
216
+ chatRef.current = chat;
217
+ const [confirmation] = useState2(() => session.createConfirmation({ ...actionConfirmationTtlMs === void 0 ? {} : { ttlMs: actionConfirmationTtlMs }, chat: {
218
+ proposeToolCall: (proposal) => chatRef.current.proposeToolCall(proposal),
219
+ approve: (id) => chatRef.current.approve(id),
220
+ deny: (id, reason) => chatRef.current.deny(id, reason)
221
+ } }));
222
+ const activePresentation = [...chat.messages].reverse().flatMap(
223
+ (message) => [...presentChatMessage(message)].reverse()
224
+ ).find((presentation2) => {
225
+ if (presentation2.kind !== "component" || definition.components === void 0) return false;
226
+ const resolved = resolveComponentFrame2(presentation2.frame, definition.components);
227
+ return resolved.ok && (definition.components[presentation2.frame.componentKey]?.events?.length ?? 0) > 0 && !resolvedInstances.has(presentation2.frame.instanceId);
228
+ });
229
+ const activeComponentInstanceId = activePresentation?.kind === "component" ? activePresentation.frame.instanceId : void 0;
230
+ const handleComponentSelect = (event, frame) => {
231
+ if (resolvedInstancesRef.current.has(event.instanceId)) return;
232
+ resolvedInstancesRef.current.add(event.instanceId);
233
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
234
+ try {
235
+ onComponentSelect(event);
236
+ } catch (error) {
237
+ setActionError(error instanceof Error ? error : new Error("Component selection callback failed."));
238
+ }
239
+ const action = resolveChoiceAction(frame, event.choiceId);
240
+ if (action) void confirmation.propose(action).catch((error) => {
241
+ resolvedInstancesRef.current.delete(event.instanceId);
242
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
243
+ setActionError(error instanceof Error ? error : new Error("Action proposal failed."));
244
+ });
245
+ else {
246
+ let submission;
247
+ try {
248
+ submission = definition.choiceSubmission?.(frame, event.choiceId, { sessionId });
249
+ } catch (error) {
250
+ resolvedInstancesRef.current.delete(event.instanceId);
251
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
252
+ setActionError(error instanceof Error ? error : new Error("Choice submission authorization failed."));
253
+ return;
254
+ }
255
+ if (submission && "unavailable" in submission) {
256
+ resolvedInstancesRef.current.delete(event.instanceId);
257
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
258
+ setActionError(new Error("This deterministic choice expired. Ask the question again."));
259
+ return;
260
+ }
261
+ if (submission) void chatRef.current.send(submission.value).then(
262
+ () => {
263
+ try {
264
+ submission.commit();
265
+ } catch (error) {
266
+ setActionError(error instanceof Error ? error : new Error("Choice submission settlement failed."));
267
+ }
268
+ },
269
+ (error) => {
270
+ try {
271
+ submission.release();
272
+ } catch {
273
+ } finally {
274
+ resolvedInstancesRef.current.delete(event.instanceId);
275
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
276
+ }
277
+ setActionError(error instanceof Error ? error : new Error("Choice submission failed."));
278
+ }
279
+ );
280
+ }
281
+ };
282
+ const interactComponent = (event) => {
283
+ if (resolvedInstancesRef.current.has(event.instanceId)) return;
284
+ resolvedInstancesRef.current.add(event.instanceId);
285
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
286
+ try {
287
+ onComponentInteract(event);
288
+ } catch (error) {
289
+ resolvedInstancesRef.current.delete(event.instanceId);
290
+ setResolvedInstances(new Set(resolvedInstancesRef.current));
291
+ setActionError(error instanceof Error ? error : new Error("Component interaction callback failed."));
292
+ }
293
+ };
294
+ const approve = (toolCallId) => {
295
+ const record = confirmation.getByToolCall(toolCallId);
296
+ void (record ? confirmation.approve(record.token, sessionId) : chat.approve(toolCallId)).catch((error) => setActionError(error instanceof Error ? error : new Error("Action approval failed.")));
297
+ };
298
+ const deny = (toolCallId, reason) => {
299
+ const record = confirmation.getByToolCall(toolCallId);
300
+ void (record ? confirmation.reject(record.token, sessionId, reason) : chat.deny(toolCallId, reason)).catch((error) => setActionError(error instanceof Error ? error : new Error("Action rejection failed.")));
301
+ };
302
+ const handleLifecycleCommand = async (input) => {
303
+ const targets = getLifecycleTargets(chat.messages);
304
+ try {
305
+ if (input === "/retry") await chat.retry();
306
+ else if (input === "/regenerate") await chat.regenerate(targets.assistantId);
307
+ else if (input.startsWith("/edit ") && targets.userId) await chat.edit(targets.userId, input.slice(6));
308
+ else return false;
309
+ setActionError(void 0);
310
+ } catch (error) {
311
+ setActionError(error instanceof Error ? error : new Error("Lifecycle operation failed."));
312
+ }
313
+ return true;
314
+ };
315
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", gap: 1, children: [
316
+ /* @__PURE__ */ jsxs2(ContainerSlot, { children: [
317
+ chat.messages.flatMap((message) => presentChatMessage(message).map((presentation2, index) => {
318
+ const key = `${message.id}:${index}`;
319
+ if (presentation2.kind === "component") {
320
+ const manifest = definition.components;
321
+ const resolved = manifest === void 0 ? void 0 : resolveComponentFrame2(presentation2.frame, manifest);
322
+ if (resolved?.ok && slots.StandardComponent === void 0 && !STANDARD_COMPONENT_KEYS.includes(presentation2.frame.componentKey)) return /* @__PURE__ */ jsx2(Text2, { children: formatSemanticFallback(presentation2.frame.fallback) }, key);
323
+ if (resolved?.ok) return presentation2.frame.componentKey === "choice-list" ? /* @__PURE__ */ jsx2(ChoiceListSlot, { frame: presentation2.frame, manifest, onSelect: (event) => handleComponentSelect(event, presentation2.frame), isActive: presentation2.frame.instanceId === activeComponentInstanceId }, key) : /* @__PURE__ */ jsx2(StandardComponentSlot, { frame: presentation2.frame, manifest, onInteract: interactComponent, isActive: presentation2.frame.instanceId === activeComponentInstanceId }, key);
324
+ return /* @__PURE__ */ jsx2(SemanticFallback, { fallback: presentation2.frame.fallback }, key);
325
+ }
326
+ if (presentation2.kind === "diagnostic") return /* @__PURE__ */ jsx2(Text2, { color: theme.toolStatus.error.color, children: presentation2.message }, key);
327
+ return /* @__PURE__ */ jsx2(MessageSlot, { message: presentation2.message }, key);
328
+ })),
329
+ chat.messages.flatMap((message) => message.toolCalls ?? []).map((toolCall) => /* @__PURE__ */ jsx2(ConfirmationSlot, { toolCall, onApprove: approve, onDeny: deny }, toolCall.id)),
330
+ /* @__PURE__ */ jsx2(ThinkingSlot, { visible: chat.status === "streaming" })
331
+ ] }),
332
+ chat.error || actionError ? /* @__PURE__ */ jsx2(Text2, { color: theme.toolStatus.error.color, children: chat.error?.message ?? actionError?.message }) : null,
333
+ /* @__PURE__ */ jsx2(InputSlot, { chat, disabled: activeComponentInstanceId !== void 0, onSubmitInput: handleLifecycleCommand, ...placeholder === void 0 ? {} : { placeholder } }),
334
+ /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "/retry \xB7 /regenerate \xB7 /edit <message> \xB7 Esc stop" })
335
+ ] });
336
+ };
337
+ var AgentChat = (props) => /* @__PURE__ */ jsx2(InkThemeProvider, { ...props.theme === void 0 ? {} : { theme: toChatInkTheme(props.theme) }, children: /* @__PURE__ */ jsx2(AgentChatSession, { ...props }, `${props.definition.id}:${props.definition.revision ?? 1}:${props.session?.sessionId ?? "new"}`) });
338
+ export {
339
+ AgentChat,
340
+ ChoiceList,
341
+ SemanticFallback,
342
+ StandardComponent,
343
+ toChatInkTheme
344
+ };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@agentskit/chat-ink",
3
+ "version": "0.1.0",
4
+ "description": "Ink application shell for AgentsKit Chat.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AgentsKit-io/agentskit-chat.git",
9
+ "directory": "packages/ink"
10
+ },
11
+ "homepage": "https://github.com/AgentsKit-io/agentskit-chat#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/AgentsKit-io/agentskit-chat/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "dependencies": {
28
+ "@agentskit/chat-protocol": "0.1.0",
29
+ "@agentskit/chat": "0.1.0"
30
+ },
31
+ "peerDependencies": {
32
+ "@agentskit/ink": "^0.10.1",
33
+ "ink": ">=7.1.0",
34
+ "react": ">=18"
35
+ },
36
+ "devDependencies": {
37
+ "@agentskit/core": "^1.12.2",
38
+ "@agentskit/ink": "^0.10.1",
39
+ "@types/react": "^19.2.17",
40
+ "ink": "^7.1.0",
41
+ "ink-testing-library": "^4.0.0",
42
+ "react": "^19.2.7",
43
+ "tsup": "^8.5.1"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "scripts": {
50
+ "build": "tsup src/index.tsx --format esm --dts --clean --external react --external ink --external @agentskit/ink",
51
+ "lint": "tsc --noEmit",
52
+ "test": "pnpm --filter @agentskit/chat build && vitest run --coverage"
53
+ }
54
+ }