@zenera/meta 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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>;
@@ -40,7 +49,8 @@ export interface Log {
40
49
  readonly answerPath: string;
41
50
  line(text: string): void;
42
51
  saveAnswer(text: string): void;
43
- close(): void;
52
+ /** resolves once every line is on disk */
53
+ close(): Promise<void>;
44
54
  }
45
55
  /**
46
56
  * `<project>/.tmp/logs/meta.<when>[-<session>].log`, opened for append. The
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.
@@ -63,9 +93,7 @@ export function openLog(dir, now = new Date(), session) {
63
93
  saveAnswer: (text) => {
64
94
  writeFileSync(answerPath, text.endsWith('\n') ? text : `${text}\n`);
65
95
  },
66
- close: () => {
67
- file.end();
68
- },
96
+ close: () => new Promise((done) => file.end(done)),
69
97
  };
70
98
  }
71
99
  /** The project's last meta session, so `zen meta resume` needs no id. */
@@ -271,9 +299,15 @@ export function transient(out) {
271
299
  if (status === 408 || status >= 500) {
272
300
  return `the provider failed (${status})`;
273
301
  }
274
- if (/timed out|ECONNRESET|socket hang up/i.test(String(data.message ?? ''))) {
302
+ const message = String(data.message ?? '');
303
+ if (/timed out|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|fetch failed/i.test(message)) {
275
304
  return 'the connection failed';
276
305
  }
306
+ // `zen key token` mints a token per request over the network; one that
307
+ // failed once in a session that has been calling it is a blip, not a bad key.
308
+ if (/API_KEY_COMMAND exited/.test(message)) {
309
+ return 'the key command failed';
310
+ }
277
311
  if (status === 400 && injected(out.events.slice(0, at))) {
278
312
  return 'refused a tool call copilot made itself (400)';
279
313
  }
@@ -0,0 +1,45 @@
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
+ /**
32
+ * The editor's files, rewritten before the agent reads them — the same refresh
33
+ * `zen open` does, for the same reason. `.github/` is the brief this agent works
34
+ * from and the prompts it is offered, and it describes the version of `zen` in
35
+ * hand; a project scaffolded by an older one would otherwise be briefed on a
36
+ * runtime that has moved. A failure is narrated, not raised: a read-only
37
+ * checkout is no reason to refuse to answer a question.
38
+ */
39
+ export declare function refreshEditor(project: Projects.Project): void;
40
+ /** What a session says on stderr before it starts: the warnings, then which model on which key. */
41
+ export declare function announce(p: Prepared<Selection>, project: Projects.Project): void;
42
+ /** The project's own `model:`, with a `models:` alias resolved to what it names. */
43
+ export declare function projectModel(dir: string): string | undefined;
44
+ export declare function asProvider(name: string): Provider;
45
+ //# sourceMappingURL=prepare.d.ts.map
@@ -0,0 +1,150 @@
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
+ // `refreshEditor` (rewrite the project's editor files), `projectModel` (agents.yaml's `model:`) and `asProvider`.
7
+ // Used by: `command.ts` (`go()` for run/resume, and `model()` for `projectModel`) and `chat/open.ts`.
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, editorFiles, 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
+ /**
88
+ * The editor's files, rewritten before the agent reads them — the same refresh
89
+ * `zen open` does, for the same reason. `.github/` is the brief this agent works
90
+ * from and the prompts it is offered, and it describes the version of `zen` in
91
+ * hand; a project scaffolded by an older one would otherwise be briefed on a
92
+ * runtime that has moved. A failure is narrated, not raised: a read-only
93
+ * checkout is no reason to refuse to answer a question.
94
+ */
95
+ export function refreshEditor(project) {
96
+ try {
97
+ const written = editorFiles(project.dir);
98
+ if (written.length) {
99
+ note(dim(`refreshed ${written.length} editor files in ${project.name}`));
100
+ }
101
+ }
102
+ catch (err) {
103
+ warn(`could not refresh the editor files — ${err.message}`);
104
+ }
105
+ }
106
+ /** What a session says on stderr before it starts: the warnings, then which model on which key. */
107
+ export function announce(p, project) {
108
+ for (const line of p.wiring.warnings) {
109
+ warn(line);
110
+ }
111
+ const competing = providersWarning();
112
+ if (competing) {
113
+ warn(competing);
114
+ }
115
+ if (p.chosen.from === 'default') {
116
+ const what = p.gateway
117
+ ? 'the best model the gateway serves'
118
+ : `the best ${p.owner} model zen knows of`;
119
+ note(dim(`no model set — using ${p.chosen.ref}, ${what}`));
120
+ note(dim('set another: zen meta model <provider>/<id>'));
121
+ }
122
+ note(cyan(`${p.owner} · ${p.wiring.model} · ${project.name}`));
123
+ }
124
+ /** The project's own `model:`, with a `models:` alias resolved to what it names. */
125
+ export function projectModel(dir) {
126
+ try {
127
+ const { config } = readProjectConfig(dir);
128
+ const top = typeof config.model === 'string' ? config.model : undefined;
129
+ const alias = top ? config.models?.[top] : undefined;
130
+ if (!alias) {
131
+ return top;
132
+ }
133
+ if (typeof alias === 'string') {
134
+ return alias;
135
+ }
136
+ const owner = PROVIDERS.find((p) => p === alias.provider);
137
+ return owner ? `${owner}/${alias.model}` : alias.model;
138
+ }
139
+ catch {
140
+ return undefined;
141
+ }
142
+ }
143
+ export function asProvider(name) {
144
+ const owner = assertOwner(name);
145
+ if (!isProvider(owner)) {
146
+ throw usageError(`${name} is not a model provider`);
147
+ }
148
+ return owner;
149
+ }
150
+ //# 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.1",
3
+ "version": "1.3.3",
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",
@@ -28,6 +28,10 @@
28
28
  "types": "./dist/command.d.ts",
29
29
  "default": "./dist/command.js"
30
30
  },
31
+ "./chat": {
32
+ "types": "./dist/chat/index.d.ts",
33
+ "default": "./dist/chat/index.js"
34
+ },
31
35
  "./package.json": "./package.json"
32
36
  },
33
37
  "files": [
@@ -43,10 +47,12 @@
43
47
  "prepack": "tsc -b"
44
48
  },
45
49
  "dependencies": {
46
- "@zenera/cli": "^1.3.1",
47
- "@zenera/engine": "^1.3.1",
48
- "@zenera/neo": "^1.3.1",
49
- "@zenera/view": "^1.3.1",
50
+ "@github/copilot-sdk": "^1.0.32",
51
+ "@inkjs/ui": "^2.0.0",
52
+ "@zenera/cli": "^1.3.3",
53
+ "@zenera/engine": "^1.3.3",
54
+ "@zenera/neo": "^1.3.3",
55
+ "@zenera/view": "^1.3.3",
50
56
  "google-auth-library": "^10.0.0",
51
57
  "ink": "^7.1.1",
52
58
  "react": "^19.2.8",