@koalaauto/agentchannel 3.96.0 → 3.97.1

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.
@@ -1,4 +1,3 @@
1
- import { randomBytes } from 'node:crypto';
2
1
  import { appendFileSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
2
  import { tmpdir } from 'node:os';
4
3
  import { join } from 'node:path';
@@ -10,11 +9,11 @@ import { copySkills } from '../capskills.js';
10
9
  import { autorunPath, loadAutorun, ruleName, smallRule } from '../autorun.js';
11
10
  import { toolchainReadRoots } from '../adapters/paths.js';
12
11
  import { developerDir } from '../adapters/scope.js';
13
- import { isRuntime, runRefusal } from '../adapters/spec.js';
12
+ import { runRefusal } from '../adapters/spec.js';
14
13
  import { modelId } from '../adapters/types.js';
15
14
  import { Client as HubClient, HubError, isTerminal } from '../client.js';
16
15
  import { taskFiles } from '../attachments.js';
17
- import { buildAgentEnv, inheritedEnv } from '../env.js';
16
+ import { buildAgentEnv } from '../env.js';
18
17
  import { unlinkWindowsSandbox } from '../codexhome.js';
19
18
  import { effectivePerm } from '../perm.js';
20
19
  import { ANSWER_SCHEMA, MENTION_SCHEMA, splitYodaNotes, buildAnswerPrompt, buildMentionPrompt, buildPreparePrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
@@ -24,20 +23,21 @@ import { RunnerState, threadKey } from './state.js';
24
23
  import { ChangeFeed, wakesRunner } from '../attention.js';
25
24
  import { isGitRepo } from './workspace.js';
26
25
  import { accountProblem, effortRejected, looksLikeLoginError, modelRejected, programMissing, summarizeRuntimeError } from '../envcheck.js';
27
- import { redact } from '../redact.js';
28
26
  import { TraceRecorder } from '../trace.js';
29
27
  import { removeQuietly } from '../removequiet.js';
30
28
  import { detectHost, looksLikeSandboxError, sandboxFix } from '../sandboxcheck.js';
31
29
  import { prepareAgentHome, realHomeOf, secretPaths } from './home.js';
32
30
  import { draftText, parsePrepared, parseStructured } from './structured.js';
33
31
  import { TraceQueue } from './traces.js';
32
+ import { RunnerReports } from './reports.js';
33
+ import { approves, jobKey, mentionOutcome, newRunId, nothingGoing, openRequests, takenOver, threadOf, unseenReplies } from './jobs.js';
34
34
  // moved out; still reachable from here for the code and tests that import them from runner.js
35
35
  export * from './home.js';
36
36
  export * from './structured.js';
37
+ export { cleanDescription, MODELS_EVERY_MS } from './reports.js';
38
+ export { approves, isHumanNoteTo, jobKey, mentionOutcome, newRunId, nothingGoing, openRequests, refusedReply, takenOver, unseenReplies } from './jobs.js';
37
39
  /** How long the runner trusts its copy of the agent's record before reading it again. */
38
40
  const ME_TTL_MS = 60_000;
39
- /** How often the runner looks whether the project's memory index changed (it reports it to the hub when it did). */
40
- const PROJECT_MEMORY_EVERY_MS = 5 * 60_000;
41
41
  /** How long a hub that has no GitHub App is left alone before a run asks it for a token again. */
42
42
  const GITHUB_OFF_MS = 10 * 60_000;
43
43
  /** The same after a failure that may pass (GitHub down, a setup being fixed). */
@@ -46,141 +46,18 @@ const GITHUB_RETRY_MS = 60_000;
46
46
  const MENTION_RUN_RETRY_MS = [3_000, 10_000];
47
47
  /** How often a parked run (waiting for an answer) is looked at: an answer reaches it this much later at most. */
48
48
  const PARKED_CHECK_MS = 12_000;
49
- export function jobKey(j) {
50
- if (j.kind === 'mention')
51
- return `mention:${j.item.mention.id}`;
52
- return j.kind === 'answer' ? `answer:${j.question.id}` : `task:${j.taskId}`;
53
- }
54
49
  /** How many post ids a thread's session remembers having been shown (the newest; an older one shown again costs a few lines). */
55
50
  const THREAD_SEEN_MAX = 400;
56
- /** Is no run going or queued? Parked runs do not count: they wait for an event, they do not need the hub asked every few seconds. */
57
- export const nothingGoing = (active, queued, runs) => active === 0 && queued === 0 && runs.every((r) => r.phase === 'parked');
58
- /** The thread a mention job answers in ('' for any other job). */
59
- const threadOf = (j) => (j.kind === 'mention' ? String(j.item.mention.thread || j.item.thread?.id || '') : '');
60
- /** What the hub is told about a mention run that ended: whether it worked, why not, its last words, the commands that failed. */
61
- /**
62
- * The flags of an `ach reply` that failed (refused, or the hub said no): `--escalate`, `--to`, `--ask`, `--evidence`, read from the
63
- * command's first line as a shell would split it. Undefined when it had none of them. 2026-11-19: a reply with `--escalate --to owner`
64
- * was refused, its text was posted from the last message, and the owner never saw the decision in their Inbox.
65
- */
66
- export function refusedReply(commands) {
67
- for (const command of [...commands].reverse()) {
68
- const line = command.trim().split('\n')[0];
69
- if (!/^ach\s+reply(\s|$)/.test(line))
70
- continue;
71
- const words = [];
72
- let w = '';
73
- let q = '';
74
- let any = false;
75
- for (let i = 0; i < line.length; i++) {
76
- const ch = line[i];
77
- if (q) {
78
- if (ch === q)
79
- q = '';
80
- else if (q === '"' && ch === '\\' && i + 1 < line.length)
81
- w += line[++i];
82
- else
83
- w += ch;
84
- }
85
- else if (ch === "'" || ch === '"') {
86
- q = ch;
87
- any = true;
88
- }
89
- else if (/\s/.test(ch)) {
90
- if (w || any)
91
- words.push(w);
92
- w = '';
93
- any = false;
94
- }
95
- else
96
- w += ch;
97
- }
98
- if (w || any)
99
- words.push(w);
100
- const after = (flag) => { const i = words.indexOf(flag); return i >= 0 ? words[i + 1] : undefined; };
101
- const escalate = words.includes('--escalate');
102
- const to = escalate ? after('--to') : undefined;
103
- const ask = escalate ? after('--ask')?.replace(/\s+/g, ' ').trim().slice(0, 200) : undefined;
104
- const evidence = after('--evidence')?.trim().slice(0, 2000);
105
- if (!escalate && !evidence)
106
- return undefined;
107
- return { ...(escalate ? { escalate: true } : {}), ...(to === 'owner' || to === 'asker' ? { to } : {}), ...(ask ? { ask } : {}), ...(evidence ? { evidence } : {}) };
108
- }
109
- return undefined;
110
- }
111
- export function mentionOutcome(result, reason, recorder, secrets = []) {
112
- const failed = (recorder?.finish().steps ?? []).filter((s) => s.kind === 'tool' && s.is_error);
113
- const reply = refusedReply(failed.map((s) => s.input ?? ''));
114
- const errors = failed
115
- .slice(-3)
116
- .map((s) => ({ name: s.name ?? 'tool', input: s.input ?? '', output: s.output ?? '' }));
117
- const error = redact(reason ? `the run was stopped (${reason})` : result.error ?? '', secrets);
118
- const text = redact(result.finalText ?? '', secrets);
119
- return {
120
- ok: !!result.ok && !reason,
121
- ...(error ? { error: error.slice(0, 400) } : {}),
122
- ...(text ? { text: text.slice(0, 6000) } : {}),
123
- ...(errors.length ? { errors } : {}),
124
- ...(reply ? { reply } : {}),
125
- };
126
- }
127
51
  const TOKEN_REFRESH_MS = 20 * 3600_000;
128
52
  const PRUNE_EVERY_MS = 10 * 60_000;
129
- /** A gate decision that lets the run go ahead (S1). Anything else rejects. */
130
- export function approves(decision) {
131
- return /^\s*(approve[ds]?|yes|ok|okay|allow(ed)?|go ahead)\b/i.test(decision);
132
- }
133
- export function newRunId() {
134
- return `run_${randomBytes(9).toString('base64url')}`;
135
- }
136
53
  function is409(e) {
137
54
  return e instanceof HubError && e.status === 409;
138
55
  }
139
56
  function is401(e) {
140
57
  return e instanceof HubError && e.status === 401;
141
58
  }
142
- /**
143
- * What the worker is still waiting on: its own open questions, blocking decision
144
- * requests, and (non-blocking) decision requests that replace one of its questions.
145
- */
146
- export function openRequests(messages, myId) {
147
- const myQuestions = new Set(messages.filter((m) => m.kind === 'question' && m.author_agent === myId).map((m) => m.id));
148
- return messages.filter((m) => {
149
- if (m.resolved)
150
- return false;
151
- if (m.kind === 'question')
152
- return m.author_agent === myId;
153
- if (m.kind !== 'decision_request')
154
- return false;
155
- if (m.blocking === false)
156
- return !!m.reply_to && myQuestions.has(m.reply_to);
157
- return true;
158
- });
159
- }
160
- /** The agent's own session claimed the task from this run (claim_task takeover): the run has nothing left to do on it. */
161
- export const takenOver = (task, runId) => task.claim_mode === 'interactive' && !!task.run_id && task.run_id !== runId;
162
- /** A human note addressed to me (panel composer / `ach admin note`): wakes a parked run. */
163
- export function isHumanNoteTo(m, myId) {
164
- return m.kind === 'note' && m.author_type === 'human' && m.to_agent === myId;
165
- }
166
- /** Answers / decisions replying to something I asked, and human notes to me, that the worker has not been shown yet. */
167
- export function unseenReplies(messages, myId, seen) {
168
- const mine = new Set(messages.filter((m) => m.author_agent === myId).map((m) => m.id));
169
- // A decision request that replaced one of my questions: its decision answers me.
170
- for (const m of messages)
171
- if (m.kind === 'decision_request' && m.reply_to && mine.has(m.reply_to))
172
- mine.add(m.id);
173
- const seenSet = new Set(seen);
174
- return messages.filter((m) => !seenSet.has(m.id) &&
175
- (((m.kind === 'answer' || m.kind === 'decision') && ((m.reply_to && mine.has(m.reply_to)) || m.to_agent === myId)) ||
176
- // a person's decision on the task I work is for me, whoever's request it answered (the sender's "approve?" decides my work)
177
- (m.kind === 'decision' && m.author_type === 'human') ||
178
- isHumanNoteTo(m, myId)));
179
- }
180
59
  /** A task handed back this many times for an account's usage or rate limit then fails normally. */
181
60
  const ACCOUNT_RELEASES = 3;
182
- /** How often the runner lists the runtime's models again (besides at start and after a rejected model). */
183
- export const MODELS_EVERY_MS = 24 * 60 * 60_000;
184
61
  export class Runner {
185
62
  state;
186
63
  queue = [];
@@ -219,13 +96,22 @@ export class Runner {
219
96
  nudged = false;
220
97
  /** decisions §27: the last sandbox probe, when it ran, and what the hub was last told (a JSON key). */
221
98
  sandbox;
222
- setupReported;
223
99
  sandboxRecheck = false;
224
100
  /** Execution traces the hub has not taken yet (kept on disk too), and the last trace of each task (a commit joins it). */
225
101
  traces;
102
+ /** what this runner tells the hub about itself (reports.ts) */
103
+ reports;
226
104
  constructor(opts) {
227
105
  this.o = { max: 2, perm: 'workdir', intervalMs: 3000, heartbeatMs: 30_000, idleMs: 60 * 60_000, ...opts };
228
106
  this.state = new RunnerState(opts.home);
107
+ this.reports = new RunnerReports(this.o, {
108
+ log: (l) => this.log(l),
109
+ authFailed: (where, e) => this.authFailed(where, e),
110
+ ensureMe: () => this.ensureMe(),
111
+ me: () => this.me,
112
+ cloud: this.cloud,
113
+ structured: this.structured,
114
+ });
229
115
  this.traces = new TraceQueue({ home: this.o.home, client: this.o.client, secrets: this.o.secrets, log: (t, l) => this.taskLog(t, l), unauthorized: () => this.authFailed('trace') });
230
116
  this.traces.load();
231
117
  }
@@ -397,30 +283,9 @@ export class Runner {
397
283
  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')}` : ''}`);
398
284
  }
399
285
  }
400
- await this.reportSetup();
286
+ await this.reports.reportSetup(this.sandbox && !this.sandbox.st.ok ? this.sandbox.st : this.account);
401
287
  return !this.sandbox.st.ok;
402
288
  }
403
- /** Tell the hub what keeps this runner from working, when that changed: a failed check first, else an account that cannot run. */
404
- async reportSetup() {
405
- const st = this.sandbox && !this.sandbox.st.ok ? this.sandbox.st : this.account;
406
- const report = !st ? null : { tool: st.tool, problem: st.problem ?? 'failed', ...(st.detail ? { detail: st.detail } : {}), ...(st.fix ? { fix: st.fix } : {}) };
407
- const key = JSON.stringify(report);
408
- if (key !== this.setupReported && this.o.client.reportSetup) {
409
- try {
410
- await this.o.client.reportSetup(report);
411
- this.setupReported = key;
412
- }
413
- catch (e) {
414
- if (is401(e))
415
- this.authFailed('setup', e);
416
- // an older hub without /me/setup: the log above is all there is
417
- else if (e instanceof HubError && e.status === 404)
418
- this.setupReported = key;
419
- else
420
- this.log(`setup report: ${e?.message ?? e}`);
421
- }
422
- }
423
- }
424
289
  /**
425
290
  * 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
426
291
  * 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.
@@ -446,206 +311,10 @@ export class Runner {
446
311
  this.account = undefined;
447
312
  this.log('account: runs work again');
448
313
  }
449
- await this.reportSetup();
450
- }
451
- /** Tell the hub which repo names this runner knows, so a task for another repo is refused when it is sent. Tried on every
452
- * poll until the hub has it: a hub that was unreachable at start would otherwise keep the previous list until a restart. */
453
- reposReported = false;
454
- async reportRepos() {
455
- if (this.reposReported)
456
- return;
457
- // an empty list is reported too: the hub then refuses a task that names a repo, and forgets names an earlier start gave
458
- const names = await this.o.workspace.repoNames?.();
459
- if (!names || !this.o.client.reportRepos) {
460
- this.reposReported = true;
461
- return;
462
- }
463
- try {
464
- await this.o.client.reportRepos(names, await this.o.workspace.repoRemotes?.().catch(() => undefined));
465
- this.reposReported = true;
466
- }
467
- catch (e) {
468
- // an older hub without /me/repos: nothing is checked there, which is how it was
469
- if (e instanceof HubError && e.status === 404)
470
- this.reposReported = true;
471
- else if (!this.reposLogged) {
472
- this.reposLogged = true;
473
- this.log(`repos report: ${e?.message ?? e} (trying again with the next poll)`);
474
- }
475
- }
476
- }
477
- reposLogged = false;
478
- /** An agent with no profile yet gets a first one, once: a short read-only run on a light model reads the repositories it works in
479
- * and writes a sentence or two. The hub keeps it only while the profile is empty; the weekly refresh (the system agent, from what the
480
- * agent did) rewrites it after. The description is the owner's and is never written here. Tried again at the next start when it
481
- * could not be had. */
482
- describeDone = false;
483
- describeBusy = false;
484
- describeTries = 0;
485
- describeNextAt = 0;
486
- async describeAgent() {
487
- const { adapter, client, workspace } = this.o;
488
- if (this.describeDone || this.describeBusy || Date.now() < this.describeNextAt || this.cloud || !client.reportProfile || !workspace.repoDirs)
489
- return;
490
- this.describeBusy = true;
491
- try {
492
- const me = await this.ensureMe();
493
- if (me.role === 'system' || String(me.profile ?? '').trim()) {
494
- this.describeDone = true;
495
- return;
496
- }
497
- const dirs = Object.entries(await workspace.repoDirs()).slice(0, 4);
498
- if (!dirs.length)
499
- return;
500
- const baseEnv = this.o.baseEnv ?? process.env;
501
- const realHome = realHomeOf(baseEnv);
502
- const { env } = prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, 'describe', realHome, baseEnv.CODEX_HOME || undefined);
503
- const run = async (pick) => {
504
- const ctl = new AbortController();
505
- const timer = setTimeout(() => ctl.abort(), 3 * 60_000);
506
- try {
507
- const refused = runRefusal(adapter.spec, { perm: 'read', ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}) });
508
- if (refused)
509
- return { ok: false, finalText: '', error: `not run: ${refused}` };
510
- return await adapter.run({
511
- ...(pick ? { model: pick.model, effort: pick.effort } : {}),
512
- prompt: describePrompt(me.name, dirs, me.lang),
513
- cwd: dirs[0][1],
514
- perm: 'read',
515
- mode: 'answer',
516
- env: { ...inheritedEnv(baseEnv, this.o.passEnv), ...env },
517
- signal: ctl.signal,
518
- hub: this.o.hub,
519
- denyReadPaths: secretPaths(this.o.home),
520
- ...(realHome ? { realHome } : {}),
521
- readRoots: dirs.map(([, d]) => d),
522
- ...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
523
- ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
524
- ...(adapter.spec.budget ? { maxBudgetUsd: 0.05 } : {}),
525
- ...(this.structured ? { outputSchema: DESCRIBE_SCHEMA } : {}),
526
- onEvent: () => { },
527
- });
528
- }
529
- finally {
530
- clearTimeout(timer);
531
- }
532
- };
533
- // the light model where the runtime has one; a model the account cannot use falls back to the runtime's default
534
- const light = adapter.spec.lightModel;
535
- let r = await run(light);
536
- if (!r.ok && light)
537
- r = await run(undefined);
538
- const text = cleanDescription(r.finalText);
539
- if (!r.ok || !text)
540
- throw new Error(r.error ? summarizeRuntimeError(r.error).slice(0, 160) : 'no profile came back');
541
- await client.reportProfile(text);
542
- this.describeDone = true;
543
- this.log(`profile: ${text.slice(0, 120)}`);
544
- }
545
- catch (e) {
546
- // an older hub without /me/profile (404) says nothing and is left alone; any other failure (a hub or network that was not
547
- // reachable while many runners restarted at once, a model that said nothing) is tried again, three times in all per start
548
- if (e instanceof HubError && e.status === 404)
549
- this.describeDone = true;
550
- else if (++this.describeTries >= 3) {
551
- this.describeDone = true;
552
- this.log(`profile: ${String(e?.message ?? e).slice(0, 200)} (gave up until the next start)`);
553
- }
554
- else {
555
- this.describeNextAt = Date.now() + (this.o.describeRetryMs ?? 5 * 60_000);
556
- this.log(`profile: ${String(e?.message ?? e).slice(0, 200)} (trying again in ${Math.round((this.o.describeRetryMs ?? 5 * 60_000) / 60_000)} min)`);
557
- }
558
- }
559
- finally {
560
- this.describeBusy = false;
561
- }
314
+ await this.reports.reportSetup(this.sandbox && !this.sandbox.st.ok ? this.sandbox.st : this.account);
562
315
  }
