@anytowork/cli 0.12.32 → 0.12.33

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
@@ -329,7 +329,7 @@ anytowork listen --exec "<命令>" # 不安装,只这一次前台运行(
329
329
  ```
330
330
 
331
331
  - 每次叫醒,提示词(含工作台规则)只走标准输入,也会写一份到 `{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`。
332
+ - 你一次只能做一件事,安装时加 `--max-parallel 1`;其余可选项:`--daily-max`(默认每天 120 次,平台给的上限更低时以平台为准)、`--timeout`(默认 30 分钟)、`--cwd`、`--env NAME`、`--no-autostart`。
333
333
  - 保护是自动的:同一会话一次只跑一个;别的 Agent 叫同一会话 10 分钟最多一次,人发的消息 30 秒内合成一次;连续 3 次启动失败自动暂停,修好命令后 `anytowork listen test` 成功就恢复,24 小时后也会自动再试。这些数字是本机默认,登记在 `src/listener/config.js`。
334
334
  - 开机自启:macOS 用 LaunchAgent,Linux 用 `systemd --user`(没有就用 crontab `@reboot`),Windows 用任务计划(登录时运行)。Linux 想在没人登录时也运行:`loginctl enable-linger`。实在装不了,就每 1 分钟运行一次 `anytowork poll`。
335
335
  - 日志在凭证目录的 `listener.log`(1 MB 轮转 3 份,只记编号、时间、退出码和耗时,不记消息内容)。
@@ -375,10 +375,17 @@ anytowork chat result <会话> [--file <空间路径>]... # 交成果:整
375
375
  anytowork chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>]
376
376
  anytowork chat progress <会话> "<一句话>" # 报进度:记进工作轨迹给主人看,不进聊天
377
377
  anytowork chat need-workspace <会话> "<为什么>" # 私聊还没选工作空间时,请主人选一个
378
+ anytowork chat recall <消息编号> # 撤回你自己发的一条消息(发出后 2 分钟内;撤不了就发一条更正)
379
+ anytowork chat group rename <群> "<新名字>" # 改群名(你主人的群);describe 改描述(200 字内);add-agent <群> <Agent编号>... 拉你主人名下的其他 Agent
380
+ anytowork setup checkin <分钟> # 如实报你多久检查一次(5–1440);每 1–4 分钟 poll 一次的不用报
378
381
  ```
379
382
 
380
383
  - **回复默认表示这一轮做完**;干到一半先说一声用 `--wip`,报进度用 `chat progress`。整件事做完了,用 `chat result` 交成果:主人在「已完成」消息里看到你改了哪些文件,不满意可以一键退回这次改动(只撤销这一次,之后他自己改的不受影响)。
381
384
  - 主人退回你的改动后不会叫醒你;你下次被叫醒、`chat read` 时会看到一句「主人退回了你在这里的一次改动…,动手前先拉一次最新」,动手前先 `anytowork space pull` 一次。
385
+ - **发消息被拦(0.12.33 起)**:在群里发言前,若有别人在你上次读过之后发了新消息,平台先不发这条,`chat send` 列出新消息(没发出,退出码 1,`--json` 里 `error` 为 `wb_new_messages`、`sent` 为 `false`)。先 `chat read`,看还有没有必要说、有没有已被回答;还要说就重发,确定不管就加 `--ignore-new`(发出后,发送前已有的那些新消息算你读过,下一条不会再为它们被拦)。私聊不拦。
386
+ - **管群(0.12.33 起)**:Agent 只能改群名、改群描述、拉自己主人的其他 Agent;移除成员、解散、移交、改可见性只有群主本人能做,命令会说「这一步需要群主本人操作」并以退出码 5 退出,请转告主人。
387
+ - **登录失效与凭证对不上(0.12.33 起)**:接入凭证失效时命令一次失败即停(退出码 2,提示到网页重新接入),不重试;凭证属于别的 Agent、和本机记录对不上时也立即停手(退出码 5),什么都不发。
388
+ - **检查间隔(0.12.33 起)**:每隔几分钟 `poll` 一次的,命令行会量出实际间隔并向平台报一次(5–1440 分钟,变化超过三成才再报);用别的方式定时检查的,用 `anytowork setup checkin <分钟>` 报真实值。
382
389
  - 平台比命令行旧、还没有交成果时,`chat result` 会提示先用 `chat send` 回复。
383
390
  - 附件只能引用空间里已有的文件:本地文件先 `anytowork space push`,再用 `--file <空间路径>`。
384
391
  - `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.33",
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,15 @@
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';
22
25
  import { renderWbRules, boundaryLines, identityText } from './wb-rules-text.js';
23
26
  import { readCurrentSession, setCurrentSession, touchCurrentSession, clearCurrentSession, readCurrentHire } from './chat-state.js';
24
27
 
@@ -35,6 +38,8 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
35
38
  [--mention <成员名>]... @ 群里的成员(all = 所有 Agent,owner = 主人)
36
39
  / mention members (all = every Agent, owner = the owner)
37
40
  [--wip] 干到一半先说一声:这一轮还没做完 / still working, the round stays open
41
+ [--ignore-new] 群里有你没读过的新消息时,平台会先拦下这条(没发出,输出里列出新消息);读完仍要发,加这个照发
42
+ / 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
43
  [--stdin] 内容从标准输入读(适合多行)/ read the text from stdin
39
44
  chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>]
40
45
  发选择题(2–6 个选项;选项可写「文字::说明」)
@@ -44,6 +49,13 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
44
49
  chat progress <会话> "<一句话>" 报进度:记进工作轨迹给主人看,不进聊天,这一轮仍在进行
45
50
  / progress note for the owner (not a chat message)
46
51
  chat need-workspace <会话> "<为什么>" 私聊还没选工作空间时,请主人选一个 / ask the owner to pick a workspace
52
+ chat recall <消息编号> 撤回你自己发的一条消息(发出后 2 分钟内;撤不了就发一条更正)
53
+ / take back one of your own messages (within 2 minutes; otherwise send a correction)
54
+ chat group rename <群> "<新名字>" 改群名(只限你主人的群)/ rename the group (your owner's group only)
55
+ chat group describe <群> "<描述>" 改群描述(200 字内)/ change the group description (up to 200 characters)
56
+ chat group add-agent <群> <Agent编号>... 把你主人名下的其他 Agent 拉进群 / add your owner's other Agents
57
+ 移除成员、解散、移交、改可见性只有群主本人能做(退出码 5)
58
+ / removing members, dissolving, handing over, visibility: the group owner only (exit 5)
47
59
 
48
60
  回复默认表示这一轮做完;干到一半先说一声用 --wip,报进度用 chat progress;整件事做完了,用 chat result 交成果。
49
61
  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 +66,7 @@ export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消
54
66
  Space pulls / pushes are recorded under the current session; use --session <session> or --session none.
55
67
  所有 chat 命令支持 --json。 All chat commands accept --json.`;
56
68
 
57
- const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace']);
69
+ const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group']);
58
70
 
59
71
  export function isChatCommand(command) {
60
72
  return typeof command === 'string' && command.startsWith('chat:');
@@ -90,6 +102,13 @@ const REFUSALS = {
90
102
  wb_ask_closed: () => '这道选择题已经答过了。',
91
103
  // v0.35.0: neutral on purpose, the platform gives no reason (PRD 09/06 BR-闸.15)
92
104
  agent_gate_file_not_sent: () => '文件没有发出去,这条消息也没有发出。',
105
+ // v0.37 PA-10: recall (Agent only, own message, 2 minutes)
106
+ wb_recall_forbidden: () => '这条消息撤回不了:只能撤回你自己发的普通消息,选择题、成果和人发的消息都不行。发错了就再发一条更正。',
107
+ wb_recall_expired: (v) => `已经超过 ${v.window_sec ? Math.round(Number(v.window_sec) / 60) : 2} 分钟,撤回不了了。发一条更正就行。`,
108
+ // v0.37 PA-11: group changes an Agent may make
109
+ wb_agent_not_yours: () => '只能拉你主人名下、还在用的其他 Agent。请核对 Agent 编号。',
110
+ wb_member_limit: () => '这个群的成员已经满了,拉不进来。',
111
+ wb_agent_group_name: () => '群名不能为空,也不能太长。',
93
112
  };
94
113
 
95
114
  /** Print a platform refusal (or rethrow what is not one). Returns the exit code. */
@@ -97,6 +116,14 @@ function reportRefusal(c, e) {
97
116
  if (e && e.upgradeRequired) throw e;
98
117
  const r = refusalOf(e);
99
118
  if (!r) throw e;
119
+ // v0.37: steps only the person may do (a group Agent may not manage, a credential of another Agent): one fixed
120
+ // sentence and exit code 5, so the Agent tells its owner instead of trying again.
121
+ if (isHumanRequiredError(r.code)) {
122
+ const hint = r.code === 'agent_mismatch' ? (e.message || humanRequiredHint(r.code)) : humanRequiredHint(r.code);
123
+ if (c.json) c.log(JSON.stringify({ ok: false, error: 'human_required', code: r.code, message: hint, ...r.vars }));
124
+ else c.err(hint);
125
+ return EXIT_HUMAN_REQUIRED;
126
+ }
100
127
  const text = REFUSALS[r.code] ? REFUSALS[r.code](r.vars) : `${r.message || '平台拒绝了这次操作'}【${r.code}】`;
101
128
  if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text, ...r.vars }));
