@zenera/cli 1.2.9 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +11 -3
  2. package/dist/command.d.ts +19 -0
  3. package/dist/command.js +5 -9
  4. package/dist/commands/index.d.ts +1 -1
  5. package/dist/commands/index.js +13 -3
  6. package/dist/commands/open.js +6 -1
  7. package/dist/commands/version.d.ts +11 -0
  8. package/dist/commands/version.js +129 -19
  9. package/dist/{completion.d.ts → complete.d.ts} +1 -1
  10. package/dist/{completion.js → complete.js} +14 -4
  11. package/dist/{meta/editor.js → editor.js} +7 -1
  12. package/dist/lib.d.ts +18 -1
  13. package/dist/lib.js +34 -0
  14. package/dist/main.js +1 -1
  15. package/dist/scaffold.js +7 -1
  16. package/package.json +6 -7
  17. package/templates/editor/.github/skills/zen-cli/references/meta.md +3 -0
  18. package/templates/editor/.github/skills/zen-cli/references/projects.md +7 -2
  19. package/dist/commands/meta.d.ts +0 -6
  20. package/dist/commands/meta.js +0 -1088
  21. package/dist/meta/finetune/analyze-brief.d.ts +0 -26
  22. package/dist/meta/finetune/analyze-brief.js +0 -131
  23. package/dist/meta/finetune/apply-brief.d.ts +0 -23
  24. package/dist/meta/finetune/apply-brief.js +0 -247
  25. package/dist/meta/finetune/brief.d.ts +0 -45
  26. package/dist/meta/finetune/brief.js +0 -158
  27. package/dist/meta/finetune/children.d.ts +0 -8
  28. package/dist/meta/finetune/children.js +0 -76
  29. package/dist/meta/finetune/command.d.ts +0 -30
  30. package/dist/meta/finetune/command.js +0 -516
  31. package/dist/meta/finetune/cost.d.ts +0 -46
  32. package/dist/meta/finetune/cost.js +0 -105
  33. package/dist/meta/finetune/dataset/anchors.d.ts +0 -41
  34. package/dist/meta/finetune/dataset/anchors.js +0 -239
  35. package/dist/meta/finetune/dataset/changes.d.ts +0 -36
  36. package/dist/meta/finetune/dataset/changes.js +0 -319
  37. package/dist/meta/finetune/dataset/command.d.ts +0 -17
  38. package/dist/meta/finetune/dataset/command.js +0 -1011
  39. package/dist/meta/finetune/dataset/drift.d.ts +0 -33
  40. package/dist/meta/finetune/dataset/drift.js +0 -71
  41. package/dist/meta/finetune/dataset/export.d.ts +0 -26
  42. package/dist/meta/finetune/dataset/export.js +0 -51
  43. package/dist/meta/finetune/dataset/index.d.ts +0 -2
  44. package/dist/meta/finetune/dataset/index.js +0 -2
  45. package/dist/meta/finetune/dataset/sample.d.ts +0 -50
  46. package/dist/meta/finetune/dataset/sample.js +0 -197
  47. package/dist/meta/finetune/dataset/schema.d.ts +0 -33
  48. package/dist/meta/finetune/dataset/schema.js +0 -216
  49. package/dist/meta/finetune/dataset/store.d.ts +0 -35
  50. package/dist/meta/finetune/dataset/store.js +0 -177
  51. package/dist/meta/finetune/dataset/types.d.ts +0 -127
  52. package/dist/meta/finetune/dataset/types.js +0 -39
  53. package/dist/meta/finetune/failure.d.ts +0 -15
  54. package/dist/meta/finetune/failure.js +0 -26
  55. package/dist/meta/finetune/feedback.d.ts +0 -57
  56. package/dist/meta/finetune/feedback.js +0 -104
  57. package/dist/meta/finetune/improvements.d.ts +0 -98
  58. package/dist/meta/finetune/improvements.js +0 -501
  59. package/dist/meta/finetune/index.d.ts +0 -2
  60. package/dist/meta/finetune/index.js +0 -2
  61. package/dist/meta/finetune/journal.d.ts +0 -35
  62. package/dist/meta/finetune/journal.js +0 -135
  63. package/dist/meta/finetune/live.d.ts +0 -84
  64. package/dist/meta/finetune/live.js +0 -272
  65. package/dist/meta/finetune/loop.d.ts +0 -3
  66. package/dist/meta/finetune/loop.js +0 -163
  67. package/dist/meta/finetune/memories.d.ts +0 -47
  68. package/dist/meta/finetune/memories.js +0 -171
  69. package/dist/meta/finetune/recheck.d.ts +0 -58
  70. package/dist/meta/finetune/recheck.js +0 -311
  71. package/dist/meta/finetune/report.d.ts +0 -40
  72. package/dist/meta/finetune/report.js +0 -1397
  73. package/dist/meta/finetune/retry.d.ts +0 -24
  74. package/dist/meta/finetune/retry.js +0 -96
  75. package/dist/meta/finetune/sampler.d.ts +0 -18
  76. package/dist/meta/finetune/sampler.js +0 -47
  77. package/dist/meta/finetune/system.d.ts +0 -27
  78. package/dist/meta/finetune/system.js +0 -132
  79. package/dist/meta/finetune/train.d.ts +0 -43
  80. package/dist/meta/finetune/train.js +0 -425
  81. package/dist/meta/finetune/tui.d.ts +0 -16
  82. package/dist/meta/finetune/tui.js +0 -316
  83. package/dist/meta/finetune/tuning.d.ts +0 -193
  84. package/dist/meta/finetune/tuning.js +0 -308
  85. package/dist/meta/finetune/usage.d.ts +0 -66
  86. package/dist/meta/finetune/usage.js +0 -260
  87. package/dist/meta/finetune/view.d.ts +0 -9
  88. package/dist/meta/finetune/view.js +0 -27
  89. package/dist/meta/host.d.ts +0 -16
  90. package/dist/meta/host.js +0 -22
  91. package/dist/meta/index.d.ts +0 -11
  92. package/dist/meta/index.js +0 -11
  93. package/dist/meta/launch.d.ts +0 -81
  94. package/dist/meta/launch.js +0 -288
  95. package/dist/meta/model.d.ts +0 -61
  96. package/dist/meta/model.js +0 -146
  97. package/dist/meta/prompts.d.ts +0 -23
  98. package/dist/meta/prompts.js +0 -84
  99. package/dist/meta/relay.d.ts +0 -20
  100. package/dist/meta/relay.js +0 -123
  101. package/dist/meta/tokens.d.ts +0 -52
  102. package/dist/meta/tokens.js +0 -226
  103. package/dist/meta/window.d.ts +0 -61
  104. package/dist/meta/window.js +0 -198
  105. package/dist/meta/wire.d.ts +0 -51
  106. package/dist/meta/wire.js +0 -159
  107. /package/dist/{meta/editor.d.ts → editor.d.ts} +0 -0
