@zenera/meta 1.3.1 → 1.3.2

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,303 @@
1
+ // packages/meta/src/chat/session.ts
2
+ //
3
+ // One `zen meta chat` conversation over the Copilot SDK, with no drawing in it: open (or resume) a session on
4
+ // the wired provider, send a turn and wait for it to settle, and narrate the SDK's events as `ChatEvent`s.
5
+ // Main: `openChat(opts)` -> `Chat` (`send`, `abort`, `close`); also `providerConfig` (a `Wiring`'s env as the
6
+ // SDK's typed provider), `toCall` (an `assistant.usage` event as a ledger `MetaCall`), `narrate` and `EFFORTS`.
7
+ // Used by: `chat/run.ts`, which drives it from the chat screen in `chat/tui.tsx`.
8
+ import { setTimeout as sleep } from 'node:timers/promises';
9
+ import { RESUME_PROMPT, resumeDelayMs, transient } from "../launch.js";
10
+ /** The real one, loaded only when a chat opens: it brings a native runtime with it. */
11
+ const connectSdk = async (options) => {
12
+ const { CopilotClient } = await import('@github/copilot-sdk');
13
+ return new CopilotClient(options);
14
+ };
15
+ // ---------------------------------------------------------------------------
16
+ // The wiring, typed
17
+ //
18
+ // `zen meta run` hands copilot its provider in `COPILOT_PROVIDER_*`; the SDK
19
+ // takes the same settings as a typed object on the session. The rest of the
20
+ // environment - a service account's key file, the ledger - still goes to the
21
+ // runtime, since the key command and the agent's own `zen` calls read it there.
22
+ // ---------------------------------------------------------------------------
23
+ const PROVIDER_ENV = /^COPILOT_(PROVIDER_|MODEL$)/;
24
+ /**
25
+ * `token`, when given, replaces the key command: the SDK calls back into this
26
+ * process before each request instead of the runtime starting `zen key token`.
27
+ */
28
+ export function providerConfig(env, token) {
29
+ const type = env.COPILOT_PROVIDER_TYPE;
30
+ const api = env.COPILOT_PROVIDER_WIRE_API;
31
+ return {
32
+ type: type === 'anthropic' ? 'anthropic' : 'openai',
33
+ baseUrl: env.COPILOT_PROVIDER_BASE_URL ?? '',
34
+ ...(env.COPILOT_PROVIDER_API_KEY ? { apiKey: env.COPILOT_PROVIDER_API_KEY } : {}),
35
+ ...(token
36
+ ? { bearerTokenProvider: token }
37
+ : env.COPILOT_PROVIDER_API_KEY_COMMAND
38
+ ? { apiKeyCommand: env.COPILOT_PROVIDER_API_KEY_COMMAND }
39
+ : {}),
40
+ ...(api === 'responses' || api === 'completions' ? { wireApi: api } : {}),
41
+ ...(env.COPILOT_PROVIDER_MODEL_ID ? { modelId: env.COPILOT_PROVIDER_MODEL_ID } : {}),
42
+ ...(env.COPILOT_PROVIDER_WIRE_MODEL ? { wireModel: env.COPILOT_PROVIDER_WIRE_MODEL } : {}),
43
+ };
44
+ }
45
+ /**
46
+ * A service account's access token, minted in this process. The key command
47
+ * starts a `zen` and asks Google for a new token before every model call, so
48
+ * one network blip in a long session failed the turn. Here the library keeps
49
+ * the token until shortly before it expires, and a failed exchange is tried
50
+ * again before the call is given up on.
51
+ */
52
+ export function googleToken(keyFile, opts = {}) {
53
+ const attempts = opts.attempts ?? 4;
54
+ const delayMs = opts.delayMs ?? 1_000;
55
+ let auth;
56
+ return async () => {
57
+ auth ??= import('google-auth-library').then(({ GoogleAuth }) => new GoogleAuth({
58
+ keyFile,
59
+ scopes: ['https://www.googleapis.com/auth/cloud-platform'],
60
+ }));
61
+ let last;
62
+ for (let i = 0; i < attempts; i++) {
63
+ try {
64
+ const token = await (await auth).getAccessToken();
65
+ if (token) {
66
+ return token;
67
+ }
68
+ last = new Error(`${keyFile} minted no token`);
69
+ }
70
+ catch (err) {
71
+ last = err;
72
+ }
73
+ if (i + 1 < attempts) {
74
+ await sleep(delayMs * 2 ** i);
75
+ }
76
+ }
77
+ throw last;
78
+ };
79
+ }
80
+ /** Everything else in the wiring's environment: what the provider object does not carry. */
81
+ export function runtimeEnv(env) {
82
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !PROVIDER_ENV.test(name)));
83
+ }
84
+ /** One model call, in the shape the ledger and the tally already take from the span file. */
85
+ export function toCall(event, session) {
86
+ if (event.type !== 'assistant.usage') {
87
+ return undefined;
88
+ }
89
+ const d = event.data;
90
+ const reasoning = d.reasoningTokens ?? 0;
91
+ const durationMs = Math.max(0, Math.round(d.duration ?? 0));
92
+ const ended = Date.parse(event.timestamp);
93
+ return {
94
+ model: d.model,
95
+ usage: {
96
+ inputTokens: d.inputTokens ?? 0,
97
+ cachedInputTokens: d.cacheReadTokens ?? 0,
98
+ // Copilot counts reasoning beside the output; zen counts it inside.
99
+ outputTokens: (d.outputTokens ?? 0) + reasoning,
100
+ reasoningTokens: reasoning,
101
+ },
102
+ ...(d.cacheWriteTokens ? { cacheWriteTokens: d.cacheWriteTokens } : {}),
103
+ startedAt: new Date((Number.isFinite(ended) ? ended : Date.now()) - durationMs).toISOString(),
104
+ durationMs,
105
+ session,
106
+ };
107
+ }
108
+ function subject(args) {
109
+ const a = (args && typeof args === 'object' ? args : {});
110
+ const what = a.command ?? a.description ?? a.path ?? a.url ?? a.pattern ?? a.skill ?? '';
111
+ return String(what).replace(/\s+/g, ' ').trim();
112
+ }
113
+ /** The SDK's event as the screen's, or nothing. A sub-agent's own steps stay in the log. */
114
+ export function narrate(event) {
115
+ if ('agentId' in event && event.agentId) {
116
+ return undefined;
117
+ }
118
+ switch (event.type) {
119
+ case 'assistant.message_delta':
120
+ return { type: 'delta', id: event.data.messageId, text: event.data.deltaContent };
121
+ case 'assistant.message':
122
+ if (event.data.parentToolCallId) {
123
+ return undefined;
124
+ }
125
+ return {
126
+ type: 'message',
127
+ id: event.data.messageId,
128
+ text: event.data.content,
129
+ tools: event.data.toolRequests?.length ?? 0,
130
+ };
131
+ case 'tool.execution_start':
132
+ if (event.data.parentToolCallId) {
133
+ return undefined;
134
+ }
135
+ return {
136
+ type: 'tool',
137
+ id: event.data.toolCallId,
138
+ name: event.data.toolTitle ?? event.data.toolName,
139
+ subject: subject(event.data.arguments),
140
+ };
141
+ case 'tool.execution_complete':
142
+ if (event.data.parentToolCallId) {
143
+ return undefined;
144
+ }
145
+ return {
146
+ type: 'tool-done',
147
+ id: event.data.toolCallId,
148
+ ok: event.data.success,
149
+ error: event.data.error?.message,
150
+ };
151
+ case 'session.error':
152
+ return { type: 'error', text: event.data.message };
153
+ case 'session.warning':
154
+ return { type: 'warn', text: event.data.message };
155
+ default:
156
+ return undefined;
157
+ }
158
+ }
159
+ /** The reasoning levels `--effort` takes. */
160
+ export const EFFORTS = [
161
+ 'none',
162
+ 'minimal',
163
+ 'low',
164
+ 'medium',
165
+ 'high',
166
+ 'xhigh',
167
+ 'max',
168
+ ];
169
+ export async function openChat(opts) {
170
+ const client = await (opts.connect ?? connectSdk)({
171
+ env: { ...process.env, ...opts.env },
172
+ workingDirectory: opts.dir,
173
+ // Your keys, never a Copilot subscription: no GitHub sign-in is looked for.
174
+ useLoggedInUser: false,
175
+ logLevel: 'error',
176
+ });
177
+ // Each turn's events, kept so `transient` can read a failure the way it reads a run's.
178
+ let turn = [];
179
+ let settle;
180
+ let failTimer;
181
+ const onEvent = (event) => {
182
+ opts.onRaw?.(event);
183
+ turn.push(event);
184
+ const said = narrate(event);
185
+ if (said) {
186
+ opts.onEvent(said);
187
+ }
188
+ const call = toCall(event, opts.sessionId);
189
+ if (call) {
190
+ opts.onEvent({ type: 'usage', call });
191
+ }
192
+ if (event.type === 'session.idle') {
193
+ clearTimeout(failTimer);
194
+ settle?.(event.data.aborted === true);
195
+ }
196
+ else if (event.type === 'session.error') {
197
+ // An error is followed by idle; if it is not, the turn still has to end.
198
+ clearTimeout(failTimer);
199
+ failTimer = setTimeout(() => settle?.(false), 5_000);
200
+ failTimer.unref();
201
+ }
202
+ };
203
+ const config = {
204
+ model: opts.model,
205
+ provider: opts.provider,
206
+ streaming: true,
207
+ workingDirectory: opts.dir,
208
+ ...(opts.addDirs?.length ? { additionalDirectories: [...opts.addDirs] } : {}),
209
+ ...(opts.agent ? { agent: opts.agent } : {}),
210
+ ...(opts.effort && EFFORTS.includes(opts.effort)
211
+ ? { reasoningEffort: opts.effort }
212
+ : {}),
213
+ onPermissionRequest: opts.decide,
214
+ onEvent,
215
+ };
216
+ let session;
217
+ try {
218
+ session = opts.resume
219
+ ? await client.resumeSession(opts.sessionId, config)
220
+ : await client.createSession({ ...config, sessionId: opts.sessionId });
221
+ }
222
+ catch (err) {
223
+ await client.stop().catch(() => undefined);
224
+ throw err;
225
+ }
226
+ let waiting;
227
+ let stopped = false;
228
+ const once = async (prompt) => {
229
+ turn = [];
230
+ const done = new Promise((resolve) => (settle = resolve));
231
+ try {
232
+ await session.send({ prompt });
233
+ }
234
+ catch (err) {
235
+ settle = undefined;
236
+ const text = err.message;
237
+ opts.onEvent({ type: 'error', text });
238
+ return {
239
+ aborted: false,
240
+ events: [{ type: 'session.error', data: { message: text } }],
241
+ };
242
+ }
243
+ const aborted = await done;
244
+ settle = undefined;
245
+ return { aborted, events: turn };
246
+ };
247
+ return {
248
+ sessionId: session.sessionId,
249
+ send: async (prompt) => {
250
+ stopped = false;
251
+ let attempt = 0;
252
+ let result = await once(prompt);
253
+ for (;;) {
254
+ if (result.aborted || stopped) {
255
+ return { aborted: true };
256
+ }
257
+ const failed = result.events.findLast((e) => e.type === 'session.error');
258
+ if (!failed) {
259
+ return { aborted: false };
260
+ }
261
+ const outcome = {
262
+ answer: '',
263
+ exitCode: 1,
264
+ sessionId: session.sessionId,
265
+ events: result.events,
266
+ };
267
+ const reason = transient(outcome);
268
+ const message = String(failed.data.message ?? '');
269
+ if (!reason || attempt >= opts.retries) {
270
+ return { aborted: false, failed: reason ?? message };
271
+ }
272
+ const waitMs = (opts.delayMs ?? resumeDelayMs)(attempt);
273
+ attempt += 1;
274
+ opts.onEvent({ type: 'retry', reason, waitMs, attempt, of: opts.retries });
275
+ waiting = new AbortController();
276
+ try {
277
+ await sleep(waitMs, undefined, { signal: waiting.signal });
278
+ }
279
+ catch {
280
+ return { aborted: true };
281
+ }
282
+ finally {
283
+ waiting = undefined;
284
+ }
285
+ result = await once(RESUME_PROMPT);
286
+ }
287
+ },
288
+ abort: async () => {
289
+ stopped = true;
290
+ if (waiting) {
291
+ waiting.abort();
292
+ return;
293
+ }
294
+ await session.abort().catch(() => undefined);
295
+ },
296
+ close: async () => {
297
+ clearTimeout(failTimer);
298
+ await session.disconnect().catch(() => undefined);
299
+ await client.stop().catch(() => undefined);
300
+ },
301
+ };
302
+ }
303
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1,18 @@
1
+ import type { ChatEvent } from './session.ts';
2
+ export type RowKind = 'you' | 'say' | 'answer' | 'tool' | 'fail' | 'warn' | 'error' | 'note';
3
+ export interface Row {
4
+ key: number;
5
+ kind: RowKind;
6
+ text: string;
7
+ }
8
+ export interface View {
9
+ rows: readonly Row[];
10
+ /** the message being written, as it arrives */
11
+ live: string;
12
+ liveId?: string;
13
+ next: number;
14
+ }
15
+ export declare const EMPTY: View;
16
+ export declare function said(view: View, kind: RowKind, text: string): View;
17
+ export declare function fold(view: View, event: ChatEvent): View;
18
+ //# sourceMappingURL=transcript.d.ts.map
@@ -0,0 +1,39 @@
1
+ // packages/meta/src/chat/transcript.ts
2
+ //
3
+ // What the `zen meta chat` screen shows, as data: the finished rows (scrolled away by Ink's `Static`) and the
4
+ // message still streaming in. Pure, so the screen's logic is tested without drawing it.
5
+ // Main: `fold(view, event)`, which applies one `ChatEvent`; also `said` (a row for something the screen itself
6
+ // says), `EMPTY` and the `Row`/`View` types.
7
+ // Used by: `chat/tui.tsx`, which folds every event the session reports and draws the result.
8
+ import { duration } from "../host.js";
9
+ export const EMPTY = { rows: [], live: '', next: 0 };
10
+ export function said(view, kind, text) {
11
+ return { ...view, rows: [...view.rows, { key: view.next, kind, text }], next: view.next + 1 };
12
+ }
13
+ export function fold(view, event) {
14
+ switch (event.type) {
15
+ case 'delta':
16
+ return event.id === view.liveId
17
+ ? { ...view, live: view.live + event.text }
18
+ : { ...view, live: event.text, liveId: event.id };
19
+ case 'message': {
20
+ // The whole message replaces its pieces, so a missed delta costs nothing.
21
+ const text = event.text.trim();
22
+ const cleared = { ...view, live: '', liveId: undefined };
23
+ return text ? said(cleared, event.tools > 0 ? 'say' : 'answer', text) : cleared;
24
+ }
25
+ case 'tool':
26
+ return said(view, 'tool', [event.name, event.subject].filter(Boolean).join(' '));
27
+ case 'tool-done':
28
+ return event.ok ? view : said(view, 'fail', event.error ?? 'failed');
29
+ case 'warn':
30
+ return said(view, 'warn', event.text);
31
+ case 'error':
32
+ return said(view, 'error', event.text);
33
+ case 'retry':
34
+ return said(view, 'warn', `${event.reason}: resuming in ${duration(event.waitMs)} (${event.attempt}/${event.of}) - Esc stops`);
35
+ case 'usage':
36
+ return view;
37
+ }
38
+ }
39
+ //# sourceMappingURL=transcript.js.map
@@ -0,0 +1,37 @@
1
+ import React from 'react';
2
+ import { type History, type Theme } from '../host.ts';
3
+ import type { Answer, Described } from './permissions.ts';
4
+ import type { Chat, ChatEvent } from './session.ts';
5
+ /** How the session, opened before the screen, reaches it: set on mount, cleared on unmount. */
6
+ export interface Bridge {
7
+ onEvent?: (event: ChatEvent) => void;
8
+ onAsk?: (request: Described) => Promise<Answer>;
9
+ }
10
+ export interface Screen {
11
+ chat: Chat;
12
+ bridge: Bridge;
13
+ history: History;
14
+ theme: Theme;
15
+ title: {
16
+ owner: string;
17
+ model: string;
18
+ project: string;
19
+ resumed: boolean;
20
+ };
21
+ /** said after the clock while a turn runs: the calls and tokens so far */
22
+ status: () => string;
23
+ prompts: {
24
+ list(): Promise<string[]>;
25
+ load(name: string): Promise<{
26
+ body: string;
27
+ description?: string;
28
+ }>;
29
+ };
30
+ /** asked as soon as the screen is up */
31
+ first?: string;
32
+ /** each prompt as it is sent, for the log */
33
+ onSend?: (shown: string, prompt: string) => void;
34
+ }
35
+ export declare function chatScreen(screen: Screen): Promise<void>;
36
+ export declare function ChatApp(props: Screen): React.ReactElement;
37
+ //# sourceMappingURL=tui.d.ts.map
@@ -0,0 +1,237 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // packages/meta/src/chat/tui.tsx
3
+ //
4
+ // The `zen meta chat` screen: an Ink transcript of the conversation, the answer streaming in as it is written,
5
+ // a status row while a turn runs, the prompt (with history and slash commands), and the tool-permission question.
6
+ // Main: `chatScreen(screen)`, which draws until the person quits; `ChatApp` is the component.
7
+ // Used by: `chat/run.ts`, which loads it with a dynamic import once the session is open.
8
+ import { TextInput } from '@inkjs/ui';
9
+ import { Box, render, Static, Text, useApp, useInput, useStdout } from 'ink';
10
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
11
+ import { duration, formatMarkdown } from "../host.js";
12
+ import { FRAME_MS } from "../sink.js";
13
+ import { EMPTY, fold, said } from "./transcript.js";
14
+ export async function chatScreen(screen) {
15
+ const app = render(_jsx(ChatApp, { ...screen }), { exitOnCtrlC: false });
16
+ await app.waitUntilExit();
17
+ }
18
+ const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
19
+ const HEADER = { key: -1, kind: 'header' };
20
+ const HELP = [
21
+ '/help this list',
22
+ '/prompts the commands this project offers',
23
+ '/<name> [words] run one of them: .github/skills/<name>/SKILL.md',
24
+ '/exit leave (Ctrl-D does too)',
25
+ 'Esc stops a turn. ↑ and ↓ walk what you asked before.',
26
+ ].join('\n');
27
+ export function ChatApp(props) {
28
+ const { chat, bridge, history, theme, title } = props;
29
+ const { exit } = useApp();
30
+ const { stdout } = useStdout();
31
+ const columns = Math.max(40, stdout.columns ?? 80);
32
+ const [view, setView] = useState(EMPTY);
33
+ const [busy, setBusy] = useState(false);
34
+ const [ask, setAsk] = useState();
35
+ const started = useRef(0);
36
+ const armed = useRef(0);
37
+ const say = useCallback((kind, text) => {
38
+ setView((v) => said(v, kind, text));
39
+ }, []);
40
+ // The prompt, as `zen chat` has it: `TextInput` is uncontrolled, so a
41
+ // recalled line is a new starting value under a new key.
42
+ const [draft, setDraft] = useState('');
43
+ const [generation, setGeneration] = useState(0);
44
+ const at = useRef(history.entries.length);
45
+ const typed = useRef('');
46
+ const pending = useRef('');
47
+ const remember = useCallback((value) => {
48
+ typed.current = value;
49
+ }, []);
50
+ const reset = useCallback(() => {
51
+ at.current = history.entries.length;
52
+ pending.current = '';
53
+ typed.current = '';
54
+ setDraft('');
55
+ setGeneration((g) => g + 1);
56
+ }, [history]);
57
+ const recall = useCallback((delta) => {
58
+ const end = history.entries.length;
59
+ if (end === 0 || (at.current === end && delta > 0)) {
60
+ return;
61
+ }
62
+ if (at.current === end) {
63
+ pending.current = typed.current;
64
+ }
65
+ const next = Math.min(end, Math.max(0, at.current + delta));
66
+ if (next === at.current) {
67
+ return;
68
+ }
69
+ at.current = next;
70
+ const value = next === end ? pending.current : (history.entries[next] ?? '');
71
+ typed.current = value;
72
+ setDraft(value);
73
+ setGeneration((g) => g + 1);
74
+ }, [history]);
75
+ const send = useCallback(async (shown, prompt) => {
76
+ say('you', shown);
77
+ props.onSend?.(shown, prompt);
78
+ started.current = Date.now();
79
+ setBusy(true);
80
+ try {
81
+ const result = await chat.send(prompt);
82
+ if (result.failed) {
83
+ say('error', `the turn failed: ${result.failed}`);
84
+ }
85
+ else if (result.aborted) {
86
+ say('note', 'stopped');
87
+ }
88
+ }
89
+ catch (err) {
90
+ say('error', err.message);
91
+ }
92
+ finally {
93
+ setBusy(false);
94
+ }
95
+ }, [chat, props, say]);
96
+ const submit = useCallback(async (raw) => {
97
+ const text = raw.trim();
98
+ reset();
99
+ if (!text) {
100
+ return;
101
+ }
102
+ history.add(text);
103
+ if (!text.startsWith('/')) {
104
+ return await send(text, text);
105
+ }
106
+ const [name = '', ...words] = text.slice(1).split(/\s+/);
107
+ if (name === 'exit' || name === 'quit') {
108
+ exit();
109
+ return;
110
+ }
111
+ if (name === 'help' || name === '') {
112
+ say('note', HELP);
113
+ return;
114
+ }
115
+ if (name === 'prompts') {
116
+ const names = await props.prompts.list();
117
+ say('note', names.length ? names.map((n) => `/${n}`).join(' ') : 'no commands here');
118
+ return;
119
+ }
120
+ let found;
121
+ try {
122
+ found = await props.prompts.load(name);
123
+ }
124
+ catch {
125
+ say('error', `no command /${name} - /prompts lists them`);
126
+ return;
127
+ }
128
+ await send(text, words.length ? `${found.body}\n\n${words.join(' ')}` : found.body);
129
+ }, [exit, history, props.prompts, reset, say, send]);
130
+ useEffect(() => {
131
+ bridge.onEvent = (event) => setView((v) => fold(v, event));
132
+ bridge.onAsk = (request) => new Promise((resolve) => {
133
+ setAsk({
134
+ request,
135
+ answer: (a) => {
136
+ setAsk(undefined);
137
+ resolve(a);
138
+ },
139
+ });
140
+ });
141
+ if (props.first) {
142
+ void submit(props.first);
143
+ }
144
+ return () => {
145
+ bridge.onEvent = undefined;
146
+ bridge.onAsk = undefined;
147
+ };
148
+ // Once, on mount: the first question is asked once.
149
+ }, []);
150
+ // The spinner and the clock move on their own, but only while a turn runs.
151
+ const [frame, setFrame] = useState(0);
152
+ useEffect(() => {
153
+ if (!busy) {
154
+ return;
155
+ }
156
+ const timer = setInterval(() => setFrame((n) => n + 1), FRAME_MS);
157
+ return () => clearInterval(timer);
158
+ }, [busy]);
159
+ useInput((input, keys) => {
160
+ if (ask) {
161
+ const choice = input.toLowerCase();
162
+ if (choice === 'y') {
163
+ ask.answer('yes');
164
+ }
165
+ else if (choice === 'a') {
166
+ ask.answer('always');
167
+ }
168
+ else if (choice === 'n' || keys.escape) {
169
+ ask.answer('no');
170
+ }
171
+ return;
172
+ }
173
+ if (keys.ctrl && input === 'c') {
174
+ if (busy) {
175
+ void chat.abort();
176
+ return;
177
+ }
178
+ // Twice, as in copilot: once is too easy to press on the way to a copy.
179
+ if (Date.now() - armed.current < 2_000) {
180
+ exit();
181
+ }
182
+ else {
183
+ armed.current = Date.now();
184
+ say('note', 'Ctrl-C again to leave');
185
+ }
186
+ return;
187
+ }
188
+ if (busy) {
189
+ if (keys.escape) {
190
+ void chat.abort();
191
+ }
192
+ return;
193
+ }
194
+ if (keys.ctrl && input === 'd') {
195
+ exit();
196
+ }
197
+ else if (keys.upArrow) {
198
+ recall(-1);
199
+ }
200
+ else if (keys.downArrow) {
201
+ recall(1);
202
+ }
203
+ });
204
+ const room = Math.max(4, (stdout.rows ?? 24) - 8);
205
+ const live = view.live ? formatMarkdown(view.live, columns - 2).slice(-room) : [];
206
+ const extra = props.status();
207
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: [HEADER, ...view.rows], children: (item) => item.kind === 'header' ? (_jsx(Header, { theme: theme, title: title }, item.key)) : (_jsx(RowView, { row: item, theme: theme, columns: columns }, item.key)) }), live.length > 0 ? (_jsx(Box, { flexDirection: "column", marginTop: 1, children: live.map((line, i) => (_jsx(Text, { children: line }, i))) })) : null, ask ? _jsx(Ask, { request: ask.request, theme: theme }) : null, busy ? (_jsxs(Box, { marginTop: 1, children: [_jsxs(Text, { color: theme.accent, children: [SPIN[frame % SPIN.length], " "] }), _jsxs(Text, { color: theme.chrome.color, children: [`working ${duration(Date.now() - started.current)}`, extra ? ` · ${extra}` : '', ask ? '' : ' · Esc stops'] })] })) : (_jsxs(Box, { marginTop: 1, children: [_jsx(Text, { color: theme.accent, children: "\u203A " }), _jsx(TextInput, { defaultValue: draft, placeholder: "Ask the meta agent\u2026 (/help, \u2191 for history, Ctrl-D leaves)", onChange: remember, onSubmit: (value) => void submit(value) }, generation)] }))] }));
208
+ }
209
+ /** The banner and the model line are already above it, printed before the screen opened. */
210
+ function Header({ theme, title }) {
211
+ return (_jsxs(Text, { color: theme.chrome.color, children: [title.resumed ? 'resumed · ' : '', "/help for commands \u00B7 Esc stops a turn \u00B7 Ctrl-D leaves"] }));
212
+ }
213
+ function RowView({ row, theme, columns, }) {
214
+ const quiet = theme.chrome.color;
215
+ switch (row.kind) {
216
+ case 'you':
217
+ return (_jsxs(Box, { marginTop: 1, children: [_jsxs(Text, { color: theme.accent, bold: true, children: ["\u203A", ' '] }), _jsx(Text, { bold: true, children: row.text })] }));
218
+ case 'answer':
219
+ return (_jsx(Box, { flexDirection: "column", marginTop: 1, children: formatMarkdown(row.text, columns - 2).map((line, i) => (_jsx(Text, { children: line }, i))) }));
220
+ case 'say':
221
+ return (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: quiet, children: row.text.replace(/\s+/g, ' ') }) }));
222
+ case 'tool':
223
+ return (_jsxs(Text, { color: quiet, wrap: "truncate-end", children: [' ⏺ ', row.text] }));
224
+ case 'fail':
225
+ return (_jsxs(Text, { color: "red", wrap: "truncate-end", children: [' ✗ ', row.text] }));
226
+ case 'warn':
227
+ return _jsxs(Text, { color: theme.warn, children: ["! ", row.text] });
228
+ case 'error':
229
+ return _jsxs(Text, { color: "red", children: ["\u2717 ", row.text] });
230
+ case 'note':
231
+ return _jsx(Text, { color: quiet, children: row.text });
232
+ }
233
+ }
234
+ function Ask({ request, theme }) {
235
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: theme.warn, paddingX: 1, marginTop: 1, children: [_jsxs(Text, { children: ['Allow ', _jsx(Text, { bold: true, children: request.kind }), request.subject ? `: ${request.subject}` : '?'] }), request.intention ? _jsx(Text, { color: theme.chrome.color, children: request.intention }) : null, _jsx(Text, { color: theme.chrome.color, children: `y yes · n no · a always allow ${request.kind} in this chat` })] }));
236
+ }
237
+ //# sourceMappingURL=tui.js.map