@cogitator-ai/bridge 0.8.0 → 0.10.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 (72) hide show
  1. package/README.md +113 -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 +386 -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 +590 -0
  38. package/dist/recipes/conductor.js.map +1 -0
  39. package/dist/recipes/debate.d.ts +21 -0
  40. package/dist/recipes/debate.d.ts.map +1 -0
  41. package/dist/recipes/debate.js +234 -0
  42. package/dist/recipes/debate.js.map +1 -0
  43. package/dist/recipes/index.d.ts +7 -0
  44. package/dist/recipes/index.d.ts.map +1 -0
  45. package/dist/recipes/index.js +7 -0
  46. package/dist/recipes/index.js.map +1 -0
  47. package/dist/recipes/race.d.ts +18 -0
  48. package/dist/recipes/race.d.ts.map +1 -0
  49. package/dist/recipes/race.js +180 -0
  50. package/dist/recipes/race.js.map +1 -0
  51. package/dist/recipes/recipe.d.ts +128 -0
  52. package/dist/recipes/recipe.d.ts.map +1 -0
  53. package/dist/recipes/recipe.js +54 -0
  54. package/dist/recipes/recipe.js.map +1 -0
  55. package/dist/recipes/steps.d.ts +50 -0
  56. package/dist/recipes/steps.d.ts.map +1 -0
  57. package/dist/recipes/steps.js +88 -0
  58. package/dist/recipes/steps.js.map +1 -0
  59. package/dist/registry.d.ts +5 -0
  60. package/dist/registry.d.ts.map +1 -1
  61. package/dist/registry.js +5 -0
  62. package/dist/registry.js.map +1 -1
  63. package/dist/tools/guidance.d.ts.map +1 -1
  64. package/dist/tools/guidance.js +1 -0
  65. package/dist/tools/guidance.js.map +1 -1
  66. package/dist/tools/tools.d.ts.map +1 -1
  67. package/dist/tools/tools.js +266 -26
  68. package/dist/tools/tools.js.map +1 -1
  69. package/dist/types.d.ts +19 -0
  70. package/dist/types.d.ts.map +1 -1
  71. package/dist/types.js.map +1 -1
  72. package/package.json +19 -9