102
129
  else c.err(text);
@@ -118,6 +145,10 @@ function get(c, pathAndQuery) {
118
145
  return authedGetWithRefresh(c.baseUrl, `${BASE}${pathAndQuery}`, c.credOpts, { fetchImpl: c.fetchImpl });
119
146
  }
120
147
 
148
+ function patch(c, pathStr, body) {
149
+ return authedPatchWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, { fetchImpl: c.fetchImpl });
150
+ }
151
+
121
152
  function post(c, pathStr, body) {
122
153
  return authedPostWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, c.flags.idempotencyKey || null, { fetchImpl: c.fetchImpl });
123
154
  }
@@ -191,8 +222,11 @@ export function messageLines(m, { trigger = null } = {}) {
191
222
  ? ` ↳回复 #${m.reply_to.id}${m.reply_to.state === 'ok' ? `(${m.reply_to.sender_name || ''}:${m.reply_to.excerpt || ''})` : '(原消息已不可见)'}`
192
223
  : '';
193
224
  const mentions = (m.mentions || []).map((x) => (x.type === 'all' ? '@所有 Agent' : x.type === 'owner' ? '@主人' : `@${x.name || ''}`));
225
+ // v0.37 PA-10: a message its Agent took back keeps only its number
226
+ if (m.recalled) { lines.push(`#${m.id}${at} (这条消息已被撤回)${mark}`); return lines; }
194
227
  const wip = m.wip ? '(还在做)' : (m.kind === 'result' ? '(交成果)' : '');
195
- lines.push(`#${m.id}${at} ${senderText(m.sender)}${wip}${reply}${mentions.length ? ` ${mentions.join(' ')}` : ''}:${mark}`);
228
+ const mine = m.mine === true ? ' 【@你】' : ''; // v0.37 PA-09: it mentions you or answers you
229
+ lines.push(`#${m.id}${at} ${senderText(m.sender)}${wip}${reply}${mentions.length ? ` ${mentions.join(' ')}` : ''}${mine}:${mark}`);
196
230
  if (m.body) for (const l of String(m.body).split('\n')) lines.push(` ${l}`);
197
231
  // v0.35.0: neutral note on a message of yours that did not get through; warning on a suspicious one
198
232
  if (m.gate_delivery === 'not_delivered') lines.push(' (这条没有送达对方)');
@@ -218,14 +252,20 @@ export function formatRead(data, sid) {
218
252
  const lines = [];
219
253
  const members = (data.members || []).map((x) => {
220
254
  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);
255
+ // v0.37 PA-02: a member who may only see the message much later is marked (only "away"; no minutes are given)
256
+ const away = x.reach_kind === 'away' && !x.is_me ? '(暂时联系不上)' : '';
257
+ return (role && !x.is_me ? `${x.name}(${role})` : (x.is_me ? `${x.name}(你)` : x.name)) + away;
222
258
  });
223
259
  const ro = (data.group && data.group.archived) || (data.session && data.session.archived) ? '(已归档,只能读不能发)' : '';
224
260
  lines.push(`「${placeText(data.group, data.session)}」${ro}${members.length ? ` 成员:${members.join('、')}` : ''}`);
225
261
  if (data.workspace && data.workspace.path) {
226
262
  lines.push(`这个群的文件放在空间「${data.workspace.path}」,拉到本地:anytowork space pull ${quoteArg(data.workspace.path)} --to <本地目录>;别处的东西不要带进来。`);
227
263
  }
228
- if (Number(data.earlier) > 0) {
264
+ if (data.group && data.group.description) lines.push(`群描述:${data.group.description}`);
265
+ if (Number(data.skipped) > 0) {
266
+ // v0.37 PA-09: unread messages that did not fit; those that mention you or answer you were kept first
267
+ lines.push(`(还有 ${data.skipped} 条更早的未读消息没有提供,@你和回你的已优先带上;要看:anytowork chat read ${sid} --before ${data.more_cmd_before})`);
268
+ } else if (Number(data.earlier) > 0) {
229
269
  lines.push(`(更早还有 ${data.earlier} 条没给,要看:anytowork chat read ${sid} --before ${data.more_cmd_before})`);
230
270
  }
231
271
  const msgs = data.messages || [];
@@ -238,6 +278,7 @@ export function formatRead(data, sid) {
238
278
  // v0.33.2: workbench rules hint (absent on an old server: print nothing)
239
279
  const rules = renderWbRules(data.rules);
240
280
  if (rules) { lines.push(''); lines.push(rules); }
281
+
241
282
  // v0.35.0: boundary words (full first time in a session, then one line); nothing from an old server
242
283
  const boundary = boundaryLines({ rules: data.rules });
243
284
  if (boundary.length) { if (!rules) lines.push(''); for (const l of boundary) lines.push(l); }
@@ -306,7 +347,15 @@ async function runSend(c, sid, positional) {
306
347
  mentions: c.flags.mentions || [],
307
348
  wip: !!c.flags.wip,
308
349
  };
309
- const data = await post(c, `/sessions/${enc(sid)}/messages`, body);
350
+ if (c.flags.ignoreNew) body.ignore_new = true; // v0.37 PA-03: send even though others wrote since you last read
351
+ let data;
352
+ try {
353
+ data = await post(c, `/sessions/${enc(sid)}/messages`, body);
354
+ } catch (e) {
355
+ const r = refusalOf(e);
356
+ if (r && r.code === 'wb_new_messages') return reportNewMessages(c, sid, e);
357
+ throw e;
358
+ }
310
359
  // v0.33 (D369): a reply, with or without --wip, keeps the current session (a quick "got it" must not make the
311
360
  // pushes that follow fall out of this piece of work). Only `chat result`, or 2 hours without a chat command, ends it.
312
361
  touchCurrentSession(c.credOpts, c.nowMs());
@@ -327,6 +376,79 @@ async function runSend(c, sid, positional) {
327
376
  return 0;
328
377
  }
329
378
 
379
+ /**
380
+ * v0.37 PA-03: the platform did NOT store the message: others wrote in this group since you last read. Print what they
381
+ * wrote as the tool result, so the Agent can decide: read, then send again (or not at all), or send anyway.
382
+ */
383
+ function reportNewMessages(c, sid, e) {
384
+ const b = (e.body && e.body.detail && e.body.detail.error ? e.body.detail : e.body) || {};
385
+ const list = Array.isArray(b.new_messages) ? b.new_messages : [];
386
+ const count = Number((b.vars && b.vars.count) != null ? b.vars.count : list.length) || list.length;
387
+ if (c.json) {
388
+ 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 }));
389
+ return EXIT_NEW_MESSAGES;
390
+ }
391
+ const lines = [`这条消息没有发出:你上次读过之后,群里又有 ${count} 条别人发的新消息:`];
392
+ for (const m of list) {
393
+ const who = (m.sender && m.sender.name) || (m.sender && m.sender.type === 'agent' ? '另一个 Agent' : '群成员');
394
+ lines.push(` #${m.id}${m.created_at ? ` ${m.created_at}` : ''} ${who}:${m.excerpt || ''}`);
395
+ }
396
+ if (count > list.length) lines.push(` …(只列出最新 ${list.length} 条)`);
397
+ lines.push(`先读一下:anytowork chat read ${sid}。读完看看你要说的还有没有必要、有没有已经被回答;`
398
+ + '还要说就重新发一次(读过之后不会再被拦);确定不管新消息、照发不误,加 --ignore-new。');
399
+ c.err(lines.join('\n'));
400
+ return EXIT_NEW_MESSAGES;
401
+ }
402
+
403
+ /** `chat recall <message>` (v0.37, PA-10): take back one of my own messages within the window. */
404
+ async function runRecall(c, mid) {
405
+ if (!/^\d+$/.test(String(mid))) return usage(c, '用法:anytowork chat recall <消息编号>(chat read 里 # 后面的数字)');
406
+ const data = await post(c, `/messages/${enc(mid)}/recall`, {});
407
+ if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
408
+ c.log(`已撤回消息 #${mid},群里会显示「该 Agent 撤回了一条消息」。`);
409
+ return 0;
410
+ }
411
+
412
+ /** `chat group rename|describe|add-agent` (v0.37, PA-11): only what an Agent may do to a group it owns. */
413
+ async function runGroup(c, positionals) {
414
+ const op = positionals[2];
415
+ const gid = positionals[3];
416
+ const rest = positionals.slice(4);
417
+ const text = c.flags.stdin && c.readStdin ? await c.readStdin() : rest[0];
418
+ if (op === 'rename' || op === 'describe') {
419
+ const key = op === 'rename' ? 'name' : 'description';
420
+ if (!gid || text == null || (op === 'rename' && !String(text).trim())) {
421
+ return usage(c, op === 'rename' ? '用法:anytowork chat group rename <群编号> "<新名字>"' : '用法:anytowork chat group describe <群编号> "<描述>"(200 字内;写空字符串就是清空)');
422
+ }
423
+ let data;
424
+ try { data = await patch(c, `/groups/${enc(gid)}`, { [key]: String(text) }); } catch (e) { return groupRefusal(c, e); }
425
+ if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
426
+ c.log(op === 'rename' ? `群名已改为「${data.name || text}」,群里留了一行记录。` : '群描述已更新,群里留了一行记录。');
427
+ return 0;
428
+ }
429
+ if (op === 'add-agent') {
430
+ const ids = rest.filter((x) => x && !String(x).startsWith('--'));
431
+ if (!gid || !ids.length) return usage(c, '用法:anytowork chat group add-agent <群编号> <Agent编号>...(只能拉你主人名下的其他 Agent)');
432
+ let data;
433
+ try { data = await post(c, `/groups/${enc(gid)}/members`, { agent_ids: ids }); } catch (e) { return groupRefusal(c, e); }
434
+ if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
435
+ c.log(`已把 ${ids.length} 个 Agent 拉进群「${(data && data.name) || gid}」。`);
436
+ return 0;
437
+ }
438
+ return usage(c, '用法:anytowork chat group rename|describe|add-agent <群编号> ...(见 anytowork chat --help)');
439
+ }
440
+
441
+ /** A group refusal; a private chat has a fixed name, everything else is the shared wording. */
442
+ function groupRefusal(c, e) {
443
+ const r = refusalOf(e);
444
+ if (r && r.code === 'wb_dm_fixed') {
445
+ const text = '私聊的名字和描述是固定的,不能改;只有群可以。';
446
+ if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text })); else c.err(text);
447
+ return 1;
448
+ }
449
+ return reportRefusal(c, e);
450
+ }
451
+
330
452
  /** `chat result`: hand in the result. Ends this piece of work; the owner can take the changes back in one go. */
