@anytowork/cli 0.12.30 → 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.
@@ -0,0 +1,316 @@
1
+ // v0.36.0: turn local log rows into standard records (anytowork.usage.v1), match them to work folders, and send them
2
+ // (contract v1 sections 1 and 3 A4; MT-6, MT-13, MT-19).
3
+ //
4
+ // Steps of `usage collect`:
5
+ // 1. read the usual log files (readers.js) since the last run (first run: the last 30 days);
6
+ // 2. keep only calls whose working directory sits inside a work folder (marker file) -> workdir_id;
7
+ // 3. drop calls already sent from this computer (local list keyed by call_key hash) and calls with no tokens;
8
+ // 4. send in batches (at most 500 records and well under 1 MiB each); remember what the platform answered;
9
+ // 5. tell the platform once which kind of records this Agent sends (record_mode call / summary).
10
+ // The local state lives in <credentials folder>/usage-cursor.json. Nothing here ever reads prompt or answer text.
11
+
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { createHash } from 'node:crypto';
16
+ import { authedPostWithRefresh, authedPutWithRefresh, authedGetWithRefresh } from '../api.js';
17
+ import { atomicWriteFile } from '../atomic-write.js';
18
+ import { resolveCredDir } from '../profile.js';
19
+ import { readLocalLogs } from './readers.js';
20
+ import { readRegistry, workdirForPath } from './workdirs.js';
21
+
22
+ export const SCHEMA = 'anytowork.usage.v1';
23
+ export const BATCH_MAX = 500;
24
+ const BODY_MAX = 900 * 1024; // stay under the platform's 1 MiB body limit
25
+ const FIRST_LOOKBACK_MS = 30 * 24 * 3600 * 1000;
26
+ const OVERLAP_MS = 24 * 3600 * 1000; // re-read a day before the last run (late-written log lines)
27
+ const SENT_KEEP_MS = 60 * 24 * 3600 * 1000; // forget sent keys after 60 days (logs older than that are not read)
28
+ export const COLLECT_INTERVAL_MIN = 10; // MT_COLLECT_INTERVAL_MIN default
29
+ export const CONTENT_FIELDS = ['prompt', 'prompts', 'completion', 'completions', 'content', 'messages', 'input', 'output', 'response_text'];
30
+ const TOKEN_FIELDS = ['input_tokens', 'output_tokens', 'cache_write_tokens', 'cache_read_tokens'];
31
+
32
+ // ---------------------------------------------------------------- local state
33
+
34
+ function stateFile(credOpts) {
35
+ return path.join(resolveCredDir(credOpts || {}), 'usage-cursor.json');
36
+ }
37
+
38
+ export function readState(credOpts) {
39
+ try {
40
+ const o = JSON.parse(fs.readFileSync(stateFile(credOpts), 'utf8'));
41
+ if (o && typeof o === 'object') return { sent: {}, ...o, sent: o.sent && typeof o.sent === 'object' ? o.sent : {} };
42
+ } catch { /* first run */ }
43
+ return { version: 1, sent: {}, last_collect_at: null, last_ok_at: null, record_mode_sent: null };
44
+ }
45
+
46
+ export function writeState(credOpts, st, nowMs = Date.now()) {
47
+ const keep = {};
48
+ for (const [k, at] of Object.entries(st.sent || {})) if (nowMs - Number(at) < SENT_KEEP_MS) keep[k] = at;
49
+ st.sent = keep;
50
+ st.version = 1;
51
+ try {
52
+ const file = stateFile(credOpts);
53
+ fs.mkdirSync(path.dirname(file), { recursive: true });
54
+ atomicWriteFile(file, JSON.stringify(st), 0o600);
55
+ } catch { /* best effort */ }
56
+ }
57
+
58
+ /** Should the listener run a collect now? */
59
+ export function collectDue(credOpts, nowMs = Date.now(), env = process.env) {
60
+ const min = env.ANYTOWORK_COLLECT_INTERVAL_MIN != null && env.ANYTOWORK_COLLECT_INTERVAL_MIN !== ''
61
+ ? Number(env.ANYTOWORK_COLLECT_INTERVAL_MIN) : COLLECT_INTERVAL_MIN;
62
+ if (!Number.isFinite(min) || min <= 0) return false; // 0 = switched off
63
+ const last = Date.parse(readState(credOpts).last_collect_at || '') || 0;
64
+ return nowMs - last >= min * 60 * 1000;
65
+ }
66
+
67
+ // ---------------------------------------------------------------- keys and rows
68
+
69
+ export function callKey(provider, callId) {
70
+ return `${String(provider || '').trim().toLowerCase()}:${String(callId || '').trim()}`;
71
+ }
72
+
73
+ export function sha256(s) {
74
+ return createHash('sha256').update(String(s)).digest('hex');
75
+ }
76
+
77
+ /** "task:<id>" / "hire:<id>" -> {scope, id}; anything else -> null. */
78
+ export function parseScope(raw) {
79
+ const m = /^(task|hire):(.+)$/.exec(String(raw || '').trim());
80
+ return m ? { scope: m[1], id: m[2].trim() } : null;
81
+ }
82
+
83
+ /** "--since" as a time or a duration (30m / 6h / 3d) -> ms epoch; null when it cannot be read. */
84
+ export function parseSince(raw, nowMs = Date.now()) {
85
+ if (raw == null || raw === '') return null;
86
+ const m = /^(\d+)\s*([mhd])$/i.exec(String(raw).trim());
87
+ if (m) return nowMs - Number(m[1]) * { m: 60e3, h: 3600e3, d: 86400e3 }[m[2].toLowerCase()];
88
+ const t = Date.parse(String(raw));
89
+ return Number.isNaN(t) ? null : t;
90
+ }
91
+
92
+ function callRow(c, wd) {
93
+ const row = {
94
+ schema: SCHEMA,
95
+ granularity: 'call',
96
+ call_id: String(c.call_id).trim().slice(0, 200),
97
+ conversation_id: String(c.conversation_id).slice(0, 200),
98
+ provider: String(c.provider || 'unknown').toLowerCase().slice(0, 60),
99
+ model: String(c.model).slice(0, 120),
100
+ started_at: c.started_at,
101
+ input_tokens: c.input_tokens,
102
+ output_tokens: c.output_tokens,
103
+ cache_write_tokens: c.cache_write_tokens || 0,
104
+ cache_read_tokens: c.cache_read_tokens || 0,
105
+ workdir_id: wd.workdir_id,
106
+ source: 'local-log',
107
+ };
108
+ if (c.message_id) row.message_id = String(c.message_id).slice(0, 200);
109
+ if (c.request_model) row.request_model = String(c.request_model).slice(0, 120);
110
+ if (c.ended_at && c.ended_at !== c.started_at) row.ended_at = c.ended_at;
111
+ if (c.cwd) row.project_dir_hash = sha256(path.resolve(c.cwd));
112
+ return row;
113
+ }
114
+
115
+ function summaryRow(s, wd) {
116
+ return {
117
+ schema: SCHEMA,
118
+ granularity: 'summary',
119
+ report_id: s.report_id,
120
+ workdir_id: wd.workdir_id,
121
+ source: 'local-log',
122
+ summary_period: s.period,
123
+ items: [s.item],
124
+ };
125
+ }
126
+
127
+ export function isZero(r) {
128
+ if (r.granularity === 'summary') return !(r.items || []).some((it) => TOKEN_FIELDS.some((k) => Number(it[k]) > 0));
129
+ return !TOKEN_FIELDS.some((k) => Number(r[k]) > 0);
130
+ }
131
+
132
+ /** Local key of a record (call: call_key hash; summary: report id). */
133
+ export function localKey(r) {
134
+ return r.granularity === 'summary' ? `s:${r.report_id}` : sha256(callKey(r.provider, r.call_id));
135
+ }
136
+
137
+ /**
138
+ * Read the logs and build the records of the work folders on this computer.
139
+ * @returns {Promise<{ rows, found, outside, byWorkdir }>} found = calls + summaries read; outside = not in a work folder
140
+ */
141
+ export async function gatherLocal({ credOpts, scope = null, sinceMs, nowMs = Date.now(), home = os.homedir(), env = process.env, readLogs = readLocalLogs, sqlite }) {
142
+ const logs = await readLogs({ home, env, sinceMs, nowMs, sqlite });
143
+ const registry = readRegistry(credOpts);
144
+ const cache = new Map();
145
+ const rows = [];
146
+ let outside = 0;
147
+ const pick = (cwd) => {
148
+ const wd = workdirForPath(cwd, registry, cache);
149
+ if (!wd) { outside += 1; return null; }
150
+ if (scope && !(wd.scope === scope.scope && String(wd.scope_id) === String(scope.id))) return null;
151
+ return wd;
152
+ };
153
+ for (const c of logs.calls) { const wd = pick(c.cwd); if (wd) rows.push(callRow(c, wd)); }
154
+ for (const s of logs.summaries) { const wd = pick(s.cwd); if (wd) rows.push(summaryRow(s, wd)); }
155
+ return { rows, found: logs.calls.length + logs.summaries.length, outside, files: logs.files };
156
+ }
157
+
158
+ // ---------------------------------------------------------------- sending
159
+
160
+ /** Split into batches: at most BATCH_MAX records and BODY_MAX bytes each. */
161
+ export function batches(rows) {
162
+ const out = [];
163
+ let cur = [];
164
+ let size = 20;
165
+ for (const r of rows) {
166
+ const s = Buffer.byteLength(JSON.stringify(r)) + 1;
167
+ if (cur.length && (cur.length >= BATCH_MAX || size + s > BODY_MAX)) { out.push(cur); cur = []; size = 20; }
168
+ cur.push(r);
169
+ size += s;
170
+ }
171
+ if (cur.length) out.push(cur);
172
+ return out;
173
+ }
174
+
175
+ function errorCode(e) {
176
+ const b = e && e.body && typeof e.body === 'object' ? e.body : null;
177
+ if (!b) return null;
178
+ const d = b.detail && typeof b.detail === 'object' ? b.detail : b;
179
+ return typeof d.error === 'string' ? d.error : null;
180
+ }
181
+
182
+ export function isFeatureOff(e) {
183
+ return errorCode(e) === 'mt_feature_off';
184
+ }
185
+
186
+ /**
187
+ * Send rows to the platform (A4). Returns totals plus whether everything got an answer.
188
+ * Every row the platform answered (accepted / duplicate / unattributed / rejected) is remembered as sent; rows of a
189
+ * batch that failed as a whole are not, so the next run sends them again (the platform de-duplicates).
190
+ */
191
+ export async function sendRows({ baseUrl, credOpts, fetchImpl, rows, state, nowMs = Date.now() }) {
192
+ const tot = { total: 0, accepted: 0, duplicate: 0, unattributed: 0, rejected: 0, reasons: {}, hint: null, calls: 0, summaries: 0, featureOff: false, error: null };
193
+ for (const batch of batches(rows)) {
194
+ const idem = `usage-${sha256(batch.map(localKey).join(',')).slice(0, 40)}`;
195
+ let d;
196
+ try {
197
+ d = await authedPostWithRefresh(baseUrl, '/api/v1/agent/usage/records', credOpts, { records: batch }, idem, { fetchImpl });
198
+ } catch (e) {
199
+ if (e && e.upgradeRequired) throw e;
200
+ if (errorCode(e) === 'mt_feature_off') { tot.featureOff = true; return tot; }
201
+ tot.error = e;
202
+ return tot;
203
+ }
204
+ const results = Array.isArray(d && d.results) ? d.results : [];
205
+ batch.forEach((r, i) => {
206
+ const res = results.find((x) => x && x.i === i) || results[i] || null;
207
+ if (!res) return;
208
+ state.sent[localKey(r)] = nowMs;
209
+ tot.total += 1;
210
+ const st = res.status;
211
+ if (st in tot && typeof tot[st] === 'number') tot[st] += 1;
212
+ if (st === 'accepted') { if (r.granularity === 'summary') tot.summaries += 1; else tot.calls += 1; }
213
+ if (res.reason) tot.reasons[res.reason] = (tot.reasons[res.reason] || 0) + 1;
214
+ });
215
+ if (d && d.cli_hint && d.cli_hint.i18n_key === 'mt.cli.upgrade') tot.hint = d.cli_hint;
216
+ }
217
+ return tot;
218
+ }
219
+
220
+ /** Tell the platform once which kind of records this Agent sends (A2 with only record_mode = partial update). */
221
+ export async function noteRecordMode({ baseUrl, credOpts, fetchImpl, state, tot }) {
222
+ const mode = tot.calls > 0 ? 'call' : (tot.summaries > 0 ? 'summary' : null);
223
+ if (!mode || state.record_mode_sent === mode || (mode === 'summary' && state.record_mode_sent === 'call')) return;
224
+ try {
225
+ await authedPutWithRefresh(baseUrl, '/api/v1/agent/model-policy', credOpts, { record_mode: mode }, { fetchImpl });
226
+ state.record_mode_sent = mode;
227
+ } catch { /* the next run tries again */ }
228
+ }
229
+
230
+ /**
231
+ * The whole `usage collect`. Never throws for platform refusals (except "upgrade required"); returns a result object
232
+ * the caller turns into words.
233
+ */
234
+ export async function collectUsage({ baseUrl, credOpts, fetchImpl, scope = null, sinceMs = null, dryRun = false, nowMs = Date.now(), home, env = process.env, readLogs, sqlite }) {
235
+ const state = readState(credOpts);
236
+ const last = Date.parse(state.last_ok_at || '') || 0;
237
+ const from = sinceMs != null ? sinceMs : (last ? last - OVERLAP_MS : nowMs - FIRST_LOOKBACK_MS);
238
+ const g = await gatherLocal({ credOpts, scope, sinceMs: from, nowMs, home, env, readLogs, sqlite });
239
+ const seen = new Set();
240
+ let zero = 0;
241
+ const fresh = [];
242
+ for (const r of g.rows) {
243
+ if (isZero(r)) { zero += 1; continue; }
244
+ const k = localKey(r);
245
+ if (seen.has(k)) continue;
246
+ seen.add(k);
247
+ if (!dryRun && state.sent[k]) continue;
248
+ fresh.push(r);
249
+ }
250
+ const res = { found: g.found, outside: g.outside, files: g.files, inWorkdir: g.rows.length, zero, rows: fresh, sent: null };
251
+ if (dryRun || !fresh.length) {
252
+ if (!dryRun) { state.last_collect_at = new Date(nowMs).toISOString(); state.last_ok_at = state.last_collect_at; writeState(credOpts, state, nowMs); }
253
+ return res;
254
+ }
255
+ const tot = await sendRows({ baseUrl, credOpts, fetchImpl, rows: fresh, state, nowMs });
256
+ res.sent = tot;
257
+ state.last_collect_at = new Date(nowMs).toISOString();
258
+ if (!tot.error && !tot.featureOff) {
259
+ state.last_ok_at = state.last_collect_at;
260
+ await noteRecordMode({ baseUrl, credOpts, fetchImpl, state, tot });
261
+ }
262
+ writeState(credOpts, state, nowMs);
263
+ return res;
264
+ }
265
+
266
+ // ---------------------------------------------------------------- local check (public part of MT01 / MT02 only)
267
+
268
+ /** Local check of a set of records: repeated call ids across work folders, token counts and times. */
269
+ export function localCheck(rows, nowMs = Date.now()) {
270
+ const out = { dup: 0, negative: 0, order: 0, future: 0, mono: 0 };
271
+ const owner = new Map();
272
+ const byConv = new Map();
273
+ for (const r of rows) {
274
+ if (r.granularity === 'summary') continue;
275
+ const k = callKey(r.provider, r.call_id);
276
+ const wd = owner.get(k);
277
+ if (wd == null) owner.set(k, r.workdir_id); else if (wd !== r.workdir_id) out.dup += 1;
278
+ if (TOKEN_FIELDS.some((f) => r[f] != null && !(Number.isInteger(r[f]) && r[f] >= 0))) out.negative += 1;
279
+ const s = Date.parse(r.started_at);
280
+ const e = r.ended_at ? Date.parse(r.ended_at) : null;
281
+ if (e != null && !Number.isNaN(e) && e < s) out.order += 1;
282
+ if (s > nowMs + 5 * 60 * 1000) out.future += 1;
283
+ const ck = `${r.workdir_id}|${r.conversation_id}`;
284
+ if (!byConv.has(ck)) byConv.set(ck, []);
285
+ byConv.get(ck).push({ s, e: e != null && !Number.isNaN(e) ? e : s });
286
+ }
287
+ for (const list of byConv.values()) {
288
+ list.sort((a, b) => a.s - b.s);
289
+ for (let i = 1; i < list.length; i++) if (list[i].e < list[i - 1].e) out.mono += 1;
290
+ }
291
+ return out;
292
+ }
293
+
294
+ /** A6: what the platform has for one work folder. */
295
+ export function getUsageStatus(baseUrl, credOpts, workdirId, fetchImpl) {
296
+ return authedGetWithRefresh(baseUrl, `/api/v1/agent/usage/status?workdir_id=${encodeURIComponent(workdirId)}`, credOpts, { fetchImpl });
297
+ }
298
+
299
+ export { errorCode };
300
+
301
+ // ---------------------------------------------------------------- listener hook (MT-19)
302
+
303
+ /**
304
+ * Called by `anytowork listen` between waits: when MT_COLLECT_INTERVAL_MIN (default 10; ANYTOWORK_COLLECT_INTERVAL_MIN,
305
+ * 0 = off) has passed and this computer has at least one work folder, send new records. Quiet: never throws, prints
306
+ * nothing; no model is called and nothing is spent.
307
+ */
308
+ export async function autoCollect({ baseUrl, credOpts, fetchImpl, env = process.env, nowMs = Date.now(), collect = collectUsage } = {}) {
309
+ try {
310
+ if (!collectDue(credOpts, nowMs, env)) return null;
311
+ if (!Object.keys(readRegistry(credOpts)).length) return null;
312
+ return await collect({ baseUrl, credOpts, fetchImpl, env, nowMs });
313
+ } catch {
314
+ return null;
315
+ }
316
+ }