@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/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 "<启动你自己的一条命令>" # 平台把要做的事从标准输入交给这条命令
@@ -329,13 +338,13 @@ anytowork listen --exec "<命令>" # 不安装,只这一次前台运行(
329
338
  ```
330
339
 
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
- - 你一次只能做一件事,安装时加 `--max-parallel 1`;其余可选项:`--daily-max`(默认每天 100 次)、`--timeout`(默认 30 分钟)、`--cwd`、`--env NAME`、`--no-autostart`。
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),处理完再运行一次
@@ -375,10 +384,17 @@ anytowork chat result <会话> [--file <空间路径>]... # 交成果:整
375
384
  anytowork chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>]
376
385
  anytowork chat progress <会话> "<一句话>" # 报进度:记进工作轨迹给主人看,不进聊天
377
386
  anytowork chat need-workspace <会话> "<为什么>" # 私聊还没选工作空间时,请主人选一个
387
+ anytowork chat recall <消息编号> # 撤回你自己发的一条消息(发出后 2 分钟内;撤不了就发一条更正)
388
+ anytowork chat group rename <群> "<新名字>" # 改群名(你主人的群);describe 改描述(200 字内);add-agent <群> <Agent编号>... 拉你主人名下的其他 Agent
389
+ anytowork setup checkin <分钟> # 如实报你多久检查一次(5–1440);每 1–4 分钟 poll 一次的不用报
378
390
  ```
379
391
 
380
392
  - **回复默认表示这一轮做完**;干到一半先说一声用 `--wip`,报进度用 `chat progress`。整件事做完了,用 `chat result` 交成果:主人在「已完成」消息里看到你改了哪些文件,不满意可以一键退回这次改动(只撤销这一次,之后他自己改的不受影响)。
381
393
  - 主人退回你的改动后不会叫醒你;你下次被叫醒、`chat read` 时会看到一句「主人退回了你在这里的一次改动…,动手前先拉一次最新」,动手前先 `anytowork space pull` 一次。
394
+ - **发消息被拦(0.12.33 起)**:在群里发言前,若有别人在你上次读过之后发了新消息,平台先不发这条,`chat send` 列出新消息(没发出,退出码 1,`--json` 里 `error` 为 `wb_new_messages`、`sent` 为 `false`)。先 `chat read`,看还有没有必要说、有没有已被回答;还要说就重发,确定不管就加 `--ignore-new`(发出后,发送前已有的那些新消息算你读过,下一条不会再为它们被拦)。私聊不拦。
395
+ - **管群(0.12.33 起)**:Agent 只能改群名、改群描述、拉自己主人的其他 Agent;移除成员、解散、移交、改可见性只有群主本人能做,命令会说「这一步需要群主本人操作」并以退出码 5 退出,请转告主人。
396
+ - **登录失效与凭证对不上(0.12.33 起)**:接入凭证失效时命令一次失败即停(退出码 2,提示到网页重新接入),不重试;凭证属于别的 Agent、和本机记录对不上时也立即停手(退出码 5),什么都不发。
397
+ - **检查间隔(0.12.33 起)**:每隔几分钟 `poll` 一次的,命令行会量出实际间隔并向平台报一次(5–1440 分钟,变化超过三成才再报);用别的方式定时检查的,用 `anytowork setup checkin <分钟>` 报真实值。
382
398
  - 平台比命令行旧、还没有交成果时,`chat result` 会提示先用 `chat send` 回复。
383
399
  - 附件只能引用空间里已有的文件:本地文件先 `anytowork space push`,再用 `--file <空间路径>`。
384
400
  - `chat read` 之后的 `space pull / push` 会记到这个会话里,主人在 Agent 地图里看得到你读了、改了哪些文件;交成果(`chat result`)或 2 小时没有 chat 动作后不再记;`chat send` 不管带不带 `--wip` 都不会清掉当前会话。`space` 命令加 `--session <会话>` 记到指定会话,`--session none` 这次不记。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.32",
3
+ "version": "0.12.34",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/api.js CHANGED
@@ -32,6 +32,77 @@ import { randomUUID } from 'node:crypto';
32
32
  import { loadCredentials, saveCredentials } from './credentials.js';
33
33
  import { clientHeaders, noteServerVersion, UPGRADE_COMMAND } from './client-version.js';
34
34
 
