@anytowork/cli 0.12.51 → 0.12.53

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.51",
3
+ "version": "0.12.53",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/mt/collect.js CHANGED
@@ -154,15 +154,16 @@ export async function gatherLocal({ credOpts, scope = null, sinceMs, nowMs = Dat
154
154
  const cache = new Map();
155
155
  const rows = [];
156
156
  let outside = 0;
157
+ let noCwd = 0; // v0.38.36: part of `outside` whose log line has no folder at all
157
158
  const pick = (cwd) => {
158
159
  const wd = workdirForPath(cwd, registry, cache);
159
- if (!wd) { outside += 1; return null; }
160
+ if (!wd) { outside += 1; if (!cwd) noCwd += 1; return null; }
160
161
  if (scope && !(wd.scope === scope.scope && String(wd.scope_id) === String(scope.id))) return null;
161
162
  return wd;
162
163
  };
163
164
  for (const c of logs.calls) { const wd = pick(c.cwd); if (wd) rows.push(callRow(c, wd)); }
164
165
  for (const s of logs.summaries) { const wd = pick(s.cwd); if (wd) rows.push(summaryRow(s, wd)); }
165
- return { rows, found: logs.calls.length + logs.summaries.length, outside, files: logs.files };
166
+ return { rows, found: logs.calls.length + logs.summaries.length, outside, noCwd, files: logs.files };
166
167
  }
167
168
 
168
169
  // ---------------------------------------------------------------- sending
@@ -257,7 +258,7 @@ export async function collectUsage({ baseUrl, credOpts, fetchImpl, scope = null,
257
258
  if (!dryRun && state.sent[k]) continue;
258
259
  fresh.push(r);
259
260
  }
260
- const res = { found: g.found, outside: g.outside, files: g.files, inWorkdir: g.rows.length, zero, rows: fresh, sent: null };
261
+ const res = { found: g.found, outside: g.outside, noCwd: g.noCwd || 0, files: g.files, inWorkdir: g.rows.length, zero, rows: fresh, sent: null };
261
262
  if (dryRun || !fresh.length) {
262
263
  if (!dryRun) { state.last_collect_at = new Date(nowMs).toISOString(); state.last_ok_at = state.last_collect_at; writeState(credOpts, state, nowMs); }
263
264
  return res;
@@ -242,9 +242,17 @@ export function describeSend(tot, env) {
242
242
  return lines;
243
243
  }
244
244
 
245
+ /** v0.38.36: how many log lines were left out and why (no folder in the log line / folder is not a work folder). */
246
+ function droppedLine(res, env) {
247
+ const out = res.outside || 0;
248
+ if (!out) return [];
249
+ const noCwd = res.noCwd || 0;
250
+ return [t('usage.dropped', { n: out, nocwd: noCwd, other: out - noCwd }, env)];
251
+ }
252
+
245
253
  export function describeCollect(res, env, { dryRun = false } = {}) {
246
254
  if (!res.found && !res.files) return [t('usage.no_logs', {}, env)];
247
- if (!res.inWorkdir) return res.found ? [t('usage.none_in_workdir', { n: res.found }, env)] : [t('usage.nothing_new', {}, env)];
255
+ if (!res.inWorkdir) return res.found ? [t('usage.none_in_workdir', { n: res.found }, env), ...droppedLine(res, env)] : [t('usage.nothing_new', {}, env)];
248
256
  const lines = [];
249
257
  if (dryRun) {
250
258
  lines.push(t('usage.dry_title', { n: res.rows.length }, env));
@@ -266,8 +274,10 @@ export function describeCollect(res, env, { dryRun = false } = {}) {
266
274
  }
267
275
  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));
268
276
  }
277
+ lines.push(...droppedLine(res, env));
269
278
  return lines;
270
279
  }
280
+ lines.push(...droppedLine(res, env));
271
281
  if (res.zero) lines.push(t('usage.zero_skipped', { n: res.zero }, env));
272
282
  if (!res.sent) { lines.push(t('usage.nothing_new', {}, env)); return lines; }
273
283
  if (res.sent.featureOff) { lines.push(t('usage.feature_off', {}, env)); return lines; }
package/src/mt/dsh.js CHANGED
@@ -114,8 +114,11 @@ function applyEvent(st, o) {
114
114
  if (!o || typeof o !== 'object') return;
115
115
  const d = o.data && typeof o.data === 'object' ? o.data : {};
116
116
  if (o.type === 'session') {
117
- if (d.id) st.sid = String(d.id);
118
- if (typeof d.cwd === 'string') st.cwd = d.cwd;
117
+ // v0.38.33: the real log keeps id and cwd at the top level of the session line (not under `data`); both read.
118
+ const sid = o.id || d.id;
119
+ const cwd = typeof o.cwd === 'string' ? o.cwd : d.cwd;
120
+ if (sid) st.sid = String(sid);
121
+ if (typeof cwd === 'string') st.cwd = cwd;
119
122
  return;
120
123
  }
121
124
  if (o.type !== 'assistant/message') return;
package/src/mt/inrun.js CHANGED
@@ -67,6 +67,18 @@ function dirMatches(cwd, dirs, home, exactOnly = false) {
67
67
  return false;
68
68
  }
69
69
 
70
+ /**
71
+ * v0.38.36: folders that say nothing about which project a call belongs to: no folder at all, the home folder (and the one
72
+ * above it), the root, the temp folders. A call from there is placed by the Agent's on-duty time window instead.
73
+ */
74
+ function unclearDir(cwd, home) {
75
+ if (!cwd) return true;
76
+ const c = norm(cwd);
77
+ if (!c) return true;
78
+ const vague = new Set([path.parse(c).root, norm(home), norm(path.dirname(home)), norm(os.tmpdir()), '/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp']);
79
+ return vague.has(c);
80
+ }
81
+
70
82
  /** The program a start command names (first word of a path or `exec`), or null when it is a wrapper we cannot tell. */
71
83
  export function programOfCommand(command) {
72
84
  const words = String(command || '').split(/\s+/).map((t) => t.replace(/^['"]+|['"]+$/g, '')).filter(Boolean);
@@ -176,7 +188,9 @@ export class RunUsageTracker {
176
188
  * `ordered`: the sessions of the folders of this crowd, by start time.
177
189
  */
178
190
  #hermesOwner(s, r, now, ordered) {
179
- const group = [r, ...this.peers(r, now)].sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
191
+ // v0.38.36: a session with no clear folder is owned by the runs of this program that were on duty when it started
192
+ const group = unclearDir(s.cwd, this.home) ? this.#onDuty('hermes', s.startedMs)
193
+ : [r, ...this.peers(r, now)].sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
180
194
  const fits = group.filter((x) => s.startedMs >= x.startMs - START_SLACK_MS && (x.endMs == null || s.startedMs <= x.endMs + FINISH_GRACE_MS));
181
195
  if (!fits.length) return { owner: null, sure: false };
182
196
  if (fits.length === 1) return { owner: fits[0], sure: true };
@@ -184,6 +198,13 @@ export class RunUsageTracker {
184
198
  return { owner: fits[Math.min(rank, fits.length - 1)], sure: false };
185
199
  }
186
200
 
201
+ /** Runs of one program that were on duty at `ms`, in start order: the possible owners of a call with no clear folder. */
202
+ #onDuty(program, ms) {
203
+ return this.runs
204
+ .filter((x) => x.prog === program && ms >= x.startMs - START_SLACK_MS && (x.endMs == null || ms <= x.endMs + FINISH_GRACE_MS))
205
+ .sort((a, b) => a.startMs - b.startMs || a.seq - b.seq);
206
+ }
207
+
187
208
  async #upload(r, final) {
188
209
  if (this.off) return null;
189
210
  const now = this.nowMs();
@@ -200,6 +221,8 @@ export class RunUsageTracker {
200
221
  const rows = [];
201
222
  const pendingCum = [];
202
223
  const heldSessions = [];
224
+ const dropped = {}; // v0.38.36: calls read inside the window but not taken, by reason
225
+ const drop = (k) => { dropped[k] = (dropped[k] || 0) + 1; };
203
226
 
204
227
  // session database: totals per session x model
205
228
  try {
@@ -208,8 +231,12 @@ export class RunUsageTracker {
208
231
  const crowdDirs = [...new Set([r, ...this.peers(r, now)].flatMap((x) => x.dirs))];
209
232
  const crowdStart = Math.min(r.startMs, ...this.peers(r, now).map((x) => x.startMs)) - START_SLACK_MS;
210
233
  const ordered = hs.sessions
211
- .filter((s) => s.source !== 'cron' && s.cwd && dirMatches(s.cwd, crowdDirs, home, true) && s.startedMs >= crowdStart)
234
+ .filter((s) => s.source !== 'cron' && s.startedMs >= crowdStart
235
+ && (s.cwd && !unclearDir(s.cwd, home) ? dirMatches(s.cwd, crowdDirs, home, true) : r.prog === 'hermes'))
212
236
  .sort((a, b) => a.startedMs - b.startedMs);
237
+ for (const s of hs.sessions) {
238
+ if (s.source !== 'cron' && s.cwd && !unclearDir(s.cwd, home) && !dirMatches(s.cwd, crowdDirs, home, true) && s.startedMs >= since && s.startedMs <= until) drop('other_dir');
239
+ }
213
240
  for (const s of ordered) {
214
241
  if (s.startedMs < since || s.startedMs > until) continue;
215
242
  const { owner, sure } = this.#hermesOwner(s, r, now, ordered);
@@ -246,10 +273,34 @@ export class RunUsageTracker {
246
273
  for (const src of fromJsonl) {
247
274
  if (r.prog && r.prog !== src.program) continue;
248
275
  try {
249
- for (const c of src.read().calls) {
250
- if (c.seenMs < since || c.seenMs > until || c.seenMs > now - settleMs) continue;
251
- if (!c.cwd || !dirMatches(c.cwd, r.dirs, home)) continue;
252
- rows.push(callRow(c, { program: src.program, reader: src.reader, attribution: attributionOfCalls, taskRef: r.taskRef, workdirId: workdirOf(c.cwd) }));
276
+ const inWin = src.read().calls.filter((c) => c.seenMs >= since && c.seenMs <= until && c.seenMs <= now - settleMs);
277
+ // v0.38.36: the folder of a call only adds or excludes. A clear folder of this run takes it, a clear folder of another
278
+ // project drops it; no / home / temp folder: the run of this program that was on duty at that moment owns it (several:
279
+ // handed out by session in start order, `window`; the ones left over stay unassigned and are counted, never taken by a guess).
280
+ const vagueConvs = [];
281
+ for (const c of inWin) if (unclearDir(c.cwd, home) && !vagueConvs.includes(c.conversation_id)) vagueConvs.push(c.conversation_id);
282
+ for (const c of inWin) {
283
+ let attribution = attributionOfCalls;
284
+ if (c.cwd && dirMatches(c.cwd, r.dirs, home)) {
285
+ // clear folder of this run
286
+ } else if (!unclearDir(c.cwd, home)) {
287
+ drop('other_dir');
288
+ continue;
289
+ } else if (r.prog !== src.program) {
290
+ drop('unknown_program');
291
+ continue;
292
+ } else {
293
+ const duty = this.#onDuty(src.program, c.seenMs);
294
+ if (!duty.includes(r)) continue;
295
+ attribution = 'run';
296
+ if (duty.length > 1) {
297
+ const rank = vagueConvs.indexOf(c.conversation_id);
298
+ if (rank >= duty.length) { if (duty[0] === r) drop('crowd'); continue; }
299
+ if (duty[rank] !== r) continue;
300
+ attribution = 'window';
301
+ }
302
+ }
303
+ rows.push(callRow(c, { program: src.program, reader: src.reader, attribution, taskRef: r.taskRef, workdirId: workdirOf(c.cwd) }));
253
304
  }
254
305
  } catch { /* one unreadable log never blocks the others */ }
255
306
  }
@@ -280,6 +331,13 @@ export class RunUsageTracker {
280
331
  } catch { /* same */ }
281
332
  }
282
333
 
334
+ const nDropped = Object.values(dropped).reduce((x, y) => x + y, 0);
335
+ if (nDropped) {
336
+ this.lastDropped = dropped;
337
+ this.log(`usage: ${nDropped} calls not taken (${Object.entries(dropped).map(([k, v]) => `${k} x${v}`).join(', ')})`);
338
+ state.lastDropped = { at: new Date(now).toISOString(), reasons: dropped };
339
+ }
340
+
283
341
  // what was already sent is not sent again (calls: the local list shared with the idle upload)
284
342
  const seen = new Set();
285
343
  const fresh = [];
@@ -292,7 +350,7 @@ export class RunUsageTracker {
292
350
  fresh.push(row);
293
351
  }
294
352
  if (final) markSummariesSent(state, heldSessions);
295
- if (!fresh.length) { if (final) writeState(this.credOpts, state, now); return { sent: 0 }; }
353
+ if (!fresh.length) { if (final || nDropped) writeState(this.credOpts, state, now); return { sent: 0, dropped }; }
296
354
  const tot = await sendRows({ baseUrl: this.baseUrl, credOpts: this.credOpts, fetchImpl: this.fetchImpl, rows: fresh, state, nowMs: now });
297
355
  if (tot.featureOff) this.off = true;
298
356
  if (!tot.error && !tot.featureOff) {
@@ -305,7 +363,7 @@ export class RunUsageTracker {
305
363
  r.sentAny = true;
306
364
  }
307
365
  writeState(this.credOpts, state, now);
308
- return { sent: fresh.length, tot };
366
+ return { sent: fresh.length, tot, dropped };
309
367
  }
310
368
  }
311
369
 
package/src/mt/readers.js CHANGED
@@ -552,6 +552,15 @@ export async function readTranscriptUsage({ home, env, sinceMs, sqlite, log }) {
552
552
  */
553
553
  export async function readLocalLogs({ home = os.homedir(), env = process.env, sinceMs = 0, nowMs = Date.now(), settleMs = 60_000, sqlite } = {}) {
554
554
  const parts = [readMsgLog({ home, env, sinceMs }), readRollout({ home, env, sinceMs }), readDshLog({ home, env, sinceMs }), await readSessionDb({ home, env, sinceMs, sqlite })];
555
+ // v0.38.36: the run-log program too. The transcript (one call per assistant message) and the run log (one total per run) describe the
556
+ // same sessions: a session that has its calls one by one is taken from the transcript only, so the two never add up twice.
557
+ try {
558
+ const tr = await readTranscriptUsage({ home, env, sinceMs, sqlite });
559
+ const rl = await readRunLog({ home, env, sinceMs, sqlite, verdictKnown: true });
560
+ const live = new Set(tr.calls.map((c) => c.session_id));
561
+ parts.push({ calls: tr.calls.map((c) => ({ ...c, reader: 'transcript_db' })), summaries: [], files: tr.files || 0 });
562
+ parts.push({ calls: rl.calls.filter((c) => !live.has(c.session_id)).map((c) => ({ ...c, reader: 'run_db' })), summaries: [], files: rl.files || 0 });
563
+ } catch { /* an unreadable run-log database never blocks the other logs */ }
555
564
  const cut = nowMs - settleMs;
556
565
  return {
557
566
  calls: parts.flatMap((p) => p.calls).filter((c) => c.seenMs <= cut),
package/src/mt/sample.js CHANGED
@@ -563,7 +563,8 @@ async function gatherSample(c, tz) {
563
563
  }
564
564
  const g = got[0];
565
565
  if (g.inWin.every((x) => unpriceable(x.model))) return { unreadable: 'model' };
566
- return { sample: buildSample({ reader: g.src.reader, calls: g.calls, tz, nowMs }), client: clientOf(g.src.reader, g.entries) };
566
+ const noModel = g.inWin.filter((x) => String(x.model || '').trim() === '').length;
567
+ return { sample: buildSample({ reader: g.src.reader, calls: g.calls, tz, nowMs }), client: clientOf(g.src.reader, g.entries), drops: { old: g.calls.length - g.inWin.length, nomodel: noModel } };
567
568
  }
568
569
 
569
570
  function resultLines(d, env) {
@@ -588,6 +589,7 @@ export async function cmdSample(c) {
588
589
  let body;
589
590
  let summary = null;
590
591
  let client = null;
592
+ let drops = null;
591
593
  if (c.flags.unreadable != null) {
592
594
  const reason = String(c.flags.unreadable).replace(/\s+/g, ' ').trim();
593
595
  if (!reason || reason.length > REASON_MAX) return c.fail(2, 'bad_reason', t('sample.bad_reason', { max: REASON_MAX }, env));
@@ -609,7 +611,7 @@ export async function cmdSample(c) {
609
611
  return 2;
610
612
  }
611
613
  body = g.sample || { kind: KIND, unreadable: true, reason: reasonText(g.unreadable, env) };
612
- if (g.sample) { summary = summarize(g.sample); client = g.client; }
614
+ if (g.sample) { summary = summarize(g.sample); client = g.client; drops = g.drops || null; }
613
615
  }
614
616
  const clientField = client ? { client } : {};
615
617
  const clientLine = client ? [t('sample.client', { v: `${client.name} · ${client.entries.join(', ')}` }, env)] : [];
@@ -622,6 +624,7 @@ export async function cmdSample(c) {
622
624
  c.log(t('sample.dry_title', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
623
625
  for (const l of clientLine) c.log(l);
624
626
  c.log(t('sample.dry_models', { v: summary.models.map((m) => `${m.model} ${m.share}%`).join(', ') }, env));
627
+ if (drops && (drops.old || drops.nomodel)) c.log(t('sample.dry_dropped', drops, env));
625
628
  }
626
629
  c.log(t('sample.own_only', {}, env));
627
630
  return 0;
package/src/mt/text.js CHANGED
@@ -76,6 +76,8 @@ const TEXT = {
76
76
  zh: '找到了 {n} 条模型调用记录,但都不在专属工作目录里,没有上传。接了单先 anytowork workdir open <单号>,在那个目录里干活。',
77
77
  en: 'Found {n} model calls, but none inside a work folder, so nothing was sent. After you get a job, run anytowork workdir open <id> and work inside that folder.',
78
78
  },
79
+ 'usage.dropped': { zh: '未上传 {n} 条:日志没有目录 {nocwd},不在工作目录 {other}。', en: 'Left out {n}: no folder in the log {nocwd}, not in a work folder {other}.' },
80
+ 'sample.dry_dropped': { zh: ' 未计入:超出 30 天 {old},没有模型名 {nomodel}', en: ' Left out: older than 30 days {old}, no model name {nomodel}' },
79
81
  'usage.nothing_new': { zh: '没有新的模型调用记录要上传。', en: 'No new model call records to send.' },
80
82
  'usage.dry_title': { zh: '试运行(不上传):找到 {n} 条可上传的记录', en: 'Dry run (nothing sent): {n} records ready to send' },
81
83
  'usage.dry_workdir': { zh: ' {wd}({scope}):{n} 条', en: ' {wd} ({scope}): {n} records' },