@koalaauto/agentchannel 3.25.0 → 3.26.1

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.
@@ -26,6 +26,11 @@ function accessBlocked(res) {
26
26
  return true;
27
27
  return /^Cloudflare-Access\b/i.test(res.headers?.get?.('www-authenticate') ?? '');
28
28
  }
29
+ /** The hub could not be reached at all (no answer, a refused connection, a DNS failure, or no answer within the time limit). */
30
+ export class NetworkError extends Error {
31
+ }
32
+ /** How long an ordinary request waits for the hub (uploads, which may be big, have no limit of their own). */
33
+ const REQUEST_TIMEOUT_MS = 60_000;
29
34
  export class HubError extends Error {
30
35
  status;
31
36
  code;
@@ -124,11 +129,25 @@ export class Client {
124
129
  if (files?.length)
125
130
  ({ body, files } = await this.splitAttachments(path, body, files));
126
131
  const multipart = !!files?.length;
127
- const res = await this.fetchFn(url, {
128
- method,
129
- headers: this.headers(!multipart),
130
- body: multipart ? await attachmentForm(body, files) : body === undefined ? undefined : JSON.stringify(body),
131
- });
132
+ let res;
133
+ try {
134
+ res = await this.fetchFn(url, {
135
+ method,
136
+ headers: this.headers(!multipart),
137
+ body: multipart ? await attachmentForm(body, files) : body === undefined ? undefined : JSON.stringify(body),
138
+ ...(multipart ? {} : { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }),
139
+ });
140
+ }
141
+ catch (e) {
142
+ const host = (() => { try {
143
+ return new URL(url).host;
144
+ }
145
+ catch {
146
+ return url;
147
+ } })();
148
+ const why = e?.name === 'TimeoutError' ? `no answer within ${REQUEST_TIMEOUT_MS / 1000} s` : String(e?.cause?.code ?? e?.cause?.message ?? e?.message ?? e);
149
+ throw new NetworkError(`cannot reach ${host} (${why}): check the hub address, your network, and whether a VPN or proxy is in the way. \`ach doctor\` checks each step.`);
150
+ }
132
151
  // Cloudflare Access in front of the hub answers with its login page (a redirect followed to *.cloudflareaccess.com,
133
152
  // or a challenge header) instead of the hub's JSON: say so, instead of failing later on a missing field
134
153
  if (accessBlocked(res)) {
@@ -19,4 +19,11 @@ export declare function probeEnvironment(tool: SandboxTool, o?: ProbeOptions & {
19
19
  */
20
20
  export declare function summarizeRuntimeError(raw: string): string;
21
21
  /** Does a run's error say the tool is not logged in (or its key was refused)? */
22
+ /**
23
+ * The account behind the runtime has no budget left right now (a weekly or daily usage limit, rate limit or overload), so the next
24
+ * task would fail the same way. `pauseMs` is how long to wait: a usage limit lasts until it resets, a rate limit or overload is short.
25
+ */
26
+ export declare function quotaProblem(s: string): {
27
+ pauseMs: number;
28
+ } | null;
22
29
  export declare function looksLikeLoginError(s: string): boolean;
@@ -93,6 +93,17 @@ export function summarizeRuntimeError(raw) {
93
93
  return picked.join(' | ').slice(0, 600);
94
94
  }
95
95
  /** Does a run's error say the tool is not logged in (or its key was refused)? */
96
+ /**
97
+ * The account behind the runtime has no budget left right now (a weekly or daily usage limit, rate limit or overload), so the next
98
+ * task would fail the same way. `pauseMs` is how long to wait: a usage limit lasts until it resets, a rate limit or overload is short.
99
+ */
100
+ export function quotaProblem(s) {
101
+ if (/hit your (weekly |daily |monthly |usage |5-hour |session )?limit|usage limit|weekly limit|session limit|5-hour limit|limit reached|quota (exceeded|reached)|insufficient (credit|quota)|credit balance/i.test(s))
102
+ return { pauseMs: 30 * 60_000 };
103
+ if (/rate.?limit|\b429\b|overloaded|too many requests/i.test(s))
104
+ return { pauseMs: 5 * 60_000 };
105
+ return null;
106
+ }
96
107
  export function looksLikeLoginError(s) {
97
108
  return /\b401\b|unauthori[sz]ed|not logged in|please (run|log)[^.\n]*login|invalid (api )?key|authentication (failed|required|error)|credentials? (expired|missing|invalid)/i.test(s);
98
109
  }
@@ -326,6 +326,14 @@ function chanOut(name, rs, desc) {
326
326
  },
327
327
  };
328
328
  }
329
+ /** "(12 commits, 3 issues, 2 PRs, 5 assigned)" for the plan printout: what the role was inferred from. */
330
+ const personActivity = (p) => {
331
+ const s = p.stats;
332
+ if (!s)
333
+ return '';
334
+ const parts = [[s.commits, 'commits'], [s.issues_opened, 'issues'], [s.prs_opened, 'PRs'], [s.assigned, 'assigned']].filter(([n]) => Number(n) > 0).map(([n, w]) => `${n} ${w}`);
335
+ return parts.length ? ` (${parts.join(', ')})` : '';
336
+ };
329
337
  /** People from commits, issues and PRs; roles inferred; bots excluded. */
330
338
  export function inferPeople(c, channels) {
331
339
  const chanOf = new Map();
@@ -393,17 +401,8 @@ export function inferPeople(c, channels) {
393
401
  for (const a of acc.values()) {
394
402
  const total = a.commits + a.opened + a.prs + a.assigned;
395
403
  const self = !!c.self && a.login.toLowerCase() === c.self.toLowerCase();
396
- const top = Object.entries(a.byRepo).sort((x, y) => y[1] - x[1]).slice(0, 3);
397
- const parts = [];
398
- if (top.length)
399
- parts.push(`commits: ${top.map(([n, k]) => `${n} ${k}`).join(', ')}`);
400
- if (a.opened)
401
- parts.push(`opened ${a.opened} issue(s)`);
402
- if (a.prs)
403
- parts.push(`opened ${a.prs} PR(s)`);
404
- if (a.assigned)
405
- parts.push(`assigned ${a.assigned}`);
406
- const label = self ? 'admin' : a.commits >= 10 ? 'maintainer' : a.opened >= 5 && a.commits < 3 ? 'reporter / tester' : 'contributor';
404
+ // a short label a person can read on their page; the counts stay in `stats` (admin is a permission, shown apart)
405
+ const label = a.commits >= 10 ? 'maintainer' : a.opened >= 5 && a.commits < 3 ? 'reporter / tester' : 'contributor';
407
406
  const invite = self || total >= 3 || a.assigned > 0;
408
407
  const u = c.users[a.login];
409
408
  people.push({
@@ -413,7 +412,7 @@ export function inferPeople(c, channels) {
413
412
  is_admin: self,
414
413
  ...(self ? { self: true } : {}),
415
414
  invite,
416
- role: `${label}${parts.length ? ` (${parts.join('; ')})` : ''}`,
415
+ role: label,
417
416
  ...(invite ? {} : { note: 'occasional contributor: confirm who this is before inviting' }),
418
417
  channels: [...a.chans.entries()].sort((x, y) => y[1] - x[1]).map(([n]) => n),
419
418
  stats: { commits: a.commits, issues_opened: a.opened, prs_opened: a.prs, assigned: a.assigned, commits_by_repo: a.byRepo },
@@ -596,7 +595,7 @@ export function planSummary(plan, file, sel) {
596
595
  L.push('');
597
596
  L.push('People:');
598
597
  for (const p of plan.people.filter((x) => x.invite !== false)) {
599
- L.push(` ${pad(p.github_login, 18)}${pad(p.name, 18)}${p.is_admin ? '[admin] ' : ''}${p.role ?? ''}${p.channels?.length ? ` -> ${p.channels.map((c) => '#' + c).join(' ')}` : ''}`);
598
+ L.push(` ${pad(p.github_login, 18)}${pad(p.name, 18)}${p.is_admin ? '[admin] ' : ''}${p.role ?? ''}${personActivity(p)}${p.channels?.length ? ` -> ${p.channels.map((c) => '#' + c).join(' ')}` : ''}`);
600
599
  }
601
600
  const later = plan.people.filter((x) => x.invite === false);
602
601
  if (later.length)
@@ -82,7 +82,7 @@ export function npxAch(version = VERSION) {
82
82
  /** The join line minus the blob (for parsing tests and docs). */
83
83
  export const JOIN_LINE_RE = /^npx -y @koalaauto\/agentchannel@\S+ join (ach2\.\S+)$/;
84
84
  /** What to tell the person who gets the line. */
85
- export const JOIN_HINT = 'They paste the line in a terminal (Node 20+); npx fetches the CLI. To type `ach` yourself: `npm i -g ' + PKG_NAME + '@next`. ' +
85
+ export const JOIN_HINT = 'They paste the line in a terminal (Node 20+); npx fetches the CLI. To type `ach` yourself: `npm i -g ' + PKG_NAME + '`. ' +
86
86
  '`ach doctor` checks the setup.';
87
87
  /** The MCP server name printed for `claude mcp add` / `codex mcp add`. */
88
88
  export const MCP_SERVER_NAME = 'ach';
package/dist/src/mcp.d.ts CHANGED
@@ -29,6 +29,13 @@ export declare function mcpInstructions(brief?: string): string;
29
29
  /** Claude Code channel capability: lets this server push a one-line reminder into an open session. */
30
30
  export declare const CLAUDE_CHANNEL_CAPABILITY = "claude/channel";
31
31
  export declare const CLAUDE_CHANNEL_METHOD = "notifications/claude/channel";
32
+ export declare const toolHints: (name: string) => {
33
+ readOnlyHint: boolean;
34
+ destructiveHint?: undefined;
35
+ } | {
36
+ readOnlyHint: boolean;
37
+ destructiveHint: boolean;
38
+ };
32
39
  export declare function buildMcpServer(client: Client, o?: {
33
40
  brief?: string;
34
41
  }): McpServer;
package/dist/src/mcp.js CHANGED
@@ -9,7 +9,8 @@ import { join } from 'node:path';
9
9
  import { AttentionNotifier, ChangeFeed, codexQueue, defaultExec, fetchAttention } from './attention.js';
10
10
  import { isZh } from './client.js';
11
11
  import { startStaleNotice } from './selfupdate.js';
12
- import { decisionTo, explainToUser } from './names.js';
12
+ import { decisionTo, explainToUser, mentionNames, unknownMentions } from './names.js';
13
+ import { HubError } from './client.js';
13
14
  export const HANDOFF_TEMPLATE = `## Goal
14
15
  <one or two sentences: what done looks like>
15
16
 
@@ -91,7 +92,7 @@ const ATTACH = z
91
92
  .array(z.string())
92
93
  .max(10)
93
94
  .optional()
94
- .describe('Local files to attach: images (png, jpg, webp, gif), videos (mp4, webm, mov), text/code up to 2 MB (txt md json ts js py go sh diff patch log csv yaml sql) or an .html report. Big videos go straight to the hub\'s bucket when it has S3/R2 storage. An https URL (R2/S3/OSS/TOS presigned or public) is attached as a link without uploading.');
95
+ .describe('Local files to attach: images (png, jpg, webp, gif), videos (mp4, webm, mov), text/code up to 2 MB (txt md json ts js py go sh diff patch log csv yaml sql) or an .html report. To refer to something that lives elsewhere, put its link in the text.');
95
96
  const LINKS_HELP = 'Refer to tasks, posts and commits by link or ID (TASK-128, a post link, a commit URL) rather than "the one above". Task tools accept TASK-128 (or T-128) wherever a task id is asked for.';
96
97
  const TASK_FIELDS_HELP = 'Fill all four header fields (the team convention): priority, purpose (why this task exists), key_question (the one question the work must answer) and money (cost before/after and budget impact, or "n/a").';
97
98
  /**
@@ -116,6 +117,7 @@ export function interactiveInstructions(o) {
116
117
  export const MCP_INSTRUCTIONS = [
117
118
  'AgentChannel hands work between the agents of one team and lets their people follow it in one panel.',
118
119
  'Tasks are referred to as TASK-128 (any tool that takes a task id accepts TASK-128). Channels are team streams named by a folder path (#general, #reela/onair): write the full path, a short name works only when one channel has it.',
120
+ 'Your user is here in this session: when a question is for them, ask them in the conversation first; request_decision and ask are for people and agents who are not.',
119
121
  'When to use which tool:',
120
122
  '- inbox: what is waiting for you (tasks sent to you, questions, answers, decisions, @mentions). owner_inbox: what waits for your owner (the person): their decisions and escalations.',
121
123
  '- send_task: hand a piece of work to another agent (title, money impact or "n/a", a markdown handoff).',
@@ -137,9 +139,31 @@ export function mcpInstructions(brief) {
137
139
  /** Claude Code channel capability: lets this server push a one-line reminder into an open session. */
138
140
  export const CLAUDE_CHANNEL_CAPABILITY = 'claude/channel';
139
141
  export const CLAUDE_CHANNEL_METHOD = 'notifications/claude/channel';
142
+ /**
143
+ * What a client may assume about a tool without asking: it only reads, or it speaks for the owner and cannot be taken back
144
+ * (deciding, granting, revoking, cancelling). A client that auto-allows read-only tools and asks before the rest is then
145
+ * right about which is which.
146
+ */
147
+ const READ_ONLY_TOOLS = new Set(['list_agents', 'list_schedules', 'get_task', 'inbox', 'owner_inbox', 'list_grants', 'list_channels', 'read_channel', 'search', 'memory_search', 'memory_read', 'wiki_search', 'wiki_read']);
148
+ const OWNER_LEVEL_TOOLS = new Set(['decide', 'grant_authorization', 'revoke_grant', 'cancel_task']);
149
+ export const toolHints = (name) => (READ_ONLY_TOOLS.has(name) ? { readOnlyHint: true } : OWNER_LEVEL_TOOLS.has(name) ? { readOnlyHint: false, destructiveHint: true } : { readOnlyHint: false, destructiveHint: false });
140
150
  export function buildMcpServer(client, o = {}) {
141
151
  const server = new McpServer({ name: 'ach', version: VERSION }, { instructions: mcpInstructions(o.brief), capabilities: { experimental: { [CLAUDE_CHANNEL_CAPABILITY]: {} } } });
152
+ // every tool carries its hints, whatever registers it
153
+ const register = server.registerTool.bind(server);
154
+ server.registerTool = (name, cfg, cb) => register(name, { ...cfg, annotations: { ...toolHints(name), ...(cfg?.annotations ?? {}) } }, cb);
142
155
  let meCache;
156
+ // @names that wake nobody: said in the result (with the closest known name), as the CLI says it, instead of failing silently
157
+ const withMentionWarnings = async (r, text) => {
158
+ if (!mentionNames(text).length)
159
+ return r;
160
+ const agents = await client.agents().catch(() => []);
161
+ if (!agents.length)
162
+ return r;
163
+ const ppl = agents.filter((x) => x.owner_name).map((x) => ({ name: x.owner_name }));
164
+ const warnings = unknownMentions(text, agents, ppl).map((u) => `@${u.name} matches no agent or person${u.suggest ? ` (did you mean @${u.suggest}?)` : ''}; nobody was notified for it`);
165
+ return warnings.length && r && typeof r === 'object' ? { ...r, warnings } : r;
166
+ };
143
167
  const me = async () => (meCache ??= await client.me());
144
168
  const att = (paths) => resolveAttachments(paths, { env: process.env, cwd: process.cwd() });
145
169
  /** P1: the run_id of my interactive claim on a task, or a clear error. */
@@ -165,7 +189,7 @@ export function buildMcpServer(client, o = {}) {
165
189
  key_question: z.string().optional().describe('The one question this work must answer (shown in the panel header)'),
166
190
  money: z.string().describe('Cost before/after and budget impact, or "n/a"'),
167
191
  handoff: z.string().describe('Markdown handoff following the template'),
168
- depends_on: z.array(z.string()).optional(),
192
+ depends_on: z.array(z.string()).optional().describe('Tasks this one comes after. The receiver is not given the task until those tasks have completed (a failed or canceled one keeps it waiting until you cancel this task).'),
169
193
  review: z.boolean().optional().describe('Set true when the work must be checked before it counts as done: it then waits for acceptance (accept_task / request_changes by you or your checker agent) instead of being completed when the worker says done'),
170
194
  base: z.string().optional().describe('Branch or commit the receiver should start from'),
171
195
  repo: z.string().optional().describe('Repo name the receiver should work in (its runner maps names to local paths)'),
@@ -214,7 +238,7 @@ export function buildMcpServer(client, o = {}) {
214
238
  handoff: z.string().describe('Markdown handoff for every run; {date} is replaced by the run date'),
215
239
  every: z.enum(['day', 'weekday', 'week', 'month']).optional().describe('Time rule (omit for an event rule)'),
216
240
  at: z.string().optional().describe('Local time HH:MM (24 h), with every'),
217
- on: z.enum(['task_completed', 'task_failed', 'figure', 'post']).optional().describe('Event rule instead of a time'),
241
+ on: z.enum(['task_completed', 'task_review', 'task_failed', 'figure', 'post']).optional().describe('Event rule instead of a time. task_review fires when work sent with review waits for acceptance (it fires again after each rework)'),
218
242
  match: z.record(z.string(), z.unknown()).optional().describe('Event filter, see above'),
219
243
  weekday: z.number().int().min(1).max(7).optional().describe('every=week: 1 = Monday .. 7 = Sunday'),
220
244
  day: z.number().int().min(1).max(28).optional().describe('every=month: day of the month 1..28'),
@@ -314,7 +338,21 @@ export function buildMcpServer(client, o = {}) {
314
338
  }, async (a) => wrap(async () => {
315
339
  const self = await me();
316
340
  const runId = `int_${randomBytes(9).toString('base64url')}`;
317
- const b = await client.claim(a.task_id, runId, 'interactive');
341
+ let b;
342
+ try {
343
+ b = await client.claim(a.task_id, runId, 'interactive');
344
+ }
345
+ catch (e) {
346
+ // a refused claim says why, so the model does not guess: taken already (often by this agent's own runner), or not yet
347
+ if (e instanceof HubError && e.status === 409) {
348
+ const t = await client.getTask(a.task_id).then((x) => x.task).catch(() => null);
349
+ if (t && t.status === 'working' && t.to_agent === self.id)
350
+ throw new Error(`${refOf(t)} is already being worked by your own runner (claim mode ${t.claim_mode || 'runner'}). Follow it with get_task instead of claiming it.`);
351
+ if (t && t.status !== 'submitted')
352
+ throw new Error(`${refOf(t)} cannot be claimed: it is ${t.status}. Only a submitted task can be claimed.`);
353
+ }
354
+ throw e;
355
+ }
318
356
  const links = (b.task.links ?? {});
319
357
  const text = interactiveInstructions({
320
358
  taskId: refOf(b.task),
@@ -377,7 +415,7 @@ export function buildMcpServer(client, o = {}) {
377
415
  server.registerTool('post', {
378
416
  description: `Post to a channel: findings, cost data, screenshots, questions to the group. @agent-name in the text reaches that agent and its owner's Inbox (the person sees it there even if the agent is offline) and wakes the agent for a short read-only reply. To address someone, @ their agent: a name written without @ reaches no one. For handing off work use send_task instead. Set announce: true only for news everyone should hear about (shipped, released, data published): every channel reader is notified. ${LINKS_HELP}`,
379
417
  inputSchema: { channel: z.string(), text: z.string(), attachments: ATTACH, announce: z.boolean().optional().describe('An announcement (shipped / released / data published): notifies every reader of the channel') },
380
- }, async (a) => wrap(async () => client.post(a.channel, a.text, att(a.attachments), { announce: !!a.announce })));
418
+ }, async (a) => wrap(async () => withMentionWarnings(await client.post(a.channel, a.text, att(a.attachments), { announce: !!a.announce }), a.text)));
381
419
  server.registerTool('reply', {
382
420
  description: `Reply in a post's thread (a reply to a reply goes to the same thread). Add evidence (files, commands, outputs) when you answer a question. ${LINKS_HELP}`,
383
421
  inputSchema: {
@@ -390,7 +428,7 @@ export function buildMcpServer(client, o = {}) {
390
428
  .describe('Answer FOR MY OWNER (the person), who is here in this session and told you what to say, to a question escalated to them (see owner_inbox). The reply is theirs, marked "via <your name>", and clears the card. It records no Memory decision and approves no schedule: those need their own click. Never use it without their say-so.'),
391
429
  attachments: ATTACH,
392
430
  },
393
- }, async (a) => wrap(async () => client.reply(a.post_id, a.text, { evidence: a.evidence, ...(a.as_owner ? { asOwner: true } : {}) }, att(a.attachments))));
431
+ }, async (a) => wrap(async () => withMentionWarnings(await client.reply(a.post_id, a.text, { evidence: a.evidence, ...(a.as_owner ? { asOwner: true } : {}) }, att(a.attachments)), a.text)));
394
432
  server.registerTool('search', {
395
433
  description: 'Search everything you can see: posts and replies, tasks (title, purpose, key question, money), handoff versions, messages and attachment names. Chinese works (1-2 character queries too). Results carry links.',
396
434
  inputSchema: {
@@ -18,6 +18,9 @@ const PATTERNS = [
18
18
  [/\bAKIA[0-9A-Z]{16}\b/g, REDACTED],
19
19
  [/\bAIza[0-9A-Za-z_-]{30,}/g, REDACTED],
20
20
  [/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, REDACTED],
21
+ // npm and git credential files: //registry/:_authToken=..., _auth=..., :_password=..., and npm's own token format
22
+ [/(_authToken|_auth|_password)(\s*=\s*)[^\s'"]+/gi, (_m, k, eq) => `${k}${eq}${REDACTED}`],
23
+ [/\bnpm_[A-Za-z0-9]{30,}\b/g, REDACTED],
21
24
  // credentials inside a URL: scheme://user:password@host
22
25
  [/\b([a-z][a-z0-9+.-]*:\/\/[^\s:/@]+):[^\s@/]+@/gi, `$1:${REDACTED}@`],
23
26
  // NAME=value and "name": "value" where the name says it is a secret
@@ -0,0 +1,4 @@
1
+ export declare class RunnerLockedError extends Error {
2
+ }
3
+ /** Takes the lock for `home`, or throws RunnerLockedError naming the process that has it. Returns the function that releases it. */
4
+ export declare function acquireRunnerLock(home: string, pid?: number): () => void;
@@ -0,0 +1,69 @@
1
+ // One runner per home. Two `ach run` processes on the same AGENTCHANNEL_HOME would both take tasks and overwrite each other's
2
+ // runs.json and sessions.json, so a task could run twice or be forgotten. The lock is a file holding the pid of the one that runs.
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync } from 'node:fs';
4
+ import { hostname } from 'node:os';
5
+ import { join } from 'node:path';
6
+ export class RunnerLockedError extends Error {
7
+ }
8
+ const alive = (pid) => {
9
+ try {
10
+ process.kill(pid, 0);
11
+ return true;
12
+ }
13
+ catch (e) {
14
+ return e?.code === 'EPERM'; // it exists, it is just not ours to signal
15
+ }
16
+ };
17
+ /** Is `pid` (on this machine) plausibly an ach/node process, not another program that was given the number later? Only Linux can tell. */
18
+ function looksLikeRunner(pid) {
19
+ try {
20
+ if (!existsSync(`/proc/${pid}/cmdline`))
21
+ return true;
22
+ return /node|ach|agentchannel/i.test(readFileSync(`/proc/${pid}/cmdline`, 'utf8'));
23
+ }
24
+ catch {
25
+ return true;
26
+ }
27
+ }
28
+ /** The lock file says `<pid>@<host>`. A lock from another host (a replaced container shares the volume, not the process table) is stale. */
29
+ function holder(text) {
30
+ const [pid, host = ''] = text.trim().split('@');
31
+ return { pid: Number(pid), host };
32
+ }
33
+ /** Takes the lock for `home`, or throws RunnerLockedError naming the process that has it. Returns the function that releases it. */
34
+ export function acquireRunnerLock(home, pid = process.pid) {
35
+ mkdirSync(home, { recursive: true, mode: 0o700 });
36
+ const file = join(home, 'runner.lock');
37
+ for (let attempt = 0; attempt < 3; attempt++) {
38
+ try {
39
+ const fd = openSync(file, 'wx', 0o600);
40
+ writeSync(fd, `${pid}@${hostname()}`);
41
+ closeSync(fd);
42
+ return () => {
43
+ try {
44
+ if (holder(readFileSync(file, 'utf8')).pid === pid)
45
+ unlinkSync(file);
46
+ }
47
+ catch { /* already gone */ }
48
+ };
49
+ }
50
+ catch (e) {
51
+ if (e?.code !== 'EEXIST')
52
+ throw e;
53
+ let text = readFileSync(file, 'utf8');
54
+ // a lock just created by another process may not have its pid written yet: give it a moment before calling it stale
55
+ if (!text.trim()) {
56
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 150);
57
+ text = readFileSync(file, 'utf8');
58
+ }
59
+ const { pid: other, host } = holder(text);
60
+ if (other && other !== pid && (!host || host === hostname()) && alive(other) && looksLikeRunner(other))
61
+ throw new RunnerLockedError(`another runner (pid ${other}) is already running with this home (${home}): stop it first, or give this one its own AGENTCHANNEL_HOME`);
62
+ try {
63
+ unlinkSync(file);
64
+ }
65
+ catch { /* someone else removed it first: try again */ }
66
+ }
67
+ }
68
+ throw new RunnerLockedError(`could not take the runner lock in ${home}`);
69
+ }
@@ -19,6 +19,10 @@ export interface RunnerOptions {
19
19
  /** The hub answered 426 client_too_old: this release is below its floor (the updater checks at once). */
20
20
  onClientTooOld?: () => void;
21
21
  heartbeatMs?: number;
22
+ /** Keep execution traces on this machine (`ach run --no-trace`, ACH_NO_TRACE=1): the task's readers see results, not commands and output. */
23
+ noTrace?: boolean;
24
+ /** How often a parked run is looked at on the hub (default 12 s; tests that drive the runner by hand use 0). */
25
+ parkedCheckMs?: number;
22
26
  idleMs?: number;
23
27
  cfId?: string;
24
28
  cfSecret?: string;
@@ -140,6 +144,16 @@ export declare class Runner {
140
144
  readonly queue: Job[];
141
145
  readonly active: Map<string, Active>;
142
146
  me?: Agent;
147
+ /** When `me` was last read from the hub (ms). */
148
+ private meAt;
149
+ /** When old work dirs were last cleaned up (ms); the first prune of a process does it. */
150
+ private lastGc;
151
+ /** No new task is taken before this time (ms): the account behind the runtime is out of budget. */
152
+ private quotaUntil;
153
+ /** How often each task was handed back for an account limit (in this process). */
154
+ private quotaReleases;
155
+ /** When each parked task was last looked at on the hub (ms). */
156
+ private parkedChecked;
143
157
  private o;
144
158
  private stopped;
145
159
  /** quiesce(): the runner takes nothing new (a CLI update is waiting for the runs in flight). */
@@ -198,6 +212,10 @@ export declare class Runner {
198
212
  /** Resolves when nothing is queued or running (tests). */
199
213
  drain(): Promise<void>;
200
214
  private runJob;
215
+ /**
216
+ * The agent's own record (permission, network allowlist, budget), read again when it is older than ME_TTL_MS: an admin who
217
+ * lowers the permission or narrows net_allow (say, after a suspected injection) is obeyed by the next run, not the next restart.
218
+ */
201
219
  private ensureMe;
202
220
  private runWork;
203
221
  private runResume;
@@ -251,6 +269,7 @@ export declare function gcWorktrees(client: Pick<Client, 'getTask'>, ws: Workspa
251
269
  days?: number;
252
270
  now?: number;
253
271
  log?: (s: string) => void;
272
+ keepFailed?: boolean;
254
273
  }): Promise<string[]>;
255
274
  /**
256
275
  * The JSON object a structured run ended with. Codex returns it bare (outputSchema); a remote run's final message may
@@ -10,7 +10,7 @@ import { buildAgentEnv } from '../env.js';
10
10
  import { effectivePerm } from '../perm.js';
11
11
  import { ANSWER_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
12
12
  import { RunnerState } from './state.js';
13
- import { looksLikeLoginError, summarizeRuntimeError } from '../envcheck.js';
13
+ import { looksLikeLoginError, quotaProblem, summarizeRuntimeError } from '../envcheck.js';
14
14
  import { redact } from '../redact.js';
15
15
  import { TraceRecorder } from '../trace.js';
16
16
  import { looksLikeSandboxError } from '../sandboxcheck.js';
@@ -190,6 +190,12 @@ export function prepareAgentHome(root, agentName, key, realHome, realCodexHome)
190
190
  env.CODEX_HOME = prepareCodexHome(home, realCodexHome || join(realHome, '.codex'));
191
191
  return { home, env };
192
192
  }
193
+ /** How long the runner trusts its copy of the agent's record before reading it again. */
194
+ const ME_TTL_MS = 60_000;
195
+ /** How often a parked run (waiting for an answer) is looked at: an answer reaches it this much later at most. */
196
+ const PARKED_CHECK_MS = 12_000;
197
+ /** A task handed back this many times for an account limit then fails normally. */
198
+ const QUOTA_RELEASES = 3;
193
199
  export function budgetBlocked(me) {
194
200
  const budget = Number(me.budget_usd ?? 0);
195
201
  return budget > 0 && Number(me.spent_usd ?? 0) >= budget;
@@ -199,6 +205,16 @@ export class Runner {
199
205
  queue = [];
200
206
  active = new Map();
201
207
  me;
208
+ /** When `me` was last read from the hub (ms). */
209
+ meAt = 0;
210
+ /** When old work dirs were last cleaned up (ms); the first prune of a process does it. */
211
+ lastGc = 0;
212
+ /** No new task is taken before this time (ms): the account behind the runtime is out of budget. */
213
+ quotaUntil = 0;
214
+ /** How often each task was handed back for an account limit (in this process). */
215
+ quotaReleases = new Map();
216
+ /** When each parked task was last looked at on the hub (ms). */
217
+ parkedChecked = new Map();
202
218
  o;
203
219
  stopped = false;
204
220
  /** quiesce(): the runner takes nothing new (a CLI update is waiting for the runs in flight). */
@@ -300,9 +316,11 @@ export class Runner {
300
316
  return; // heartbeats of parked runs went out in checkActive; nothing new is taken (it waits in the hub's inbox)
301
317
  if (await this.sandboxBlocked())
302
318
  return; // design §27: same, until the sandbox works
303
- if (!this.me || inbox.tasks_to_me.length)
319
+ if (!this.me || inbox.tasks_to_me.length) {
304
320
  this.me = await this.o.client.me();
305
- const me = this.me;
321
+ this.meAt = Date.now();
322
+ }
323
+ const me = await this.ensureMe();
306
324
  // New tasks.
307
325
  const blocked = budgetBlocked(me);
308
326
  const now = Date.now();
@@ -316,6 +334,8 @@ export class Runner {
316
334
  await this.notifyBudget(t, me);
317
335
  continue;
318
336
  }
337
+ if (now < this.quotaUntil)
338
+ continue; // out of usage at the provider: the pause is over soon enough
319
339
  this.enqueue({ kind: 'work', taskId: t.id });
320
340
  }
321
341
  // Replies for parked runs.
@@ -439,6 +459,10 @@ export class Runner {
439
459
  for (const rec of Object.values(this.state.runs.runs)) {
440
460
  if (rec.phase !== 'parked' || this.isQueuedOrActive(`task:${rec.taskId}`))
441
461
  continue;
462
+ // a parked run waits for a person: asking the hub about it every few seconds costs a request each time for nothing
463
+ if (now - (this.parkedChecked.get(rec.taskId) ?? 0) < (this.o.parkedCheckMs ?? PARKED_CHECK_MS))
464
+ continue;
465
+ this.parkedChecked.set(rec.taskId, now);
442
466
  try {
443
467
  const bundle = await this.o.client.getTask(rec.taskId);
444
468
  const task = bundle.task;
@@ -522,8 +546,21 @@ export class Runner {
522
546
  delete this.state.runs.handledQuestions[q];
523
547
  }
524
548
  this.state.pruneTasks(dead);
525
- for (const id of dead)
549
+ for (const id of dead) {
526
550
  rmSync(this.filesDir(id), { recursive: true, force: true });
551
+ // the task's scratch HOME (caches, a Codex session) is not needed once the task has ended
552
+ if (this.me?.name)
553
+ rmSync(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)), { recursive: true, force: true });
554
+ }
555
+ // 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)
556
+ if (now - this.lastGc >= 24 * 3600_000) {
557
+ this.lastGc = now;
558
+ // in the background (it asks the hub about every work dir), and never a failed task's dir: it may hold work worth looking at
559
+ void gcWorktrees(this.o.client, this.o.workspace, { days: 7, log: (s) => this.log(s), keepFailed: true })
560
+ .then((removed) => { if (removed.length)
561
+ this.log(`removed ${removed.length} old work dir(s)`); })
562
+ .catch((e) => this.log(`gc: ${e?.message ?? e}`));
563
+ }
527
564
  }
528
565
  pump() {
529
566
  while (!this.stopped && this.active.size < this.o.max && this.queue.length) {
@@ -563,6 +600,9 @@ export class Runner {
563
600
  await new Promise((r) => this.waiters.push(r));
564
601
  }
565
602
  async runJob(job, entry) {
603
+ // queued before the account ran out: it stays on the hub (submitted) and is taken again after the pause
604
+ if (job.kind === 'work' && Date.now() < this.quotaUntil)
605
+ return;
566
606
  if (job.kind === 'work')
567
607
  return this.runWork(job.taskId, entry);
568
608
  if (job.kind === 'resume')
@@ -571,9 +611,22 @@ export class Runner {
571
611
  return this.runMention(job.item, entry);
572
612
  return this.runAnswer(job.question, entry);
573
613
  }
614
+ /**
615
+ * The agent's own record (permission, network allowlist, budget), read again when it is older than ME_TTL_MS: an admin who
616
+ * lowers the permission or narrows net_allow (say, after a suspected injection) is obeyed by the next run, not the next restart.
617
+ */
574
618
  async ensureMe() {
575
- if (!this.me)
576
- this.me = await this.o.client.me();
619
+ if (!this.me || Date.now() - this.meAt > ME_TTL_MS) {
620
+ try {
621
+ this.me = await this.o.client.me();
622
+ this.meAt = Date.now();
623
+ this.meAt = Date.now();
624
+ }
625
+ catch (e) {
626
+ if (!this.me)
627
+ throw e; // the hub does not answer: the last record is better than none
628
+ }
629
+ }
577
630
  return this.me;
578
631
  }
579
632
  async runWork(taskId, entry) {
@@ -605,6 +658,9 @@ export class Runner {
605
658
  let workdir;
606
659
  let sensitive = [];
607
660
  let readRepos = [];
661
+ // preparing can take minutes (a fetch of a big repo, a new worktree): keep the claim alive meanwhile, or the lease expires
662
+ // and the hub hands the task to another run while this one is still getting ready
663
+ const prepHb = setInterval(() => void this.o.client.heartbeat(taskId, runId).catch((e) => this.log(`heartbeat ${taskId}: ${e?.message ?? e}`)), this.o.heartbeatMs);
608
664
  try {
609
665
  // Other repos first: an unknown repo name fails the task before any worktree exists.
610
666
  readRepos = (await this.o.workspace.readRepos?.(claim.task)) ?? [];
@@ -618,6 +674,9 @@ export class Runner {
618
674
  this.state.drop(taskId);
619
675
  return;
620
676
  }
677
+ finally {
678
+ clearInterval(prepHb);
679
+ }
621
680
  const rec = {
622
681
  taskId,
623
682
  runId,
@@ -852,6 +911,24 @@ export class Runner {
852
911
  }
853
912
  if (!result.ok) {
854
913
  const err = result.error ?? 'unknown';
914
+ // The account has no budget left (a usage or rate limit): the task goes back to the queue untouched and this runner takes
915
+ // nothing new until the pause is over, instead of failing every queued task one by one for the same reason.
916
+ const quota = quotaProblem(err);
917
+ // released for this at most QUOTA_RELEASES times: a task whose own failure text mentions a rate limit (a third-party 429) must
918
+ // still be able to fail
919
+ const quotaTimes = (this.quotaReleases.get(taskId) ?? 0) + 1;
920
+ if (quota && client.release && quotaTimes <= QUOTA_RELEASES) {
921
+ this.quotaReleases.set(taskId, quotaTimes);
922
+ this.quotaUntil = Math.max(this.quotaUntil, Date.now() + quota.pauseMs);
923
+ const why = `the account behind ${this.o.adapter.name} hit a usage or rate limit (${summarizeRuntimeError(err).slice(0, 160)}); this runner takes no new task until ${new Date(this.quotaUntil).toISOString().slice(11, 16)} UTC`;
924
+ const done = await client.release(taskId, why, rec.runId).then(() => true, (e) => { this.log(`release ${taskId}: ${e?.message ?? e}`); return false; });
925
+ if (done) {
926
+ this.log(why);
927
+ this.taskLog(taskId, `released: ${why}`);
928
+ this.state.drop(taskId);
929
+ return;
930
+ }
931
+ }
855
932
  // The machine, not the task: when the run died of a login or sandbox problem and the check now confirms it, the task goes
856
933
  // back to the queue (the runner takes nothing more until the check passes, and the owner has been told) instead of failing.
857
934
  if (this.o.sandboxCheck && (looksLikeSandboxError(err) || looksLikeLoginError(err))) {
@@ -1148,7 +1225,9 @@ export class Runner {
1148
1225
  const inflight = new Set();
1149
1226
  // the execution trace of this run: what it thought, ran and printed, masked before it leaves this machine
1150
1227
  const startedAt = new Date();
1151
- const recorder = new TraceRecorder([rec.runToken, ...(this.o.secrets ?? []), this.o.cfSecret ?? ''].filter(Boolean));
1228
+ // the values of the variables handed through (--pass-env) are secrets too: masked wherever a tool prints them
1229
+ const passed = (this.o.passEnv ?? []).map((n) => process.env[n] ?? '').filter((v) => v.length >= 8);
1230
+ const recorder = new TraceRecorder([rec.runToken, ...(this.o.secrets ?? []), this.o.cfSecret ?? '', ...passed].filter(Boolean));
1152
1231
  let hb;
1153
1232
  hb =
1154
1233
  mode === 'work'
@@ -1197,6 +1276,8 @@ export class Runner {
1197
1276
  achHome: this.o.home,
1198
1277
  readRoots: this.readRoots(rec.workdir, rec.readRepos, rec.taskId),
1199
1278
  ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
1279
+ // the agent's budget is a cap on the run too, not only a gate on taking the next task (a run that loops stops at what is left)
1280
+ ...(Number(me.budget_usd ?? 0) > 0 ? { maxBudgetUsd: Math.max(0.01, Number(me.budget_usd) - Number(me.spent_usd ?? 0)) + ((mode === 'mention' ? undefined : this.state.session(taskId, mode))?.costTotal ?? 0) } : {}),
1200
1281
  ...(outputSchema ? { outputSchema } : {}),
1201
1282
  onEvent: (e) => {
1202
1283
  lastEvent = Date.now();
@@ -1222,12 +1303,18 @@ export class Runner {
1222
1303
  clearInterval(hb);
1223
1304
  clearInterval(idle);
1224
1305
  }
1225
- if (result.sessionId && mode !== 'mention')
1226
- this.state.setSession(taskId, mode, { id: result.sessionId, cwd: rec.workdir });
1306
+ // Claude reports the running total of the whole session; the hub adds up what each run reports, so report only this run's part
1307
+ let runCost = Number(result.costUsd ?? 0);
1308
+ if (result.sessionId && mode !== 'mention') {
1309
+ const before = this.state.session(taskId, mode)?.costTotal;
1310
+ if (result.costCumulative && before !== undefined && runCost >= before)
1311
+ runCost -= before;
1312
+ this.state.setSession(taskId, mode, { id: result.sessionId, cwd: rec.workdir, ...(result.costCumulative && result.costUsd !== undefined ? { costTotal: Number(result.costUsd) } : {}) });
1313
+ }
1227
1314
  // §14.7: usage after every adapter run, success or failure.
1228
1315
  const usage = extra.usage ?? ((cost, est) => client.usage(taskId, rec.runId, cost, est));
1229
1316
  if (!this.fatal)
1230
- await usage(Number(result.costUsd ?? 0), !!result.estimated).catch((e) => this.log(`usage ${taskId}: ${e?.message ?? e}`));
1317
+ await usage(runCost, !!result.estimated).catch((e) => this.log(`usage ${taskId}: ${e?.message ?? e}`));
1231
1318
  this.taskLog(taskId, `${mode} run end ok=${result.ok} cost=${result.costUsd ?? 0} err=${result.error ?? ''}`);
1232
1319
  if (mode !== 'mention')
1233
1320
  await this.uploadTrace(taskId, rec.runId, mode, startedAt, result, recorder, !this.fatal);
@@ -1254,7 +1341,7 @@ export class Runner {
1254
1341
  }
1255
1342
  /** Build and send the trace of the run that just ended. Never throws; a failed upload is kept and retried. */
1256
1343
  async uploadTrace(taskId, runId, mode, startedAt, result, recorder, send) {
1257
- if (!this.o.client.putTrace)
1344
+ if (!this.o.client.putTrace || this.o.noTrace)
1258
1345
  return;
1259
1346
  try {
1260
1347
  const { steps, omitted } = recorder.finish();
@@ -1385,6 +1472,8 @@ export async function gcWorktrees(client, ws, o = {}) {
1385
1472
  const { task } = await client.getTask(id);
1386
1473
  if (!isTerminal(task.status))
1387
1474
  continue;
1475
+ if (o.keepFailed && task.status === 'failed')
1476
+ continue;
1388
1477
  const when = Date.parse(String(task.updated ?? '').replace(' ', 'T')) || ws.mtime(id);
1389
1478
  if (when > cutoff)
1390
1479
  continue;