@zenera/meta 0.0.0-stage → 1.3.0

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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/dist/command.d.ts +5 -0
  4. package/dist/command.js +1086 -0
  5. package/dist/dataset/anchors.d.ts +41 -0
  6. package/dist/dataset/anchors.js +239 -0
  7. package/dist/dataset/changes.d.ts +36 -0
  8. package/dist/dataset/changes.js +319 -0
  9. package/dist/dataset/command.d.ts +17 -0
  10. package/dist/dataset/command.js +1011 -0
  11. package/dist/dataset/drift.d.ts +33 -0
  12. package/dist/dataset/drift.js +71 -0
  13. package/dist/dataset/export.d.ts +26 -0
  14. package/dist/dataset/export.js +51 -0
  15. package/dist/dataset/index.d.ts +2 -0
  16. package/dist/dataset/index.js +2 -0
  17. package/dist/dataset/sample.d.ts +50 -0
  18. package/dist/dataset/sample.js +197 -0
  19. package/dist/dataset/schema.d.ts +33 -0
  20. package/dist/dataset/schema.js +216 -0
  21. package/dist/dataset/store.d.ts +35 -0
  22. package/dist/dataset/store.js +177 -0
  23. package/dist/dataset/types.d.ts +127 -0
  24. package/dist/dataset/types.js +39 -0
  25. package/dist/finetune/analyze-brief.d.ts +26 -0
  26. package/dist/finetune/analyze-brief.js +131 -0
  27. package/dist/finetune/apply-brief.d.ts +23 -0
  28. package/dist/finetune/apply-brief.js +247 -0
  29. package/dist/finetune/brief.d.ts +45 -0
  30. package/dist/finetune/brief.js +158 -0
  31. package/dist/finetune/children.d.ts +8 -0
  32. package/dist/finetune/children.js +76 -0
  33. package/dist/finetune/command.d.ts +30 -0
  34. package/dist/finetune/command.js +520 -0
  35. package/dist/finetune/cost.d.ts +46 -0
  36. package/dist/finetune/cost.js +105 -0
  37. package/dist/finetune/failure.d.ts +15 -0
  38. package/dist/finetune/failure.js +26 -0
  39. package/dist/finetune/feedback.d.ts +57 -0
  40. package/dist/finetune/feedback.js +104 -0
  41. package/dist/finetune/improvements.d.ts +98 -0
  42. package/dist/finetune/improvements.js +501 -0
  43. package/dist/finetune/index.d.ts +2 -0
  44. package/dist/finetune/index.js +2 -0
  45. package/dist/finetune/journal.d.ts +35 -0
  46. package/dist/finetune/journal.js +135 -0
  47. package/dist/finetune/live.d.ts +84 -0
  48. package/dist/finetune/live.js +272 -0
  49. package/dist/finetune/loop.d.ts +3 -0
  50. package/dist/finetune/loop.js +163 -0
  51. package/dist/finetune/memories.d.ts +47 -0
  52. package/dist/finetune/memories.js +171 -0
  53. package/dist/finetune/next-case.d.ts +18 -0
  54. package/dist/finetune/next-case.js +47 -0
  55. package/dist/finetune/recheck.d.ts +58 -0
  56. package/dist/finetune/recheck.js +311 -0
  57. package/dist/finetune/report.d.ts +40 -0
  58. package/dist/finetune/report.js +1397 -0
  59. package/dist/finetune/retry.d.ts +24 -0
  60. package/dist/finetune/retry.js +96 -0
  61. package/dist/finetune/system.d.ts +27 -0
  62. package/dist/finetune/system.js +132 -0
  63. package/dist/finetune/train.d.ts +43 -0
  64. package/dist/finetune/train.js +425 -0
  65. package/dist/finetune/tui.d.ts +16 -0
  66. package/dist/finetune/tui.js +316 -0
  67. package/dist/finetune/tuning.d.ts +193 -0
  68. package/dist/finetune/tuning.js +308 -0
  69. package/dist/finetune/usage.d.ts +66 -0
  70. package/dist/finetune/usage.js +260 -0
  71. package/dist/finetune/view.d.ts +9 -0
  72. package/dist/finetune/view.js +27 -0
  73. package/dist/host.d.ts +2 -0
  74. package/dist/host.js +14 -0
  75. package/dist/index.d.ts +10 -0
  76. package/dist/index.js +15 -0
  77. package/dist/launch.d.ts +90 -0
  78. package/dist/launch.js +310 -0
  79. package/dist/model.d.ts +61 -0
  80. package/dist/model.js +146 -0
  81. package/dist/prompts.d.ts +23 -0
  82. package/dist/prompts.js +84 -0
  83. package/dist/relay.d.ts +20 -0
  84. package/dist/relay.js +123 -0
  85. package/dist/sink.d.ts +61 -0
  86. package/dist/sink.js +198 -0
  87. package/dist/tokens.d.ts +52 -0
  88. package/dist/tokens.js +226 -0
  89. package/dist/wire.d.ts +51 -0
  90. package/dist/wire.js +159 -0
  91. package/package.json +54 -5
