@koalaauto/agentchannel 3.45.2 → 3.45.3
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/dist/src/adapters/codex.js +4 -0
- package/dist/src/args.d.ts +1 -1
- package/dist/src/args.js +7 -60
- package/dist/src/cli-admin.d.ts +3 -0
- package/dist/src/cli-admin.js +307 -0
- package/dist/src/cli-memory.d.ts +3 -0
- package/dist/src/cli-memory.js +138 -0
- package/dist/src/cli-run.d.ts +28 -0
- package/dist/src/cli-run.js +429 -0
- package/dist/src/cli-shared.d.ts +73 -0
- package/dist/src/cli-shared.js +159 -0
- package/dist/src/cli.d.ts +9 -38
- package/dist/src/cli.js +21 -1181
- package/dist/src/client.d.ts +0 -22
- package/dist/src/client.js +0 -29
- package/dist/src/codexdaemon.d.ts +22 -0
- package/dist/src/codexdaemon.js +68 -0
- package/dist/src/invite_people.d.ts +31 -0
- package/dist/src/invite_people.js +238 -0
- package/dist/src/invite_person.d.ts +1 -1
- package/dist/src/invite_person.js +1 -1
- package/dist/src/mcp.d.ts +1 -1
- package/dist/src/mcp.js +7 -47
- package/dist/src/prompts.d.ts +2 -2
- package/dist/src/prompts.js +6 -17
- package/dist/src/runner/home.d.ts +45 -0
- package/dist/src/runner/home.js +150 -0
- package/dist/src/runner/runner.d.ts +3 -76
- package/dist/src/runner/runner.js +24 -326
- package/dist/src/runner/structured.d.ts +20 -0
- package/dist/src/runner/structured.js +64 -0
- package/dist/src/runner/traces.d.ts +29 -0
- package/dist/src/runner/traces.js +119 -0
- package/dist/src/sandboxcheck.d.ts +3 -0
- package/dist/src/sandboxcheck.js +16 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -1
- package/dist/src/import.d.ts +0 -244
- package/dist/src/import.js +0 -998
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// `ach remember`, `ach recall`, `ach decide-draft` and `ach memory ...`: the team Memory from the command line.
|
|
2
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import { UsageError } from './args.js';
|
|
4
|
+
import { HubError } from './client.js';
|
|
5
|
+
import { loadConfig } from './config.js';
|
|
6
|
+
import { untrustedBlock as wrapUntrusted } from './prompts.js';
|
|
7
|
+
import { MEMORY_NOTE, absUrl, channelFile, noAgentHint, str, text } from './cli-shared.js';
|
|
8
|
+
/** `ach remember`, `ach recall`, `ach decide-draft`, `ach memory ...`: the team Memory. */
|
|
9
|
+
export async function memoryCommand(ctx) {
|
|
10
|
+
const { p, io, env, v, out, client, admin } = ctx;
|
|
11
|
+
switch (p.cmd) {
|
|
12
|
+
case 'remember': {
|
|
13
|
+
const source = str(v.source);
|
|
14
|
+
if (!source)
|
|
15
|
+
throw new UsageError('remember: --source <link> is required (a hub permalink like #/t/TASK-12 or a GitHub URL)');
|
|
16
|
+
const r = await client().remember(text(p, '"<fact or lesson>"'), source, { channel: str(v.channel), topic: str(v.topic), toTeam: !!v['to-team'] });
|
|
17
|
+
if (v.json)
|
|
18
|
+
out(r);
|
|
19
|
+
else if (r?.held)
|
|
20
|
+
out(`held for review: ${r.conflicts?.[0]?.reason ?? 'it contradicts Memory'} (an admin or the decider accepts or discards it in the Inbox)`);
|
|
21
|
+
else if (v['to-team'])
|
|
22
|
+
out(`promoted to the team overview ${r?.id ?? ''}${r?.source_private ? ' (source stays private: others see "source: private channel")' : ''}`);
|
|
23
|
+
else
|
|
24
|
+
out(`remembered ${r?.id ?? ''} (the Memory maintainer folds it into a page)`);
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
|
27
|
+
case 'decide-draft': {
|
|
28
|
+
const source = str(v.source);
|
|
29
|
+
if (!source)
|
|
30
|
+
throw new UsageError('decide-draft: --source <link> is required');
|
|
31
|
+
const task = str(v.task) ?? str(env.ACH_TASK_ID);
|
|
32
|
+
const r = await client().decideDraft({ text: text(p, '"<who decided what>"'), source, by: str(v.by), channel: str(v.channel), topic: str(v.topic), task, ...(str(v.scope) ? { scope: str(v.scope) } : {}) });
|
|
33
|
+
if (v.json)
|
|
34
|
+
out(r);
|
|
35
|
+
else
|
|
36
|
+
out(`asked ${r?.decider_name ?? 'the decider'} ${r?.request_url ?? ''} (decision ${r?.id ?? ''}, ${r?.scope === 'task' ? 'for this task only, not a channel rule' : 'a standing channel rule'}${r?.money ? ' [money]' : ''}): their reply records it; nothing counts until they reply`);
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
case 'recall':
|
|
40
|
+
case 'memory search': {
|
|
41
|
+
const limit = str(v.limit) ? Number(str(v.limit)) : p.cmd === 'recall' ? 5 : undefined;
|
|
42
|
+
if (limit !== undefined && !(Number.isInteger(limit) && limit >= 1 && limit <= 30))
|
|
43
|
+
throw new UsageError(`${p.cmd}: --limit must be 1-30`);
|
|
44
|
+
const r = await client().wikiSearch(text(p, '"<query>"'), limit);
|
|
45
|
+
if (v.json)
|
|
46
|
+
out(r);
|
|
47
|
+
else if (p.cmd === 'recall') {
|
|
48
|
+
// one line + link per hit (never bloats the context)
|
|
49
|
+
// marks: superseded (with the current value), stale ("may be outdated, verify"), unconfirmed ("verify first")
|
|
50
|
+
const mark = (m) => (m === 'stale' ? '[stale: may be outdated, verify]' : m === 'unconfirmed' ? '[unconfirmed: not a confirmed decision, verify first]' : `[${m}]`);
|
|
51
|
+
const lines = r.results.slice(0, limit).map((x) => `- ${Array.isArray(x.marks) && x.marks.length ? `${x.marks.map(String).map(mark).join(' ')} ` : ''}${String(x.line ?? x.title).replace(/\s+/g, ' ').slice(0, 240)} — ${x.title} ${absUrl(env, x.url)}`);
|
|
52
|
+
out(lines.length ? [MEMORY_NOTE, ...lines].join('\n') : `nothing in Memory for "${r.query}" (try ach search for posts and tasks: background only)`);
|
|
53
|
+
}
|
|
54
|
+
else
|
|
55
|
+
out(wrapUntrusted(r.results.map((x) => ({ slug: x.slug, title: x.title, channel: x.channel_name, line: x.line, ...(x.marks?.length ? { marks: x.marks } : {}), url: absUrl(env, x.url) }))));
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
58
|
+
case 'memory read': {
|
|
59
|
+
const slug = p.positionals[0];
|
|
60
|
+
if (!slug)
|
|
61
|
+
throw new UsageError('memory read: <slug> is required');
|
|
62
|
+
const r = await client().wikiPage(slug);
|
|
63
|
+
out(v.json ? r : wrapUntrusted(r));
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
|
66
|
+
case 'memory hook': {
|
|
67
|
+
// Claude Code SessionStart hook: print a bounded Memory summary (stdout is added to the session context).
|
|
68
|
+
// It never fails the session: on any error it prints nothing and exits 0.
|
|
69
|
+
try {
|
|
70
|
+
const cfg = loadConfig(env);
|
|
71
|
+
if (!cfg.hub || !(cfg.key || cfg.runToken))
|
|
72
|
+
return 0;
|
|
73
|
+
const task = str(v.task) ?? str(env.ACH_TASK_ID);
|
|
74
|
+
const channel = str(v.channel) ?? str(env.ACH_CHANNEL) ?? channelFile(io.cwd ?? process.cwd());
|
|
75
|
+
const r = await client().memoryBrief(task ? { task } : channel ? { channel } : {});
|
|
76
|
+
out(v.json ? r : `${MEMORY_NOTE}\n${r.text}`);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
/* the session starts without Memory */
|
|
80
|
+
}
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
case 'memory pull': {
|
|
84
|
+
const dir = p.positionals[0];
|
|
85
|
+
if (!dir)
|
|
86
|
+
throw new UsageError('memory pull: <dir> is required');
|
|
87
|
+
const cfg = loadConfig(env);
|
|
88
|
+
if (!cfg.key && !cfg.runToken) {
|
|
89
|
+
io.err(await noAgentHint(cfg.adminToken ? admin() : undefined, 'memory pull <dir>'));
|
|
90
|
+
return 1;
|
|
91
|
+
}
|
|
92
|
+
const base = io.cwd ?? process.cwd();
|
|
93
|
+
const files = await (await import('./wiki.js')).wikiPull(client(), isAbsolute(dir) ? dir : resolve(base, dir), str(v.channel));
|
|
94
|
+
out(v.json ? { files } : `pulled ${files.length} page(s) into ${dir} (edit, then: ach memory push ${dir} --note "<what changed>")`);
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
case 'memory push': {
|
|
98
|
+
const dir = p.positionals[0];
|
|
99
|
+
if (!dir)
|
|
100
|
+
throw new UsageError('memory push: <dir> is required');
|
|
101
|
+
const note = str(v.note);
|
|
102
|
+
if (!note)
|
|
103
|
+
throw new UsageError('memory push: --note "<what changed>" is required');
|
|
104
|
+
const base = io.cwd ?? process.cwd();
|
|
105
|
+
let r;
|
|
106
|
+
try {
|
|
107
|
+
r = await (await import('./wiki.js')).wikiPush(client(), isAbsolute(dir) ? dir : resolve(base, dir), note);
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
// lint: list every problem line with its reason, then fail
|
|
111
|
+
const body = e instanceof HubError ? e.body : undefined;
|
|
112
|
+
if (e instanceof HubError && e.code === 'lint' && Array.isArray(body?.problems)) {
|
|
113
|
+
io.err(`not pushed: ${body.problems.length} problem(s). Fix each line and push again:`);
|
|
114
|
+
for (const x of body.problems)
|
|
115
|
+
io.err(` ${x.slug}.md${x.line ? ` line ${x.line}` : ''}: ${x.problem}${x.text ? `\n ${x.text}` : ''}`);
|
|
116
|
+
return 1;
|
|
117
|
+
}
|
|
118
|
+
throw e;
|
|
119
|
+
}
|
|
120
|
+
if (v.json) {
|
|
121
|
+
out(r);
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
if (r.held) {
|
|
125
|
+
out(`held for review, nothing written: ${r.message ?? ''}`);
|
|
126
|
+
for (const c of r.conflicts ?? [])
|
|
127
|
+
io.err(` ${c.reason}`);
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
out(`pushed: ${r.pages.length ? r.pages.map((x) => `${x.slug} v${x.version}${x.note && x.note !== note ? ` (${x.note})` : ''}`).join(', ') : 'no page changes'}; ${r.figures.length} new figure(s)`);
|
|
131
|
+
// warnings do not block the push: fix them in the next one
|
|
132
|
+
for (const w of r.warnings ?? [])
|
|
133
|
+
io.err(`warning: ${w.slug}.md line ${w.line}: ${w.problem}: ${w.text}`);
|
|
134
|
+
return 0;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type Parsed } from './args.js';
|
|
2
|
+
import { type Io } from './cli-shared.js';
|
|
3
|
+
/** A shell line with this terminal's stdin/stdout/stderr (sudo asks for its password there); its exit code. */
|
|
4
|
+
export declare function runInTerminal(line: string, env: NodeJS.ProcessEnv): Promise<number>;
|
|
5
|
+
/**
|
|
6
|
+
* Write <home>/bin/ach, a shim that runs this exact CLI with this node, so spawned
|
|
7
|
+
* agents always find a matching `ach` on PATH (even when the runner was started
|
|
8
|
+
* with npx or `node dist/src/cli.js`). Returns the dir to prepend to PATH.
|
|
9
|
+
*/
|
|
10
|
+
export declare function writeAchShim(home: string): string | undefined;
|
|
11
|
+
export declare function runCommand(p: Parsed, io: Io): Promise<number>;
|
|
12
|
+
/**
|
|
13
|
+
* `ach run` where the agent's key is not stored: the key lives only on its own machine and the hub keeps a hash of it, so it
|
|
14
|
+
* cannot be read back. The way back is a new key (the panel: the agent's page, Settings or the stopped-runner card) and its join line.
|
|
15
|
+
*/
|
|
16
|
+
export declare const NO_KEY_MESSAGE: {
|
|
17
|
+
readonly en: "ach run: there is no key for this agent on this machine (deleted, or a new machine or directory).\nA key cannot be recovered: in the panel open the agent and rotate its key (an admin or its owner can), then run the new `join` line here, in the agent's project directory.";
|
|
18
|
+
readonly zh: "ach run:这台机器上没有这个智能体的密钥(被删除了,或是新机器、新目录)。\n密钥找不回,只能换新:在面板里打开这个智能体,点「换新密钥」(管理员或负责人可以),再到它的项目目录里运行新生成的 `join` 命令。";
|
|
19
|
+
};
|
|
20
|
+
/** B7: `ach run` exit code when the hub answers 401 (systemd: RestartPreventExitStatus=78). */
|
|
21
|
+
export declare const AUTH_EXIT_CODE = 78;
|
|
22
|
+
export declare const AUTH_EXIT_MESSAGE = "ach run: key rotated or agent deactivated \u2014 run ach join";
|
|
23
|
+
/**
|
|
24
|
+
* The agent whose key this home already holds for `hub`, when it is another agent than `meId` and its key still works (a key the
|
|
25
|
+
* hub refuses belongs to nobody: replacing it loses nothing). Unknown (hub unreachable) counts as another agent: keeping a key
|
|
26
|
+
* costs a folder, losing one costs a runner.
|
|
27
|
+
*/
|
|
28
|
+
export declare function otherAgentHere(env: NodeJS.ProcessEnv, hub: string, newKey: string, meId: string, cfId: string | undefined, cfSecret: string | undefined, fetch: Io['fetch']): Promise<string | undefined>;
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
// `ach run`: the runner on this machine. Starting it (one per agent home, a lock), its self-update supervision, and installing
|
|
2
|
+
// it as a user service (systemd, launchd) that starts it again after a reboot or an update.
|
|
3
|
+
import { execFileSync, execSync, spawn } from 'node:child_process';
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { basename, delimiter, dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { developerDir } from './adapters/scope.js';
|
|
8
|
+
import { acquireRunnerLock, RunnerLockedError } from './runner/lock.js';
|
|
9
|
+
import { UsageError } from './args.js';
|
|
10
|
+
import { Client, clientFromConfig, HubError, isZh } from './client.js';
|
|
11
|
+
import { achHome, defaultHome, loadConfig, readFileConfig, resolveClaimDelay, writeFileConfig } from './config.js';
|
|
12
|
+
import { isPerm } from './perm.js';
|
|
13
|
+
import { bootGuard, markHealthy, SelfUpdater, superviseSelf, UPDATE_EXIT_CODE, UPDATE_HANDOFF_EXIT_CODE, waitForWindowsUpdate } from './selfupdate.js';
|
|
14
|
+
import { inheritedEnv } from './env.js';
|
|
15
|
+
import { parseNum, splitList, str } from './cli-shared.js';
|
|
16
|
+
import { fileURLToPath as toPath } from 'node:url';
|
|
17
|
+
import { dirname as dirOf, join as joinPath } from 'node:path';
|
|
18
|
+
/** The CLI's entry (dist/src/cli.js, next to this file): what a runner shim and a service start. */
|
|
19
|
+
const CLI_JS = joinPath(dirOf(toPath(import.meta.url)), 'cli.js');
|
|
20
|
+
/** A shell line with this terminal's stdin/stdout/stderr (sudo asks for its password there); its exit code. */
|
|
21
|
+
export function runInTerminal(line, env) {
|
|
22
|
+
return new Promise((res) => {
|
|
23
|
+
const c = spawn('/bin/sh', ['-c', line], { env, stdio: 'inherit' });
|
|
24
|
+
c.on('error', () => res(127));
|
|
25
|
+
c.on('exit', (code) => res(code ?? 1));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function shq(s) {
|
|
29
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Write <home>/bin/ach, a shim that runs this exact CLI with this node, so spawned
|
|
33
|
+
* agents always find a matching `ach` on PATH (even when the runner was started
|
|
34
|
+
* with npx or `node dist/src/cli.js`). Returns the dir to prepend to PATH.
|
|
35
|
+
*/
|
|
36
|
+
export function writeAchShim(home) {
|
|
37
|
+
if (process.platform === 'win32')
|
|
38
|
+
return undefined;
|
|
39
|
+
const dir = join(home, 'bin');
|
|
40
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
41
|
+
const f = join(dir, 'ach');
|
|
42
|
+
writeFileSync(f, `#!/bin/sh\nexec ${shq(process.execPath)} ${shq(CLI_JS)} "$@"\n`, { mode: 0o700 });
|
|
43
|
+
chmodSync(f, 0o700);
|
|
44
|
+
return dir;
|
|
45
|
+
}
|
|
46
|
+
export async function runCommand(p, io) {
|
|
47
|
+
const v = p.values;
|
|
48
|
+
const env = io.env;
|
|
49
|
+
if (env.ACH_RUN_TOKEN)
|
|
50
|
+
throw new UsageError('run: refusing to start a runner inside a spawned agent (ACH_RUN_TOKEN is set)');
|
|
51
|
+
// Windows: a release being installed by the helper of the runner before this one (a Startup script restarted it in between).
|
|
52
|
+
// Wait before the key is read (that loads a native module, whose file the install replaces), then start the new release.
|
|
53
|
+
if (process.platform === 'win32' && (await waitForWindowsUpdate(achHome(env), { log: io.err }))) {
|
|
54
|
+
return env.ACH_SUPERVISED === '1' ? UPDATE_EXIT_CODE : superviseSelf({ log: io.err });
|
|
55
|
+
}
|
|
56
|
+
const cfg = loadConfig(env);
|
|
57
|
+
// No key on this machine (deleted, a new machine or directory). It exits like a refused key: a service that exits 2 here
|
|
58
|
+
// would be restarted for ever, and `ach login` is no way back for someone who no longer has the key.
|
|
59
|
+
if (!cfg.key)
|
|
60
|
+
return authExit(io, NO_KEY_MESSAGE[isZh(env) ? 'zh' : 'en']);
|
|
61
|
+
// the hub names the newest release on every answer: the updater hears it at once instead of at its next 6-hourly check
|
|
62
|
+
let updater;
|
|
63
|
+
const c = clientFromConfig(cfg, { fetch: io.fetch, role: 'runner', onLatestClient: (latest) => void updater?.heardLatest(latest)?.catch(() => { }) });
|
|
64
|
+
const home = achHome(env);
|
|
65
|
+
const dir = resolve(io.cwd ?? process.cwd(), str(v.dir) ?? '.');
|
|
66
|
+
// the default home, joined before join recorded its directory, learns it from its runner so its MCP sessions can say where
|
|
67
|
+
// it belongs (display only: homes under agents/ are found by their dir, so only join sets theirs)
|
|
68
|
+
try {
|
|
69
|
+
const file = readFileConfig(env);
|
|
70
|
+
if (!file.dir && home === defaultHome(env))
|
|
71
|
+
writeFileConfig({ ...file, dir }, env);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
/* read-only home: the MCP just cannot say where this agent belongs */
|
|
75
|
+
}
|
|
76
|
+
const { GitWorkspace, parseRepoFlags } = await import('./runner/workspace.js');
|
|
77
|
+
const { Runner, gcWorktrees, prepareAgentHome, realHomeOf } = await import('./runner/runner.js');
|
|
78
|
+
let repoFlags;
|
|
79
|
+
try {
|
|
80
|
+
repoFlags = parseRepoFlags(Array.isArray(v.repo) ? v.repo : [], io.cwd ?? process.cwd());
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
throw new UsageError(`run: ${e.message}`);
|
|
84
|
+
}
|
|
85
|
+
// P3: repos from config.json, overridden by --repo name=path.
|
|
86
|
+
const repos = { ...(cfg.repos ?? {}), ...repoFlags };
|
|
87
|
+
const ws = new GitWorkspace(dir, home, io.err, repos);
|
|
88
|
+
if (v.gc) {
|
|
89
|
+
const removed = await gcWorktrees(c, ws, { days: str(v.days) ? parseNum(str(v.days), 'days') : 7, log: io.err });
|
|
90
|
+
io.out(removed.length ? `removed ${removed.length} worktree(s): ${removed.join(', ')}` : 'nothing to remove');
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
const perm = (str(v.perm) ?? 'workdir');
|
|
94
|
+
if (!isPerm(perm))
|
|
95
|
+
throw new UsageError('run: --perm must be read|workdir|full');
|
|
96
|
+
const claimDelay = resolveClaimDelay({
|
|
97
|
+
claimDelay: str(v['claim-delay']) ? parseNum(str(v['claim-delay']), 'claim-delay') : undefined,
|
|
98
|
+
interactiveFirst: !!v['interactive-first'] || !!cfg.interactiveFirst,
|
|
99
|
+
});
|
|
100
|
+
let me;
|
|
101
|
+
try {
|
|
102
|
+
me = await c.me();
|
|
103
|
+
}
|
|
104
|
+
catch (e) {
|
|
105
|
+
// B7: a key that is already refused at startup exits like a 401 mid-run, so systemd/launchd stop restarting it
|
|
106
|
+
if (e instanceof HubError && e.status === 401)
|
|
107
|
+
return authExit(io);
|
|
108
|
+
throw e;
|
|
109
|
+
}
|
|
110
|
+
if (v['install-service'])
|
|
111
|
+
return installService(p, io, { agentName: me.name, formerNames: me.former_names ?? [], dir, repos: repoFlags, home });
|
|
112
|
+
// started by a service written by an early release (node on the npx cache, which no restart ever refreshes): make it `npx -y <spec>`
|
|
113
|
+
const moved = await moveOldService(io, me.name, home);
|
|
114
|
+
if (moved)
|
|
115
|
+
return UPDATE_EXIT_CODE;
|
|
116
|
+
const runtime = str(v.runtime) ?? (me.runtime === 'codex' || me.runtime === 'kiro' ? me.runtime : 'claude');
|
|
117
|
+
// what the permission and the network list do not cover, said where the person starting the runner will read it
|
|
118
|
+
if (perm === 'full')
|
|
119
|
+
io.err('warning: --perm full runs commands with no sandbox (bypassPermissions): anything in a task that reaches the agent can run anything with your rights.');
|
|
120
|
+
const { makeAdapter } = await import('./adapters/index.js');
|
|
121
|
+
let adapter;
|
|
122
|
+
try {
|
|
123
|
+
adapter = makeAdapter(runtime, { model: str(v.model), env });
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
throw new UsageError(`run: ${e.message}`);
|
|
127
|
+
}
|
|
128
|
+
// keeps this runner on the hub's release: waits for the runs in flight, installs, exits UPDATE_EXIT_CODE so the service restarts
|
|
129
|
+
const passEnv = (Array.isArray(v['pass-env']) ? v['pass-env'] : []).flatMap(splitList);
|
|
130
|
+
const baseEnv = (() => {
|
|
131
|
+
const shim = writeAchShim(home);
|
|
132
|
+
// macOS: the real git and python3 of the developer tools before the /usr/bin shims (scope.ts developerDir)
|
|
133
|
+
const dev = developerDir();
|
|
134
|
+
const path = [shim, dev ? `${dev}/usr/bin` : undefined, env.PATH].filter(Boolean).join(delimiter);
|
|
135
|
+
return shim || dev ? { ...env, PATH: path } : env;
|
|
136
|
+
})();
|
|
137
|
+
const runner = new Runner({
|
|
138
|
+
client: c,
|
|
139
|
+
adapter,
|
|
140
|
+
workspace: ws,
|
|
141
|
+
home,
|
|
142
|
+
hub: cfg.hub,
|
|
143
|
+
dir,
|
|
144
|
+
max: str(v.max) ? Math.max(1, Math.floor(parseNum(str(v.max), 'max'))) : 2,
|
|
145
|
+
perm,
|
|
146
|
+
intervalMs: (str(v.interval) ? parseNum(str(v.interval), 'interval') : 3) * 1000,
|
|
147
|
+
claimDelayMs: claimDelay * 1000,
|
|
148
|
+
readAhead: true,
|
|
149
|
+
noTrace: !!v['no-trace'] || env.ACH_NO_TRACE === '1',
|
|
150
|
+
cfId: cfg.cfId,
|
|
151
|
+
cfSecret: cfg.cfSecret,
|
|
152
|
+
secrets: [cfg.key ?? ''].filter(Boolean),
|
|
153
|
+
publicUrl: env.ACH_PUBLIC_URL || undefined,
|
|
154
|
+
onClientTooOld: () => void updater?.nudge(),
|
|
155
|
+
passEnv,
|
|
156
|
+
startInfo: await (async () => {
|
|
157
|
+
const { startedByService } = await import('./servicefix.js');
|
|
158
|
+
const service = !startedByService(me.name, process.platform, env) ? '' : process.platform === 'darwin' ? 'launchd' : 'systemd';
|
|
159
|
+
return {
|
|
160
|
+
dir,
|
|
161
|
+
...(env.AGENTCHANNEL_HOME ? { home: home } : {}),
|
|
162
|
+
...(Object.keys(repoFlags).length ? { repos: repoFlags } : {}),
|
|
163
|
+
...(v['interactive-first'] ? { interactive_first: true } : {}),
|
|
164
|
+
service,
|
|
165
|
+
...(service === 'systemd' ? { linger: lingers(env) } : {}),
|
|
166
|
+
};
|
|
167
|
+
})(),
|
|
168
|
+
baseEnv,
|
|
169
|
+
log: io.err,
|
|
170
|
+
sandboxCheck: async () => {
|
|
171
|
+
// kiro runs in Kiro's cloud sandbox: what this machine needs is kiro-cli and its key
|
|
172
|
+
if (runtime === 'kiro')
|
|
173
|
+
return (await import('./kirocheck.js')).probeKiro({ env });
|
|
174
|
+
const { probeEnvironment } = await import('./envcheck.js');
|
|
175
|
+
// the sandboxed command gets the env a run gets (inherited vars and a scratch home like a task's), so what a run cannot start
|
|
176
|
+
// without shows here, not in the first task (TASK-59)
|
|
177
|
+
const { env: homeEnv } = prepareAgentHome(join(tmpdir(), 'ach-homes'), me.name, 'startup-check', realHomeOf(baseEnv), baseEnv.CODEX_HOME || undefined);
|
|
178
|
+
return probeEnvironment(runtime === 'codex' ? 'codex' : 'claude', { env, hub: cfg.hub, runEnv: { ...inheritedEnv(baseEnv, passEnv), ...homeEnv } });
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
io.err(`ach run: agent ${me.name}, runtime ${runtime}, perm min(${me.perm_level}, ${perm}), dir ${dir}` +
|
|
182
|
+
(Object.keys(repos).length ? `, repos ${Object.entries(repos).map(([k, x]) => `${k}=${x}`).join(' ')}` : '') +
|
|
183
|
+
`, claim delay ${claimDelay}s`);
|
|
184
|
+
// desktop notifications for the owner (deduped by event id, also across restarts)
|
|
185
|
+
let desk = null;
|
|
186
|
+
if (v.notify && !v['no-notify']) {
|
|
187
|
+
const { DeskNotifier } = await import('./desknotify.js');
|
|
188
|
+
const dn = new DeskNotifier({ request: (m, path) => c.request(m, path), socket: () => c.eventsSocket(), home, hub: env.ACH_PUBLIC_URL || cfg.hub, env, log: io.err });
|
|
189
|
+
dn.start();
|
|
190
|
+
desk = dn;
|
|
191
|
+
io.err('ach run: desktop notifications on');
|
|
192
|
+
}
|
|
193
|
+
updater = new SelfUpdater({
|
|
194
|
+
fetchVersions: () => c.request('GET', '/api/ach/auth/config'),
|
|
195
|
+
runner,
|
|
196
|
+
home,
|
|
197
|
+
env,
|
|
198
|
+
log: io.err,
|
|
199
|
+
});
|
|
200
|
+
updater.start();
|
|
201
|
+
const shutdown = () => {
|
|
202
|
+
io.err('stopping runner...');
|
|
203
|
+
updater?.stop();
|
|
204
|
+
desk?.stop();
|
|
205
|
+
runner.stop().then(() => process.exit(0));
|
|
206
|
+
};
|
|
207
|
+
process.once('SIGINT', shutdown);
|
|
208
|
+
process.once('SIGTERM', shutdown);
|
|
209
|
+
// one runner per home: a second one would overwrite the first's state
|
|
210
|
+
let release = () => { };
|
|
211
|
+
try {
|
|
212
|
+
release = acquireRunnerLock(home);
|
|
213
|
+
}
|
|
214
|
+
catch (e) {
|
|
215
|
+
if (e instanceof RunnerLockedError)
|
|
216
|
+
throw new UsageError(`run: ${e.message}`);
|
|
217
|
+
throw e;
|
|
218
|
+
}
|
|
219
|
+
process.once('exit', () => release()); // the shutdown path ends with process.exit, which skips the finally below
|
|
220
|
+
// the brake (counted only for the runner that holds the lock, not for a second `ach run` the lock turns away): a release this
|
|
221
|
+
// runner updated itself to that keeps failing to start goes back to the one before
|
|
222
|
+
if ((await bootGuard(home, { log: io.err })) === 'rolledback') {
|
|
223
|
+
release();
|
|
224
|
+
return UPDATE_EXIT_CODE;
|
|
225
|
+
}
|
|
226
|
+
// five minutes of running is a working release (the guard stops counting its starts)
|
|
227
|
+
setTimeout(() => markHealthy(home), 5 * 60_000).unref?.();
|
|
228
|
+
let end;
|
|
229
|
+
try {
|
|
230
|
+
end = await runner.start();
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
release();
|
|
234
|
+
}
|
|
235
|
+
updater.stop();
|
|
236
|
+
desk?.stop();
|
|
237
|
+
// B7: the hub refused the agent key: rotated, agent disabled or owner deactivated.
|
|
238
|
+
if (end === 'unauthorized')
|
|
239
|
+
return authExit(io);
|
|
240
|
+
if (updater.restarting && updater.installed === 'handoff') {
|
|
241
|
+
io.err(`ach run: exiting for the update; the installer starts the runner again when it is done`);
|
|
242
|
+
return UPDATE_HANDOFF_EXIT_CODE;
|
|
243
|
+
}
|
|
244
|
+
if (updater.restarting) {
|
|
245
|
+
// started by hand (no systemd / launchd behind it) from a global install: nothing would start it again, so it does that itself
|
|
246
|
+
if (updater.installed === 'global' && process.env.ACH_SUPERVISED !== '1' && !(await import('./servicefix.js')).startedByService(me.name, process.platform, process.env)) {
|
|
247
|
+
io.err('ach run: updated; starting the new release here');
|
|
248
|
+
return superviseSelf({ log: io.err });
|
|
249
|
+
}
|
|
250
|
+
io.err(`ach run: updated; exiting ${UPDATE_EXIT_CODE} so the service restarts on the new release (started by hand? run it again)`);
|
|
251
|
+
return UPDATE_EXIT_CODE;
|
|
252
|
+
}
|
|
253
|
+
return 0;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* `ach run` where the agent's key is not stored: the key lives only on its own machine and the hub keeps a hash of it, so it
|
|
257
|
+
* cannot be read back. The way back is a new key (the panel: the agent's page, Settings or the stopped-runner card) and its join line.
|
|
258
|
+
*/
|
|
259
|
+
export const NO_KEY_MESSAGE = {
|
|
260
|
+
en: 'ach run: there is no key for this agent on this machine (deleted, or a new machine or directory).\nA key cannot be recovered: in the panel open the agent and rotate its key (an admin or its owner can), then run the new `join` line here, in the agent\'s project directory.',
|
|
261
|
+
zh: 'ach run:这台机器上没有这个智能体的密钥(被删除了,或是新机器、新目录)。\n密钥找不回,只能换新:在面板里打开这个智能体,点「换新密钥」(管理员或负责人可以),再到它的项目目录里运行新生成的 `join` 命令。',
|
|
262
|
+
};
|
|
263
|
+
/** B7: print the rejoin hint and return the auth exit code (ACH_AUTH_EXIT_CODE overrides it). */
|
|
264
|
+
function authExit(io, message = AUTH_EXIT_MESSAGE) {
|
|
265
|
+
io.err(message);
|
|
266
|
+
const code = Number(io.env.ACH_AUTH_EXIT_CODE ?? AUTH_EXIT_CODE);
|
|
267
|
+
return Number.isInteger(code) && code >= 0 ? code : AUTH_EXIT_CODE;
|
|
268
|
+
}
|
|
269
|
+
/** B7: `ach run` exit code when the hub answers 401 (systemd: RestartPreventExitStatus=78). */
|
|
270
|
+
export const AUTH_EXIT_CODE = 78;
|
|
271
|
+
export const AUTH_EXIT_MESSAGE = 'ach run: key rotated or agent deactivated — run ach join';
|
|
272
|
+
/**
|
|
273
|
+
* P4: write a launchd plist (macOS) or systemd user unit (Linux) that runs this
|
|
274
|
+
* runner with the same flags, and load it: it runs now and at every login.
|
|
275
|
+
* From the npx cache the unit runs `npx -y <spec>` (the cache may be cleared;
|
|
276
|
+
* the MCP entry does the same). ACH_SERVICE_DIR / ACH_SERVICE_PLATFORM override
|
|
277
|
+
* the location and platform (tests); with ACH_SERVICE_DIR nothing is loaded.
|
|
278
|
+
*/
|
|
279
|
+
async function installService(p, io, o) {
|
|
280
|
+
const { serviceFile, writeServiceFile } = await import('./service.js');
|
|
281
|
+
const { isBundledBin, npmSpec, whichAll } = await import('./invite.js');
|
|
282
|
+
const env = io.env;
|
|
283
|
+
const platform = (env.ACH_SERVICE_PLATFORM || process.platform);
|
|
284
|
+
if (platform !== 'darwin' && platform !== 'linux' && platform !== 'win32')
|
|
285
|
+
throw new UsageError(`run --install-service: unsupported platform ${platform} (macOS, Linux and Windows only)`);
|
|
286
|
+
const v = p.values;
|
|
287
|
+
const args = ['--dir', o.dir];
|
|
288
|
+
for (const [name, path] of Object.entries(o.repos))
|
|
289
|
+
args.push('--repo', `${name}=${path}`);
|
|
290
|
+
for (const f of ['runtime', 'interval', 'max', 'perm', 'model', 'claim-delay'])
|
|
291
|
+
if (str(v[f]))
|
|
292
|
+
args.push(`--${f}`, str(v[f]));
|
|
293
|
+
if (v['interactive-first'])
|
|
294
|
+
args.push('--interactive-first');
|
|
295
|
+
// desktop notifications only when asked for: browser notifications are the main way to reach the person
|
|
296
|
+
if (v.notify && !v['no-notify'])
|
|
297
|
+
args.push('--notify');
|
|
298
|
+
const passEnv = (Array.isArray(v['pass-env']) ? v['pass-env'] : []).flatMap(splitList);
|
|
299
|
+
for (const n of passEnv)
|
|
300
|
+
args.push('--pass-env', n);
|
|
301
|
+
// not the npx cache's bin dirs: they vanish when npm clears the cache, and hold bundled tools (a codex) that are not the user's
|
|
302
|
+
const path = (env.PATH ?? '').split(delimiter).filter((d) => d && !isBundledBin(join(d, 'x'))).join(delimiter);
|
|
303
|
+
const svcEnv = { PATH: path || '/usr/bin:/bin' };
|
|
304
|
+
if (env.AGENTCHANNEL_HOME)
|
|
305
|
+
svcEnv.AGENTCHANNEL_HOME = env.AGENTCHANNEL_HOME;
|
|
306
|
+
if (env.ACH_KEYSTORE)
|
|
307
|
+
svcEnv.ACH_KEYSTORE = env.ACH_KEYSTORE;
|
|
308
|
+
// B7: launchd restarts only after an unsuccessful exit (KeepAlive.SuccessfulExit
|
|
309
|
+
// = false), so under launchd a 401 exits 0 and the runner stays down.
|
|
310
|
+
if (platform === 'darwin')
|
|
311
|
+
svcEnv.ACH_AUTH_EXIT_CODE = '0';
|
|
312
|
+
mkdirSync(join(o.home, 'logs'), { recursive: true, mode: 0o700 });
|
|
313
|
+
const self = CLI_JS;
|
|
314
|
+
const npx = /[\\/]_npx[\\/]/.test(self) ? (whichAll('npx', env).find((x) => !isBundledBin(x)) ?? join(dirname(process.execPath), 'npx')) : undefined;
|
|
315
|
+
const f = serviceFile({
|
|
316
|
+
platform,
|
|
317
|
+
agentName: o.agentName,
|
|
318
|
+
command: npx ? [npx, '-y', npmSpec()] : [process.execPath, self],
|
|
319
|
+
args,
|
|
320
|
+
env: svcEnv,
|
|
321
|
+
logFile: join(o.home, 'logs', 'runner.log'),
|
|
322
|
+
}, env.ACH_SERVICE_DIR || undefined, env);
|
|
323
|
+
writeServiceFile(f);
|
|
324
|
+
const load = !env.ACH_SERVICE_DIR;
|
|
325
|
+
// an agent that was renamed has an older service under its former name: two runners on one key. They go.
|
|
326
|
+
// A service in this home under a name this agent never had is another agent's runner (its key here was replaced): it stays.
|
|
327
|
+
const { retireSiblings } = await import('./servicefix.js');
|
|
328
|
+
const kept = [];
|
|
329
|
+
const retired = retireSiblings({ platform, dir: env.ACH_SERVICE_DIR || undefined, env, ownPath: f.path, ownHome: o.home, run: load, names: [o.agentName, ...o.formerNames], kept });
|
|
330
|
+
let failed = '';
|
|
331
|
+
if (load) {
|
|
332
|
+
for (const c of f.start) {
|
|
333
|
+
try {
|
|
334
|
+
if (platform === 'win32')
|
|
335
|
+
execSync(c, { env, stdio: ['ignore', 'ignore', 'pipe'] }); // cmd.exe
|
|
336
|
+
else
|
|
337
|
+
execFileSync('/bin/sh', ['-c', c], { env, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
338
|
+
}
|
|
339
|
+
catch (e) {
|
|
340
|
+
failed = `${c}: ${String(e?.stderr ?? e?.message ?? e).trim().split('\n')[0]}`;
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
// Linux: a user unit stops at logout (an SSH session ending) unless the user lingers
|
|
346
|
+
const linger = platform === 'linux' && load && !failed ? lingers(env) : true;
|
|
347
|
+
const logs = platform === 'linux' ? `journalctl --user -u ${basename(f.path)} -f` : join(o.home, 'logs', 'runner.log');
|
|
348
|
+
if (v.json) {
|
|
349
|
+
io.out(JSON.stringify({ path: f.path, started: load && !failed, ...(failed ? { error: failed } : {}), start: f.start, stop: f.stop, retired, ...(kept.length ? { kept } : {}), ...(linger ? {} : { linger: false }) }, null, 2));
|
|
350
|
+
return failed ? 1 : 0;
|
|
351
|
+
}
|
|
352
|
+
io.out([
|
|
353
|
+
!load ? `wrote ${f.path} (not loaded: ACH_SERVICE_DIR is set). Start it with:` : failed ? `wrote ${f.path}, but starting it failed: ${failed}\nStart it with:` : `installed and started ${f.path} (also starts at login)`,
|
|
354
|
+
...(!load || failed ? f.start.map((x) => ` ${x}`) : []),
|
|
355
|
+
...retired.map((r) => `stopped and removed the older service of this agent (${r.agentName}): ${r.path}`),
|
|
356
|
+
...kept.map((r) => `Note: ${r.path} runs agent ${r.agentName} from the same AgentChannel home (${o.home}), whose key is now ${o.agentName}'s: left alone. Give each agent its own home (AGENTCHANNEL_HOME) and run its join line again there.`),
|
|
357
|
+
`Stop it with: ${f.stop.join(' && ')}`,
|
|
358
|
+
`Runner output: ${logs}`,
|
|
359
|
+
...(linger ? [] : ['Note: it stops when you log out of this machine. To keep it running: sudo loginctl enable-linger "$USER"']),
|
|
360
|
+
...(passEnv.length ? [`Note: the unit passes --pass-env ${passEnv.join(',')} but not their values; add them to the unit's environment yourself.`] : []),
|
|
361
|
+
].join('\n'));
|
|
362
|
+
return failed ? 1 : 0;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* The agent whose key this home already holds for `hub`, when it is another agent than `meId` and its key still works (a key the
|
|
366
|
+
* hub refuses belongs to nobody: replacing it loses nothing). Unknown (hub unreachable) counts as another agent: keeping a key
|
|
367
|
+
* costs a folder, losing one costs a runner.
|
|
368
|
+
*/
|
|
369
|
+
export async function otherAgentHere(env, hub, newKey, meId, cfId, cfSecret, fetch) {
|
|
370
|
+
let saved;
|
|
371
|
+
try {
|
|
372
|
+
saved = loadConfig(env);
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
if (saved.hub !== hub || !saved.key || saved.key === newKey)
|
|
378
|
+
return undefined;
|
|
379
|
+
try {
|
|
380
|
+
const prev = await new Client({ hub, token: saved.key, cfId: saved.cfId ?? cfId, cfSecret: saved.cfSecret ?? cfSecret, fetch }).me();
|
|
381
|
+
return prev.id === meId ? undefined : prev.name;
|
|
382
|
+
}
|
|
383
|
+
catch (e) {
|
|
384
|
+
if (e instanceof HubError && (e.status === 401 || (e.status === 403 && e.code !== 'cf_access')))
|
|
385
|
+
return undefined;
|
|
386
|
+
return 'unknown (the hub did not answer)';
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** Linux: does this user's systemd outlive their logins (loginctl linger)? Unknown counts as yes (no false alarm). */
|
|
390
|
+
function lingers(env) {
|
|
391
|
+
try {
|
|
392
|
+
return execFileSync('loginctl', ['show-user', env.USER || String(process.getuid?.() ?? ''), '-p', 'Linger', '--value'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() !== 'no';
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return true;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/** The runner is the service's own process and the service is in the old form: rewrite it, have the supervisor reload it, and stop (the reload starts the new one). */
|
|
399
|
+
async function moveOldService(io, agentName, home) {
|
|
400
|
+
const env = io.env;
|
|
401
|
+
const platform = (env.ACH_SERVICE_PLATFORM || process.platform);
|
|
402
|
+
if (platform !== 'darwin' && platform !== 'linux')
|
|
403
|
+
return false;
|
|
404
|
+
const { migrateOldService, reloadDetached, startedByService } = await import('./servicefix.js');
|
|
405
|
+
if (!env.ACH_SERVICE_DIR && !startedByService(agentName, platform, env))
|
|
406
|
+
return false;
|
|
407
|
+
const { npmSpec, whichAll, isBundledBin } = await import('./invite.js');
|
|
408
|
+
// the new service must be able to start: without an npx to point at, the old one (stale, but running) stays as it is
|
|
409
|
+
const beside = join(dirname(process.execPath), 'npx');
|
|
410
|
+
const npx = whichAll('npx', env).find((x) => !isBundledBin(x)) ?? (existsSync(beside) ? beside : '');
|
|
411
|
+
if (!npx) {
|
|
412
|
+
io.err('[ach run] this service starts a fixed copy of the CLI from the npx cache, but there is no npx to start it with: leaving it. Run `ach run --install-service` after installing npm.');
|
|
413
|
+
return false;
|
|
414
|
+
}
|
|
415
|
+
let m;
|
|
416
|
+
try {
|
|
417
|
+
m = migrateOldService({ agentName, platform, dir: env.ACH_SERVICE_DIR || undefined, env, home, npx, spec: npmSpec() });
|
|
418
|
+
}
|
|
419
|
+
catch (e) {
|
|
420
|
+
io.err(`[ach run] could not rewrite the service file: ${e?.message ?? e}`);
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
if (!m)
|
|
424
|
+
return false;
|
|
425
|
+
io.err(`[ach run] this service started a fixed copy of the CLI from the npx cache, which no restart updates: rewrote ${m.path} to start \`npx -y ${npmSpec()}\` and reloading it`);
|
|
426
|
+
if (!env.ACH_SERVICE_DIR)
|
|
427
|
+
reloadDetached(m.start, env);
|
|
428
|
+
return true;
|
|
429
|
+
}
|