@bridgebrew/sessions 0.0.0-stage → 0.0.8

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -2
  3. package/answers.ts +167 -0
  4. package/browser/branch-actions.tsx +166 -0
  5. package/browser/changes.tsx +415 -0
  6. package/browser/children.tsx +650 -0
  7. package/browser/conversation.tsx +2381 -0
  8. package/browser/decision-questions.tsx +191 -0
  9. package/browser/elapsed.tsx +44 -0
  10. package/browser/gallery.tsx +218 -0
  11. package/browser/index.tsx +3434 -0
  12. package/browser/media-origins.tsx +38 -0
  13. package/browser/mobile.tsx +663 -0
  14. package/browser/open-link.tsx +30 -0
  15. package/browser/pull-request.tsx +116 -0
  16. package/browser/questions.tsx +156 -0
  17. package/browser/session-scheduled.tsx +203 -0
  18. package/browser/subagent-view.tsx +136 -0
  19. package/browser/subagents.tsx +339 -0
  20. package/browser/tabs.tsx +228 -0
  21. package/browser/tsconfig.json +15 -0
  22. package/browser/views/view.tsx +1064 -0
  23. package/browser/views.tsx +166 -0
  24. package/contract.ts +287 -0
  25. package/delegations.ts +1975 -0
  26. package/diff.ts +88 -0
  27. package/docs/en/images.mdx +51 -0
  28. package/docs/en/index.mdx +22 -0
  29. package/docs/en/meta.json +4 -0
  30. package/docs/en/organize-sessions.mdx +53 -0
  31. package/docs/en/start-a-session.mdx +63 -0
  32. package/docs/meta.json +4 -0
  33. package/git.ts +223 -0
  34. package/listing.ts +382 -0
  35. package/package.json +1023 -4
  36. package/peers.ts +677 -0
  37. package/pull-request-watch.ts +282 -0
  38. package/pull-requests.ts +606 -0
  39. package/server.ts +5920 -0
  40. package/text.ts +19 -0
  41. package/tsconfig.json +3 -0
  42. package/viewer-activity.ts +57 -0
  43. package/views/examples.ts +153 -0
  44. package/views/library.ts +1116 -0
