@anytowork/cli 0.12.66 → 0.12.68

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 CHANGED
@@ -342,6 +342,7 @@ anytowork listen --exec "<命令>" # 不安装,只这一次前台运行(
342
342
  - 开机自启:macOS 用 LaunchAgent,Linux 用 `systemd --user`(没有就用 crontab `@reboot`),Windows 用任务计划(登录时运行)。Linux 想在没人登录时也运行:`loginctl enable-linger`。用户级系统服务与开机定时项都装不上时,方案 A 不可用,改用方案 B。
343
343
  - 日志在凭证目录的 `listener.log`(1 MB 轮转 3 份,只记编号、时间、退出码和耗时,不记消息内容)。
344
344
  - 常驻监听有自己的游标,和 `anytowork poll` 互不影响;订单事件仍走你原来的 `poll` / `listen`。
345
+ - 0.12.68 起:你的命令运行期间,监听每分钟告诉平台它还在跑(同一次运行最长按 60 分钟算),工作台一直显示「在干活」;命令异常结束(退出码不是 0、超时,或只留下一条错误)时,监听只把错误的类别(额度不足、限流、超时、登录失效、网络、其他)和一个短代码告诉平台,工作台会用一句话提示主人。命令的输出内容不会上传,只在内存里取最后几 KB 判断类别,用完即弃。
345
346
 
346
347
  **方案 B:每 1 分钟 poll**:定时任务每 1 分钟运行一次 `anytowork poll`:没有新事件时不输出、退出码 0,不启动模型;有新事件时打印并退出码 1,这时才把输出交给模型;出错退出码 2。这个定时任务同时是接单、求职的盯单,用方案 A 的也要保留;监听健康时新消息交给监听,不会叫醒两次。
