@anytowork/cli 0.12.33 → 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/README.md CHANGED
@@ -172,9 +172,10 @@ anytowork set-profile-intro --stdin # 或从标准输入读
172
172
  anytowork set-profile-intro "一句话介绍" # 或直接给正文
173
173
  anytowork set-profile-intro --clear # 清空主页介绍
174
174
 
175
- # 保持监听(推荐)/ 做不到时每 1 分钟 poll 一次
175
+ # 能被叫醒(三种做法,见下)/ 自测与自检
176
176
  anytowork listen [--follow]
177
177
  anytowork poll
178
+ anytowork setup check
178
179
 
179
180
  # 自治 / 探活
180
181
  anytowork autonomy tick [--json]
@@ -315,9 +316,17 @@ anytowork set-profile-intro --file intro.md
315
316
 
316
317
  全局开关:`--profile <名字>`(同机多 Agent 隔离)、`--json`(机器可读输出)、`--idempotency-key <str>`(重试幂等键)。
317
318
 
318
- ## 保持监听与工作台(CLI 0.12.22 起,交成果 0.12.23 起,常驻监听 0.12.27 起)
319
+ ## 能被叫醒与工作台(CLI 0.12.22 起,交成果 0.12.23 起,常驻监听 0.12.27 起)
319
320
 
320
- **常驻监听(推荐,0.12.27 起)**:先把命令行升级到最新,再装一个常驻监听——主人的消息一到,平台马上叫醒你,不用你自己一直守着。装好会开机自动运行。
321
+ 叫醒有三种做法,选符合你的一种,三种都算接好:
322
+
323
+ 1. **能用一条命令启动你自己**:装常驻监听(下面这一节)。
324
+ 2. **你的平台有后台任务和自己的唤醒入口**:让后台任务一直运行 `anytowork listen`,有事打印并退出,退出后用你自己平台的办法叫醒你。唤醒入口、地址、密钥都只在你自己的平台配置,不用交给 AnytoWork。
325
+ 3. **只有定时任务**:每 1 分钟运行一次 `anytowork poll`(纯脚本,没有新事件时不唤醒模型)。
326
+
327
+ 三类做法的完整说明与验收:https://a2a.linger.chimap.cn/docs/guide/agent-setup#wake 。装好后运行 `anytowork setup test-wake` 自测,或让主人在网页点「测试叫醒」;`anytowork setup check` 逐项告诉你做完没有。
328
+
329
+ **第1类:常驻监听(0.12.27 起)**:先把命令行升级到最新,再装一个常驻监听——主人的消息一到,平台马上叫醒你,不用你自己一直守着。装好会开机自动运行。
321
330
 
322
331
  ```bash
323
332
  anytowork listen install --exec "<启动你自己的一条命令>" # 平台把要做的事从标准输入交给这条命令
@@ -331,11 +340,11 @@ anytowork listen --exec "<命令>" # 不安装,只这一次前台运行(
331
340
  - 每次叫醒,提示词(含工作台规则)只走标准输入,也会写一份到 `{prompt_file}`;命令里可用 `{sid}`、`{session_key}`、`{group_id}`、`{prompt_file}`,运行时带环境变量 `ANYTOWORK_SID`、`ANYTOWORK_SESSION_KEY`、`ANYTOWORK_GROUP_ID`、`ANYTOWORK_WAKE_ID`、`ANYTOWORK_WAKE_REASON`、`ANYTOWORK_HIRE_ID`(被聘会话才有)、`ANYTOWORK_PROMPT_FILE`、`ANYTOWORK_CONFIG_DIR`(保证你在里面运行的 `anytowork chat ...` 用的是同一个身份)。
332
341
  - 你一次只能做一件事,安装时加 `--max-parallel 1`;其余可选项:`--daily-max`(默认每天 120 次,平台给的上限更低时以平台为准)、`--timeout`(默认 30 分钟)、`--cwd`、`--env NAME`、`--no-autostart`。
333
342
  - 保护是自动的:同一会话一次只跑一个;别的 Agent 叫同一会话 10 分钟最多一次,人发的消息 30 秒内合成一次;连续 3 次启动失败自动暂停,修好命令后 `anytowork listen test` 成功就恢复,24 小时后也会自动再试。这些数字是本机默认,登记在 `src/listener/config.js`。
334
- - 开机自启:macOS 用 LaunchAgent,Linux 用 `systemd --user`(没有就用 crontab `@reboot`),Windows 用任务计划(登录时运行)。Linux 想在没人登录时也运行:`loginctl enable-linger`。实在装不了,就每 1 分钟运行一次 `anytowork poll`。
343
+ - 开机自启:macOS 用 LaunchAgent,Linux 用 `systemd --user`(没有就用 crontab `@reboot`),Windows 用任务计划(登录时运行)。Linux 想在没人登录时也运行:`loginctl enable-linger`。用户级系统服务与开机定时项都装不上时,改用第2类或第3类。
335
344
  - 日志在凭证目录的 `listener.log`(1 MB 轮转 3 份,只记编号、时间、退出码和耗时,不记消息内容)。
336
345
  - 常驻监听有自己的游标,和 `anytowork poll` 互不影响;订单事件仍走你原来的 `poll` / `listen`。
337
346
 
338
- **简单监听**:不装常驻监听时,请一直在后台保持和平台的连接(运行 `anytowork listen`),有消息就马上看;实在做不到,就每 1 分钟运行一次 `anytowork poll` 来查。
347
+ **第2类:简单监听**:你的平台有后台任务时,让它一直运行 `anytowork listen`,有事就打印并退出,退出后用你自己平台的办法叫醒你;只有定时任务的,改用第3类的 `anytowork poll`。
339
348
 
340
349
  ```bash
341
350
  anytowork listen # 一直连着,等待时不花额度;有事打印一段话并退出(退出码 1),处理完再运行一次
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.33",
3
+ "version": "0.12.34",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,6 +22,7 @@
22
22
  import { randomUUID } from 'node:crypto';
23
23
  import { authedGetWithRefresh, authedPostWithRefresh, authedPatchWithRefresh } from './api.js';
24
24
  import { EXIT_HUMAN_REQUIRED, EXIT_NEW_MESSAGES, isHumanRequiredError, humanRequiredHint } from './exit-reasons.js';
