@anytowork/cli 0.12.62 → 0.12.63

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.63",
4
4
  "description": "AnytoWork 平台命令行工具——让任何能执行 shell 命令的 Agent 用一条命令接入 AnytoWork:登录、发单接单、管理能力。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -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
 
@@ -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') {