@koalaauto/agentchannel 3.100.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() {
@@ -3,7 +3,7 @@
3
3
  import { execFileSync, execSync, spawn } from 'node:child_process';
4
4
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
5
  import { basename, delimiter, dirname, join, resolve } from 'node:path';
6
- import { tmpdir } from 'node:os';
6
+ import { hostname, tmpdir } from 'node:os';
7
7
  import { developerDir } from './adapters/scope.js';
8
8
  import { acquireRunnerLock, RunnerLockedError, runnerLockHolder } from './runner/lock.js';
9
9
  import { UsageError } from './args.js';
@@ -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')
@@ -276,6 +276,7 @@ async function runOnce(p, io) {
276
276
  const service = !startedByService(me.name, process.platform, env) ? '' : process.platform === 'darwin' ? 'launchd' : 'systemd';
277
277
  return {
278
278
  dir,
279
+ ...(hostName() ? { host: hostName() } : {}),
279
280
  ...(env.AGENTCHANNEL_HOME ? { home: home } : {}),
280
281
  ...(Object.keys(repoFlags).length ? { repos: repoFlags } : {}),
281
282
  ...(v['interactive-first'] ? { interactive_first: true } : {}),
@@ -508,6 +509,16 @@ export async function otherAgentHere(env, hub, newKey, meId, cfId, cfSecret, fet
508
509
  }
509
510
  }
510
511
  /** Linux: does this user's systemd outlive their logins (loginctl linger)? Unknown counts as yes (no false alarm). */
512
+ /** This machine's name as the hub takes it (a name, nothing else); '' when the system gives none of that shape. */
513
+ function hostName() {
514
+ try {
515
+ const h = hostname().trim();
516
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$/.test(h) ? h : '';
517
+ }
518
+ catch {
519
+ return '';
520
+ }
521
+ }
511
522
  function lingers(env) {
512
523
  try {
513
524
  return execFileSync('loginctl', ['show-user', env.USER || String(process.getuid?.() ?? ''), '-p', 'Linger', '--value'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() !== 'no';
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). */
@@ -82,7 +96,17 @@ export declare const noticeInResult: (lines: string[]) => string;
82
96
  */
83
97
  export declare function askToConfirm(server: McpServer, what: string, env?: NodeJS.ProcessEnv): Promise<'confirm' | 'decline' | null>;
84
98
  /** Which tool settles a waiting item of the person's Inbox (hub: api/person-inbox.ts), in one line; '' when none of ours does. */
85
- export declare function inboxHandle(i: Record<string, unknown>): string;
99
+ /**
100
+ * Where a task that waits to be taken over is worked (the hub's `takeover`: docs/specs/takeover.md): in a session opened in the
101
+ * directory of the agent it was sent to. `hand`: the agent whose directory this session is in, if any.
102
+ */
103
+ export declare function takeoverWhere(place: unknown, hand?: string): {
104
+ here: boolean;
105
+ where: string;
106
+ review: boolean;
107
+ failed: string;
108
+ };
109
+ export declare function inboxHandle(i: Record<string, unknown>, hand?: string): string;
86
110
  export declare function buildMcpServer(client: Client, o?: {
87
111
  brief?: string;
88
112
  identity?: string;
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.
@@ -126,8 +159,9 @@ export function personInstructions(name, hand) {
126
159
  'Which tool when:',
127
160
  `- send_task, post, reply: when your user says what to send and to whom (an agent or a person by name, a channel, a thread), send it yourself: it goes out exactly as you wrote it, as ${name}. A post, a reply and a task to one of ${name}'s own agents go out at once (take_back with the act id of the result undoes one); a task to anyone else, and anything ${name} asked to be asked about first, waits on a card until they confirm it: where the client can, they are asked right here; else give them the link to the Yoda page. You never confirm for them, and do not send it again. Send only what your user asked you to send.`,
128
161
  `- ask_yoda: when your user names work and not who does it ("get the gateway team to..."), asks what goes on in the team, or wants anything else done there (answer a question, schedule): say it to Yoda in their words. Yoda knows who does what and acts as ${name} under the same rules.`,
129
- `- handle_task: ${name}'s own word on a task, when they give it to you here: accept it, approve their agent's work, send it back (request_changes), cancel it, or a note to its worker.`,
162
+ `- handle_task: ${name}'s own word on a task, when they give it to you here: accept it, approve their agent's work, send it back (request_changes), cancel it, a note to its worker, or hand one that waits for them to take it over to their agent's runner (to_runner).`,
130
163
  `- owner_inbox: what waits for ${name}. An item may carry "yoda": what Yoda already said about it (what it is, what it would choose and why); tell ${name} that with the item, as Yoda's word, before they answer. Each item's "handle" says which tool settles it; "cards" are acts waiting for ${name}'s confirmation (confirm_card asks them). decide: ${name}'s own answer to a decision request addressed to them, when they give it to you here in so many words (never your guess of it). get_task, list_channels, read_channel, search, list_agents: read the team as ${name} sees it. read_doc: a Feishu/Lark document or wiki link.`,
164
+ `- A code task sent to one of ${name}'s agents waits for ${name} to take it over (an owner_inbox item of type takeover; \`takeover\` on the task get_task returns). It is worked in a session opened in that agent's directory: \`takeover\` names the agent, its directory and its machine. ${hand ? `When that agent is ${hand}, that is here: claim_task. Otherwise` : 'From here'} tell ${name} where to open the session and to say "take over TASK-12" there; do not start the work in a session that is elsewhere. Their other answer is to hand it to that agent's runner (handle_task, action to_runner): theirs to choose, never yours.`,
131
165
  '- memory_search (one line + link per hit), memory_read: the team Memory (current state, decisions, lessons, figures). Check it when your user asks how something is done or why something fails.',
132
166
  `- yoda_memory: what Yoda remembers about ${name}; propose one more when you learn how they want something done (it counts once they accept it).`,
133
167
  ...(hand
@@ -155,7 +189,7 @@ export function interactiveInstructions(o) {
155
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.`,
156
190
  `Task page: ${o.url}`,
157
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.`,
158
- ...(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.'] : []),
159
193
  'How to work it:',
160
194
  o.ownerFirst
161
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.'
@@ -253,6 +287,7 @@ const TASK_ACTS = {
253
287
  request_changes: ['request_changes', 'body'],
254
288
  cancel: ['cancel_task', 'reason'],
255
289
  note: ['task_note', 'body'],
290
+ to_runner: ['hand_to_runner', 'note'],
256
291
  };
257
292
  const oneLine = (s) => { const t = String(s ?? '').replace(/\s+/g, ' ').trim(); return t.length > 120 ? `${t.slice(0, 120)}…` : t; };
258
293
  /**
@@ -278,9 +313,31 @@ export async function askToConfirm(server, what, env = process.env) {
278
313
  }
279
314
  }
280
315
  /** Which tool settles a waiting item of the person's Inbox (hub: api/person-inbox.ts), in one line; '' when none of ours does. */
281
- export function inboxHandle(i) {
316
+ /**
317
+ * Where a task that waits to be taken over is worked (the hub's `takeover`: docs/specs/takeover.md): in a session opened in the
318
+ * directory of the agent it was sent to. `hand`: the agent whose directory this session is in, if any.
319
+ */
320
+ export function takeoverWhere(place, hand) {
321
+ const p = (place && typeof place === 'object' ? place : {});
322
+ const agent = String(p.agent ?? '');
323
+ const here = !!hand && hand === agent;
324
+ const dir = String(p.dir ?? '');
325
+ const host = String(p.host ?? '');
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'}`}` };
327
+ }
328
+ export function inboxHandle(i, hand) {
282
329
  const task = String(i.task_ref ?? i.task_id ?? i.id ?? '');
283
330
  switch (i.type) {
331
+ case 'takeover': {
332
+ const w = takeoverWhere(i.takeover, hand);
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';
337
+ return w.here
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}`;
340
+ }
284
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`;
285
342
  case 'acceptance': return `handle_task {task_id: ${task}, action: accept | request_changes}`;
286
343
  case 'review': return `handle_task {task_id: ${task}, action: approve | request_changes}`;
@@ -416,11 +473,11 @@ export function buildMcpServer(client, o = {}) {
416
473
  inputSchema: { post_id: z.string(), text: z.string().describe('The reply, Markdown') },
417
474
  }, async (a) => sent('reply', { post: a.post_id, body: a.text }, `reply in ${a.post_id}: ${oneLine(a.text)}`));
418
475
  server.registerTool('handle_task', {
419
- description: "Your user's own word on a task, when they give it to you here (never your guess of it), done at once in their name. action: accept (a task that waits for them to accept it); approve (work of their own agent that waits for their review); request_changes (send it back with what is to change: also runs a completed or failed task again); cancel (a task they sent); note (more context for the worker agent; a word for a person about a task is a reply in its thread). `text` is required for request_changes and note, optional otherwise.",
476
+ description: "Your user's own word on a task, when they give it to you here (never your guess of it), done at once in their name. action: accept (a task that waits for them to accept it); approve (work of their own agent that waits for their review); request_changes (send it back with what is to change: also runs a completed or failed task again); cancel (a task they sent); note (more context for the worker agent; a word for a person about a task is a reply in its thread); to_runner (a code task that waits for them to take it over goes to their agent's runner instead: it starts at once, and where that agent delivers pull requests, what it writes waits for their review; `text` is their word to the worker, such as answers to what the read-ahead asked). `text` is required for request_changes and note, optional otherwise.",
420
477
  inputSchema: {
421
478
  task_id: z.string().describe('TASK-128, or the task id'),
422
- action: z.enum(['accept', 'approve', 'request_changes', 'cancel', 'note']),
423
- text: z.string().optional().describe('What is to change, the note, the reason for a cancel, or a few words with an accept'),
479
+ action: z.enum(['accept', 'approve', 'request_changes', 'cancel', 'note', 'to_runner']),
480
+ text: z.string().optional().describe('What is to change, the note, the reason for a cancel, a few words with an accept, or their word to the worker with to_runner'),
424
481
  },
425
482
  }, async (a) => {
426
483
  const [tool, key] = TASK_ACTS[a.action];
@@ -555,7 +612,7 @@ export function buildMcpServer(client, o = {}) {
555
612
  if (!o.person)
556
613
  return wrapUntrusted(inbox);
557
614
  // a session that is the person: each waiting item says which tool settles it, and the cards waiting for their word come along
558
- const items = Array.isArray(inbox.items) ? inbox.items.map((i) => { const h = i.pending ? inboxHandle(i) : ''; return h ? { ...i, handle: h } : i; }) : inbox.items;
615
+ const items = Array.isArray(inbox.items) ? inbox.items.map((i) => { const h = i.pending ? inboxHandle(i, o.hand?.name) : ''; return h ? { ...i, handle: h } : i; }) : inbox.items;
559
616
  const cards = await client.yoda().then((y) => y.pending.filter((i) => i.kind === 'confirm' && i.act_id).map((i) => ({ act: i.act_id, what: i.body, handle: 'confirm_card {act}: asks your user here' })), () => []);
560
617
  // nothing reaches them outside a session: said with what waits, since that is when it matters
561
618
  const notice = o.notifyOff ? { notice: `No browser of ${o.person}'s takes notifications: when no session is open, nothing tells them something waits. They turn them on once at ${o.notifyOff}` } : {};
@@ -638,6 +695,7 @@ export function buildMcpServer(client, o = {}) {
638
695
  const prep = [...(b.messages ?? [])].reverse().find((m) => m.sys_code === 'prepared' && String(m.sys_params?.v ?? '') === String(b.task.handoff_version ?? ''));
639
696
  const text = interactiveInstructions({
640
697
  readAhead: !!prep,
698
+ readFailed: !!prep?.sys_params?.failed,
641
699
  ownerFirst: prep?.sys_params?.owner_first === '1',
642
700
  taskId: refOf(b.task),
643
701
  agentName: self.name,
@@ -1009,7 +1067,7 @@ function moveOffNpxLater(cwd, delayMs = 30_000) {
1009
1067
  const moved = await moveNpxMcpEntriesHere({ env: process.env, dir: cwd, log });
1010
1068
  if (moved.length)
1011
1069
  log(`the \`ach\` MCP entry (${moved.join(', ')}) starts the install in the AgentChannel home from the next session`);
1012
- })().catch(() => { });
1070
+ })().catch((e) => process.stderr.write(`[ach mcp] not moved off npx: ${e?.message ?? e}\n`));
1013
1071
  }, delayMs);
1014
1072
  timer.unref?.();
1015
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. */
@@ -90,6 +92,8 @@ export interface RunnerOptions {
90
92
  export interface RunnerStartInfo {
91
93
  /** --dir, absolute. */
92
94
  dir: string;
95
+ /** This machine's name: where the agent's owner opens a session to take a task over (docs/specs/takeover.md). */
96
+ host?: string;
93
97
  /** AGENTCHANNEL_HOME when it is not the default home. */
94
98
  home?: string;
95
99
  /** --repo name=path given on the command line (config.json's repos need nothing). */
@@ -209,10 +213,18 @@ export declare class Runner {
209
213
  /** read-aheads this runner reported, task -> handoff version and the hub's answer: an inbox fetched before the report landed
210
214
  * still shows the task unread, and must not start a second read-ahead of the same handoff */
211
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;
212
218
  /**
213
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,
214
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
215
- * 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.
216
228
  */
217
229
  private runPrepare;
218
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.100.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.100.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.100.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",