@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.
@@ -0,0 +1,117 @@
1
+ import type { BearerTokenProvider, CopilotClientOptions, PermissionRequest, PermissionRequestResult, ProviderConfig, ResumeSessionConfig, SessionConfig, SessionEvent } from '@github/copilot-sdk';
2
+ import type { MetaCall } from '../tokens.ts';
3
+ export type ChatEvent =
4
+ /** a piece of the message being written, by its id */
5
+ {
6
+ type: 'delta';
7
+ id: string;
8
+ text: string;
9
+ }
10
+ /** a whole message; `tools` > 0 means it was said on the way to a tool call */
11
+ | {
12
+ type: 'message';
13
+ id: string;
14
+ text: string;
15
+ tools: number;
16
+ } | {
17
+ type: 'tool';
18
+ id: string;
19
+ name: string;
20
+ subject: string;
21
+ } | {
22
+ type: 'tool-done';
23
+ id: string;
24
+ ok: boolean;
25
+ error?: string;
26
+ } | {
27
+ type: 'usage';
28
+ call: MetaCall;
29
+ } | {
30
+ type: 'warn';
31
+ text: string;
32
+ } | {
33
+ type: 'error';
34
+ text: string;
35
+ } | {
36
+ type: 'retry';
37
+ reason: string;
38
+ waitMs: number;
39
+ attempt: number;
40
+ of: number;
41
+ };
42
+ export interface TurnResult {
43
+ aborted: boolean;
44
+ /** why the turn failed for good, when it did */
45
+ failed?: string;
46
+ }
47
+ export interface SessionLike {
48
+ readonly sessionId: string;
49
+ on(handler: (event: SessionEvent) => void): () => void;
50
+ send(options: {
51
+ prompt: string;
52
+ }): Promise<string>;
53
+ abort(): Promise<void>;
54
+ disconnect(): Promise<void>;
55
+ }
56
+ export interface ClientLike {
57
+ createSession(config: SessionConfig): Promise<SessionLike>;
58
+ resumeSession(id: string, config: ResumeSessionConfig): Promise<SessionLike>;
59
+ stop(): Promise<Error[]>;
60
+ }
61
+ export type Connect = (options: CopilotClientOptions) => ClientLike | Promise<ClientLike>;
62
+ /**
63
+ * `token`, when given, replaces the key command: the SDK calls back into this
64
+ * process before each request instead of the runtime starting `zen key token`.
65
+ */
66
+ export declare function providerConfig(env: Record<string, string>, token?: BearerTokenProvider): ProviderConfig;
67
+ /**
68
+ * A service account's access token, minted in this process. The key command
69
+ * starts a `zen` and asks Google for a new token before every model call, so
70
+ * one network blip in a long session failed the turn. Here the library keeps
71
+ * the token until shortly before it expires, and a failed exchange is tried
72
+ * again before the call is given up on.
73
+ */
74
+ export declare function googleToken(keyFile: string, opts?: {
75
+ attempts?: number;
76
+ delayMs?: number;
77
+ }): BearerTokenProvider;
78
+ /** Everything else in the wiring's environment: what the provider object does not carry. */
79
+ export declare function runtimeEnv(env: Record<string, string>): Record<string, string>;
80
+ /** One model call, in the shape the ledger and the tally already take from the span file. */
81
+ export declare function toCall(event: SessionEvent, session: string): MetaCall | undefined;
82
+ /** The SDK's event as the screen's, or nothing. A sub-agent's own steps stay in the log. */
83
+ export declare function narrate(event: SessionEvent): ChatEvent | undefined;
84
+ export interface ChatOptions {
85
+ dir: string;
86
+ /** the model's id, as `SessionConfig.model` */
87
+ model: string;
88
+ provider: ProviderConfig;
89
+ /** the runtime's whole environment */
90
+ env: Record<string, string>;
91
+ sessionId: string;
92
+ /** carry on `sessionId` rather than start it */
93
+ resume: boolean;
94
+ agent?: string;
95
+ effort?: string;
96
+ addDirs?: readonly string[];
97
+ decide: (request: PermissionRequest) => Promise<PermissionRequestResult>;
98
+ onEvent: (event: ChatEvent) => void;
99
+ /** every SDK event, before it is narrated: the log and `--events` file */
100
+ onRaw?: (event: SessionEvent) => void;
101
+ /** resumes after a failure time can cure, per turn */
102
+ retries: number;
103
+ delayMs?: (attempt: number) => number;
104
+ connect?: Connect;
105
+ }
106
+ export interface Chat {
107
+ readonly sessionId: string;
108
+ /** resolves when the turn has settled: answered, failed for good, or stopped */
109
+ send(prompt: string): Promise<TurnResult>;
110
+ /** stops the turn in flight, or the wait before a resume */
111
+ abort(): Promise<void>;
112
+ close(): Promise<void>;
113
+ }
114
+ /** The reasoning levels `--effort` takes. */
115
+ export declare const EFFORTS: readonly string[];
116
+ export declare function openChat(opts: ChatOptions): Promise<Chat>;
117
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1,303 @@
1
+ // packages/meta/src/chat/session.ts
2
+ //
3
+ // One `zen meta chat` conversation over the Copilot SDK, with no drawing in it: open (or resume) a session on
4
+ // the wired provider, send a turn and wait for it to settle, and narrate the SDK's events as `ChatEvent`s.
5
+ // Main: `openChat(opts)` -> `Chat` (`send`, `abort`, `close`); also `providerConfig` (a `Wiring`'s env as the
6
+ // SDK's typed provider), `toCall` (an `assistant.usage` event as a ledger `MetaCall`), `narrate` and `EFFORTS`.
7
+ // Used by: `chat/run.ts`, which drives it from the chat screen in `chat/tui.tsx`.
8
+ import { setTimeout as sleep } from 'node:timers/promises';
9
+ import { RESUME_PROMPT, resumeDelayMs, transient } from "../launch.js";
10
+ /** The real one, loaded only when a chat opens: it brings a native runtime with it. */
11
+ const connectSdk = async (options) => {
12
+ const { CopilotClient } = await import('@github/copilot-sdk');
13
+ return new CopilotClient(options);
14
+ };
15
+ // ---------------------------------------------------------------------------
16
+ // The wiring, typed
17
+ //
18
+ // `zen meta run` hands copilot its provider in `COPILOT_PROVIDER_*`; the SDK
19
+ // takes the same settings as a typed object on the session. The rest of the
20
+ // environment - a service account's key file, the ledger - still goes to the
21
+ // runtime, since the key command and the agent's own `zen` calls read it there.
22
+ // ---------------------------------------------------------------------------
23
+ const PROVIDER_ENV = /^COPILOT_(PROVIDER_|MODEL$)/;
24
+ /**
25
+ * `token`, when given, replaces the key command: the SDK calls back into this
26
+ * process before each request instead of the runtime starting `zen key token`.
27
+ */
28
+ export function providerConfig(env, token) {
29
+ const type = env.COPILOT_PROVIDER_TYPE;
30
+ const api = env.COPILOT_PROVIDER_WIRE_API;
31
+ return {
32
+ type: type === 'anthropic' ? 'anthropic' : 'openai',
33
+ baseUrl: env.COPILOT_PROVIDER_BASE_URL ?? '',
34
+ ...(env.COPILOT_PROVIDER_API_KEY ? { apiKey: env.COPILOT_PROVIDER_API_KEY } : {}),
35
+ ...(token
36
+ ? { bearerTokenProvider: token }
37
+ : env.COPILOT_PROVIDER_API_KEY_COMMAND
38
+ ? { apiKeyCommand: env.COPILOT_PROVIDER_API_KEY_COMMAND }
39
+ : {}),
40
+ ...(api === 'responses' || api === 'completions' ? { wireApi: api } : {}),
41
+ ...(env.COPILOT_PROVIDER_MODEL_ID ? { modelId: env.COPILOT_PROVIDER_MODEL_ID } : {}),
42
+ ...(env.COPILOT_PROVIDER_WIRE_MODEL ? { wireModel: env.COPILOT_PROVIDER_WIRE_MODEL } : {}),
43
+ };
44
+ }
45
+ /**
46
+ * A service account's access token, minted in this process. The key command
47
+ * starts a `zen` and asks Google for a new token before every model call, so
48
+ * one network blip in a long session failed the turn. Here the library keeps
49
+ * the token until shortly before it expires, and a failed exchange is tried
50
+ * again before the call is given up on.
51
+ */
52
+ export function googleToken(keyFile, opts = {}) {
53
+ const attempts = opts.attempts ?? 4;
54
+ const delayMs = opts.delayMs ?? 1_000;
55
+ let auth;
56
+ return async () => {
57
+ auth ??= import('google-auth-library').then(({ GoogleAuth }) => new GoogleAuth({
58
+ keyFile,
59
+ scopes: ['https://www.googleapis.com/auth/cloud-platform'],
60
+ }));
61
+ let last;
62
+ for (let i = 0; i < attempts; i++) {
63
+ try {
64
+ const token = await (await auth).getAccessToken();
65
+ if (token) {
66
+ return token;
67
+ }
68
+ last = new Error(`${keyFile} minted no token`);
69
+ }
70
+ catch (err) {
71
+ last = err;
72
+ }
73
+ if (i + 1 < attempts) {
74
+ await sleep(delayMs * 2 ** i);
75
+ }
76
+ }
77
+ throw last;
78
+ };
79
+ }
80
+ /** Everything else in the wiring's environment: what the provider object does not carry. */
81
+ export function runtimeEnv(env) {
82
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !PROVIDER_ENV.test(name)));
83
+ }
84
+ /** One model call, in the shape the ledger and the tally already take from the span file. */
85
+ export function toCall(event, session) {
86
+ if (event.type !== 'assistant.usage') {
87
+ return undefined;
88
+ }
89
+ const d = event.data;
90
+ const reasoning = d.reasoningTokens ?? 0;
91
+ const durationMs = Math.max(0, Math.round(d.duration ?? 0));
92
+ const ended = Date.parse(event.timestamp);
93
+ return {
94
+ model: d.model,
95
+ usage: {
96
+ inputTokens: d.inputTokens ?? 0,
97
+ cachedInputTokens: d.cacheReadTokens ?? 0,
98
+ // Copilot counts reasoning beside the output; zen counts it inside.
99
+ outputTokens: (d.outputTokens ?? 0) + reasoning,
100
+ reasoningTokens: reasoning,
101
+ },
102
+ ...(d.cacheWriteTokens ? { cacheWriteTokens: d.cacheWriteTokens } : {}),
103
+ startedAt: new Date((Number.isFinite(ended) ? ended : Date.now()) - durationMs).toISOString(),
104
+ durationMs,
105
+ session,
106
+ };
107
+ }
108
+ function subject(args) {
109
+ const a = (args && typeof args === 'object' ? args : {});
110
+ const what = a.command ?? a.description ?? a.path ?? a.url ?? a.pattern ?? a.skill ?? '';
111
+ return String(what).replace(/\s+/g, ' ').trim();
112
+ }
113
+ /** The SDK's event as the screen's, or nothing. A sub-agent's own steps stay in the log. */
114
+ export function narrate(event) {
115
+ if ('agentId' in event && event.agentId) {
116
+ return undefined;
117
+ }
118
+ switch (event.type) {
119
+ case 'assistant.message_delta':
120
+ return { type: 'delta', id: event.data.messageId, text: event.data.deltaContent };
121
+ case 'assistant.message':
122
+ if (event.data.parentToolCallId) {
123
+ return undefined;
124
+ }
125
+ return {
126
+ type: 'message',
127
+ id: event.data.messageId,
128
+ text: event.data.content,
129
+ tools: event.data.toolRequests?.length ?? 0,
130
+ };
131
+ case 'tool.execution_start':
132
+ if (event.data.parentToolCallId) {
133
+ return undefined;
134
+ }
135
+ return {
136
+ type: 'tool',
137
+ id: event.data.toolCallId,
138
+ name: event.data.toolTitle ?? event.data.toolName,
139
+ subject: subject(event.data.arguments),
140
+ };
141
+ case 'tool.execution_complete':
142
+ if (event.data.parentToolCallId) {
143
+ return undefined;
144
+ }
145
+ return {
146
+ type: 'tool-done',
147
+ id: event.data.toolCallId,
148
+ ok: event.data.success,
149
+ error: event.data.error?.message,
150
+ };
151
+ case 'session.error':
152
+ return { type: 'error', text: event.data.message };
153
+ case 'session.warning':
154
+ return { type: 'warn', text: event.data.message };
155
+ default:
156
+ return undefined;
157
+ }
158
+ }
159
+ /** The reasoning levels `--effort` takes. */
160
+ export const EFFORTS = [
161
+ 'none',
162
+ 'minimal',
163
+ 'low',
164
+ 'medium',
165
+ 'high',
166
+ 'xhigh',
167
+ 'max',
168
+ ];
169
+ export async function openChat(opts) {
170
+ const client = await (opts.connect ?? connectSdk)({
171
+ env: { ...process.env, ...opts.env },
172
+ workingDirectory: opts.dir,
173
+ // Your keys, never a Copilot subscription: no GitHub sign-in is looked for.
174
+ useLoggedInUser: false,
175
+ logLevel: 'error',
176
+ });
177
+ // Each turn's events, kept so `transient` can read a failure the way it reads a run's.
178
+ let turn = [];
179
+ let settle;
180
+ let failTimer;
181
+ const onEvent = (event) => {
182
+ opts.onRaw?.(event);
183
+ turn.push(event);
184
+ const said = narrate(event);
185
+ if (said) {
186
+ opts.onEvent(said);
187
+ }
188
+ const call = toCall(event, opts.sessionId);
189
+ if (call) {
190
+ opts.onEvent({ type: 'usage', call });
191
+ }
192
+ if (event.type === 'session.idle') {
193
+ clearTimeout(failTimer);
194
+ settle?.(event.data.aborted === true);
195
+ }
196
+ else if (event.type === 'session.error') {
197
+ // An error is followed by idle; if it is not, the turn still has to end.
198
+ clearTimeout(failTimer);
199
+ failTimer = setTimeout(() => settle?.(false), 5_000);
200
+ failTimer.unref();
201
+ }
202
+ };
203
+ const config = {
204
+ model: opts.model,
205
+ provider: opts.provider,
206
+ streaming: true,
207
+ workingDirectory: opts.dir,
208
+ ...(opts.addDirs?.length ? { additionalDirectories: [...opts.addDirs] } : {}),
209
+ ...(opts.agent ? { agent: opts.agent } : {}),
210
+ ...(opts.effort && EFFORTS.includes(opts.effort)
211
+ ? { reasoningEffort: opts.effort }
212
+ : {}),
213
+ onPermissionRequest: opts.decide,
214
+ onEvent,
215
+ };
216
+ let session;
217
+ try {
218
+ session = opts.resume
219
+ ? await client.resumeSession(opts.sessionId, config)
220
+ : await client.createSession({ ...config, sessionId: opts.sessionId });
221
+ }
222
+ catch (err) {
223
+ await client.stop().catch(() => undefined);
224
+ throw err;
225
+ }
226
+ let waiting;
227
+ let stopped = false;
228
+ const once = async (prompt) => {
229
+ turn = [];
230
+ const done = new Promise((resolve) => (settle = resolve));
231
+ try {
232
+ await session.send({ prompt });
233
+ }
234
+ catch (err) {
235
+ settle = undefined;
236
+ const text = err.message;
237
+ opts.onEvent({ type: 'error', text });
238
+ return {
239
+ aborted: false,
240
+ events: [{ type: 'session.error', data: { message: text } }],
241
+ };
242
+ }
243
+ const aborted = await done;
244
+ settle = undefined;
245
+ return { aborted, events: turn };
246
+ };
247
+ return {
248
+ sessionId: session.sessionId,
249
+ send: async (prompt) => {
250
+ stopped = false;
251
+ let attempt = 0;
252
+ let result = await once(prompt);
253
+ for (;;) {
254
+ if (result.aborted || stopped) {
255
+ return { aborted: true };
256
+ }
257
+ const failed = result.events.findLast((e) => e.type === 'session.error');
258
+ if (!failed) {
259
+ return { aborted: false };
260
+ }
261
+ const outcome = {
262
+ answer: '',
263
+ exitCode: 1,
264
+ sessionId: session.sessionId,
265
+ events: result.events,
266
+ };
267
+ const reason = transient(outcome);
268
+ const message = String(failed.data.message ?? '');
269
+ if (!reason || attempt >= opts.retries) {
270
+ return { aborted: false, failed: reason ?? message };
271
+ }
272
+ const waitMs = (opts.delayMs ?? resumeDelayMs)(attempt);
273
+ attempt += 1;
274
+ opts.onEvent({ type: 'retry', reason, waitMs, attempt, of: opts.retries });
275
+ waiting = new AbortController();
276
+ try {
277
+ await sleep(waitMs, undefined, { signal: waiting.signal });
278
+ }
279
+ catch {
280
+ return { aborted: true };
281
+ }
282
+ finally {
283
+ waiting = undefined;
284
+ }
285
+ result = await once(RESUME_PROMPT);
286
+ }
287
+ },
288
+ abort: async () => {
289
+ stopped = true;
290
+ if (waiting) {
291
+ waiting.abort();
292
+ return;
293
+ }
294
+ await session.abort().catch(() => undefined);
295
+ },
296
+ close: async () => {
297
+ clearTimeout(failTimer);
298
+ await session.disconnect().catch(() => undefined);
299
+ await client.stop().catch(() => undefined);
300
+ },
301
+ };
302
+ }
303
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1,18 @@
1
+ import type { ChatEvent } from './session.ts';
2
+ export type RowKind = 'you' | 'say' | 'answer' | 'tool' | 'fail' | 'warn' | 'error' | 'note';
3
+ export interface Row {
4
+ key: number;
5
+ kind: RowKind;
6
+ text: string;
7
+ }
8
+ export interface View {
9
+ rows: readonly Row[];
10
+ /** the message being written, as it arrives */
11
+ live: string;
12
+ liveId?: string;
13
+ next: number;
14
+ }
15
+ export declare const EMPTY: View;
16
+ export declare function said(view: View, kind: RowKind, text: string): View;
17
+ export declare function fold(view: View, event: ChatEvent): View;
18
+ //# sourceMappingURL=transcript.d.ts.map
@@ -0,0 +1,39 @@
1
+ // packages/meta/src/chat/transcript.ts
2
+ //
3
+ // What the `zen meta chat` screen shows, as data: the finished rows (scrolled away by Ink's `Static`) and the
4
+ // message still streaming in. Pure, so the screen's logic is tested without drawing it.
5
+ // Main: `fold(view, event)`, which applies one `ChatEvent`; also `said` (a row for something the screen itself
6
+ // says), `EMPTY` and the `Row`/`View` types.
7
+ // Used by: `chat/tui.tsx`, which folds every event the session reports and draws the result.
8
+ import { duration } from "../host.js";
9
+ export const EMPTY = { rows: [], live: '', next: 0 };
10
+ export function said(view, kind, text) {
11
+ return { ...view, rows: [...view.rows, { key: view.next, kind, text }], next: view.next + 1 };
12
+ }
13
+ export function fold(view, event) {
14
+ switch (event.type) {
15
+ case 'delta':
16
+ return event.id === view.liveId
17
+ ? { ...view, live: view.live + event.text }
18
+ : { ...view, live: event.text, liveId: event.id };
19
+ case 'message': {
20
+ // The whole message replaces its pieces, so a missed delta costs nothing.
21
+ const text = event.text.trim();
22
+ const cleared = { ...view, live: '', liveId: undefined };
23
+ return text ? said(cleared, event.tools > 0 ? 'say' : 'answer', text) : cleared;
24
+ }
25
+ case 'tool':
26
+ return said(view, 'tool', [event.name, event.subject].filter(Boolean).join(' '));
27
+ case 'tool-done':
28
+ return event.ok ? view : said(view, 'fail', event.error ?? 'failed');
29
+ case 'warn':
30
+ return said(view, 'warn', event.text);
31
+ case 'error':
32
+ return said(view, 'error', event.text);
33
+ case 'retry':
34
+ return said(view, 'warn', `${event.reason}: resuming in ${duration(event.waitMs)} (${event.attempt}/${event.of}) - Esc stops`);
35
+ case 'usage':
36
+ return view;
37
+ }
38
+ }
39
+ //# sourceMappingURL=transcript.js.map
@@ -0,0 +1,37 @@
1
+ import React from 'react';
2
+ import { type History, type Theme } from '../host.ts';
3
+ import type { Answer, Described } from './permissions.ts';
4
+ import type { Chat, ChatEvent } from './session.ts';
5
+ /** How the session, opened before the screen, reaches it: set on mount, cleared on unmount. */
6
+ export interface Bridge {
7
+ onEvent?: (event: ChatEvent) => void;
8
+ onAsk?: (request: Described) => Promise<Answer>;
9
+ }
10
+ export interface Screen {
11
+ chat: Chat;
12
+ bridge: Bridge;
13
+ history: History;
14
+ theme: Theme;
15
+ title: {
16
+ owner: string;
17
+ model: string;
18
+ project: string;
19
+ resumed: boolean;
20
+ };
21
+ /** said after the clock while a turn runs: the calls and tokens so far */
22
+ status: () => string;
23
+ prompts: {
24
+ list(): Promise<string[]>;
25
+ load(name: string): Promise<{
26
+ body: string;
27
+ description?: string;
28
+ }>;
29
+ };
30
+ /** asked as soon as the screen is up */
31
+ first?: string;
32
+ /** each prompt as it is sent, for the log */
33
+ onSend?: (shown: string, prompt: string) => void;
34
+ }
35
+ export declare function chatScreen(screen: Screen): Promise<void>;
36
+ export declare function ChatApp(props: Screen): React.ReactElement;
37
+ //# sourceMappingURL=tui.d.ts.map