@koalaauto/agentchannel 3.53.4 → 3.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +5 -2
  2. package/dist/src/adapters/antigravity.d.ts +154 -0
  3. package/dist/src/adapters/antigravity.js +345 -0
  4. package/dist/src/adapters/claude.d.ts +24 -0
  5. package/dist/src/adapters/claude.js +2 -0
  6. package/dist/src/adapters/codex.d.ts +24 -1
  7. package/dist/src/adapters/codex.js +2 -1
  8. package/dist/src/adapters/fake.d.ts +6 -3
  9. package/dist/src/adapters/fake.js +21 -5
  10. package/dist/src/adapters/index.d.ts +2 -0
  11. package/dist/src/adapters/index.js +7 -1
  12. package/dist/src/adapters/kiro.d.ts +20 -2
  13. package/dist/src/adapters/kiro.js +2 -2
  14. package/dist/src/adapters/spec.d.ts +164 -0
  15. package/dist/src/adapters/spec.js +104 -0
  16. package/dist/src/adapters/types.d.ts +4 -7
  17. package/dist/src/agycheck.d.ts +21 -0
  18. package/dist/src/agycheck.js +58 -0
  19. package/dist/src/appinstall.d.ts +54 -0
  20. package/dist/src/appinstall.js +216 -0
  21. package/dist/src/args.d.ts +1 -1
  22. package/dist/src/args.js +3 -2
  23. package/dist/src/cli-run.js +93 -26
  24. package/dist/src/client.d.ts +19 -0
  25. package/dist/src/doctor.d.ts +3 -3
  26. package/dist/src/doctor.js +13 -7
  27. package/dist/src/invite.js +6 -2
  28. package/dist/src/onboard.d.ts +21 -2
  29. package/dist/src/onboard.js +56 -3
  30. package/dist/src/prompts.d.ts +9 -2
  31. package/dist/src/prompts.js +57 -5
  32. package/dist/src/runner/context.d.ts +2 -2
  33. package/dist/src/runner/context.js +3 -3
  34. package/dist/src/runner/runner.d.ts +4 -0
  35. package/dist/src/runner/runner.js +49 -24
  36. package/dist/src/runtimecheck.d.ts +26 -0
  37. package/dist/src/runtimecheck.js +20 -0
  38. package/dist/src/sandboxcheck.d.ts +2 -1
  39. package/dist/src/sandboxcheck.js +10 -5
  40. package/dist/src/selfupdate.d.ts +10 -1
  41. package/dist/src/selfupdate.js +28 -5
  42. package/dist/src/service.d.ts +5 -4
  43. package/dist/src/service.js +2 -0
  44. package/dist/src/servicefix.d.ts +4 -4
  45. package/dist/src/servicefix.js +10 -8
  46. package/dist/src/version.d.ts +1 -1
  47. package/dist/src/version.js +1 -1
  48. package/package.json +1 -1
@@ -1,7 +1,10 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
+ import { parseMcpEntry } from './doctor.js';
3
4
  import { probeSandbox } from './sandboxcheck.js';
5
+ import { adoptFromNpx, appAch } from './appinstall.js';
4
6
  import { identifyAch, isOurs, MCP_SERVER_NAME, npxAch, thisCliPath, userBin, whichAll } from './invite.js';
7
+ import { PKG_NAME } from './version.js';
5
8
  /** The closing line: which tool to open and what to say to it. */
