@kuralle-agents/cli 0.13.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ # @kuralle-agents/cli
2
+
3
+ Kuralle's interactive chat, send, simulation, and trace inspection CLI.
4
+
5
+ ```bash
6
+ kuralle trace session-42
7
+ kuralle trace session-42 --last
8
+ kuralle trace session-42 --json
9
+ kuralle trace session-42 --web --port 4319
10
+ ```
11
+
12
+ The terminal view prints a span waterfall with durations and tool, handoff, and
13
+ error markers. `--json` returns the native `AgentTrace` JSON for agents and CI.
14
+ `--web` starts a loopback-only read-only viewer backed by the runtime's configured
15
+ native `TraceStore`; its JSON routes are `/api/traces/:session` and `/api/trace/:id`.
16
+
17
+ Custom agent modules export `buildRuntime(sessionId?, store?)`. Configure a durable
18
+ trace store on that runtime when traces must survive separate CLI invocations.
@@ -0,0 +1,5 @@
1
+ import type { BuildRuntime } from './agentRuntime.js';
2
+ export interface LoaderOptions {
3
+ modelFlag?: string;
4
+ }
5
+ export declare function resolveBuildRuntime(agentPath?: string, options?: LoaderOptions): Promise<BuildRuntime>;
@@ -0,0 +1,144 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { createRuntime, MemoryStore, MemoryTraceStore, } from '@kuralle-agents/core';
4
+ import { buildDemoRuntime } from './demoAgent.js';
5
+ import { fileSessionStore } from './fileStore.js';
6
+ import { fileTraceStore } from './fileTraceStore.js';
7
+ import { readAgentRunState } from './runState.js';
8
+ import { resolveCliModel } from './resolveModel.js';
9
+ import { newSessionId } from './sessionId.js';
10
+ const NAMED_KEYS = ['runtime', 'agent', 'buildRuntime', 'build'];
11
+ function isRuntime(value) {
12
+ return typeof value === 'object' && value !== null && typeof value.run === 'function';
13
+ }
14
+ function isAgentConfig(value) {
15
+ return (typeof value === 'object'
16
+ && value !== null
17
+ && typeof value.id === 'string'
18
+ && 'instructions' in value
19
+ && !isRuntime(value));
20
+ }
21
+ function isAgentRuntime(value) {
22
+ return (typeof value === 'object'
23
+ && value !== null
24
+ && 'runtime' in value
25
+ && 'readState' in value
26
+ && isRuntime(value.runtime));
27
+ }
28
+ function classifyExport(value) {
29
+ if (isRuntime(value))
30
+ return { kind: 'runtime', value };
31
+ if (isAgentConfig(value))
32
+ return { kind: 'agent', value };
33
+ if (typeof value === 'function')
34
+ return { kind: 'factory', value: value };
35
+ return undefined;
36
+ }
37
+ function resolveModuleExport(mod) {
38
+ const candidates = [];
39
+ if ('default' in mod)
40
+ candidates.push(mod.default);
41
+ for (const key of NAMED_KEYS) {
42
+ if (key in mod)
43
+ candidates.push(mod[key]);
44
+ }
45
+ for (const candidate of candidates) {
46
+ const resolved = classifyExport(candidate);
47
+ if (resolved)
48
+ return resolved;
49
+ }
50
+ return undefined;
51
+ }
52
+ function defaultStores(sessionId, store, traceStore) {
53
+ if (store) {
54
+ return {
55
+ sessionStore: store,
56
+ traceStore: traceStore ?? new MemoryTraceStore(),
57
+ fileBacked: false,
58
+ };
59
+ }
60
+ // sim: buildRuntime() with no args → file-backed session store
61
+ if (sessionId === undefined) {
62
+ const path = join(process.cwd(), 'runs/tui-sessions.json');
63
+ return {
64
+ sessionStore: fileSessionStore(path),
65
+ traceStore: traceStore ?? fileTraceStore(path.replace(/\.json$/, '') + '.traces.json'),
66
+ fileBacked: true,
67
+ };
68
+ }
69
+ // chat one-shot: sessionId only → in-memory
70
+ return {
71
+ sessionStore: new MemoryStore(),
72
+ traceStore: traceStore ?? new MemoryTraceStore(),
73
+ fileBacked: false,
74
+ };
75
+ }
76
+ function assembleAgentRuntime(runtime, sessionStore, sessionId, agentId) {
77
+ return {
78
+ runtime,
79
+ store: sessionStore,
80
+ sessionId,
81
+ agentId,
82
+ label: `agent: ${agentId}`,
83
+ readState: () => readAgentRunState(sessionStore, sessionId),
84
+ };
85
+ }
86
+ function buildFromAgent(agent, options) {
87
+ return (sessionId, store, traceStore) => {
88
+ const sid = sessionId ?? newSessionId();
89
+ const stores = defaultStores(sessionId, store, traceStore);
90
+ const model = resolveCliModel(agent, options?.modelFlag);
91
+ const runtime = createRuntime({
92
+ agents: [agent],
93
+ defaultAgentId: agent.id,
94
+ sessionStore: stores.sessionStore,
95
+ defaultModel: model,
96
+ tracing: { store: stores.traceStore },
97
+ });
98
+ return assembleAgentRuntime(runtime, stores.sessionStore, sid, agent.id);
99
+ };
100
+ }
101
+ function buildFromRuntime(runtime) {
102
+ return (sessionId) => {
103
+ const sid = sessionId ?? newSessionId();
104
+ const sessionStore = runtime.getSessionStore();
105
+ const agentId = 'agent';
106
+ return assembleAgentRuntime(runtime, sessionStore, sid, agentId);
107
+ };
108
+ }
109
+ function buildFromFactory(factory) {
110
+ return (sessionId, store, traceStore) => {
111
+ const sid = sessionId ?? newSessionId();
112
+ const stores = defaultStores(sessionId, store, traceStore);
113
+ const result = factory(sid, stores.sessionStore, stores.traceStore);
114
+ if (result instanceof Promise) {
115
+ throw new Error('async buildRuntime factories are not supported');
116
+ }
117
+ if (isAgentRuntime(result))
118
+ return result;
119
+ if (isRuntime(result)) {
120
+ return assembleAgentRuntime(result, stores.sessionStore, sid, 'agent');
121
+ }
122
+ console.error('buildRuntime factory must return Runtime or AgentRuntime');
123
+ process.exit(2);
124
+ };
125
+ }
126
+ export async function resolveBuildRuntime(agentPath, options) {
127
+ if (!agentPath)
128
+ return buildFromFactory(buildDemoRuntime);
129
+ const abs = resolve(agentPath);
130
+ const mod = (await import(pathToFileURL(abs).href));
131
+ const resolved = resolveModuleExport(mod);
132
+ if (!resolved) {
133
+ console.error(`Agent module must export a Runtime, AgentConfig (defineAgent), or buildRuntime factory: ${abs}`);
134
+ process.exit(2);
135
+ }
136
+ switch (resolved.kind) {
137
+ case 'agent':
138
+ return buildFromAgent(resolved.value, options);
139
+ case 'runtime':
140
+ return buildFromRuntime(resolved.value);
141
+ case 'factory':
142
+ return buildFromFactory(resolved.value);
143
+ }
144
+ }
@@ -0,0 +1,15 @@
1
+ import type { Runtime, SessionStore, TraceStore } from '@kuralle-agents/core';
2
+ export interface AgentRuntime {
3
+ runtime: Runtime;
4
+ store: SessionStore;
5
+ sessionId: string;
6
+ agentId: string;
7
+ label: string;
8
+ readState: () => Promise<{
9
+ activeFlow?: string;
10
+ runEpoch?: number;
11
+ completedFlows?: unknown;
12
+ roles: string[];
13
+ }>;
14
+ }
15
+ export type BuildRuntime = (sessionId?: string, store?: SessionStore, traceStore?: TraceStore) => AgentRuntime;
@@ -0,0 +1 @@
1
+ export {};
package/dist/chat.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { BuildRuntime } from './agentRuntime.js';
2
+ export declare function runChat(argv: string[], buildRuntime: BuildRuntime): void;
package/dist/chat.js ADDED
@@ -0,0 +1,179 @@
1
+ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * Kuralle TUI chat — interactive terminal REPL for a live Kuralle runtime.
4
+ *
5
+ * Slash commands: /state /reset /help /quit
6
+ */
7
+ import { useEffect, useRef, useState } from 'react';
8
+ import { render, Box, Text, useApp, useInput, Static } from 'ink';
9
+ import TextInput from 'ink-text-input';
10
+ import { newSessionId } from './sessionId.js';
11
+ import { fileSessionStore } from './fileStore.js';
12
+ import { fileTraceStore } from './fileTraceStore.js';
13
+ /** Order spans as a depth-first tree (turn root → flow → node → tool/handoff). */
14
+ function orderSpans(spans) {
15
+ const byParent = new Map();
16
+ for (const s of spans) {
17
+ const list = byParent.get(s.parentSpanId) ?? [];
18
+ list.push(s);
19
+ byParent.set(s.parentSpanId, list);
20
+ }
21
+ const roots = spans.filter((s) => !s.parentSpanId || !spans.some((p) => p.spanId === s.parentSpanId));
22
+ const out = [];
23
+ const walk = (s, depth) => {
24
+ out.push({ span: s, depth });
25
+ for (const child of byParent.get(s.spanId) ?? [])
26
+ walk(child, depth + 1);
27
+ };
28
+ for (const r of roots)
29
+ walk(r, 0);
30
+ return out;
31
+ }
32
+ const kindColor = (k) => k === 'turn' ? 'white' : k === 'flow' ? 'magenta' : k === 'node' ? 'blue' : k === 'tool' ? 'yellow' : k === 'handoff' ? 'cyan' : 'gray';
33
+ /** Live trace side panel — the built-in AgentTrace of the last turn. */
34
+ function TracePanel({ trace }) {
35
+ const turn = trace?.spans.find((s) => s.kind === 'turn');
36
+ const tin = turn?.attributes.tokensIn;
37
+ const tout = turn?.attributes.tokensOut;
38
+ const ctx = turn?.attributes.contextTokens;
39
+ const parts = [];
40
+ if (tin !== undefined || tout !== undefined)
41
+ parts.push(`turn ${tin ?? '?'}↓/${tout ?? '?'}↑ tok`);
42
+ if (ctx !== undefined)
43
+ parts.push(`ctx ${ctx} tok`);
44
+ const tokensLine = parts.length > 0 ? parts.join(' · ') : undefined;
45
+ return (_jsxs(Box, { flexDirection: "column", width: 46, borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { bold: true, color: "gray", children: ["TRACE ", trace ? `· ${trace.traceId.slice(0, 8)}` : ''] }), !trace && _jsx(Text, { dimColor: true, children: "run a turn to see its trace\u2026" }), trace && (_jsxs(_Fragment, { children: [orderSpans(trace.spans).map(({ span, depth }) => (_jsxs(Text, { color: kindColor(span.kind), children: [' '.repeat(depth), span.status === 'error' ? '✖ ' : '', span.name, _jsxs(Text, { dimColor: true, children: [" \u00B7 ", span.endTime ? `${span.endTime - span.startTime}ms` : '…'] })] }, span.spanId))), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [tokensLine && _jsx(Text, { color: "cyan", children: tokensLine }), _jsxs(Text, { dimColor: true, children: ["used tool: ", String(trace.usedTool)] }), trace.toolResults.map((r, i) => (_jsxs(Text, { color: "yellow", wrap: "truncate-end", children: ["\u2192 ", r.name, ": ", JSON.stringify(r.result)] }, i)))] })] }))] }));
46
+ }
47
+ let LINE_ID = 0;
48
+ const line = (kind, text) => ({ id: LINE_ID++, kind, text });
49
+ async function runTurn(demo, input, onText, onEvent) {
50
+ const handle = demo.runtime.run({ sessionId: demo.sessionId, input });
51
+ let text = '';
52
+ try {
53
+ for await (const part of handle.events) {
54
+ if (part.type === 'text-delta') {
55
+ text += part.delta;
56
+ onText(text);
57
+ }
58
+ else if (part.type === 'tool-call')
59
+ onEvent(`⚙ tool ${part.toolName}`);
60
+ else if (part.type === 'flow-enter')
61
+ onEvent(`▸ enter flow ${part.flow}`);
62
+ else if (part.type === 'flow-end')
63
+ onEvent(`■ end flow ${part.flow}`);
64
+ else if (part.type === 'handoff')
65
+ onEvent(`→ handoff ${part.targetAgent}`);
66
+ else if (part.type === 'paused')
67
+ onEvent(`⏸ paused ${part.waitingFor ?? ''}`);
68
+ else if (part.type === 'error')
69
+ onEvent(`✖ ${part.error}`);
70
+ }
71
+ const res = await handle;
72
+ if (!text && typeof res.text === 'string')
73
+ text = res.text;
74
+ }
75
+ catch (e) {
76
+ onEvent(`✖ ${e instanceof Error ? e.message : String(e)}`);
77
+ }
78
+ return text.trim();
79
+ }
80
+ function App({ scripted, buildRuntime, showTrace, persist }) {
81
+ const { exit } = useApp();
82
+ const make = (sid) => persist ? buildRuntime(sid ?? persist.sessionId, persist.sessionStore, persist.traceStore) : buildRuntime(sid);
83
+ const demoRef = useRef(make());
84
+ const [log, setLog] = useState([line('system', demoRef.current.label)]);
85
+ const [live, setLive] = useState('');
86
+ const [events, setEvents] = useState([]);
87
+ const [status, setStatus] = useState('flow: none · epoch: 0');
88
+ const [value, setValue] = useState('');
89
+ const [busy, setBusy] = useState(false);
90
+ const [trace, setTrace] = useState(null);
91
+ useInput((input, key) => { if (key.ctrl && input === 'c')
92
+ exit(); }, { isActive: !scripted && Boolean(process.stdin.isTTY) });
93
+ const push = (l) => setLog((prev) => [...prev, l]);
94
+ const refreshStatus = async () => {
95
+ const s = await demoRef.current.readState();
96
+ setStatus(`flow: ${s.activeFlow ?? 'none'} · epoch: ${s.runEpoch ?? 0} · done: ${JSON.stringify(s.completedFlows ?? [])}`);
97
+ };
98
+ const submit = async (raw) => {
99
+ const text = raw.trim();
100
+ if (!text || busy)
101
+ return;
102
+ setValue('');
103
+ if (text === '/quit') {
104
+ exit();
105
+ return;
106
+ }
107
+ if (text === '/help') {
108
+ push(line('system', 'commands: /state /reset /quit'));
109
+ return;
110
+ }
111
+ if (text === '/reset') {
112
+ demoRef.current = make(newSessionId());
113
+ push(line('system', `— new session ${demoRef.current.sessionId.slice(0, 8)} —`));
114
+ await refreshStatus();
115
+ return;
116
+ }
117
+ if (text === '/state') {
118
+ const s = await demoRef.current.readState();
119
+ push(line('system', `state: flow=${s.activeFlow ?? 'none'} epoch=${s.runEpoch ?? 0} completed=${JSON.stringify(s.completedFlows ?? [])} roles=[${s.roles.join(',')}]`));
120
+ return;
121
+ }
122
+ push(line('user', text));
123
+ setBusy(true);
124
+ setEvents([]);
125
+ setLive('');
126
+ const turnEvents = [];
127
+ const answer = await runTurn(demoRef.current, text, setLive, (e) => { turnEvents.push(e); setEvents([...turnEvents]); });
128
+ setLive('');
129
+ for (const e of turnEvents)
130
+ push(line('event', e));
131
+ push(line('assistant', answer || '(no text)'));
132
+ setBusy(false);
133
+ await refreshStatus();
134
+ if (showTrace) {
135
+ setTrace((await demoRef.current.runtime.listTraces(demoRef.current.sessionId))[0] ?? null);
136
+ }
137
+ };
138
+ useEffect(() => {
139
+ if (!scripted?.length)
140
+ return;
141
+ let cancelled = false;
142
+ (async () => {
143
+ for (const t of scripted) {
144
+ if (cancelled)
145
+ return;
146
+ await submit(t);
147
+ }
148
+ push(line('system', '— auto complete —'));
149
+ setTimeout(() => exit(), 100);
150
+ })();
151
+ return () => { cancelled = true; };
152
+ // eslint-disable-next-line react-hooks/exhaustive-deps
153
+ }, []);
154
+ const color = (k) => (k === 'user' ? 'cyan' : k === 'assistant' ? 'green' : k === 'event' ? 'gray' : 'yellow');
155
+ const prefix = (k) => (k === 'user' ? 'You' : k === 'assistant' ? 'Agent' : k === 'event' ? ' ·' : ' ~');
156
+ const body = (_jsxs(Box, { flexDirection: "column", flexGrow: 1, paddingRight: showTrace ? 1 : 0, children: [_jsx(Static, { items: log, children: (l) => (_jsxs(Text, { color: color(l.kind), children: [_jsx(Text, { bold: l.kind === 'user' || l.kind === 'assistant', children: prefix(l.kind) }), ' ', l.text] }, l.id)) }), busy && (_jsxs(Box, { flexDirection: "column", children: [events.length > 0 && _jsx(Text, { color: "gray", children: events.join(' ') }), _jsxs(Text, { color: "green", children: [_jsx(Text, { bold: true, children: "Agent" }), " ", live, _jsx(Text, { color: "green", children: "\u258C" })] })] })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: status }) }), !scripted && (_jsxs(Box, { children: [_jsx(Text, { color: "cyan", children: busy ? '…thinking ' : '❯ ' }), !busy && _jsx(TextInput, { value: value, onChange: setValue, onSubmit: submit, placeholder: "type a message, or /help" })] }))] }));
157
+ return showTrace ? (_jsxs(Box, { flexDirection: "row", children: [body, _jsx(TracePanel, { trace: trace })] })) : body;
158
+ }
159
+ export function runChat(argv, buildRuntime) {
160
+ const flag = (name) => {
161
+ const i = argv.indexOf(name);
162
+ return i >= 0 ? argv[i + 1] : undefined;
163
+ };
164
+ const scripted = argv.includes('--auto')
165
+ ? (flag('--auto') ?? '').split('|').map((s) => s.trim()).filter(Boolean)
166
+ : undefined;
167
+ const showTrace = argv.includes('--trace');
168
+ // --store persists BOTH the session (conversation/journal) and the traces to
169
+ // JSON files, so `--trace` accumulates across launches. --session picks the id.
170
+ const storePath = flag('--store');
171
+ const persist = storePath
172
+ ? {
173
+ sessionStore: fileSessionStore(storePath),
174
+ traceStore: fileTraceStore(storePath.replace(/\.json$/, '') + '.traces.json'),
175
+ sessionId: flag('--session') ?? 'default',
176
+ }
177
+ : undefined;
178
+ render(_jsx(App, { scripted: scripted, buildRuntime: buildRuntime, showTrace: showTrace, persist: persist }));
179
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * kuralle — Kuralle CLI for interactive chat, adaptive send, and simulation.
4
+ *
5
+ * kuralle chat [--trace] [--store <file>] [--session <id>] [--auto "msg1|msg2"] [--agent <path.ts>]
6
+ * kuralle send --session <id> [--store <file>] [--state|--reset] "<message>"
7
+ * kuralle sim --goal "<goal>" [--turns N] [--profile "<who>"] [--agent <path.ts>]
8
+ * kuralle trace <session> [--last] [--json] [--web] [--port N]
9
+ */
10
+ import { resolveBuildRuntime } from './agentLoader.js';
11
+ import { runChat } from './chat.js';
12
+ import { runSend } from './send.js';
13
+ import { runSim } from './sim.js';
14
+ import { runTrace } from './trace.js';
15
+ const HELP = `kuralle — Kuralle agent CLI
16
+
17
+ Usage:
18
+ kuralle chat [--trace] [--store <file>] [--session <id>] [--auto "msg1|msg2"] [--agent <path.ts>]
19
+ kuralle send --session <id> [--store <file>] [--state|--reset] "<message>"
20
+ kuralle sim --goal "<goal>" [--turns N] [--profile "<who>"] [--agent <path.ts>]
21
+ kuralle trace <session> [--last] [--json] [--web] [--port N]
22
+
23
+ Options:
24
+ --agent <path.ts> Load a Runtime, defineAgent export, or buildRuntime factory
25
+ --model <id> OpenAI model id when the agent export has no model (bare-agent shape)
26
+ --auto "a|b|c" Headless scripted turns (chat only)
27
+ --trace Live trace side panel — the built-in AgentTrace of each turn (chat only)
28
+ --store <file> Persist the session + traces to JSON files so chat survives across launches (chat only)
29
+ --session <id> Session id to resume with --store (default: "default")
30
+ `;
31
+ function flag(argv, name) {
32
+ const i = argv.indexOf(name);
33
+ return i >= 0 ? argv[i + 1] : undefined;
34
+ }
35
+ function stripGlobalFlags(argv) {
36
+ const rest = [];
37
+ let agentPath;
38
+ for (let i = 0; i < argv.length; i += 1) {
39
+ const a = argv[i];
40
+ if (a === '--agent') {
41
+ agentPath = argv[i + 1];
42
+ i += 1;
43
+ continue;
44
+ }
45
+ rest.push(a);
46
+ }
47
+ return { rest, agentPath };
48
+ }
49
+ async function main() {
50
+ const rawArgv = process.argv.slice(2);
51
+ if (rawArgv.length === 0 || rawArgv.includes('--help') || rawArgv.includes('-h')) {
52
+ process.stdout.write(HELP);
53
+ process.exit(0);
54
+ }
55
+ const { rest, agentPath } = stripGlobalFlags(rawArgv);
56
+ const sub = rest[0];
57
+ const subArgv = rest.slice(1);
58
+ const buildRuntime = await resolveBuildRuntime(agentPath ?? flag(rawArgv, '--agent'), {
59
+ modelFlag: flag(rawArgv, '--model'),
60
+ });
61
+ switch (sub) {
62
+ case 'chat':
63
+ runChat(subArgv, buildRuntime);
64
+ break;
65
+ case 'send':
66
+ await runSend(subArgv, buildRuntime);
67
+ break;
68
+ case 'sim':
69
+ await runSim(subArgv, buildRuntime);
70
+ break;
71
+ case 'trace':
72
+ await runTrace(subArgv, buildRuntime);
73
+ break;
74
+ default:
75
+ console.error(`Unknown command: ${sub}\n`);
76
+ process.stdout.write(HELP);
77
+ process.exit(2);
78
+ }
79
+ }
80
+ main().catch((err) => {
81
+ console.error(err instanceof Error ? err.message : String(err));
82
+ process.exit(1);
83
+ });
@@ -0,0 +1,7 @@
1
+ import type { LanguageModel } from 'ai';
2
+ import { type SessionStore, type TraceStore } from '@kuralle-agents/core';
3
+ import type { AgentRuntime, BuildRuntime } from './agentRuntime.js';
4
+ export declare function demoModel(): LanguageModel;
5
+ export declare function buildDemoRuntime(sessionId?: string, store?: SessionStore, traceStore?: TraceStore): AgentRuntime;
6
+ /** Alias matching the custom-agent contract (`buildRuntime`). */
7
+ export declare const buildRuntime: BuildRuntime;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Demo agent for the CLI — a cafe concierge that exercises fixed behaviours:
3
+ * order flow (collect item+day → place), global tool (todays_special), repeatable
4
+ * flows, and billing handoff. Provider: OpenAI gpt-4.1-mini (forced).
5
+ */
6
+ import { config } from 'dotenv';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { z } from 'zod';
10
+ import { createOpenAI } from '@ai-sdk/openai';
11
+ import { createRuntime, defineAgent, defineFlow, reply, collect, defineTool, MemoryStore, MemoryTraceStore, } from '@kuralle-agents/core';
12
+ import { readAgentRunState } from './runState.js';
13
+ import { newSessionId } from './sessionId.js';
14
+ const here = dirname(fileURLToPath(import.meta.url));
15
+ config({ path: join(here, '../.env') });
16
+ config({ path: join(here, '../../../.env') });
17
+ export function demoModel() {
18
+ const key = process.env.OPENAI_API_KEY;
19
+ if (!key) {
20
+ console.error('No OPENAI_API_KEY — set it in packages/cli/.env or the repo .env');
21
+ process.exit(2);
22
+ }
23
+ return createOpenAI({ apiKey: key })(process.env.OPENAI_MODEL ?? 'gpt-4.1-mini');
24
+ }
25
+ export function buildDemoRuntime(sessionId = newSessionId(), store = new MemoryStore(), traceStore = new MemoryTraceStore()) {
26
+ const model = demoModel();
27
+ const lastInvoice = defineTool({
28
+ name: 'last_invoice',
29
+ description: 'Return the caller last invoice total. Bill uses this to answer billing questions.',
30
+ input: z.object({}),
31
+ execute: async () => ({ invoiceUsd: 18.5, date: '2026-07-01' }),
32
+ });
33
+ const billing = defineAgent({
34
+ // Bill from billing — no forced self-introduction, so the handoff reads as one
35
+ // continuous assistant (silent handoff is on by default). Instructing a handoff
36
+ // target to greet/introduce itself is the anti-pattern that leaks the transfer.
37
+ id: 'billing',
38
+ instructions: 'You are Bill, the billing specialist. Answer billing/invoice questions using last_invoice. Keep replies to one or two sentences.',
39
+ model,
40
+ globalTools: { last_invoice: lastInvoice },
41
+ });
42
+ const done = reply({
43
+ id: 'done',
44
+ instructions: 'Say the order is placed for {{item}} on {{day}} — one upbeat sentence. Do not ask anything else.',
45
+ next: () => ({ end: 'ordered' }),
46
+ });
47
+ const collectOrder = collect({
48
+ id: 'collect_order',
49
+ schema: z.object({ item: z.string().min(2).nullable(), day: z.string().min(2).nullable() }),
50
+ required: ['item', 'day'],
51
+ maxTurns: 6,
52
+ instructions: (missing) => `Take the cafe order. Missing: ${missing.join(', ') || 'none'}. Ask for the item and the day; if the caller corrects a value, use the new one.`,
53
+ onComplete: () => done,
54
+ });
55
+ const orderFlow = defineFlow({
56
+ name: 'order',
57
+ description: 'Take a cafe order (item + day) and place it.',
58
+ start: collectOrder,
59
+ nodes: [collectOrder, done],
60
+ });
61
+ const special = defineTool({
62
+ name: 'todays_special',
63
+ description: "Return today's cafe special. Call this whenever the caller asks about the special.",
64
+ input: z.object({}),
65
+ execute: async () => ({ special: 'Cardamom bun', priceUsd: 3.5 }),
66
+ });
67
+ const concierge = defineAgent({
68
+ id: 'concierge',
69
+ instructions: 'You are a warm cafe concierge. Coffee is $4. Use the order flow when the caller wants to order. ' +
70
+ 'Use todays_special for the special. Transfer billing/invoice questions to the billing specialist. Keep replies short.',
71
+ model,
72
+ flows: [orderFlow],
73
+ globalTools: { todays_special: special },
74
+ handoffs: ['billing'],
75
+ agents: [billing],
76
+ experimental: { outOfBandControl: true },
77
+ });
78
+ const runtime = createRuntime({
79
+ agents: [concierge, billing],
80
+ defaultAgentId: 'concierge',
81
+ sessionStore: store,
82
+ defaultModel: model,
83
+ tracing: { store: traceStore },
84
+ });
85
+ const readState = () => readAgentRunState(store, sessionId);
86
+ return {
87
+ runtime,
88
+ store,
89
+ sessionId,
90
+ agentId: 'concierge',
91
+ label: 'Cafe concierge (order flow · special tool · billing handoff)',
92
+ readState,
93
+ };
94
+ }
95
+ /** Alias matching the custom-agent contract (`buildRuntime`). */
96
+ export const buildRuntime = buildDemoRuntime;
@@ -0,0 +1,2 @@
1
+ import type { SessionStore } from '@kuralle-agents/core';
2
+ export declare function fileSessionStore(path: string): SessionStore;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A tiny JSON-file-backed SessionStore so a conversation survives across separate
3
+ * process invocations — the substrate that lets `send` do adaptive multi-turn
4
+ * (one turn per call). `reviveSession` spreads all keys, so the durable-run state
5
+ * (`durableRuns`: journal + flow position + runEpoch) round-trips through JSON intact.
6
+ */
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
8
+ import { dirname } from 'node:path';
9
+ import { reviveSession } from '@kuralle-agents/core';
10
+ export function fileSessionStore(path) {
11
+ const readAll = () => {
12
+ if (!existsSync(path))
13
+ return {};
14
+ try {
15
+ return JSON.parse(readFileSync(path, 'utf8'));
16
+ }
17
+ catch {
18
+ return {};
19
+ }
20
+ };
21
+ const writeAll = (map) => {
22
+ mkdirSync(dirname(path), { recursive: true });
23
+ writeFileSync(path, JSON.stringify(map));
24
+ };
25
+ return {
26
+ async get(id) {
27
+ const map = readAll();
28
+ return map[id] ? reviveSession(map[id]) : null;
29
+ },
30
+ async save(session) {
31
+ const map = readAll();
32
+ map[session.id] = session;
33
+ writeAll(map);
34
+ },
35
+ async delete(id) {
36
+ const map = readAll();
37
+ delete map[id];
38
+ writeAll(map);
39
+ },
40
+ async list(userId) {
41
+ return Object.values(readAll())
42
+ .map((raw) => reviveSession(raw))
43
+ .filter((s) => (userId ? s.userId === userId : true));
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,2 @@
1
+ import type { TraceStore } from '@kuralle-agents/core';
2
+ export declare function fileTraceStore(path: string): TraceStore;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * A tiny JSONL-file-backed TraceStore so `kuralle chat --trace --store <file>`
3
+ * accumulates traces across launches (dev only). Spans are APPENDED one-per-line
4
+ * — O(1) per write, no full-file rewrite — and reconstructed on read (last write
5
+ * wins per spanId). Production trace stores live in @kuralle-agents/{redis,postgres}-store
6
+ * and @kuralle-agents/cf-agent.
7
+ */
8
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
9
+ import { dirname } from 'node:path';
10
+ import { traceFromSpans } from '@kuralle-agents/core/tracing';
11
+ export function fileTraceStore(path) {
12
+ let dirReady = false;
13
+ const putSpan = (span) => {
14
+ if (!dirReady) {
15
+ mkdirSync(dirname(path), { recursive: true });
16
+ dirReady = true;
17
+ }
18
+ appendFileSync(path, `${JSON.stringify(span)}\n`);
19
+ };
20
+ const readByTrace = () => {
21
+ const byTrace = new Map();
22
+ if (!existsSync(path))
23
+ return byTrace;
24
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
25
+ if (!line)
26
+ continue;
27
+ try {
28
+ const span = JSON.parse(line);
29
+ let spans = byTrace.get(span.traceId);
30
+ if (!spans) {
31
+ spans = new Map();
32
+ byTrace.set(span.traceId, spans);
33
+ }
34
+ spans.set(span.spanId, span); // last write wins (span updates)
35
+ }
36
+ catch {
37
+ // skip a torn/partial line rather than fail the read
38
+ }
39
+ }
40
+ return byTrace;
41
+ };
42
+ return {
43
+ write: putSpan,
44
+ putSpan,
45
+ async getTrace(traceId) {
46
+ return traceFromSpans([...(readByTrace().get(traceId)?.values() ?? [])]);
47
+ },
48
+ async listTraces(sessionId, window) {
49
+ const traces = [...readByTrace().values()]
50
+ .map((spans) => traceFromSpans([...spans.values()]))
51
+ .filter((t) => t !== null && t.sessionId === sessionId)
52
+ .sort((a, b) => b.startedAt - a.startedAt);
53
+ return window?.limit === undefined ? traces : traces.slice(0, window.limit);
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,4 @@
1
+ import type { LanguageModel } from 'ai';
2
+ import type { AgentConfig } from '@kuralle-agents/core';
3
+ /** Resolve a speaker model for a bare agent: agent.model → --model → OPENAI_MODEL → error. */
4
+ export declare function resolveCliModel(agent: AgentConfig, modelFlag?: string): LanguageModel;
@@ -0,0 +1,24 @@
1
+ import { config } from 'dotenv';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { createOpenAI } from '@ai-sdk/openai';
5
+ const here = dirname(fileURLToPath(import.meta.url));
6
+ config({ path: join(here, '../.env') });
7
+ config({ path: join(here, '../../../.env') });
8
+ /** Resolve a speaker model for a bare agent: agent.model → --model → OPENAI_MODEL → error. */
9
+ export function resolveCliModel(agent, modelFlag) {
10
+ if (agent.model)
11
+ return agent.model;
12
+ const key = process.env.OPENAI_API_KEY;
13
+ if (!key) {
14
+ console.error('No OPENAI_API_KEY — set it in packages/cli/.env or the repo .env');
15
+ process.exit(2);
16
+ }
17
+ const openai = createOpenAI({ apiKey: key });
18
+ if (modelFlag)
19
+ return openai(modelFlag);
20
+ if (process.env.OPENAI_MODEL)
21
+ return openai(process.env.OPENAI_MODEL);
22
+ console.error('agent has no model; pass --model');
23
+ process.exit(2);
24
+ }
@@ -0,0 +1,9 @@
1
+ import type { SessionStore } from '@kuralle-agents/core';
2
+ export interface AgentRunState {
3
+ activeFlow?: string;
4
+ runEpoch?: number;
5
+ completedFlows?: unknown;
6
+ roles: string[];
7
+ }
8
+ /** Read flow position + message roles from the durable run journal (CLI-internal). */
9
+ export declare function readAgentRunState(store: SessionStore, sessionId: string): Promise<AgentRunState>;
@@ -0,0 +1,11 @@
1
+ /** Read flow position + message roles from the durable run journal (CLI-internal). */
2
+ export async function readAgentRunState(store, sessionId) {
3
+ const s = await store.get(sessionId);
4
+ const rs = s?.durableRuns?.[sessionId]?.runState;
5
+ return {
6
+ activeFlow: rs?.activeFlow,
7
+ runEpoch: rs?.runEpoch,
8
+ completedFlows: rs?.state?.__completedFlows,
9
+ roles: (s?.messages ?? []).map((m) => m.role),
10
+ };
11
+ }
package/dist/send.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { BuildRuntime } from './agentRuntime.js';
2
+ export declare function runSend(argv: string[], buildRuntime: BuildRuntime): Promise<void>;
package/dist/send.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * send — ONE turn against a PERSISTED session for adaptive multi-turn conversations.
3
+ *
4
+ * Flags: --session <id> · --store <file> · --state · --reset
5
+ */
6
+ import { join } from 'node:path';
7
+ import { fileSessionStore } from './fileStore.js';
8
+ function flag(argv, name) {
9
+ const i = argv.indexOf(name);
10
+ return i >= 0 ? argv[i + 1] : undefined;
11
+ }
12
+ export async function runSend(argv, buildRuntime) {
13
+ const sessionId = flag(argv, '--session') ?? 'default';
14
+ const storePath = flag(argv, '--store') ?? join(process.cwd(), 'runs/tui-sessions.json');
15
+ const doReset = argv.includes('--reset');
16
+ const doState = argv.includes('--state');
17
+ const reserved = new Set(['--session', sessionId, '--store', storePath]);
18
+ const message = argv
19
+ .filter((a, i) => !a.startsWith('--') && !(i > 0 && (argv[i - 1] === '--session' || argv[i - 1] === '--store')))
20
+ .join(' ')
21
+ .trim();
22
+ const store = fileSessionStore(storePath);
23
+ const demo = buildRuntime(sessionId, store);
24
+ async function readState() {
25
+ const s = await store.get(sessionId);
26
+ const rs = s?.durableRuns?.[sessionId]?.runState;
27
+ return `[state] flow=${rs?.activeFlow ?? 'none'} · epoch=${rs?.runEpoch ?? 0} · done=${JSON.stringify(rs?.state?.__completedFlows ?? [])} · turns=${(s?.messages ?? []).filter((m) => m.role === 'user').length}`;
28
+ }
29
+ if (doReset) {
30
+ await store.delete(sessionId);
31
+ console.log(`reset session "${sessionId}"`);
32
+ return;
33
+ }
34
+ if (doState || !message) {
35
+ console.log(await readState());
36
+ if (!message && !doState)
37
+ console.error('(no message — pass one to take a turn, or --state to inspect)');
38
+ return;
39
+ }
40
+ const events = [];
41
+ const handle = demo.runtime.run({ sessionId, input: message });
42
+ let text = '';
43
+ for await (const part of handle.events) {
44
+ if (part.type === 'text-delta') {
45
+ text += part.delta;
46
+ process.stdout.write(part.delta);
47
+ }
48
+ else if (part.type === 'tool-call')
49
+ events.push(`tool:${part.toolName}`);
50
+ else if (part.type === 'flow-enter')
51
+ events.push(`enter:${part.flow}`);
52
+ else if (part.type === 'flow-end')
53
+ events.push(`end:${part.flow}`);
54
+ else if (part.type === 'handoff')
55
+ events.push(`handoff:${part.targetAgent}`);
56
+ else if (part.type === 'paused')
57
+ events.push(`paused:${part.waitingFor ?? ''}`);
58
+ else if (part.type === 'error')
59
+ events.push(`error:${part.error}`);
60
+ }
61
+ const res = await handle;
62
+ if (!text && typeof res.text === 'string')
63
+ text = res.text;
64
+ if (!text.endsWith('\n'))
65
+ process.stdout.write('\n');
66
+ if (events.length)
67
+ console.log(`[events] ${events.join(' ')}`);
68
+ console.log(await readState());
69
+ }
@@ -0,0 +1,2 @@
1
+ /** Local session id helper — core's `newSessionId` is not on the public index. */
2
+ export declare function newSessionId(): string;
@@ -0,0 +1,5 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ /** Local session id helper — core's `newSessionId` is not on the public index. */
3
+ export function newSessionId() {
4
+ return randomUUID();
5
+ }
package/dist/sim.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { BuildRuntime } from './agentRuntime.js';
2
+ export declare function runSim(argv: string[], buildRuntime: BuildRuntime): Promise<void>;
package/dist/sim.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * sim — drive simulateConversation with a persona toward a goal and print the transcript.
3
+ */
4
+ import { simulateConversation, createJudge } from '@kuralle-agents/core';
5
+ import { demoModel } from './demoAgent.js';
6
+ function flag(argv, name) {
7
+ const i = argv.indexOf(name);
8
+ return i >= 0 ? argv[i + 1] : undefined;
9
+ }
10
+ export async function runSim(argv, buildRuntime) {
11
+ const goal = flag(argv, '--goal');
12
+ if (!goal) {
13
+ console.error('Usage: kuralle sim --goal "<persona goal>" [--turns N] [--profile "<who>"] [--agent <path.ts>]');
14
+ process.exit(2);
15
+ }
16
+ const turnsRaw = flag(argv, '--turns');
17
+ const maxTurns = turnsRaw ? Number.parseInt(turnsRaw, 10) : 10;
18
+ if (!Number.isFinite(maxTurns) || maxTurns < 1) {
19
+ console.error('--turns must be a positive integer');
20
+ process.exit(2);
21
+ }
22
+ const profile = flag(argv, '--profile') ?? 'a customer chatting with the agent';
23
+ const model = demoModel();
24
+ const demo = buildRuntime();
25
+ const persona = { profile, goal, temperament: 'brief and direct' };
26
+ console.log(`Simulating: ${profile}`);
27
+ console.log(`Goal: ${goal}`);
28
+ console.log(`Max turns: ${maxTurns}\n`);
29
+ const result = await simulateConversation({
30
+ runtime: demo.runtime,
31
+ persona,
32
+ userModel: model,
33
+ maxTurns,
34
+ sessionId: demo.sessionId,
35
+ });
36
+ for (const turn of result.transcript) {
37
+ const label = turn.role === 'user' ? 'You' : 'Agent';
38
+ console.log(`${label}: ${turn.content}\n`);
39
+ }
40
+ console.log(`— ended by: ${result.endedBy} · turns: ${result.turns} · tools: ${result.toolsCalled.join(', ') || 'none'} —`);
41
+ const judge = createJudge({ model });
42
+ const verdict = await judge.judge(result, persona);
43
+ console.log(`Judge: overall=${verdict.overall.toFixed(1)} pass=${verdict.pass} — ${verdict.summary}`);
44
+ }
@@ -0,0 +1,6 @@
1
+ import type { AgentTrace } from '@kuralle-agents/core';
2
+ import { type Server } from 'node:http';
3
+ import type { BuildRuntime } from './agentRuntime.js';
4
+ export declare function runTrace(argv: string[], buildRuntime: BuildRuntime): Promise<void>;
5
+ export declare function startTraceWebServer(runtime: Pick<import('@kuralle-agents/core').Runtime, 'listTraces' | 'getTrace'>, sessionId: string, port?: number): Promise<Server>;
6
+ export declare function formatTrace(trace: AgentTrace): string;
package/dist/trace.js ADDED
@@ -0,0 +1,116 @@
1
+ import { renderTraceViewerDocument } from '@kuralle-agents/trace-ui';
2
+ import { createServer } from 'node:http';
3
+ export async function runTrace(argv, buildRuntime) {
4
+ const sessionId = argv.find((arg) => !arg.startsWith('--'));
5
+ if (!sessionId)
6
+ throw new Error('Usage: kuralle trace <session> [--last] [--json]');
7
+ const { runtime } = buildRuntime(sessionId);
8
+ if (argv.includes('--web')) {
9
+ const port = numberFlag(argv, '--port') ?? 4319;
10
+ await startTraceWebServer(runtime, sessionId, port);
11
+ process.stdout.write(`Kuralle trace viewer: http://127.0.0.1:${port}\n`);
12
+ return;
13
+ }
14
+ const traces = await runtime.listTraces(sessionId);
15
+ const selected = argv.includes('--last') ? traces.slice(0, 1) : traces;
16
+ if (argv.includes('--json')) {
17
+ process.stdout.write(`${JSON.stringify(argv.includes('--last') ? selected[0] ?? null : selected, null, 2)}\n`);
18
+ return;
19
+ }
20
+ if (selected.length === 0) {
21
+ process.stdout.write(`No traces found for session ${sessionId}\n`);
22
+ return;
23
+ }
24
+ process.stdout.write(`${selected.map(formatTrace).join('\n\n')}\n`);
25
+ }
26
+ export async function startTraceWebServer(runtime, sessionId, port = 4319) {
27
+ const server = createServer(async (request, response) => {
28
+ try {
29
+ const url = new URL(request.url ?? '/', 'http://localhost');
30
+ if (url.pathname === `/api/traces/${encodeURIComponent(sessionId)}`) {
31
+ return sendJson(response, await runtime.listTraces(sessionId));
32
+ }
33
+ if (url.pathname.startsWith('/api/trace/')) {
34
+ const traceId = decodeURIComponent(url.pathname.slice('/api/trace/'.length));
35
+ const trace = await runtime.getTrace(traceId);
36
+ return sendJson(response, trace, trace ? 200 : 404);
37
+ }
38
+ if (url.pathname === '/') {
39
+ const nonce = crypto.randomUUID().replaceAll('-', '');
40
+ const html = renderTraceViewerDocument(await runtime.listTraces(sessionId), {
41
+ title: `Kuralle traces · ${sessionId}`,
42
+ nonce,
43
+ });
44
+ response.writeHead(200, {
45
+ 'content-type': 'text/html; charset=utf-8',
46
+ 'content-security-policy': `default-src 'none'; style-src 'nonce-${nonce}'; base-uri 'none'; frame-ancestors 'self'`,
47
+ 'cache-control': 'no-store',
48
+ });
49
+ response.end(html);
50
+ return;
51
+ }
52
+ response.writeHead(404).end('Not found');
53
+ }
54
+ catch (error) {
55
+ response.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
56
+ response.end(error instanceof Error ? error.message : String(error));
57
+ }
58
+ });
59
+ await new Promise((resolve, reject) => {
60
+ server.once('error', reject);
61
+ server.listen(port, '127.0.0.1', resolve);
62
+ });
63
+ return server;
64
+ }
65
+ function sendJson(response, value, status = 200) {
66
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
67
+ response.end(JSON.stringify(value));
68
+ }
69
+ function numberFlag(argv, name) {
70
+ const index = argv.indexOf(name);
71
+ if (index < 0)
72
+ return undefined;
73
+ const value = Number(argv[index + 1]);
74
+ if (!Number.isInteger(value) || value < 0 || value > 65535)
75
+ throw new Error(`${name} requires a valid port`);
76
+ return value;
77
+ }
78
+ export function formatTrace(trace) {
79
+ const start = trace.startedAt;
80
+ const end = trace.endedAt ?? Math.max(...trace.spans.map((span) => span.endTime ?? span.startTime));
81
+ const duration = Math.max(1, end - start);
82
+ const lines = [
83
+ `trace ${trace.traceId} session ${trace.sessionId} ${formatDuration(end - start)}`,
84
+ ' offset duration span',
85
+ ];
86
+ for (const span of trace.spans) {
87
+ const offset = span.startTime - start;
88
+ const width = Math.max(1, Math.round(((span.endTime ?? end) - span.startTime) / duration * 30));
89
+ const indent = depth(span, trace.spans) * 2;
90
+ lines.push(`${String(offset).padStart(7)}ms ${formatDuration((span.endTime ?? end) - span.startTime).padStart(8)} ` +
91
+ `${' '.repeat(indent)}${marker(span)} ${span.name} ${'━'.repeat(width)}`);
92
+ }
93
+ return lines.join('\n');
94
+ }
95
+ function depth(span, spans) {
96
+ const byId = new Map(spans.map((entry) => [entry.spanId, entry]));
97
+ let parent = span.parentSpanId;
98
+ let value = 0;
99
+ while (parent && value < 10) {
100
+ value += 1;
101
+ parent = byId.get(parent)?.parentSpanId;
102
+ }
103
+ return value;
104
+ }
105
+ function marker(span) {
106
+ if (span.status === 'error')
107
+ return '✕';
108
+ if (span.kind === 'tool')
109
+ return '🔧';
110
+ if (span.kind === 'handoff')
111
+ return '⇢';
112
+ return '●';
113
+ }
114
+ function formatDuration(ms) {
115
+ return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${ms}ms`;
116
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@kuralle-agents/cli",
3
+ "license": "Apache-2.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/kuralle/kuralle-agents.git",
7
+ "directory": "packages/cli"
8
+ },
9
+ "version": "0.13.0",
10
+ "description": "Kuralle CLI — interactive TUI chat, adaptive send, and conversation simulation",
11
+ "type": "module",
12
+ "bin": {
13
+ "kuralle": "./dist/cli.js"
14
+ },
15
+ "dependencies": {
16
+ "@ai-sdk/openai": "^3.0.0",
17
+ "ai": "^6.0.0",
18
+ "dotenv": "^16.4.0",
19
+ "ink": "^7.1.0",
20
+ "ink-text-input": "^6.0.0",
21
+ "react": "^19.2.7",
22
+ "zod": "^4.0.0",
23
+ "@kuralle-agents/core": "0.13.0",
24
+ "@kuralle-agents/trace-ui": "0.13.0"
25
+ },
26
+ "peerDependencies": {
27
+ "ai": "^6.0.0",
28
+ "zod": "^4.0.0",
29
+ "@kuralle-agents/core": "0.13.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^20.11.0",
33
+ "@types/react": "^19.2.17",
34
+ "typescript": "^5.3.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "README.md"
42
+ ],
43
+ "scripts": {
44
+ "prebuild": "rm -rf dist",
45
+ "build": "tsc -p tsconfig.json",
46
+ "typecheck": "tsc --noEmit -p tsconfig.json",
47
+ "clean": "rm -rf dist"
48
+ }
49
+ }