@koalaauto/agentchannel 3.84.0 → 3.85.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.
@@ -61,13 +61,12 @@ export async function runCommand(p, io) {
61
61
  return 1;
62
62
  }
63
63
  if (!(await waitForKey(io, r.message))) {
64
- markStopped(achHome(env0(io))); // stopped by a person while it waited: the watchdog leaves it stopped
64
+ markStopped(achHome(io.env)); // stopped by a person while it waited: the watchdog leaves it stopped
65
65
  return 0;
66
66
  }
67
67
  io.err('ach run: the hub accepts the key; starting again');
68
68
  }
69
69
  }
70
- const env0 = (io) => io.env;
71
70
  /** Why runOnce stopped: no key here, or the hub refused it (401). */
72
71
  class KeyRefused {
73
72
  message;
package/dist/src/cli.js CHANGED
@@ -24,7 +24,7 @@ export { KEY_RETRY_MS, NO_KEY_MESSAGE, waitForKey, writeAchShim } from './cli-ru
24
24
  // moved to cli-shared.ts; still reachable from here for the code and tests that import them from cli.js
25
25
  export { channelFile, loginTokenOf } from './cli-shared.js';
26
26
  /** Why a task failed (docs/specs/task-failures.md); the hub's list. */
27
- const FAIL_CAUSES = ['secret', 'network', 'permission', 'workspace', 'quota', 'runtime', 'task', 'other'];
27
+ const FAIL_CAUSES = ['secret', 'network', 'permission', 'workspace', 'access', 'quota', 'runtime', 'task', 'other'];
28
28
  const defaultIo = () => ({
29
29
  env: process.env,
30
30
  out: (s) => process.stdout.write(s + '\n'),
@@ -1020,6 +1020,10 @@ async function dispatch(p, io) {
1020
1020
  const r = await pool.tick();
1021
1021
  if (r.started.length || r.stopped.length)
1022
1022
  io.err(`pool ${name}: started ${r.started.join(', ') || 'none'}; stopped ${r.stopped.join(', ') || 'none'}; running ${pool.running.size}`);
1023
+ if (pool.restartDue) {
1024
+ io.err(`pool ${name}: every runner has exited; restarting on ${pool.restartDue}`);
1025
+ return (await import('./selfupdate.js')).UPDATE_EXIT_CODE;
1026
+ }
1023
1027
  }
1024
1028
  catch (e) {
1025
1029
  io.err(`pool ${name}: the hub did not answer (${e?.message ?? e}); the runners keep going`);
@@ -526,7 +526,17 @@ export class Client {
526
526
  }
527
527
  /** `cause` / `needs`: why, for the owner (docs/specs/task-failures.md); omitted, the hub works it out from the reason. */
528
528
  async fail(taskId, reason, run_id, owner_action, why) {
529
- return this.ach('POST', `/tasks/${enc(taskId)}/fail`, { reason, ...(run_id ? { run_id } : {}), ...(owner_action ? { owner_action } : {}), ...(why?.cause ? { cause: why.cause } : {}), ...(why?.needs ? { needs: why.needs } : {}) });
529
+ const send = (cause) => this.ach('POST', `/tasks/${enc(taskId)}/fail`, { reason, ...(run_id ? { run_id } : {}), ...(owner_action ? { owner_action } : {}), ...(cause ? { cause } : {}), ...(why?.needs ? { needs: why.needs } : {}) });
530
+ try {
531
+ return await send(why?.cause);
532
+ }
533
+ catch (e) {
534
+ // a hub older than this client does not know the cause (`access`, 2026-11-24): the failure must still be recorded, so it
535
+ // goes without one and the hub works the cause out from the reason
536
+ if (why?.cause && e instanceof HubError && e.status === 400 && /cause must be one of/.test(e.message))
537
+ return send();
538
+ throw e;
539
+ }
530
540
  }
531
541
  async cancel(taskId, reason) {
532
542
  return this.ach('POST', `/tasks/${enc(taskId)}/cancel`, { reason });
package/dist/src/mcp.js CHANGED
@@ -420,12 +420,12 @@ export function buildMcpServer(client, o = {}) {
420
420
  inputSchema: { task_id: z.string(), what: z.string().describe('What is wrong and what to change') },
421
421
  }, async (a) => wrap(async () => client.requestChanges(a.task_id, a.what).then(() => `sent ${a.task_id} back to its worker`)));
422
422
  server.registerTool('fail_task', {
423
- description: 'Give up on a task you claimed with claim_task, or decline a task sent to you that nobody claimed yet, with the reason. A failure always reaches your owner; if it needs them to do something (log in, install a tool), say it in owner_action. cause says what kind of thing stopped it: secret, network, permission, workspace and quota only your owner can fix (one Inbox item for them however often it fails that way), task when the task itself is wrong.',
423
+ description: 'Give up on a task you claimed with claim_task, or decline a task sent to you that nobody claimed yet, with the reason. A failure always reaches your owner; if it needs them to do something (log in, install a tool), say it in owner_action. cause says what kind of thing stopped it: secret, network, permission, workspace, access (a system outside the repository this run could not read: production logs, a database) and quota only your owner can fix (one Inbox item for them however often it fails that way), task when the task itself is wrong.',
424
424
  inputSchema: {
425
425
  task_id: z.string(),
426
426
  reason: z.string(),
427
427
  owner_action: z.string().optional().describe('What your owner must do, in one or two sentences'),
428
- cause: z.enum(['secret', 'network', 'permission', 'workspace', 'quota', 'runtime', 'task', 'other']).optional().describe('Why: omitted, the hub works it out from the reason'),
428
+ cause: z.enum(['secret', 'network', 'permission', 'workspace', 'access', 'quota', 'runtime', 'task', 'other']).optional().describe('Why: omitted, the hub works it out from the reason'),
429
429
  needs: z.string().optional().describe('What exactly is missing: a variable name, a host, a repo, a permission (a few words)'),
430
430
  },
431
431
  }, async (a) => wrap(async () => {
@@ -18,10 +18,17 @@ export interface PoolOptions {
18
18
  cfSecret?: string;
19
19
  env: NodeJS.ProcessEnv;
20
20
  log: (s: string) => void;
21
- /** tests: start a runner (default: this CLI's `run`) */
21
+ /** tests: start a runner (default: `run` of the release the install names, else of this CLI) */
22
22
  start?: (a: PoolAgent, home: string, dir: string, env: NodeJS.ProcessEnv) => PoolChild;
23
+ /** this pool's release and the one the install starts now; both undefined when the pool does not run from the install */
24
+ releases?: () => {
25
+ mine?: string;
26
+ current?: string;
27
+ };
23
28
  now?: () => number;
24
29
  }
30
+ /** How long a pool on an old release waits for its runners to exit by themselves before it stops the rest. */
31
+ export declare const MOVE_WAIT_MS: number;
25
32
  export interface PoolChild {
26
33
  /** set once it has exited */
27
34
  exited?: {
@@ -50,7 +57,12 @@ export declare class Pool {
50
57
  readonly running: Map<string, Running>;
51
58
  /** when a runner that exited may be started again, and how often it has in a row */
52
59
  private retry;
60
+ /** set once the install names another release and no runner is left: the pool should exit so that its service restarts it */
61
+ restartDue?: string;
62
+ /** when the pool saw that the install names another release than its own */
63
+ private movedAt?;
53
64
  private start;
65
+ private releases;
54
66
  private now;
55
67
  constructor(o: PoolOptions, hub: PoolHub);
56
68
  /** One round: what the hub says is in the pool is what runs. Returns what changed (for the log, and the tests). */
@@ -59,6 +71,11 @@ export declare class Pool {
59
71
  stopped: string[];
60
72
  failed: string[];
61
73
  }>;
74
+ /**
75
+ * The install names another release than the pool's: start nothing, let each runner exit by itself (it updates, finishing its
76
+ * runs first), and once none is left say that the pool should restart. One that has not exited after MOVE_WAIT_MS is stopped.
77
+ */
78
+ private moving;
62
79
  stop(): void;
63
80
  }
64
81
  export {};
package/dist/src/pool.js CHANGED
@@ -4,13 +4,21 @@
4
4
  // hub which agents are in the pool, gives each a home and a directory of its own, takes that agent's key once, and keeps an
5
5
  // ordinary `ach run` going for it (the same runner a person starts by hand: nothing about a run is different here). An agent
6
6
  // that leaves the pool has its runner stopped; one whose repositories changed has it restarted.
7
+ //
8
+ // Releases (2026-11-24: every cloud workspace sat on 3.67.0 for a day while 17 releases went by): the runners are started through
9
+ // the install's launcher, so a runner that updated itself (it installs, sets `current`, exits) comes back on the new release. The
10
+ // pool itself moves with them: once `current` names another release than its own, it starts no runner again, and when the last
11
+ // one has exited (each finishes its runs first) it exits too, so that its service starts it on the new release.
7
12
  import { spawn } from 'node:child_process';
8
13
  import { chmodSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
9
14
  import { dirname, join } from 'node:path';
10
15
  import { fileURLToPath } from 'node:url';
16
+ import { appDir, appVersionOf, currentVersion, inApp, launcherPath } from './appinstall.js';
11
17
  import { cfSecretPath, keyFilePath } from './keystore.js';
12
18
  /** The CLI's entry (dist/src/cli.js, next to this file). */
13
19
  const CLI_JS = join(dirname(fileURLToPath(import.meta.url)), 'cli.js');
20
+ /** How long a pool on an old release waits for its runners to exit by themselves before it stops the rest. */
21
+ export const MOVE_WAIT_MS = 30 * 60_000;
14
22
  const safe = (name) => name.replace(/[^A-Za-z0-9-]/g, '-');
15
23
  export const agentHomeIn = (base, a) => join(base, 'homes', safe(a.name));
16
24
  export const agentDirIn = (base, a) => join(base, 'work', safe(a.name));
@@ -36,9 +44,19 @@ export async function ensureHome(o, a, hub) {
36
44
  secret(keyFilePath(home), key);
37
45
  return { home, dir, made: true };
38
46
  }
47
+ /** What starts a runner: the install's launcher when this pool runs from the install (a runner then starts on `current`), else this CLI. */
48
+ function entry() {
49
+ const app = appDir();
50
+ return inApp(CLI_JS, app) && existsSync(launcherPath(app)) ? launcherPath(app) : CLI_JS;
51
+ }
52
+ /** This pool's release and the install's `current`, when the pool runs from the install. */
53
+ function appReleases() {
54
+ const app = appDir();
55
+ return inApp(CLI_JS, app) ? { mine: appVersionOf(CLI_JS, app), current: currentVersion(app) } : {};
56
+ }
39
57
  function startRunner(name, log) {
40
58
  return (a, home, dir, env) => {
41
- const proc = spawn(process.execPath, [CLI_JS, 'run', '--dir', dir, '--runtime', name, '--max', '1'], { env, stdio: ['ignore', 'pipe', 'pipe'] });
59
+ const proc = spawn(process.execPath, [entry(), 'run', '--dir', dir, '--runtime', name, '--max', '1'], { env, stdio: ['ignore', 'pipe', 'pipe'] });
42
60
  const child = { stop: () => { try {
43
61
  proc.kill('SIGTERM');
44
62
  }
@@ -60,17 +78,25 @@ export class Pool {
60
78
  running = new Map();
61
79
  /** when a runner that exited may be started again, and how often it has in a row */
62
80
  retry = new Map();
81
+ /** set once the install names another release and no runner is left: the pool should exit so that its service restarts it */
82
+ restartDue;
83
+ /** when the pool saw that the install names another release than its own */
84
+ movedAt;
63
85
  start;
86
+ releases;
64
87
  now;
65
88
  constructor(o, hub) {
66
89
  this.o = o;
67
90
  this.hub = hub;
68
91
  this.start = o.start ?? startRunner(o.name, o.log);
92
+ this.releases = o.releases ?? appReleases;
69
93
  this.now = o.now ?? Date.now;
70
94
  }
71
95
  /** One round: what the hub says is in the pool is what runs. Returns what changed (for the log, and the tests). */
72
96
  async tick() {
73
97
  const out = { started: [], stopped: [], failed: [] };
98
+ if (this.moving(out))
99
+ return out;
74
100
  const agents = await this.hub.agents();
75
101
  const want = new Map(agents.map((a) => [a.id, a]));
76
102
  for (const [id, r] of this.running) {
@@ -114,6 +140,34 @@ export class Pool {
114
140
  this.retry.delete(id);
115
141
  return out;
116
142
  }
143
+ /**
144
+ * The install names another release than the pool's: start nothing, let each runner exit by itself (it updates, finishing its
145
+ * runs first), and once none is left say that the pool should restart. One that has not exited after MOVE_WAIT_MS is stopped.
146
+ */
147
+ moving(out) {
148
+ const { mine, current } = this.releases();
149
+ if (!mine || !current || mine === current) {
150
+ this.movedAt = undefined;
151
+ return false;
152
+ }
153
+ if (this.movedAt === undefined) {
154
+ this.movedAt = this.now();
155
+ this.o.log(`the install starts ${current} now (this pool is ${mine}): no runner is started again; the pool restarts once they have exited`);
156
+ }
157
+ const late = this.now() - this.movedAt > MOVE_WAIT_MS;
158
+ for (const [id, r] of this.running) {
159
+ if (r.child.exited)
160
+ this.running.delete(id);
161
+ else if (late) {
162
+ r.child.stop();
163
+ this.running.delete(id);
164
+ out.stopped.push(r.agent.name);
165
+ }
166
+ }
167
+ if (!this.running.size)
168
+ this.restartDue = current;
169
+ return true;
170
+ }
117
171
  stop() {
118
172
  for (const r of this.running.values())
119
173
  r.child.stop();
@@ -305,4 +305,9 @@ export declare function buildMentionPrompt(c: {
305
305
  judgment?: Judgment;
306
306
  /** tasks the thread names, read by the runner for a structured run (runner/linked-tasks.ts) */
307
307
  tasks?: LinkedTask[];
308
+ /** This run continues the agent's earlier session in this thread: the posts that session was shown, and when its last run began. */
309
+ since?: {
310
+ seen: string[];
311
+ at?: string;
312
+ };
308
313
  }): string;
@@ -47,7 +47,7 @@ export const JUDGMENT = [
47
47
  'How to decide (AgentChannel\'s default for every agent):',
48
48
  '- 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.',
49
49
  '- Ask an agent, not a person, when what is missing is information or work that belongs to another agent: `ach ask` the sender. If the task belongs to another agent or repository, `ach fail --cause task` and name who should do it.',
50
- '- Ask a person only for: something you do not have (a secret, a permission, network access, money): `ach fail --cause … --needs …`, or `--owner-action` for a step they can do; an irreversible or outside step (production, merging to main, deleting, paying, contacting someone outside): `ach ask-human`; a choice of direction (priorities, who owns what, whether the requirement is right): `ach ask-human`; the same thing failing again.',
50
+ '- Ask a person only for: something you do not have (a secret, a permission, network access, access to an outside system, money): `ach fail --cause … --needs …`, or `--owner-action` for a step they can do; an irreversible or outside step (production, merging to main, deleting, paying, contacting someone outside): `ach ask-human`; a choice of direction (priorities, who owns what, whether the requirement is right): `ach ask-human`; the same thing failing again.',
51
51
  '- When you ask a person, say which of these it is ("a person decides: irreversible").',
52
52
  '- 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 `ach progress`.',
53
53
  "- Never copy what your owner's notes say about secrets, accounts, machines or people into results, messages or files that others read.",
@@ -340,7 +340,7 @@ function rules(review) {
340
340
  ' - `ach withdraw <message-id>` closes your own open question or request that no longer stands; do it whenever you re-ask the same thing elsewhere.',
341
341
  ' - A person\'s decision on this task (to your request or to the sender\'s) is their answer: when it settles what you were waiting for, never ask it again or wait for a second answer. When it says the work is not to be done (declined, not now), the task has its outcome: stop there and `ach complete` with a result that quotes the decision and says nothing was built, never `ach fail` (fail is for work that could not be done), even when the handoff says not to complete without approval.',
342
342
  ' - `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.',
343
- ' - `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).',
343
+ ' - `ach fail "<reason>" --cause <secret|network|permission|workspace|access|quota|task|other> [--needs "<what is missing>"]` if it cannot be done. The cause tells your owner what to fix: secret, network, permission, workspace, access and quota only they can (say exactly what is missing in --needs: a variable name, a host, a repo); access when you cannot read a system outside this repository that the task needs (production logs, a database: name it); task when the task itself is wrong (name the agent or repository that should do it).',
344
344
  completeRule(review),
345
345
  ' - To share files, add `--attach <file>` (repeatable; images png/jpg/webp/gif, videos mp4/webm/mov, text/code up to 2 MB such as .md .log .diff .json .ts .py; files in this directory) to `ach progress`, `ach ask`, `ach ask-human` or `ach complete`.',
346
346
  ' - A report with charts or a prototype: `ach artifact publish <file.html> --title "<t>"`, then name its A-12 in your result (`--artifact A-12` updates it).',
@@ -587,8 +587,15 @@ export function buildPreparePrompt(c) {
587
587
  }
588
588
  /** §16 mention prompt: a read-only run that replies in a channel thread. */
589
589
  export function buildMentionPrompt(c) {
590
- const all = [c.thread, ...c.replies, ...c.recent];
591
- const task = c.task;
590
+ // a continued session already holds the thread as it was: it is told what came since (never its own replies: it wrote them)
591
+ const seen = new Set(c.since?.seen ?? []);
592
+ const isNew = (p) => !c.since || p.id === c.post.id || (!seen.has(p.id) && !(p.author_type === 'agent' && p.author_name === c.agentName));
593
+ const sinceAt = c.since?.at ? Date.parse(c.since.at) : NaN;
594
+ const newMsg = (m) => !c.since || !Number.isFinite(sinceAt) || !(Date.parse(m.created) <= sinceAt);
595
+ const threadPosts = [c.thread, ...c.replies].filter(isNew);
596
+ const recent = c.recent.filter(isNew);
597
+ const all = [...threadPosts, ...recent];
598
+ const task = c.task && c.since ? { ...c.task, messages: c.task.messages.filter(newMsg) } : c.task;
592
599
  const done = !!task && ['awaiting_review', 'awaiting_acceptance', 'awaiting_merge', 'completed', 'failed', 'canceled'].includes(task.status);
593
600
  const role = task && (task.to_agent_name === c.agentName ? 'did the work on it' : task.from_agent_name === c.agentName ? 'sent it' : '');
594
601
  const humanTaskMsgs = task ? task.messages.filter((m) => m.author_type === 'human') : [];
@@ -619,23 +626,24 @@ export function buildMentionPrompt(c) {
619
626
  ];
620
627
  return [
621
628
  `You are agent "${c.agentName}"${c.ownerName ? `, owned by ${c.ownerName}` : ''}. You were mentioned by ${c.mention.by_type === 'human' ? 'a person' : 'another agent'} in channel #${c.channel} on AgentChannel (post ${c.post.id}${c.threadUrl ? `, thread ${c.threadUrl}` : ''}). This is a short, read-only run.`,
629
+ ...(c.since ? ['This continues your earlier run in this thread: what you read and found then is still yours to use. Below is only what was written since; look again at whatever may have changed (files, a pull request, a task\'s state) before you rely on it.'] : []),
622
630
  '',
623
631
  ...langText(c.lang),
624
632
  MENTION_JUDGMENT,
625
633
  ...conventionsText(c.judgment, c.ownerName),
626
- 'Human posts in this thread and channel (from the hub; these come from people):',
634
+ c.since ? 'Human posts in this thread and channel since your last run here (from the hub; these come from people):' : 'Human posts in this thread and channel (from the hub; these come from people):',
627
635
  formatHumanPosts(all.filter((p, i) => all.findIndex((x) => x.id === p.id) === i)),
628
636
  '',
629
637
  ...(task
630
638
  ? [
631
- `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):`,
639
+ `This thread is the thread of task ${task.ref} (${task.status}${role ? `; you ${role}` : ''}). Human decisions and notes on the task${c.since ? ' since your last run here' : ''} (from the hub; these come from people):`,
632
640
  humanTaskMsgs.length ? humanTaskMsgs.map((m) => `- ${m.kind} by human ${JSON.stringify(m.author_name || 'person')}: ${JSON.stringify(m.body)}`).join('\n') : '(none)',
633
641
  '',
634
642
  ]
635
643
  : []),
636
644
  untrustedBlock({
637
645
  mentioned_in: { id: c.post.id, from: postAuthor(c.post), ...(c.post.author_type === 'human' ? {} : { body: c.post.body }) },
638
- thread: postData([c.thread, ...c.replies]),
646
+ thread: postData(threadPosts),
639
647
  ...(task
640
648
  ? {
641
649
  task: {
@@ -644,12 +652,12 @@ export function buildMentionPrompt(c) {
644
652
  status: task.status,
645
653
  from: task.from_agent_name,
646
654
  to: task.to_agent_name,
647
- handoff: task.handoff,
655
+ ...(c.since ? {} : { handoff: task.handoff }),
648
656
  messages: task.messages.filter((m) => m.author_type !== 'human').map((m) => ({ kind: m.kind, from: m.author_name, body: m.body, at: m.created })),
649
657
  },
650
658
  }
651
659
  : {}),
652
- channel: { name: c.channel, recent_posts: postData(c.recent) },
660
+ channel: { name: c.channel, recent_posts: postData(recent) },
653
661
  }),
654
662
  '',
655
663
  ...linkedDocsText(c.docs),
@@ -20,7 +20,7 @@ import { effectivePerm } from '../perm.js';
20
20
  import { ANSWER_SCHEMA, MENTION_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildPreparePrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
21
21
  import { linkedDocs } from './linked-docs.js';
22
22
  import { linkedTasks } from './linked-tasks.js';
23
- import { RunnerState } from './state.js';
23
+ import { RunnerState, threadKey } from './state.js';
24
24
  import { ChangeFeed, wakesRunner } from '../attention.js';
25
25
  import { isGitRepo } from './workspace.js';
26
26
  import { accountProblem, effortRejected, looksLikeLoginError, modelRejected, programMissing, summarizeRuntimeError } from '../envcheck.js';
@@ -49,6 +49,10 @@ export function jobKey(j) {
49
49
  return `mention:${j.item.mention.id}`;
50
50
  return j.kind === 'answer' ? `answer:${j.question.id}` : `task:${j.taskId}`;
51
51
  }
52
+ /** How many post ids a thread's session remembers having been shown (the newest; an older one shown again costs a few lines). */
53
+ const THREAD_SEEN_MAX = 400;
54
+ /** The thread a mention job answers in ('' for any other job). */
55
+ const threadOf = (j) => (j.kind === 'mention' ? String(j.item.mention.thread || j.item.thread?.id || '') : '');
52
56
  /** What the hub is told about a mention run that ended: whether it worked, why not, its last words, the commands that failed. */
53
57
  /**
54
58
  * The flags of an `ach reply` that failed (refused, or the hub said no): `--escalate`, `--to`, `--ask`, `--evidence`, read from the
@@ -794,6 +798,9 @@ export class Runner {
794
798
  delete this.state.runs.handledQuestions[q];
795
799
  }
796
800
  this.state.pruneTasks(dead);
801
+ // a thread nobody mentioned this agent in for a week: its session and its scratch HOME go (the next mention starts over)
802
+ // (never one a run is in right now: its HOME is that run's)
803
+ dead.push(...this.state.pruneThreads(now, new Set([...this.active.values()].map((a) => threadOf(a.job)).filter(Boolean).map(threadKey))));
797
804
  for (const id of dead) {
798
805
  removeQuietly(this.filesDir(id));
799
806
  // the task's scratch HOME (caches, a Codex session) is not needed once the task has ended
@@ -815,7 +822,12 @@ export class Runner {
815
822
  }
816
823
  pump() {
817
824
  while (!this.stopped && this.active.size < this.o.max && this.queue.length) {
818
- const job = this.queue.shift();
825
+ // the mention runs of one thread are one session, so they run one after the other: the second continues what the first read
826
+ const busy = new Set([...this.active.values()].map((a) => threadOf(a.job)).filter(Boolean));
827
+ const at = this.queue.findIndex((j) => !busy.has(threadOf(j)));
828
+ if (at < 0)
829
+ break;
830
+ const job = this.queue.splice(at, 1)[0];
819
831
  const controller = new AbortController();
820
832
  const entry = { job, controller, done: Promise.resolve() };
821
833
  this.active.set(jobKey(job), entry);
@@ -1517,6 +1529,13 @@ export class Runner {
1517
1529
  const threadId = run.thread.id;
1518
1530
  const rec = { taskId: key, runId, phase: 'running', workdir: this.o.dir, runToken: run.run_token, tokenAt: Date.now(), seen: [] };
1519
1531
  const structured = !!this.structured;
1532
+ // the agent's runs in one thread are one session: a later mention there continues it and is shown only what is new, instead
1533
+ // of reading the thread, the files and the history again (2026-11: over half the mentions were in a thread the agent had
1534
+ // already answered in). Kept on this machine, for this directory; a thread idle for a week starts over.
1535
+ const sessKey = threadKey(threadId);
1536
+ const sess = this.state.session(sessKey, 'mention');
1537
+ const resume = sess && sess.cwd === this.o.dir ? sess.id : undefined;
1538
+ const startedAt = new Date().toISOString();
1520
1539
  // 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
1521
1540
  let outcome = { ok: false, error: 'the run did not finish' };
1522
1541
  let recorded;
@@ -1524,7 +1543,8 @@ export class Runner {
1524
1543
  const material = [run.post?.body, run.thread?.body, ...(run.replies ?? []).map((p) => p.body), run.task?.handoff, ...(run.task?.messages ?? []).map((m) => m.body)];
1525
1544
  const docs = structured ? await this.linkedDocs(material, key) : [];
1526
1545
  const tasks = structured ? await this.linkedTasks([run.post?.body, run.thread?.body, ...(run.replies ?? []).map((p) => p.body)], key, run.task?.ref) : [];
1527
- const prompt = buildMentionPrompt({
1546
+ const promptFor = (since) => buildMentionPrompt({
1547
+ ...(since ? { since } : {}),
1528
1548
  docs,
1529
1549
  tasks,
1530
1550
  agentName: me.name,
@@ -1541,12 +1561,20 @@ export class Runner {
1541
1561
  threadUrl: !this.o.publicUrl && typeof run.thread.url === 'string' && /^https?:\/\//.test(run.thread.url) ? run.thread.url : postUrl(this.base(), threadId),
1542
1562
  structured,
1543
1563
  });
1544
- const result = await this.execute(rec, entry, prompt, undefined, 'mention', structured ? MENTION_SCHEMA : undefined, {
1564
+ const prompt = promptFor(resume ? { seen: sess.seen ?? [], ...(sess.at ? { at: sess.at } : {}) } : undefined);
1565
+ const result = await this.execute(rec, entry, prompt, resume, 'mention', structured ? MENTION_SCHEMA : undefined, {
1545
1566
  threadId,
1567
+ fresh: () => promptFor(),
1546
1568
  usage: (cost, est, used) => client.mentionUsage(mid, runId, cost, est, used),
1547
1569
  recorder: (r) => { recorded = r; },
1548
1570
  mentionId: mid,
1549
1571
  });
1572
+ // what this session has now been shown (a session that could not be continued was replaced by a new one, shown everything)
1573
+ const now = this.state.session(sessKey, 'mention');
1574
+ if (now) {
1575
+ const shown = [run.thread, ...(run.replies ?? []), ...(run.recent ?? []), run.post].map((p) => String(p?.id ?? '')).filter(Boolean);
1576
+ this.state.setSession(sessKey, 'mention', { ...now, seen: Array.from(new Set([...(now.id === sess?.id ? sess?.seen ?? [] : []), ...shown])).slice(-THREAD_SEEN_MAX), at: startedAt });
1577
+ }
1550
1578
  outcome = mentionOutcome(result, entry.reason, recorded, [rec.runToken, ...(this.o.secrets ?? []), this.o.cfSecret ?? ''].filter(Boolean));
1551
1579
  if (structured && result.ok && !entry.reason)
1552
1580
  await this.postStructuredReply(threadId, run.run_token, result.finalText, key);
@@ -1744,6 +1772,9 @@ export class Runner {
1744
1772
  const { client } = this.o;
1745
1773
  const me = await this.ensureMe();
1746
1774
  const taskId = rec.taskId;
1775
+ // where this run's session is kept: a task's by the task, a thread's mention runs by the thread, a read-ahead's nowhere
1776
+ const sessKey = mode === 'mention' ? (extra.threadId ? threadKey(extra.threadId) : '') : mode === 'prepare' ? '' : taskId;
1777
+ const sessKind = mode;
1747
1778
  const perm = mode === 'work' ? effectivePerm(me.perm_level, this.o.perm) : 'read';
1748
1779
  const env = buildAgentEnv(this.o.baseEnv ?? process.env, {
1749
1780
  hub: this.o.hub,
@@ -1760,7 +1791,7 @@ export class Runner {
1760
1791
  // B1: HOME is a per-task scratch dir (never the runner's own home).
1761
1792
  const baseEnv = this.o.baseEnv ?? process.env;
1762
1793
  const realHome = realHomeOf(baseEnv);
1763
- Object.assign(env, prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, taskId, realHome, baseEnv.CODEX_HOME || undefined).env);
1794
+ Object.assign(env, prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, mode === 'mention' && sessKey ? sessKey : taskId, realHome, baseEnv.CODEX_HOME || undefined).env);
1764
1795
  // a read-only GitHub token issued by the hub for this run (see githubToken)
1765
1796
  const gh = await this.githubToken(rec);
1766
1797
  if (gh) {
@@ -1845,7 +1876,7 @@ export class Runner {
1845
1876
  ...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
1846
1877
  ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
1847
1878
  // 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)
1848
- ...(Number(me.budget_usd ?? 0) > 0 ? { maxBudgetUsd: Math.max(0.01, Number(me.budget_usd) - Number(me.spent_usd ?? 0)) + ((mode === 'mention' || mode === 'prepare' ? undefined : this.state.session(taskId, mode))?.costTotal ?? 0) } : {}),
1879
+ ...(Number(me.budget_usd ?? 0) > 0 ? { maxBudgetUsd: Math.max(0.01, Number(me.budget_usd) - Number(me.spent_usd ?? 0)) + ((sessKey ? this.state.session(sessKey, sessKind) : undefined)?.costTotal ?? 0) } : {}),
1849
1880
  ...(outputSchema ? { outputSchema } : {}),
1850
1881
  onEvent: (e) => {
1851
1882
  lastEvent = Date.now();
@@ -1856,8 +1887,8 @@ export class Runner {
1856
1887
  inflight.add(id);
1857
1888
  if (e.type === 'tool_end' && id)
1858
1889
  inflight.delete(id);
1859
- if (e.type === 'session' && e.data && mode !== 'mention' && mode !== 'prepare') {
1860
- this.state.setSession(taskId, mode, { id: String(e.data), cwd: rec.workdir });
1890
+ if (e.type === 'session' && e.data && sessKey) {
1891
+ this.state.setSession(sessKey, sessKind, { id: String(e.data), cwd: rec.workdir });
1861
1892
  }
1862
1893
  recorder.event(e);
1863
1894
  // the log keeps its one line per event; what a tool printed is in the trace, not here
@@ -1887,6 +1918,20 @@ export class Runner {
1887
1918
  if (!entry.controller.signal.aborted)
1888
1919
  result = await go(m, ef);
1889
1920
  }
1921
+ // the session to continue was not there any more (the runtime cleared it, another machine's): nobody must go unanswered
1922
+ // for that. A new session, with the whole prompt. Never for a run that was refused (it must not start at all), nor when
1923
+ // the account or the login is what failed: a new session fails the same way, and the old one is still good.
1924
+ const sameAgain = (e) => !!accountProblem(e) || looksLikeLoginError(e) || programMissing(e);
1925
+ if (resume && extra.fresh && !refused && !result.ok && !toolsRan && !entry.controller.signal.aborted && !sameAgain(result.error ?? '')) {
1926
+ const note = `the earlier session could not be continued (${summarizeRuntimeError(result.error ?? '').slice(0, 160)}); starting a new one`;
1927
+ recorder.event({ type: 'error', data: note });
1928
+ this.taskLog(taskId, note);
1929
+ if (sessKey)
1930
+ this.state.dropSession(sessKey, sessKind);
1931
+ resume = undefined;
1932
+ prompt = extra.fresh();
1933
+ result = await go(m, ef);
1934
+ }
1890
1935
  // a model or an effort level the runtime does not take (a typo, one the account cannot use, a level the model lacks) must
1891
1936
  // not stop the agent: run again on the default, and say so in the trace (the run's chip then shows what really answered)
1892
1937
  for (let i = 0; i < 2 && !result.ok && !toolsRan && !entry.controller.signal.aborted; i++) {
@@ -1918,11 +1963,11 @@ export class Runner {
1918
1963
  }
1919
1964
  // Claude reports the running total of the whole session; the hub adds up what each run reports, so report only this run's part
1920
1965
  let runCost = Number(result.costUsd ?? 0);
1921
- if (result.sessionId && mode !== 'mention' && mode !== 'prepare') {
1922
- const before = this.state.session(taskId, mode)?.costTotal;
1966
+ if (result.sessionId && sessKey) {
1967
+ const before = this.state.session(sessKey, sessKind)?.costTotal;
1923
1968
  if (result.costCumulative && before !== undefined && runCost >= before)
1924
1969
  runCost -= before;
1925
- this.state.setSession(taskId, mode, { id: result.sessionId, cwd: rec.workdir, ...(result.costCumulative && result.costUsd !== undefined ? { costTotal: Number(result.costUsd) } : {}) });
1970
+ this.state.setSession(sessKey, sessKind, { id: result.sessionId, cwd: rec.workdir, ...(result.costCumulative && result.costUsd !== undefined ? { costTotal: Number(result.costUsd) } : {}) });
1926
1971
  }
1927
1972
  // §14.7: usage after every adapter run, success or failure.
1928
1973
  // with the model and the effort the run really ran with: the panel shows them on the run, so nobody has to guess
@@ -41,13 +41,23 @@ export interface SessionRef {
41
41
  cwd: string;
42
42
  /** The running cost total the runtime last reported for this task's session (Claude reports a total, the hub adds up increments). */
43
43
  costTotal?: number;
44
+ /** A thread's session only: the posts its runs were shown, so the next run in the thread is told what is new. */
45
+ seen?: string[];
46
+ /** A thread's session only: when its last run started (what a task's thread got since then is new too; an idle one is forgotten). */
47
+ at?: string;
44
48
  }
49
+ export type SessionKind = 'work' | 'answer' | 'mention';
50
+ /** Keyed by task id; a thread's session (the mention runs of one thread are one conversation) is under `threadKey(thread)`. */
45
51
  export interface SessionsFile {
46
- [taskId: string]: {
52
+ [key: string]: {
47
53
  work?: SessionRef;
48
54
  answer?: SessionRef;
55
+ mention?: SessionRef;
49
56
  };
50
57
  }
58
+ export declare const threadKey: (threadId: string) => string;
59
+ /** A thread nobody mentioned this agent in for this long starts over: the next mention reads the thread afresh. */
60
+ export declare const THREAD_SESSION_IDLE_MS: number;
51
61
  /** Persisted runner state: runs.json and sessions.json, both mode 0600. */
52
62
  export declare class RunnerState {
53
63
  readonly home: string;
@@ -65,6 +75,9 @@ export declare class RunnerState {
65
75
  bookkeepingTasks(): string[];
66
76
  /** C8: forget bookkeeping (and sessions) of tasks that are terminal or gone. */
67
77
  pruneTasks(taskIds: string[]): void;
68
- setSession(taskId: string, kind: 'work' | 'answer', ref: SessionRef): void;
69
- session(taskId: string, kind: 'work' | 'answer'): SessionRef | undefined;
78
+ setSession(taskId: string, kind: SessionKind, ref: SessionRef): void;
79
+ session(taskId: string, kind: SessionKind): SessionRef | undefined;
80
+ dropSession(key: string, kind: SessionKind): void;
81
+ /** Forget the sessions of threads idle for THREAD_SESSION_IDLE_MS, but for the `busy` ones (a run is in them); returns their keys. */
82
+ pruneThreads(now: number, busy?: ReadonlySet<string>): string[];
70
83
  }
@@ -1,5 +1,8 @@
1
1
  import { join } from 'node:path';
2
2
  import { readJson, writeJsonPrivate } from '../config.js';
3
+ export const threadKey = (threadId) => `thread-${threadId}`;
4
+ /** A thread nobody mentioned this agent in for this long starts over: the next mention reads the thread afresh. */
5
+ export const THREAD_SESSION_IDLE_MS = 7 * 86_400_000;
3
6
  /** Persisted runner state: runs.json and sessions.json, both mode 0600. */
4
7
  export class RunnerState {
5
8
  home;
@@ -68,9 +71,18 @@ export class RunnerState {
68
71
  }
69
72
  setSession(taskId, kind, ref) {
70
73
  const cur = this.sessions[taskId] ?? {};
71
- // the cost baseline survives a new session id (a resumed run may start a new one that still carries the earlier cost)
72
- const keep = ref.costTotal !== undefined ? ref : { ...ref, ...(cur[kind]?.costTotal !== undefined ? { costTotal: cur[kind].costTotal } : {}) };
73
- if (cur[kind]?.id === keep.id && cur[kind]?.cwd === keep.cwd && cur[kind]?.costTotal === keep.costTotal)
74
+ const was = cur[kind];
75
+ // the cost baseline survives a new session id (a resumed run may start a new one that still carries the earlier cost);
76
+ // what a thread's session was shown stays with that session, and goes with it
77
+ const keep = {
78
+ ...(was?.costTotal !== undefined ? { costTotal: was.costTotal } : {}),
79
+ ...(was && was.id === ref.id ? { ...(was.seen ? { seen: was.seen } : {}), ...(was.at ? { at: was.at } : {}) } : {}),
80
+ ...ref,
81
+ };
82
+ // a thread's session is dated from its first moment: one without a date would be forgotten at once
83
+ if (kind === 'mention' && !keep.at)
84
+ keep.at = new Date().toISOString();
85
+ if (was?.id === keep.id && was?.cwd === keep.cwd && was?.costTotal === keep.costTotal && was?.at === keep.at && was?.seen === keep.seen)
74
86
  return;
75
87
  cur[kind] = keep;
76
88
  this.sessions[taskId] = cur;
@@ -79,4 +91,31 @@ export class RunnerState {
79
91
  session(taskId, kind) {
80
92
  return this.sessions[taskId]?.[kind];
81
93
  }
94
+ dropSession(key, kind) {
95
+ const cur = this.sessions[key];
96
+ if (!cur?.[kind])
97
+ return;
98
+ delete cur[kind];
99
+ if (!Object.keys(cur).length)
100
+ delete this.sessions[key];
101
+ this.saveSessions();
102
+ }
103
+ /** Forget the sessions of threads idle for THREAD_SESSION_IDLE_MS, but for the `busy` ones (a run is in them); returns their keys. */
104
+ pruneThreads(now, busy = new Set()) {
105
+ const gone = [];
106
+ for (const [key, v] of Object.entries(this.sessions)) {
107
+ if (!v.mention || busy.has(key))
108
+ continue;
109
+ const at = Date.parse(v.mention.at ?? '');
110
+ if (Number.isFinite(at) && now - at <= THREAD_SESSION_IDLE_MS)
111
+ continue;
112
+ delete v.mention;
113
+ if (!Object.keys(v).length)
114
+ delete this.sessions[key];
115
+ gone.push(key);
116
+ }
117
+ if (gone.length)
118
+ this.saveSessions();
119
+ return gone;
120
+ }
82
121
  }
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.84.0";
1
+ export declare const VERSION = "3.85.0";
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export declare const PKG_NAME = "@koalaauto/agentchannel";
4
4
  /**
@@ -1,4 +1,4 @@
1
- export const VERSION = '3.84.0';
1
+ export const VERSION = '3.85.0';
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export const PKG_NAME = '@koalaauto/agentchannel';
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalaauto/agentchannel",
3
- "version": "3.84.0",
3
+ "version": "3.85.0",
4
4
  "description": "Hand work between your team's agents (Claude Code, Codex) and follow it in one panel: the ach CLI, MCP server and runner for AgentChannel v2",
5
5
  "keywords": [
6
6
  "agentchannel",