6
9
  export function doneLine(tools, zh) {
7
10
  const names = [...new Set(tools)].map((k) => (k === 'claude' ? 'Claude Code' : 'Codex'));
@@ -61,8 +64,10 @@ export async function detect(env, exec, self, probe) {
61
64
  const d = {
62
65
  claude, codex, npx,
63
66
  claudeHasAch: false, codexHasAch: false,
64
- // run through npx: the MCP entry uses the same pinned spec as the join line
65
- achCmd: npx ? npxAch() : absoluteAch(env, self),
67
+ // run through npx (the join line): this release is copied into the AgentChannel home and the MCP entry and service start it
68
+ // from there (appinstall.ts); npx at every start fails while npm catches up with a release. The npx spec if the copy failed;
69
+ // a dry run (no probe) copies nothing and shows the install's command.
70
+ achCmd: npx ? (probe ? (adoptFromNpx({ self, env }) ?? npxAch()) : appAch(env)) : absoluteAch(env, self),
66
71
  };
67
72
  if (!probe)
68
73
  return d;
@@ -240,7 +245,7 @@ async function fixSandbox(io, s, before, probe, zh) {
240
245
  }
241
246
  let ok = true;
242
247
  for (const st of before.filter((x) => !x.ok)) {
243
- if (st.tool === 'kiro')
248
+ if (st.tool !== 'claude' && st.tool !== 'codex')
244
249
  continue; // onboarding probes only the local sandboxes
245
250
  const now = await probe(st.tool);
246
251
  if (now.ok)
@@ -315,3 +320,51 @@ function printOnly(io, d, plan, o) {
315
320
  out.push('', `${zh ? '随时检查配置:' : 'Check the setup any time with: '}${shellLine([...(d.npx ? d.achCmd : ['ach']), 'doctor'])}`);
316
321
  io.out(out.join('\n'));
317
322
  }
323
+ /** An entry that starts this package through npx (`npx -y @koalaauto/agentchannel@3 mcp`). */
324
+ export function isNpxEntry(e) {
325
+ return !!e.command && /(^|[\\/])npx(\.cmd)?$/.test(e.command) && e.args.at(-1) === 'mcp' && e.args.some((a) => a === PKG_NAME || a.startsWith(`${PKG_NAME}@`));
326
+ }
327
+ /**
328
+ * The `ach` MCP entries of Claude Code and Codex that join wrote as `npx -y <spec> mcp` are pointed at the install in the AgentChannel
329
+ * home (`achCmd`), keeping their scope and AGENTCHANNEL_HOME: npx re-resolves the spec at every session start and fails while npm catches
330
+ * up with a release. `exec` runs in the runner's project dir, where Claude Code keeps a local-scope entry; `userExec` in a dir with no
331
+ * entries of its own, where `claude mcp get` shows the user-scope one (a local entry hides it). A project-scope entry (.mcp.json, in the
332
+ * repository) is left alone. Returns what was moved, as `<tool> <scope>`.
333
+ */
334
+ export async function moveNpxMcpEntries(o) {
335
+ const moved = [];
336
+ const looks = [
337
+ { kind: 'claude', exec: o.exec },
338
+ ...(o.userExec ? [{ kind: 'claude', exec: o.userExec }] : []),
339
+ { kind: 'codex', exec: o.exec },
340
+ ];
341
+ for (const { kind, exec } of looks) {
342
+ const bin = userBin(kind, o.env);
343
+ if (!bin)
344
+ continue;
345
+ const got = await exec(bin, ['mcp', 'get', MCP_SERVER_NAME], o.env);
346
+ if (got.code !== 0)
347
+ continue;
348
+ const e = parseMcpEntry(got.stdout, MCP_SERVER_NAME);
349
+ if (!isNpxEntry(e))
350
+ continue;
351
+ const scope = kind === 'codex' ? 'user' : /^\s*Scope:\s*Local/im.test(got.stdout) ? 'local' : /^\s*Scope:\s*User/im.test(got.stdout) ? 'user' : undefined;
352
+ if (!scope || moved.includes(`${kind} ${scope}`))
353
+ continue;
354
+ const local = scope === 'local';
355
+ const rm = await exec(bin, mcpRemoveArgv(kind, bin, MCP_SERVER_NAME, local).slice(1), o.env);
356
+ if (rm.code !== 0) {
357
+ o.log?.(`could not remove the npx \`ach\` entry of ${kind} (exit ${rm.code}): ${rm.stderr.trim().split('\n')[0] ?? ''}`);
358
+ continue;
359
+ }
360
+ const add = await exec(bin, mcpAddArgv(kind, bin, o.achCmd, e.home, local).slice(1), o.env);
361
+ if (add.code !== 0) {
362
+ // the entry is gone now: put the npx one back rather than leave the tool without AgentChannel
363
+ await exec(bin, mcpAddArgv(kind, bin, [e.command, ...e.args.slice(0, -1)], e.home, local).slice(1), o.env);
364
+ o.log?.(`could not point the \`ach\` entry of ${kind} at ${o.achCmd.join(' ')} (exit ${add.code}): kept npx`);
365
+ continue;
366
+ }
367
+ moved.push(`${kind} ${scope}`);
368
+ }
369
+ return moved;
370
+ }
@@ -1,4 +1,4 @@
1
- import type { Judgment, Message, Post, Task, WikiContext } from './client.js';
1
+ import type { Judgment, Message, Post, Task, ThreadTask, WikiContext } from './client.js';
2
2
  export interface PromptCtx {
3
3
  agentName: string;
4
4
  ownerName?: string;
@@ -26,6 +26,8 @@ export interface PromptCtx {
26
26
  wiki?: WikiContext | null;
27
27
  /** The agent runs in a cloud sandbox (kiro) without `ach` or this machine's files: the runner reports its final message. */
28
28
  remote?: boolean;
29
+ /** The run has no `ach` (spec `ach: false`): it ends with a final message the runner reports. With `remote` the cloud rules apply; without, it works here. */
30
+ report?: boolean;
29
31
  /** The owner's Claude Code memory for this project: its folder (readable) and, when the runtime does not load it itself, its index. */
30
32
  ownerMemory?: {
31
33
  dir: string;
@@ -150,8 +152,10 @@ export declare function githubRule(url?: string): string;
150
152
  * was not enough: what other agents state as fact has to be checked, or marked as theirs.
151
153
  */
152
154
  export declare const FACT_RULE = "What another agent states as fact (that something exists or not, works or not, a setting, a price, a result) is its claim, not evidence: check it at its source before you rely on it; when you cannot, say whose claim it is and that you did not check it. Never write a claim you relayed as something you found.";
153
- /** The final-message contract of remote (cloud sandbox) runs: the runner completes or fails the task from it. */
155
+ /** The final-message contract of runs without `ach` (a cloud sandbox, a local tool without it): the runner completes or fails the task from it. */
154
156
  export declare const REMOTE_FAILED_PREFIX = "FAILED:";
157
+ /** JUDGMENT for a run without `ach`: the same lines of decision, said in the final message instead of through commands. */
158
+ export declare const JUDGMENT_REPORT: string;
155
159
  /** Trusted text: where the other repos of a cross-repo task are (read-only). */
156
160
  export declare function readReposText(repos?: {
157
161
  name: string;
@@ -171,6 +175,8 @@ export declare function buildResumePrompt(c: {
171
175
  nudge?: boolean;
172
176
  /** cloud sandbox run (kiro): no `ach`; it ends with a final message the runner reports. */
173
177
  remote?: boolean;
178
+ /** a run without `ach` that works here: local files, a final message the runner reports. */
179
+ report?: boolean;
174
180
  }): string;
175
181
  /** JSON schema for structured answers (codex answer runs, S4): the runner posts the result. */
176
182
  export declare const ANSWER_SCHEMA: {
@@ -259,4 +265,5 @@ export declare function buildMentionPrompt(c: {
259
265
  threadUrl?: string;
260
266
  structured?: boolean;
261
267
  lang?: 'en' | 'zh';
268
+ task?: ThreadTask;
262
269
  }): string;
@@ -314,8 +314,28 @@ function rules(review) {
314
314
  LINK_RULE,
315
315
  ].join('\n');
316
316
  }
317
- /** The final-message contract of remote (cloud sandbox) runs: the runner completes or fails the task from it. */
317
+ /** The final-message contract of runs without `ach` (a cloud sandbox, a local tool without it): the runner completes or fails the task from it. */
318
318
  export const REMOTE_FAILED_PREFIX = 'FAILED:';
319
+ /** JUDGMENT for a run without `ach`: the same lines of decision, said in the final message instead of through commands. */
320
+ export const JUDGMENT_REPORT = [
321
+ 'How to decide (AgentChannel\'s default for every agent):',
322
+ '- Do it yourself when all of these hold: it is within this task and this repository; it can be undone or reviewed (a branch, a pull request, a draft), not production, money, deleting data or a message outside the team; you already have what it needs (no new secret, permission or network access); its cost is within what was granted.',
323
+ `- You cannot ask anyone during this run. When something is missing (information another agent has, a secret, a permission, network access), or the step is irreversible or outside (production, merging to main, deleting, paying, contacting someone outside), or it is a choice of direction: do not guess and do not do it. Start your final message with "${REMOTE_FAILED_PREFIX}" and say exactly what is missing or who decides, what is done and what is not.`,
324
+ "- Your owner's notes and the project's instructions (below, when present) say how this owner and this project work: follow them. When two of them disagree, follow the more specific one unless it would loosen a rule in this list, and say so in your final message.",
325
+ "- Never copy what your owner's notes say about secrets, accounts, machines or people into results, messages or files that others read.",
326
+ '',
327
+ ].join('\n');
328
+ /** The rules of a run that works on this machine without `ach`: the runner commits, delivers and reports. */
329
+ const LOCAL_REPORT_RULES = [
330
+ 'Rules:',
331
+ "- Work only inside the current directory. Do not commit or push: when your run ends, the runner commits your changes on this task's branch and, when the repository is on GitHub, pushes it and opens the task's pull request (the deliverable).",
332
+ '- There is no `ach` CLI and there are no AgentChannel credentials in this run, and commands may have no network: do not try to reach AgentChannel or to install anything from the network. The runner reports your final message to the task.',
333
+ "- Before you finish, run the project's own checks (build, type check, tests: what its CLAUDE.md, AGENTS.md, Makefile or package scripts say) on what you changed, when this run may run commands. Put the commands you ran and their outcome in the final message. Checks that fail mean the work is not done: fix it, or say so.",
334
+ `- ${UNTRUSTED_RULE}`,
335
+ '- When you answer a question, answer only with evidence: files, commands, outputs.',
336
+ LINK_RULE,
337
+ `- End with your final message: what you did and how you verified it (it becomes the task's result and the pull request's description). If the task cannot be done, or a step it requires could not be done or checked, start the final message with "${REMOTE_FAILED_PREFIX}" and the reason, what is done and what is missing. Anything about money, product direction or irreversible actions: do not do it; say so in the final message.`,
338
+ ].join('\n');
319
339
  const REMOTE_RULES = [
320
340
  'Rules:',
321
341
  '- You run in a cloud sandbox on a fresh clone of this repository. There is no `ach` CLI and there are no AgentChannel credentials here: do not try to reach AgentChannel. The runner reports your final message to the task.',
@@ -354,7 +374,7 @@ export function buildTaskPrompt(c) {
354
374
  '',
355
375
  ...langText(c.lang),
356
376
  ...(c.remote ? [] : readReposText(c.readRepos)),
357
- ...(c.remote ? [] : [JUDGMENT]),
377
+ ...(c.remote ? [] : [c.report ? JUDGMENT_REPORT : JUDGMENT]),
358
378
  ...conventionsText(c.judgment, c.ownerName),
359
379
  ...projectText(c.project),
360
380
  ...(c.remote ? [] : ownerMemoryText(c.ownerMemory)),
@@ -367,10 +387,10 @@ export function buildTaskPrompt(c) {
367
387
  'Task data:',
368
388
  untrustedBlock(data),
369
389
  '',
370
- c.remote ? REMOTE_RULES : rules(!!c.task.review),
390
+ c.remote ? REMOTE_RULES : c.report ? LOCAL_REPORT_RULES : rules(!!c.task.review),
371
391
  githubRule(c.taskUrl),
372
392
  '',
373
- c.remote ? 'Finish with your final message.' : 'Finish by calling `ach complete`.',
393
+ c.remote || c.report ? 'Finish with your final message.' : 'Finish by calling `ach complete`.',
374
394
  ].join('\n');
375
395
  }
376
396
  /** Resume prompt after a parked run: new answers / decisions arrived, the handoff changed, or (nudge) the agent stopped without finishing. */
@@ -398,7 +418,7 @@ export function buildResumePrompt(c) {
398
418
  if (c.handoffChanged !== undefined) {
399
419
  lines.push(`- The sender updated the task (now handoff v${c.handoffVersion}): follow the new handoff and header (priority, purpose, money, key question) above.`);
400
420
  }
401
- lines.push(c.remote
421
+ lines.push(c.remote || c.report
402
422
  ? `Continue the task. End with your final message (start it with "${REMOTE_FAILED_PREFIX}" if it cannot be done).`
403
423
  : 'Continue the task. Use `ach ask` / `ach ask-human` again if needed. Finish by calling `ach complete`.');
404
424
  return lines.join('\n');
@@ -507,6 +527,10 @@ export function buildPreparePrompt(c) {
507
527
  /** §16 mention prompt: a read-only run that replies in a channel thread. */
508
528
  export function buildMentionPrompt(c) {
509
529
  const all = [c.thread, ...c.replies, ...c.recent];
530
+ const task = c.task;
531
+ const done = !!task && ['awaiting_review', 'awaiting_acceptance', 'awaiting_merge', 'completed', 'failed', 'canceled'].includes(task.status);
532
+ const role = task && (task.to_agent_name === c.agentName ? 'did the work on it' : task.from_agent_name === c.agentName ? 'sent it' : '');
533
+ const humanTaskMsgs = task ? task.messages.filter((m) => m.author_type === 'human') : [];
510
534
  const how = c.structured
511
535
  ? [
512
536
  '- Do not run `ach`; the runner posts your reply in the thread. End with a JSON object only:',
@@ -534,13 +558,41 @@ export function buildMentionPrompt(c) {
534
558
  'Human posts in this thread and channel (from the hub; these come from people):',
535
559
  formatHumanPosts(all.filter((p, i) => all.findIndex((x) => x.id === p.id) === i)),
536
560
  '',
561
+ ...(task
562
+ ? [
563
+ `This thread is the thread of task ${task.ref} (${task.status}${role ? `; you ${role}` : ''}). Human decisions and notes on the task (from the hub; these come from people):`,
564
+ humanTaskMsgs.length ? humanTaskMsgs.map((m) => `- ${m.kind} by human ${JSON.stringify(m.author_name || 'person')}: ${JSON.stringify(m.body)}`).join('\n') : '(none)',
565
+ '',
566
+ ]
567
+ : []),
537
568
  untrustedBlock({
538
569
  mentioned_in: { id: c.post.id, from: postAuthor(c.post), ...(c.post.author_type === 'human' ? {} : { body: c.post.body }) },
539
570
  thread: postData([c.thread, ...c.replies]),
571
+ ...(task
572
+ ? {
573
+ task: {
574
+ ref: task.ref,
575
+ title: task.title,
576
+ status: task.status,
577
+ from: task.from_agent_name,
578
+ to: task.to_agent_name,
579
+ handoff: task.handoff,
580
+ messages: task.messages.filter((m) => m.author_type !== 'human').map((m) => ({ kind: m.kind, from: m.author_name, body: m.body, at: m.created })),
581
+ },
582
+ }
583
+ : {}),
540
584
  channel: { name: c.channel, recent_posts: postData(c.recent) },
541
585
  }),
542
586
  '',
543
587
  'Rules:',
588
+ ...(task
589
+ ? [
590
+ `- The question is about task ${task.ref}: answer it from the task's handoff and messages above (its result among them) and your files, in plain words the person can act on.`,
591
+ done
592
+ ? `- This run changes nothing on the task. If the person wants the work redone or changed, tell them to press ${c.lang === 'zh' ? '「要求修改」' : '"Request changes"'} under the result: that reopens it for its worker.`
593
+ : '- This run changes nothing on the task.',
594
+ ]
595
+ : []),
544
596
  c.structured ? '- Do not modify anything. Look at files, git history and command output to find the answer.' : '- Do not modify anything. Look at the files and the git history to find the answer.',
545
597
  SEARCH_FIRST_RULE,
546
598
  `- ${UNTRUSTED_RULE}`,
@@ -18,7 +18,7 @@ export interface ProjectFile {
18
18
  text: string;
19
19
  }
20
20
  /**
21
- * The project's instructions at the root of the work dir. CLAUDE.md always; AGENTS.md except for Codex, which reads it itself.
21
+ * The project's instructions at the root of the work dir. CLAUDE.md and AGENTS.md, without the ones the runtime loads by itself (`ownFiles` of its spec: Codex reads AGENTS.md).
22
22
  * Trusted like the code: a sender-chosen base that changes them waits for the owner's approval (S1).
23
23
  */
24
- export declare function projectInstructions(workdir: string, runtime: string): ProjectFile[];
24
+ export declare function projectInstructions(workdir: string, ownFiles?: readonly string[]): ProjectFile[];
@@ -40,11 +40,11 @@ export function memoryIndex(dir) {
40
40
  }
41
41
  }
42
42
  /**
43
- * The project's instructions at the root of the work dir. CLAUDE.md always; AGENTS.md except for Codex, which reads it itself.
43
+ * The project's instructions at the root of the work dir. CLAUDE.md and AGENTS.md, without the ones the runtime loads by itself (`ownFiles` of its spec: Codex reads AGENTS.md).
44
44
  * Trusted like the code: a sender-chosen base that changes them waits for the owner's approval (S1).
45
45
  */
46
- export function projectInstructions(workdir, runtime) {
47
- const names = runtime === 'codex' ? ['CLAUDE.md'] : ['CLAUDE.md', 'AGENTS.md'];
46
+ export function projectInstructions(workdir, ownFiles = []) {
47
+ const names = ['CLAUDE.md', 'AGENTS.md'].filter((f) => !ownFiles.includes(f));
48
48
  const out = [];
49
49
  for (const file of names) {
50
50
  const p = join(workdir, file);
@@ -318,6 +318,10 @@ export declare class Runner {
318
318
  private postStructuredAnswer;
319
319
  /** Readable roots for the spawned agent besides its cwd (S4). */
320
320
  private readRoots;
321
+ /** The run works elsewhere (a cloud sandbox): nothing of this machine (files, memory, capabilities) reaches it. */
322
+ private get cloud();
323
+ /** Short runs return JSON by a schema and the runner posts it: the runtime's way, and the only way without `ach` in the run. */
324
+ private get structured();
321
325
  /** Owned by no one person (the system agent, or a team agent such as one that does a channel mechanism for the team). */
322
326
  private teamOwned;
323
327
  /** What a full task prompt carries besides the task: the owner's memory for this project and the project's instructions. */
@@ -9,6 +9,7 @@ import { capsPath, capsPromptText, capsServeArgs, loadCaps } from '../caps.js';
9
9
  import { autorunPath, loadAutorun, ruleName, smallRule } from '../autorun.js';
10
10
  import { toolchainReadRoots } from '../adapters/paths.js';
11
11
  import { developerDir } from '../adapters/scope.js';
12
+ import { isRuntime, runRefusal } from '../adapters/spec.js';
12
13
  import { modelId } from '../adapters/types.js';
13
14
  import { Client as HubClient, HubError, isTerminal } from '../client.js';
14
15
  import { taskFiles } from '../attachments.js';
@@ -408,7 +409,7 @@ export class Runner {
408
409
  if (!billing && !(result.ok && this.account))
409
410
  return;
410
411
  const was = this.account;
411
- const tool = ['claude', 'codex', 'kiro'].find((x) => x === this.o.adapter.name) ?? 'claude';
412
+ const tool = this.o.adapter.name;
412
413
  if (billing) {
413
414
  const st = { tool, ok: false, problem: 'billing', detail: summarizeRuntimeError(result.error ?? '').slice(0, 300) };
414
415
  st.fix = sandboxFix(st, detectHost(process.env, process.platform));
@@ -458,7 +459,7 @@ export class Runner {
458
459
  describeNextAt = 0;
459
460
  async describeAgent() {
460
461
  const { adapter, client, workspace } = this.o;
461
- if (this.describeDone || this.describeBusy || Date.now() < this.describeNextAt || adapter.remote || !client.reportDescription || !workspace.repoDirs)
462
+ if (this.describeDone || this.describeBusy || Date.now() < this.describeNextAt || this.cloud || !client.reportDescription || !workspace.repoDirs)
462
463
  return;
463
464
  this.describeBusy = true;
464
465
  try {
@@ -477,6 +478,9 @@ export class Runner {
477
478
  const ctl = new AbortController();
478
479
  const timer = setTimeout(() => ctl.abort(), 3 * 60_000);
479
480
  try {
481
+ const refused = runRefusal(adapter.spec, { perm: 'read', ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}) });
482
+ if (refused)
483
+ return { ok: false, finalText: '', error: `not run: ${refused}` };
480
484
  return await adapter.run({
481
485
  ...(pick ? { model: pick.model, effort: pick.effort } : {}),
482
486
  prompt: describePrompt(me.name, dirs),
@@ -491,8 +495,8 @@ export class Runner {
491
495
  readRoots: dirs.map(([, d]) => d),
492
496
  ...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
493
497
  ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
494
- ...(adapter.name === 'claude' ? { maxBudgetUsd: 0.05 } : {}),
495
- ...(adapter.structuredAnswers ? { outputSchema: DESCRIBE_SCHEMA } : {}),
498
+ ...(adapter.spec.budget ? { maxBudgetUsd: 0.05 } : {}),
499
+ ...(this.structured ? { outputSchema: DESCRIBE_SCHEMA } : {}),
496
500
  onEvent: () => { },
497
501
  });
498
502
  }
@@ -501,7 +505,7 @@ export class Runner {
501
505
  }
502
506
  };
503
507
  // the light model where the runtime has one; a model the account cannot use falls back to the runtime's default
504
- const light = DESCRIBE_MODELS[adapter.name];
508
+ const light = adapter.spec.lightModel;
505
509
  let r = await run(light);
506
510
  if (!r.ok && light)
507
511
  r = await run(undefined);
@@ -541,12 +545,12 @@ export class Runner {
541
545
  if (!this.o.client.reportRunner)
542
546
  return;
543
547
  // the names and descriptions only, never the commands: teammates see them in the agent directory
544
- const capabilities = this.o.adapter.remote ? [] : loadCaps(this.o.capsFile ?? capsPath(this.o.home)).caps.map((c) => ({ name: c.name, description: c.description.slice(0, 300) }));
548
+ const capabilities = this.cloud ? [] : loadCaps(this.o.capsFile ?? capsPath(this.o.home)).caps.map((c) => ({ name: c.name, description: c.description.slice(0, 300) }));
545
549
  const sig = JSON.stringify(capabilities);
546
550
  if (this.runnerReported && sig === this.capsReported)
547
551
  return;
548
552
  const runtime = this.o.adapter.name;
549
- if (runtime !== 'claude' && runtime !== 'codex' && runtime !== 'kiro') {
553
+ if (!isRuntime(runtime)) {
550
554
  this.runnerReported = true;
551
555
  this.capsReported = sig;
552
556
  return;
@@ -850,7 +854,7 @@ export class Runner {
850
854
  /** Whether this runner reads new tasks ahead: a local runtime in a git checkout that delivers pull requests, and a hub that knows how. */
851
855
  readsAhead(me) {
852
856
  const { client, workspace, adapter } = this.o;
853
- return !!this.o.readAhead && !this.noReadAhead && me.role !== 'system' && !adapter.remote && !!workspace.deliverable && !!client.prepareRun && !!client.prepared;
857
+ return !!this.o.readAhead && !this.noReadAhead && me.role !== 'system' && !this.cloud && !!workspace.deliverable && !!client.prepareRun && !!client.prepared;
854
858
  }
855
859
  /**
856
860
  * The read-ahead (owner-pulls-tasks.md): a short read-only run on a task nobody took yet. It reports whether the task changes code,
@@ -1032,7 +1036,8 @@ export class Runner {
1032
1036
  channel: await this.channelContext(claim.task),
1033
1037
  wiki: claim.wiki,
1034
1038
  judgment: claim.judgment,
1035
- remote: !!this.o.adapter.remote,
1039
+ remote: !!this.cloud,
1040
+ report: !this.o.adapter.spec.ach,
1036
1041
  ...this.runContext(workdir),
1037
1042
  });
1038
1043
  this.reportPromptSize(taskId, rec.runId, prompt);
@@ -1116,7 +1121,8 @@ export class Runner {
1116
1121
  handoffChanged,
1117
1122
  files: files.filter((f) => !shown.has(f.key)).map(promptFile),
1118
1123
  nudge,
1119
- remote: !!this.o.adapter.remote,
1124
+ remote: !!this.cloud,
1125
+ report: !this.o.adapter.spec.ach,
1120
1126
  })
1121
1127
  : buildTaskPrompt({
1122
1128
  agentName: me.name,
@@ -1133,7 +1139,8 @@ export class Runner {
1133
1139
  channel: await this.channelContext(bundle.task),
1134
1140
  wiki: bundle.wiki,
1135
1141
  judgment: bundle.judgment,
1136
- remote: !!this.o.adapter.remote,
1142
+ remote: !!this.cloud,
1143
+ report: !this.o.adapter.spec.ach,
1137
1144
  ...this.runContext(rec.workdir),
1138
1145
  });
1139
1146
  if (!resume)
@@ -1321,9 +1328,15 @@ export class Runner {
1321
1328
  this.state.drop(taskId);
1322
1329
  return;
1323
1330
  }
1324
- // A remote (cloud sandbox) agent has no `ach`: its final message is the result, reported here.
1325
- if (this.o.adapter.remote && task.status === 'working') {
1331
+ // A run without `ach` (a cloud sandbox, a local tool that gets none): its final message is the result, reported here.
1332
+ if (!this.o.adapter.spec.ach && task.status === 'working') {
1326
1333
  await this.reportRemote(rec, result);
1334
+ // a run that worked here left its changes in the task's branch (committed above): now that the task is finished, deliver them
1335
+ if (!this.cloud) {
1336
+ const after = await client.getTask(taskId).catch(() => undefined);
1337
+ if (after)
1338
+ await this.deliverPr(rec, after.task, after.messages);
1339
+ }
1327
1340
  this.state.drop(taskId);
1328
1341
  return;
1329
1342
  }
@@ -1419,7 +1432,7 @@ export class Runner {
1419
1432
  const key = `mention-${mid}`;
1420
1433
  const threadId = run.thread.id;
1421
1434
  const rec = { taskId: key, runId, phase: 'running', workdir: this.o.dir, runToken: run.run_token, tokenAt: Date.now(), seen: [] };
1422
- const structured = !!this.o.adapter.structuredAnswers;
1435
+ const structured = !!this.structured;
1423
1436
  // how it went, told to the hub when the mention is closed: a run that ends with nothing said in the thread is made visible there
1424
1437
  let outcome = { ok: false, error: 'the run did not finish' };
1425
1438
  let recorded;
@@ -1434,6 +1447,7 @@ export class Runner {
1434
1447
  thread: run.thread,
1435
1448
  replies: run.replies ?? [],
1436
1449
  recent: run.recent ?? [],
1450
+ task: run.task,
1437
1451
  threadUrl: !this.o.publicUrl && typeof run.thread.url === 'string' && /^https?:\/\//.test(run.thread.url) ? run.thread.url : postUrl(this.base(), threadId),
1438
1452
  structured,
1439
1453
  });
@@ -1505,7 +1519,7 @@ export class Runner {
1505
1519
  const bundle = await this.o.client.getTask(taskId);
1506
1520
  const cwd = this.state.get(taskId)?.workdir ?? this.o.dir;
1507
1521
  const rec = { taskId, runId, phase: 'running', workdir: cwd, runToken: token, tokenAt: Date.now(), seen: [] };
1508
- const structured = !!this.o.adapter.structuredAnswers;
1522
+ const structured = !!this.structured;
1509
1523
  const prompt = buildAnswerPrompt({
1510
1524
  agentName: me.name,
1511
1525
  ownerName: me.owner_name,
@@ -1565,19 +1579,28 @@ export class Runner {
1565
1579
  ...(this.teamOwned() ? [] : [ownerMemoryDir(cwd, home)].filter((d) => !!d)),
1566
1580
  ];
1567
1581
  }
1582
+ /** The run works elsewhere (a cloud sandbox): nothing of this machine (files, memory, capabilities) reaches it. */
1583
+ get cloud() {
1584
+ return this.o.adapter.spec.where === 'cloud';
1585
+ }
1586
+ /** Short runs return JSON by a schema and the runner posts it: the runtime's way, and the only way without `ach` in the run. */
1587
+ get structured() {
1588
+ const spec = this.o.adapter.spec;
1589
+ return spec.structuredAnswers || !spec.ach;
1590
+ }
1568
1591
  /** Owned by no one person (the system agent, or a team agent such as one that does a channel mechanism for the team). */
1569
1592
  teamOwned() {
1570
1593
  return this.me?.kind === 'team';
1571
1594
  }
1572
1595
  /** What a full task prompt carries besides the task: the owner's memory for this project and the project's instructions. */
1573
1596
  runContext(workdir) {
1574
- if (this.o.adapter.remote)
1597
+ if (this.cloud)
1575
1598
  return { project: [] };
1576
1599
  // a team agent (the system agent too) works for the team: no person's memory, whatever machine it runs on (docs/mechanisms.md)
1577
1600
  const dir = this.teamOwned() ? undefined : ownerMemoryDir(workdir, realHomeOf(this.o.baseEnv ?? process.env));
1578
1601
  // Claude Code shows the index itself (it keys memory by the repository); other runtimes get it in the prompt
1579
- const ownerMemory = dir ? { dir, ...(this.o.adapter.name === 'claude' ? {} : { index: memoryIndex(dir) }) } : undefined;
1580
- return { ownerMemory, project: projectInstructions(workdir, this.o.adapter.name) };
1602
+ const ownerMemory = dir ? { dir, ...(this.o.adapter.spec.ownerMemory === 'native' ? {} : { index: memoryIndex(dir) }) } : undefined;
1603
+ return { ownerMemory, project: projectInstructions(workdir, this.o.adapter.spec.ownFiles) };
1581
1604
  }
1582
1605
  /** Where a task's attachments are downloaded for its agents (readable, outside the worktree). */
1583
1606
  filesDir(taskId) {
@@ -1748,7 +1771,13 @@ export class Runner {
1748
1771
  });
1749
1772
  let m = model;
1750
1773
  let ef = effort;
1751
- result = await go(m, ef);
1774
+ // fail closed (docs/specs/runtimes.md §4): what the tool cannot enforce for this run is not allowed to happen
1775
+ const refused = runRefusal(this.o.adapter.spec, { perm, ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}) });
1776
+ if (refused) {
1777
+ recorder.event({ type: 'error', data: `not run: ${refused}` });
1778
+ this.taskLog(taskId, `not run: ${refused}`);
1779
+ }
1780
+ result = refused ? { ok: false, finalText: '', error: `not run: ${refused}` } : await go(m, ef);
1752
1781
  // the runtime's program was not there: most often another ach on this machine is installing a new release into the npx
1753
1782
  // cache they share, which takes seconds. Once more after a wait; only a second miss reaches the hub as a broken install.
1754
1783
  if (!result.ok && !toolsRan && !entry.controller.signal.aborted && programMissing(result.error)) {
@@ -1816,7 +1845,7 @@ export class Runner {
1816
1845
  }
1817
1846
  /** decisions §34: the capabilities server of one run, or undefined when nothing is declared (or the run is in the cloud). */
1818
1847
  capsFor(taskId, runId, realHome, tmpDir) {
1819
- if (this.o.adapter.remote)
1848
+ if (this.cloud)
1820
1849
  return undefined;
1821
1850
  const file = this.o.capsFile ?? capsPath(this.o.home);
1822
1851
  const { caps, problems } = loadCaps(file);
@@ -1932,10 +1961,6 @@ function promptFile(f) {
1932
1961
  }
1933
1962
  /** The light model that writes an agent's description, per runtime (none listed: the runtime's default). A runtime that does not
1934
1963
  * take it runs the default instead. */
1935
- const DESCRIBE_MODELS = {
1936
- claude: { model: 'claude-haiku-5-5', effort: 'low' },
1937
- codex: { model: 'gpt-6.1-sol', effort: 'medium' },
1938
- };
1939
1964
  const DESCRIBE_SCHEMA = { type: 'object', properties: { description: { type: 'string' } }, required: ['description'], additionalProperties: false };
1940
1965
  function describePrompt(name, dirs) {
1941
1966
  const where = dirs.map(([n, d]) => `- ${n}: ${d}`).join('\n');
@@ -0,0 +1,26 @@
1
+ import { RUNTIME_SPECS, type RuntimeName } from './adapters/spec.js';
2
+ import type { SandboxStatus } from './sandboxcheck.js';
3
+ /**
4
+ * What a runtime needs on this machine before its runner takes a task (docs/specs/runtimes.md, `check`): for a tool with a
5
+ * local sandbox, its login and a real sandbox probe; for any other, the runtime's own probe (binary, version, key).
6
+ */
7
+ export interface ToolCheck {
8
+ /** The tool is on this machine (doctor then checks it even when the agent's runtime is another one). */
9
+ installed(env: NodeJS.ProcessEnv): Promise<boolean>;
10
+ probe(o: {
11
+ env: NodeJS.ProcessEnv;
12
+ }): Promise<SandboxStatus>;
13
+ }
14
+ type ToolRuntime = {
15
+ [K in RuntimeName]: (typeof RUNTIME_SPECS)[K]['check'] extends 'tool' ? K : never;
16
+ }[RuntimeName];
17
+ /** The probes of the runtimes whose spec says `check: 'tool'`: one entry each (a missing one does not compile). */
18
+ export declare const TOOL_CHECKS: Record<ToolRuntime, ToolCheck>;
19
+ export declare const toolCheck: (name: string) => ToolCheck | undefined;
20
+ /** The machine check `ach run` does when it starts, and again while a problem lasts. */
21
+ export declare function probeRuntime(name: RuntimeName, o: {
22
+ env: NodeJS.ProcessEnv;
23
+ hub?: string;
24
+ runEnv?: NodeJS.ProcessEnv;
25
+ }): Promise<SandboxStatus>;
26
+ export {};
@@ -0,0 +1,20 @@
1
+ /** The probes of the runtimes whose spec says `check: 'tool'`: one entry each (a missing one does not compile). */
2
+ export const TOOL_CHECKS = {
3
+ kiro: {
4
+ installed: async (env) => !!(await import('./kirocheck.js')).kiroBin(env),
5
+ probe: async (o) => (await import('./kirocheck.js')).probeKiro(o),
6
+ },
7
+ antigravity: {
8
+ installed: async (env) => !!(await import('./agycheck.js')).agyPathOf(env),
9
+ probe: async (o) => (await import('./agycheck.js')).probeAgy(o),
10
+ },
11
+ };
12
+ export const toolCheck = (name) => (Object.hasOwn(TOOL_CHECKS, name) ? TOOL_CHECKS[name] : undefined);
13
+ /** The machine check `ach run` does when it starts, and again while a problem lasts. */
14
+ export async function probeRuntime(name, o) {
15
+ const tool = toolCheck(name);
16
+ if (tool)
17
+ return tool.probe({ env: o.env });
18
+ const { probeEnvironment } = await import('./envcheck.js');
19
+ return probeEnvironment(name, o);
20
+ }
@@ -39,7 +39,8 @@ export interface SandboxFix {
39
39
  commands: string[];
40
40
  }
41
41
  export interface SandboxStatus {
42
- tool: SandboxTool | 'kiro';
42
+ /** the runtime's name (adapters/spec.ts) */
43
+ tool: string;
43
44
  ok: boolean;
44
45
  /** ok, but the probe could not run (an older Codex without `codex sandbox`): not blocking, doctor warns. */
45
46
  unverified?: boolean;
@@ -1,4 +1,5 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { runtimeLabel, runtimeSpec } from './adapters/spec.js';
2
3
  import { randomBytes } from 'node:crypto';
3
4
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
5
  import { createRequire } from 'node:module';
@@ -361,7 +362,11 @@ export const BWRAP_APPARMOR = `printf '%s\\n' 'abi <abi/4.0>,' 'include <tunable
361
362
  `| sudo tee /etc/apparmor.d/bwrap >/dev/null && sudo apparmor_parser -r /etc/apparmor.d/bwrap`;
362
363
  /** The fix for a failed probe on this host. */
363
364
  export function sandboxFix(st, host) {
364
- const name = st.tool === 'claude' ? 'Claude Code' : st.tool === 'kiro' ? 'Kiro' : 'Codex';
365
+ const name = runtimeLabel(st.tool);
366
+ // how this tool is logged in (its spec): a command a person runs, or a key in the runner's environment
367
+ const login = runtimeSpec(st.tool)?.login;
368
+ const cmd = login && 'command' in login ? login.command : undefined;
369
+ const key = login && 'key' in login ? login.key : undefined;
365
370
  // the Codex package came without its platform binary (an optional dependency npm skipped): runs cannot start either
366
371
  if (st.tool === 'codex' && /Missing optional dependency @openai\/codex-/i.test(st.detail ?? '')) {
367
372
  const cmd = 'npm install -g @koalaauto/agentchannel@latest';
@@ -393,15 +398,15 @@ export function sandboxFix(st, host) {
393
398
  }
394
399
  switch (st.problem) {
395
400
  case 'not-logged-in': {
396
- const cmd = st.tool === 'claude' ? 'claude auth login' : 'codex login';
401
+ if (!cmd)
402
+ return { en: `${name} is not logged in on this machine${key ? `: set ${key} in the runner's environment` : ''}.`, zh: `${name} 在这台机器上没有登录${key ? `:在 runner 的环境变量里设置 ${key}` : ''}。`, commands: [] };
397
403
  return { en: `${name} is not logged in on this machine: run \`${cmd}\` as the user that runs this agent.`, zh: `${name} 在这台机器上没有登录:以运行这个智能体的用户身份执行 \`${cmd}\`。`, commands: [cmd] };
398
404
  }
399
405
  case 'billing': {
400
406
  const en = `The account ${name} uses on this machine cannot run: its plan or credit is not usable (a payment past due, no credit left).`;
401
407
  const zh = `这台机器上 ${name} 用的账号用不了:订阅或余额不可用(付款逾期、余额用完)。`;
402
- if (st.tool === 'kiro')
403
- return { en: `${en} Renew it, or set another KIRO_API_KEY.`, zh: `${zh}续费,或换一个 KIRO_API_KEY。`, commands: [] };
404
- const cmd = st.tool === 'claude' ? 'claude auth login' : 'codex login';
408
+ if (!cmd)
409
+ return { en: `${en} Renew it${key ? `, or set another ${key}` : ''}.`, zh: `${zh}续费${key ? `,或换一个 ${key}` : ''}。`, commands: [] };
405
410
  return {
406
411
  en: `${en} Renew it, or log in with another account: run \`${cmd}\` as the user that runs this agent.`,
407
412
  zh: `${zh}续费,或换一个账号:以运行这个智能体的用户身份执行 \`${cmd}\`。`,
@@ -52,6 +52,11 @@ export type InstallKind =
52
52
  kind: 'global';
53
53
  dir: string;
54
54
  }
55
+ /** The install in the AgentChannel home (appinstall.ts): a release per dir under `dir`, the launcher starts `current`. */
56
+ | {
57
+ kind: 'app';
58
+ dir: string;
59
+ }
55
60
  /** Source checkout, `npm link`, a project dependency, or anything else: not ours to replace. */
56
61
  | {
57
62
  kind: 'other';
@@ -62,6 +67,7 @@ export declare function detectInstall(o?: {
62
67
  self?: string;
63
68
  exec?: ExecFn;
64
69
  version?: string;
70
+ app?: string;
65
71
  }): Promise<InstallKind>;
66
72
  /**
67
73
  * Before the runner stops taking work: the release exists on npm, and a global install can be written. Nothing has been paused or
@@ -99,6 +105,8 @@ export type CheckResult = 'none' | 'manual' | 'off' | 'backoff' | 'busy' | 'fail
99
105
  export interface SelfUpdaterOptions {
100
106
  fetchVersions: () => Promise<HubVersions | null>;
101
107
  platform?: NodeJS.Platform;
108
+ /** The install in the AgentChannel home (default appDir()); tests point it elsewhere. */
109
+ app?: string;
102
110
  /** Windows: starts the helper that installs after this runner exited (default startWindowsUpdate). */
103
111
  handoff?: (target: string, dir: string) => boolean;
104
112
  runner: Quiescable;
@@ -220,12 +228,13 @@ export declare function markHealthy(home: string, version?: string): void;
220
228
  /**
221
229
  * Called first thing when `ach run` starts. A release this runner updated itself to, that has started BOOT_LIMIT times within
222
230
  * ten minutes without once becoming healthy, is marked bad here and the release before it is installed again (a global install;
223
- * an npx install has nothing to go back to and only marks it). Returns what it did; 'rolledback' means: exit UPDATE_EXIT_CODE.
231
+ * the install in the AgentChannel home points its launcher back; an npx install has nothing to go back to and only marks it). Returns what it did; 'rolledback' means: exit UPDATE_EXIT_CODE.
224
232
  */
225
233
  export declare function bootGuard(home: string, o?: {
226
234
  version?: string;
227
235
  exec?: ExecFn;
228
236
  self?: string;
237
+ app?: string;
229
238
  now?: () => number;
230
239
  log?: (s: string) => void;
231
240
  }): Promise<'ok' | 'rolledback' | 'marked'>;