@koalaauto/agentchannel 3.45.1 → 3.45.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +9 -6
  2. package/dist/src/adapters/claude.d.ts +1 -1
  3. package/dist/src/adapters/claude.js +1 -1
  4. package/dist/src/adapters/codex.d.ts +1 -1
  5. package/dist/src/adapters/codex.js +5 -1
  6. package/dist/src/adapters/types.d.ts +1 -1
  7. package/dist/src/args.d.ts +1 -1
  8. package/dist/src/args.js +9 -62
  9. package/dist/src/caps.d.ts +1 -1
  10. package/dist/src/caps.js +1 -1
  11. package/dist/src/cli-admin.d.ts +3 -0
  12. package/dist/src/cli-admin.js +307 -0
  13. package/dist/src/cli-memory.d.ts +3 -0
  14. package/dist/src/cli-memory.js +138 -0
  15. package/dist/src/cli-run.d.ts +28 -0
  16. package/dist/src/cli-run.js +429 -0
  17. package/dist/src/cli-shared.d.ts +73 -0
  18. package/dist/src/cli-shared.js +159 -0
  19. package/dist/src/cli.d.ts +9 -38
  20. package/dist/src/cli.js +23 -1184
  21. package/dist/src/client.d.ts +1 -23
  22. package/dist/src/client.js +1 -30
  23. package/dist/src/codexdaemon.d.ts +22 -0
  24. package/dist/src/codexdaemon.js +68 -0
  25. package/dist/src/desknotify.js +11 -7
  26. package/dist/src/doctor.js +1 -1
  27. package/dist/src/envcheck.js +1 -1
  28. package/dist/src/invite_people.d.ts +31 -0
  29. package/dist/src/invite_people.js +238 -0
  30. package/dist/src/invite_person.d.ts +1 -1
  31. package/dist/src/invite_person.js +1 -1
  32. package/dist/src/mcp.d.ts +1 -1
  33. package/dist/src/mcp.js +7 -47
  34. package/dist/src/onboard.d.ts +3 -6
  35. package/dist/src/onboard.js +6 -14
  36. package/dist/src/prompts.d.ts +2 -2
  37. package/dist/src/prompts.js +6 -17
  38. package/dist/src/runner/home.d.ts +45 -0
  39. package/dist/src/runner/home.js +150 -0
  40. package/dist/src/runner/runner.d.ts +9 -82
  41. package/dist/src/runner/runner.js +31 -333
  42. package/dist/src/runner/structured.d.ts +20 -0
  43. package/dist/src/runner/structured.js +64 -0
  44. package/dist/src/runner/traces.d.ts +29 -0
  45. package/dist/src/runner/traces.js +119 -0
  46. package/dist/src/sandboxcheck.d.ts +4 -1
  47. package/dist/src/sandboxcheck.js +16 -1
  48. package/dist/src/service.d.ts +1 -1
  49. package/dist/src/version.d.ts +1 -1
  50. package/dist/src/version.js +1 -1
  51. package/package.json +1 -1
  52. package/dist/src/import.d.ts +0 -244
  53. package/dist/src/import.js +0 -998
package/dist/src/mcp.js CHANGED
@@ -69,17 +69,12 @@ export const MCP_TOOLS = [
69
69
  'download_files',
70
70
  'list_channels',
71
71
  'read_channel',
72
- 'schedule_task',
73
- 'list_schedules',
74
72
  'post',
75
73
  'reply',
76
74
  'search',
77
75
  'remember',
78
76
  'decide_draft',
79
77
  'decide',
80
- 'grant_authorization',
81
- 'list_grants',
82
- 'revoke_grant',
83
78
  'memory_search',
84
79
  'memory_read',
85
80
  'memory_write',
@@ -156,11 +151,11 @@ export const CLAUDE_CHANNEL_CAPABILITY = 'claude/channel';
156
151
  export const CLAUDE_CHANNEL_METHOD = 'notifications/claude/channel';
157
152
  /**
158
153
  * What a client may assume about a tool without asking: it only reads, or it speaks for the owner and cannot be taken back
159
- * (deciding, granting, revoking, cancelling). A client that auto-allows read-only tools and asks before the rest is then
154
+ * (deciding, cancelling). A client that auto-allows read-only tools and asks before the rest is then
160
155
  * right about which is which.
161
156
  */
162
- 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']);
163
- const OWNER_LEVEL_TOOLS = new Set(['decide', 'grant_authorization', 'revoke_grant', 'cancel_task']);
157
+ const READ_ONLY_TOOLS = new Set(['list_agents', 'get_task', 'inbox', 'owner_inbox', 'list_channels', 'read_channel', 'search', 'memory_search', 'memory_read', 'wiki_search', 'wiki_read']);
158
+ const OWNER_LEVEL_TOOLS = new Set(['decide', 'cancel_task']);
164
159
  export const toolHints = (name) => (READ_ONLY_TOOLS.has(name) ? { readOnlyHint: true } : OWNER_LEVEL_TOOLS.has(name) ? { readOnlyHint: false, destructiveHint: true } : { readOnlyHint: false, destructiveHint: false });
165
160
  export function buildMcpServer(client, o = {}) {
166
161
  const server = new McpServer({ name: 'ach', version: VERSION }, { instructions: mcpInstructions(o.brief, o.identity), capabilities: { experimental: { [CLAUDE_CHANNEL_CAPABILITY]: {} } } });
@@ -238,32 +233,6 @@ export function buildMcpServer(client, o = {}) {
238
233
  }
239
234
  : {}),
240
235
  }, att(a.attachments))));