@@ -1,84 +0,0 @@
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
@@ -1,20 +0,0 @@
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
@@ -1,123 +0,0 @@
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
@@ -1,52 +0,0 @@
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
@@ -1,226 +0,0 @@
1
- import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { join } from 'node:path';
4
- /** An OTel time: `[seconds, nanoseconds]` in this exporter; epoch ms either way. */
5
- function epochMs(t) {
6
- if (Array.isArray(t) && typeof t[0] === 'number') {
7
- return t[0] * 1000 + Number(t[1] ?? 0) / 1e6;
8
- }
9
- if (typeof t === 'number') {
10
- return t;
11
- }
12
- return typeof t === 'string' ? Date.parse(t) : undefined;
13
- }
14
- /**
15
- * One line of the span file, as a model call - anything else is undefined.
16
- * Only counts are read off it: whatever else a span may carry, none of it
17
- * reaches the ledger.
18
- */
19
- export function readSpan(line) {
20
- let span;
21
- try {
22
- span = JSON.parse(line);
23
- }
24
- catch {
25
- return undefined;
26
- }
27
- const attrs = (span.attributes ?? {});
28
- if (span.type !== 'span' || attrs['gen_ai.operation.name'] !== 'chat') {
29
- return undefined;
30
- }
31
- const num = (key) => Number(attrs[key] ?? 0) || 0;
32
- const start = epochMs(span.startTime) ?? 0;
33
- const end = epochMs(span.endTime) ?? start;
34
- // Copilot counts reasoning beside the output; zen counts it inside.
35
- const reasoning = num('gen_ai.usage.reasoning.output_tokens');
36
- const cacheWrite = num('gen_ai.usage.cache_creation.input_tokens') ||
37
- num('gen_ai.usage.cache_creation_input_tokens');
38
- return {
39
- model: String(attrs['gen_ai.response.model'] ?? attrs['gen_ai.request.model'] ?? '?'),
40
- usage: {
41
- inputTokens: num('gen_ai.usage.input_tokens'),
42
- cachedInputTokens: num('gen_ai.usage.cache_read.input_tokens') ||
43
- num('gen_ai.usage.cache_read_input_tokens'),
44
- outputTokens: num('gen_ai.usage.output_tokens') + reasoning,
45
- reasoningTokens: reasoning,
46
- },
47
- ...(cacheWrite ? { cacheWriteTokens: cacheWrite } : {}),
48
- startedAt: new Date(start).toISOString(),
49
- durationMs: Math.max(0, Math.round(end - start)),
50
- session: typeof attrs['gen_ai.conversation.id'] === 'string'
51
- ? attrs['gen_ai.conversation.id']
52
- : undefined,
53
- traceId: typeof span.traceId === 'string' ? span.traceId : undefined,
54
- spanId: typeof span.spanId === 'string' ? span.spanId : undefined,
55
- };
56
- }
57
- /** Whole lines out of a stream read in chunks; the unfinished tail is carried. */
58
- export function splitLines(carry, chunk) {
59
- const parts = `${carry}${chunk}`.split('\n');
60
- const rest = parts.pop() ?? '';
61
- return { lines: parts.filter((l) => l.trim()), carry: rest };
62
- }
63
- /** Reads a span file as it grows. `stop()` reads what is left, once. */
64
- export function tailSpans(path, onCall, everyMs = 1000) {
65
- let offset = 0;
66
- let carry = '';
67
- const poll = () => {
68
- let fd;
69
- try {
70
- const size = statSync(path).size;
71
- if (size <= offset) {
72
- return;
73
- }
74
- fd = openSync(path, 'r');
75
- const buf = Buffer.alloc(size - offset);
76
- readSync(fd, buf, 0, buf.length, offset);
77
- offset = size;
78
- const split = splitLines(carry, buf.toString('utf8'));
79
- carry = split.carry;
80
- for (const line of split.lines) {
81
- const call = readSpan(line);
82
- if (call) {
83
- onCall(call);
84
- }
85
- }
86
- }
87
- catch {
88
- // Not there yet: copilot creates it at the first span.
89
- }
90
- finally {
91
- if (fd !== undefined) {
92
- closeSync(fd);
93
- }
94
- }
95
- };
96
- const timer = setInterval(poll, everyMs);
97
- timer.unref();
98
- return {
99
- stop: () => {
100
- clearInterval(timer);
101
- poll();
102
- },
103
- };
104
- }
105
- /** Calls and tokens so far, in the one line the status row and the summary share. */
106
- export class Tally {
107
- calls = 0;
108
- usage = {
109
- inputTokens: 0,
110
- cachedInputTokens: 0,
111
- outputTokens: 0,
112
- reasoningTokens: 0,
113
- };
114
- add(call) {
115
- this.calls += 1;
116
- this.usage = {
117
- inputTokens: this.usage.inputTokens + call.usage.inputTokens,
118
- cachedInputTokens: this.usage.cachedInputTokens + call.usage.cachedInputTokens,
119
- outputTokens: this.usage.outputTokens + call.usage.outputTokens,
120
- reasoningTokens: this.usage.reasoningTokens + call.usage.reasoningTokens,
121
- };
122
- }
123
- toString() {
124
- const u = this.usage;
125
- const cached = u.cachedInputTokens ? ` (${compact(u.cachedInputTokens)} cached)` : '';
126
- return (`${this.calls} call${this.calls === 1 ? '' : 's'} · ${compact(u.inputTokens)} in${cached}` +
127
- ` · ${compact(u.outputTokens)} out`);
128
- }
129
- }
130
- /** 950, 12.3k, 1.8M. */
131
- export function compact(n) {
132
- if (n < 1000) {
133
- return String(n);
134
- }
135
- if (n < 1e6) {
136
- return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}k`;
137
- }
138
- return `${(n / 1e6).toFixed(n < 1e7 ? 2 : 1)}M`;
139
- }
140
- /**
141
- * Copilot's own per-model totals from the last `session.shutdown` in a session's
142
- * events - cumulative over every resume of it. Reasoning folded into output,
143
- * as everywhere in zen.
144
- */
145
- export function shutdownModels(events) {
146
- const line = events
147
- .split('\n')
148
- .reverse()
149
- .find((l) => l.includes('"session.shutdown"'));
150
- if (!line) {
151
- return undefined;
152
- }
153
- let metrics;
154
- try {
155
- metrics = JSON.parse(line).data?.modelMetrics ?? {};
156
- }
157
- catch {
158
- return undefined;
159
- }
160
- return Object.entries(metrics).map(([model, m]) => {
161
- const u = m.usage ?? {};
162
- const reasoning = Number(u.reasoningTokens ?? 0);
163
- return {
164
- model,
165
- calls: Number(m.requests?.count ?? 0),
166
- usage: {
167
- inputTokens: Number(u.inputTokens ?? 0),
168
- cachedInputTokens: Number(u.cacheReadTokens ?? 0),
169
- outputTokens: Number(u.outputTokens ?? 0) + reasoning,
170
- reasoningTokens: reasoning,
171
- },
172
- };
173
- });
174
- }
175
- export function sessionTotals(sessionId) {
176
- const home = process.env.COPILOT_HOME ?? join(homedir(), '.copilot');
177
- try {
178
- return shutdownModels(readFileSync(join(home, 'session-state', sessionId, 'events.jsonl'), 'utf8'));
179
- }
180
- catch {
181
- return undefined;
182
- }
183
- }
184
- /** Whether this machine holds the session, which is what `--resume` needs. */
185
- export function sessionKept(sessionId) {
186
- const home = process.env.COPILOT_HOME ?? join(homedir(), '.copilot');
187
- return existsSync(join(home, 'session-state', sessionId));
188
- }
189
- /**
190
- * The model a session's history was written by: its last answer's, else the one it started on.
191
- * A failed resume on another model writes no answer, so it never becomes the session's model.
192
- */
193
- export function sessionModel(sessionId) {
194
- const home = process.env.COPILOT_HOME ?? join(homedir(), '.copilot');
195
- let text;
196
- try {
197
- text = readFileSync(join(home, 'session-state', sessionId, 'events.jsonl'), 'utf8');
198
- }
199
- catch {
200
- return undefined;
201
- }
202
- let started;
203
- const lines = text.split('\n');
204
- for (let i = lines.length - 1; i >= 0; i--) {
205
- const line = lines[i];
206
- if (!line.includes('"assistant.message"') && !line.includes('"session.start"')) {
207
- continue;
208
- }
209
- try {
210
- const event = JSON.parse(line);
211
- if (event.type === 'assistant.message' && typeof event.data?.model === 'string') {
212
- return event.data.model;
213
- }
214
- if (event.type === 'session.start' && typeof event.data?.selectedModel === 'string') {
215
- started = event.data.selectedModel;
216
- }
217
- }
218
- catch {
219
- // A line cut by a crash says nothing.
220
- }
221
- }
222
- return started;
223
- }
224
- /** `google/gemini-3.8-flash` and `gemini-3.8-flash` are one model to copilot. */
225
- export const sameModel = (a, b) => a.replace(/^.*\//, '').toLowerCase() === b.replace(/^.*\//, '').toLowerCase();
226
- //# sourceMappingURL=tokens.js.map
@@ -1,61 +0,0 @@
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=window.d.ts.map