@koalaauto/agentchannel 3.66.0 → 3.67.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.
@@ -54,7 +54,8 @@ export function kiroArgs(o) {
54
54
  'chat',
55
55
  '--v3',
56
56
  '--no-interactive',
57
- ...(o.resume ? ['--resume-id', o.resume] : ['--cloud', '--repo', o.repo]),
57
+ // no repository (ACH_KIRO_REPO=none): the sandbox starts empty
58
+ ...(o.resume ? ['--resume-id', o.resume] : o.repo ? ['--cloud', '--repo', o.repo] : ['--cloud']),
58
59
  ...(o.format === 'stream-json' ? ['--output-format', 'stream-json'] : []),
59
60
  ...(o.model ? ['--model', o.model] : []),
60
61
  ...(o.effort && /^[a-z]{2,12}$/.test(o.effort) ? ['--effort', o.effort] : []),
@@ -273,16 +274,18 @@ export class KiroAdapter {
273
274
  }
274
275
  async run(opts) {
275
276
  const env = this.o.env ?? process.env;
276
- const repo = kiroRepoFor(opts.cwd, { ...env, ...opts.env, ACH_KIRO_REPO: env.ACH_KIRO_REPO }, this.o.git);
277
- if (!repo) {
277
+ // ACH_KIRO_REPO=none: a cloud workspace that was given no repository runs in an empty sandbox (a pool sets it)
278
+ const none = (env.ACH_KIRO_REPO ?? '').trim().toLowerCase() === 'none';
279
+ const repo = none ? '' : kiroRepoFor(opts.cwd, { ...env, ...opts.env, ACH_KIRO_REPO: env.ACH_KIRO_REPO }, this.o.git);
280
+ if (repo === undefined) {
278
281
  const error = `kiro: no GitHub repo for ${opts.cwd} (set ACH_KIRO_REPO=owner/name, or give the directory a github.com origin remote)`;
279
282
  opts.onEvent({ type: 'error', data: error });
280
283
  return { finalText: '', ok: false, error };
281
284
  }
282
- const first = await this.runOnce(opts, repo, 'stream-json');
285
+ const first = await this.runOnce(opts, repo ?? '', 'stream-json');
283
286
  if (!first.result.ok && !first.progressed && !opts.signal.aborted && FORMAT_REFUSED.test(first.result.error ?? '')) {
284
287
  opts.onEvent({ type: 'error', data: 'kiro-cli refused --output-format stream-json; running in text mode' });
285
- return (await this.runOnce(opts, repo, 'text')).result;
288
+ return (await this.runOnce(opts, repo ?? '', 'text')).result;
286
289
  }
287
290
  return first.result;
288
291
  }
package/dist/src/args.js CHANGED
@@ -48,6 +48,7 @@ export const COMMANDS = {
48
48
  dir: s, runtime: s, interval: s, max: s, perm: s, model: s, gc: b, days: s, 'pass-env': sm,
49
49
  repo: sm, 'claim-delay': s, 'interactive-first': b, 'install-service': b, notify: b, 'no-notify': b, 'no-trace': b, ...json,
50
50
  },
51
+ pool: { dir: s, interval: s, ...json },
51
52
  mcp: { ...json },
52
53
  caps: { ...json },
53
54
  open: { print: b, ...json },
@@ -232,6 +233,8 @@ Runner: ach run --dir <path> [--repo name=path ...] [--runtime ${RUNTIME_NAM
232
233
  notifications; off by default; macOS needs terminal-notifier)
233
234
  ach run --install-service [same flags] (installs and starts a launchd/systemd user unit; runs at login)
234
235
  ach run --gc [--dir <path>] [--days 7]
236
+ Pool: ach pool <name> --dir <base> [--interval 60] (keeps a runner going for every cloud workspace of a pool, e.g. kiro;
237
+ ACH_POOL_KEY is the pool's key, from an admin; docs/runner.md "A pool of cloud workspaces")
235
238
  MCP: ach mcp (stdio server; your interactive agent can also claim and work tasks)
236
239
  Panel: ach open [--print] (opens the panel in your browser, logged in as this agent's owner; 60 s single-use link)
237
240
  Admin: ach admin login --link <login link>
package/dist/src/cli.js CHANGED
@@ -919,6 +919,42 @@ async function dispatch(p, io) {
919
919
  }
920
920
  case 'run':
921
921
  return runCommand(p, io);
922
+ case 'pool': {
923
+ // the supervisor of a pool of cloud workspaces (pool.ts): `ach pool kiro --dir /srv/ach-pool`, with ACH_POOL_KEY
924
+ const name = p.positionals[0];
925
+ if (!name)
926
+ throw new UsageError('ach pool <name> --dir <base> (the pool, e.g. kiro; ACH_POOL_KEY is its key)');
927
+ const key = (env.ACH_POOL_KEY || '').trim();
928
+ if (!key)
929
+ throw new UsageError('ACH_POOL_KEY is not set: an admin makes the key (POST /api/ach/admin/pools/<name>/key)');
930
+ const cfg = loadConfig(env);
931
+ if (!cfg.hub)
932
+ throw new UsageError('No hub configured: set ACH_HUB, or run this where an agent was joined');
933
+ const base = resolve(io.cwd ?? process.cwd(), String(p.values.dir || `ach-pool-${name}`));
934
+ const { Pool } = await import('./pool.js');
935
+ const client = new Client({ hub: cfg.hub, token: key, cfId: cfg.cfId, cfSecret: cfg.cfSecret, fetch: io.fetch });
936
+ // the pool's key is not the runners': each runs with its own agent's key, from its own home
937
+ const childEnv = { ...env };
938
+ delete childEnv.ACH_POOL_KEY;
939
+ delete childEnv.ACH_KEY;
940
+ const pool = new Pool({ name, base, hub: cfg.hub, cfId: cfg.cfId, cfSecret: cfg.cfSecret, env: childEnv, log: io.err }, { agents: () => client.poolAgents(name), key: (id) => client.poolAgentKey(name, id) });
941
+ const everyMs = Math.max(5, Number(p.values.interval) || 60) * 1000;
942
+ io.err(`ach pool ${name}: homes and work under ${base}; asking the hub every ${everyMs / 1000}s`);
943
+ const stop = () => { pool.stop(); process.exit(0); };
944
+ process.once('SIGTERM', stop);
945
+ process.once('SIGINT', stop);
946
+ for (;;) {
947
+ try {
948
+ const r = await pool.tick();
949
+ if (r.started.length || r.stopped.length)
950
+ io.err(`pool ${name}: started ${r.started.join(', ') || 'none'}; stopped ${r.stopped.join(', ') || 'none'}; running ${pool.running.size}`);
951
+ }
952
+ catch (e) {
953
+ io.err(`pool ${name}: the hub did not answer (${e?.message ?? e}); the runners keep going`);
954
+ }
955
+ await new Promise((r) => setTimeout(r, everyMs));
956
+ }
957
+ }
922
958
  case 'mcp': {
923
959
  const { startMcp } = await import('./mcp.js');
924
960
  // a project with an agent of its own speaks as that agent, even from the user-wide MCP entry
@@ -540,6 +540,14 @@ export declare class Client {
540
540
  projects: Project[];
541
541
  refreshed_at: string;
542
542
  }>;
543
+ /** `ach pool`: the agents of a pool (this client's token is the pool's key). */
544
+ poolAgents(name: string): Promise<{
545
+ id: string;
546
+ name: string;
547
+ repos: string[];
548
+ }[]>;
549
+ /** A fresh key for one of the pool's agents (its old one stops working). */
550
+ poolAgentKey(name: string, agentId: string): Promise<string>;
543
551
  agents(): Promise<Agent[]>;
544
552
  sendTask(input: SendTaskInput, files?: string[]): Promise<Task>;
545
553
  /** The sender's side accepts a task that waits for acceptance: it is completed. */
@@ -338,6 +338,15 @@ export class Client {
338
338
  async projects() {
339
339
  return this.ach('GET', '/projects');
340
340
  }
341
+ /** `ach pool`: the agents of a pool (this client's token is the pool's key). */
342
+ async poolAgents(name) {
343
+ const r = await this.ach('GET', `/pool/${encodeURIComponent(name)}/agents`);
344
+ return arr(r?.agents).map((a) => ({ id: String(a.id), name: String(a.name), repos: arr(a.repos).map(String) }));
345
+ }
346
+ /** A fresh key for one of the pool's agents (its old one stops working). */
347
+ async poolAgentKey(name, agentId) {
348
+ return String((await this.ach('POST', `/pool/${encodeURIComponent(name)}/agents/${encodeURIComponent(agentId)}/key`))?.key ?? '');
349
+ }
341
350
  async agents() {
342
351
  const r = await this.ach('GET', '/agents');
343
352
  return Array.isArray(r) ? r : arr(r?.agents ?? r?.items);
@@ -0,0 +1,64 @@
1
+ export interface PoolAgent {
2
+ id: string;
3
+ name: string;
4
+ /** owner/name GitHub repositories its cloud session opens */
5
+ repos: string[];
6
+ }
7
+ export interface PoolHub {
8
+ agents(): Promise<PoolAgent[]>;
9
+ /** a fresh key for one agent (its old key stops working): asked once, when its home is made */
10
+ key(agentId: string): Promise<string>;
11
+ }
12
+ export interface PoolOptions {
13
+ name: string;
14
+ /** where the homes and directories of the pool's agents live */
15
+ base: string;
16
+ hub: string;
17
+ cfId?: string;
18
+ cfSecret?: string;
19
+ env: NodeJS.ProcessEnv;
20
+ log: (s: string) => void;
21
+ /** tests: start a runner (default: this CLI's `run`) */
22
+ start?: (a: PoolAgent, home: string, dir: string, env: NodeJS.ProcessEnv) => PoolChild;
23
+ now?: () => number;
24
+ }
25
+ export interface PoolChild {
26
+ /** set once it has exited */
27
+ exited?: {
28
+ code: number | null;
29
+ };
30
+ stop(): void;
31
+ }
32
+ export declare const agentHomeIn: (base: string, a: PoolAgent) => string;
33
+ export declare const agentDirIn: (base: string, a: PoolAgent) => string;
34
+ /** What the Kiro runtime opens: the agent's repositories, or `none` for an empty sandbox. */
35
+ export declare const reposEnv: (a: PoolAgent) => string;
36
+ /** The agent's home, made the first time with a key taken for it; later starts find it there. */
37
+ export declare function ensureHome(o: Pick<PoolOptions, 'base' | 'hub' | 'cfId' | 'cfSecret'>, a: PoolAgent, hub: PoolHub): Promise<{
38
+ home: string;
39
+ dir: string;
40
+ made: boolean;
41
+ }>;
42
+ interface Running {
43
+ agent: PoolAgent;
44
+ child: PoolChild;
45
+ repos: string;
46
+ }
47
+ export declare class Pool {
48
+ private o;
49
+ private hub;
50
+ readonly running: Map<string, Running>;
51
+ /** when a runner that exited may be started again, and how often it has in a row */
52
+ private retry;
53
+ private start;
54
+ private now;
55
+ constructor(o: PoolOptions, hub: PoolHub);
56
+ /** One round: what the hub says is in the pool is what runs. Returns what changed (for the log, and the tests). */
57
+ tick(): Promise<{
58
+ started: string[];
59
+ stopped: string[];
60
+ failed: string[];
61
+ }>;
62
+ stop(): void;
63
+ }
64
+ export {};
@@ -0,0 +1,122 @@
1
+ // `ach pool <name>`: the supervisor of a pool of cloud workspaces (docs/specs/primary-agent-design.md §8.2). A cloud
2
+ // workspace is an agent whose work happens in the vendor's cloud (Kiro), so nobody's own machine has to be on for it; but each
3
+ // still needs a runner that takes its tasks and starts the cloud session. This process is that: with the pool's key it asks the
4
+ // hub which agents are in the pool, gives each a home and a directory of its own, takes that agent's key once, and keeps an
5
+ // ordinary `ach run` going for it (the same runner a person starts by hand: nothing about a run is different here). An agent
6
+ // that leaves the pool has its runner stopped; one whose repositories changed has it restarted.
7
+ import { spawn } from 'node:child_process';
8
+ import { chmodSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { cfSecretPath, keyFilePath } from './keystore.js';
12
+ /** The CLI's entry (dist/src/cli.js, next to this file). */
13
+ const CLI_JS = join(dirname(fileURLToPath(import.meta.url)), 'cli.js');
14
+ const safe = (name) => name.replace(/[^A-Za-z0-9-]/g, '-');
15
+ export const agentHomeIn = (base, a) => join(base, 'homes', safe(a.name));
16
+ export const agentDirIn = (base, a) => join(base, 'work', safe(a.name));
17
+ /** What the Kiro runtime opens: the agent's repositories, or `none` for an empty sandbox. */
18
+ export const reposEnv = (a) => (a.repos.length ? a.repos.join(',') : 'none');
19
+ /** The agent's home, made the first time with a key taken for it; later starts find it there. */
20
+ export async function ensureHome(o, a, hub) {
21
+ const home = agentHomeIn(o.base, a);
22
+ const dir = agentDirIn(o.base, a);
23
+ mkdirSync(dir, { recursive: true });
24
+ if (existsSync(keyFilePath(home)))
25
+ return { home, dir, made: false };
26
+ mkdirSync(home, { recursive: true, mode: 0o700 });
27
+ const key = await hub.key(a.id);
28
+ const secret = (path, value) => {
29
+ writeFileSync(path, value + '\n', { mode: 0o600 });
30
+ chmodSync(path, 0o600);
31
+ };
32
+ writeFileSync(join(home, 'config.json'), JSON.stringify({ hub: o.hub, ...(o.cfId ? { cf_id: o.cfId } : {}), dir }, null, 2) + '\n', { mode: 0o600 });
33
+ if (o.cfSecret)
34
+ secret(cfSecretPath(home), o.cfSecret);
35
+ // the key last: a home without it is made again next time
36
+ secret(keyFilePath(home), key);
37
+ return { home, dir, made: true };
38
+ }
39
+ function startRunner(name, log) {
40
+ return (a, home, dir, env) => {
41
+ const proc = spawn(process.execPath, [CLI_JS, 'run', '--dir', dir, '--runtime', name, '--max', '1'], { env, stdio: ['ignore', 'pipe', 'pipe'] });
42
+ const child = { stop: () => { try {
43
+ proc.kill('SIGTERM');
44
+ }
45
+ catch { /* gone */ } } };
46
+ const say = (d) => { for (const line of String(d).split('\n'))
47
+ if (line.trim())
48
+ log(`[${a.name}] ${line}`); };
49
+ proc.stdout?.on('data', say);
50
+ proc.stderr?.on('data', say);
51
+ proc.on('error', (e) => { log(`[${a.name}] could not start: ${e.message}`); child.exited = { code: null }; });
52
+ proc.on('exit', (code) => { child.exited = { code }; });
53
+ return child;
54
+ };
55
+ }
56
+ const BACKOFF_MS = [10_000, 30_000, 60_000, 300_000];
57
+ export class Pool {
58
+ o;
59
+ hub;
60
+ running = new Map();
61
+ /** when a runner that exited may be started again, and how often it has in a row */
62
+ retry = new Map();
63
+ start;
64
+ now;
65
+ constructor(o, hub) {
66
+ this.o = o;
67
+ this.hub = hub;
68
+ this.start = o.start ?? startRunner(o.name, o.log);
69
+ this.now = o.now ?? Date.now;
70
+ }
71
+ /** One round: what the hub says is in the pool is what runs. Returns what changed (for the log, and the tests). */
72
+ async tick() {
73
+ const out = { started: [], stopped: [], failed: [] };
74
+ const agents = await this.hub.agents();
75
+ const want = new Map(agents.map((a) => [a.id, a]));
76
+ for (const [id, r] of this.running) {
77
+ const a = want.get(id);
78
+ // gone from the pool, or its repositories changed (the runner reads them when it starts)
79
+ if (!a || reposEnv(a) !== r.repos) {
80
+ r.child.stop();
81
+ this.running.delete(id);
82
+ this.retry.delete(id);
83
+ out.stopped.push(r.agent.name);
84
+ }
85
+ else if (r.child.exited) {
86
+ this.running.delete(id);
87
+ const n = (this.retry.get(id)?.n ?? 0) + 1;
88
+ this.retry.set(id, { at: this.now() + BACKOFF_MS[Math.min(n - 1, BACKOFF_MS.length - 1)], n });
89
+ this.o.log(`[${r.agent.name}] its runner exited (${r.child.exited.code ?? 'no code'}); starting it again`);
90
+ }
91
+ }
92
+ for (const a of agents) {
93
+ if (this.running.has(a.id))
94
+ continue;
95
+ const wait = this.retry.get(a.id);
96
+ if (wait && wait.at > this.now())
97
+ continue;
98
+ try {
99
+ const { home, dir, made } = await ensureHome(this.o, a, this.hub);
100
+ if (made)
101
+ this.o.log(`[${a.name}] home made at ${home}`);
102
+ const child = this.start(a, home, dir, { ...this.o.env, AGENTCHANNEL_HOME: home, ACH_KIRO_REPO: reposEnv(a) });
103
+ this.running.set(a.id, { agent: a, child, repos: reposEnv(a) });
104
+ out.started.push(a.name);
105
+ }
106
+ catch (e) {
107
+ out.failed.push(a.name);
108
+ this.o.log(`[${a.name}] not started: ${e?.message ?? e}`);
109
+ }
110
+ }
111
+ // a runner that has stayed up is no longer "failing in a row"
112
+ for (const [id, r] of this.running)
113
+ if (!r.child.exited && this.retry.has(id) && this.retry.get(id).at + 600_000 < this.now())
114
+ this.retry.delete(id);
115
+ return out;
116
+ }
117
+ stop() {
118
+ for (const r of this.running.values())
119
+ r.child.stop();
120
+ this.running.clear();
121
+ }
122
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Remove a temporary path the runner made; one that stays is left to the OS. On Windows a process that just exited (a sandboxed
3
+ * probe, a run's Codex) can still hold its folder for a moment, and a plain rmSync threw EBUSY out of the caller: the sandbox
4
+ * probe lost its verdict and the agent was shown as needing setup (zip-reela-analytics, 3.63.1).
5
+ */
6
+ export declare function removeQuietly(p: string): void;
@@ -0,0 +1,14 @@
1
+ import { rmSync } from 'node:fs';
2
+ /**
3
+ * Remove a temporary path the runner made; one that stays is left to the OS. On Windows a process that just exited (a sandboxed
4
+ * probe, a run's Codex) can still hold its folder for a moment, and a plain rmSync threw EBUSY out of the caller: the sandbox
5
+ * probe lost its verdict and the agent was shown as needing setup (zip-reela-analytics, 3.63.1).
6
+ */
7
+ export function removeQuietly(p) {
8
+ try {
9
+ rmSync(p, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
10
+ }
11
+ catch {
12
+ // a leftover temporary folder harms nothing
13
+ }
14
+ }
@@ -1,5 +1,5 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { appendFileSync, mkdirSync, rmSync } from 'node:fs';
2
+ import { appendFileSync, mkdirSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
@@ -24,6 +24,7 @@ import { isGitRepo } from './workspace.js';
24
24
  import { accountProblem, effortRejected, looksLikeLoginError, modelRejected, programMissing, summarizeRuntimeError } from '../envcheck.js';
25
25
  import { redact } from '../redact.js';
26
26
  import { TraceRecorder } from '../trace.js';
27
+ import { removeQuietly } from '../removequiet.js';
27
28
  import { detectHost, looksLikeSandboxError, sandboxFix } from '../sandboxcheck.js';
28
29
  import { prepareAgentHome, realHomeOf, secretPaths } from './home.js';
29
30
  import { draftText, parsePrepared, parseStructured } from './structured.js';
@@ -787,12 +788,12 @@ export class Runner {
787
788
  }
788
789
  this.state.pruneTasks(dead);
789
790
  for (const id of dead) {
790
- rmSync(this.filesDir(id), { recursive: true, force: true });
791
+ removeQuietly(this.filesDir(id));
791
792
  // the task's scratch HOME (caches, a Codex session) is not needed once the task has ended
792
793
  if (this.me?.name) {
793
794
  const h = join(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), this.me.name.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80), id.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80));
794
795
  unlinkWindowsSandbox(join(h, '.codex')); // the user's own sandbox setup: never removed with the run
795
- rmSync(h, { recursive: true, force: true });
796
+ removeQuietly(h);
796
797
  }
797
798
  }
798
799
  // once a day: work dirs of tasks that ended more than a week ago (`ach run --gc` by hand does the same; branches are kept)
@@ -1,7 +1,8 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { runtimeLabel, runtimeSpec } from './adapters/spec.js';
3
3
  import { randomBytes } from 'node:crypto';
4
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { removeQuietly } from './removequiet.js';
5
6
  import { createRequire } from 'node:module';
6
7
  import { homedir, tmpdir } from 'node:os';
7
8
  import { delimiter, dirname, join } from 'node:path';
@@ -286,13 +287,13 @@ async function probe(tool, o) {
286
287
  return { tool, ok: false, problem: classify(err, host), detail: firstLine(err) || `exit ${r.code}` };
287
288
  }
288
289
  finally {
289
- rmSync(dir, { recursive: true, force: true });
290
- rmSync(outside, { force: true });
290
+ removeQuietly(dir);
291
+ removeQuietly(outside);
291
292
  if (canaryDir)
292
- rmSync(canaryDir, { recursive: true, force: true });
293
+ removeQuietly(canaryDir);
293
294
  if (codexHome) {
294
295
  unlinkWindowsSandbox(codexHome);
295
- rmSync(codexHome, { recursive: true, force: true });
296
+ removeQuietly(codexHome);
296
297
  }
297
298
  }
298
299
  }
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.66.0";
1
+ export declare const VERSION = "3.67.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.66.0';
1
+ export const VERSION = '3.67.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.66.0",
3
+ "version": "3.67.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",