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/cost.js ADDED
@@ -0,0 +1,278 @@
1
+ 'use strict';
2
+ // Cost of GLM usage at API list price. The source of truth is the engine's
3
+ // own per-request ledger (model_usage in <session home>/.zcode/cli/db/
4
+ // db.sqlite): every request of the implementer, its subagents and the visual
5
+ // verifier, with cached input split out (GLM agents run ~95% cached, so
6
+ // pricing all input at the full rate would overstate cost ~5x). Sessions
7
+ // without an engine DB fall back to the record's usageTotal (no cache split:
8
+ // marked `estimate`). Read-only; never blocks the engine (WAL readers).
9
+ const fs = require('node:fs');
10
+ const os = require('node:os');
11
+ const path = require('node:path');
12
+ const { spawnSync } = require('node:child_process');
13
+ const store = require('./store.js');
14
+
15
+ // USD per million tokens, Z.ai API list prices. ZCODE_PRICES (JSON, same
16
+ // shape, keyed by model id, case-insensitive) overrides or adds models.
17
+ const LIST_PRICES = {
18
+ 'GLM-5.3-Flash': { input: 0.15, cached: 0.03, output: 0.5 },
19
+ 'GLM-5.3': { input: 1.4, cached: 0.26, output: 4.4 },
20
+ };
21
+
22
+ function priceTable(env = process.env) {
23
+ const table = {};
24
+ for (const [k, v] of Object.entries(LIST_PRICES)) table[k.toLowerCase()] = v;
25
+ if (env.ZCODE_PRICES) {
26
+ try {
27
+ const extra = JSON.parse(env.ZCODE_PRICES);
28
+ for (const [k, v] of Object.entries(extra || {})) {
29
+ if (v && typeof v === 'object') table[k.toLowerCase()] = { ...table[k.toLowerCase()], ...v };
30
+ }
31
+ } catch {
32
+ /* ignored: list prices */
33
+ }
34
+ }
35
+ return table;
36
+ }
37
+
38
+ // USD for one model's token counts, or null when the model has no price.
39
+ // `input` includes cached and cache-write tokens, as the engine records it.
40
+ function priceOf(model, { input = 0, cached = 0, cacheWrite = 0, output = 0 }, env = process.env) {
41
+ const p = priceTable(env)[String(model || '').toLowerCase()];
42
+ if (!p) return null;
43
+ const fresh = Math.max(0, input - cached - cacheWrite);
44
+ return (fresh * p.input + cached * (p.cached ?? p.input) + cacheWrite * (p.cacheWrite ?? p.input) + output * p.output) / 1e6;
45
+ }
46
+
47
+ // --- sqlite (node:sqlite on Node >= 22.5, else the sqlite3 CLI) ---------------
48
+
49
+ let nodeSqlite;
50
+ function loadNodeSqlite() {
51
+ if (nodeSqlite !== undefined) return nodeSqlite;
52
+ const emit = process.emitWarning;
53
+ process.emitWarning = (w, ...rest) => (/sqlite/i.test(String(w)) ? undefined : emit.call(process, w, ...rest));
54
+ try {
55
+ nodeSqlite = require('node:sqlite');
56
+ } catch {
57
+ nodeSqlite = null;
58
+ } finally {
59
+ process.emitWarning = emit;
60
+ }
61
+ return nodeSqlite;
62
+ }
63
+
64
+ // Rows of `sql` against `file` opened read-only, or null when unreadable.
65
+ function query(file, sql, params = []) {
66
+ if (!fs.existsSync(file)) return null;
67
+ const mod = loadNodeSqlite();
68
+ if (mod && mod.DatabaseSync) {
69
+ let db;
70
+ try {
71
+ db = new mod.DatabaseSync(file, { readOnly: true });
72
+ return db.prepare(sql).all(...params);
73
+ } catch {
74
+ return null;
75
+ } finally {
76
+ try {
77
+ if (db) db.close();
78
+ } catch {
79
+ /* closed */
80
+ }
81
+ }
82
+ }
83
+ if (params.length) {
84
+ // The CLI has no bind parameters; callers only bind paths, quoted here.
85
+ let i = 0;
86
+ sql = sql.replace(/\?/g, () => `'${String(params[i++]).replace(/'/g, "''")}'`);
87
+ }
88
+ const r = spawnSync('sqlite3', ['-readonly', '-json', file, sql], { encoding: 'utf8', timeout: 15000 });
89
+ if (r.status !== 0) return null;
90
+ try {
91
+ return r.stdout.trim() ? JSON.parse(r.stdout) : [];
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ const SUMS = `count(*) AS requests,
98
+ coalesce(sum(input_tokens), 0) AS input,
99
+ coalesce(sum(cache_read_input_tokens), 0) AS cached,
100
+ coalesce(sum(cache_creation_input_tokens), 0) AS cacheWrite,
101
+ coalesce(sum(output_tokens), 0) AS output`;
102
+
103
+ function engineDbOf(id, env = process.env) {
104
+ return path.join(store.sessionDir(id, env), 'home', '.zcode', 'cli', 'db', 'db.sqlite');
105
+ }
106
+
107
+ // Fold per-model rows into {requests, input, cached, cacheWrite, output,
108
+ // usd, models: {model: {...counts, usd}}, unpriced?: [models]}.
109
+ function fold(rows, env) {
110
+ const total = { requests: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, usd: 0, models: {} };
111
+ const unpriced = [];
112
+ for (const r of rows) {
113
+ const counts = {
114
+ requests: Number(r.requests) || 0,
115
+ input: Number(r.input) || 0,
116
+ cached: Number(r.cached) || 0,
117
+ cacheWrite: Number(r.cacheWrite) || 0,
118
+ output: Number(r.output) || 0,
119
+ };
120
+ const usd = priceOf(r.model, counts, env);
121
+ if (usd === null) unpriced.push(r.model);
122
+ total.models[r.model] = { ...counts, usd };
123
+ for (const k of ['requests', 'input', 'cached', 'cacheWrite', 'output']) total[k] += counts[k];
124
+ total.usd += usd || 0;
125
+ }
126
+ if (unpriced.length) total.unpriced = unpriced;
127
+ return total;
128
+ }
129
+
130
+ // Mtime-keyed cache so `zcode watch` can ask every 2 s without re-querying an
131
+ // idle session's DB.
132
+ const cache = new Map();
133
+ function dbStamp(file) {
134
+ let s = '';
135
+ for (const f of [file, `${file}-wal`]) {
136
+ try {
137
+ const st = fs.statSync(f);
138
+ s += `${st.mtimeMs}:${st.size};`;
139
+ } catch {
140
+ s += '-;';
141
+ }
142
+ }
143
+ return s;
144
+ }
145
+
146
+ // Cost of one zcode session (every invocation and resume, verifier and
147
+ // subagents included), or null when nothing is known.
148
+ function sessionCost(record, env = process.env) {
149
+ if (!record || !record.id) return null;
150
+ const file = engineDbOf(record.id, env);
151
+ const stamp = dbStamp(file);
152
+ const hit = cache.get(file);
153
+ if (hit && hit.stamp === stamp) return hit.cost;
154
+ let cost = null;
155
+ const rows = query(file, `SELECT model_id AS model, ${SUMS} FROM model_usage GROUP BY model_id`);
156
+ if (rows && rows.length) {
157
+ cost = fold(rows, env);
158
+ } else if (record.usageTotal && (record.usageTotal.inputTokens || record.usageTotal.outputTokens)) {
159
+ const u = record.usageTotal;
160
+ cost = fold([{ model: record.model, requests: u.modelRequests || 0, input: u.inputTokens || 0, output: u.outputTokens || 0 }], env);
161
+ cost.estimate = true; // no cache split: priced as uncached input
162
+ }
163
+ cache.set(file, { stamp, cost });
164
+ return cost;
165
+ }
166
+
167
+ const real = (p) => {
168
+ try {
169
+ return fs.realpathSync(p);
170
+ } catch {
171
+ return path.resolve(p);
172
+ }
173
+ };
174
+
175
+ // Is `p` the directory `dir` or inside it? (symlinks resolved: /var vs /private/var)
176
+ function within(p, dir) {
177
+ if (!p) return false;
178
+ const rel = path.relative(real(dir), real(p));
179
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
180
+ }
181
+
182
+ // zcode sessions whose workspace is `dir` or below it, newest first, each
183
+ // {id, status, model, label, cwd, createdAt, updatedAt, cost}.
184
+ function dirSessions(dir, env = process.env) {
185
+ const out = [];
186
+ for (const v of store.listSessions(env)) {
187
+ if (!within(v.cwd, dir) && !within(v.workspaceRoot, dir)) continue;
188
+ out.push({
189
+ id: v.id,
190
+ status: v.state === 'finished' ? v.status || 'finished' : v.state,
191
+ model: v.model,
192
+ label: v.label || null,
193
+ cwd: v.cwd,
194
+ createdAt: v.createdAt,
195
+ updatedAt: v.updatedAt,
196
+ cost: sessionCost(v, env),
197
+ });
198
+ }
199
+ return out;
200
+ }
201
+
202
+ // The desktop app's own sessions (its DB, not zcode's) whose directory is
203
+ // `dir` or below it. ZCODE_APP_DB overrides the path (tests).
204
+ function appDb(env = process.env) {
205
+ return env.ZCODE_APP_DB || path.join(env.HOME || os.homedir(), '.zcode', 'cli', 'db', 'db.sqlite');
206
+ }
207
+
208
+ function appSessions(dir, env = process.env) {
209
+ const file = appDb(env);
210
+ // The app stores the directory as it was opened: match the given and the
211
+ // symlink-resolved spelling.
212
+ const forms = [...new Set([path.resolve(dir), real(dir)])].map((d) => d.replace(/\/+$/, '') || '/');
213
+ const where = forms.map(() => '(s.directory = ? OR s.directory LIKE ?)').join(' OR ');
214
+ const rows = query(
215
+ file,
216
+ `SELECT s.id AS id, s.title AS title, s.directory AS cwd, m.model_id AS model, ${SUMS},
217
+ min(m.started_at) AS startedAt, max(coalesce(m.completed_at, m.started_at)) AS endedAt
218
+ FROM model_usage m JOIN session s ON s.id = m.session_id
219
+ WHERE ${where}
220
+ GROUP BY s.id, m.model_id`,
221
+ forms.flatMap((d) => [d, `${d === '/' ? '' : d}/%`])
222
+ );
223
+ if (!rows) return null;
224
+ const byId = new Map();
225
+ for (const r of rows) {
226
+ const e = byId.get(r.id) || { id: r.id, title: r.title, cwd: r.cwd, rows: [], startedAt: r.startedAt, endedAt: r.endedAt };
227
+ e.rows.push(r);
228
+ e.startedAt = Math.min(e.startedAt, r.startedAt);
229
+ e.endedAt = Math.max(e.endedAt, r.endedAt);
230
+ byId.set(r.id, e);
231
+ }
232
+ return [...byId.values()]
233
+ .map((e) => ({
234
+ id: e.id,
235
+ title: e.title,
236
+ cwd: e.cwd,
237
+ model: e.rows.map((r) => r.model).join(','),
238
+ createdAt: new Date(Number(e.startedAt)).toISOString(),
239
+ updatedAt: new Date(Number(e.endedAt)).toISOString(),
240
+ cost: fold(e.rows, env),
241
+ }))
242
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
243
+ }
244
+
245
+ function sumCosts(costs) {
246
+ const t = { requests: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, usd: 0 };
247
+ for (const c of costs) {
248
+ if (!c) continue;
249
+ for (const k of Object.keys(t)) t[k] += c[k] || 0;
250
+ if (c.estimate) t.estimate = true;
251
+ }
252
+ return t;
253
+ }
254
+
255
+ function formatUsd(usd) {
256
+ if (usd === null || usd === undefined) return '$?';
257
+ return usd < 10 ? `$${usd.toFixed(2)}` : `$${usd.toFixed(1)}`;
258
+ }
259
+
260
+ function formatTokens(n) {
261
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
262
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
263
+ return String(n);
264
+ }
265
+
266
+ module.exports = {
267
+ LIST_PRICES,
268
+ priceTable,
269
+ priceOf,
270
+ sessionCost,
271
+ dirSessions,
272
+ appSessions,
273
+ sumCosts,
274
+ formatUsd,
275
+ formatTokens,
276
+ engineDbOf,
277
+ query,
278
+ };
package/lib/engine.js ADDED
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+ // Engine resolution + builtin provider config (DESIGN §4).
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const crypto = require('node:crypto');
7
+ const { spawnSync } = require('node:child_process');
8
+
9
+ // The ZCode desktop app's engine, per platform (the app never puts it on
10
+ // PATH). Windows: %LOCALAPPDATA%\\Programs\\ZCode; Linux: the usual
11
+ // AppImage/deb/rpm extraction dirs.
12
+ function appBundleEngines(env = process.env) {
13
+ if (process.platform === 'darwin') {
14
+ return [
15
+ '/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs',
16
+ path.join(os.homedir(), 'Applications', 'ZCode.app', 'Contents', 'Resources', 'glm', 'zcode.cjs'),
17
+ ];
18
+ }
19
+ if (process.platform === 'win32') {
20
+ const local = env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
21
+ return [path.join(local, 'Programs', 'ZCode', 'resources', 'glm', 'zcode.cjs')];
22
+ }
23
+ return ['/opt/ZCode/resources/glm/zcode.cjs', '/usr/lib/zcode/resources/glm/zcode.cjs', '/usr/share/zcode/resources/glm/zcode.cjs'];
24
+ }
25
+ const APP_BUNDLE_ENGINE = appBundleEngines()[0];
26
+
27
+ // The engine this package was tested with: the @zcode-agent/engine
28
+ // dependency (1.0), which mirrors the app's Resources layout
29
+ // (glm/zcode.cjs + config/provider/zcode-builtin.json). null when it isn't
30
+ // installed or not built (a source checkout before `npm run build:engine`).
31
+ function packagedEngine() {
32
+ try {
33
+ const engine = require('@zcode-agent/engine');
34
+ return engine && engine.enginePath && fs.existsSync(engine.enginePath) ? engine.enginePath : null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ class EngineNotFoundError extends Error {
41
+ constructor(probed) {
42
+ super(
43
+ `ZCode engine not found. Probed:\n ${probed.join('\n ')}\n` +
44
+ 'Reinstall zcode-agent (its @zcode-agent/engine dependency ships the engine), ' +
45
+ 'install the ZCode app, or set ZAI_CODE_ENGINE to a zcode.cjs path.'
46
+ );
47
+ this.code = 'ZAI_NO_ENGINE';
48
+ this.probed = probed;
49
+ }
50
+ }
51
+
52
+ class BuiltinConfigNotFoundError extends Error {
53
+ constructor(probed) {
54
+ super(
55
+ `ZCode builtin provider config not found. Probed:\n ${probed.join('\n ')}\n` +
56
+ 'Set ZAI_CODE_BUILTIN_PROVIDER_CONFIG to the zcode-builtin.json path.'
57
+ );
58
+ this.code = 'ZAI_NO_BUILTIN_CONFIG';
59
+ this.probed = probed;
60
+ }
61
+ }
62
+
63
+ // Our own wrapper's real path. The engine resolver must never resolve to
64
+ // itself: `npm install -g` puts a `zcode` symlink on PATH, and before the
65
+ // 0.3.1 fix the PATH probe grabbed it as "the engine" (0.3.0 regression:
66
+ // every command then exited 4 probing <prefix>/config/provider/…).
67
+ const SELF_BIN_PATH = (() => {
68
+ try {
69
+ return fs.realpathSync(path.join(__dirname, '..', 'bin', 'zcode-agent.js'));
70
+ } catch {
71
+ return null;
72
+ }
73
+ })();
74
+
75
+ function isSelf(candidate) {
76
+ if (!SELF_BIN_PATH) return false;
77
+ try {
78
+ return fs.realpathSync(candidate) === SELF_BIN_PATH;
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ // Resolves a candidate that is either the zcode.cjs file itself or a
85
+ // directory containing it. strictFile (default true for everything except
86
+ // an explicit ZAI_CODE_ENGINE): a bare file is only accepted when it is
87
+ // literally named zcode.cjs — the engine bundle — so wrappers and launchers
88
+ // named `zcode` never pass. Our own binary is always rejected.
89
+ function resolveCandidate(candidate, { strictFile = true } = {}) {
90
+ if (isSelf(candidate)) return null;
91
+ let st;
92
+ try {
93
+ st = fs.statSync(candidate);
94
+ } catch {
95
+ return null;
96
+ }
97
+ if (st.isFile()) {
98
+ if (strictFile && path.basename(candidate) !== 'zcode.cjs') return null;
99
+ return path.resolve(candidate);
100
+ }
101
+ if (st.isDirectory()) {
102
+ const inner = path.join(candidate, 'zcode.cjs');
103
+ try {
104
+ if (fs.statSync(inner).isFile() && !isSelf(inner)) {
105
+ return path.resolve(inner);
106
+ }
107
+ } catch {
108
+ /* not there */
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+
114
+ function whichOnPath(bin, envPath) {
115
+ if (!envPath) return null;
116
+ for (const dir of envPath.split(path.delimiter)) {
117
+ if (!dir) continue;
118
+ const candidate = path.join(dir, bin);
119
+ try {
120
+ if (fs.statSync(candidate).isFile()) return candidate;
121
+ } catch {
122
+ /* keep scanning */
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ // First hit wins (DESIGN §4, revised 1.0): explicit env override, then the
129
+ // packaged engine (pinned and tested with this release), then the desktop
130
+ // app's bundle, then PATH/home probes — which only accept a real
131
+ // zcode.cjs, never a same-named wrapper. Throws EngineNotFoundError listing
132
+ // all probes.
133
+ function resolveEngine(env = process.env) {
134
+ const probed = [];
135
+ const candidates = [];
136
+ if (env.ZAI_CODE_ENGINE) candidates.push({ path: env.ZAI_CODE_ENGINE, strictFile: false });
137
+ const packaged = env.ZAI_CODE_NO_PACKAGED_ENGINE === '1' ? null : packagedEngine();
138
+ if (packaged) candidates.push({ path: packaged });
139
+ else probed.push('@zcode-agent/engine (not installed)');
140
+ for (const p of appBundleEngines(env)) candidates.push({ path: p });
141
+ const onPath = whichOnPath('zcode', env.PATH);
142
+ if (onPath) candidates.push({ path: onPath });
143
+ candidates.push({ path: path.join(os.homedir(), '.local', 'bin', 'zcode') });
144
+ candidates.push({ path: path.join(os.homedir(), '.zcode', 'runtime', 'zcode.cjs') });
145
+ for (const candidate of candidates) {
146
+ const resolved = resolveCandidate(candidate.path, {
147
+ strictFile: candidate.strictFile ?? true,
148
+ });
149
+ if (resolved) return resolved;
150
+ probed.push(candidate.path);
151
+ }
152
+ throw new EngineNotFoundError(probed);
153
+ }
154
+
155
+ // Engine-adjacent builtin provider config, or env override. Throws
156
+ // BuiltinConfigNotFoundError with the probed paths.
157
+ function resolveBuiltinProviderConfig(enginePath, env = process.env) {
158
+ const probed = [];
159
+ const candidates = [];
160
+ if (env.ZAI_CODE_BUILTIN_PROVIDER_CONFIG) {
161
+ candidates.push(env.ZAI_CODE_BUILTIN_PROVIDER_CONFIG);
162
+ }
163
+ // The engine's own layout (<dir>/provider/, used by @zcode-agent/engine),
164
+ // then the desktop app's (Resources/glm/zcode.cjs → Resources/config/provider/).
165
+ candidates.push(path.resolve(path.dirname(enginePath), 'provider', 'zcode-builtin.json'));
166
+ candidates.push(
167
+ path.resolve(
168
+ path.dirname(enginePath),
169
+ '..',
170
+ 'config',
171
+ 'provider',
172
+ 'zcode-builtin.json'
173
+ )
174
+ );
175
+ for (const candidate of candidates) {
176
+ try {
177
+ if (fs.statSync(candidate).isFile()) return path.resolve(candidate);
178
+ } catch {
179
+ /* fall through */
180
+ }
181
+ probed.push(candidate);
182
+ }
183
+ throw new BuiltinConfigNotFoundError(probed);
184
+ }
185
+
186
+ function sha256File(file) {
187
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
188
+ }
189
+
190
+ // `zcode.cjs version` run under the ISOLATED env (never the live HOME).
191
+ // Returns trimmed stdout or null.
192
+ function engineVersion(nodeBin, enginePath, childEnv) {
193
+ const res = spawnSync(nodeBin, [enginePath, 'version'], {
194
+ env: childEnv,
195
+ encoding: 'utf8',
196
+ timeout: 20000,
197
+ });
198
+ if (res.error || res.status !== 0) return null;
199
+ return (res.stdout || '').trim() || null;
200
+ }
201
+
202
+ module.exports = {
203
+ resolveEngine,
204
+ resolveBuiltinProviderConfig,
205
+ sha256File,
206
+ engineVersion,
207
+ EngineNotFoundError,
208
+ BuiltinConfigNotFoundError,
209
+ APP_BUNDLE_ENGINE,
210
+ appBundleEngines,
211
+ packagedEngine,
212
+ };