241
- server.registerTool('schedule_task', {
242
- description: 'Propose a recurring task (a daily report, a weekly check, a monthly bill pull) or an automatic rule (when X happens, send this task): ' +
243
- 'give every+at for a time rule, or on+match for an event: task_completed/task_failed {from?, to?, channel?, title?} (tasks your agent sent or received; chain steps), ' +
244
- 'figure {topic, metric, op: > >= < <=, value} (a Memory figure crossing a threshold: alerts), post {channel, contains?, author?} (e.g. CI posting "failed" through an inbound hook). ' +
245
- 'Event rules fill {ref} {title} {link} {metric} {value} {unit} {as_of} {text} in the title and handoff; a task a rule created never fires that rule again. ' +
246
- 'It does not run until your owner replies "approve" to the question it creates; tell them so. Each run is an ordinary task; ' +
247
- '{date} in the title or handoff becomes that run\'s date; a run is skipped while the previous run\'s task is still open. ' +
248
- `${HANDOFF_HELP}`,
249
- inputSchema: {
250
- to: z.string().describe('Agent name or id that does the work each time (see list_agents)'),
251
- title: z.string(),
252
- money: z.string().describe('Cost per run and budget impact, or "n/a"'),
253
- handoff: z.string().describe('Markdown handoff for every run; {date} is replaced by the run date'),
254
- every: z.enum(['day', 'weekday', 'week', 'month']).optional().describe('Time rule (omit for an event rule)'),
255
- at: z.string().optional().describe('Local time HH:MM (24 h), with every'),
256
- 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)'),
257
- match: z.record(z.string(), z.unknown()).optional().describe('Event filter, see above'),
258
- weekday: z.number().int().min(1).max(7).optional().describe('every=week: 1 = Monday .. 7 = Sunday'),
259
- day: z.number().int().min(1).max(28).optional().describe('every=month: day of the month 1..28'),
260
- tz: z.string().optional().describe('UTC offset like +08:00 (default: the hub\'s)'),
261
- purpose: z.string().optional(),
262
- priority: z.enum(['P0', 'P1', 'P2', 'P3']).default('P2'),
263
- channel: z.string().optional().describe('Channel for the runs (default #general)'),
264
- },
265
- }, async (a) => wrap(() => client.proposeSchedule({ ...a, ...(a.channel ? { channel: a.channel.replace(/^#/, '') } : {}) })));
266
- server.registerTool('list_schedules', { description: 'Recurring tasks your agent sends or receives: status (proposed, active, paused), when, next run, runs and skipped runs.', inputSchema: {} }, async () => wrap(() => client.schedules()));
267
236
  server.registerTool('update_handoff', {
268
237
  description: `Update a task you sent instead of appending comments: replace the handoff (send the complete new handoff, not a diff) and/or change the header fields priority, purpose, money, key_question. ` +
269
238
  `Each update is a new handoff version with your change note; the worker sees it. ${HANDOFF_HELP}`,
@@ -333,18 +302,9 @@ export function buildMcpServer(client, o = {}) {
333
302
  .catch(async (e) => { throw to.to_user ? await explainToUser(e, to.to_user, client, a.task_id) : e; });
334
303
  }));
335
304
  server.registerTool('decide', {
336
- description: 'Reply to a decision request addressed to your owner, as your owner (your owner is present in this session; recorded "via <agent>"). Never for anyone else. Or, as a grantee agent, answer an option an authorization grant covers (grant + option).',
337
- inputSchema: { task_id: z.string(), message_id: z.string(), reply: z.string().optional(), grant: z.string().optional(), option: z.number().int().min(0).optional() },
338
- }, async (a) => wrap(() => (a.grant ? client.grantDecide(a.task_id, a.message_id, a.option ?? -1, a.grant) : client.decide(a.task_id, a.message_id, String(a.reply ?? '')))));
339
- server.registerTool('grant_authorization', {
340
- description: 'Your owner (present in this session) authorizes an agent or a person to decide for them within a scope (a task or channel), up to a cumulative money cap, until a date. Never covers deleting data, deploying to production, external communication or anything irreversible.',
341
- inputSchema: {
342
- agent: z.string().optional(), person: z.string().optional(), task: z.string().optional(), channel: z.string().optional(),
343
- cap: z.number().min(0), until: z.string().optional().describe('YYYY-MM-DD'), note: z.string().optional(), requester: z.string().optional().describe('only questions from this agent or person'),
344
- },
345
- }, async (a) => wrap(() => client.createGrant(a)));
346
- server.registerTool('list_grants', { description: 'Authorization grants your owner gave, and grants given to you.', inputSchema: {} }, async () => wrap(() => client.listGrants()));
347
- server.registerTool('revoke_grant', { description: 'Revoke an authorization grant your owner gave.', inputSchema: { grant_id: z.string() } }, async (a) => wrap(() => client.revokeGrant(a.grant_id)));
305
+ description: 'Reply to a decision request addressed to your owner, as your owner (your owner is present in this session; recorded "via <agent>"). Never for anyone else.',
306
+ inputSchema: { task_id: z.string(), message_id: z.string(), reply: z.string() },
307
+ }, async (a) => wrap(() => client.decide(a.task_id, a.message_id, a.reply)));
348
308
  server.registerTool('cancel_task', { description: 'Cancel a task you sent. The receiving run is stopped.', inputSchema: { task_id: z.string(), reason: z.string() } }, async (a) => wrap(() => client.cancel(a.task_id, a.reason)));
349
309
  // ---- P1: work a task sent to me in this interactive session ----
350
310
  server.registerTool('claim_task', {
@@ -450,7 +410,7 @@ export function buildMcpServer(client, o = {}) {
450
410
  as_owner: z
451
411
  .boolean()
452
412
  .optional()
453
- .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.'),
413
+ .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: that needs their own click. Never use it without their say-so.'),
454
414
  attachments: ATTACH,
455
415
  },
456
416
  }, 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)));
@@ -5,11 +5,11 @@ import { type SandboxStatus, type SandboxTool } from './sandboxcheck.js';
5
5
  *
6
6
  * 1. connect: add the `ach` MCP server to the agent's own tool (Claude Code
7
7
  * for a claude agent, Codex for a codex one; both found ones for "other")
8
- * 2. sandbox (design §27): when the probe of the agent tool's sandbox fails, the
8
+ * 2. sandbox (decisions §27): when the probe of the agent tool's sandbox fails, the
9
9
  * commands that fix it (sudo included), run only after Enter in a terminal;
10
10
  * with no terminal they are printed and nothing runs
11
- * 3. background helper, only with --service: `ach run --install-service`
12
- * (+ --notify on a machine with a desktop), which installs and starts it.
11
+ * 3. background helper, only with --service: `ach run --install-service`,
12
+ * which installs and starts it (no desktop notifications: the browser's are the main ones).
13
13
  * Run through npx, the helper runs the same pinned npx spec as the MCP
14
14
  * entry, never a path in the npx cache.
15
15
  *
@@ -61,8 +61,6 @@ export interface Step {
61
61
  }
62
62
  /** The closing line: which tool to open and what to say to it. */
63
63
  export declare function doneLine(tools: ('claude' | 'codex')[], zh: boolean): string;
64
- /** A desktop to show notifications on: macOS, Windows, or Linux with a display. */
65
- export declare function hasDesktop(env: NodeJS.ProcessEnv, platform?: string): boolean;
66
64
  /** The tools an agent of this runtime is added to: its own; both for "other" or unknown. */
67
65
  export declare function toolsFor(runtime: string | undefined): ('claude' | 'codex')[];
68
66
  /** True when this CLI runs from the npx cache (it disappears; install it first). */
@@ -106,7 +104,6 @@ export declare function planSteps(d: Detected, o: {
106
104
  env?: NodeJS.ProcessEnv;
107
105
  runtime?: string;
108
106
  service?: boolean;
109
- desktop?: boolean;
110
107
  sandbox?: SandboxStatus[];
111
108
  }): Step[];
112
109
  export interface SetupResult {
@@ -8,12 +8,6 @@ export function doneLine(tools, zh) {
8
8
  const where = names.length ? names.join(zh ? ' 或 ' : ' or ') : zh ? '你的 Claude Code 或 Codex' : 'your Claude Code or Codex';
9
9
  return zh ? `完成。打开 ${where},对它说:看看我的 AgentChannel 收件箱` : `Done. Open ${where} and say: check my AgentChannel inbox`;
10
10
  }
11
- /** A desktop to show notifications on: macOS, Windows, or Linux with a display. */
12
- export function hasDesktop(env, platform = process.platform) {
13
- if (platform === 'darwin' || platform === 'win32')
14
- return true;
15
- return !!(env.DISPLAY || env.WAYLAND_DISPLAY);
16
- }
17
11
  /** The tools an agent of this runtime is added to: its own; both for "other" or unknown. */
18
12
  export function toolsFor(runtime) {
19
13
  return runtime === 'claude' ? ['claude'] : runtime === 'codex' ? ['codex'] : ['claude', 'codex'];
@@ -125,14 +119,13 @@ export function planSteps(d, o) {
125
119
  }
126
120
  // 3. background helper: only when asked for (--service)
127
121
  if (o.service) {
128
- const notify = o.desktop !== false;
129
- const helper = ['run', '--install-service', ...(notify ? ['--notify'] : []), '--interactive-first', '--dir', o.cwd];
122
+ const helper = ['run', '--install-service', '--interactive-first', '--dir', o.cwd];
130
123
  steps.push({
131
124
  id: 'service',
132
125
  question: [
133
126
  zh
134
- ? `安装后台小助手(在 ${o.cwd} 里自动领取任务${notify ? ',并弹出系统通知' : ''})?会运行:`
135
- : `Install the background helper (picks up tasks in ${o.cwd}${notify ? ' and shows desktop notifications' : ''})? This runs:`,
127
+ ? `安装后台小助手(在 ${o.cwd} 里自动领取任务)?会运行:`
128
+ : `Install the background helper (picks up tasks in ${o.cwd})? This runs:`,
136
129
  ` ${shellLine([...o.achCmd, ...helper])}`,
137
130
  ].join('\n') + '\n',
138
131
  commands: [[...o.achCmd, ...helper]],
@@ -152,11 +145,10 @@ export async function runSetup(io, o) {
152
145
  const home = env.AGENTCHANNEL_HOME || undefined;
153
146
  const result = { ran: [], skipped: [], failed: [], tools: [] };
154
147
  const zh = !!o.zh;
155
- const desktop = hasDesktop(env);
156
- // design §27: probe the sandbox of the tools this agent runs with (not in a dry run: it runs nothing)
148
+ // decisions §27: probe the sandbox of the tools this agent runs with (not in a dry run: it runs nothing)
157
149
  const probe = io.sandbox ?? ((t) => probeSandbox(t, { env }));
158
150
  const sandbox = o.dryRun ? [] : await Promise.all(toolsFor(o.runtime).map((t) => probe(t)));
159
- const plan = planSteps(d, { home, local: o.local, achCmd: d.achCmd, cwd: io.cwd, zh, env, runtime: o.runtime, service: o.service, desktop, sandbox });
151
+ const plan = planSteps(d, { home, local: o.local, achCmd: d.achCmd, cwd: io.cwd, zh, env, runtime: o.runtime, service: o.service, sandbox });
160
152
  if (o.dryRun) {
161
153
  printOnly(io, d, plan, { zh, join: o.join });
162
154
  return result;
@@ -232,7 +224,7 @@ export async function runSetup(io, o) {
232
224
  }
233
225
  if (!o.service) {
234
226
  // the home goes with the command: without it `ach run` starts the default home's agent
235
- const run = shellLine([...(home ? [`AGENTCHANNEL_HOME=${home}`] : []), ...(d.npx ? d.achCmd : ['ach']), 'run', '--install-service', ...(desktop ? ['--notify'] : []), '--dir', io.cwd]);
227
+ const run = shellLine([...(home ? [`AGENTCHANNEL_HOME=${home}`] : []), ...(d.npx ? d.achCmd : ['ach']), 'run', '--install-service', '--dir', io.cwd]);
236
228
  io.out(zh ? `可选:让它在后台自动领任务:${run}` : `Optional, to have it pick up tasks in the background: ${run}`);
237
229
  }
238
230
  return result;
@@ -46,8 +46,8 @@ export interface PromptCtx {
46
46
  export declare function conventionsText(j?: Judgment, ownerName?: string): string[];
47
47
  /**
48
48
  * How an agent decides between doing it, asking another agent and asking a person (docs/specs/agent-autonomy.md). The same for
49
- * every agent; the owner's notes and the project's instructions below refine it, the system's limits (sandbox, branch-only push,
50
- * grants) hold whatever any text says.
49
+ * every agent; the owner's notes and the project's instructions below refine it, the system's limits (sandbox, branch-only push)
50
+ * hold whatever any text says.
51
51
  */
52
52
  export declare const JUDGMENT: string;
53
53
  /** Trusted: the project's instructions, as written in the repository. */
@@ -13,8 +13,8 @@ export function conventionsText(j, ownerName) {
13
13
  }
14
14
  /**
15
15
  * How an agent decides between doing it, asking another agent and asking a person (docs/specs/agent-autonomy.md). The same for
16
- * every agent; the owner's notes and the project's instructions below refine it, the system's limits (sandbox, branch-only push,
17
- * grants) hold whatever any text says.
16
+ * every agent; the owner's notes and the project's instructions below refine it, the system's limits (sandbox, branch-only push)
17
+ * hold whatever any text says.
18
18
  */
19
19
  export const JUDGMENT = [
20
20
  'How to decide (AgentChannel\'s default for every agent):',
@@ -59,17 +59,7 @@ export function refOf(t) {
59
59
  }
60
60
  /** §19: agents speak in links. Trusted rule text. */
61
61
  export const LINK_RULE = '- Refer to tasks, posts and commits by link or ID (TASK-128, a post link, a commit URL), never "the one above" or "that task".';
62
- /** An imported GitHub item: attributed to its GitHub author, not to the hub person it maps to. */
63
- function externalAuthor(p) {
64
- const x = p.external;
65
- if (!x || typeof x !== 'object')
66
- return '';
67
- return `GitHub: ${String(x.author || x.author_name || '?')}`;
68
- }
69
62
  function postAuthor(p) {
70
- const ext = externalAuthor(p);
71
- if (ext)
72
- return ext;
73
63
  if (p.author_type === 'human')
74
64
  return 'human';
75
65
  if (p.author_type === 'system')
@@ -133,7 +123,7 @@ export function channelLines(posts, w, max = CHANNEL_PROMPT_CHARS) {
133
123
  let used = 0;
134
124
  const sorted = [...posts].sort((a, b) => String(b.created ?? '').localeCompare(String(a.created ?? '')));
135
125
  for (const p of sorted) {
136
- const human = p.author_type === 'human' && !externalAuthor(p);
126
+ const human = p.author_type === 'human';
137
127
  const ti = p.kind === 'task' && p.task_info ? p.task_info : null;
138
128
  const item = ti
139
129
  ? { id: p.id, from: postAuthor(p), human, task: { ref: ti.ref, title: ti.title, status: ti.status } }
@@ -150,7 +140,7 @@ export function channelLines(posts, w, max = CHANNEL_PROMPT_CHARS) {
150
140
  }
151
141
  /** Human posts, outside the untrusted block (author_type is set by the hub). */
152
142
  export function formatHumanPosts(posts) {
153
- const hs = posts.filter((p) => p.author_type === 'human' && !externalAuthor(p));
143
+ const hs = posts.filter((p) => p.author_type === 'human');
154
144
  if (!hs.length)
155
145
  return '(none)';
156
146
  return hs.map((p) => `- post id=${p.id} by human ${JSON.stringify(String(p.author_name || 'person'))}: ${JSON.stringify(p.body)}`).join('\n');
@@ -218,8 +208,7 @@ export function formatHumanDecisions(msgs) {
218
208
  return ds
219
209
  .map((m) => {
220
210
  const via = m.via_agent_name ? ` via agent ${JSON.stringify(String(m.via_agent_name))}` : '';
221
- const behalf = m.on_behalf_of_name ? ` on behalf of ${JSON.stringify(String(m.on_behalf_of_name))} per authorization #${String(m.grant || '?')}` : '';
222
- const who = `by human ${JSON.stringify(String(m.author_name || 'owner'))}${via}${behalf}`;
211
+ const who = `by human ${JSON.stringify(String(m.author_name || 'owner'))}${via}`;
223
212
  const files = attachmentList(m);
224
213
  const att = files.length ? ` (attached: ${files.map((f) => JSON.stringify(f.name)).join(', ')}; see files)` : '';
225
214
  return m.kind === 'note'
@@ -300,7 +289,7 @@ function rules(review) {
300
289
  '- Talk through the `ach` CLI (the task id is already set):',
301
290
  ' - `ach progress "<text>"` for short status updates.',
302
291
  ' - `ach ask "<question>"` asks the sender a factual question. Then stop and end your turn; you will be resumed with the answer.',
303
- ' - `ach ask-human "<one question>" --option "A|<detail>|<money>" --option "B|<detail>|<money>" [--recommend 0]` for anything about money, product direction or irreversible actions (your owner decides; add `--to both` when the choice also affects the sender\'s side (never for a fact only your owner knows, such as whether a rerun finished: they answer it, the sender\'s owner cannot), or `--to <name|email>` when the call belongs to a specific person in the task\'s channel, e.g. an ops decision to the ops owner; your owner is cc\'d). One question per request; 2–3 options, recommended first; state the money/impact of each option. Never ask what you can verify yourself (files, commands, Memory) or what resolves itself. The person replies by picking an option or typing; that reply is the decision. Then stop. If it says an authorization grant covers some options, pick one that fits and answer it with the printed `ach decide ... --grant <id> --option <n>`; never claim a person decided anything they did not reply.',
292
+ ' - `ach ask-human "<one question>" --option "A|<detail>|<money>" --option "B|<detail>|<money>" [--recommend 0]` for anything about money, product direction or irreversible actions (your owner decides; add `--to both` when the choice also affects the sender\'s side (never for a fact only your owner knows, such as whether a rerun finished: they answer it, the sender\'s owner cannot), or `--to <name|email>` when the call belongs to a specific person in the task\'s channel, e.g. an ops decision to the ops owner; your owner is cc\'d). One question per request; 2–3 options, recommended first; state the money/impact of each option. Never ask what you can verify yourself (files, commands, Memory) or what resolves itself. The person replies by picking an option or typing; that reply is the decision. Then stop. Never claim a person decided anything they did not reply.',
304
293
  ' - `ach complete --result-file .ach/<file>` (or `ach complete "<text>"`) when done: summary, how it was verified. It becomes the pull request\'s description; the runner links the pull request on the task.',
305
294
  ' - `ach fail "<reason>" --cause <secret|network|permission|workspace|quota|task|other> [--needs "<what is missing>"]` if it cannot be done. The cause tells your owner what to fix: secret, network, permission, workspace and quota only they can (say exactly what is missing in --needs: a variable name, a host, a repo); task when the task itself is wrong (name the agent or repository that should do it).',
306
295
  completeRule(review),
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Runner files a spawned agent must never read: the agent key (config.json), other
3
+ * runs' tokens (runs.json), session ids and logs. Not the whole home: the per-task
4
+ * worktrees live in <home>/work and must stay readable.
5
+ */
6
+ export declare function secretPaths(home: string): string[];
7
+ /**
8
+ * Runtime config a spawned agent's CLI needs from the real home: linked into the
9
+ * scratch home. Claude only: its user settings, hooks and MCP servers are not
10
+ * loaded anyway (settingSources [], strictMcpConfig). Codex is NOT linked: it
11
+ * gets its own CODEX_HOME (see prepareCodexHome).
12
+ */
13
+ export declare const RUNTIME_HOME_LINKS: string[];
14
+ /**
15
+ * macOS (live test): Claude Code keeps its login in the login keychain, which
16
+ * `security` finds through $HOME/Library/Keychains. Without this link a worker
17
+ * with a scratch HOME reports "Not logged in". Only the folder is linked; the
18
+ * sandbox still denies the worker's tools every path under the real home.
19
+ */
20
+ export declare function runtimeHomeLinks(platform?: NodeJS.Platform): string[];
21
+ /** The config.toml of a worker's own CODEX_HOME: nothing from the user's global config (no mcp_servers, profiles, notify hooks). */
22
+ export declare const CODEX_WORKER_CONFIG: string;
23
+ /**
24
+ * Codex isolation (live test): a worker run must not load the user's global
25
+ * Codex config (~/.codex/config.toml: MCP servers with their own credentials,
26
+ * profiles, notify hooks, AGENTS.md). The run gets its own CODEX_HOME holding
27
+ * only a generated config.toml and a symlink to the login file (auth.json) of
28
+ * the user's Codex home. The login file is placed by path only: it is never
29
+ * opened or copied here. Codex rewrites it in place through the link, so a
30
+ * refreshed login stays the user's. Sessions of the run stay in this home, so
31
+ * a resumed run of the same task finds its thread.
32
+ */
33
+ export declare function prepareCodexHome(home: string, realCodexHome?: string, platform?: NodeJS.Platform): string;
34
+ /** The user's real home: HOME, or USERPROFILE on Windows, where HOME is usually not set. */
35
+ export declare function realHomeOf(env: NodeJS.ProcessEnv | Record<string, string | undefined>, platform?: NodeJS.Platform): string | undefined;
36
+ /**
37
+ * B1: a per-task scratch HOME for spawned agents, so `~/.config/agentchannel`
38
+ * (agent key file, admin session, runner state) is not reachable through
39
+ * $HOME. Runtime config (.claude, .codex) is linked, the git identity
40
+ * (.gitconfig) copied; npm keeps the real cache via npm_config_cache.
41
+ */
42
+ export declare function prepareAgentHome(root: string, agentName: string, key: string, realHome?: string, realCodexHome?: string, platform?: NodeJS.Platform): {
43
+ home: string;
44
+ env: Record<string, string>;
45
+ };
@@ -0,0 +1,150 @@
1
+ // The scratch HOME a spawned agent runs in (B1): the runner's own files out of reach, the runtime's config linked or copied in,
2
+ // Codex given a home of its own. Pure filesystem work, no hub.
3
+ import { copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { linkWindowsSandbox, WINDOWS_ELEVATED_CONFIG } from '../codexhome.js';
6
+ /**
7
+ * Runner files a spawned agent must never read: the agent key (config.json), other
8
+ * runs' tokens (runs.json), session ids and logs. Not the whole home: the per-task
9
+ * worktrees live in <home>/work and must stay readable.
10
+ */
11
+ export function secretPaths(home) {
12
+ return ['config.json', 'agent-key', 'admin-session', 'cf-secret', 'runs.json', 'sessions.json', 'logs'].map((f) => join(home, f));
13
+ }
14
+ /**
15
+ * Runtime config a spawned agent's CLI needs from the real home: linked into the
16
+ * scratch home. Claude only: its user settings, hooks and MCP servers are not
17
+ * loaded anyway (settingSources [], strictMcpConfig). Codex is NOT linked: it
18
+ * gets its own CODEX_HOME (see prepareCodexHome).
19
+ */
20
+ export const RUNTIME_HOME_LINKS = ['.claude', '.claude.json'];
21
+ /**
22
+ * macOS (live test): Claude Code keeps its login in the login keychain, which
23
+ * `security` finds through $HOME/Library/Keychains. Without this link a worker
24
+ * with a scratch HOME reports "Not logged in". Only the folder is linked; the
25
+ * sandbox still denies the worker's tools every path under the real home.
26
+ */
27
+ export function runtimeHomeLinks(platform = process.platform) {
28
+ return platform === 'darwin' ? [...RUNTIME_HOME_LINKS, 'Library/Keychains'] : RUNTIME_HOME_LINKS;
29
+ }
30
+ /** The config.toml of a worker's own CODEX_HOME: nothing from the user's global config (no mcp_servers, profiles, notify hooks). */
31
+ export const CODEX_WORKER_CONFIG = [
32
+ '# Written by agentchannel for background worker runs. The user\'s global Codex',
33
+ '# config (MCP servers, profiles, hooks, AGENTS.md) is deliberately not used here.',
34
+ '# Model and sandbox are set per run by the runner.',
35
+ '',
36
+ ].join('\n');
37
+ /**
38
+ * Codex isolation (live test): a worker run must not load the user's global
39
+ * Codex config (~/.codex/config.toml: MCP servers with their own credentials,
40
+ * profiles, notify hooks, AGENTS.md). The run gets its own CODEX_HOME holding
41
+ * only a generated config.toml and a symlink to the login file (auth.json) of
42
+ * the user's Codex home. The login file is placed by path only: it is never
43
+ * opened or copied here. Codex rewrites it in place through the link, so a
44
+ * refreshed login stays the user's. Sessions of the run stay in this home, so
45
+ * a resumed run of the same task finds its thread.
46
+ */
47
+ export function prepareCodexHome(home, realCodexHome, platform = process.platform) {
48
+ const dir = join(home, '.codex');
49
+ try {
50
+ // an older scratch home linked the whole ~/.codex: replace the link
51
+ if (lstatSync(dir).isSymbolicLink())
52
+ rmSync(dir);
53
+ }
54
+ catch {
55
+ /* not there */
56
+ }
57
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
58
+ // Windows: the elevated sandbox, once its one-time setup is done (codexhome.ts)
59
+ const elevated = platform === 'win32' && linkWindowsSandbox(dir, realCodexHome);
60
+ writeFileSync(join(dir, 'config.toml'), CODEX_WORKER_CONFIG + (elevated ? WINDOWS_ELEVATED_CONFIG : ''), { mode: 0o600 });
61
+ if (realCodexHome) {
62
+ const src = join(realCodexHome, 'auth.json');
63
+ const dst = join(dir, 'auth.json');
64
+ let have = false;
65
+ try {
66
+ lstatSync(dst);
67
+ have = true;
68
+ }
69
+ catch {
70
+ /* not there */
71
+ }
72
+ if (!have && existsSync(src)) {
73
+ try {
74
+ symlinkSync(src, dst);
75
+ }
76
+ catch {
77
+ // Windows makes file symlinks only with developer mode or admin; a hard link needs neither
78
+ if (platform === 'win32') {
79
+ try {
80
+ linkSync(src, dst);
81
+ }
82
+ catch {
83
+ /* best effort: codex then reports "not logged in" */
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+ return dir;
90
+ }
91
+ /** The user's real home: HOME, or USERPROFILE on Windows, where HOME is usually not set. */
92
+ export function realHomeOf(env, platform = process.platform) {
93
+ return env.HOME || (platform === 'win32' ? env.USERPROFILE : undefined) || undefined;
94
+ }
95
+ /**
96
+ * B1: a per-task scratch HOME for spawned agents, so `~/.config/agentchannel`
97
+ * (agent key file, admin session, runner state) is not reachable through
98
+ * $HOME. Runtime config (.claude, .codex) is linked, the git identity
99
+ * (.gitconfig) copied; npm keeps the real cache via npm_config_cache.
100
+ */
101
+ export function prepareAgentHome(root, agentName, key, realHome, realCodexHome, platform = process.platform) {
102
+ const safe = (x) => x.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80);
103
+ const home = join(root, safe(agentName), safe(key));
104
+ mkdirSync(home, { recursive: true, mode: 0o700 });
105
+ // the run's own temporary directory, the one place besides its task directory a sandboxed run writes: tools need one, and
106
+ // Claude Code keeps its sandbox's network bridge there (a sandbox that reads only its own paths cannot reach /tmp)
107
+ const tmp = join(home, 'tmp');
108
+ mkdirSync(tmp, { recursive: true, mode: 0o700 });
109
+ const env = { HOME: home, TMPDIR: tmp };
110
+ // Windows programs find the home in USERPROFILE and the temporary directory in TEMP/TMP
111
+ if (platform === 'win32')
112
+ Object.assign(env, { USERPROFILE: home, TEMP: tmp, TMP: tmp });
113
+ if (!realHome) {
114
+ env.CODEX_HOME = prepareCodexHome(home, realCodexHome, platform);
115
+ return { home, env };
116
+ }
117
+ for (const name of runtimeHomeLinks(platform)) {
118
+ const src = join(realHome, name);
119
+ const dst = join(home, name);
120
+ if (!existsSync(src))
121
+ continue;
122
+ try {
123
+ lstatSync(dst);
124
+ }
125
+ catch {
126
+ try {
127
+ mkdirSync(dirname(dst), { recursive: true, mode: 0o700 });
128
+ // a junction links a Windows directory without developer mode or admin
129
+ symlinkSync(src, dst, platform === 'win32' && lstatSync(src).isDirectory() ? 'junction' : undefined);
130
+ }
131
+ catch {
132
+ /* best effort */
133
+ }
134
+ }
135
+ }
136
+ const git = join(realHome, '.gitconfig');
137
+ if (existsSync(git)) {
138
+ try {
139
+ copyFileSync(git, join(home, '.gitconfig'));
140
+ }
141
+ catch {
142
+ /* best effort */
143
+ }
144
+ }
145
+ const npmCache = join(realHome, '.npm');
146
+ if (existsSync(npmCache))
147
+ env.npm_config_cache = npmCache;
148
+ env.CODEX_HOME = prepareCodexHome(home, realCodexHome || join(realHome, '.codex'), platform);
149
+ return { home, env };
150
+ }
@@ -5,6 +5,8 @@ import { RunnerState } from './state.js';
5
5
  import { type Workspace } from './workspace.js';
6
6
  import { TraceRecorder } from '../trace.js';
7
7
  import { type SandboxStatus } from '../sandboxcheck.js';
8
+ export * from './home.js';
9
+ export * from './structured.js';
8
10
  export type RunnerClient = Pick<Client, 'me' | 'inbox' | 'claim' | 'getTask' | 'postMessage' | 'complete' | 'fail' | 'usage' | 'heartbeat' | 'answerRun' | 'endRun'> & Partial<Pick<Client, 'download' | 'githubToken' | 'channelPosts' | 'mentionRun' | 'mentionEnd' | 'mentionUsage' | 'promptSize' | 'reportSetup' | 'reportRepos' | 'reportRunner' | 'release' | 'putTrace' | 'pushToken' | 'taskPr' | 'prepareRun' | 'prepared'>>;
9
11
  export interface RunnerOptions {
10
12
  client: RunnerClient;
@@ -53,7 +55,7 @@ export interface RunnerOptions {
53
55
  /** §16: how many recent channel posts work prompts carry (default 15; 0 = none). */
54
56
  channelContext?: number;
55
57
  /**
56
- * design §27: probes the agent tool's sandbox. While it fails the runner takes nothing new (tasks wait in the hub's
58
+ * decisions §27: probes the agent tool's sandbox. While it fails the runner takes nothing new (tasks wait in the hub's
57
59
  * inbox), reports why, and probes again every `sandboxRecheckMs`. Absent: no check (tests).
58
60
  */
59
61
  sandboxCheck?: () => Promise<SandboxStatus>;
@@ -62,7 +64,7 @@ export interface RunnerOptions {
62
64
  secrets?: string[];
63
65
  /** A machine that checked out is checked again this often (default 6 h), so a login that expired is found before a task is taken. */
64
66
  okRecheckMs?: number;
65
- /** design §34: the capabilities file (default <home>/capabilities.json). */
67
+ /** decisions §34: the capabilities file (default <home>/capabilities.json). */
66
68
  capsFile?: string;
67
69
  /** the `ach` entry point the capabilities server runs (default this package's cli.js) */
68
70
  cliPath?: string;
@@ -127,51 +129,6 @@ export declare function openRequests(messages: Message[], myId: string): Message
127
129
  export declare function isHumanNoteTo(m: Message, myId: string): boolean;
128
130
  /** Answers / decisions replying to something I asked, and human notes to me, that the worker has not been shown yet. */
129
131
  export declare function unseenReplies(messages: Message[], myId: string, seen: string[]): Message[];
130
- /**
131
- * Runner files a spawned agent must never read: the agent key (config.json), other
132
- * runs' tokens (runs.json), session ids and logs. Not the whole home: the per-task
133
- * worktrees live in <home>/work and must stay readable.
134
- */
135
- export declare function secretPaths(home: string): string[];
136
- /**
137
- * Runtime config a spawned agent's CLI needs from the real home: linked into the
138
- * scratch home. Claude only: its user settings, hooks and MCP servers are not
139
- * loaded anyway (settingSources [], strictMcpConfig). Codex is NOT linked: it
140
- * gets its own CODEX_HOME (see prepareCodexHome).
141
- */
142
- export declare const RUNTIME_HOME_LINKS: string[];
143
- /**
144
- * macOS (live test): Claude Code keeps its login in the login keychain, which
145
- * `security` finds through $HOME/Library/Keychains. Without this link a worker
146
- * with a scratch HOME reports "Not logged in". Only the folder is linked; the
147
- * sandbox still denies the worker's tools every path under the real home.
148
- */
149
- export declare function runtimeHomeLinks(platform?: NodeJS.Platform): string[];
150
- /** The config.toml of a worker's own CODEX_HOME: nothing from the user's global config (no mcp_servers, profiles, notify hooks). */
151
- export declare const CODEX_WORKER_CONFIG: string;
152
- /**
153
- * Codex isolation (live test): a worker run must not load the user's global
154
- * Codex config (~/.codex/config.toml: MCP servers with their own credentials,
155
- * profiles, notify hooks, AGENTS.md). The run gets its own CODEX_HOME holding
156
- * only a generated config.toml and a symlink to the login file (auth.json) of
157
- * the user's Codex home. The login file is placed by path only: it is never
158
- * opened or copied here. Codex rewrites it in place through the link, so a
159
- * refreshed login stays the user's. Sessions of the run stay in this home, so
160
- * a resumed run of the same task finds its thread.
161
- */
162
- export declare function prepareCodexHome(home: string, realCodexHome?: string, platform?: NodeJS.Platform): string;
163
- /** The user's real home: HOME, or USERPROFILE on Windows, where HOME is usually not set. */
164
- export declare function realHomeOf(env: NodeJS.ProcessEnv | Record<string, string | undefined>, platform?: NodeJS.Platform): string | undefined;
165
- /**
166
- * B1: a per-task scratch HOME for spawned agents, so `~/.config/agentchannel`
167
- * (agent key file, admin session, runner state) is not reachable through
168
- * $HOME. Runtime config (.claude, .codex) is linked, the git identity
169
- * (.gitconfig) copied; npm keeps the real cache via npm_config_cache.
170
- */
171
- export declare function prepareAgentHome(root: string, agentName: string, key: string, realHome?: string, realCodexHome?: string, platform?: NodeJS.Platform): {
172
- home: string;
173
- env: Record<string, string>;
174
- };
175
132
  export declare function budgetBlocked(me: Agent): boolean;
176
133
  export declare class Runner {
177
134
  readonly state: RunnerState;
@@ -202,7 +159,7 @@ export declare class Runner {
202
159
  /** B7: set when the hub answered 401 (key rotated, agent or owner deactivated): the runner stops. */
203
160
  fatal?: 'unauthorized';
204
161
  private wake?;
205
- /** design §27: the last sandbox probe, when it ran, and what the hub was last told (a JSON key). */
162
+ /** decisions §27: the last sandbox probe, when it ran, and what the hub was last told (a JSON key). */
206
163
  sandbox?: {
207
164
  st: SandboxStatus;
208
165
  at: number;
@@ -210,8 +167,7 @@ export declare class Runner {
210
167
  private sandboxReported?;
211
168
  private sandboxRecheck;
212
169
  /** Execution traces the hub has not taken yet (kept on disk too), and the last trace of each task (a commit joins it). */
213
- private traceQueue;
214
- private lastTrace;
170
+ private traces;
215
171
  constructor(opts: RunnerOptions);
216
172
  private log;
217
173
  private taskLog;
@@ -226,7 +182,7 @@ export declare class Runner {
226
182
  authFailed(where: string): void;
227
183
  /** One poll cycle. */
228
184
  tick(): Promise<void>;
229
- /** design §27: probe the sandbox when due, tell the hub when the answer changes; true = take nothing new. */
185
+ /** decisions §27: probe the sandbox when due, tell the hub when the answer changes; true = take nothing new. */
230
186
  private sandboxBlocked;
231
187
  /** Tell the hub which repo names this runner knows, so a task for another repo is refused when it is sent. Tried on every
232
188
  * poll until the hub has it: a hub that was unreachable at start would otherwise keep the previous list until a restart. */
@@ -238,7 +194,7 @@ export declare class Runner {
238
194
  private runnerReported;
239
195
  /** the capabilities file problems last logged (logged again only when they change) */
240
196
  private capsProblems;
241
- /** the capabilities last told to the hub (design §34): an edit of the file is reported again on the next poll */
197
+ /** the capabilities last told to the hub (decisions §34): an edit of the file is reported again on the next poll */
242
198
  private capsReported;
243
199
  private reportRunner;
244
200
  private notifyBudget;
@@ -336,16 +292,8 @@ export declare class Runner {
336
292
  private githubToken;
337
293
  /** Run the adapter with heartbeat, idle watchdog, session persistence and usage posting. */
338
294
  private execute;
339
- /** design §34: the capabilities server of one run, or undefined when nothing is declared (or the run is in the cloud). */
295
+ /** decisions §34: the capabilities server of one run, or undefined when nothing is declared (or the run is in the cloud). */
340
296
  private capsFor;
341
- private traceDir;
342
- /** Traces an earlier process could not upload are tried again. */
343
- private loadPendingTraces;
344
- /** Build and send the trace of the run that just ended. Never throws; a failed upload is kept and retried. */
345
- private uploadTrace;
346
- private persistTrace;
347
- /** Send what is waiting (a few at a time). A trace never holds up a task: failures are logged and tried again on the next poll. */
348
- private flushTraces;
349
297
  /** Polls until stop() or a 401 (B7: resolves 'unauthorized' after aborting every job). */
350
298
  start(): Promise<'stopped' | 'unauthorized'>;
351
299
  /** Stop polling; abort running jobs without failing their tasks (they resume on restart). */
@@ -358,24 +306,3 @@ export declare function gcWorktrees(client: Pick<Client, 'getTask'>, ws: Workspa
358
306
  log?: (s: string) => void;
359
307
  keepFailed?: boolean;
360
308
  }): Promise<string[]>;
361
- /**
362
- * The JSON object a structured run ended with. Codex returns it bare (outputSchema); a remote run's final message may
363
- * wrap it in a ```json fence or a sentence, so the last {...} in the text is taken. Throws when there is none.
364
- */
365
- export declare function parseStructured(text: string): {
366
- action?: string;
367
- text?: string;
368
- evidence?: string;
369
- };
370
- /** What a read-ahead found (its final JSON object). */
371
- export interface PrepareOut {
372
- code: boolean;
373
- files: string[];
374
- plan: string;
375
- questions: string[];
376
- }
377
- /** The read-ahead's final JSON object: the last one in its message (bare, fenced, or after a sentence). Throws when there is none. */
378
- export declare function parsePrepared(text: string): PrepareOut;
379
- /** The draft as the owner reads it on the task: the plan, the files, the questions, and the small-job rule it fell inside. */
380
- export declare function draftText(o: PrepareOut, rule: string): string;
381
- export {};