@anytowork/cli 0.12.72 → 0.12.74

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.
@@ -1,685 +0,0 @@
1
- // anytowork chat — talk in the owner's workbench (PRD 26 §7.4, contract v0.32 §6.1).
2
- //
3
- // chat list the groups / sessions you are in, and which have something unread
4
- // chat read <session> [--before <msg>] what to handle now (everything since you last read, plus the
5
- // message that woke you); reading counts as read, and the session
6
- // becomes this Agent's "current session" (see chat-state.js)
7
- // chat send <session> "<text>" [--reply <msg>] [--file <space path>]... [--mention <member>]... [--wip]
8
- // reply; by default this ends your round. --wip = "still working,
9
- // just letting you know" (the round stays open)
10
- // chat result <session> [--file <space path>]...
11
- // hand in the result: a "done" message, ends this piece of work (v0.33);
12
- // without --file the platform lists what you changed
13
- // chat ask <session> --title "<question>" --option "<choice>"... [--recommend <n>]
14
- // chat progress <session> "<one line>" progress note for the owner's Agent map (not a chat message)
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)
18
- //
19
- // The platform answers refusals with a stable code; this file turns them into plain words. The CLI never decides
20
- // business rules itself (limits, who may post where): it only checks that the arguments are present.
21
-
22
- import { randomUUID } from 'node:crypto';
23
- import { authedGetWithRefresh, authedPostWithRefresh, authedPatchWithRefresh, authedPutWithRefresh } from './api.js';
24
- import { EXIT_HUMAN_REQUIRED, EXIT_NEW_MESSAGES, isHumanRequiredError, humanRequiredHint } from './exit-reasons.js';
25
- import { setupHintLines } from './setup-hints.js';
26
- import { replyHintLine, hasUnhandledFromOthers } from './reply-hint.js';
27
- import { renderWbRules, boundaryLines, identityText } from './wb-rules-text.js';
28
- import { readCurrentSession, setCurrentSession, touchCurrentSession, clearCurrentSession, readCurrentHire } from './chat-state.js';
29
-
30
- export const CHAT_HELP = `anytowork chat — 在主人的工作台里收发消息 / talk in the owner's workbench
31
-
32
- chat list 你所在的群和会话,哪些有没读的 / your sessions and what is unread
33
- chat read <会话> [--before <消息编号>] 读这次要处理的内容:上次读过之后的消息 + 叫醒你的那条 + 群的工作空间
34
- 读了就算已读,并把这个会话记成「当前会话」
35
- / read what is new (counts as read; becomes the current session)
36
- chat send <会话> "<内容>" 回复。默认表示这一轮做完了 / reply; by default this ends your round
37
- [--reply <消息编号>] 回复某一条 / reply to one message
38
- [--file <空间路径>]... 带上空间里的文件(本地文件先 anytowork space push)
39
- / attach files already in the space (push local files first)
40
- [--mention <成员名>]... @ 群里的成员(all = 所有 Agent,owner = 主人)
41
- / mention members (all = every Agent, owner = the owner)
42
- [--wip] 干到一半先说一声:这一轮还没做完 / still working, the round stays open
43
- [--ignore-new] 群里有你没读过的新消息时,平台会先拦下这条(没发出,输出里列出新消息);读完仍要发,加这个照发
44
- / the platform holds the message (not sent, the new ones are listed) when others wrote since you last read; add this to send anyway
45
- [--stdin] 内容从标准输入读(适合多行)/ read the text from stdin
46
- 聊天支持加粗、标题、有序/无序列表、行内代码和代码块;表格在气泡里按行拆开显示;内容很长就先落成文件再发。
47
- The chat renders bold, headings, ordered / bullet lists, inline code and code blocks; a table is shown row by row in the bubble; send very long content as a file.
48
- chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>]
49
- 发选择题(2–6 个选项;选项可写「文字::说明」)
50
- / ask the owner to choose (2–6 options; "label::note")
51
- chat result <会话> [--file <空间路径>]... 交成果:发一条「已完成」,这件事算做完;不写 --file 时平台会列出你这次改过和新建的文件
52
- / hand in the result (a "done" message); without --file the platform lists what you changed
53
- chat progress <会话> "<一句话>" 报进度:记进工作轨迹给主人看,不进聊天,这一轮仍在进行
54
- / progress note for the owner (not a chat message)
55
- chat plan <会话> "<第一步|第二步|第三步>" [--done 1,2] [--doing 3]
56
- 三步以上的活,开工前先把计划说给主人看(3 到 8 步,用 | 隔开);做完一步用 --done 勾掉,同时做几步都标 --doing
57
- / show your plan first (3 to 8 steps split by |); tick a step with --done, mark parallel ones with --doing
58
- chat need-workspace <会话> "<为什么>" 私聊还没选工作空间时,请主人选一个 / ask the owner to pick a workspace
59
- chat recall <消息编号> 撤回你自己发的一条消息(发出后 2 分钟内;撤不了就发一条更正)
60
- / take back one of your own messages (within 2 minutes; otherwise send a correction)
61
- chat group rename <群> "<新名字>" 改群名(只限你主人的群)/ rename the group (your owner's group only)
62
- chat group describe <群> "<描述>" 改群描述(200 字内)/ change the group description (up to 200 characters)
63
- chat group add-agent <群> <Agent编号>... 把你主人名下的其他 Agent 拉进群 / add your owner's other Agents
64
- 移除成员、解散、移交、改可见性只有群主本人能做(退出码 5)
65
- / removing members, dissolving, handing over, visibility: the group owner only (exit 5)
66
-
67
- 回复默认表示这一轮做完;干到一半先说一声用 --wip,报进度用 chat progress;整件事做完了,用 chat result 交成果。
68
- 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.
69
- 读、报进度、--wip 都算你在干活;隔几分钟没有动作,主人那边会显示「还没回」。
70
- Reading, progress notes and --wip all count as working; after a few quiet minutes the owner sees "Not replied yet".
71
- 读了消息就要有动作:回复、--wip 或 progress,三选一。只读不动,平台会再叫你一次。主人问你的问题,必须用聊天里的回复(chat send)回答;progress 主人看不到,不算回答。
72
- Once you read a message, act on it: reply, --wip or progress, pick one. If you only read, the platform will call you once more. When your owner asks you something, answer with a reply in the chat (chat send); your owner cannot see progress, so it does not count as an answer.
73
- 命令返回里如果提示「另有 N 条新消息」,说明主人又说话了:必须先 chat read 读完,再决定原来的活继续做还是改方向,不要等手头这一步做完再读。订单里有补充需求或追问进度,同样先读再动。
74
- If the answer of a command says there are N new messages, your owner has said more: you must run chat read first, then decide whether to carry on with the original work or change course. Do not wait until the step in hand is done. The same goes for a supplement or a progress question on an order: read first, then act.
75
- 做事时用到的空间文件,anytowork space pull / push 会自动记到「当前会话」里;要指定别的会话加 --session <会话>,
76
- 不想记进任何会话加 --session none。
77
- Space pulls / pushes are recorded under the current session; use --session <session> or --session none.
78
- 所有 chat 命令支持 --json。 All chat commands accept --json.`;
79
-
80
- const SUBS = new Set(['list', 'read', 'send', 'result', 'ask', 'progress', 'need-workspace', 'recall', 'group', 'plan']);
81
-
82
- export function isChatCommand(command) {
83
- return typeof command === 'string' && command.startsWith('chat:');
84
- }
85
-
86
- // ---------------------------------------------------------------- refusals in plain words
87
-
88
- /** The refusal the platform sent: { code, message, vars } (FastAPI may wrap it in `detail`). */
89
- function refusalOf(e) {
90
- const b = e && e.body && typeof e.body === 'object' ? e.body : null;
91
- if (!b) return null;
92
- const body = b.detail && typeof b.detail === 'object' && b.detail.error ? b.detail : b;
93
- const code = typeof body.error === 'string' ? body.error : null;
94
- if (!code) return null;
95
- return { code, message: body.message || '', vars: body.vars && typeof body.vars === 'object' ? body.vars : {} };
96
- }
97
-
98
- const NOT_OPEN = '主人还没开通工作台,暂时用不了 chat 命令。订单相关的事照常用 anytowork poll 收。';
99
-
100
- const REFUSALS = {
101
- feature_not_open: () => NOT_OPEN,
102
- wb_not_found: () => '找不到这个会话,或你已经不在这个群里了。用 anytowork chat list 看看你现在在哪些会话里。',
103
- wb_archived: (v) => `这个${v.scope === 'group' ? '群' : '会话'}已归档,只能读、不能发。主人发消息后会自动取消归档。`,
104
- wb_trashed: () => '这个会话在回收站里,主人恢复之前不能发消息。',
105
- wb_msg_too_long: (v) => `内容太长了(最多 ${v.max} 字)。可以拆成几条发,或把长内容写成文件,anytowork space push 后用 --file 引用。`,
106
- wb_too_many_files: (v) => `一条消息最多带 ${v.max} 个文件,请分几条发。`,
107
- wb_rate_limited: (v) => `发得太快了,${v.retry_after ? `${v.retry_after} 秒后` : '稍后'}再试。`,
108
- wb_file_not_found: (v) => `空间里没有这个文件${v.path ? `:${v.path}` : ''}。本地文件请先 anytowork space push 放进空间,再用空间里的路径引用(文件夹不能当附件)。`,
109
- wb_mention_unknown: (v) => `群里没有叫「${v.name || ''}」的成员。${Array.isArray(v.candidates) && v.candidates.length ? `群里有:${v.candidates.join('、')}。` : ''}@ 所有 Agent 写 all,@ 主人写 owner。`,
110
- wb_reply_unknown: () => '要回复的那条消息不在这个会话里,请核对消息编号(chat read 里 # 后面的数字)。',
111
- wb_dm_fixed: () => '只有私聊需要请主人选工作空间;群在建的时候就绑好了工作空间,chat read 里能看到路径。',
112
- wb_workspace_missing: () => '这个群绑定的工作空间文件夹已经被删了,请告诉主人在群设置里换一个。',
113
- wb_ask_closed: () => '这道选择题已经答过了。',
114
- // v0.38.x: the workbench plan card (PRD 26 plan card design); the first two never make the Agent retry
115
- wb_plan_steps: () => '计划要 3 到 8 步。',
116
- wb_plan_text: () => '每一步都要有内容,而且不超过 60 字。',
117
- wb_plan_missing: () => '这一轮还没发计划,先把 3 到 8 步发一份。',
118
- wb_plan_closed: () => '这一段工作已经结束了,计划不用再更新。',
119
- // v0.35.0: neutral on purpose, the platform gives no reason (PRD 09/06 BR-闸.15)
120
- agent_gate_file_not_sent: () => '文件没有发出去,这条消息也没有发出。',
121
- // v0.37 PA-10: recall (Agent only, own message, 2 minutes)
122
- wb_recall_forbidden: () => '这条消息撤回不了:只能撤回你自己发的普通消息,选择题、成果和人发的消息都不行。发错了就再发一条更正。',
123
- wb_recall_expired: (v) => `已经超过 ${v.window_sec ? Math.round(Number(v.window_sec) / 60) : 2} 分钟,撤回不了了。发一条更正就行。`,
124
- // v0.37 PA-11: group changes an Agent may make
125
- wb_agent_not_yours: () => '只能拉你主人名下、还在用的其他 Agent。请核对 Agent 编号。',
126
- wb_member_limit: () => '这个群的成员已经满了,拉不进来。',
127
- wb_agent_group_name: () => '群名不能为空,也不能太长。',
128
- };
129
-
130
- /** Print a platform refusal (or rethrow what is not one). Returns the exit code. */
131
- function reportRefusal(c, e) {
132
- if (e && e.upgradeRequired) throw e;
133
- const r = refusalOf(e);
134
- if (!r) throw e;
135
- // v0.37: steps only the person may do (a group Agent may not manage, a credential of another Agent): one fixed
136
- // sentence and exit code 5, so the Agent tells its owner instead of trying again.
137
- if (isHumanRequiredError(r.code)) {
138
- const hint = r.code === 'agent_mismatch' ? (e.message || humanRequiredHint(r.code)) : humanRequiredHint(r.code);
139
- if (c.json) c.log(JSON.stringify({ ok: false, error: 'human_required', code: r.code, message: hint, ...r.vars }));
140
- else c.err(hint);
141
- return EXIT_HUMAN_REQUIRED;
142
- }
143
- const text = REFUSALS[r.code] ? REFUSALS[r.code](r.vars) : `${r.message || '平台拒绝了这次操作'}【${r.code}】`;
144
- if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text, ...r.vars }));
145
- else c.err(text);
146
- return 1;
147
- }
148
-
149
- function usage(c, text) {
150
- if (c.json) c.log(JSON.stringify({ ok: false, error: 'bad_arguments', message: text }));
151
- else c.err(text);
152
- return 2;
153
- }
154
-
155
- // ---------------------------------------------------------------- platform calls
156
-
157
- const BASE = '/api/v1/agent/chat';
158
- const enc = encodeURIComponent;
159
-
160
- function get(c, pathAndQuery) {
161
- return authedGetWithRefresh(c.baseUrl, `${BASE}${pathAndQuery}`, c.credOpts, { fetchImpl: c.fetchImpl });
162
- }
163
-
164
- function patch(c, pathStr, body) {
165
- return authedPatchWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, { fetchImpl: c.fetchImpl });
166
- }
167
-
168
-
169
- // PUT has no idempotency header (contract 4.0): `client_key` in the body is what makes a retry harmless.
170
- function put(c, pathStr, body) {
171
- return authedPutWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, { fetchImpl: c.fetchImpl });
172
- }
173
- function post(c, pathStr, body) {
174
- return authedPostWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, c.flags.idempotencyKey || null, { fetchImpl: c.fetchImpl });
175
- }
176
-
177
- // ---------------------------------------------------------------- what the Agent sees
178
-
179
- /** "品牌升级 / 首页改版", or "私聊 / 首页改版". */
180
- export function placeText(group, session) {
181
- const g = group || {};
182
- const s = session || {};
183
- const head = g.kind === 'dm' ? '私聊' : (g.name || '群聊');
184
- return s.title ? `${head} / ${s.title}` : head;
185
- }
186
-
187
- function senderText(sender) {
188
- const s = sender || {};
189
- if (s.is_me) return '你';
190
- if (s.type === 'system') return '系统';
191
- // v0.35.0: the relation the server sent decides the words; a person who is not the owner is never called "主人"
192
- // (the server sends type "member" for them; old CLIs fall through to the name below, which already carries the identity).
193
- const byRelation = identityText(s);
194
- if (byRelation) return byRelation;
195
- if (s.type === 'member') return s.name || '群成员';
196
- if (s.type === 'user') return `主人${s.name ? `(${s.name})` : ''}`;
197
- if (s.type === 'system') return '系统';
198
- return s.name || 'Agent';
199
- }
200
-
201
- const SYS_TEXT = {
202
- 'wb.sys.workspace_changed': (v) => `工作空间改为「${v.name || ''}」`,
203
- 'wb.sys.leader_changed': (v) => `${v.name || ''} 成为群主`,
204
- 'wb.sys.member_left': (v) => `${v.name || ''} 已${v.why === 'unbound' ? '解绑' : '被移出群聊'}`,
205
- 'wb.sys.member_joined': (v) => `${Array.isArray(v.names) ? v.names.join('、') : (v.names || '')} 加入了群聊`,
206
- 'wb.sys.chain_limited': (v) => `Agent 之间已连着说了 ${v.n} 条,主人说一句你们再继续`,
207
- 'wb.sys.chain_changed': (v) => `Agent 连续对话上限改为 ${v.n} 条`,
208
- 'wb.sys.pick_workspace': (v) => (v.resolved ? '主人已选好工作空间' : `等主人选一个工作空间${v.text ? `(理由:${v.text})` : ''}`),
209
- 'wb.sys.group_renamed': (v) => `群名改为「${v.name || ''}」`,
210
- 'wb.sys.session_renamed': (v) => `会话名改为「${v.name || ''}」`,
211
- // v0.33: the owner took back one piece of an Agent's work. Zero counts are left out ("还原 2 个、恢复 1 个文件").
212
- // Said to the Agent it belongs to (sys.about_me) in PRD 26 7.4 words; for anyone else it is a neutral line.
213
- 'wb.sys.segment_reverted': (v, sys) => {
214
- const parts = [];
215
- if (Number(v.mod) > 0) parts.push(`还原 ${Number(v.mod)} 个`);
216
- if (Number(v.add) > 0) parts.push(`移除 ${Number(v.add)} 个`);
217
- if (Number(v.del) > 0) parts.push(`恢复 ${Number(v.del)} 个`);
218
- const detail = parts.length ? `(${parts.join('、')}文件)` : '';
219
- return sys && sys.about_me === true
220
- ? `主人退回了你在这里的一次改动${detail},动手前先拉一次最新`
221
- : `主人退回了${v.agent_name ? ` ${v.agent_name} ` : '一个 Agent '}的一次改动${detail}`;
222
- },
223
- };
224
-
225
- function fileLines(files, ind) {
226
- return (files || []).map((f) => (f.state === 'deleted' || !f.path
227
- ? `${ind}📎 ${f.name || ''}(已从空间删除)`
228
- : `${ind}📎 ${f.path}`));
229
- }
230
-
231
- /** The lines of one message in `chat read`. */
232
- export function messageLines(m, { trigger = null } = {}) {
233
- const lines = [];
234
- const at = m.created_at ? ` ${m.created_at}` : '';
235
- const mark = trigger != null && m.id === trigger ? ' ← 这条叫醒了你' : '';
236
- if (m.kind === 'system') {
237
- const sys = m.sys || {};
238
- const f = SYS_TEXT[sys.key];
239
- lines.push(`#${m.id}${at} (${f ? f(sys.vars || {}, sys) : sys.key || '系统消息'})${mark}`);
240
- return lines;
241
- }
242
- const reply = m.reply_to && m.reply_to.id
243
- ? ` ↳回复 #${m.reply_to.id}${m.reply_to.state === 'ok' ? `(${m.reply_to.sender_name || ''}:${m.reply_to.excerpt || ''})` : '(原消息已不可见)'}`
244
- : '';
245
- const mentions = (m.mentions || []).map((x) => (x.type === 'all' ? '@所有 Agent' : x.type === 'owner' ? '@主人' : `@${x.name || ''}`));
246
- // v0.37 PA-10: a message its Agent took back keeps only its number
247
- if (m.recalled) { lines.push(`#${m.id}${at} (这条消息已被撤回)${mark}`); return lines; }
248
- const wip = m.wip ? '(还在做)' : (m.kind === 'result' ? '(交成果)' : '');
249
- const mine = m.mine === true ? ' 【@你】' : ''; // v0.37 PA-09: it mentions you or answers you
250
- lines.push(`#${m.id}${at} ${senderText(m.sender)}${wip}${reply}${mentions.length ? ` ${mentions.join(' ')}` : ''}${mine}:${mark}`);
251
- if (m.body) for (const l of String(m.body).split('\n')) lines.push(` ${l}`);
252
- // v0.35.0: neutral note on a message of yours that did not get through; warning on a suspicious one
253
- if (m.gate_delivery === 'not_delivered') lines.push(' (这条没有送达对方)');
254
- if (m.boundary_warn === true) for (const l of boundaryLines({ warn: true })) lines.push(` ⚠ ${l}`);
255
- if (m.kind === 'ask' && m.ask) {
256
- const a = m.ask;
257
- lines.push(` 【选择题】${a.title || ''}`);
258
- (a.options || []).forEach((o, i) => {
259
- lines.push(` ${i + 1}. ${o.label || ''}${a.recommend === i + 1 ? '(推荐)' : ''}${o.desc ? ` — ${o.desc}` : ''}`);
260
- });
261
- if (a.answer) {
262
- const pick = a.answer.option != null && a.options && a.options[a.answer.option] ? a.options[a.answer.option].label : null;
263
- lines.push(` ${a.answer.by || '主人'} 选了:${pick || a.answer.text || ''}`);
264
- } else {
265
- lines.push(' (还没回答)');
266
- }
267
- }
268
- for (const l of fileLines(m.files, ' ')) lines.push(l);
269
- return lines;
270
- }
271
-
272
- export function formatRead(data, sid, env = process.env) {
273
- const lines = [];
274
- const members = (data.members || []).map((x) => {
275
- const role = x.is_me ? '你' : (x.type === 'user' ? '主人' : (x.role === 'leader' ? '群主' : ''));
276
- // v0.37 PA-02: a member who may only see the message much later is marked (only "away"; no minutes are given)
277
- // v0.37.7: "unset" (never set up any way of being woken) is just as unreachable for now
278
- const away = (x.reach_kind === 'away' || x.reach_kind === 'unset') && !x.is_me ? '(暂时联系不上)' : '';
279
- return (role && !x.is_me ? `${x.name}(${role})` : (x.is_me ? `${x.name}(你)` : x.name)) + away;
280
- });
281
- const ro = (data.group && data.group.archived) || (data.session && data.session.archived) ? '(已归档,只能读不能发)' : '';
282
- lines.push(`「${placeText(data.group, data.session)}」${ro}${members.length ? ` 成员:${members.join('、')}` : ''}`);
283
- if (data.workspace && data.workspace.path) {
284
- lines.push(`这个群的文件放在空间「${data.workspace.path}」,拉到本地:anytowork space pull ${quoteArg(data.workspace.path)} --to <本地目录>;别处的东西不要带进来。`);
285
- }
286
- if (data.group && data.group.description) lines.push(`群描述:${data.group.description}`);
287
- if (Number(data.skipped) > 0) {
288
- // v0.37 PA-09: unread messages that did not fit; those that mention you or answer you were kept first
289
- lines.push(`(还有 ${data.skipped} 条更早的未读消息没有提供,@你和回你的已优先带上;要看:anytowork chat read ${sid} --before ${data.more_cmd_before})`);
290
- } else if (Number(data.earlier) > 0) {
291
- lines.push(`(更早还有 ${data.earlier} 条没给,要看:anytowork chat read ${sid} --before ${data.more_cmd_before})`);
292
- }
293
- const msgs = data.messages || [];
294
- if (!msgs.length) lines.push('(没有新消息)');
295
- for (const m of msgs) for (const l of messageLines(m, { trigger: data.trigger_msg_id })) lines.push(l);
296
- lines.push('');
297
- lines.push(`回复:anytowork chat send ${sid} "<内容>"(默认表示这一轮做完;干到一半先说一声加 --wip)`);
298
- lines.push(`报进度:anytowork chat progress ${sid} "<一句话>"`);
299
- lines.push(`整件事做完了:anytowork chat result ${sid}(交成果;只是回答问题不用)`);
300
- // v0.33.2: workbench rules hint (absent on an old server: print nothing)
301
- const rules = renderWbRules(data.rules);
302
- if (rules) { lines.push(''); lines.push(rules); }
303
- // v0.37: the platform's "settings after connecting" reminder (at most once a day per item)
304
- const hint = setupHintLines(data.setup_hint, env);
305
- if (hint.length) { lines.push(''); for (const l of hint) lines.push(l); }
306
- // v0.35.0: boundary words (full first time in a session, then one line); nothing from an old server
307
- const boundary = boundaryLines({ rules: data.rules });
308
- if (boundary.length) { if (!rules) lines.push(''); for (const l of boundary) lines.push(l); }
309
- return lines.join('\n');
310
- }
311
-
312
- function quoteArg(s) {
313
- return /^[\w./-]+$/.test(s) ? s : `"${String(s).replace(/"/g, '\\"')}"`;
314
- }
315
-
316
- function formatList(data) {
317
- const items = data.items || [];
318
- if (!items.length) return '你还不在任何群或私聊里。主人在工作台和你私聊或把你拉进群后,这里就会出现。';
319
- const lines = ['你所在的会话(最近有消息的在前):'];
320
- for (const it of items) {
321
- const tags = [];
322
- if (it.pending_wake) tags.push('等你处理');
323
- if (Number(it.unread) > 0) tags.push(`未读 ${it.unread}`);
324
- if ((it.group && it.group.archived) || (it.session && it.session.archived)) tags.push('已归档');
325
- lines.push(` • ${placeText(it.group, it.session)}${tags.length ? `(${tags.join(',')})` : ''} 会话 ${it.session && it.session.id}`);
326
- }
327
- if (data.next_cursor) lines.push(`(还有更多:anytowork chat list --cursor ${data.next_cursor})`);
328
- lines.push('读一个会话:anytowork chat read <会话>');
329
- return lines.join('\n');
330
- }
331
-
332
- // ---------------------------------------------------------------- commands
333
-
334
- async function runList(c) {
335
- const qs = new URLSearchParams();
336
- if (c.flags.cursor) qs.set('cursor', c.flags.cursor);
337
- const data = await get(c, `/sessions${qs.toString() ? `?${qs}` : ''}`);
338
- c.log(c.json ? JSON.stringify(data, null, 2) : formatList(data));
339
- return 0;
340
- }
341
-
342
- /** v0.37.7 (B7): the platform may add `news` ("N new messages elsewhere / since") to an answer; print its one line. */
343
- export function newsLine(data) {
344
- const n = data && data.news;
345
- return n && typeof n.hint === 'string' && n.hint.trim() ? n.hint.trim() : '';
346
- }
347
-
348
- async function runRead(c, sid) {
349
- const before = c.flags.before;
350
- if (before != null && !/^\d+$/.test(String(before))) return usage(c, '--before 要写消息编号(数字)。');
351
- const data = await get(c, `/sessions/${enc(sid)}/read${before != null ? `?before=${enc(before)}` : ''}`);
352
- // Reading new messages makes this the current session; looking back (--before) only keeps the clock alive.
353
- if (before == null) setCurrentSession(data.current_session || sid, c.credOpts, c.nowMs(), data.hire_id || null);
354
- else touchCurrentSession(c.credOpts, c.nowMs());
355
- // v0.12.41: unhandled messages from others and no local listener: one platform line, last
356
- const hint = !c.json && before == null && hasUnhandledFromOthers(data.messages) ? replyHintLine(c.credOpts, c.env, c.nowMs()) : '';
357
- c.log(c.json ? JSON.stringify(data, null, 2) : [formatRead(data, sid, c.env), newsLine(data), hint].filter(Boolean).join('\n'));
358
- return 0;
359
- }
360
-
361
- async function bodyText(c, positional) {
362
- if (c.flags.stdin) return c.readStdin ? c.readStdin() : '';
363
- return positional;
364
- }
365
-
366
- async function runSend(c, sid, positional) {
367
- const text = await bodyText(c, positional);
368
- const files = c.flags.files || [];
369
- if ((text == null || String(text).trim() === '') && !files.length) {
370
- return usage(c, '用法:anytowork chat send <会话> "<内容>" [--reply <消息编号>] [--file <空间路径>]... [--mention <成员名>]... [--wip]');
371
- }
372
- const replyTo = c.flags.reply != null ? Number(c.flags.reply) : null;
373
- if (c.flags.reply != null && !Number.isInteger(replyTo)) return usage(c, '--reply 要写消息编号(数字)。');
374
- const body = {
375
- client_key: c.flags.idempotencyKey || randomUUID(),
376
- body: text == null ? '' : String(text),
377
- reply_to: replyTo,
378
- files,
379
- mentions: c.flags.mentions || [],
380
- wip: !!c.flags.wip,
381
- };
382
- if (c.flags.ignoreNew) body.ignore_new = true; // v0.37 PA-03: send even though others wrote since you last read
383
- let data;
384
- try {
385
- data = await post(c, `/sessions/${enc(sid)}/messages`, body);
386
- } catch (e) {
387
- const r = refusalOf(e);
388
- if (r && r.code === 'wb_new_messages') return reportNewMessages(c, sid, e);
389
- throw e;
390
- }
391
- // v0.33 (D369): a reply, with or without --wip, keeps the current session (a quick "got it" must not make the
392
- // pushes that follow fall out of this piece of work). Only `chat result`, or 2 hours without a chat command, ends it.
393
- touchCurrentSession(c.credOpts, c.nowMs());
394
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
395
- const lines = [data.gate_delivery === 'not_delivered'
396
- ? `这条消息没有送达对方(消息 #${data.message && data.message.id})。`
397
- : `已发出(消息 #${data.message && data.message.id})。`];
398
- const woke = (data.woke || []).map((w) => w.agent_name).filter(Boolean);
399
- if (woke.length) lines.push(`叫醒了:${woke.join('、')}。`);
400
- for (const n of data.notices || []) {
401
- const code = typeof n === 'string' ? n : n && n.code;
402
- const v = (n && typeof n === 'object' && n.vars) || data.notice_vars || {};
403
- if (code === 'wb_chain_limit') lines.push(`Agent 之间已连着说了${v.n ? ` ${v.n} ` : ''}条,这次没有叫醒别的 Agent;主人说一句你们再继续。`);
404
- }
405
- if (c.flags.wip) lines.push('这一轮还在进行中;做完后再回复一次(不带 --wip)。');
406
- else if (data.subtask && data.subtask.status === 'done') lines.push(`这一轮已结束。整件事做完了,请用 anytowork chat result ${sid} 交成果。`);
407
- if (newsLine(data)) lines.push(newsLine(data));
408
- c.log(lines.join('\n'));
409
- return 0;
410
- }
411
-
412
- /**
413
- * v0.37 PA-03: the platform did NOT store the message: others wrote in this group since you last read. Print what they
414
- * wrote as the tool result, so the Agent can decide: read, then send again (or not at all), or send anyway.
415
- */
416
- function reportNewMessages(c, sid, e) {
417
- const b = (e.body && e.body.detail && e.body.detail.error ? e.body.detail : e.body) || {};
418
- const list = Array.isArray(b.new_messages) ? b.new_messages : [];
419
- const count = Number((b.vars && b.vars.count) != null ? b.vars.count : list.length) || list.length;
420
- if (c.json) {
421
- 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 }));
422
- return EXIT_NEW_MESSAGES;
423
- }
424
- const lines = [`这条消息没有发出:你上次读过之后,群里又有 ${count} 条别人发的新消息:`];
425
- for (const m of list) {
426
- const who = (m.sender && m.sender.name) || (m.sender && m.sender.type === 'agent' ? '另一个 Agent' : '群成员');
427
- lines.push(` #${m.id}${m.created_at ? ` ${m.created_at}` : ''} ${who}:${m.excerpt || ''}`);
428
- }
429
- if (count > list.length) lines.push(` …(只列出最新 ${list.length} 条)`);
430
- lines.push(`先读一下:anytowork chat read ${sid}。读完看看你要说的还有没有必要、有没有已经被回答;`
431
- + '还要说就重新发一次(读过之后不会再被拦);确定不管新消息、照发不误,加 --ignore-new。');
432
- c.err(lines.join('\n'));
433
- return EXIT_NEW_MESSAGES;
434
- }
435
-
436
- /** `chat recall <message>` (v0.37, PA-10): take back one of my own messages within the window. */
437
- async function runRecall(c, mid) {
438
- if (!/^\d+$/.test(String(mid))) return usage(c, '用法:anytowork chat recall <消息编号>(chat read 里 # 后面的数字)');
439
- const data = await post(c, `/messages/${enc(mid)}/recall`, {});
440
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
441
- c.log(`已撤回消息 #${mid},群里会显示「该 Agent 撤回了一条消息」。`);
442
- return 0;
443
- }
444
-
445
- /** `chat group rename|describe|add-agent` (v0.37, PA-11): only what an Agent may do to a group it owns. */
446
- async function runGroup(c, positionals) {
447
- const op = positionals[2];
448
- const gid = positionals[3];
449
- const rest = positionals.slice(4);
450
- const text = c.flags.stdin && c.readStdin ? await c.readStdin() : rest[0];
451
- if (op === 'rename' || op === 'describe') {
452
- const key = op === 'rename' ? 'name' : 'description';
453
- if (!gid || text == null || (op === 'rename' && !String(text).trim())) {
454
- return usage(c, op === 'rename' ? '用法:anytowork chat group rename <群编号> "<新名字>"' : '用法:anytowork chat group describe <群编号> "<描述>"(200 字内;写空字符串就是清空)');
455
- }
456
- let data;
457
- try { data = await patch(c, `/groups/${enc(gid)}`, { [key]: String(text) }); } catch (e) { return groupRefusal(c, e); }
458
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
459
- c.log(op === 'rename' ? `群名已改为「${data.name || text}」,群里留了一行记录。` : '群描述已更新,群里留了一行记录。');
460
- return 0;
461
- }
462
- if (op === 'add-agent') {
463
- const ids = rest.filter((x) => x && !String(x).startsWith('--'));
464
- if (!gid || !ids.length) return usage(c, '用法:anytowork chat group add-agent <群编号> <Agent编号>...(只能拉你主人名下的其他 Agent)');
465
- let data;
466
- try { data = await post(c, `/groups/${enc(gid)}/members`, { agent_ids: ids }); } catch (e) { return groupRefusal(c, e); }
467
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
468
- c.log(`已把 ${ids.length} 个 Agent 拉进群「${(data && data.name) || gid}」。`);
469
- return 0;
470
- }
471
- return usage(c, '用法:anytowork chat group rename|describe|add-agent <群编号> ...(见 anytowork chat --help)');
472
- }
473
-
474
- /** A group refusal; a private chat has a fixed name, everything else is the shared wording. */
475
- function groupRefusal(c, e) {
476
- const r = refusalOf(e);
477
- if (r && r.code === 'wb_dm_fixed') {
478
- const text = '私聊的名字和描述是固定的,不能改;只有群可以。';
479
- if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text })); else c.err(text);
480
- return 1;
481
- }
482
- return reportRefusal(c, e);
483
- }
484
-
485
- /** `chat result`: hand in the result. Ends this piece of work; the owner can take the changes back in one go. */
486
- async function runResult(c, sid) {
487
- const files = c.flags.files || [];
488
- const data = await post(c, `/sessions/${enc(sid)}/result`, { client_key: c.flags.idempotencyKey || randomUUID(), files });
489
- // v0.35.3: the hire this session belongs to (from the result answer, else remembered by `chat read`); read before the
490
- // current session is cleared below.
491
- const hireId = data.hire_id || (readCurrentSession(c.credOpts, c.nowMs()) === sid ? readCurrentHire(c.credOpts) : null);
492
- // The piece of work is over: forget the current session (only if it is this one), later pushes record nothing.
493
- if (readCurrentSession(c.credOpts, c.nowMs()) === sid) clearCurrentSession(c.credOpts);
494
- else touchCurrentSession(c.credOpts, c.nowMs());
495
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
496
- const lines = [data.gate_delivery === 'not_delivered'
497
- ? `这条成果消息没有送达对方(消息 #${data.message && data.message.id})。`
498
- : `已交成果(消息 #${data.message && data.message.id})。`];
499
- const listed = data.files || [];
500
- for (const f of listed) lines.push(` 📎 ${f.path || f.name || ''}`);
501
- if (Number(data.files_more) > 0) lines.push(` …等 ${data.files_more} 个文件`);
502
- if (!listed.length && !files.length) lines.push('这次没有改动空间里的文件,成果消息里没有附件。');
503
- if (data.segment && data.segment.ended) lines.push('这一段工作已结束;主人不满意的话可以在网页上一键退回这次改动。');
504
- // Print only (never reported for you): a hired Agent's time counts only when usage is reported.
505
- if (hireId) lines.push(`用量由平台自动读取,不用报;读不到时会提示你,再补一次:有本机日志用 anytowork usage push --file <记录文件> --scope hire:${hireId},没有本机日志(云端运行时)用 anytowork usage sample --from <导出文件> --scope hire:${hireId}。干着活隔一会儿补一次。叫醒里会写今日剩余额度(百分比);剩余额度不足时先告诉主人,再接大活。`);
506
- c.log(lines.join('\n'));
507
- return 0;
508
- }
509
-
510
- function parseOption(raw) {
511
- const s = String(raw);
512
- const i = s.indexOf('::');
513
- if (i < 0) return { label: s.trim(), desc: null };
514
- return { label: s.slice(0, i).trim(), desc: s.slice(i + 2).trim() || null };
515
- }
516
-
517
- async function runAsk(c, sid) {
518
- const opts = (c.flags.options || []).map(parseOption).filter((o) => o.label);
519
- if (!c.flags.title || opts.length < 2) {
520
- return usage(c, '用法:anytowork chat ask <会话> --title "<问题>" --option "<选项>" --option "<选项>"... [--recommend <序号>](至少 2 个选项)');
521
- }
522
- if (opts.length > 6) return usage(c, '选项最多 6 个(「都不是,我来说」平台会自动加,不用写)。');
523
- let recommend = null;
524
- if (c.flags.recommend != null) {
525
- recommend = Number(c.flags.recommend);
526
- if (!Number.isInteger(recommend) || recommend < 1 || recommend > opts.length) {
527
- return usage(c, `--recommend 要写 1–${opts.length} 之间的序号。`);
528
- }
529
- }
530
- const data = await post(c, `/sessions/${enc(sid)}/asks`, {
531
- client_key: c.flags.idempotencyKey || randomUUID(), title: c.flags.title, options: opts, recommend,
532
- });
533
- touchCurrentSession(c.credOpts, c.nowMs());
534
- c.log(c.json ? JSON.stringify(data, null, 2)
535
- : [`选择题已发出(消息 #${data.message && data.message.id})。主人回答后你会被叫醒。`, newsLine(data)].filter(Boolean).join('\n'));
536
- return 0;
537
- }
538
-
539
- async function runProgress(c, sid, positional) {
540
- const text = await bodyText(c, positional);
541
- if (!text || !String(text).trim()) return usage(c, '用法:anytowork chat progress <会话> "<一句话>"');
542
- const data = await post(c, `/sessions/${enc(sid)}/progress`, { text: String(text) });
543
- touchCurrentSession(c.credOpts, c.nowMs());
544
- c.log(c.json ? JSON.stringify(data, null, 2)
545
- : ['已记进工作轨迹(主人在 Agent 地图里看得到,不进聊天),这一轮仍在进行中。', newsLine(data)].filter(Boolean).join('\n'));
546
- return 0;
547
- }
548
-
549
- async function runNeedWorkspace(c, sid, positional) {
550
- const reason = positional;
551
- if (!reason || !String(reason).trim()) return usage(c, '用法:anytowork chat need-workspace <会话> "<为什么需要工作空间>"');
552
- const data = await post(c, `/sessions/${enc(sid)}/need-workspace`, { reason: String(reason) });
553
- touchCurrentSession(c.credOpts, c.nowMs());
554
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
555
- if (data.workspace_path) {
556
- c.log(`这个私聊已经有工作空间了:「${data.workspace_path}」,直接用它:anytowork space pull ${quoteArg(data.workspace_path)} --to <本地目录>`);
557
- } else {
558
- c.log(`已请主人选一个工作空间(会话里出现了一张选择卡)。主人选好后,用 anytowork chat read ${sid} 就能看到路径。`);
559
- }
560
- return 0;
561
- }
562
-
563
- /**
564
- * anytowork chat <list|read|send|result|ask|progress|plan|need-workspace>
565
- * @param {object} p { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, deps? }
566
- */
567
- // ---------------------------------------------------------------- chat plan (v0.38.x, PRD 26 plan card design)
568
-
569
- /** "1,2,3" -> [1,2,3]; null when anything is not a positive whole number. */
570
- function ordList(raw) {
571
- if (raw == null) return null;
572
- const out = [];
573
- for (const piece of String(raw).split(',')) {
574
- const t = piece.trim();
575
- if (!/^\d+$/.test(t) || Number(t) < 1) return null;
576
- out.push(Number(t));
577
- }
578
- return out;
579
- }
580
-
581
- const PLAN_STATE_WORD = { done: '完成', doing: '在做' };
582
-
583
- /**
584
- * `chat plan <session> "<one|two|three>" [--done 1,2] [--doing 3]`
585
- * One command, two uses: give a whole plan (3 to 8 steps, split by |) or only move steps to a new state.
586
- * The platform decides the rest; this only checks the arguments and turns refusals into plain words.
587
- */
588
- async function runPlan(c, sid, positional) {
589
- const steps = (positional == null ? '' : String(positional)).split('|').map((x) => x.trim()).filter(Boolean);
590
- const done = ordList(c.flags.done);
591
- const doing = ordList(c.flags.doing);
592
- if (c.flags.done != null && !done) return usage(c, '--done 要写第几步(数字,多个用逗号隔开,如 --done 1,2)。');
593
- if (c.flags.doing != null && !doing) return usage(c, '--doing 要写第几步(数字,多个用逗号隔开,如 --doing 3)。');
594
- if ((doing || []).some((n) => (done || []).includes(n))) return usage(c, '同一个步骤不能既 --done 又 --doing。');
595
- const set = [];
596
- for (const ord of done || []) set.push({ ord, state: 'done' });
597
- for (const ord of doing || []) set.push({ ord, state: 'doing' });
598
- if (!steps.length && !set.length) {
599
- return usage(c, '用法:anytowork chat plan <会话> "第一步|第二步|第三步"(3 到 8 步),或者 --done 1 --doing 2 只改状态。');
600
- }
601
- if (steps.length) {
602
- // 3 to 8: fewer makes no card (chat progress is enough), more is an error, never a silent trim
603
- if (steps.length < 3 || steps.length > 8) return usage(c, '计划要 3 到 8 步。');
604
- const tooLong = steps.find((x) => x.length > 60);
605
- if (tooLong) return usage(c, `每一步不超过 60 字:「${tooLong.slice(0, 12)}…」太长了。`);
606
- }
607
- const body = { client_key: c.flags.idempotencyKey || randomUUID() };
608
- if (steps.length) body.steps = steps.map((text) => ({ text }));
609
- if (set.length) body.set = set;
610
- let data;
611
- try {
612
- data = await put(c, `/sessions/${enc(sid)}/plan`, body);
613
- } catch (e) {
614
- const r = refusalOf(e);
615
- // An older platform has no /plan route: a bare 404, not one of our coded refusals. Stay quiet, keep working.
616
- if (!r && e && e.status === 404) {
617
- const text = '平台还不支持计划,这一轮照常用 chat progress。';
618
- if (c.json) c.log(JSON.stringify({ ok: false, error: 'plan_unsupported', message: text }));
619
- else c.log(text);
620
- return 0;
621
- }
622
- // Nothing broke: one line, exit 0, no retry.
623
- if (r && (r.code === 'wb_plan_missing' || r.code === 'wb_plan_closed')) {
624
- const text = REFUSALS[r.code]();
625
- if (c.json) c.log(JSON.stringify({ ok: false, error: r.code, message: text, ...r.vars }));
626
- else c.log(text);
627
- return 0;
628
- }
629
- throw e;
630
- }
631
- touchCurrentSession(c.credOpts, c.nowMs());
632
- if (c.json) { c.log(JSON.stringify(data, null, 2)); return 0; }
633
- const plan = data.plan || {};
634
- const lines = [];
635
- if (steps.length) {
636
- lines.push(Number(plan.version) > 1
637
- ? '计划已换掉,从头开始勾。'
638
- : `计划已发给主人(${steps.length} 步)。每做完一步用 --done 勾掉。`);
639
- }
640
- if (set.length) {
641
- const words = set.map((x) => `第 ${x.ord} 步${PLAN_STATE_WORD[x.state] || ''}`).join(',');
642
- lines.push(steps.length ? `${words}。` : `计划已更新:${words}。`);
643
- }
644
- c.log([...lines, newsLine(data)].filter(Boolean).join('\n'));
645
- return 0;
646
- }
647
-
648
- export async function runChat(p) {
649
- const { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err } = p;
650
- const deps = p.deps || {};
651
- const c = {
652
- flags, json: flags.json, log, err, baseUrl, credOpts, fetchImpl,
653
- nowMs: deps.nowMs || Date.now,
654
- env: p.env || process.env,
655
- readStdin: deps.readStdin,
656
- };
657
- const sub = command.slice('chat:'.length);
658
- if (!SUBS.has(sub)) { err(CHAT_HELP); return 2; }
659
- const sid = positionals[2];
660
- const rest = positionals[3];
661
- if (sub === 'group') {
662
- try { return await runGroup(c, positionals); } catch (e) { return reportRefusal(c, e); }
663
- }
664
- if (sub !== 'list' && !sid) return usage(c, `缺少会话编号。用法见 anytowork chat --help(会话编号在 chat list 和叫醒你的消息里)。`);
665
- try {
666
- if (sub === 'list') return await runList(c);
667
- if (sub === 'read') return await runRead(c, sid);
668
- if (sub === 'send') return await runSend(c, sid, rest);
669
- if (sub === 'result') return await runResult(c, sid);
670
- if (sub === 'ask') return await runAsk(c, sid);
671
- if (sub === 'progress') return await runProgress(c, sid, rest);
672
- if (sub === 'plan') return await runPlan(c, sid, rest);
673
- if (sub === 'recall') return await runRecall(c, sid);
674
- return await runNeedWorkspace(c, sid, rest);
675
- } catch (e) {
676
- // An older platform has no result route: a bare 404 that is not one of our refusals (those carry an error code).
677
- if (sub === 'result' && e && e.status === 404 && !refusalOf(e)) {
678
- const text = '平台还不支持交成果,先用 anytowork chat send 回复。';
679
- if (c.json) c.log(JSON.stringify({ ok: false, error: 'result_unsupported', message: text }));
680
- else c.err(text);
681
- return 1;
682
- }
683
- return reportRefusal(c, e);
684
- }
685
- }