@anytowork/cli 0.12.62 → 0.12.64

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.62",
3
+ "version": "0.12.64",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
package/src/format.js CHANGED
@@ -1126,8 +1126,8 @@ export function formatPoll(data, { json = false, isFirstRun = false, activeTasks
1126
1126
  /** Lines under a hire.* event (empty for every other event). */
1127
1127
  export function hireEventLines(e) {
1128
1128
  const t = e && e.event_type;
1129
- // v0.38.57: the owner's shop opened (shop.opened): orders and job seeking take effect now, tell the owner
1130
- if (t === 'shop.opened') return [' 主人的店已开张,接单和求职已生效,请告诉主人'];
1129
+ // v0.38.57: the owner's shop opened (shop.opened): orders and job seeking can be turned on now, tell the owner
1130
+ if (t === 'shop.opened') return [' 主人的店铺开张了,接单和求职现在可以开启,请告诉主人'];
1131
1131
  if (!t || !String(t).startsWith('hire.')) return [];
1132
1132
  const p = (e && e.payload) || {};
1133
1133
  const ind = ' ';
package/src/index.js CHANGED
@@ -126,6 +126,7 @@ import { runRefund, isRefundCommand } from './refund-commands.js';
126
126
  import { runDiscover, isDiscoverCommand } from './discover-commands.js';
127
127
  import { runExtension } from './extension-commands.js';
128
128
  import { mapApiError } from './error-map.js';
129
+ import { withNetworkHint } from './network-hint.js';
129
130
  import { runContinue } from './cont-commands.js';
130
131
  import { runSpace, runTaskWorkspace, isSpaceCommand, isTaskWorkspaceCommand, SPACE_HELP, TASK_WORKSPACE_HELP } from './space-commands.js';
131
132
  import { runListen, LISTEN_HELP } from './listen-command.js';
@@ -735,7 +736,8 @@ async function runCore(argv, deps = {}, ctx = {}) {
735
736
  const env = deps.env || process.env;
736
737
  setHintEnv(env);
737
738
  const credDir = deps.credDir; // undefined → 用默认 ~/.anytowork(或 --profile 目录)
738
- const fetchImpl = deps.fetchImpl; // undefined → api 函数用全局 fetch
739
+ // v0.12.64: one wrapper for every command: a failed network request gets the same general hint (see network-hint.js)
740
+ const fetchImpl = withNetworkHint((...a) => (deps.fetchImpl || globalThis.fetch)(...a), env);
739
741
 
740
742
  const { command, flags, positionals, retiredKey, aliasOf } = parseArgs(argv);
741
743
  const baseUrl = resolveBaseUrl(env);
@@ -20,6 +20,8 @@ export const LISTEN_HELP = `anytowork listen — 保持监听 / stay connected
20
20
  Starts at login. As soon as a message arrives the platform wakes you: the task (with the workbench rules) is handed to
21
21
  your start command on standard input. Placeholders {sid} {session_key} {group_id} {prompt_file} work inside the command;
22
22
  the environment variables above are set for each run. Add --max-parallel 1 only if you really can do one thing at a time (default: up to 50 at once).
23
+ 启动项带上当前 HOME 与配置目录(HOME 不是系统主目录时);同一个身份只留一个启动项,重复安装是替换,不会多出一个。
24
+ The entry carries this HOME and config folder (when HOME is not the system home); one identity keeps one entry: installing again replaces it.
23
25
  anytowork listen test 用一条测试提示词试着启动你的命令,只看能不能启动,不碰平台消息
24
26
  Tries your start command once with a test prompt; touches no platform message.
25
27
  anytowork listen status 装了没有 / 在不在跑 / 今天叫醒几次 / 最近一次结果 / 是否暂停
@@ -2,9 +2,10 @@
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 os from 'node:os';
5
6
  import { configFromFlags, readConfig, writeConfig, readState, writeState, runsToday, statePath, configPath, cursorFile, effectiveDailyMax, LISTENER_SEEN_FRESH_MS } from './config.js';
6
7
  import { Listener, runStartTest } from './run.js';
7
- import { installAutostart, uninstallAutostart, labelOf, unitNameOf, defaultEntryPath, homeDiffers } from './install.js';
8
+ import { installAutostart, uninstallAutostart, labelOf, unitNameOf, defaultEntryPath, homeDiffers, slotOf } from './install.js';
8
9
  import { lt } from './text.js';
9
10
  import { reportListener } from '../api.js';
10
11
  import { resolveCredDir, configRootFromEnv, profileRootFromEnv } from '../profile.js';
@@ -48,6 +49,8 @@ export async function runListenInstall(p) {
48
49
  const cfg = configFromFlags(flags);
49
50
  const { profile, configDir, odd } = listenSlot(flags, env, deps);
50
51
  const dir = resolveCredDir(credOpts);
52
+ // v0.12.63: the HOME to write into the entry, only when it is not the system home (see listenSlot)
53
+ const runHome = odd ? (deps.envHome || env.HOME || env.USERPROFILE || os.homedir()) : null;
51
54
  // v0.12.40: start the command once before installing anything; a command that does not start is never installed.
52
55
  log(lt('install.trial', {}, env));
53
56
  const trial = await runStartTest({ cfg, credOpts, deps, env });
@@ -58,16 +61,23 @@ export async function runListenInstall(p) {
58
61
  result = { kind: 'none', notes: [] };
59
62
  } else {
60
63
  try {
64
+ // v0.12.63: one identity keeps one entry. This credentials folder may already have an entry under another name
65
+ // (installed with a profile name, then without one): remove it first, so the system never runs two listeners for it.
66
+ const prev = readConfig(credOpts);
67
+ const was = prev && prev.autostartEntry;
68
+ if (was && slotOf(was.profile, was.configDir) !== slotOf(profile, configDir)) {
69
+ await (deps.uninstallAutostart || uninstallAutostart)({ profile: was.profile, configDir: was.configDir, platform: deps.platform, home: deps.home, uid: deps.uid, runCmd: deps.runCmd });
70
+ }
61
71
  result = await (deps.installAutostart || installAutostart)({
62
- profile, configDir, logFile: `${dir}/listener.log`,
72
+ profile, configDir, runHome, logFile: `${dir}/listener.log`,
63
73
  platform: deps.platform, home: deps.home, runCmd: deps.runCmd, node: deps.node, entry: deps.entry, pathEnv: deps.pathEnv,
64
- startNow: deps.startNow,
74
+ startNow: deps.startNow, uid: deps.uid,
65
75
  });
66
76
  } catch (e) { failure = e && e.message ? e.message : String(e); }
67
77
  }
68
78
  writeConfig({
69
79
  ...cfg, autostart: !flags.noAutostart && !failure && result.kind !== 'none',
70
- autostartKind: result.kind, installedAt: new Date().toISOString(),
80
+ autostartKind: result.kind, autostartEntry: result.kind === 'none' ? null : { profile, configDir }, installedAt: new Date().toISOString(),
71
81
  nodePath: deps.node || process.execPath, entryPath: deps.entry || defaultEntryPath(),
72
82
  }, credOpts);
73
83
  if (flags.noAutostart) { log(lt('install.noautostart', {}, env)); return 0; }
@@ -83,8 +93,10 @@ export async function runListenUninstall(p) {
83
93
  const { flags, credOpts, baseUrl, fetchImpl, log, deps = {} } = p;
84
94
  const env = deps.env || process.env;
85
95
  try {
86
- const slot = listenSlot(flags, env, deps);
87
- await (deps.uninstallAutostart || uninstallAutostart)({ profile: slot.profile, configDir: slot.configDir, platform: deps.platform, home: deps.home, runCmd: deps.runCmd });
96
+ // v0.12.63: the entry recorded at install time is the one to remove, whatever name this command is given now
97
+ const rec = readConfig(credOpts);
98
+ const slot = rec && rec.autostartEntry ? rec.autostartEntry : listenSlot(flags, env, deps);
99
+ await (deps.uninstallAutostart || uninstallAutostart)({ profile: slot.profile, configDir: slot.configDir, platform: deps.platform, home: deps.home, uid: deps.uid, runCmd: deps.runCmd });
88
100
  } catch { /* nothing to undo */ }
89
101
  for (const f of [configPath(credOpts), cursorFile(credOpts), statePath(credOpts)]) { try { fs.unlinkSync(f); } catch { /* none */ } }
90
102
  try {
@@ -94,6 +94,7 @@ export function readConfig(credOpts) {
94
94
  nodePath: c.nodePath || null,
95
95
  entryPath: c.entryPath || null,
96
96
  autostartKind: c.autostartKind || null,
97
+ autostartEntry: c.autostartEntry && typeof c.autostartEntry === 'object' ? { profile: c.autostartEntry.profile || null, configDir: c.autostartEntry.configDir || null } : null, // v0.12.63: which start-at-login entry belongs to this identity
97
98
  };
98
99
  }
99
100
 
@@ -27,7 +27,7 @@ export function hireEventExpired(e, nowMs) {
27
27
  }
28
28
 
29
29
  const EN_LINE = {
30
- 'shop.opened': () => '- Your owner\'s shop is open: orders and job seeking are in effect now, tell your owner',
30
+ 'shop.opened': () => '- Your owner\'s shop is open: orders and job seeking can be turned on now, tell your owner',
31
31
  '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)`,
32
32
  '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`,
33
33
  '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,9 +33,10 @@ function xml(s) {
33
33
  }
34
34
 
35
35
  /** macOS LaunchAgent plist text. */
36
- export function launchdPlist({ label, node, entry, profile, pathEnv, configDir, logFile }) {
36
+ export function launchdPlist({ label, node, entry, profile, pathEnv, configDir, runHome, logFile }) {
37
37
  const args = [node, entry, ...runArgs(profile)];
38
- const env = { PATH: pathEnv || '/usr/local/bin:/usr/bin:/bin', ...(configDir ? { ANYTOWORK_CONFIG_DIR: configDir } : {}) };
38
+ // v0.12.63: HOME is written in when it is not the system home (a woken run would otherwise start in the login home)
39
+ const env = { PATH: pathEnv || '/usr/local/bin:/usr/bin:/bin', ...(runHome ? { HOME: runHome } : {}), ...(configDir ? { ANYTOWORK_CONFIG_DIR: configDir } : {}) };
39
40
  return `<?xml version="1.0" encoding="UTF-8"?>
40
41
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
41
42
  <plist version="1.0">
@@ -63,7 +64,7 @@ ${Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}
63
64
  function sdQuote(s) { return `"${String(s).replace(/(["\\])/g, '\\$1')}"`; }
64
65
 
65
66
  /** Linux systemd --user unit text. */
66
- export function systemdUnit({ node, entry, profile, pathEnv, configDir }) {
67
+ export function systemdUnit({ node, entry, profile, pathEnv, configDir, runHome }) {
67
68
  const exec = [node, entry, ...runArgs(profile)].map(sdQuote).join(' ');
68
69
  return `[Unit]
69
70
  Description=AnytoWork always-on listener (${profile || 'default'})
@@ -72,7 +73,7 @@ After=network-online.target
72
73
  [Service]
73
74
  ExecStart=${exec}
74
75
  Environment=${sdQuote(`PATH=${pathEnv || '/usr/local/bin:/usr/bin:/bin'}`)}
75
- ${configDir ? `Environment=${sdQuote(`ANYTOWORK_CONFIG_DIR=${configDir}`)}\n` : ''}Restart=on-failure
76
+ ${runHome ? `Environment=${sdQuote(`HOME=${runHome}`)}\n` : ''}${configDir ? `Environment=${sdQuote(`ANYTOWORK_CONFIG_DIR=${configDir}`)}\n` : ''}Restart=on-failure
76
77
  RestartSec=30
77
78
 
78
79
  [Install]
@@ -83,17 +84,18 @@ WantedBy=default.target
83
84
  function shSingle(s) { return `'${String(s).replace(/'/g, `'\\''`)}'`; }
84
85
 
85
86
  /** The crontab line used when there is no systemd (container, minimal Linux). */
86
- export function cronLine({ node, entry, profile, configDir }) {
87
+ export function cronLine({ node, entry, profile, configDir, runHome }) {
87
88
  const cmd = [shSingle(node), shSingle(entry), ...runArgs(profile).map(shSingle)].join(' ');
88
- const envPart = configDir ? `ANYTOWORK_CONFIG_DIR=${shSingle(configDir)} ` : '';
89
+ const envPart = `${runHome ? `HOME=${shSingle(runHome)} ` : ''}${configDir ? `ANYTOWORK_CONFIG_DIR=${shSingle(configDir)} ` : ''}`;
89
90
  return `@reboot ${envPart}${cmd} >/dev/null 2>&1 ${cronMarkOf(slotOf(profile, configDir))}`;
90
91
  }
91
92
 
92
93
  /** Windows: the arguments of `schtasks /Create` (run at the user's logon, no administrator needed). */
93
- export function schtasksCreateArgs({ node, entry, profile, configDir }) {
94
+ export function schtasksCreateArgs({ node, entry, profile, configDir, runHome }) {
94
95
  const run = [`"${node}"`, `"${entry}"`, ...runArgs(profile)].join(" ");
95
- // a task cannot carry environment variables, so a custom config dir is set by a small cmd wrapper
96
- const tr = configDir ? `cmd /c "set ANYTOWORK_CONFIG_DIR=${configDir}&& ${run}"` : run;
96
+ // a task cannot carry environment variables, so HOME and a custom config dir are set by a small cmd wrapper
97
+ const sets = `${runHome ? `set HOME=${runHome}&& ` : ''}${configDir ? `set ANYTOWORK_CONFIG_DIR=${configDir}&& ` : ''}`;
98
+ const tr = sets ? `cmd /c "${sets}${run}"` : run;
97
99
  return ["/Create", "/TN", taskNameOf(slotOf(profile, configDir)), "/SC", "ONLOGON", "/TR", tr, "/F"];
98
100
  }
99
101
 
@@ -139,7 +141,7 @@ export async function installAutostart(o) {
139
141
  const entry = o.entry || defaultEntryPath();
140
142
  const pathEnv = o.pathEnv != null ? o.pathEnv : process.env.PATH;
141
143
  const slot = slotOf(o.profile, o.configDir);
142
- const common = { node, entry, profile: o.profile || null, pathEnv, configDir: o.configDir || null };
144
+ const common = { node, entry, profile: o.profile || null, pathEnv, configDir: o.configDir || null, runHome: o.runHome || null };
143
145
  const notes = [];
144
146
 
145
147
  if (platform === 'darwin') {
@@ -570,6 +570,12 @@ export class Listener {
570
570
  await this.sleep(PAUSED_TICK_MS);
571
571
  }
572
572
 
573
+ /** v0.12.63: the loop is alive (also while the platform is busy or unreachable): `listen status` reads this mark. Saved at most every 30 s. */
574
+ beatAlive() {
575
+ this.state.seenAt = this.nowMs();
576
+ if (this.state.seenAt - (this.lastSeenSave || 0) >= 30000) { this.lastSeenSave = this.state.seenAt; this.save(); }
577
+ }
578
+
573
579
  /** @returns {Promise<number>} exit code: 0 stopped on request, 2 login lost / refused */
574
580
  async loop() {
575
581
  this.state.startedAt = this.nowMs();
@@ -608,6 +614,7 @@ export class Listener {
608
614
  this.err(`平台拒绝了监听请求,已停止 / The platform refused the request, stopped: ${msg}`);
609
615
  return 2;
610
616
  }
617
+ this.beatAlive();
611
618
  if (kind === 'busy') { await this.sleep(BUSY_MIN_MS + Math.floor(this.random() * BUSY_SPAN_MS)); continue; }
612
619
  if (!broken) this.err(`和平台的连接断了(${e && e.message ? e.message : '没有回应'}),正在自动重连,不用处理。 / Connection lost, reconnecting by itself.`);
613
620
  broken = true;
@@ -619,8 +626,7 @@ export class Listener {
619
626
  broken = false;
620
627
  reconnectMs = RECONNECT_FIRST_MS;
621
628
  if (data && data.next_cursor != null) { cursor = data.next_cursor; writeListenerCursor(cursor, this.credOpts); }
622
- this.state.seenAt = this.nowMs();
623
- if (this.state.seenAt - (this.lastSeenSave || 0) >= 30000) { this.lastSeenSave = this.state.seenAt; this.save(); } // lets `listen status` tell it is alive
629
+ this.beatAlive();
624
630
  const lis = data && data.listener;
625
631
  // v0.37 PA-06: the platform's own numbers (daily limit, failures before a pause) replace the local defaults
626
632
  if (lis && lis.limits && typeof lis.limits === 'object') {
@@ -0,0 +1,38 @@
1
+ // v0.12.64: one general hint for a failed network request. Sandboxed environments often block outgoing connections, and
2
+ // then every command ends in the bare "fetch failed"; the Agent cannot tell that this is something to ask for.
3
+ // runCore wraps its fetch once with this, so every command (also --json) gets the same line and nothing else changes.
4
+
5
+ import { pickLang } from "./model-pledge.js";
6
+
7
+ const NETWORK_CODES = new Set([
8
+ "ENOTFOUND", "ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "ENETDOWN",
9
+ "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET",
10
+ ]);
11
+
12
+ const HINT = {
13
+ zh: "提示:多半是当前环境禁止联网(比如沙箱)。请申请放行网络访问后重试。",
14
+ en: "Hint: this usually means the current environment blocks network access (a sandbox, for example). Ask to allow network access, then try again.",
15
+ };
16
+
17
+ /** True for a request that never got an HTTP answer: Node's "fetch failed" or a socket error code. */
18
+ export function isNetworkError(e) {
19
+ if (!e || typeof e !== "object" || e.status) return false;
20
+ const code = e.code || (e.cause && e.cause.code);
21
+ if (code && NETWORK_CODES.has(code)) return true;
22
+ return /fetch failed/i.test(String(e.message || ""));
23
+ }
24
+
25
+ /** Wrap a fetch function: a network failure gets the hint as a second line of its message (once); all else passes. */
26
+ export function withNetworkHint(fetchFn, env = process.env) {
27
+ return async (...args) => {
28
+ try {
29
+ return await fetchFn(...args);
30
+ } catch (e) {
31
+ if (isNetworkError(e) && !e.networkHinted) {
32
+ e.message = `${e.message}\n${HINT[pickLang(env)]}`;
33
+ e.networkHinted = true;
34
+ }
35
+ throw e;
36
+ }
37
+ };
38
+ }
@@ -35,8 +35,8 @@ const TEXT = {
35
35
  wakeTodo: { zh: ' ✗ 能被叫醒:还没验收。不用问主人,自己按 {url} 配好(方案 A 常驻监听;A 不可用时方案 B 每分钟 poll),再运行 anytowork setup test-wake', en: ' ✗ Be wakeable: not verified yet. Do not ask your owner: set it up following {url} (Plan A, the always-on listener; Plan B, a poll every minute, when A is unavailable), then run anytowork setup test-wake' },
36
36
  modelDone: { zh: ' ✓ 说明你用的模型:已说明', en: ' ✓ Say which models you use: done' },
37
37
  modelTodo: { zh: ' ✗ 说明你用的模型:还没说明。自己判断用的模型(读自己的配置或日志,必要时 anytowork usage sample --from <目录> --dry-run,读不到如实说),去 {url}#model-policy 照做,设一次默认策略就行', en: ' ✗ Say which models you use: not stated yet. Work out your models yourself (read your own config or logs, and if needed anytowork usage sample --from <dir> --dry-run; say so if you cannot tell), then follow {url}#model-policy; one default policy is enough' },
38
- shopOpen: { zh: ' 店铺(shop):已开张,接单和求职已生效', en: ' Shop: open, orders and jobs are in effect' },
39
- shopWait: { zh: ' 店铺(shop: {stage}):主人的店还没开张,接单和求职已保存但还不生效。{hint}', en: ' Shop ({stage}): your owner\'s shop is not open yet, order and job settings are saved but not in effect. {hint}' },
38
+ shopOpen: { zh: ' 接单和求职:现在可以开启,由主人在「我的团队」里决定、配置;你只转述,不替主人开启', en: ' Orders and jobs: can be turned on now. Your owner decides and sets them up in My Team; only pass this on, do not turn them on for your owner' },
39
+ shopWait: { zh: ' 店铺(shop: {stage}):主人的店还没开张,开张前接单和求职都开始不了。{hint}', en: ' Shop ({stage}): your owner\'s shop is not open yet; orders and jobs cannot start before it opens. {hint}' },
40
40
  cliOk: { zh: ' 命令行:已是最新', en: ' Command line: up to date' },
41
41
  cliTodo: { zh: ' ✗ 命令行:需要升级(现在 {cur},至少 {min})。自己运行 {cmd},用 anytowork --version 确认', en: ' ✗ Command line: upgrade needed (now {cur}, at least {min}). Run {cmd} yourself and confirm with anytowork --version' },
42
42
  checkinDone: { zh: ' ✓ 检查间隔:已报告(每 {n} 分钟)', en: ' ✓ Check-in interval: reported (every {n} minutes)' },