@zenera/meta 1.3.1 → 1.3.3

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,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
package/dist/command.js CHANGED
@@ -1,23 +1,24 @@
1
1
  // packages/meta/src/command.ts
2
2
  //
3
3
  // `zen meta`: the meta agent's command - a coding agent (GitHub Copilot CLI) run over a zen project on your keys.
4
- // Main: `command: Command`, which routes `run`, `prompts`, `resume`, `model`, `dataset` and `finetune`; the run
5
- // itself is `go()` (choose the model, wire the key, log, launch, resume after transient failures).
6
- // Also `completeMeta` (tab completion) and the `subsystems` hook reporting copilot to `zen version`.
4
+ // Main: `command: Command`, which routes `run`, `chat`, `prompts`, `resume`, `model`, `dataset` and `finetune`; the
5
+ // run itself is `go()` (prepare the model and key, log, launch, resume after transient failures), and `chat()`
6
+ // checks the terminal and hands over to `chat/run.ts`.
7
+ // Also `completeMeta` (tab completion) and the `subsystems` hook reporting copilot and its SDK to `zen version`.
7
8
  // Used by: `@zenera/cli`, which loads it by name as `@zenera/meta/command` (`EXTERNAL.meta` in its commands/index.ts).
8
9
  import * as Projects from '@zenera/engine';
9
- import { assertOwner, ensureHome, isProvider, KeyStore, loadProjectEnv, PROVIDERS, } from '@zenera/engine';
10
- import { gatewayOf, readProjectConfig } from '@zenera/neo';
11
- import { spawn } from 'node:child_process';
12
- import { randomUUID } from 'node:crypto';
13
- import { existsSync, readFileSync } from 'node:fs';
10
+ import { ensureHome, isProvider, KeyStore, loadProjectEnv, PROVIDERS } from '@zenera/engine';
11
+ import { gatewayOf } from '@zenera/neo';
12
+ import { readFileSync } from 'node:fs';
14
13
  import { join, resolve } from 'node:path';
15
14
  import { setTimeout as sleep } from 'node:timers/promises';
16
- import { appendUsage, bold, browseModels, choose, CliError, copilotEventLog, credentialError, cyan, dim, duration, editorFiles, EXIT, green, isInteractive, json, LEDGER_ENV, ledgerPath, matching, META_PROMPT_ENV, META_SESSION_ENV, note, pad, parse, probeChat, probeModel, progress, projectNames, readStdin, resolveProject, splitRef, table, TEMPLATES, usageError, warn, wrap, write, writeAll, } from "./host.js";
17
- import { answerBox, chooseModel, copilotVersion, DATASET_DETAILS, DATASET_SUMMARY, DATASET_USAGE, datasetProjectFlag, DEFAULT_RESUMES, fallbackRef, FINETUNE_DETAILS, FINETUNE_SUMMARY, FINETUNE_USAGE, finetuneProjectFlag, lastSession, launch, listPrompts, loadPrompt, locate, masked, metaCompatible, misspelledProvider, MODEL_ENV, openLog, ORDER, SKILL_DIR, providersWarning, readMeta, recordSession, RESUME_PROMPT, resumeDelayMs, runDataset, runFinetune, sameModel, sessionModel, sessionTotals, SOURCE_LABELS, startVertexRelay, tailSpans, Tally, terminalSink, transient, wire, wireGateway, writeMeta, } from "./index.js";
15
+ import { appendUsage, bold, browseModels, choose, CliError, copilotEventLog, credentialError, cyan, dim, duration, EXIT, green, isInteractive, json, LEDGER_ENV, ledgerPath, matching, META_PROMPT_ENV, META_SESSION_ENV, note, pad, parse, probeChat, probeModel, progress, projectNames, readStdin, resolveProject, splitRef, table, TEMPLATES, usageError, warn, wrap, write, writeAll, } from "./host.js";
16
+ import { answerBox, chooseModel, copilotVersion, DATASET_DETAILS, DATASET_SUMMARY, DATASET_USAGE, datasetProjectFlag, DEFAULT_RESUMES, fallbackRef, FINETUNE_DETAILS, FINETUNE_SUMMARY, FINETUNE_USAGE, finetuneProjectFlag, lastSession, launch, listPrompts, loadPrompt, masked, metaCompatible, misspelledProvider, MODEL_ENV, openLog, ORDER, SKILL_DIR, readMeta, recordSession, RESUME_PROMPT, resumeDelayMs, runDataset, runFinetune, sdkVersion, sessionTotals, SOURCE_LABELS, startVertexRelay, tailSpans, Tally, terminalSink, transient, writeMeta, } from "./index.js";
17
+ import { EFFORTS } from "./chat/session.js";
18
+ import { announce, prepare, projectModel, refreshEditor } from "./prepare.js";
19
+ import { usageReporter } from "./reporter.js";
18
20
  const USAGE = 'zen meta run [project] [prompt] [options]';