347
348
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.66",
3
+ "version": "0.12.68",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/api.js CHANGED
@@ -1221,7 +1221,21 @@ export async function reportListener(baseUrl, credOpts = {}, body = {}, opts = {
1221
1221
  * command for this session is still running (only with the listener header; an older platform answers 404).
1222
1222
  */
1223
1223
  export async function postListenerBeat(baseUrl, credOpts = {}, sid, opts = {}) {
1224
- return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/beat`, credOpts, { source: 'listener' }, null,
1224
+ // v0.38.76: childAlive + ageS say the listener itself started the Agent program and it is still running (an older platform ignores both)
1225
+ const { childAlive, ageS, ...rest } = opts;
1226
+ const body = { source: 'listener', ...(childAlive ? { child_alive: true, age_s: Math.max(0, Math.floor(Number(ageS) || 0)) } : {}) };
1227
+ return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/beat`, credOpts, body, null,
1228
+ { ...rest, headers: { ...LISTENER_HEADER, ...(rest.headers || {}) } });
1229
+ }
1230
+
1231
+ /**
1232
+ * POST /api/v1/agent/chat/sessions/{sid}/run-end - v0.38.76: the listener says the Agent program of this session ended and, when
1233
+ * it broke off, the error category (quota / rate_limit / timeout / auth / network / other) with a short code. Never any output text.
1234
+ * Only with the listener header; an older platform answers 404.
1235
+ */
1236
+ export async function postListenerRunEnd(baseUrl, credOpts = {}, sid, body = {}, opts = {}) {
1237
+ const safe = { exit_code: body.exit_code ?? null, timed_out: !!body.timed_out, category: body.category || null, code: body.code || null };
1238
+ return authedPostWithRefresh(baseUrl, `/api/v1/agent/chat/sessions/${encodeURIComponent(sid)}/run-end`, credOpts, safe, null,
1225
1239
  { ...opts, headers: { ...LISTENER_HEADER, ...(opts.headers || {}) } });
1226
1240
  }
1227
1241
 
@@ -0,0 +1,81 @@
1
+ // What went wrong when the Agent program the listener started ended badly (Echo 470 step 2).
2
+ //
3
+ // The listener keeps only the last few KB of the program's output in memory, reads them once with this small table and
4
+ // forgets them. Only a CATEGORY and a short code ever leave this module: never a line of the output, never a key, token
5
+ // or request. To teach it a new situation, add a row to RULES (first match wins, so put the specific ones first).
6
+
7
+ /** The categories the platform understands; anything else it stores as "other". */
8
+ export const RUN_ERROR_CATEGORIES = ['quota', 'rate_limit', 'timeout', 'auth', 'network', 'other'];
9
+
10
+ /** Bytes of output kept per stream while the program runs (the tail only; older output is dropped). */
11
+ export const TAIL_BYTES = 4096;
12
+
13
+ /** "status 402", "HTTP 402", "code: 402", "error 402" or "402 Payment Required" style mentions of one HTTP status. */
14
+ function status(n) {
15
+ return new RegExp(`(?:status(?:\\s*code)?|http|code|error|err)\\D{0,12}\\b${n}\\b|\\b${n}\\b\\s*(?:-|:)?\\s*(?:payment|too many|unauthori|forbidden|insufficient|error|client error)`, 'i');
16
+ }
17
+
18
+ /**
19
+ * Ordered rows: [category, short code, patterns]. The short code is a fixed word or the HTTP status, never text from the output.
20
+ * Quota first: a balance message often also mentions "limit" or "401-ish" words.
21
+ */
22
+ export const RULES = [
23
+ ['quota', '402', [
24
+ status(402),
25
+ /insufficient[\s_-]*(?:balance|funds|quota|credits?|account)|(?:balance|quota|credits?)\s*(?:is\s*)?(?:insufficient|exhausted|exceeded|depleted|used up|too low)|out of (?:credits?|quota|balance)|payment required|billing[^\n]{0,30}(?:not active|inactive|failed|required)|exceeded your current quota|余额不足|额度(?:不足|已用完|用完|耗尽)|欠费/i,
26
+ ]],
27
+ ['rate_limit', '429', [
28
+ status(429),
29
+ /rate[\s_-]*limit|too many requests|requests? per (?:minute|second)|overloaded|限流|请求过于频繁/i,
30
+ ]],
31
+ ['auth', '401', [
32
+ status(401), status(403),
33
+ /unauthori[sz]ed|invalid[\s_-]*(?:api[\s_-]*)?key|incorrect api key|authentication[\s_-]*(?:failed|error|required)|invalid[\s_-]*token|token (?:expired|has expired)|forbidden|认证失败|密钥(?:无效|错误)/i,
34
+ ]],
35
+ ['timeout', 'timeout', [
36
+ /timed? ?out|ETIMEDOUT|ESOCKETTIMEDOUT|deadline exceeded|超时/i,
37
+ ]],
38
+ ['network', 'net', [
39
+ /ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|socket hang up|getaddrinfo|connection (?:refused|reset|error|closed)|network (?:error|is unreachable)|fetch failed|网络(?:错误|异常)/i,
40
+ ]],
41
+ ];
42
+
43
+ /**
44
+ * Put one ended run down to a category.
45
+ * @param {{code?: number|null, timedOut?: boolean, error?: string, signal?: string|null, tail?: string}} res what the exec helper returned
46
+ * @returns {{broke: boolean, category: string|null, code: string|null}}
47
+ * broke the program did not end in an orderly way (a non-zero exit, killed, timed out, could not start)
48
+ * category the matched category, or null when nothing in the output points at one (a broken run is then "other")
49
+ * code a short token (`402`, `429`, `timeout`, `net`, `exit_1`, `spawn`) or null
50
+ */
51
+ export function classifyRunEnd(res) {
52
+ const r = res || {};
53
+ const exitCode = r.code == null ? null : Number(r.code);
54
+ const broke = !!r.timedOut || !!r.error || exitCode !== 0;
55
+ const text = String(r.tail || '').slice(-TAIL_BYTES);
56
+ let category = null;
57
+ let code = null;
58
+ if (r.timedOut) { category = 'timeout'; code = 'timeout'; }
59
+ else if (r.error) { category = 'other'; code = 'spawn'; }
60
+ else {
61
+ for (const [cat, short, patterns] of RULES) {
62
+ if (patterns.some((p) => p.test(text))) { category = cat; code = short; break; }
63
+ }
64
+ // the status mentioned decides the short code of the auth row (401 or 403)
65
+ if (category === 'auth' && status(403).test(text) && !status(401).test(text)) code = '403';
66
+ }
67
+ if (broke && !category) {
68
+ category = 'other';
69
+ code = exitCode != null ? `exit_${Math.abs(exitCode) % 1000}` : (r.signal ? 'signal' : 'exit');
70
+ }
71
+ return { broke, category, code };
72
+ }
73
+
74
+ /** A bounded tail buffer: keeps the last `max` characters of what is pushed in. */
75
+ export function makeTail(max = TAIL_BYTES) {
76
+ let buf = '';
77
+ return {
78
+ push(chunk) { buf = (buf + String(chunk)).slice(-max); },
79
+ text() { return buf; },
80
+ };
81
+ }
@@ -12,7 +12,7 @@
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { spawn } from 'node:child_process';
15
- import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, LISTENER_HEADER } from '../api.js';
15
+ import { getPoll, getListenerInfo, reportListener, getWbReadState, postListenerBeat, postListenerRunEnd, LISTENER_HEADER } from '../api.js';
16
16
  import { readCursor } from '../poll-state.js';
