@koalaauto/agentchannel 3.41.1 → 3.43.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.
- package/dist/src/adapters/claude.d.ts +1 -1
- package/dist/src/adapters/claude.js +8 -3
- package/dist/src/adapters/codex.d.ts +2 -2
- package/dist/src/adapters/fake.d.ts +1 -1
- package/dist/src/adapters/types.d.ts +1 -1
- package/dist/src/args.d.ts +1 -1
- package/dist/src/args.js +2 -0
- package/dist/src/autorun.d.ts +26 -0
- package/dist/src/autorun.js +95 -0
- package/dist/src/cli.js +22 -1
- package/dist/src/client.d.ts +56 -3
- package/dist/src/client.js +16 -2
- package/dist/src/mcp.d.ts +2 -0
- package/dist/src/mcp.js +14 -6
- package/dist/src/prompts.d.ts +10 -0
- package/dist/src/prompts.js +29 -2
- package/dist/src/runner/runner.d.ts +42 -5
- package/dist/src/runner/runner.js +187 -18
- package/dist/src/runner/workspace.d.ts +12 -0
- package/dist/src/runner/workspace.js +101 -15
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -1
package/dist/src/prompts.js
CHANGED
|
@@ -274,7 +274,7 @@ function channelText(c) {
|
|
|
274
274
|
function header(c) {
|
|
275
275
|
const t = c.task;
|
|
276
276
|
return [
|
|
277
|
-
`You are agent "${c.agentName}"${c.ownerName ? `, owned by ${c.ownerName}` : ''}. Agent "${c.senderName ?? t.from_agent ?? 'unknown'}" sent you task ${refOf(t)} via AgentChannel.`,
|
|
277
|
+
`You are agent "${c.agentName}"${c.system ? ", the team's system agent (owned by no one; the team's admins look after you)" : c.ownerName ? `, owned by ${c.ownerName}` : ''}. Agent "${c.senderName ?? t.from_agent ?? 'unknown'}" sent you task ${refOf(t)} via AgentChannel.`,
|
|
278
278
|
`Priority: ${t.priority ?? 'n/a'}. Handoff version: ${c.handoffVersion ?? t.handoff_version ?? 1}.`,
|
|
279
279
|
...(c.taskUrl ? [`Task page: ${c.taskUrl}`] : []),
|
|
280
280
|
].join('\n');
|
|
@@ -295,7 +295,8 @@ function completeRule(review) {
|
|
|
295
295
|
function rules(review) {
|
|
296
296
|
return [
|
|
297
297
|
'Rules:',
|
|
298
|
-
"- Work only inside the current directory. Do not commit or push: when your run ends, the runner commits your changes on this task's branch and, when the repository is on GitHub, pushes it and opens the task's pull request (the deliverable
|
|
298
|
+
"- Work only inside the current directory. Do not commit or push: when your run ends, the runner commits your changes on this task's branch and, when the repository is on GitHub, pushes it and opens the task's pull request (the deliverable; each later round updates it). When the task is someone else's, your owner reviews it before the sender sees it. Keep notes, result files and screenshots in `.ach/` here: it is never committed.",
|
|
299
|
+
"- Before `ach complete`, run the project's own checks (build, type check, tests: what its CLAUDE.md, AGENTS.md, Makefile or package scripts say) on what you changed. The checkout's installed dependencies are linked in. Put the commands you ran and their outcome in the result. Checks that fail mean the work is not done: fix them, and if you cannot, start the result with what fails.",
|
|
299
300
|
'- Talk through the `ach` CLI (the task id is already set):',
|
|
300
301
|
' - `ach progress "<text>"` for short status updates.',
|
|
301
302
|
' - `ach ask "<question>"` asks the sender a factual question. Then stop and end your turn; you will be resumed with the answer.',
|
|
@@ -446,6 +447,32 @@ export function buildAnswerPrompt(c) {
|
|
|
446
447
|
...how,
|
|
447
448
|
].join('\n');
|
|
448
449
|
}
|
|
450
|
+
/**
|
|
451
|
+
* The read-ahead (docs/specs/owner-pulls-tasks.md): a short read-only run before anyone works the task. It finds out whether the task
|
|
452
|
+
* changes code, which files it would touch and how, and what is unclear, and ends with one JSON object the runner reports. Its owner
|
|
453
|
+
* may take the task over from this draft in their own session, so it is written for them.
|
|
454
|
+
*/
|
|
455
|
+
export function buildPreparePrompt(c) {
|
|
456
|
+
return [
|
|
457
|
+
`You are agent "${c.agentName}"${c.ownerName ? `, owned by ${c.ownerName}` : ''}. Task ${c.task.id} was sent to you on AgentChannel. Nobody works it yet. This is a short, read-only run: read the task and the code, and write a draft for whoever does the work, most likely your owner in their own session.`,
|
|
458
|
+
'',
|
|
459
|
+
HUMAN_HEADING,
|
|
460
|
+
formatHumanDecisions(c.messages),
|
|
461
|
+
'',
|
|
462
|
+
...filesText(c.task.id, c.files),
|
|
463
|
+
untrustedBlock({ task: taskData(c), handoff: c.handoff }),
|
|
464
|
+
'',
|
|
465
|
+
'Rules:',
|
|
466
|
+
'- Do not modify anything and do not run `ach`. Read the files, search the code, look at git history.',
|
|
467
|
+
`- ${UNTRUSTED_RULE}`,
|
|
468
|
+
'- Decide whether doing this task changes files in this repository (code, configuration, docs): "code". A question, a lookup or a report is not.',
|
|
469
|
+
'- For a code change, list the files you expect to change (paths relative to the repository root), as few as the change needs.',
|
|
470
|
+
...(c.small?.length ? [`- Your owner lets you do small changes yourself when they stay inside: ${c.small.join('; ')}. Do not stretch the plan to fit; list what the task really needs.`] : []),
|
|
471
|
+
'- The plan: what to change where and how, in a few short points; what is out of scope; the checks to run. Then what is unclear or missing in the task, as questions for the sender.',
|
|
472
|
+
'- End with one JSON object only:',
|
|
473
|
+
' {"code": true, "files": ["<path>", ...], "plan": "<markdown: approach, scope, checks>", "questions": ["<question for the sender>", ...]}',
|
|
474
|
+
].join('\n');
|
|
475
|
+
}
|
|
449
476
|
/** §16 mention prompt: a read-only run that replies in a channel thread. */
|
|
450
477
|
export function buildMentionPrompt(c) {
|
|
451
478
|
const all = [c.thread, ...c.replies, ...c.recent];
|
|
@@ -2,10 +2,10 @@ import type { AdapterResult, RuntimeAdapter } from '../adapters/types.js';
|
|
|
2
2
|
import { type Agent, type Client, type MentionItem, type MentionOutcome, type Message } from '../client.js';
|
|
3
3
|
import { type Perm } from '../perm.js';
|
|
4
4
|
import { RunnerState } from './state.js';
|
|
5
|
-
import type
|
|
5
|
+
import { type Workspace } from './workspace.js';
|
|
6
6
|
import { TraceRecorder } from '../trace.js';
|
|
7
7
|
import { type SandboxStatus } from '../sandboxcheck.js';
|
|
8
|
-
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' | 'release' | 'putTrace' | 'pushToken' | 'taskPr'>>;
|
|
8
|
+
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' | 'release' | 'putTrace' | 'pushToken' | 'taskPr' | 'prepareRun' | 'prepared'>>;
|
|
9
9
|
export interface RunnerOptions {
|
|
10
10
|
client: RunnerClient;
|
|
11
11
|
adapter: RuntimeAdapter;
|
|
@@ -42,6 +42,8 @@ export interface RunnerOptions {
|
|
|
42
42
|
* owner can claim them interactively first (default 0: claim at once).
|
|
43
43
|
*/
|
|
44
44
|
claimDelayMs?: number;
|
|
45
|
+
/** read new tasks ahead and leave code tasks for the owner (docs/specs/owner-pulls-tasks.md); `ach run` turns it on */
|
|
46
|
+
readAhead?: boolean;
|
|
45
47
|
/** Client acting with a run token (posts structured answers for codex). Default: a hub Client. */
|
|
46
48
|
tokenClient?: (token: string) => Pick<Client, 'postMessage' | 'reply'>;
|
|
47
49
|
/** §19: base URL for links in prompts (ACH_PUBLIC_URL); default the hub URL. */
|
|
@@ -95,6 +97,11 @@ export type Job = {
|
|
|
95
97
|
} | {
|
|
96
98
|
kind: 'mention';
|
|
97
99
|
item: MentionItem;
|
|
100
|
+
}
|
|
101
|
+
/** read a new task ahead before anyone works it (owner-pulls-tasks.md) */
|
|
102
|
+
| {
|
|
103
|
+
kind: 'prepare';
|
|
104
|
+
taskId: string;
|
|
98
105
|
};
|
|
99
106
|
export declare function jobKey(j: Job): string;
|
|
100
107
|
/** What the hub is told about a mention run that ended: whether it worked, why not, its last words, the commands that failed. */
|
|
@@ -258,15 +265,34 @@ export declare class Runner {
|
|
|
258
265
|
* The agent's own record (permission, network allowlist, budget), read again when it is older than ME_TTL_MS: an admin who
|
|
259
266
|
* lowers the permission or narrows net_allow (say, after a suspected injection) is obeyed by the next run, not the next restart.
|
|
260
267
|
*/
|
|
268
|
+
/**
|
|
269
|
+
* The system agent works for the team, so no person's memory may reach its runs: Claude Code loads the memory of the git
|
|
270
|
+
* checkout a run is in. Its runner must start in a directory that is not one (docs/specs/system-channels.md); in a checkout
|
|
271
|
+
* it takes nothing and says so once.
|
|
272
|
+
*/
|
|
273
|
+
private systemCheckoutWarned;
|
|
274
|
+
private systemInCheckout;
|
|
261
275
|
private ensureMe;
|
|
276
|
+
/** the hub has no read-ahead routes (an older hub, or the minutes between a release and its deploy): work tasks as before */
|
|
277
|
+
private noReadAhead;
|
|
278
|
+
/** Whether this runner reads new tasks ahead: a local runtime in a git checkout that delivers pull requests, and a hub that knows how. */
|
|
279
|
+
private readsAhead;
|
|
280
|
+
/**
|
|
281
|
+
* 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,
|
|
282
|
+
* 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
|
|
283
|
+
* hub then says whether the owner takes it over. A read-ahead that fails reports a code task: the owner looks, nothing is lost.
|
|
284
|
+
*/
|
|
285
|
+
private runPrepare;
|
|
262
286
|
private runWork;
|
|
263
287
|
private runResume;
|
|
264
288
|
/** S10: the agent cannot write .git, so the runner commits its changes after every work run. */
|
|
265
289
|
private commitWork;
|
|
266
290
|
/**
|
|
267
|
-
* The deliverable of a code task is its pull request. Once the agent finished a round (the task waits for
|
|
268
|
-
* completed), the runner pushes the task's branch with a push token for that one repository and the hub
|
|
269
|
-
* (or the open one simply gets the new commits
|
|
291
|
+
* The deliverable of a code task is its pull request. Once the agent finished a round (the task waits for its owner's review or
|
|
292
|
+
* for acceptance, or is completed), the runner pushes the task's branch with a push token for that one repository and the hub
|
|
293
|
+
* opens the pull request (a draft while the owner reviews it) or the open one simply gets the new commits. The agent never holds
|
|
294
|
+
* the token. A failed push is said on the task. A round that changed no code tells the hub so: a task waiting for its owner's
|
|
295
|
+
* review then has nothing to review and goes on to acceptance.
|
|
270
296
|
*/
|
|
271
297
|
private deliverPr;
|
|
272
298
|
private afterWork;
|
|
@@ -339,4 +365,15 @@ export declare function parseStructured(text: string): {
|
|
|
339
365
|
text?: string;
|
|
340
366
|
evidence?: string;
|
|
341
367
|
};
|
|
368
|
+
/** What a read-ahead found (its final JSON object). */
|
|
369
|
+
export interface PrepareOut {
|
|
370
|
+
code: boolean;
|
|
371
|
+
files: string[];
|
|
372
|
+
plan: string;
|
|
373
|
+
questions: string[];
|
|
374
|
+
}
|
|
375
|
+
/** The read-ahead's final JSON object: the last one in its message (bare, fenced, or after a sentence). Throws when there is none. */
|
|
376
|
+
export declare function parsePrepared(text: string): PrepareOut;
|
|
377
|
+
/** The draft as the owner reads it on the task: the plan, the files, the questions, and the small-job rule it fell inside. */
|
|
378
|
+
export declare function draftText(o: PrepareOut, rule: string): string;
|
|
342
379
|
export {};
|
|
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
6
6
|
import { gitCommonDir } from '../adapters/index.js';
|
|
7
7
|
import { memoryIndex, ownerMemoryDir, projectInstructions } from './context.js';
|
|
8
8
|
import { capsPath, capsPromptText, capsServeArgs, loadCaps } from '../caps.js';
|
|
9
|
+
import { autorunPath, loadAutorun, ruleName, smallRule } from '../autorun.js';
|
|
9
10
|
import { toolchainReadRoots } from '../adapters/paths.js';
|
|
10
11
|
import { developerDir } from '../adapters/scope.js';
|
|
11
12
|
import { Client as HubClient, HubError, isTerminal } from '../client.js';
|
|
@@ -13,8 +14,9 @@ import { taskFiles } from '../attachments.js';
|
|
|
13
14
|
import { buildAgentEnv } from '../env.js';
|
|
14
15
|
import { linkWindowsSandbox, unlinkWindowsSandbox, WINDOWS_ELEVATED_CONFIG } from '../codexhome.js';
|
|
15
16
|
import { effectivePerm } from '../perm.js';
|
|
16
|
-
import { ANSWER_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
|
|
17
|
+
import { ANSWER_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildPreparePrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
|
|
17
18
|
import { RunnerState } from './state.js';
|
|
19
|
+
import { isGitRepo } from './workspace.js';
|
|
18
20
|
import { looksLikeLoginError, quotaProblem, summarizeRuntimeError } from '../envcheck.js';
|
|
19
21
|
import { redact } from '../redact.js';
|
|
20
22
|
import { TraceRecorder } from '../trace.js';
|
|
@@ -369,6 +371,8 @@ export class Runner {
|
|
|
369
371
|
this.meAt = Date.now();
|
|
370
372
|
}
|
|
371
373
|
const me = await this.ensureMe();
|
|
374
|
+
if (me.system && (await this.systemInCheckout()))
|
|
375
|
+
return;
|
|
372
376
|
// New tasks.
|
|
373
377
|
const blocked = budgetBlocked(me);
|
|
374
378
|
const now = Date.now();
|
|
@@ -384,6 +388,16 @@ export class Runner {
|
|
|
384
388
|
}
|
|
385
389
|
if (now < this.quotaUntil)
|
|
386
390
|
continue; // out of usage at the provider: the pause is over soon enough
|
|
391
|
+
// 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
|
|
392
|
+
// is not code, or one of the owner's declared small jobs; what the owner sent themselves is theirs to hand to the runner
|
|
393
|
+
if (this.readsAhead(me) && !t.from_owner) {
|
|
394
|
+
if (t.prepared?.owner_first)
|
|
395
|
+
continue;
|
|
396
|
+
if (!t.prepared) {
|
|
397
|
+
this.enqueue({ kind: 'prepare', taskId: t.id });
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
387
401
|
this.enqueue({ kind: 'work', taskId: t.id });
|
|
388
402
|
}
|
|
389
403
|
// Replies for parked runs.
|
|
@@ -508,7 +522,8 @@ export class Runner {
|
|
|
508
522
|
return;
|
|
509
523
|
}
|
|
510
524
|
try {
|
|
511
|
-
|
|
525
|
+
// review: this runner knows the owner's review step (a task it finishes may wait in awaiting_review, design §36)
|
|
526
|
+
await this.o.client.reportRunner({ perm: this.o.perm, runtime, pass_env: [...new Set(this.o.passEnv ?? [])], capabilities, review: true, ...(this.o.startInfo ?? {}) });
|
|
512
527
|
this.runnerReported = true;
|
|
513
528
|
this.capsReported = sig;
|
|
514
529
|
}
|
|
@@ -720,12 +735,28 @@ export class Runner {
|
|
|
720
735
|
return this.runResume(job.taskId, job.replies, entry, job.nudge);
|
|
721
736
|
if (job.kind === 'mention')
|
|
722
737
|
return this.runMention(job.item, entry);
|
|
738
|
+
if (job.kind === 'prepare')
|
|
739
|
+
return this.runPrepare(job.taskId, entry);
|
|
723
740
|
return this.runAnswer(job.question, entry);
|
|
724
741
|
}
|
|
725
742
|
/**
|
|
726
743
|
* The agent's own record (permission, network allowlist, budget), read again when it is older than ME_TTL_MS: an admin who
|
|
727
744
|
* lowers the permission or narrows net_allow (say, after a suspected injection) is obeyed by the next run, not the next restart.
|
|
728
745
|
*/
|
|
746
|
+
/**
|
|
747
|
+
* The system agent works for the team, so no person's memory may reach its runs: Claude Code loads the memory of the git
|
|
748
|
+
* checkout a run is in. Its runner must start in a directory that is not one (docs/specs/system-channels.md); in a checkout
|
|
749
|
+
* it takes nothing and says so once.
|
|
750
|
+
*/
|
|
751
|
+
systemCheckoutWarned = false;
|
|
752
|
+
async systemInCheckout() {
|
|
753
|
+
if (!(await isGitRepo(this.o.dir)))
|
|
754
|
+
return false;
|
|
755
|
+
if (!this.systemCheckoutWarned)
|
|
756
|
+
this.log(`${this.o.dir} is a git checkout: the system agent's runner must start in a directory that is not one (no project, no one's memory). Taking no tasks.`);
|
|
757
|
+
this.systemCheckoutWarned = true;
|
|
758
|
+
return true;
|
|
759
|
+
}
|
|
729
760
|
async ensureMe() {
|
|
730
761
|
if (!this.me || Date.now() - this.meAt > ME_TTL_MS) {
|
|
731
762
|
try {
|
|
@@ -740,6 +771,91 @@ export class Runner {
|
|
|
740
771
|
}
|
|
741
772
|
return this.me;
|
|
742
773
|
}
|
|
774
|
+
/** the hub has no read-ahead routes (an older hub, or the minutes between a release and its deploy): work tasks as before */
|
|
775
|
+
noReadAhead = false;
|
|
776
|
+
/** Whether this runner reads new tasks ahead: a local runtime in a git checkout that delivers pull requests, and a hub that knows how. */
|
|
777
|
+
readsAhead(me) {
|
|
778
|
+
const { client, workspace, adapter } = this.o;
|
|
779
|
+
return !!this.o.readAhead && !this.noReadAhead && !me.system && !adapter.remote && !!workspace.deliverable && !!client.prepareRun && !!client.prepared;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* 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,
|
|
783
|
+
* 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
|
|
784
|
+
* hub then says whether the owner takes it over. A read-ahead that fails reports a code task: the owner looks, nothing is lost.
|
|
785
|
+
*/
|
|
786
|
+
async runPrepare(taskId, entry) {
|
|
787
|
+
const { client, workspace } = this.o;
|
|
788
|
+
const me = await this.ensureMe();
|
|
789
|
+
const runId = (this.o.newRunId ?? newRunId)();
|
|
790
|
+
let bundle;
|
|
791
|
+
try {
|
|
792
|
+
bundle = await client.prepareRun(taskId, runId);
|
|
793
|
+
}
|
|
794
|
+
catch (e) {
|
|
795
|
+
if (is401(e))
|
|
796
|
+
return this.authFailed(`prepare ${taskId}`);
|
|
797
|
+
this.taskLog(taskId, `read-ahead: ${e?.message ?? e}`);
|
|
798
|
+
// a 404 for a task that exists is a hub without the route: stop reading ahead, the next poll works the task as before
|
|
799
|
+
if (e instanceof HubError && e.status === 404 && (await client.getTask(taskId).then(() => true, () => false))) {
|
|
800
|
+
this.noReadAhead = true;
|
|
801
|
+
this.log('the hub cannot read tasks ahead (an older hub): tasks are worked as they come');
|
|
802
|
+
}
|
|
803
|
+
return; // otherwise taken: the next poll sees where it stands
|
|
804
|
+
}
|
|
805
|
+
const report = async (r) => {
|
|
806
|
+
try {
|
|
807
|
+
const out = await client.prepared(taskId, { ...r, handoff_version: bundle.task.handoff_version });
|
|
808
|
+
this.taskLog(taskId, `read ahead: code=${r.code} small=${!!r.small} owner_first=${out.owner_first}`);
|
|
809
|
+
}
|
|
810
|
+
catch (e) {
|
|
811
|
+
this.taskLog(taskId, `read-ahead report: ${e?.message ?? e}`);
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
try {
|
|
815
|
+
let workdir;
|
|
816
|
+
try {
|
|
817
|
+
workdir = await workspace.prepare(bundle.task, me.name);
|
|
818
|
+
}
|
|
819
|
+
catch (e) {
|
|
820
|
+
// the work run fails it with the same reason, as before
|
|
821
|
+
return await report({ code: false, draft: `read-ahead: workspace: ${e?.message ?? e}` });
|
|
822
|
+
}
|
|
823
|
+
const { rules, problems } = loadAutorun(autorunPath(this.o.home));
|
|
824
|
+
if (problems.length)
|
|
825
|
+
this.taskLog(taskId, `autorun.json: ${problems.join('; ')}`);
|
|
826
|
+
const repo = (await workspace.githubOf?.(taskId)) ?? '';
|
|
827
|
+
const mine = rules.filter((r) => r.repo === repo.toLowerCase());
|
|
828
|
+
const rec = { taskId, runId, phase: 'running', workdir, runToken: bundle.run_token, tokenAt: Date.now(), seen: [] };
|
|
829
|
+
const prompt = buildPreparePrompt({
|
|
830
|
+
agentName: me.name,
|
|
831
|
+
ownerName: me.owner_name,
|
|
832
|
+
senderName: bundle.task.from_agent_name,
|
|
833
|
+
task: bundle.task,
|
|
834
|
+
handoff: bundle.handoff,
|
|
835
|
+
messages: bundle.messages,
|
|
836
|
+
files: (await this.fetchFiles(taskId, bundle)).map(promptFile),
|
|
837
|
+
small: mine.map((r) => `${r.paths.join(', ')} (at most ${r.max_files ?? 3} files)`),
|
|
838
|
+
});
|
|
839
|
+
const result = await this.execute(rec, entry, prompt, undefined, 'prepare');
|
|
840
|
+
if (entry.reason)
|
|
841
|
+
return; // stopped (cancel, shutdown): read again next time
|
|
842
|
+
let out;
|
|
843
|
+
try {
|
|
844
|
+
if (!result.ok)
|
|
845
|
+
throw new Error(summarizeRuntimeError(result.error ?? 'the run failed'));
|
|
846
|
+
out = parsePrepared(result.finalText);
|
|
847
|
+
}
|
|
848
|
+
catch (e) {
|
|
849
|
+
return await report({ code: true, draft: `The read-ahead did not finish (${e?.message ?? e}); the task waits for a person to look.` });
|
|
850
|
+
}
|
|
851
|
+
const rule = out.code ? smallRule(rules, repo, out.files) : undefined;
|
|
852
|
+
await report({ code: out.code, small: !!rule, rule: rule ? ruleName(rule) : '', files: out.files, draft: draftText(out, rule ? ruleName(rule) : '') });
|
|
853
|
+
}
|
|
854
|
+
finally {
|
|
855
|
+
if (!this.fatal)
|
|
856
|
+
await client.endRun(taskId, runId).catch((e) => this.log(`end-run ${taskId}: ${e?.message ?? e}`));
|
|
857
|
+
}
|
|
858
|
+
}
|
|
743
859
|
async runWork(taskId, entry) {
|
|
744
860
|
const me = await this.ensureMe();
|
|
745
861
|
const prev = this.state.get(taskId);
|
|
@@ -829,6 +945,7 @@ export class Runner {
|
|
|
829
945
|
const prompt = buildTaskPrompt({
|
|
830
946
|
agentName: me.name,
|
|
831
947
|
ownerName: me.owner_name,
|
|
948
|
+
system: !!me.system,
|
|
832
949
|
senderName: claim.task.from_agent_name,
|
|
833
950
|
task: claim.task,
|
|
834
951
|
handoff: claim.handoff,
|
|
@@ -928,6 +1045,7 @@ export class Runner {
|
|
|
928
1045
|
: buildTaskPrompt({
|
|
929
1046
|
agentName: me.name,
|
|
930
1047
|
ownerName: me.owner_name,
|
|
1048
|
+
system: !!me.system,
|
|
931
1049
|
senderName: bundle.task.from_agent_name,
|
|
932
1050
|
task: bundle.task,
|
|
933
1051
|
handoff: bundle.handoff,
|
|
@@ -972,18 +1090,27 @@ export class Runner {
|
|
|
972
1090
|
}
|
|
973
1091
|
}
|
|
974
1092
|
/**
|
|
975
|
-
* The deliverable of a code task is its pull request. Once the agent finished a round (the task waits for
|
|
976
|
-
* completed), the runner pushes the task's branch with a push token for that one repository and the hub
|
|
977
|
-
* (or the open one simply gets the new commits
|
|
1093
|
+
* The deliverable of a code task is its pull request. Once the agent finished a round (the task waits for its owner's review or
|
|
1094
|
+
* for acceptance, or is completed), the runner pushes the task's branch with a push token for that one repository and the hub
|
|
1095
|
+
* opens the pull request (a draft while the owner reviews it) or the open one simply gets the new commits. The agent never holds
|
|
1096
|
+
* the token. A failed push is said on the task. A round that changed no code tells the hub so: a task waiting for its owner's
|
|
1097
|
+
* review then has nothing to review and goes on to acceptance.
|
|
978
1098
|
*/
|
|
979
|
-
async deliverPr(rec, task) {
|
|
1099
|
+
async deliverPr(rec, task, messages = []) {
|
|
980
1100
|
const { client, workspace } = this.o;
|
|
981
|
-
if (!
|
|
1101
|
+
if (!client.taskPr)
|
|
982
1102
|
return;
|
|
983
|
-
if (task.status !== 'awaiting_acceptance' && task.status !== 'completed')
|
|
1103
|
+
if (task.status !== 'awaiting_review' && task.status !== 'awaiting_acceptance' && task.status !== 'completed')
|
|
984
1104
|
return;
|
|
985
1105
|
if ((task.run_id ?? '') !== rec.runId)
|
|
986
1106
|
return;
|
|
1107
|
+
const nothing = async () => {
|
|
1108
|
+
if (task.status !== 'awaiting_review')
|
|
1109
|
+
return;
|
|
1110
|
+
await client.taskPr(rec.taskId, { run_id: rec.runId, nothing: true }).catch((e) => this.taskLog(rec.taskId, `nothing to review: ${e?.message ?? e}`));
|
|
1111
|
+
};
|
|
1112
|
+
if (!workspace.deliverable || !workspace.push || !client.pushToken)
|
|
1113
|
+
return nothing();
|
|
987
1114
|
let d;
|
|
988
1115
|
try {
|
|
989
1116
|
d = await workspace.deliverable(task);
|
|
@@ -993,7 +1120,15 @@ export class Runner {
|
|
|
993
1120
|
return;
|
|
994
1121
|
}
|
|
995
1122
|
if (!d)
|
|
996
|
-
return;
|
|
1123
|
+
return nothing();
|
|
1124
|
+
// a small job (owner-pulls-tasks.md) is checked against what it really changed: outside its rule, the hub says so on the task
|
|
1125
|
+
let outside;
|
|
1126
|
+
const prep = [...messages].reverse().find((m) => m.sys_code === 'prepared');
|
|
1127
|
+
if (prep?.sys_params?.small === '1' && workspace.changedFiles) {
|
|
1128
|
+
const files = await workspace.changedFiles(task).catch(() => []);
|
|
1129
|
+
if (!smallRule(loadAutorun(autorunPath(this.o.home)).rules, d.github, files))
|
|
1130
|
+
outside = files.slice(0, 100);
|
|
1131
|
+
}
|
|
997
1132
|
const say = (error) => client.taskPr(rec.taskId, { run_id: rec.runId, github: d.github, error }).catch(() => undefined);
|
|
998
1133
|
let tok;
|
|
999
1134
|
try {
|
|
@@ -1015,7 +1150,7 @@ export class Runner {
|
|
|
1015
1150
|
return;
|
|
1016
1151
|
}
|
|
1017
1152
|
try {
|
|
1018
|
-
const r = await client.taskPr(rec.taskId, { run_id: rec.runId, github: d.github, branch: d.branch, commit: d.commit });
|
|
1153
|
+
const r = await client.taskPr(rec.taskId, { run_id: rec.runId, github: d.github, branch: d.branch, commit: d.commit, ...(outside ? { outside } : {}) });
|
|
1019
1154
|
this.taskLog(rec.taskId, `pull request ${r.opened ? 'opened' : 'updated'}: ${r.pr ?? ''}`);
|
|
1020
1155
|
}
|
|
1021
1156
|
catch (e) {
|
|
@@ -1042,7 +1177,7 @@ export class Runner {
|
|
|
1042
1177
|
}
|
|
1043
1178
|
const bundle = await client.getTask(taskId);
|
|
1044
1179
|
const task = bundle.task;
|
|
1045
|
-
await this.deliverPr(rec, task);
|
|
1180
|
+
await this.deliverPr(rec, task, bundle.messages);
|
|
1046
1181
|
if (isTerminal(task.status)) {
|
|
1047
1182
|
this.taskLog(taskId, `run ended; task already ${task.status}`);
|
|
1048
1183
|
this.state.drop(taskId);
|
|
@@ -1352,15 +1487,16 @@ export class Runner {
|
|
|
1352
1487
|
join(this.o.home, 'bin'),
|
|
1353
1488
|
...readRepos.flatMap((r) => r.roots),
|
|
1354
1489
|
...(taskId ? [this.filesDir(taskId)] : []),
|
|
1355
|
-
// the owner's Claude Code memory for this project, read-only (docs/specs/agent-autonomy.md)
|
|
1356
|
-
...[ownerMemoryDir(cwd, home)].filter((d) => !!d),
|
|
1490
|
+
// the owner's Claude Code memory for this project, read-only (docs/specs/agent-autonomy.md); the system agent has no owner
|
|
1491
|
+
...(this.me?.system ? [] : [ownerMemoryDir(cwd, home)].filter((d) => !!d)),
|
|
1357
1492
|
];
|
|
1358
1493
|
}
|
|
1359
1494
|
/** What a full task prompt carries besides the task: the owner's memory for this project and the project's instructions. */
|
|
1360
1495
|
runContext(workdir) {
|
|
1361
1496
|
if (this.o.adapter.remote)
|
|
1362
1497
|
return { project: [] };
|
|
1363
|
-
|
|
1498
|
+
// the system agent works for the team: no person's memory, whatever machine it runs on (docs/specs/system-channels.md)
|
|
1499
|
+
const dir = this.me?.system ? undefined : ownerMemoryDir(workdir, realHomeOf(this.o.baseEnv ?? process.env));
|
|
1364
1500
|
// Claude Code shows the index itself (it keys memory by the repository); other runtimes get it in the prompt
|
|
1365
1501
|
const ownerMemory = dir ? { dir, ...(this.o.adapter.name === 'claude' ? {} : { index: memoryIndex(dir) }) } : undefined;
|
|
1366
1502
|
return { ownerMemory, project: projectInstructions(workdir, this.o.adapter.name) };
|
|
@@ -1461,7 +1597,7 @@ export class Runner {
|
|
|
1461
1597
|
// Except when the agent finished it itself (`ach complete` / `ach fail`, which leaves
|
|
1462
1598
|
// a task sent with review waiting for acceptance): let the turn end so its usage is recorded.
|
|
1463
1599
|
const st = e instanceof HubError ? String(e.body?.status ?? '') : '';
|
|
1464
|
-
const finished = ['completed', 'failed', 'awaiting_acceptance', 'awaiting_merge'].includes(st);
|
|
1600
|
+
const finished = ['completed', 'failed', 'awaiting_review', 'awaiting_acceptance', 'awaiting_merge'].includes(st);
|
|
1465
1601
|
if (is409(e) && !entry.reason && !finished) {
|
|
1466
1602
|
entry.reason = 'lost';
|
|
1467
1603
|
this.taskLog(taskId, 'heartbeat 409: run lost the task; aborting');
|
|
@@ -1506,7 +1642,7 @@ export class Runner {
|
|
|
1506
1642
|
...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
|
|
1507
1643
|
...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
|
|
1508
1644
|
// the agent's budget is a cap on the run too, not only a gate on taking the next task (a run that loops stops at what is left)
|
|
1509
|
-
...(Number(me.budget_usd ?? 0) > 0 ? { maxBudgetUsd: Math.max(0.01, Number(me.budget_usd) - Number(me.spent_usd ?? 0)) + ((mode === 'mention' ? undefined : this.state.session(taskId, mode))?.costTotal ?? 0) } : {}),
|
|
1645
|
+
...(Number(me.budget_usd ?? 0) > 0 ? { maxBudgetUsd: Math.max(0.01, Number(me.budget_usd) - Number(me.spent_usd ?? 0)) + ((mode === 'mention' || mode === 'prepare' ? undefined : this.state.session(taskId, mode))?.costTotal ?? 0) } : {}),
|
|
1510
1646
|
...(outputSchema ? { outputSchema } : {}),
|
|
1511
1647
|
onEvent: (e) => {
|
|
1512
1648
|
lastEvent = Date.now();
|
|
@@ -1515,7 +1651,7 @@ export class Runner {
|
|
|
1515
1651
|
inflight.add(id);
|
|
1516
1652
|
if (e.type === 'tool_end' && id)
|
|
1517
1653
|
inflight.delete(id);
|
|
1518
|
-
if (e.type === 'session' && e.data && mode !== 'mention') {
|
|
1654
|
+
if (e.type === 'session' && e.data && mode !== 'mention' && mode !== 'prepare') {
|
|
1519
1655
|
this.state.setSession(taskId, mode, { id: String(e.data), cwd: rec.workdir });
|
|
1520
1656
|
}
|
|
1521
1657
|
recorder.event(e);
|
|
@@ -1534,7 +1670,7 @@ export class Runner {
|
|
|
1534
1670
|
}
|
|
1535
1671
|
// Claude reports the running total of the whole session; the hub adds up what each run reports, so report only this run's part
|
|
1536
1672
|
let runCost = Number(result.costUsd ?? 0);
|
|
1537
|
-
if (result.sessionId && mode !== 'mention') {
|
|
1673
|
+
if (result.sessionId && mode !== 'mention' && mode !== 'prepare') {
|
|
1538
1674
|
const before = this.state.session(taskId, mode)?.costTotal;
|
|
1539
1675
|
if (result.costCumulative && before !== undefined && runCost >= before)
|
|
1540
1676
|
runCost -= before;
|
|
@@ -1785,3 +1921,36 @@ export function parseStructured(text) {
|
|
|
1785
1921
|
}
|
|
1786
1922
|
throw new Error('no JSON object');
|
|
1787
1923
|
}
|
|
1924
|
+
/** The read-ahead's final JSON object: the last one in its message (bare, fenced, or after a sentence). Throws when there is none. */
|
|
1925
|
+
export function parsePrepared(text) {
|
|
1926
|
+
const t = text.trim();
|
|
1927
|
+
const tries = [t];
|
|
1928
|
+
for (const f of (t.match(/```(?:json)?\s*([\s\S]*?)```/g) ?? []).reverse())
|
|
1929
|
+
tries.push(f.replace(/^```(?:json)?\s*/, '').replace(/```$/, '').trim());
|
|
1930
|
+
const start = t.lastIndexOf('{"code"');
|
|
1931
|
+
if (start >= 0)
|
|
1932
|
+
tries.push(t.slice(start, t.lastIndexOf('}') + 1));
|
|
1933
|
+
for (const x of tries) {
|
|
1934
|
+
let j;
|
|
1935
|
+
try {
|
|
1936
|
+
j = JSON.parse(x);
|
|
1937
|
+
}
|
|
1938
|
+
catch {
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
if (!j || typeof j !== 'object' || typeof j.code !== 'boolean')
|
|
1942
|
+
continue;
|
|
1943
|
+
const list = (v) => (Array.isArray(v) ? v.map((s) => String(s).trim()).filter(Boolean) : []);
|
|
1944
|
+
return { code: j.code, files: list(j.files).slice(0, 200), plan: String(j.plan ?? '').trim(), questions: list(j.questions).slice(0, 20) };
|
|
1945
|
+
}
|
|
1946
|
+
throw new Error('no JSON object with "code"');
|
|
1947
|
+
}
|
|
1948
|
+
/** The draft as the owner reads it on the task: the plan, the files, the questions, and the small-job rule it fell inside. */
|
|
1949
|
+
export function draftText(o, rule) {
|
|
1950
|
+
return [
|
|
1951
|
+
o.plan || (o.code ? '(no plan given)' : 'No code change.'),
|
|
1952
|
+
...(o.files.length ? ['', 'Files:', ...o.files.map((f) => `- ${f}`)] : []),
|
|
1953
|
+
...(o.questions.length ? ['', 'Questions for the sender:', ...o.questions.map((q) => `- ${q}`)] : []),
|
|
1954
|
+
...(rule ? ['', `Small job (autorun.json): ${rule}`] : []),
|
|
1955
|
+
].join('\n');
|
|
1956
|
+
}
|
|
@@ -31,6 +31,10 @@ export interface Workspace {
|
|
|
31
31
|
deliverable?(task: Task): Promise<Deliverable | undefined>;
|
|
32
32
|
/** Push the task's branch to its GitHub repository with a push token (never stored, never seen by the agent). */
|
|
33
33
|
push?(taskId: string, d: Deliverable, token: string): Promise<void>;
|
|
34
|
+
/** "owner/name" of the task's work dir origin on GitHub, '' when it has none (owner-pulls-tasks.md: which autorun rules apply). */
|
|
35
|
+
githubOf?(taskId: string): Promise<string>;
|
|
36
|
+
/** The files the task's branch changed since its base (the small-job check at delivery). */
|
|
37
|
+
changedFiles?(task: Task): Promise<string[]>;
|
|
34
38
|
}
|
|
35
39
|
export interface Deliverable {
|
|
36
40
|
/** "owner/name" on github.com */
|
|
@@ -87,7 +91,15 @@ export declare class GitWorkspace implements Workspace {
|
|
|
87
91
|
*/
|
|
88
92
|
commit(taskId: string, message: string): Promise<string | undefined>;
|
|
89
93
|
deliverable(task: Task): Promise<Deliverable | undefined>;
|
|
94
|
+
githubOf(taskId: string): Promise<string>;
|
|
95
|
+
changedFiles(task: Task): Promise<string[]>;
|
|
90
96
|
push(taskId: string, d: Deliverable, token: string): Promise<void>;
|
|
91
97
|
list(): string[];
|
|
92
98
|
mtime(taskId: string): number;
|
|
93
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* A fresh worktree has the code but none of the checkout's installed dependencies, so the agent could neither build nor test what
|
|
102
|
+
* it wrote. Each node_modules the checkout has (at its root and up to two folders down) that git ignores is linked into the same
|
|
103
|
+
* place in the worktree. The agent reads them; its sandbox lets it write only inside the worktree, so it cannot change them.
|
|
104
|
+
*/
|
|
105
|
+
export declare function linkDeps(dir: string, p: string, log?: (s: string) => void): Promise<number>;
|