@koalaauto/agentchannel 3.50.0 → 3.51.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.
@@ -558,6 +558,11 @@ export declare class Client {
558
558
  release(taskId: string, reason: string, run_id?: string): Promise<any>;
559
559
  /** The repo names this runner can work in (never local paths): the directory shows them, and the hub refuses a task for another repo. */
560
560
  reportRepos(repos: string[], remotes?: Record<string, string>): Promise<any>;
561
+ /** A description the runner wrote from the repository it works in; the hub keeps it only if the agent's description is still empty. */
562
+ reportDescription(description: string): Promise<{
563
+ ok: boolean;
564
+ set: boolean;
565
+ }>;
561
566
  /** How this runner runs tasks: its --perm, the tool, and the NAMES of the variables it hands its agents (never values); and how
562
567
  * it was started (directory, home, --repo paths, its supervisor), which the owner's page turns into the line that restarts it. */
563
568
  /** The models the runtime offers on the runner's machine and the one a run uses when none is picked (the agent's settings list them). */
@@ -396,6 +396,10 @@ export class Client {
396
396
  async reportRepos(repos, remotes) {
397
397
  return this.ach('PUT', '/me/repos', { repos, ...(remotes ? { remotes } : {}) });
398
398
  }
399
+ /** A description the runner wrote from the repository it works in; the hub keeps it only if the agent's description is still empty. */
400
+ async reportDescription(description) {
401
+ return this.ach('PUT', '/me/description', { description });
402
+ }
399
403
  /** How this runner runs tasks: its --perm, the tool, and the NAMES of the variables it hands its agents (never values); and how
400
404
  * it was started (directory, home, --repo paths, its supervisor), which the owner's page turns into the line that restarts it. */
401
405
  /** The models the runtime offers on the runner's machine and the one a run uses when none is picked (the agent's settings list them). */
@@ -18,14 +18,20 @@ export declare function probeEnvironment(tool: SandboxTool, o?: ProbeOptions & {
18
18
  * lines that look like a cause come first (at most 3), then the first remaining line; capped at 600 characters.
19
19
  */
20
20
  export declare function summarizeRuntimeError(raw: string): string;
21
- /** Does a run's error say the tool is not logged in (or its key was refused)? */
22
21
  /**
23
- * The account behind the runtime has no budget left right now (a weekly or daily usage limit, rate limit or overload), so the next
24
- * task would fail the same way. `pauseMs` is how long to wait: a usage limit lasts until it resets, a rate limit or overload is short.
22
+ * The account behind the runtime cannot run anything right now, so the next task would fail the same way. `pauseMs` is how long the
23
+ * runner takes nothing new before it tries again.
24
+ * - billing: the account's plan or credit is not usable (a payment past due, an ended subscription, no credit left). It does not
25
+ * come back by itself: a person pays or logs in with another account, so the owner is told. A run that fails this way costs
26
+ * nothing, so the retry is the check.
27
+ * - limit: a usage or rate limit, or an overload. It resets by itself: a usage limit after a while, a rate limit or overload soon.
25
28
  */
26
- export declare function quotaProblem(s: string): {
29
+ export type AccountProblem = {
30
+ kind: 'billing' | 'limit';
27
31
  pauseMs: number;
28
- } | null;
32
+ };
33
+ export declare const BILLING_ERROR: RegExp;
34
+ export declare function accountProblem(s: string): AccountProblem | null;
29
35
  /**
30
36
  * The runtime refused the model it was asked for (a typo, one the account cannot use): Claude Code's "issue with the selected
31
37
  * model (x). It may not exist or you may not have access to it", the API's not_found_error on a model, Codex's "model `x` does
@@ -34,4 +40,5 @@ export declare function quotaProblem(s: string): {
34
40
  /** The runtime refused the effort level it was asked for (one the model does not take). */
35
41
  export declare function effortRejected(s: string | undefined): boolean;
36
42
  export declare function modelRejected(s: string | undefined): boolean;
43
+ /** Does a run's error say the tool is not logged in (or its key was refused)? */
37
44
  export declare function looksLikeLoginError(s: string): boolean;
@@ -92,16 +92,14 @@ export function summarizeRuntimeError(raw) {
92
92
  picked.unshift(lines[0]);
93
93
  return picked.join(' | ').slice(0, 600);
94
94
  }
95
- /** Does a run's error say the tool is not logged in (or its key was refused)? */
96
- /**
97
- * The account behind the runtime has no budget left right now (a weekly or daily usage limit, rate limit or overload), so the next
98
- * task would fail the same way. `pauseMs` is how long to wait: a usage limit lasts until it resets, a rate limit or overload is short.
99
- */
100
- export function quotaProblem(s) {
101
- if (/hit your (weekly |daily |monthly |usage |5-hour |session )?limit|usage limit|weekly limit|session limit|5-hour limit|limit reached|quota (exceeded|reached)|insufficient (credit|quota)|credit balance/i.test(s))
102
- return { pauseMs: 30 * 60_000 };
95
+ export const BILLING_ERROR = /can[’']?t use your (claude )?subscription|payment (is )?past due|pay or renew|credit balance is too low|insufficient[ _](credit|quota)|subscription (has )?(expired|ended|lapsed|been cancell?ed)|no active subscription/i;
96
+ export function accountProblem(s) {
97
+ if (BILLING_ERROR.test(s))
98
+ return { kind: 'billing', pauseMs: 10 * 60_000 };
99
+ if (/hit your (weekly |daily |monthly |usage |5-hour |session )?limit|usage limit|weekly limit|session limit|5-hour limit|limit reached|quota (exceeded|reached)/i.test(s))
100
+ return { kind: 'limit', pauseMs: 30 * 60_000 };
103
101
  if (/rate.?limit|\b429\b|overloaded|too many requests/i.test(s))
104
- return { pauseMs: 5 * 60_000 };
102
+ return { kind: 'limit', pauseMs: 5 * 60_000 };
105
103
  return null;
106
104
  }
107
105
  /**
@@ -120,6 +118,7 @@ export function modelRejected(s) {
120
118
  return false;
121
119
  return /issue with the selected model|\bmodel\b[^\n]{0,80}\b(does not exist|not found|not available|not supported|is not (a )?valid|unknown|invalid|you do not have access)|\b(invalid|unknown|unsupported) model\b|not_found_error[^\n]{0,40}model/i.test(s);
122
120
  }
121
+ /** Does a run's error say the tool is not logged in (or its key was refused)? */
123
122
  export function looksLikeLoginError(s) {
124
123
  return /\b401\b|unauthori[sz]ed|not logged in|please (run|log)[^.\n]*login|invalid (api )?key|authentication (failed|required|error)|credentials? (expired|missing|invalid)/i.test(s);
125
124
  }
package/dist/src/mcp.js CHANGED
@@ -188,7 +188,7 @@ export function buildMcpServer(client, o = {}) {
188
188
  }
189
189
  return task.run_id;
190
190
  }
191
- server.registerTool('list_agents', { description: 'List the team\'s agents (name, owner, runtime, what they are good at, the repos their runner works in). Use it to pick who to hand work to; a task\'s repo must be one of the receiver\'s repos when it lists any.', inputSchema: {} }, async () => wrap(() => client.agents()));
191
+ server.registerTool('list_agents', { description: 'List the team\'s agents (name, owner, runtime, description, the repos their runner works in, capabilities, when the runner was last seen, blockers). Use it to pick who to hand work to or ask: read the description and repos for what each is for, runner_at for whether it is running, blockers for what it cannot do right now. A task\'s repo must be one of the receiver\'s repos when it lists any.', inputSchema: {} }, async () => wrap(() => client.agents()));
192
192
  server.registerTool('send_task', {
193
193
  description: `Hand a piece of work to another agent as a task. The receiving agent is woken on its machine (or its owner picks it up interactively) and works in a fresh git worktree. ${TASK_FIELDS_HELP} ${HANDOFF_HELP}`,
194
194
  inputSchema: {
@@ -7,7 +7,7 @@ import { TraceRecorder } from '../trace.js';
7
7
  import { type SandboxStatus } from '../sandboxcheck.js';
8
8
  export * from './home.js';
9
9
  export * from './structured.js';
10
- export type RunnerClient = Pick<Client, 'me' | 'inbox' | 'claim' | 'getTask' | 'postMessage' | 'complete' | 'fail' | 'usage' | 'heartbeat' | 'answerRun' | 'endRun'> & Partial<Pick<Client, 'download' | 'githubToken' | 'channelPosts' | 'mentionRun' | 'mentionEnd' | 'mentionUsage' | 'promptSize' | 'reportSetup' | 'reportRepos' | 'reportRunner' | 'reportModels' | 'release' | 'putTrace' | 'pushToken' | 'taskPr' | 'prepareRun' | 'prepared'>>;
10
+ export type RunnerClient = Pick<Client, 'me' | 'inbox' | 'claim' | 'getTask' | 'postMessage' | 'complete' | 'fail' | 'usage' | 'heartbeat' | 'answerRun' | 'endRun'> & Partial<Pick<Client, 'download' | 'githubToken' | 'channelPosts' | 'mentionRun' | 'mentionEnd' | 'mentionUsage' | 'promptSize' | 'reportSetup' | 'reportRepos' | 'reportDescription' | 'reportRunner' | 'reportModels' | 'release' | 'putTrace' | 'pushToken' | 'taskPr' | 'prepareRun' | 'prepared'>>;
11
11
  export interface RunnerOptions {
12
12
  client: RunnerClient;
13
13
  adapter: RuntimeAdapter;
@@ -143,10 +143,12 @@ export declare class Runner {
143
143
  private githubOffUntil;
144
144
  /** When old work dirs were last cleaned up (ms); the first prune of a process does it. */
145
145
  private lastGc;
146
- /** No new task is taken before this time (ms): the account behind the runtime is out of budget. */
147
- private quotaUntil;
148
- /** How often each task was handed back for an account limit (in this process). */
149
- private quotaReleases;
146
+ /** No new task is taken before this time (ms): the account behind the runtime cannot run (a limit, or its plan or credit). */
147
+ private accountPausedUntil;
148
+ /** The account's plan or credit was not usable in the last run (the owner hears it as a setup problem); cleared by a run that works. */
149
+ private account?;
150
+ /** How often each task was handed back for an account problem (in this process). */
151
+ private accountReleases;
150
152
  /** When each parked task was last looked at on the hub (ms). */
151
153
  private parkedChecked;
152
154
  private o;
@@ -166,7 +168,7 @@ export declare class Runner {
166
168
  st: SandboxStatus;
167
169
  at: number;
168
170
  };
169
- private sandboxReported?;
171
+ private setupReported?;
170
172
  private sandboxRecheck;
171
173
  /** Execution traces the hub has not taken yet (kept on disk too), and the last trace of each task (a commit joins it). */
172
174
  private traces;
@@ -186,11 +188,25 @@ export declare class Runner {
186
188
  tick(): Promise<void>;
187
189
  /** decisions §27: probe the sandbox when due, tell the hub when the answer changes; true = take nothing new. */
188
190
  private sandboxBlocked;
191
+ /** Tell the hub what keeps this runner from working, when that changed: a failed check first, else an account that cannot run. */
192
+ private reportSetup;
193
+ /**
194
+ * What a run says about the account behind the runtime: a limit or a plan that is not usable pauses new work (whatever the run
195
+ * was for: a task, an answer, a mention), and the plan problem is the owner's to fix, so it is reported like a broken sandbox.
196
+ * A run that works clears it.
197
+ */
198
+ private noteAccount;
189
199
  /** Tell the hub which repo names this runner knows, so a task for another repo is refused when it is sent. Tried on every
190
200
  * poll until the hub has it: a hub that was unreachable at start would otherwise keep the previous list until a restart. */
191
201
  private reposReported;
192
202
  private reportRepos;
193
203
  private reposLogged;
204
+ /** An agent with no description gets one, once: a short read-only run on a light model reads the repositories it works in and
205
+ * writes a sentence or two. The hub keeps it only while the description is empty, so a person's own text is never replaced, and
206
+ * the owner edits it like any other. Tried again at the next start when it could not be had. */
207
+ private describeDone;
208
+ private describeBusy;
209
+ private describeAgent;
194
210
  /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
195
211
  * owner sees on its page what a task sent to it can reach. Tried on every poll until the hub has it; an older hub (404) is left alone. */
196
212
  private runnerReported;
@@ -321,3 +337,5 @@ export declare function gcWorktrees(client: Pick<Client, 'getTask'>, ws: Workspa
321
337
  log?: (s: string) => void;
322
338
  keepFailed?: boolean;
323
339
  }): Promise<string[]>;
340
+ /** The model's text as a description: its first paragraph, without markdown marks or wrapping quotes, at most 300 characters. */
341
+ export declare function cleanDescription(raw: string): string;
@@ -18,10 +18,10 @@ import { effectivePerm } from '../perm.js';
18
18
  import { ANSWER_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildPreparePrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
19
19
  import { RunnerState } from './state.js';
20
20
  import { isGitRepo } from './workspace.js';
21
- import { effortRejected, looksLikeLoginError, modelRejected, quotaProblem, summarizeRuntimeError } from '../envcheck.js';
21
+ import { accountProblem, effortRejected, looksLikeLoginError, modelRejected, summarizeRuntimeError } from '../envcheck.js';
22
22
  import { redact } from '../redact.js';
23
23
  import { TraceRecorder } from '../trace.js';
24
- import { looksLikeSandboxError } from '../sandboxcheck.js';
24
+ import { detectHost, looksLikeSandboxError, sandboxFix } from '../sandboxcheck.js';
25
25
  import { prepareAgentHome, realHomeOf, secretPaths } from './home.js';
26
26
  import { draftText, parsePrepared, parseStructured } from './structured.js';
27
27
  import { TraceQueue } from './traces.js';
@@ -104,8 +104,8 @@ export function unseenReplies(messages, myId, seen) {
104
104
  return messages.filter((m) => !seenSet.has(m.id) &&
105
105
  (((m.kind === 'answer' || m.kind === 'decision') && ((m.reply_to && mine.has(m.reply_to)) || m.to_agent === myId)) || isHumanNoteTo(m, myId)));
106
106
  }
107
- /** A task handed back this many times for an account limit then fails normally. */
108
- const QUOTA_RELEASES = 3;
107
+ /** A task handed back this many times for an account's usage or rate limit then fails normally. */
108
+ const ACCOUNT_RELEASES = 3;
109
109
  export function budgetBlocked(me) {
110
110
  const budget = Number(me.budget_usd ?? 0);
111
111
  return budget > 0 && Number(me.spent_usd ?? 0) >= budget;
@@ -123,10 +123,12 @@ export class Runner {
123
123
  githubOffUntil = 0;
124
124
  /** When old work dirs were last cleaned up (ms); the first prune of a process does it. */
125
125
  lastGc = 0;
126
- /** No new task is taken before this time (ms): the account behind the runtime is out of budget. */
127
- quotaUntil = 0;
128
- /** How often each task was handed back for an account limit (in this process). */
129
- quotaReleases = new Map();
126
+ /** No new task is taken before this time (ms): the account behind the runtime cannot run (a limit, or its plan or credit). */
127
+ accountPausedUntil = 0;
128
+ /** The account's plan or credit was not usable in the last run (the owner hears it as a setup problem); cleared by a run that works. */
129
+ account;
130
+ /** How often each task was handed back for an account problem (in this process). */
131
+ accountReleases = new Map();
130
132
  /** When each parked task was last looked at on the hub (ms). */
131
133
  parkedChecked = new Map();
132
134
  o;
@@ -143,7 +145,7 @@ export class Runner {
143
145
  wake;
144
146
  /** decisions §27: the last sandbox probe, when it ran, and what the hub was last told (a JSON key). */
145
147
  sandbox;
146
- sandboxReported;
148
+ setupReported;
147
149
  sandboxRecheck = false;
148
150
  /** Execution traces the hub has not taken yet (kept on disk too), and the last trace of each task (a commit joins it). */
149
151
  traces;
@@ -250,8 +252,8 @@ export class Runner {
250
252
  await this.notifyBudget(t, me);
251
253
  continue;
252
254
  }
253
- if (now < this.quotaUntil)
254
- continue; // out of usage at the provider: the pause is over soon enough
255
+ if (now < this.accountPausedUntil)
256
+ continue; // the account cannot run: it is tried again when the pause is over
255
257
  // a code task waits for its owner to take it over (owner-pulls-tasks.md): read each new one ahead first, then work only what
256
258
  // is not code, or one of the owner's declared small jobs; what the owner sent themselves is theirs to hand to the runner
257
259
  if (this.readsAhead(me) && !t.from_owner) {
@@ -317,25 +319,56 @@ export class Runner {
317
319
  this.log(`sandbox: ${st.fix?.en ?? st.detail ?? st.problem} Taking no tasks until it works.${st.fix?.commands.length ? `\n fix:\n${st.fix.commands.map((c) => ` ${c}`).join('\n')}` : ''}`);
318
320
  }
319
321
  }
320
- const st = this.sandbox.st;
321
- const report = st.ok ? null : { tool: st.tool, problem: st.problem ?? 'failed', ...(st.detail ? { detail: st.detail } : {}), ...(st.fix ? { fix: st.fix } : {}) };
322
+ await this.reportSetup();
323
+ return !this.sandbox.st.ok;
324
+ }
325
+ /** Tell the hub what keeps this runner from working, when that changed: a failed check first, else an account that cannot run. */
326
+ async reportSetup() {
327
+ const st = this.sandbox && !this.sandbox.st.ok ? this.sandbox.st : this.account;
328
+ const report = !st ? null : { tool: st.tool, problem: st.problem ?? 'failed', ...(st.detail ? { detail: st.detail } : {}), ...(st.fix ? { fix: st.fix } : {}) };
322
329
  const key = JSON.stringify(report);
323
- if (key !== this.sandboxReported && this.o.client.reportSetup) {
330
+ if (key !== this.setupReported && this.o.client.reportSetup) {
324
331
  try {
325
332
  await this.o.client.reportSetup(report);
326
- this.sandboxReported = key;
333
+ this.setupReported = key;
327
334
  }
328
335
  catch (e) {
329
336
  if (is401(e))
330
337
  this.authFailed('setup');
331
338
  // an older hub without /me/setup: the log above is all there is
332
339
  else if (e instanceof HubError && e.status === 404)
333
- this.sandboxReported = key;
340
+ this.setupReported = key;
334
341
  else
335
342
  this.log(`setup report: ${e?.message ?? e}`);
336
343
  }
337
344
  }
338
- return !st.ok;
345
+ }
346
+ /**
347
+ * What a run says about the account behind the runtime: a limit or a plan that is not usable pauses new work (whatever the run
348
+ * was for: a task, an answer, a mention), and the plan problem is the owner's to fix, so it is reported like a broken sandbox.
349
+ * A run that works clears it.
350
+ */
351
+ async noteAccount(result) {
352
+ const problem = result.ok ? null : accountProblem(result.error ?? '');
353
+ if (problem)
354
+ this.accountPausedUntil = Math.max(this.accountPausedUntil, Date.now() + problem.pauseMs);
355
+ const billing = problem?.kind === 'billing';
356
+ if (!billing && !(result.ok && this.account))
357
+ return;
358
+ const was = this.account;
359
+ const tool = ['claude', 'codex', 'kiro'].find((x) => x === this.o.adapter.name) ?? 'claude';
360
+ if (billing) {
361
+ const st = { tool, ok: false, problem: 'billing', detail: summarizeRuntimeError(result.error ?? '').slice(0, 300) };
362
+ st.fix = sandboxFix(st, detectHost(process.env, process.platform));
363
+ this.account = st;
364
+ if (!was)
365
+ this.log(`account: ${st.fix.en} Taking no tasks until a run works; trying again every ${problem.pauseMs / 60_000} min.`);
366
+ }
367
+ else {
368
+ this.account = undefined;
369
+ this.log('account: runs work again');
370
+ }
371
+ await this.reportSetup();
339
372
  }
340
373
  /** Tell the hub which repo names this runner knows, so a task for another repo is refused when it is sent. Tried on every
341
374
  * poll until the hub has it: a hub that was unreachable at start would otherwise keep the previous list until a restart. */
@@ -364,6 +397,77 @@ export class Runner {
364
397
  }
365
398
  }
366
399
  reposLogged = false;
400
+ /** An agent with no description gets one, once: a short read-only run on a light model reads the repositories it works in and
401
+ * writes a sentence or two. The hub keeps it only while the description is empty, so a person's own text is never replaced, and
402
+ * the owner edits it like any other. Tried again at the next start when it could not be had. */
403
+ describeDone = false;
404
+ describeBusy = false;
405
+ async describeAgent() {
406
+ const { adapter, client, workspace } = this.o;
407
+ if (this.describeDone || this.describeBusy || adapter.remote || !client.reportDescription || !workspace.repoDirs)
408
+ return;
409
+ this.describeBusy = true;
410
+ try {
411
+ const me = await this.ensureMe();
412
+ if (me.role === 'system' || String(me.description ?? '').trim()) {
413
+ this.describeDone = true;
414
+ return;
415
+ }
416
+ const dirs = Object.entries(await workspace.repoDirs()).slice(0, 4);
417
+ if (!dirs.length)
418
+ return;
419
+ const baseEnv = this.o.baseEnv ?? process.env;
420
+ const realHome = realHomeOf(baseEnv);
421
+ const { env } = prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, 'describe', realHome, baseEnv.CODEX_HOME || undefined);
422
+ const run = async (pick) => {
423
+ const ctl = new AbortController();
424
+ const timer = setTimeout(() => ctl.abort(), 3 * 60_000);
425
+ try {
426
+ return await adapter.run({
427
+ ...(pick ? { model: pick.model, effort: pick.effort } : {}),
428
+ prompt: describePrompt(me.name, dirs),
429
+ cwd: dirs[0][1],
430
+ perm: 'read',
431
+ mode: 'answer',
432
+ env: { ...inheritedEnv(baseEnv, this.o.passEnv), ...env },
433
+ signal: ctl.signal,
434
+ hub: this.o.hub,
435
+ denyReadPaths: secretPaths(this.o.home),
436
+ ...(realHome ? { realHome } : {}),
437
+ readRoots: dirs.map(([, d]) => d),
438
+ ...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
439
+ ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
440
+ ...(adapter.name === 'claude' ? { maxBudgetUsd: 0.05 } : {}),
441
+ ...(adapter.structuredAnswers ? { outputSchema: DESCRIBE_SCHEMA } : {}),
442
+ onEvent: () => { },
443
+ });
444
+ }
445
+ finally {
446
+ clearTimeout(timer);
447
+ }
448
+ };
449
+ // the light model where the runtime has one; a model the account cannot use falls back to the runtime's default
450
+ const light = DESCRIBE_MODELS[adapter.name];
451
+ let r = await run(light);
452
+ if (!r.ok && light)
453
+ r = await run(undefined);
454
+ const text = cleanDescription(r.finalText);
455
+ if (!r.ok || !text)
456
+ throw new Error(r.error ? summarizeRuntimeError(r.error).slice(0, 160) : 'no description came back');
457
+ await client.reportDescription(text);
458
+ this.describeDone = true;
459
+ this.log(`description: ${text.slice(0, 120)}`);
460
+ }
461
+ catch (e) {
462
+ // once per start, whatever the outcome; an older hub without /me/description (404) says nothing
463
+ if (!(e instanceof HubError && e.status === 404))
464
+ this.log(`description: ${String(e?.message ?? e).slice(0, 200)} (trying again at the next start)`);
465
+ this.describeDone = true;
466
+ }
467
+ finally {
468
+ this.describeBusy = false;
469
+ }
470
+ }
367
471
  /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
368
472
  * owner sees on its page what a task sent to it can reach. Tried on every poll until the hub has it; an older hub (404) is left alone. */
369
473
  runnerReported = false;
@@ -635,7 +739,7 @@ export class Runner {
635
739
  }
636
740
  async runJob(job, entry) {
637
741
  // queued before the account ran out: it stays on the hub (submitted) and is taken again after the pause
638
- if (job.kind === 'work' && Date.now() < this.quotaUntil)
742
+ if (job.kind === 'work' && Date.now() < this.accountPausedUntil)
639
743
  return;
640
744
  if (job.kind === 'work')
641
745
  return this.runWork(job.taskId, entry);
@@ -1114,16 +1218,18 @@ export class Runner {
1114
1218
  }
1115
1219
  if (!result.ok) {
1116
1220
  const err = result.error ?? 'unknown';
1117
- // The account has no budget left (a usage or rate limit): the task goes back to the queue untouched and this runner takes
1118
- // nothing new until the pause is over, instead of failing every queued task one by one for the same reason.
1119
- const quota = quotaProblem(err);
1120
- // released for this at most QUOTA_RELEASES times: a task whose own failure text mentions a rate limit (a third-party 429) must
1121
- // still be able to fail
1122
- const quotaTimes = (this.quotaReleases.get(taskId) ?? 0) + 1;
1123
- if (quota && client.release && quotaTimes <= QUOTA_RELEASES) {
1124
- this.quotaReleases.set(taskId, quotaTimes);
1125
- this.quotaUntil = Math.max(this.quotaUntil, Date.now() + quota.pauseMs);
1126
- const why = `the account behind ${this.o.adapter.name} hit a usage or rate limit (${summarizeRuntimeError(err).slice(0, 160)}); this runner takes no new task until ${new Date(this.quotaUntil).toISOString().slice(11, 16)} UTC`;
1221
+ // The account cannot run (a usage or rate limit, or its plan or credit is not usable): the task goes back to the queue
1222
+ // untouched and this runner takes nothing new until the pause is over (execute() set it), instead of failing every queued
1223
+ // task one by one for the same reason.
1224
+ const account = accountProblem(err);
1225
+ // released for a limit at most ACCOUNT_RELEASES times: a task whose own failure text mentions a rate limit (a third-party 429)
1226
+ // must still be able to fail. A billing error is the tool's own refusal to start: the task waits like it does for a broken
1227
+ // sandbox, and the owner has been told.
1228
+ const times = (this.accountReleases.get(taskId) ?? 0) + 1;
1229
+ if (account && client.release && (account.kind === 'billing' || times <= ACCOUNT_RELEASES)) {
1230
+ this.accountReleases.set(taskId, times);
1231
+ const what = account.kind === 'billing' ? 'cannot run: its plan or credit is not usable' : 'hit a usage or rate limit';
1232
+ const why = `the account behind ${this.o.adapter.name} ${what} (${summarizeRuntimeError(err).slice(0, 160)}); this runner takes no new task until ${new Date(this.accountPausedUntil).toISOString().slice(11, 16)} UTC`;
1127
1233
  const done = await client.release(taskId, why, rec.runId).then(() => true, (e) => { this.log(`release ${taskId}: ${e?.message ?? e}`); return false; });
1128
1234
  if (done) {
1129
1235
  this.log(why);
@@ -1618,6 +1724,8 @@ export class Runner {
1618
1724
  if (!this.fatal)
1619
1725
  await usage(runCost, !!result.estimated, { model: result.model, effort: result.effort }).catch((e) => this.log(`usage ${taskId}: ${e?.message ?? e}`));
1620
1726
  this.taskLog(taskId, `${mode} run end ok=${result.ok} cost=${result.costUsd ?? 0} model=${result.model ?? '?'} effort=${result.effort ?? '?'} err=${result.error ?? ''}`);
1727
+ if (!this.fatal)
1728
+ await this.noteAccount(result);
1621
1729
  if (mode !== 'mention' && !this.o.noTrace)
1622
1730
  await this.traces.add(taskId, rec.runId, mode, startedAt, result, recorder, !this.fatal);
1623
1731
  return result;
@@ -1655,6 +1763,7 @@ export class Runner {
1655
1763
  await this.reportRunner();
1656
1764
  // not awaited: listing starts the tool (up to a few seconds), and claiming work must not wait for it
1657
1765
  void this.reportModels();
1766
+ void this.describeAgent();
1658
1767
  await this.tick();
1659
1768
  }
1660
1769
  catch (e) {
@@ -1737,3 +1846,34 @@ function promptFile(f) {
1737
1846
  const { key: _key, ...rest } = f;
1738
1847
  return rest;
1739
1848
  }
1849
+ /** The light model that writes an agent's description, per runtime (none listed: the runtime's default). A runtime that does not
1850
+ * take it runs the default instead. */
1851
+ const DESCRIBE_MODELS = {
1852
+ claude: { model: 'claude-haiku-5-5', effort: 'low' },
1853
+ codex: { model: 'gpt-6.1-sol', effort: 'medium' },
1854
+ };
1855
+ const DESCRIBE_SCHEMA = { type: 'object', properties: { description: { type: 'string' } }, required: ['description'], additionalProperties: false };
1856
+ function describePrompt(name, dirs) {
1857
+ const where = dirs.map(([n, d]) => `- ${n}: ${d}`).join('\n');
1858
+ return [
1859
+ `You are writing the one-paragraph profile of the agent "${name}" for the team directory. Teammates and other agents read it to decide whether to send this agent a piece of work.`,
1860
+ `The agent works in these repositories (read-only for you; start with README, CLAUDE.md, AGENTS.md and the top-level layout, do not read everything):`,
1861
+ where,
1862
+ `Write one or two sentences in Chinese: what the repository is for and what kind of work belongs with this agent. Be specific (name the main parts or systems), not generic. At most 160 characters. Plain text only: no markdown, no quotes, no list, no preface.`,
1863
+ 'Answer with the profile text only.',
1864
+ ].filter(Boolean).join('\n\n');
1865
+ }
1866
+ /** The model's text as a description: its first paragraph, without markdown marks or wrapping quotes, at most 300 characters. */
1867
+ export function cleanDescription(raw) {
1868
+ let t = String(raw ?? '').trim();
1869
+ try {
1870
+ const j = JSON.parse(t);
1871
+ if (j && typeof j.description === 'string')
1872
+ t = j.description;
1873
+ }
1874
+ catch {
1875
+ /* plain text */
1876
+ }
1877
+ t = t.split(/\n\s*\n/)[0].replace(/[`*_#>]/g, '').replace(/\s+/g, ' ').trim().replace(/^["'“”「」]+|["'“”「」]+$/g, '').trim();
1878
+ return t.slice(0, 300);
1879
+ }
@@ -18,6 +18,8 @@ export interface Workspace {
18
18
  /** The repo names a task may name (links.repo, links.repos): the runner tells the hub, which refuses others when sent.
19
19
  * Only git checkouts: a task that names a plain directory would get an empty work dir. */
20
20
  repoNames?(): string[] | Promise<string[]>;
21
+ /** Where each of those repos is on this machine: {name: absolute path}. Read by the runner itself, never sent to the hub. */
22
+ repoDirs?(): Promise<Record<string, string>>;
21
23
  /** Where each of those comes from: {name: "owner/name"} of its origin (never a local path). The hub tells a sender whose handoff names another repository. */
22
24
  repoRemotes?(): Promise<Record<string, string>>;
23
25
  /**
@@ -65,6 +67,7 @@ export declare class GitWorkspace implements Workspace {
65
67
  /** The local repo a task works in (P3). */
66
68
  repoDir(task: Task): string;
67
69
  repoNames(): Promise<string[]>;
70
+ repoDirs(): Promise<Record<string, string>>;
68
71
  repoRemotes(): Promise<Record<string, string>>;
69
72
  /** Map a repo name to its local path, or fail with the names this runner knows. */
70
73
  lookup(r: unknown, what: string): string;
@@ -86,6 +86,12 @@ export class GitWorkspace {
86
86
  }
87
87
  return out;
88
88
  }
89
+ async repoDirs() {
90
+ const out = {};
91
+ for (const n of await this.repoNames())
92
+ out[n] = this.lookup(n, 'repo');
93
+ return out;
94
+ }
89
95
  async repoRemotes() {
90
96
  const out = {};
91
97
  for (const n of await this.repoNames()) {
@@ -25,6 +25,8 @@ export type SandboxProblem =
25
25
  | 'unsupported'
26
26
  /** the tool is not logged in on this machine (envcheck.ts): not the sandbox, but the same "takes no tasks" state */
27
27
  | 'not-logged-in'
28
+ /** the account the tool is logged in with cannot run (a payment past due, no credit left), seen in a run's error (envcheck.ts) */
29
+ | 'billing'
28
30
  /** Codex's sandbox starts but has no network although the runner asks for it: the agent's `ach` cannot reach the hub (`detail`: the host) */
29
31
  | 'no-network'
30
32
  /** anything else: `detail` has the first line of the error */
@@ -361,7 +361,7 @@ export const BWRAP_APPARMOR = `printf '%s\\n' 'abi <abi/4.0>,' 'include <tunable
361
361
  `| sudo tee /etc/apparmor.d/bwrap >/dev/null && sudo apparmor_parser -r /etc/apparmor.d/bwrap`;
362
362
  /** The fix for a failed probe on this host. */
363
363
  export function sandboxFix(st, host) {
364
- const name = st.tool === 'claude' ? 'Claude Code' : 'Codex';
364
+ const name = st.tool === 'claude' ? 'Claude Code' : st.tool === 'kiro' ? 'Kiro' : 'Codex';
365
365
  // the Codex package came without its platform binary (an optional dependency npm skipped): runs cannot start either
366
366
  if (st.tool === 'codex' && /Missing optional dependency @openai\/codex-/i.test(st.detail ?? '')) {
367
367
  const cmd = 'npm install -g @koalaauto/agentchannel@latest';
@@ -396,6 +396,18 @@ export function sandboxFix(st, host) {
396
396
  const cmd = st.tool === 'claude' ? 'claude auth login' : 'codex login';
397
397
  return { en: `${name} is not logged in on this machine: run \`${cmd}\` as the user that runs this agent.`, zh: `${name} 在这台机器上没有登录:以运行这个智能体的用户身份执行 \`${cmd}\`。`, commands: [cmd] };
398
398
  }
399
+ case 'billing': {
400
+ const en = `The account ${name} uses on this machine cannot run: its plan or credit is not usable (a payment past due, no credit left).`;
401
+ const zh = `这台机器上 ${name} 用的账号用不了:订阅或余额不可用(付款逾期、余额用完)。`;
402
+ if (st.tool === 'kiro')
403
+ return { en: `${en} Renew it, or set another KIRO_API_KEY.`, zh: `${zh}续费,或换一个 KIRO_API_KEY。`, commands: [] };
404
+ const cmd = st.tool === 'claude' ? 'claude auth login' : 'codex login';
405
+ return {
406
+ en: `${en} Renew it, or log in with another account: run \`${cmd}\` as the user that runs this agent.`,
407
+ zh: `${zh}续费,或换一个账号:以运行这个智能体的用户身份执行 \`${cmd}\`。`,
408
+ commands: [cmd],
409
+ };
410
+ }
399
411
  case 'windows-native':
400
412
  return {
401
413
  en: 'Claude Code has no sandbox on native Windows: run this agent inside WSL2 (wsl --install, then join again there).',
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.50.0";
1
+ export declare const VERSION = "3.51.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.50.0';
1
+ export const VERSION = '3.51.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.50.0",
3
+ "version": "3.51.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",