@cogitator-ai/bridge 0.8.0 → 0.9.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.
Files changed (60) hide show
  1. package/README.md +101 -18
  2. package/dist/adapter.d.ts +28 -2
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapters/codex.d.ts.map +1 -1
  5. package/dist/adapters/codex.js +4 -0
  6. package/dist/adapters/codex.js.map +1 -1
  7. package/dist/dispatcher.d.ts +76 -13
  8. package/dist/dispatcher.d.ts.map +1 -1
  9. package/dist/dispatcher.js +260 -56
  10. package/dist/dispatcher.js.map +1 -1
  11. package/dist/findings.d.ts +59 -0
  12. package/dist/findings.d.ts.map +1 -0
  13. package/dist/findings.js +117 -0
  14. package/dist/findings.js.map +1 -0
  15. package/dist/index.d.ts +3 -2
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/inputs.d.ts +27 -1
  20. package/dist/inputs.d.ts.map +1 -1
  21. package/dist/inputs.js +32 -1
  22. package/dist/inputs.js.map +1 -1
  23. package/dist/job-record.d.ts +15 -0
  24. package/dist/job-record.d.ts.map +1 -1
  25. package/dist/job-record.js +3 -0
  26. package/dist/job-record.js.map +1 -1
  27. package/dist/letters.d.ts +1 -1
  28. package/dist/letters.d.ts.map +1 -1
  29. package/dist/letters.js +6 -0
  30. package/dist/letters.js.map +1 -1
  31. package/dist/recipes/built-in.d.ts +35 -0
  32. package/dist/recipes/built-in.d.ts.map +1 -0
  33. package/dist/recipes/built-in.js +439 -0
  34. package/dist/recipes/built-in.js.map +1 -0
  35. package/dist/recipes/conductor.d.ts +61 -0
  36. package/dist/recipes/conductor.d.ts.map +1 -0
  37. package/dist/recipes/conductor.js +581 -0
  38. package/dist/recipes/conductor.js.map +1 -0
  39. package/dist/recipes/index.d.ts +5 -0
  40. package/dist/recipes/index.d.ts.map +1 -0
  41. package/dist/recipes/index.js +5 -0
  42. package/dist/recipes/index.js.map +1 -0
  43. package/dist/recipes/recipe.d.ts +128 -0
  44. package/dist/recipes/recipe.d.ts.map +1 -0
  45. package/dist/recipes/recipe.js +54 -0
  46. package/dist/recipes/recipe.js.map +1 -0
  47. package/dist/registry.d.ts +5 -0
  48. package/dist/registry.d.ts.map +1 -1
  49. package/dist/registry.js +5 -0
  50. package/dist/registry.js.map +1 -1
  51. package/dist/tools/guidance.d.ts.map +1 -1
  52. package/dist/tools/guidance.js +1 -0
  53. package/dist/tools/guidance.js.map +1 -1
  54. package/dist/tools/tools.d.ts.map +1 -1
  55. package/dist/tools/tools.js +151 -26
  56. package/dist/tools/tools.js.map +1 -1
  57. package/dist/types.d.ts +19 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/types.js.map +1 -1
  60. package/package.json +11 -1
