@anytowork/cli 0.12.72 → 0.12.73

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,706 +0,0 @@
1
- // anytowork hire — being hired (v0.34, CLI 0.12.25; PRD 25 十三 / 二十, contract v0.34 七).
2
- //
3
- // What this is for: an Agent whose owner has turned job seeking on. The owner sets the policy on the web once and it
4
- // lives in the cloud (a change takes effect at once, nothing has to be sent again). From then on the Agent reads its
5
- // own policy, applies to openings with an amount, signs for the merchant when the owner granted that, reports usage
6
- // after each piece of work, and handles the events that arrive through the always-on listener or `poll`.
7
- //
8
- // hire policy my job policy and my room for the next 90 days (read live from the cloud)
9
- // hire openings [--cursor] [--limit] hires I can apply to, with what blocks each one and the amount range
10
- // hire show <hire_id> one hire from my side: the public text before signing, the original after
11
- // hire apply <hire_id> --offer-cents apply with an amount (applying again updates the amount and the reason)
12
- // hire withdraw <hire_id> take my application back before it is picked
13
- // hire pass <hire_id> [--reason] not applying to this one (nothing is recorded)
14
- // hire sign <hire_id> [--lang] sign for my merchant (only while the owner's grant is live)
15
- // hire decline <hire_id> hand the pick back at once, so the employer can pick someone else
16
- // hire decide <hire_id> --request <id> --accept|--reject answer the employer's new start date
17
- // hire topup <hire_id> --accept|--reject answer the employer's top-up of today
18
- // hire mine the hires I am picked for (signing / waiting to start / on duty)
19
- // hire comment <hire_id> "<text>" [--reply-to <comment_id>] | --list ask the employer on the hire (v0.38.57; read-only once signed)
20
- // hire usage <hire_id> --occurred-at --item ... report the usage of one piece of work
21
- // hire habit --occurred-at --item ... "what I usually use per day" (no hire)
22
- // hire usage-view <hire_id> [--range] [--date] my own usage numbers
23
- //
24
- // Two rules the wording follows (PRD 25 03 二 / 八):
25
- // * read the tokens, do not estimate: when the numbers cannot be read, do not report at all (the command refuses an
26
- // empty report instead of sending a zero);
27
- // * report each piece where it happened: the platform puts a report into the 10-minute slot it belongs to, so pass
28
- // the real time, never a whole day merged together.
29
- //
30
- // Exit codes: 0 done / 1 refused or failed / 2 a problem with the arguments / 4 the CLI is too old for hiring.
31
-
32
- import { withApplyBackoff, tooFastText, OUTRANKED_TEXT } from './apply-backoff.js';
33
- import { randomUUID } from 'node:crypto';
34
- import { authedGetWithRefresh, authedPostWithRefresh } from './api.js';
35
- import { moneyText } from './error-map.js';
36
- import { UPGRADE_COMMAND } from './client-version.js';
37
- import { BRAND } from './brand.js';
38
- import { t as mtText } from './mt/text.js';
39
- import { ignoredPolicyNotice, mapMtError } from './mt/commands.js';
40
- import { describeApplyModels } from './model-pledge.js';
41
-
42
- const BASE = '/api/v1/agent/hire';
43
- const enc = encodeURIComponent;
44
-
45
- export const HIRE_HELP = `anytowork hire — 求职与被聘 / looking for work and being hired
46
- 该功能目前只对受邀账号开放;受邀后命令照常可用,用法以平台页面上的说明为准。
47
- This feature is currently available to invited accounts only; once invited the commands work as usual, and the platform page has the details.`;
48
-
49
- export function isHireCommand(command) {
50
- return typeof command === 'string' && command.startsWith('hire:');
51
- }
52
-
53
- // ---------------------------------------------------------------- refusals in plain words
54
-
55
- /** The platform's refusal: { code, message, vars } (FastAPI may wrap it in `detail`). */
56
- function refusalOf(e) {
57
- const b = e && e.body && typeof e.body === 'object' ? e.body : null;
58
- if (!b) return null;
59
- const body = b.detail && typeof b.detail === 'object' && b.detail.error ? b.detail : b;
60
- const code = typeof body.error === 'string' ? body.error : null;
61
- if (!code) return null;
62
- const vars = body.vars && typeof body.vars === 'object' ? body.vars : {};
63
- return { code, message: body.message || '', vars };
64
- }
65
-
66
- const NOT_OPEN = `招聘与聘用目前只对受邀账号开放,这个 Agent 还没在受邀名单里。`
67
- + `想开通,请主人到网页的「我的团队」里申请,或等平台通知。订单相关的事照常用 anytowork poll 收。`;
68
-
69
- /** What a blocked application means, in words an Agent can pass on (contract 6, eight gates). */
70
- function gateLine(code, vars) {
71
- switch (code) {
72
- case 'hire_gate_feature': return '聘用功能还没对双方开放';
73
- case 'hire_gate_job_off': return `${vars.agent || '这个 Agent'} 现在没有在求职`;
74
- case 'hire_gate_blocked': return '你们之间有屏蔽关系';
75
- case 'hire_gate_employers_full': return `在岗雇主已满(最多 ${vars.limit} 位)`;
76
- case 'hire_gate_schedule': {
77
- const dates = Array.isArray(vars.dates) ? vars.dates.map((d) => d.date || d).join('、') : '';
78
- return `聘期内有几天排不开${dates ? `:${dates}` : ''}`;
79
- }
80
- case 'hire_gate_cli': return `命令行版本太低(要 ${vars.min} 或更高)`;
81
- case 'hire_gate_real_pay': return '商家还没有开通收款';
82
- case 'hire_gate_closed': {
83
- if (vars.reason === 'not_invited') return '这张只对受邀的 Agent 开放';
84
- if (vars.reason === 'deadline') return '报名已经截止';
85
- return '这张招聘现在不能报名';
86
- }
87
- default: return null;
88
- }
89
- }
90
-
91
- const REFUSAL_HINTS = {
92
- hire_not_found: () => '找不到这张招聘,或者这单不是你的、你无权查看。用 anytowork hire openings 看看现在能报哪些。',
93
- public_qa_closed: () => '这张招聘已经录用或已关闭,留言只读了。已录用的,新沟通请在工作台里进行(anytowork chat list)。',
94
- hire_forbidden: () => '这一步你不能做,只能由雇主或对应的商家来做。',
95
- hire_bad_state: (v) => `现在的状态(${v.status || '未知'})不能做这个操作。用 anytowork hire mine 看看进展到哪一步了。`,
96
- hire_invalid: (v) => `填写的内容有误${v.field ? `(${v.field})` : ''}。`,
97
- hire_offer_below_min: (v) => `报的量低于这张招聘的下限 ${moneyText(v.min)}。报量要不低于下限,也不要超过你能给的量。`,
98
- hire_offer_over_cap: (v) => `报的量超过了你那几天真能给的量(最多 ${moneyText(v.max)})。`,
99
- apply_outranked: () => OUTRANKED_TEXT,
100
- hire_apply_locked: () => '你已经报过名,3 分钟公示期结束后不能再改报量和理由;还没报名的 Agent 截止前仍可以新报名。',
101
- // v0.37.6 (#452): a hire application needs a declared main model the price table covers
102
- hire_apply_model_missing: () => '应聘前要先说明主力模型和模型策略:设一次默认策略 anytowork model policy set --primary <模型>,'
103
- + '或这次报名带上 --primary <模型>。主力模型要在平台价格表里。',
104
- hire_apply_model_unpriced: (v) => `主力模型 ${v.model || ''} 不在平台价格表里,算不出用量额度,这次报不了名。`
105
- + '换成价格表里有的主力模型(anytowork model policy set --primary <模型>,或这次带 --primary <模型>)再报。',
106
- hire_sign_not_authorized: () => '主人没有授权你代签,或者授权已经撤销。请主人本人签署,或先在网页上开好求职。',
107
- hire_sign_timeout: () => '这张已经超时,不用再处理了。',
108
- hire_protocol_outdated: () => '协议版本更新过,请重新打开这张招聘再签一次。',
109
- hire_change_invalid: () => '雇主给的新入职日不合适,请在网页上请雇主重新提。',
110
- hire_change_capacity: () => '新日期的档期不够,请主人调整档期后再说。',
111
- feature_not_open: () => NOT_OPEN,
112
- hire_gate_feature: () => NOT_OPEN,
113
- hire_gate_job_off: (v) => `${v.agent || '这个 Agent'} 现在没有在求职,报名不了。请主人在网页上打开求职。`,
114
- hire_gate_blocked: () => '你们之间有屏蔽关系,报不了这张。',
115
- hire_gate_employers_full: (v) => `在岗雇主已满(最多 ${v.limit} 位),等有单结束再来。`,
116
- hire_gate_schedule: (v) => {
117
- const dates = Array.isArray(v.dates) ? v.dates.map((d) => d.date || d).join('、') : '';
118
- return `聘期里有几天档期排不开${dates ? `:${dates}` : ''}。请主人在网页上调整档期。`;
119
- },
120
- hire_gate_cli: (v) => `命令行版本太低(要 ${v.min} 或更高)。先升级:${UPGRADE_COMMAND}`,
121
- hire_gate_real_pay: () => '这位商家还没有开通收款,暂时不能接真钱的聘用。',
122
- hire_gate_closed: (v) => {
123
- if (v.reason === 'not_invited') return '这张只对受邀的 Agent 开放,你不在受邀名单里。';
124
- if (v.reason === 'deadline') return '这张招聘的报名已经截止。';
125
- return '这张招聘现在不能报名。';
126
- },
127
- // usage reports (session C's codes)
128
- hire_usage_not_found: () => '找不到这张聘用,或者这单不是你的。用 anytowork hire mine 看看你现在被聘了哪些。',
129
- hire_usage_forbidden: () => '这条用量不能由你来报:只有被这家雇主录用的那个 Agent 能报。',
130
- hire_usage_not_on_duty: () => '这张现在不在岗(还没入职或已经结束),先不报用量;结束日当天的补报还可以报。',
131
- hire_usage_bad_time: () => '--occurred-at 不对:要写真实发生的时刻并带上时区,不能是将来,也不能早于入职日、晚于结束日。',
132
- hire_usage_bad_items: () => '用量条数不合法:每条要有模型名,四个 token 数是非负整数,且至少一个大于 0,一次最多 20 条。',
133
- hire_usage_bad_range: () => '--range 只能是 day、week、month。',
134
- hire_usage_bad_cursor: () => '翻页游标失效了,从头看一次即可。',
135
- };
136
-
137
- // ---------------------------------------------------------------- text
138
-
139
- function money(minor, currency) {
140
- const t = moneyText(minor, currency || 'CNY');
141
- return t == null ? '—' : t;
142
- }
143
-
144
- function pctText(pct) {
145
- return pct == null ? '—' : `${pct}%`;
146
- }
147
-
148
- function gateOf(row) {
149
- const g = row && row.gate;
150
- if (!g || !g.code) return '能报';
151
- return `不能报:${gateLine(g.code, g.vars || {}) || g.code}`;
152
- }
153
-
154
- function applicationLine(a) {
155
- if (!a) return '还没报';
156
- if (a.status === 'handed') return '商家把它交给你判断(还没报量)';
157
- if (a.status === 'applied') return `已报 ${money(a.offered_usage_minor)}`;
158
- if (a.status === 'picked') return '雇主录用了你';
159
- if (a.status === 'withdrawn') return '已撤回报名';
160
- if (a.status === 'standby') return '在候选里等雇主选';
161
- if (a.status === 'not_picked') return '没被选上';
162
- return a.status;
163
- }
164
-
165
- /** Off-hours windows as text. The platform stores {start,end}; older shapes {from,to} and plain strings still print. */
166
- export function offHoursText(list) {
167
- return (Array.isArray(list) ? list : []).map((w) => {
168
- if (typeof w === "string") return w;
169
- if (!w || typeof w !== "object") return "";
170
- const a = w.start || w.from, b = w.end || w.to;
171
- return a && b ? `${a}–${b}` : "";
172
- }).filter(Boolean).join("、");
173
- }
174
-
175
- function policyText(d) {
176
- const lines = ['求职策略(存在云端,改了立即生效)'];
177
- const on = !!d.is_on;
178
- lines.push(` 求职:${on ? '已开启' : '未开启'}${on && d.authorized ? '(已授权代签)' : ''}`);
179
- if (!on) {
180
- lines.push(' 主人现在没开求职。想让 Agent 接聘用,请主人在「我的团队」里打开这个 Agent 的求职。');
181
- return lines.join('\n');
182
- }
183
- lines.push(` 每天能给的量:${d.daily_give_minor == null ? '不设上限' : money(d.daily_give_minor)}`);
184
- const bps = Number(d.min_discount_bps);
185
- if (Number.isFinite(bps) && bps > 0) lines.push(` 最低接受打几折:${(bps / 1000).toFixed(1)} 折`);
186
- const off = Array.isArray(d.off_hours) ? d.off_hours : [];
187
- lines.push(` 每天不在线时段:${offHoursText(off) || '不设'}`);
188
- if (d.tz) lines.push(` 时区:${d.tz}`);
189
- if (d.note_to_agent) lines.push(` 主人的话:${d.note_to_agent}`);
190
- const cap = Array.isArray(d.capacity) ? d.capacity : [];
191
- const odd = cap.filter((c) => c && (c.rest || c.remain_minor === 0));
192
- if (odd.length) {
193
- lines.push(` 档期里不上班的日子(未来 90 天):${odd.filter((c) => c.rest).length} 天`);
194
- const rests = odd.filter((c) => c.rest).slice(0, 10).map((c) => c.date);
195
- if (rests.length) lines.push(` ${rests.join('、')}${odd.filter((c) => c.rest).length > 10 ? ' 等' : ''}`);
196
- const full = odd.filter((c) => !c.rest);
197
- if (full.length) lines.push(` 已约满:${full.slice(0, 10).map((c) => c.date).join('、')}${full.length > 10 ? ' 等' : ''}`);
198
- }
199
- const open = cap.filter((c) => c && !c.rest && c.remain_minor != null && c.remain_minor > 0).slice(0, 3);
200
- if (open.length) lines.push(` 其余日子有量:${open.map((c) => `${c.date} 还能给 ${money(c.remain_minor)}`).join(';')}`);
201
- return lines.join('\n');
202
- }
203
-
204
- // One-line conclusion for an offer: what the employer pays, the quantity the Agent may give, the discount that
205
- // makes (daily price / quantity), and whether it is inside the Agent's own floor (min_discount_bps, may be absent).
206
- function discountText(n) {
207
- const t = (Math.round(n * 10) / 10).toFixed(1);
208
- return t.endsWith('.0') ? t.slice(0, -2) : t;
209
- }
210
-
211
- function discountLine(d) {
212
- const r = d.offer_range || {};
213
- const daily = Number(d.daily_minor);
214
- if (r.min == null || r.max == null || !(daily > 0) || !(r.min > 0) || r.max < r.min) return null;
215
- const multi = Number(d.days) > 1;
216
- const hi = discountText((daily / r.min) * 10); // least discount (lowest quantity)
217
- const lo = discountText((daily / r.max) * 10); // deepest discount (highest quantity)
218
- const pay = `${multi ? '雇主每天付' : '雇主付'} ${money(multi ? d.daily_minor : d.budget_minor, d.currency)}`;
219
- const qty = r.min === r.max ? money(r.min, d.currency) : `${money(r.min, d.currency)}—${money(r.max, d.currency)}`;
220
- const give = `${multi ? '你每天给出' : '你给出'} ${qty} 的量`;
221
- const bps = d.min_discount_bps == null ? null : Number(d.min_discount_bps);
222
- if (bps === 10000) return ` ${pay},${give},不打折(你的策略不打折,${r.min <= daily ? '可报' : '超出你的底线'})`;
223
- const shown = lo === hi ? `约 ${hi} 折` : `折合 ${lo}—${hi} 折`;
224
- if (bps == null || !(bps > 0)) return ` ${pay},${give},${shown}`;
225
- const floorTxt = `你的底线 ${discountText(bps / 1000)} 折`;
226
- const over = (daily / r.min) * 10000 < bps - 1e-6;
227
- return ` ${pay},${give},${shown}(${floorTxt},${over ? '超出你的底线' : '可报'})`;
228
- }
229
-
230
- function openingsText(d) {
231
- const items = Array.isArray(d.items) ? d.items : [];
232
- if (!items.length) {
233
- const lines = ['现在没有你能报的招聘。'];
234
- if (d.next_cursor) lines.push(` 还有下一页:anytowork hire openings --cursor ${d.next_cursor}`);
235
- return lines.join('\n');
236
- }
237
- const lines = [`能看的招聘 ${items.length} 张:`];
238
- items.forEach((r, i) => {
239
- const range = r.offer_range || {};
240
- lines.push(` ${i + 1}) ${r.title || '(无标题)'} · ${r.start_date} → ${r.end_date}(${r.days} 天)`);
241
- if (r.employer) lines.push(` 雇主:${r.employer}(日期按雇主所在时区)`);
242
- lines.push(` 总价 ${money(r.budget_minor, r.currency)},平均每天 ${money(r.daily_minor, r.currency)}`);
243
- if (r.deadline_at) lines.push(` 报名截止:${r.deadline_at}`);
244
- if (range.min != null && range.max != null) lines.push(` 能报的量:${money(range.min, r.currency)} — ${money(range.max, r.currency)}`);
245
- { const dl = discountLine(r); if (dl) lines.push(` ${dl}`); }
246
- lines.push(` ${gateOf(r)}`);
247
- lines.push(` 我这边:${applicationLine(r.application)}${r.source === 'invited' ? '(雇主点名邀请你)' : (r.source === 'handed' ? '(商家交给你判断)' : '')}`);
248
- lines.push(` 详情:anytowork hire show ${r.hire_id}`);
249
- });
250
- if (d.next_cursor) lines.push(`还有下一页:anytowork hire openings --cursor ${d.next_cursor}`);
251
- return lines.join('\n');
252
- }
253
-
254
- function detailText(d) {
255
- const lines = [`${d.title || '(无标题)'} · ${d.start_date} → ${d.end_date}(${d.days} 天)`];
256
- lines.push(` 状态:${d.status || '—'}`);
257
- if (d.employer) lines.push(` 雇主:${d.employer}(日期按雇主所在时区)`);
258
- lines.push(` 总价 ${money(d.budget_minor, d.currency)},平均每天 ${money(d.daily_minor, d.currency)}`);
259
- if (d.agreed_daily_usage_minor != null) lines.push(` 这条给我的每天的量:${money(d.agreed_daily_usage_minor, d.currency)}`);
260
- if (d.sign_deadline_at) lines.push(` 签署截止:${d.sign_deadline_at}`);
261
- if (d.description) lines.push(' 需求:', ` ${d.description}`);
262
- if (d.pending_change && d.pending_change.new_start_date) {
263
- lines.push(` 雇主要把入职日改成 ${d.pending_change.new_start_date},要你确认:`);
264
- lines.push(` anytowork hire decide ${d.hire_id} --request ${d.pending_change.id || '<改期申请号>'} --accept|--reject`);
265
- }
266
- const r = d.offer_range || {};
267
- if (r.min != null && r.max != null) lines.push(` 能报的量:${money(r.min, d.currency)} — ${money(r.max, d.currency)}`);
268
- { const dl = discountLine(d); if (dl) lines.push(dl); }
269
- lines.push(` 我这边:${applicationLine(d.application)}`);
270
- const g = d.gate;
271
- if (g && g.code) lines.push(` ${gateLine(g.code, g.vars || {}) || g.code}`);
272
- return lines.join('\n');
273
- }
274
-
275
- function mineText(d) {
276
- const items = Array.isArray(d.items) ? d.items : [];
277
- if (!items.length) return '现在没有你被聘的单。用 anytowork hire openings 看看能报哪些。';
278
- const statusWord = { signing: '待签署', pending_start: '待入职', on_duty: '在岗', ended: '已结束' };
279
- const lines = [`你被聘的单 ${items.length} 张:`];
280
- for (const r of items) {
281
- lines.push(` ${r.hire_id} · ${statusWord[r.status] || r.status} · ${r.start_date} → ${r.end_date}(雇主时区 ${r.employer_tz || '—'})`);
282
- lines.push(` 这条每天的约定量:${money(r.agreed_daily_usage_minor)}`);
283
- const t = r.today;
284
- if (t) {
285
- const st = t.off_duty ? '今天已经下班了(明天继续)' : `今天已用 ${money(t.used_minor)},约 ${pctText(t.pct)}`;
286
- lines.push(` ${st}`);
287
- }
288
- if (r.status === 'signing') lines.push(` 要签协议:anytowork hire sign ${r.hire_id};不想接就尽早退回:anytowork hire decline ${r.hire_id}`);
289
- const offText = offHoursText(r.off_hours);
290
- if (offText) lines.push(` 不在线时段:${offText}`);
291
- }
292
- return lines.join('\n');
293
- }
294
-
295
- function usageText(d) {
296
- const lines = [];
297
- if (d.duplicate) lines.push(`这条之前报过(编号 ${d.report_id}),平台只记了一次:`);
298
- else lines.push(`已报上(编号 ${d.report_id}):`);
299
- lines.push(` 这一天(${d.local_date || '—'})记入 ${money(d.amount_minor, d.currency)}`);
300
- if (d.status === 'late') lines.push(' 这条超过了补报时限,只留痕、不算进当天用量。');
301
- const t = d.today;
302
- if (t) {
303
- lines.push(` 今天:已用 ${money(t.used_minor)},约定 ${money(t.agreed_minor)},约 ${pctText(t.pct)}`);
304
- if (t.off_duty) lines.push(' 到 100% 了,今天先停下,明天继续。');
305
- }
306
- const un = Array.isArray(d.unpriced_models) ? d.unpriced_models : [];
307
- if (un.length) lines.push(` 这些模型不在价格表里,只记了 token、不算钱:${un.join('、')}(用它干的活不计入给量)`);
308
- return lines.join('\n');
309
- }
310
-
311
- function usageViewText(d, hireId) {
312
- const lines = [`这张的用量(${d.range || 'day'}${d.date ? ` · ${d.date}` : ''}):`];
313
- const t = d.today || {};
314
- const cur = t.currency || 'CNY';
315
- if (t.used_minor != null) {
316
- lines.push(` 今天已用 ${money(t.used_minor, cur)},约定 ${money(t.agreed_minor, cur)},约 ${pctText(t.pct)}`);
317
- if (t.off_duty) lines.push(' 到 100% 了,今天先停下,明天继续。');
318
- } else {
319
- lines.push(' 今天还没有计入的用量。');
320
- }
321
- if (d.avg_minor != null) lines.push(` 有上报的日子里日均:${money(d.avg_minor, cur)}`);
322
- if (d.refund_minor) lines.push(` 这一天已自动退:${money(d.refund_minor, cur)}`);
323
- const unpriced = Array.isArray(d.models) ? d.models.filter((m) => m && !m.priced) : [];
324
- if (unpriced.length) lines.push(` 这些模型不在价格表里,只记 token、不算钱:${unpriced.map((m) => m.model).join('、')}`);
325
- lines.push(` 完整数字(曲线、模型占比、逐条明细):anytowork hire usage-view ${hireId} --json`);
326
- return lines.join('\n');
327
- }
328
-
329
- // ---------------------------------------------------------------- platform calls
330
-
331
- function get(c, pathAndQuery) {
332
- return authedGetWithRefresh(c.baseUrl, `${BASE}${pathAndQuery}`, c.credOpts, { fetchImpl: c.fetchImpl });
333
- }
334
-
335
- function post(c, pathStr, body, idem) {
336
- return authedPostWithRefresh(c.baseUrl, `${BASE}${pathStr}`, c.credOpts, body, idem || c.flags.idempotencyKey || null,
337
- { fetchImpl: c.fetchImpl });
338
- }
339
-
340
- function makeIo(c) {
341
- return {
342
- ok(data, text) {
343
- c.log(c.flags.json ? JSON.stringify({ ok: true, ...data }) : text);
344
- return 0;
345
- },
346
- fail(exit, code, message, extra) {
347
- if (c.flags.json) c.log(JSON.stringify({ ok: false, error: code, message, ...(extra || {}) }));
348
- else c.err(message);
349
- return exit;
350
- },
351
- };
352
- }
353
-
354
- /** Turn a platform error into plain words. A 426 from the hiring API means "upgrade the CLI first". */
355
- export function mapHireError(e) {
356
- if (e && e.upgradeRequired) return { exit: 4, code: 'cli_upgrade_required', message: e.message };
357
- const r = refusalOf(e);
358
- if (!r) {
359
- const msg = (e && e.body && (e.body.message || (e.body.detail && e.body.detail.message))) || (e && e.message) || String(e);
360
- return { exit: 1, code: 'request_failed', message: msg };
361
- }
362
- if (r.code === 'hire_cli_too_old') {
363
- return {
364
- exit: 4,
365
- code: r.code,
366
- message: `${BRAND.name} 命令行版本太旧(要 ${r.vars.min || ''} 或更高),招聘的命令暂时用不了。先升级再重试:${UPGRADE_COMMAND}`,
367
- };
368
- }
369
- const hint = REFUSAL_HINTS[r.code];
370
- const text = hint ? hint(r.vars) : `${r.message || '平台拒绝了这次操作'}【${r.code}】`;
371
- return { exit: r.code === 'feature_not_open' ? 1 : 1, code: r.code, message: text, body: r };
372
- }
373
-
374
- // ---------------------------------------------------------------- items (usage reports)
375
-
376
- const TOKEN_KEYS = [
377
- ['input_tokens', 'input'],
378
- ['output_tokens', 'output'],
379
- ['cache_write_tokens', 'cache_write'],
380
- ['cache_read_tokens', 'cache_read'],
381
- ];
382
-
383
- /**
384
- * "qwen-plus:1200:800:0:120" -> { model: 'qwen-plus', input_tokens: 1200, ... }.
385
- * The last four colon-separated parts are the numbers, so a model name may itself contain colons.
386
- */
387
- export function parseItem(spec) {
388
- const parts = String(spec == null ? '' : spec).split(':');
389
- if (parts.length < 5) return null;
390
- const nums = parts.slice(-4);
391
- const model = parts.slice(0, -4).join(':').trim();
392
- if (!model) return null;
393
- const out = { model };
394
- for (let i = 0; i < 4; i += 1) {
395
- const raw = nums[i].trim();
396
- if (!/^\d+$/.test(raw)) return null;
397
- out[TOKEN_KEYS[i][0]] = Number(raw);
398
- }
399
- if (!TOKEN_KEYS.some(([k]) => out[k] > 0)) return null;
400
- return out;
401
- }
402
-
403
- /** Normalise one item from a JSON file; same shape as the platform expects, unknown keys dropped. */
404
- function cleanItem(raw) {
405
- if (!raw || typeof raw !== 'object') return null;
406
- const model = typeof raw.model === 'string' ? raw.model.trim() : '';
407
- if (!model) return null;
408
- const out = { model };
409
- for (const [k] of TOKEN_KEYS) {
410
- const v = raw[k] == null ? 0 : raw[k];
411
- if (!Number.isInteger(v) || v < 0) return null;
412
- out[k] = v;
413
- }
414
- if (!TOKEN_KEYS.some(([k]) => out[k] > 0)) return null;
415
- return out;
416
- }
417
-
418
- const NO_ITEMS = '没有给出用量条数。读不到用量就不要报,也不要估一个数——平台按你报的算,报 0 也算一条。';
419
-
420
- function collectItems(flags, readFile) {
421
- const items = [];
422
- for (const spec of flags.items || []) {
423
- const it = parseItem(spec);
424
- if (!it) return { error: `--item 写法不对:${spec}。格式是 "<模型>:<输入 token>:<输出 token>:<缓存写>:<缓存读>",四个数都要写,读不到的写 0。` };
425
- items.push(it);
426
- }
427
- if (flags.itemsFile) {
428
- let raw;
429
- try {
430
- raw = JSON.parse(readFile(flags.itemsFile));
431
- } catch (e) {
432
- return { error: `读不了 --items-file 指定文件:${e && e.message ? e.message : e}` };
433
- }
434
- const list = Array.isArray(raw) ? raw : (raw && Array.isArray(raw.items) ? raw.items : null);
435
- if (!list) return { error: '--items-file 里要是一个数组:[{"model":"…","input_tokens":0,…}],或 {"items":[…]}。' };
436
- for (const one of list) {
437
- const it = cleanItem(one);
438
- if (!it) return { error: '--items-file 里有一条不合法:model 必须有,token 必须是非负整数,且至少有一个大于 0。' };
439
- items.push(it);
440
- }
441
- }
442
- return { items };
443
- }
444
-
445
- // ---------------------------------------------------------------- handlers
446
-
447
- function hireIdOf(c, index) {
448
- const id = c.positionals[index];
449
- return id && String(id).trim() ? String(id).trim() : null;
450
- }
451
-
452
- async function cmdPolicy(c, io) {
453
- const d = await get(c, '/policy');
454
- return io.ok(d, policyText(d));
455
- }
456
-
457
- async function cmdOpenings(c, io) {
458
- const q = new URLSearchParams();
459
- if (c.flags.cursor) q.set('cursor', String(c.flags.cursor));
460
- if (c.flags.limit) q.set('limit', String(c.flags.limit));
461
- const d = await get(c, `/openings${q.toString() ? `?${q}` : ''}`);
462
- return io.ok(d, openingsText(d));
463
- }
464
-
465
- async function cmdShow(c, io) {
466
- const id = hireIdOf(c, 2);
467
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire show <招聘编号>');
468
- const d = await get(c, `/${enc(id)}`);
469
- return io.ok(d, detailText(d));
470
- }
471
-
472
- async function cmdApply(c, io) {
473
- const id = hireIdOf(c, 2);
474
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire apply <招聘编号> --offer-cents <分>');
475
- const offered = c.flags.offerCents;
476
- if (offered == null || !Number.isInteger(offered) || offered <= 0) {
477
- return io.fail(2, 'offer_required', '要报多少量:anytowork hire apply <招聘编号> --offer-cents <分>(先 anytowork hire show 看能报的范围)');
478
- }
479
- const body = { offered_usage_minor: offered };
480
- if (c.flags.reason) body.reason = String(c.flags.reason);
481
- if (c.flags.modelLabel) body.model_label = String(c.flags.modelLabel);
482
- // v0.36 (MT-43): --primary / --role / --note = the model policy of THIS application (different per employer);
483
- // nothing given = the platform copies the Agent's default policy; --model-label is the old main-model-only way
484
- // (the platform ignores it when a policy snapshot exists).
485
- // v0.38.42: no policy of its own any more: the flags are accepted and ignored, with a one-line hint after the result.
486
- const ignored = ignoredPolicyNotice({ primary: c.flags.primary, roles: c.flags.roles, note: c.flags.note }, c.env || process.env);
487
- // Echo #371: sit out a short 429 (Retry-After <= 10 s, at most 3 times), then say it plainly
488
- let d;
489
- try {
490
- d = await withApplyBackoff(() => post(c, `/${enc(id)}/apply`, body), { sleep: c.deps.sleep });
491
- } catch (e) {
492
- if (e && e.applyTooFast != null) return io.fail(1, 'rate_limited', tooFastText(e.applyTooFast), { retry_after: e.applyTooFast });
493
- const mt = mapMtError(e, c.env || process.env);
494
- if (mt && mt.code && mt.code.startsWith('mt_policy_')) return io.fail(mt.exit, mt.code, mt.text);
495
- throw e;
496
- }
497
- const policyLines = describeApplyModels({ model_policy: d.model_policy }, c.env || process.env, { sentPolicy: false });
498
- const text = [`报名已记下(${d.status || 'applied'}):每天报 ${money(d.offered_usage_minor)}。`
499
- + '3 分钟公示期内可以再报一次改报量和理由,之后只能撤回;被录用后按主人的授权签署协议。', ...policyLines, ...(ignored ? [ignored] : [])].join('\n');
500
- return io.ok(d, text);
501
- }
502
-
503
- /**
504
- * `hire pass`: the Agent looked at an opening and decided not to apply. The platform keeps no record of that (a hire has no
505
- * pass table, unlike `task pass`), so nothing is sent; the command only answers "fine, that is not a failure" with exit 0.
506
- */
507
- async function cmdPass(c, io) {
508
- const id = hireIdOf(c, 2);
509
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire pass <招聘编号> [--reason "<一句>"]');
510
- const reason = c.flags.reason ? String(c.flags.reason).slice(0, 200) : '';
511
- return io.ok({ hire_id: id, applied: false, recorded: false, reason },
512
- '好,这单不报名。平台不记录放弃,也不算失败,不用再做别的;想改主意,截止前随时 anytowork hire apply。');
513
- }
514
-
515
- async function cmdWithdraw(c, io) {
516
- const id = hireIdOf(c, 2);
517
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire withdraw <招聘编号>');
518
- const d = await post(c, `/${enc(id)}/withdraw`, {});
519
- return io.ok(d, '报名已撤回。之后再想报,重新 anytowork hire apply 就行。');
520
- }
521
-
522
- async function cmdSign(c, io) {
523
- const id = hireIdOf(c, 2);
524
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire sign <招聘编号> [--lang zh-CN|en]');
525
- const lang = c.flags.lang ? String(c.flags.lang) : undefined;
526
- const d = await post(c, `/${enc(id)}/sign`, lang ? { lang } : {});
527
- const cv = d.contract || {};
528
- const lines = [`已替主人签署《Agent 聘用服务协议》(${cv.version || '当前版本'}${cv.lang ? ` · ${cv.lang}` : ''})。`];
529
- lines.push(' 按雇主的安排在群里干活;用量平台会自动读取,读不到时会提示你,再用 anytowork usage push 补上。');
530
- lines.push(' 收尾、下班、离职这类提醒会和新事件一起送到,照着做就行。');
531
- return io.ok(d, lines.join('\n'));
532
- }
533
-
534
- async function cmdDecline(c, io) {
535
- const id = hireIdOf(c, 2);
536
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire decline <招聘编号>');
537
- const d = await post(c, `/${enc(id)}/decline`, {});
538
- return io.ok(d, '已退回,雇主可以马上换人。');
539
- }
540
-
541
- async function cmdDecide(c, io) {
542
- const id = hireIdOf(c, 2);
543
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire decide <招聘编号> --request <改期申请号> --accept|--reject');
544
- if (c.flags.request == null) return io.fail(2, 'request_required', '缺少改期申请号:先 anytowork hire show 看有没有待确认的改期。');
545
- if (!c.flags.accept && !c.flags.rejectFlag) return io.fail(2, 'decision_required', '要说明同意还是拒绝:加 --accept 或 --reject。');
546
- if (c.flags.accept && c.flags.rejectFlag) return io.fail(2, 'decision_required', '--accept 和 --reject 只能选一个。');
547
- const d = await post(c, `/${enc(id)}/change-requests/${enc(c.flags.request)}/decide`, { accept: !!c.flags.accept });
548
- const text = d.accepted
549
- ? `已同意改入职日:${d.start_date} → ${d.end_date}。请主人留意这条聘用的日期变了。`
550
- : `已拒绝改入职日,还是按原来约定的日期。`;
551
- return io.ok(d, text);
552
- }
553
-
554
- async function cmdTopup(c, io) {
555
- const id = hireIdOf(c, 2);
556
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire topup <招聘编号> --accept|--reject');
557
- if (!c.flags.accept && !c.flags.rejectFlag) return io.fail(2, 'decision_required', '要说明同意还是拒绝:加 --accept 或 --reject。');
558
- if (c.flags.accept && c.flags.rejectFlag) return io.fail(2, 'decision_required', '--accept 和 --reject 只能选一个。');
559
- const d = await post(c, `/${enc(id)}/topup/decide`, { accept: !!c.flags.accept });
560
- const yuan = (n) => (Number(n || 0) / 100).toFixed(2).replace(/\.00$/, '');
561
- const text = d.status === 'confirmed'
562
- ? `已同意加量,今天的用量上限提到 ${yuan(d.agreed_minor)} 元${d.resumed ? ',可以接着干活了' : ''}。`
563
- : d.status === 'expired'
564
- ? '这次加量已超时,钱已退回雇主。'
565
- : '已拒绝加量,钱已退回雇主。';
566
- return io.ok(d, text);
567
- }
568
-
569
- async function cmdMine(c, io) {
570
- const d = await get(c, '/mine');
571
- return io.ok(d, mineText(d));
572
- }
573
-
574
- async function cmdUsage(c, io) {
575
- const id = hireIdOf(c, 2);
576
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire usage <招聘编号> --occurred-at <时刻> --item "<模型>:<输入>:<输出>:<缓存写>:<缓存读>"');
577
- if (!c.flags.occurredAt) return io.fail(2, 'occurred_at_required', '缺少这件事发生的时刻:加 --occurred-at 2026-11-14T10:20:00+08:00(要带时区)。');
578
- const got = collectItems(c.flags, c.deps.readFile);
579
- if (got.error) return io.fail(2, 'bad_items', got.error);
580
- if (!got.items.length) return io.fail(2, 'no_items', NO_ITEMS);
581
- if (got.items.length > 20) return io.fail(2, 'too_many_items', '一次最多 20 条,分几次报。');
582
- const body = {
583
- report_id: c.flags.reportId || randomUUID(),
584
- occurred_at: String(c.flags.occurredAt),
585
- items: got.items,
586
- };
587
- if (c.flags.instructionRef) body.instruction_ref = String(c.flags.instructionRef);
588
- const d = await post(c, `/${enc(id)}/usage`, body, c.flags.idempotencyKey || null);
589
- // v0.36: summaries still count; suggest call-by-call records from the work folder
590
- return io.ok(d, `${usageText(d)}\n${mtText('usage.hire_prefer_records', {}, c.env || process.env)}`);
591
- }
592
-
593
- async function cmdHabit(c, io) {
594
- if (!c.flags.occurredAt) return io.fail(2, 'occurred_at_required', '缺少这一天:加 --occurred-at 2026-11-14T10:20:00+08:00(要带时区)。');
595
- const got = collectItems(c.flags, c.deps.readFile);
596
- if (got.error) return io.fail(2, 'bad_items', got.error);
597
- if (!got.items.length) return io.fail(2, 'no_items', NO_ITEMS);
598
- if (got.items.length > 20) return io.fail(2, 'too_many_items', '一次最多 20 条,分几次报。');
599
- const body = { report_id: c.flags.reportId || randomUUID(), occurred_at: String(c.flags.occurredAt), items: got.items };
600
- const d = await post(c, '/habit', body, c.flags.idempotencyKey || null);
601
- const text = d.duplicate
602
- ? `这一天之前报过,平台只记了一次(${money(d.amount_minor, d.currency)})。`
603
- : `已报上 ${d.local_date || ''} 这一天的用量:${money(d.amount_minor, d.currency)}。`;
604
- const un = Array.isArray(d.unpriced_models) ? d.unpriced_models : [];
605
- if (un.length) c.log(` 这些模型不在价格表里,只记了 token:${un.join('、')}`);
606
- return io.ok(d, text);
607
- }
608
-
609
- // Public questions under a hire (v0.38.57): the same comment module as the task questions, one path apart. The applicant
610
- // asks the employer while the hire is open for applications; once it is signed the thread is read-only (the platform says
611
- // so with public_qa_closed) and talk moves to the workbench.
612
- const COMMENT_BASE = '/api/v1/hires';
613
- const COMMENT_USAGE = '用法:anytowork hire comment <招聘编号> "<内容>" [--reply-to <留言编号>];看留言:anytowork hire comment <招聘编号> --list';
614
-
615
- function commentsText(d, id) {
616
- const list = Array.isArray(d && d.comments) ? d.comments : (Array.isArray(d) ? d : []);
617
- if (!list.length) return '这张招聘下暂时没有留言。';
618
- const lines = [`招聘留言(共 ${list.length} 条):`, ''];
619
- for (const m of list) {
620
- const role = m.speaker_type === 'task_owner' || m.speaker_type === 'buyer' || m.speaker_type === 'employer' ? '雇主'
621
- : (m.speaker_role === 'applicant' ? '报名者' : (m.speaker_role === 'visitor' ? '访客' : m.speaker_type || '?'));
622
- const who = m.speaker_name ? `${m.speaker_name}(${role})` : role;
623
- const re = m.parent_id ? ` ↳回复 #${m.parent_id}${m.parent_speaker_name ? `(${m.parent_speaker_name})` : ''}` : '';
624
- lines.push(` #${m.id} ${who}${re}${m.created_at ? ` [${m.created_at}]` : ''}:${m.content}`);
625
- }
626
- lines.push('', `回答某条留言:anytowork hire comment ${id} "<内容>" --reply-to <留言编号>`);
627
- return lines.join('\n');
628
- }
629
-
630
- async function cmdComment(c, io) {
631
- const id = hireIdOf(c, 2);
632
- if (!id) return io.fail(2, 'hire_id_required', `缺少招聘编号。${COMMENT_USAGE}`);
633
- const path = `${COMMENT_BASE}/${enc(id)}/comments`;
634
- if (c.flags.list) {
635
- const d = await authedGetWithRefresh(c.baseUrl, path, c.credOpts, { fetchImpl: c.fetchImpl });
636
- return io.ok(d, commentsText(d, id));
637
- }
638
- const content = c.positionals[3] != null ? String(c.positionals[3]).trim() : (c.flags.message ? String(c.flags.message).trim() : '');
639
- if (!content) return io.fail(2, 'content_required', `缺少留言内容。${COMMENT_USAGE}`);
640
- let parentId = null;
641
- if (c.flags.replyTo != null) {
642
- if (!/^\d+$/.test(String(c.flags.replyTo))) return io.fail(2, 'reply_to_invalid', `--reply-to 要填留言编号(数字)。${COMMENT_USAGE}`);
643
- parentId = Number(c.flags.replyTo);
644
- }
645
- const body = parentId != null ? { content, parent_id: parentId } : { content };
646
- const d = await authedPostWithRefresh(c.baseUrl, path, c.credOpts, body, c.flags.idempotencyKey || null, { fetchImpl: c.fetchImpl });
647
- const lines = ['留言已发出。'];
648
- if (d && d.id) lines.push(` 留言 ID:${d.id}`);
649
- lines.push(` 雇主回复后看:anytowork hire comment ${id} --list`);
650
- return io.ok(d || {}, lines.join('\n'));
651
- }
652
-
653
- async function cmdUsageView(c, io) {
654
- const id = hireIdOf(c, 2);
655
- if (!id) return io.fail(2, 'hire_id_required', '缺少招聘编号:anytowork hire usage-view <招聘编号> [--range day|week|month]');
656
- const q = new URLSearchParams();
657
- if (c.flags.range) q.set('range', String(c.flags.range));
658
- if (c.flags.date) q.set('date', String(c.flags.date));
659
- const d = await get(c, `/${enc(id)}/usage${q.toString() ? `?${q}` : ''}`);
660
- return io.ok(d, usageViewText(d, id));
661
- }
662
-
663
- const HANDLERS = {
664
- 'hire:policy': cmdPolicy,
665
- 'hire:openings': cmdOpenings,
666
- 'hire:show': cmdShow,
667
- 'hire:apply': cmdApply,
668
- 'hire:withdraw': cmdWithdraw,
669
- 'hire:pass': cmdPass,
670
- 'hire:sign': cmdSign,
671
- 'hire:decline': cmdDecline,
672
- 'hire:decide': cmdDecide,
673
- 'hire:topup': cmdTopup,
674
- 'hire:mine': cmdMine,
675
- 'hire:usage': cmdUsage,
676
- 'hire:habit': cmdHabit,
677
- 'hire:usage-view': cmdUsageView,
678
- 'hire:comment': cmdComment,
679
- };
680
-
681
- /**
682
- * Run one hire command. ctx: { command, positionals, flags, baseUrl, credOpts, fetchImpl, log, err, deps }.
683
- * deps.readFile(path) is injectable for tests (default: node:fs).
684
- */
685
- export async function runHire(ctx) {
686
- const io = makeIo(ctx);
687
- const deps = ctx.deps || {};
688
- const c = {
689
- ...ctx,
690
- deps: {
691
- sleep: deps.sleep,
692
- readFile: deps.readFile || ((p) => {
693
- // eslint-disable-next-line global-require
694
- return String(requireReadFileSync()(p, 'utf8'));
695
- }),
696
- },
697
- };
698
- try {
699
- const handler = HANDLERS[ctx.command];
700
- if (!handler) return io.fail(2, 'unknown_hire_command', '不认识的 hire 命令。运行 anytowork hire --help 看用法。');
701
- return await handler(c, io);
702
- } catch (e) {
703
- const m = mapHireError(e);
704
- return io.fail(m.exit, m.code, m.message, m.body && m.body.vars ? { vars: m.body.vars } : undefined);
705
- }
706
- }