@koalaauto/agentchannel 3.54.0 → 3.55.0

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/README.md CHANGED
@@ -40,8 +40,11 @@ installed or changed.
40
40
  pasting the line was the consent, so it does the same and says what it ran.
41
41
  - `--service` also installs the background helper (`ach run --install-service
42
42
  --interactive-first` for the current directory, without desktop
43
- notifications), and starts it. Through npx the service runs the same pinned
44
- npx spec as the MCP entry, so nothing is installed globally.
43
+ notifications), and starts it.
44
+ - Run through npx, join copies this release into `~/.config/agentchannel/app`
45
+ (one dir per release, no root needed) and the MCP entry and the service start
46
+ its launcher, `node ~/.config/agentchannel/app/ach.mjs`. Nothing waits on npm
47
+ when a session starts; the runner installs new releases there.
45
48
  - When the agent tool's sandbox does not work on this machine (on Linux: bubblewrap and
46
49
  socat missing, or Ubuntu's AppArmor rule), it shows the commands that fix it and runs
47
50
  them only after you say yes in a terminal (they use sudo). Without a terminal it only
@@ -102,6 +102,10 @@ export declare function agyOutcome(o: {
102
102
  ok: boolean;
103
103
  error?: string;
104
104
  };
105
+ /** How often a run that was refused an action is resumed to finish without it. */
106
+ export declare const AGY_DENIED_RETRIES = 2;
107
+ /** What a resumed run is told after an action was refused: what it was, and what this run may do. Pure. */
108
+ export declare function agyRefusedPrompt(refused: string[], perm: Perm, cwd: string): string;
105
109
  /** `agy models` prints "<slug>\t<label>" per line (after a "Fetching..." line). Pure. */
106
110
  export declare function agyModels(out: string): RuntimeModels | undefined;
107
111
  export interface AntigravityAdapterOptions {
@@ -140,5 +144,11 @@ export declare class AntigravityAdapter implements RuntimeAdapter {
140
144
  realHome?: string;
141
145
  }): Promise<RuntimeModels>;
142
146
  private bin;
147
+ /**
148
+ * One run. An action nobody could approve blanks agy's answer (see the header): the conversation is then resumed, at most
149
+ * twice, told what was refused and what this run may do, so one stray attempt does not cost the whole run. The action
150
+ * stays refused; a run that still ends without an answer fails.
151
+ */
143
152
  run(opts: AdapterRunOptions): Promise<AdapterResult>;
153
+ private once;
144
154
  }
@@ -235,6 +235,13 @@ export function agyOutcome(o) {
235
235
  return { ok: false, error: `agy reported ${o.out.status ?? 'success'} with no final message${tail ? `: ${tail}` : ''}`.slice(0, 2000) };
236
236
  return { ok: true };
237
237
  }
238
+ /** How often a run that was refused an action is resumed to finish without it. */
239
+ export const AGY_DENIED_RETRIES = 2;
240
+ /** What a resumed run is told after an action was refused: what it was, and what this run may do. Pure. */
241
+ export function agyRefusedPrompt(refused, perm, cwd) {
242
+ const may = perm === 'read' ? `Here you may only read files (no commands, no writes, no URLs).` : `Here you may run commands, and read and write files inside ${cwd} only.`;
243
+ return `An action you tried was refused and cannot be approved in this run: ${refused.join(', ')}. ${may} Do not try a refused action again, and do not look outside ${cwd} unless the task says to. Go on with the task and end with your final message, as the rules of the task say; say there what you could not do.`;
244
+ }
238
245
  /** `agy models` prints "<slug>\t<label>" per line (after a "Fetching..." line). Pure. */