19
- const VERBS = new Set(['model', 'run', 'prompts', 'resume', 'dataset', 'finetune']);
20
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
+ const VERBS = new Set(['model', 'run', 'chat', 'prompts', 'resume', 'dataset', 'finetune']);
21
22
  /** A copilot session id, or the 7+ hex prefix of one it also accepts. */
22
23
  const SESSION_ID = /^[0-9a-f]{7,}(?:-[0-9a-f]+)*$/i;
23
24
  /** Verbs that own their flags and their help page. */
@@ -124,14 +125,15 @@ export const command = {
124
125
  'Forms:',
125
126
  ...RUN_FORMS,
126
127
  ' zen meta prompts [project] list its commands',
128
+ ' zen meta chat [project] [question] talk it through, turn by turn',
127
129
  ' zen meta resume [project] [session] carry on a run that stopped',
128
130
  ' zen meta model [ref] show or set the model it uses',
129
131
  ' zen meta dataset <verb> the cases it tunes against',
130
132
  ' zen meta finetune <verb> tune the project on those cases',
131
133
  '',
132
134
  'The project may come before the verb instead: `zen meta acme run`.',
133
- '`zen meta dataset --help`, `zen meta finetune --help` and `zen meta run --help`',
134
- 'have their own pages; the last lists the commands.',
135
+ '`zen meta dataset --help`, `zen meta finetune --help`, `zen meta chat --help`',
136
+ 'and `zen meta run --help` have their own pages; the last lists the commands.',
135
137
  '',
136
138
  ...RUN_ARGUMENTS,
137
139
  '',
@@ -197,10 +199,13 @@ export const command = {
197
199
  if (words[0] === 'run' || words[1] === 'run') {
198
200
  return await runHelp(ctx, words);
199
201
  }
202
+ if (words[0] === 'chat' || words[1] === 'chat') {
203
+ return page(CHAT_PAGE);
204
+ }
200
205
  page({ ...command, details: command.details ?? [] });
201
206
  },
202
207
  complete: (args, cur, cwd) => completeMeta(args, cur, cwd),
203
- subsystems: async () => [await copilotVersion()],
208
+ subsystems: async () => [await copilotVersion(), sdkVersion()],
204
209
  run: async (ctx) => {
205
210
  // These own their flags, so they are routed before the meta agent's are parsed.
206
211
  const sub = subcommand(ctx.args);
@@ -242,6 +247,9 @@ export const command = {
242
247
  if (verb === 'resume') {
243
248
  return await resumeRun(ctx, values, args);
244
249
  }
250
+ if (verb === 'chat') {
251
+ return await chat(ctx, values, args);
252
+ }
245
253
  throw usageError(first === undefined ? 'nothing to run' : 'a prompt goes through `run`', `try: zen meta run ${positionals.map(requote).join(' ') || '"what does this project do?"'}`);
246
254
  },
247
255
  };
@@ -302,25 +310,6 @@ async function where(ctx, flag, positionals) {
302
310
  });
