@cogitator-ai/bridge 0.10.1 → 0.11.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/README.md +73 -22
- package/dist/checks.d.ts +10 -1
- package/dist/checks.d.ts.map +1 -1
- package/dist/checks.js +12 -0
- package/dist/checks.js.map +1 -1
- package/dist/client.d.ts +6 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +8 -0
- package/dist/client.js.map +1 -1
- package/dist/dispatcher.d.ts +77 -3
- package/dist/dispatcher.d.ts.map +1 -1
- package/dist/dispatcher.js +327 -39
- package/dist/dispatcher.js.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/inputs.d.ts +44 -2
- package/dist/inputs.d.ts.map +1 -1
- package/dist/inputs.js +22 -1
- package/dist/inputs.js.map +1 -1
- package/dist/job-record.d.ts +19 -0
- package/dist/job-record.d.ts.map +1 -1
- package/dist/job-record.js +16 -1
- package/dist/job-record.js.map +1 -1
- package/dist/protocol.d.ts +3 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +3 -1
- package/dist/protocol.js.map +1 -1
- package/dist/recipes/built-in.d.ts.map +1 -1
- package/dist/recipes/built-in.js +6 -2
- package/dist/recipes/built-in.js.map +1 -1
- package/dist/recipes/debate.d.ts.map +1 -1
- package/dist/recipes/debate.js +3 -1
- package/dist/recipes/debate.js.map +1 -1
- package/dist/recipes/race.d.ts.map +1 -1
- package/dist/recipes/race.js +3 -1
- package/dist/recipes/race.js.map +1 -1
- package/dist/recipes/steps.d.ts +10 -9
- package/dist/recipes/steps.d.ts.map +1 -1
- package/dist/recipes/steps.js +10 -12
- package/dist/recipes/steps.js.map +1 -1
- package/dist/registry.d.ts +15 -2
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +18 -2
- package/dist/registry.js.map +1 -1
- package/dist/scoreboard.d.ts +162 -0
- package/dist/scoreboard.d.ts.map +1 -0
- package/dist/scoreboard.js +314 -0
- package/dist/scoreboard.js.map +1 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/tools/guidance.d.ts.map +1 -1
- package/dist/tools/guidance.js +1 -0
- package/dist/tools/guidance.js.map +1 -1
- package/dist/tools/tools.d.ts.map +1 -1
- package/dist/tools/tools.js +47 -4
- package/dist/tools/tools.js.map +1 -1
- package/dist/types.d.ts +61 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +21 -0
- package/dist/types.js.map +1 -1
- package/fakes/claude.mjs +2 -2
- package/fakes/codex.mjs +4 -4
- package/fakes/lib.mjs +50 -9
- package/package.json +2 -1
package/dist/dispatcher.js
CHANGED
|
@@ -6,13 +6,15 @@ import { MAX_RECALL_LIMIT } from './board.js';
|
|
|
6
6
|
import { runCheck, skippedCheck, summarizeChecks } from './checks.js';
|
|
7
7
|
import { BridgeError } from './errors.js';
|
|
8
8
|
import { deliveryBackoff, exhaustedBudget, formatDuration, nextDepth, resolveBudget, resolveLimits, } from './guards.js';
|
|
9
|
-
import { AgentsFilterSchema, CreateJobInputSchema, DEFAULT_INBOX_LIMIT, DEFAULT_LIST_LIMIT, DEFAULT_VERDICT_WAIT_MS, DEFAULT_WAIT_MS, DeliveredInputSchema, EscalateInputSchema, InboxInputSchema, JobsFilterSchema, JournalQuerySchema, LettersFilterSchema, PersonAnswerInputSchema, SendLetterInputSchema, StuckInputSchema, VerdictInputSchema, VerificationInputSchema, AcceptInputSchema, DiffInputSchema, ForgetInputSchema, RecallInputSchema, RejectInputSchema, RememberInputSchema, WaitInputSchema, WithdrawInputSchema, } from './inputs.js';
|
|
9
|
+
import { AgentsFilterSchema, CreateJobInputSchema, DEFAULT_INBOX_LIMIT, DEFAULT_LIST_LIMIT, DEFAULT_VERDICT_WAIT_MS, DEFAULT_WAIT_MS, DeliveredInputSchema, EscalateInputSchema, InboxInputSchema, JobsFilterSchema, JournalQuerySchema, LettersFilterSchema, PersonAnswerInputSchema, SendLetterInputSchema, StuckInputSchema, VerdictInputSchema, VerificationInputSchema, AcceptInputSchema, DiffInputSchema, ForgetInputSchema, RecallInputSchema, RejectInputSchema, RememberInputSchema, ResultsInputSchema, SuggestInputSchema, WaitInputSchema, WithdrawInputSchema, } from './inputs.js';
|
|
10
|
+
import { parseFindings } from './findings.js';
|
|
10
11
|
import { HANDOVER_GAP, buildHandover } from './handover.js';
|
|
11
12
|
import { isFinishedJobState, jobOf, jobRecordOf } from './job-record.js';
|
|
12
13
|
import { expectationOf, forHistory, newLetterId, normalizeBody, oneLine, quoted, renderLetter, repeats, titleOf, } from './letters.js';
|
|
13
14
|
import { canonicalPath, findCheckoutRoot, findProjectRoot, inCheckout, isInside } from './paths.js';
|
|
14
15
|
import { DISCARDED_REFS, GitError, addJobWorktree, branchTip, busyWith, changesOf, checkoutOf, conflictsOf, patchOf, pointRef, removeJobWorktree, shownPath, snapshotOf, squashInto, } from './worktree.js';
|
|
15
|
-
import { allocateAgentName, resolveAddress } from './registry.js';
|
|
16
|
+
import { AUTO_ADDRESS, NEW_SESSION, aliasOfHarness, allocateAgentName, autoAddressOf, resolveAddress, } from './registry.js';
|
|
17
|
+
import { resultOf, suggestFrom } from './scoreboard.js';
|
|
16
18
|
import { BRIDGE_JOB_KEY, BRIDGE_SENDER, CallerIdentitySchema, DEFAULT_LIMITS, HarnessNameSchema, INBOX_DELIVERY, NO_CAPABILITIES, PERSON, } from './types.js';
|
|
17
19
|
const ACTIVE_JOB_STATES = ['submitted', 'working', 'input-required'];
|
|
18
20
|
const FINISHED_JOB_STATES = ['completed', 'failed', 'canceled'];
|
|
@@ -155,6 +157,10 @@ function asError(error) {
|
|
|
155
157
|
}
|
|
156
158
|
/** The ids the conductor of a recipe gives the letters it writes. */
|
|
157
159
|
const RECIPE_LETTER_ID = /^(recipe|relay)-/;
|
|
160
|
+
/** How many finished jobs the scoreboard reads, the newest: more than a machine ends in its window. */
|
|
161
|
+
const SCORED_JOBS = 5_000;
|
|
162
|
+
/** How many reviews of its work the record of a job keeps, the first ones. */
|
|
163
|
+
const REVIEWS_KEPT = 20;
|
|
158
164
|
const NO_CONDUCTOR = 'This bridge carries out no recipes: its host gave it no conductor (recipeAdapter of @cogitator-ai/bridge/recipes)';
|
|
159
165
|
/** `work`, or a rejection when it takes longer than `ms`. */
|
|
160
166
|
function within(work, ms, what) {
|
|
@@ -204,6 +210,8 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
204
210
|
board;
|
|
205
211
|
/** When each agent's other parties were last told it waits at its window, see `stuck` */
|
|
206
212
|
stuckTold = new Map();
|
|
213
|
+
/** The agents a listing of their harness showed waiting at their window, until it shows them not */
|
|
214
|
+
stuckNow = new Set();
|
|
207
215
|
/** Those waiting for the verdict of a permission request, by its id, see `verdict` */
|
|
208
216
|
verdictWaiters = new Map();
|
|
209
217
|
/** What the person route is told, one thing after another */
|
|
@@ -358,6 +366,11 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
358
366
|
async createJob(caller, input) {
|
|
359
367
|
const request = parse(CreateJobInputSchema, input, 'Cannot create the job');
|
|
360
368
|
this.checkBody(request.body);
|
|
369
|
+
const auto = autoAddressOf(request.to);
|
|
370
|
+
if (auto && request.recipe) {
|
|
371
|
+
throw new BridgeError('invalid_input', `A recipe goes to the conductor of the bridge, not to ${AUTO_ADDRESS}: name ${AUTO_ADDRESS} in the input of the recipe, where it says who does a step`);
|
|
372
|
+
}
|
|
373
|
+
const choice = auto ? await this.choiceFor(caller, request) : undefined;
|
|
361
374
|
const handover = request.recipe ? undefined : await this.handoverFor(caller, request);
|
|
362
375
|
const withContext = handover ? `${request.body}${HANDOVER_GAP}${handover}` : request.body;
|
|
363
376
|
const body = withContext.length <= this.limits.maxBodyLength ? withContext : request.body;
|
|
@@ -372,19 +385,30 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
372
385
|
this.taskText(sent) !== request.body) {
|
|
373
386
|
throw new BridgeError('invalid_letter', `The letter id ${request.letterId} belongs to another letter. Give a new job a new id`, { letter: request.letterId });
|
|
374
387
|
}
|
|
375
|
-
|
|
388
|
+
const known = this.requireJob(sent.job).job;
|
|
389
|
+
return {
|
|
390
|
+
job: known,
|
|
391
|
+
letter: sent,
|
|
392
|
+
duplicate: true,
|
|
393
|
+
...(known.routed && { routed: known.routed }),
|
|
394
|
+
};
|
|
376
395
|
}
|
|
377
396
|
}
|
|
378
397
|
if (request.recipe && this.conductors().length === 0) {
|
|
379
398
|
throw new BridgeError('invalid_input', NO_CONDUCTOR, { recipe: request.recipe.name });
|
|
380
399
|
}
|
|
381
|
-
const
|
|
400
|
+
const addressed = {
|
|
382
401
|
project: from.project,
|
|
383
402
|
caller: from.name,
|
|
384
403
|
now: this.now(),
|
|
385
404
|
canSpawn: (harness) => this.adapters.get(harness)?.createSession !== undefined,
|
|
386
|
-
fresh: request.worktree === true || request.recipe !== undefined,
|
|
387
|
-
}
|
|
405
|
+
fresh: request.worktree === true || request.recipe !== undefined || auto?.fresh === true,
|
|
406
|
+
};
|
|
407
|
+
const reviewed = request.reviewOf === undefined ? undefined : this.checkReviewAsked(from, request.reviewOf);
|
|
408
|
+
const taken = choice
|
|
409
|
+
? this.takeChoice(choice, from, addressed, reviewed && this.store.getAgent(reviewed.to)?.harness)
|
|
410
|
+
: undefined;
|
|
411
|
+
const resolution = taken?.resolution ?? resolveAddress(this.store, request.to, addressed);
|
|
388
412
|
this.checkRecipeAsked(resolution, request.recipe);
|
|
389
413
|
if (this.closing && resolution.kind === 'spawn') {
|
|
390
414
|
throw new BridgeError('not_running', 'The bridge dispatcher is closing and starts no session now. Hand the job over again when it runs');
|
|
@@ -430,7 +454,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
430
454
|
if (request.worktree)
|
|
431
455
|
this.checkWorktreeAsked(from, resolution, cwd);
|
|
432
456
|
const now = this.now();
|
|
433
|
-
const refusal = this.handOverRefusal(from, resolution, request.body, cwd, now);
|
|
457
|
+
const refusal = this.handOverRefusal(from, resolution, request.body, cwd, now, !!taken);
|
|
434
458
|
if (refusal) {
|
|
435
459
|
this.journal(tx, {
|
|
436
460
|
type: 'letter.rejected',
|
|
@@ -473,7 +497,10 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
473
497
|
project: from.project,
|
|
474
498
|
cwd,
|
|
475
499
|
...(body !== request.body && { taskLength: request.body.length }),
|
|
500
|
+
...(request.type && { type: request.type }),
|
|
476
501
|
...(request.recipe && { recipe: request.recipe }),
|
|
502
|
+
...(request.reviewOf !== undefined && { reviewOf: request.reviewOf }),
|
|
503
|
+
...(taken && { routed: taken.reason }),
|
|
477
504
|
...(request.worktree && { isolation: 'worktree' }),
|
|
478
505
|
checks: request.checks ?? [],
|
|
479
506
|
budget,
|
|
@@ -493,7 +520,15 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
493
520
|
type: 'job.created',
|
|
494
521
|
job: number,
|
|
495
522
|
agent: from.name,
|
|
496
|
-
data: {
|
|
523
|
+
data: {
|
|
524
|
+
title: record.title,
|
|
525
|
+
from: from.name,
|
|
526
|
+
to: to.name,
|
|
527
|
+
depth,
|
|
528
|
+
cwd,
|
|
529
|
+
...(record.type && { type: record.type }),
|
|
530
|
+
...(taken && { routed: taken.reason }),
|
|
531
|
+
},
|
|
497
532
|
});
|
|
498
533
|
const letter = this.acceptLetter(tx, {
|
|
499
534
|
id: firstLetterId,
|
|
@@ -508,7 +543,12 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
508
543
|
tx.wake.delete(to.name);
|
|
509
544
|
tx.spawns.push({ agent: to.name, job: number, letter: letter.id });
|
|
510
545
|
}
|
|
511
|
-
return {
|
|
546
|
+
return {
|
|
547
|
+
job: this.jobFrom(task),
|
|
548
|
+
letter,
|
|
549
|
+
duplicate: false,
|
|
550
|
+
...(taken && { routed: taken.reason }),
|
|
551
|
+
};
|
|
512
552
|
});
|
|
513
553
|
if (outcome instanceof Refusal)
|
|
514
554
|
throw outcome.error;
|
|
@@ -609,7 +649,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
609
649
|
const reason = exhausted === 'letters'
|
|
610
650
|
? `the job used all ${job.budget.letters} letters of its budget`
|
|
611
651
|
: ranOutOfTime(job);
|
|
612
|
-
await this.failJob(tx, job.number, reason);
|
|
652
|
+
await this.failJob(tx, job.number, reason, exhausted === 'letters' ? 'other' : 'timeout');
|
|
613
653
|
return new Refusal(new BridgeError('budget_exhausted', `Job ${job.number} has failed: ${reason}. The letter was not delivered`, {
|
|
614
654
|
job: job.number,
|
|
615
655
|
exhausted,
|
|
@@ -656,6 +696,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
656
696
|
if (forPerson) {
|
|
657
697
|
tx.asked.push({ letter: letter.id, again: false });
|
|
658
698
|
await this.startWaiting(job.number, now);
|
|
699
|
+
await this.neededPerson(job.number);
|
|
659
700
|
}
|
|
660
701
|
if (answered && request.kind === 'answer') {
|
|
661
702
|
this.markHandled(tx, answered);
|
|
@@ -668,12 +709,20 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
668
709
|
const state = letter.outcome === 'failed' ? 'failed' : 'completed';
|
|
669
710
|
await this.transition(tx, job.number, state, forHistory(request.body, letter.id));
|
|
670
711
|
if (state === 'failed')
|
|
671
|
-
await this.patchRecord(job.taskId, {
|
|
712
|
+
await this.patchRecord(job.taskId, {
|
|
713
|
+
reason: `reported as failed by ${from.name}`,
|
|
714
|
+
failure: 'reported',
|
|
715
|
+
});
|
|
672
716
|
if (changes && job.worktree && !job.worktree.end) {
|
|
673
717
|
await this.patchRecord(job.taskId, { changes });
|
|
674
718
|
}
|
|
675
|
-
|
|
676
|
-
|
|
719
|
+
const findings = request.findings ??
|
|
720
|
+
(job.reviewOf !== undefined ? parseFindings(request.body) : undefined);
|
|
721
|
+
if (findings)
|
|
722
|
+
await this.patchRecord(job.taskId, { findings });
|
|
723
|
+
if (findings && state === 'completed' && job.reviewOf !== undefined) {
|
|
724
|
+
await this.noteReview(job, from.name, findings, now);
|
|
725
|
+
}
|
|
677
726
|
if (state === 'completed' && job.checks.length > 0) {
|
|
678
727
|
this.store.updateLetter(letter.id, { state: 'held' });
|
|
679
728
|
await this.patchRecord(job.taskId, {
|
|
@@ -760,6 +809,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
760
809
|
});
|
|
761
810
|
tx.asked.push({ letter: letter.id, again: false });
|
|
762
811
|
await this.startWaiting(job.number, now);
|
|
812
|
+
await this.neededPerson(job.number);
|
|
763
813
|
return updated;
|
|
764
814
|
});
|
|
765
815
|
}
|
|
@@ -819,13 +869,17 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
819
869
|
*/
|
|
820
870
|
async stuck(caller, input) {
|
|
821
871
|
const request = parse(StuckInputSchema, input, 'Cannot note that the session waits');
|
|
822
|
-
return this.asCaller(caller, async (tx) => this.noteStuck(tx, this.requireCaller(caller), request.what));
|
|
872
|
+
return this.asCaller(caller, async (tx) => this.noteStuck(tx, this.requireCaller(caller), request.what, 'hook'));
|
|
823
873
|
}
|
|
824
|
-
|
|
874
|
+
/**
|
|
875
|
+
* Notes that a session waits for a person at its own window. `seen` says how the bridge
|
|
876
|
+
* learned of it: a `hook` runs once for each dialog, a `listing` of the harness shows the same
|
|
877
|
+
* wait again every time it is asked, so only the first sight of it counts as one more time
|
|
878
|
+
* the jobs of the session needed the person. Whoever handed those jobs over is told, and not
|
|
879
|
+
* again within `limits.windowNoticeMs`.
|
|
880
|
+
*/
|
|
881
|
+
async noteStuck(tx, agent, what, seen) {
|
|
825
882
|
const now = this.now();
|
|
826
|
-
const told = this.stuckTold.get(agent.name);
|
|
827
|
-
if (told !== undefined && now - told < this.limits.windowNoticeMs)
|
|
828
|
-
return [];
|
|
829
883
|
const jobs = this.store
|
|
830
884
|
.jobTasks({ to: agent.name, states: ACTIVE_JOB_STATES })
|
|
831
885
|
.flatMap((task) => jobOf(task) ?? [])
|
|
@@ -833,6 +887,14 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
833
887
|
.sort((a, b) => a.number - b.number);
|
|
834
888
|
if (jobs.length === 0)
|
|
835
889
|
return [];
|
|
890
|
+
const again = seen === 'listing' && this.stuckNow.has(agent.name);
|
|
891
|
+
this.stuckNow.add(agent.name);
|
|
892
|
+
if (!again)
|
|
893
|
+
for (const job of jobs)
|
|
894
|
+
await this.neededPerson(job.number);
|
|
895
|
+
const told = this.stuckTold.get(agent.name);
|
|
896
|
+
if (told !== undefined && now - told < this.limits.windowNoticeMs)
|
|
897
|
+
return [];
|
|
836
898
|
this.stuckTold.set(agent.name, now);
|
|
837
899
|
for (const job of jobs) {
|
|
838
900
|
this.systemNote(tx, job, job.from, `${agent.name} waits for a person at its own window, and job #${job.number} stands still until they answer there. It shows:\n${quoted(what)}\nNobody can answer that from here. If the user is with you, tell them in one line.`);
|
|
@@ -1443,6 +1505,194 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
1443
1505
|
.filter((adapter) => adapter.recipeProblem !== undefined)
|
|
1444
1506
|
.map((adapter) => adapter.harness);
|
|
1445
1507
|
}
|
|
1508
|
+
/**
|
|
1509
|
+
* A review names the job it reviews, and only somebody with a say in that job may: one of its
|
|
1510
|
+
* two agents, whoever handed it over, or the conductor of a recipe, which reviews by the word
|
|
1511
|
+
* of whoever started it.
|
|
1512
|
+
*/
|
|
1513
|
+
checkReviewAsked(from, reviewed) {
|
|
1514
|
+
const { job } = this.requireJob(reviewed);
|
|
1515
|
+
if (job.recipe) {
|
|
1516
|
+
throw new BridgeError('invalid_input', `Job ${reviewed} is a recipe: review the job of the step that did the work`, { job: reviewed });
|
|
1517
|
+
}
|
|
1518
|
+
const party = from.name === job.from || from.name === job.to;
|
|
1519
|
+
if (party || this.conducts(from) || this.handedOver(from.name, job))
|
|
1520
|
+
return job;
|
|
1521
|
+
throw new BridgeError('not_a_party', `Job ${reviewed} is between ${job.from} and ${job.to}: only they, or whoever handed it over, have its work reviewed`, { job: reviewed });
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Counts what a review found on the record of the job it reviewed, once for each review. A
|
|
1525
|
+
* review by the agent that did the work, and one that agent had made of its own work, count
|
|
1526
|
+
* for nothing: nobody rates itself. The first reviews of a job are the ones kept, so a later
|
|
1527
|
+
* one cannot push an earlier one out.
|
|
1528
|
+
*/
|
|
1529
|
+
async noteReview(review, by, findings, now) {
|
|
1530
|
+
if (review.reviewOf === undefined)
|
|
1531
|
+
return;
|
|
1532
|
+
const task = this.store.taskOfJob(review.reviewOf);
|
|
1533
|
+
const reviewed = task && jobOf(task);
|
|
1534
|
+
if (!reviewed || by === reviewed.to || this.ruledBy(review) === reviewed.to)
|
|
1535
|
+
return;
|
|
1536
|
+
const known = reviewed.reviews ?? [];
|
|
1537
|
+
if (known.length >= REVIEWS_KEPT || known.some((kept) => kept.job === review.number))
|
|
1538
|
+
return;
|
|
1539
|
+
const counted = {
|
|
1540
|
+
job: review.number,
|
|
1541
|
+
by,
|
|
1542
|
+
at: this.iso(now),
|
|
1543
|
+
blocker: 0,
|
|
1544
|
+
major: 0,
|
|
1545
|
+
minor: 0,
|
|
1546
|
+
nit: 0,
|
|
1547
|
+
};
|
|
1548
|
+
for (const finding of findings)
|
|
1549
|
+
counted[finding.severity] += 1;
|
|
1550
|
+
await this.patchRecord(reviewed.taskId, { reviews: [...known, counted] });
|
|
1551
|
+
}
|
|
1552
|
+
/** Notes that a job needed the person once more: the scoreboard counts how often it did. */
|
|
1553
|
+
async neededPerson(number) {
|
|
1554
|
+
const { job } = this.requireJob(number);
|
|
1555
|
+
await this.patchRecord(job.taskId, { personNeeded: (job.personNeeded ?? 0) + 1 });
|
|
1556
|
+
}
|
|
1557
|
+
/** The harnesses a job can be handed to with nobody named, in the order of the adapters. */
|
|
1558
|
+
routable() {
|
|
1559
|
+
return [...this.adapters.values()]
|
|
1560
|
+
.filter((adapter) => adapter.createSession !== undefined && !adapter.recipeProblem)
|
|
1561
|
+
.map((adapter) => adapter.harness);
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* What became of the jobs that ended within the window of the scoreboard, newest first. The
|
|
1565
|
+
* window is measured from when a job ended, whenever it was handed over, among the newest
|
|
1566
|
+
* `SCORED_JOBS` finished jobs.
|
|
1567
|
+
*/
|
|
1568
|
+
scored() {
|
|
1569
|
+
const harnesses = new Map();
|
|
1570
|
+
const harnessOf = (agent) => {
|
|
1571
|
+
if (!harnesses.has(agent))
|
|
1572
|
+
harnesses.set(agent, this.store.getAgent(agent)?.harness);
|
|
1573
|
+
return harnesses.get(agent);
|
|
1574
|
+
};
|
|
1575
|
+
const since = this.now() - this.limits.scoreWindowMs;
|
|
1576
|
+
return this.store
|
|
1577
|
+
.jobTasks({ states: ['completed', 'failed'], limit: SCORED_JOBS })
|
|
1578
|
+
.flatMap((task) => {
|
|
1579
|
+
const job = jobOf(task);
|
|
1580
|
+
const harness = job && harnessOf(job.to);
|
|
1581
|
+
if (!job || !harness || this.adapters.get(harness)?.recipeProblem)
|
|
1582
|
+
return [];
|
|
1583
|
+
const result = resultOf(job, harness);
|
|
1584
|
+
return result && Date.parse(result.endedAt) >= since ? [result] : [];
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Who a job handed to `auto` goes to, worked out before the job is created: the suggestion of
|
|
1589
|
+
* the scoreboard, and the sessions of the caller's project that would not wake for a letter,
|
|
1590
|
+
* which `auto` passes over for a fresh session. Undefined for a job that was handed over
|
|
1591
|
+
* before under the same letter id: it is with whoever got it then.
|
|
1592
|
+
*/
|
|
1593
|
+
async choiceFor(caller, request) {
|
|
1594
|
+
const { letterId, type } = request;
|
|
1595
|
+
const known = await this.enqueue(async () => ({
|
|
1596
|
+
sent: letterId !== undefined && this.store.getLetter(letterId) !== undefined,
|
|
1597
|
+
project: this.store.getAgent(caller)?.project,
|
|
1598
|
+
harnesses: this.routable(),
|
|
1599
|
+
}));
|
|
1600
|
+
if (known.sent)
|
|
1601
|
+
return undefined;
|
|
1602
|
+
const suggestion = await this.suggest(type === undefined ? {} : { type });
|
|
1603
|
+
const { project, harnesses } = known;
|
|
1604
|
+
const sessions = project === undefined
|
|
1605
|
+
? []
|
|
1606
|
+
: await this.enqueue(async () => this.store
|
|
1607
|
+
.listAgents({ project, statuses: ['active'] })
|
|
1608
|
+
.filter((agent) => agent.name !== caller && harnesses.includes(agent.harness)));
|
|
1609
|
+
const asleep = new Set();
|
|
1610
|
+
for (const agent of sessions) {
|
|
1611
|
+
if (!(await this.wakes(agent.name)))
|
|
1612
|
+
asleep.add(agent.name);
|
|
1613
|
+
}
|
|
1614
|
+
return { suggestion, asleep };
|
|
1615
|
+
}
|
|
1616
|
+
/** The agents a caller works for: those that handed it its jobs, and those above them. */
|
|
1617
|
+
worksFor(caller) {
|
|
1618
|
+
const above = new Set();
|
|
1619
|
+
for (const task of this.store.jobTasks({ to: caller, states: ACTIVE_JOB_STATES })) {
|
|
1620
|
+
const job = jobOf(task);
|
|
1621
|
+
if (!job)
|
|
1622
|
+
continue;
|
|
1623
|
+
for (const link of this.chainOf(job.number))
|
|
1624
|
+
above.add(link.from);
|
|
1625
|
+
}
|
|
1626
|
+
return above;
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Finds the agent a job handed to `auto` goes to: the best of the suggestion first, then the
|
|
1630
|
+
* others a job can go to. Each is tried by its harness word, and by a fresh session where the
|
|
1631
|
+
* session that is there would not wake, several fit, or the session is one the caller works
|
|
1632
|
+
* for, which would then wait for the caller while the caller waits for it. A harness the
|
|
1633
|
+
* bridge cannot start a session of right now is passed over for the next. `avoid` names a
|
|
1634
|
+
* harness to take last: the one that did the work a review is of.
|
|
1635
|
+
*
|
|
1636
|
+
* @throws BridgeError `no_session` when the job can go to none of them
|
|
1637
|
+
*/
|
|
1638
|
+
takeChoice(choice, from, context, avoid) {
|
|
1639
|
+
const { suggestion, asleep } = choice;
|
|
1640
|
+
const open = suggestion.candidates.filter((candidate) => candidate.available);
|
|
1641
|
+
const first = open.find((candidate) => candidate.harness === suggestion.best);
|
|
1642
|
+
const ranked = first ? [first, ...open.filter((candidate) => candidate !== first)] : open;
|
|
1643
|
+
const order = [
|
|
1644
|
+
...ranked.filter((candidate) => candidate.harness !== avoid),
|
|
1645
|
+
...ranked.filter((candidate) => candidate.harness === avoid),
|
|
1646
|
+
];
|
|
1647
|
+
const above = this.worksFor(from.name);
|
|
1648
|
+
const passed = [];
|
|
1649
|
+
for (const candidate of order) {
|
|
1650
|
+
const name = aliasOfHarness(candidate.harness);
|
|
1651
|
+
let refused;
|
|
1652
|
+
for (const address of [candidate.harness, `${candidate.harness}:${NEW_SESSION}`]) {
|
|
1653
|
+
let resolution;
|
|
1654
|
+
try {
|
|
1655
|
+
resolution = resolveAddress(this.store, address, context);
|
|
1656
|
+
}
|
|
1657
|
+
catch (error) {
|
|
1658
|
+
if (!(error instanceof BridgeError) ||
|
|
1659
|
+
(error.code !== 'ambiguous_agent' && error.code !== 'no_session')) {
|
|
1660
|
+
throw error;
|
|
1661
|
+
}
|
|
1662
|
+
if (error.code === 'no_session')
|
|
1663
|
+
refused = error.message;
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
if (resolution.kind === 'agent') {
|
|
1667
|
+
const { agent } = resolution;
|
|
1668
|
+
if (asleep.has(agent.name) || above.has(agent.name))
|
|
1669
|
+
continue;
|
|
1670
|
+
}
|
|
1671
|
+
else {
|
|
1672
|
+
const full = this.startingRefusal();
|
|
1673
|
+
if (full) {
|
|
1674
|
+
refused = full.message;
|
|
1675
|
+
continue;
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
const reason = candidate.harness === suggestion.best
|
|
1679
|
+
? suggestion.reason
|
|
1680
|
+
: `${suggestion.reason}. ${passed.length > 0
|
|
1681
|
+
? `The job could not go there (${passed.join('. ')})`
|
|
1682
|
+
: `${aliasOfHarness(avoid ?? '')} did the work this job reviews`}, so ${name} took it`;
|
|
1683
|
+
return { resolution, reason };
|
|
1684
|
+
}
|
|
1685
|
+
passed.push(`${name}: ${refused ?? 'its session would not wake for the job'}`);
|
|
1686
|
+
}
|
|
1687
|
+
throw new BridgeError('no_session', `${AUTO_ADDRESS} found no agent the job can go to. ${passed.length > 0 ? passed.join('. ') : suggestion.reason}`, { harnesses: order.map((candidate) => candidate.harness) });
|
|
1688
|
+
}
|
|
1689
|
+
/** Why the bridge starts no session right now, when too many are being started already. */
|
|
1690
|
+
startingRefusal() {
|
|
1691
|
+
const starting = this.store.listAgents({ statuses: ['starting'] }).length;
|
|
1692
|
+
if (starting < this.limits.maxStartingSessions)
|
|
1693
|
+
return undefined;
|
|
1694
|
+
return new BridgeError('no_session', `The bridge is already starting ${starting} sessions, the most at once. Hand the job over again when they are up`, { starting, max: this.limits.maxStartingSessions });
|
|
1695
|
+
}
|
|
1446
1696
|
/**
|
|
1447
1697
|
* Refuses a recipe the conductor cannot start, and a job for the conductor that names none.
|
|
1448
1698
|
* Every recipe gets a conductor of its own, so a recipe is addressed by the harness word of
|
|
@@ -2313,6 +2563,40 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2313
2563
|
return fitting(this.store.readJournal({ ...request, limit: request.limit ?? DEFAULT_LIST_LIMIT }), size);
|
|
2314
2564
|
});
|
|
2315
2565
|
}
|
|
2566
|
+
/**
|
|
2567
|
+
* What became of the jobs that ended within the window of the scoreboard
|
|
2568
|
+
* (`limits.scoreWindowMs`), newest first: who carried each out, its type, whether anything
|
|
2569
|
+
* confirmed its result, what its reviews found, how long it took, how many letters, and how
|
|
2570
|
+
* many times it needed the person. Canceled jobs and recipes are not among them.
|
|
2571
|
+
*/
|
|
2572
|
+
async results(input = {}) {
|
|
2573
|
+
const request = parse(ResultsInputSchema, input, 'Cannot list the results');
|
|
2574
|
+
return this.enqueue(async () => this.scored()
|
|
2575
|
+
.filter((result) => (request.type === undefined || result.type === request.type) &&
|
|
2576
|
+
(request.harness === undefined || result.harness === request.harness) &&
|
|
2577
|
+
(request.agent === undefined || result.agent === request.agent))
|
|
2578
|
+
.slice(0, request.limit ?? DEFAULT_LIST_LIMIT));
|
|
2579
|
+
}
|
|
2580
|
+
/**
|
|
2581
|
+
* Who a job should go to, by how earlier jobs went: every harness the bridge can start a
|
|
2582
|
+
* session of with its rate of jobs that held and the interval of that rate, the one `auto`
|
|
2583
|
+
* would take now, and why. With too few checked jobs it says so, and goes by the order of the
|
|
2584
|
+
* adapters instead of a rating it does not have.
|
|
2585
|
+
*/
|
|
2586
|
+
async suggest(input = {}) {
|
|
2587
|
+
const request = parse(SuggestInputSchema, input, 'Cannot suggest an agent');
|
|
2588
|
+
const { results, harnesses } = await this.enqueue(async () => ({
|
|
2589
|
+
results: this.scored(),
|
|
2590
|
+
harnesses: this.routable(),
|
|
2591
|
+
}));
|
|
2592
|
+
return suggestFrom(results, {
|
|
2593
|
+
...(request.type !== undefined && { type: request.type }),
|
|
2594
|
+
minJobs: this.limits.scoreMinJobs,
|
|
2595
|
+
windowMs: this.limits.scoreWindowMs,
|
|
2596
|
+
harnesses,
|
|
2597
|
+
unavailable: () => undefined,
|
|
2598
|
+
});
|
|
2599
|
+
}
|
|
2316
2600
|
/**
|
|
2317
2601
|
* The harnesses the bridge can start a session of for a job. The conductor of recipes is none
|
|
2318
2602
|
* of them: it takes a recipe, not a job.
|
|
@@ -2386,7 +2670,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2386
2670
|
continue;
|
|
2387
2671
|
if (this.waitsForPerson(late.number))
|
|
2388
2672
|
continue;
|
|
2389
|
-
await this.failJob(tx, late.number, ranOutOfTime(late));
|
|
2673
|
+
await this.failJob(tx, late.number, ranOutOfTime(late), 'timeout');
|
|
2390
2674
|
failed.push(late.number);
|
|
2391
2675
|
}
|
|
2392
2676
|
for (const letter of this.store.listLetters({ replyDueBy: now })) {
|
|
@@ -2439,7 +2723,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2439
2723
|
reminded.push(letter.id);
|
|
2440
2724
|
continue;
|
|
2441
2725
|
}
|
|
2442
|
-
await this.failJob(tx, job.number, `${letter.to} did not ${pickup ? 'take' : 'answer'} the ${letter.kind} ${letter.id} in ${formatDuration(2 * job.budget.replyTimeoutMs)}
|
|
2726
|
+
await this.failJob(tx, job.number, `${letter.to} did not ${pickup ? 'take' : 'answer'} the ${letter.kind} ${letter.id} in ${formatDuration(2 * job.budget.replyTimeoutMs)}`, letter.to === job.to ? 'silent' : 'other');
|
|
2443
2727
|
failed.push(job.number);
|
|
2444
2728
|
}
|
|
2445
2729
|
failed.push(...(await this.remindOfReports(tx, now)));
|
|
@@ -2478,7 +2762,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2478
2762
|
continue;
|
|
2479
2763
|
if (this.inTurn(this.store.getAgent(job.to)))
|
|
2480
2764
|
continue;
|
|
2481
|
-
await this.failJob(tx, job.number, `${job.to} ended its turn without a report and did not react to the reminder in ${formatDuration(patience)}
|
|
2765
|
+
await this.failJob(tx, job.number, `${job.to} ended its turn without a report and did not react to the reminder in ${formatDuration(patience)}`, 'silent');
|
|
2482
2766
|
failed.push(job.number);
|
|
2483
2767
|
}
|
|
2484
2768
|
for (const [name, waiter] of this.waiters) {
|
|
@@ -2559,12 +2843,15 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2559
2843
|
.then((sessions) => this.mutate(async (tx) => {
|
|
2560
2844
|
await this.applyPresence(tx, harness, new Set(sessions.map((session) => session.sessionId)), adapter.ownsSessions === true, asked, new Set(sessions.flatMap((session) => (session.busy ? [session.sessionId] : []))));
|
|
2561
2845
|
for (const session of sessions) {
|
|
2562
|
-
if (!session.waitingFor)
|
|
2563
|
-
continue;
|
|
2564
2846
|
const agent = this.store.agentOfSession(harness, session.sessionId);
|
|
2847
|
+
if (!session.waitingFor) {
|
|
2848
|
+
if (agent)
|
|
2849
|
+
this.stuckNow.delete(agent.name);
|
|
2850
|
+
continue;
|
|
2851
|
+
}
|
|
2565
2852
|
if (agent?.status !== 'active')
|
|
2566
2853
|
continue;
|
|
2567
|
-
this.noteStuck(tx, agent, `It waits for: ${session.waitingFor}
|
|
2854
|
+
await this.noteStuck(tx, agent, `It waits for: ${session.waitingFor}`, 'listing');
|
|
2568
2855
|
}
|
|
2569
2856
|
}))
|
|
2570
2857
|
.finally(() => this.listing.delete(harness)));
|
|
@@ -2883,12 +3170,16 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2883
3170
|
this.store.updateLetter(task.id, { clear: ['replyDueAt'] });
|
|
2884
3171
|
}
|
|
2885
3172
|
}
|
|
2886
|
-
|
|
3173
|
+
/**
|
|
3174
|
+
* Fails a job. `failure` says whose doing it was: the scoreboard holds only what its agent did
|
|
3175
|
+
* against the agent.
|
|
3176
|
+
*/
|
|
3177
|
+
async failJob(tx, number, reason, failure = 'other') {
|
|
2887
3178
|
const { job } = this.requireJob(number);
|
|
2888
3179
|
if (isFinishedJobState(job.state))
|
|
2889
3180
|
return;
|
|
2890
3181
|
await this.transition(tx, number, 'failed', reason);
|
|
2891
|
-
await this.patchRecord(job.taskId, { reason });
|
|
3182
|
+
await this.patchRecord(job.taskId, { reason, failure });
|
|
2892
3183
|
this.closeLetters(tx, number);
|
|
2893
3184
|
await this.stopWaiting(number, this.now(), false);
|
|
2894
3185
|
this.noteOutcome(tx, number);
|
|
@@ -2923,17 +3214,20 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2923
3214
|
}
|
|
2924
3215
|
/**
|
|
2925
3216
|
* Why an agent may not hand this job over right now, if it may not: it is the job it already
|
|
2926
|
-
* handed to the same agent and that is still in progress
|
|
2927
|
-
*
|
|
3217
|
+
* handed to the same agent and that is still in progress (for a job left to `auto`: one it
|
|
3218
|
+
* left to `auto` before, whoever got it), it has too many jobs out, it hands jobs over too
|
|
3219
|
+
* fast, or too many sessions are being started.
|
|
2928
3220
|
*/
|
|
2929
|
-
handOverRefusal(from, resolution, body, cwd, now) {
|
|
3221
|
+
handOverRefusal(from, resolution, body, cwd, now, routed = false) {
|
|
2930
3222
|
const open = this.store
|
|
2931
3223
|
.jobTasks({ from: from.name, states: ACTIVE_JOB_STATES })
|
|
2932
3224
|
.flatMap((task) => jobOf(task) ?? []);
|
|
2933
3225
|
const wanted = normalizeBody(body);
|
|
2934
|
-
const sameAgent = (job) =>
|
|
2935
|
-
? job.
|
|
2936
|
-
:
|
|
3226
|
+
const sameAgent = (job) => routed
|
|
3227
|
+
? job.routed !== undefined
|
|
3228
|
+
: resolution.kind === 'agent'
|
|
3229
|
+
? job.to === resolution.agent.name
|
|
3230
|
+
: this.store.getAgent(job.to)?.harness === resolution.harness;
|
|
2937
3231
|
const same = open.find((job) => {
|
|
2938
3232
|
if (job.cwd !== cwd || !sameAgent(job))
|
|
2939
3233
|
return false;
|
|
@@ -2950,13 +3244,7 @@ export class BridgeDispatcher extends EventEmitter {
|
|
|
2950
3244
|
if (recent >= this.limits.jobsPerHour) {
|
|
2951
3245
|
return new BridgeError('budget_exhausted', `You handed over ${recent} jobs in the last hour, the most there may be. This looks like a loop: stop and tell the person what is going on`, { recent, max: this.limits.jobsPerHour });
|
|
2952
3246
|
}
|
|
2953
|
-
|
|
2954
|
-
const starting = this.store.listAgents({ statuses: ['starting'] }).length;
|
|
2955
|
-
if (starting >= this.limits.maxStartingSessions) {
|
|
2956
|
-
return new BridgeError('no_session', `The bridge is already starting ${starting} sessions, the most at once. Hand the job over again when they are up`, { starting, max: this.limits.maxStartingSessions });
|
|
2957
|
-
}
|
|
2958
|
-
}
|
|
2959
|
-
return undefined;
|
|
3247
|
+
return resolution.kind === 'spawn' ? this.startingRefusal() : undefined;
|
|
2960
3248
|
}
|
|
2961
3249
|
/**
|
|
2962
3250
|
* A finished job waits for nothing: its own letter and the questions nobody answered are done
|