239
246
  export function agyModels(out) {
240
247
  const models = out
@@ -267,18 +274,40 @@ export class AntigravityAdapter {
267
274
  bin() {
268
275
  return this.o.bin ?? agyBin(this.o.env ?? process.env);
269
276
  }
270
- run(opts) {
277
+ /**
278
+ * One run. An action nobody could approve blanks agy's answer (see the header): the conversation is then resumed, at most
279
+ * twice, told what was refused and what this run may do, so one stray attempt does not cost the whole run. The action
280
+ * stays refused; a run that still ends without an answer fails.
281
+ */
282
+ async run(opts) {
271
283
  const model = opts.model ?? this.o.model;
272
284
  const perm = agyPerm(opts.perm, opts.mode);
273
- const out = new AgyOutput(opts.onEvent);
274
- let stderr = '';
275
285
  // a sandboxed command sees every file outside the home directory: the runner's secrets must not be among them
276
286
  const exposed = perm === 'workdir' ? agyExposed(opts.denyReadPaths ?? [], opts.realHome) : [];
277
287
  if (exposed.length) {
278
288
  const error = `not run: Antigravity's sandbox hides only the home directory, and the runner keeps its key outside it (${exposed[0]}); keep the agent home under the home directory, or run with full access`;
279
289
  opts.onEvent({ type: 'error', data: error });
280
- return Promise.resolve({ finalText: '', ok: false, error });
290
+ return { finalText: '', ok: false, error };
281
291
  }
292
+ let prompt = opts.prompt;
293
+ let resume = opts.resume;
294
+ for (let attempt = 0;; attempt++) {
295
+ const r = await this.once(opts, { prompt, resume, perm, model });
296
+ const finalText = r.out.finalText();
297
+ const { ok, error } = agyOutcome({ code: r.code, out: r.out, finalText, stderr: r.stderr, aborted: opts.signal.aborted, spawnError: r.spawnError });
298
+ const used = r.out.model ?? (modelId(model) ? model : undefined);
299
+ const result = { finalText, sessionId: r.out.sessionId ?? resume, ok, ...(error ? { error } : {}), ...(used ? { model: used } : {}) };
300
+ const refused = [...new Set(r.out.denied)];
301
+ if (ok || !refused.length || !r.out.sessionId || attempt >= AGY_DENIED_RETRIES || opts.signal.aborted || r.spawnError)
302
+ return result;
303
+ opts.onEvent({ type: 'error', data: `Antigravity was refused ${refused.join(', ')} and gave no answer; resuming the conversation to finish without it` });
304
+ prompt = agyRefusedPrompt(refused, perm, opts.cwd);
305
+ resume = r.out.sessionId;
306
+ }
307
+ }
308
+ once(opts, o) {
309
+ const out = new AgyOutput(opts.onEvent);
310
+ let stderr = '';
282
311
  return new Promise((resolve) => {
283
312
  const env = agyEnv(opts.env, { realHome: opts.realHome });
284
313
  env.PATH = agyPath(env, opts.realHome);
@@ -288,14 +317,11 @@ export class AntigravityAdapter {
288
317
  return;
289
318
  done = true;
290
319
  out.end();
291
- const finalText = out.finalText();
292
- const { ok, error } = agyOutcome({ code, out, finalText, stderr, aborted: opts.signal.aborted, spawnError });
293
- const used = out.model ?? (modelId(model) ? model : undefined);
294
- resolve({ finalText, sessionId: out.sessionId, ok, ...(error ? { error } : {}), ...(used ? { model: used } : {}) });
320
+ resolve({ out, code, stderr, ...(spawnError ? { spawnError } : {}) });
295
321
  };
296
322
  let child;
297
323
  try {
298
- child = spawnGroup(this.bin(), agyArgs({ prompt: opts.prompt, perm, model, effort: opts.effort, resume: opts.resume, denyReadPaths: opts.denyReadPaths, readRoots: opts.readRoots, outputSchema: opts.outputSchema }), {
324
+ child = spawnGroup(this.bin(), agyArgs({ prompt: o.prompt, perm: o.perm, model: o.model, effort: opts.effort, resume: o.resume, denyReadPaths: opts.denyReadPaths, readRoots: opts.readRoots, outputSchema: opts.outputSchema }), {
299
325
  cwd: opts.cwd,
300
326
  env,
301
327
  signal: opts.signal,
@@ -0,0 +1,54 @@
1
+ /** Where the install lives: one per user, shared by every agent home on the machine (they run the same CLI). */
2
+ export declare function appDir(env?: NodeJS.ProcessEnv): string;
3
+ export declare const launcherPath: (app: string) => string;
4
+ /** The CLI file of one release in the install. */
5
+ export declare const cliOf: (app: string, version: string) => string;
6
+ /** Plain JS, run by node: starts the release named in ./current. The CLI checks that it is the entry by process.argv[1]. */
7
+ export declare const LAUNCHER_SCRIPT: string;
8
+ /** The release `current` names, when its files are there. */
9
+ export declare function currentVersion(app?: string): string | undefined;
10
+ /** Is this CLI file inside the install? */
11
+ export declare function inApp(self: string, app?: string): boolean;
12
+ /** The release of the install this CLI file belongs to (from its dir name). */
13
+ export declare function appVersionOf(self: string, app?: string): string | undefined;
14
+ /**
15
+ * The node to start the launcher with: the first `node` on PATH as PATH names it (a version manager's or Homebrew's stable link, not
16
+ * the versioned file behind it, which an upgrade removes), else this one.
17
+ */
18
+ export declare function nodeCommand(env?: NodeJS.ProcessEnv, execPath?: string): string;
19
+ /** How an MCP entry or a service starts the install. */
20
+ export declare function appAch(env?: NodeJS.ProcessEnv, app?: string): string[];
21
+ /** Point the launcher at `version` (its files must be there). Writes the launcher too, so an install that lost it gets it back. */
22
+ export declare function setCurrent(app: string, version: string): void;
23
+ /** The node_modules dir an npx cache run of this CLI lives in, or undefined when it is not one. */
24
+ export declare function npxModulesOf(self: string): string | undefined;
25
+ /**
26
+ * Put the release this CLI is into the install by copying its npx cache dir (nothing is downloaded, so nothing waits on npm), and point
27
+ * `current` at it unless `current` already names a newer release. Returns the install's command, or undefined when this is not an npx
28
+ * run or the copy failed (the caller keeps using npx then).
29
+ */
30
+ export declare function adoptFromNpx(o: {
31
+ self: string;
32
+ env?: NodeJS.ProcessEnv;
33
+ version?: string;
34
+ log?: (s: string) => void;
35
+ }): string[] | undefined;
36
+ export type InstallExec = (file: string, args: string[], o?: {
37
+ timeoutMs?: number;
38
+ }) => Promise<{
39
+ code: number;
40
+ stdout: string;
41
+ stderr: string;
42
+ }>;
43
+ /** Can the install be written (the updater asks before it stops taking work)? */
44
+ export declare function appWritable(app: string): boolean;
45
+ /** Install `version` from npm into a dir of its own (`npm install --prefix`, scripts off), read it back, point `current` at it, prune. */
46
+ export declare function installIntoApp(app: string, version: string, exec: InstallExec): Promise<{
47
+ ok: boolean;
48
+ detail: string;
49
+ }>;
50
+ /**
51
+ * Remove releases nothing should still run: not `current`, not among the three newest, and untouched for three days (an MCP session
52
+ * started on an old release keeps reading its files until it is restarted).
53
+ */
54
+ export declare function pruneApp(app: string, now?: number, keep?: number, minAgeMs?: number): string[];
@@ -0,0 +1,216 @@
1
+ // The CLI's own install in the user's AgentChannel home: <defaultHome>/app. No root (a global npm install often needs it), and no
2
+ // npx at start-up (npx re-resolves `@3` on every start: in the minutes after a release npm names a version it does not serve yet,
3
+ // and the start fails with ETARGET; and every `@3` process shares one npx cache dir that the next release is written over).
4
+ //
5
+ // app/<version>/node_modules/... one release per dir, never changed once written
6
+ // app/current the version the launcher starts
7
+ // app/ach.mjs the launcher: MCP entries and services run `node app/ach.mjs ...`
8
+ //
9
+ // A new release goes into a dir of its own and `current` is switched by a rename, so processes running the old one keep their files
10
+ // (Windows included: nothing they hold is replaced). Old dirs are removed once they are a few releases back and some days old.
11
+ import { accessSync, constants, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
12
+ import { delimiter, join, sep } from 'node:path';
13
+ import { defaultHome } from './config.js';
14
+ import { newerVersion, PKG_NAME, VERSION } from './version.js';
15
+ const isVersion = (v) => typeof v === 'string' && /^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/.test(v);
16
+ /** Where the install lives: one per user, shared by every agent home on the machine (they run the same CLI). */
17
+ export function appDir(env = process.env) {
18
+ return join(defaultHome(env), 'app');
19
+ }
20
+ export const launcherPath = (app) => join(app, 'ach.mjs');
21
+ const currentFile = (app) => join(app, 'current');
22
+ const pkgDir = (app, version) => join(app, version, 'node_modules', ...PKG_NAME.split('/'));
23
+ /** The CLI file of one release in the install. */
24
+ export const cliOf = (app, version) => join(pkgDir(app, version), 'dist', 'src', 'cli.js');
25
+ /** Plain JS, run by node: starts the release named in ./current. The CLI checks that it is the entry by process.argv[1]. */
26
+ export const LAUNCHER_SCRIPT = `// written by agentchannel (ach): starts the release named in ./current
27
+ import { readFileSync } from 'node:fs';
28
+ import { dirname, join } from 'node:path';
29
+ import { fileURLToPath, pathToFileURL } from 'node:url';
30
+ const app = dirname(fileURLToPath(import.meta.url));
31
+ const version = readFileSync(join(app, 'current'), 'utf8').trim();
32
+ const cli = join(app, version, 'node_modules', ${PKG_NAME.split('/').map((s) => JSON.stringify(s)).join(', ')}, 'dist', 'src', 'cli.js');
33
+ process.argv[1] = cli;
34
+ await import(pathToFileURL(cli).href);
35
+ `;
36
+ const readVersion = (dir) => {
37
+ try {
38
+ return String(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version ?? '');
39
+ }
40
+ catch {
41
+ return '';
42
+ }
43
+ };
44
+ /** The release `current` names, when its files are there. */
45
+ export function currentVersion(app = appDir()) {
46
+ let v = '';
47
+ try {
48
+ v = readFileSync(currentFile(app), 'utf8').trim();
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ return isVersion(v) && existsSync(launcherPath(app)) && readVersion(pkgDir(app, v)) === v ? v : undefined;
54
+ }
55
+ /** Is this CLI file inside the install? */
56
+ export function inApp(self, app = appDir()) {
57
+ return self.startsWith(app + sep);
58
+ }
59
+ /** The release of the install this CLI file belongs to (from its dir name). */
60
+ export function appVersionOf(self, app = appDir()) {
61
+ if (!inApp(self, app))
62
+ return undefined;
63
+ const v = self.slice(app.length + 1).split(/[\\/]/)[0];
64
+ return isVersion(v) ? v : undefined;
65
+ }
66
+ /**
67
+ * The node to start the launcher with: the first `node` on PATH as PATH names it (a version manager's or Homebrew's stable link, not
68
+ * the versioned file behind it, which an upgrade removes), else this one.
69
+ */
70
+ export function nodeCommand(env = process.env, execPath = process.execPath) {
71
+ if (process.platform === 'win32')
72
+ return execPath;
73
+ for (const d of (env.PATH ?? '').split(delimiter)) {
74
+ if (!d || /[\\/]_npx[\\/]|[\\/]node_modules[\\/]\.bin$/.test(d))
75
+ continue;
76
+ const f = join(d, 'node');
77
+ try {
78
+ accessSync(f, constants.X_OK);
79
+ return f;
80
+ }
81
+ catch {
82
+ /* next */
83
+ }
84
+ }
85
+ return execPath;
86
+ }
87
+ /** How an MCP entry or a service starts the install. */
88
+ export function appAch(env = process.env, app = appDir(env)) {
89
+ return [nodeCommand(env), launcherPath(app)];
90
+ }
91
+ const writeAtomic = (f, s) => {
92
+ const tmp = `${f}.${process.pid}.tmp`;
93
+ writeFileSync(tmp, s, { mode: 0o644 });
94
+ renameSync(tmp, f);
95
+ };
96
+ /** Point the launcher at `version` (its files must be there). Writes the launcher too, so an install that lost it gets it back. */
97
+ export function setCurrent(app, version) {
98
+ if (readVersion(pkgDir(app, version)) !== version)
99
+ throw new Error(`${pkgDir(app, version)} does not hold ${version}`);
100
+ writeAtomic(launcherPath(app), LAUNCHER_SCRIPT);
101
+ writeAtomic(currentFile(app), `${version}\n`);
102
+ }
103
+ /** The node_modules dir an npx cache run of this CLI lives in, or undefined when it is not one. */
104
+ export function npxModulesOf(self) {
105
+ const m = /^(.*[\\/]_npx[\\/][^\\/]+[\\/]node_modules)[\\/]/.exec(self);
106
+ return m?.[1];
107
+ }
108
+ /**
109
+ * Put the release this CLI is into the install by copying its npx cache dir (nothing is downloaded, so nothing waits on npm), and point
110
+ * `current` at it unless `current` already names a newer release. Returns the install's command, or undefined when this is not an npx
111
+ * run or the copy failed (the caller keeps using npx then).
112
+ */
113
+ export function adoptFromNpx(o) {
114
+ const env = o.env ?? process.env;
115
+ const version = o.version ?? VERSION;
116
+ const modules = npxModulesOf(o.self);
117
+ if (!modules || !isVersion(version) || !existsSync(join(modules, ...PKG_NAME.split('/'))))
118
+ return undefined;
119
+ const app = appDir(env);
120
+ try {
121
+ mkdirSync(app, { recursive: true, mode: 0o700 });
122
+ if (readVersion(pkgDir(app, version)) !== version) {
123
+ const tmp = join(app, `.${version}.${process.pid}.tmp`);
124
+ rmSync(tmp, { recursive: true, force: true });
125
+ cpSync(modules, join(tmp, 'node_modules'), { recursive: true, verbatimSymlinks: true });
126
+ try {
127
+ renameSync(tmp, join(app, version));
128
+ }
129
+ catch (e) {
130
+ rmSync(tmp, { recursive: true, force: true });
131
+ if (readVersion(pkgDir(app, version)) !== version)
132
+ throw e; // another process put the same release there first: fine
133
+ }
134
+ }
135
+ const cur = currentVersion(app);
136
+ if (!cur || cur === version || newerVersion(version, cur))
137
+ setCurrent(app, version);
138
+ return appAch(env, app);
139
+ }
140
+ catch (e) {
141
+ o.log?.(`could not install ach ${version} into ${app}: ${e?.message ?? e}`);
142
+ return undefined;
143
+ }
144
+ }
145
+ /** Can the install be written (the updater asks before it stops taking work)? */
146
+ export function appWritable(app) {
147
+ try {
148
+ accessSync(app, constants.W_OK);
149
+ return true;
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ }
155
+ /** Install `version` from npm into a dir of its own (`npm install --prefix`, scripts off), read it back, point `current` at it, prune. */
156
+ export async function installIntoApp(app, version, exec) {
157
+ if (!isVersion(version))
158
+ return { ok: false, detail: `not a version: ${version}` };
159
+ if (readVersion(pkgDir(app, version)) !== version) {
160
+ const tmp = join(app, `.${version}.${process.pid}.tmp`);
161
+ rmSync(tmp, { recursive: true, force: true });
162
+ mkdirSync(tmp, { recursive: true, mode: 0o700 });
163
+ const r = await exec('npm', ['install', '--prefix', tmp, '--ignore-scripts', '--no-audit', '--no-fund', '--no-save', '--no-package-lock', `${PKG_NAME}@${version}`], { timeoutMs: 5 * 60_000 });
164
+ const got = readVersion(join(tmp, 'node_modules', ...PKG_NAME.split('/')));
165
+ if (r.code !== 0 || got !== version) {
166
+ rmSync(tmp, { recursive: true, force: true });
167
+ return { ok: false, detail: `npm install ${PKG_NAME}@${version} into ${app} failed (${r.code !== 0 ? (r.stderr || r.stdout).trim().split('\n').slice(-3).join(' | ').slice(0, 300) : `got ${got || 'nothing'}`})` };
168
+ }
169
+ try {
170
+ renameSync(tmp, join(app, version));
171
+ }
172
+ catch (e) {
173
+ rmSync(tmp, { recursive: true, force: true });
174
+ if (readVersion(pkgDir(app, version)) !== version)
175
+ return { ok: false, detail: `could not move ${version} into place: ${e?.message ?? e}` };
176
+ }
177
+ }
178
+ try {
179
+ setCurrent(app, version);
180
+ }
181
+ catch (e) {
182
+ return { ok: false, detail: `installed ${version} but could not switch to it: ${e?.message ?? e}` };
183
+ }
184
+ pruneApp(app);
185
+ return { ok: true, detail: `installed ${version} into ${app}` };
186
+ }
187
+ /**
188
+ * Remove releases nothing should still run: not `current`, not among the three newest, and untouched for three days (an MCP session
189
+ * started on an old release keeps reading its files until it is restarted).
190
+ */
191
+ export function pruneApp(app, now = Date.now(), keep = 3, minAgeMs = 3 * 24 * 3600_000) {
192
+ const cur = currentVersion(app);
193
+ let names = [];
194
+ try {
195
+ names = readdirSync(app).filter(isVersion);
196
+ }
197
+ catch {
198
+ return [];
199
+ }
200
+ const newest = [...names].sort((a, b) => (newerVersion(a, b) ? -1 : newerVersion(b, a) ? 1 : 0)).slice(0, keep);
201
+ const out = [];
202
+ for (const v of names) {
203
+ if (v === cur || newest.includes(v))
204
+ continue;
205
+ try {
206
+ if (now - statSync(join(app, v)).mtimeMs < minAgeMs)
207
+ continue;
208
+ rmSync(join(app, v), { recursive: true, force: true });
209
+ out.push(v);
210
+ }
211
+ catch {
212
+ /* left for the next prune */
213
+ }
214
+ }
215
+ return out;
216
+ }
@@ -1,7 +1,7 @@
1
1
  // `ach run`: the runner on this machine. Starting it (one per agent home, a lock), its self-update supervision, and installing
2
2
  // it as a user service (systemd, launchd) that starts it again after a reboot or an update.
3
3
  import { execFileSync, execSync, spawn } from 'node:child_process';
4
- import { chmodSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
+ import { chmodSync, mkdirSync, writeFileSync } from 'node:fs';
5
5
  import { basename, delimiter, dirname, join, resolve } from 'node:path';
6
6
  import { tmpdir } from 'node:os';
7
7
  import { developerDir } from './adapters/scope.js';
@@ -110,10 +110,11 @@ export async function runCommand(p, io) {
110
110
  }
111
111
  if (v['install-service'])
112
112
  return installService(p, io, { agentName: me.name, formerNames: me.former_names ?? [], dir, repos: repoFlags, home });
113
- // 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
+ // started by a service that starts through the npx cache: make it start the install in the AgentChannel home
114
114
  const moved = await moveOldService(io, me.name, home);
115
115
  if (moved)
116
116
  return UPDATE_EXIT_CODE;
117
+ void moveMcpEntries(io, dir).catch(() => { });
117
118
  const runtime = str(v.runtime) ?? (isRuntime(me.runtime) ? me.runtime : 'claude');
118
119
  // what the permission and the network list do not cover, said where the person starting the runner will read it
119
120
  if (asked === 'full')
@@ -248,10 +249,12 @@ export async function runCommand(p, io) {
248
249
  return UPDATE_HANDOFF_EXIT_CODE;
249
250
  }
250
251
  if (updater.restarting) {
251
- // started by hand (no systemd / launchd behind it) from a global install: nothing would start it again, so it does that itself
252
- if (updater.installed === 'global' && process.env.ACH_SUPERVISED !== '1' && !(await import('./servicefix.js')).startedByService(me.name, process.platform, process.env)) {
252
+ // started by hand (no systemd / launchd behind it) from a global or home install: nothing would start it again, so it does that itself
253
+ if ((updater.installed === 'global' || updater.installed === 'app') && process.env.ACH_SUPERVISED !== '1' && !(await import('./servicefix.js')).startedByService(me.name, process.platform, process.env)) {
253
254
  io.err('ach run: updated; starting the new release here');
254
- return superviseSelf({ log: io.err });
255
+ // the install in the AgentChannel home: through its launcher (this process's argv names the old release's own file)
256
+ const { appDir, launcherPath } = await import('./appinstall.js');
257
+ return superviseSelf({ log: io.err, ...(updater.installed === 'app' ? { argv: [process.argv[0], launcherPath(appDir(env)), ...process.argv.slice(2)] } : {}) });
255
258
  }
256
259
  io.err(`ach run: updated; exiting ${UPDATE_EXIT_CODE} so the service restarts on the new release (started by hand? run it again)`);
257
260
  return UPDATE_EXIT_CODE;
@@ -317,11 +320,16 @@ async function installService(p, io, o) {
317
320
  svcEnv.ACH_AUTH_EXIT_CODE = '0';
318
321
  mkdirSync(join(o.home, 'logs'), { recursive: true, mode: 0o700 });
319
322
  const self = CLI_JS;
320
- const npx = /[\\/]_npx[\\/]/.test(self) ? (whichAll('npx', env).find((x) => !isBundledBin(x)) ?? join(dirname(process.execPath), 'npx')) : undefined;
323
+ // the install in the AgentChannel home (appinstall.ts), so the service follows its updates; run through npx, this release is copied
324
+ // there first. npx itself only when that copy failed; node on this very file for any other install (a global one, a checkout).
325
+ const { adoptFromNpx, appAch, appDir, inApp } = await import('./appinstall.js');
326
+ const npxRun = /[\\/]_npx[\\/]/.test(self);
327
+ const app = inApp(self, appDir(env)) ? appAch(env) : npxRun ? adoptFromNpx({ self, env, log: (s) => io.err(`[ach run] ${s}`) }) : undefined;
328
+ const npx = !app && npxRun ? (whichAll('npx', env).find((x) => !isBundledBin(x)) ?? join(dirname(process.execPath), 'npx')) : undefined;
321
329
  const f = serviceFile({
322
330
  platform,
323
331
  agentName: o.agentName,
324
- command: npx ? [npx, '-y', npmSpec()] : [process.execPath, self],
332
+ command: app ?? (npx ? [npx, '-y', npmSpec()] : [process.execPath, self]),
325
333
  args,
326
334
  env: svcEnv,
327
335
  logFile: join(o.home, 'logs', 'runner.log'),
@@ -401,7 +409,11 @@ function lingers(env) {
401
409
  return true;
402
410
  }
403
411
  }
404
- /** 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). */
412
+ /**
413
+ * The runner is the service's own process and the service starts through the npx cache: this release is copied into the install in
414
+ * the AgentChannel home, the service rewritten to start that, the supervisor has it reloaded, and this one stops (the reload starts the
415
+ * new one).
416
+ */
405
417
  async function moveOldService(io, agentName, home) {
406
418
  const env = io.env;
407
419
  const platform = (env.ACH_SERVICE_PLATFORM || process.platform);
@@ -410,17 +422,19 @@ async function moveOldService(io, agentName, home) {
410
422
  const { migrateOldService, reloadDetached, startedByService } = await import('./servicefix.js');
411
423
  if (!env.ACH_SERVICE_DIR && !startedByService(agentName, platform, env))
412
424
  return false;
413
- const { npmSpec, whichAll, isBundledBin } = await import('./invite.js');
414
- // the new service must be able to start: without an npx to point at, the old one (stale, but running) stays as it is
415
- const beside = join(dirname(process.execPath), 'npx');
416
- const npx = whichAll('npx', env).find((x) => !isBundledBin(x)) ?? (existsSync(beside) ? beside : '');
417
- if (!npx) {
418
- 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.');
425
+ const { listServices } = await import('./service.js');
426
+ const own = listServices(platform, env.ACH_SERVICE_DIR || undefined, env).find((s) => s.agentName === agentName.replace(/[^A-Za-z0-9-]/g, '-'));
427
+ if (!own || (own.format !== 'npx' && own.format !== 'node-cache'))
428
+ return false;
429
+ const { adoptFromNpx, appAch, appDir, currentVersion } = await import('./appinstall.js');
430
+ const { thisCliPath } = await import('./invite.js');
431
+ // the new service must be able to start: without the install (the copy failed), the old one stays as it is
432
+ const command = adoptFromNpx({ self: thisCliPath(), env, log: (s) => io.err(`[ach run] ${s}`) }) ?? (currentVersion(appDir(env)) ? appAch(env) : undefined);
433
+ if (!command)
419
434
  return false;
420
- }
421
435
  let m;
422
436
  try {
423
- m = migrateOldService({ agentName, platform, dir: env.ACH_SERVICE_DIR || undefined, env, home, npx, spec: npmSpec() });
437
+ m = migrateOldService({ agentName, platform, dir: env.ACH_SERVICE_DIR || undefined, env, home, command });
424
438
  }
425
439
  catch (e) {
426
440
  io.err(`[ach run] could not rewrite the service file: ${e?.message ?? e}`);
@@ -428,8 +442,55 @@ async function moveOldService(io, agentName, home) {
428
442
  }
429
443
  if (!m)
430
444
  return false;
431
- 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`);
445
+ io.err(`[ach run] this service started ach through the npx cache: rewrote ${m.path} to start ${command.join(' ')} and reloading it`);
432
446
  if (!env.ACH_SERVICE_DIR)
433
447
  reloadDetached(m.start, env);
434
448
  return true;
435
449
  }
450
+ /** A runner of the install in the AgentChannel home points the `ach` MCP entries that still start npx at it (onboard moveNpxMcpEntries). */
451
+ async function moveMcpEntries(io, dir) {
452
+ const { appAch, appDir, inApp } = await import('./appinstall.js');
453
+ const { thisCliPath } = await import('./invite.js');
454
+ if (io.env.ACH_SERVICE_DIR || !inApp(thisCliPath(), appDir(io.env)))
455
+ return; // tests, and runs of other installs
456
+ const { moveNpxMcpEntries } = await import('./onboard.js');
457
+ const { execFile } = await import('node:child_process');
458
+ const execIn = (cwd) => (file, args, env) => new Promise((res) => execFile(file, args, { cwd, env, timeout: 30_000, encoding: 'utf8' }, (err, stdout, stderr) => res({ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })));
459
+ // the user-scope entry is seen from a dir with no local entry: an empty one of ours
460
+ const empty = join(appDir(io.env), 'mcp-cwd');
461
+ (await import('node:fs')).mkdirSync(empty, { recursive: true });
462
+ // the runners of one machine restart together after a release: one at a time, since each `claude mcp add` rewrites ~/.claude.json
463
+ const { openSync, closeSync, statSync, unlinkSync } = await import('node:fs');
464
+ const lock = join(appDir(io.env), 'mcp-move.lock');
465
+ for (let i = 0;; i++) {
466
+ try {
467
+ closeSync(openSync(lock, 'wx'));
468
+ break;
469
+ }
470
+ catch {
471
+ try {
472
+ if (Date.now() - statSync(lock).mtimeMs > 120_000)
473
+ unlinkSync(lock); // left by a runner that died holding it
474
+ }
475
+ catch {
476
+ /* gone already */
477
+ }
478
+ if (i >= 90)
479
+ return;
480
+ await new Promise((r) => setTimeout(r, 2000));
481
+ }
482
+ }
483
+ try {
484
+ const moved = await moveNpxMcpEntries({ env: io.env, exec: execIn(dir), userExec: execIn(empty), achCmd: appAch(io.env), log: (s) => io.err(`[ach run] ${s}`) });
485
+ if (moved.length)
486
+ io.err(`[ach run] the \`ach\` MCP entry (${moved.join(', ')}) started npx: it starts ${appAch(io.env).join(' ')} now (new sessions)`);
487
+ }
488
+ finally {
489
+ try {
490
+ unlinkSync(lock);
491
+ }
492
+ catch {
493
+ /* gone already */
494
+ }
495
+ }
496
+ }
@@ -298,10 +298,29 @@ export interface MentionOutcome {
298
298
  evidence?: string;
299
299
  };
300
300
  }
301
+ /** The task behind a task's thread, handed to its worker or sender when a mention wakes it there. */
302
+ export interface ThreadTask {
303
+ ref: string;
304
+ url?: string;
305
+ title: string;
306
+ status: string;
307
+ from_agent_name: string;
308
+ to_agent_name: string;
309
+ handoff: string;
310
+ messages: {
311
+ kind: string;
312
+ author_type: string;
313
+ author_name: string;
314
+ body: string;
315
+ created: string;
316
+ }[];
317
+ }
301
318
  export interface MentionRun extends MentionItem {
302
319
  replies: Post[];
303
320
  recent: Post[];
304
321
  run_token: string;
322
+ /** set when the thread is a task's and the agent is a party to it (an older hub leaves it out) */
323
+ task?: ThreadTask;
305
324
  }
306
325
  export interface SearchResult {
307
326
  type: 'post' | 'task' | 'message' | 'handoff';
@@ -1,6 +1,7 @@
1
1
  import { accessSync, constants, readFileSync, realpathSync, statSync } from 'node:fs';
2
2
  import { delimiter, dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { appAch, appDir, currentVersion, inApp } from './appinstall.js';
4
5
  import { PKG_NAME, VERSION } from './version.js';
5
6
  const PREFIX = 'ach2.';
6
7
  export const JOIN_TOKEN_RE = /^ach_jt_[a-z0-9]{15}_[A-Za-z0-9]{40}$/;
@@ -203,9 +204,12 @@ export function mcpCommands(o) {
203
204
  * earlier on PATH, or none, must never be what the MCP entry runs).
204
205
  */
205
206
  export function achCommand(env = process.env, self = thisCliPath()) {
206
- // run through npx: the cache may be cleared, so entries use the pinned npx spec
207
+ // the install in the AgentChannel home (appinstall.ts): its launcher, which follows the updates
208
+ if (inApp(self, appDir(env)))
209
+ return appAch(env);
210
+ // run through npx: the install when join put one there, else the pinned npx spec (the cache may be cleared)
207
211
  if (/[\\/]_npx[\\/]/.test(self))
208
- return npxAch();
212
+ return currentVersion(appDir(env)) ? appAch(env) : npxAch();
209
213
  const first = whichAll('ach', env)[0];
210
214
  if (first && isOurs(identifyAch(first, self)))
211
215
  return ['ach'];
@@ -1,4 +1,4 @@
1
- import type { ExecLike } from './doctor.js';
1
+ import { type ExecLike } from './doctor.js';
2
2
  import { type SandboxStatus, type SandboxTool } from './sandboxcheck.js';
3
3
  /**
4
4
  * One-line onboarding: what `ach join` sets up after the key is stored.
@@ -84,7 +84,7 @@ export interface Detected {
84
84
  /** An `ach` entry already registered (it is replaced). */
85
85
  claudeHasAch: boolean;
86
86
  codexHasAch: boolean;
87
- /** How the MCP entry and service start ach: the pinned npx spec when run through npx, else an absolute `ach`. */
87
+ /** How the MCP entry and service start ach: the install in the AgentChannel home when run through npx, else an absolute `ach`. */
88
88
  achCmd: Argv;
89
89
  }
90
90
  /** The absolute command that starts this CLI: the first `ach` on PATH when it is this package, else node + this file. */
@@ -117,3 +117,22 @@ export interface SetupResult {
117
117
  export declare function runSetup(io: SetupIo, o: SetupOptions): Promise<SetupResult>;
118
118
  /** The Linux command that lets a user's services outlive their logins. */
119
119
  export declare const LINGER_CMD = "sudo loginctl enable-linger \"$USER\"";
120
+ /** An entry that starts this package through npx (`npx -y @koalaauto/agentchannel@3 mcp`). */
121
+ export declare function isNpxEntry(e: {
122
+ command?: string;
123
+ args: string[];
124
+ }): boolean;
125
+ /**
126
+ * The `ach` MCP entries of Claude Code and Codex that join wrote as `npx -y <spec> mcp` are pointed at the install in the AgentChannel
127
+ * home (`achCmd`), keeping their scope and AGENTCHANNEL_HOME: npx re-resolves the spec at every session start and fails while npm catches
128
+ * up with a release. `exec` runs in the runner's project dir, where Claude Code keeps a local-scope entry; `userExec` in a dir with no
129
+ * entries of its own, where `claude mcp get` shows the user-scope one (a local entry hides it). A project-scope entry (.mcp.json, in the
130
+ * repository) is left alone. Returns what was moved, as `<tool> <scope>`.
131
+ */
132
+ export declare function moveNpxMcpEntries(o: {
133
+ env: NodeJS.ProcessEnv;
134
+ exec: ExecLike;
135
+ userExec?: ExecLike;
136
+ achCmd: Argv;
137
+ log?: (s: string) => void;
138
+ }): Promise<string[]>;
@@ -1,7 +1,10 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
+ import { parseMcpEntry } from './doctor.js';
3
4
  import { probeSandbox } from './sandboxcheck.js';
5
+ import { adoptFromNpx, appAch } from './appinstall.js';
4
6
  import { identifyAch, isOurs, MCP_SERVER_NAME, npxAch, thisCliPath, userBin, whichAll } from './invite.js';
7
+ import { PKG_NAME } from './version.js';
5
8
  /** The closing line: which tool to open and what to say to it. */
6
9
  export function doneLine(tools, zh) {
7
10
  const names = [...new Set(tools)].map((k) => (k === 'claude' ? 'Claude Code' : 'Codex'));
@@ -61,8 +64,10 @@ export async function detect(env, exec, self, probe) {
61
64
  const d = {
62
65
  claude, codex, npx,
63
66
  claudeHasAch: false, codexHasAch: false,
64
- // run through npx: the MCP entry uses the same pinned spec as the join line
65
- achCmd: npx ? npxAch() : absoluteAch(env, self),
67
+ // run through npx (the join line): this release is copied into the AgentChannel home and the MCP entry and service start it
68
+ // from there (appinstall.ts); npx at every start fails while npm catches up with a release. The npx spec if the copy failed;
69
+ // a dry run (no probe) copies nothing and shows the install's command.
70
+ achCmd: npx ? (probe ? (adoptFromNpx({ self, env }) ?? npxAch()) : appAch(env)) : absoluteAch(env, self),
66
71
  };
67
72
  if (!probe)
68
73
  return d;
@@ -315,3 +320,51 @@ function printOnly(io, d, plan, o) {
315
320
  out.push('', `${zh ? '随时检查配置:' : 'Check the setup any time with: '}${shellLine([...(d.npx ? d.achCmd : ['ach']), 'doctor'])}`);
316
321
  io.out(out.join('\n'));
317
322
  }
323
+ /** An entry that starts this package through npx (`npx -y @koalaauto/agentchannel@3 mcp`). */
324
+ export function isNpxEntry(e) {
325
+ return !!e.command && /(^|[\\/])npx(\.cmd)?$/.test(e.command) && e.args.at(-1) === 'mcp' && e.args.some((a) => a === PKG_NAME || a.startsWith(`${PKG_NAME}@`));
326
+ }
327
+ /**
328
+ * The `ach` MCP entries of Claude Code and Codex that join wrote as `npx -y <spec> mcp` are pointed at the install in the AgentChannel
329
+ * home (`achCmd`), keeping their scope and AGENTCHANNEL_HOME: npx re-resolves the spec at every session start and fails while npm catches
330
+ * up with a release. `exec` runs in the runner's project dir, where Claude Code keeps a local-scope entry; `userExec` in a dir with no
331
+ * entries of its own, where `claude mcp get` shows the user-scope one (a local entry hides it). A project-scope entry (.mcp.json, in the
332
+ * repository) is left alone. Returns what was moved, as `<tool> <scope>`.
333
+ */
334
+ export async function moveNpxMcpEntries(o) {
335
+ const moved = [];
336
+ const looks = [
337
+ { kind: 'claude', exec: o.exec },
338
+ ...(o.userExec ? [{ kind: 'claude', exec: o.userExec }] : []),
339
+ { kind: 'codex', exec: o.exec },
340
+ ];
341
+ for (const { kind, exec } of looks) {
342
+ const bin = userBin(kind, o.env);
343
+ if (!bin)
344
+ continue;
345
+ const got = await exec(bin, ['mcp', 'get', MCP_SERVER_NAME], o.env);
346
+ if (got.code !== 0)
347
+ continue;
348
+ const e = parseMcpEntry(got.stdout, MCP_SERVER_NAME);
349
+ if (!isNpxEntry(e))
350
+ continue;
351
+ const scope = kind === 'codex' ? 'user' : /^\s*Scope:\s*Local/im.test(got.stdout) ? 'local' : /^\s*Scope:\s*User/im.test(got.stdout) ? 'user' : undefined;
352
+ if (!scope || moved.includes(`${kind} ${scope}`))
353
+ continue;
354
+ const local = scope === 'local';
355
+ const rm = await exec(bin, mcpRemoveArgv(kind, bin, MCP_SERVER_NAME, local).slice(1), o.env);
356
+ if (rm.code !== 0) {
357
+ o.log?.(`could not remove the npx \`ach\` entry of ${kind} (exit ${rm.code}): ${rm.stderr.trim().split('\n')[0] ?? ''}`);
358
+ continue;
359
+ }
360
+ const add = await exec(bin, mcpAddArgv(kind, bin, o.achCmd, e.home, local).slice(1), o.env);
361
+ if (add.code !== 0) {
362
+ // the entry is gone now: put the npx one back rather than leave the tool without AgentChannel
363
+ await exec(bin, mcpAddArgv(kind, bin, [e.command, ...e.args.slice(0, -1)], e.home, local).slice(1), o.env);
364
+ o.log?.(`could not point the \`ach\` entry of ${kind} at ${o.achCmd.join(' ')} (exit ${add.code}): kept npx`);
365
+ continue;
366
+ }
367
+ moved.push(`${kind} ${scope}`);
368
+ }
369
+ return moved;
370
+ }
@@ -1,4 +1,4 @@
1
- import type { Judgment, Message, Post, Task, WikiContext } from './client.js';
1
+ import type { Judgment, Message, Post, Task, ThreadTask, WikiContext } from './client.js';
2
2
  export interface PromptCtx {
3
3
  agentName: string;
4
4
  ownerName?: string;
@@ -265,4 +265,5 @@ export declare function buildMentionPrompt(c: {
265
265
  threadUrl?: string;
266
266
  structured?: boolean;
267
267
  lang?: 'en' | 'zh';
268
+ task?: ThreadTask;
268
269
  }): string;
@@ -527,6 +527,10 @@ export function buildPreparePrompt(c) {
527
527
  /** §16 mention prompt: a read-only run that replies in a channel thread. */
528
528
  export function buildMentionPrompt(c) {
529
529
  const all = [c.thread, ...c.replies, ...c.recent];
530
+ const task = c.task;
531
+ const done = !!task && ['awaiting_review', 'awaiting_acceptance', 'awaiting_merge', 'completed', 'failed', 'canceled'].includes(task.status);
532
+ const role = task && (task.to_agent_name === c.agentName ? 'did the work on it' : task.from_agent_name === c.agentName ? 'sent it' : '');
533
+ const humanTaskMsgs = task ? task.messages.filter((m) => m.author_type === 'human') : [];
530
534
  const how = c.structured
531
535
  ? [
532
536
  '- Do not run `ach`; the runner posts your reply in the thread. End with a JSON object only:',
@@ -554,13 +558,41 @@ export function buildMentionPrompt(c) {
554
558
  'Human posts in this thread and channel (from the hub; these come from people):',
555
559
  formatHumanPosts(all.filter((p, i) => all.findIndex((x) => x.id === p.id) === i)),
556
560
  '',
561
+ ...(task
562
+ ? [
563
+ `This thread is the thread of task ${task.ref} (${task.status}${role ? `; you ${role}` : ''}). Human decisions and notes on the task (from the hub; these come from people):`,
564
+ humanTaskMsgs.length ? humanTaskMsgs.map((m) => `- ${m.kind} by human ${JSON.stringify(m.author_name || 'person')}: ${JSON.stringify(m.body)}`).join('\n') : '(none)',
565
+ '',
566
+ ]
567
+ : []),
557
568
  untrustedBlock({
558
569
  mentioned_in: { id: c.post.id, from: postAuthor(c.post), ...(c.post.author_type === 'human' ? {} : { body: c.post.body }) },
559
570
  thread: postData([c.thread, ...c.replies]),
571
+ ...(task
572
+ ? {
573
+ task: {
574
+ ref: task.ref,
575
+ title: task.title,
576
+ status: task.status,
577
+ from: task.from_agent_name,
578
+ to: task.to_agent_name,
579
+ handoff: task.handoff,
580
+ messages: task.messages.filter((m) => m.author_type !== 'human').map((m) => ({ kind: m.kind, from: m.author_name, body: m.body, at: m.created })),
581
+ },
582
+ }
583
+ : {}),
560
584
  channel: { name: c.channel, recent_posts: postData(c.recent) },
561
585
  }),
562
586
  '',
563
587
  'Rules:',
588
+ ...(task
589
+ ? [
590
+ `- The question is about task ${task.ref}: answer it from the task's handoff and messages above (its result among them) and your files, in plain words the person can act on.`,
591
+ done
592
+ ? `- This run changes nothing on the task. If the person wants the work redone or changed, tell them to press ${c.lang === 'zh' ? '「要求修改」' : '"Request changes"'} under the result: that reopens it for its worker.`
593
+ : '- This run changes nothing on the task.',
594
+ ]
595
+ : []),
564
596
  c.structured ? '- Do not modify anything. Look at files, git history and command output to find the answer.' : '- Do not modify anything. Look at the files and the git history to find the answer.',
565
597
  SEARCH_FIRST_RULE,
566
598
  `- ${UNTRUSTED_RULE}`,
@@ -1447,6 +1447,7 @@ export class Runner {
1447
1447
  thread: run.thread,
1448
1448
  replies: run.replies ?? [],
1449
1449
  recent: run.recent ?? [],
1450
+ task: run.task,
1450
1451
  threadUrl: !this.o.publicUrl && typeof run.thread.url === 'string' && /^https?:\/\//.test(run.thread.url) ? run.thread.url : postUrl(this.base(), threadId),
1451
1452
  structured,
1452
1453
  });
@@ -52,6 +52,11 @@ export type InstallKind =
52
52
  kind: 'global';
53
53
  dir: string;
54
54
  }
55
+ /** The install in the AgentChannel home (appinstall.ts): a release per dir under `dir`, the launcher starts `current`. */
56
+ | {
57
+ kind: 'app';
58
+ dir: string;
59
+ }
55
60
  /** Source checkout, `npm link`, a project dependency, or anything else: not ours to replace. */
56
61
  | {
57
62
  kind: 'other';
@@ -62,6 +67,7 @@ export declare function detectInstall(o?: {
62
67
  self?: string;
63
68
  exec?: ExecFn;
64
69
  version?: string;
70
+ app?: string;
65
71
  }): Promise<InstallKind>;
66
72
  /**
67
73
  * Before the runner stops taking work: the release exists on npm, and a global install can be written. Nothing has been paused or
@@ -99,6 +105,8 @@ export type CheckResult = 'none' | 'manual' | 'off' | 'backoff' | 'busy' | 'fail
99
105
  export interface SelfUpdaterOptions {
100
106
  fetchVersions: () => Promise<HubVersions | null>;
101
107
  platform?: NodeJS.Platform;
108
+ /** The install in the AgentChannel home (default appDir()); tests point it elsewhere. */
109
+ app?: string;
102
110
  /** Windows: starts the helper that installs after this runner exited (default startWindowsUpdate). */
103
111
  handoff?: (target: string, dir: string) => boolean;
104
112
  runner: Quiescable;
@@ -220,12 +228,13 @@ export declare function markHealthy(home: string, version?: string): void;
220
228
  /**
221
229
  * Called first thing when `ach run` starts. A release this runner updated itself to, that has started BOOT_LIMIT times within
222
230
  * ten minutes without once becoming healthy, is marked bad here and the release before it is installed again (a global install;
223
- * an npx install has nothing to go back to and only marks it). Returns what it did; 'rolledback' means: exit UPDATE_EXIT_CODE.
231
+ * the install in the AgentChannel home points its launcher back; an npx install has nothing to go back to and only marks it). Returns what it did; 'rolledback' means: exit UPDATE_EXIT_CODE.
224
232
  */
225
233
  export declare function bootGuard(home: string, o?: {
226
234
  version?: string;
227
235
  exec?: ExecFn;
228
236
  self?: string;
237
+ app?: string;
229
238
  now?: () => number;
230
239
  log?: (s: string) => void;
231
240
  }): Promise<'ok' | 'rolledback' | 'marked'>;
@@ -1,8 +1,9 @@
1
1
  // Keeping a running `ach` current. Two jobs:
2
2
  //
3
3
  // - the runner (`ach run`, a long-lived daemon under systemd / launchd): SelfUpdater asks the hub which CLI release is the
4
- // newest, and when this one is behind it stops taking new work, waits for the runs in flight, installs the release (a
5
- // global install) or relies on npx to fetch it (a service started from the npx cache), and exits with UPDATE_EXIT_CODE.
4
+ // newest, and when this one is behind it stops taking new work, waits for the runs in flight, installs the release (into its
5
+ // own dir of the install in the AgentChannel home, appinstall.ts; or a global install) or relies on npx to fetch it (a service
6
+ // started from the npx cache), and exits with UPDATE_EXIT_CODE.
6
7
  // systemd (Restart=on-failure) and launchd (KeepAlive/SuccessfulExit=false) restart a non-zero exit, so the service comes
7
8
  // back on the new release. Parked runs and queued answers live in the hub and the runner's state file: nothing is lost.
8
9
  // - an MCP session (`ach mcp`, started by Claude Code or Codex): it cannot be restarted from outside, so startStaleNotice
@@ -18,6 +19,7 @@
18
19
  import { execFile, spawn } from 'node:child_process';
19
20
  import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
20
21
  import { dirname, join, sep } from 'node:path';
22
+ import { appDir, appWritable, inApp, installIntoApp, setCurrent } from './appinstall.js';
21
23
  import { thisCliPath } from './invite.js';
22
24
  import { CLIENT_PROTO, newerVersion, PKG_NAME, VERSION } from './version.js';
23
25
  /** A restart-worthy exit: not 0 (systemd on-failure and launchd restart only a failure) and not 78 (key refused: do not restart). */
@@ -81,6 +83,9 @@ const real = (p) => {
81
83
  /** How this CLI was installed, so that the right update is used (or none). */
82
84
  export async function detectInstall(o = {}) {
83
85
  const self = real(o.self ?? thisCliPath());
86
+ const app = real(o.app ?? appDir());
87
+ if (inApp(self, app))
88
+ return { kind: 'app', dir: app };
84
89
  if (/[\\/]_npx[\\/]/.test(self)) {
85
90
  // `...@3` re-resolves on a restart; an exact prerelease spec (`...@3.5.0-rc.1`) never moves
86
91
  return (o.version ?? VERSION).includes('-') ? { kind: 'other', why: 'started with npx from an exact prerelease version: run the join line (or `ach run --install-service`) again with the new release' } : { kind: 'npx' };
@@ -102,6 +107,8 @@ export async function preflight(kind, target, exec = defaultInstallExec) {
102
107
  const v = await exec('npm', ['view', `${PKG_NAME}@${target}`, 'version'], { timeoutMs: 30_000 });
103
108
  if (v.code !== 0 || !v.stdout.split(/\s+/).includes(target))
104
109
  return { ok: false, detail: `${PKG_NAME}@${target} is not on npm (yet), or npm cannot reach it` };
110
+ if (kind.kind === 'app' && !appWritable(kind.dir))
111
+ return { ok: false, detail: `no permission to write ${kind.dir}` };
105
112
  if (kind.kind === 'global') {
106
113
  try {
107
114
  accessSync(dirname(kind.dir), constants.W_OK); // <npm root -g>/@koalaauto: where npm replaces the package
@@ -118,6 +125,8 @@ export async function installRelease(kind, target, exec = defaultInstallExec) {
118
125
  return { ok: false, detail: kind.why };
119
126
  if (kind.kind === 'npx')
120
127
  return { ok: true, detail: 'npx fetches it on restart' };
128
+ if (kind.kind === 'app')
129
+ return installIntoApp(kind.dir, target, exec);
121
130
  const r = await exec('npm', ['install', '-g', '--ignore-scripts', '--no-audit', '--no-fund', `${PKG_NAME}@${target}`], { timeoutMs: 5 * 60_000 });
122
131
  if (r.code !== 0)
123
132
  return { ok: false, detail: `npm install -g ${PKG_NAME}@${target} failed (${(r.stderr || r.stdout).trim().split('\n').slice(-3).join(' | ').slice(0, 300)})` };
@@ -255,7 +264,7 @@ export class SelfUpdater {
255
264
  this.once(`backoff:${v.target}`, `ach ${v.target} is out but the last try ${new Date(last.at).toISOString()} did not end on it; trying again after a day`);
256
265
  return 'backoff';
257
266
  }
258
- const kind = await detectInstall({ self: this.o.self, exec: this.o.exec, version });
267
+ const kind = await detectInstall({ self: this.o.self, exec: this.o.exec, version, app: this.o.app });
259
268
  if (kind.kind === 'other') {
260
269
  this.once(`other:${v.target}`, `ach ${v.target} is out (this is ${version}) and cannot be installed by itself: ${kind.why}`);
261
270
  return 'manual';
@@ -495,7 +504,7 @@ export function markHealthy(home, version = VERSION) {
495
504
  /**
496
505
  * Called first thing when `ach run` starts. A release this runner updated itself to, that has started BOOT_LIMIT times within
497
506
  * ten minutes without once becoming healthy, is marked bad here and the release before it is installed again (a global install;
498
- * an npx install has nothing to go back to and only marks it). Returns what it did; 'rolledback' means: exit UPDATE_EXIT_CODE.
507
+ * the install in the AgentChannel home points its launcher back; an npx install has nothing to go back to and only marks it). Returns what it did; 'rolledback' means: exit UPDATE_EXIT_CODE.
499
508
  */
500
509
  export async function bootGuard(home, o = {}) {
501
510
  const version = o.version ?? VERSION;
@@ -512,7 +521,21 @@ export async function bootGuard(home, o = {}) {
512
521
  const log = o.log ?? ((s) => console.error(s));
513
522
  writeJson(home, badFile(home), [...new Set([...localBad(home), version])]);
514
523
  log(`[ach update] ${version} started ${b.starts.length} times in ten minutes without working: marked bad here, going back to ${upd.previous}`);
515
- const kind = await detectInstall({ self: o.self, exec: o.exec, version });
524
+ const kind = await detectInstall({ self: o.self, exec: o.exec, version, app: o.app });
525
+ if (kind.kind === 'app') {
526
+ // the release before is still in its own dir (or installed again): the launcher is pointed back at it
527
+ let r;
528
+ try {
529
+ setCurrent(kind.dir, upd.previous);
530
+ r = { ok: true, detail: '' };
531
+ }
532
+ catch {
533
+ r = await installRelease(kind, upd.previous, o.exec);
534
+ }
535
+ log(`[ach update] ${r.ok ? `back on ${upd.previous}` : `going back failed: ${r.detail}`}`);
536
+ writeJson(home, bootsFile(home), { version: upd.previous, starts: [], healthy: false });
537
+ return r.ok ? 'rolledback' : 'marked';
538
+ }
516
539
  if (kind.kind !== 'global') {
517
540
  log(`[ach update] cannot go back by itself (${kind.kind === 'npx' ? 'an npx install fetches the newest release on every start' : kind.why}): ask the hub's admin to mark ${version} bad (ACH_BAD_CLIENTS)`);
518
541
  return 'marked';
@@ -7,7 +7,7 @@
7
7
  export interface ServiceSpec {
8
8
  platform: 'darwin' | 'linux' | 'win32';
9
9
  agentName: string;
10
- /** What starts the CLI: node + cli.js of an install, or `npx -y <spec>` when it runs from the npx cache. */
10
+ /** What starts the CLI: node + the launcher of the install in the AgentChannel home, node + cli.js of another install, or `npx -y <spec>`. */
11
11
  command: string[];
12
12
  /** `run` arguments, without --install-service. */
13
13
  args: string[];
@@ -40,9 +40,10 @@ export interface FoundService {
40
40
  args: string[];
41
41
  env: Record<string, string>;
42
42
  logFile: string;
43
- /** `npx`: starts `npx -y <spec>`, so a restart gets the newest release. `node-cache`: starts node on a file inside the npx cache, which only ever
44
- * runs the release that was cached. `node`: node on some other install. */
45
- format: 'npx' | 'node-cache' | 'node' | 'unknown';
43
+ /** `app`: node on the launcher of the install in the AgentChannel home (appinstall.ts). `npx`: starts `npx -y <spec>`, which re-resolves
44
+ * the spec at every start (and fails while npm catches up with a release). `node-cache`: starts node on a file inside the npx cache,
45
+ * which only ever runs the release that was cached. `node`: node on some other install. */
46
+ format: 'app' | 'npx' | 'node-cache' | 'node' | 'unknown';
46
47
  }
47
48
  /** Where this platform keeps the files serviceFile() writes. */
48
49
  export declare function serviceDir(platform: ServiceSpec['platform'], env?: NodeJS.ProcessEnv): string;
@@ -163,6 +163,8 @@ const formatOf = (command) => {
163
163
  return 'unknown';
164
164
  if (/(^|[\\/])npx(\.cmd)?$/.test(command[0]))
165
165
  return 'npx';
166
+ if (command.length === 2 && /[\\/]app[\\/]ach\.mjs$/.test(command[1]))
167
+ return 'app';
166
168
  return command.slice(1).some((x) => /[\\/]_npx[\\/]/.test(x)) ? 'node-cache' : 'node';
167
169
  };
168
170
  /** Read a service file this module wrote (launchd plist or systemd unit); null for anything else, a Windows script included. */
@@ -29,8 +29,9 @@ export interface Migration {
29
29
  start: string[];
30
30
  }
31
31
  /**
32
- * This agent's own service, when it is in the old form (node on the npx cache): rewritten to start `npx -y <spec>`. Null when there is
33
- * none, or it is already fine. Writing only; the caller decides when to reload (that ends this very process).
32
+ * This agent's own service, when it starts through the npx cache (`npx -y <spec>`, or node on a file in the cache): rewritten to start
33
+ * `command`, the install in the AgentChannel home. Null when there is none, or it is already fine. Writing only; the caller decides when
34
+ * to reload (that ends this very process).
34
35
  */
35
36
  export declare function migrateOldService(o: {
36
37
  agentName: string;
@@ -38,8 +39,7 @@ export declare function migrateOldService(o: {
38
39
  dir?: string;
39
40
  env: NodeJS.ProcessEnv;
40
41
  home: string;
41
- npx: string;
42
- spec: string;
42
+ command: string[];
43
43
  }): Migration | null;
44
44
  /** Run the reload so that it outlives this process (the reload stops it): a detached shell. */
45
45
  export declare function reloadDetached(start: string[], env: NodeJS.ProcessEnv): void;
@@ -1,9 +1,10 @@
1
- // Keeping an agent's runner service right (issue #4): one service per agent, and a service that starts `npx -y <spec>`.
1
+ // Keeping an agent's runner service right (issue #4): one service per agent, and a service that starts the install in the AgentChannel home.
2
2
  // - Installing a service retires the others on this machine that run the same agent (same AGENTCHANNEL_HOME): a renamed agent
3
3
  // gets a new service label, and the old one went on running beside it.
4
- // - A service written by an early release starts node on a file inside the npx cache. A restart (including the self-update's)
5
- // runs that same cached file, so the runner never moves to a newer release. At start the runner rewrites such a service to
6
- // `npx -y <spec>` and has the supervisor reload it.
4
+ // - A service that starts through the npx cache: node on a cached file (early releases) never moves to a newer release, and
5
+ // `npx -y <spec>` re-resolves the spec at every start, which fails while npm catches up with a release. At start the runner
6
+ // copies itself into the install in the AgentChannel home (appinstall.ts), rewrites the service to start that, and has the
7
+ // supervisor reload it.
7
8
  import { execFileSync, spawn } from 'node:child_process';
8
9
  import { unlinkSync } from 'node:fs';
9
10
  import { achHome } from './config.js';
@@ -59,15 +60,16 @@ export function startedByService(agentName, platform, env) {
59
60
  return false;
60
61
  }
61
62
  /**
62
- * This agent's own service, when it is in the old form (node on the npx cache): rewritten to start `npx -y <spec>`. Null when there is
63
- * none, or it is already fine. Writing only; the caller decides when to reload (that ends this very process).
63
+ * This agent's own service, when it starts through the npx cache (`npx -y <spec>`, or node on a file in the cache): rewritten to start
64
+ * `command`, the install in the AgentChannel home. Null when there is none, or it is already fine. Writing only; the caller decides when
65
+ * to reload (that ends this very process).
64
66
  */
65
67
  export function migrateOldService(o) {
66
68
  const name = o.agentName.replace(/[^A-Za-z0-9-]/g, '-');
67
69
  const own = listServices(o.platform, o.dir, o.env).find((s) => s.agentName === name && homeOfService(s, o.env) === o.home);
68
- if (!own || own.format !== 'node-cache')
70
+ if (!own || (own.format !== 'npx' && own.format !== 'node-cache'))
69
71
  return null;
70
- const f = serviceFile(specOf(own, o.platform, [o.npx, '-y', o.spec]), o.dir, o.env);
72
+ const f = serviceFile(specOf(own, o.platform, o.command), o.dir, o.env);
71
73
  writeServiceFile(f);
72
74
  return { path: f.path, start: f.start };
73
75
  }
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.54.0";
1
+ export declare const VERSION = "3.55.0";
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export declare const PKG_NAME = "@koalaauto/agentchannel";
4
4
  /**
@@ -1,4 +1,4 @@
1
- export const VERSION = '3.54.0';
1
+ export const VERSION = '3.55.0';
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export const PKG_NAME = '@koalaauto/agentchannel';
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalaauto/agentchannel",
3
- "version": "3.54.0",
3
+ "version": "3.55.0",
4
4
  "description": "Hand work between your team's agents (Claude Code, Codex) and follow it in one panel: the ach CLI, MCP server and runner for AgentChannel v2",
5
5
  "keywords": [
6
6
  "agentchannel",