@anytowork/cli 0.12.54 → 0.12.55

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anytowork/cli",
3
- "version": "0.12.54",
3
+ "version": "0.12.55",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/format.js CHANGED
@@ -1178,7 +1178,9 @@ export function hireEventLines(e) {
1178
1178
  case 'hire.topup': {
1179
1179
  const yuan = (n) => (Number(n || 0) / 100).toFixed(2).replace(/\.00$/, '');
1180
1180
  return [
1181
- `${ind}➕ 雇主今天给这条聘用加量:多付 ${yuan(p.pay_minor)} 元,今天的用量上限加 ${yuan(p.add_minor)} 元${p.deadline_at ? ',' + p.deadline_at + ' 前回复' : ''}`,
1181
+ p.reminder
1182
+ ? `${ind}⏰ 提醒:雇主今天的加量还在等你回复(多付 ${yuan(p.pay_minor)} 元,用量上限加 ${yuan(p.add_minor)} 元)${p.deadline_at ? ',' + p.deadline_at + ' 前不回复就全额退回雇主' : ',快到期了'}`
1183
+ : `${ind}➕ 雇主今天给这条聘用加量:多付 ${yuan(p.pay_minor)} 元,今天的用量上限加 ${yuan(p.add_minor)} 元${p.deadline_at ? ',' + p.deadline_at + ' 前回复' : ''}`,
1182
1184
  `${ind}能接就同意,接不了就拒绝(拒绝或超时,雇主的钱全额退回):anytowork hire topup ${id} --accept(或 --reject)`,
1183
1185
  ];
1184
1186
  }
@@ -0,0 +1,59 @@
1
+ // Always-on listener: waking the Agent for a hire event that waits for its answer (v0.38.41).
2
+ //
3
+ // Before this, the listener woke the Agent only for a workbench message (`wb.wake`). A hire event such as "you were
4
+ // picked, sign" or "the employer paid a top-up, accept or refuse" reached only whoever ran `anytowork poll`, so an Agent
5
+ // that is connected through the listener never heard of it. These events now start the Agent once, in a session of its
6
+ // own (the fixed key `hire-events`: there is no workbench session for them), with a prompt that names what waits and
7
+ // the commands to answer it. Informational hire events (start, wrap-up, stop for the day, left) do not wake the Agent.
8
+
9
+ import { hireEventLines } from '../format.js';
10
+ import { pickLang } from '../model-pledge.js';
11
+
12
+ /** The hire events that wait for an answer from the Agent and may end in a refund or a lost hire when nobody answers. */
13
+ export const WAKE_HIRE_EVENTS = new Set(['hire.to_sign', 'hire.topup', 'hire.reschedule']);
14
+
15
+ /** The session key every such run uses (placeholders {sid} and {session_key} of the start command). */
16
+ export const HIRE_WAKE_KEY = 'hire-events';
17
+
18
+ /** Events of one poll answer that should wake the Agent for a hire (an id is needed to tell a repeat from a new one). */
19
+ export function hireWakeEvents(events) {
20
+ return (events || []).filter((e) => e && WAKE_HIRE_EVENTS.has(e.event_type) && e.id != null);
21
+ }
22
+
23
+ /** True when the event itself says its time to answer has already gone by (an old event met after a restart). */
24
+ export function hireEventExpired(e, nowMs) {
25
+ const dl = e && e.payload && e.payload.deadline_at ? Date.parse(e.payload.deadline_at) : NaN;
26
+ return Number.isFinite(dl) && dl < nowMs;
27
+ }
28
+
29
+ const EN_LINE = {
30
+ 'hire.to_sign': (p) => `- You were picked for a hire${p.title ? ` "${p.title}"` : ''}${p.deadline_at ? `, sign before ${p.deadline_at}` : ''}: anytowork hire sign ${p.hire_id || '<hire id>'} (or hire decline)`,
31
+ 'hire.topup': (p) => `- ${p.reminder ? 'Reminder: ' : ''}the employer paid a top-up for today${p.deadline_at ? `, answer before ${p.deadline_at}` : ''}; no answer in time = a full refund: anytowork hire topup ${p.hire_id || '<hire id>'} --accept | --reject`,
32
+ 'hire.reschedule': (p) => `- The employer asks to move the start date to ${p.new_start_date || 'a new date'}: anytowork hire decide ${p.hire_id || '<hire id>'} --request ${p.request_id || '<request id>'} --accept | --reject`,
33
+ };
34
+
35
+ /** The words handed to the Agent on standard input. */
36
+ export function hireWakePrompt(events, env = process.env) {
37
+ const lang = pickLang(env);
38
+ const list = hireWakeEvents(events);
39
+ if (lang === 'en') {
40
+ const lines = list.map((e) => EN_LINE[e.event_type]((e.payload) || {}));
41
+ return [
42
+ '[AnytoWork] There are hire events waiting for you (this is not a chat message).',
43
+ ...lines,
44
+ 'Run `anytowork poll` to see everything that waits and `anytowork hire mine` for your hires (a top-up shows there as well), then answer; stop when done.',
45
+ ].join('\n');
46
+ }
47
+ const lines = [];
48
+ for (const e of list) {
49
+ const p = (e && e.payload) || {};
50
+ const own = hireEventLines(e).map((x) => `- ${x.trim()}`);
51
+ lines.push(...(own.length ? own : [`- ${e.event_type}`]));
52
+ if (p.reminder) lines.push(' (这是加量的到期提醒,快到回复截止时间了)');
53
+ }
54
+ return [
55
+ '[AnytoWork] 有招聘事件等你处理(不是聊天消息)。',
56
+ ...lines,
57
+ '先运行 anytowork poll 看全部待办,再运行 anytowork hire mine 看你的聘用(加量也在里面);加量用 anytowork hire topup <招聘编号> --accept 或 --reject。处理完就结束。',
58
+ ].join('\n');
59
+ }
@@ -20,6 +20,7 @@ import { WakeQueue } from './queue.js';
20
20
  import { buildPrompt, testPrompt } from './prompt.js';
21
21
  import { lt } from './text.js';
22
22
  import { writeNudge } from './nudge.js';
23
+ import { hireWakeEvents, hireWakePrompt, hireEventExpired, HIRE_WAKE_KEY } from './hire-wake.js'; // v0.38.41: hire events that wait for an answer
23
24
  import { wakeTestPrompt, noteWakeTests, testCode } from '../setup-hints.js'; // v0.37: wake-up test event
24
25
  import { autoCollect } from '../mt/collect.js'; // v0.36 (MT-19): send call records while idle
25
26
  import { workdirFromEvent, workdirsForScope } from '../mt/workdirs.js';
@@ -308,7 +309,7 @@ export class Listener {
308
309
  }
309
310
 
310
311
  // ---- waking ----------------------------------------------------------------------------------------
311
- /** Turn the events of one poll answer into queue entries; everything but wb.wake is ignored. */
312
+ /** Turn the events of one poll answer into queue entries; wb.wake, wake_test and the hire events that wait for an answer wake the Agent, everything else is ignored. */
312
313
  handleEvents(events) {
313
314
  // v0.36: a picked / signed event may carry the work folder of the job: set it up on this computer
314
315
  for (const e of events || []) { const wp = workdirFromEvent(this.credOpts, e); if (wp) this.logLine(`workdir ${wp}`); }
@@ -318,6 +319,7 @@ export class Listener {
318
319
  for (const e of events || []) {
319
320
  if (e && e.event_type === 'wake_test') this.handleWakeTest(e);
320
321
  }
322
+ this.handleHireEvents(events);
321
323
  for (const e of events || []) {
322
324
  if (!e || e.event_type !== 'wb.wake') continue;
323
325
  const p = e.payload || {};
@@ -357,6 +359,65 @@ export class Listener {
357
359
  this.pump();
358
360
  }
359
361
 
362
+ /**
363
+ * v0.38.41: a hire event that waits for the Agent (picked: sign; top-up: accept or refuse; new start date: decide).
364
+ * One run for all such events of one poll answer, in the session `hire-events` (no workbench session needed). An event
365
+ * id that was already handled is not started twice, an event whose own deadline has passed is skipped, a run already
366
+ * going holds the next one back until it ends. Like a wake-up it stops while paused and counts against the daily limit.
367
+ */
368
+ handleHireEvents(events) {
369
+ const fresh = hireWakeEvents(events);
370
+ if (!fresh.length) return;
371
+ if (!this.seenHire) this.seenHire = new Set();
372
+ const now = this.nowMs();
373
+ for (const e of fresh) {
374
+ const key = String(e.id);
375
+ if (this.seenHire.has(key)) continue;
376
+ this.seenHire.add(key);
377
+ if (this.seenHire.size > 200) this.seenHire.delete(this.seenHire.values().next().value);
378
+ if (hireEventExpired(e, now)) { this.logLine(`hire event id=${key} expired`); continue; }
379
+ if (this.isPaused()) { this.logLine(`hire event id=${key} paused`); continue; }
380
+ (this.hireWaiting || (this.hireWaiting = [])).push(e);
381
+ }
382
+ this.pumpHire();
383
+ }
384
+
385
+ pumpHire() {
386
+ if (this.hireRunning || !this.hireWaiting || !this.hireWaiting.length || this.isPaused()) return;
387
+ const now = this.nowMs();
388
+ if (runsToday(this.state, now) >= effectiveDailyMax(this.cfg, this.state)) { this.hireWaiting = []; this.pause('cap'); return; }
389
+ const batch = this.hireWaiting.splice(0);
390
+ countRun(this.state, now);
391
+ this.save();
392
+ this.hireRunning = true;
393
+ const pr = this.runHireWake(batch).catch(() => {}).finally(() => { this.hireRunning = false; this.active.delete(pr); this.pumpHire(); });
394
+ this.active.add(pr);
395
+ }
396
+
397
+ async runHireWake(batch) {
398
+ const now0 = this.nowMs();
399
+ const key = HIRE_WAKE_KEY;
400
+ const firstId = String(batch[0].id);
401
+ const promptFile = path.join(promptsDir(this.credOpts), `hire-${firstId}-${now0}.txt`);
402
+ let wrote = false;
403
+ const prompt = hireWakePrompt(batch, this.env);
404
+ try {
405
+ fs.mkdirSync(path.dirname(promptFile), { recursive: true, mode: 0o700 });
406
+ fs.writeFileSync(promptFile, prompt, { mode: 0o600 });
407
+ wrote = true;
408
+ } catch { /* the prompt still goes on standard input */ }
409
+ try {
410
+ const hid = batch.map((e) => e.payload && e.payload.hire_id).find((h) => isSafeId(String(h || ''))) || '';
411
+ const vals = { sid: key, sessionKey: key, groupId: '', wakeId: firstId, reason: 'hire_event', hireId: hid ? String(hid) : '', promptFile };
412
+ const env = buildRunEnv({ base: this.env, cfg: this.cfg, vals, credDir: this.credDir });
413
+ const res = await this.execCommand({ command: expandCommand(this.cfg.exec, vals), input: `${prompt}\n`, env, cwd: this.cfg.cwd, timeoutMs: this.cfg.timeoutMs });
414
+ const ok = !!res && res.code === 0 && !res.timedOut && !res.error;
415
+ this.logLine(`hire wake ids=${batch.map((e) => e.id).join(',')} ${ok ? 'ok' : 'fail'} ms=${this.nowMs() - now0}`);
416
+ } finally {
417
+ if (wrote) { try { fs.unlinkSync(promptFile); } catch { /* gone */ } }
418
+ }
419
+ }
420
+
360
421
  /**
361
422
  * v0.37 PA-12: the platform started a wake-up test for this Agent (`wake_test`: {test_id, nonce, deadline_at, next_action}).
362
423
  * Start the Agent once with a prompt that only asks it to answer the test. The isolation key is the fixed word