zcode-agent 0.0.0-stage → 1.1.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.
package/lib/key.js ADDED
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+ // API key resolution (DESIGN §5): ZAI_API_KEY env →
3
+ // ~/.zcode-agent/credentials.json ({"apiKey":"…"}, mode 600, written by
4
+ // `zcode-agent login`) → the ZCode desktop app's own Z.ai API key (1.0:
5
+ // people with the app need no login). The desktop key is read in place,
6
+ // never copied anywhere but the per-session provider config, and only a
7
+ // plain API key qualifies: OAuth tokens (credentials.json) are never read.
8
+ // The key is never printed, logged, or echoed by anything in this package.
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const { migrateRoot, rootDir, liveDir } = require('./isolation.js');
12
+
13
+ function credentialsPath(env = process.env) {
14
+ return path.join(rootDir(env), 'credentials.json');
15
+ }
16
+
17
+ class NoKeyError extends Error {
18
+ constructor() {
19
+ super('No API key configured. Run "zcode-agent login" (key on stdin), set ZAI_API_KEY, or add a Z.ai API key in the ZCode app.');
20
+ this.code = 'ZAI_NO_KEY';
21
+ }
22
+ }
23
+
24
+ function readJson(file) {
25
+ try {
26
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ const str = (v) => (typeof v === 'string' ? v.trim() : '');
33
+
34
+ // Reads {"apiKey": ...} from the credentials file; returns '' when absent.
35
+ function readCredentialsKey(file) {
36
+ const parsed = readJson(file);
37
+ return parsed ? str(parsed.apiKey) : '';
38
+ }
39
+
40
+ // The desktop's Z.ai API key, in the order the app itself uses it: the
41
+ // zai-api provider rule (v2/provider_config.json), then the builtin:zai
42
+ // provider of the CLI config, then the enabled builtin Z.ai providers of
43
+ // v2/config.json. Plan tokens of other shapes (start-plan JWTs) are skipped.
44
+ function readDesktopKey(live) {
45
+ const rules = readJson(path.join(live, 'v2', 'provider_config.json'));
46
+ const list = rules && rules.config && rules.config.providerConfigRules && rules.config.providerConfigRules.providerRules;
47
+ for (const rule of Array.isArray(list) ? list : []) {
48
+ const access = rule && rule.providerId === 'zai-api' && rule.config && rule.config.access;
49
+ if (access && access.type === 'api-key' && str(access.apiKey)) return str(access.apiKey);
50
+ }
51
+ const cli = readJson(path.join(live, 'cli', 'config.json'));
52
+ const zai = cli && cli.provider && cli.provider['builtin:zai'];
53
+ if (zai && zai.options && str(zai.options.apiKey)) return str(zai.options.apiKey);
54
+ const v2 = readJson(path.join(live, 'v2', 'config.json'));
55
+ for (const id of ['builtin:zai-coding-plan', 'builtin:zai', 'builtin:bigmodel-coding-plan', 'builtin:bigmodel']) {
56
+ const p = v2 && v2.provider && v2.provider[id];
57
+ if (p && p.enabled !== false && p.options && str(p.options.apiKey)) return str(p.options.apiKey);
58
+ }
59
+ return '';
60
+ }
61
+
62
+ // {key, source}: source is "env", "login" or "desktop". Throws NoKeyError
63
+ // when none holds a key.
64
+ function resolveKeyInfo(env = process.env) {
65
+ migrateRoot(env); // vacate legacy roots first
66
+ const fromEnv = str(env.ZAI_API_KEY);
67
+ if (fromEnv) return { key: fromEnv, source: 'env' };
68
+ const fromFile = readCredentialsKey(credentialsPath(env));
69
+ if (fromFile) return { key: fromFile, source: 'login' };
70
+ if (env.ZCODE_NO_DESKTOP_KEY !== '1') {
71
+ const fromDesktop = readDesktopKey(liveDir(env));
72
+ if (fromDesktop) return { key: fromDesktop, source: 'desktop' };
73
+ }
74
+ throw new NoKeyError();
75
+ }
76
+
77
+ function resolveKey(env = process.env) {
78
+ return resolveKeyInfo(env).key;
79
+ }
80
+
81
+ module.exports = { resolveKey, resolveKeyInfo, readDesktopKey, credentialsPath, rootDir, NoKeyError };
package/lib/models.js ADDED
@@ -0,0 +1,179 @@
1
+ 'use strict';
2
+ // The ONLY place model ids are chosen (DESIGN §7). The wrapper constructs
3
+ // every engine request itself, so nothing outside this allowlist can reach
4
+ // the wire.
5
+
6
+ const fs = require('node:fs');
7
+
8
+ const DEFAULT_MODEL = 'GLM-5.3-Flash';
9
+
10
+ // Case-insensitive aliases → official ids (exact ids pass through verbatim;
11
+ // they are exactly "GLM-5.3" / "GLM-5.3-Flash").
12
+ const ALIASES = new Map([
13
+ ['glm-5.3', 'GLM-5.3'],
14
+ ['5.3', 'GLM-5.3'],
15
+ ['53', 'GLM-5.3'],
16
+ ['glm-5.3-flash', 'GLM-5.3-Flash'],
17
+ ['5.3-flash', 'GLM-5.3-Flash'],
18
+ ['flash', 'GLM-5.3-Flash'],
19
+ ['53f', 'GLM-5.3-Flash'],
20
+ ]);
21
+
22
+ const SUPPORTED = ['glm-5.3', 'glm-5.3-flash'];
23
+
24
+ // Effort enum per the bundle's schema (DESIGN §8). `max` is the default and
25
+ // the only guaranteed-portable choice across both models.
26
+ const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
27
+
28
+ function normalizeEffort(input) {
29
+ const raw = String(input ?? '').trim().toLowerCase();
30
+ return EFFORT_LEVELS.includes(raw) ? raw : null;
31
+ }
32
+
33
+ // Returns the official model id, or null when input is not allowed.
34
+ function normalizeModel(input) {
35
+ const raw = String(input ?? '').trim();
36
+ if (!raw) return null;
37
+ return ALIASES.get(raw.toLowerCase()) ?? null;
38
+ }
39
+
40
+ function unknownModelMessage(input) {
41
+ return (
42
+ `unknown model "${input}". zcode-agent supports only ` +
43
+ `${SUPPORTED[0]} and ${SUPPORTED[1]} ` +
44
+ `(official ids: GLM-5.3, GLM-5.3-Flash).`
45
+ );
46
+ }
47
+
48
+ // --- supported effort levels per model ---------------------------------------
49
+ //
50
+ // The engine rejects an unsupported reasoning level only after it has been
51
+ // spawned and a session opened (GLM-5.3 refused `medium` that way in a real
52
+ // run). The levels live in the engine's builtin provider config
53
+ // (config/provider/zcode-builtin.json, the path `zcode doctor` reports):
54
+ // modelConfigRules.modelRules[] = {modelMatch: <regex>, config:
55
+ // {optionSpecs: {reasoningLevel: {values: […]}}}}. Later rules refine
56
+ // earlier ones (a generic `glm-5` rule lists disabled/enabled; the
57
+ // `glm-5.3(-flash)?` rule after it lists low/high/max), so the LAST matching
58
+ // rule that lists values wins. Unreadable or unmatched → the table below
59
+ // (observed in zcode-builtin.json shipped with ZCode 0.16.x).
60
+ const FALLBACK_LEVELS = {
61
+ 'GLM-5.3': ['low', 'high', 'max'],
62
+ 'GLM-5.3-Flash': ['low', 'high', 'max'],
63
+ };
64
+ const OFFICIAL_IDS = Object.keys(FALLBACK_LEVELS);
65
+
66
+ const levelCache = new Map(); // path:mtime:size → parsed rules
67
+
68
+ function readRules(file) {
69
+ try {
70
+ const st = fs.statSync(file);
71
+ const key = `${file}:${st.mtimeMs}:${st.size}`;
72
+ if (!levelCache.has(key)) {
73
+ const json = JSON.parse(fs.readFileSync(file, 'utf8'));
74
+ const rules = json && json.config && json.config.modelConfigRules && json.config.modelConfigRules.modelRules;
75
+ levelCache.set(key, Array.isArray(rules) ? rules : []);
76
+ }
77
+ return levelCache.get(key);
78
+ } catch {
79
+ return [];
80
+ }
81
+ }
82
+
83
+ function builtinConfigPath(env) {
84
+ try {
85
+ const { resolveEngine, resolveBuiltinProviderConfig } = require('./engine.js');
86
+ return resolveBuiltinProviderConfig(resolveEngine(env), env);
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ // Efforts (a subset of EFFORT_LEVELS, in enum order) the model accepts.
93
+ function supportedEfforts(model, { env = process.env, builtinConfig } = {}) {
94
+ const file = builtinConfig || builtinConfigPath(env);
95
+ let values = null;
96
+ if (file) {
97
+ for (const rule of readRules(file)) {
98
+ let match = false;
99
+ try {
100
+ match = new RegExp(`^(?:${rule.modelMatch})$`, 'i').test(model);
101
+ } catch {
102
+ /* a malformed pattern matches nothing */
103
+ }
104
+ const v = match && rule.config && rule.config.optionSpecs && rule.config.optionSpecs.reasoningLevel
105
+ && rule.config.optionSpecs.reasoningLevel.values;
106
+ if (Array.isArray(v)) values = v;
107
+ }
108
+ }
109
+ const levels = values ? EFFORT_LEVELS.filter((l) => values.includes(l)) : [];
110
+ return levels.length ? levels : FALLBACK_LEVELS[model] || [];
111
+ }
112
+
113
+ // {modelId: [levels]} for every supported model (doctor).
114
+ function modelLevels(opts) {
115
+ return Object.fromEntries(OFFICIAL_IDS.map((id) => [id, supportedEfforts(id, opts)]));
116
+ }
117
+
118
+ // --- image input per model ---------------------------------------------------
119
+ //
120
+ // Same resolution as reasoning levels: modelRules[].config.properties
121
+ // .inputFormat.supportsImage, last matching rule that sets it wins (the
122
+ // generic `glm-5.3(-flash)?` rule says false, the later `glm-5.3-flash` rule
123
+ // true). GLM-5.3 cannot see images: reading a PNG returns only an upload
124
+ // confirmation, so it must never be the judge of a screenshot.
125
+ const FALLBACK_IMAGES = { 'GLM-5.3': false, 'GLM-5.3-Flash': true };
126
+
127
+ function supportsImage(model, { env = process.env, builtinConfig } = {}) {
128
+ const file = builtinConfig || builtinConfigPath(env);
129
+ let value = null;
130
+ if (file) {
131
+ for (const rule of readRules(file)) {
132
+ let match = false;
133
+ try {
134
+ match = new RegExp(`^(?:${rule.modelMatch})$`, 'i').test(model);
135
+ } catch {
136
+ /* a malformed pattern matches nothing */
137
+ }
138
+ if (!match) continue;
139
+ const v = rule.config && rule.config.properties && rule.config.properties.inputFormat
140
+ && rule.config.properties.inputFormat.supportsImage;
141
+ if (typeof v === 'boolean') value = v;
142
+ }
143
+ }
144
+ return value === null ? FALLBACK_IMAGES[model] === true : value;
145
+ }
146
+
147
+ // {modelId: bool} for every supported model (doctor).
148
+ function modelVision(opts) {
149
+ return Object.fromEntries(OFFICIAL_IDS.map((id) => [id, supportsImage(id, opts)]));
150
+ }
151
+
152
+ // The first image-capable model: judges screenshots for the visual verifier.
153
+ function visionModel(opts) {
154
+ return OFFICIAL_IDS.find((id) => supportsImage(id, opts)) || DEFAULT_MODEL;
155
+ }
156
+
157
+ // null when `effort` is usable with `model`, else the one-line refusal.
158
+ // `source` names where the value came from ("--effort", "contract effort").
159
+ function effortProblem(model, effort, { source = '--effort', ...opts } = {}) {
160
+ const levels = supportedEfforts(model, opts);
161
+ if (levels.includes(effort)) return null;
162
+ return `${source} ${effort} is not supported by ${model} (supported: ${levels.join(', ')}).`;
163
+ }
164
+
165
+ module.exports = {
166
+ supportsImage,
167
+ modelVision,
168
+ visionModel,
169
+ supportedEfforts,
170
+ modelLevels,
171
+ effortProblem,
172
+ FALLBACK_LEVELS,
173
+ DEFAULT_MODEL,
174
+ normalizeModel,
175
+ unknownModelMessage,
176
+ normalizeEffort,
177
+ EFFORT_LEVELS,
178
+ SUPPORTED,
179
+ };