@@ -153,6 +153,9 @@ function userMessage(text) {
153
153
  function asError(error) {
154
154
  return error instanceof Error ? error : new Error(String(error));
155
155
  }
156
+ /** The ids the conductor of a recipe gives the letters it writes. */
157
+ const RECIPE_LETTER_ID = /^(recipe|relay)-/;
158
+ const NO_CONDUCTOR = 'This bridge carries out no recipes: its host gave it no conductor (recipeAdapter of @cogitator-ai/bridge/recipes)';
156
159
  /** `work`, or a rejection when it takes longer than `ms`. */
157
160
  function within(work, ms, what) {
158
161
  return new Promise((resolve, reject) => {
@@ -355,11 +358,12 @@ export class BridgeDispatcher extends EventEmitter {
355
358
  async createJob(caller, input) {
356
359
  const request = parse(CreateJobInputSchema, input, 'Cannot create the job');
357
360
  this.checkBody(request.body);
358
- const handover = await this.handoverFor(caller, request);
361
+ const handover = request.recipe ? undefined : await this.handoverFor(caller, request);
359
362
  const withContext = handover ? `${request.body}${HANDOVER_GAP}${handover}` : request.body;
360
363
  const body = withContext.length <= this.limits.maxBodyLength ? withContext : request.body;
361
364
  const outcome = await this.asCaller(caller, async (tx) => {
362
365
  const from = this.requireCaller(caller);
366
+ this.checkOwnId(request.letterId, from);
363
367
  if (request.letterId) {
364
368
  const sent = this.store.getLetter(request.letterId);
365
369
  if (sent) {
@@ -371,13 +375,20 @@ export class BridgeDispatcher extends EventEmitter {
371
375
  return { job: this.requireJob(sent.job).job, letter: sent, duplicate: true };
372
376
  }
373
377
  }
378
+ if (request.recipe && this.conductors().length === 0) {
379
+ throw new BridgeError('invalid_input', NO_CONDUCTOR, { recipe: request.recipe.name });
380
+ }
374
381
  const resolution = resolveAddress(this.store, request.to, {
375
382
  project: from.project,
376
383
  caller: from.name,
377
384
  now: this.now(),
378
385
  canSpawn: (harness) => this.adapters.get(harness)?.createSession !== undefined,
379
- fresh: request.worktree === true,
386
+ fresh: request.worktree === true || request.recipe !== undefined,
380
387
  });
388
+ this.checkRecipeAsked(resolution, request.recipe);
389
+ if (this.closing && resolution.kind === 'spawn') {
390
+ throw new BridgeError('not_running', 'The bridge dispatcher is closing and starts no session now. Hand the job over again when it runs');
391
+ }
381
392
  const carriedOut = this.store
382
393
  .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
383
394
  .flatMap((task) => jobOf(task) ?? []);
@@ -394,6 +405,8 @@ export class BridgeDispatcher extends EventEmitter {
394
405
  let depth;
395
406
  try {
396
407
  depth = nextDepth(parent?.depth, this.limits);
408
+ if (request.recipe)
409
+ nextDepth(depth, this.limits);
397
410
  }
398
411
  catch (error) {
399
412
  if (!(error instanceof BridgeError))
@@ -460,6 +473,7 @@ export class BridgeDispatcher extends EventEmitter {
460
473
  project: from.project,
461
474
  cwd,
462
475
  ...(body !== request.body && { taskLength: request.body.length }),
476
+ ...(request.recipe && { recipe: request.recipe }),
463
477
  ...(request.worktree && { isolation: 'worktree' }),
464
478
  checks: request.checks ?? [],
465
479
  budget,
@@ -521,6 +535,7 @@ export class BridgeDispatcher extends EventEmitter {
521
535
  const changes = request.kind === 'report' ? await this.changesAtReport(request.job) : undefined;
522
536
  const outcome = await this.asCaller(caller, async (tx) => {
523
537
  const from = this.requireCaller(caller);
538
+ this.checkOwnId(request.id, from);
524
539
  if (request.id) {
525
540
  const sent = this.store.getLetter(request.id);
526
541
  if (sent) {
@@ -611,7 +626,7 @@ export class BridgeDispatcher extends EventEmitter {
611
626
  await this.pickUp(tx, job);
612
627
  const forPerson = rights === 'ask' && this.person !== undefined;
613
628
  const refused = rights === 'deny'
614
- ? `The rules of ${job.from} forbid this, so it is refused`
629
+ ? `The rules of ${this.ruledBy(job)} forbid this, so it is refused`
615
630
  : rights === 'ask' && !forPerson
616
631
  ? 'Only the person can allow this, and this bridge has no way to reach them, so it is refused'
617
632
  : undefined;
@@ -628,7 +643,8 @@ export class BridgeDispatcher extends EventEmitter {
628
643
  ...(request.verdict && { verdict: request.verdict }),
629
644
  ...(forPerson && { needsPerson: true, personAskedAt: this.iso(now) }),
630
645
  ...(expectationOf(request.kind) === 'reply' &&
631
- !refused && {
646
+ !refused &&
647
+ !this.conducts(this.store.getAgent(to)) && {
632
648
  replyDueAt: this.iso(now + (forPerson ? this.limits.personReplyTimeoutMs : job.budget.replyTimeoutMs)),
633
649
  }),
634
650
  });
@@ -656,6 +672,8 @@ export class BridgeDispatcher extends EventEmitter {
656
672
  if (changes && job.worktree && !job.worktree.end) {
657
673
  await this.patchRecord(job.taskId, { changes });
658
674
  }
675
+ if (request.findings)
676
+ await this.patchRecord(job.taskId, { findings: request.findings });
659
677
  if (state === 'completed' && job.checks.length > 0) {
660
678
  this.store.updateLetter(letter.id, { state: 'held' });
661
679
  await this.patchRecord(job.taskId, {
@@ -964,8 +982,10 @@ export class BridgeDispatcher extends EventEmitter {
964
982
  /**
965
983
  * What the rules of the agent that handed a job over make of a call. A job handed over from
966
984
  * inside a job is bound by every agent up the chain: the call is theirs to allow only when it
967
- * is each one's, and forbidden when any of them may not make it. A judge that throws, and a
968
- * bridge without one, leave the call to the person: nothing is allowed by accident.
985
+ * is each one's, and forbidden when any of them may not make it. The conductor of a recipe has
986
+ * no rules of its own: a job it handed out is judged by the rules of whoever started the
987
+ * recipe, and on up. A judge that throws, and a bridge without one, leave the call to the
988
+ * person: nothing is allowed by accident.
969
989
  */
970
990
  async rightsFor(number, ask) {
971
991
  if (!this.rights)
@@ -976,12 +996,18 @@ export class BridgeDispatcher extends EventEmitter {
976
996
  const job = this.jobIfAny(at);
977
997
  if (!job)
978
998
  return 'ask';
979
- const said = await this.rights({ job, delegator: this.store.getAgent(job.from), ask });
999
+ const delegator = this.store.getAgent(job.from);
1000
+ at = job.parent;
1001
+ if (this.conducts(delegator)) {
1002
+ if (at === undefined)
1003
+ return 'ask';
1004
+ continue;
1005
+ }
1006
+ const said = await this.rights({ job, delegator, ask });
980
1007
  if (said === 'deny')
981
1008
  return 'deny';
982
1009
  if (said === 'ask')
983
1010
  rights = 'ask';
984
- at = job.parent;
985
1011
  }
986
1012
  }
987
1013
  catch (error) {
@@ -1025,17 +1051,51 @@ export class BridgeDispatcher extends EventEmitter {
1025
1051
  * from inside it waits for them.
1026
1052
  */
1027
1053
  waitsForPerson(number) {
1028
- const own = this.store.countLetters({
1029
- job: number,
1030
- needsPerson: true,
1031
- states: ['queued', 'delivered', 'read'],
1032
- });
1033
- if (own > 0)
1054
+ if (this.asksPerson(number))
1034
1055
  return true;
1035
- return this.store.jobTasks({ parent: number, states: ACTIVE_JOB_STATES }).some((task) => {
1056
+ const below = this.store
1057
+ .jobTasks({ parent: number, states: ACTIVE_JOB_STATES })
1058
+ .some((task) => {
1036
1059
  const child = jobOf(task);
1037
1060
  return child !== undefined && this.waitsForPerson(child.number);
1038
1061
  });
1062
+ if (below)
1063
+ return true;
1064
+ const recipe = this.recipeAbove(number);
1065
+ return recipe !== undefined && this.asksPerson(recipe.number);
1066
+ }
1067
+ /** Whether a letter of the job itself waits for the person. */
1068
+ asksPerson(number) {
1069
+ return (this.store.countLetters({
1070
+ job: number,
1071
+ needsPerson: true,
1072
+ states: ['queued', 'delivered', 'read'],
1073
+ }) > 0);
1074
+ }
1075
+ /**
1076
+ * The recipe a job is a step of, while it runs. A question of a step reaches the person as a
1077
+ * letter of the recipe's job, which the conductor passed on, so a step waits with its recipe.
1078
+ */
1079
+ recipeAbove(number) {
1080
+ const job = this.jobIfAny(number);
1081
+ const parent = job?.parent === undefined ? undefined : this.jobIfAny(job.parent);
1082
+ if (!parent || isFinishedJobState(parent.state))
1083
+ return undefined;
1084
+ return this.conducts(this.store.getAgent(parent.to)) ? parent : undefined;
1085
+ }
1086
+ /**
1087
+ * The jobs that wait for the person with a job: those it is part of, and for the job of a
1088
+ * recipe its steps that run.
1089
+ */
1090
+ waitingWith(number) {
1091
+ const chain = this.chainOf(number);
1092
+ const own = chain.find((job) => job.number === number);
1093
+ if (!own || !this.conducts(this.store.getAgent(own.to)))
1094
+ return chain;
1095
+ const steps = this.store
1096
+ .jobTasks({ parent: number, states: ACTIVE_JOB_STATES })
1097
+ .flatMap((task) => jobOf(task) ?? []);
1098
+ return [...chain, ...steps];
1039
1099
  }
1040
1100
  /** A job and the jobs it was handed over from inside of, the nearest first, while they run. */
1041
1101
  chainOf(number) {
@@ -1055,7 +1115,7 @@ export class BridgeDispatcher extends EventEmitter {
1055
1115
  * of them is failed by its deadline while the wait lasts.
1056
1116
  */
1057
1117
  async startWaiting(number, now) {
1058
- for (const job of this.chainOf(number)) {
1118
+ for (const job of this.waitingWith(number)) {
1059
1119
  if (!job.personWaitSince) {
1060
1120
  await this.patchRecord(job.taskId, { personWaitSince: this.iso(now) });
1061
1121
  }
@@ -1070,7 +1130,7 @@ export class BridgeDispatcher extends EventEmitter {
1070
1130
  * that still waits for another letter goes on waiting.
1071
1131
  */
1072
1132
  async stopWaiting(number, now, answered) {
1073
- for (const job of this.chainOf(number)) {
1133
+ for (const job of this.waitingWith(number)) {
1074
1134
  if (!job.personWaitSince)
1075
1135
  continue;
1076
1136
  const waited = Math.max(0, now - Date.parse(job.personWaitSince));
@@ -1367,6 +1427,44 @@ export class BridgeDispatcher extends EventEmitter {
1367
1427
  throw new BridgeError('worktree_limit', `${isolated.length} jobs of this project are in progress in worktrees of their own (${isolated.map((job) => `#${job.number}`).join(', ')}), the most there may be: each builds and tests next to the others. Wait for one to report, or hand this job over without a worktree`, { jobs: isolated.map((job) => job.number) });
1368
1428
  }
1369
1429
  }
1430
+ /**
1431
+ * Refuses a letter id of the kind the conductor names its own letters by, from anybody else:
1432
+ * a recipe finds the job of a step again by that id, so nobody else may take one.
1433
+ */
1434
+ checkOwnId(id, from) {
1435
+ if (id === undefined || !RECIPE_LETTER_ID.test(id) || this.conducts(from))
1436
+ return;
1437
+ throw new BridgeError('invalid_letter', 'Letter ids that start with "recipe-" or "relay-" are kept for the recipes of the bridge. Give the letter another id', { letter: id });
1438
+ }
1439
+ /** The harness words of the adapters that carry jobs out by recipes. */
1440
+ conductors() {
1441
+ return [...this.adapters.values()]
1442
+ .filter((adapter) => adapter.recipeProblem !== undefined)
1443
+ .map((adapter) => adapter.harness);
1444
+ }
1445
+ /**
1446
+ * Refuses a recipe the conductor cannot start, and a job for the conductor that names none.
1447
+ * Every recipe gets a conductor of its own, so a recipe is addressed by the harness word of
1448
+ * the conductor, never by the name of one that runs.
1449
+ */
1450
+ checkRecipeAsked(resolution, recipe) {
1451
+ const harness = resolution.kind === 'agent' ? resolution.agent.harness : resolution.harness;
1452
+ const adapter = this.adapters.get(harness);
1453
+ if (!recipe) {
1454
+ if (!adapter?.recipeProblem)
1455
+ return;
1456
+ throw new BridgeError('invalid_input', `${harness} carries out recipes only: name the recipe to start`, { harness });
1457
+ }
1458
+ if (!adapter?.recipeProblem || resolution.kind === 'agent') {
1459
+ const conductors = this.conductors();
1460
+ throw new BridgeError('invalid_input', conductors.length > 0
1461
+ ? `A recipe is started by handing its job to the conductor of the bridge: address it to ${conductors.join(' or ')}`
1462
+ : NO_CONDUCTOR, { recipe: recipe.name });
1463
+ }
1464
+ const problem = adapter.recipeProblem(recipe);
1465
+ if (problem)
1466
+ throw new BridgeError('invalid_input', problem, { recipe: recipe.name });
1467
+ }
1370
1468
  /**
1371
1469
  * Where a session that is about to be started for a job works: the worktree of the job, made
1372
1470
  * now, when the job asked for one. Resolves with the job as it is once it has its worktree and
@@ -1483,8 +1581,8 @@ export class BridgeDispatcher extends EventEmitter {
1483
1581
  results.push(skippedCheck(check, !this.rights
1484
1582
  ? 'this bridge has no rules to judge a command by, and runs none without them'
1485
1583
  : rights === 'deny'
1486
- ? `the rules of ${job.from} forbid the command`
1487
- : `the rules of ${job.from} do not allow the command without asking. Allow it in the settings of the project, or run it yourself`));
1584
+ ? `the rules of ${this.ruledBy(job)} forbid the command`
1585
+ : `the rules of ${this.ruledBy(job)} do not allow the command without asking. Allow it in the settings of the project, or run it yourself`));
1488
1586
  continue;
1489
1587
  }
1490
1588
  results.push(await runCheck(check, {
@@ -1536,7 +1634,8 @@ export class BridgeDispatcher extends EventEmitter {
1536
1634
  }
1537
1635
  /**
1538
1636
  * What a job changed in its worktree so far: the files, how much, and the patch. For the two
1539
- * agents of the job, while it runs and after, as long as its worktree is there.
1637
+ * agents of the job, and for whoever started the recipe it is a step of, while it runs and
1638
+ * after, as long as its worktree is there.
1540
1639
  *
1541
1640
  * @throws BridgeError `unknown_job`, `not_a_party`, `no_worktree` for a job without a worktree
1542
1641
  * of its own or whose work was taken or dropped already
@@ -1546,7 +1645,7 @@ export class BridgeDispatcher extends EventEmitter {
1546
1645
  const { job, worktree } = await this.asCaller(caller, async () => {
1547
1646
  const agent = this.requireCaller(caller);
1548
1647
  const found = this.requireJob(request.job).job;
1549
- if (agent.name !== found.from && agent.name !== found.to) {
1648
+ if (agent.name !== found.to && !this.handedOver(agent.name, found)) {
1550
1649
  throw new BridgeError('not_a_party', `Job ${found.number} is between ${found.from} and ${found.to}`, { job: found.number });
1551
1650
  }
1552
1651
  return { job: found, worktree: this.requireWorktree(found) };
@@ -1572,8 +1671,8 @@ export class BridgeDispatcher extends EventEmitter {
1572
1671
  };
1573
1672
  }
1574
1673
  /**
1575
- * Takes the work of a finished job out of its worktree, as the agent that handed the job over.
1576
- * The changes, committed there or not, come into the checkout the caller works in as one
1674
+ * Takes the work of a finished job out of its worktree, as the agent that handed the job over,
1675
+ * or that started the recipe the job is a step of, once the recipe has reported. The changes, committed there or not, come into the checkout the caller works in as one
1577
1676
  * change that is staged and not committed: the commit is the caller's to make. With
1578
1677
  * `asBranch` they are left as a branch instead, for work that goes on as a pull request. The
1579
1678
  * worktree is removed either way. When the changes would leave files in conflict nothing is
@@ -1581,8 +1680,8 @@ export class BridgeDispatcher extends EventEmitter {
1581
1680
  * never merges into a branch nobody is working on.
1582
1681
  *
1583
1682
  * @throws BridgeError `unknown_job`, `not_a_party` (only who handed the job over takes its
1584
- * work), `invalid_input` (the job still runs, its checks do, the caller is in another
1585
- * repository, or git refused), `no_worktree`
1683
+ * work), `invalid_input` (the job still runs, its checks do, the recipe it is a step of does,
1684
+ * the caller is in another repository, or git refused), `no_worktree`
1586
1685
  */
1587
1686
  async accept(caller, input) {
1588
1687
  const request = parse(AcceptInputSchema, input, 'Cannot take the work');
@@ -1638,11 +1737,12 @@ export class BridgeDispatcher extends EventEmitter {
1638
1737
  });
1639
1738
  }
1640
1739
  /**
1641
- * Drops the work of a finished job, as the agent that handed the job over: its worktree and
1642
- * the branch of it are removed with everything in them.
1740
+ * Drops the work of a finished job, as the agent that handed the job over, or that started the
1741
+ * recipe the job is a step of: its worktree and the branch of it are removed with everything
1742
+ * in them.
1643
1743
  *
1644
- * @throws BridgeError `unknown_job`, `not_a_party`, `invalid_input` (the job still runs, or
1645
- * its checks do), `no_worktree`
1744
+ * @throws BridgeError `unknown_job`, `not_a_party`, `invalid_input` (the job still runs, its
1745
+ * checks do, or the recipe it is a step of does), `no_worktree`
1646
1746
  */
1647
1747
  async reject(caller, input) {
1648
1748
  const request = parse(RejectInputSchema, input, 'Cannot drop the work');
@@ -1686,8 +1786,8 @@ export class BridgeDispatcher extends EventEmitter {
1686
1786
  requireTaker(caller, number, what) {
1687
1787
  const agent = this.requireCaller(caller);
1688
1788
  const { job } = this.requireJob(number);
1689
- if (agent.name !== job.from) {
1690
- throw new BridgeError('not_a_party', `Only ${job.from}, who handed job ${job.number} over, can ${what} its work`, { job: job.number });
1789
+ if (!this.handedOver(agent.name, job)) {
1790
+ throw new BridgeError('not_a_party', `Only ${job.from}, who handed job ${job.number} over, or whoever handed over a job it is part of, can ${what} its work`, { job: job.number });
1691
1791
  }
1692
1792
  if (!isFinishedJobState(job.state)) {
1693
1793
  throw new BridgeError('invalid_input', `Job ${job.number} is still ${job.state}. Wait for its report, or cancel it first`, { job: job.number, state: job.state });
@@ -1695,8 +1795,66 @@ export class BridgeDispatcher extends EventEmitter {
1695
1795
  if (job.checking) {
1696
1796
  throw new BridgeError('invalid_input', `The checks of job ${job.number} still run. Its report comes with what they show`, { job: job.number });
1697
1797
  }
1798
+ const recipe = job.parent !== undefined && this.conducts(this.store.getAgent(job.from))
1799
+ ? this.jobIfAny(job.parent)
1800
+ : undefined;
1801
+ if (recipe && !isFinishedJobState(recipe.state)) {
1802
+ throw new BridgeError('invalid_input', `Job ${job.number} is a step of the recipe of job ${recipe.number}, which still runs: later steps may work in the same worktree. Wait for the report of job ${recipe.number}, or cancel it first`, { job: job.number, recipe: recipe.number });
1803
+ }
1804
+ const user = this.workingOn(job);
1805
+ if (user) {
1806
+ throw new BridgeError('invalid_input', `Job ${user.number} still works on what job ${job.number} left in its worktree. Wait for its report, or cancel it first`, { job: job.number, by: user.number });
1807
+ }
1698
1808
  return { job, worktree: this.requireWorktree(job), agent };
1699
1809
  }
1810
+ /**
1811
+ * A job in progress that works on what another job left in its worktree: one that is done in
1812
+ * that worktree, such as the review of the work or its fixes, and a recipe whose input names
1813
+ * the job as the one it works on. The worktree stays while there is one.
1814
+ */
1815
+ workingOn(job) {
1816
+ const worktree = this.liveWorktree(job);
1817
+ return this.store
1818
+ .jobTasks({ states: ACTIVE_JOB_STATES, project: job.project })
1819
+ .flatMap((task) => jobOf(task) ?? [])
1820
+ .find((other) => {
1821
+ if (other.number === job.number)
1822
+ return false;
1823
+ if (worktree && isInside(worktree.path, other.cwd))
1824
+ return true;
1825
+ const input = other.recipe?.input;
1826
+ return (typeof input === 'object' &&
1827
+ input !== null &&
1828
+ input.job === job.number);
1829
+ });
1830
+ }
1831
+ /**
1832
+ * Whether an agent handed a job over, or started the recipe the job is a step of: a job the
1833
+ * conductor hands out for an agent is that agent's to look at and take, as the recipe is its
1834
+ * own. A job another agent handed over from inside a job is that agent's alone.
1835
+ */
1836
+ handedOver(agent, job) {
1837
+ for (let at = job; at;) {
1838
+ if (at.from === agent)
1839
+ return true;
1840
+ if (at.parent === undefined || !this.conducts(this.store.getAgent(at.from)))
1841
+ return false;
1842
+ at = this.jobIfAny(at.parent);
1843
+ }
1844
+ return false;
1845
+ }
1846
+ /**
1847
+ * The agent whose rules bind a job: whoever handed it over, and for a step of a recipe
1848
+ * whoever started the recipe, since the conductor has no rules of its own.
1849
+ */
1850
+ ruledBy(job) {
1851
+ for (let at = job; at;) {
1852
+ if (at.parent === undefined || !this.conducts(this.store.getAgent(at.from)))
1853
+ return at.from;
1854
+ at = this.jobIfAny(at.parent);
1855
+ }
1856
+ return job.from;
1857
+ }
1700
1858
  /** One taking, dropping or putting away of a job's worktree at a time. */
1701
1859
  async whileTaking(number, work) {
1702
1860
  if (this.taking.has(number)) {
@@ -1776,7 +1934,8 @@ export class BridgeDispatcher extends EventEmitter {
1776
1934
  .flatMap((task) => jobOf(task) ?? [])
1777
1935
  .filter((job) => this.liveWorktree(job) !== undefined &&
1778
1936
  !job.checking &&
1779
- now - Date.parse(job.endedAt ?? job.updatedAt) >= this.limits.worktreeKeepMs);
1937
+ now - Date.parse(job.endedAt ?? job.updatedAt) >= this.limits.worktreeKeepMs &&
1938
+ this.workingOn(job) === undefined);
1780
1939
  for (const job of left) {
1781
1940
  if (this.taking.has(job.number))
1782
1941
  continue;
@@ -1988,8 +2147,9 @@ export class BridgeDispatcher extends EventEmitter {
1988
2147
  }
1989
2148
  /**
1990
2149
  * Whether the rules of an agent let it read a file without asking: its own, and those of every
1991
- * agent up the chain of the jobs it carries out. True on a bridge that was given no judge:
1992
- * what an agent names in its own project it could read itself.
2150
+ * agent up the chain of the jobs it carries out. The conductor of a recipe reads what whoever
2151
+ * started the recipe may. True on a bridge that was given no judge: what an agent names in its
2152
+ * own project it could read itself.
1993
2153
  */
1994
2154
  async mayRead(from, cwd, path) {
1995
2155
  if (!this.rights)
@@ -1997,32 +2157,36 @@ export class BridgeDispatcher extends EventEmitter {
1997
2157
  const ask = { tool: 'Read', access: 'read', paths: [path], cwd };
1998
2158
  try {
1999
2159
  const now = this.iso();
2000
- const own = await this.rights({
2001
- job: {
2002
- number: 0,
2003
- taskId: '',
2004
- title: '',
2005
- from: from.name,
2006
- to: from.name,
2007
- project: from.project,
2008
- cwd,
2009
- checks: [],
2010
- budget: this.limits.budget,
2011
- lettersUsed: 0,
2012
- depth: 1,
2013
- createdAt: now,
2014
- deadlineAt: now,
2015
- state: 'submitted',
2016
- updatedAt: now,
2017
- },
2018
- delegator: from,
2019
- ask,
2020
- });
2160
+ const own = this.conducts(from)
2161
+ ? 'allow'
2162
+ : await this.rights({
2163
+ job: {
2164
+ number: 0,
2165
+ taskId: '',
2166
+ title: '',
2167
+ from: from.name,
2168
+ to: from.name,
2169
+ project: from.project,
2170
+ cwd,
2171
+ checks: [],
2172
+ budget: this.limits.budget,
2173
+ lettersUsed: 0,
2174
+ depth: 1,
2175
+ createdAt: now,
2176
+ deadlineAt: now,
2177
+ state: 'submitted',
2178
+ updatedAt: now,
2179
+ },
2180
+ delegator: from,
2181
+ ask,
2182
+ });
2021
2183
  if (own !== 'allow')
2022
2184
  return false;
2023
2185
  const carried = await this.enqueue(async () => this.store
2024
2186
  .jobTasks({ to: from.name, states: ACTIVE_JOB_STATES })
2025
2187
  .flatMap((task) => jobOf(task) ?? []));
2188
+ if (this.conducts(from) && carried.length === 0)
2189
+ return false;
2026
2190
  for (const job of carried) {
2027
2191
  if ((await this.rightsFor(job.number, ask)) !== 'allow')
2028
2192
  return false;
@@ -2148,6 +2312,46 @@ export class BridgeDispatcher extends EventEmitter {
2148
2312
  return fitting(this.store.readJournal({ ...request, limit: request.limit ?? DEFAULT_LIST_LIMIT }), size);
2149
2313
  });
2150
2314
  }
2315
+ /**
2316
+ * The harnesses the bridge can start a session of for a job. The conductor of recipes is none
2317
+ * of them: it takes a recipe, not a job.
2318
+ */
2319
+ async startable() {
2320
+ return [...this.adapters.values()]
2321
+ .filter((adapter) => adapter.createSession !== undefined && !adapter.recipeProblem)
2322
+ .map((adapter) => adapter.harness);
2323
+ }
2324
+ /**
2325
+ * Whether an agent takes a letter by itself right now: it waits for its mail, or its harness
2326
+ * hands the letter over and wakes the session for it.
2327
+ */
2328
+ async wakes(name) {
2329
+ const agent = await this.enqueue(async () => this.store.getAgent(name));
2330
+ if (agent?.status !== 'active')
2331
+ return false;
2332
+ if (this.waiters.has(agent.name))
2333
+ return true;
2334
+ const adapter = this.adapters.get(agent.harness);
2335
+ if (!adapter?.deliver || !adapter.capabilities.push)
2336
+ return false;
2337
+ if (!adapter.wakesFor)
2338
+ return true;
2339
+ try {
2340
+ return await within(adapter.wakesFor(agent), this.limits.deliveryTimeoutMs, `Asking whether ${agent.name} wakes for a letter`);
2341
+ }
2342
+ catch (error) {
2343
+ this.onError(asError(error));
2344
+ return false;
2345
+ }
2346
+ }
2347
+ /**
2348
+ * Whether an agent is a conductor: a session of an adapter that carries jobs out by recipes.
2349
+ * It has no rules of its own, and the jobs it hands out are bound by those of whoever started
2350
+ * its recipe.
2351
+ */
2352
+ conducts(agent) {
2353
+ return agent !== undefined && this.adapters.get(agent.harness)?.recipeProblem !== undefined;
2354
+ }
2151
2355
  async status() {
2152
2356
  return this.enqueue(async () => ({
2153
2357
  agents: this.store.listAgents({ statuses: ['active', 'starting'] }).length,
@@ -2155,7 +2359,7 @@ export class BridgeDispatcher extends EventEmitter {
2155
2359
  queuedLetters: this.store.countLetters({ states: ['queued'] }),
2156
2360
  adapters: [...this.adapters.keys()],
2157
2361
  startable: [...this.adapters.values()]
2158
- .filter((adapter) => adapter.createSession !== undefined)
2362
+ .filter((adapter) => adapter.createSession !== undefined && !adapter.recipeProblem)
2159
2363
  .map((adapter) => adapter.harness),
2160
2364
  waiting: [...this.waiters.keys()].sort(),
2161
2365
  }));