@koalaauto/agentchannel 3.101.0 → 3.102.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.
@@ -123,11 +123,13 @@ export class KiroOutput {
123
123
  }
124
124
  /** The agent's last message (stream-json), else the text transcript's tail. */
125
125
  finalText() {
126
- if (this.runFinal.trim())
127
- return this.runFinal.trim();
128
- const last = [...this.messages].reverse().find((m) => m.trim());
126
+ const last = [...this.messages].reverse().find((m) => m.trim())?.trim();
127
+ const run = this.runFinal.trim();
128
+ // runFinished joins every message of the run ("I'll read the steering file first." + the report): the streamed last one is the answer
129
+ if (run && !(last && run.endsWith(last)))
130
+ return run;
129
131
  if (last)
130
- return last.trim();
132
+ return last;
131
133
  return this.text.join('\n').trim().slice(-8000);
132
134
  }
133
135
  flushMessage() {
@@ -146,7 +146,7 @@ async function runOnce(p, io) {
146
146
  return new KeyRefused(NO_KEY_MESSAGE[isZh(env) ? 'zh' : 'en']);
147
147
  // the hub names the newest release on every answer: the updater hears it at once instead of at its next 6-hourly check
148
148
  let updater;
149
- const c = clientFromConfig(cfg, { fetch: io.fetch, role: 'runner', onLatestClient: (latest) => void updater?.heardLatest(latest)?.catch(() => { }) });
149
+ const c = clientFromConfig(cfg, { fetch: io.fetch, role: 'runner', onLatestClient: (latest) => void updater?.heardLatest(latest)?.catch((e) => io.err(`update: the check for ${latest} failed: ${e?.message ?? e}`)) });
150
150
  const home = achHome(env);
151
151
  const dir = resolve(io.cwd ?? process.cwd(), str(v.dir) ?? '.');
152
152
  // the default home, joined before join recorded its directory, learns it from its runner so its MCP sessions can say where
@@ -212,7 +212,7 @@ async function runOnce(p, io) {
212
212
  const moved = await moveOldService(io, { agentName: me.name, formerNames: me.former_names ?? [], runDir: dir }, home);
213
213
  if (moved)
214
214
  return UPDATE_EXIT_CODE;
215
- void moveMcpEntries(io, dir).catch(() => { });
215
+ void moveMcpEntries(io, dir).catch((e) => io.err(`the \`ach\` MCP entry was not moved to the install in the AgentChannel home: ${e?.message ?? e}`));
216
216
  const runtime = str(v.runtime) ?? (isRuntime(me.runtime) ? me.runtime : 'claude');
217
217
  // what the permission and the network list do not cover, said where the person starting the runner will read it
218
218
  if (asked === 'full')
package/dist/src/cli.js CHANGED
@@ -1130,10 +1130,18 @@ async function dispatch(p, io) {
1130
1130
  // agent of this directory beside them when there is one; else that agent, as before
1131
1131
  const parts = sessionParts(cwd, env);
1132
1132
  const menv = { ...env, AGENTCHANNEL_HOME: parts.person ?? parts.agent };
1133
+ // a computer that was never connected (or lost what it was connected with) still answers its session: how to connect
1134
+ const mcfg = loadConfig(menv);
1135
+ const missing = !mcfg.hub ? 'no team address' : !(mcfg.runToken || mcfg.key) ? 'no key or connection' : '';
1136
+ if (missing) {
1137
+ const { startUnconnectedMcp } = await import('./mcp.js');
1138
+ await startUnconnectedMcp(missing);
1139
+ return await new Promise(() => { });
1140
+ }
1133
1141
  // every answer names the newest release: this machine's install moves on to it even with no runner here (mcpupdate.ts)
1134
1142
  const { mcpUpdater } = await import('./mcpupdate.js');
1135
1143
  const upd = mcpUpdater({ env: menv, log: (s) => process.stderr.write(`[ach mcp] ${s}\n`) });
1136
- const main = clientFromConfig(loadConfig(menv), { fetch: io.fetch, onLatestClient: (latest) => void upd.heard(latest)?.catch(() => { }) });
1144
+ const main = clientFromConfig(mcfg, { fetch: io.fetch, onLatestClient: (latest) => void upd.heard(latest)?.catch((e) => process.stderr.write(`[ach mcp] could not move to ${latest}: ${e?.message ?? e}\n`)) });
1137
1145
  const aenv = parts.person && parts.agent ? { ...env, AGENTCHANNEL_HOME: parts.agent } : undefined;
1138
1146
  const acfg = aenv ? loadConfig(aenv) : undefined;
1139
1147
  await startMcp(main, { cwd, dir: parts.dir, inside: parts.inside, ...(acfg?.key ? { hand: clientFromConfig(acfg, { fetch: io.fetch }) } : {}) });
@@ -1186,7 +1194,7 @@ async function dispatch(p, io) {
1186
1194
  }
1187
1195
  }
1188
1196
  finally {
1189
- await client.close().catch(() => { });
1197
+ await client.close().catch(() => { }); // the list is out: a server that does not close cleanly changes nothing
1190
1198
  }
1191
1199
  return 0;
1192
1200
  }
@@ -1198,7 +1206,7 @@ async function dispatch(p, io) {
1198
1206
  open: (url) => {
1199
1207
  if (!(process.stdout.isTTY || io.openUrl))
1200
1208
  return false;
1201
- (io.openUrl ?? openUrlDefault)(url).catch(() => { });
1209
+ (io.openUrl ?? openUrlDefault)(url).catch(() => { }); // no browser opened: the address is printed for the person to open
1202
1210
  return !!(env.DISPLAY || env.WAYLAND_DISPLAY || process.platform === 'darwin' || process.platform === 'win32' || io.openUrl);
1203
1211
  },
1204
1212
  ...(io.ask ? { readLine: (q) => io.ask(q) } : {}),
@@ -29,6 +29,6 @@ export class ToolUse {
29
29
  return;
30
30
  const rows = [...this.rows.values()];
31
31
  this.rows.clear();
32
- await this.o.send(rows).catch(() => { });
32
+ await this.o.send(rows).catch(() => { }); // a count of tool calls: losing one report must not fail the session that made them
33
33
  }
34
34
  }
@@ -462,11 +462,21 @@ export interface DecisionOption {
462
462
  export declare const CLIENT_HEADERS: Record<string, string>;
463
463
  export declare class NetworkError extends Error {
464
464
  }
465
- /** A 503 that says the hub is read-only: its note and the wait it asks for (Retry-After, 5 s to 5 min); null for any other 503. */
466
- export declare function readOnlyPause(res: Response, text: string): {
465
+ /** The hub said to wait and ask again: why, for how long, and whether this request may be sent again as it is. */
466
+ export interface HubWait {
467
+ code: 'read_only' | 'busy';
467
468
  note: string;
468
469
  ms: number;
469
- } | null;
470
+ again: boolean;
471
+ }
472
+ /**
473
+ * A 503 in which the hub says to wait (Retry-After); null for any other 503.
474
+ * - `read_only`: the hub is under maintenance and wrote nothing, so any request goes again (5 s to 5 min).
475
+ * - `busy`: its database refused for a moment. A read goes again, and so does a write the hub says it had not begun
476
+ * (`retry_safe`); one it had begun may be half done, so the caller gets the error. The wait is the hub's and as much again
477
+ * at random: the requests refused together must not come back together.
478
+ */
479
+ export declare function hubWait(method: string, res: Response, text: string, random?: () => number): HubWait | null;
470
480
  /**
471
481
  * Whether a failed fetch is worth sending again: a passing fault on the way to the hub, not a wrong address
472
482
  * (ENOTFOUND, ECONNREFUSED) or a hub that took the request and did not answer in time.
@@ -530,8 +540,10 @@ export interface ClientOptions {
530
540
  retryDelaysMs?: number[];
531
541
  /** How long a request waits in all while the hub is read-only before it gives up (default 45 min). */
532
542
  readOnlyWaitMs?: number;
533
- /** Told each time a request waits for read-only mode to end: the hub's note and how long until the next try. */
534
- onReadOnly?: (note: string, waitMs: number) => void;
543
+ /** How long a request waits in all while the hub says it is busy before it gives up (default 20 s). */
544
+ busyWaitMs?: number;
545
+ /** Told each time a request waits because the hub said to (read-only, busy): the hub's note and how long until the next try. */
546
+ onWait?: (note: string, waitMs: number) => void;
535
547
  }
536
548
  /** Round 2: human-facing CLI text in Chinese when LANG/LC_ALL starts with zh. */
537
549
  export declare function isZh(env: NodeJS.ProcessEnv): boolean;
@@ -553,7 +565,8 @@ export declare class Client {
553
565
  constructor(o: ClientOptions);
554
566
  private retryDelaysMs;
555
567
  private readOnlyWaitMs;
556
- private onReadOnly?;
568
+ private busyWaitMs;
569
+ private onWait?;
557
570
  /** The hub said, on its latest answer, that it is read-only (`x-ach-read-only`): the runner starts nothing new meanwhile. */
558
571
  readOnly: boolean;
559
572
  private role?;
@@ -763,7 +776,12 @@ export declare class Client {
763
776
  prepareRun(taskId: string, run_id: string): Promise<TaskBundle & {
764
777
  run_token: string;
765
778
  }>;
766
- /** What the read-ahead found; the hub answers whether the task now waits for the owner to take it over. */
779
+ /**
780
+ * What the read-ahead found; the hub answers whether the task now waits for the owner to take it over. `failed`: it did not
781
+ * finish, and why (`unreadable`: the run worked, its answer could not be read; `attempt`: which read of this handoff). The hub
782
+ * then may answer `blocked` (the reason is this machine: a blocker is open on the agent) or `retry` (read it again in a while);
783
+ * nothing was written on the task in either case. A hub before that knows neither and records the draft, as it always did.
784
+ */
767
785
  prepared(taskId: string, body: {
768
786
  code: boolean;
769
787
  small?: boolean;
@@ -771,10 +789,16 @@ export declare class Client {
771
789
  files?: string[];
772
790
  draft?: string;
773
791
  handoff_version?: number;
792
+ failed?: string;
793
+ unreadable?: boolean;
794
+ attempt?: number;
795
+ ran?: boolean;
774
796
  }): Promise<{
775
797
  owner_first: boolean;
776
798
  small: boolean;
777
799
  status: string;
800
+ blocked?: string;
801
+ retry?: boolean;
778
802
  }>;
779
803
  answerRun(taskId: string, question_id: string, run_id: string): Promise<{
780
804
  run_token: string;
@@ -38,8 +38,20 @@ const REQUEST_TIMEOUT_MS = 60_000;
38
38
  const RETRY_DELAYS_MS = [1_000, 3_000, 8_000];
39
39
  /** How long a request waits in all while the hub is read-only (a cutover takes 15 to 30 minutes). */
40
40
  const READ_ONLY_WAIT_MS = 45 * 60_000;
41
- /** A 503 that says the hub is read-only: its note and the wait it asks for (Retry-After, 5 s to 5 min); null for any other 503. */
42
- export function readOnlyPause(res, text) {
41
+ /**
42
+ * How long a request waits in all while the hub says it is busy (its database refused it for a moment): two or three tries.
43
+ * Well under a minute, which is how long some clients give one tool call (Codex): a call given up on there whose request
44
+ * still went through later would be made a second time by the model.
45
+ */
46
+ const BUSY_WAIT_MS = 20_000;
47
+ /**
48
+ * A 503 in which the hub says to wait (Retry-After); null for any other 503.
49
+ * - `read_only`: the hub is under maintenance and wrote nothing, so any request goes again (5 s to 5 min).
50
+ * - `busy`: its database refused for a moment. A read goes again, and so does a write the hub says it had not begun
51
+ * (`retry_safe`); one it had begun may be half done, so the caller gets the error. The wait is the hub's and as much again
52
+ * at random: the requests refused together must not come back together.
53
+ */
54
+ export function hubWait(method, res, text, random = Math.random) {
43
55
  let data;
44
56
  try {
45
57
  data = JSON.parse(text);
@@ -47,10 +59,15 @@ export function readOnlyPause(res, text) {
47
59
  catch {
48
60
  return null;
49
61
  }
50
- if (data?.code !== 'read_only')
62
+ const code = data?.code;
63
+ if (code !== 'read_only' && code !== 'busy')
51
64
  return null;
52
65
  const s = Number(res.headers?.get?.('retry-after') ?? data.retry_after);
53
- return { note: typeof data.error === 'string' ? data.error : 'the hub is read-only', ms: Math.min(Math.max(Number.isFinite(s) ? s : 60, 5), 300) * 1000 };
66
+ const note = typeof data.error === 'string' ? data.error : code === 'busy' ? 'the hub is busy' : 'the hub is read-only';
67
+ if (code === 'read_only')
68
+ return { code, note, ms: Math.min(Math.max(Number.isFinite(s) ? s : 60, 5), 300) * 1000, again: true };
69
+ const base = Math.min(Math.max(Number.isFinite(s) ? s : 5, 1), 60) * 1000;
70
+ return { code, note, ms: Math.round(base + random() * base), again: data.retry_safe === true || method === 'GET' || method === 'HEAD' };
54
71
  }
55
72
  /** Faults while connecting: the request never left this machine, so any method may be sent again. */
56
73
  const CONNECT_FAULTS = new Set(['ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH']);
@@ -117,7 +134,7 @@ export function clientFromConfig(cfg, opts = {}) {
117
134
  return new Client({
118
135
  hub: cfg.hub, token, cfId: cfg.cfId, cfSecret: cfg.cfSecret, fetch: opts.fetch, role: opts.role, onLatestClient: opts.onLatestClient,
119
136
  // stderr: stdout may be an MCP stream or JSON someone parses
120
- onReadOnly: (note, ms) => process.stderr.write(`ach: ${note}; trying again in ${Math.round(ms / 1000)} s\n`),
137
+ onWait: (note, ms) => process.stderr.write(`ach: ${note}; trying again in ${Math.round(ms / 1000)} s\n`),
121
138
  });
122
139
  }
123
140
  function arr(v) {
@@ -153,11 +170,13 @@ export class Client {
153
170
  this.onLatestClient = o.onLatestClient;
154
171
  this.retryDelaysMs = o.retryDelaysMs ?? RETRY_DELAYS_MS;
155
172
  this.readOnlyWaitMs = o.readOnlyWaitMs ?? READ_ONLY_WAIT_MS;
156
- this.onReadOnly = o.onReadOnly;
173
+ this.busyWaitMs = o.busyWaitMs ?? BUSY_WAIT_MS;
174
+ this.onWait = o.onWait;
157
175
  }
158
176
  retryDelaysMs;
159
177
  readOnlyWaitMs;
160
- onReadOnly;
178
+ busyWaitMs;
179
+ onWait;
161
180
  /** The hub said, on its latest answer, that it is read-only (`x-ach-read-only`): the runner starts nothing new meanwhile. */
162
181
  readOnly = false;
163
182
  role;
@@ -203,8 +222,10 @@ export class Client {
203
222
  const multipart = !!files?.length;
204
223
  let res;
205
224
  let text;
206
- // the hub read-only (503, code read_only) wrote nothing: send the request again once it says to, any method
207
- for (let waited = 0;;) {
225
+ // the hub said to wait (503 read_only or busy: hubWait): send the request again once it says to, when that is safe
226
+ // (each kind of wait has its own time: a request that sat out a long read-only spell still gets its tries at a busy hub)
227
+ const waited = { read_only: 0, busy: 0 };
228
+ for (;;) {
208
229
  for (let attempt = 0;; attempt++) {
209
230
  try {
210
231
  res = await this.fetchFn(url, {
@@ -233,14 +254,15 @@ export class Client {
233
254
  }
234
255
  }
235
256
  text = await res.text();
236
- const pause = res.status === 503 ? readOnlyPause(res, text) : null;
237
- this.readOnly = !!pause || res.headers?.get?.('x-ach-read-only') === '1';
238
- if (!pause || waited >= this.readOnlyWaitMs)
257
+ const wait = res.status === 503 ? hubWait(method, res, text) : null;
258
+ this.readOnly = wait?.code === 'read_only' || res.headers?.get?.('x-ach-read-only') === '1';
259
+ const most = wait?.code === 'busy' ? this.busyWaitMs : this.readOnlyWaitMs;
260
+ if (!wait || !wait.again || waited[wait.code] >= most)
239
261
  break;
240
- const ms = Math.min(pause.ms, this.readOnlyWaitMs - waited);
241
- this.onReadOnly?.(pause.note, ms);
262
+ const ms = Math.min(wait.ms, most - waited[wait.code]);
263
+ this.onWait?.(wait.note, ms);
242
264
  await new Promise((r) => setTimeout(r, ms));
243
- waited += ms;
265
+ waited[wait.code] += ms;
244
266
  }
245
267
  // Cloudflare Access in front of the hub answers with its login page (a redirect followed to *.cloudflareaccess.com,
246
268
  // or a challenge header) instead of the hub's JSON: say so, instead of failing later on a missing field
@@ -544,7 +566,12 @@ export class Client {
544
566
  const r = await this.ach('POST', `/tasks/${enc(taskId)}/prepare-run`, { run_id });
545
567
  return { ...normalizeBundle(r), run_token: r?.run_token ?? '' };
546
568
  }
547
- /** What the read-ahead found; the hub answers whether the task now waits for the owner to take it over. */
569
+ /**
570
+ * What the read-ahead found; the hub answers whether the task now waits for the owner to take it over. `failed`: it did not
571
+ * finish, and why (`unreadable`: the run worked, its answer could not be read; `attempt`: which read of this handoff). The hub
572
+ * then may answer `blocked` (the reason is this machine: a blocker is open on the agent) or `retry` (read it again in a while);
573
+ * nothing was written on the task in either case. A hub before that knows neither and records the draft, as it always did.
574
+ */
548
575
  async prepared(taskId, body) {
549
576
  return this.ach('POST', `/tasks/${enc(taskId)}/prepared`, body);
550
577
  }
@@ -230,7 +230,7 @@ export async function invitePeople(values, io, admin) {
230
230
  io.out(`${x.p.name}: ${url}`);
231
231
  }
232
232
  for (const m of newMaps)
233
- await a.request('POST', '/api/ach/admin/feishu/mappings', m).catch(() => undefined);
233
+ await a.request('POST', '/api/ach/admin/feishu/mappings', m).catch((e) => io.err(`the Feishu mapping of ${m.user} was not saved (the next invite looks them up again): ${e?.message ?? e}`));
234
234
  if (values.json)
235
235
  io.out(JSON.stringify(results, null, 2));
236
236
  io.err('Each link works once and expires in 24 h; a new invite replaces the older link.');
package/dist/src/mcp.d.ts CHANGED
@@ -2,6 +2,19 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import type { Agent, Client } from './client.js';
3
3
  import { AttentionNotifier, ChangeFeed, type ChangeFeedOptions, type Exec } from './attention.js';
4
4
  export declare const HANDOFF_TEMPLATE = "## Goal\n<one or two sentences: what done looks like>\n\n## Context and what was tried\n<background, links, what already failed and why>\n\n## Where\n<repo, branch, commit (the receiver starts from links.base if you pass base)>\n\n## Money\n<cost before/after, budget impact, or \"n/a\">\n\n## Acceptance\n<checkable criteria: tests, outputs, numbers>\n\n## Open questions\n<what you do not know yet; the receiver may ask you>";
5
+ /**
6
+ * How this computer gets connected to a team, for a session to tell its user: said by the server a computer with no connection
7
+ * starts (startUnconnectedMcp), and under the error of a tool the hub refused for its key (wrap). The session cannot do it
8
+ * itself: the line is a one-time code its person gets from the panel.
9
+ */
10
+ export declare const CONNECT_HELP = "To connect this computer to their AgentChannel team, your user:\n1. opens the team's AgentChannel panel in a browser and chooses \"Connect your computer\" (\u8FDE\u63A5\u4F60\u7684\u7535\u8111), or \"Connect an agent\" (\u63A5\u5165\u667A\u80FD\u4F53) for a project's own agent;\n2. runs the `ach join ...` line shown there in a terminal on this computer;\n3. starts this session again (the tools load when a session starts).\nYou cannot do this for them: the line is a one-time code only they can get. Tell them these steps; do not look for a key or a token on this computer.";
11
+ /**
12
+ * The server a computer with no connection to a team starts (no hub address, or nothing to prove who it is): one tool that says
13
+ * how to connect, and the same in its instructions. Until 3.102 \`ach mcp\` exited here, and the session saw only "the ach server
14
+ * failed to start": neither it nor its person learned what to do.
15
+ */
16
+ export declare function buildUnconnectedMcpServer(why: string): McpServer;
17
+ export declare function startUnconnectedMcp(why: string): Promise<void>;
5
18
  /**
6
19
  * S9: task content returned to the person's interactive agent was written by
7
20
  * other agents. Mark it so the model treats it as data, never as instructions.
@@ -37,7 +50,8 @@ export declare function interactiveInstructions(o: {
37
50
  repo?: string;
38
51
  base?: string;
39
52
  branch: string;
40
- readAhead?: boolean;
53
+ readAhead?: boolean; /** that read-ahead did not finish */
54
+ readFailed?: boolean;
41
55
  ownerFirst?: boolean;
42
56
  }): string;
43
57
  /** Round 2: what AgentChannel is and which tool to use when (MCP server instructions). */
@@ -90,6 +104,7 @@ export declare function takeoverWhere(place: unknown, hand?: string): {
90
104
  here: boolean;
91
105
  where: string;
92
106
  review: boolean;
107
+ failed: string;
93
108
  };
94
109
  export declare function inboxHandle(i: Record<string, unknown>, hand?: string): string;
95
110
  export declare function buildMcpServer(client: Client, o?: {
package/dist/src/mcp.js CHANGED
@@ -35,6 +35,18 @@ export const HANDOFF_TEMPLATE = `## Goal
35
35
  ## Open questions
36
36
  <what you do not know yet; the receiver may ask you>`;
37
37
  const HANDOFF_HELP = `The handoff is the full context package, in markdown, with these sections:\n${HANDOFF_TEMPLATE}\nWrite it so a fresh agent with no chat history can do the work.`;
38
+ /**
39
+ * How this computer gets connected to a team, for a session to tell its user: said by the server a computer with no connection
40
+ * starts (startUnconnectedMcp), and under the error of a tool the hub refused for its key (wrap). The session cannot do it
41
+ * itself: the line is a one-time code its person gets from the panel.
42
+ */
43
+ export const CONNECT_HELP = `To connect this computer to their AgentChannel team, your user:
44
+ 1. opens the team's AgentChannel panel in a browser and chooses "Connect your computer" (连接你的电脑), or "Connect an agent" (接入智能体) for a project's own agent;
45
+ 2. runs the \`ach join ...\` line shown there in a terminal on this computer;
46
+ 3. starts this session again (the tools load when a session starts).
47
+ You cannot do this for them: the line is a one-time code only they can get. Tell them these steps; do not look for a key or a token on this computer.`;
48
+ /** The key or link this session holds no longer works: what the hub said is not enough for a session to act on. */
49
+ const refusedKey = (e) => e instanceof HubError && e.status === 401 && e.code === 'unauthorized';
38
50
  async function wrap(fn) {
39
51
  try {
40
52
  const r = await fn();
@@ -44,9 +56,30 @@ async function wrap(fn) {
44
56
  // a refused Memory push: which lines and why (the hub's message only counts them)
45
57
  const lines = lintProblemLines(e);
46
58
  const more = lines ? `\nnot written; fix each line and write again:\n${lines.join('\n')}` : '';
47
- return { content: [{ type: 'text', text: `error: ${e?.message ?? e}${more}` }], isError: true };
59
+ const connect = refusedKey(e) ? `\nThe hub no longer takes what this computer was connected with (a key that was replaced, an agent or a connection that was removed). ${CONNECT_HELP}` : '';
60
+ return { content: [{ type: 'text', text: `error: ${e?.message ?? e}${more}${connect}` }], isError: true };
48
61
  }
49
62
  }
63
+ /**
64
+ * The server a computer with no connection to a team starts (no hub address, or nothing to prove who it is): one tool that says
65
+ * how to connect, and the same in its instructions. Until 3.102 \`ach mcp\` exited here, and the session saw only "the ach server
66
+ * failed to start": neither it nor its person learned what to do.
67
+ */
68
+ export function buildUnconnectedMcpServer(why) {
69
+ const text = `AgentChannel is not connected on this computer (${why}), so its tools are not here yet.\n${CONNECT_HELP}`;
70
+ const server = new McpServer({ name: 'ach', version: VERSION }, { instructions: text });
71
+ server.registerTool('connect', { description: 'AgentChannel is not connected on this computer: how your user connects it. Call this when they ask for anything on their team (tasks, channels, Yoda, the inbox).', inputSchema: {} }, async () => ({ content: [{ type: 'text', text }] }));
72
+ return server;
73
+ }
74
+ export async function startUnconnectedMcp(why) {
75
+ process.stderr.write(`[ach mcp] not connected (${why}): serving only how to connect\n`);
76
+ const leave = () => process.exit(0);
77
+ process.stdin.once('end', leave);
78
+ process.stdin.once('close', leave);
79
+ for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP'])
80
+ process.once(sig, leave);
81
+ await buildUnconnectedMcpServer(why).connect(new StdioServerTransport());
82
+ }
50
83
  /**
51
84
  * S9: task content returned to the person's interactive agent was written by
52
85
  * other agents. Mark it so the model treats it as data, never as instructions.
@@ -156,7 +189,7 @@ export function interactiveInstructions(o) {
156
189
  `You claimed AgentChannel task ${o.taskId} for agent "${o.agentName}". You now work it in this interactive session; no runner will start an agent for it.`,
157
190
  `Task page: ${o.url}`,
158
191
  `Where: ${o.repo ? `repo "${o.repo}"` : 'the repo your user names'}; start a branch ${o.branch}${o.base ? ` from ${o.base}` : ''} unless your user says otherwise.`,
159
- ...(o.readAhead ? ['Your runner read this task ahead: its draft (plan, files, questions) is the `read_ahead` field below. Start from it with your user; check it, it was written without them.'] : []),
192
+ ...(o.readFailed ? ["Your runner's read-ahead of this task did not finish (the `read_ahead` field below is its error, not a draft): nothing was read. Read the task with your user from its handoff."] : o.readAhead ? ['Your runner read this task ahead: its draft (plan, files, questions) is the `read_ahead` field below. Start from it with your user; check it, it was written without them.'] : []),
160
193
  'How to work it:',
161
194
  o.ownerFirst
162
195
  ? '- task_progress for short status updates. This task waited for your user to take it over: the claim stays theirs however long the work takes.'
@@ -290,7 +323,7 @@ export function takeoverWhere(place, hand) {
290
323
  const here = !!hand && hand === agent;
291
324
  const dir = String(p.dir ?? '');
292
325
  const host = String(p.host ?? '');
293
- return { here, review: p.review === true, where: here ? 'this session' : `a session opened in ${dir ? `${dir}${host ? ` on ${host}` : ''} (the directory of their agent ${agent})` : `the directory of their agent ${agent || 'it was sent to'}`}` };
326
+ return { here, review: p.review === true, failed: String(p.failed ?? ''), where: here ? 'this session' : `a session opened in ${dir ? `${dir}${host ? ` on ${host}` : ''} (the directory of their agent ${agent})` : `the directory of their agent ${agent || 'it was sent to'}`}` };
294
327
  }
295
328
  export function inboxHandle(i, hand) {
296
329
  const task = String(i.task_ref ?? i.task_id ?? i.id ?? '');
@@ -298,9 +331,12 @@ export function inboxHandle(i, hand) {
298
331
  case 'takeover': {
299
332
  const w = takeoverWhere(i.takeover, hand);
300
333
  const runner = `handle_task {task_id: ${task}, action: to_runner, text}: their agent's runner does it${w.review ? ' and they review what it writes' : ' (nobody reviews what it writes: that agent delivers no pull requests)'}`;
334
+ // (a read-ahead that did not finish read nothing: there is no draft, and it is not known that the task changes code)
335
+ // (the reason is the run's own error text: it stays in the item, as data, and is not repeated in these words)
336
+ const read = w.failed ? "The runner's read-ahead did not finish (`takeover.failed` is why): nothing was read, so tell them that, and that it is not known whether the task changes code" : '`text` is what the runner read ahead';
301
337
  return w.here
302
- ? `your user's choice of two: claim_task {task_id: ${task}}: they take it over and work it here ("take over ${task}"); or ${runner}. \`text\` is what the runner read ahead`
303
- : `your user's choice of two: they take it over in ${w.where}, by saying "take over ${task}" (接 ${task}) there (it is not worked in this session: tell them that place); or ${runner}. \`text\` is what the runner read ahead`;
338
+ ? `your user's choice of two: claim_task {task_id: ${task}}: they take it over and work it here ("take over ${task}"); or ${runner}. ${read}`
339
+ : `your user's choice of two: they take it over in ${w.where}, by saying "take over ${task}" (接 ${task}) there (it is not worked in this session: tell them that place); or ${runner}. ${read}`;
304
340
  }
305
341
  case 'decision': return `decide {task_id: ${String(i.task_ref ?? i.task_id ?? '')}, message_id: ${String(i.message_id ?? '')}, reply}: your user's own answer`;
306
342
  case 'acceptance': return `handle_task {task_id: ${task}, action: accept | request_changes}`;
@@ -659,6 +695,7 @@ export function buildMcpServer(client, o = {}) {
659
695
  const prep = [...(b.messages ?? [])].reverse().find((m) => m.sys_code === 'prepared' && String(m.sys_params?.v ?? '') === String(b.task.handoff_version ?? ''));
660
696
  const text = interactiveInstructions({
661
697
  readAhead: !!prep,
698
+ readFailed: !!prep?.sys_params?.failed,
662
699
  ownerFirst: prep?.sys_params?.owner_first === '1',
663
700
  taskId: refOf(b.task),
664
701
  agentName: self.name,
@@ -1030,7 +1067,7 @@ function moveOffNpxLater(cwd, delayMs = 30_000) {
1030
1067
  const moved = await moveNpxMcpEntriesHere({ env: process.env, dir: cwd, log });
1031
1068
  if (moved.length)
1032
1069
  log(`the \`ach\` MCP entry (${moved.join(', ')}) starts the install in the AgentChannel home from the next session`);
1033
- })().catch(() => { });
1070
+ })().catch((e) => process.stderr.write(`[ach mcp] not moved off npx: ${e?.message ?? e}\n`));
1034
1071
  }, delayMs);
1035
1072
  timer.unref?.();
1036
1073
  }
@@ -58,7 +58,7 @@ export class RunnerReports {
58
58
  return;
59
59
  }
60
60
  try {
61
- await this.o.client.reportRepos(names, await this.o.workspace.repoRemotes?.().catch(() => undefined));
61
+ await this.o.client.reportRepos(names, await this.o.workspace.repoRemotes?.().catch(() => undefined)); // (no remotes read: the names alone are reported)
62
62
  this.reposReported = true;
63
63
  }
64
64
  catch (e) {
@@ -64,6 +64,8 @@ export interface RunnerOptions {
64
64
  claimDelayMs?: number;
65
65
  /** read new tasks ahead and leave code tasks for the owner (docs/specs/owner-pulls-tasks.md); `ach run` turns it on */
66
66
  readAhead?: boolean;
67
+ /** a read-ahead the hub asks to be read again waits this long, times the tries so far (default two minutes) */
68
+ readAgainMs?: number;
67
69
  /** Client acting with a run token (posts structured answers for codex). Default: a hub Client. */
68
70
  tokenClient?: (token: string) => Pick<Client, 'postMessage' | 'reply'>;
69
71
  /** §19: base URL for links in prompts (ACH_PUBLIC_URL); default the hub URL. */
@@ -211,10 +213,18 @@ export declare class Runner {
211
213
  /** read-aheads this runner reported, task -> handoff version and the hub's answer: an inbox fetched before the report landed
212
214
  * still shows the task unread, and must not start a second read-ahead of the same handoff */
213
215
  private readAhead;
216
+ /** read-aheads that did not finish and are read again, task -> handoff version, tries so far and the earliest next one */
217
+ private readTries;
214
218
  /**
215
219
  * 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,
216
220
  * the files it expects to touch, a plan and questions; the files decide whether it is one of the owner's declared small jobs. The
217
- * hub then says whether the owner takes it over. A read-ahead that fails reports a code task: the owner looks, nothing is lost.
221
+ * hub then says whether the owner takes it over.
222
+ *
223
+ * One that does not finish has read nothing, so it does not report "a code task" (takeover.md §7; until 3.102 it did, and tasks
224
+ * waited days for an owner to "take over" what was a broken login). The account behind the runtime (a limit, an unpaid plan)
225
+ * and a sandbox or login this runner's own check confirms are this runner's to wait out: it takes nothing new meanwhile and
226
+ * reads the task again after. Every other read that ran and did not finish it tells the hub with the reason, and the hub sorts it: this machine (a blocker
227
+ * on the agent; nothing is handed out while it holds), read it again in a while, or record it and let the owner look.
218
228
  */
219
229
  private runPrepare;
220
230
  private runWork;
@@ -210,6 +210,10 @@ export class Runner {
210
210
  for (const id of this.readAhead.keys())
211
211
  if (!waiting.has(id))
212
212
  this.readAhead.delete(id);
213
+ // (kept while the task is out of sight for a while, held by a blocker, a decision, a dependency: its tries still count)
214
+ for (const [id, r] of this.readTries)
215
+ if (!waiting.has(id) && now - r.notBefore > 6 * 3600_000)
216
+ this.readTries.delete(id);
213
217
  for (const t of inbox.tasks_to_me) {
214
218
  if (this.isQueuedOrActive(`task:${t.id}`))
215
219
  continue;
@@ -226,7 +230,10 @@ export class Runner {
226
230
  if (prepared?.owner_first)
227
231
  continue;
228
232
  if (!prepared) {
229
- this.enqueue({ kind: 'prepare', taskId: t.id });
233
+ // one whose read-ahead did not finish and is to be read again: not before its time (runPrepare)
234
+ const tried = this.readTries.get(t.id);
235
+ if (!(tried && tried.v === Number(t.handoff_version) && now < tried.notBefore))
236
+ this.enqueue({ kind: 'prepare', taskId: t.id });
230
237
  continue;
231
238
  }
232
239
  }
@@ -569,10 +576,18 @@ export class Runner {
569
576
  /** read-aheads this runner reported, task -> handoff version and the hub's answer: an inbox fetched before the report landed
570
577
  * still shows the task unread, and must not start a second read-ahead of the same handoff */
571
578
  readAhead = new Map();
579
+ /** read-aheads that did not finish and are read again, task -> handoff version, tries so far and the earliest next one */
580
+ readTries = new Map();
572
581
  /**
573
582
  * 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,
574
583
  * the files it expects to touch, a plan and questions; the files decide whether it is one of the owner's declared small jobs. The
575
- * hub then says whether the owner takes it over. A read-ahead that fails reports a code task: the owner looks, nothing is lost.
584
+ * hub then says whether the owner takes it over.
585
+ *
586
+ * One that does not finish has read nothing, so it does not report "a code task" (takeover.md §7; until 3.102 it did, and tasks
587
+ * waited days for an owner to "take over" what was a broken login). The account behind the runtime (a limit, an unpaid plan)
588
+ * and a sandbox or login this runner's own check confirms are this runner's to wait out: it takes nothing new meanwhile and
589
+ * reads the task again after. Every other read that ran and did not finish it tells the hub with the reason, and the hub sorts it: this machine (a blocker
590
+ * on the agent; nothing is handed out while it holds), read it again in a while, or record it and let the owner look.
576
591
  */
577
592
  async runPrepare(taskId, entry) {
578
593
  const { client, workspace } = this.o;
@@ -594,12 +609,30 @@ export class Runner {
594
609
  return; // otherwise taken: the next poll sees where it stands
595
610
  }
596
611
  const report = async (r) => {
612
+ const v = Number(bundle.task.handoff_version);
613
+ const before = this.readTries.get(taskId);
614
+ const n = r.failed === undefined ? 0 : (before?.v === v ? before.n : 0) + 1;
597
615
  try {
598
- const out = await client.prepared(taskId, { ...r, handoff_version: bundle.task.handoff_version });
599
- this.readAhead.set(taskId, { v: Number(bundle.task.handoff_version), owner_first: !!out.owner_first });
600
- this.taskLog(taskId, `read ahead: code=${r.code} small=${!!r.small} owner_first=${out.owner_first}`);
616
+ const out = await client.prepared(taskId, { ...r, ...(n ? { attempt: n } : {}), handoff_version: bundle.task.handoff_version });
617
+ if (out.blocked) {
618
+ // (not a try of this task: the hub hands this runner nothing while that blocker holds, then it is read again)
619
+ this.taskLog(taskId, `read-ahead: ${r.failed}: this machine (${out.blocked}); a blocker is open on the agent, the task is read again when it is over`);
620
+ return;
621
+ }
622
+ if (out.retry) {
623
+ this.readTries.set(taskId, { v, n, notBefore: Date.now() + (this.o.readAgainMs ?? 2 * 60_000) * n });
624
+ this.taskLog(taskId, `read-ahead: ${r.failed}: read again later (try ${n})`);
625
+ return;
626
+ }
627
+ this.readTries.delete(taskId);
628
+ this.readAhead.set(taskId, { v, owner_first: !!out.owner_first });
629
+ this.taskLog(taskId, r.failed === undefined ? `read ahead: code=${r.code} small=${!!r.small} owner_first=${out.owner_first}` : `read-ahead: ${r.failed}: recorded as not finished, owner_first=${out.owner_first}`);
601
630
  }
602
631
  catch (e) {
632
+ // the hub did not take it (it is down, the task changed meanwhile): the task is not read again in the same breath, and
633
+ // the try counts (a new handoff is another version, and is read at once)
634
+ const tries = n || (before?.v === v ? before.n : 0) + 1;
635
+ this.readTries.set(taskId, { v, n: tries, notBefore: Date.now() + (this.o.readAgainMs ?? 2 * 60_000) * tries });
603
636
  this.taskLog(taskId, `read-ahead report: ${e?.message ?? e}`);
604
637
  }
605
638
  };
@@ -630,19 +663,35 @@ export class Runner {
630
663
  small: mine.map((r) => `${r.paths.join(', ')} (at most ${r.max_files ?? 3} files)`),
631
664
  });
632
665
  const result = await this.execute(rec, entry, prompt, undefined, 'prepare');
666
+ // it went quiet: reported like any other read that did not finish (left unsaid, it was read again at every look, a run each)
667
+ if (entry.reason === 'idle')
668
+ return await report({ code: true, failed: 'idle timeout: the read-ahead went quiet', draft: 'The read-ahead did not finish (idle timeout: the read-ahead went quiet); the task waits for a person to look.' });
633
669
  if (entry.reason)
634
670
  return; // stopped (cancel, shutdown): read again next time
671
+ // (the draft's words are what a hub before 3.102 records, and how it knew a read-ahead had failed)
672
+ const unread = (failed, unreadable) => report({ code: true, failed, unreadable, draft: `The read-ahead did not finish (${failed}); the task waits for a person to look.` });
673
+ if (!result.ok) {
674
+ const err = result.error ?? 'the run failed';
675
+ // the account cannot run now: execute() paused new work, and the task is read again when the pause is over
676
+ if (accountProblem(err))
677
+ return this.taskLog(taskId, `read-ahead: ${summarizeRuntimeError(err).slice(0, 200)}: read again after the pause`);
678
+ // this runner's own check confirms its sandbox or login is broken: it takes nothing until the check passes (the owner has been told)
679
+ if (this.o.sandboxCheck && (looksLikeSandboxError(err) || looksLikeLoginError(err))) {
680
+ this.sandboxRecheck = true;
681
+ if (await this.sandboxBlocked())
682
+ return this.taskLog(taskId, `read-ahead: ${summarizeRuntimeError(err).slice(0, 200)}: read again when this machine can run`);
683
+ }
684
+ return await unread(summarizeRuntimeError(err), false);
685
+ }
635
686
  let out;
636
687
  try {
637
- if (!result.ok)
638
- throw new Error(summarizeRuntimeError(result.error ?? 'the run failed'));
639
688
  out = parsePrepared(result.finalText);
640
689
  }
641
690
  catch (e) {
642
- return await report({ code: true, draft: `The read-ahead did not finish (${e?.message ?? e}); the task waits for a person to look.` });
691
+ return await unread(String(e?.message ?? e), true);
643
692
  }
644
693
  const rule = out.code ? smallRule(rules, repo, out.files) : undefined;
645
- await report({ code: out.code, small: !!rule, rule: rule ? ruleName(rule) : '', files: out.files, draft: draftText(out, rule ? ruleName(rule) : '') });
694
+ await report({ code: out.code, small: !!rule, rule: rule ? ruleName(rule) : '', files: out.files, draft: draftText(out, rule ? ruleName(rule) : ''), ran: true });
646
695
  }
647
696
  finally {
648
697
  if (!this.fatal)
@@ -933,7 +982,7 @@ export class Runner {
933
982
  if (!smallRule(loadAutorun(autorunPath(this.o.home)).rules, d.github, files))
934
983
  outside = files.slice(0, 100);
935
984
  }
936
- const say = (error) => client.taskPr(rec.taskId, { run_id: rec.runId, github: d.github, error }).catch(() => undefined);
985
+ const say = (error) => client.taskPr(rec.taskId, { run_id: rec.runId, github: d.github, error }).catch((e) => this.taskLog(rec.taskId, `pull request: the hub was not told (${error}): ${e?.message ?? e}`));
937
986
  let tok;
938
987
  try {
939
988
  tok = await client.pushToken(rec.taskId, rec.runId, d.github);
@@ -1061,7 +1110,7 @@ export class Runner {
1061
1110
  await this.reportRemote(rec, result);
1062
1111
  // a run that worked here left its changes in the task's branch (committed above): now that the task is finished, deliver them
1063
1112
  if (!this.cloud) {
1064
- const after = await client.getTask(taskId).catch(() => undefined);
1113
+ const after = await client.getTask(taskId).catch((e) => void this.taskLog(taskId, `pull request: not delivered, the finished task could not be read: ${e?.message ?? e}`));
1065
1114
  if (after)
1066
1115
  await this.deliverPr(rec, after.task, after.messages);
1067
1116
  }
@@ -23,11 +23,15 @@ export function decodeOutput(b) {
23
23
  try {
24
24
  return new TextDecoder('utf-8', { fatal: true }).decode(b);
25
25
  }
26
- catch { }
26
+ catch {
27
+ /* not UTF-8: a Chinese Windows console writes GBK, tried next */
28
+ }
27
29
  try {
28
30
  return new TextDecoder('gbk', { fatal: true }).decode(b);
29
31
  }
30
- catch { }
32
+ catch {
33
+ /* neither: shown as it is, with the bytes that do not decode replaced */
34
+ }
31
35
  return b.toString('utf8');
32
36
  }
33
37
  export const defaultRun = (file, args, opts) => new Promise((res) => {
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.101.0";
1
+ export declare const VERSION = "3.102.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.101.0';
1
+ export const VERSION = '3.102.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.101.0",
3
+ "version": "3.102.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",