303
311
  return { project, rest: named ? tail : positionals };
304
312
  }
305
- /**
306
- * The editor's files, rewritten before the agent reads them — the same refresh
307
- * `zen open` does, for the same reason. `.github/` is the brief this agent works
308
- * from and the prompts it is offered, and it describes the version of `zen` in
309
- * hand; a project scaffolded by an older one would otherwise be briefed on a
310
- * runtime that has moved. A failure is narrated, not raised: a read-only
311
- * checkout is no reason to refuse to answer a question.
312
- */
313
- function refresh(project) {
314
- try {
315
- const written = editorFiles(project.dir);
316
- if (written.length) {
317
- note(dim(`refreshed ${written.length} editor files in ${project.name}`));
318
- }
319
- }
320
- catch (err) {
321
- warn(`could not refresh the editor files — ${err.message}`);
322
- }
323
- }
324
313
  // ---------------------------------------------------------------------------
325
314
  // zen meta run [project] [/<name>|<question>] [words...]
326
315
  //
@@ -349,7 +338,7 @@ async function stored(ctx, values, args) {
349
338
  }
350
339
  const { project } = await where(ctx, values.project, head);
351
340
  if (!values['no-refresh']) {
352
- refresh(project);
341
+ refreshEditor(project);
353
342
  }