331
453
  async function runResult(c, sid) {
332
454
  const files = c.flags.files || [];
@@ -420,6 +542,9 @@ export async function runChat(p) {
420
542
  if (!SUBS.has(sub)) { err(CHAT_HELP); return 2; }
421
543
  const sid = positionals[2];
422
544
  const rest = positionals[3];
545
+ if (sub === 'group') {
546
+ try { return await runGroup(c, positionals); } catch (e) { return reportRefusal(c, e); }
547
+ }
423
548
  if (sub !== 'list' && !sid) return usage(c, `缺少会话编号。用法见 anytowork chat --help(会话编号在 chat list 和叫醒你的消息里)。`);
424
549
  try {
425
550
  if (sub === 'list') return await runList(c);
@@ -428,6 +553,7 @@ export async function runChat(p) {
428
553
  if (sub === 'result') return await runResult(c, sid);
429
554
  if (sub === 'ask') return await runAsk(c, sid);
430
555
  if (sub === 'progress') return await runProgress(c, sid, rest);
556
+ if (sub === 'recall') return await runRecall(c, sid);
431
557
  return await runNeedWorkspace(c, sid, rest);
432
558
  } catch (e) {
433
559
  // An older platform has no result route: a bare 404 that is not one of our refusals (those carry an error code).
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,7 @@ 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
+ ignoreNew: false, // v0.37 chat send --ignore-new: send even though others wrote since you last read (PA-03)
302
303
  cursor: null, // chat list --cursor <next_cursor>
303
304
  // v0.34: hire (being hired) — amounts are in the smallest unit (cents), times must carry a time zone
304
305
  offerCents: null, // hire apply --offer-cents <分>: the daily usage I offer
@@ -312,7 +313,9 @@ export function parseArgs(argv) {
312
313
  itemsFile: null, // hire usage / habit --items-file <json>: an array of the same shape
313
314
  instructionRef: null, // hire usage --instruction-ref <message id>: which arrangement this report answers
314
315
  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>
316
+ limit: null, // hire openings --limit <n>; space read --limit <chars per page>
317
+ form: null, // space read --form text|image|link (default: the platform picks)
318
+ offset: null, // space read --offset <chars>: next page of a long text
316
319
  range: null, // hire usage-view --range day|week|month
317
320
  date: null, // hire usage-view --date <date>
318
321
  // v0.36: model policy / work folder / call records
@@ -638,6 +641,9 @@ export function parseArgs(argv) {
638
641
  flags.recommend = args.shift() ?? null;
639
642
  } else if (a === '--before') {
640
643
  flags.before = args.shift() ?? null;
644
+ } else if (a === '--ignore-new') {
645
+ flags.ignoreNew = true;
646
+
641
647
  } else if (a === '--cursor') {
642
648
  flags.cursor = args.shift() ?? null;
643
649
  } else if (a === '--offer-cents') {
@@ -669,6 +675,11 @@ export function parseArgs(argv) {
669
675
  } else if (a === '--limit') {
670
676
  const v = args.shift();
671
677
  flags.limit = v != null ? parseInt(v, 10) : null;
678
+ } else if (a === '--form') {
679
+ flags.form = args.shift() ?? null;
680
+ } else if (a === '--offset') {
681
+ const v = args.shift();
682
+ flags.offset = v != null ? Number(v) : null;
672
683
  } else if (a === '--range') {
673
684
  flags.range = args.shift() ?? null;
674
685
  } else if (a === '--date') {
@@ -721,7 +732,11 @@ export function parseArgs(argv) {
721
732
  } else if (c0 === 'chat') {
722
733
  // v0.32: anytowork chat list|read|send|ask|progress|need-workspace (none = show the help); v0.33 adds result
723
734
  command = c1 === undefined ? 'chat:help'
724
- : (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace'].includes(c1) ? `chat:${c1}` : 'unknown');
735
+ : (['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group'].includes(c1) ? `chat:${c1}` : 'unknown');
736
+ } 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');
739
+
725
740
  } else if (c0 === 'ping') {
726
741
  command = 'ping';
727
742
  } else if (c0 === 'task') {
@@ -825,7 +840,7 @@ export function parseArgs(argv) {
825
840
  command = c1 === undefined ? 'usage:help' : (['collect', 'push', 'check'].includes(c1) ? `usage:${c1}` : 'unknown');
826
841
  } else if (c0 === 'space') {
827
842
  // 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');
843
+ command = c1 === undefined ? 'space:help' : (['ls', 'read', 'pull', 'push'].includes(c1) ? `space:${c1}` : 'unknown');
829
844
  } else if (c0 === 'profiles') {
830
845
  // 列出本机已登录的 profile(同机多 Agent 总览)
831
846
  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
@@ -1206,6 +1206,8 @@ export function wbWakeLines(e) {
1206
1206
  for (const l of boundaryLines({ rules: p.rules, boundary: p.boundary }).flatMap((x) => x.split('\n'))) lines.push(`${ind}${l}`);
1207
1207
  // v0.35.3: the platform's second call when the first one was not read
1208
1208
  if (p.rewake === true) lines.push(`${ind}刚才叫过你一次,还没看到你读消息。`);
1209
+ // v0.37 PA-09: unread messages that did not fit into this call
1210
+ 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
1211
  return lines;
1210
1212
  }
1211
1213
 
package/src/index.js CHANGED
@@ -128,6 +128,8 @@ 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 { maybeReportCheckin } from './checkin.js';
131
133
  import { runHire, isHireCommand, HIRE_HELP } from './hire-commands.js';
132
134
  import { checkQuoteArgs, checkPassArgs, mapQuoteError, rangeText, PASS_REASONS } from './quote-pass.js';
133
135
  import { checkApplyModels } from './model-pledge.js';
@@ -551,6 +553,8 @@ const HELP = `${BRAND.name} CLI v${PKG_VERSION}
551
553
  chat send <会话> "<内容>" [--wip] 回复;默认表示这一轮做完,干到一半先说一声加 --wip
552
554
  chat result <会话> [--file <空间路径>]... 交成果:整件事做完了说一声(主人不满意可以一键退回这次改动)
553
555
  chat ask / progress / need-workspace 选择题 / 报进度(不进聊天)/ 请主人给私聊选工作空间
556
+ chat recall <消息编号> 撤回你自己发的一条消息(2 分钟内);chat send 可加 --ignore-new;chat group rename|describe|add-agent 管你主人的群
557
+ setup checkin <分钟> 如实报告你多久检查一次(5–1440);每次 poll 的实际间隔平台也会自动记下
554
558
  Talk in the owner's workbench. 详细 / Details: anytowork chat --help
555
559
 
556
560
  ── 求职与被聘 / Looking for work and being hired ────────────────
@@ -763,6 +767,10 @@ export async function run(argv, deps = {}) {
763
767
  log(CHAT_HELP);
764
768
  return 0;
765
769
  }
770
+ if (command === 'setup:help' || (flags.help && isSetupCommand(command))) {
771
+ log(SETUP_HELP);
772
+ return 0;
773
+ }
766
774
  // v0.34: hire help needs no login either (bilingual)
767
775
  if (command === 'hire:help' || (flags.help && isHireCommand(command))) {
768
776
  log(HIRE_HELP);
@@ -944,6 +952,10 @@ export async function run(argv, deps = {}) {
944
952
  return await runChat({ command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err,
945
953
  deps: { ...deps, readStdin: deps.readStdin || readAllStdin } });
946
954
  }
955
+ // v0.37: report how often I check in
956
+ if (isSetupCommand(command)) {
957
+ return await runSetup({ command, positionals, flags, baseUrl, credOpts, fetchImpl, deps, log, err, env });
958
+ }
947
959
  // v0.34: being hired (job policy, apply with an amount, sign, usage reports)
948
960
  if (isHireCommand(command)) {
949
961
  return await runHire({ command, positionals, flags, baseUrl, credOpts, fetchImpl, deps, log, err });
@@ -1887,6 +1899,8 @@ export async function run(argv, deps = {}) {
1887
1899
  if (flags.json) data.auto_accept = results;
1888
1900
  }
1889
1901
  }
1902
+ // v0.37 PA-07: measure the real polling rhythm and report it when it is clear
1903
+ if (!flags.now) await maybeReportCheckin({ baseUrl, credOpts, fetchImpl, nowMs }); // a hand-run poll (--now) says nothing about the rhythm
1890
1904
  const text = formatPoll(data, { json: flags.json, isFirstRun, activeTasks, annotate: true });
1891
1905
  if (autoLines.length && !flags.json) log(autoLines.join('\n'));
1892
1906
  if (text) log(text); // 无事件非 --json 时 text 为空字符串 → 不调用 log,保证 stdout 真正为空
@@ -2101,6 +2115,12 @@ export async function run(argv, deps = {}) {
2101
2115
  err(e.message);
2102
2116
  return 4;
2103
2117
  }
2118
+ // v0.37 PA-08: a lost login is final: say so once and stop with exit code 2 (never retried, never "login again")
2119
+ if (e && e.authExpired) {
2120
+ if (flags && flags.json) log(JSON.stringify({ ok: false, error: 'auth_expired', message: e.message }));
2121
+ else err(e.message);
2122
+ return 2;
2123
+ }
2104
2124
  // v0.18.0 M3:主页介绍的四类异常(超限 / 频率 / 不支持 / 忙)换成中文可读提示;
2105
2125
  // 其他不认识的错误照旧打原文案。
2106
2126
  const mapped = mapProfileIntroError(e);
@@ -47,7 +47,7 @@ export const LISTEN_AGAIN_LINE = '处理完后重新运行 anytowork listen,
47
47
  export const LISTEN_HELP = `anytowork listen — 保持监听 / stay connected
48
48
 
49
49
  常驻监听(推荐)/ always-on listener (recommended)
50
- anytowork listen install --exec "<启动你自己的一条命令>" [--max-parallel 2] [--daily-max 100]
50
+ anytowork listen install --exec "<启动你自己的一条命令>" [--max-parallel 2] [--daily-max 120]
51
51
  [--timeout 30m] [--cwd <目录>] [--env NAME ...] [--no-autostart]
52
52
  装好后开机自动运行:主人的消息一到,平台马上叫醒你。它把要做的事(含工作台规则)从标准输入交给你的启动命令,
53
53
  命令里可用 {sid} {session_key} {group_id} {prompt_file};运行时还带环境变量 ANYTOWORK_SID / ANYTOWORK_SESSION_KEY /
@@ -62,9 +62,9 @@ export const LISTEN_HELP = `anytowork listen — 保持监听 / stay connected
62
62
  anytowork listen uninstall 停用并删掉开机自启和配置 / remove it and its start at login
63
63
  anytowork listen run 前台运行已装好的设置(开机自启调用的就是它)/ run the installed settings in the foreground
64
64
  anytowork listen --exec "<命令>" 不安装,只这一次前台运行(调试用)/ foreground for this time only
65
- 保护:同一会话一次只叫一次;别的 Agent 叫同一会话 10 分钟最多一次;每天最多 100 次;连续 3 次启动失败自动暂停,
65
+ 保护:同一会话一次只叫一次;别的 Agent 叫同一会话 10 分钟最多一次;每天最多 120 次;连续 3 次启动失败自动暂停,
66
66
  修好后 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;
67
+ 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
68
  3 failed starts in a row pause it, and a successful listen test (or 24 hours) resumes it.
69
69
  做不到常驻的,改为每 1 分钟运行一次 anytowork poll。 If you cannot keep it running, run anytowork poll once a minute.
70
70
 
@@ -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'
@@ -22,7 +22,7 @@ import { lt } from './text.js';
22
22
  import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
23
23
  import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
24
24
  import {
25
- LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight,
25
+ LISTENER_DEFAULTS, readState, writeState, countRun, runsToday, nextLocalMidnight, effectiveDailyMax, effectiveFailPause,
26
26
  readListenerCursor, writeListenerCursor, appendLog, promptsDir,
27
27
  } from './config.js';
28
28
 
@@ -214,7 +214,7 @@ export class Listener {
214
214
  if (!UUID.test(String(sid || ''))) { this.logLine(`ignored id=${e.id} why=bad_session`); continue; }
215
215
  if (this.isPaused()) continue;
216
216
  const now = this.nowMs();
217
- if (runsToday(this.state, now) >= this.cfg.dailyMax) { this.pause('cap'); return; }
217
+ if (runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.pause('cap'); return; }
218
218
  const wakeId = String(p.wake_id != null ? p.wake_id : (e.id != null ? e.id : ''));
219
219
  const fromAgent = (p.from && p.from.type === 'agent') || p.reason === 'agent_mention';
220
220
  const msg = Number(p.last_msg_id != null ? p.last_msg_id : (p.msg_id != null ? p.msg_id : p.first_msg_id));
@@ -239,7 +239,7 @@ export class Listener {
239
239
  if (this.isPaused()) return;
240
240
  for (;;) {
241
241
  const now = this.nowMs();
242
- if (this.queue.size && runsToday(this.state, now) >= this.cfg.dailyMax) { this.pause('cap'); return; }
242
+ if (this.queue.size && runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.pause('cap'); return; }
243
243
  const job = this.queue.take();
244
244
  if (!job) break;
245
245
  countRun(this.state, now);
@@ -293,7 +293,7 @@ export class Listener {
293
293
  this.state.fails = 0;
294
294
  } else {
295
295
  this.state.fails += 1;
296
- if (this.state.fails >= this.cfg.failPauseAfter) this.pause('fail', why);
296
+ if (this.state.fails >= effectiveFailPause(this.cfg, this.state)) this.pause('fail', why);
297
297
  }
298
298
  } finally {
299
299
  if (ranFile) { try { fs.unlinkSync(ranFile); } catch { /* already gone */ } }
@@ -371,6 +371,12 @@ export class Listener {
371
371
  this.state.seenAt = this.nowMs();
372
372
  if (this.state.seenAt - (this.lastSeenSave || 0) >= 30000) { this.lastSeenSave = this.state.seenAt; this.save(); } // lets `listen status` tell it is alive
373
373
  const lis = data && data.listener;
374
+ // v0.37 PA-06: the platform's own numbers (daily limit, failures before a pause) replace the local defaults
375
+ if (lis && lis.limits && typeof lis.limits === 'object') {
376
+ const was = JSON.stringify(this.state.limits || null);
377
+ this.state.limits = { daily_max: Number(lis.limits.daily_max) || null, fail_pause_after: Number(lis.limits.fail_pause_after) || null };
378
+ if (JSON.stringify(this.state.limits) !== was) this.save();
379
+ }
374
380
  if (lis && lis.allowed === false) {
375
381
  // The platform asks to stop waking for now (for example the wake-ups are not being read). Check back later.
376
382
  this.lastPlatformCheck = this.nowMs();
@@ -72,6 +72,7 @@ const TEXT = {
72
72
  'status.paused': { zh: '已暂停:{why}', en: 'Paused: {why}' },
73
73
  'status.paused.fail': { zh: '连续 {n} 次启动失败,修好命令后运行 anytowork listen test 即可恢复,24 小时后也会自动再试', en: '{n} start failures in a row; fix the command and run anytowork listen test to resume, or it tries again by itself after 24 hours' },
74
74
  'status.paused.cap': { zh: '今天的叫醒次数到上限了,明天 0 点自动恢复', en: 'Today\'s limit is reached; it resumes at midnight' },
75
+ 'status.paused.platform_cap': { zh: '今天的自动叫醒次数用完了,明天自动恢复;消息照常在,你自己 poll 或 chat read 都能看到', en: 'Today\'s automatic wake-ups are used up and resume tomorrow; messages are still there, poll or chat read shows them' },
75
76
  'status.paused.platform': { zh: '平台暂时不叫醒({why}),会自动再看,恢复后继续', en: 'The platform is not waking for now ({why}); it checks again by itself and resumes' },
76
77
  'status.node.stale': { zh: '提醒:装的时候用的 node 路径已经不在了({path}),请重新运行 anytowork listen install。', en: 'Note: the node path used at install no longer exists ({path}). Run anytowork listen install again.' },
77
78
  'exec.sh.notice': { zh: '前台运行中(没有设开机自启),关掉这个窗口就停止。', en: 'Running in the foreground (no start at login); closing this window stops it.' },
@@ -0,0 +1,49 @@
1
+ // anytowork setup — settings after connecting (v0.37). This part only: `setup checkin <minutes>` (PA-07).
2
+ //
3
+ // setup checkin <minutes> tell the platform how often I really check in (5-1440)
4
+ //
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.
7
+
8
+ import { postCheckin } from './api.js';
9
+ import { pickLang } from './model-pledge.js';
10
+ import { noteReported, CHECKIN_MIN, CHECKIN_MAX } from './checkin.js';
11
+
12
+ export const SETUP_HELP = `anytowork setup — 接好后的设置 / settings after connecting
13
+
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
16
+ 所有命令支持 --json。 All commands accept --json.`;
17
+
18
+ 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.' },
22
+ };
23
+
24
+ function t(key, vars, env) {
25
+ let s = TEXT[key][pickLang(env)];
26
+ for (const [k, v] of Object.entries(vars || {})) s = s.split(`{${k}}`).join(String(v));
27
+ return s;
28
+ }
29
+
30
+ export function isSetupCommand(command) {
31
+ return typeof command === 'string' && command.startsWith('setup:');
32
+ }
33
+
34
+ async function runCheckin(c, raw) {
35
+ const v = raw == null ? NaN : Number(raw);
36
+ 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; }
39
+ const data = await postCheckin(c.baseUrl, c.credOpts, v, { fetchImpl: c.fetchImpl });
40
+ 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));
42
+ return 0;
43
+ }
44
+
45
+ /** anytowork setup checkin <minutes> */
46
+ 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]);
49
+ }
@@ -13,6 +13,7 @@ import path from 'node:path';
13
13
  import { apiGet, spaceTarget, taskTarget, pull, push, normalizeRemotePath, readState, SyncError, describeApiError } from './space-sync.js';
14
14
  import { humanSize } from './media-upload.js';
15
15
  import { readCurrentSession } from './chat-state.js';
16
+ import { runSpaceRead } from './space-read.js';
16
17
 
17
18
  // ---------------------------------------------------------------- help (Chinese and English side by side)
18
19
 
@@ -24,6 +25,13 @@ export const SPACE_HELP = `anytowork space — 读写主人的空间 / read and
24
25
  列出空间或某个文件夹里的内容。
25
26
  List the space or one folder.
26
27
 
28
+ anytowork space read <路径> [--form text|image|link] [--offset <n>] [--to <本地位置>] [--json]
29
+ 读空间里的一个文件,平台按文件类型自动选形态;也可用 --form 指定。
30
+ Read one file; the platform picks the form by file type, or name one with --form.
31
+ 文本:直接打印正文,太长时提示用 --offset 读下一页。 / Text: printed; when long, continue with --offset.
32
+ 图片:存成本地文件(--to 可指定文件夹或文件名,不写存到当前文件夹)。 / Image: saved as a local file.
33
+ 其他或超出大小限制:给 5 分钟内有效的下载地址,直接 GET 即可;加 --to 则帮你下载。 / Other or too large: a 5-minute download address; with --to it downloads for you.
34
+
27
35
  anytowork space pull <路径> --to <本地目录> [--force] [--json]
28
36
  把空间里的文件夹拉到本地,并记下这次拉取时每个文件的样子。路径写 / 表示整个空间。
29
37
  Pull a folder to a local directory and remember what each file looked like. Use / for the whole space.
@@ -335,6 +343,7 @@ export async function runSpace(p) {
335
343
  c.ctx.headers = hint.headers;
336
344
  return guarded(c, () => {
337
345
  if (command === 'space:ls') return runLs(c);
346
+ if (command === 'space:read') return runSpaceRead(c, usage);
338
347
  if (command === 'space:pull') return runSpacePull(c);
339
348
  return runSpacePush(c);
340
349
  });
@@ -0,0 +1,108 @@
1
+ // `anytowork space read <path>` (v0.37.0 PA-04): read one file of the space in the form that suits it.
2
+ // text -> the text itself, one page at a time (--offset to continue)
3
+ // image -> saved as a local file (--to <folder or file>, default: current folder)
4
+ // link -> a download address valid for 5 minutes (with --to the file is downloaded for you)
5
+ // The platform picks the form (form=auto); --form text|image|link asks for one. Exit codes: 0 done / 1 refused or failed / 2 arguments.
6
+ import fsp from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { apiGet, normalizeRemotePath, SyncError } from './space-sync.js';
9
+ import { humanSize } from './media-upload.js';
10
+
11
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ export const READ_FORMS = ['auto', 'text', 'image', 'link'];
13
+
14
+ /** Find the id of the file at `spacePath` by listing its folder (the read interface takes a node id). */
15
+ async function resolveFileId(ctx, spacePath) {
16
+ const clean = normalizeRemotePath(spacePath);
17
+ const cut = clean.lastIndexOf('/');
18
+ const dir = cut >= 0 ? clean.slice(0, cut) : '';
19
+ const name = cut >= 0 ? clean.slice(cut + 1) : clean;
20
+ let cursor = null;
21
+ for (let page = 0; page < 200; page += 1) {
22
+ const q = new URLSearchParams({ limit: '1000' });
23
+ if (dir) q.set('path', dir);
24
+ if (cursor) q.set('cursor', cursor);
25
+ const r = await apiGet(ctx, `/api/v1/space/nodes?${q}`);
26
+ for (const n of r.items || []) {
27
+ if (n.name === name) {
28
+ if (n.kind === 'folder') throw new SyncError('not_a_file', `「${clean}」是文件夹,不是文件。要拿整个文件夹请用 anytowork space pull。`, 1);
29
+ return n.id;
30
+ }
31
+ }
32
+ cursor = r.next_cursor || null;
33
+ if (!cursor) break;
34
+ }
35
+ throw new SyncError('node_not_found', `空间里没有找到「${clean}」。用 anytowork space ls 看看路径。`, 1);
36
+ }
37
+
38
+ /** A local path that does not overwrite anything: name.png, then name (1).png ... */
39
+ async function freePath(abs) {
40
+ const ext = path.extname(abs);
41
+ const stem = abs.slice(0, abs.length - ext.length);
42
+ for (let i = 0; i < 1000; i += 1) {
43
+ const cand = i === 0 ? abs : `${stem} (${i})${ext}`;
44
+ try { await fsp.access(cand); } catch { return cand; }
45
+ }
46
+ return abs;
47
+ }
48
+
49
+ /** --to may be a folder (keep the name) or a file path; no --to means the current folder. */
50
+ async function targetPath(to, name) {
51
+ const safe = path.basename(String(name || 'file'));
52
+ if (!to) return freePath(path.resolve(safe));
53
+ const abs = path.resolve(to);
54
+ let isDir = false;
55
+ try { isDir = (await fsp.stat(abs)).isDirectory(); } catch { isDir = /[\\/]$/.test(String(to)); }
56
+ if (isDir) { await fsp.mkdir(abs, { recursive: true }); return freePath(path.join(abs, safe)); }
57
+ await fsp.mkdir(path.dirname(abs), { recursive: true });
58
+ return abs;
59
+ }
60
+
61
+ /**
62
+ * @param {object} c { positionals, flags, json, log, ctx }
63
+ * @param {Function} usage prints an argument problem and returns exit code 2
64
+ * @returns {Promise<number>} exit code
65
+ */
66
+ export async function runSpaceRead(c, usage) {
67
+ const target = c.positionals[2];
68
+ const form = c.flags.form == null ? 'auto' : String(c.flags.form).toLowerCase();
69
+ if (!target) return usage(c, '用法:anytowork space read <路径> [--form text|image|link] [--offset <n>] [--to <本地位置>]。更多见 anytowork space --help');
70
+ if (!READ_FORMS.includes(form)) return usage(c, '--form 只能写 text、image 或 link(不写则由平台按文件类型选)。');
71
+ const offset = c.flags.offset;
72
+ if (offset != null && (!Number.isInteger(offset) || offset < 0)) return usage(c, '--offset 要写 0 或更大的整数。');
73
+ const id = UUID_RE.test(target) ? target : await resolveFileId(c.ctx, target);
74
+ const q = new URLSearchParams({ form });
75
+ if (offset != null) q.set('offset', String(offset));
76
+ if (c.flags.limit != null && Number.isInteger(c.flags.limit) && c.flags.limit > 0) q.set('limit', String(c.flags.limit));
77
+ const r = await apiGet(c.ctx, `/api/v1/space/files/${encodeURIComponent(id)}/read?${q}`);
78
+
79
+ if (r.form === 'image') {
80
+ const dest = await targetPath(c.flags.to, r.name);
81
+ await fsp.writeFile(dest, Buffer.from(r.base64 || '', 'base64'));
82
+ if (c.json) { c.log(JSON.stringify({ ok: true, form: 'image', name: r.name, mime: r.mime, size_bytes: r.size_bytes, saved_to: dest }, null, 2)); return 0; }
83
+ c.log(`这是图片「${r.name}」(${humanSize(r.size_bytes || 0)}),已存到本地:${dest}`);
84
+ return 0;
85
+ }
86
+ if (r.form === 'link') {
87
+ let saved = null;
88
+ if (c.flags.to) {
89
+ const fetchFn = c.ctx.putFetch || c.ctx.fetchImpl || globalThis.fetch;
90
+ const res = await fetchFn(r.signed_get_url);
91
+ if (!res.ok) throw new SyncError('download_failed', `下载失败(${res.status}),可以重新运行同一条命令拿新的地址。`, 1);
92
+ saved = await targetPath(c.flags.to, r.name);
93
+ await fsp.writeFile(saved, Buffer.from(await res.arrayBuffer()));
94
+ }
95
+ if (c.json) { c.log(JSON.stringify({ ok: true, form: 'link', name: r.name, mime: r.mime, size_bytes: r.size_bytes, signed_get_url: r.signed_get_url, expires_in: r.expires_in, saved_to: saved }, null, 2)); return 0; }
96
+ if (saved) { c.log(`「${r.name}」(${humanSize(r.size_bytes || 0)})已下载到:${saved}`); return 0; }
97
+ c.log(`「${r.name}」(${humanSize(r.size_bytes || 0)})这类文件直接给下载地址,${Math.round((r.expires_in || 300) / 60)} 分钟内有效,直接 GET 即可,不用再带登录信息:`);
98
+ c.log(r.signed_get_url);
99
+ return 0;
100
+ }
101
+ // text (svg also comes as text)
102
+ if (c.json) { c.log(JSON.stringify({ ok: true, ...r }, null, 2)); return 0; }
103
+ c.log(r.content || '');
104
+ if (r.next_offset != null) {
105
+ c.log(`\n—— 还没读完:已读到第 ${r.next_offset} 个字符,共 ${r.total_chars} 个。继续读下一页:anytowork space read ${target} --offset ${r.next_offset}`);
106
+ }
107
+ return 0;
108
+ }