563
- /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
564
- * 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. */
565
- runnerReported = false;
566
316
  /** the capabilities file problems last logged (logged again only when they change) */
567
317
  capsProblems = '';
568
- /** the capabilities last told to the hub (decisions §34, §38): an edit of the file is reported again on the next poll */
569
- capsReported = '';
570
- async reportRunner() {
571
- if (!this.o.client.reportRunner)
572
- return;
573
- // the names and descriptions only, never the commands: teammates see them in the agent directory
574
- // decisions §38: MCP servers with their tool names, skills by name; never a URL, a command or a credential
575
- const decl = this.cloud ? undefined : loadCaps(this.o.capsFile ?? capsPath(this.o.home));
576
- const capabilities = decl
577
- ? [
578
- ...decl.caps.map((c) => ({ kind: 'command', name: c.name, description: c.description.slice(0, 300) })),
579
- ...decl.mcp.map((m) => ({ kind: 'mcp', name: m.name, description: m.description.slice(0, 300), tools: m.tools.slice(0, 50) })),
580
- ...decl.skills.map((k) => ({ kind: 'skill', name: k.name, description: k.description.slice(0, 300) })),
581
- ].slice(0, 50)
582
- : [];
583
- const sig = JSON.stringify(capabilities);
584
- if (this.runnerReported && sig === this.capsReported)
585
- return;
586
- const runtime = this.o.adapter.name;
587
- if (!isRuntime(runtime)) {
588
- this.runnerReported = true;
589
- this.capsReported = sig;
590
- return;
591
- }
592
- try {
593
- // review: this runner knows the owner's review step (a task it finishes may wait in awaiting_review, decisions §36)
594
- await this.o.client.reportRunner({ perm: this.o.perm, runtime, pass_env: [...new Set(this.o.passEnv ?? [])], capabilities, review: true, ...(this.o.startInfo ?? {}) });
595
- this.runnerReported = true;
596
- this.capsReported = sig;
597
- }
598
- catch (e) {
599
- if (e instanceof HubError && e.status === 404) {
600
- this.runnerReported = true;
601
- this.capsReported = sig;
602
- }
603
- }
604
- }
605
- /**
606
- * Tell the hub which models the runtime offers here and which one a run uses when none is picked (the agent's settings
607
- * page lists them): when the runner starts, again a day later (a login or the tool's catalog changes), and at once after
608
- * a run's model was rejected. Asked with the environment a run gets, so the list is what this agent's login can use.
609
- */
610
- modelsAt = 0;
611
- modelsBusy = false;
612
- /** set when a run's model was rejected: the list on the hub is out of date */
613
- modelsStale = false;
614
- /** an older hub without /me/models, or a runtime that cannot list: asked no more */
615
- modelsOff = false;
616
- modelsLogged = '';
617
- async reportModels() {
618
- const adapter = this.o.adapter;
619
- if (this.modelsOff || this.modelsBusy || !adapter.listModels || !this.o.client.reportModels)
620
- return;
621
- if (this.modelsAt && !this.modelsStale && Date.now() - this.modelsAt < MODELS_EVERY_MS)
622
- return;
623
- this.modelsBusy = true;
624
- this.modelsAt = Date.now();
625
- this.modelsStale = false;
626
- try {
627
- const me = await this.ensureMe();
628
- const baseEnv = this.o.baseEnv ?? process.env;
629
- const realHome = realHomeOf(baseEnv);
630
- const { home, env } = prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, 'model-list', realHome, baseEnv.CODEX_HOME || undefined);
631
- const list = await adapter.listModels({ env: { ...inheritedEnv(baseEnv, this.o.passEnv), ...env }, cwd: home, ...(realHome ? { realHome } : {}) });
632
- await this.o.client.reportModels({ runtime: adapter.name, ...list });
633
- this.modelsLogged = '';
634
- }
635
- catch (e) {
636
- if (e instanceof HubError && e.status === 404)
637
- this.modelsOff = true;
638
- const msg = String(e?.message ?? e).slice(0, 300);
639
- // a list that cannot be had is not worth a line every day: said once until it changes
640
- if (!this.modelsOff && msg !== this.modelsLogged) {
641
- this.modelsLogged = msg;
642
- this.log(`model list: ${msg} (trying again in a day)`);
643
- }
644
- }
645
- finally {
646
- this.modelsBusy = false;
647
- }
648
- }
649
318
  /**
650
319
  * Cancel running jobs whose task went terminal; forget parked runs of
651
320
  * terminal tasks; keep parked leases alive; and (C1) resume a parked run
@@ -1713,34 +1382,6 @@ export class Runner {
1713
1382
  const spec = this.o.adapter.spec;
1714
1383
  return spec.structuredAnswers || !spec.ach;
1715
1384
  }
1716
- /** the project memory index last told to the hub, and when the file was last looked at */
1717
- projectMemoryReported;
1718
- projectMemoryCheckedAt = 0;
1719
- /**
1720
- * Tell the hub what this agent knows about its project: the index of the owner's memory for it on this machine (one line per
1721
- * note, never the notes). The owner's Yoda reads it, so it knows what each of its parts knows (primary-agent-design §11.15).
1722
- * Looked at every few minutes, sent when it changed. Not for a team agent (no person) or a cloud run (no machine).
1723
- */
1724
- async reportProjectMemory(now = Date.now()) {
1725
- if (!this.o.client.reportProjectMemory || this.cloud || !this.me || this.teamOwned())
1726
- return;
1727
- if (now - this.projectMemoryCheckedAt < PROJECT_MEMORY_EVERY_MS)
1728
- return;
1729
- this.projectMemoryCheckedAt = now;
1730
- const dir = ownerMemoryDir(this.o.dir, realHomeOf(this.o.baseEnv ?? process.env));
1731
- const index = dir ? memoryIndex(dir) : '';
1732
- if (index === this.projectMemoryReported || (!index && this.projectMemoryReported === undefined))
1733
- return;
1734
- try {
1735
- await this.o.client.reportProjectMemory(index);
1736
- this.projectMemoryReported = index;
1737
- }
1738
- catch (e) {
1739
- // an older hub has no such route: say nothing more
1740
- if (e instanceof HubError && (e.status === 404 || e.status === 400))
1741
- this.projectMemoryReported = index;
1742
- }
1743
- }
1744
1385
  /** Owned by no one person (the system agent, or a team agent such as one that does a channel mechanism for the team). */