354
343
  if (name) {
355
344
  return await runPrompt(ctx, values, project, name, rest);
@@ -475,7 +464,7 @@ export async function completeMeta(args, cur, cwd) {
475
464
  return words.length === 1 && (await findProject(words[0])) ? matching(verbs, cur) : [];
476
465
  }
477
466
  const rest = words.slice(at + 1);
478
- if (verb === 'prompts' || verb === 'resume') {
467
+ if (verb === 'prompts' || verb === 'resume' || verb === 'chat') {
479
468
  return flagged || named || rest.length > 0 ? [] : matching(await projectNames(), cur);
480
469
  }
481
470
  if (verb !== 'run' || rest.some((w) => w.startsWith('/'))) {
@@ -500,7 +489,7 @@ export async function completeMeta(args, cur, cwd) {
500
489
  // ---------------------------------------------------------------------------
501
490
  async function prompts(ctx, values, args) {
502
491
  const { project } = await where(ctx, values.project, args);
503
- refresh(project);
492
+ refreshEditor(project);
504
493
  const names = await listPrompts(project.dir);
505
494
  const found = await Promise.all(names.map((name) => loadPrompt(project.dir, name)));
506
495
  if (ctx.json) {
@@ -515,6 +504,85 @@ async function prompts(ctx, values, args) {
515
504
  note(dim(`run one: zen meta run /${found[0].name}`));
516
505
  }
517
506
  // ---------------------------------------------------------------------------
507
+ // zen meta chat [project] [question]
508
+ //
509
+ // `run` is one question and one answer, for a terminal nobody is watching or a
510
+ // script. A conversation is the other half: the same agent on the same keys,
511
+ // asked again with what it said still in hand. It goes through the Copilot SDK
512
+ // rather than copilot's `-p`, since a turn has to stream in and a tool call can
513
+ // stop to ask - and both of those need someone at the terminal.
514
+ // ---------------------------------------------------------------------------
515
+ const CHAT_PAGE = {
516
+ usage: 'zen meta chat [project] [question] [options]',
517
+ summary: 'Talk to the meta agent: a conversation over this project, on your own keys.',
518
+ details: [
519
+ 'Arguments:',
520
+ ' [project] Name of a project. Default: the one you are in.',
521
+ ' [question] Asked as soon as the chat opens. Or --prompt.',
522
+ '',
523
+ 'Options:',
524
+ ' --project <name|dir> Which project to work in. The agent is rooted there.',
525
+ ' --model <ref> Model for this chat, e.g. vertex/gemini-3.8-flash.',
526
+ ' --provider <name> Force the key to use. Default: the model ref says.',
527
+ ' --agent <name> A .github/agents/<name>.agent.md.',
528
+ ` --effort <level> ${EFFORTS.join(', ')}.`,
529
+ ' --allow-tool <list> Only these: read, shell(git:*), write(README.md).',
530
+ ' --ask Ask before each tool: y, n, or a for always. Default: it does not.',
531
+ ' --add-dir <dir> Another directory it may touch. Repeatable.',
532
+ ' --resume <id> Carry on a session - a chat or a run. --continue takes the last.',
533
+ ' --session-id <uuid> Start a new session under this id. Default: a random one.',
534
+ ` --retries <n> Resume a turn after a rate limit or outage. Default ${DEFAULT_RESUMES}.`,
535
+ ' --events <file> Append what the agent does to this file as it does it.',
536
+ ' --no-refresh Leave the editor files as they are.',
537
+ '',
538
+ 'In the chat:',
539
+ ' /help the commands',
540
+ ' /prompts the commands this project offers',
541
+ ' /<name> [words] run one: .github/skills/<name>/SKILL.md',
542
+ ' /exit leave; Ctrl-D, or Ctrl-C twice, does too',
543
+ ' Esc stop the turn in flight',
544
+ ' ↑ ↓ what you asked before, kept per project',
545
+ '',
546
+ 'The model, the key and the editor files are chosen and refreshed as for',
547
+ '`zen meta run`, and every call is counted and logged the same way. The',
548
+ "session is copilot's, so `zen meta resume` and `--resume` take a chat as",
549
+ 'readily as a run. It needs a terminal: for one answer in a script, or as',
550
+ 'JSON, use `zen meta run`.',
551
+ '',
552
+ 'Examples:',
553
+ ' zen meta chat',
554
+ ' zen meta chat acme "what does this project do?"',
555
+ ' zen meta chat --continue',
556
+ ' zen meta chat --ask --allow-tool read',
557
+ ],
558
+ };
559
+ async function chat(ctx, values, args) {
560
+ if (ctx.json) {
561
+ throw usageError('zen meta chat is a conversation, with no one answer to print as JSON', 'for that: zen meta run "<question>" --json');
562
+ }
563
+ for (const flag of ['dry-run', 'share', 'prompt-file']) {
564
+ if (values[flag]) {
565
+ throw usageError(`zen meta chat takes no --${flag}`, `zen meta run takes it`);
566
+ }
567
+ }
568
+ if (values.effort && !EFFORTS.includes(values.effort)) {
569
+ throw usageError(`--effort takes ${EFFORTS.join(', ')}`, `got "${values.effort}"`);
570
+ }
571
+ const retries = count(values.retries, '--retries') ?? DEFAULT_RESUMES;
572
+ if (!isInteractive() || !process.stdout.isTTY) {
573
+ throw usageError('zen meta chat needs a terminal to talk in', 'for one answer: zen meta run "<question>"');
574
+ }
575
+ const { project, rest } = await where(ctx, values.project, args);
576
+ const { runChat } = await import("./chat/run.js");
577
+ await runChat({
578
+ values,
579
+ project,
580
+ cwd: ctx.cwd,
581
+ first: (values.prompt ?? rest.join(' ')).trim() || undefined,
582
+ retries,
583
+ });
584
+ }
585
+ // ---------------------------------------------------------------------------
518
586
  // zen meta resume [project] [session id] [words...]
519
587
  //
520
588
  // A long run stops for reasons nobody chose - a refused request, a closed
@@ -531,7 +599,7 @@ async function resumeRun(ctx, values, args) {
531
599
  }
532
600
  note(dim(`resuming session ${session}`));
533
601
  if (!values['no-refresh']) {
534
- refresh(project);
602
+ refreshEditor(project);
535
603
  }
536
604
  const message = withFile(values, (values.prompt ?? words.join(' ')).trim()) || RESUME_PROMPT;
537
605
  await go(ctx, { ...values, resume: session, continue: false }, project, message);
@@ -540,62 +608,10 @@ async function resumeRun(ctx, values, args) {
540
608
  // The run itself
541
609
  // ---------------------------------------------------------------------------
542
610
  async function go(ctx, values, project, prompt, promptName) {
543
- const fresh = values['session-id'];
544
- if (fresh !== undefined) {
545
- if (values.resume || values.continue) {
546
- throw usageError('--session-id starts a new session', 'drop --resume / --continue');
547
- }
548
- if (!UUID.test(fresh)) {
549
- throw usageError(`--session-id must be a UUID, not ${fresh}`, 'try: uuidgen');
550
- }
551
- }
552
- const shell = process.env[MODEL_ENV];
553
- loadProjectEnv(project.dir);
554
- ensureHome();
555
- const store = await KeyStore.open();
556
- store.materialize();
557
- // After materialize: a keyring in bifrost mode is what sets the url.
558
- const gateway = gatewayOf();
559
- const only = values.provider ? asProvider(values.provider) : undefined;
560
- // The fallback can cost a gateway listing, so it is only looked up when nothing else answers.
561
- const chosen = chooseModel({
562
- flag: values.model,
563
- shell,
564
- env: process.env[MODEL_ENV],
565
- stored: (await readMeta()).model,
566
- project: projectModel(project.dir),
567
- }) ?? chooseModel({ fallback: await fallbackRef(store, only, gateway !== undefined) });
568
- if (!chosen) {
569
- if (only) {
570
- throw credentialError(`no ${only} key`, `add one: zen key add ${only}`);
571
- }
572
- throw credentialError('no model for the meta agent', store.entries.length === 0
573
- ? 'add a key: zen key add openai'
574
- : 'set one: zen meta model <provider>/<id>');
575
- }
576
- const { provider, id } = splitRef(chosen.ref);
577
- const owner = only ?? provider ?? 'openai';
578
- const meant = misspelledProvider(chosen.ref);
579
- if (meant && !only) {
580
- warn(`${chosen.ref} names no provider — did you mean ${meant}/${id}?`);
581
- }
582
- const entry = gateway ? undefined : store.active(owner);
583
- if (!gateway && !entry) {
584
- throw credentialError(`no ${owner} key`, `add one: zen key add ${owner}`);
585
- }
586
- const wiring = gateway ? wireGateway(gateway, owner, id) : wire(store, entry, id);
587
- const binary = locate();
588
- // Copilot cannot carry a session to another model: the resume fails on the first call.
589
- const ran = values.resume ? sessionModel(values.resume) : undefined;
590
- if (values.resume && ran && !sameModel(ran, wiring.model)) {
591
- if (prompt === RESUME_PROMPT) {
592
- throw usageError(`session ${values.resume} ran on ${ran}, and the meta model is now ${wiring.model} - copilot cannot carry a session to another model`, `switch back for it: zen meta model ${owner}/${ran.replace(/^.*\//, '')} - or ask again, which starts a new session`);
593
- }
594
- warn(`session ${values.resume} ran on ${ran}; the meta model is now ${wiring.model}, so this starts a new session`);
595
- values = { ...values, resume: undefined };
596
- }
597
- // Named up front, so a run killed before copilot reports its id can still be resumed.
598
- let session = values.resume ?? (values.continue ? undefined : (fresh ?? randomUUID()));
611
+ const prepared = await prepare(values, project, prompt);
612
+ const { owner, chosen, wiring, binary } = prepared;
613
+ values = prepared.values;
614
+ let session = prepared.session;
599
615
  const args = argv(values, project.dir, prompt, wiring.secret, session);
600
616
  const retries = count(values.retries, '--retries') ?? DEFAULT_RESUMES;
601
617
  if (values['dry-run']) {
@@ -615,21 +631,7 @@ async function go(ctx, values, project, prompt, promptName) {
615
631
  note(dim(`model ${chosen.ref} from ${SOURCE_LABELS[chosen.from]}`));
616
632
  return;
617
633
  }
618
- for (const line of wiring.warnings) {
619
- warn(line);
620
- }
621
- const competing = providersWarning();
622
- if (competing) {
623
- warn(competing);
624
- }
625
- if (chosen.from === 'default') {
626
- const what = gateway
627
- ? 'the best model the gateway serves'
628
- : `the best ${owner} model zen knows of`;
629
- note(dim(`no model set — using ${chosen.ref}, ${what}`));
630
- note(dim('set another: zen meta model <provider>/<id>'));
631
- }
632
- note(cyan(`${owner} · ${wiring.model} · ${project.name}`));
634
+ announce(prepared, project);
633
635
  const log = openLog(project.dir, new Date(), session);
634
636
  note(`log ${log.path}`);
635
637
  const elided = args.map((a, i) => (args[i - 1] === '-p' ? '<prompt>' : a));
@@ -775,46 +777,9 @@ async function go(ctx, values, project, prompt, promptName) {
775
777
  tail.stop();
776
778
  reporter.stop();
777
779
  await relay?.close();
778
- log.close();
780
+ await log.close();
779
781
  }
780
782
  }
781
- /** How often a running meta agent rewrites the fine-tuning's usage report. */
782
- const REPORT_EVERY_MS = 5 * 60_000;
783
- /**
784
- * Rewrites `finetune/USAGE.md` on a timer and once more at the end, when the
785
- * project is being tuned. Detached and silent: the report is a by-product, and
786
- * neither its time nor its failure belongs to the run.
787
- */
788
- function usageReporter(dir) {
789
- const script = join(dir, '.github/skills/zen-finetune/scripts/usage.mjs');
790
- if (!existsSync(join(dir, 'finetune')) || !existsSync(script)) {
791
- return { stop: () => undefined };
792
- }
793
- let running = false;
794
- const refresh = () => {
795
- if (running) {
796
- return;
797
- }
798
- running = true;
799
- const child = spawn(process.execPath, [script, '-q'], {
800
- cwd: dir,
801
- stdio: 'ignore',
802
- detached: true,
803
- });
804
- child.on('exit', () => (running = false));
805
- child.on('error', () => (running = false));
806
- child.unref();
807
- };
808
- const timer = setInterval(refresh, REPORT_EVERY_MS);
809
- timer.unref();
810
- return {
811
- stop: () => {
812
- clearInterval(timer);
813
- running = false;
814
- refresh();
815
- },
816
- };
817
- }
818
783
  /** The wait before a resume, cut short by Ctrl-C - which still says how to resume. */
819
784
  async function pause(ms, hint) {
820
785
  const stop = new AbortController();
@@ -868,25 +833,6 @@ function argv(values, dir, prompt, secret, fresh) {
868
833
  }
869
834
  return args;
870
835
  }
871
- /** The project's own `model:`, with a `models:` alias resolved to what it names. */
872
- function projectModel(dir) {
873
- try {
874
- const { config } = readProjectConfig(dir);
875
- const top = typeof config.model === 'string' ? config.model : undefined;
876
- const alias = top ? config.models?.[top] : undefined;
877
- if (!alias) {
878
- return top;
879
- }
880
- if (typeof alias === 'string') {
881
- return alias;
882
- }
883
- const owner = PROVIDERS.find((p) => p === alias.provider);
884
- return owner ? `${owner}/${alias.model}` : alias.model;
885
- }
886
- catch {
887
- return undefined;
888
- }
889
- }
890
836
  function count(text, flag) {
891
837
  if (text === undefined) {
892
838
  return undefined;
@@ -897,13 +843,6 @@ function count(text, flag) {
897
843
  }
898
844
  return value;
899
845
  }
900
- function asProvider(name) {
901
- const owner = assertOwner(name);
902
- if (!isProvider(owner)) {
903
- throw usageError(`${name} is not a model provider`);
904
- }
905
- return owner;
906
- }
907
846
  // ---------------------------------------------------------------------------
908
847
  // zen meta model
909
848
  //
package/dist/host.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { appendUsage, bold, boxWidth, browseModels, choose, CliError, confirm, copilotEventLog, copyTree, credentialError, cut, cyan, dim, duration, editorFiles, envOf, EXIT, formatInline, formatMarkdown, green, invalidError, invokedAs, isInteractive, json, LEDGER_ENV, ledgerPath, loadCatalogs, matching, META_PROMPT_ENV, META_SESSION_ENV, note, pad, parse, paths, plain, probeChat, probeModel, progress, projectNames, PROVIDER_NAMES, PROVIDERS, rankModels, readJson, readStdin, red, resolveProject, resolveTheme, safe, SHARED_RULES, splitRef, styled, table, TEMPLATES, usageError, validateProject, warn, wrap, write, writeAll, writeJson, yellow, type Candidate, type Command, type Context, type EventLine, type KeyEntry, type KeyStore, type ProjectReport, type Provider, type Theme, } from '@zenera/cli/lib';
1
+ export { appendUsage, bold, boxWidth, browseModels, choose, CliError, confirm, copilotEventLog, copyTree, credentialError, cut, cyan, dim, duration, editorFiles, envOf, EXIT, formatInline, formatMarkdown, green, History, invalidError, invokedAs, isInteractive, json, LEDGER_ENV, ledgerPath, loadCatalogs, matching, META_PROMPT_ENV, META_SESSION_ENV, note, pad, parse, paths, plain, probeChat, probeModel, progress, projectNames, PROVIDER_NAMES, PROVIDERS, rankModels, readJson, readStdin, red, resolveProject, resolveTheme, safe, SHARED_RULES, splitRef, styled, table, TEMPLATES, usageError, validateProject, warn, wrap, write, writeAll, writeJson, yellow, type Candidate, type Command, type Context, type EventLine, type KeyEntry, type KeyStore, type ProjectReport, type Provider, type Theme, } from '@zenera/cli/lib';
2
2
  //# sourceMappingURL=host.d.ts.map
package/dist/host.js CHANGED
@@ -10,5 +10,5 @@
10
10
  // what `@zenera/meta` needs of `@zenera/cli/lib` is one list, read in one place.
11
11
  // `test/meta-boundary.test.ts` holds the line.
12
12
  // ---------------------------------------------------------------------------
13
- export { appendUsage, bold, boxWidth, browseModels, choose, CliError, confirm, copilotEventLog, copyTree, credentialError, cut, cyan, dim, duration, editorFiles, envOf, EXIT, formatInline, formatMarkdown, green, invalidError, invokedAs, isInteractive, json, LEDGER_ENV, ledgerPath, loadCatalogs, matching, META_PROMPT_ENV, META_SESSION_ENV, note, pad, parse, paths, plain, probeChat, probeModel, progress, projectNames, PROVIDER_NAMES, PROVIDERS, rankModels, readJson, readStdin, red, resolveProject, resolveTheme, safe, SHARED_RULES, splitRef, styled, table, TEMPLATES, usageError, validateProject, warn, wrap, write, writeAll, writeJson, yellow, } from '@zenera/cli/lib';
13
+ export { appendUsage, bold, boxWidth, browseModels, choose, CliError, confirm, copilotEventLog, copyTree, credentialError, cut, cyan, dim, duration, editorFiles, envOf, EXIT, formatInline, formatMarkdown, green, History, invalidError, invokedAs, isInteractive, json, LEDGER_ENV, ledgerPath, loadCatalogs, matching, META_PROMPT_ENV, META_SESSION_ENV, note, pad, parse, paths, plain, probeChat, probeModel, progress, projectNames, PROVIDER_NAMES, PROVIDERS, rankModels, readJson, readStdin, red, resolveProject, resolveTheme, safe, SHARED_RULES, splitRef, styled, table, TEMPLATES, usageError, validateProject, warn, wrap, write, writeAll, writeJson, yellow, } from '@zenera/cli/lib';
14
14
  //# sourceMappingURL=host.js.map