@zenera/meta 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -0,0 +1,46 @@
1
+ // packages/meta/src/reporter.ts
2
+ //
3
+ // Keeps `finetune/USAGE.md` current while a meta agent session runs in a project that is being tuned.
4
+ // Main: `usageReporter(dir)` - reruns the shipped usage script on a timer and once at the end, detached.
5
+ // Used by: `command.ts` (`go()`, for run and resume) and `chat/run.ts` (`zen meta chat`).
6
+ import { spawn } from 'node:child_process';
7
+ import { existsSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ /** How often a running meta agent rewrites the fine-tuning's usage report. */
10
+ const REPORT_EVERY_MS = 5 * 60_000;
11
+ /**
12
+ * Rewrites `finetune/USAGE.md` on a timer and once more at the end, when the
13
+ * project is being tuned. Detached and silent: the report is a by-product, and
14
+ * neither its time nor its failure belongs to the run.
15
+ */
16
+ export function usageReporter(dir) {
17
+ const script = join(dir, '.github/skills/zen-finetune/scripts/usage.mjs');
18
+ if (!existsSync(join(dir, 'finetune')) || !existsSync(script)) {
19
+ return { stop: () => undefined };
20
+ }
21
+ let running = false;
22
+ const refresh = () => {
23
+ if (running) {
24
+ return;
25
+ }
26
+ running = true;
27
+ const child = spawn(process.execPath, [script, '-q'], {
28
+ cwd: dir,
29
+ stdio: 'ignore',
30
+ detached: true,
31
+ });
32
+ child.on('exit', () => (running = false));
33
+ child.on('error', () => (running = false));
34
+ child.unref();
35
+ };
36
+ const timer = setInterval(refresh, REPORT_EVERY_MS);
37
+ timer.unref();
38
+ return {
39
+ stop: () => {
40
+ clearInterval(timer);
41
+ running = false;
42
+ refresh();
43
+ },
44
+ };
45
+ }
46
+ //# sourceMappingURL=reporter.js.map
package/dist/wire.d.ts CHANGED
@@ -27,6 +27,8 @@ export interface Wiring {
27
27
  location: string;
28
28
  keyFile: string;
29
29
  };
30
+ /** a service account's key file, when the key command mints its token from one */
31
+ keyFile?: string;
30
32
  }
31
33
  /** Where the relay's url goes once it is listening. */
32
34
  export declare const RELAY_URL = "http://127.0.0.1:<relay>";
package/dist/wire.js CHANGED
@@ -115,7 +115,14 @@ export function wire(store, entry, id) {
115
115
  env.COPILOT_PROVIDER_API_KEY = store.reveal(entry);
116
116
  secret.push('COPILOT_PROVIDER_API_KEY');
117
117
  }
118
- return { provider, model: env.COPILOT_PROVIDER_WIRE_MODEL ?? id, env, secret, warnings };
118
+ return {
119
+ provider,
120
+ model: env.COPILOT_PROVIDER_WIRE_MODEL ?? id,
121
+ env,
122
+ secret,
123
+ warnings,
124
+ ...(entry.holds === 'file' ? { keyFile: store.fileOf(entry) } : {}),
125
+ };
119
126
  }
120
127
  /**
121
128
  * Through a gateway: one virtual key, and Bifrost's OpenAI or Anthropic drop-in,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/meta",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "The meta agent for zen: GitHub Copilot over a zen project on your own keys, plus the dataset and fine-tuning loop.",
5
5
  "keywords": [
6
6
  "agents",
@@ -43,10 +43,12 @@
43
43
  "prepack": "tsc -b"
44
44
  },
45
45
  "dependencies": {
46
- "@zenera/cli": "^1.3.0",
47
- "@zenera/engine": "^1.3.0",
48
- "@zenera/neo": "^1.3.0",
49
- "@zenera/view": "^1.3.0",
46
+ "@github/copilot-sdk": "^1.0.32",
47
+ "@inkjs/ui": "^2.0.0",
48
+ "@zenera/cli": "^1.3.2",
49
+ "@zenera/engine": "^1.3.2",
50
+ "@zenera/neo": "^1.3.2",
51
+ "@zenera/view": "^1.3.2",
50
52
  "google-auth-library": "^10.0.0",
51
53
  "ink": "^7.1.1",
52
54
  "react": "^19.2.8",