1745
1386
  teamOwned() {
1746
1387
  return this.me?.kind === 'team';
@@ -2016,7 +1657,7 @@ export class Runner {
2016
1657
  break;
2017
1658
  recorder.event({ type: 'error', data: note });
2018
1659
  this.taskLog(taskId, note);
2019
- this.modelsStale = true;
1660
+ this.reports.modelsStale = true;
2020
1661
  result = await go(m, ef);
2021
1662
  }
2022
1663
  }
@@ -2102,12 +1743,12 @@ export class Runner {
2102
1743
  while (!this.stopped) {
2103
1744
  let wait = this.o.intervalMs;
2104
1745
  try {
2105
- await this.reportRepos();
2106
- await this.reportRunner();
2107
- await this.reportProjectMemory();
1746
+ await this.reports.reportRepos();
1747
+ await this.reports.reportRunner();
1748
+ await this.reports.reportProjectMemory();
2108
1749
  // not awaited: listing starts the tool (up to a few seconds), and claiming work must not wait for it
2109
- void this.reportModels();
2110
- void this.describeAgent();
1750
+ void this.reports.reportModels();
1751
+ void this.reports.describeAgent();
2111
1752
  await this.tick();
2112
1753
  }
2113
1754
  catch (e) {
@@ -2200,30 +1841,3 @@ function promptFile(f) {
2200
1841
  const { key: _key, ...rest } = f;
2201
1842
  return rest;
2202
1843
  }
2203
- /** The light model that writes an agent's first profile, per runtime (none listed: the runtime's default). A runtime that does not
2204
- * take it runs the default instead. */
2205
- const DESCRIBE_SCHEMA = { type: 'object', properties: { profile: { type: 'string' } }, required: ['profile'], additionalProperties: false };
2206
- function describePrompt(name, dirs, lang) {
2207
- const where = dirs.map(([n, d]) => `- ${n}: ${d}`).join('\n');
2208
- return [
2209
- `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.`,
2210
- `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):`,
2211
- where,
2212
- `Write one or two sentences in ${lang === 'en' ? 'English' : '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.`,
2213
- 'Answer with the profile text only.',
2214
- ].filter(Boolean).join('\n\n');
2215
- }
2216
- /** The model's text as a profile: its first paragraph, without markdown marks or wrapping quotes, at most 300 characters. */
2217
- export function cleanDescription(raw) {
2218
- let t = String(raw ?? '').trim();
2219
- try {
2220
- const j = JSON.parse(t);
2221
- if (j && typeof j.profile === 'string')
2222
- t = j.profile;
2223
- }
2224
- catch {
2225
- /* plain text */
2226
- }
2227
- t = t.split(/\n\s*\n/)[0].replace(/\*\*|__|[`*]|^\s*[#>]+\s*/gm, '').replace(/\s+/g, ' ').trim().replace(/^["'“”「」]+|["'“”「」]+$/g, '').trim();
2228
- return t.slice(0, 300);
2229
- }
@@ -101,7 +101,8 @@ export interface Quiescable {
101
101
  busy(): number;
102
102
  stop(): Promise<void>;
103
103
  }
104
- export type CheckResult = 'none' | 'manual' | 'off' | 'backoff' | 'busy' | 'failed' | 'restarting';
104
+ /** 'unreachable': the hub's versions could not be read (offline, an old hub, or the hub failing for a while) */
105
+ export type CheckResult = 'none' | 'unreachable' | 'manual' | 'off' | 'backoff' | 'busy' | 'failed' | 'restarting';
105
106
  export interface SelfUpdaterOptions {
106
107
  fetchVersions: () => Promise<HubVersions | null>;
107
108
  platform?: NodeJS.Platform;
@@ -238,8 +238,11 @@ export class SelfUpdater {
238
238
  if (r === 'manual' || r === 'off')
239
239
  this.heard.set(latest, -1);
240
240
  // the hub names a release the moment it is deployed, a minute or two before npm serves it: that try fails with nothing
241
- // paused, and waiting the hour for it kept every runner an hour behind each release. It is asked again in five minutes.
242
- this.heardWait.set(latest, r === 'failed' ? 5 * 60_000 : 3600_000);
241
+ // paused, and waiting the hour for it kept every runner an hour behind each release. A hub that names the release on an
242
+ // error and then fails the versions read is the same: 2026-11-25 three of twelve pool runners heard 3.95.1 while the hub
243
+ // was failing, waited the hour, and held their pool (which restarts once every runner has moved) half an hour. Both are
244
+ // asked again in five minutes.
245
+ this.heardWait.set(latest, r === 'failed' || r === 'unreachable' ? 5 * 60_000 : 3600_000);
243
246
  return r;
244
247
  });
245
248
  }
@@ -253,7 +256,7 @@ export class SelfUpdater {
253
256
  hub = await this.o.fetchVersions();
254
257
  }
255
258
  catch {
256
- return 'none'; // offline or an old hub: nothing to act on
259
+ return 'unreachable';
257
260
  }
258
261
  const prior = loadUpdateState(this.o.home);
259
262
  if (prior && prior.target === version && isHealthy(this.o.home, version))
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.96.0";
1
+ export declare const VERSION = "3.97.1";
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.96.0';
1
+ export const VERSION = '3.97.1';
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.96.0",
3
+ "version": "3.97.1",
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",