@zenera/meta 1.3.0 → 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,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
15
  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";
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 } 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
  };
@@ -475,7 +483,7 @@ export async function completeMeta(args, cur, cwd) {
475
483
  return words.length === 1 && (await findProject(words[0])) ? matching(verbs, cur) : [];
476
484
  }
477
485
  const rest = words.slice(at + 1);
478
- if (verb === 'prompts' || verb === 'resume') {
486
+ if (verb === 'prompts' || verb === 'resume' || verb === 'chat') {
479
487
  return flagged || named || rest.length > 0 ? [] : matching(await projectNames(), cur);
480
488
  }
481
489
  if (verb !== 'run' || rest.some((w) => w.startsWith('/'))) {
@@ -515,6 +523,98 @@ async function prompts(ctx, values, args) {
515
523
  note(dim(`run one: zen meta run /${found[0].name}`));
516
524
  }
517
525
  // ---------------------------------------------------------------------------
526
+ // zen meta chat [project] [question]
527
+ //
528
+ // `run` is one question and one answer, for a terminal nobody is watching or a
529
+ // script. A conversation is the other half: the same agent on the same keys,
530
+ // asked again with what it said still in hand. It goes through the Copilot SDK
531
+ // rather than copilot's `-p`, since a turn has to stream in and a tool call can
532
+ // stop to ask - and both of those need someone at the terminal.
533
+ // ---------------------------------------------------------------------------
534
+ const CHAT_PAGE = {
535
+ usage: 'zen meta chat [project] [question] [options]',
536
+ summary: 'Talk to the meta agent: a conversation over this project, on your own keys.',
537
+ details: [
538
+ 'Arguments:',
539
+ ' [project] Name of a project. Default: the one you are in.',
540
+ ' [question] Asked as soon as the chat opens. Or --prompt.',
541
+ '',
542
+ 'Options:',
543
+ ' --project <name|dir> Which project to work in. The agent is rooted there.',
544
+ ' --model <ref> Model for this chat, e.g. vertex/gemini-3.8-flash.',
545
+ ' --provider <name> Force the key to use. Default: the model ref says.',
546
+ ' --agent <name> A .github/agents/<name>.agent.md.',
547
+ ` --effort <level> ${EFFORTS.join(', ')}.`,
548
+ ' --allow-tool <list> Only these: read, shell(git:*), write(README.md).',
549
+ ' --ask Ask before each tool: y, n, or a for always. Default: it does not.',
550
+ ' --add-dir <dir> Another directory it may touch. Repeatable.',
551
+ ' --resume <id> Carry on a session - a chat or a run. --continue takes the last.',
552
+ ' --session-id <uuid> Start a new session under this id. Default: a random one.',
553
+ ` --retries <n> Resume a turn after a rate limit or outage. Default ${DEFAULT_RESUMES}.`,
554
+ ' --events <file> Append what the agent does to this file as it does it.',
555
+ ' --no-refresh Leave the editor files as they are.',
556
+ '',
557
+ 'In the chat:',
558
+ ' /help the commands',
559
+ ' /prompts the commands this project offers',
560
+ ' /<name> [words] run one: .github/skills/<name>/SKILL.md',
561
+ ' /exit leave; Ctrl-D, or Ctrl-C twice, does too',
562
+ ' Esc stop the turn in flight',
563
+ ' ↑ ↓ what you asked before, kept per project',
564
+ '',
565
+ 'The model, the key and the editor files are chosen and refreshed as for',
566
+ '`zen meta run`, and every call is counted and logged the same way. The',
567
+ "session is copilot's, so `zen meta resume` and `--resume` take a chat as",
568
+ 'readily as a run. It needs a terminal: for one answer in a script, or as',
569
+ 'JSON, use `zen meta run`.',
570
+ '',
571
+ 'Examples:',
572
+ ' zen meta chat',
573
+ ' zen meta chat acme "what does this project do?"',
574
+ ' zen meta chat --continue',
575
+ ' zen meta chat --ask --allow-tool read',
576
+ ],
577
+ };
578
+ async function chat(ctx, values, args) {
579
+ if (ctx.json) {
580
+ throw usageError('zen meta chat is a conversation, with no one answer to print as JSON', 'for that: zen meta run "<question>" --json');
581
+ }
582
+ for (const flag of ['dry-run', 'share', 'prompt-file']) {
583
+ if (values[flag]) {
584
+ throw usageError(`zen meta chat takes no --${flag}`, `zen meta run takes it`);
585
+ }
586
+ }
587
+ if (values.effort && !EFFORTS.includes(values.effort)) {
588
+ throw usageError(`--effort takes ${EFFORTS.join(', ')}`, `got "${values.effort}"`);
589
+ }
590
+ const retries = count(values.retries, '--retries') ?? DEFAULT_RESUMES;
591
+ if (!isInteractive() || !process.stdout.isTTY) {
592
+ throw usageError('zen meta chat needs a terminal to talk in', 'for one answer: zen meta run "<question>"');
593
+ }
594
+ const { project, rest } = await where(ctx, values.project, args);
595
+ if (!values['no-refresh']) {
596
+ refresh(project);
597
+ }
598
+ let resume = values.resume;
599
+ if (values.continue && !resume) {
600
+ resume = lastSession(project.dir);
601
+ if (!resume) {
602
+ note(dim(`no meta session recorded in ${project.name} - starting a new one`));
603
+ }
604
+ }
605
+ if (resume) {
606
+ note(dim(`resuming session ${resume}`));
607
+ }
608
+ const { runChat } = await import("./chat/run.js");
609
+ await runChat({
610
+ values: { ...values, resume, continue: false },
611
+ project,
612
+ cwd: ctx.cwd,
613
+ first: (values.prompt ?? rest.join(' ')).trim() || undefined,
614
+ retries,
615
+ });
616
+ }
617
+ // ---------------------------------------------------------------------------
518
618
  // zen meta resume [project] [session id] [words...]
519
619
  //
520
620
  // A long run stops for reasons nobody chose - a refused request, a closed
@@ -540,62 +640,10 @@ async function resumeRun(ctx, values, args) {
540
640
  // The run itself
541
641
  // ---------------------------------------------------------------------------
542
642
  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()));
643
+ const prepared = await prepare(values, project, prompt);
644
+ const { owner, chosen, wiring, binary } = prepared;
645
+ values = prepared.values;
646
+ let session = prepared.session;
599
647
  const args = argv(values, project.dir, prompt, wiring.secret, session);
600
648
  const retries = count(values.retries, '--retries') ?? DEFAULT_RESUMES;
601
649
  if (values['dry-run']) {
@@ -615,21 +663,7 @@ async function go(ctx, values, project, prompt, promptName) {
615
663
  note(dim(`model ${chosen.ref} from ${SOURCE_LABELS[chosen.from]}`));
616
664
  return;
617
665
  }
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}`));
666
+ announce(prepared, project);
633
667
  const log = openLog(project.dir, new Date(), session);
634
668
  note(`log ${log.path}`);
635
669
  const elided = args.map((a, i) => (args[i - 1] === '-p' ? '<prompt>' : a));
@@ -778,43 +812,6 @@ async function go(ctx, values, project, prompt, promptName) {
778
812
  log.close();
779
813
  }
780
814
  }
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
815
  /** The wait before a resume, cut short by Ctrl-C - which still says how to resume. */
819
816
  async function pause(ms, hint) {
820
817
  const stop = new AbortController();
@@ -868,25 +865,6 @@ function argv(values, dir, prompt, secret, fresh) {
868
865
  }
869
866
  return args;
870
867
  }
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
868
  function count(text, flag) {
891
869
  if (text === undefined) {
892
870
  return undefined;
@@ -897,13 +875,6 @@ function count(text, flag) {
897
875
  }
898
876
  return value;
899
877
  }
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
878
  // ---------------------------------------------------------------------------
908
879
  // zen meta model
909
880
  //
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
package/dist/launch.d.ts CHANGED
@@ -21,6 +21,15 @@ export declare function copilotVersion(binary?: Binary): Promise<{
21
21
  version?: string;
22
22
  detail?: string;
23
23
  }>;
24
+ /**
25
+ * The Copilot SDK `zen meta chat` runs on, with the runtime it bundles. Its
26
+ * manifest is not exported, so it is found by walking up from its entry point.
27
+ */
28
+ export declare function sdkVersion(): {
29
+ name: string;
30
+ version?: string;
31
+ detail?: string;
32
+ };
24
33
  interface Event {
25
34
  type: string;
26
35
  data?: Record<string, unknown>;