@@ -0,0 +1,234 @@
1
+ import { WorkflowBuilder } from '@cogitator-ai/workflows';
2
+ import { z } from 'zod';
3
+ import { oneLine, quoted } from '../letters.js';
4
+ import { defineRecipe } from './recipe.js';
5
+ import { Address, ONE_LINE, TASK_LENGTH, attempted, clip, freshFor, handBack, plural, } from './steps.js';
6
+ /** How many rounds a debate goes at most when its input names no number. */
7
+ export const DEFAULT_DEBATE_ROUNDS = 3;
8
+ /** The most turns one debate takes: its debaters times its rounds. */
9
+ const MAX_TURNS = 40;
10
+ /** How much of what a debater said the others are shown, and the report quotes. */
11
+ const SAID_LENGTH = 2_500;
12
+ const Role = z.string().trim().min(1).max(60).regex(ONE_LINE, 'A role is one line');
13
+ const DebateInput = z
14
+ .strictObject({
15
+ debaters: z
16
+ .array(z.union([Address, z.strictObject({ to: Address, role: Role.optional() })]))
17
+ .min(2)
18
+ .max(6),
19
+ rounds: z.number().int().min(1).max(10).optional(),
20
+ moderator: Address.optional(),
21
+ })
22
+ .refine((input) => input.debaters.length * (input.rounds ?? DEFAULT_DEBATE_ROUNDS) <= MAX_TURNS, {
23
+ message: `A debate takes ${MAX_TURNS} turns at most: fewer debaters, or fewer rounds`,
24
+ path: ['rounds'],
25
+ });
26
+ function seatsOf(input) {
27
+ return input.debaters.map((debater) => typeof debater === 'string'
28
+ ? { to: debater }
29
+ : { to: debater.to, ...(debater.role && { role: oneLine(debater.role) }) });
30
+ }
31
+ /** What a debater is to do, by its role: the rules a debate of the runtime's swarms goes by. */
32
+ function stand(role) {
33
+ const named = role?.toLowerCase();
34
+ if (named === 'advocate') {
35
+ return 'You argue in favor of the position or solution in question: make the strongest case for it.';
36
+ }
37
+ if (named === 'critic') {
38
+ return 'You argue against the position or solution in question: find its weaknesses, its risks and what it overlooks.';
39
+ }
40
+ return `${role ? `Your role is ${role}. ` : ''}Give your own view of the question, with your reasons.`;
41
+ }
42
+ const HOW_TO_END = 'End with one line, exactly in this form: STANCE: agree when you now hold the position the others hold and nothing of weight is left in dispute, STANCE: disagree otherwise.';
43
+ /** The agent that spoke for a seat last: a seat keeps its place when its session changes. */
44
+ function lastOf(state, seat) {
45
+ return state.turns.filter((turn) => turn.seat === seat && turn.agent !== undefined).at(-1)?.agent;
46
+ }
47
+ function nameOf(state, seats, turn) {
48
+ const known = turn.agent ?? lastOf(state, turn.seat) ?? `debater ${turn.seat + 1}`;
49
+ const role = seats[turn.seat]?.role;
50
+ return role ? `${known} (${role})` : known;
51
+ }
52
+ function transcript(state, seats, rounds) {
53
+ return state.turns
54
+ .filter((turn) => !rounds || rounds.includes(turn.round))
55
+ .map((turn) => `${nameOf(state, seats, turn)}, round ${turn.round}:\n${quoted(clip(turn.said ?? 'gave no answer', SAID_LENGTH))}`)
56
+ .join('\n');
57
+ }
58
+ function turnText(run, state, seats, seat, round, rounds) {
59
+ const head = `You are debater ${seat + 1} of ${seats.length} in a debate of agents on a question. ${stand(seats[seat]?.role)} Change no file: read what you need, and argue.`;
60
+ if (round === 1) {
61
+ return [
62
+ head,
63
+ `The question:\n${quoted(run.task)}`,
64
+ `This is round 1 of ${rounds} at most. Nobody has spoken yet: the others answer the same question now, and from the next round on everybody sees what the others said.`,
65
+ HOW_TO_END,
66
+ ].join('\n\n');
67
+ }
68
+ return [
69
+ head,
70
+ `Continue the debate on:\n${quoted(run.task)}`,
71
+ `This is round ${round} of ${rounds} at most. What was said before:\n${transcript(state, seats)}`,
72
+ 'Answer the strongest points of the others, and move where they convinced you.',
73
+ HOW_TO_END,
74
+ ].join('\n\n');
75
+ }
76
+ /**
77
+ * The seats that took part: those that answered in some round. Agreement is theirs to reach
78
+ * together, so one that argued before and is silent now has not agreed.
79
+ */
80
+ function tookPart(turns) {
81
+ return [...new Set(turns.filter((turn) => turn.said !== undefined).map((turn) => turn.seat))];
82
+ }
83
+ function stanceOf(said) {
84
+ const last = [
85
+ ...(said ?? '').matchAll(/^[ \t]*\*{0,2}STANCE:\*{0,2}[ \t]*(agree|disagree)\b/gim),
86
+ ].at(-1);
87
+ return last ? last[1].toLowerCase() === 'agree' : undefined;
88
+ }
89
+ async function round(run, state, seats, at, rounds) {
90
+ if (state.ended)
91
+ return {};
92
+ const turns = await Promise.all(seats.map(async (seat, index) => {
93
+ const job = {
94
+ title: `${run.job.title} (debate, round ${at})`,
95
+ body: turnText(run, state, seats, index, at, rounds),
96
+ };
97
+ const before = lastOf(state, index);
98
+ const known = before ? await run.agent(before) : undefined;
99
+ const step = `round-${at}.${index + 1}`;
100
+ const tried = await attempted(run, () => known
101
+ ? handBack(run, step, known, job, '')
102
+ : run.handOver(step, { ...job, to: freshFor(seat.to) }));
103
+ if ('refused' in tried)
104
+ return { round: at, seat: index, refused: tried.refused };
105
+ const outcome = tried.done;
106
+ const said = outcome.job.state === 'completed' ? outcome.report : undefined;
107
+ const agrees = stanceOf(said);
108
+ return {
109
+ round: at,
110
+ seat: index,
111
+ job: outcome.job.number,
112
+ agent: outcome.job.to,
113
+ ...(said && { said }),
114
+ ...(agrees !== undefined && { agrees }),
115
+ };
116
+ }));
117
+ const spoke = turns.filter((turn) => turn.said !== undefined);
118
+ const all = [...state.turns, ...turns];
119
+ const agreed = tookPart(all).every((seat) => turns.find((turn) => turn.seat === seat)?.agrees === true);
120
+ const ended = spoke.length < 2
121
+ ? 'silent'
122
+ : at > 1 && agreed
123
+ ? 'agreed'
124
+ : at === rounds
125
+ ? 'rounds'
126
+ : undefined;
127
+ return { turns: all, ...(ended && { ended }) };
128
+ }
129
+ async function sumUp(run, input, state, seats) {
130
+ const spoken = state.turns.some((turn) => turn.said !== undefined);
131
+ if (!input.moderator || !spoken)
132
+ return {};
133
+ const to = freshFor(input.moderator);
134
+ const tried = await attempted(run, () => run.handOver('moderator', {
135
+ to,
136
+ title: `${run.job.title} (debate, summing up)`,
137
+ body: [
138
+ `Sum up a debate of ${seats.length} agents. Change no file.`,
139
+ `The question:\n${quoted(run.task)}`,
140
+ `What was said:\n${transcript(state, seats)}`,
141
+ 'Write a balanced summary of the positions, where the debaters agree and where they still disagree, the strongest arguments of each side, and what you recommend.',
142
+ ].join('\n\n'),
143
+ }));
144
+ if ('refused' in tried)
145
+ return { summed: { refused: tried.refused } };
146
+ const { job, report } = tried.done;
147
+ return {
148
+ summed: {
149
+ job: job.number,
150
+ by: job.to,
151
+ ...(job.state === 'completed' && report && { said: report }),
152
+ },
153
+ };
154
+ }
155
+ function summary(state, seats) {
156
+ const last = Math.max(0, ...state.turns.map((turn) => turn.round));
157
+ const closing = state.turns.filter((turn) => turn.round === last && turn.said !== undefined);
158
+ const agreeing = closing.filter((turn) => turn.agrees === true).length;
159
+ const part = tookPart(state.turns).length;
160
+ const how = state.ended === 'agreed'
161
+ ? part < seats.length
162
+ ? `the ${part} that took part hold the same position now`
163
+ : 'all of them hold the same position now'
164
+ : state.ended === 'silent'
165
+ ? 'fewer than two of them answered'
166
+ : `the rounds ran out, and ${agreeing} of ${closing.length} said they agree at the end`;
167
+ const lines = [
168
+ `The debate of ${plural(seats.length, 'agent')} ended after ${plural(last, 'round')}: ${how}.`,
169
+ ];
170
+ for (const turn of state.turns) {
171
+ if (turn.refused) {
172
+ lines.push(`${nameOf(state, seats, turn)} did not get its turn of round ${turn.round}: ${oneLine(turn.refused)}`);
173
+ }
174
+ }
175
+ if (state.summed?.said) {
176
+ lines.push(`${state.summed.by} sums it up:`, quoted(clip(state.summed.said, 4 * SAID_LENGTH)));
177
+ }
178
+ else {
179
+ if (state.summed) {
180
+ lines.push(state.summed.refused
181
+ ? `Nobody summed it up: ${oneLine(state.summed.refused)}`
182
+ : `${state.summed.by} was asked to sum it up in job #${state.summed.job} and reported nothing.`);
183
+ }
184
+ if (last > 0)
185
+ lines.push('The positions at the end:', transcript(state, seats, [last]));
186
+ }
187
+ const jobs = state.turns.flatMap((turn) => (turn.job === undefined ? [] : [`#${turn.job}`]));
188
+ if (jobs.length > 0) {
189
+ lines.push(`Every turn is a job of its own, with all that was said: ${jobs.join(', ')}.`);
190
+ }
191
+ return { report: lines.join('\n'), ...(state.ended === 'silent' && { failed: true }) };
192
+ }
193
+ function debateWorkflow(input, run) {
194
+ if (run.task.length > TASK_LENGTH) {
195
+ throw new Error(`the question of a debate takes ${TASK_LENGTH} characters at most, and this one has ${run.task.length}. Every debater reads it whole in every round: put the details in a file and name it`);
196
+ }
197
+ const seats = seatsOf(input);
198
+ const rounds = input.rounds ?? DEFAULT_DEBATE_ROUNDS;
199
+ const builder = new WorkflowBuilder('bridge-debate').initialState({ turns: [] });
200
+ let last;
201
+ const step = (name, work) => {
202
+ builder.addNode(name, async ({ state }) => ({ state: await work(state) }), last === undefined ? undefined : { after: [last] });
203
+ last = name;
204
+ };
205
+ for (let at = 1; at <= rounds; at += 1) {
206
+ step(`round-${at}`, (state) => round(run, state, seats, at, rounds));
207
+ }
208
+ step('moderator', (state) => sumUp(run, input, state, seats));
209
+ step('report', async (state) => summary(state, seats));
210
+ return builder.build();
211
+ }
212
+ /**
213
+ * `debate`: a question to several agents, by the rules a debate of the runtime's swarms goes by.
214
+ * In the first round each answers the question alone. From the second on each sees what the
215
+ * others said in the rounds before and answers them, and ends its turn by saying whether it
216
+ * agrees now. The debate ends when all that took part agree in the same round, or the rounds run
217
+ * out: a debater that argued before and gives no answer now has not agreed. A `moderator` then
218
+ * sums it up: the positions, what is agreed and what is not, the strongest arguments, a
219
+ * recommendation. Without one the report carries the positions of the last round.
220
+ *
221
+ * Input: `debaters`, two to six agents or harness words, each as a word or as `{ to, role }`:
222
+ * an `advocate` argues for, a `critic` against, any other role is told to the agent as it is.
223
+ * `rounds`, 3 by default. `moderator`, nobody by default. Debaters times rounds is 40 at most.
224
+ *
225
+ * A turn the bridge refuses to hand over, and a moderator it cannot reach, are said in the
226
+ * report, which still carries what the others said.
227
+ */
228
+ export const debateRecipe = defineRecipe({
229
+ name: 'debate',
230
+ summary: 'A question to several agents, who answer each other round by round until they agree or the rounds run out',
231
+ input: DebateInput,
232
+ workflow: debateWorkflow,
233
+ });
234
+ //# sourceMappingURL=debate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debate.js","sourceRoot":"","sources":["../../src/recipes/debate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,YAAY,EAAiD,MAAM,aAAa,CAAC;AAC1F,OAAO,EACL,OAAO,EACP,QAAQ,EACR,WAAW,EACX,SAAS,EACT,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,MA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QAAQ,EAAE,cAAc;CACzB,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ export { RECIPE_DELIVERY, recipeAdapter, type RecipeAdapterOptions } from './conductor.js';
2
+ export { RECIPE_HARNESS } from '../registry.js';
3
+ export { BUILT_IN_RECIPES, DEFAULT_REVIEW_ROUNDS, DEFAULT_REVIEW_THRESHOLD, buildRecipe, reviewRecipe, } from './built-in.js';
4
+ export { DEFAULT_DEBATE_ROUNDS, debateRecipe } from './debate.js';
5
+ export { raceRecipe } from './race.js';
6
+ export { defineRecipe, type Recipe, type RecipeDefinition, type RecipeEngine, type RecipeJob, type RecipeOutcome, type RecipeRun, type RecipeState, } from './recipe.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/recipes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,KAAK,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3F,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,wBAAwB,EACxB,WAAW,EACX,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACL,YAAY,EACZ,KAAK,MAAM,EACX,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,WAAW,GACjB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,7 @@
1
+ export { RECIPE_DELIVERY, recipeAdapter } from './conductor.js';
2
+ export { RECIPE_HARNESS } from '../registry.js';
3
+ export { BUILT_IN_RECIPES, DEFAULT_REVIEW_ROUNDS, DEFAULT_REVIEW_THRESHOLD, buildRecipe, reviewRecipe, } from './built-in.js';
4
+ export { DEFAULT_DEBATE_ROUNDS, debateRecipe } from './debate.js';
5
+ export { raceRecipe } from './race.js';
6
+ export { defineRecipe, } from './recipe.js';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/recipes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,aAAa,EAA6B,MAAM,gBAAgB,CAAC;AAC3F,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,wBAAwB,EACxB,WAAW,EACX,YAAY,GACb,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EACL,YAAY,GAQb,MAAM,aAAa,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { type Recipe } from './recipe.js';
2
+ /**
3
+ * `race`: the same job to two or more agents at the same time, each in a git worktree of its
4
+ * own. The bridge runs the checks of the input on every attempt, and the report lays the
5
+ * attempts side by side: which finished, what their checks showed, how much each changed. With a
6
+ * `judge` another agent reads them and says which it would take. The recipe takes none itself:
7
+ * whoever started it takes one with `accept` and drops the others with `reject`.
8
+ *
9
+ * Input: `to`, two to six harness words, the same one twice for two sessions of one harness.
10
+ * `checks`, the commands that show a result holds. `context`, what the caller knows and the
11
+ * agents do not. `judge`, who compares the attempts, nobody by default.
12
+ *
13
+ * The bridge keeps only so many worktrees of a project in progress and starts only so many
14
+ * sessions at once: attempts beyond that wait their turn. An attempt the bridge refuses, and a
15
+ * judge it cannot reach, are said in the report, which still lays out the rest.
16
+ */
17
+ export declare const raceRecipe: Recipe;
18
+ //# sourceMappingURL=race.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"race.d.ts","sourceRoot":"","sources":["../../src/recipes/race.ts"],"names":[],"mappings":"AAMA,OAAO,EAAgB,KAAK,MAAM,EAAoC,MAAM,aAAa,CAAC;AA2N1F;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,UAAU,EAAE,MAMvB,CAAC"}
@@ -0,0 +1,180 @@
1
+ import { WorkflowBuilder } from '@cogitator-ai/workflows';
2
+ import { z } from 'zod';
3
+ import { JobContextSchema } from '../handover.js';
4
+ import { oneLine, quoted } from '../letters.js';
5
+ import { JobCheckSchema } from '../types.js';
6
+ import { defineRecipe } from './recipe.js';
7
+ import { Address, TASK_LENGTH, attempted, checkedOf, clip, freshFor, plural, } from './steps.js';
8
+ const RaceInput = z.strictObject({
9
+ to: z.array(Address).min(2).max(6),
10
+ checks: z.array(JobCheckSchema).max(50).optional(),
11
+ context: JobContextSchema.optional(),
12
+ judge: Address.optional(),
13
+ });
14
+ function checksOf(attempt) {
15
+ if (!attempt.checked)
16
+ return 'no checks';
17
+ if (attempt.checked.verified)
18
+ return 'checks passed';
19
+ return attempt.checked.failed ? 'checks not passed' : 'checks not verified';
20
+ }
21
+ function changesOf(attempt) {
22
+ const changes = attempt.changes;
23
+ if (!changes)
24
+ return '';
25
+ return `, ${plural(changes.files, 'file')} +${changes.insertions} -${changes.deletions}`;
26
+ }
27
+ function attemptLine(attempt, take) {
28
+ if (attempt.job === undefined) {
29
+ return `- ${attempt.to}: not started: ${oneLine(attempt.reason ?? 'the bridge refused the job')}`;
30
+ }
31
+ const how = attempt.state === 'completed'
32
+ ? `completed, ${checksOf(attempt)}${changesOf(attempt)}`
33
+ : `${attempt.state ?? 'not finished'}${attempt.reason ? ` (${oneLine(attempt.reason)})` : ''}`;
34
+ const picked = take === attempt.job ? ', the pick of the judge' : '';
35
+ return `- job #${attempt.job} by ${attempt.agent ?? attempt.to}: ${how}${picked}`;
36
+ }
37
+ /** The attempts that finished, those whose checks hold first. */
38
+ function finished(state) {
39
+ const rank = (attempt) => attempt.checked?.verified ? 0 : attempt.checked?.failed ? 2 : 1;
40
+ return state.attempts
41
+ .filter((attempt) => attempt.state === 'completed')
42
+ .sort((a, b) => rank(a) - rank(b));
43
+ }
44
+ async function attempt(run, input, to, at) {
45
+ const note = `This is attempt ${at} of ${input.to.length} at the same job: ${input.to.length} agents do it at the same time, each in a git worktree of its own. Do not look for the work of the others: whoever started the race compares the results and takes one.`;
46
+ const tried = await attempted(run, () => run.handOver(`attempt-${at}`, {
47
+ to,
48
+ title: `${run.job.title} (attempt ${at})`,
49
+ body: `${run.task}\n\n${note}`,
50
+ worktree: true,
51
+ ...(input.checks && { checks: input.checks }),
52
+ ...(input.context && { context: input.context }),
53
+ }));
54
+ if ('refused' in tried)
55
+ return { to, reason: tried.refused };
56
+ const { job, report } = tried.done;
57
+ const checked = checkedOf(job);
58
+ return {
59
+ to,
60
+ job: job.number,
61
+ agent: job.to,
62
+ state: job.state,
63
+ ...(job.reason && { reason: job.reason }),
64
+ ...(job.worktree && !job.worktree.end && { worktree: job.worktree.path }),
65
+ ...(job.worktree && { base: job.worktree.base }),
66
+ ...(checked && { checked }),
67
+ ...(job.changes && {
68
+ changes: {
69
+ files: job.changes.files,
70
+ insertions: job.changes.insertions,
71
+ deletions: job.changes.deletions,
72
+ },
73
+ }),
74
+ ...(report && { report }),
75
+ };
76
+ }
77
+ function judgeText(run, done) {
78
+ return [
79
+ `Compare ${done.length} attempts at the same job, and say which one you would take. Change no file: read, run what you need to check, and report.`,
80
+ `The job was:\n${quoted(clip(run.task, TASK_LENGTH))}`,
81
+ [
82
+ 'The attempts, each in a git worktree of its own:',
83
+ ...done.map((one) => `- job #${one.job} by ${one.agent}: ${checksOf(one)}${changesOf(one)}, in ${one.worktree ?? 'a worktree that is gone'}${one.base ? ` (\`git diff ${one.base.slice(0, 10)}\` there shows what it changed)` : ''}`),
84
+ ].join('\n'),
85
+ 'Say of each attempt in a few lines what it does well and what is wrong with it.\nEnd with one line, exactly in this form: TAKE: job <number>\nor TAKE: none when none of them should be taken.',
86
+ ].join('\n\n');
87
+ }
88
+ function takeOf(report, done) {
89
+ const said = [
90
+ ...(report ?? '').matchAll(/^[ \t]*\*{0,2}TAKE:\*{0,2}[ \t]*(?:job[ \t]*#?(\d{1,9})|(none))\b/gim),
91
+ ].at(-1);
92
+ if (!said)
93
+ return undefined;
94
+ if (said[2])
95
+ return 'none';
96
+ const job = Number(said[1]);
97
+ return done.some((one) => one.job === job) ? job : undefined;
98
+ }
99
+ async function judge(run, input, state) {
100
+ const done = finished(state);
101
+ if (!input.judge || done.length < 2)
102
+ return {};
103
+ const to = freshFor(input.judge);
104
+ const tried = await attempted(run, () => run.handOver('judge', {
105
+ to,
106
+ title: `Compare the attempts at ${run.job.title}`,
107
+ body: judgeText(run, done),
108
+ }));
109
+ if ('refused' in tried)
110
+ return { judged: { refused: tried.refused } };
111
+ const { job, report } = tried.done;
112
+ const take = job.state === 'completed' ? takeOf(report, done) : undefined;
113
+ return {
114
+ judged: {
115
+ job: job.number,
116
+ by: job.to,
117
+ ...(report && { report }),
118
+ ...(take !== undefined && { take }),
119
+ },
120
+ };
121
+ }
122
+ function summary(state) {
123
+ const done = finished(state);
124
+ const judged = state.judged;
125
+ const take = judged?.take;
126
+ const lines = [
127
+ `${plural(state.attempts.length, 'agent')} ${state.attempts.length === 1 ? 'was' : 'were'} asked to do the job, ${done.length} finished it${done.length === 0 ? ': there is nothing to take' : ''}.`,
128
+ ...state.attempts.map((one) => attemptLine(one, take)),
129
+ ];
130
+ if (judged?.refused) {
131
+ lines.push(`Nobody compared them: ${oneLine(judged.refused)}`);
132
+ }
133
+ else if (judged) {
134
+ lines.push(take === undefined
135
+ ? `${judged.by} compared them in job #${judged.job} and named none to take:`
136
+ : take === 'none'
137
+ ? `${judged.by} compared them in job #${judged.job} and would take none:`
138
+ : `${judged.by} compared them in job #${judged.job} and would take job #${take}:`, quoted(clip(judged.report ?? 'It reported nothing.')));
139
+ }
140
+ if (done.length > 0) {
141
+ lines.push('Each attempt is in the worktree of its job: look at one with diff, take one with accept, and drop the others with reject.');
142
+ }
143
+ return { report: lines.join('\n'), ...(done.length === 0 && { failed: true }) };
144
+ }
145
+ function raceWorkflow(input, run) {
146
+ return new WorkflowBuilder('bridge-race')
147
+ .initialState({ attempts: [] })
148
+ .addNode('attempts', async () => ({
149
+ state: {
150
+ attempts: await Promise.all(input.to.map((to, at) => attempt(run, input, to, at + 1))),
151
+ },
152
+ }))
153
+ .addNode('judge', async ({ state }) => ({ state: await judge(run, input, state) }), {
154
+ after: ['attempts'],
155
+ })
156
+ .addNode('report', async ({ state }) => ({ state: summary(state) }), { after: ['judge'] })
157
+ .build();
158
+ }
159
+ /**
160
+ * `race`: the same job to two or more agents at the same time, each in a git worktree of its
161
+ * own. The bridge runs the checks of the input on every attempt, and the report lays the
162
+ * attempts side by side: which finished, what their checks showed, how much each changed. With a
163
+ * `judge` another agent reads them and says which it would take. The recipe takes none itself:
164
+ * whoever started it takes one with `accept` and drops the others with `reject`.
165
+ *
166
+ * Input: `to`, two to six harness words, the same one twice for two sessions of one harness.
167
+ * `checks`, the commands that show a result holds. `context`, what the caller knows and the
168
+ * agents do not. `judge`, who compares the attempts, nobody by default.
169
+ *
170
+ * The bridge keeps only so many worktrees of a project in progress and starts only so many
171
+ * sessions at once: attempts beyond that wait their turn. An attempt the bridge refuses, and a
172
+ * judge it cannot reach, are said in the report, which still lays out the rest.
173
+ */
174
+ export const raceRecipe = defineRecipe({
175
+ name: 'race',
176
+ summary: 'The same job to several agents at once, each in a worktree of its own: the checks and, when asked, a judge show which attempt to take',
177
+ input: RaceInput,
178
+ workflow: raceWorkflow,
179
+ });
180
+ //# sourceMappingURL=race.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"race.js","sourceRoot":"","sources":["../../src/recipes/race.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAE,MAAM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AE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC,EAAE;QAClF,KAAK,EAAE,CAAC,UAAU,CAAC;KACpB,CAAC;SACD,OAAO,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC;SACzF,KAAK,EAAE,CAAC;AACb,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,UAAU,GAAW,YAAY,CAAC;IAC7C,IAAI,EAAE,MAAM;IACZ,OAAO,EACL,uIAAuI;IACzI,KAAK,EAAE,SAAS;IAChB,QAAQ,EAAE,YAAY;CACvB,CAAC,CAAC"}
@@ -0,0 +1,128 @@
1
+ import type { Workflow, WorkflowState } from '@cogitator-ai/types';
2
+ import type { z } from 'zod';
3
+ import type { Finding } from '../findings.js';
4
+ import type { CreateJobInput } from '../inputs.js';
5
+ import type { AgentRecord, BridgeJob } from '../types.js';
6
+ /** What a run of a recipe ends with, in its state: the words for whoever started it. */
7
+ export interface RecipeState extends WorkflowState {
8
+ /** The report of the recipe, once its last step wrote it */
9
+ report?: string;
10
+ /** Set when the recipe could not do what it was started for */
11
+ failed?: boolean;
12
+ /** What the last review of the run found, handed on with the report */
13
+ findings?: Finding[];
14
+ }
15
+ /** A job a step of a recipe hands over. The bridge adds whose job it is part of. */
16
+ export type RecipeJob = Omit<CreateJobInput, 'parent' | 'letterId' | 'recipe'>;
17
+ /** How a job a recipe handed over ended. */
18
+ export interface RecipeOutcome {
19
+ /** The job as it is now that it is over: its state, its checks, its findings */
20
+ job: BridgeJob;
21
+ /** What its report said, undefined when it ended without one */
22
+ report?: string;
23
+ }
24
+ /**
25
+ * What the steps of a recipe do through: the bridge, as the conductor of this run. Everything
26
+ * here may be called again after the dispatcher was restarted in the middle of a step, and then
27
+ * goes on where it was instead of doing the same thing twice.
28
+ */
29
+ export interface RecipeRun {
30
+ /** The job of the recipe itself: who started it, where, with what */
31
+ readonly job: BridgeJob;
32
+ /** The text the recipe was started with, as its caller wrote it */
33
+ readonly task: string;
34
+ /** The name of the conductor that carries this run out */
35
+ readonly conductor: string;
36
+ /** Aborts when the job of the recipe is over before the recipe is, or the host closes */
37
+ readonly signal: AbortSignal;
38
+ /**
39
+ * Hands a job over as part of the recipe and resolves when that job is over, however it
40
+ * ended, with its checks run. `step` names the hand-over within the run (`work`, `review-2`):
41
+ * the same step asked for again finds the job it handed over the first time, so it must hand
42
+ * over the same text.
43
+ */
44
+ handOver(step: string, job: RecipeJob): Promise<RecipeOutcome>;
45
+ /** The job a step of this run handed over before, undefined when it handed none over yet */
46
+ handedOver(step: string): Promise<BridgeJob | undefined>;
47
+ /** A job by its number */
48
+ lookAt(job: number): Promise<BridgeJob>;
49
+ /** An agent by its name, undefined when the bridge knows none */
50
+ agent(name: string): Promise<AgentRecord | undefined>;
51
+ /** The text a job was handed over with, without what the bridge put under it */
52
+ taskOf(job: BridgeJob): Promise<string>;
53
+ /** The harnesses the bridge can start a session of, the conductor's own aside */
54
+ startable(): Promise<string[]>;
55
+ /**
56
+ * Whether an agent takes a letter by itself right now. A session that would only find it when
57
+ * a person opens it is no one to wait for in a recipe: start a fresh one instead
58
+ */
59
+ wakes(agent: string): Promise<boolean>;
60
+ }
61
+ /** Runs the steps of a recipe, and goes on from the last finished one after a restart. */
62
+ export interface RecipeEngine {
63
+ run<TState extends RecipeState>(workflow: Workflow<TState>): Promise<TState>;
64
+ }
65
+ /**
66
+ * A recipe as the conductor of the bridge holds it: a name to start it by, a check of what it is
67
+ * started with, and its run. Made with `defineRecipe`.
68
+ */
69
+ export interface Recipe {
70
+ readonly name: string;
71
+ /** What it does, in a line, for whoever chooses among recipes */
72
+ readonly summary: string;
73
+ /** What is wrong with what a run would be started with, undefined when it can start */
74
+ problem(input: unknown): string | undefined;
75
+ /** Carries one run out, and resolves with the state its last step left */
76
+ carryOut(input: unknown, run: RecipeRun, engine: RecipeEngine): Promise<RecipeState>;
77
+ }
78
+ /**
79
+ * What a recipe is written as: steps the conductor of the bridge carries a job out by, with no
80
+ * model deciding what comes next. The steps are the nodes of a workflow of
81
+ * `@cogitator-ai/workflows`, which runs with a checkpoint after every node, so a run goes on from
82
+ * its last finished step when the dispatcher was restarted.
83
+ *
84
+ * A step runs again when the dispatcher stopped in the middle of it. Steps that hand jobs over
85
+ * with `run.handOver` and keep what they learned in the state are safe to run again. Lay the
86
+ * rounds of a recipe out as nodes of their own, one after another (`review-1`, `fix-1`,
87
+ * `review-2`), each of which looks at the state and does nothing when it is not needed, rather
88
+ * than as a loop over one node.
89
+ */
90
+ export interface RecipeDefinition<TInput, TState extends RecipeState> {
91
+ /** What the recipe is started by: lower-case letters, digits and `-` */
92
+ name: string;
93
+ summary: string;
94
+ /** Reads what the recipe was started with, and refuses what it cannot work with */
95
+ input: z.ZodType<TInput>;
96
+ /** The steps of one run, laid out for what it was started with */
97
+ workflow(input: TInput, run: RecipeRun): Workflow<TState> | Promise<Workflow<TState>>;
98
+ }
99
+ /**
100
+ * Makes a recipe of its definition.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * const twice = defineRecipe({
105
+ * name: 'twice',
106
+ * summary: 'The same job to two agents, both answers side by side',
107
+ * input: z.object({ to: z.array(z.string()).length(2) }),
108
+ * workflow: (input, run) =>
109
+ * new WorkflowBuilder<RecipeState & { answers: string[] }>('twice')
110
+ * .initialState({ answers: [] })
111
+ * .addNode('first', async ({ state }) => {
112
+ * const { report } = await run.handOver('first', { to: input.to[0], body: run.task });
113
+ * return { state: { answers: [...state.answers, report ?? ''] } };
114
+ * })
115
+ * .addNode(
116
+ * 'second',
117
+ * async ({ state }) => {
118
+ * const { report } = await run.handOver('second', { to: input.to[1], body: run.task });
119
+ * return { state: { report: [...state.answers, report ?? ''].join('\n\n') } };
120
+ * },
121
+ * { after: ['first'] }
122
+ * )
123
+ * .build(),
124
+ * });
125
+ * ```
126
+ */
127
+ export declare function defineRecipe<TInput, TState extends RecipeState = RecipeState>(definition: RecipeDefinition<TInput, TState>): Recipe;
128
+ //# sourceMappingURL=recipe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recipe.d.ts","sourceRoot":"","sources":["../../src/recipes/recipe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE1D,wFAAwF;AACxF,MAAM,WAAW,WAAY,SAAQ,aAAa;IAChD,4DAA4D;IAC5D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,uEAAuE;IACvE,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAC;CACtB;AAED,oFAAoF;AACpF,MAAM,MAAM,SAAS,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,UAAU,GAAG,QAAQ,CAAC,CAAC;AAE/E,4CAA4C;AAC5C,MAAM,WAAW,aAAa;IAC5B,gFAAgF;IAChF,GAAG,EAAE,SAAS,CAAC;IACf,gEAAgE;IAChE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,qEAAqE;IACrE,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC;IACxB,mEAAmE;IACnE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,0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