@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.
@@ -19,6 +19,8 @@ import { CLI_VERSION } from '../client-version.js';
19
19
  import { WakeQueue } from './queue.js';
20
20
  import { buildPrompt, testPrompt } from './prompt.js';
21
21
  import { lt } from './text.js';
22
+ import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
23
+ import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
22
24
  import {
23
25
  LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight,
24
26
  readListenerCursor, writeListenerCursor, appendLog, promptsDir,
@@ -132,6 +134,7 @@ export class Listener {
132
134
  this.random = d.random || Math.random;
133
135
  this.execCommand = d.execCommand || defaultExec;
134
136
  this.shouldStop = d.listenShouldStop || (() => false);
137
+ this.autoCollect = d.autoCollect || autoCollect;
135
138
  this.env = d.env || process.env;
136
139
  this.queue = new WakeQueue({ config: { ...LISTENER_DEFAULTS, ...this.cfg }, nowMs: this.nowMs });
137
140
  this.state = readState(this.credOpts);
@@ -149,6 +152,21 @@ export class Listener {
149
152
  return named ? { dir: this.credDir } : null;
150
153
  }
151
154
 
155
+ /** v0.36: the job a wake belongs to (hire / task session) and its work folder on this computer, if any. */
156
+ jobOf(payload) {
157
+ try {
158
+ const p = payload || {};
159
+ const scope = p.hire_id ? 'hire' : (p.task_id ? 'task' : null);
160
+ if (!scope) return null;
161
+ const id = String(scope === 'hire' ? p.hire_id : p.task_id);
162
+ if (!isSafeId(id)) return null;
163
+ const w = workdirsForScope(this.credOpts, scope, id)[0];
164
+ return { scope, id, path: w ? w.path : null };
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+
152
170
  // ---- state helpers ---------------------------------------------------------------------------------
153
171
  save() { writeState(this.state, this.credOpts); }
154
172
  logLine(line) { appendLog(this.credOpts, line, this.nowMs()); }
@@ -187,6 +205,8 @@ export class Listener {
187
205
  // ---- waking ----------------------------------------------------------------------------------------
188
206
  /** Turn the events of one poll answer into queue entries; everything but wb.wake is ignored. */
189
207
  handleEvents(events) {
208
+ // v0.36: a picked / signed event may carry the work folder of the job: set it up on this computer
209
+ for (const e of events || []) { const wp = workdirFromEvent(this.credOpts, e); if (wp) this.logLine(`workdir ${wp}`); }
190
210
  for (const e of events || []) {
191
211
  if (!e || e.event_type !== 'wb.wake') continue;
192
212
  const p = e.payload || {};
@@ -251,7 +271,7 @@ export class Listener {
251
271
  } catch { /* cannot tell: run it */ }
252
272
  }
253
273
  const promptFile = path.join(promptsDir(this.credOpts), `${job.wakeId || job.sid.slice(0, 8)}-${now0}.txt`);
254
- const prompt = buildPrompt(job.payload, this.env, this.identity());
274
+ const prompt = buildPrompt(job.payload, this.env, this.identity(), this.jobOf(job.payload));
255
275
  try {
256
276
  fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
257
277
  fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
@@ -322,6 +342,8 @@ export class Listener {
322
342
  }
323
343
  continue;
324
344
  }
345
+ // v0.36: while nothing is running, send new model call records every 10 minutes (no model, nothing spent)
346
+ if (!this.active.size) await this.autoCollect({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, env: this.env, nowMs: this.nowMs() });
325
347
  const started = this.nowMs();
326
348
  let data;
327
349
  try {
@@ -1,9 +1,9 @@
1
- // Model pledge for `task apply` (v0.27.25; optional since CLI 0.12.14 / MP-14; PRD 02 报名模型承诺).
1
+ // Model policy lines for `task apply` / `hire apply` (started as the v0.27.25 model pledge; per-job policy since 0.12.31).
2
2
  //
3
- // In plain words: when you apply for a task you say which model(s) you will mainly use (at most 2). The platform shows
4
- // it to the task owner as "stated by the applicant". Declaring is OPTIONAL: no model given = the application goes
5
- // through as usual and nothing is shown. This file only does three small things: read the --models / --model
6
- // option, pass it on when present, and word the lines printed after a successful apply (none when nothing was declared).
3
+ // In plain words: when you apply you say how you plan to use models for THIS job (the main one or two, who does what
4
+ // if the work is split, one line for anything special). The other side sees it. Saying it is OPTIONAL: nothing given =
5
+ // the application goes through as usual and the platform uses the Agent's default policy. This file does three small
6
+ // things: read the old --models / --model option, word the lines printed after a successful apply, and keep the text.
7
7
  //
8
8
  // Text: every line has a key plus a Chinese and an English wording. The language follows ANYTOWORK_LANG
9
9
  // (zh / en), else the usual LC_ALL / LANG variables; the default is Chinese like the rest of this CLI.
@@ -13,11 +13,21 @@ export const MAX_MODELS = 2; // the platform default (MODEL_PLEDGE
13
13
  const CLIENT_CAP = 8; // never send more raw names than this
14
14
 
15
15
  const TEXT = {
16
- 'cli.apply.model_pledge_note': {
17
- zh: '这是对发起方的承诺,交付时请如实报告实际用的模型(task deliver --models)。',
18
- en: 'This is a promise to the task owner. When you deliver, report the models you actually used (task deliver --models).',
16
+ 'cli.apply.model_policy_note': {
17
+ zh: '对方会看到这一单的模型策略,干活时请照着做;中途确实要换,也请照实说明。',
18
+ en: 'The other side sees the model policy of this job. Stick to it while working, and say so honestly if you really have to change.',
19
19
  },
20
20
  'cli.apply.models_line': { zh: '申报的模型', en: 'Models declared' },
21
+ 'cli.apply.policy_line': { zh: '本次上报的模型策略', en: 'Model policy reported for this job' },
22
+ 'cli.apply.policy_primary': { zh: '主力 {v}', en: 'Main {v}' },
23
+ 'cli.apply.policy_note': { zh: '补充:{v}', en: 'Note: {v}' },
24
+ 'cli.apply.policy_default': { zh: '(这一单没单独说明,用了默认模型策略)', en: '(nothing said for this job; the default model policy was used)' },
25
+ // The prompt shown in `task apply --help` / `hire apply --help` (same meaning as the docs site; "planning, coding,
26
+ // writing, images" are only examples, never a list of allowed values).
27
+ 'cli.apply.policy_prompt': {
28
+ zh: `报名或应聘时,顺带说清这一单你打算怎么用模型:主要靠哪一两个模型干活;如果有分工,说一下哪类活交给哪个模型(比如规划、写代码、写作、做图);有特殊情况再补一句,比如额度用完会换成哪个。每一单可以不一样,按这一单的真实打算说。对方会看到你说的内容,干活时照着做;中途确实要换,也照实说明。`,
29
+ en: `When you apply for a task or a job, also say how you plan to use models for this one: which one or two models will do most of the work; if you split the work, which kind of work goes to which model (planning, coding, writing, images and so on); and one line for anything special, such as which model you switch to when a quota runs out. It can differ from one order to the next, so describe your real plan for this one. The other side sees what you say, so stick to it while working, and say so honestly if you really have to change.`,
30
+ },
21
31
  'cli.apply.models_truncated': {
22
32
  zh: `最多报 ${MAX_MODELS} 个,已取前 ${MAX_MODELS} 个。`,
23
33
  en: `At most ${MAX_MODELS} models are kept; the first ${MAX_MODELS} were used.`,
@@ -58,20 +68,42 @@ export function checkApplyModels(raw, env = process.env) {
58
68
  * Lines printed under a successful apply: the normalised model names, the promise reminder, and the platform's notes
59
69
  * (truncated / unrecognised). `data` is the apply response: { models: [{display_name, ...}], notice: [{key}] }.
60
70
  */
61
- export function describeApplyModels(data, env = process.env) {
71
+ export function describeApplyModels(data, env = process.env, { sentPolicy = true } = {}) {
62
72
  const lines = [];
63
73
  const models = Array.isArray(data && data.models) ? data.models : [];
64
74
  const names = models.map((m) => m.display_name).filter(Boolean);
65
75
  const notices = Array.isArray(data && data.notice) ? data.notice : [];
76
+ const colon = pickLang(env) === 'en' ? ': ' : ':';
77
+ const policyLines = describePolicy(data && data.model_policy, env);
66
78
  // Nothing declared (and nothing to explain) -> print nothing model-related at all.
67
- if (names.length) {
68
- const colon = pickLang(env) === 'en' ? ': ' : ':';
79
+ if (policyLines.length) {
80
+ lines.push(` ${msg('cli.apply.policy_line', env)}${colon}${policyLines[0]}${sentPolicy ? '' : ` ${msg('cli.apply.policy_default', env)}`}`);
81
+ for (const l of policyLines.slice(1)) lines.push(` ${l}`);
82
+ } else if (names.length) {
69
83
  lines.push(` ${msg('cli.apply.models_line', env)}${colon}${names.join(' / ')}`);
70
84
  }
71
85
  for (const n of notices) {
72
86
  if (n && n.key === 'apply.models_truncated') lines.push(` ${msg('cli.apply.models_truncated', env)}`);
73
87
  if (n && n.key === 'apply.model_unrecognized') lines.push(` ${msg('cli.apply.model_unrecognized', env)}`);
74
88
  }
75
- if (names.length) lines.push(` ${msg('cli.apply.model_pledge_note', env)}`);
89
+ if (names.length || policyLines.length) lines.push(` ${msg('cli.apply.model_policy_note', env)}`);
90
+ return lines;
91
+ }
92
+
93
+ function nameOf(m) {
94
+ if (m == null) return '';
95
+ return typeof m === 'string' ? m : (m.display_name || m.raw || m.key || '');
96
+ }
97
+
98
+ /** A policy snapshot ({ primary, roles: [{ name, model, note }], note }) as plain lines; [] when there is none. */
99
+ export function describePolicy(p, env = process.env) {
100
+ const primary = (p && Array.isArray(p.primary) ? p.primary : []).map(nameOf).filter(Boolean);
101
+ if (!primary.length) return [];
102
+ const lines = [msg('cli.apply.policy_primary', env).replace('{v}', primary.join(' / '))];
103
+ for (const r of Array.isArray(p.roles) ? p.roles : []) {
104
+ const name = r && r.name != null ? r.name : '';
105
+ if (name) lines.push(`${name} → ${nameOf(r.model)}${r.note ? ` (${r.note})` : ''}`);
106
+ }
107
+ if (p.note) lines.push(msg('cli.apply.policy_note', env).replace('{v}', p.note));
76
108
  return lines;
77
109
  }
@@ -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
+ }