17
17
  import { resolveCredDir } from '../profile.js';
18
18
  import { CLI_VERSION } from '../client-version.js';
@@ -20,6 +20,7 @@ import { WakeQueue } from './queue.js';
20
20
  import { buildPrompt, testPrompt } from './prompt.js';
21
21
  import { lt } from './text.js';
22
22
  import { writeNudge } from './nudge.js';
23
+ import { classifyRunEnd, makeTail } from './run-error.js'; // v0.38.76: why a run broke off (category only)
23
24
  import { hireWakeEvents, hireWakePrompt, hireEventExpired, HIRE_WAKE_KEY } from './hire-wake.js'; // v0.38.41: hire events that wait for an answer
24
25
  import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
25
26
  import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
@@ -112,22 +113,28 @@ export function buildRunEnv({ base, cfg, vals, credDir }) {
112
113
  return env;
113
114
  }
114
115
 
115
- /** Start the command through the system shell; resolves with {code, timedOut, error?}. Never rejects. */
116
+ /** Start the command through the system shell; resolves with {code, timedOut, error?, signal?, tail}. Never rejects. v0.38.76: tail = last few KB of its output, memory only. */
116
117
  export function defaultExec({ command, input, env, cwd, timeoutMs }) {
117
118
  return new Promise((resolve) => {
118
119
  let done = false;
119
120
  let timedOut = false;
120
121
  let timer = null;
121
122
  const finish = (r) => { if (done) return; done = true; if (timer) clearTimeout(timer); resolve(r); };
123
+ const tail = makeTail();
122
124
  let child;
123
125
  try {
124
126
  child = spawn(command, {
125
- shell: true, env, cwd: cwd || undefined, stdio: ['pipe', 'ignore', 'ignore'],
127
+ shell: true, env, cwd: cwd || undefined, stdio: ['pipe', 'pipe', 'pipe'],
126
128
  detached: process.platform !== 'win32', windowsHide: true,
127
129
  });
128
130
  } catch { return finish({ code: null, timedOut: false, error: 'spawn' }); }
129
131
  child.on('error', () => finish({ code: null, timedOut: false, error: 'spawn' }));
130
- child.on('close', (code) => finish({ code, timedOut }));
132
+ child.on('close', (code, signal) => finish({ code, timedOut, signal: signal || null, tail: tail.text() }));
133
+ for (const st of [child.stdout, child.stderr]) {
134
+ if (!st) continue;
135
+ st.on('data', (d) => tail.push(d));
136
+ st.on('error', () => {});
137
+ }
131
138
  child.stdin.on('error', () => { /* the command may not read its input */ });
132
139
  try { child.stdin.end(input); } catch { /* same */ }
133
140
  timer = setTimeout(() => {
@@ -165,6 +172,7 @@ export class Listener {
165
172
  this.shouldStop = d.listenShouldStop || (() => false);
166
173
  this.autoCollect = d.autoCollect || autoCollect;
167
174
  this.env = d.env || process.env;
175
+ this.runEndOff = false; // v0.38.76: the platform has no run-end route (older version): stop trying
168
176
  this.beatOff = false; // v0.37.7 C1: the platform has no beat route (older version): stop trying
169
177
  this.installedVersion = d.installedVersion || installedVersionOnDisk;
170
178
  this.versionCheckMs = Number(d.versionCheckMs || p.cfg && p.cfg.versionCheckMs) || VERSION_CHECK_MS;
@@ -238,10 +246,13 @@ export class Listener {
238
246
  startBeat(sid) {
239
247
  const every = this.cfg.beatEveryMs != null ? Number(this.cfg.beatEveryMs) : BEAT_EVERY_MS;
240
248
  if (!(every > 0) || this.beatOff) return null;
249
+ const startedAt = this.nowMs();
241
250
  const t = setInterval(async () => {
242
251
  if (this.beatOff) return;
243
252
  try {
244
- await postListenerBeat(this.baseUrl, this.credOpts, sid, { fetchImpl: this.fetchImpl });
253
+ // v0.38.76: this listener started the program itself and it has not ended: say so, and for how long
254
+ const ageS = Math.max(0, Math.round((this.nowMs() - startedAt) / 1000));
255
+ await postListenerBeat(this.baseUrl, this.credOpts, sid, { fetchImpl: this.fetchImpl, childAlive: true, ageS });
245
256
  } catch (e) {
246
257
  // 404: an older platform without the route. 403: the platform did not take it for a listener call. Both: stop for good.
247
258
  if (e && (e.status === 404 || e.status === 403)) { this.beatOff = true; this.logLine(`beat off status=${e.status}`); }
@@ -251,6 +262,30 @@ export class Listener {
251
262
  return t;
252
263
  }
253
264
 
265
+ /**
266
+ * v0.38.76 (Echo 470 step 2): the program of this session ended. Tell the platform (no more "working") and, when it broke
267
+ * off or left an error behind, which CATEGORY it was (quota / rate_limit / timeout / auth / network / other) with a short
268
+ * code. No line of the program output is sent. An older platform without the route is asked once, then left alone.
269
+ * Never throws.
270
+ */
271
+ async reportRunEnd(sid, res) {
272
+ if (this.runEndOff) return;
273
+ try {
274
+ const r = classifyRunEnd(res);
275
+ const body = { exit_code: res && res.code != null ? Number(res.code) : null, timed_out: !!(res && res.timedOut), category: r.category, code: r.code };
276
+ if (r.broke) this.logLine(`run_end sid=${String(sid).slice(0, 8)} category=${r.category} code=${r.code}`);
277
+ let t;
278
+ try {
279
+ await Promise.race([
280
+ postListenerRunEnd(this.baseUrl, this.credOpts, sid, body, { fetchImpl: this.fetchImpl }),
281
+ new Promise((r) => { t = setTimeout(r, 8000); }),
282
+ ]);
283
+ } finally { clearTimeout(t); }
284
+ } catch (e) {
285
+ if (e && (e.status === 404 || e.status === 403)) { this.runEndOff = true; this.logLine(`run_end off status=${e.status}`); }
286
+ }
287
+ }
288
+
254
289
  /** v0.37.7 C2: note a run that belongs to a hire / task; its usage is read from the local logs while it runs. */
255
290
  beginUsage(job, command, jobInfo) {
256
291
  try {
@@ -527,6 +562,7 @@ export class Listener {
527
562
  for (const t of timers) if (t) clearInterval(t);
528
563
  }
529
564
  if (urun) await within(this.usage.finish(urun), FINAL_UPLOAD_WAIT_MS);
565
+ await this.reportRunEnd(job.sid, res);
530
566
  const ok = res && res.code === 0 && !res.timedOut && !res.error;
531
567
  const ms = this.nowMs() - now0;
532
568
  const why = !res ? 'spawn' : (res.timedOut ? 'timeout' : (res.error ? 'spawn' : `exit_${res.code}`));
package/src/mt/recipes.js CHANGED
@@ -1,4 +1,4 @@
1
- // v0.38.69 (CLI 0.12.66): a recipe-driven log reader.
1
+ // v0.38.71 (CLI 0.12.67): a recipe-driven log reader.
2
2
  //
3
3
  // Why: every Agent used to need its own hand-written reader in readers.js. A new Agent now only needs a recipe, which is
4
4
  // data: where its logs are, which file name to take, which lines carry a model call, where the numbers sit, and which
@@ -21,6 +21,10 @@
21
21
  // required fields a matching line must carry (a missing value is refused, never counted as 0)
22
22
  // modelSuffixes trailing tags that do not change the price (thinking effort); stripped from the end, repeatedly
23
23
  // sessionFrom "dir" = the first folder under the root is the conversation id
24
+ // sniff (optional) a function(headText) -> bool. A recipe with sniff has no default folder and is never found by
25
+ // file name or folder walk: it is used only for a single --from file whose first line passes sniff
26
+ // strictLines (optional) every non-empty line must be a JSON object; anything else is refused, never skipped
27
+ // dedupeRequired (optional) a matching line without the dedupeKey value is refused
24
28
  //
25
29
  // Adding an Agent: append one object to RECIPES. No other file changes.
26
30
 
@@ -51,8 +55,43 @@ export const RECIPES = [
51
55
  modelSuffixes: ["-low", "-medium", "-high", "-xhigh", "-sonar", "-tiered"],
52
56
  sessionFrom: "dir",
53
57
  },
58
+ // v0.38.71: a file an Agent exported by hand (its usage lives in a runtime database, not in a local log). One JSON object
59
+ // per line: message_id (the call, written twice keeps the last), model, input_tokens, output_tokens, created_at (unix
60
+ // seconds or ISO time), optional cache_read_tokens / cache_write_tokens; any other field is ignored. Never scanned by
61
+ // default. The platform is told reader "export" and marks the check low-trust: an exported file is the Agent own copy,
62
+ // so it must not pass for a log the CLI read on this machine.
63
+ {
64
+ id: "export",
65
+ client: null,
66
+ roots: [],
67
+ glob: "*.jsonl",
68
+ fields: {
69
+ model: "model",
70
+ input: "input_tokens",
71
+ output: "output_tokens",
72
+ cacheRead: "cache_read_tokens",
73
+ cacheWrite: "cache_write_tokens",
74
+ time: "created_at",
75
+ },
76
+ dedupeKey: "message_id",
77
+ dedupeRequired: true,
78
+ strictLines: true,
79
+ required: ["model", "time", "input", "output"],
80
+ modelSuffixes: [],
81
+ sniff: sniffExport,
82
+ },
54
83
  ];
55
84
 
85
+ /** The first non-empty line of an export file: a JSON object carrying all of message_id / model / created_at / both token counts. */
86
+ function sniffExport(head) {
87
+ const first = String(head || "").split("\n").find((l) => l.trim() !== "");
88
+ if (!first || first.trim()[0] !== "{") return false;
89
+ let o;
90
+ try { o = JSON.parse(first); } catch { return false; }
91
+ return !!o && typeof o === "object"
92
+ && ["message_id", "model", "created_at", "input_tokens", "output_tokens"].every((k) => k in o);
93
+ }
94
+
56
95
  export function recipeById(id) {
57
96
  return RECIPES.find((r) => r.id === id) || null;
58
97
  }
@@ -98,7 +137,8 @@ function isEmpty(v) {
98
137
 
99
138
  function toMs(v) {
100
139
  if (v == null || v === "") return null;
101
- const ms = typeof v === "number" ? (v < 1e12 ? v * 1000 : v) : Date.parse(String(v));
140
+ const num = typeof v === "number" ? v : (/^\s*\d+(\.\d+)?\s*$/.test(String(v)) ? Number(v) : null); // unix seconds / ms, also as text
141
+ const ms = num != null ? (num < 1e12 ? num * 1000 : num) : Date.parse(String(v));
102
142
  return Number.isFinite(ms) ? ms : null;
103
143
  }
104
144
 
@@ -186,6 +226,7 @@ function rowOf(recipe, obj, entry, lineNo) {
186
226
  const cacheRead = countAt(recipe, obj, "cacheRead", entry.file, lineNo);
187
227
  const cacheWrite = countAt(recipe, obj, "cacheWrite", entry.file, lineNo);
188
228
  const step = recipe.dedupeKey ? fieldOf(obj, recipe.dedupeKey) : undefined;
229
+ if (recipe.dedupeRequired && isEmpty(step)) bad(recipe, entry.file, lineNo, "missing " + recipe.dedupeKey);
189
230
  const id = isEmpty(step) ? path.basename(entry.file) + ":" + lineNo : String(step);
190
231
  return {
191
232
  call_id: (entry.session || path.basename(entry.file)) + ":" + id,
@@ -261,11 +302,19 @@ export function readRecipeCalls(recipe, { home = os.homedir(), sinceMs = 0, root
261
302
  const list = text.split("\n");
262
303
  for (let i = 0; i < list.length; i += 1) {
263
304
  const raw = list[i];
264
- if (!raw || raw[0] !== "{") continue;
305
+ if (recipe.strictLines && raw.trim() === "") continue;
306
+ if (!raw || (!recipe.strictLines && raw[0] !== "{")) continue;
265
307
  if (needle && raw.indexOf(needle) === -1) continue;
266
308
  let obj;
267
- try { obj = JSON.parse(raw); } catch { continue; }
268
- if (!obj || typeof obj !== "object" || !matchesFilter(recipe, obj)) continue;
309
+ try { obj = JSON.parse(raw); } catch {
310
+ if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON line");
311
+ continue;
312
+ }
313
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
314
+ if (recipe.strictLines) bad(recipe, entry.file, i + 1, "not a JSON object");
315
+ continue;
316
+ }
317
+ if (!matchesFilter(recipe, obj)) continue;
269
318
  lines += 1;
270
319
  const row = rowOf(recipe, obj, entry, i + 1);
271
320
  const step = recipe.dedupeKey ? fieldOf(obj, recipe.dedupeKey) : undefined;
@@ -299,21 +348,34 @@ export function recipeForPath(abs, st) {
299
348
  const as = (r) => ({ reader: "recipe", recipe: r.id, client: r.client || null, roots: [abs], root: abs });
300
349
  if (st.isFile()) {
301
350
  const name = path.basename(abs);
302
- const r = RECIPES.find((x) => nameMatches(x.glob, name));
303
- return r ? as(r) : null;
351
+ const r = RECIPES.find((x) => !x.sniff && nameMatches(x.glob, name));
352
+ if (r) return as(r);
353
+ // a file with its own shape check (an Agent export): only a .jsonl file whose first line passes
354
+ const s = RECIPES.find((x) => x.sniff && abs.endsWith(".jsonl") && sniffFile(x, abs));
355
+ return s ? as(s) : null;
304
356
  }
305
357
  if (!st.isDirectory()) return null;
306
- for (const r of RECIPES) {
358
+ for (const r of RECIPES.filter((x) => !x.sniff)) {
307
359
  for (const root of expandRoots(r, os.homedir())) {
308
360
  if (abs === root || abs.startsWith(root + path.sep)) return as(r);
309
361
  }
310
362
  }
311
- for (const r of RECIPES) {
363
+ for (const r of RECIPES.filter((x) => !x.sniff)) {
312
364
  if (hasFileBelow(abs, r, 3)) return as(r);
313
365
  }
314
366
  return null;
315
367
  }
316
368
 
369
+ function sniffFile(recipe, abs) {
370
+ try {
371
+ const fd = fs.openSync(abs, "r");
372
+ try {
373
+ const b = Buffer.alloc(65536);
374
+ return !!recipe.sniff(b.toString("utf8", 0, fs.readSync(fd, b, 0, b.length, 0)));
375
+ } finally { fs.closeSync(fd); }
376
+ } catch { return false; }
377
+ }
378
+
317
379
  function hasFileBelow(dir, recipe, depth) {
318
380
  let entries;
319
381
  try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
package/src/mt/sample.js CHANGED
@@ -521,7 +521,8 @@ export function buildSample({ reader, calls, tz, nowMs }) {
521
521
  return {
522
522
  kind: KIND,
523
523
  tz,
524
- source: 'local-log',
524
+ // an Agent export file is the Agent own copy: it never passes for a log read on this computer
525
+ source: reader === 'export' ? 'agent-export' : 'local-log',
525
526
  reader,
526
527
  calls: inWin.slice(-RECENT_CALLS).map((c) => ({
527
528
  at: isoLocal(c.atMs, tz), model: c.model, input_tokens: c.input_tokens, output_tokens: c.output_tokens,
@@ -677,6 +678,7 @@ export async function cmdSample(c) {
677
678
  }
678
679
  if (drops && (drops.old || drops.nomodel)) c.log(t('sample.dry_dropped', drops, env));
679
680
  }
681
+ if (body.reader === 'export') c.log(t('sample.export_note', {}, env));
680
682
  c.log(t('sample.own_only', {}, env));
681
683
  return 0;
682
684
  }
@@ -701,5 +703,6 @@ export async function cmdSample(c) {
701
703
  : t('sample.delivered', { reader: body.reader, days: summary.days, calls: summary.calls }, env));
702
704
  for (const l of clientLine) c.log(l);
703
705
  for (const l of resultLines(d, env)) c.log(l);
706
+ if (body.reader === 'export') c.log(t('sample.export_note', {}, env));
704
707
  return 0;
705
708
  }
package/src/mt/text.js CHANGED
@@ -137,6 +137,10 @@ const TEXT = {
137
137
  zh: '试读(不上传):读不到可用的用量({reason})。正式运行会把这句原因交给平台。',
138
138
  en: 'Trial read (nothing sent): no usable usage ({reason}). A real run sends this reason to the platform.',
139
139
  },
140
+ 'sample.export_note': {
141
+ zh: '来源是 Agent 导出的文件,平台会标为低可信来源。',
142
+ en: 'The source is a file exported by the Agent; the platform marks it as a low-trust source.',
143
+ },
140
144
  'sample.own_only': {
141
145
  zh: '只算你自己这个程序的用量:如果读到的不是你自己这个程序的日志,用 --from <你自己这个程序的日志位置> 指定。',
142
146
  en: 'Only the usage of your own program counts: if this is not the log of your own program, point to it with --from <your own log path>.',