@zenera/meta 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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>;
package/dist/launch.js CHANGED
@@ -1,12 +1,15 @@
1
1
  // packages/meta/src/launch.ts
2
2
  //
3
3
  // Running GitHub Copilot CLI: finding it, launching it, and reading its JSONL into an answer and a narration.
4
- // Main: `launch(opts)`; also `locate`, `copilotVersion`, `absorb`, `openLog`, `recordSession`/`lastSession`,
4
+ // Main: `launch(opts)`; also `locate`, `copilotVersion`, `sdkVersion`, `absorb`, `openLog`, `recordSession`/`lastSession`,
5
5
  // and the resume policy (`transient`, `resumeDelayMs`, `RESUME_PROMPT`).
6
- // Used by: `command.ts` (`go()` for `zen meta run|resume`, and the `subsystems` hook for `zen version`).
6
+ // Used by: `command.ts` (`go()` for `zen meta run|resume`, and the `subsystems` hook for `zen version`) and
7
+ // `chat/` (the log, the folding and the resume policy).
7
8
  import { execFile, spawn as nodeSpawn } from 'node:child_process';
8
9
  import { createWriteStream, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
9
11
  import { createInterface } from 'node:readline';
12
+ import { fileURLToPath } from 'node:url';
10
13
  import { cut, dim, duration, formatInline, plain } from "./host.js";
11
14
  import { FRAME_MS, windowSink } from "./sink.js";
12
15
  /**
@@ -40,6 +43,33 @@ function onPath(cmd) {
40
43
  const dirs = (process.env.PATH ?? '').split(':').filter(Boolean);
41
44
  return dirs.some((d) => existsSync(`${d}/${cmd}`));
42
45
  }
46
+ /**
47
+ * The Copilot SDK `zen meta chat` runs on, with the runtime it bundles. Its
48
+ * manifest is not exported, so it is found by walking up from its entry point.
49
+ */
50
+ export function sdkVersion() {
51
+ const name = 'copilot-sdk';
52
+ try {
53
+ let dir = dirname(fileURLToPath(import.meta.resolve('@github/copilot-sdk')));
54
+ for (; dir !== dirname(dir); dir = dirname(dir)) {
55
+ const file = join(dir, 'package.json');
56
+ if (existsSync(file)) {
57
+ const pkg = JSON.parse(readFileSync(file, 'utf8'));
58
+ if (pkg.name === '@github/copilot-sdk') {
59
+ return {
60
+ name,
61
+ version: pkg.version,
62
+ detail: 'zen meta chat, its runtime bundled',
63
+ };
64
+ }
65
+ }
66
+ }
67
+ }
68
+ catch {
69
+ // Not installed: an optional dependency that failed, or a pruned install.
70
+ }
71
+ return { name, detail: 'not installed - zen meta chat needs it' };
72
+ }
43
73
  /**
44
74
  * `<project>/.tmp/logs/meta.<when>[-<session>].log`, opened for append. The
45
75
  * session keeps runs started in the same second - a tuning loop's - apart.
@@ -271,9 +301,15 @@ export function transient(out) {
271
301
  if (status === 408 || status >= 500) {
272
302
  return `the provider failed (${status})`;
273
303
  }
274
- if (/timed out|ECONNRESET|socket hang up/i.test(String(data.message ?? ''))) {
304
+ const message = String(data.message ?? '');
305
+ if (/timed out|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|fetch failed/i.test(message)) {
275
306
  return 'the connection failed';
276
307
  }
308
+ // `zen key token` mints a token per request over the network; one that
309
+ // failed once in a session that has been calling it is a blip, not a bad key.
310
+ if (/API_KEY_COMMAND exited/.test(message)) {
311
+ return 'the key command failed';
312
+ }
277
313
  if (status === 400 && injected(out.events.slice(0, at))) {
278
314
  return 'refused a tool call copilot made itself (400)';
279
315
  }
@@ -0,0 +1,36 @@
1
+ import * as Projects from '@zenera/engine';
2
+ import { type Provider } from '@zenera/engine';
3
+ import { type Binary } from './launch.ts';
4
+ import type { ModelChoice } from './model.ts';
5
+ import { type Wiring } from './wire.ts';
6
+ /** The flags that decide the model, the key and the session. */
7
+ export interface Selection {
8
+ provider?: string;
9
+ model?: string;
10
+ resume?: string;
11
+ continue?: boolean;
12
+ 'session-id'?: string;
13
+ }
14
+ export interface Prepared<F extends Selection> {
15
+ /** the flags, with `resume` dropped when the session cannot be carried to this model */
16
+ values: F;
17
+ owner: Provider;
18
+ chosen: ModelChoice;
19
+ gateway: boolean;
20
+ wiring: Wiring;
21
+ binary: Binary;
22
+ /** named up front, so a run killed before copilot reports its id can still be resumed */
23
+ session?: string;
24
+ }
25
+ /**
26
+ * `prompt` is what the session will be told first: a bare resume (the
27
+ * `RESUME_PROMPT`) cannot become a new session, since it would have nothing to
28
+ * continue, so a model change refuses it instead of starting over.
29
+ */
30
+ export declare function prepare<F extends Selection>(values: F, project: Projects.Project, prompt?: string): Promise<Prepared<F>>;
31
+ /** What a session says on stderr before it starts: the warnings, then which model on which key. */
32
+ export declare function announce(p: Prepared<Selection>, project: Projects.Project): void;
33
+ /** The project's own `model:`, with a `models:` alias resolved to what it names. */
34
+ export declare function projectModel(dir: string): string | undefined;
35
+ export declare function asProvider(name: string): Provider;
36
+ //# sourceMappingURL=prepare.d.ts.map
@@ -0,0 +1,131 @@
1
+ // packages/meta/src/prepare.ts
2
+ //
3
+ // Everything a meta agent session needs before it starts, shared by `zen meta run` and `zen meta chat`.
4
+ // Main: `prepare(values, project)` - load the project's .env, open the keyring, choose the model, wire the key,
5
+ // settle the session id (refusing a resume across models). Also `announce` (the stderr lines a run opens with),
6
+ // `projectModel` (agents.yaml's `model:`) and `asProvider`.
7
+ // Used by: `command.ts` (`go()` for run/resume, `chat()`, and `model()` for `projectModel`).
8
+ 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 { randomUUID } from 'node:crypto';
12
+ import { credentialError, cyan, dim, note, splitRef, usageError, warn } from "./host.js";
13
+ import { locate, RESUME_PROMPT } from "./launch.js";
14
+ import { chooseModel, fallbackRef, misspelledProvider, MODEL_ENV, readMeta } from "./model.js";
15
+ import { sameModel, sessionModel } from "./tokens.js";
16
+ import { providersWarning, wire, wireGateway } from "./wire.js";
17
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ /**
19
+ * `prompt` is what the session will be told first: a bare resume (the
20
+ * `RESUME_PROMPT`) cannot become a new session, since it would have nothing to
21
+ * continue, so a model change refuses it instead of starting over.
22
+ */
23
+ export async function prepare(values, project, prompt) {
24
+ const fresh = values['session-id'];
25
+ if (fresh !== undefined) {
26
+ if (values.resume || values.continue) {
27
+ throw usageError('--session-id starts a new session', 'drop --resume / --continue');
28
+ }
29
+ if (!UUID.test(fresh)) {
30
+ throw usageError(`--session-id must be a UUID, not ${fresh}`, 'try: uuidgen');
31
+ }
32
+ }
33
+ const shell = process.env[MODEL_ENV];
34
+ loadProjectEnv(project.dir);
35
+ ensureHome();
36
+ const store = await KeyStore.open();
37
+ store.materialize();
38
+ // After materialize: a keyring in bifrost mode is what sets the url.
39
+ const gateway = gatewayOf();
40
+ const only = values.provider ? asProvider(values.provider) : undefined;
41
+ // The fallback can cost a gateway listing, so it is only looked up when nothing else answers.
42
+ const chosen = chooseModel({
43
+ flag: values.model,
44
+ shell,
45
+ env: process.env[MODEL_ENV],
46
+ stored: (await readMeta()).model,
47
+ project: projectModel(project.dir),
48
+ }) ?? chooseModel({ fallback: await fallbackRef(store, only, gateway !== undefined) });
49
+ if (!chosen) {
50
+ if (only) {
51
+ throw credentialError(`no ${only} key`, `add one: zen key add ${only}`);
52
+ }
53
+ throw credentialError('no model for the meta agent', store.entries.length === 0
54
+ ? 'add a key: zen key add openai'
55
+ : 'set one: zen meta model <provider>/<id>');
56
+ }
57
+ const { provider, id } = splitRef(chosen.ref);
58
+ const owner = only ?? provider ?? 'openai';
59
+ const meant = misspelledProvider(chosen.ref);
60
+ if (meant && !only) {
61
+ warn(`${chosen.ref} names no provider — did you mean ${meant}/${id}?`);
62
+ }
63
+ const entry = gateway ? undefined : store.active(owner);
64
+ if (!gateway && !entry) {
65
+ throw credentialError(`no ${owner} key`, `add one: zen key add ${owner}`);
66
+ }
67
+ const wiring = gateway ? wireGateway(gateway, owner, id) : wire(store, entry, id);
68
+ // Copilot cannot carry a session to another model: the resume fails on the first call.
69
+ const ran = values.resume ? sessionModel(values.resume) : undefined;
70
+ if (values.resume && ran && !sameModel(ran, wiring.model)) {
71
+ if (prompt === RESUME_PROMPT) {
72
+ 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`);
73
+ }
74
+ warn(`session ${values.resume} ran on ${ran}; the meta model is now ${wiring.model}, so this starts a new session`);
75
+ values = { ...values, resume: undefined };
76
+ }
77
+ return {
78
+ values,
79
+ owner,
80
+ chosen,
81
+ gateway: gateway !== undefined,
82
+ wiring,
83
+ binary: locate(),
84
+ session: values.resume ?? (values.continue ? undefined : (fresh ?? randomUUID())),
85
+ };
86
+ }
87
+ /** What a session says on stderr before it starts: the warnings, then which model on which key. */
88
+ export function announce(p, project) {
89
+ for (const line of p.wiring.warnings) {
90
+ warn(line);
91
+ }
92
+ const competing = providersWarning();
93
+ if (competing) {
94
+ warn(competing);
95
+ }
96
+ if (p.chosen.from === 'default') {
97
+ const what = p.gateway
98
+ ? 'the best model the gateway serves'
99
+ : `the best ${p.owner} model zen knows of`;
100
+ note(dim(`no model set — using ${p.chosen.ref}, ${what}`));
101
+ note(dim('set another: zen meta model <provider>/<id>'));
102
+ }
103
+ note(cyan(`${p.owner} · ${p.wiring.model} · ${project.name}`));
104
+ }
105
+ /** The project's own `model:`, with a `models:` alias resolved to what it names. */
106
+ export function projectModel(dir) {
107
+ try {
108
+ const { config } = readProjectConfig(dir);
109
+ const top = typeof config.model === 'string' ? config.model : undefined;
110
+ const alias = top ? config.models?.[top] : undefined;
111
+ if (!alias) {
112
+ return top;
113
+ }
114
+ if (typeof alias === 'string') {
115
+ return alias;
116
+ }
117
+ const owner = PROVIDERS.find((p) => p === alias.provider);
118
+ return owner ? `${owner}/${alias.model}` : alias.model;
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ }
124
+ export function asProvider(name) {
125
+ const owner = assertOwner(name);
126
+ if (!isProvider(owner)) {
127
+ throw usageError(`${name} is not a model provider`);
128
+ }
129
+ return owner;
130
+ }
131
+ //# sourceMappingURL=prepare.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Rewrites `finetune/USAGE.md` on a timer and once more at the end, when the
3
+ * project is being tuned. Detached and silent: the report is a by-product, and
4
+ * neither its time nor its failure belongs to the run.
5
+ */
6
+ export declare function usageReporter(dir: string): {
7
+ stop(): void;
8
+ };
9
+ //# sourceMappingURL=reporter.d.ts.map