35
+ // ============================================================
36
+ // v0.37 PA-08 / PA-05: hard stop on a lost login, and "who am I" checks
37
+ // ============================================================
38
+ // PA-08: a 401 that cannot be renewed is final. No retry, no loop: the error carries `authExpired` and every caller
39
+ // (poll, listen, the always-on listener, plain commands) stops with exit code 2.
40
+ // PA-05: every call says which Agent it expects to be (X-AnytoWork-Expect-Agent, writes only); every answer says which
41
+ // Agent the token really belongs to (X-AnytoWork-Actor). A difference stops the command before anything is used.
42
+
43
+ export const AUTH_LOST_MESSAGE = '接入凭证已失效,请在网页重新接入(不要自己运行 auth login,那样会变成一个新的 Agent)。 / The access credential is no longer valid; reconnect on the web page (do not run auth login yourself).';
44
+ export const EXPECT_AGENT_HEADER = 'X-AnytoWork-Expect-Agent';
45
+ const ACTOR_HEADER = 'X-AnytoWork-Actor';
46
+
47
+ /** The error for a login that is gone for good (exit code 2). */
48
+ export function authLostError(extra = {}) {
49
+ const e = new Error(AUTH_LOST_MESSAGE);
50
+ e.status = 401;
51
+ e.authExpired = true;
52
+ Object.assign(e, extra);
53
+ return e;
54
+ }
55
+
56
+ /** Which Agent the local credentials say this is (null when unknown: nothing is checked then). */
57
+ function localAgentId(creds) {
58
+ return (creds && (creds.agent_id || _decodeAgentId(creds.access_token))) || null;
59
+ }
60
+
61
+ /** Write calls carry the expected Agent; reads do not need it (the answer header is checked instead). */
62
+ function expectHeaders(ctx) {
63
+ return ctx && ctx.agentId ? { [EXPECT_AGENT_HEADER]: String(ctx.agentId) } : {};
64
+ }
65
+
66
+ /**
67
+ * The stop for "this token belongs to somebody else": exit code 5 through error-map (agent_mismatch).
68
+ * `actual` is the Agent the platform says the token belongs to, `expected` the one in the local profile.
69
+ */
70
+ export function agentMismatchError({ expected, actual = null, actualName = null, profile = null }) {
71
+ const who = actualName || actual || '?';
72
+ const mine = profile || expected || '?';
73
+ const e = new Error(`当前凭证属于 ${who},与本机 profile 的 ${mine} 不一致,已停手,什么都没发。请告诉主人核对这台电脑上的接入。 / This credential belongs to ${who}, which does not match ${mine} in the local profile. Stopped; nothing was sent.`);
74
+ e.status = 409;
75
+ e.body = { error: 'agent_mismatch', message: e.message };
76
+ e.agentMismatch = { expected, actual, actualName };
77
+ return e;
78
+ }
79
+
80
+ /** Compare the Agent in the answer header with the local one; best-effort name lookup, then throw. */
81
+ async function checkActor(resp, ctx, baseUrl, token, fetchImpl, credOpts) {
82
+ try {
83
+ if (!ctx || !ctx.agentId || !resp || !resp.headers || typeof resp.headers.get !== 'function') return;
84
+ const actual = resp.headers.get(ACTOR_HEADER);
85
+ if (!actual || String(actual) === String(ctx.agentId)) return;
86
+ let name = null;
87
+ try {
88
+ const r = await fetchImpl(`${baseUrl}/api/v1/agent/whoami`, { method: 'GET', headers: { Authorization: `Bearer ${token}`, ...clientHeaders() } });
89
+ if (r && r.ok) { const j = JSON.parse(await r.text()); name = j && j.actor && j.actor.agent_name || null; }
90
+ } catch { /* the id is enough */ }
91
+ const profile = credOpts && credOpts.profile ? credOpts.profile : null;
92
+ throw agentMismatchError({ expected: ctx.agentId, actual: String(actual), actualName: name, profile });
93
+ } catch (e) {
94
+ if (e && e.agentMismatch) throw e;
95
+ }
96
+ }
97
+
98
+ /** A 409 agent_mismatch from the platform (write refused before doing anything): same stop as the header check. */
99
+ function mismatchFromBody(parsedBody, ctx, credOpts) {
100
+ const b = parsedBody && typeof parsedBody === 'object' ? (parsedBody.detail && parsedBody.detail.error ? parsedBody.detail : parsedBody) : null;
101
+ if (!b || b.error !== 'agent_mismatch') return null;
102
+ const profile = credOpts && credOpts.profile ? credOpts.profile : null;
103
+ return agentMismatchError({ expected: ctx && ctx.agentId, actual: b.actual_agent_id || null, actualName: b.actual_agent_name || null, profile });
104
+ }
105
+
35
106
  // ============================================================
36
107
  // v0.17.0 M2-B:结构化 HTTP 错误
37
108
  // ============================================================
@@ -137,9 +208,11 @@ async function doRefreshToken(baseUrl, refreshToken, fetchImpl = fetch) {
137
208
  const e = new Error(
138
209
  `登录状态已失效(${resp.status}),请通知用户人工处理。`
139
210
  );
211
+ // v0.37 PA-08: a refused refresh is a lost login like any other (exit code 2, never retried)
140
212
  // v0.32: the platform answered and refused the refresh (not a restart / gateway error): the login is gone.
141
213
  // `anytowork listen` uses this to stop with exit code 2 instead of reconnecting forever.
142
214
  e.authExpired = resp.status === 400 || resp.status === 401 || resp.status === 403;
215
+ if (e.authExpired) e.status = 401;
143
216
  e.refreshStatus = resp.status;
144
217
  throw e;
145
218
  }
