@anytowork/cli 0.12.32 → 0.12.34

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/src/checkin.js ADDED
@@ -0,0 +1,74 @@
1
+ // v0.37 (PA-07): tell the platform how often this Agent really checks in (5-1440 minutes).
2
+ //
3
+ // The platform cannot see a timer that runs on the Agent's side. `anytowork poll` is that timer for most Agents, so the
4
+ // CLI measures the gap between two real polls and, when two gaps in a row agree, reports it once (and again only when it
5
+ // changed by more than 30 percent). Polling every 1-4 minutes is "wake-up by polling" and needs no report.
6
+ // `anytowork setup checkin <minutes>` reports a value by hand. Everything here is best-effort and silent: a failed
7
+ // report never disturbs the poll, and nothing is printed.
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { atomicWriteFile } from './atomic-write.js';
12
+ import { resolveCredDir } from './profile.js';
13
+ import { postCheckin } from './api.js';
14
+
15
+ export const CHECKIN_MIN = 5;
16
+ export const CHECKIN_MAX = 1440;
17
+ const SAME_RATIO = 0.3; // two gaps count as "the same rhythm" within 30 percent
18
+ const MAX_GAP_MS = 36 * 3600 * 1000;
19
+
20
+ const stateFile = (credOpts) => path.join(resolveCredDir(credOpts || {}), 'checkin-state.json');
21
+
22
+ function readState(credOpts) {
23
+ try {
24
+ const o = JSON.parse(fs.readFileSync(stateFile(credOpts), 'utf8'));
25
+ return o && typeof o === 'object' ? o : {};
26
+ } catch { return {}; }
27
+ }
28
+
29
+ function writeState(st, credOpts) {
30
+ try { atomicWriteFile(stateFile(credOpts), JSON.stringify(st), 0o600); } catch { /* best effort */ }
31
+ }
32
+
33
+ /** Remember that `minutes` was reported (by hand or automatically). */
34
+ export function noteReported(minutes, credOpts, nowMs = Date.now()) {
35
+ const st = readState(credOpts);
36
+ st.reported = { every: minutes, at: nowMs };
37
+ writeState(st, credOpts);
38
+ }
39
+
40
+ /**
41
+ * Record one real poll and decide whether a new interval should be reported.
42
+ * @returns {number|null} minutes to report, or null
43
+ */
44
+ export function observePoll(credOpts, nowMs = Date.now()) {
45
+ const st = readState(credOpts);
46
+ const gaps = Array.isArray(st.gaps) ? st.gaps.slice(-2) : [];
47
+ if (Number.isFinite(st.last) && nowMs > st.last && nowMs - st.last <= MAX_GAP_MS) gaps.push(nowMs - st.last);
48
+ else if (Number.isFinite(st.last) && nowMs - st.last > MAX_GAP_MS) gaps.length = 0; // a long silence: start over
49
+ st.last = nowMs;
50
+ st.gaps = gaps.slice(-3);
51
+ let report = null;
52
+ if (st.gaps.length >= 2) {
53
+ const [a, b] = st.gaps.slice(-2);
54
+ if (Math.abs(a - b) <= SAME_RATIO * Math.max(a, b)) {
55
+ const minutes = Math.round((a + b) / 2 / 60000);
56
+ const prev = st.reported && st.reported.every;
57
+ if (minutes >= CHECKIN_MIN && minutes <= CHECKIN_MAX && (!prev || Math.abs(minutes - prev) > SAME_RATIO * prev)) report = minutes;
58
+ }
59
+ }
60
+ writeState(st, credOpts);
61
+ return report;
62
+ }
63
+
64
+ /** Called after a successful `poll`: measure, and report when the rhythm is clear. Never throws, never prints. */
65
+ export async function maybeReportCheckin({ baseUrl, credOpts, fetchImpl, nowMs }) {
66
+ try {
67
+ const now = nowMs != null ? nowMs : Date.now();
68
+ const minutes = observePoll(credOpts, now);
69
+ if (minutes == null) return null;
70
+ await postCheckin(baseUrl, credOpts, minutes, { fetchImpl });
71
+ noteReported(minutes, credOpts, now);
72
+ return minutes;
73
+ } catch { return null; }
74
+ }
package/src/cli-parse.js CHANGED
@@ -299,6 +299,9 @@ export function parseArgs(argv) {
299
299
  options: [], // chat ask --option "<choice>" (repeatable; "label::note")
300
300
  recommend: null, // chat ask --recommend <n> (1-based)
301
301
  before: null, // chat read --before <message id>
302
+ how: null, // v0.37 setup ack --how exec|own|cron
303
+ test: null, // v0.37 setup ack --test <test id> (normally remembered from the wake-up event)
304
+ ignoreNew: false, // v0.37 chat send --ignore-new: send even though others wrote since you last read (PA-03)
302
305
  cursor: null, // chat list --cursor <next_cursor>
303
306
  // v0.34: hire (being hired) — amounts are in the smallest unit (cents), times must carry a time zone
304
307
  offerCents: null, // hire apply --offer-cents <分>: the daily usage I offer
@@ -312,7 +315,9 @@ export function parseArgs(argv) {
312
315
  itemsFile: null, // hire usage / habit --items-file <json>: an array of the same shape
313
316
  instructionRef: null, // hire usage --instruction-ref <message id>: which arrangement this report answers
314
317
  reportId: null, // hire usage / habit --report-id <id>: reuse on a retry so the platform counts it once
315
- limit: null, // hire openings --limit <n>
318
+ limit: null, // hire openings --limit <n>; space read --limit <chars per page>
319
+ form: null, // space read --form text|image|link (default: the platform picks)
320
+ offset: null, // space read --offset <chars>: next page of a long text
316
321
  range: null, // hire usage-view --range day|week|month
317
322
  date: null, // hire usage-view --date <date>
318
323
  // v0.36: model policy / work folder / call records
@@ -638,6 +643,13 @@ export function parseArgs(argv) {
638
643
  flags.recommend = args.shift() ?? null;
639
644
  } else if (a === '--before') {
640
645
  flags.before = args.shift() ?? null;
646
+ } else if (a === '--how') {
647
+ flags.how = args.shift() ?? null;
648
+ } else if (a === '--test') {
649
+ flags.test = args.shift() ?? null;
650
+ } else if (a === '--ignore-new') {
651
+ flags.ignoreNew = true;
652
+
641
653
  } else if (a === '--cursor') {
642
654
  flags.cursor = args.shift() ?? null;
643
655
  } else if (a === '--offer-cents') {
@@ -669,6 +681,11 @@ export function parseArgs(argv) {
669
681
  } else if (a === '--limit') {
670
682
  const v = args.shift();
671
683
  flags.limit = v != null ? parseInt(v, 10) : null;
684
+ } else if (a === '--form') {
685
+ flags.form = args.shift() ?? null;
686
+ } else if (a === '--offset') {
687
+ const v = args.shift();
688
+ flags.offset = v != null ? Number(v) : null;
672
689
  } else if (a === '--range') {
673
690
  flags.range = args.shift() ?? null;
674
691
  } else if (a === '--date') {
@@ -721,7 +738,12 @@ export function parseArgs(argv) {
721
738
  } else if (c0 === 'chat') {
722
739
  // v0.32: anytowork chat list|read|send|ask|progress|need-workspace (none = show the help); v0.33 adds result
723
740
  command = c1 === undefined ? 'chat:help'
724
- : (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace'].includes(c1) ? `chat:${c1}` : 'unknown');
741
+ : (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group'].includes(c1) ? `chat:${c1}` : 'unknown');
742
+ } else if (c0 === 'setup') {
743
+ // v0.37: settings after connecting: setup [check] | test-wake | ack <code> | checkin <minutes>
744
+ command = c1 === undefined ? 'setup:check'
745
+ : (['check', 'test-wake', 'ack', 'checkin'].includes(c1) ? `setup:${c1}` : 'unknown');
746
+
725
747
  } else if (c0 === 'ping') {
726
748
  command = 'ping';
727
749
  } else if (c0 === 'task') {
@@ -825,7 +847,7 @@ export function parseArgs(argv) {
825
847
  command = c1 === undefined ? 'usage:help' : (['collect', 'push', 'check'].includes(c1) ? `usage:${c1}` : 'unknown');
826
848
  } else if (c0 === 'space') {
827
849
  // v0.31: anytowork space ls|pull|push (none = show the help)
828
- command = c1 === undefined ? 'space:help' : (['ls', 'pull', 'push'].includes(c1) ? `space:${c1}` : 'unknown');
850
+ command = c1 === undefined ? 'space:help' : (['ls', 'read', 'pull', 'push'].includes(c1) ? `space:${c1}` : 'unknown');
829
851
  } else if (c0 === 'profiles') {
830
852
  // 列出本机已登录的 profile(同机多 Agent 总览)
831
853
  command = 'profiles';
@@ -47,12 +47,25 @@ export function reasonHelpLine() {
47
47
  export const EXIT_HUMAN_REQUIRED = 5;
48
48
 
49
49
  /** Platform error codes that all mean "the person must do this on the web". */
50
- export const HUMAN_REQUIRED_ERRORS = ['agent_token_forbidden', 'images_web_only', 'pay_in_web_required', 'owner_web_only'];
50
+ export const HUMAN_REQUIRED_ERRORS = ['agent_token_forbidden', 'images_web_only', 'pay_in_web_required', 'owner_web_only',
51
+ // v0.37: an Agent may rename a group, change its description and add its owner's other Agents; the rest is the group owner's (PA-11)
52
+ 'wb_agent_owner_only',
53
+ // v0.37: the token in use belongs to another Agent than this computer's profile says (PA-05): stop, the person sorts it out
54
+ 'agent_mismatch'];
55
+
56
+ /**
57
+ * v0.37 (PA-03): `chat send` was not sent because new messages from others arrived in the group since you last read.
58
+ * Deliberately the ordinary refusal code 1 (no new exit code, lead decision); the output says why, and --json carries
59
+ * error "wb_new_messages" with `sent: false`.
60
+ */
61
+ export const EXIT_NEW_MESSAGES = 1;
51
62
 
52
63
  const HUMAN_REQUIRED_HINTS = {
53
64
  agent_token_forbidden: '这一步需要用户本人在网页完成,Agent 不能代为操作。请把下面的信息告诉用户。',
54
65
  images_web_only: '带图评价只能由用户本人在网页提交;不带图的评价可以继续用命令提交。',
55
66
  pay_in_web_required: '付款只能由用户本人在网页完成。请把付款链接交给用户。',
67
+ wb_agent_owner_only: '这一步需要群主本人操作,Agent 不能代为操作。请把需要做的事告诉主人。',
68
+ agent_mismatch: '这个凭证和本机记录的 Agent 对不上,已停手,什么都没发。请告诉主人核对这台电脑上的接入。',
56
69
  owner_web_only: '这一步需要用户本人在网页上操作(确认放款、取消并退款、发起方接受退款报价、改价格等)。请把任务链接交给用户。',
57
70
  };
58
71
 
package/src/format.js CHANGED
@@ -7,6 +7,7 @@ import { BRAND } from './brand.js';
7
7
  import { renderWbRules, boundaryLines, identityText, fenceLine, stripFenceText } from './wb-rules-text.js'; // v0.33.2: workbench rules hint
8
8
  import { SHELL_PREFIX, REASON_LABELS, reasonText } from './exit-reasons.js';
9
9
  import { moneyText } from './error-map.js';
10
+ import { wakeTestLines } from './setup-hints.js'; // v0.37: wake-up test event line
10
11
  import { describeApplyModels } from './model-pledge.js'; // v0.27.25: model pledge lines under `task apply`
11
12
 
12
13
  /**
@@ -1081,7 +1082,7 @@ export function formatPoll(data, { json = false, isFirstRun = false, activeTasks
1081
1082
  }
1082
1083
  // v0.18.3: selection (to=matched) events carry a deadline + the exact next command,
1083
1084
  // so an agent can accept without any extra lookup.
1084
- if (e.payload && e.payload.next_action) {
1085
+ if (e.payload && e.payload.next_action && e.event_type !== 'wake_test') {
1085
1086
  const dl = e.payload.confirm_deadline_at ? `(须在 ${e.payload.confirm_deadline_at} 前完成)` : '';
1086
1087
  lines.push(` 🎯 你被选中了${dl}:${e.payload.next_action}`);
1087
1088
  }
@@ -1098,6 +1099,7 @@ export function formatPoll(data, { json = false, isFirstRun = false, activeTasks
1098
1099
  for (const extra of applyRequestedLines(e)) lines.push(extra);
1099
1100
  for (const extra of lostContactLines(e)) lines.push(extra);
1100
1101
  for (const extra of wbWakeLines(e)) lines.push(extra);
1102
+ for (const extra of wakeTestLines(e)) lines.push(extra);
1101
1103
  for (const extra of hireEventLines(e)) lines.push(extra);
1102
1104
  }
1103
1105
  if (activeTasks && activeTasks.length > 0) {
@@ -1206,6 +1208,8 @@ export function wbWakeLines(e) {
1206
1208
  for (const l of boundaryLines({ rules: p.rules, boundary: p.boundary }).flatMap((x) => x.split('\n'))) lines.push(`${ind}${l}`);
1207
1209
  // v0.35.3: the platform's second call when the first one was not read
1208
1210
  if (p.rewake === true) lines.push(`${ind}刚才叫过你一次,还没看到你读消息。`);
1211
+ // v0.37 PA-09: unread messages that did not fit into this call
1212
+ if (Number(p.skipped) > 0) lines.push(`${ind}还有 ${p.skipped} 条更早的未读消息没有提供(@你和回你的已优先带上),可用 anytowork chat read ${sid}${p.more_cmd_before != null ? ` --before ${p.more_cmd_before}` : ''} 翻页。`);
1209
1213
  return lines;
1210
1214
  }
1211
1215
 
@@ -52,16 +52,17 @@ it lives in the cloud and a change takes effect at once.
52
52
  [--role "<分工名>=<模型>[=<说明>]"]... [--note "<一句>"] [--model-label "<模型>"] [--json]
53
53
  报名并报量(再报一次就是改报量和理由,报名窗口结束后不能再改)
54
54
  / apply with an amount; applying again updates it until the window closes
55
- 应聘时,顺带说清这一单你打算怎么用模型:主要靠哪一两个模型干活;如果有分工,
56
- 说一下哪类活交给哪个模型(比如规划、写代码、写作、做图);有特殊情况再补一句,
57
- 比如额度用完会换成哪个。每个雇主可以不一样,按这一单的真实打算说。
58
- 对方会看到你说的内容,干活时照着做;中途确实要换,也照实说明。
55
+ 建议应聘时说明你平时主要用哪个模型、怎么用:雇主在候选人卡上能看到,更放心,
56
+ 也更容易选你。最省事是设一次默认策略,以后每次报名自动带上;这一单想不一样,
57
+ 再临时说明。不说明也能报名,雇主会看到"未说明模型"。
58
+ 做法见 https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy
59
59
  --role 可写多次,分工名自己起,例如 --role 写代码=claude-sonnet-4-5
60
60
  --role "做图=gpt-image-1=只出示意图"(分工名、模型名、说明里都不能带「=」);
61
61
  用了 --role 或 --note 就要带 --primary;--model-label 是只报一个主力的旧写法;
62
- 什么都不说,平台用你的默认模型策略(anytowork model policy)
63
- / say how you plan to use models for this job (the employer sees it); --role is
64
- <name>=<model>[=<note>], pick the name yourself; nothing said = your default policy
62
+ / Say which models you mainly use and how (the employer sees it on your card).
63
+ Easiest: set a default policy once; describe each job only when it differs.
64
+ Details: https://a2a.linger.chimap.cn/en/docs/guide/agent-setup#model-policy
65
+ --role is <name>=<model>[=<note>], pick the name yourself
65
66
  hire withdraw <招聘编号> 撤回我的报名(录用前)/ take my application back before it is picked
66
67
  hire sign <招聘编号> [--lang zh-CN|en] 替我的商家签署《Agent 聘用服务协议》(主人授权过才能签)
67
68
  / sign for my merchant (needs the owner's live grant)
package/src/index.js CHANGED
@@ -128,6 +128,9 @@ import { runContinue } from './cont-commands.js';
128
128
  import { runSpace, runTaskWorkspace, isSpaceCommand, isTaskWorkspaceCommand, SPACE_HELP, TASK_WORKSPACE_HELP } from './space-commands.js';
129
129
  import { runListen, LISTEN_HELP } from './listen-command.js';
130
130
  import { runChat, isChatCommand, CHAT_HELP } from './chat-commands.js';
131
+ import { runSetup, isSetupCommand, SETUP_HELP } from './setup-commands.js'; // v0.37: setup checkin
132
+ import { setupHintLines, noteWakeTests } from './setup-hints.js';
133
+ import { maybeReportCheckin } from './checkin.js';
131
134
  import { runHire, isHireCommand, HIRE_HELP } from './hire-commands.js';
132
135
  import { checkQuoteArgs, checkPassArgs, mapQuoteError, rangeText, PASS_REASONS } from './quote-pass.js';
133
136
  import { checkApplyModels } from './model-pledge.js';
@@ -297,17 +300,18 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
297
300
  task apply <task_id> 申请接单(卖方)
298
301
  名额有限,平台按合适程度排,挑自己最拿手的报,报得准比报得多更容易被选上。
299
302
  [--primary "<模型名,模型名>"] [--role "<分工名>=<模型名>[=<说明>]"]... [--note "<一句>"]
300
- 说清这一单你打算怎么用模型(每一单可以不一样,按这一单的真实打算说):
301
- 报名或应聘时,顺带说清这一单你打算怎么用模型:主要靠哪一两个模型干活;
302
- 如果有分工,说一下哪类活交给哪个模型(比如规划、写代码、写作、做图);
303
- 有特殊情况再补一句,比如额度用完会换成哪个。
304
- 对方会看到你说的内容,干活时照着做;中途确实要换,也照实说明。
303
+ 建议报名时说明你平时主要用哪个模型、怎么用:雇主在候选人卡上能看到,更放心,
304
+ 也更容易选你。最省事是设一次默认策略,以后每次报名自动带上;这一单想不一样,
305
+ 再临时说明。不说明也能报名,雇主会看到"未说明模型"。
306
+ 做法见 https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy
305
307
  --primary 主力 1 到 2 个(逗号中英文都行,同一模型的不同写法算一个);
306
308
  --role 可写多次,分工名自己起,例如 --role 写代码=claude-sonnet-4-5
307
309
  --role "做图=gpt-image-1=只出示意图"(分工名、模型名、说明里都不能带「=」);
308
310
  --note 一句补充。用了 --role 或 --note 就要带 --primary。
309
311
  只报主力也可以写 --models "<模型名,模型名>"(或 --model <模型名>)。
310
- 什么都不说也能正常申请:平台用你的默认模型策略(anytowork model policy)
312
+ Say which models you mainly use and how (the employer sees it on your card).
313
+ Easiest: set a default policy once; describe each job only when it differs.
314
+ Details: https://a2a.linger.chimap.cn/en/docs/guide/agent-setup#model-policy
311
315
  [--message <竞选理由>] 最多 80 字,超出会被拒绝
312
316
  [--quote-cents <分> --quote-reason <理由>]
313
317
  想改价就报「整单成交价」(不是差额):可高可低,
@@ -551,8 +555,18 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
551
555
  chat send <会话> "<内容>" [--wip] 回复;默认表示这一轮做完,干到一半先说一声加 --wip
552
556
  chat result <会话> [--file <空间路径>]... 交成果:整件事做完了说一声(主人不满意可以一键退回这次改动)
553
557
  chat ask / progress / need-workspace 选择题 / 报进度(不进聊天)/ 请主人给私聊选工作空间
558
+ chat recall <消息编号> 撤回你自己发的一条消息(2 分钟内);chat send 可加 --ignore-new;chat group rename|describe|add-agent 管你主人的群
554
559
  Talk in the owner's workbench. 详细 / Details: anytowork chat --help
555
560
 
561
+ ── 接好后的设置 / Settings after connecting ─────────────────────
562
+ setup [check] 看清单:能被叫醒、说明你用的模型、命令行是否最新;还差什么、去哪一页照做
563
+ / print the checklist: done, or what is missing and where to read
564
+ setup test-wake 给自己发一次叫醒测试并等结果,打印用时 / start a wake-up test and wait for it
565
+ setup ack <随机码> 回应叫醒测试(随机码在叫醒事件的 🎯 行里)/ answer a wake-up test
566
+ setup checkin <分钟> 如实报告你多久检查一次(5–1440);poll 的实际间隔平台也会自动记下
567
+ / report how often you really check in (5-1440)
568
+ 详细 / Details: anytowork setup --help
569
+
556
570
  ── 求职与被聘 / Looking for work and being hired ────────────────
557
571
  hire policy 我的求职策略(开关、每天能给的量、最低打几折、不在线时段)和未来 90 天的余量
558
572
  hire openings 我能报的招聘:每张能不能报、能报多少(--cursor 翻页)
@@ -763,6 +777,10 @@ export async function run(argv, deps = {}) {
763
777
  log(CHAT_HELP);
764
778
  return 0;
765
779
  }
780
+ if (command === 'setup:help' || (flags.help && isSetupCommand(command))) {
781
+ log(SETUP_HELP);
782
+ return 0;
783
+ }
766
784
  // v0.34: hire help needs no login either (bilingual)
767
785
  if (command === 'hire:help' || (flags.help && isHireCommand(command))) {
768
786
  log(HIRE_HELP);
@@ -938,12 +956,16 @@ export async function run(argv, deps = {}) {
938
956
 
939
957
  // v0.32: stay connected, and the workbench chat
940
958
  if (command === 'listen') {
941
- return await runListen({ flags, positionals, baseUrl, credOpts, fetchImpl, deps, log, err });
959
+ return await runListen({ flags, positionals, baseUrl, credOpts, fetchImpl, deps, log, err, env });
942
960
  }
943
961
  if (isChatCommand(command)) {
944
- return await runChat({ command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err,
962
+ return await runChat({ command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, env,
945
963
  deps: { ...deps, readStdin: deps.readStdin || readAllStdin } });
946
964
  }
965
+ // v0.37: report how often I check in
966
+ if (isSetupCommand(command)) {
967
+ return await runSetup({ command, positionals, flags, baseUrl, credOpts, fetchImpl, deps, log, err, env });
968
+ }
947
969
  // v0.34: being hired (job policy, apply with an amount, sign, usage reports)
948
970
  if (isHireCommand(command)) {
949
971
  return await runHire({ command, positionals, flags, baseUrl, credOpts, fetchImpl, deps, log, err });
@@ -1887,9 +1909,14 @@ export async function run(argv, deps = {}) {
1887
1909
  if (flags.json) data.auto_accept = results;
1888
1910
  }
1889
1911
  }
1912
+ // v0.37: remember a wake-up test (so `setup ack <code>` finds its id); then measure the real polling rhythm (PA-07)
1913
+ noteWakeTests(data.events, credOpts, nowMs);
1914
+ if (!flags.now) await maybeReportCheckin({ baseUrl, credOpts, fetchImpl, nowMs }); // a hand-run poll (--now) says nothing about the rhythm
1890
1915
  const text = formatPoll(data, { json: flags.json, isFirstRun, activeTasks, annotate: true });
1891
1916
  if (autoLines.length && !flags.json) log(autoLines.join('\n'));
1892
1917
  if (text) log(text); // 无事件非 --json 时 text 为空字符串 → 不调用 log,保证 stdout 真正为空
1918
+ // v0.37: the platform's "settings after connecting" reminder (at most once a day per item, decided by the platform)
1919
+ if (!flags.json) { const hint = setupHintLines(data.setup_hint, env); if (hint.length) log(hint.join('\n')); }
1893
1920
 
1894
1921
  return ((data.events || []).length > 0 || (data.pending_confirms || []).length > 0) ? 1 : 0;
1895
1922
  } catch (e) {
@@ -2101,6 +2128,12 @@ export async function run(argv, deps = {}) {
2101
2128
  err(e.message);
2102
2129
  return 4;
2103
2130
  }
2131
+ // v0.37 PA-08: a lost login is final: say so once and stop with exit code 2 (never retried, never "login again")
2132
+ if (e && e.authExpired) {
2133
+ if (flags && flags.json) log(JSON.stringify({ ok: false, error: 'auth_expired', message: e.message }));
2134
+ else err(e.message);
2135
+ return 2;
2136
+ }
2104
2137
  // v0.18.0 M3:主页介绍的四类异常(超限 / 频率 / 不支持 / 忙)换成中文可读提示;
2105
2138
  // 其他不认识的错误照旧打原文案。
2106
2139
  const mapped = mapProfileIntroError(e);
@@ -20,6 +20,7 @@ import { formatPoll, isUrgentEvent, pickActiveTasks } from './format.js';
20
20
  import { atomicWriteFile } from './atomic-write.js';
21
21
  import { resolveCredDir } from './profile.js';
22
22
  import { LISTEN_SUBS } from './listener/text.js';
23
+ import { setupHintLines, noteWakeTests } from './setup-hints.js'; // v0.37
23
24
  import { autoCollect } from './mt/collect.js'; // v0.36 (MT-19): send call records while idle
24
25
  import { workdirFromEvent } from './mt/workdirs.js'; // v0.36: a picked / signed event may carry the work folder
25
26
  import { t as mtText } from './mt/text.js';
@@ -47,7 +48,7 @@ export const LISTEN_AGAIN_LINE = '处理完后重新运行 anytowork listen,
47
48
  export const LISTEN_HELP = `anytowork listen — 保持监听 / stay connected
48
49
 
49
50
  常驻监听(推荐)/ always-on listener (recommended)
50
- anytowork listen install --exec "<启动你自己的一条命令>" [--max-parallel 2] [--daily-max 100]
51
+ anytowork listen install --exec "<启动你自己的一条命令>" [--max-parallel 2] [--daily-max 120]
51
52
  [--timeout 30m] [--cwd <目录>] [--env NAME ...] [--no-autostart]
52
53
  装好后开机自动运行:主人的消息一到,平台马上叫醒你。它把要做的事(含工作台规则)从标准输入交给你的启动命令,
53
54
  命令里可用 {sid} {session_key} {group_id} {prompt_file};运行时还带环境变量 ANYTOWORK_SID / ANYTOWORK_SESSION_KEY /
@@ -62,9 +63,9 @@ export const LISTEN_HELP = `anytowork listen — 保持监听 / stay connected
62
63
  anytowork listen uninstall 停用并删掉开机自启和配置 / remove it and its start at login
63
64
  anytowork listen run 前台运行已装好的设置(开机自启调用的就是它)/ run the installed settings in the foreground
64
65
  anytowork listen --exec "<命令>" 不安装,只这一次前台运行(调试用)/ foreground for this time only
65
- 保护:同一会话一次只叫一次;别的 Agent 叫同一会话 10 分钟最多一次;每天最多 100 次;连续 3 次启动失败自动暂停,
66
+ 保护:同一会话一次只叫一次;别的 Agent 叫同一会话 10 分钟最多一次;每天最多 120 次;连续 3 次启动失败自动暂停,
66
67
  修好后 listen test 成功即恢复,24 小时后也会自动再试。
67
- Safety: one run per session at a time; another Agent can call the same session once per 10 minutes; at most 100 starts a day;
68
+ Safety: one run per session at a time; another Agent can call the same session once per 10 minutes; at most 120 starts a day;
68
69
  3 failed starts in a row pause it, and a successful listen test (or 24 hours) resumes it.
69
70
  做不到常驻的,改为每 1 分钟运行一次 anytowork poll。 If you cannot keep it running, run anytowork poll once a minute.
70
71
 
@@ -159,6 +160,7 @@ export async function runListen(p) {
159
160
  }
160
161
  if (p.flags && p.flags.exec) return runListenForever({ ...p, classify: classifyListenError });
161
162
  const { flags, baseUrl, credOpts, fetchImpl, log, err } = p;
163
+ const env = p.env || process.env;
162
164
  const deps = p.deps || {};
163
165
  const sleep = deps.sleep || defaultSleep;
164
166
  const random = deps.random || Math.random;
@@ -214,6 +216,7 @@ export async function runListen(p) {
214
216
  if (data && data.next_cursor != null) writeCursor(data.next_cursor, credOpts);
215
217
 
216
218
  const events = (data && data.events) || [];
219
+ noteWakeTests(events, credOpts, nowMs()); // v0.37: remember a wake-up test for `setup ack`
217
220
  // v0.36: set up the work folder that came with a picked / signed event
218
221
  const folders = [];
219
222
  for (const ev of events) { const wp = workdirFromEvent(credOpts, ev); if (wp) folders.push(wp); }
@@ -231,7 +234,9 @@ export async function runListen(p) {
231
234
  const shown = { ...data, events, pending_confirms: pending };
232
235
  const text = formatPoll(shown, { json: flags.json, activeTasks, annotate: true });
233
236
  const folderLines = folders.map((wp) => mtText('workdir.event', { path: wp })).join('\n');
234
- if (text) log(flags.json ? text : `${text}\n${folderLines ? `${folderLines}\n` : ''}${LISTEN_AGAIN_LINE}`);
237
+ // v0.37: the platform's "settings after connecting" reminder rides along (at most once a day per item)
238
+ const hintText = flags.json ? '' : setupHintLines(data && data.setup_hint, env).join('\n');
239
+ if (text) log(flags.json ? text : `${text}\n${folderLines ? `${folderLines}\n` : ''}${hintText ? `${hintText}\n` : ''}${LISTEN_AGAIN_LINE}`);
235
240
  return 1;
236
241
  }
237
242
 
@@ -2,7 +2,7 @@
2
2
  // There is no consent step and no switch: installing it is the standard way to connect (decision 11-15).
3
3
 
4
4
  import fs from 'node:fs';
5
- import { configFromFlags, readConfig, writeConfig, readState, writeState, runsToday, statePath, configPath, cursorFile } from './config.js';
5
+ import { configFromFlags, readConfig, writeConfig, readState, writeState, runsToday, statePath, configPath, cursorFile, effectiveDailyMax } from './config.js';
6
6
  import { Listener, runStartTest } from './run.js';
7
7
  import { installAutostart, uninstallAutostart, labelOf, unitNameOf, defaultEntryPath } from './install.js';
8
8
  import { lt } from './text.js';
@@ -98,7 +98,7 @@ export async function runListenStatus(p) {
98
98
  if (flags.json) {
99
99
  log(JSON.stringify({
100
100
  installed: !!cfg, autostart: cfg ? cfg.autostartKind : null, running, runs_today: used,
101
- daily_max: cfg ? cfg.dailyMax : null, paused: st.paused, last: st.last, node_path_missing: nodeStale,
101
+ daily_max: cfg ? effectiveDailyMax(cfg, st) : null, paused: st.paused, last: st.last, node_path_missing: nodeStale,
102
102
  }, null, 2));
103
103
  return 0;
104
104
  }
@@ -106,14 +106,14 @@ export async function runListenStatus(p) {
106
106
  if (!cfg) { lines.push(lt('status.installed.no', {}, env)); log(lines.join('\n')); return 0; }
107
107
  lines.push((cfg.autostartKind && cfg.autostartKind !== 'none' ? lt('status.installed.yes', { kind: cfg.autostartKind }, env) : lt('status.installed.noauto', {}, env)));
108
108
  lines.push(lt(running ? 'status.running.yes' : 'status.running.no', {}, env));
109
- lines.push(lt('status.today', { n: used, max: cfg.dailyMax }, env));
109
+ lines.push(lt('status.today', { n: used, max: effectiveDailyMax(cfg, st) }, env));
110
110
  if (st.last) {
111
111
  lines.push(st.last.ok
112
112
  ? lt('status.last.ok', { time: fmtTime(st.last.at), sec: Math.round((st.last.ms || 0) / 1000) }, env)
113
113
  : lt('status.last.fail', { time: fmtTime(st.last.at), why: whyText(st.last.why, env) }, env));
114
114
  } else lines.push(lt('status.last.none', {}, env));
115
115
  if (st.paused) {
116
- const key = `status.paused.${st.paused.reason}`;
116
+ const key = st.paused.reason === 'platform' && st.paused.detail === 'cap' ? 'status.paused.platform_cap' : `status.paused.${st.paused.reason}`;
117
117
  const why = lt(key, { n: st.fails, why: st.paused.detail || '' }, env);
118
118
  lines.push(lt('status.paused', { why }, env));
119
119
  }
@@ -17,7 +17,7 @@ import { resolveCredDir } from '../profile.js';
17
17
 
18
18
  export const LISTENER_DEFAULTS = Object.freeze({
19
19
  maxParallel: 2, // sessions running at the same time (1-4)
20
- dailyMax: 100, // starts per local day; at the limit the listener stops waking until local midnight
20
+ dailyMax: 120, // starts per local day (v0.37: 100 -> 120, PL-03; the platform sends the same number in `limits`)
21
21
  timeoutMs: 30 * 60 * 1000, // one run is killed after this long and counts as a failure
22
22
  agentWakeGapMs: 10 * 60 * 1000, // the same session is woken by another Agent at most once per this long
23
23
  humanMergeMs: 30 * 1000, // messages from people inside this window are merged into one run
@@ -70,6 +70,7 @@ export function configFromFlags(flags) {
70
70
  exec: String(flags.exec || '').trim(),
71
71
  maxParallel: clampInt(flags.maxParallel, MAX_PARALLEL_RANGE[0], MAX_PARALLEL_RANGE[1], LISTENER_DEFAULTS.maxParallel),
72
72
  dailyMax: clampInt(flags.dailyMax, 1, 10000, LISTENER_DEFAULTS.dailyMax),
73
+ dailyMaxSet: flags.dailyMax != null && flags.dailyMax !== '' && Number.isFinite(parseInt(flags.dailyMax, 10)), // chosen on purpose: may only lower the platform number
73
74
  timeoutMs: timeout || LISTENER_DEFAULTS.timeoutMs,
74
75
  cwd: flags.cwd ? String(flags.cwd) : null,
75
76
  env: (flags.envNames || []).filter((n) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(n)),
@@ -80,7 +81,7 @@ export function readConfig(credOpts) {
80
81
  const c = readJson(configPath(credOpts));
81
82
  if (!c || typeof c.exec !== 'string' || !c.exec.trim()) return null;
82
83
  return {
83
- ...configFromFlags({ exec: c.exec, maxParallel: c.maxParallel, dailyMax: c.dailyMax, cwd: c.cwd, envNames: c.env }),
84
+ ...configFromFlags({ exec: c.exec, maxParallel: c.maxParallel, dailyMax: c.dailyMaxSet === true ? c.dailyMax : null, cwd: c.cwd, envNames: c.env }),
84
85
  timeoutMs: Number(c.timeoutMs) > 0 ? Number(c.timeoutMs) : LISTENER_DEFAULTS.timeoutMs,
85
86
  autostart: c.autostart !== false,
86
87
  installedAt: c.installedAt || null,
@@ -108,6 +109,24 @@ export function emptyState() {
108
109
  };
109
110
  }
110
111
 
112
+ /**
113
+ * The daily limit in force (v0.37, PA-06): the number the platform sends in `limits` wins; a number the owner chose
114
+ * with --daily-max may only make it smaller. Without a platform number (old platform, nothing heard yet) the saved one.
115
+ */
116
+ export function effectiveDailyMax(cfg, state) {
117
+ const own = Number(cfg && cfg.dailyMax) || LISTENER_DEFAULTS.dailyMax;
118
+ const plat = Number(state && state.limits && state.limits.daily_max);
119
+ if (!Number.isFinite(plat) || plat <= 0) return own;
120
+ return cfg && cfg.dailyMaxSet ? Math.min(own, plat) : plat;
121
+ }
122
+
123
+ /** Consecutive failed starts before pausing: the platform number when it sent one, else the local default. */
124
+ export function effectiveFailPause(cfg, state) {
125
+ const plat = Number(state && state.limits && state.limits.fail_pause_after);
126
+ const own = Number(cfg && cfg.failPauseAfter) || LISTENER_DEFAULTS.failPauseAfter;
127
+ return Number.isFinite(plat) && plat > 0 ? plat : own;
128
+ }
129
+
111
130
  export function readState(credOpts) {
112
131
  return { ...emptyState(), ...(readJson(statePath(credOpts)) || {}) };
113
132
  }
@@ -61,6 +61,13 @@ export function buildPrompt(payload, env = process.env, identity = null, job = n
61
61
  const wl = workdirLine(job, lang);
62
62
  if (wl) lines.push(wl);
63
63
  if (p.rewake === true) lines.push(REWAKE_LINE[lang]);
64
+ // v0.37 PA-09: unread messages that did not fit into this call: say how many and how to page back
65
+ if (Number(p.skipped) > 0) {
66
+ const more = p.more_cmd_before != null ? ` --before ${p.more_cmd_before}` : ' --before <编号>';
67
+ lines.push(lang === 'en'
68
+ ? `${p.skipped} older unread messages are not included here (the ones that mention you or answer you come first). Page back with: anytowork chat read ${sid}${more.replace('<编号>', '<number>')}`
69
+ : `还有 ${p.skipped} 条更早的未读消息没有提供(@你和回你的已优先带上),可用 anytowork chat read ${sid}${more} 翻页。`);
70
+ }
64
71
  if (identity && (identity.profile || identity.dir)) {
65
72
  const pf = identity.profile;
66
73
  lines.push(lang === 'en'
@@ -19,10 +19,11 @@ 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 { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
22
23
  import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
23
24
  import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
24
25
  import {
25
- LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight,
26
+ LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight, effectiveDailyMax, effectiveFailPause,
26
27
  readListenerCursor, writeListenerCursor, appendLog, promptsDir,
27
28
  } from './config.js';
28
29
 
@@ -207,6 +208,12 @@ export class Listener {
207
208
  handleEvents(events) {
208
209
  // v0.36: a picked / signed event may carry the work folder of the job: set it up on this computer
209
210
  for (const e of events || []) { const wp = workdirFromEvent(this.credOpts, e); if (wp) this.logLine(`workdir ${wp}`); }
211
+ // v0.37 PA-12: a wake-up test has no session. Recognise it before any session id is looked at; it never enters a
212
+ // session's queue or context, and it is not counted against the daily limit.
213
+ noteWakeTests(events, this.credOpts, this.nowMs());
214
+ for (const e of events || []) {
215
+ if (e && e.event_type === 'wake_test') this.handleWakeTest(e);
216
+ }
210
217
  for (const e of events || []) {
211
218
  if (!e || e.event_type !== 'wb.wake') continue;
212
219
  const p = e.payload || {};
@@ -214,7 +221,7 @@ export class Listener {
214
221
  if (!UUID.test(String(sid || ''))) { this.logLine(`ignored id=${e.id} why=bad_session`); continue; }
215
222
  if (this.isPaused()) continue;
216
223
  const now = this.nowMs();
217
- if (runsToday(this.state, now) >= this.cfg.dailyMax) { this.pause('cap'); return; }
224
+ if (runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.pause('cap'); return; }
218
225
  const wakeId = String(p.wake_id != null ? p.wake_id : (e.id != null ? e.id : ''));
219
226
  const fromAgent = (p.from && p.from.type === 'agent') || p.reason === 'agent_mention';
220
227
  const msg = Number(p.last_msg_id != null ? p.last_msg_id : (p.msg_id != null ? p.msg_id : p.first_msg_id));
@@ -234,12 +241,56 @@ export class Listener {
234
241
  this.pump();
235
242
  }
236
243
 
244
+ /**
245
+ * v0.37 PA-12: the platform started a wake-up test for this Agent (`wake_test`: {test_id, nonce, deadline_at, next_action}).
246
+ * Start the Agent once with a prompt that only asks it to answer the test. The isolation key is the fixed word
247
+ * `wake-test`: no session id, no session queue, no session context, not counted in the daily limit, and a test that is
248
+ * already running (or was handled) is not started twice.
249
+ */
250
+ handleWakeTest(e) {
251
+ const p = (e && e.payload) || {};
252
+ const testId = String(p.test_id || '');
253
+ const nonce = testCode(p);
254
+ if (!isSafeId(testId) || !/^[A-Za-z0-9]{4,32}$/.test(nonce)) { this.logLine(`ignored id=${e.id} why=bad_wake_test`); return; }
255
+ if (!this.seenTests) this.seenTests = new Set();
256
+ if (this.seenTests.has(testId)) return;
257
+ this.seenTests.add(testId);
258
+ if (this.seenTests.size > 50) this.seenTests.delete(this.seenTests.values().next().value);
259
+ const dl = p.deadline_at ? Date.parse(p.deadline_at) : NaN;
260
+ if (Number.isFinite(dl) && dl < this.nowMs()) { this.logLine(`wake_test id=${testId.slice(0, 8)} expired`); return; }
261
+ const pr = this.runWakeTest({ testId, nonce, payload: p }).catch(() => {}).finally(() => this.active.delete(pr));
262
+ this.active.add(pr);
263
+ }
264
+
265
+ async runWakeTest({ testId, nonce, payload }) {
266
+ const now0 = this.nowMs();
267
+ const key = 'wake-test';
268
+ const promptFile = path.join(promptsDir(this.credOpts), `wake-test-${testId.slice(0, 8)}-${now0}.txt`);
269
+ let wrote = false;
270
+ const prompt = wakeTestPrompt({ ...payload, nonce }, this.env);
271
+ try {
272
+ fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
273
+ fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
274
+ wrote = true;
275
+ } catch { /* the prompt still goes on standard input */ }
276
+ try {
277
+ const vals = { sid: key, sessionKey: key, groupId: '', wakeId: testId, reason: 'wake_test', hireId: '', promptFile };
278
+ const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
279
+ env.ANYTOWORK_WAKE_TEST_ID = testId;
280
+ const res = await this.execCommand({ command: expandCommand(this.cfg.exec, vals), input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
281
+ const ok = !!res && res.code === 0 && !res.timedOut && !res.error;
282
+ this.logLine(`wake_test id=${testId.slice(0, 8)} ${ok ? 'ok' : 'fail'} ms=${this.nowMs() - now0}`);
283
+ } finally {
284
+ if (wrote) { try { fs.unlinkSync(promptFile); } catch { /* gone */ } }
285
+ }
286
+ }
287
+
237
288
  /** Start whatever may start now, and arm a timer for what must wait. */
238
289
  pump() {
239
290
  if (this.isPaused()) return;
240
291
  for (;;) {
241
292
  const now = this.nowMs();
242
- if (this.queue.size && runsToday(this.state, now) >= this.cfg.dailyMax) { this.pause('cap'); return; }
293
+ if (this.queue.size && runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.pause('cap'); return; }
243
294
  const job = this.queue.take();
244
295
  if (!job) break;
245
296
  countRun(this.state, now);
@@ -293,7 +344,7 @@ export class Listener {
293
344
  this.state.fails = 0;
294
345
  } else {
295
346
  this.state.fails += 1;
296
- if (this.state.fails >= this.cfg.failPauseAfter) this.pause('fail', why);
347
+ if (this.state.fails >= effectiveFailPause(this.cfg, this.state)) this.pause('fail', why);
297
348
  }
298
349
  } finally {
299
350
  if (ranFile) { try { fs.unlinkSync(ranFile); } catch { /* already gone */ } }
@@ -371,6 +422,12 @@ export class Listener {
371
422
  this.state.seenAt = this.nowMs();
372
423
  if (this.state.seenAt - (this.lastSeenSave || 0) >= 30000) { this.lastSeenSave = this.state.seenAt; this.save(); } // lets `listen status` tell it is alive
373
424
  const lis = data && data.listener;
425
+ // v0.37 PA-06: the platform's own numbers (daily limit, failures before a pause) replace the local defaults
426
+ if (lis && lis.limits && typeof lis.limits === 'object') {
427
+ const was = JSON.stringify(this.state.limits || null);
428
+ this.state.limits = { daily_max: Number(lis.limits.daily_max) || null, fail_pause_after: Number(lis.limits.fail_pause_after) || null };
429
+ if (JSON.stringify(this.state.limits) !== was) this.save();
430
+ }
374
431
  if (lis && lis.allowed === false) {
375
432
  // The platform asks to stop waking for now (for example the wake-ups are not being read). Check back later.
376
433
  this.lastPlatformCheck = this.nowMs();