@zenera/cli 1.2.9 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/dist/command.d.ts +19 -0
- package/dist/command.js +5 -9
- package/dist/commands/index.d.ts +1 -1
- package/dist/commands/index.js +13 -3
- package/dist/commands/open.js +6 -1
- package/dist/commands/version.d.ts +11 -0
- package/dist/commands/version.js +129 -19
- package/dist/{completion.d.ts → complete.d.ts} +1 -1
- package/dist/{completion.js → complete.js} +14 -4
- package/dist/{meta/editor.js → editor.js} +7 -1
- package/dist/lib.d.ts +18 -1
- package/dist/lib.js +34 -0
- package/dist/main.js +1 -1
- package/dist/scaffold.js +7 -1
- package/package.json +6 -7
- package/templates/editor/.github/skills/zen-cli/references/meta.md +3 -0
- package/templates/editor/.github/skills/zen-cli/references/projects.md +7 -2
- package/dist/commands/meta.d.ts +0 -6
- package/dist/commands/meta.js +0 -1088
- package/dist/meta/finetune/analyze-brief.d.ts +0 -26
- package/dist/meta/finetune/analyze-brief.js +0 -131
- package/dist/meta/finetune/apply-brief.d.ts +0 -23
- package/dist/meta/finetune/apply-brief.js +0 -247
- package/dist/meta/finetune/brief.d.ts +0 -45
- package/dist/meta/finetune/brief.js +0 -158
- package/dist/meta/finetune/children.d.ts +0 -8
- package/dist/meta/finetune/children.js +0 -76
- package/dist/meta/finetune/command.d.ts +0 -30
- package/dist/meta/finetune/command.js +0 -516
- package/dist/meta/finetune/cost.d.ts +0 -46
- package/dist/meta/finetune/cost.js +0 -105
- package/dist/meta/finetune/dataset/anchors.d.ts +0 -41
- package/dist/meta/finetune/dataset/anchors.js +0 -239
- package/dist/meta/finetune/dataset/changes.d.ts +0 -36
- package/dist/meta/finetune/dataset/changes.js +0 -319
- package/dist/meta/finetune/dataset/command.d.ts +0 -17
- package/dist/meta/finetune/dataset/command.js +0 -1011
- package/dist/meta/finetune/dataset/drift.d.ts +0 -33
- package/dist/meta/finetune/dataset/drift.js +0 -71
- package/dist/meta/finetune/dataset/export.d.ts +0 -26
- package/dist/meta/finetune/dataset/export.js +0 -51
- package/dist/meta/finetune/dataset/index.d.ts +0 -2
- package/dist/meta/finetune/dataset/index.js +0 -2
- package/dist/meta/finetune/dataset/sample.d.ts +0 -50
- package/dist/meta/finetune/dataset/sample.js +0 -197
- package/dist/meta/finetune/dataset/schema.d.ts +0 -33
- package/dist/meta/finetune/dataset/schema.js +0 -216
- package/dist/meta/finetune/dataset/store.d.ts +0 -35
- package/dist/meta/finetune/dataset/store.js +0 -177
- package/dist/meta/finetune/dataset/types.d.ts +0 -127
- package/dist/meta/finetune/dataset/types.js +0 -39
- package/dist/meta/finetune/failure.d.ts +0 -15
- package/dist/meta/finetune/failure.js +0 -26
- package/dist/meta/finetune/feedback.d.ts +0 -57
- package/dist/meta/finetune/feedback.js +0 -104
- package/dist/meta/finetune/improvements.d.ts +0 -98
- package/dist/meta/finetune/improvements.js +0 -501
- package/dist/meta/finetune/index.d.ts +0 -2
- package/dist/meta/finetune/index.js +0 -2
- package/dist/meta/finetune/journal.d.ts +0 -35
- package/dist/meta/finetune/journal.js +0 -135
- package/dist/meta/finetune/live.d.ts +0 -84
- package/dist/meta/finetune/live.js +0 -272
- package/dist/meta/finetune/loop.d.ts +0 -3
- package/dist/meta/finetune/loop.js +0 -163
- package/dist/meta/finetune/memories.d.ts +0 -47
- package/dist/meta/finetune/memories.js +0 -171
- package/dist/meta/finetune/recheck.d.ts +0 -58
- package/dist/meta/finetune/recheck.js +0 -311
- package/dist/meta/finetune/report.d.ts +0 -40
- package/dist/meta/finetune/report.js +0 -1397
- package/dist/meta/finetune/retry.d.ts +0 -24
- package/dist/meta/finetune/retry.js +0 -96
- package/dist/meta/finetune/sampler.d.ts +0 -18
- package/dist/meta/finetune/sampler.js +0 -47
- package/dist/meta/finetune/system.d.ts +0 -27
- package/dist/meta/finetune/system.js +0 -132
- package/dist/meta/finetune/train.d.ts +0 -43
- package/dist/meta/finetune/train.js +0 -425
- package/dist/meta/finetune/tui.d.ts +0 -16
- package/dist/meta/finetune/tui.js +0 -316
- package/dist/meta/finetune/tuning.d.ts +0 -193
- package/dist/meta/finetune/tuning.js +0 -308
- package/dist/meta/finetune/usage.d.ts +0 -66
- package/dist/meta/finetune/usage.js +0 -260
- package/dist/meta/finetune/view.d.ts +0 -9
- package/dist/meta/finetune/view.js +0 -27
- package/dist/meta/host.d.ts +0 -16
- package/dist/meta/host.js +0 -22
- package/dist/meta/index.d.ts +0 -11
- package/dist/meta/index.js +0 -11
- package/dist/meta/launch.d.ts +0 -81
- package/dist/meta/launch.js +0 -288
- package/dist/meta/model.d.ts +0 -61
- package/dist/meta/model.js +0 -146
- package/dist/meta/prompts.d.ts +0 -23
- package/dist/meta/prompts.js +0 -84
- package/dist/meta/relay.d.ts +0 -20
- package/dist/meta/relay.js +0 -123
- package/dist/meta/tokens.d.ts +0 -52
- package/dist/meta/tokens.js +0 -226
- package/dist/meta/window.d.ts +0 -61
- package/dist/meta/window.js +0 -198
- package/dist/meta/wire.d.ts +0 -51
- package/dist/meta/wire.js +0 -159
- /package/dist/{meta/editor.d.ts → editor.d.ts} +0 -0
package/dist/commands/meta.js
DELETED
|
@@ -1,1088 +0,0 @@
|
|
|
1
|
-
import * as Projects from '@zenera/engine';
|
|
2
|
-
import { assertOwner, ensureHome, isProvider, KeyStore, loadProjectEnv, PROVIDERS, } from '@zenera/engine';
|
|
3
|
-
import { gatewayOf, readProjectConfig } from '@zenera/neo';
|
|
4
|
-
import { spawn } from 'node:child_process';
|
|
5
|
-
import { randomUUID } from 'node:crypto';
|
|
6
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
7
|
-
import { join, resolve } from 'node:path';
|
|
8
|
-
import { setTimeout as sleep } from 'node:timers/promises';
|
|
9
|
-
import { parse } from "../args.js";
|
|
10
|
-
import { matching, projectNames } from "../candidates.js";
|
|
11
|
-
import { copilotEventLog } from "../eventlog.js";
|
|
12
|
-
import { probeChat, probeModel } from "../liveness.js";
|
|
13
|
-
import { answerBox, chooseModel, DATASET_DETAILS, DATASET_SUMMARY, DATASET_USAGE, datasetProjectFlag, DEFAULT_RESUMES, editorFiles, 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 "../meta/index.js";
|
|
14
|
-
import { splitRef } from "../modelref.js";
|
|
15
|
-
import { duration } from "../narrate.js";
|
|
16
|
-
import { project as resolveProject } from "../resolve.js";
|
|
17
|
-
import { TEMPLATES } from "../scaffold.js";
|
|
18
|
-
import { bold, choose, CliError, credentialError, cyan, dim, EXIT, green, isInteractive, json, note, pad, progress, readStdin, table, usageError, warn, write, writeAll, } from "../term.js";
|
|
19
|
-
import { wrap } from "../tui/wrap.js";
|
|
20
|
-
import { appendUsage, LEDGER_ENV, ledgerPath, META_PROMPT_ENV, META_SESSION_ENV, } from "../usage.js";
|
|
21
|
-
const USAGE = 'zen meta run [project] [prompt] [options]';
|
|
22
|
-
const VERBS = new Set(['model', 'run', 'prompts', 'resume', 'dataset', 'finetune']);
|
|
23
|
-
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
24
|
-
/** A copilot session id, or the 7+ hex prefix of one it also accepts. */
|
|
25
|
-
const SESSION_ID = /^[0-9a-f]{7,}(?:-[0-9a-f]+)*$/i;
|
|
26
|
-
/** Verbs that own their flags and their help page. */
|
|
27
|
-
const SUBCOMMANDS = {
|
|
28
|
-
dataset: {
|
|
29
|
-
run: runDataset,
|
|
30
|
-
projectFlag: datasetProjectFlag,
|
|
31
|
-
page: { usage: DATASET_USAGE, summary: DATASET_SUMMARY, details: DATASET_DETAILS },
|
|
32
|
-
},
|
|
33
|
-
finetune: {
|
|
34
|
-
run: runFinetune,
|
|
35
|
-
projectFlag: finetuneProjectFlag,
|
|
36
|
-
page: { usage: FINETUNE_USAGE, summary: FINETUNE_SUMMARY, details: FINETUNE_DETAILS },
|
|
37
|
-
},
|
|
38
|
-
};
|
|
39
|
-
/** `zen meta dataset ...` or `zen meta acme dataset ...`: which one, and where its own args start. */
|
|
40
|
-
function subcommand(args) {
|
|
41
|
-
for (const name of Object.keys(SUBCOMMANDS)) {
|
|
42
|
-
if (args[0] === name) {
|
|
43
|
-
return { name, at: 0 };
|
|
44
|
-
}
|
|
45
|
-
if (args[1] === name && !args[0]?.startsWith('-')) {
|
|
46
|
-
return { name, at: 1 };
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
return undefined;
|
|
50
|
-
}
|
|
51
|
-
function page(p) {
|
|
52
|
-
write(bold(p.usage));
|
|
53
|
-
write(`\n ${p.summary}`);
|
|
54
|
-
write('');
|
|
55
|
-
for (const line of p.details) {
|
|
56
|
-
write(line ? ` ${line}` : '');
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
/** Kept apart from `run` so that shell completion offers exactly what is parsed. */
|
|
60
|
-
const OPTIONS = {
|
|
61
|
-
project: { type: 'string' },
|
|
62
|
-
provider: { type: 'string' },
|
|
63
|
-
model: { type: 'string' },
|
|
64
|
-
prompt: { type: 'string', short: 'p' },
|
|
65
|
-
'prompt-file': { type: 'string' },
|
|
66
|
-
agent: { type: 'string' },
|
|
67
|
-
effort: { type: 'string' },
|
|
68
|
-
share: { type: 'string' },
|
|
69
|
-
events: { type: 'string' },
|
|
70
|
-
resume: { type: 'string' },
|
|
71
|
-
continue: { type: 'boolean' },
|
|
72
|
-
'session-id': { type: 'string' },
|
|
73
|
-
retries: { type: 'string' },
|
|
74
|
-
'allow-all': { type: 'boolean' },
|
|
75
|
-
'allow-tool': { type: 'string' },
|
|
76
|
-
ask: { type: 'boolean' },
|
|
77
|
-
'add-dir': { type: 'string', multiple: true },
|
|
78
|
-
'dry-run': { type: 'boolean' },
|
|
79
|
-
local: { type: 'boolean' },
|
|
80
|
-
pick: { type: 'boolean' },
|
|
81
|
-
clear: { type: 'boolean' },
|
|
82
|
-
force: { type: 'boolean' },
|
|
83
|
-
'no-refresh': { type: 'boolean' },
|
|
84
|
-
};
|
|
85
|
-
const RUN_FORMS = [
|
|
86
|
-
' zen meta run [project] "<question>" ask it something',
|
|
87
|
-
' zen meta run [project] /<name> [words] run one of its commands',
|
|
88
|
-
' zen meta run [project] pick one of its commands',
|
|
89
|
-
];
|
|
90
|
-
const RUN_ARGUMENTS = [
|
|
91
|
-
'Arguments:',
|
|
92
|
-
' [project] Name of a project. Default: the one you are in.',
|
|
93
|
-
' [prompt] Your question, in quotes. Or --prompt, or piped in when neither',
|
|
94
|
-
' it nor --prompt-file is given.',
|
|
95
|
-
' /<name> A command: the skill in .github/skills/<name>/SKILL.md.',
|
|
96
|
-
' [words] Given to that command, after its text.',
|
|
97
|
-
];
|
|
98
|
-
const RUN_OPTIONS = [
|
|
99
|
-
'Options:',
|
|
100
|
-
' --project <name|dir> Which project to work in. The agent is rooted there.',
|
|
101
|
-
' --model <ref> Model for this run, e.g. vertex/gemini-3.8-flash.',
|
|
102
|
-
' --provider <name> Force the key to use. Default: the model ref says.',
|
|
103
|
-
' -p, --prompt <text> The question, in place of [prompt].',
|
|
104
|
-
' Ignored with /<name>: put words after it instead.',
|
|
105
|
-
' --prompt-file <file> Added after the question - or after /<name> and its',
|
|
106
|
-
' words - past a blank line. Alone, it is the question.',
|
|
107
|
-
' --agent <name> A .github/agents/<name>.agent.md.',
|
|
108
|
-
' --effort <level> none, minimal, low, medium, high, xhigh or max.',
|
|
109
|
-
' --allow-tool <list> Only these: read, shell(git:*), write(README.md).',
|
|
110
|
-
' --ask Have it ask before each tool. Default: it does not.',
|
|
111
|
-
' --add-dir <dir> Another directory it may touch. Repeatable.',
|
|
112
|
-
' --resume <id> Continue a copilot session. --continue takes the last.',
|
|
113
|
-
' --session-id <uuid> Start a new session under this id. Default: a random one.',
|
|
114
|
-
` --retries <n> Resume after a rate limit or outage. Default ${DEFAULT_RESUMES}, 0 = off.`,
|
|
115
|
-
' --share <file> Write the transcript to a markdown file.',
|
|
116
|
-
' --events <file> Append what the agent does to this file as it does it:',
|
|
117
|
-
' one JSON line per model call, tool call and message.',
|
|
118
|
-
' --dry-run Print what would run, secrets masked, and stop.',
|
|
119
|
-
' --no-refresh Leave the editor files as they are (parallel runs).',
|
|
120
|
-
' --json Print one object: answer, answerFile, sessionId, exitCode, tokens.',
|
|
121
|
-
];
|
|
122
|
-
export const meta = {
|
|
123
|
-
summary: 'Run the meta agent over this project, on your own keys.',
|
|
124
|
-
usage: USAGE,
|
|
125
|
-
banner: { head: 'Zenera', accent: 'Meta', subtitle: 'Meta Agent', hue: 'cyan' },
|
|
126
|
-
details: [
|
|
127
|
-
'Forms:',
|
|
128
|
-
...RUN_FORMS,
|
|
129
|
-
' zen meta prompts [project] list its commands',
|
|
130
|
-
' zen meta resume [project] [session] carry on a run that stopped',
|
|
131
|
-
' zen meta model [ref] show or set the model it uses',
|
|
132
|
-
' zen meta dataset <verb> the cases it tunes against',
|
|
133
|
-
' zen meta finetune <verb> tune the project on those cases',
|
|
134
|
-
'',
|
|
135
|
-
'The project may come before the verb instead: `zen meta acme run`.',
|
|
136
|
-
'`zen meta dataset --help`, `zen meta finetune --help` and `zen meta run --help`',
|
|
137
|
-
'have their own pages; the last lists the commands.',
|
|
138
|
-
'',
|
|
139
|
-
...RUN_ARGUMENTS,
|
|
140
|
-
'',
|
|
141
|
-
...RUN_OPTIONS,
|
|
142
|
-
'',
|
|
143
|
-
'It always uses your own keys — `zen key add` — and never a coding-agent',
|
|
144
|
-
'subscription. The answer goes to stdout and the progress to stderr, so',
|
|
145
|
-
'`> out.md` keeps the answer alone.',
|
|
146
|
-
'',
|
|
147
|
-
'It may use every tool without asking, because a prompt written for an',
|
|
148
|
-
'editor expects to read, write and run things, and a terminal has nobody',
|
|
149
|
-
'watching to answer. Narrow it with --allow-tool, or restore the asking',
|
|
150
|
-
'with --ask.',
|
|
151
|
-
'',
|
|
152
|
-
'`zen meta resume` picks up the last session the project ran - or the one',
|
|
153
|
-
'named - where it stopped. A run that ends any way but success prints it.',
|
|
154
|
-
'',
|
|
155
|
-
'Its tokens are counted as it runs and summed when it ends. In a project with',
|
|
156
|
-
'a finetune/, every call - and every zen run and inspect ask it makes - is',
|
|
157
|
-
'appended to finetune/usage/ledger.jsonl, and finetune/USAGE.md is rewritten.',
|
|
158
|
-
'',
|
|
159
|
-
'Nothing it needs is put on a command line: every credential reaches it',
|
|
160
|
-
'through the environment, where other processes cannot read it.',
|
|
161
|
-
'',
|
|
162
|
-
'The editor files `zen init` writes (.vscode/ and the .github/',
|
|
163
|
-
'tree) are refreshed in the project first, the way `zen open` refreshes',
|
|
164
|
-
'them: the agent is about to read that brief, and it describes this version',
|
|
165
|
-
'of zen. Edits to them do not survive.',
|
|
166
|
-
'',
|
|
167
|
-
'The model is looked for in this order: --model, ZENERA_META_MODEL in the',
|
|
168
|
-
"shell, ZENERA_META_MODEL in the project's .env, `zen meta model`, then",
|
|
169
|
-
'agents.yaml. With none of them set it uses the best model it knows of for',
|
|
170
|
-
'a provider you hold a key for, and says which on stderr. Through a gateway',
|
|
171
|
-
'it asks what the gateway serves and takes the best of that, as ranked by',
|
|
172
|
-
'`zen models ls --chat --best`.',
|
|
173
|
-
'',
|
|
174
|
-
'Setting one asks the provider a one-word question first, so a model that',
|
|
175
|
-
"will not answer is never stored. A model whose API rejects copilot's tools",
|
|
176
|
-
'(gpt-4o and older) is refused before that. --force skips both.',
|
|
177
|
-
'',
|
|
178
|
-
'`zen meta model --pick` browses every model your keys reach: / filters,',
|
|
179
|
-
't asks one a question, p takes it.',
|
|
180
|
-
'',
|
|
181
|
-
'Examples:',
|
|
182
|
-
' zen meta run "what does this project do?"',
|
|
183
|
-
' zen meta run acme "review the last commit"',
|
|
184
|
-
' zen meta prompts',
|
|
185
|
-
' zen meta run /project-review',
|
|
186
|
-
' zen meta run acme /spec-sync-project agents/triage.md',
|
|
187
|
-
' zen meta run acme /analyze --json',
|
|
188
|
-
' zen meta resume acme',
|
|
189
|
-
' git diff | zen meta run "what broke?" --allow-tool read',
|
|
190
|
-
' zen meta model vertex/gemini-3.8-flash',
|
|
191
|
-
' zen meta model --pick',
|
|
192
|
-
' zen meta run --dry-run "hello"',
|
|
193
|
-
],
|
|
194
|
-
help: async (ctx) => {
|
|
195
|
-
const sub = subcommand(ctx.args);
|
|
196
|
-
if (sub) {
|
|
197
|
-
return page(SUBCOMMANDS[sub.name].page);
|
|
198
|
-
}
|
|
199
|
-
const words = ctx.args.filter((a) => !a.startsWith('-'));
|
|
200
|
-
if (words[0] === 'run' || words[1] === 'run') {
|
|
201
|
-
return await runHelp(ctx, words);
|
|
202
|
-
}
|
|
203
|
-
page({ ...meta, details: meta.details ?? [] });
|
|
204
|
-
},
|
|
205
|
-
run: async (ctx) => {
|
|
206
|
-
// These own their flags, so they are routed before the meta agent's are parsed.
|
|
207
|
-
const sub = subcommand(ctx.args);
|
|
208
|
-
if (sub) {
|
|
209
|
-
const { run, projectFlag } = SUBCOMMANDS[sub.name];
|
|
210
|
-
const args = ctx.args.slice(sub.at + 1);
|
|
211
|
-
const found = await resolveProject({
|
|
212
|
-
cwd: ctx.cwd,
|
|
213
|
-
project: projectFlag(args) ?? (sub.at === 1 ? ctx.args[0] : undefined),
|
|
214
|
-
});
|
|
215
|
-
return await run({ args, json: ctx.json, cwd: ctx.cwd }, found);
|
|
216
|
-
}
|
|
217
|
-
const { values, positionals } = parse(ctx.args, OPTIONS, USAGE);
|
|
218
|
-
// `zen meta acme run` is typed at least as often as `zen meta run acme`,
|
|
219
|
-
// and read literally it asks the agent the one-word question "run" —
|
|
220
|
-
// a whole model call spent on a typo, with nothing on screen to say so.
|
|
221
|
-
const [first, second] = positionals;
|
|
222
|
-
const named = first !== undefined &&
|
|
223
|
-
second !== undefined &&
|
|
224
|
-
!VERBS.has(first) &&
|
|
225
|
-
VERBS.has(second) &&
|
|
226
|
-
(await Projects.find(first))
|
|
227
|
-
? first
|
|
228
|
-
: undefined;
|
|
229
|
-
const verb = named ? second : first;
|
|
230
|
-
const args = named ? [named, ...positionals.slice(2)] : positionals.slice(1);
|
|
231
|
-
if (verb === 'model') {
|
|
232
|
-
if (named) {
|
|
233
|
-
throw usageError('the model is not per-project', 'try: zen meta model');
|
|
234
|
-
}
|
|
235
|
-
return await model(ctx, values, args);
|
|
236
|
-
}
|
|
237
|
-
if (verb === 'run') {
|
|
238
|
-
return await stored(ctx, values, args);
|
|
239
|
-
}
|
|
240
|
-
if (verb === 'prompts') {
|
|
241
|
-
return await prompts(ctx, values, args);
|
|
242
|
-
}
|
|
243
|
-
if (verb === 'resume') {
|
|
244
|
-
return await resumeRun(ctx, values, args);
|
|
245
|
-
}
|
|
246
|
-
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?"'}`);
|
|
247
|
-
},
|
|
248
|
-
};
|
|
249
|
-
// ---------------------------------------------------------------------------
|
|
250
|
-
// zen meta run --help
|
|
251
|
-
//
|
|
252
|
-
// The prompts are the reason to type `run`, so its page names them. The
|
|
253
|
-
// shipped ones come from the templates, which `run` refreshes into the project
|
|
254
|
-
// first; a project's own additions are read from the project.
|
|
255
|
-
// ---------------------------------------------------------------------------
|
|
256
|
-
async function runHelp(ctx, words) {
|
|
257
|
-
const at = ctx.args.indexOf('--project');
|
|
258
|
-
const flag = ctx.args.find((a) => a.startsWith('--project='))?.slice('--project='.length) ??
|
|
259
|
-
(at >= 0 ? ctx.args[at + 1] : undefined);
|
|
260
|
-
const named = flag ?? (words[1] === 'run' ? words[0] : words[1]);
|
|
261
|
-
const project = (named && !named.startsWith('/') ? await Projects.find(named) : undefined) ??
|
|
262
|
-
(await Projects.current(ctx.cwd));
|
|
263
|
-
const shipped = join(TEMPLATES, 'editor');
|
|
264
|
-
const ours = new Set(await listPrompts(shipped));
|
|
265
|
-
const theirs = project ? await listPrompts(project.dir) : [];
|
|
266
|
-
const names = [...new Set([...ours, ...theirs])].sort();
|
|
267
|
-
const found = await Promise.all(names.map((n) => loadPrompt(ours.has(n) ? shipped : project.dir, n)));
|
|
268
|
-
const lines = [
|
|
269
|
-
'Forms:',
|
|
270
|
-
...RUN_FORMS,
|
|
271
|
-
'',
|
|
272
|
-
project ? `Prompts in ${project.name}:` : 'Prompts:',
|
|
273
|
-
];
|
|
274
|
-
const nameWidth = Math.max(...found.map((p) => p.name.length + 1));
|
|
275
|
-
const room = Math.max(30, Math.min(process.stdout.columns ?? 80, 100) - nameWidth - 6);
|
|
276
|
-
for (const p of found) {
|
|
277
|
-
const [first = '', ...more] = wrap(p.description ?? '', room);
|
|
278
|
-
lines.push(` ${pad(`/${p.name}`, nameWidth)} ${first}`.trimEnd());
|
|
279
|
-
lines.push(...more.map((l) => ` ${' '.repeat(nameWidth)} ${l}`));
|
|
280
|
-
}
|
|
281
|
-
lines.push('', ...RUN_ARGUMENTS, '', ...RUN_OPTIONS, '', 'Examples:', ' zen meta run "what does this project do?"', ' zen meta run acme /project-review', ' zen meta run acme /spec-sync-project agents/triage.md', ' zen meta run acme /analyze --json');
|
|
282
|
-
page({
|
|
283
|
-
usage: 'zen meta run [project] [/<name> [words] | "<question>"] [options]',
|
|
284
|
-
summary: 'Ask the meta agent a question, or run one of the commands.',
|
|
285
|
-
details: lines,
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
/** Words the shell would have split are shown back the way they were typed. */
|
|
289
|
-
const requote = (s) => (/\s/.test(s) ? JSON.stringify(s) : s);
|
|
290
|
-
// ---------------------------------------------------------------------------
|
|
291
|
-
// Which project
|
|
292
|
-
//
|
|
293
|
-
// `zen meta run acme "…"` is what gets typed before anyone finds --project, and
|
|
294
|
-
// a project name is a bare word where a prompt is a sentence — the same reading
|
|
295
|
-
// `zen run` gives its first positional, for the same reason.
|
|
296
|
-
// ---------------------------------------------------------------------------
|
|
297
|
-
async function where(ctx, flag, positionals) {
|
|
298
|
-
const [head, ...tail] = positionals;
|
|
299
|
-
const named = !flag && head ? await Projects.find(head) : undefined;
|
|
300
|
-
const project = await resolveProject({
|
|
301
|
-
cwd: ctx.cwd,
|
|
302
|
-
project: flag ?? (named ? head : undefined),
|
|
303
|
-
});
|
|
304
|
-
return { project, rest: named ? tail : positionals };
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* The editor's files, rewritten before the agent reads them — the same refresh
|
|
308
|
-
* `zen open` does, for the same reason. `.github/` is the brief this agent works
|
|
309
|
-
* from and the prompts it is offered, and it describes the version of `zen` in
|
|
310
|
-
* hand; a project scaffolded by an older one would otherwise be briefed on a
|
|
311
|
-
* runtime that has moved. A failure is narrated, not raised: a read-only
|
|
312
|
-
* checkout is no reason to refuse to answer a question.
|
|
313
|
-
*/
|
|
314
|
-
function refresh(project) {
|
|
315
|
-
try {
|
|
316
|
-
const written = editorFiles(project.dir);
|
|
317
|
-
if (written.length) {
|
|
318
|
-
note(dim(`refreshed ${written.length} editor files in ${project.name}`));
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
catch (err) {
|
|
322
|
-
warn(`could not refresh the editor files — ${err.message}`);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
// ---------------------------------------------------------------------------
|
|
326
|
-
// zen meta run [project] [/<name>|<question>] [words...]
|
|
327
|
-
//
|
|
328
|
-
// The leading slash is a marker, not decoration: with it there is nothing to
|
|
329
|
-
// guess, because the project is whatever came before and the extra words are
|
|
330
|
-
// whatever came after, even when a project and a prompt share a name. Without
|
|
331
|
-
// one the words are the question itself.
|
|
332
|
-
// ---------------------------------------------------------------------------
|
|
333
|
-
async function stored(ctx, values, args) {
|
|
334
|
-
const slash = args.findIndex((a) => a.startsWith('/'));
|
|
335
|
-
let head;
|
|
336
|
-
let name;
|
|
337
|
-
let rest;
|
|
338
|
-
if (slash >= 0) {
|
|
339
|
-
head = args.slice(0, slash);
|
|
340
|
-
name = args[slash];
|
|
341
|
-
rest = args.slice(slash + 1);
|
|
342
|
-
}
|
|
343
|
-
else if (args[0] !== undefined && (await Projects.find(args[0]))) {
|
|
344
|
-
head = [args[0]];
|
|
345
|
-
rest = args.slice(1);
|
|
346
|
-
}
|
|
347
|
-
else {
|
|
348
|
-
head = [];
|
|
349
|
-
rest = args;
|
|
350
|
-
}
|
|
351
|
-
const { project } = await where(ctx, values.project, head);
|
|
352
|
-
if (!values['no-refresh']) {
|
|
353
|
-
refresh(project);
|
|
354
|
-
}
|
|
355
|
-
if (name) {
|
|
356
|
-
return await runPrompt(ctx, values, project, name, rest);
|
|
357
|
-
}
|
|
358
|
-
const question = withFile(values, (values.prompt ?? rest.join(' ')).trim()) || (await readStdin());
|
|
359
|
-
if (question) {
|
|
360
|
-
return await go(ctx, values, project, question);
|
|
361
|
-
}
|
|
362
|
-
// Nothing said and nothing piped: the commands are what is left to offer.
|
|
363
|
-
return await runPrompt(ctx, values, project, await pickPrompt(ctx, project), []);
|
|
364
|
-
}
|
|
365
|
-
async function runPrompt(ctx, values, project, name, extra) {
|
|
366
|
-
const found = await loadPrompt(project.dir, name);
|
|
367
|
-
if (found.description) {
|
|
368
|
-
note(dim(found.description));
|
|
369
|
-
}
|
|
370
|
-
const prompt = withFile(values, extra.length > 0 ? `${found.body}\n\n${extra.join(' ')}` : found.body);
|
|
371
|
-
await go(ctx, values, project, prompt, name.replace(/^\//, ''));
|
|
372
|
-
}
|
|
373
|
-
/** The prompt with `--prompt-file` after it: text too long, or too awkward to quote, for a word. */
|
|
374
|
-
function withFile(values, prompt) {
|
|
375
|
-
const file = values['prompt-file'];
|
|
376
|
-
if (!file) {
|
|
377
|
-
return prompt;
|
|
378
|
-
}
|
|
379
|
-
let text;
|
|
380
|
-
try {
|
|
381
|
-
text = readFileSync(resolve(file), 'utf8').trim();
|
|
382
|
-
}
|
|
383
|
-
catch {
|
|
384
|
-
throw usageError(`no prompt file at ${file}`, 'name a file that exists');
|
|
385
|
-
}
|
|
386
|
-
return [prompt, text].filter(Boolean).join('\n\n');
|
|
387
|
-
}
|
|
388
|
-
async function pickPrompt(ctx, project) {
|
|
389
|
-
const names = await listPrompts(project.dir);
|
|
390
|
-
if (names.length === 0) {
|
|
391
|
-
throw usageError('nothing to run', `try: zen meta run ${project.name} "what does this project do?"`);
|
|
392
|
-
}
|
|
393
|
-
if (!isInteractive() || ctx.json) {
|
|
394
|
-
throw usageError('which prompt?', `try: ${names.map((n) => `/${n}`).join(', ')}`);
|
|
395
|
-
}
|
|
396
|
-
return await choose('Which prompt?', names.map((n) => ({ label: `/${n}`, value: n })));
|
|
397
|
-
}
|
|
398
|
-
// ---------------------------------------------------------------------------
|
|
399
|
-
// Completing it
|
|
400
|
-
//
|
|
401
|
-
// `zen meta run acme /<Tab>` is where a terminal can show what an editor's menu
|
|
402
|
-
// shows. It reads the line the way `stored` does — a leading slash is a prompt,
|
|
403
|
-
// a bare word that names a project is the project — and it only ever reads:
|
|
404
|
-
// the editor files are not refreshed for the sake of a Tab.
|
|
405
|
-
// ---------------------------------------------------------------------------
|
|
406
|
-
async function findProject(name) {
|
|
407
|
-
try {
|
|
408
|
-
return await Projects.find(name);
|
|
409
|
-
}
|
|
410
|
-
catch {
|
|
411
|
-
return undefined;
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
async function promptsOf(project) {
|
|
415
|
-
if (!project) {
|
|
416
|
-
return [];
|
|
417
|
-
}
|
|
418
|
-
const names = await listPrompts(project.dir);
|
|
419
|
-
return await Promise.all(names.map(async (name) => ({
|
|
420
|
-
value: `/${name}`,
|
|
421
|
-
description: (await loadPrompt(project.dir, name).catch(() => undefined))?.description,
|
|
422
|
-
})));
|
|
423
|
-
}
|
|
424
|
-
/** `args` is what came after `meta`, without the word being completed. */
|
|
425
|
-
export async function completeMeta(args, cur, cwd) {
|
|
426
|
-
const words = [];
|
|
427
|
-
let flagged;
|
|
428
|
-
let waiting;
|
|
429
|
-
for (const arg of args) {
|
|
430
|
-
if (waiting) {
|
|
431
|
-
if (waiting === 'project') {
|
|
432
|
-
flagged = arg;
|
|
433
|
-
}
|
|
434
|
-
waiting = undefined;
|
|
435
|
-
}
|
|
436
|
-
else if (arg.startsWith('--')) {
|
|
437
|
-
const [flag, value] = arg.slice(2).split(/=(.*)/s);
|
|
438
|
-
if (value !== undefined) {
|
|
439
|
-
flagged = flag === 'project' ? value : flagged;
|
|
440
|
-
}
|
|
441
|
-
else if (OPTIONS[flag]?.type === 'string') {
|
|
442
|
-
waiting = flag;
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
else if (arg === '-p') {
|
|
446
|
-
waiting = 'prompt';
|
|
447
|
-
}
|
|
448
|
-
else if (!arg.startsWith('-')) {
|
|
449
|
-
words.push(arg);
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
// A flag's value is the flag's to name, and most of them are free text or a
|
|
453
|
-
// path — which is the shell's.
|
|
454
|
-
if (waiting === 'provider') {
|
|
455
|
-
return matching(PROVIDERS.map((value) => ({ value })), cur);
|
|
456
|
-
}
|
|
457
|
-
if (waiting === 'project') {
|
|
458
|
-
return matching(await projectNames(), cur);
|
|
459
|
-
}
|
|
460
|
-
if (waiting) {
|
|
461
|
-
return [];
|
|
462
|
-
}
|
|
463
|
-
const at = words.findIndex((w) => VERBS.has(w));
|
|
464
|
-
const named = at === 1 ? words[0] : undefined;
|
|
465
|
-
const verb = at === 0 || (named && (await findProject(named))) ? words[at] : undefined;
|
|
466
|
-
if (cur.startsWith('-')) {
|
|
467
|
-
return verb === 'dataset' || verb === 'finetune'
|
|
468
|
-
? []
|
|
469
|
-
: matching(Object.keys(OPTIONS).map((flag) => ({ value: `--${flag}` })), cur);
|
|
470
|
-
}
|
|
471
|
-
if (!verb) {
|
|
472
|
-
const verbs = [...VERBS].map((value) => ({ value }));
|
|
473
|
-
if (words.length === 0) {
|
|
474
|
-
return matching([...verbs, ...(await projectNames())], cur);
|
|
475
|
-
}
|
|
476
|
-
return words.length === 1 && (await findProject(words[0])) ? matching(verbs, cur) : [];
|
|
477
|
-
}
|
|
478
|
-
const rest = words.slice(at + 1);
|
|
479
|
-
if (verb === 'prompts' || verb === 'resume') {
|
|
480
|
-
return flagged || named || rest.length > 0 ? [] : matching(await projectNames(), cur);
|
|
481
|
-
}
|
|
482
|
-
if (verb !== 'run' || rest.some((w) => w.startsWith('/'))) {
|
|
483
|
-
// Past the prompt's name, what follows is files and words.
|
|
484
|
-
return [];
|
|
485
|
-
}
|
|
486
|
-
const given = flagged ?? named ?? rest[0];
|
|
487
|
-
if (given === undefined) {
|
|
488
|
-
const here = await Projects.current(cwd).catch(() => undefined);
|
|
489
|
-
return matching([...(await promptsOf(here)), ...(await projectNames())], cur);
|
|
490
|
-
}
|
|
491
|
-
const project = await findProject(given);
|
|
492
|
-
const fromRest = !flagged && !named;
|
|
493
|
-
const free = rest.length - (fromRest && project ? 1 : 0);
|
|
494
|
-
return free > 0 ? [] : matching(await promptsOf(project), cur);
|
|
495
|
-
}
|
|
496
|
-
// ---------------------------------------------------------------------------
|
|
497
|
-
// zen meta prompts [project]
|
|
498
|
-
//
|
|
499
|
-
// A slash command is only discoverable inside an editor, where a menu drops
|
|
500
|
-
// down as you type it. On a terminal the same files have to be asked for.
|
|
501
|
-
// ---------------------------------------------------------------------------
|
|
502
|
-
async function prompts(ctx, values, args) {
|
|
503
|
-
const { project } = await where(ctx, values.project, args);
|
|
504
|
-
refresh(project);
|
|
505
|
-
const names = await listPrompts(project.dir);
|
|
506
|
-
const found = await Promise.all(names.map((name) => loadPrompt(project.dir, name)));
|
|
507
|
-
if (ctx.json) {
|
|
508
|
-
return json(found.map(({ name, description, path }) => ({ name, description, path })));
|
|
509
|
-
}
|
|
510
|
-
if (found.length === 0) {
|
|
511
|
-
note(dim(`no commands in ${project.name}/${SKILL_DIR}`));
|
|
512
|
-
return;
|
|
513
|
-
}
|
|
514
|
-
writeAll(table(found.map((p) => [`/${p.name}`, p.description ? dim(p.description) : ''])));
|
|
515
|
-
note();
|
|
516
|
-
note(dim(`run one: zen meta run /${found[0].name}`));
|
|
517
|
-
}
|
|
518
|
-
// ---------------------------------------------------------------------------
|
|
519
|
-
// zen meta resume [project] [session id] [words...]
|
|
520
|
-
//
|
|
521
|
-
// A long run stops for reasons nobody chose - a refused request, a closed
|
|
522
|
-
// laptop, Ctrl-C. Copilot keeps the session; this hands it back, by default the
|
|
523
|
-
// last one the project ran, with the words (or a plain "continue") as the turn.
|
|
524
|
-
// ---------------------------------------------------------------------------
|
|
525
|
-
async function resumeRun(ctx, values, args) {
|
|
526
|
-
const { project, rest } = await where(ctx, values.project, args);
|
|
527
|
-
const named = rest[0] !== undefined && SESSION_ID.test(rest[0]) ? rest[0] : undefined;
|
|
528
|
-
const words = named ? rest.slice(1) : rest;
|
|
529
|
-
const session = named ?? values.resume ?? lastSession(project.dir);
|
|
530
|
-
if (!session) {
|
|
531
|
-
throw usageError(`no meta session recorded in ${project.name}`, `name one: zen meta resume ${project.name} <session id>`);
|
|
532
|
-
}
|
|
533
|
-
note(dim(`resuming session ${session}`));
|
|
534
|
-
if (!values['no-refresh']) {
|
|
535
|
-
refresh(project);
|
|
536
|
-
}
|
|
537
|
-
const message = withFile(values, (values.prompt ?? words.join(' ')).trim()) || RESUME_PROMPT;
|
|
538
|
-
await go(ctx, { ...values, resume: session, continue: false }, project, message);
|
|
539
|
-
}
|
|
540
|
-
// ---------------------------------------------------------------------------
|
|
541
|
-
// The run itself
|
|
542
|
-
// ---------------------------------------------------------------------------
|
|
543
|
-
async function go(ctx, values, project, prompt, promptName) {
|
|
544
|
-
const fresh = values['session-id'];
|
|
545
|
-
if (fresh !== undefined) {
|
|
546
|
-
if (values.resume || values.continue) {
|
|
547
|
-
throw usageError('--session-id starts a new session', 'drop --resume / --continue');
|
|
548
|
-
}
|
|
549
|
-
if (!UUID.test(fresh)) {
|
|
550
|
-
throw usageError(`--session-id must be a UUID, not ${fresh}`, 'try: uuidgen');
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
const shell = process.env[MODEL_ENV];
|
|
554
|
-
loadProjectEnv(project.dir);
|
|
555
|
-
ensureHome();
|
|
556
|
-
const store = await KeyStore.open();
|
|
557
|
-
store.materialize();
|
|
558
|
-
// After materialize: a keyring in bifrost mode is what sets the url.
|
|
559
|
-
const gateway = gatewayOf();
|
|
560
|
-
const only = values.provider ? asProvider(values.provider) : undefined;
|
|
561
|
-
// The fallback can cost a gateway listing, so it is only looked up when nothing else answers.
|
|
562
|
-
const chosen = chooseModel({
|
|
563
|
-
flag: values.model,
|
|
564
|
-
shell,
|
|
565
|
-
env: process.env[MODEL_ENV],
|
|
566
|
-
stored: (await readMeta()).model,
|
|
567
|
-
project: projectModel(project.dir),
|
|
568
|
-
}) ?? chooseModel({ fallback: await fallbackRef(store, only, gateway !== undefined) });
|
|
569
|
-
if (!chosen) {
|
|
570
|
-
if (only) {
|
|
571
|
-
throw credentialError(`no ${only} key`, `add one: zen key add ${only}`);
|
|
572
|
-
}
|
|
573
|
-
throw credentialError('no model for the meta agent', store.entries.length === 0
|
|
574
|
-
? 'add a key: zen key add openai'
|
|
575
|
-
: 'set one: zen meta model <provider>/<id>');
|
|
576
|
-
}
|
|
577
|
-
const { provider, id } = splitRef(chosen.ref);
|
|
578
|
-
const owner = only ?? provider ?? 'openai';
|
|
579
|
-
const meant = misspelledProvider(chosen.ref);
|
|
580
|
-
if (meant && !only) {
|
|
581
|
-
warn(`${chosen.ref} names no provider — did you mean ${meant}/${id}?`);
|
|
582
|
-
}
|
|
583
|
-
const entry = gateway ? undefined : store.active(owner);
|
|
584
|
-
if (!gateway && !entry) {
|
|
585
|
-
throw credentialError(`no ${owner} key`, `add one: zen key add ${owner}`);
|
|
586
|
-
}
|
|
587
|
-
const wiring = gateway ? wireGateway(gateway, owner, id) : wire(store, entry, id);
|
|
588
|
-
const binary = locate();
|
|
589
|
-
// Copilot cannot carry a session to another model: the resume fails on the first call.
|
|
590
|
-
const ran = values.resume ? sessionModel(values.resume) : undefined;
|
|
591
|
-
if (values.resume && ran && !sameModel(ran, wiring.model)) {
|
|
592
|
-
if (prompt === RESUME_PROMPT) {
|
|
593
|
-
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`);
|
|
594
|
-
}
|
|
595
|
-
warn(`session ${values.resume} ran on ${ran}; the meta model is now ${wiring.model}, so this starts a new session`);
|
|
596
|
-
values = { ...values, resume: undefined };
|
|
597
|
-
}
|
|
598
|
-
// Named up front, so a run killed before copilot reports its id can still be resumed.
|
|
599
|
-
let session = values.resume ?? (values.continue ? undefined : (fresh ?? randomUUID()));
|
|
600
|
-
const args = argv(values, project.dir, prompt, wiring.secret, session);
|
|
601
|
-
const retries = count(values.retries, '--retries') ?? DEFAULT_RESUMES;
|
|
602
|
-
if (values['dry-run']) {
|
|
603
|
-
const lines = masked(wiring.env, wiring.secret);
|
|
604
|
-
if (ctx.json) {
|
|
605
|
-
return json({
|
|
606
|
-
project: project.dir,
|
|
607
|
-
provider: owner,
|
|
608
|
-
model: chosen.ref,
|
|
609
|
-
from: SOURCE_LABELS[chosen.from],
|
|
610
|
-
command: [binary.command, ...binary.args, ...args],
|
|
611
|
-
env: Object.fromEntries(lines.map((l) => l.split('=', 2))),
|
|
612
|
-
});
|
|
613
|
-
}
|
|
614
|
-
write(`${binary.command} ${[...binary.args, ...args].join(' ')}`);
|
|
615
|
-
writeAll(lines.map((l) => dim(l)));
|
|
616
|
-
note(dim(`model ${chosen.ref} from ${SOURCE_LABELS[chosen.from]}`));
|
|
617
|
-
return;
|
|
618
|
-
}
|
|
619
|
-
for (const line of wiring.warnings) {
|
|
620
|
-
warn(line);
|
|
621
|
-
}
|
|
622
|
-
const competing = providersWarning();
|
|
623
|
-
if (competing) {
|
|
624
|
-
warn(competing);
|
|
625
|
-
}
|
|
626
|
-
if (chosen.from === 'default') {
|
|
627
|
-
const what = gateway
|
|
628
|
-
? 'the best model the gateway serves'
|
|
629
|
-
: `the best ${owner} model zen knows of`;
|
|
630
|
-
note(dim(`no model set — using ${chosen.ref}, ${what}`));
|
|
631
|
-
note(dim('set another: zen meta model <provider>/<id>'));
|
|
632
|
-
}
|
|
633
|
-
note(cyan(`${owner} · ${wiring.model} · ${project.name}`));
|
|
634
|
-
const log = openLog(project.dir, new Date(), session);
|
|
635
|
-
note(`log ${log.path}`);
|
|
636
|
-
const elided = args.map((a, i) => (args[i - 1] === '-p' ? '<prompt>' : a));
|
|
637
|
-
log.line(`zen meta ${new Date().toISOString()}`);
|
|
638
|
-
log.line(`project ${project.name} ${project.dir}`);
|
|
639
|
-
log.line(`model ${chosen.ref} from ${SOURCE_LABELS[chosen.from]}`);
|
|
640
|
-
log.line(`command ${[binary.command, ...binary.args, ...elided].join(' ')}`);
|
|
641
|
-
if (session) {
|
|
642
|
-
recordSession(project.dir, session);
|
|
643
|
-
log.line(`session ${session}`);
|
|
644
|
-
}
|
|
645
|
-
const relay = wiring.relay ? await startVertexRelay(wiring.relay) : undefined;
|
|
646
|
-
if (relay) {
|
|
647
|
-
wiring.env.COPILOT_PROVIDER_BASE_URL = relay.url;
|
|
648
|
-
log.line(`relay ${relay.url} -> vertex rawPredict`);
|
|
649
|
-
}
|
|
650
|
-
log.line('');
|
|
651
|
-
log.line('--- prompt ---');
|
|
652
|
-
log.line(prompt);
|
|
653
|
-
log.line('');
|
|
654
|
-
log.line('--- run ---');
|
|
655
|
-
const resumeHint = () => session ? `resume it: zen meta resume ${project.name} ${session}` : undefined;
|
|
656
|
-
// Every zen command the agent runs inherits these, so a batch it starts or
|
|
657
|
-
// an ask it makes lands in the same ledger, tagged with this session.
|
|
658
|
-
const spans = log.path.replace(/\.log$/, '.otel.jsonl');
|
|
659
|
-
const ledger = ledgerPath(project.dir);
|
|
660
|
-
const env = {
|
|
661
|
-
...wiring.env,
|
|
662
|
-
COPILOT_OTEL_FILE_EXPORTER_PATH: spans,
|
|
663
|
-
...(ledger ? { [LEDGER_ENV]: ledger } : {}),
|
|
664
|
-
...(session ? { [META_SESSION_ENV]: session } : {}),
|
|
665
|
-
...(promptName ? { [META_PROMPT_ENV]: promptName } : {}),
|
|
666
|
-
};
|
|
667
|
-
const tally = new Tally();
|
|
668
|
-
const record = values.events ? copilotEventLog(resolve(ctx.cwd, values.events)) : undefined;
|
|
669
|
-
const tail = tailSpans(spans, (call) => {
|
|
670
|
-
tally.add(call);
|
|
671
|
-
record?.call(call);
|
|
672
|
-
appendUsage(project.dir, {
|
|
673
|
-
kind: 'meta.call',
|
|
674
|
-
ts: new Date(Date.parse(call.startedAt) + call.durationMs).toISOString(),
|
|
675
|
-
...call,
|
|
676
|
-
session: call.session ?? session,
|
|
677
|
-
});
|
|
678
|
-
});
|
|
679
|
-
const reporter = usageReporter(project.dir);
|
|
680
|
-
const tokens = () => {
|
|
681
|
-
tail.stop();
|
|
682
|
-
return tally.toString();
|
|
683
|
-
};
|
|
684
|
-
// A run that dies still has to leave a readable file behind.
|
|
685
|
-
try {
|
|
686
|
-
let resumes = 0;
|
|
687
|
-
const run = async (argList) => {
|
|
688
|
-
const launchedAt = new Date();
|
|
689
|
-
const outcome = await launch({
|
|
690
|
-
binary,
|
|
691
|
-
args: argList,
|
|
692
|
-
env,
|
|
693
|
-
cwd: project.dir,
|
|
694
|
-
log,
|
|
695
|
-
sink: ctx.json ? terminalSink : undefined,
|
|
696
|
-
onEvent: record?.event,
|
|
697
|
-
status: () => (tally.calls > 0 ? tally.toString() : ''),
|
|
698
|
-
});
|
|
699
|
-
if (outcome.sessionId && outcome.sessionId !== session) {
|
|
700
|
-
session = outcome.sessionId;
|
|
701
|
-
recordSession(project.dir, session);
|
|
702
|
-
}
|
|
703
|
-
const models = session ? sessionTotals(session) : undefined;
|
|
704
|
-
if (session && models) {
|
|
705
|
-
appendUsage(project.dir, {
|
|
706
|
-
kind: 'meta.session',
|
|
707
|
-
ts: new Date().toISOString(),
|
|
708
|
-
session,
|
|
709
|
-
models,
|
|
710
|
-
exitCode: outcome.exitCode,
|
|
711
|
-
resumes,
|
|
712
|
-
startedAt: launchedAt.toISOString(),
|
|
713
|
-
durationMs: Date.now() - launchedAt.getTime(),
|
|
714
|
-
});
|
|
715
|
-
}
|
|
716
|
-
return outcome;
|
|
717
|
-
};
|
|
718
|
-
let outcome = await run(args);
|
|
719
|
-
for (let reason = transient(outcome); reason && resumes < retries;) {
|
|
720
|
-
const wait = resumeDelayMs(resumes);
|
|
721
|
-
resumes += 1;
|
|
722
|
-
const said = `${reason}: resuming in ${duration(wait)} (${resumes}/${retries})`;
|
|
723
|
-
warn(said);
|
|
724
|
-
log.line('');
|
|
725
|
-
log.line(`--- resume ${resumes}: ${said} ---`);
|
|
726
|
-
await pause(wait, resumeHint());
|
|
727
|
-
const again = { ...values, resume: session, continue: false };
|
|
728
|
-
outcome = await run(argv(again, project.dir, RESUME_PROMPT, wiring.secret));
|
|
729
|
-
reason = transient(outcome);
|
|
730
|
-
}
|
|
731
|
-
log.line('');
|
|
732
|
-
log.line('--- answer ---');
|
|
733
|
-
log.line(outcome.answer);
|
|
734
|
-
if (outcome.answer) {
|
|
735
|
-
log.saveAnswer(outcome.answer);
|
|
736
|
-
}
|
|
737
|
-
const spent = tokens();
|
|
738
|
-
log.line('');
|
|
739
|
-
log.line(`tokens ${spent}`);
|
|
740
|
-
if (ctx.json) {
|
|
741
|
-
json({
|
|
742
|
-
project: project.dir,
|
|
743
|
-
provider: owner,
|
|
744
|
-
model: chosen.ref,
|
|
745
|
-
sessionId: outcome.sessionId,
|
|
746
|
-
exitCode: outcome.exitCode,
|
|
747
|
-
resumes,
|
|
748
|
-
usage: outcome.usage,
|
|
749
|
-
tokens: { calls: tally.calls, ...tally.usage },
|
|
750
|
-
answer: outcome.answer,
|
|
751
|
-
answerFile: outcome.answer ? log.answerPath : undefined,
|
|
752
|
-
});
|
|
753
|
-
}
|
|
754
|
-
else if (outcome.answer) {
|
|
755
|
-
writeAll(answerBox(outcome.answer));
|
|
756
|
-
// After the answer, not before: it is the thing you click once you
|
|
757
|
-
// have read enough to want it in an editor.
|
|
758
|
-
note(cyan(log.answerPath));
|
|
759
|
-
}
|
|
760
|
-
if (!ctx.json && tally.calls > 0) {
|
|
761
|
-
note(dim(`tokens ${spent}`));
|
|
762
|
-
}
|
|
763
|
-
if (outcome.exitCode !== 0) {
|
|
764
|
-
throw new CliError(`the meta agent exited ${outcome.exitCode}`, EXIT.failed, resumeHint() ??
|
|
765
|
-
(binary.from === 'npx' ? 'install it: npm i -g @github/copilot' : undefined));
|
|
766
|
-
}
|
|
767
|
-
}
|
|
768
|
-
catch (err) {
|
|
769
|
-
const hint = resumeHint();
|
|
770
|
-
if (hint && !(err instanceof CliError)) {
|
|
771
|
-
note(dim(hint));
|
|
772
|
-
}
|
|
773
|
-
throw err;
|
|
774
|
-
}
|
|
775
|
-
finally {
|
|
776
|
-
tail.stop();
|
|
777
|
-
reporter.stop();
|
|
778
|
-
await relay?.close();
|
|
779
|
-
log.close();
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
/** How often a running meta agent rewrites the fine-tuning's usage report. */
|
|
783
|
-
const REPORT_EVERY_MS = 5 * 60_000;
|
|
784
|
-
/**
|
|
785
|
-
* Rewrites `finetune/USAGE.md` on a timer and once more at the end, when the
|
|
786
|
-
* project is being tuned. Detached and silent: the report is a by-product, and
|
|
787
|
-
* neither its time nor its failure belongs to the run.
|
|
788
|
-
*/
|
|
789
|
-
function usageReporter(dir) {
|
|
790
|
-
const script = join(dir, '.github/skills/zen-finetune/scripts/usage.mjs');
|
|
791
|
-
if (!existsSync(join(dir, 'finetune')) || !existsSync(script)) {
|
|
792
|
-
return { stop: () => undefined };
|
|
793
|
-
}
|
|
794
|
-
let running = false;
|
|
795
|
-
const refresh = () => {
|
|
796
|
-
if (running) {
|
|
797
|
-
return;
|
|
798
|
-
}
|
|
799
|
-
running = true;
|
|
800
|
-
const child = spawn(process.execPath, [script, '-q'], {
|
|
801
|
-
cwd: dir,
|
|
802
|
-
stdio: 'ignore',
|
|
803
|
-
detached: true,
|
|
804
|
-
});
|
|
805
|
-
child.on('exit', () => (running = false));
|
|
806
|
-
child.on('error', () => (running = false));
|
|
807
|
-
child.unref();
|
|
808
|
-
};
|
|
809
|
-
const timer = setInterval(refresh, REPORT_EVERY_MS);
|
|
810
|
-
timer.unref();
|
|
811
|
-
return {
|
|
812
|
-
stop: () => {
|
|
813
|
-
clearInterval(timer);
|
|
814
|
-
running = false;
|
|
815
|
-
refresh();
|
|
816
|
-
},
|
|
817
|
-
};
|
|
818
|
-
}
|
|
819
|
-
/** The wait before a resume, cut short by Ctrl-C - which still says how to resume. */
|
|
820
|
-
async function pause(ms, hint) {
|
|
821
|
-
const stop = new AbortController();
|
|
822
|
-
const onInt = () => stop.abort();
|
|
823
|
-
process.once('SIGINT', onInt);
|
|
824
|
-
try {
|
|
825
|
-
await sleep(ms, undefined, { signal: stop.signal });
|
|
826
|
-
}
|
|
827
|
-
catch {
|
|
828
|
-
throw new CliError('interrupted', EXIT.failed, hint);
|
|
829
|
-
}
|
|
830
|
-
finally {
|
|
831
|
-
process.off('SIGINT', onInt);
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
/** Copilot's own flags, assembled once. Nothing secret goes on this line. */
|
|
835
|
-
function argv(values, dir, prompt, secret, fresh) {
|
|
836
|
-
const args = ['-C', dir, '-p', prompt, '--output-format', 'json', '--no-color'];
|
|
837
|
-
// A prompt written for an editor expects to read, write and run things, and
|
|
838
|
-
// there is nobody at a `-p` run to answer the question. Naming tools is the
|
|
839
|
-
// narrower answer and wins; --ask is the way back to being asked.
|
|
840
|
-
if (values['allow-all'] || (!values.ask && !values['allow-tool'])) {
|
|
841
|
-
args.push('--allow-all-tools');
|
|
842
|
-
}
|
|
843
|
-
if (values['allow-tool']) {
|
|
844
|
-
args.push('--allow-tool', values['allow-tool']);
|
|
845
|
-
}
|
|
846
|
-
for (const extra of values['add-dir'] ?? []) {
|
|
847
|
-
args.push('--add-dir', extra);
|
|
848
|
-
}
|
|
849
|
-
if (values.agent) {
|
|
850
|
-
args.push('--agent', values.agent);
|
|
851
|
-
}
|
|
852
|
-
if (values.effort) {
|
|
853
|
-
args.push('--reasoning-effort', values.effort);
|
|
854
|
-
}
|
|
855
|
-
if (values.share) {
|
|
856
|
-
args.push('--share', values.share);
|
|
857
|
-
}
|
|
858
|
-
if (values.resume) {
|
|
859
|
-
args.push('--resume', values.resume);
|
|
860
|
-
}
|
|
861
|
-
else if (values.continue) {
|
|
862
|
-
args.push('--continue');
|
|
863
|
-
}
|
|
864
|
-
else if (fresh) {
|
|
865
|
-
args.push('--session-id', fresh);
|
|
866
|
-
}
|
|
867
|
-
if (secret.length > 0) {
|
|
868
|
-
args.push('--secret-env-vars', secret.join(','));
|
|
869
|
-
}
|
|
870
|
-
return args;
|
|
871
|
-
}
|
|
872
|
-
/** The project's own `model:`, with a `models:` alias resolved to what it names. */
|
|
873
|
-
function projectModel(dir) {
|
|
874
|
-
try {
|
|
875
|
-
const { config } = readProjectConfig(dir);
|
|
876
|
-
const top = typeof config.model === 'string' ? config.model : undefined;
|
|
877
|
-
const alias = top ? config.models?.[top] : undefined;
|
|
878
|
-
if (!alias) {
|
|
879
|
-
return top;
|
|
880
|
-
}
|
|
881
|
-
if (typeof alias === 'string') {
|
|
882
|
-
return alias;
|
|
883
|
-
}
|
|
884
|
-
const owner = PROVIDERS.find((p) => p === alias.provider);
|
|
885
|
-
return owner ? `${owner}/${alias.model}` : alias.model;
|
|
886
|
-
}
|
|
887
|
-
catch {
|
|
888
|
-
return undefined;
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
function count(text, flag) {
|
|
892
|
-
if (text === undefined) {
|
|
893
|
-
return undefined;
|
|
894
|
-
}
|
|
895
|
-
const value = Number(text);
|
|
896
|
-
if (!Number.isInteger(value) || value < 0) {
|
|
897
|
-
throw usageError(`${flag} takes a whole number, 0 or more`, `got "${text}"`);
|
|
898
|
-
}
|
|
899
|
-
return value;
|
|
900
|
-
}
|
|
901
|
-
function asProvider(name) {
|
|
902
|
-
const owner = assertOwner(name);
|
|
903
|
-
if (!isProvider(owner)) {
|
|
904
|
-
throw usageError(`${name} is not a model provider`);
|
|
905
|
-
}
|
|
906
|
-
return owner;
|
|
907
|
-
}
|
|
908
|
-
// ---------------------------------------------------------------------------
|
|
909
|
-
// zen meta model
|
|
910
|
-
//
|
|
911
|
-
// Bare, it answers the question that actually gets asked, which is not "what
|
|
912
|
-
// model" but "why that one" — so the chain is printed with the winner marked,
|
|
913
|
-
// the same way `zen key ls` marks the key a run would use.
|
|
914
|
-
// ---------------------------------------------------------------------------
|
|
915
|
-
async function model(ctx, values, args) {
|
|
916
|
-
const project = await Projects.current(ctx.cwd);
|
|
917
|
-
const shell = process.env[MODEL_ENV];
|
|
918
|
-
if (project) {
|
|
919
|
-
loadProjectEnv(project.dir);
|
|
920
|
-
}
|
|
921
|
-
ensureHome();
|
|
922
|
-
if (values.clear) {
|
|
923
|
-
return clear(values, project);
|
|
924
|
-
}
|
|
925
|
-
const ref = values.pick ? await pickModel(ctx) : args[0];
|
|
926
|
-
if (ref) {
|
|
927
|
-
return set(ctx, values, project, ref);
|
|
928
|
-
}
|
|
929
|
-
const store = await KeyStore.open();
|
|
930
|
-
store.materialize();
|
|
931
|
-
const sources = {
|
|
932
|
-
flag: undefined,
|
|
933
|
-
shell,
|
|
934
|
-
env: process.env[MODEL_ENV],
|
|
935
|
-
stored: (await readMeta()).model,
|
|
936
|
-
project: project ? projectModel(project.dir) : undefined,
|
|
937
|
-
fallback: await fallbackRef(store, undefined, gatewayOf() !== undefined),
|
|
938
|
-
};
|
|
939
|
-
const chosen = chooseModel(sources);
|
|
940
|
-
const at = {
|
|
941
|
-
flag: sources.flag,
|
|
942
|
-
shell: sources.shell,
|
|
943
|
-
env: sources.shell ? undefined : sources.env,
|
|
944
|
-
store: sources.stored,
|
|
945
|
-
project: sources.project,
|
|
946
|
-
default: sources.fallback,
|
|
947
|
-
};
|
|
948
|
-
if (ctx.json) {
|
|
949
|
-
return json({
|
|
950
|
-
model: chosen?.ref,
|
|
951
|
-
from: chosen ? SOURCE_LABELS[chosen.from] : undefined,
|
|
952
|
-
sources: Object.fromEntries(ORDER.map((s) => [SOURCE_LABELS[s], at[s] ?? null])),
|
|
953
|
-
});
|
|
954
|
-
}
|
|
955
|
-
if (chosen) {
|
|
956
|
-
write(chosen.ref);
|
|
957
|
-
}
|
|
958
|
-
note();
|
|
959
|
-
for (const source of ORDER) {
|
|
960
|
-
const value = at[source];
|
|
961
|
-
const mark = chosen?.from === source ? green('*') : ' ';
|
|
962
|
-
note(` ${mark} ${SOURCE_LABELS[source].padEnd(26)} ${value ?? dim('not set')}`);
|
|
963
|
-
}
|
|
964
|
-
if (!chosen) {
|
|
965
|
-
note();
|
|
966
|
-
note(dim('set one: zen meta model <provider>/<id>'));
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
async function set(ctx, values, project, ref) {
|
|
970
|
-
if (!values.force) {
|
|
971
|
-
await vet(ctx, ref);
|
|
972
|
-
}
|
|
973
|
-
if (values.local) {
|
|
974
|
-
if (!project) {
|
|
975
|
-
throw usageError('--local needs a project', 'run it inside one, or drop --local');
|
|
976
|
-
}
|
|
977
|
-
await writeLocal(project.dir, ref);
|
|
978
|
-
if (!ctx.json) {
|
|
979
|
-
note(dim(`${MODEL_ENV}=${ref} in ${project.name}/.env`));
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
else {
|
|
983
|
-
const file = await readMeta();
|
|
984
|
-
writeMeta({ ...file, model: ref });
|
|
985
|
-
}
|
|
986
|
-
if (ctx.json) {
|
|
987
|
-
json({ model: ref, where: values.local ? '.env' : 'meta.json' });
|
|
988
|
-
}
|
|
989
|
-
else {
|
|
990
|
-
write(ref);
|
|
991
|
-
}
|
|
992
|
-
}
|
|
993
|
-
// ---------------------------------------------------------------------------
|
|
994
|
-
// Vetting a ref
|
|
995
|
-
//
|
|
996
|
-
// Naming a model is a deliberate act and the run that follows is not free, so
|
|
997
|
-
// the provider is asked one cheap question now. Without it a slip of the hand
|
|
998
|
-
// is stored happily and surfaces much later as a 404 from a vendor nobody
|
|
999
|
-
// named — `vertes/…` has no known prefix, so it would be sent whole to OpenAI.
|
|
1000
|
-
// ---------------------------------------------------------------------------
|
|
1001
|
-
async function vet(ctx, ref) {
|
|
1002
|
-
const meant = misspelledProvider(ref);
|
|
1003
|
-
if (meant) {
|
|
1004
|
-
const [head, ...rest] = ref.split('/');
|
|
1005
|
-
throw usageError(`no provider called "${head}"`, `did you mean ${meant}/${rest.join('/')}?`);
|
|
1006
|
-
}
|
|
1007
|
-
const { provider, id } = splitRef(ref);
|
|
1008
|
-
const owner = provider ?? 'openai';
|
|
1009
|
-
if (!metaCompatible(owner, id)) {
|
|
1010
|
-
throw usageError(`${owner}/${id} cannot run the meta agent: its API rejects copilot's tools`, 'pick a reasoning model, e.g. from: zen models ls --chat --best');
|
|
1011
|
-
}
|
|
1012
|
-
const store = await KeyStore.open();
|
|
1013
|
-
store.materialize();
|
|
1014
|
-
if (!gatewayOf() && !store.active(owner)) {
|
|
1015
|
-
throw credentialError(`no ${owner} key to try ${id} with`, `add one: zen key add ${owner}`);
|
|
1016
|
-
}
|
|
1017
|
-
const bar = ctx.json ? undefined : progress();
|
|
1018
|
-
bar?.update(dim(`asking ${owner} about ${id} …`));
|
|
1019
|
-
const probe = await probeModel({
|
|
1020
|
-
// The colon form, so a refusal suggests `zen models ls <provider>`.
|
|
1021
|
-
ref: `${owner}:${id}`,
|
|
1022
|
-
kind: 'model',
|
|
1023
|
-
model: probeChat(owner, id),
|
|
1024
|
-
});
|
|
1025
|
-
bar?.done();
|
|
1026
|
-
if (probe.check.state !== 'live') {
|
|
1027
|
-
const why = probe.check.detail ? ` — ${probe.check.detail}` : '';
|
|
1028
|
-
const fix = probe.check.fix ?? `see what it serves: zen models ls ${owner}`;
|
|
1029
|
-
throw credentialError(`${owner} did not answer to ${id}${why}`, `${fix}, or --force`);
|
|
1030
|
-
}
|
|
1031
|
-
if (!ctx.json) {
|
|
1032
|
-
note(dim(`${owner} answered in ${(probe.ms / 1000).toFixed(1)}s`));
|
|
1033
|
-
}
|
|
1034
|
-
}
|
|
1035
|
-
async function clear(values, project) {
|
|
1036
|
-
if (values.local) {
|
|
1037
|
-
if (!project) {
|
|
1038
|
-
throw usageError('--local needs a project');
|
|
1039
|
-
}
|
|
1040
|
-
await writeLocal(project.dir, undefined);
|
|
1041
|
-
}
|
|
1042
|
-
else {
|
|
1043
|
-
const file = await readMeta();
|
|
1044
|
-
delete file.model;
|
|
1045
|
-
writeMeta(file);
|
|
1046
|
-
}
|
|
1047
|
-
note(dim('cleared'));
|
|
1048
|
-
}
|
|
1049
|
-
async function writeLocal(dir, ref) {
|
|
1050
|
-
const { readFile, writeFile } = await import('node:fs/promises');
|
|
1051
|
-
const path = `${dir}/.env`;
|
|
1052
|
-
let text = '';
|
|
1053
|
-
try {
|
|
1054
|
-
text = await readFile(path, 'utf8');
|
|
1055
|
-
}
|
|
1056
|
-
catch {
|
|
1057
|
-
text = '';
|
|
1058
|
-
}
|
|
1059
|
-
const line = new RegExp(`^${MODEL_ENV}=.*$`, 'm');
|
|
1060
|
-
const next = line.test(text)
|
|
1061
|
-
? text.replace(line, ref ? `${MODEL_ENV}=${ref}` : '')
|
|
1062
|
-
: ref
|
|
1063
|
-
? `${text}${text.endsWith('\n') || text === '' ? '' : '\n'}${MODEL_ENV}=${ref}\n`
|
|
1064
|
-
: text;
|
|
1065
|
-
await writeFile(path, next, { mode: 0o600 });
|
|
1066
|
-
}
|
|
1067
|
-
async function pickModel(ctx) {
|
|
1068
|
-
if (!isInteractive() || ctx.json) {
|
|
1069
|
-
throw usageError('--pick needs a terminal', 'name the model instead');
|
|
1070
|
-
}
|
|
1071
|
-
const store = await KeyStore.open();
|
|
1072
|
-
store.materialize();
|
|
1073
|
-
const known = store.entries.map((e) => e.provider).filter(isProvider);
|
|
1074
|
-
if (known.length === 0 && !gatewayOf()) {
|
|
1075
|
-
throw credentialError('no keys to choose from', 'add one: zen key add openai');
|
|
1076
|
-
}
|
|
1077
|
-
const held = gatewayOf() ? [] : [...new Set(known)];
|
|
1078
|
-
const { browseModels } = await import("./models.js");
|
|
1079
|
-
const chosen = await browseModels({
|
|
1080
|
-
initial: held.length === 1 ? held[0] : undefined,
|
|
1081
|
-
role: 'chat',
|
|
1082
|
-
});
|
|
1083
|
-
if (!chosen) {
|
|
1084
|
-
throw usageError('nothing picked', 'name the model instead: zen meta model <provider>/<id>');
|
|
1085
|
-
}
|
|
1086
|
-
return `${chosen.provider}/${chosen.id}`;
|
|
1087
|
-
}
|
|
1088
|
-
//# sourceMappingURL=meta.js.map
|