@anytowork/cli 0.12.29 → 0.12.31
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 +37 -7
- package/package.json +1 -1
- package/src/apply-backoff.js +62 -0
- package/src/chat-commands.js +2 -2
- package/src/cli-parse.js +33 -0
- package/src/error-map.js +7 -0
- package/src/format.js +6 -4
- package/src/hire-commands.js +39 -5
- package/src/index.js +75 -9
- package/src/listen-command.js +14 -2
- package/src/listener/prompt.js +20 -1
- package/src/listener/run.js +23 -1
- package/src/model-pledge.js +44 -12
- package/src/mt/collect.js +316 -0
- package/src/mt/commands.js +502 -0
- package/src/mt/readers.js +278 -0
- package/src/mt/text.js +190 -0
- package/src/mt/workdirs.js +145 -0
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
// v0.36.0 model and usage trust: `anytowork model policy`, `anytowork workdir`, `anytowork usage` (contract v1 section 10),
|
|
2
|
+
// plus two hooks used by other commands: the policy snapshot sent with an application, and the records sent before a
|
|
3
|
+
// delivery.
|
|
4
|
+
//
|
|
5
|
+
// Exit codes: 0 done / 1 refused or failed / 2 a problem with the arguments / 4 the CLI is too old.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import { authedGetWithRefresh, authedPostWithRefresh, authedPutWithRefresh } from '../api.js';
|
|
10
|
+
import { UPGRADE_COMMAND } from '../client-version.js';
|
|
11
|
+
import { t, MT_HELP } from './text.js';
|
|
12
|
+
import { ensureLocalWorkdir, readRegistry, workdirsForScope } from './workdirs.js';
|
|
13
|
+
import {
|
|
14
|
+
collectUsage, sendRows, readState, writeState, noteRecordMode, localCheck, getUsageStatus, gatherLocal,
|
|
15
|
+
parseScope, parseSince, isZero, localKey, errorCode, SCHEMA, CONTENT_FIELDS,
|
|
16
|
+
} from './collect.js';
|
|
17
|
+
import { readLocalLogs } from './readers.js';
|
|
18
|
+
|
|
19
|
+
export { MT_HELP };
|
|
20
|
+
const POLICY_PATH = '/api/v1/agent/model-policy';
|
|
21
|
+
|
|
22
|
+
export function isMtCommand(command) {
|
|
23
|
+
return typeof command === 'string' && /^(model|workdir|usage):/.test(command);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function isMtHelp(command) {
|
|
27
|
+
return command === 'model:help' || command === 'workdir:help' || command === 'usage:help';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ---------------------------------------------------------------- refusals in plain words
|
|
31
|
+
|
|
32
|
+
function varsOf(e) {
|
|
33
|
+
const b = e && e.body && typeof e.body === 'object' ? e.body : {};
|
|
34
|
+
const d = b.detail && typeof b.detail === 'object' ? b.detail : b;
|
|
35
|
+
return d.vars && typeof d.vars === 'object' ? d.vars : {};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Platform refusal -> { exit, code, text } or null when it is not one of ours. */
|
|
39
|
+
export function mapMtError(e, env = process.env) {
|
|
40
|
+
if (e && e.upgradeRequired) return { exit: 4, code: 'cli_upgrade_required', text: e.message };
|
|
41
|
+
const code = errorCode(e);
|
|
42
|
+
const v = varsOf(e);
|
|
43
|
+
switch (code) {
|
|
44
|
+
case 'mt_feature_off': return { exit: 1, code, text: t('usage.feature_off', {}, env) };
|
|
45
|
+
case 'mt_policy_invalid': {
|
|
46
|
+
const n = Number.isInteger(v.index) ? v.index + 1 : null;
|
|
47
|
+
const where = v.field === 'primary' && n ? t('policy.err.where.primary', { n }, env)
|
|
48
|
+
: (v.field === 'roles' && n ? t('policy.err.where.roles', { n }, env) : t('policy.err.where.other', {}, env));
|
|
49
|
+
if (v.field === 'roles' && n) return { exit: 1, code, text: t('policy.err.invalid_role', { n }, env) };
|
|
50
|
+
return { exit: 1, code, text: t('policy.err.invalid', { where }, env) };
|
|
51
|
+
}
|
|
52
|
+
case 'mt_policy_role_too_long': return { exit: 1, code, text: t('policy.err.role_too_long', { n: Number.isInteger(v.index) ? v.index + 1 : '?', max: v.max != null ? v.max : 20 }, env) };
|
|
53
|
+
case 'mt_policy_role_note_too_long': return { exit: 1, code, text: t('policy.err.role_note_too_long', { n: Number.isInteger(v.index) ? v.index + 1 : '?', max: v.max != null ? v.max : 60 }, env) };
|
|
54
|
+
case 'mt_policy_too_many_roles': return { exit: 1, code, text: t('policy.err.too_many_roles', { max: v.max != null ? v.max : 5 }, env) };
|
|
55
|
+
case 'mt_policy_note_too_long': return { exit: 1, code, text: t('policy.err.note_too_long', { max: v.max != null ? v.max : 200 }, env) };
|
|
56
|
+
case 'mt_workdir_forbidden': return { exit: 1, code, text: t('workdir.err.forbidden', {}, env) };
|
|
57
|
+
case 'mt_scope_closed': return { exit: 1, code, text: t('workdir.err.closed', {}, env) };
|
|
58
|
+
case 'mt_content_forbidden': return { exit: 1, code, text: t('usage.content_forbidden', { n: '?', field: v.field || 'content' }, env) };
|
|
59
|
+
default: return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------- policy
|
|
64
|
+
|
|
65
|
+
function rawOf(m) {
|
|
66
|
+
if (m == null) return '';
|
|
67
|
+
if (typeof m === 'string') return m;
|
|
68
|
+
return m.raw || m.key || m.display_name || '';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The policy as the application body carries it (contract A2 request shape; roles = { name, model, note? }). */
|
|
72
|
+
export function policyBody(p) {
|
|
73
|
+
if (!p) return null;
|
|
74
|
+
const primary = (Array.isArray(p.primary) ? p.primary : []).map(rawOf).filter(Boolean);
|
|
75
|
+
if (!primary.length) return null;
|
|
76
|
+
const roles = (Array.isArray(p.roles) ? p.roles : [])
|
|
77
|
+
.map((r) => {
|
|
78
|
+
const o = { name: r.name, model: rawOf(r.model) };
|
|
79
|
+
if (r.note) o.note = r.note;
|
|
80
|
+
return o;
|
|
81
|
+
})
|
|
82
|
+
.filter((r) => r.name && r.model);
|
|
83
|
+
return { primary, roles, note: p.note || null };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The model policy for THIS application (task apply / hire apply), built from the flags of that one command:
|
|
88
|
+
* --primary a,b [--role <name>=<model>[=<note>]]... [--note "..."] -> the full policy of this job;
|
|
89
|
+
* --models a,b (task apply) / --model-label a (hire apply) -> main models only (the old way);
|
|
90
|
+
* nothing at all -> no field is sent, the platform copies
|
|
91
|
+
* the Agent's default policy.
|
|
92
|
+
* Returns { policy } (policy may be null) or { error: { code, text } } for a local argument problem.
|
|
93
|
+
* The policy is never written back as the default one: it belongs to this job only (contract v1.1, MT-43).
|
|
94
|
+
*/
|
|
95
|
+
export function policyForApply({ models = [], primary = null, roles = [], note = null } = {}, env = process.env) {
|
|
96
|
+
const main = primary != null && String(primary).trim() !== '' ? splitList(primary) : (models || []);
|
|
97
|
+
const rolesRaw = Array.isArray(roles) ? roles : [];
|
|
98
|
+
const hasNote = note != null && String(note).trim() !== '';
|
|
99
|
+
if (!main.length) {
|
|
100
|
+
if (rolesRaw.length || hasNote) return { error: { code: 'primary_required', text: t('apply.need_primary', {}, env) } };
|
|
101
|
+
return { policy: null };
|
|
102
|
+
}
|
|
103
|
+
if (main.length > 2) {
|
|
104
|
+
if (primary != null && String(primary).trim() !== '') return { error: { code: 'too_many_primary', text: t('policy.too_many_primary', {}, env) } };
|
|
105
|
+
}
|
|
106
|
+
const outRoles = [];
|
|
107
|
+
for (const raw of rolesRaw) {
|
|
108
|
+
const r = parseRole(raw);
|
|
109
|
+
if (r.error) return { error: { code: r.error, text: t(`policy.${r.error}`, {}, env) } };
|
|
110
|
+
outRoles.push(r);
|
|
111
|
+
}
|
|
112
|
+
return { policy: { primary: main.slice(0, 2), roles: outRoles, note: hasNote ? String(note).trim() : null } };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* "<name>=<model>[=<note>]" -> { name, model, note? } or { error }. Cut at the first two "=": the model name has no
|
|
117
|
+
* "=", and neither the name nor the note may contain one. The name is the Agent's own wording (any language); the
|
|
118
|
+
* platform checks the length limits and answers with the entry number and the limit, so nothing is hard-coded here.
|
|
119
|
+
*/
|
|
120
|
+
export function parseRole(raw) {
|
|
121
|
+
const s = String(raw || '').trim();
|
|
122
|
+
const i = s.indexOf('=');
|
|
123
|
+
if (i <= 0) return { error: 'bad_role' };
|
|
124
|
+
const j = s.indexOf('=', i + 1);
|
|
125
|
+
const name = s.slice(0, i).replace(/\s+/g, ' ').trim();
|
|
126
|
+
const model = (j < 0 ? s.slice(i + 1) : s.slice(i + 1, j)).trim();
|
|
127
|
+
const note = j < 0 ? '' : s.slice(j + 1).replace(/\s+/g, ' ').trim();
|
|
128
|
+
if (!name || !model) return { error: 'bad_role' };
|
|
129
|
+
if (note.includes('=')) return { error: 'bad_role_eq' };
|
|
130
|
+
return note ? { name, model, note } : { name, model };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function splitList(raw) {
|
|
134
|
+
return String(raw == null ? '' : raw).split(/[,,]/).map((s) => s.trim()).filter(Boolean);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function policyText(d, env) {
|
|
138
|
+
const p = d && d.policy;
|
|
139
|
+
if (!p) return t('policy.none', {}, env);
|
|
140
|
+
const lines = [t('policy.title', {}, env)];
|
|
141
|
+
lines.push(t('policy.primary', { v: (p.primary || []).map(rawOf).join(' / ') }, env));
|
|
142
|
+
for (const r of p.roles || []) {
|
|
143
|
+
lines.push(t('policy.role', { role: r.name != null ? r.name : (r.role || ''), model: rawOf(r.model), text: r.note ? `(${r.note})` : '' }, env));
|
|
144
|
+
}
|
|
145
|
+
if (p.note) lines.push(t('policy.note', { v: p.note }, env));
|
|
146
|
+
if (p.record_mode) lines.push(t('policy.record_mode', { v: t(`policy.record_mode.${p.record_mode}`, {}, env) }, env));
|
|
147
|
+
if (p.updated_at) lines.push(t('policy.updated', { at: p.updated_at }, env));
|
|
148
|
+
return lines.join('\n');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Models used most on this computer in the last 7 days (by input + output tokens); [] when nothing is found. */
|
|
152
|
+
export async function suggestModels({ home, env, nowMs = Date.now(), readLogs = readLocalLogs }) {
|
|
153
|
+
try {
|
|
154
|
+
const logs = await readLogs({ home, env, sinceMs: nowMs - 7 * 86400e3, nowMs, settleMs: 0 });
|
|
155
|
+
const w = new Map();
|
|
156
|
+
for (const c of logs.calls) w.set(c.model, (w.get(c.model) || 0) + c.input_tokens + c.output_tokens);
|
|
157
|
+
for (const s of logs.summaries) w.set(s.item.model, (w.get(s.item.model) || 0) + s.item.input_tokens + s.item.output_tokens);
|
|
158
|
+
return [...w.entries()].filter(([, n]) => n > 0).sort((a, b) => b[1] - a[1]).slice(0, 2).map(([m]) => m);
|
|
159
|
+
} catch {
|
|
160
|
+
return [];
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function cmdPolicyShow(c) {
|
|
165
|
+
const d = await authedGetWithRefresh(c.baseUrl, POLICY_PATH, c.credOpts, { fetchImpl: c.fetchImpl });
|
|
166
|
+
let suggest = [];
|
|
167
|
+
if (!d || !d.policy) suggest = await suggestModels({ home: c.home, env: c.env, readLogs: c.readLogs });
|
|
168
|
+
if (c.flags.json) { c.log(JSON.stringify({ ok: true, ...d, ...(suggest.length ? { suggested_primary: suggest } : {}) })); return 0; }
|
|
169
|
+
c.log(policyText(d, c.env));
|
|
170
|
+
if (suggest.length) c.log(t('policy.suggest', { v: suggest.join(' / ') }, c.env));
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function cmdPolicySet(c) {
|
|
175
|
+
const env = c.env;
|
|
176
|
+
const primary = splitList(c.flags.primary);
|
|
177
|
+
if (!primary.length) return c.fail(2, 'primary_required', t('policy.need_primary', {}, env));
|
|
178
|
+
if (primary.length > 2) return c.fail(2, 'too_many_primary', t('policy.too_many_primary', {}, env));
|
|
179
|
+
const roles = [];
|
|
180
|
+
for (const raw of c.flags.roles || []) {
|
|
181
|
+
const r = parseRole(raw);
|
|
182
|
+
if (r.error) return c.fail(2, r.error, t(`policy.${r.error}`, {}, env));
|
|
183
|
+
roles.push(r);
|
|
184
|
+
}
|
|
185
|
+
const body = { primary, roles };
|
|
186
|
+
if (c.flags.note != null) body.note = String(c.flags.note);
|
|
187
|
+
if (c.flags.recordMode != null) {
|
|
188
|
+
if (!['call', 'summary'].includes(String(c.flags.recordMode))) return c.fail(2, 'bad_record_mode', t('policy.bad_record_mode', {}, env));
|
|
189
|
+
body.record_mode = String(c.flags.recordMode);
|
|
190
|
+
}
|
|
191
|
+
const d = await authedPutWithRefresh(c.baseUrl, POLICY_PATH, c.credOpts, body, { fetchImpl: c.fetchImpl });
|
|
192
|
+
if (c.flags.json) { c.log(JSON.stringify({ ok: true, ...d })); return 0; }
|
|
193
|
+
c.log(t('policy.saved', {}, env));
|
|
194
|
+
c.log(policyText(d, env));
|
|
195
|
+
return 0;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ---------------------------------------------------------------- workdir
|
|
199
|
+
|
|
200
|
+
async function requestWorkdir(c, raw) {
|
|
201
|
+
const sc = parseScope(raw);
|
|
202
|
+
const post = (body) => authedPostWithRefresh(c.baseUrl, '/api/v1/agent/workdirs', c.credOpts, body,
|
|
203
|
+
c.flags.idempotencyKey || null, { fetchImpl: c.fetchImpl }); // the platform returns the same folder anyway
|
|
204
|
+
if (sc) return post(sc.scope === 'hire' ? { hire_id: sc.id } : { task_id: sc.id });
|
|
205
|
+
// A bare id: try it as a task first, then as a hire.
|
|
206
|
+
try {
|
|
207
|
+
return await post({ task_id: raw });
|
|
208
|
+
} catch (e) {
|
|
209
|
+
const st = Number(e && e.status);
|
|
210
|
+
const code = errorCode(e);
|
|
211
|
+
if (st === 404 || st === 422 || (code && /not_found/.test(code))) return post({ hire_id: raw });
|
|
212
|
+
throw e;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function cmdWorkdirOpen(c) {
|
|
217
|
+
const raw = c.positionals[2];
|
|
218
|
+
if (!raw) return c.fail(2, 'id_required', t('workdir.need_id', {}, c.env));
|
|
219
|
+
let d;
|
|
220
|
+
try {
|
|
221
|
+
d = await requestWorkdir(c, String(raw));
|
|
222
|
+
} catch (e) {
|
|
223
|
+
const st = Number(e && e.status);
|
|
224
|
+
const code = errorCode(e);
|
|
225
|
+
if (st === 404 || (code && /not_found/.test(code))) return c.fail(1, 'not_found', t('workdir.err.not_found', {}, c.env));
|
|
226
|
+
throw e;
|
|
227
|
+
}
|
|
228
|
+
const local = ensureLocalWorkdir(c.credOpts, d, { path: c.flags.path || null, home: c.home });
|
|
229
|
+
if (c.flags.json) { c.log(JSON.stringify({ ok: true, ...d, path: local.path })); return 0; }
|
|
230
|
+
c.log(t('workdir.opened', { path: local.path }, c.env));
|
|
231
|
+
c.log(t('workdir.opened_line', {}, c.env));
|
|
232
|
+
return 0;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function cmdWorkdirList(c) {
|
|
236
|
+
const reg = readRegistry(c.credOpts);
|
|
237
|
+
const ids = Object.keys(reg);
|
|
238
|
+
if (c.flags.json) { c.log(JSON.stringify({ ok: true, workdirs: ids.map((id) => ({ workdir_id: id, ...reg[id] })) })); return 0; }
|
|
239
|
+
if (!ids.length) { c.log(t('workdir.list_empty', {}, c.env)); return 0; }
|
|
240
|
+
c.log(t('workdir.list_title', {}, c.env));
|
|
241
|
+
for (const id of ids) c.log(` ${id} ${reg[id].scope}:${reg[id].scope_id} ${reg[id].path}`);
|
|
242
|
+
return 0;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ---------------------------------------------------------------- usage
|
|
246
|
+
|
|
247
|
+
function n(x) {
|
|
248
|
+
return Number(x || 0).toLocaleString('en-US');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Words for a collect / push result. */
|
|
252
|
+
export function describeSend(tot, env) {
|
|
253
|
+
const lines = [t('usage.sent', tot, env)];
|
|
254
|
+
const rs = Object.entries(tot.reasons || {});
|
|
255
|
+
if (rs.length) lines.push(t('usage.reasons', { v: rs.map(([k, v]) => `${k} ×${v}`).join(',') }, env));
|
|
256
|
+
if (tot.hint) lines.push(t('usage.upgrade', { min: (tot.hint.params && tot.hint.params.min) || '', cmd: UPGRADE_COMMAND }, env));
|
|
257
|
+
return lines;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function describeCollect(res, env, { dryRun = false } = {}) {
|
|
261
|
+
if (!res.found && !res.files) return [t('usage.no_logs', {}, env)];
|
|
262
|
+
if (!res.inWorkdir) return res.found ? [t('usage.none_in_workdir', { n: res.found }, env)] : [t('usage.nothing_new', {}, env)];
|
|
263
|
+
const lines = [];
|
|
264
|
+
if (dryRun) {
|
|
265
|
+
lines.push(t('usage.dry_title', { n: res.rows.length }, env));
|
|
266
|
+
const byWd = new Map();
|
|
267
|
+
for (const r of res.rows) {
|
|
268
|
+
if (!byWd.has(r.workdir_id)) byWd.set(r.workdir_id, []);
|
|
269
|
+
byWd.get(r.workdir_id).push(r);
|
|
270
|
+
}
|
|
271
|
+
for (const [wd, rows] of byWd) {
|
|
272
|
+
lines.push(t('usage.dry_workdir', { wd, scope: rows[0].granularity, n: rows.length }, env));
|
|
273
|
+
const per = new Map();
|
|
274
|
+
for (const r of rows) {
|
|
275
|
+
const items = r.granularity === 'summary' ? r.items : [r];
|
|
276
|
+
for (const it of items) {
|
|
277
|
+
const a = per.get(it.model) || { in: 0, out: 0, cw: 0, cr: 0 };
|
|
278
|
+
a.in += it.input_tokens || 0; a.out += it.output_tokens || 0; a.cw += it.cache_write_tokens || 0; a.cr += it.cache_read_tokens || 0;
|
|
279
|
+
per.set(it.model, a);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
for (const [model, a] of per) lines.push(t('usage.dry_model', { model, in: n(a.in), out: n(a.out), cw: n(a.cw), cr: n(a.cr) }, env));
|
|
283
|
+
}
|
|
284
|
+
return lines;
|
|
285
|
+
}
|
|
286
|
+
if (res.zero) lines.push(t('usage.zero_skipped', { n: res.zero }, env));
|
|
287
|
+
if (!res.sent) { lines.push(t('usage.nothing_new', {}, env)); return lines; }
|
|
288
|
+
if (res.sent.featureOff) { lines.push(t('usage.feature_off', {}, env)); return lines; }
|
|
289
|
+
if (res.sent.total) lines.push(...describeSend(res.sent, env));
|
|
290
|
+
if (res.sent.error) lines.push(t('usage.send_failed', { msg: res.sent.error.message || String(res.sent.error) }, env));
|
|
291
|
+
return lines;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function scopeFlag(c) {
|
|
295
|
+
if (c.flags.scope == null) return { scope: null };
|
|
296
|
+
const sc = parseScope(c.flags.scope);
|
|
297
|
+
return sc ? { scope: sc } : { error: true };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function cmdCollect(c) {
|
|
301
|
+
const sf = scopeFlag(c);
|
|
302
|
+
if (sf.error) return c.fail(2, 'bad_scope', t('usage.bad_scope', {}, c.env));
|
|
303
|
+
const sinceMs = c.flags.since != null ? parseSince(c.flags.since, c.nowMs()) : null;
|
|
304
|
+
if (c.flags.since != null && sinceMs == null) return c.fail(2, 'bad_since', t('usage.bad_since', {}, c.env));
|
|
305
|
+
const res = await collectUsage({
|
|
306
|
+
baseUrl: c.baseUrl, credOpts: c.credOpts, fetchImpl: c.fetchImpl, scope: sf.scope, sinceMs,
|
|
307
|
+
dryRun: !!c.flags.dryRun, nowMs: c.nowMs(), home: c.home, env: c.env, readLogs: c.readLogs, sqlite: c.sqlite,
|
|
308
|
+
});
|
|
309
|
+
if (c.flags.json) {
|
|
310
|
+
c.log(JSON.stringify({ ok: !(res.sent && res.sent.error), found: res.found, in_workdir: res.inWorkdir, zero: res.zero,
|
|
311
|
+
ready: res.rows.length, sent: res.sent ? { ...res.sent, error: res.sent.error ? String(res.sent.error.message || res.sent.error) : null } : null,
|
|
312
|
+
...(c.flags.dryRun ? { records: res.rows } : {}) }));
|
|
313
|
+
} else {
|
|
314
|
+
for (const l of describeCollect(res, c.env, { dryRun: !!c.flags.dryRun })) c.log(l);
|
|
315
|
+
}
|
|
316
|
+
return res.sent && res.sent.error ? 1 : 0;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Read a standard-format file: JSON Lines (or one JSON array). Returns { rows, notes, forbidden }.
|
|
321
|
+
* Lines carrying content fields stop everything (MT-15): nothing is sent.
|
|
322
|
+
*/
|
|
323
|
+
export function readRecordsFile(text, env) {
|
|
324
|
+
const notes = [];
|
|
325
|
+
const rows = [];
|
|
326
|
+
let items;
|
|
327
|
+
const trimmed = String(text || '').trim();
|
|
328
|
+
if (trimmed.startsWith('[')) {
|
|
329
|
+
try { items = JSON.parse(trimmed).map((o, i) => ({ o, n: i + 1 })); } catch { items = []; notes.push(t('usage.bad_line', { n: 1 }, env)); }
|
|
330
|
+
} else {
|
|
331
|
+
items = [];
|
|
332
|
+
String(text || '').split('\n').forEach((line, i) => {
|
|
333
|
+
const s = line.trim();
|
|
334
|
+
if (!s) return;
|
|
335
|
+
try { items.push({ o: JSON.parse(s), n: i + 1 }); } catch { notes.push(t('usage.bad_line', { n: i + 1 }, env)); }
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
let zero = 0;
|
|
339
|
+
for (const { o, n: line } of items) {
|
|
340
|
+
if (!o || typeof o !== 'object') { notes.push(t('usage.bad_line', { n: line }, env)); continue; }
|
|
341
|
+
const bad = CONTENT_FIELDS.find((f) => o[f] != null && (typeof o[f] === 'string' || Array.isArray(o[f]) || typeof o[f] === 'object'));
|
|
342
|
+
if (bad) return { rows: [], notes, forbidden: t('usage.content_forbidden', { n: line, field: bad }, env) };
|
|
343
|
+
const r = { schema: SCHEMA, source: 'agent-converted', granularity: 'call', ...o };
|
|
344
|
+
const need = r.granularity === 'summary'
|
|
345
|
+
? ['report_id', 'workdir_id', 'summary_period', 'items']
|
|
346
|
+
: ['call_id', 'conversation_id', 'provider', 'model', 'started_at', 'input_tokens', 'output_tokens', 'workdir_id'];
|
|
347
|
+
const miss = need.find((f) => r[f] == null || r[f] === '');
|
|
348
|
+
if (miss) { notes.push(t('usage.missing_field', { n: line, field: miss }, env)); continue; }
|
|
349
|
+
if (isZero(r)) { zero += 1; continue; }
|
|
350
|
+
rows.push(r);
|
|
351
|
+
}
|
|
352
|
+
if (zero) notes.push(t('usage.zero_skipped', { n: zero }, env));
|
|
353
|
+
return { rows, notes, forbidden: null };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function readFileArg(c) {
|
|
357
|
+
try {
|
|
358
|
+
return { text: c.readFile(String(c.flags.file)) };
|
|
359
|
+
} catch (e) {
|
|
360
|
+
return { error: t('usage.read_failed', { msg: e && e.message ? e.message : String(e) }, c.env) };
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function cmdPush(c) {
|
|
365
|
+
if (!c.flags.file) return c.fail(2, 'file_required', t('usage.need_file', {}, c.env));
|
|
366
|
+
const f = readFileArg(c);
|
|
367
|
+
if (f.error) return c.fail(2, 'read_failed', f.error);
|
|
368
|
+
const got = readRecordsFile(f.text, c.env);
|
|
369
|
+
if (got.forbidden) return c.fail(2, 'mt_content_forbidden', got.forbidden);
|
|
370
|
+
if (!c.flags.json) for (const l of got.notes) c.err(l);
|
|
371
|
+
if (!got.rows.length) { if (c.flags.json) c.log(JSON.stringify({ ok: true, sent: null, notes: got.notes })); else c.log(t('usage.nothing_new', {}, c.env)); return 0; }
|
|
372
|
+
const state = readState(c.credOpts);
|
|
373
|
+
const tot = await sendRows({ baseUrl: c.baseUrl, credOpts: c.credOpts, fetchImpl: c.fetchImpl, rows: got.rows, state, nowMs: c.nowMs() });
|
|
374
|
+
if (!tot.error && !tot.featureOff) await noteRecordMode({ baseUrl: c.baseUrl, credOpts: c.credOpts, fetchImpl: c.fetchImpl, state, tot });
|
|
375
|
+
writeState(c.credOpts, state, c.nowMs());
|
|
376
|
+
if (c.flags.json) {
|
|
377
|
+
c.log(JSON.stringify({ ok: !tot.error, sent: { ...tot, error: tot.error ? String(tot.error.message || tot.error) : null }, notes: got.notes }));
|
|
378
|
+
} else if (tot.featureOff) {
|
|
379
|
+
c.log(t('usage.feature_off', {}, c.env));
|
|
380
|
+
} else {
|
|
381
|
+
if (tot.total) for (const l of describeSend(tot, c.env)) c.log(l);
|
|
382
|
+
if (tot.error) c.err(t('usage.send_failed', { msg: tot.error.message || String(tot.error) }, c.env));
|
|
383
|
+
}
|
|
384
|
+
return tot.error ? 1 : 0;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function statusLines(wd, d, env) {
|
|
388
|
+
const lines = [t('usage.check_server', { wd }, env)];
|
|
389
|
+
const counted = d.counted != null ? d.counted : d.accepted;
|
|
390
|
+
lines.push(t('usage.check_server_counts', {
|
|
391
|
+
received: n(d.received != null ? d.received : d.total), counted: n(counted), dup: n(d.not_counted != null ? d.not_counted : d.duplicate),
|
|
392
|
+
last: d.last_received_at ? t('usage.check_server_last', { at: d.last_received_at }, env) : '',
|
|
393
|
+
}, env));
|
|
394
|
+
const checks = d.checks;
|
|
395
|
+
if (checks && Array.isArray(checks.rules)) {
|
|
396
|
+
for (const r of checks.rules) lines.push(` ${t(r.i18n_key || `mt.check.rule.${r.rule}`, r.params || { n: r.hits }, env)}`);
|
|
397
|
+
}
|
|
398
|
+
return lines;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function cmdCheck(c) {
|
|
402
|
+
const sf = scopeFlag(c);
|
|
403
|
+
if (sf.error) return c.fail(2, 'bad_scope', t('usage.bad_scope', {}, c.env));
|
|
404
|
+
let rows;
|
|
405
|
+
if (c.flags.file) {
|
|
406
|
+
const f = readFileArg(c);
|
|
407
|
+
if (f.error) return c.fail(2, 'read_failed', f.error);
|
|
408
|
+
const got = readRecordsFile(f.text, c.env);
|
|
409
|
+
if (got.forbidden) return c.fail(2, 'mt_content_forbidden', got.forbidden);
|
|
410
|
+
rows = got.rows;
|
|
411
|
+
} else {
|
|
412
|
+
const sinceMs = c.flags.since != null ? parseSince(c.flags.since, c.nowMs()) : c.nowMs() - 30 * 86400e3;
|
|
413
|
+
if (sinceMs == null) return c.fail(2, 'bad_since', t('usage.bad_since', {}, c.env));
|
|
414
|
+
rows = (await gatherLocal({ credOpts: c.credOpts, scope: sf.scope, sinceMs, nowMs: c.nowMs(), home: c.home, env: c.env, readLogs: c.readLogs, sqlite: c.sqlite })).rows;
|
|
415
|
+
}
|
|
416
|
+
const chk = localCheck(rows, c.nowMs());
|
|
417
|
+
// The work folders to compare with the platform: the --scope one(s), else every folder seen in the records.
|
|
418
|
+
const wds = sf.scope ? workdirsForScope(c.credOpts, sf.scope.scope, sf.scope.id).map((w) => w.workdir_id)
|
|
419
|
+
: [...new Set(rows.map((r) => r.workdir_id))];
|
|
420
|
+
const server = [];
|
|
421
|
+
for (const wd of wds) {
|
|
422
|
+
try { server.push({ wd, d: await getUsageStatus(c.baseUrl, c.credOpts, wd, c.fetchImpl) }); } catch (e) {
|
|
423
|
+
if (e && e.upgradeRequired) throw e;
|
|
424
|
+
server.push({ wd, error: errorCode(e) === 'mt_feature_off' ? t('usage.feature_off', {}, c.env) : (e && e.message ? e.message : String(e)) });
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (c.flags.json) { c.log(JSON.stringify({ ok: true, records: rows.length, local: chk, platform: server.map((s) => ({ workdir_id: s.wd, ...(s.d || {}), ...(s.error ? { error: s.error } : {}) })) })); return 0; }
|
|
428
|
+
c.log(t('usage.check_title', { n: rows.length }, c.env));
|
|
429
|
+
const map = { dup: 'usage.check_dup', negative: 'usage.check_negative', order: 'usage.check_order', future: 'usage.check_future', mono: 'usage.check_mono' };
|
|
430
|
+
let any = false;
|
|
431
|
+
for (const [k, key] of Object.entries(map)) if (chk[k]) { any = true; c.log(t(key, { n: chk[k] }, c.env)); }
|
|
432
|
+
if (!any) c.log(t('usage.check_ok', {}, c.env));
|
|
433
|
+
for (const s of server) {
|
|
434
|
+
if (s.error) { c.log(t('usage.check_server', { wd: s.wd }, c.env)); c.log(t('usage.check_server_failed', { msg: s.error }, c.env)); continue; }
|
|
435
|
+
for (const l of statusLines(s.wd, s.d || {}, c.env)) c.log(l);
|
|
436
|
+
}
|
|
437
|
+
return 0;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// ---------------------------------------------------------------- delivery hook (MT-19)
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Before a delivery: send this task's records. Never throws; returns lines to print (possibly empty).
|
|
444
|
+
* No work folder for the task on this computer -> one tip line.
|
|
445
|
+
*/
|
|
446
|
+
export async function collectForDelivery({ baseUrl, credOpts, fetchImpl, taskId, env = process.env, home, readLogs, sqlite, nowMs }) {
|
|
447
|
+
try {
|
|
448
|
+
if (!workdirsForScope(credOpts, 'task', taskId).length) return [t('usage.deliver_no_workdir', {}, env)];
|
|
449
|
+
const now = typeof nowMs === 'function' ? nowMs() : (nowMs || Date.now());
|
|
450
|
+
const res = await collectUsage({ baseUrl, credOpts, fetchImpl, scope: { scope: 'task', id: taskId }, env, home, readLogs, sqlite, nowMs: now });
|
|
451
|
+
if (res.sent && res.sent.error) return [t('usage.deliver_failed', { msg: res.sent.error.message || String(res.sent.error) }, env)];
|
|
452
|
+
if (!res.sent || res.sent.featureOff || !res.sent.total) return [];
|
|
453
|
+
return [t('usage.deliver_title', {}, env), ...describeSend(res.sent, env).map((l) => ` ${l.trim()}`)];
|
|
454
|
+
} catch (e) {
|
|
455
|
+
if (e && e.upgradeRequired) return [];
|
|
456
|
+
return [t('usage.deliver_failed', { msg: e && e.message ? e.message : String(e) }, env)];
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ---------------------------------------------------------------- dispatch
|
|
461
|
+
|
|
462
|
+
const HANDLERS = {
|
|
463
|
+
'model:policy-show': cmdPolicyShow,
|
|
464
|
+
'model:policy-set': cmdPolicySet,
|
|
465
|
+
'workdir:open': cmdWorkdirOpen,
|
|
466
|
+
'workdir:list': cmdWorkdirList,
|
|
467
|
+
'usage:collect': cmdCollect,
|
|
468
|
+
'usage:push': cmdPush,
|
|
469
|
+
'usage:check': cmdCheck,
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* ctx: { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, env, deps }
|
|
474
|
+
* deps (tests): home, readLogs, sqlite, nowMs, readFile
|
|
475
|
+
*/
|
|
476
|
+
export async function runMt(ctx) {
|
|
477
|
+
const deps = ctx.deps || {};
|
|
478
|
+
const env = ctx.env || process.env;
|
|
479
|
+
const c = {
|
|
480
|
+
...ctx,
|
|
481
|
+
env,
|
|
482
|
+
home: deps.home || os.homedir(),
|
|
483
|
+
readLogs: deps.readLogs,
|
|
484
|
+
sqlite: deps.sqlite,
|
|
485
|
+
nowMs: deps.nowMs || Date.now,
|
|
486
|
+
readFile: deps.readFile || ((p) => fs.readFileSync(p, 'utf8')),
|
|
487
|
+
fail(exit, code, message) {
|
|
488
|
+
if (ctx.flags.json) ctx.log(JSON.stringify({ ok: false, error: code, message }));
|
|
489
|
+
else ctx.err(message);
|
|
490
|
+
return exit;
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
const handler = HANDLERS[ctx.command];
|
|
494
|
+
if (!handler) { ctx.log(MT_HELP); return ctx.command && ctx.command.endsWith(':help') ? 0 : 2; }
|
|
495
|
+
try {
|
|
496
|
+
return await handler(c);
|
|
497
|
+
} catch (e) {
|
|
498
|
+
const m = mapMtError(e, env);
|
|
499
|
+
if (!m) throw e;
|
|
500
|
+
return c.fail(m.exit, m.code, m.text);
|
|
501
|
+
}
|
|
502
|
+
}
|