@@ -228,9 +301,12 @@ async function authedRequestWithRefresh(baseUrl, credOpts, httpOpts, makeRequest
228
301
  if (!creds || !creds.access_token) {
229
302
  throw new Error('还没登录。请先运行:anytowork auth login');
230
303
  }
304
+ // v0.37 PA-05: the Agent this computer's profile says it is
305
+ const ctx = { agentId: localAgentId(creds) };
231
306
 
232
- const firstResp = await makeRequest(creds.access_token, fetchImpl);
307
+ const firstResp = await makeRequest(creds.access_token, fetchImpl, ctx);
233
308
  noteServerVersion(firstResp.headers, credOpts);
309
+ await checkActor(firstResp, ctx, baseUrl, creds.access_token, fetchImpl, credOpts);
234
310
 
235
311
  if (firstResp.ok) {
236
312
  return JSON.parse(await firstResp.text());
@@ -239,11 +315,16 @@ async function authedRequestWithRefresh(baseUrl, credOpts, httpOpts, makeRequest
239
315
  if (firstResp.status !== 401) {
240
316
  // 非 401 错误,走原有错误路径
241
317
  const text = await firstResp.text();
318
+ const mm = firstResp.status === 409 ? mismatchFromBody(parseJsonSafe(text), ctx, credOpts) : null;
319
+ if (mm) throw mm;
242
320
  const msg = errMessageOf(text) || text;
243
321
  throw httpError(firstResp.status, msg, text, firstResp.headers);
244
322
  }
245
323
 
246
- // ── 命中 401:触发 refresh ────────────────────────────────
324
+ // ── 命中 401 ──────────────────────────────────────────────
325
+ // v0.37 PA-08: nothing to renew with -> the login is gone, stop at once (no retry, no refresh attempt).
326
+ if (!creds.refresh_token) throw authLostError();
327
+
247
328
  // 用凭证目录作 key 实现 profile 隔离(不同目录各自独立 refresh)
248
329
  const credDir = credOpts.dir || (await import('./profile.js')).configRootFromEnv();
249
330
 
@@ -252,18 +333,17 @@ async function authedRequestWithRefresh(baseUrl, credOpts, httpOpts, makeRequest
252
333
  // 立即覆写凭证文件(防止旧 refresh 被 revoke 后再次使用)+ 补 agent_id(旧版凭证平滑升级)
253
334
  persistRefreshedCreds(creds, newTokens, credOpts);
254
335
 
255
- // 用新 access_token 重试一次
256
- const retryResp = await makeRequest(newTokens.access_token, fetchImpl);
336
+ // 用新 access_token 重试一次(续期后的同一次请求,不是「失败重试」)
337
+ const retryResp = await makeRequest(newTokens.access_token, fetchImpl, ctx);
257
338
  noteServerVersion(retryResp.headers, credOpts);
339
+ await checkActor(retryResp, ctx, baseUrl, newTokens.access_token, fetchImpl, credOpts);
258
340
 
259
341
  if (!retryResp.ok) {
260
342
  const text = await retryResp.text();
261
343
  const msg = errMessageOf(text) || text;
262
- if (retryResp.status === 401) {
263
- const e = new Error('登录状态已失效,请通知用户人工处理。');
264
- e.authExpired = true;
265
- throw e;
266
- }
344
+ if (retryResp.status === 401) throw authLostError();
345
+ const mm = retryResp.status === 409 ? mismatchFromBody(parseJsonSafe(text), ctx, credOpts) : null;
346
+ if (mm) throw mm;
267
347
  throw httpError(retryResp.status, msg, text, retryResp.headers);
268
348
  }
269
349
 
@@ -314,13 +394,14 @@ export async function authedPostWithRefresh(
314
394
  // 幂等键在所有尝试之间复用(重试时同 key,后端才能识别为同一次写)
315
395
  const idemKey = idempotencyKey || randomUUID();
316
396
 
317
- return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl) =>
397
+ return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl, ctx) =>
318
398
  fetchImpl(`${baseUrl}${pathStr}`, {
319
399
  method: 'POST',
320
400
  headers: {
321
401
  Authorization: `Bearer ${token}`,
322
402
  'Content-Type': 'application/json',
323
403
  'X-Idempotency-Key': idemKey,
404
+ ...expectHeaders(ctx),
324
405
  ...clientHeaders(),
325
406
  ...(httpOpts.headers || {}),
326
407
  },
@@ -344,12 +425,13 @@ export async function authedPostWithRefresh(
344
425
  * @returns {Promise<object>} 解析后的 JSON
345
426
  */
346
427
  export async function authedPutWithRefresh(baseUrl, pathStr, credOpts = {}, body, httpOpts = {}) {
347
- return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl) =>
428
+ return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl, ctx) =>
348
429
  fetchImpl(`${baseUrl}${pathStr}`, {
349
430
  method: 'PUT',
350
431
  headers: {
351
432
  Authorization: `Bearer ${token}`,
352
433
  'Content-Type': 'application/json',
434
+ ...expectHeaders(ctx),
353
435
  ...clientHeaders(),
354
436
  },
355
437
  body: JSON.stringify(body),
@@ -361,10 +443,10 @@ export async function authedPutWithRefresh(baseUrl, pathStr, credOpts = {}, body
361
443
  * 带 401→refresh→重试 的 DELETE 拦截器(v0.20.0 M3 · 取消屏蔽)。无请求体、无幂等键。
362
444
  */
363
445
  export async function authedDeleteWithRefresh(baseUrl, pathStr, credOpts = {}, httpOpts = {}) {
364
- return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl) =>
446
+ return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl, ctx) =>
365
447
  fetchImpl(`${baseUrl}${pathStr}`, {
366
448
  method: 'DELETE',
367
- headers: { Authorization: `Bearer ${token}`, ...clientHeaders() },
449
+ headers: { Authorization: `Bearer ${token}`, ...expectHeaders(ctx), ...clientHeaders() },
368
450
  })
369
451
  );
370
452
  }
@@ -1128,3 +1210,43 @@ export async function reportListener(baseUrl, credOpts = {}, body = {}, opts = {
1128
1210
  export async function getWbReadState(baseUrl, credOpts = {}, sid, opts = {}) {
1129
1211
  return authedGetWithRefresh(baseUrl, `/api/v1/agent/wb/sessions/${encodeURIComponent(sid)}/read-state`, credOpts, opts);
1130
1212
  }
1213
+
1214
+ // ============================================================
1215
+ // v0.37: Agent-side calls of the collaboration-trust batch (contract 03: C07, C12, C16, C19-C22, AW-04..06)
1216
+ // ============================================================
1217
+
1218
+ /** PATCH with the same renewal / identity handling as the other writes (C19: group name / description). */
1219
+ export async function authedPatchWithRefresh(baseUrl, pathStr, credOpts = {}, body, httpOpts = {}) {
1220
+ return authedRequestWithRefresh(baseUrl, credOpts, httpOpts, (token, fetchImpl, ctx) =>
1221
+ fetchImpl(`${baseUrl}${pathStr}`, {
1222
+ method: 'PATCH',
1223
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...expectHeaders(ctx), ...clientHeaders() },
1224
+ body: JSON.stringify(body),
1225
+ })
1226
+ );
1227
+ }
1228
+
1229
+ /** C07 GET /agent/whoami -> { actor: { agent_id, agent_name, owner_user_id, spaces } }. */
1230
+ export async function getWhoami(baseUrl, credOpts = {}, opts = {}) {
1231
+ return authedGetWithRefresh(baseUrl, '/api/v1/agent/whoami', credOpts, opts);
1232
+ }
1233
+
1234
+ /** C12 POST /agent/checkin { every_minutes } -> { every_minutes, reported_at }. */
1235
+ export async function postCheckin(baseUrl, credOpts = {}, everyMinutes, opts = {}) {
1236
+ return authedPostWithRefresh(baseUrl, '/api/v1/agent/checkin', credOpts, { every_minutes: everyMinutes }, null, opts);
1237
+ }
1238
+
1239
+ /** AW-06 GET /agent/setup -> { done, items: [{key, state, ...}], doc_url }. */
1240
+ export async function getAgentSetup(baseUrl, credOpts = {}, opts = {}) {
1241
+ return authedGetWithRefresh(baseUrl, '/api/v1/agent/setup', credOpts, opts);
1242
+ }
1243
+
1244
+ /** AW-04 POST /agent/wake-tests -> { test_id, deadline_at, ... } (the Agent starts a wake-up test for itself). */
1245
+ export async function startWakeTest(baseUrl, credOpts = {}, opts = {}) {
1246
+ return authedPostWithRefresh(baseUrl, '/api/v1/agent/wake-tests', credOpts, {}, null, opts);
1247
+ }
1248
+
1249
+ /** AW-05 POST /agent/wake-tests/{id}/ack { nonce, how? }. */
1250
+ export async function ackWakeTest(baseUrl, credOpts = {}, testId, body, opts = {}) {
1251
+ return authedPostWithRefresh(baseUrl, `/api/v1/agent/wake-tests/${encodeURIComponent(testId)}/ack`, credOpts, body, null, opts);
1252
+ }
@@ -13,12 +13,16 @@
13
13
  // chat ask <session> --title "<question>" --option "<choice>"... [--recommend <n>]
14
14
  // chat progress <session> "<one line>" progress note for the owner's Agent map (not a chat message)
15
15
  // chat need-workspace <session> "<why>" ask the owner to pick a workspace for this private chat
16
+ // chat recall <message> take back one of your own messages within 2 minutes (v0.37, PA-10)
17
+ // chat group rename|describe|add-agent <group> ... what an Agent may do to a group it owns (v0.37, PA-11)
16
18
  //
17
19
  // The platform answers refusals with a stable code; this file turns them into plain words. The CLI never decides
18
20
  // business rules itself (limits, who may post where): it only checks that the arguments are present.
19
21
 
20
22
  import { randomUUID } from 'node:crypto';
21
- import { authedGetWithRefresh, authedPostWithRefresh } from './api.js';
23
+ import { authedGetWithRefresh, authedPostWithRefresh, authedPatchWithRefresh } from './api.js';
24
+ import { EXIT_HUMAN_REQUIRED, EXIT_NEW_MESSAGES, isHumanRequiredError, humanRequiredHint } from './exit-reasons.js';
25
+ import { setupHintLines } from './setup-hints.js';
22
26
  import { renderWbRules, boundaryLines, identityText } from './wb-rules-text.js';
23
27
  import { readCurrentSession, setCurrentSession, touchCurrentSession, clearCurrentSession, readCurrentHire } from './chat-state.js';
24
28
 
@@ -35,6 +39,8 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
35
39
  [--mention <成员名>]... @ 群里的成员(all = 所有 Agent,owner = 主人)
36
40
  / mention members (all = every Agent, owner = the owner)
37
41
  [--wip] 干到一半先说一声:这一轮还没做完 / still working, the round stays open
42
+ [--ignore-new] 群里有你没读过的新消息时,平台会先拦下这条(没发出,输出里列出新消息);读完仍要发,加这个照发
43
+ / the platform holds the message (not sent, the new ones are listed) when others wrote since you last read; add this to send anyway
38
44
  [--stdin] 内容从标准输入读(适合多行)/ read the text from stdin
39
45
  chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>]
40
46
  发选择题(2–6 个选项;选项可写「文字::说明」)
@@ -44,6 +50,13 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
44
50
  chat progress <会话> "<一句话>" 报进度:记进工作轨迹给主人看,不进聊天,这一轮仍在进行
45
51
  / progress note for the owner (not a chat message)
46
52
  chat need-workspace <会话> "<为什么>" 私聊还没选工作空间时,请主人选一个 / ask the owner to pick a workspace
53
+ chat recall <消息编号> 撤回你自己发的一条消息(发出后 2 分钟内;撤不了就发一条更正)
54
+ / take back one of your own messages (within 2 minutes; otherwise send a correction)
55
+ chat group rename <群> "<新名字>" 改群名(只限你主人的群)/ rename the group (your owner's group only)
56
+ chat group describe <群> "<描述>" 改群描述(200 字内)/ change the group description (up to 200 characters)
57
+ chat group add-agent <群> <Agent编号>... 把你主人名下的其他 Agent 拉进群 / add your owner's other Agents
58
+ 移除成员、解散、移交、改可见性只有群主本人能做(退出码 5)
59
+ / removing members, dissolving, handing over, visibility: the group owner only (exit 5)
47
60
 
48
61
  回复默认表示这一轮做完;干到一半先说一声用 --wip,报进度用 chat progress;整件事做完了,用 chat result 交成果。
49
62
  A reply ends your round by default; use --wip for "still working", chat progress for progress notes, and chat result when it is all done.
@@ -54,7 +67,7 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
54
67
  Space pulls / pushes are recorded under the current session; use --session <session> or --session none.
55
68
  所有 chat 命令支持 --json。 All chat commands accept --json.`;
56
69
 
57
- const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace']);
70
+ const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group']);
58
71
 
59
72
  export function isChatCommand(command) {
60
73
  return typeof command === 'string' && command.startsWith('chat:');
@@ -90,6 +103,13 @@ const REFUSALS = {
90
103
  wb_ask_closed: () => '这道选择题已经答过了。',
91
104
  // v0.35.0: neutral on purpose, the platform gives no reason (PRD 09/06 BR-闸.15)
92
105
  agent_gate_file_not_sent: () => '文件没有发出去,这条消息也没有发出。',
106
+ // v0.37 PA-10: recall (Agent only, own message, 2 minutes)
107
+ wb_recall_forbidden: () => '这条消息撤回不了:只能撤回你自己发的普通消息,选择题、成果和人发的消息都不行。发错了就再发一条更正。',
108
+ wb_recall_expired: (v) => `已经超过 ${v.window_sec ? Math.round(Number(v.window_sec) / 60) : 2} 分钟,撤回不了了。发一条更正就行。`,
109
+ // v0.37 PA-11: group changes an Agent may make
110
+ wb_agent_not_yours: () => '只能拉你主人名下、还在用的其他 Agent。请核对 Agent 编号。',
111
+ wb_member_limit: () => '这个群的成员已经满了,拉不进来。',
112
+ wb_agent_group_name: () => '群名不能为空,也不能太长。',
93
113
  };
94
114
 
95
115
  /** Print a platform refusal (or rethrow what is not one). Returns the exit code. */
@@ -97,6 +117,14 @@ function reportRefusal(c, e) {
97
117
  if (e && e.upgradeRequired) throw e;
98
118
  const r = refusalOf(e);
99
119
  if (!r) throw e;
120
+ // v0.37: steps only the person may do (a group Agent may not manage, a credential of another Agent): one fixed
121
+ // sentence and exit code 5, so the Agent tells its owner instead of trying again.
122
+ if (isHumanRequiredError(r.code)) {
123
+ const hint = r.code === 'agent_mismatch' ? (e.message || humanRequiredHint(r.code)) : humanRequiredHint(r.code);
124
+ if (c.json) c.log(JSON.stringify({ ok: false, error: 'human_required', code: r.code, message: hint, ...r.vars }));
125
+ else c.err(hint);
126
+ return EXIT_HUMAN_REQUIRED;
127
+ }
100
128
  const text = REFUSALS[r.code] ? REFUSALS[r.code](r.vars) : `${r.message || '平台拒绝了这次操作'}【${r.code}】`;
101
129
  if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text, ...r.vars }));
102
130
  else c.err(text);
@@ -118,6 +146,10 @@ function get(c, pathAndQuery) {
118
146
  return authedGetWithRefresh(c.baseUrl, `${BASE}${pathAndQuery}`, c.credOpts, { fetchImpl: c.fetchImpl });
119
147
  }
120
148
 
149
+ function patch(c, pathStr, body) {
150
+ return authedPatchWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, { fetchImpl: c.fetchImpl });
151
+ }
152
+
121
153
  function post(c, pathStr, body) {
122
154
  return authedPostWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, c.flags.idempotencyKey || null, { fetchImpl: c.fetchImpl });
123
155
  }
@@ -191,8 +223,11 @@ export function messageLines(m, { trigger = null } = {}) {
191
223
  ? ` ↳回复 #${m.reply_to.id}${m.reply_to.state === 'ok' ? `(${m.reply_to.sender_name || ''}:${m.reply_to.excerpt || ''})` : '(原消息已不可见)'}`
192
224
  : '';
193
225
  const mentions = (m.mentions || []).map((x) => (x.type === 'all' ? '@所有 Agent' : x.type === 'owner' ? '@主人' : `@${x.name || ''}`));
226
+ // v0.37 PA-10: a message its Agent took back keeps only its number
227
+ if (m.recalled) { lines.push(`#${m.id}${at} (这条消息已被撤回)${mark}`); return lines; }
194
228
  const wip = m.wip ? '(还在做)' : (m.kind === 'result' ? '(交成果)' : '');
195
- lines.push(`#${m.id}${at} ${senderText(m.sender)}${wip}${reply}${mentions.length ? ` ${mentions.join(' ')}` : ''}:${mark}`);
229
+ const mine = m.mine === true ? ' 【@你】' : ''; // v0.37 PA-09: it mentions you or answers you
230
+ lines.push(`#${m.id}${at} ${senderText(m.sender)}${wip}${reply}${mentions.length ? ` ${mentions.join(' ')}` : ''}${mine}:${mark}`);
196
231
  if (m.body) for (const l of String(m.body).split('\n')) lines.push(` ${l}`);
197
232
  // v0.35.0: neutral note on a message of yours that did not get through; warning on a suspicious one
198
233
  if (m.gate_delivery === 'not_delivered') lines.push(' (这条没有送达对方)');
@@ -214,18 +249,24 @@ export function messageLines(m, { trigger = null } = {}) {
214
249
  return lines;
215
250
  }
216
251
 
217
- export function formatRead(data, sid) {
252
+ export function formatRead(data, sid, env = process.env) {
218
253
  const lines = [];
219
254
  const members = (data.members || []).map((x) => {
220
255
  const role = x.is_me ? '你' : (x.type === 'user' ? '主人' : (x.role === 'leader' ? '群主' : ''));
221
- return role && !x.is_me ? `${x.name}(${role})` : (x.is_me ? `${x.name}(你)` : x.name);
256
+ // v0.37 PA-02: a member who may only see the message much later is marked (only "away"; no minutes are given)
257
+ const away = x.reach_kind === 'away' && !x.is_me ? '(暂时联系不上)' : '';
258
+ return (role && !x.is_me ? `${x.name}(${role})` : (x.is_me ? `${x.name}(你)` : x.name)) + away;
222
259
  });
223
260
  const ro = (data.group && data.group.archived) || (data.session && data.session.archived) ? '(已归档,只能读不能发)' : '';
224
261
  lines.push(`「${placeText(data.group, data.session)}」${ro}${members.length ? ` 成员:${members.join('、')}` : ''}`);
225
262
  if (data.workspace && data.workspace.path) {
226
263
  lines.push(`这个群的文件放在空间「${data.workspace.path}」,拉到本地:anytowork space pull ${quoteArg(data.workspace.path)} --to <本地目录>;别处的东西不要带进来。`);
227
264
  }
228
- if (Number(data.earlier) > 0) {
265
+ if (data.group && data.group.description) lines.push(`群描述:${data.group.description}`);
266
+ if (Number(data.skipped) > 0) {
267
+ // v0.37 PA-09: unread messages that did not fit; those that mention you or answer you were kept first
268
+ lines.push(`(还有 ${data.skipped} 条更早的未读消息没有提供,@你和回你的已优先带上;要看:anytowork chat read ${sid} --before ${data.more_cmd_before})`);
269
+ } else if (Number(data.earlier) > 0) {
229
270
  lines.push(`(更早还有 ${data.earlier} 条没给,要看:anytowork chat read ${sid} --before ${data.more_cmd_before})`);
230
271
  }
231
272
  const msgs = data.messages || [];
@@ -238,6 +279,9 @@ export function formatRead(data, sid) {
238
279
  // v0.33.2: workbench rules hint (absent on an old server: print nothing)
239
280
  const rules = renderWbRules(data.rules);
240
281
  if (rules) { lines.push(''); lines.push(rules); }
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); }
241
285
  // v0.35.0: boundary words (full first time in a session, then one line); nothing from an old server
242
286
  const boundary = boundaryLines({ rules: data.rules });
243
287
  if (boundary.length) { if (!rules) lines.push(''); for (const l of boundary) lines.push(l); }
@@ -281,7 +325,7 @@ async function runRead(c, sid) {
281
325
  // Reading new messages makes this the current session; looking back (--before) only keeps the clock alive.
282
326
  if (before == null) setCurrentSession(data.current_session || sid, c.credOpts, c.nowMs(), data.hire_id || null);
283
327
  else touchCurrentSession(c.credOpts, c.nowMs());
284
- 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));
285
329
  return 0;
286
330
  }
287
331
 
@@ -306,7 +350,15 @@ async function runSend(c, sid, positional) {
306
350
  mentions: c.flags.mentions || [],
307
351
  wip: !!c.flags.wip,
308
352
  };
309
- const data = await post(c, `/sessions/${enc(sid)}/messages`, body);
353
+ if (c.flags.ignoreNew) body.ignore_new = true; // v0.37 PA-03: send even though others wrote since you last read
354
+ let data;
355
+ try {
356
+ data = await post(c, `/sessions/${enc(sid)}/messages`, body);
357
+ } catch (e) {
358
+ const r = refusalOf(e);
359
+ if (r && r.code === 'wb_new_messages') return reportNewMessages(c, sid, e);
360
+ throw e;
361
+ }
310
362
  // v0.33 (D369): a reply, with or without --wip, keeps the current session (a quick "got it" must not make the
311
363
  // pushes that follow fall out of this piece of work). Only `chat result`, or 2 hours without a chat command, ends it.
312
364
  touchCurrentSession(c.credOpts, c.nowMs());
@@ -327,6 +379,79 @@ async function runSend(c, sid, positional) {
327
379
  return 0;
328
380
  }
329
381
 
382
+ /**
383
+ * v0.37 PA-03: the platform did NOT store the message: others wrote in this group since you last read. Print what they
384
+ * wrote as the tool result, so the Agent can decide: read, then send again (or not at all), or send anyway.
385
+ */
386
+ function reportNewMessages(c, sid, e) {
387
+ const b = (e.body && e.body.detail && e.body.detail.error ? e.body.detail : e.body) || {};
388
+ const list = Array.isArray(b.new_messages) ? b.new_messages : [];
389
+ const count = Number((b.vars && b.vars.count) != null ? b.vars.count : list.length) || list.length;
390
+ if (c.json) {
391
+ c.log(JSON.stringify({ ok: false, error: 'wb_new_messages', sent: false, count, new_messages: list, latest_id: b.latest_id != null ? b.latest_id : null }));
392
+ return EXIT_NEW_MESSAGES;
393
+ }
394
+ const lines = [`这条消息没有发出:你上次读过之后,群里又有 ${count} 条别人发的新消息:`];
395
+ for (const m of list) {
396
+ const who = (m.sender && m.sender.name) || (m.sender && m.sender.type === 'agent' ? '另一个 Agent' : '群成员');
397
+ lines.push(` #${m.id}${m.created_at ? ` ${m.created_at}` : ''} ${who}:${m.excerpt || ''}`);
398
+ }
399
+ if (count > list.length) lines.push(` …(只列出最新 ${list.length} 条)`);
400
+ lines.push(`先读一下:anytowork chat read ${sid}。读完看看你要说的还有没有必要、有没有已经被回答;`
401
+ + '还要说就重新发一次(读过之后不会再被拦);确定不管新消息、照发不误,加 --ignore-new。');
402
+ c.err(lines.join('\n'));
403
+ return EXIT_NEW_MESSAGES;
404
+ }
405
+
406
+ /** `chat recall <message>` (v0.37, PA-10): take back one of my own messages within the window. */
407
+ async function runRecall(c, mid) {
408
+ if (!/^\d+$/.test(String(mid))) return usage(c, '用法:anytowork chat recall <消息编号>(chat read 里 # 后面的数字)');
409
+ const data = await post(c, `/messages/${enc(mid)}/recall`, {});
410
+ if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
411
+ c.log(`已撤回消息 #${mid},群里会显示「该 Agent 撤回了一条消息」。`);
412
+ return 0;
413
+ }
414
+
415
+ /** `chat group rename|describe|add-agent` (v0.37, PA-11): only what an Agent may do to a group it owns. */
416
+ async function runGroup(c, positionals) {
417
+ const op = positionals[2];
418
+ const gid = positionals[3];
419
+ const rest = positionals.slice(4);
420
+ const text = c.flags.stdin && c.readStdin ? await c.readStdin() : rest[0];
421
+ if (op === 'rename' || op === 'describe') {
422
+ const key = op === 'rename' ? 'name' : 'description';
423
+ if (!gid || text == null || (op === 'rename' && !String(text).trim())) {
424
+ return usage(c, op === 'rename' ? '用法:anytowork chat group rename <群编号> "<新名字>"' : '用法:anytowork chat group describe <群编号> "<描述>"(200 字内;写空字符串就是清空)');
425
+ }
426
+ let data;
427
+ try { data = await patch(c, `/groups/${enc(gid)}`, { [key]: String(text) }); } catch (e) { return groupRefusal(c, e); }
428
+ if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
429
+ c.log(op === 'rename' ? `群名已改为「${data.name || text}」,群里留了一行记录。` : '群描述已更新,群里留了一行记录。');
430
+ return 0;
431
+ }
432
+ if (op === 'add-agent') {
433
+ const ids = rest.filter((x) => x && !String(x).startsWith('--'));
434
+ if (!gid || !ids.length) return usage(c, '用法:anytowork chat group add-agent <群编号> <Agent编号>...(只能拉你主人名下的其他 Agent)');
435
+ let data;
436
+ try { data = await post(c, `/groups/${enc(gid)}/members`, { agent_ids: ids }); } catch (e) { return groupRefusal(c, e); }
437
+ if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
438
+ c.log(`已把 ${ids.length} 个 Agent 拉进群「${(data && data.name) || gid}」。`);
439
+ return 0;
440
+ }
441
+ return usage(c, '用法:anytowork chat group rename|describe|add-agent <群编号> ...(见 anytowork chat --help)');
442
+ }
443
+
444
+ /** A group refusal; a private chat has a fixed name, everything else is the shared wording. */
445
+ function groupRefusal(c, e) {
446
+ const r = refusalOf(e);
447
+ if (r && r.code === 'wb_dm_fixed') {
448
+ const text = '私聊的名字和描述是固定的,不能改;只有群可以。';
449
+ if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text })); else c.err(text);
450
+ return 1;
451
+ }
452
+ return reportRefusal(c, e);
453
+ }
454
+
330
455
  /** `chat result`: hand in the result. Ends this piece of work; the owner can take the changes back in one go. */
331
456
  async function runResult(c, sid) {
332
457
  const files = c.flags.files || [];
@@ -414,12 +539,16 @@ export async function runChat(p) {
414
539
  const c = {
415
540
  flags, json: flags.json, log, err, baseUrl, credOpts, fetchImpl,
416
541
  nowMs: deps.nowMs || Date.now,
542
+ env: p.env || process.env,
417
543
  readStdin: deps.readStdin,
418
544
  };
419
545
  const sub = command.slice('chat:'.length);
420
546
  if (!SUBS.has(sub)) { err(CHAT_HELP); return 2; }
421
547
  const sid = positionals[2];
422
548
  const rest = positionals[3];
549
+ if (sub === 'group') {
550
+ try { return await runGroup(c, positionals); } catch (e) { return reportRefusal(c, e); }
551
+ }
423
552
  if (sub !== 'list' && !sid) return usage(c, `缺少会话编号。用法见 anytowork chat --help(会话编号在 chat list 和叫醒你的消息里)。`);
424
553
  try {
425
554
  if (sub === 'list') return await runList(c);
@@ -428,6 +557,7 @@ export async function runChat(p) {
428
557
  if (sub === 'result') return await runResult(c, sid);
429
558
  if (sub === 'ask') return await runAsk(c, sid);
430
559
  if (sub === 'progress') return await runProgress(c, sid, rest);
560
+ if (sub === 'recall') return await runRecall(c, sid);
431
561
  return await runNeedWorkspace(c, sid, rest);
432
562
  } catch (e) {
433
563
  // An older platform has no result route: a bare 404 that is not one of our refusals (those carry an error code).