package/peers.ts ADDED
@@ -0,0 +1,677 @@
1
+ // Sessions coordinating with each other without GitButler: the active sessions (not settled, not archived) take part.
2
+ // A message to a settled one (notify, ask) makes it active again and is delivered, a snoozed one wakes (research-082,
3
+ // bridge#212 S2); an archived one is refused, and a settled one neither asks nor claims. A session's agent knows its
4
+ // id (`<bridge_session>`) and uses the `bridge` MCP server's tools:
5
+ // - `notify_session` `{ from, to, text }`: "I am doing this", no answer. It waits in the target's `inbox` and reaches its
6
+ // agent at the start of its next turn: no turn is started for it (no inference spent).
7
+ // - `ask_session` `{ from, to, text }` → `{ request, delivery, expiresAt }`: a question the target's agent answers with
8
+ // `answer_session` `{ from, request, verdict: ok | wait | no, text? }`. A target with a turn running gets it once that
9
+ // turn ends, in a turn Bridge starts for it (`auto`, at most `AUTO_MAX` in a row without a user message); one without
10
+ // a turn running gets it at its next user prompt only, so the asker is told not to wait. `wait_answer` `{ from,
11
+ // request }` waits for the answer (`WAIT_MS`, within the host's request deadline) and may be called again; an answer
12
+ // the asker has not read reaches it at its next turn.
13
+ // - Its deadline, `expiresAt`: the asker's node's `questionMinutes` after it was asked, or at once when the asker's turn
14
+ // ends while the target has no turn running (nobody would answer). Expired unanswered, it is the user's call
15
+ // (`sessions/question-expired`, `waiting` in the listing): Force continue (`answer` ok as the user), Stop (no), or
16
+ // Wait again (`POST /sessions/peer/extend` `{ request }`: a new deadline). The user may also answer before it, in
17
+ // either session's view. A user's answer reaches the target's agent too, at its next turn.
18
+ // - Node events, for the notification center to come (nothing listens yet): `sessions/question-asked`,
19
+ // `sessions/question-expired`, `sessions/question-answered`, each `{ node, id, from, request }` (`node` and `id`: the
20
+ // target's).
21
+ // - `claim_files` `{ id, files, note? }` and `release_files` `{ id, files? }`: files the session is about to change;
22
+ // every other active session's agent reads the claims in its repository before each turn. Settling or archiving a
23
+ // session, or committing a file, releases its claims.
24
+ // Each step is a history line: `peer/sent {request?, kind, to, title, text}` (asker), `peer/received {request?, kind,
25
+ // from, title, text}` (target, when its agent reads it), `peer/answer {request, question, verdict, text?, by}` (both).
26
+ import { randomUUID } from 'node:crypto';
27
+ import { z } from 'zod';
28
+ import { cutText } from './text.ts';
29
+
30
+ export interface Claim {
31
+ path: string;
32
+ at: string;
33
+ note?: string | undefined;
34
+ }
35
+ export interface Message {
36
+ request?: string | undefined;
37
+ from: string;
38
+ /** The sender's node. */
39
+ node?: string | undefined;
40
+ title: string;
41
+ kind: 'notify' | 'ask';
42
+ text: string;
43
+ at: string;
44
+ expiresAt?: string | undefined;
45
+ }
46
+ export interface Ask {
47
+ request: string;
48
+ to: string;
49
+ title: string;
50
+ text: string;
51
+ at: string;
52
+ expiresAt?: string | undefined;
53
+ answer?:
54
+ | { verdict: 'ok' | 'wait' | 'no'; text?: string | undefined; by: 'agent' | 'user'; at: string }
55
+ | undefined;
56
+ read?: true | undefined;
57
+ }
58
+ interface Value {
59
+ title: string;
60
+ settledAt?: string | undefined;
61
+ files?: string[] | undefined;
62
+ claims?: Claim[] | undefined;
63
+ inbox?: Message[] | undefined;
64
+ asks?: Ask[] | undefined;
65
+ }
66
+ interface Found<V> {
67
+ id: string;
68
+ node: string;
69
+ value: V;
70
+ archived?: boolean | undefined;
71
+ }
72
+
73
+ /** How long `wait_answer` waits: within the host's request deadline (30 s). */
74
+ const WAIT_MS = 25_000;
75
+ /** Turns Bridge starts in a row for a session (questions to answer) before it waits for its user. */
76
+ const AUTO_MAX = 3;
77
+ const INBOX_MAX = 50;
78
+ const ASKS_MAX = 100;
79
+ /** What Bridge's own turn says after the questions it delivers. */
80
+ const AUTO_TEXT =
81
+ 'Answer each question above with the answer_session tool (ok, wait or no, and why), then stop: do not go on with your own task in this turn.';
82
+
83
+ /** A question still open, as the listing shows it on the session asking it (`asker`) and on the one asked (`target`). */
84
+ export interface Question {
85
+ request: string;
86
+ role: 'asker' | 'target';
87
+ other: string;
88
+ title: string;
89
+ text: string;
90
+ at: string;
91
+ expiresAt?: string | undefined;
92
+ expired: boolean;
93
+ delivered: boolean;
94
+ }
95
+ /** What a user's answer is called: Force continue (ok), Stop (no). */
96
+ const userVerdicts = { ok: 'Force continue', wait: 'Wait', no: 'Stop' } as const;
97
+ const extendBody = z.strictObject({ request: z.string().min(1) });
98
+ const notifyBody = z.strictObject({
99
+ from: z.string().min(1),
100
+ to: z.string().min(1),
101
+ text: z.string().trim().min(1).max(4000),
102
+ });
103
+ const waitBody = z.strictObject({ from: z.string().min(1), request: z.string().min(1) });
104
+ const answerBody = z.strictObject({
105
+ from: z.string().min(1).optional(),
106
+ request: z.string().min(1),
107
+ verdict: z.enum(['ok', 'wait', 'no']),
108
+ text: z.string().max(4000).optional(),
109
+ });
110
+ const claimBody = z.strictObject({
111
+ id: z.string().min(1),
112
+ files: z.array(z.string().min(1)).min(1).max(200),
113
+ note: z.string().max(500).optional(),
114
+ });
115
+ const releaseBody = z.strictObject({
116
+ id: z.string().min(1),
117
+ files: z.array(z.string().min(1)).optional(),
118
+ });
119
+
120
+ /** Whether `actor` may act as session `id` (`undefined`: as the user): an agent only as its own session (`agent:<id>`,
121
+ * as its MCP token makes its calls), so one with no token (`agent`) as none; the user, or a plugin, as any. */
122
+ export const actsAs = (actor: string | undefined, id: string | undefined) =>
123
+ !actor?.startsWith('agent') || (id !== undefined && actor === `agent:${id}`);
124
+
125
+ /** A session takes part: neither settled nor archived. */
126
+ export const active = (
127
+ found: { value: { settledAt?: string | undefined }; archived?: boolean | undefined } | undefined,
128
+ ) => !!found && !found.archived && !found.value.settledAt;
129
+
130
+ export function createPeers<V extends Value>({
131
+ route,
132
+ get,
133
+ query,
134
+ change,
135
+ append,
136
+ running,
137
+ startTurn,
138
+ unsettle,
139
+ endSnooze,
140
+ refused,
141
+ parse,
142
+ scopeOf,
143
+ log,
144
+ minutesOf,
145
+ emit,
146
+ }: {
147
+ route: (
148
+ method: string,
149
+ path: string,
150
+ handle: (request: { body?: Uint8Array | undefined; actor?: string | undefined }) => unknown,
151
+ ) => void;
152
+ get: (id: string) => Promise<Found<V> | undefined>;
153
+ /** Every session, archived ones too. */
154
+ query: () => Promise<Found<V>[]>;
155
+ change: (id: string, fn: (value: V) => V) => Promise<V>;
156
+ /** Appends a history line once the session's queued lines are counted. */
157
+ append: (id: string, type: string, data: object) => Promise<void>;
158
+ running: Set<string>;
159
+ startTurn: (found: Found<V>, text: string, auto: boolean) => Promise<unknown>;
160
+ /** `value` active again: without its settled state. */
161
+ unsettle: (value: V) => V;
162
+ /** Ends session `id`'s snooze, marked Woke. */
163
+ endSnooze: (id: string) => Promise<void>;
164
+ refused: (code: string, message: string, status?: number) => Error;
165
+ parse: <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string) => T;
166
+ /** The repository of session `found` and how a path given there reads in it (`undefined`: outside it). */
167
+ scopeOf: (
168
+ found: Found<V>,
169
+ ) => Promise<{ top: string; path: (path: string) => string | undefined } | undefined>;
170
+ log: (what: string) => (error: unknown) => void;
171
+ /** A question's time to answer, in minutes, on the asker's node. */
172
+ minutesOf: (node: string) => number;
173
+ /** A node event (`ctx.nodes.emit`). */
174
+ emit: (event: string, payload: { node: string; [key: string]: unknown }) => void;
175
+ }) {
176
+ /** Each open question's deadline timer, by request. */
177
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
178
+ const deadline = (node: string) =>
179
+ new Date(Date.now() + Math.max(1, minutesOf(node)) * 60_000).toISOString();
180
+ /** The asking session and its question `request`. */
181
+ const findAsk = async (request: string) => {
182
+ const asker = (await query()).find((each) =>
183
+ each.value.asks?.some((ask) => ask.request === request),
184
+ );
185
+ return asker && { asker, ask: asker.value.asks!.find((each) => each.request === request)! };
186
+ };
187
+ const expired = (ask: Ask) =>
188
+ !ask.answer && !!ask.expiresAt && ask.expiresAt <= new Date().toISOString();
189
+ /** Fires at `request`'s deadline: still open and due, it is the user's call (a node event; the waiting asker is woken). */
190
+ const arm = (request: string, expiresAt: string | undefined) => {
191
+ clearTimeout(timers.get(request));
192
+ timers.delete(request);
193
+ if (!expiresAt) return;
194
+ timers.set(
195
+ request,
196
+ setTimeout(
197
+ () =>
198
+ void (async () => {
199
+ timers.delete(request);
200
+ const found = await findAsk(request);
201
+ if (!found || found.ask.answer) return;
202
+ if (!expired(found.ask)) return arm(request, found.ask.expiresAt); // extended meanwhile
203
+ const target = await get(found.ask.to);
204
+ emit('sessions/question-expired', {
205
+ node: target?.node ?? found.asker.node,
206
+ id: found.ask.to,
207
+ from: found.asker.id,
208
+ request,
209
+ });
210
+ for (const wake of [...(waiting.get(request) ?? [])]) wake();
211
+ })().catch(log(`question ${request}: deadline not handled`)),
212
+ Math.min(2_147_483_647, Math.max(0, Date.parse(expiresAt) - Date.now())),
213
+ ),
214
+ );
215
+ };
216
+ /** Sets `request`'s deadline on the asker and on the target's waiting message, and arms it. */
217
+ const setDeadline = async (asker: string, to: string, request: string, expiresAt: string) => {
218
+ await change(asker, (now) => ({
219
+ ...now,
220
+ asks: now.asks?.map((each) => (each.request === request ? { ...each, expiresAt } : each)),
221
+ }));
222
+ await change(to, (now) => ({
223
+ ...now,
224
+ inbox: now.inbox?.map((each) => (each.request === request ? { ...each, expiresAt } : each)),
225
+ })).catch(() => {});
226
+ arm(request, expiresAt);
227
+ };
228
+ /** The `wait_answer` calls waiting, by request. */
229
+ const waiting = new Map<string, Set<() => void>>();
230
+ /** Set as this plugin disposes: a `wait_answer` no longer waits, so no timer outlives the stop. */
231
+ let disposed = false;
232
+ /** Bridge's turns in a row per session, reset by a user's turn. */
233
+ const autos = new Map<string, number>();
234
+ /** Sessions owed a turn for questions once their running turn ends. */
235
+ const owed = new Set<string>();
236
+
237
+ const session = async (id: string, role: string) => {
238
+ const found = await get(id);
239
+ if (!found || found.archived) throw refused('not_found', `no ${role} session ${id}`, 404);
240
+ return found;
241
+ };
242
+ /** The asker, active, and its target, distinct, neither archived. */
243
+ const pair = async (from: string, to: string) => {
244
+ if (from === to) throw refused('same_session', 'a session does not message itself');
245
+ const asker = await session(from, 'asking');
246
+ const target = await session(to, 'target');
247
+ if (!active(asker))
248
+ throw refused(
249
+ 'session_inactive',
250
+ `session ${from} is settled: only active sessions coordinate`,
251
+ 409,
252
+ );
253
+ return { asker, target };
254
+ };
255
+ /** A message reached session `id`: settled, it is active again; snoozed, it wakes. */
256
+ const reached = async (id: string) => {
257
+ if ((await get(id))?.value.settledAt)
258
+ await change(id, (now) => (now.settledAt ? unsettle(now) : now));
259
+ await endSnooze(id);
260
+ };
261
+ /** Refuses `actor` acting as session `id` unless it may (`actsAs`). */
262
+ const own = (actor: string | undefined, id: string | undefined) => {
263
+ if (!actsAs(actor, id))
264
+ throw refused(
265
+ 'not_your_session',
266
+ `an agent acts only as its own session, not as ${id === undefined ? 'the user' : `session ${id}`}`,
267
+ 403,
268
+ );
269
+ };
270
+ const deliver = (target: string, message: Message) =>
271
+ change(target, (now) => ({ ...now, inbox: [...(now.inbox ?? []), message].slice(-INBOX_MAX) }));
272
+
273
+ route('POST', '/sessions/peer/notify', async ({ actor, body }) => {
274
+ const { from, to, text } = parse(
275
+ notifyBody,
276
+ body,
277
+ 'POST /sessions/peer/notify takes { from, to, text }',
278
+ );
279
+ own(actor, from);
280
+ const { asker, target } = await pair(from, to);
281
+ await deliver(to, {
282
+ from,
283
+ node: asker.node,
284
+ title: asker.value.title,
285
+ kind: 'notify',
286
+ text,
287
+ at: new Date().toISOString(),
288
+ });
289
+ await reached(to);
290
+ await append(from, 'peer/sent', { kind: 'notify', to, title: target.value.title, text });
291
+ return { delivered: 'at its next turn', to, title: target.value.title };
292
+ });
293
+
294
+ route('POST', '/sessions/peer/ask', async ({ actor, body }) => {
295
+ const { from, to, text } = parse(
296
+ notifyBody,
297
+ body,
298
+ 'POST /sessions/peer/ask takes { from, to, text }',
299
+ );
300
+ own(actor, from);
301
+ const { asker, target } = await pair(from, to);
302
+ const request = randomUUID();
303
+ const at = new Date().toISOString();
304
+ const expiresAt = deadline(asker.node);
305
+ await change(from, (now) => ({
306
+ ...now,
307
+ asks: [
308
+ ...(now.asks ?? []),
309
+ { request, to, title: target.value.title, text, at, expiresAt },
310
+ ].slice(-ASKS_MAX),
311
+ }));
312
+ await deliver(to, {
313
+ request,
314
+ from,
315
+ node: asker.node,
316
+ title: asker.value.title,
317
+ kind: 'ask',
318
+ text,
319
+ at,
320
+ expiresAt,
321
+ });
322
+ await reached(to);
323
+ await append(from, 'peer/sent', { request, kind: 'ask', to, title: target.value.title, text });
324
+ arm(request, expiresAt);
325
+ emit('sessions/question-asked', { node: target.node, id: to, from, request });
326
+ if (running.has(to)) {
327
+ owed.add(to);
328
+ return {
329
+ request,
330
+ delivery: 'after its running turn',
331
+ expiresAt,
332
+ hint: 'Call wait_answer with this request for its answer; it may take a few minutes. Past expiresAt, the user decides.',
333
+ };
334
+ }
335
+ return {
336
+ request,
337
+ delivery: 'at its next user prompt',
338
+ expiresAt,
339
+ hint: 'It has no turn running and is not interrupted for this: do not wait for its answer. Decide without it (carefully, keeping its work), or stop and let the user decide.',
340
+ };
341
+ });
342
+
343
+ route('POST', '/sessions/peer/wait', async ({ actor, body }) => {
344
+ const { from, request } = parse(
345
+ waitBody,
346
+ body,
347
+ 'POST /sessions/peer/wait takes { from, request }',
348
+ );
349
+ own(actor, from);
350
+ const answerOf = async () =>
351
+ (await session(from, 'asking')).value.asks?.find((each) => each.request === request);
352
+ let ask = await answerOf();
353
+ if (!ask) throw refused('not_found', `session ${from} asked no request ${request}`, 404);
354
+ if (!ask.answer && !expired(ask) && !disposed) {
355
+ await new Promise<void>((done) => {
356
+ const timer = setTimeout(wake, WAIT_MS);
357
+ function wake() {
358
+ clearTimeout(timer);
359
+ waiting.get(request)?.delete(wake);
360
+ done();
361
+ }
362
+ if (!waiting.has(request)) waiting.set(request, new Set());
363
+ waiting.get(request)!.add(wake);
364
+ });
365
+ ask = await answerOf();
366
+ }
367
+ if (ask && !ask.answer && expired(ask))
368
+ return {
369
+ request,
370
+ expired: true,
371
+ hint: 'No answer in time: the user decides now (force continue, wait again, or stop). Stop here and wait for them.',
372
+ };
373
+ if (!ask?.answer)
374
+ return {
375
+ request,
376
+ pending: true,
377
+ hint: 'No answer yet: call wait_answer again, or go on without it.',
378
+ };
379
+ await change(from, (now) => ({
380
+ ...now,
381
+ asks: now.asks?.map((each) =>
382
+ each.request === request ? { ...each, read: true as const } : each,
383
+ ),
384
+ }));
385
+ return {
386
+ request,
387
+ ...ask.answer,
388
+ ...(ask.answer.by === 'user' && {
389
+ hint:
390
+ ask.answer.verdict === 'no'
391
+ ? 'The user stops this: do not make the change.'
392
+ : 'The user lets you go ahead.',
393
+ }),
394
+ };
395
+ });
396
+
397
+ route('POST', '/sessions/peer/answer', async ({ actor, body }) => {
398
+ const { from, request, verdict, text } = parse(
399
+ answerBody,
400
+ body,
401
+ 'POST /sessions/peer/answer takes { from?, request, verdict: ok | wait | no, text? }',
402
+ );
403
+ // Without `from`, the user answers: never an agent.
404
+ own(actor, from);
405
+ const found = await findAsk(request);
406
+ if (!found) throw refused('not_found', `no request ${request}`, 404);
407
+ const { asker, ask } = found;
408
+ if (from !== undefined && from !== ask.to)
409
+ throw refused(
410
+ 'not_asked',
411
+ `request ${request} was asked to session ${ask.to}, not ${from}`,
412
+ 403,
413
+ );
414
+ if (ask.answer)
415
+ throw refused('already_answered', `request ${request} is answered already`, 409);
416
+ const answer = {
417
+ verdict,
418
+ ...(text && { text }),
419
+ by: from === undefined ? ('user' as const) : ('agent' as const),
420
+ at: new Date().toISOString(),
421
+ };
422
+ await change(asker.id, (now) => ({
423
+ ...now,
424
+ asks: now.asks?.map((each) => (each.request === request ? { ...each, answer } : each)),
425
+ }));
426
+ // The question leaves the target's inbox; answered by the user, its agent hears it at its next turn.
427
+ const told =
428
+ from === undefined
429
+ ? [
430
+ {
431
+ from: asker.id,
432
+ node: asker.node,
433
+ title: asker.value.title,
434
+ kind: 'notify' as const,
435
+ text: `The user answered "${userVerdicts[verdict]}" in your place to this question: ${ask.text}${text ? ` (${text})` : ''}`,
436
+ at: answer.at,
437
+ },
438
+ ]
439
+ : [];
440
+ await change(ask.to, (now) => ({
441
+ ...now,
442
+ inbox: [...(now.inbox ?? []).filter((each) => each.request !== request), ...told],
443
+ })).catch(() => {});
444
+ for (const id of [asker.id, ask.to])
445
+ await append(id, 'peer/answer', { request, question: ask.text, ...answer });
446
+ arm(request, undefined);
447
+ const target = await get(ask.to);
448
+ emit('sessions/question-answered', {
449
+ node: target?.node ?? asker.node,
450
+ id: ask.to,
451
+ from: asker.id,
452
+ request,
453
+ });
454
+ for (const wake of [...(waiting.get(request) ?? [])]) wake();
455
+ waiting.delete(request);
456
+ return { request, ...answer };
457
+ });
458
+
459
+ route('POST', '/sessions/peer/extend', async ({ body }) => {
460
+ const { request } = parse(extendBody, body, 'POST /sessions/peer/extend takes { request }');
461
+ const found = await findAsk(request);
462
+ if (!found) throw refused('not_found', `no request ${request}`, 404);
463
+ if (found.ask.answer)
464
+ throw refused('already_answered', `request ${request} is answered already`, 409);
465
+ const expiresAt = deadline(found.asker.node);
466
+ await setDeadline(found.asker.id, found.ask.to, request, expiresAt);
467
+ return { request, expiresAt };
468
+ });
469
+
470
+ route('POST', '/sessions/claims', async ({ actor, body }) => {
471
+ const { id, files, note } = parse(
472
+ claimBody,
473
+ body,
474
+ 'POST /sessions/claims takes { id, files, note? }',
475
+ );
476
+ own(actor, id);
477
+ const found = await session(id, 'claiming');
478
+ if (!active(found)) throw refused('session_inactive', `session ${id} is settled`, 409);
479
+ const scope = await scopeOf(found);
480
+ const paths = [
481
+ ...new Set(
482
+ files
483
+ .map((file) => (scope ? scope.path(file) : file))
484
+ .filter((path): path is string => !!path),
485
+ ),
486
+ ];
487
+ if (!paths.length)
488
+ throw refused('outside_repository', "no file given is in the session's repository");
489
+ const at = new Date().toISOString();
490
+ const value = await change(id, (now) => ({
491
+ ...now,
492
+ claims: [
493
+ ...(now.claims ?? []).filter((each) => !paths.includes(each.path)),
494
+ ...paths.map((path) => ({ path, at, ...(note && { note }) })),
495
+ ],
496
+ }));
497
+ return {
498
+ id,
499
+ claims: value.claims,
500
+ others: scope ? await claimsBeside(found, scope.top, paths) : [],
501
+ };
502
+ });
503
+
504
+ route('POST', '/sessions/claims/release', async ({ actor, body }) => {
505
+ const { id, files } = parse(
506
+ releaseBody,
507
+ body,
508
+ 'POST /sessions/claims/release takes { id, files? }',
509
+ );
510
+ own(actor, id);
511
+ const found = await session(id, 'claiming');
512
+ const scope = await scopeOf(found);
513
+ const paths = files?.map((file) => (scope ? scope.path(file) : file) ?? file);
514
+ const value = await change(id, (now) => release(now, paths));
515
+ return { id, claims: value.claims ?? [] };
516
+ });
517
+
518
+ /** The other active sessions in repository `top` claiming or changing some of `paths` (all of their claims without). */
519
+ const claimsBeside = async (self: Found<V>, top: string, paths?: string[]) => {
520
+ const found = [];
521
+ for (const other of await query()) {
522
+ if (other.id === self.id || !active(other) || !other.value.claims?.length) continue;
523
+ if ((await scopeOf(other))?.top !== top) continue;
524
+ const claims = other.value.claims.filter((each) => !paths || paths.includes(each.path));
525
+ if (claims.length)
526
+ found.push({
527
+ id: other.id,
528
+ title: other.value.title,
529
+ running: running.has(other.id),
530
+ claims,
531
+ });
532
+ }
533
+ return found;
534
+ };
535
+
536
+ /** What the agent of `found` reads before its turn's message: the messages waiting for it (written as received, its
537
+ * inbox emptied), the answers to its questions it has not read (marked read), and the other active sessions'
538
+ * claims in its repository. */
539
+ const preface = async (found: Found<V>, top: string | undefined) => {
540
+ const { id, value } = found;
541
+ let text = '';
542
+ const inbox = value.inbox ?? [];
543
+ if (inbox.length) {
544
+ await change(id, (now) => ({
545
+ ...now,
546
+ inbox: (now.inbox ?? []).filter(
547
+ (each) =>
548
+ !inbox.some(
549
+ (taken) =>
550
+ taken.at === each.at && taken.from === each.from && taken.text === each.text,
551
+ ),
552
+ ),
553
+ }));
554
+ for (const { request, kind, from, title, text: said } of inbox)
555
+ await append(id, 'peer/received', {
556
+ ...(request && { request }),
557
+ kind,
558
+ from,
559
+ title,
560
+ text: said,
561
+ });
562
+ text += `<bridge_messages>\nOther active Bridge sessions wrote to this one. A question (ask) waits for your answer: answer it with the answer_session tool (its request, ok | wait | no, and why) before you go on.\n${inbox.map(({ request, kind, from, title, text: said }) => `- ${kind === 'ask' ? `ask ${request}` : 'notify'} from ${from} "${title}": ${said.replaceAll('</bridge_messages>', '')}`).join('\n')}\n</bridge_messages>\n\n`;
563
+ }
564
+ const answered = (value.asks ?? []).filter((each) => each.answer && !each.read);
565
+ if (answered.length) {
566
+ await change(id, (now) => ({
567
+ ...now,
568
+ asks: now.asks?.map((each) =>
569
+ answered.some((done) => done.request === each.request)
570
+ ? { ...each, read: true as const }
571
+ : each,
572
+ ),
573
+ }));
574
+ text += `<bridge_answers>\nAnswers to your questions to other sessions:\n${answered.map(({ request, title, text: asked, answer }) => `- ${request} to "${title}" (${cutText(asked, 120)}): ${answer!.verdict}${answer!.text ? `, ${answer!.text}` : ''} (by its ${answer!.by})`).join('\n')}\n</bridge_answers>\n\n`;
575
+ }
576
+ if (top) {
577
+ const claims = await claimsBeside(found, top);
578
+ if (claims.length) {
579
+ text += `<bridge_claims>\nOther active sessions are about to change these files: before you edit one, ask its session (ask_session) or tell it (notify_session).\n${claims
580
+ .slice(0, 20)
581
+ .map(
582
+ ({ id: other, title, running: busy, claims: theirs }) =>
583
+ `- ${other} "${title}"${busy ? ' (a turn running)' : ''}: ${theirs
584
+ .slice(0, 20)
585
+ .map(({ path, note }) => (note ? `${path} (${note})` : path))
586
+ .join(', ')}`,
587
+ )
588
+ .join('\n')}\n</bridge_claims>\n\n`;
589
+ }
590
+ }
591
+ return text;
592
+ };
593
+
594
+ /** After session `id`'s turn ended (`byUser`: a user's turn): a session owed questions gets a turn to answer them,
595
+ * unless it had `AUTO_MAX` such turns in a row. */
596
+ const ended = (id: string, byUser: boolean) => {
597
+ if (byUser) autos.delete(id);
598
+ // Its turn over, a question to a session without a turn running would wait for nobody: it is the user's call now.
599
+ void (async () => {
600
+ const asker = await get(id);
601
+ const now = new Date().toISOString();
602
+ for (const ask of asker?.value.asks ?? []) {
603
+ if (ask.answer || expired(ask) || running.has(ask.to) || owed.has(ask.to)) continue;
604
+ await setDeadline(id, ask.to, ask.request, now);
605
+ }
606
+ })().catch(log(`session ${id}: questions not expired`));
607
+ if (!owed.delete(id)) return;
608
+ void (async () => {
609
+ const found = await get(id);
610
+ if (
611
+ !active(found) ||
612
+ running.has(id) ||
613
+ !found!.value.inbox?.some((each) => each.kind === 'ask')
614
+ )
615
+ return;
616
+ const count = autos.get(id) ?? 0;
617
+ if (count >= AUTO_MAX) return;
618
+ autos.set(id, count + 1);
619
+ await startTurn(found!, AUTO_TEXT, true);
620
+ })().catch(log(`session ${id}: questions not delivered`));
621
+ };
622
+
623
+ /** The open questions of each session among `all`, asked and asked of it. */
624
+ const questionsOf = (all: Found<V>[]) => {
625
+ const byId = new Map<string, Question[]>();
626
+ const add = (id: string, question: Question) =>
627
+ byId.set(id, [...(byId.get(id) ?? []), question]);
628
+ const titles = new Map(all.map((each) => [each.id, each.value.title]));
629
+ for (const asker of all) {
630
+ for (const ask of asker.value.asks ?? []) {
631
+ if (ask.answer) continue;
632
+ const target = all.find((each) => each.id === ask.to);
633
+ if (!target) continue;
634
+ const delivered = !target.value.inbox?.some((each) => each.request === ask.request);
635
+ const shared = {
636
+ request: ask.request,
637
+ text: ask.text,
638
+ at: ask.at,
639
+ ...(ask.expiresAt && { expiresAt: ask.expiresAt }),
640
+ expired: expired(ask),
641
+ delivered,
642
+ };
643
+ add(asker.id, {
644
+ ...shared,
645
+ role: 'asker',
646
+ other: ask.to,
647
+ title: titles.get(ask.to) ?? ask.title,
648
+ });
649
+ add(ask.to, { ...shared, role: 'target', other: asker.id, title: asker.value.title });
650
+ }
651
+ }
652
+ return byId;
653
+ };
654
+ /** Arms the deadlines of the open questions (at start). */
655
+ const start = async () => {
656
+ for (const asker of await query())
657
+ for (const ask of asker.value.asks ?? []) if (!ask.answer) arm(ask.request, ask.expiresAt);
658
+ };
659
+ const dispose = () => {
660
+ disposed = true;
661
+ for (const timer of timers.values()) clearTimeout(timer);
662
+ timers.clear();
663
+ // Its waiting `wait_answer` calls answer now (pending), their timers cleared: one left kept a stopping worker busy.
664
+ for (const wakes of [...waiting.values()]) for (const wake of [...wakes]) wake();
665
+ };
666
+
667
+ return { preface, ended, claimsBeside, questionsOf, start, dispose };
668
+ }
669
+
670
+ /** `value` without its claims on `paths` (all of them without). */
671
+ export const release = <V extends { claims?: Claim[] | undefined }>(
672
+ { claims, ...rest }: V,
673
+ paths?: string[],
674
+ ): V => {
675
+ const kept = paths ? claims?.filter((each) => !paths.includes(each.path)) : [];
676
+ return { ...rest, ...(kept?.length && { claims: kept }) } as V;
677
+ };