@zenera/meta 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -26
- package/dist/chat/permissions.d.ts +37 -0
- package/dist/chat/permissions.js +144 -0
- package/dist/chat/run.d.ts +27 -0
- package/dist/chat/run.js +172 -0
- package/dist/chat/session.d.ts +117 -0
- package/dist/chat/session.js +303 -0
- package/dist/chat/transcript.d.ts +18 -0
- package/dist/chat/transcript.js +39 -0
- package/dist/chat/tui.d.ts +37 -0
- package/dist/chat/tui.js +237 -0
- package/dist/command.js +120 -149
- package/dist/host.d.ts +1 -1
- package/dist/host.js +1 -1
- package/dist/launch.d.ts +9 -0
- package/dist/launch.js +39 -3
- package/dist/prepare.d.ts +36 -0
- package/dist/prepare.js +131 -0
- package/dist/reporter.d.ts +9 -0
- package/dist/reporter.js +46 -0
- package/dist/wire.d.ts +2 -0
- package/dist/wire.js +8 -1
- package/package.json +7 -5
package/README.md
CHANGED
|
@@ -1,43 +1,149 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img
|
|
3
|
+
src="https://raw.githubusercontent.com/zenera-ai/ZeneraNeo/main/docs/imgs/zenera-logo-with-media-queries.svg"
|
|
4
|
+
alt="Zenera Logo"
|
|
5
|
+
width="20"
|
|
6
|
+
/>
|
|
7
|
+
<div>Powered By Zenera</div>
|
|
8
|
+
</div>
|
|
9
|
+
<br>
|
|
10
|
+
|
|
11
|
+
<div align="center">
|
|
12
|
+
<img src="https://raw.githubusercontent.com/zenera-ai/ZeneraNeo/main/docs/imgs/banner-meta-with-media-queries.svg" alt="ZENERA META" width="801">
|
|
13
|
+
|
|
14
|
+
[](https://www.npmjs.com/package/@zenera/meta)
|
|
15
|
+
[](https://github.com/zenera-ai/ZeneraNeo/blob/main/LICENSE)
|
|
16
|
+
[](https://nodejs.org)
|
|
17
|
+
[](https://github.com/zenera-ai/ZeneraNeo/actions/workflows/ci.yml)
|
|
18
|
+
|
|
19
|
+
[Install](#install) · [Use](#use) · [Commands](#commands) · [Models](#models) · [Credentials](#credentials) · [Family](#the-rest-of-the-family) · [License](#license)
|
|
20
|
+
|
|
21
|
+
</div>
|
|
22
|
+
|
|
1
23
|
# @zenera/meta
|
|
2
24
|
|
|
3
|
-
The meta-agent
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
25
|
+
**The meta-agent: a coding agent pointed _at_ a zen project, on your own keys.
|
|
26
|
+
`zen run` runs the agents a project describes; `zen meta` runs an agent over
|
|
27
|
+
the project to change it - generate it from its specification, review it,
|
|
28
|
+
build its evaluation dataset and fine-tune its prompts against that dataset.**
|
|
29
|
+
|
|
30
|
+
It drives [GitHub Copilot CLI](https://github.com/github/copilot-cli) - and, for
|
|
31
|
+
a conversation, the [Copilot SDK](https://github.com/github/copilot-sdk) - with
|
|
32
|
+
your provider keys, never a Copilot subscription.
|
|
33
|
+
|
|
34
|
+
> Part of [ZeneraNeo](https://github.com/zenera-ai/ZeneraNeo). It ships no
|
|
35
|
+
> binary of its own: installing it adds a `meta` **subcommand** to
|
|
36
|
+
> [`zen`](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/cli/README.md),
|
|
37
|
+
> which is also where the credentials already are.
|
|
7
38
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
39
|
+
## What you get
|
|
40
|
+
|
|
41
|
+
- **Specification-driven builds** - `/spec-sync-project` reads
|
|
42
|
+
`SPECIFICATION.md` and writes the agents, prompts, tools and skills, then asks
|
|
43
|
+
what it could not decide in `SPECIFICATION-FEEDBACK.md`.
|
|
44
|
+
- **A chat in the terminal** - `zen meta chat` is the same agent turn by turn:
|
|
45
|
+
the answer streams in, each tool call is a line, and `--ask` has it stop for a
|
|
46
|
+
yes or no before it touches anything.
|
|
47
|
+
- **Commands from the project** - every `.github/skills/<name>/SKILL.md` the
|
|
48
|
+
project carries is a `/<name>` you can run from the terminal, the same ones
|
|
49
|
+
the editor offers.
|
|
50
|
+
- **Runs that survive** - a rate limit or provider outage is waited out and the
|
|
51
|
+
session resumed; `zen meta resume` picks up one that stopped for any other
|
|
52
|
+
reason.
|
|
53
|
+
- **A dataset and a tuning loop** - `zen meta dataset` keeps the cases a project
|
|
54
|
+
is evaluated on; `zen meta finetune` runs them, analyzes each run and edits
|
|
55
|
+
the project's prose until the cases pass. No model weights are touched.
|
|
56
|
+
- **Accounting** - tokens are counted per call as it runs; in a project being
|
|
57
|
+
tuned every call lands in `finetune/usage/ledger.jsonl`.
|
|
11
58
|
|
|
12
59
|
## Install
|
|
13
60
|
|
|
14
|
-
|
|
61
|
+
Node.js 24+. Install it alongside the CLI:
|
|
15
62
|
|
|
16
63
|
```sh
|
|
17
|
-
npm
|
|
64
|
+
npm i -g @zenera/cli @zenera/meta
|
|
65
|
+
zen key add openai # the keyring `zen` already uses
|
|
18
66
|
```
|
|
19
67
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
68
|
+
Copilot CLI is used from `PATH` when it is there (`npm i -g @github/copilot`)
|
|
69
|
+
and fetched with `npx` otherwise. `zen meta chat` needs neither: the Copilot SDK
|
|
70
|
+
it runs on is a dependency and brings its own runtime. `zen version` shows
|
|
71
|
+
both, and every `@zenera/*` package version beside them.
|
|
72
|
+
|
|
73
|
+
## Use
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
zen meta model --pick # choose the model once
|
|
77
|
+
zen meta run "what does this project do?" # ask it something
|
|
78
|
+
zen meta run acme /spec-sync-project # run one of the project's commands
|
|
79
|
+
git diff | zen meta run "what broke?" --allow-tool read
|
|
80
|
+
zen meta resume acme # carry on the last session
|
|
81
|
+
zen meta chat acme # talk it through, turn by turn
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The answer goes to stdout and the progress to stderr, so `> out.md` keeps the
|
|
85
|
+
answer alone. The whole run - prompt, every step, the answer - is logged under
|
|
86
|
+
`<project>/.tmp/logs/`, and the answer is saved beside it as markdown.
|
|
87
|
+
|
|
88
|
+
It may use every tool without asking: a prompt written for an editor expects
|
|
89
|
+
to read, write and run things, and a terminal has nobody watching to answer.
|
|
90
|
+
Narrow it with `--allow-tool`, or restore the asking with `--ask`.
|
|
91
|
+
|
|
92
|
+
`zen meta chat` takes the same model, key, tools and log as `run`, in a
|
|
93
|
+
conversation: the answer streams in, Esc stops a turn, `/help` lists the
|
|
94
|
+
chat's commands and `/<name>` runs a project command inside it. It ends by
|
|
95
|
+
printing the session, which `zen meta chat --resume` - or `--continue`, for
|
|
96
|
+
the last one - and `zen meta resume` both take.
|
|
97
|
+
|
|
98
|
+
The editor files `zen init` writes (`.vscode/` and the `.github/` tree) are
|
|
99
|
+
refreshed in the project before each run, because they are the brief the agent
|
|
100
|
+
works from and they describe this version of `zen`.
|
|
24
101
|
|
|
25
102
|
## Commands
|
|
26
103
|
|
|
27
104
|
```
|
|
28
|
-
zen meta run [project] "<question>"
|
|
29
|
-
zen meta run [project] /<name> [words]
|
|
30
|
-
zen meta run [project]
|
|
31
|
-
zen meta
|
|
32
|
-
zen meta
|
|
33
|
-
zen meta
|
|
34
|
-
zen meta
|
|
35
|
-
zen meta
|
|
105
|
+
zen meta run [project] "<question>" Ask it something.
|
|
106
|
+
zen meta run [project] /<name> [words] Run .github/skills/<name>/SKILL.md.
|
|
107
|
+
zen meta run [project] Pick one of those commands.
|
|
108
|
+
zen meta chat [project] [question] Talk it through, turn by turn.
|
|
109
|
+
zen meta prompts [project] List those commands.
|
|
110
|
+
zen meta resume [project] [session] Carry on a session that stopped.
|
|
111
|
+
zen meta model [ref] Show or set the model it uses.
|
|
112
|
+
zen meta dataset <verb> The cases a project is evaluated on.
|
|
113
|
+
zen meta finetune <verb> Tune the project on those cases.
|
|
36
114
|
```
|
|
37
115
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
116
|
+
Useful options: `--project`, `--model`, `--provider`, `--prompt-file`,
|
|
117
|
+
`--agent`, `--effort`, `--allow-tool`, `--ask`, `--add-dir`, `--retries`,
|
|
118
|
+
`--share`, `--events`, `--dry-run` (print the command, secrets masked),
|
|
119
|
+
`--json`. `zen meta --help`, `zen meta run --help`, `zen meta chat --help`,
|
|
120
|
+
`zen meta dataset --help` and `zen meta finetune --help` print the full tables. The tuning loop is
|
|
121
|
+
described in [docs/finetuning.md](https://github.com/zenera-ai/ZeneraNeo/blob/main/docs/finetuning.md).
|
|
122
|
+
|
|
123
|
+
## Models
|
|
124
|
+
|
|
125
|
+
The model is looked for in this order: `--model`, `ZENERA_META_MODEL` in the
|
|
126
|
+
shell, `ZENERA_META_MODEL` in the project's `.env`, what `zen meta model`
|
|
127
|
+
stored, then the project's `agents.yaml`. With none set it uses the best model
|
|
128
|
+
it knows of for a provider you hold a key for - through a gateway, the best one
|
|
129
|
+
the gateway serves - and says which on stderr.
|
|
130
|
+
|
|
131
|
+
`zen meta model <provider>/<id>` asks the provider a one-word question before
|
|
132
|
+
storing it, so a model that will not answer is never kept; one whose API
|
|
133
|
+
rejects Copilot's tools (gpt-4o and older) is refused. `--force` skips both.
|
|
134
|
+
|
|
135
|
+
## Credentials
|
|
136
|
+
|
|
137
|
+
The keyring is `zen`'s, so there is nothing new to configure:
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
zen key add openai
|
|
141
|
+
zen key ls --check
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Every credential reaches Copilot through its environment, never on a command
|
|
145
|
+
line, where other processes could read it. Vertex Claude goes through a local
|
|
146
|
+
relay that signs each request with your service account.
|
|
41
147
|
|
|
42
148
|
## Design
|
|
43
149
|
|
|
@@ -45,8 +151,20 @@ It reaches `zen` only through [src/host.ts](src/host.ts), which imports
|
|
|
45
151
|
`@zenera/cli/lib` and nothing else; [test/meta-boundary.test.ts](test/meta-boundary.test.ts)
|
|
46
152
|
holds that line. The CLI keeps what `zen init` and `zen open` also need - the
|
|
47
153
|
`.github/` editor tree and its templates, and the usage ledger. See §7.6 of the
|
|
48
|
-
[CLI design notes](
|
|
154
|
+
[CLI design notes](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/cli/DESIGN.md).
|
|
155
|
+
|
|
156
|
+
## The rest of the family
|
|
157
|
+
|
|
158
|
+
| Package | What it is |
|
|
159
|
+
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------- |
|
|
160
|
+
| [`@zenera/cli`](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/cli/README.md) | `zen` - agent projects on the command line |
|
|
161
|
+
| [`@zenera/neo`](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/neo/README.md) | the runtime - agents, models, tools, skills, memory |
|
|
162
|
+
| **`@zenera/meta`** | `zen meta` - the meta-agent that builds and tunes a project |
|
|
163
|
+
| [`@zenera/gym`](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/gym/README.md) | `zen gym` - a mock API from an openapi/swagger document |
|
|
164
|
+
| [`@zenera/rag`](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/rag/README.md) | `zen rag` - indexing and search for documents and API schemas |
|
|
165
|
+
| [`@zenera/view`](https://github.com/zenera-ai/ZeneraNeo/blob/main/packages/view/README.md) | `zen view` - a live local viewer for a folder |
|
|
49
166
|
|
|
50
167
|
## License
|
|
51
168
|
|
|
52
|
-
|
|
169
|
+
Early days and moving fast - issues, questions and pull requests are welcome.
|
|
170
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { PermissionRequest, PermissionRequestResult } from '@github/copilot-sdk';
|
|
2
|
+
/** One entry of `--allow-tool`: `read`, `shell(git:*)`, `write(README.md)`, `url(github.com)`. */
|
|
3
|
+
export interface Rule {
|
|
4
|
+
kind: string;
|
|
5
|
+
pattern?: string;
|
|
6
|
+
}
|
|
7
|
+
/** What the person at the chat said to one request. */
|
|
8
|
+
export type Answer = 'yes' | 'no' | 'always';
|
|
9
|
+
/** A request as a person reads it: which kind of tool, and on what. */
|
|
10
|
+
export interface Described {
|
|
11
|
+
kind: string;
|
|
12
|
+
subject: string;
|
|
13
|
+
intention?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Copilot's own list syntax, so a flag copied from a `zen meta run` line means
|
|
17
|
+
* the same thing here. Separators inside a pattern's parentheses do not split it.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parseRules(list: string | undefined): Rule[];
|
|
20
|
+
export declare function describe(request: PermissionRequest): Described;
|
|
21
|
+
/** Whether any rule covers the request. A compound shell line needs every command covered. */
|
|
22
|
+
export declare function allows(rules: readonly Rule[], request: PermissionRequest): boolean;
|
|
23
|
+
export interface PolicyOptions {
|
|
24
|
+
allowAll?: boolean;
|
|
25
|
+
ask?: boolean;
|
|
26
|
+
allowTool?: string;
|
|
27
|
+
/** asks the person at the chat; only called with `ask` */
|
|
28
|
+
prompt?: (request: Described) => Promise<Answer>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The callback for the SDK, with `zen meta run`'s defaults: every tool unless
|
|
32
|
+
* `--allow-tool` narrows it or `--ask` restores the asking. Named tools win over
|
|
33
|
+
* asking, and anything they leave out is asked about with `--ask` and refused
|
|
34
|
+
* without it. "Always" covers that kind of tool for the rest of the session.
|
|
35
|
+
*/
|
|
36
|
+
export declare function permissionPolicy(opts: PolicyOptions): (request: PermissionRequest) => Promise<PermissionRequestResult>;
|
|
37
|
+
//# sourceMappingURL=permissions.d.ts.map
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// packages/meta/src/chat/permissions.ts
|
|
2
|
+
//
|
|
3
|
+
// Whether `zen meta chat` lets the agent use a tool: the same three answers `zen meta run` gives copilot's flags
|
|
4
|
+
// (every tool, the ones `--allow-tool` names, or ask), decided in-process for the SDK's permission callback.
|
|
5
|
+
// Main: `permissionPolicy(opts)`, which returns the callback; also `parseRules`, `allows` and `describe`.
|
|
6
|
+
// Used by: `chat/run.ts`, which hands the callback to `openChat` and the asking to the chat screen.
|
|
7
|
+
/**
|
|
8
|
+
* Copilot's own list syntax, so a flag copied from a `zen meta run` line means
|
|
9
|
+
* the same thing here. Separators inside a pattern's parentheses do not split it.
|
|
10
|
+
*/
|
|
11
|
+
export function parseRules(list) {
|
|
12
|
+
const rules = [];
|
|
13
|
+
let depth = 0;
|
|
14
|
+
let word = '';
|
|
15
|
+
const push = () => {
|
|
16
|
+
const text = word.trim();
|
|
17
|
+
word = '';
|
|
18
|
+
if (!text) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const m = /^([\w-]+)\s*(?:\((.*)\))?$/s.exec(text);
|
|
22
|
+
rules.push(m ? { kind: m[1], pattern: m[2]?.trim() || undefined } : { kind: text });
|
|
23
|
+
};
|
|
24
|
+
for (const ch of list ?? '') {
|
|
25
|
+
if (ch === '(') {
|
|
26
|
+
depth += 1;
|
|
27
|
+
}
|
|
28
|
+
else if (ch === ')') {
|
|
29
|
+
depth = Math.max(0, depth - 1);
|
|
30
|
+
}
|
|
31
|
+
if ((ch === ',' || ch === ' ') && depth === 0) {
|
|
32
|
+
push();
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
word += ch;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
push();
|
|
39
|
+
return rules;
|
|
40
|
+
}
|
|
41
|
+
export function describe(request) {
|
|
42
|
+
const intention = 'intention' in request && typeof request.intention === 'string'
|
|
43
|
+
? request.intention
|
|
44
|
+
: undefined;
|
|
45
|
+
switch (request.kind) {
|
|
46
|
+
case 'shell':
|
|
47
|
+
return { kind: 'shell', subject: request.fullCommandText, intention };
|
|
48
|
+
case 'write':
|
|
49
|
+
return { kind: 'write', subject: request.fileName, intention };
|
|
50
|
+
case 'read':
|
|
51
|
+
return { kind: 'read', subject: request.path, intention };
|
|
52
|
+
case 'url':
|
|
53
|
+
return { kind: 'url', subject: request.url, intention };
|
|
54
|
+
case 'mcp':
|
|
55
|
+
return { kind: 'mcp', subject: `${request.serverName}/${request.toolName}`, intention };
|
|
56
|
+
default: {
|
|
57
|
+
const r = request;
|
|
58
|
+
return { kind: request.kind, subject: String(r.toolName ?? r.name ?? ''), intention };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** `git:*` is "git, with anything after"; a trailing `*` is a prefix; otherwise the whole of it. */
|
|
63
|
+
function matches(pattern, value) {
|
|
64
|
+
if (pattern.endsWith(':*')) {
|
|
65
|
+
const head = pattern.slice(0, -2);
|
|
66
|
+
return value === head || value.startsWith(`${head} `);
|
|
67
|
+
}
|
|
68
|
+
if (pattern.endsWith('*')) {
|
|
69
|
+
return value.startsWith(pattern.slice(0, -1));
|
|
70
|
+
}
|
|
71
|
+
return value === pattern;
|
|
72
|
+
}
|
|
73
|
+
const pathMatches = (pattern, path) => matches(pattern, path) ||
|
|
74
|
+
matches(pattern, path.split('/').pop() ?? path) ||
|
|
75
|
+
path.endsWith(`/${pattern}`);
|
|
76
|
+
/** Whether any rule covers the request. A compound shell line needs every command covered. */
|
|
77
|
+
export function allows(rules, request) {
|
|
78
|
+
return rules.some((rule) => {
|
|
79
|
+
if (rule.kind !== request.kind) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
const pattern = rule.pattern;
|
|
83
|
+
if (!pattern) {
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
switch (request.kind) {
|
|
87
|
+
case 'shell': {
|
|
88
|
+
const segments = request.commandSegments?.map((s) => s.fullCommandText.trim());
|
|
89
|
+
const lines = segments?.length ? segments : [request.fullCommandText.trim()];
|
|
90
|
+
return lines.every((line) => matches(pattern, line));
|
|
91
|
+
}
|
|
92
|
+
case 'write':
|
|
93
|
+
return pathMatches(pattern, request.fileName);
|
|
94
|
+
case 'read':
|
|
95
|
+
return pathMatches(pattern, request.path);
|
|
96
|
+
case 'url': {
|
|
97
|
+
let host = request.url;
|
|
98
|
+
try {
|
|
99
|
+
host = new URL(request.url).hostname;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// Not a url the parser takes: the pattern is matched against it as written.
|
|
103
|
+
}
|
|
104
|
+
return matches(pattern, host) || host.endsWith(`.${pattern}`);
|
|
105
|
+
}
|
|
106
|
+
case 'mcp':
|
|
107
|
+
return pattern === request.serverName || pattern === request.toolName;
|
|
108
|
+
default:
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The callback for the SDK, with `zen meta run`'s defaults: every tool unless
|
|
115
|
+
* `--allow-tool` narrows it or `--ask` restores the asking. Named tools win over
|
|
116
|
+
* asking, and anything they leave out is asked about with `--ask` and refused
|
|
117
|
+
* without it. "Always" covers that kind of tool for the rest of the session.
|
|
118
|
+
*/
|
|
119
|
+
export function permissionPolicy(opts) {
|
|
120
|
+
const rules = parseRules(opts.allowTool);
|
|
121
|
+
const everything = opts.allowAll || (!opts.ask && rules.length === 0);
|
|
122
|
+
const granted = new Set();
|
|
123
|
+
return async (request) => {
|
|
124
|
+
if (request.managedApprovalRequired) {
|
|
125
|
+
return { kind: 'no-result' };
|
|
126
|
+
}
|
|
127
|
+
if (everything || granted.has(request.kind) || allows(rules, request)) {
|
|
128
|
+
return { kind: 'approve-once' };
|
|
129
|
+
}
|
|
130
|
+
if (!opts.ask || !opts.prompt) {
|
|
131
|
+
return {
|
|
132
|
+
kind: 'reject',
|
|
133
|
+
feedback: `Not allowed: this chat only allows ${opts.allowTool}.`,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const answer = await opts.prompt(describe(request));
|
|
137
|
+
if (answer === 'always') {
|
|
138
|
+
granted.add(request.kind);
|
|
139
|
+
}
|
|
140
|
+
// Copilot tells the model a person said no; there is nothing to add to that.
|
|
141
|
+
return answer === 'no' ? { kind: 'reject' } : { kind: 'approve-once' };
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=permissions.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type * as Projects from '@zenera/engine';
|
|
2
|
+
import { type Selection } from '../prepare.ts';
|
|
3
|
+
import { type Connect } from './session.ts';
|
|
4
|
+
import type { Screen } from './tui.tsx';
|
|
5
|
+
export interface ChatFlags extends Selection {
|
|
6
|
+
agent?: string;
|
|
7
|
+
effort?: string;
|
|
8
|
+
events?: string;
|
|
9
|
+
'allow-all'?: boolean;
|
|
10
|
+
'allow-tool'?: string;
|
|
11
|
+
ask?: boolean;
|
|
12
|
+
'add-dir'?: string[];
|
|
13
|
+
}
|
|
14
|
+
export interface RunChat {
|
|
15
|
+
values: ChatFlags;
|
|
16
|
+
project: Projects.Project;
|
|
17
|
+
cwd: string;
|
|
18
|
+
/** the first question, from the command line */
|
|
19
|
+
first?: string;
|
|
20
|
+
retries: number;
|
|
21
|
+
/** injected by the tests, which want no runtime */
|
|
22
|
+
connect?: Connect;
|
|
23
|
+
/** likewise: the tests have no terminal to draw on */
|
|
24
|
+
screen?: (screen: Screen) => Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export declare function runChat(opts: RunChat): Promise<void>;
|
|
27
|
+
//# sourceMappingURL=run.d.ts.map
|
package/dist/chat/run.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// packages/meta/src/chat/run.ts
|
|
2
|
+
//
|
|
3
|
+
// `zen meta chat` from flags to the last line: prepare the model and key, open the log, start the Vertex relay
|
|
4
|
+
// when Claude needs it, open the SDK session, hand it to the chat screen, and on the way out record the
|
|
5
|
+
// session's usage and say how to carry on.
|
|
6
|
+
// Main: `runChat(opts)`.
|
|
7
|
+
// Used by: `command.ts`, whose `chat()` checks the terminal and the project and then calls this.
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { join, resolve } from 'node:path';
|
|
10
|
+
import { appendUsage, copilotEventLog, cyan, dim, History, LEDGER_ENV, ledgerPath, META_SESSION_ENV, note, resolveTheme, } from "../host.js";
|
|
11
|
+
import { absorb, openLog, recordSession } from "../launch.js";
|
|
12
|
+
import { announce, prepare } from "../prepare.js";
|
|
13
|
+
import { listPrompts, loadPrompt } from "../prompts.js";
|
|
14
|
+
import { startVertexRelay } from "../relay.js";
|
|
15
|
+
import { usageReporter } from "../reporter.js";
|
|
16
|
+
import { SOURCE_LABELS } from "../model.js";
|
|
17
|
+
import { sessionTotals, Tally } from "../tokens.js";
|
|
18
|
+
import { permissionPolicy } from "./permissions.js";
|
|
19
|
+
import { googleToken, openChat, providerConfig, runtimeEnv, } from "./session.js";
|
|
20
|
+
export async function runChat(opts) {
|
|
21
|
+
const { project } = opts;
|
|
22
|
+
const prepared = await prepare(opts.values, project);
|
|
23
|
+
const { values, wiring, chosen } = prepared;
|
|
24
|
+
const resumed = values.resume;
|
|
25
|
+
// `prepare` names a fresh session unless --continue, which the caller has already resolved.
|
|
26
|
+
const session = prepared.session ?? randomUUID();
|
|
27
|
+
announce(prepared, project);
|
|
28
|
+
recordSession(project.dir, session);
|
|
29
|
+
const log = openLog(project.dir, new Date(), session);
|
|
30
|
+
note(`log ${log.path}`);
|
|
31
|
+
log.line(`zen meta chat ${new Date().toISOString()}`);
|
|
32
|
+
log.line(`project ${project.name} ${project.dir}`);
|
|
33
|
+
log.line(`model ${chosen.ref} from ${SOURCE_LABELS[chosen.from]}`);
|
|
34
|
+
log.line(`session ${session}${resumed ? ' (resumed)' : ''}`);
|
|
35
|
+
const relay = wiring.relay ? await startVertexRelay(wiring.relay) : undefined;
|
|
36
|
+
if (relay) {
|
|
37
|
+
wiring.env.COPILOT_PROVIDER_BASE_URL = relay.url;
|
|
38
|
+
log.line(`relay ${relay.url} -> vertex rawPredict`);
|
|
39
|
+
}
|
|
40
|
+
// As with `run`: every zen command the agent runs lands in the same ledger, tagged with this session.
|
|
41
|
+
const ledger = ledgerPath(project.dir);
|
|
42
|
+
const env = {
|
|
43
|
+
...runtimeEnv(wiring.env),
|
|
44
|
+
...(ledger ? { [LEDGER_ENV]: ledger } : {}),
|
|
45
|
+
[META_SESSION_ENV]: session,
|
|
46
|
+
};
|
|
47
|
+
const tally = new Tally();
|
|
48
|
+
const record = values.events ? copilotEventLog(resolve(opts.cwd, values.events)) : undefined;
|
|
49
|
+
const reporter = usageReporter(project.dir);
|
|
50
|
+
// The log keeps what `run`'s log keeps, through the same folding.
|
|
51
|
+
const logSink = {
|
|
52
|
+
answer: () => undefined,
|
|
53
|
+
narrate: (line) => log.line(line),
|
|
54
|
+
detail: (line) => log.line(line),
|
|
55
|
+
warn: (line) => log.line(`! ${line}`),
|
|
56
|
+
};
|
|
57
|
+
const folded = { answer: '', exitCode: 0, events: [] };
|
|
58
|
+
// Paths inside the project read better from where the agent stands.
|
|
59
|
+
const relative = (text) => text.replaceAll(`${project.dir}/`, '');
|
|
60
|
+
const bridge = {};
|
|
61
|
+
const decide = permissionPolicy({
|
|
62
|
+
allowAll: values['allow-all'],
|
|
63
|
+
ask: values.ask,
|
|
64
|
+
allowTool: values['allow-tool'],
|
|
65
|
+
prompt: (request) => bridge.onAsk?.({ ...request, subject: relative(request.subject) }) ??
|
|
66
|
+
Promise.resolve('no'),
|
|
67
|
+
});
|
|
68
|
+
let chat;
|
|
69
|
+
const startedAt = new Date();
|
|
70
|
+
try {
|
|
71
|
+
chat = await openChat({
|
|
72
|
+
dir: project.dir,
|
|
73
|
+
model: wiring.env.COPILOT_MODEL ?? wiring.model,
|
|
74
|
+
provider: providerConfig(wiring.env, wiring.keyFile ? googleToken(wiring.keyFile) : undefined),
|
|
75
|
+
env,
|
|
76
|
+
sessionId: session,
|
|
77
|
+
resume: Boolean(resumed),
|
|
78
|
+
agent: values.agent,
|
|
79
|
+
effort: values.effort,
|
|
80
|
+
addDirs: values['add-dir']?.map((d) => resolve(opts.cwd, d)),
|
|
81
|
+
decide,
|
|
82
|
+
retries: opts.retries,
|
|
83
|
+
connect: opts.connect,
|
|
84
|
+
onRaw: (event) => {
|
|
85
|
+
// The log helpers take copilot's JSONL shape, which an SDK event already is.
|
|
86
|
+
const line = event;
|
|
87
|
+
record?.event(line);
|
|
88
|
+
folded.events.length = 0;
|
|
89
|
+
absorb(line, folded, logSink, Infinity);
|
|
90
|
+
},
|
|
91
|
+
onEvent: (event) => {
|
|
92
|
+
if (event.type === 'usage') {
|
|
93
|
+
tally.add(event.call);
|
|
94
|
+
record?.call(event.call);
|
|
95
|
+
appendUsage(project.dir, {
|
|
96
|
+
kind: 'meta.call',
|
|
97
|
+
ts: new Date(Date.parse(event.call.startedAt) + event.call.durationMs).toISOString(),
|
|
98
|
+
...event.call,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
else if (event.type === 'message' && event.tools === 0 && event.text.trim()) {
|
|
102
|
+
log.line('');
|
|
103
|
+
log.line('--- answer ---');
|
|
104
|
+
log.line(event.text.trim());
|
|
105
|
+
log.saveAnswer(event.text.trim());
|
|
106
|
+
}
|
|
107
|
+
else if (event.type === 'retry') {
|
|
108
|
+
log.line(`--- resume ${event.attempt}: ${event.reason} ---`);
|
|
109
|
+
}
|
|
110
|
+
else if (event.type === 'tool') {
|
|
111
|
+
event = { ...event, subject: relative(event.subject) };
|
|
112
|
+
}
|
|
113
|
+
bridge.onEvent?.(event);
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
const screen = opts.screen ?? (await import("./tui.js")).chatScreen;
|
|
117
|
+
await screen({
|
|
118
|
+
chat,
|
|
119
|
+
bridge,
|
|
120
|
+
history: new History(join(project.dir, '.tmp', 'logs', 'meta.history')),
|
|
121
|
+
theme: await resolveTheme(),
|
|
122
|
+
title: {
|
|
123
|
+
owner: prepared.owner,
|
|
124
|
+
model: wiring.model,
|
|
125
|
+
project: project.name,
|
|
126
|
+
resumed: Boolean(resumed),
|
|
127
|
+
},
|
|
128
|
+
status: () => (tally.calls > 0 ? tally.toString() : ''),
|
|
129
|
+
prompts: {
|
|
130
|
+
list: () => listPrompts(project.dir),
|
|
131
|
+
load: (name) => loadPrompt(project.dir, name),
|
|
132
|
+
},
|
|
133
|
+
first: opts.first,
|
|
134
|
+
onSend: (shown, prompt) => {
|
|
135
|
+
log.line('');
|
|
136
|
+
log.line(`--- you: ${shown.split('\n')[0]} ---`);
|
|
137
|
+
if (prompt !== shown) {
|
|
138
|
+
log.line(prompt);
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
await chat?.close();
|
|
145
|
+
const models = sessionTotals(session);
|
|
146
|
+
if (models) {
|
|
147
|
+
appendUsage(project.dir, {
|
|
148
|
+
kind: 'meta.session',
|
|
149
|
+
ts: new Date().toISOString(),
|
|
150
|
+
session,
|
|
151
|
+
models,
|
|
152
|
+
exitCode: 0,
|
|
153
|
+
resumes: 0,
|
|
154
|
+
startedAt: startedAt.toISOString(),
|
|
155
|
+
durationMs: Date.now() - startedAt.getTime(),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (tally.calls > 0) {
|
|
159
|
+
log.line('');
|
|
160
|
+
log.line(`tokens ${tally.toString()}`);
|
|
161
|
+
}
|
|
162
|
+
reporter.stop();
|
|
163
|
+
await relay?.close();
|
|
164
|
+
log.close();
|
|
165
|
+
}
|
|
166
|
+
if (tally.calls > 0) {
|
|
167
|
+
note(dim(`tokens ${tally.toString()}`));
|
|
168
|
+
}
|
|
169
|
+
note(dim(`carry on: zen meta chat ${project.name} --resume ${session}`));
|
|
170
|
+
note(cyan(log.path));
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=run.js.map
|