@@ -0,0 +1,84 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { usageError } from "./host.js";
4
+ // ---------------------------------------------------------------------------
5
+ // Stored commands
6
+ //
7
+ // The editor offers `.github/skills/<name>/SKILL.md` as `/name`. The `zen-*`
8
+ // skills are reference the model loads on its own (`user-invocable: false`);
9
+ // the rest are commands somebody types (`disable-model-invocation: true`), and
10
+ // those are what `zen meta run /<name>` runs. Copilot would expand `/name`
11
+ // itself, but reading the file and handing over its body works the same with
12
+ // every model and leaves room for `--prompt-file` after it.
13
+ //
14
+ // `.github/prompts/*.prompt.md` is the format these used to be in. Copilot has
15
+ // dropped it, but a project may still have prompt files of its own, so one
16
+ // whose name no skill takes is still run.
17
+ // ---------------------------------------------------------------------------
18
+ export const SKILL_DIR = '.github/skills';
19
+ export const PROMPT_DIR = '.github/prompts';
20
+ const PROMPT_SUFFIX = '.prompt.md';
21
+ /** `/project-review`, `project-review`, `project-review.prompt.md` or a path. */
22
+ export function promptPath(dir, name) {
23
+ const bare = name.replace(/^\//, '');
24
+ if (bare.includes('/') || bare.endsWith('.md')) {
25
+ return `${dir}/${bare}`;
26
+ }
27
+ const skill = `${dir}/${SKILL_DIR}/${bare}/SKILL.md`;
28
+ const legacy = `${dir}/${PROMPT_DIR}/${bare}${PROMPT_SUFFIX}`;
29
+ return !existsSync(skill) && existsSync(legacy) ? legacy : skill;
30
+ }
31
+ /**
32
+ * Frontmatter is the editor's business — `name`, `argument-hint`, the
33
+ * invocation switches — and none of it means anything once the body is the
34
+ * prompt, so only the body is sent. `description` is kept for the one line of
35
+ * narration that says which command is running.
36
+ */
37
+ export function readPrompt(path, name, text) {
38
+ let body = text;
39
+ let description;
40
+ let invocable = true;
41
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
42
+ if (match) {
43
+ body = text.slice(match[0].length);
44
+ const found = /^description:\s*(.+)$/m.exec(match[1]);
45
+ description = found?.[1].trim().replace(/^['"]|['"]$/g, '');
46
+ invocable = !/^user-invocable:\s*['"]?false['"]?\s*$/m.test(match[1]);
47
+ }
48
+ return { name, path, description, invocable, body: body.trim() };
49
+ }
50
+ export async function loadPrompt(dir, name) {
51
+ const path = promptPath(dir, name);
52
+ if (!existsSync(path)) {
53
+ const known = await listPrompts(dir);
54
+ throw usageError(`no command named ${name.replace(/^\//, '')}`, known.length > 0
55
+ ? `try: ${known.map((p) => `/${p}`).join(', ')}`
56
+ : `put one in ${SKILL_DIR}/<name>/SKILL.md`);
57
+ }
58
+ return readPrompt(path, name.replace(/^\//, ''), await readFile(path, 'utf8'));
59
+ }
60
+ /** The commands a person may type: every skill not marked for the model only, and any legacy prompt file. */
61
+ export async function listPrompts(dir) {
62
+ const names = new Set();
63
+ for (const entry of entries(`${dir}/${SKILL_DIR}`)) {
64
+ const path = `${dir}/${SKILL_DIR}/${entry}/SKILL.md`;
65
+ if (existsSync(path) && readPrompt(path, entry, readFileSync(path, 'utf8')).invocable) {
66
+ names.add(entry);
67
+ }
68
+ }
69
+ for (const entry of entries(`${dir}/${PROMPT_DIR}`)) {
70
+ if (entry.endsWith(PROMPT_SUFFIX)) {
71
+ names.add(entry.slice(0, -PROMPT_SUFFIX.length));
72
+ }
73
+ }
74
+ return [...names].sort();
75
+ }
76
+ function entries(path) {
77
+ try {
78
+ return readdirSync(path);
79
+ }
80
+ catch {
81
+ return [];
82
+ }
83
+ }
84
+ //# sourceMappingURL=prompts.js.map
@@ -0,0 +1,20 @@
1
+ export interface Relay {
2
+ url: string;
3
+ close(): Promise<void>;
4
+ }
5
+ export interface RelaySpec {
6
+ /** the per-session secret copilot must present; anything else on the machine is refused */
7
+ key: string;
8
+ /** `https://…/v1/projects/<project>/locations/<location>` */
9
+ base: string;
10
+ token: () => Promise<string>;
11
+ }
12
+ export interface VertexRelaySpec {
13
+ key: string;
14
+ project: string;
15
+ location: string;
16
+ keyFile: string;
17
+ }
18
+ export declare function startVertexRelay(spec: VertexRelaySpec): Promise<Relay>;
19
+ export declare function startRelay(spec: RelaySpec): Promise<Relay>;
20
+ //# sourceMappingURL=relay.d.ts.map
package/dist/relay.js ADDED
@@ -0,0 +1,123 @@
1
+ import { vertexEndpoint } from '@zenera/neo';
2
+ import { GoogleAuth } from 'google-auth-library';
3
+ import { timingSafeEqual } from 'node:crypto';
4
+ import { createServer } from 'node:http';
5
+ import { Readable } from 'node:stream';
6
+ const VERTEX_VERSION = 'vertex-2023-10-16';
7
+ export async function startVertexRelay(spec) {
8
+ const auth = new GoogleAuth({
9
+ keyFile: spec.keyFile,
10
+ scopes: ['https://www.googleapis.com/auth/cloud-platform'],
11
+ });
12
+ const at = vertexEndpoint({
13
+ project: spec.project,
14
+ location: spec.location,
15
+ token: async () => {
16
+ const token = await auth.getAccessToken();
17
+ if (!token) {
18
+ throw new Error(`${spec.keyFile} minted no access token`);
19
+ }
20
+ return token;
21
+ },
22
+ });
23
+ return startRelay({ key: spec.key, base: at.base, token: at.token });
24
+ }
25
+ export async function startRelay(spec) {
26
+ const server = createServer((req, res) => {
27
+ relay(spec, req, res).catch((err) => {
28
+ fail(res, 502, 'api_error', `relay to vertex: ${err.message}`);
29
+ });
30
+ });
31
+ await new Promise((done, reject) => {
32
+ server.once('error', reject);
33
+ server.listen(0, '127.0.0.1', done);
34
+ });
35
+ const { port } = server.address();
36
+ return {
37
+ url: `http://127.0.0.1:${port}`,
38
+ close: () => new Promise((done) => {
39
+ server.closeAllConnections();
40
+ server.close(() => done());
41
+ }),
42
+ };
43
+ }
44
+ async function relay(spec, req, res) {
45
+ if (!authorized(spec.key, req)) {
46
+ fail(res, 401, 'authentication_error', 'not this session’s relay key');
47
+ return;
48
+ }
49
+ const path = new URL(req.url ?? '/', 'http://relay').pathname;
50
+ const counting = path === '/v1/messages/count_tokens';
51
+ if (req.method !== 'POST' || (path !== '/v1/messages' && !counting)) {
52
+ fail(res, 404, 'not_found_error', `vertex serves no ${req.method} ${path} for Claude`);
53
+ return;
54
+ }
55
+ let parsed;
56
+ try {
57
+ parsed = JSON.parse(await readBody(req));
58
+ }
59
+ catch {
60
+ fail(res, 400, 'invalid_request_error', 'the body is not JSON');
61
+ return;
62
+ }
63
+ const { model, ...rest } = parsed;
64
+ if (!model) {
65
+ fail(res, 400, 'invalid_request_error', 'no model in the body');
66
+ return;
67
+ }
68
+ const url = counting
69
+ ? `${spec.base}/publishers/anthropic/models/count-tokens:rawPredict`
70
+ : `${spec.base}/publishers/anthropic/models/${encodeURIComponent(model)}:${rest.stream ? 'streamRawPredict' : 'rawPredict'}`;
71
+ const body = counting ? parsed : { ...rest, anthropic_version: VERTEX_VERSION };
72
+ const abort = new AbortController();
73
+ res.on('close', () => {
74
+ if (!res.writableFinished) {
75
+ abort.abort();
76
+ }
77
+ });
78
+ const beta = req.headers['anthropic-beta'];
79
+ const upstream = await fetch(url, {
80
+ method: 'POST',
81
+ headers: {
82
+ authorization: `Bearer ${await spec.token()}`,
83
+ 'content-type': 'application/json',
84
+ ...(typeof beta === 'string' ? { 'anthropic-beta': beta } : {}),
85
+ },
86
+ body: JSON.stringify(body),
87
+ signal: abort.signal,
88
+ });
89
+ res.writeHead(upstream.status, {
90
+ 'content-type': upstream.headers.get('content-type') ?? 'application/json',
91
+ });
92
+ if (!upstream.body) {
93
+ res.end();
94
+ return;
95
+ }
96
+ Readable.fromWeb(upstream.body)
97
+ .on('error', () => res.destroy())
98
+ .pipe(res);
99
+ }
100
+ function authorized(key, req) {
101
+ const header = req.headers['x-api-key'] ?? req.headers.authorization?.replace(/^Bearer /i, '');
102
+ const given = Buffer.from(typeof header === 'string' ? header : '');
103
+ const wanted = Buffer.from(key);
104
+ return given.length === wanted.length && timingSafeEqual(given, wanted);
105
+ }
106
+ function readBody(req) {
107
+ return new Promise((done, reject) => {
108
+ const chunks = [];
109
+ req.on('data', (c) => chunks.push(c));
110
+ req.on('end', () => done(Buffer.concat(chunks).toString('utf8')));
111
+ req.on('error', reject);
112
+ });
113
+ }
114
+ /** Anthropic's error shape, so copilot reports it as it would a direct call. */
115
+ function fail(res, code, type, message) {
116
+ if (res.headersSent) {
117
+ res.destroy();
118
+ return;
119
+ }
120
+ res.writeHead(code, { 'content-type': 'application/json' });
121
+ res.end(JSON.stringify({ type: 'error', error: { type, message } }));
122
+ }
123
+ //# sourceMappingURL=relay.js.map
package/dist/sink.d.ts ADDED
@@ -0,0 +1,61 @@
1
+ export interface Sink {
2
+ answer(text: string): void;
3
+ narrate(line: string): void;
4
+ warn(line: string): void;
5
+ /** Kept by the log, never shown: the step-by-step nobody reads while it runs. */
6
+ detail?(line: string): void;
7
+ /** A transient last row, replaced each time and never kept. '' removes it. */
8
+ status?(line: string): void;
9
+ /** Called once when the run ends, so a repainting sink can clear itself. */
10
+ close?(): void;
11
+ }
12
+ export declare const terminalSink: Sink;
13
+ /** Rows of narration the window keeps on screen. */
14
+ export declare const WINDOW_ROWS = 8;
15
+ /** How often the border is redrawn — the wave's frame, not the clock's. */
16
+ export declare const FRAME_MS = 80;
17
+ /** Cells the crest travels per frame — a lap of a wide window in a few seconds. */
18
+ export declare const WAVE_STEP = 3;
19
+ /**
20
+ * How brightly one cell of the border is lit, given where the crest has got to.
21
+ *
22
+ * `position` counts clockwise from the top left corner, so one index walks the
23
+ * whole ring and the wave rounds the corners without a seam. Everything the
24
+ * tail has passed sits at the dimmest tone, which is the border's resting
25
+ * colour: the ring is always drawn, only the crest moves.
26
+ */
27
+ export declare function toneAt(position: number, head: number, span: number): number;
28
+ /**
29
+ * The bottom rule as cells, with the status label set into it near the left.
30
+ *
31
+ * Waiting belongs to the frame rather than to the narration: a row of its own
32
+ * costs a step of what the agent is doing every time, and it settles just
33
+ * under the last line, which is where the eye already is. Near the left, where
34
+ * reading starts, and not so near that it displaces the corner.
35
+ */
36
+ export declare function footerCells(label: string, width: number): string[];
37
+ /**
38
+ * Narration held to a fixed number of rows that rewrite themselves in place.
39
+ *
40
+ * A long run is hundreds of tool calls, and printing each as its own line
41
+ * scrolls the question, the model line and every warning off the top of the
42
+ * screen — by the end the terminal holds a transcript nobody asked for and the
43
+ * answer is somewhere in the middle of it. Only the last few steps say what it
44
+ * is doing now, which is the only thing narration is for; the rest is in the
45
+ * session copilot recorded.
46
+ *
47
+ * Warnings are not narration: they leave the window and stay on the screen.
48
+ *
49
+ * Without a terminal there is nothing to rewrite over, so every line is its
50
+ * own — which is what a CI log wants anyway.
51
+ */
52
+ export declare function windowSink(rows?: number): Sink;
53
+ /**
54
+ * The answer in the same box `zen run` draws it in: bounded width, rounded
55
+ * rule, formatted with full markdown styling (bold, italics, code, lists, quotes, tables).
56
+ *
57
+ * Redirected output gets the text and nothing else — `zen meta run ... > out.md`
58
+ * is meant to produce a file you can read, not one with a border down its side.
59
+ */
60
+ export declare function answerBox(text: string, columns?: number): string[];
61
+ //# sourceMappingURL=sink.d.ts.map
package/dist/sink.js ADDED
@@ -0,0 +1,198 @@
1
+ import { boxWidth, cut, cyan, dim, formatMarkdown, note, pad, red, styled, write } from "./host.js";
2
+ export const terminalSink = {
3
+ answer: (text) => write(text),
4
+ narrate: (line) => note(line),
5
+ warn: (line) => note(red(line)),
6
+ };
7
+ /** Rows of narration the window keeps on screen. */
8
+ export const WINDOW_ROWS = 8;
9
+ const BOX = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' };
10
+ /** How often the border is redrawn — the wave's frame, not the clock's. */
11
+ export const FRAME_MS = 80;
12
+ // Dimmest first, crest last. Written as escapes rather than `styleText` because
13
+ // a named colour has no ramp, which is also why `styled()` has to be asked.
14
+ const WAVE = [
15
+ '\u001b[0;38;5;24m',
16
+ '\u001b[0;38;5;31m',
17
+ '\u001b[0;38;5;38m',
18
+ '\u001b[0;38;5;45m',
19
+ '\u001b[0;38;5;51m',
20
+ '\u001b[1;38;5;159m',
21
+ '\u001b[1;38;5;231m',
22
+ ];
23
+ const RESET = '\u001b[0m';
24
+ /** Cells each tone of the tail covers, so the crest reads as a band, not a dot. */
25
+ const WAVE_TAIL = 2;
26
+ /** Cells the crest travels per frame — a lap of a wide window in a few seconds. */
27
+ export const WAVE_STEP = 3;
28
+ /**
29
+ * How brightly one cell of the border is lit, given where the crest has got to.
30
+ *
31
+ * `position` counts clockwise from the top left corner, so one index walks the
32
+ * whole ring and the wave rounds the corners without a seam. Everything the
33
+ * tail has passed sits at the dimmest tone, which is the border's resting
34
+ * colour: the ring is always drawn, only the crest moves.
35
+ */
36
+ export function toneAt(position, head, span) {
37
+ const behind = (((head - position) % span) + span) % span;
38
+ const step = Math.floor(behind / WAVE_TAIL);
39
+ return step < WAVE.length ? WAVE.length - 1 - step : 0;
40
+ }
41
+ /**
42
+ * A run of border cells, coloured by the wave and emitting an escape only where
43
+ * the tone changes — a frame of the whole ring is a handful of them.
44
+ *
45
+ * `from` is the ring position of the first cell and `step` which way round the
46
+ * ring the cells run, because the bottom rule is printed left to right while
47
+ * the ring travels it right to left.
48
+ */
49
+ function lit(cells, from, step, head, span) {
50
+ let out = '';
51
+ let tone = -1;
52
+ for (let i = 0; i < cells.length; i++) {
53
+ const next = toneAt(from + i * step, head, span);
54
+ if (next !== tone) {
55
+ out += WAVE[next];
56
+ tone = next;
57
+ }
58
+ out += cells[i];
59
+ }
60
+ return `${out}${RESET}`;
61
+ }
62
+ /**
63
+ * The bottom rule as cells, with the status label set into it near the left.
64
+ *
65
+ * Waiting belongs to the frame rather than to the narration: a row of its own
66
+ * costs a step of what the agent is doing every time, and it settles just
67
+ * under the last line, which is where the eye already is. Near the left, where
68
+ * reading starts, and not so near that it displaces the corner.
69
+ */
70
+ export function footerCells(label, width) {
71
+ const room = width - 6;
72
+ const text = label && room > 0 ? [...label].slice(0, room) : [];
73
+ const cells = text.length > 0 ? [BOX.bl, BOX.h, ' ', ...text, ' '] : [BOX.bl];
74
+ while (cells.length < width - 1) {
75
+ cells.push(BOX.h);
76
+ }
77
+ return [...cells, BOX.br];
78
+ }
79
+ /**
80
+ * Narration held to a fixed number of rows that rewrite themselves in place.
81
+ *
82
+ * A long run is hundreds of tool calls, and printing each as its own line
83
+ * scrolls the question, the model line and every warning off the top of the
84
+ * screen — by the end the terminal holds a transcript nobody asked for and the
85
+ * answer is somewhere in the middle of it. Only the last few steps say what it
86
+ * is doing now, which is the only thing narration is for; the rest is in the
87
+ * session copilot recorded.
88
+ *
89
+ * Warnings are not narration: they leave the window and stay on the screen.
90
+ *
91
+ * Without a terminal there is nothing to rewrite over, so every line is its
92
+ * own — which is what a CI log wants anyway.
93
+ */
94
+ export function windowSink(rows = WINDOW_ROWS) {
95
+ if (!process.stderr.isTTY) {
96
+ return terminalSink;
97
+ }
98
+ const kept = [];
99
+ const colour = styled();
100
+ let label = '';
101
+ let head = 0;
102
+ let painted = 0;
103
+ // The frame must stay under the viewport: a block taller than the screen
104
+ // scrolls its own top away, and then the cursor-up erase falls short and
105
+ // strands a copy of every repaint. The two border rows count towards it.
106
+ const height = () => Math.max(1, Math.min(rows, (process.stderr.rows ?? 24) - 4));
107
+ const columns = () => Math.max(20, (process.stderr.columns ?? 80) - 1);
108
+ const innerOf = () => columns() - 4;
109
+ const erase = () => {
110
+ if (painted > 0) {
111
+ process.stderr.write(`\u001b[${painted}A\u001b[0J`);
112
+ painted = 0;
113
+ }
114
+ };
115
+ /** The whole frame, border lit by the wave, every row exactly one row. */
116
+ const frameOf = (show, inner) => {
117
+ const width = inner + 4;
118
+ // Clockwise from the top left: across the top, down the right, back
119
+ // along the bottom, up the left. One ring, so one index addresses it.
120
+ const span = 2 * width + 2 * show.length;
121
+ const top = [BOX.tl, ...Array(width - 2).fill(BOX.h), BOX.tr];
122
+ const bottom = footerCells(label, width);
123
+ const edge = (position) => colour ? lit([BOX.v], position, 1, head, span) : cyan(BOX.v);
124
+ return [
125
+ colour ? lit(top, 0, 1, head, span) : cyan(top.join('')),
126
+ ...show.map((line, r) => `${edge(span - 1 - r)} ${pad(cut(line, inner), inner)} ${edge(width + r)}`),
127
+ colour
128
+ ? lit(bottom, 2 * width + show.length - 1, -1, head, span)
129
+ : cyan(bottom.join('')),
130
+ ];
131
+ };
132
+ const paint = () => {
133
+ const show = kept.slice(-height());
134
+ if (show.length === 0 && label === '') {
135
+ erase();
136
+ return;
137
+ }
138
+ // The wave wants a frame to run round before there is anything to say.
139
+ const lines = frameOf(show.length > 0 ? show : [''], innerOf());
140
+ if (painted === lines.length) {
141
+ // Erasing before a repaint is what flickers; overwriting in place
142
+ // does not, and at frame rate the whole border has to be redrawn.
143
+ process.stderr.write(`\u001b[${painted}A${lines.map((l) => `\r${l}\u001b[0K\n`).join('')}`);
144
+ return;
145
+ }
146
+ erase();
147
+ process.stderr.write(lines.map((l) => `${l}\n`).join(''));
148
+ painted = lines.length;
149
+ };
150
+ return {
151
+ answer: (text) => {
152
+ erase();
153
+ write(text);
154
+ },
155
+ narrate: (line) => {
156
+ kept.push(...line.split('\n'));
157
+ if (kept.length > height() * 4) {
158
+ kept.splice(0, kept.length - height());
159
+ }
160
+ paint();
161
+ },
162
+ warn: (line) => {
163
+ erase();
164
+ note(red(line));
165
+ paint();
166
+ },
167
+ status: (line) => {
168
+ label = line;
169
+ head += WAVE_STEP;
170
+ paint();
171
+ },
172
+ close: erase,
173
+ };
174
+ }
175
+ /**
176
+ * The answer in the same box `zen run` draws it in: bounded width, rounded
177
+ * rule, formatted with full markdown styling (bold, italics, code, lists, quotes, tables).
178
+ *
179
+ * Redirected output gets the text and nothing else — `zen meta run ... > out.md`
180
+ * is meant to produce a file you can read, not one with a border down its side.
181
+ */
182
+ export function answerBox(text, columns = process.stdout.columns ?? 80) {
183
+ if (!process.stdout.isTTY) {
184
+ return text.split('\n');
185
+ }
186
+ const outer = boxWidth(text, columns);
187
+ const inner = outer - 4;
188
+ const body = formatMarkdown(text, inner);
189
+ const rule = BOX.h.repeat(outer - 2);
190
+ return [
191
+ '',
192
+ dim(`${BOX.tl}${rule}${BOX.tr}`),
193
+ ...body.map((l) => `${dim(BOX.v)} ${pad(l, inner)} ${dim(BOX.v)}`),
194
+ dim(`${BOX.bl}${rule}${BOX.br}`),
195
+ '',
196
+ ];
197
+ }
198
+ //# sourceMappingURL=sink.js.map
@@ -0,0 +1,52 @@
1
+ import type { ModelUsage, TokenUsage } from '@zenera/neo';
2
+ export interface MetaCall {
3
+ model: string;
4
+ usage: TokenUsage;
5
+ cacheWriteTokens?: number;
6
+ startedAt: string;
7
+ durationMs: number;
8
+ session?: string;
9
+ traceId?: string;
10
+ spanId?: string;
11
+ }
12
+ /**
13
+ * One line of the span file, as a model call - anything else is undefined.
14
+ * Only counts are read off it: whatever else a span may carry, none of it
15
+ * reaches the ledger.
16
+ */
17
+ export declare function readSpan(line: string): MetaCall | undefined;
18
+ /** Whole lines out of a stream read in chunks; the unfinished tail is carried. */
19
+ export declare function splitLines(carry: string, chunk: string): {
20
+ lines: string[];
21
+ carry: string;
22
+ };
23
+ /** Reads a span file as it grows. `stop()` reads what is left, once. */
24
+ export declare function tailSpans(path: string, onCall: (call: MetaCall) => void, everyMs?: number): {
25
+ stop: () => void;
26
+ };
27
+ /** Calls and tokens so far, in the one line the status row and the summary share. */
28
+ export declare class Tally {
29
+ calls: number;
30
+ usage: TokenUsage;
31
+ add(call: MetaCall): void;
32
+ toString(): string;
33
+ }
34
+ /** 950, 12.3k, 1.8M. */
35
+ export declare function compact(n: number): string;
36
+ /**
37
+ * Copilot's own per-model totals from the last `session.shutdown` in a session's
38
+ * events - cumulative over every resume of it. Reasoning folded into output,
39
+ * as everywhere in zen.
40
+ */
41
+ export declare function shutdownModels(events: string): ModelUsage[] | undefined;
42
+ export declare function sessionTotals(sessionId: string): ModelUsage[] | undefined;
43
+ /** Whether this machine holds the session, which is what `--resume` needs. */
44
+ export declare function sessionKept(sessionId: string): boolean;
45
+ /**
46
+ * The model a session's history was written by: its last answer's, else the one it started on.
47
+ * A failed resume on another model writes no answer, so it never becomes the session's model.
48
+ */
49
+ export declare function sessionModel(sessionId: string): string | undefined;
50
+ /** `google/gemini-3.8-flash` and `gemini-3.8-flash` are one model to copilot. */
51
+ export declare const sameModel: (a: string, b: string) => boolean;
52
+ //# sourceMappingURL=tokens.d.ts.map