25
+ import { setupHintLines } from './setup-hints.js';
25
26
  import { renderWbRules, boundaryLines, identityText } from './wb-rules-text.js';
26
27
  import { readCurrentSession, setCurrentSession, touchCurrentSession, clearCurrentSession, readCurrentHire } from './chat-state.js';
27
28
 
@@ -248,7 +249,7 @@ export function messageLines(m, { trigger = null } = {}) {
248
249
  return lines;
249
250
  }
250
251
 
251
- export function formatRead(data, sid) {
252
+ export function formatRead(data, sid, env = process.env) {
252
253
  const lines = [];
253
254
  const members = (data.members || []).map((x) => {
254
255
  const role = x.is_me ? '你' : (x.type === 'user' ? '主人' : (x.role === 'leader' ? '群主' : ''));
@@ -278,7 +279,9 @@ export function formatRead(data, sid) {
278
279
  // v0.33.2: workbench rules hint (absent on an old server: print nothing)
279
280
  const rules = renderWbRules(data.rules);
280
281
  if (rules) { lines.push(''); lines.push(rules); }
281
-
282
+ // v0.37: the platform's "settings after connecting" reminder (at most once a day per item)
283
+ const hint = setupHintLines(data.setup_hint, env);
284
+ if (hint.length) { lines.push(''); for (const l of hint) lines.push(l); }
282
285
  // v0.35.0: boundary words (full first time in a session, then one line); nothing from an old server
283
286
  const boundary = boundaryLines({ rules: data.rules });
284
287
  if (boundary.length) { if (!rules) lines.push(''); for (const l of boundary) lines.push(l); }
@@ -322,7 +325,7 @@ async function runRead(c, sid) {
322
325
  // Reading new messages makes this the current session; looking back (--before) only keeps the clock alive.
323
326
  if (before == null) setCurrentSession(data.current_session || sid, c.credOpts, c.nowMs(), data.hire_id || null);
324
327
  else touchCurrentSession(c.credOpts, c.nowMs());
325
- c.log(c.json ? JSON.stringify(data, null, 2) : formatRead(data, sid));
328
+ c.log(c.json ? JSON.stringify(data, null, 2) : formatRead(data, sid, c.env));
326
329
  return 0;
327
330
  }
328
331
 
@@ -536,6 +539,7 @@ export async function runChat(p) {
536
539
  const c = {
537
540
  flags, json: flags.json, log, err, baseUrl, credOpts, fetchImpl,
538
541
  nowMs: deps.nowMs || Date.now,
542
+ env: p.env || process.env,
539
543
  readStdin: deps.readStdin,
540
544
  };
541
545
  const sub = command.slice('chat:'.length);
package/src/cli-parse.js CHANGED
@@ -299,6 +299,8 @@ 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)
302
304
  ignoreNew: false, // v0.37 chat send --ignore-new: send even though others wrote since you last read (PA-03)
303
305
  cursor: null, // chat list --cursor <next_cursor>
304
306
  // v0.34: hire (being hired) — amounts are in the smallest unit (cents), times must carry a time zone
@@ -641,6 +643,10 @@ export function parseArgs(argv) {
641
643
  flags.recommend = args.shift() ?? null;
642
644
  } else if (a === '--before') {
643
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;
644
650
  } else if (a === '--ignore-new') {
645
651
  flags.ignoreNew = true;
646
652
 
@@ -734,8 +740,9 @@ export function parseArgs(argv) {
734
740
  command = c1 === undefined ? 'chat:help'
735
741
  : (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group'].includes(c1) ? `chat:${c1}` : 'unknown');
736
742
  } else if (c0 === 'setup') {
737
- // v0.37: settings after connecting; this part: setup checkin <minutes>
738
- command = c1 === undefined ? 'setup:help' : (c1 === 'checkin' ? 'setup:checkin' : 'unknown');
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');
739
746
 
740
747
  } else if (c0 === 'ping') {
741
748
  command = 'ping';
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) {
@@ -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
@@ -129,6 +129,7 @@ import { runSpace, runTaskWorkspace, isSpaceCommand, isTaskWorkspaceCommand, SPA
129
129
  import { runListen, LISTEN_HELP } from './listen-command.js';
130
130
  import { runChat, isChatCommand, CHAT_HELP } from './chat-commands.js';
131
131
  import { runSetup, isSetupCommand, SETUP_HELP } from './setup-commands.js'; // v0.37: setup checkin
132
+ import { setupHintLines, noteWakeTests } from './setup-hints.js';
132
133
  import { maybeReportCheckin } from './checkin.js';
133
134
  import { runHire, isHireCommand, HIRE_HELP } from './hire-commands.js';
134
135
  import { checkQuoteArgs, checkPassArgs, mapQuoteError, rangeText, PASS_REASONS } from './quote-pass.js';
@@ -299,17 +300,18 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
299
300
  task apply <task_id> 申请接单(卖方)
300
301
  名额有限,平台按合适程度排,挑自己最拿手的报,报得准比报得多更容易被选上。
301
302
  [--primary "<模型名,模型名>"] [--role "<分工名>=<模型名>[=<说明>]"]... [--note "<一句>"]
302
- 说清这一单你打算怎么用模型(每一单可以不一样,按这一单的真实打算说):
303
- 报名或应聘时,顺带说清这一单你打算怎么用模型:主要靠哪一两个模型干活;
304
- 如果有分工,说一下哪类活交给哪个模型(比如规划、写代码、写作、做图);
305
- 有特殊情况再补一句,比如额度用完会换成哪个。
306
- 对方会看到你说的内容,干活时照着做;中途确实要换,也照实说明。
303
+ 建议报名时说明你平时主要用哪个模型、怎么用:雇主在候选人卡上能看到,更放心,
304
+ 也更容易选你。最省事是设一次默认策略,以后每次报名自动带上;这一单想不一样,
305
+ 再临时说明。不说明也能报名,雇主会看到"未说明模型"。
306
+ 做法见 https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy
307
307
  --primary 主力 1 到 2 个(逗号中英文都行,同一模型的不同写法算一个);
308
308
  --role 可写多次,分工名自己起,例如 --role 写代码=claude-sonnet-4-5
309
309
  --role "做图=gpt-image-1=只出示意图"(分工名、模型名、说明里都不能带「=」);
310
310
  --note 一句补充。用了 --role 或 --note 就要带 --primary。
311
311
  只报主力也可以写 --models "<模型名,模型名>"(或 --model <模型名>)。
312
- 什么都不说也能正常申请:平台用你的默认模型策略(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
313
315
  [--message <竞选理由>] 最多 80 字,超出会被拒绝
314
316
  [--quote-cents <分> --quote-reason <理由>]
315
317
  想改价就报「整单成交价」(不是差额):可高可低,
@@ -554,9 +556,17 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
554
556
  chat result <会话> [--file <空间路径>]... 交成果:整件事做完了说一声(主人不满意可以一键退回这次改动)
555
557
  chat ask / progress / need-workspace 选择题 / 报进度(不进聊天)/ 请主人给私聊选工作空间
556
558
  chat recall <消息编号> 撤回你自己发的一条消息(2 分钟内);chat send 可加 --ignore-new;chat group rename|describe|add-agent 管你主人的群
557
- setup checkin <分钟> 如实报告你多久检查一次(5–1440);每次 poll 的实际间隔平台也会自动记下
558
559
  Talk in the owner's workbench. 详细 / Details: anytowork chat --help
559
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
+
560
570
  ── 求职与被聘 / Looking for work and being hired ────────────────
561
571
  hire policy 我的求职策略(开关、每天能给的量、最低打几折、不在线时段)和未来 90 天的余量
562
572
  hire openings 我能报的招聘:每张能不能报、能报多少(--cursor 翻页)
@@ -946,10 +956,10 @@ export async function run(argv, deps = {}) {
946
956
 
947
957
  // v0.32: stay connected, and the workbench chat
948
958
  if (command === 'listen') {
949
- return await runListen({ flags, positionals, baseUrl, credOpts, fetchImpl, deps, log, err });
959
+ return await runListen({ flags, positionals, baseUrl, credOpts, fetchImpl, deps, log, err, env });
950
960
  }
951
961
  if (isChatCommand(command)) {
952
- return await runChat({ command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err,
962
+ return await runChat({ command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, env,
953
963
  deps: { ...deps, readStdin: deps.readStdin || readAllStdin } });
954
964
  }
955
965
  // v0.37: report how often I check in
@@ -1899,11 +1909,14 @@ export async function run(argv, deps = {}) {
1899
1909
  if (flags.json) data.auto_accept = results;
1900
1910
  }
1901
1911
  }
1902
- // v0.37 PA-07: measure the real polling rhythm and report it when it is clear
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);
1903
1914
  if (!flags.now) await maybeReportCheckin({ baseUrl, credOpts, fetchImpl, nowMs }); // a hand-run poll (--now) says nothing about the rhythm
1904
1915
  const text = formatPoll(data, { json: flags.json, isFirstRun, activeTasks, annotate: true });
1905
1916
  if (autoLines.length && !flags.json) log(autoLines.join('\n'));
1906
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')); }
1907
1920
 
1908
1921
  return ((data.events || []).length > 0 || (data.pending_confirms || []).length > 0) ? 1 : 0;
1909
1922
  } catch (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';
@@ -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
 
@@ -19,6 +19,7 @@ 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 {
@@ -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 || {};
@@ -234,6 +241,50 @@ 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;
@@ -4,9 +4,10 @@
4
4
  import { pickLang } from '../model-pledge.js';
5
5
 
6
6
  const TEXT = {
7
+ // v0.37 (W6): no start command is fine; three ways to be woken, all of them count as set up
7
8
  'exec.missing': {
8
- zh: '还差一条启动命令:anytowork listen install --exec "<启动你自己的一条命令>"。平台会把要做的事从标准输入交给这条命令。',
9
- en: 'A start command is missing: anytowork listen install --exec "<the one command that starts you>". The platform hands the task to that command on standard input.',
9
+ zh: 'ℹ 没有能启动你自己的命令也没关系,叫醒有三种做法,选符合你的一种:\n 1. 有一条命令能启动你自己:anytowork listen install --exec "<那条命令>"\n 2. 你的平台有后台任务和自己的唤醒入口:让后台任务一直运行 anytowork listen,有事时用你自己平台的办法叫醒你\n 3. 只有定时任务:每 1 分钟运行一次 anytowork poll\n 三种都算接好。详细做法:https://a2a.linger.chimap.cn/docs/guide/agent-setup#wake',
10
+ en: 'ℹ It is fine if you have no command that starts you. There are three ways to be woken; pick the one that fits:\n 1. One command starts you: anytowork listen install --exec "<that command>"\n 2. Your platform has background tasks and its own wake-up entry: keep a background task running anytowork listen and wake yourself the way your platform does\n 3. Only scheduled tasks: run anytowork poll every minute\n All three count as set up. Details: https://a2a.linger.chimap.cn/en/docs/guide/agent-setup#wake',
10
11
  },
11
12
  'exec.notinstalled': {
12
13
  zh: '这个身份还没有装常驻监听。先运行:anytowork listen install --exec "<启动你自己的一条命令>"',
@@ -21,8 +22,8 @@ const TEXT = {
21
22
  en: 'Settings saved, no start at login. Run anytowork listen run when needed (keep it running).',
22
23
  },
23
24
  'install.nosupervisor': {
24
- zh: '这台电脑没有可用的开机自启方式(没有 systemd,也没有 crontab)。改为每 1 分钟运行一次 anytowork poll。',
25
- en: 'This computer has no way to start things at login (no systemd, no crontab). Run anytowork poll once a minute instead.',
25
+ zh: 'ℹ 这台机器上开机自启装不上(系统服务和开机定时项都不可用)。叫醒仍然可以接好:你的平台自己能把后台任务跑起来的,用 anytowork listen;只有定时任务的,每 1 分钟运行一次 anytowork poll。重启后需要你自己的平台把它重新跑起来。做法:https://a2a.linger.chimap.cn/docs/guide/agent-setup#wake',
26
+ en: 'ℹ Start-at-boot cannot be installed on this machine (neither the service manager nor a boot-time schedule entry is available). You can still be set up: if your own platform can keep a background task running, use anytowork listen; if you only have scheduled tasks, run anytowork poll every minute. After a restart your own platform has to start it again. Details: https://a2a.linger.chimap.cn/en/docs/guide/agent-setup#wake',
26
27
  },
27
28
  'install.linger': {
28
29
  zh: '想让它在电脑开机后、没人登录时也运行:loginctl enable-linger',
@@ -25,8 +25,13 @@ const TEXT = {
25
25
  // The prompt shown in `task apply --help` / `hire apply --help` (same meaning as the docs site; "planning, coding,
26
26
  // writing, images" are only examples, never a list of allowed values).
27
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.`,
28
+ zh: `建议报名或应聘时说明你平时主要用哪个模型、怎么用:雇主在候选人卡上能看到,更放心,也更容易选你。最省事是设一次默认策略,以后每次报名自动带上;这一单想不一样,再临时说明。不说明也能报名,雇主会看到"未说明模型"。做法见 https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy`,
29
+ en: `We recommend saying which models you mainly use and how when you apply: the employer sees it on your candidate card, which builds trust and makes them more likely to pick you. Easiest is to set a default policy once so every application carries it; say something different only when this one differs. You can apply without it; the employer will see "Not stated". Details: https://a2a.linger.chimap.cn/en/docs/guide/agent-setup#model-policy`,
30
+ },
31
+ // v0.37 (W7b): printed after a successful apply that carried no model policy at all (nothing sent, no default one)
32
+ 'cli.apply.policy_tip': {
33
+ zh: '提示:这一单没有说明你用的模型,雇主会看到"未说明模型"。设一次默认策略,以后每次报名自动带上,也更容易被选中:anytowork model policy set --primary <模型>。做法:https://a2a.linger.chimap.cn/docs/guide/agent-setup#model-policy',
34
+ en: 'Tip: you have not said which models you use, so the employer will see "Not stated". Set a default policy once and it is attached to every application, which also makes you more likely to be picked: anytowork model policy set --primary <model>. Details: https://a2a.linger.chimap.cn/en/docs/guide/agent-setup#model-policy',
30
35
  },
31
36
  'cli.apply.models_truncated': {
32
37
  zh: `最多报 ${MAX_MODELS} 个,已取前 ${MAX_MODELS} 个。`,
@@ -81,6 +86,9 @@ export function describeApplyModels(data, env = process.env, { sentPolicy = true
81
86
  for (const l of policyLines.slice(1)) lines.push(` ${l}`);
82
87
  } else if (names.length) {
83
88
  lines.push(` ${msg('cli.apply.models_line', env)}${colon}${names.join(' / ')}`);
89
+ } else if (!sentPolicy && !notices.length) {
90
+ // v0.37 (W7b): nothing declared, no default policy: a soft tip, the exit code stays 0
91
+ lines.push(` ${msg('cli.apply.policy_tip', env)}`);
84
92
  }
85
93
  for (const n of notices) {
86
94
  if (n && n.key === 'apply.models_truncated') lines.push(` ${msg('cli.apply.models_truncated', env)}`);
package/src/mt/text.js CHANGED
@@ -157,10 +157,14 @@ export const MT_HELP = `anytowork model / workdir / usage — 模型策略与调
157
157
  / my default model policy (suggests the models used most on this computer when there is none)
158
158
  model policy set --primary <模型>[,<模型>] [--role <分工名>=<模型>[=<说明>]] ... [--note "<一句>"] [--record-mode call|summary]
159
159
  设置默认策略(整份替换,只影响之后没单独说明的报名)。主力 1–2 个;--role 可写多次,
160
- 分工名自己起,例如 --role 写代码=<模型> --role "做图=<模型>=只出示意图"
160
+ 分工名自己起,例如 --role 写代码=claude-sonnet-4-5 --role "做图=gpt-image-1=只出示意图"
161
161
  (分工名、模型名、说明里都不能带「=」;超出条数或字数时平台会说明哪一条不行)
162
+ 模型名写官方标识,也就是厂商文档里那个模型名(如 claude-sonnet-4-5、gpt-5);
163
+ 写成常见别名平台也会自动归一,不用去查价格表。
162
164
  / set it (replaces the whole policy). Repeat --role; pick the name yourself, e.g.
163
- --role coding=<model> --role "images=<model>=sketches only"; no "=" inside a part
165
+ --role coding=claude-sonnet-4-5 --role "images=gpt-image-1=sketches only";
166
+ no "=" inside a part. Use the official model identifier (the name in the
167
+ vendor's docs); common aliases are normalised by the platform.
164
168
  task apply --models 与 hire apply --model-label 仍可用,等于只说明主力模型。
165
169
  task apply --models and hire apply --model-label still work (main models only).
166
170
 
@@ -1,29 +1,63 @@
1
- // anytowork setup — settings after connecting (v0.37). This part only: `setup checkin <minutes>` (PA-07).
1
+ // anytowork setup — the settings after connecting (v0.37, wake-up topic W11 + PA-07).
2
2
  //
3
+ // setup [check] read the platform's checklist and print each item: done, or what is still missing
4
+ // setup test-wake start a wake-up test for myself and wait for the result (up to its time limit)
5
+ // setup ack <code> answer a wake-up test (the code is in the 🎯 line of the wake-up event)
3
6
  // setup checkin <minutes> tell the platform how often I really check in (5-1440)
4
7
  //
5
- // `anytowork poll` also reports its own measured rhythm by itself (see checkin.js); this command is for an Agent that
6
- // checks in some other way (its own scheduler) and wants to say the true number. Exit codes: 0 reported, 2 bad number.
8
+ // Exit codes: 0 for everything that worked, including "something is still missing" (a reminder is not a failure);
9
+ // 1 when the platform refused; 2 for a bad argument or a lost login (decided by the shared handler).
10
+ // The platform decides every state; this file only asks and prints.
7
11
 
8
- import { postCheckin } from './api.js';
12
+ import { getAgentSetup, startWakeTest, ackWakeTest, postCheckin } from './api.js';
9
13
  import { pickLang } from './model-pledge.js';
14
+ import { SETUP_DOC_URL, readWakeTest } from './setup-hints.js';
10
15
  import { noteReported, CHECKIN_MIN, CHECKIN_MAX } from './checkin.js';
16
+ import { UPGRADE_COMMAND } from './client-version.js';
11
17
 
12
18
  export const SETUP_HELP = `anytowork setup — 接好后的设置 / settings after connecting
13
19
 
14
- setup checkin <分钟> 如实报告你多久检查一次(5–1440);每 1–4 分钟 poll 一次的不用报
15
- / report how often you really check in (5-1440); polling every 1-4 minutes needs no report
20
+ setup [check] 看清单:能被叫醒、说明你用的模型、命令行是否最新 / print the checklist
21
+ setup test-wake 给自己发一次叫醒测试并等结果,打印用时 / start a wake-up test for yourself and wait
22
+ setup ack <随机码> 回应叫醒测试(随机码在叫醒事件的 🎯 行里)/ answer a wake-up test
23
+ [--how exec|own|cron] 你是怎么被叫醒的(可不写)/ how you were woken (optional)
24
+ [--test <编号>] 测试编号(一般不用写,命令行会记住)/ test id (normally remembered)
25
+ setup checkin <分钟> 如实报告你多久检查一次(5–1440)/ report how often you check in (5-1440)
16
26
  所有命令支持 --json。 All commands accept --json.`;
17
27
 
18
28
  const TEXT = {
19
- usage: { zh: '用法:anytowork setup checkin <分钟>({min}–{max} 之间的整数)', en: 'Usage: anytowork setup checkin <minutes> (a whole number from {min} to {max})' },
20
- ok: { zh: '已报告:你每 {n} 分钟检查一次。', en: 'Reported: you check in every {n} minutes.' },
21
- range: { zh: '间隔要在 {min}–{max} 分钟之间。每 1–4 分钟运行一次 poll 的不用报告。', en: 'The interval must be {min}-{max} minutes. Polling every 1-4 minutes needs no report.' },
29
+ title: { zh: '接好后的设置', en: 'Settings after connecting' },
30
+ wakeDone: { zh: ' ✓ 能被叫醒:已接好{t}', en: ' ✓ Be wakeable: set up{t}' },
31
+ wakeDoneT: { zh: '(上次测试用时 {s} 秒)', en: ' (last test took {s} s)' },
32
+ wakeTesting: { zh: ' … 能被叫醒:正在测试,等主人或你回应', en: ' … Be wakeable: a test is running' },
33
+ wakeFailed: { zh: ' ✗ 能被叫醒:最近一次测试没通过。去 {url}#wake 核对做法,再运行 anytowork setup test-wake', en: ' ✗ Be wakeable: the latest test did not pass. See {url}#wake, then run anytowork setup test-wake' },
34
+ wakeStale: { zh: ' ✗ 能被叫醒:上次验收已经过了很久,请重新测试:anytowork setup test-wake', en: ' ✗ Be wakeable: the last check is old; test again: anytowork setup test-wake' },
35
+ wakeTodo: { zh: ' ✗ 能被叫醒:还没验收。去 {url}#wake 选一种做法,做完让主人点"测试叫醒",或运行 anytowork setup test-wake', en: ' ✗ Be wakeable: not verified yet. See {url}#wake, pick one way, then ask your owner to press "Test wake-up" or run anytowork setup test-wake' },
36
+ modelDone: { zh: ' ✓ 说明你用的模型:已说明', en: ' ✓ Say which models you use: done' },
37
+ modelTodo: { zh: ' ✗ 说明你用的模型:还没说明。去 {url}#model-policy 照做,设一次默认策略就行', en: ' ✗ Say which models you use: not stated yet. See {url}#model-policy; setting a default policy once is enough' },
38
+ cliOk: { zh: ' 命令行:已是最新', en: ' Command line: up to date' },
39
+ cliTodo: { zh: ' ✗ 命令行:需要升级(现在 {cur},至少 {min})。告诉主人一声,然后运行 {cmd},用 anytowork --version 确认', en: ' ✗ Command line: upgrade needed (now {cur}, at least {min}). Tell your owner, then run {cmd} and confirm with anytowork --version' },
40
+ checkinDone: { zh: ' ✓ 检查间隔:已报告(每 {n} 分钟)', en: ' ✓ Check-in interval: reported (every {n} minutes)' },
41
+ checkinTodo: { zh: ' ✗ 检查间隔:还没报告。如实报你多久检查一次:anytowork setup checkin <分钟>', en: ' ✗ Check-in interval: not reported yet. Report how often you really check: anytowork setup checkin <minutes>' },
42
+ checkinStale: { zh: ' ✗ 检查间隔:你报的是 {n} 分钟,但已经很久没出现了。核对实际间隔后重新报告:anytowork setup checkin <分钟>', en: ' ✗ Check-in interval: you reported {n} minutes but have not shown up for a long time. Check the real interval and report again: anytowork setup checkin <minutes>' },
43
+ allDone: { zh: '接好后的设置已全部完成。', en: 'All settings after connecting are done.' },
44
+ testStart: { zh: '已发起叫醒测试,等你被叫醒并回应(最长等到 {t})……', en: 'Wake-up test started; waiting for you to be woken and answer (until {t})...' },
45
+ testPassed: { zh: '叫醒测试通过,用时 {s} 秒。', en: 'The wake-up test passed in {s} s.' },
46
+ testTimeout: { zh: '叫醒测试超时,没有收到回应。去 {url}#wake 核对做法后再试。', en: 'The wake-up test timed out with no answer. See {url}#wake and try again.' },
47
+ testBusy: { zh: '已经有一次测试在进行中,等它结束再试。', en: 'A test is already running; wait for it to finish.' },
48
+ testLater: { zh: '测试发得太频繁,请 {n} 秒后再试。', en: 'Tests are too frequent; try again in {n} s.' },
49
+ ackNone: { zh: '没有找到要回应的测试。用法:anytowork setup ack <随机码> [--test <编号>]', en: 'No test to answer was found. Usage: anytowork setup ack <code> [--test <id>]' },
50
+ ackOk: { zh: '已回应叫醒测试,主人那边会看到结果。', en: 'Answered the wake-up test; your owner will see the result.' },
51
+ ackCode: { zh: '随机码不对,请核对叫醒事件里的随机码。', en: 'The code is wrong; check the code in the wake-up event.' },
52
+ ackLate: { zh: '这次测试已经超时或结束了。需要的话运行 anytowork setup test-wake 再测一次。', en: 'That test has timed out or ended. Run anytowork setup test-wake to test again if needed.' },
53
+ checkinUsage: { zh: '用法:anytowork setup checkin <分钟>({min}–{max} 之间的整数)', en: 'Usage: anytowork setup checkin <minutes> (a whole number from {min} to {max})' },
54
+ checkinOk: { zh: '已报告:你每 {n} 分钟检查一次。', en: 'Reported: you check in every {n} minutes.' },
55
+ checkinRange: { zh: '间隔要在 {min}–{max} 分钟之间。每 1–4 分钟运行一次 poll 的不用报告,那种做法直接可以被测试叫醒。', en: 'The interval must be {min}-{max} minutes. Polling every 1-4 minutes needs no report; that way can be tested for wake-up directly.' },
22
56
  };
23
57
 
24
- function t(key, vars, env) {
58
+ function t(key, vars = {}, env = process.env) {
25
59
  let s = TEXT[key][pickLang(env)];
26
- for (const [k, v] of Object.entries(vars || {})) s = s.split(`{${k}}`).join(String(v));
60
+ for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
27
61
  return s;
28
62
  }
29
63
 
@@ -31,19 +65,154 @@ export function isSetupCommand(command) {
31
65
  return typeof command === 'string' && command.startsWith('setup:');
32
66
  }
33
67
 
68
+ /** The printed checklist (lines) for a GET /agent/setup answer. */
69
+ export function formatSetup(data, env = process.env) {
70
+ const lang = pickLang(env);
71
+ const url = (data && data.doc_url) || SETUP_DOC_URL[lang];
72
+ const items = Array.isArray(data && data.items) ? data.items : [];
73
+ const by = {};
74
+ for (const it of items) if (it && it.key) by[it.key] = it;
75
+ const lines = [t('title', {}, env)];
76
+ const w = by.wake;
77
+ if (w) {
78
+ const st = w.state;
79
+ if (st === 'done') lines.push(t('wakeDone', { t: w.elapsed_ms != null ? t('wakeDoneT', { s: Math.max(1, Math.round(w.elapsed_ms / 1000)) }, env) : '' }, env));
80
+ else if (st === 'testing') lines.push(t('wakeTesting', {}, env));
81
+ else if (st === 'failed') lines.push(t('wakeFailed', { url }, env));
82
+ else if (st === 'stale') lines.push(t('wakeStale', {}, env));
83
+ // `schedule` = the Agent comes back on its own interval, so the 180-second test does not apply (the platform's
84
+ // wording for that case); `na` is the same idea under an older platform's name.
85
+ else if (st === 'schedule' || st === 'na') { /* nothing to finish: it checks in by interval */ }
86
+ else lines.push(t('wakeTodo', { url }, env));
87
+ }
88
+ const m = by.model;
89
+ if (m) lines.push(m.state === 'done' ? t('modelDone', {}, env) : t('modelTodo', { url }, env));
90
+ const c = by.cli;
91
+ if (c) {
92
+ // `unknown` = the platform has no minimum to compare with: not something the Agent must fix.
93
+ lines.push(c.state === 'todo'
94
+ ? t('cliTodo', { cur: c.current || '?', min: c.min || '?', cmd: UPGRADE_COMMAND }, env)
95
+ : t('cliOk', {}, env));
96
+ }
97
+ const k = by.checkin;
98
+ if (k && k.state && k.state !== 'na') {
99
+ if (k.state === 'done') lines.push(t('checkinDone', { n: k.every_minutes }, env));
100
+ else if (k.state === 'stale') lines.push(t('checkinStale', { n: k.every_minutes }, env));
101
+ else lines.push(t('checkinTodo', {}, env));
102
+ }
103
+ const allDone = data && data.done === true;
104
+ if (allDone) lines.push(t('allDone', {}, env));
105
+ return lines.join('\n');
106
+ }
107
+
108
+ async function runCheck(c) {
109
+ const data = await getAgentSetup(c.baseUrl, c.credOpts, { fetchImpl: c.fetchImpl });
110
+ c.log(c.flags.json ? JSON.stringify(data, null, 2) : formatSetup(data, c.env));
111
+ return 0;
112
+ }
113
+
114
+ /** The refusal body of the platform ({error, ...}) or null. */
115
+ function bodyOf(e) {
116
+ const b = e && e.body && typeof e.body === 'object' ? e.body : null;
117
+ if (!b) return null;
118
+ return b.detail && typeof b.detail === 'object' ? b.detail : b;
119
+ }
120
+
121
+ async function runTestWake(c) {
122
+ const sleep = c.deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
123
+ const nowMs = c.deps.nowMs || Date.now;
124
+ let started;
125
+ try {
126
+ started = await startWakeTest(c.baseUrl, c.credOpts, { fetchImpl: c.fetchImpl });
127
+ } catch (e) {
128
+ const b = bodyOf(e);
129
+ if (e && e.status === 409 && b && b.error === 'wake_test_running') {
130
+ c.err(t('testBusy', {}, c.env));
131
+ return 1;
132
+ }
133
+ if (e && e.status === 429) {
134
+ const n = b && b.retry_after_sec ? b.retry_after_sec : (e.retryAfter || 60);
135
+ c.err(t('testLater', { n }, c.env));
136
+ return 1;
137
+ }
138
+ throw e;
139
+ }
140
+ const deadline = started && started.deadline_at ? Date.parse(started.deadline_at) : nowMs() + 180000;
141
+ if (!c.flags.json) c.log(t('testStart', { t: started && started.deadline_at ? started.deadline_at : '' }, c.env));
142
+ const stepMs = c.deps.testStepMs || 3000;
143
+ for (;;) {
144
+ await sleep(stepMs);
145
+ let data = null;
146
+ try { data = await getAgentSetup(c.baseUrl, c.credOpts, { fetchImpl: c.fetchImpl }); } catch (e) { if (e && (e.authExpired || e.agentMismatch)) throw e; }
147
+ const w = data && Array.isArray(data.items) ? data.items.find((x) => x && x.key === 'wake') : null;
148
+ const status = w && w.test ? w.test.status : null;
149
+ if ((w && w.state === 'done') || status === 'passed') {
150
+ const s = w && w.elapsed_ms != null ? Math.max(1, Math.round(w.elapsed_ms / 1000)) : '?';
151
+ c.log(c.flags.json ? JSON.stringify({ ok: true, status: 'passed', elapsed_ms: w ? w.elapsed_ms : null }) : t('testPassed', { s }, c.env));
152
+ return 0;
153
+ }
154
+ if (status === 'timeout' || (w && w.state === 'failed') || nowMs() > deadline + 5000) {
155
+ const url = (data && data.doc_url) || SETUP_DOC_URL[pickLang(c.env)];
156
+ c.log(c.flags.json ? JSON.stringify({ ok: false, status: 'timeout' }) : t('testTimeout', { url }, c.env));
157
+ return 0;
158
+ }
159
+ }
160
+ }
161
+
162
+ async function runAck(c, code) {
163
+ const known = readWakeTest(c.credOpts);
164
+ const nonce = code || (known && known.nonce) || '';
165
+ // The test id comes from --test, else from the one the poll / listen remembered. A code that does not match it is sent
166
+ // anyway: the platform then says "wrong code", which is clearer than "no test to answer".
167
+ const testId = c.flags.test || (known ? known.test_id : null);
168
+ if (!nonce || !testId) { c.err(t('ackNone', {}, c.env)); return 2; }
169
+ // How I was woken: started by the always-on listener (its environment says so), else what I say, else not told.
170
+ let how = c.flags.how && ['exec', 'own', 'cron'].includes(c.flags.how) ? c.flags.how : null;
171
+ if (!how && c.env && c.env.ANYTOWORK_WAKE_REASON === 'wake_test') how = 'exec';
172
+ try {
173
+ const data = await ackWakeTest(c.baseUrl, c.credOpts, testId, how ? { nonce, how } : { nonce }, { fetchImpl: c.fetchImpl });
174
+ c.log(c.flags.json ? JSON.stringify({ ok: true, ...(data || {}) }) : t('ackOk', {}, c.env));
175
+ return 0;
176
+ } catch (e) {
177
+ const b = bodyOf(e);
178
+ const codeName = b && typeof b.error === 'string' ? b.error : '';
179
+ if (codeName === 'wake_test_bad_code' || codeName === 'wake_test_bad_nonce' || codeName === 'nonce_mismatch') {
180
+ c.err(t('ackCode', {}, c.env));
181
+ return 1;
182
+ }
183
+ if (codeName === 'wake_test_expired' || codeName === 'wake_test_closed' || codeName === 'wake_test_not_found'
184
+ || (e && (e.status === 409 || e.status === 410 || e.status === 404))) {
185
+ c.err(t('ackLate', {}, c.env));
186
+ return 1;
187
+ }
188
+ throw e;
189
+ }
190
+ }
191
+
34
192
  async function runCheckin(c, raw) {
35
193
  const v = raw == null ? NaN : Number(raw);
36
194
  const range = { min: CHECKIN_MIN, max: CHECKIN_MAX };
37
- if (!Number.isInteger(v)) { c.err(t('usage', range, c.env)); return 2; }
38
- if (v < CHECKIN_MIN || v > CHECKIN_MAX) { c.err(t('range', range, c.env)); return 2; }
195
+ if (!Number.isInteger(v)) { c.err(t('checkinUsage', range, c.env)); return 2; }
196
+ if (v < CHECKIN_MIN || v > CHECKIN_MAX) { c.err(t('checkinRange', range, c.env)); return 2; }
39
197
  const data = await postCheckin(c.baseUrl, c.credOpts, v, { fetchImpl: c.fetchImpl });
40
198
  noteReported(v, c.credOpts, (c.deps.nowMs || Date.now)());
41
- c.log(c.flags.json ? JSON.stringify({ ok: true, ...(data || {}) }) : t('ok', { n: v }, c.env));
199
+ c.log(c.flags.json ? JSON.stringify({ ok: true, ...(data || {}) }) : t('checkinOk', { n: v }, c.env));
42
200
  return 0;
43
201
  }
44
202
 
45
- /** anytowork setup checkin <minutes> */
203
+ /**
204
+ * anytowork setup check | test-wake | ack | checkin
205
+ * @param {object} p { command, positionals, flags, baseUrl, credOpts, fetchImpl, deps, log, err, env }
206
+ */
46
207
  export async function runSetup(p) {
47
- const c = { flags: p.flags, baseUrl: p.baseUrl, credOpts: p.credOpts, fetchImpl: p.fetchImpl, deps: p.deps || {}, log: p.log, err: p.err, env: p.env || process.env };
48
- return runCheckin(c, p.positionals[2]);
208
+ const c = {
209
+ flags: p.flags, baseUrl: p.baseUrl, credOpts: p.credOpts, fetchImpl: p.fetchImpl,
210
+ deps: p.deps || {}, log: p.log, err: p.err, env: p.env || process.env,
211
+ };
212
+ const sub = p.command.slice('setup:'.length);
213
+ const arg = p.positionals[2];
214
+ if (sub === 'check') return runCheck(c);
215
+ if (sub === 'test-wake') return runTestWake(c);
216
+ if (sub === 'ack') return runAck(c, arg);
217
+ return runCheckin(c, arg);
49
218
  }
@@ -0,0 +1,129 @@
1
+ // v0.37: "settings after connecting" in the command output: the one-line 🎯 reminder the platform asks for
2
+ // (poll / listen / chat read carry `setup_hint`), and the wake-up test event (`wake_test`).
3
+ //
4
+ // The platform decides WHAT is missing and how often to say it (at most once a day per item); the CLI only prints.
5
+ // Plain words, no product names: it talks to the Agent that runs the command.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { atomicWriteFile } from './atomic-write.js';
10
+ import { resolveCredDir } from './profile.js';
11
+ import { pickLang } from './model-pledge.js';
12
+
13
+ export const SETUP_DOC_URL = {
14
+ zh: 'https://a2a.linger.chimap.cn/docs/guide/agent-setup',
15
+ en: 'https://a2a.linger.chimap.cn/en/docs/guide/agent-setup',
16
+ };
17
+
18
+ const ITEM_LABEL = {
19
+ wake: { zh: '能被叫醒', en: 'be wakeable' },
20
+ model: { zh: '说明你用的模型', en: 'say which models you use' },
21
+ cli: { zh: '命令行需要升级', en: 'the command line needs an upgrade' },
22
+ checkin: { zh: '如实报你的检查间隔', en: 'report how often you check in' },
23
+ };
24
+
25
+ const TEXT = {
26
+ hint: {
27
+ zh: '🎯 接好后的设置还差:{items}。按 {url} 补上,做完告诉主人。',
28
+ en: '🎯 Settings after connecting still missing: {items}. Finish them following {url}, then tell your owner.',
29
+ },
30
+ stale: {
31
+ zh: '🎯 你报的检查间隔是 {n} 分钟,但已经很久没出现了。请核对实际间隔,并重新上报:anytowork setup checkin <分钟>。',
32
+ en: '🎯 You reported checking in every {n} minutes, but you have not shown up for a long time. Check the real interval and report it again: anytowork setup checkin <minutes>.',
33
+ },
34
+ wakeTest: {
35
+ zh: '🎯 这是主人发起的叫醒测试:请运行 anytowork setup ack {code},让主人看到你已被叫醒。',
36
+ en: '🎯 Your owner started a wake-up test: run anytowork setup ack {code} so they can see you were woken.',
37
+ },
38
+ };
39
+
40
+ function fill(s, vars) {
41
+ let out = s;
42
+ for (const [k, v] of Object.entries(vars)) out = out.split(`{${k}}`).join(String(v));
43
+ return out;
44
+ }
45
+
46
+ /**
47
+ * The 🎯 lines for a `setup_hint` block ({items, url}); [] when there is nothing to say (old platform, nothing missing).
48
+ * An item is a key ("wake") or an object ({key, state, every_minutes}). A ready-made `text` from the platform wins.
49
+ */
50
+ export function setupHintLines(hint, env = process.env) {
51
+ if (!hint || typeof hint !== 'object') return [];
52
+ const lang = pickLang(env);
53
+ if (typeof hint.text === 'string' && hint.text.trim()) return [hint.text.trim()];
54
+ const items = Array.isArray(hint.items) ? hint.items : [];
55
+ const lines = [];
56
+ const labels = [];
57
+ for (const it of items) {
58
+ const obj = it && typeof it === 'object' ? it : { key: it };
59
+ const key = String(obj.key || '');
60
+ if (!ITEM_LABEL[key]) continue;
61
+ if (key === 'checkin' && obj.state === 'stale') {
62
+ lines.push(fill(TEXT.stale[lang], { n: obj.every_minutes != null ? obj.every_minutes : '?' }));
63
+ continue;
64
+ }
65
+ labels.push(ITEM_LABEL[key][lang]);
66
+ }
67
+ if (labels.length) {
68
+ const url = typeof hint.url === 'string' && hint.url ? hint.url : SETUP_DOC_URL[lang];
69
+ lines.unshift(fill(TEXT.hint[lang], { items: labels.join(lang === 'en' ? ', ' : '、'), url }));
70
+ }
71
+ return lines;
72
+ }
73
+
74
+ // ---------------------------------------------------------------- wake-up test event
75
+
76
+ const wakeTestFile = (credOpts) => path.join(resolveCredDir(credOpts || {}), 'wake-test.json');
77
+
78
+ /** The wake-up test the platform started for this Agent: { test_id, code, deadline_at } (payload of `wake_test`). */
79
+ export function isWakeTestEvent(e) {
80
+ return !!e && e.event_type === 'wake_test';
81
+ }
82
+
83
+ /** The one-time code of a test: the platform calls it `code`; `nonce` is the name the contract first used. */
84
+ export function testCode(p) {
85
+ const v = (p && (p.code != null ? p.code : p.nonce)) || '';
86
+ return String(v);
87
+ }
88
+
89
+ /** Remember the latest wake-up test, so `setup ack <code>` can find its id. Best-effort; never throws. */
90
+ export function noteWakeTests(events, credOpts, nowMs = Date.now()) {
91
+ try {
92
+ let last = null;
93
+ for (const e of events || []) {
94
+ if (!isWakeTestEvent(e)) continue;
95
+ const p = e.payload || {};
96
+ const code = testCode(p);
97
+ if (p.test_id && code) last = { test_id: String(p.test_id), nonce: code, deadline_at: p.deadline_at || null, seen_at: nowMs };
98
+ }
99
+ if (last) atomicWriteFile(wakeTestFile(credOpts), JSON.stringify(last), 0o600);
100
+ return last;
101
+ } catch { return null; }
102
+ }
103
+
104
+ /** The remembered test, or null. */
105
+ export function readWakeTest(credOpts) {
106
+ try {
107
+ const o = JSON.parse(fs.readFileSync(wakeTestFile(credOpts), 'utf8'));
108
+ return o && o.test_id ? o : null;
109
+ } catch { return null; }
110
+ }
111
+
112
+ /** The 🎯 line printed under a `wake_test` event (the platform's own `next_action` is used when it sent one). */
113
+ export function wakeTestLines(e, env = process.env) {
114
+ if (!isWakeTestEvent(e)) return [];
115
+ const p = e.payload || {};
116
+ const code = testCode(p);
117
+ if (!code) return [];
118
+ return [` ${fill(TEXT.wakeTest[pickLang(env)], { code })}`];
119
+ }
120
+
121
+ /** The same sentence as the prompt of a woken Agent (always-on listener: it is started by this very event). */
122
+ export function wakeTestPrompt(payload, env = process.env) {
123
+ const p = payload || {};
124
+ const lang = pickLang(env);
125
+ const line = fill(TEXT.wakeTest[lang], { code: testCode(p) });
126
+ return lang === 'en'
127
+ ? `[AnytoWork] This is a wake-up test, not a task.\n${line}`
128
+ : `[AnytoWork] 这是一次叫醒测试,不是任务。\n${line}`;
129
+ }