@bridgebrew/sessions 0.0.0-stage → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +43 -2
- package/answers.ts +167 -0
- package/browser/branch-actions.tsx +166 -0
- package/browser/changes.tsx +415 -0
- package/browser/children.tsx +650 -0
- package/browser/conversation.tsx +2381 -0
- package/browser/decision-questions.tsx +191 -0
- package/browser/elapsed.tsx +44 -0
- package/browser/gallery.tsx +218 -0
- package/browser/index.tsx +3434 -0
- package/browser/media-origins.tsx +38 -0
- package/browser/mobile.tsx +663 -0
- package/browser/open-link.tsx +30 -0
- package/browser/pull-request.tsx +116 -0
- package/browser/questions.tsx +156 -0
- package/browser/session-scheduled.tsx +203 -0
- package/browser/subagent-view.tsx +136 -0
- package/browser/subagents.tsx +339 -0
- package/browser/tabs.tsx +228 -0
- package/browser/tsconfig.json +15 -0
- package/browser/views/view.tsx +1064 -0
- package/browser/views.tsx +166 -0
- package/contract.ts +287 -0
- package/delegations.ts +1975 -0
- package/diff.ts +88 -0
- package/docs/en/images.mdx +51 -0
- package/docs/en/index.mdx +22 -0
- package/docs/en/meta.json +4 -0
- package/docs/en/organize-sessions.mdx +53 -0
- package/docs/en/start-a-session.mdx +63 -0
- package/docs/meta.json +4 -0
- package/git.ts +223 -0
- package/listing.ts +382 -0
- package/package.json +1023 -4
- package/peers.ts +677 -0
- package/pull-request-watch.ts +282 -0
- package/pull-requests.ts +606 -0
- package/server.ts +5915 -0
- package/text.ts +19 -0
- package/tsconfig.json +3 -0
- package/viewer-activity.ts +57 -0
- package/views/examples.ts +153 -0
- package/views/library.ts +1116 -0
package/pull-requests.ts
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
// A session's pull request (research-086 S1-S3): one per session, on its record (`pullRequest`), read through the
|
|
2
|
+
// optional `github` service (bridge-plugins' `@bridgebrew/github`: the machine's gh, no token kept by Bridge).
|
|
3
|
+
// - Linked: found from the session's branch (its folder's branch and `origin`) at each turn's end and when its page
|
|
4
|
+
// opens, an open or draft one only (a merged one found by branch is an old one); or by `link_pull_request` (the
|
|
5
|
+
// agent's own session, the user's any). An unlinked url (`pullRequestUnlinked`) is never found by branch again.
|
|
6
|
+
// - Read: one read per pull request serves every session linked to it, at most `READS` at once. A linked open or draft
|
|
7
|
+
// one of a session not settled every `pullRequestSyncMinutes` (10), a watched one every `pullRequestWatchMinutes`
|
|
8
|
+
// (2), and at a turn's end and a page's open (then not when read in the last 30 s); a merged or closed one never
|
|
9
|
+
// again. One timer per worker, ticking at the shorter interval.
|
|
10
|
+
// - Settles: merged settles the session (`auto`, a notice line), once, at its turn's end when one runs; closed with
|
|
11
|
+
// the setting `pullRequestSettle`. An open or draft one keeps its session out of auto-settle
|
|
12
|
+
// (`pullRequestKeepsActive`, server.ts's `idle`).
|
|
13
|
+
// - Watched (`watch_pull_request`, refused in a child session and in a settled one): the rules of
|
|
14
|
+
// ./pull-request-watch.ts, their memory on the record (a worker restart tells nothing twice; watching again repeats no
|
|
15
|
+
// check or conflict news); a wake is a message `from: 'bridge'` put in the session's queue in the same write as the
|
|
16
|
+
// memory that told it (its id `pull-request:…`), then sent as any queued message: at once when no turn runs, after
|
|
17
|
+
// the running one, held after the user's Stop; never a steer. A merge or a close drops the news still queued. Ends:
|
|
18
|
+
// unwatch, the user's Stop, settle, archive, merged (no message), closed (one message), 10 comment-only wakes, 8
|
|
19
|
+
// failed reads in a row as the reference counts them: GitHub refusing the read counts; no network or a timeout
|
|
20
|
+
// starts the count over; a rate limit, gh missing, signed out or outdated (the `github` service's own attention)
|
|
21
|
+
// leave it as it was. A watched session counts as working (the inbox's Working, never auto-settled).
|
|
22
|
+
// ponytail: a read gets the last 50 comments and 30 reviews (each review's first inline comment): more news than that
|
|
23
|
+
// between two reads, or an edit to an older one, is not told; the reference pages through review threads.
|
|
24
|
+
import { z } from 'zod';
|
|
25
|
+
import {
|
|
26
|
+
closedText,
|
|
27
|
+
evaluate,
|
|
28
|
+
READ_FAILURE_LIMIT,
|
|
29
|
+
startWatch,
|
|
30
|
+
unreadableText,
|
|
31
|
+
wakeText,
|
|
32
|
+
type Read,
|
|
33
|
+
} from './pull-request-watch.ts';
|
|
34
|
+
|
|
35
|
+
export const SYNC_MS = 10 * 60_000;
|
|
36
|
+
export const WATCH_MS = 2 * 60_000;
|
|
37
|
+
/** A read this recent serves a turn's end or a page's open. */
|
|
38
|
+
const FRESH_MS = 30_000;
|
|
39
|
+
/** Reads at once (the `github` service runs at most 4 gh). */
|
|
40
|
+
const READS = 4;
|
|
41
|
+
|
|
42
|
+
const watchMemory = z.strictObject({
|
|
43
|
+
startedAt: z.string(),
|
|
44
|
+
headSha: z.string().optional(),
|
|
45
|
+
failedChecks: z.array(z.string()),
|
|
46
|
+
passed: z.boolean(),
|
|
47
|
+
passedChecks: z.array(z.string()),
|
|
48
|
+
owedChecks: z.array(z.string()),
|
|
49
|
+
remarksThrough: z.string(),
|
|
50
|
+
remarkIds: z.array(z.string()),
|
|
51
|
+
conflicting: z.boolean(),
|
|
52
|
+
wakes: z.number().int(),
|
|
53
|
+
checksAwaitedSince: z.string().optional(),
|
|
54
|
+
draft: z.literal(true).optional(),
|
|
55
|
+
});
|
|
56
|
+
/** A session's pull request on its record. */
|
|
57
|
+
export const pullRequestRecord = z.strictObject({
|
|
58
|
+
repository: z.string(),
|
|
59
|
+
number: z.number().int(),
|
|
60
|
+
url: z.string(),
|
|
61
|
+
title: z.string().optional(),
|
|
62
|
+
/** Its head branch, as GitHub last said (the Git button trusts it on that branch only). */
|
|
63
|
+
headBranch: z.string().optional(),
|
|
64
|
+
/** How it was linked: found from the session's branch, by its agent, by the user. */
|
|
65
|
+
by: z.enum(['branch', 'agent', 'user']),
|
|
66
|
+
// Its last read.
|
|
67
|
+
state: z.enum(['draft', 'open', 'merged', 'closed']).optional(),
|
|
68
|
+
checks: z.enum(['none', 'pending', 'passed', 'failed']).optional(),
|
|
69
|
+
conflicting: z.literal(true).optional(),
|
|
70
|
+
readAt: z.string().optional(),
|
|
71
|
+
/** Watched: read every `pullRequestWatchMinutes`, waking the agent on news. */
|
|
72
|
+
watching: z.literal(true).optional(),
|
|
73
|
+
/** What the watch told (kept once it ends, so watching again repeats nothing). */
|
|
74
|
+
watch: watchMemory.optional(),
|
|
75
|
+
/** Failed reads in a row while watched (those counted). */
|
|
76
|
+
failures: z.number().int().optional(),
|
|
77
|
+
/** The session was settled for this pull request's merge or close: never again for it. */
|
|
78
|
+
settled: z.literal(true).optional(),
|
|
79
|
+
});
|
|
80
|
+
export type PullRequest = z.infer<typeof pullRequestRecord>;
|
|
81
|
+
|
|
82
|
+
/** A queued message, as the record keeps it. */
|
|
83
|
+
interface Queued {
|
|
84
|
+
id: string;
|
|
85
|
+
text: string;
|
|
86
|
+
at: string;
|
|
87
|
+
from?: 'bridge' | undefined;
|
|
88
|
+
}
|
|
89
|
+
/** What the record holds of it, on a session. */
|
|
90
|
+
interface Value {
|
|
91
|
+
createdAt: string;
|
|
92
|
+
pullRequest?: PullRequest | undefined;
|
|
93
|
+
pullRequestUnlinked?: string[] | undefined;
|
|
94
|
+
settledAt?: string | undefined;
|
|
95
|
+
parent?: string | undefined;
|
|
96
|
+
queue?: Queued[] | undefined;
|
|
97
|
+
}
|
|
98
|
+
/** The id of a queued wake: pull request news. */
|
|
99
|
+
const WAKE = 'pull-request:';
|
|
100
|
+
/** `value` with Bridge's message `text` last in its queue (in the write that keeps the memory telling it). */
|
|
101
|
+
const withWake = <V extends Value>(value: V, text: string, at: number): V => ({
|
|
102
|
+
...value,
|
|
103
|
+
queue: [
|
|
104
|
+
...(value.queue ?? []),
|
|
105
|
+
{ id: `${WAKE}${crypto.randomUUID()}`, text, at: new Date(at).toISOString(), from: 'bridge' as const },
|
|
106
|
+
],
|
|
107
|
+
});
|
|
108
|
+
/** `value` without the pull request news still queued: merged or closed, it is no longer news. */
|
|
109
|
+
const withoutWakes = <V extends Value>(value: V): V => {
|
|
110
|
+
if (!value.queue?.some((each) => each.id.startsWith(WAKE))) return value;
|
|
111
|
+
const { queue, ...rest } = value;
|
|
112
|
+
const kept = queue.filter((each) => !each.id.startsWith(WAKE));
|
|
113
|
+
return (kept.length ? { ...rest, queue: kept } : rest) as V;
|
|
114
|
+
};
|
|
115
|
+
interface Found<V> {
|
|
116
|
+
id: string;
|
|
117
|
+
node: string;
|
|
118
|
+
value: V;
|
|
119
|
+
archived?: boolean | undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The `github` service's part this reads (`@bridgebrew/github`, never imported). */
|
|
123
|
+
export interface GitHubReads {
|
|
124
|
+
repositoryOf(remoteUrl: string): string | undefined;
|
|
125
|
+
pullRequestsForBranch(request: { repository: string; branch: string }): Promise<
|
|
126
|
+
{
|
|
127
|
+
number: number;
|
|
128
|
+
url: string;
|
|
129
|
+
title: string;
|
|
130
|
+
state: 'draft' | 'open' | 'merged' | 'closed';
|
|
131
|
+
createdAt?: string;
|
|
132
|
+
}[]
|
|
133
|
+
>;
|
|
134
|
+
readPullRequest(request: { repository: string; number: number }): Promise<
|
|
135
|
+
Read & {
|
|
136
|
+
title: string;
|
|
137
|
+
repository: string;
|
|
138
|
+
headBranch: string;
|
|
139
|
+
checksSum: 'none' | 'pending' | 'passed' | 'failed';
|
|
140
|
+
}
|
|
141
|
+
>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** `https://github.com/o/r/pull/7` (and its tabs, `/files`…) → `{ repository: 'o/r', number: 7, url }`. */
|
|
145
|
+
export const pullRequestOf = (url: string) => {
|
|
146
|
+
const found = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)(?:[/?#].*)?$/.exec(
|
|
147
|
+
url.trim(),
|
|
148
|
+
);
|
|
149
|
+
return found
|
|
150
|
+
? { repository: `${found[1]}/${found[2]}`, number: Number(found[3]), url: `https://github.com/${found[1]}/${found[2]}/pull/${found[3]}` }
|
|
151
|
+
: undefined;
|
|
152
|
+
};
|
|
153
|
+
const keyOf = (pr: { repository: string; number: number }) => `${pr.repository}#${pr.number}`;
|
|
154
|
+
const open = (pr: PullRequest | undefined) => !!pr && (pr.state === undefined || pr.state === 'draft' || pr.state === 'open');
|
|
155
|
+
/** The open or draft pull request that keeps a session active. */
|
|
156
|
+
export const keepsActive = (value: Value) => open(value.pullRequest);
|
|
157
|
+
/** Without a watch: its pull request no longer watched. */
|
|
158
|
+
export const unwatched = <V extends Value>(value: V): V =>
|
|
159
|
+
value.pullRequest?.watching ? { ...value, pullRequest: { ...value.pullRequest, watching: undefined } } : value;
|
|
160
|
+
|
|
161
|
+
/** Error codes of the `github` service a watch counts as a failed read (GitHub answered, and not what was asked), and
|
|
162
|
+
* those that start the count over (no answer: the reference's transport failures). The others leave it. */
|
|
163
|
+
const COUNTED = ['not_found', 'forbidden', 'invalid_response', 'http'];
|
|
164
|
+
const RESET = ['network', 'timeout'];
|
|
165
|
+
|
|
166
|
+
export function createPullRequests<V extends Value>(deps: {
|
|
167
|
+
route: (
|
|
168
|
+
method: string,
|
|
169
|
+
path: string,
|
|
170
|
+
description: string,
|
|
171
|
+
handle: (request: { body?: Uint8Array | undefined; actor?: string | undefined }) => unknown,
|
|
172
|
+
) => void;
|
|
173
|
+
github: () => GitHubReads | undefined;
|
|
174
|
+
get: (id: string) => Promise<Found<V> | undefined>;
|
|
175
|
+
/** Every session not archived. */
|
|
176
|
+
query: () => Promise<Found<V>[]>;
|
|
177
|
+
change: (id: string, fn: (value: V) => V) => Promise<V>;
|
|
178
|
+
running: Set<string>;
|
|
179
|
+
/** Session `found`'s git branch and its `origin`'s URL (`undefined`: none, or the default branch). */
|
|
180
|
+
branchOf: (found: Found<V>) => Promise<{ branch: string; remote: string } | undefined>;
|
|
181
|
+
/** Sends session `id`'s queue as after a completed turn: a wake just queued starts a turn when none runs, never after
|
|
182
|
+
* the user's Stop or a turn that did not complete (the queue then waits for the user). */
|
|
183
|
+
deliver: (id: string) => void;
|
|
184
|
+
/** How many times the user stopped session `id` (in memory): a watch asked before a Stop is not started after it. */
|
|
185
|
+
stops: (id: string) => number;
|
|
186
|
+
/** Settles session `id` (`auto`) with a notice line, unless it may not be now (pinned, a child running…). */
|
|
187
|
+
settle: (id: string, notice: string) => Promise<boolean>;
|
|
188
|
+
/** The session's record changed: its pages list again. */
|
|
189
|
+
changed: (id: string) => void;
|
|
190
|
+
settings: () => { settle: 'merged' | 'merged or closed' | 'never'; watchMs: number; syncMs: number };
|
|
191
|
+
refused: (code: string, message: string, status?: number) => Error;
|
|
192
|
+
parse: <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string) => T;
|
|
193
|
+
actsAs: (actor: string | undefined, id: string) => boolean;
|
|
194
|
+
log: (what: string) => (error: unknown) => void;
|
|
195
|
+
now?: () => number;
|
|
196
|
+
}) {
|
|
197
|
+
const { github, get, query, change, running, refused, parse, log } = deps;
|
|
198
|
+
const now = deps.now ?? Date.now;
|
|
199
|
+
/** When each pull request was last read (its key), and the reads under way. */
|
|
200
|
+
const readAt = new Map<string, number>();
|
|
201
|
+
const reading = new Map<string, Promise<void>>();
|
|
202
|
+
|
|
203
|
+
const service = () => {
|
|
204
|
+
const found = github();
|
|
205
|
+
return found && typeof found.readPullRequest === 'function' ? found : undefined;
|
|
206
|
+
};
|
|
207
|
+
const unavailable = () =>
|
|
208
|
+
refused(
|
|
209
|
+
'github_unavailable',
|
|
210
|
+
'GitHub is not available in this workspace: install GitHub (@bridgebrew/github) and sign in with gh auth login',
|
|
211
|
+
409,
|
|
212
|
+
);
|
|
213
|
+
|
|
214
|
+
/** One read of pull request `pr`, applied to every session linked to it; a read under way serves a second ask. */
|
|
215
|
+
const read = (pr: { repository: string; number: number }) => {
|
|
216
|
+
const key = keyOf(pr);
|
|
217
|
+
const under = reading.get(key);
|
|
218
|
+
if (under) return under;
|
|
219
|
+
const work = (async () => {
|
|
220
|
+
const reads = service();
|
|
221
|
+
if (!reads) return;
|
|
222
|
+
readAt.set(key, now());
|
|
223
|
+
let snapshot: Awaited<ReturnType<GitHubReads['readPullRequest']>> | undefined;
|
|
224
|
+
let failure: unknown;
|
|
225
|
+
try {
|
|
226
|
+
snapshot = await reads.readPullRequest({ repository: pr.repository, number: pr.number });
|
|
227
|
+
} catch (error) {
|
|
228
|
+
failure = error;
|
|
229
|
+
}
|
|
230
|
+
const linked = (await query()).filter(
|
|
231
|
+
(each) => each.value.pullRequest && keyOf(each.value.pullRequest) === key,
|
|
232
|
+
);
|
|
233
|
+
for (const each of linked)
|
|
234
|
+
await (snapshot ? apply(each.id, key, snapshot) : failed(each.id, key, failure)).catch(
|
|
235
|
+
log(`session ${each.id}: pull request ${key} not stored`),
|
|
236
|
+
);
|
|
237
|
+
if (failure) log(`pull request ${key} not read`)(failure);
|
|
238
|
+
})().finally(() => reading.delete(key));
|
|
239
|
+
reading.set(key, work);
|
|
240
|
+
return work;
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
/** A read failed: a watch counts it (`COUNTED`) and ends at the limit with one message, or starts over (`RESET`). */
|
|
244
|
+
const failed = async (id: string, key: string, error: unknown) => {
|
|
245
|
+
const code = (error as { code?: unknown } | undefined)?.code;
|
|
246
|
+
const counted = typeof code === 'string' && COUNTED.includes(code);
|
|
247
|
+
if (!counted && !(typeof code === 'string' && RESET.includes(code))) return;
|
|
248
|
+
let ended = false;
|
|
249
|
+
await change(id, (value) => {
|
|
250
|
+
const pr = value.pullRequest;
|
|
251
|
+
if (!pr?.watching || keyOf(pr) !== key) return value;
|
|
252
|
+
const { failures: was, ...rest } = pr;
|
|
253
|
+
if (!counted) return was === undefined ? value : { ...value, pullRequest: rest };
|
|
254
|
+
const failures = (was ?? 0) + 1;
|
|
255
|
+
if (failures < READ_FAILURE_LIMIT) return { ...value, pullRequest: { ...rest, failures } };
|
|
256
|
+
ended = true;
|
|
257
|
+
const stopped = { ...value, pullRequest: { ...rest, watching: undefined } };
|
|
258
|
+
return value.settledAt ? stopped : withWake(stopped, unreadableText(pr.number, pr.url), now());
|
|
259
|
+
});
|
|
260
|
+
if (ended) {
|
|
261
|
+
deps.changed(id);
|
|
262
|
+
deps.deliver(id);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
/** A read of pull request `key` reached session `id`: its state stored, its watch evaluated, its wake sent. */
|
|
267
|
+
const apply = async (
|
|
268
|
+
id: string,
|
|
269
|
+
key: string,
|
|
270
|
+
snapshot: Awaited<ReturnType<GitHubReads['readPullRequest']>>,
|
|
271
|
+
) => {
|
|
272
|
+
let message: string | undefined;
|
|
273
|
+
const at = now();
|
|
274
|
+
const value = await change(id, (current) => {
|
|
275
|
+
const pr = current.pullRequest;
|
|
276
|
+
if (!pr || keyOf(pr) !== key) return current;
|
|
277
|
+
message = undefined;
|
|
278
|
+
// Merged or closed: the news still queued is no longer news.
|
|
279
|
+
const was = snapshot.state === 'merged' || snapshot.state === 'closed' ? withoutWakes(current) : current;
|
|
280
|
+
const next: PullRequest = {
|
|
281
|
+
...pr,
|
|
282
|
+
url: snapshot.url || pr.url,
|
|
283
|
+
title: snapshot.title,
|
|
284
|
+
headBranch: snapshot.headBranch,
|
|
285
|
+
state: snapshot.state,
|
|
286
|
+
checks: snapshot.checksSum,
|
|
287
|
+
readAt: new Date(at).toISOString(),
|
|
288
|
+
};
|
|
289
|
+
delete next.conflicting;
|
|
290
|
+
delete next.failures;
|
|
291
|
+
if (snapshot.mergeable === 'conflicting') next.conflicting = true;
|
|
292
|
+
// A watch on a settled session, or in a child (never started there), ends without a word.
|
|
293
|
+
if (pr.watching && (was.settledAt || was.parent)) next.watching = undefined;
|
|
294
|
+
else if (pr.watching && snapshot.state === 'merged') next.watching = undefined;
|
|
295
|
+
else if (pr.watching && snapshot.state === 'closed') {
|
|
296
|
+
next.watching = undefined;
|
|
297
|
+
message = closedText(pr.number, next.url);
|
|
298
|
+
} else if (pr.watching) {
|
|
299
|
+
const report = evaluate(pr.watch ?? startWatch(at), snapshot, at);
|
|
300
|
+
next.watch = report.next;
|
|
301
|
+
if (report.changes.length) message = wakeText(snapshot, report);
|
|
302
|
+
if (report.exhausted) next.watching = undefined;
|
|
303
|
+
}
|
|
304
|
+
// A wake goes into the queue with the memory that told it, in one write: a restart neither loses nor repeats it.
|
|
305
|
+
return message ? withWake({ ...was, pullRequest: next }, message, at) : { ...was, pullRequest: next };
|
|
306
|
+
});
|
|
307
|
+
deps.changed(id);
|
|
308
|
+
if (message) deps.deliver(id);
|
|
309
|
+
if (value.pullRequest?.state === 'merged' || value.pullRequest?.state === 'closed') await settleIfDone(id);
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
/** Settles session `id` once for its merged (or, with the setting, closed) pull request; at its turn's end when one
|
|
313
|
+
* runs. */
|
|
314
|
+
const settleIfDone = async (id: string) => {
|
|
315
|
+
if (running.has(id)) return;
|
|
316
|
+
const found = await get(id);
|
|
317
|
+
const pr = found?.value.pullRequest;
|
|
318
|
+
if (!found || found.archived || !pr || pr.settled || found.value.settledAt) return;
|
|
319
|
+
const mode = deps.settings().settle;
|
|
320
|
+
const done =
|
|
321
|
+
(pr.state === 'merged' && mode !== 'never') || (pr.state === 'closed' && mode === 'merged or closed');
|
|
322
|
+
if (!done) return;
|
|
323
|
+
if (!(await deps.settle(id, `Settled: pull request #${pr.number} ${pr.state}.`))) return;
|
|
324
|
+
await change(id, (value) =>
|
|
325
|
+
value.pullRequest && keyOf(value.pullRequest) === keyOf(pr)
|
|
326
|
+
? { ...value, pullRequest: { ...value.pullRequest, settled: true } }
|
|
327
|
+
: value,
|
|
328
|
+
);
|
|
329
|
+
deps.changed(id);
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
/** Finds session `found`'s pull request from its branch, not unlinked before: an open or draft one, else one made
|
|
333
|
+
* since the session was (made and merged within one turn); an older merged one is not this session's. */
|
|
334
|
+
const findByBranch = async (found: Found<V>) => {
|
|
335
|
+
const reads = service();
|
|
336
|
+
if (!reads || found.value.pullRequest) return;
|
|
337
|
+
const at = await deps.branchOf(found);
|
|
338
|
+
const repository = at && reads.repositoryOf(at.remote);
|
|
339
|
+
if (!at || !repository) return;
|
|
340
|
+
const listed = await reads.pullRequestsForBranch({ repository, branch: at.branch });
|
|
341
|
+
const unlinked = found.value.pullRequestUnlinked ?? [];
|
|
342
|
+
const candidates = listed.filter((each) => !unlinked.includes(each.url));
|
|
343
|
+
const pick =
|
|
344
|
+
candidates.find((each) => each.state === 'open' || each.state === 'draft') ??
|
|
345
|
+
candidates.find((each) => !!each.createdAt && each.createdAt >= found.value.createdAt);
|
|
346
|
+
if (!pick) return;
|
|
347
|
+
// Read again in the write: unlinked, or linked meanwhile (another refresh, the user), it stays as it is now.
|
|
348
|
+
await change(found.id, (value) =>
|
|
349
|
+
value.pullRequest || value.pullRequestUnlinked?.includes(pick.url)
|
|
350
|
+
? value
|
|
351
|
+
: {
|
|
352
|
+
...value,
|
|
353
|
+
pullRequest: {
|
|
354
|
+
repository,
|
|
355
|
+
number: pick.number,
|
|
356
|
+
url: pick.url,
|
|
357
|
+
title: pick.title,
|
|
358
|
+
by: 'branch',
|
|
359
|
+
state: pick.state,
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
);
|
|
363
|
+
deps.changed(found.id);
|
|
364
|
+
await read({ repository, number: pick.number });
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
/** A turn ended, or the page opened session `id`: its pull request found or read again (unless read just now), and
|
|
368
|
+
* its session settled when it merged meanwhile. */
|
|
369
|
+
const refresh = async (id: string) => {
|
|
370
|
+
const found = await get(id);
|
|
371
|
+
if (!found || found.archived || !service()) return;
|
|
372
|
+
const pr = found.value.pullRequest;
|
|
373
|
+
if (!pr) await findByBranch(found);
|
|
374
|
+
else if (open(pr) && now() - (readAt.get(keyOf(pr)) ?? 0) >= FRESH_MS) await read(pr);
|
|
375
|
+
await settleIfDone(id);
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
/** One sweep: each pull request due, read once for all its sessions, `READS` at once. */
|
|
379
|
+
const sweep = async () => {
|
|
380
|
+
if (!service()) return;
|
|
381
|
+
const { watchMs, syncMs } = deps.settings();
|
|
382
|
+
const due = new Map<string, { repository: string; number: number }>();
|
|
383
|
+
const at = now();
|
|
384
|
+
for (const { value } of await query()) {
|
|
385
|
+
const pr = value.pullRequest;
|
|
386
|
+
if (!pr || !open(pr)) continue;
|
|
387
|
+
const watched = pr.watching && !value.settledAt && !value.parent;
|
|
388
|
+
if (!watched && value.settledAt) continue;
|
|
389
|
+
const last = readAt.get(keyOf(pr)) ?? (pr.readAt ? Date.parse(pr.readAt) : 0);
|
|
390
|
+
// Within half a tick of its interval: read at the nearest tick, not one later.
|
|
391
|
+
if (at - last >= (watched ? watchMs : syncMs) - Math.min(watchMs, syncMs) / 2)
|
|
392
|
+
due.set(keyOf(pr), pr);
|
|
393
|
+
}
|
|
394
|
+
const queue = [...due.values()];
|
|
395
|
+
await Promise.all(
|
|
396
|
+
Array.from({ length: Math.min(READS, queue.length) }, async () => {
|
|
397
|
+
for (let next = queue.shift(); next; next = queue.shift()) await read(next);
|
|
398
|
+
}),
|
|
399
|
+
);
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
/** At start: a session whose pull request merged (or closed) while it was not settled yet (a turn ran, the worker
|
|
403
|
+
* stopped) settles now; a merged one is never read again to tell it. */
|
|
404
|
+
const settlePending = async () => {
|
|
405
|
+
for (const { id, value } of await query())
|
|
406
|
+
if (value.pullRequest && !open(value.pullRequest) && !value.pullRequest.settled && !value.settledAt)
|
|
407
|
+
await settleIfDone(id).catch(log(`session ${id}: not settled for its pull request`));
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
/** The timer: a tick at the shorter interval (read again at each tick: the settings apply live), each a sweep; a
|
|
411
|
+
* tick while a sweep runs sweeps again once it ends, never two at once. */
|
|
412
|
+
const start = () => {
|
|
413
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
414
|
+
let stopped = false;
|
|
415
|
+
let sweeping: Promise<void> | undefined;
|
|
416
|
+
let again = false;
|
|
417
|
+
const run = () => {
|
|
418
|
+
if (sweeping) {
|
|
419
|
+
again = true;
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
sweeping = sweep()
|
|
423
|
+
.catch(log('pull requests not read'))
|
|
424
|
+
.finally(() => {
|
|
425
|
+
sweeping = undefined;
|
|
426
|
+
if (again && !stopped) {
|
|
427
|
+
again = false;
|
|
428
|
+
run();
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
};
|
|
432
|
+
const tick = () => {
|
|
433
|
+
const { watchMs, syncMs } = deps.settings();
|
|
434
|
+
timer = setTimeout(() => {
|
|
435
|
+
tick();
|
|
436
|
+
run();
|
|
437
|
+
}, Math.min(watchMs, syncMs));
|
|
438
|
+
};
|
|
439
|
+
tick();
|
|
440
|
+
void settlePending().catch(log('pull request settles not checked'));
|
|
441
|
+
return () => {
|
|
442
|
+
stopped = true;
|
|
443
|
+
clearTimeout(timer);
|
|
444
|
+
};
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
// The tools (the agent's own session; the user's any).
|
|
448
|
+
const idBody = z.strictObject({ id: z.string().min(1).optional() });
|
|
449
|
+
const urlBody = z.strictObject({ id: z.string().min(1).optional(), url: z.string().min(1) });
|
|
450
|
+
const target = async (actor: string | undefined, input: { id?: string | undefined }) => {
|
|
451
|
+
const id = input.id ?? (actor?.startsWith('agent:') ? actor.slice('agent:'.length) : undefined);
|
|
452
|
+
if (id === undefined) throw refused('invalid_id', 'give the session id');
|
|
453
|
+
if (!deps.actsAs(actor, id)) throw refused('not_your_session', 'An agent acts on its own session only', 403);
|
|
454
|
+
const found = await get(id);
|
|
455
|
+
if (!found || found.archived) throw refused('not_found', `no session ${id}`, 404);
|
|
456
|
+
return found;
|
|
457
|
+
};
|
|
458
|
+
/** Links `url` to session `found` (replacing its link), read at once. */
|
|
459
|
+
const link = async (found: Found<V>, url: string, by: 'agent' | 'user') => {
|
|
460
|
+
const reads = service();
|
|
461
|
+
if (!reads) throw unavailable();
|
|
462
|
+
const pr = pullRequestOf(url);
|
|
463
|
+
if (!pr) throw refused('invalid_url', `not a GitHub pull request URL: ${url} (https://github.com/<owner>/<name>/pull/<number>)`);
|
|
464
|
+
const snapshot = await reads.readPullRequest(pr).catch((error: unknown) => {
|
|
465
|
+
throw refused(
|
|
466
|
+
'pull_request_unreadable',
|
|
467
|
+
`pull request ${pr.url} could not be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
468
|
+
409,
|
|
469
|
+
);
|
|
470
|
+
});
|
|
471
|
+
const at = now();
|
|
472
|
+
readAt.set(keyOf(pr), at);
|
|
473
|
+
const value = await change(found.id, (was) => {
|
|
474
|
+
const same = was.pullRequest && keyOf(was.pullRequest) === keyOf(pr) ? was.pullRequest : undefined;
|
|
475
|
+
const { pullRequestUnlinked: unlinked, ...rest } = was;
|
|
476
|
+
const kept = unlinked?.filter((each) => each !== pr.url);
|
|
477
|
+
return {
|
|
478
|
+
...rest,
|
|
479
|
+
...(kept?.length && { pullRequestUnlinked: kept }),
|
|
480
|
+
pullRequest: {
|
|
481
|
+
...same,
|
|
482
|
+
repository: pr.repository,
|
|
483
|
+
number: pr.number,
|
|
484
|
+
url: snapshot.url || pr.url,
|
|
485
|
+
title: snapshot.title,
|
|
486
|
+
headBranch: snapshot.headBranch,
|
|
487
|
+
by: same?.by ?? by,
|
|
488
|
+
state: snapshot.state,
|
|
489
|
+
checks: snapshot.checksSum,
|
|
490
|
+
...(snapshot.mergeable === 'conflicting' ? { conflicting: true as const } : {}),
|
|
491
|
+
readAt: new Date(at).toISOString(),
|
|
492
|
+
},
|
|
493
|
+
} as V;
|
|
494
|
+
});
|
|
495
|
+
deps.changed(found.id);
|
|
496
|
+
return { id: found.id, pullRequest: value.pullRequest };
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
deps.route(
|
|
500
|
+
'POST',
|
|
501
|
+
'/sessions/pull-request/link',
|
|
502
|
+
"Links a GitHub pull request to a session (its only one, replacing any): { id?, url }",
|
|
503
|
+
async ({ actor, body }) => {
|
|
504
|
+
const input = parse(urlBody, body, 'POST /sessions/pull-request/link takes { id?, url }');
|
|
505
|
+
const found = await target(actor, input);
|
|
506
|
+
return link(found, input.url, actor?.startsWith('agent') ? 'agent' : 'user');
|
|
507
|
+
},
|
|
508
|
+
);
|
|
509
|
+
deps.route(
|
|
510
|
+
'POST',
|
|
511
|
+
'/sessions/pull-request/unlink',
|
|
512
|
+
"Unlinks a session's pull request (never found again from its branch); its watch ends: { id? }",
|
|
513
|
+
async ({ actor, body }) => {
|
|
514
|
+
const found = await target(actor, parse(idBody, body, 'POST /sessions/pull-request/unlink takes { id? }'));
|
|
515
|
+
const value = await change(found.id, (was) => {
|
|
516
|
+
if (!was.pullRequest) return was;
|
|
517
|
+
const { pullRequest, ...rest } = was;
|
|
518
|
+
return {
|
|
519
|
+
...rest,
|
|
520
|
+
pullRequestUnlinked: [...(was.pullRequestUnlinked ?? []).filter((each) => each !== pullRequest.url), pullRequest.url].slice(-20),
|
|
521
|
+
} as V;
|
|
522
|
+
});
|
|
523
|
+
deps.changed(found.id);
|
|
524
|
+
return { id: found.id, pullRequest: value.pullRequest ?? null };
|
|
525
|
+
},
|
|
526
|
+
);
|
|
527
|
+
deps.route(
|
|
528
|
+
'POST',
|
|
529
|
+
'/sessions/pull-request/watch',
|
|
530
|
+
"Watches a session's pull request: Bridge reads it every 2 minutes and wakes the agent when something needs it: { id?, url? }",
|
|
531
|
+
async ({ actor, body }) => {
|
|
532
|
+
const input = parse(
|
|
533
|
+
z.strictObject({ id: z.string().min(1).optional(), url: z.string().min(1).optional() }),
|
|
534
|
+
body,
|
|
535
|
+
'POST /sessions/pull-request/watch takes { id?, url? }',
|
|
536
|
+
);
|
|
537
|
+
const found = await target(actor, input);
|
|
538
|
+
if (found.value.parent !== undefined)
|
|
539
|
+
throw refused(
|
|
540
|
+
'child_session',
|
|
541
|
+
'A child session does not watch a pull request: the session that delegated to it does',
|
|
542
|
+
409,
|
|
543
|
+
);
|
|
544
|
+
if (found.value.settledAt)
|
|
545
|
+
throw refused('session_settled', `session ${found.id} is settled: un-settle it before watching`, 409);
|
|
546
|
+
const stops = deps.stops(found.id);
|
|
547
|
+
const url = input.url ?? found.value.pullRequest?.url;
|
|
548
|
+
if (!url)
|
|
549
|
+
throw refused(
|
|
550
|
+
'no_pull_request',
|
|
551
|
+
`session ${found.id} has no pull request: give its url (watch_pull_request { url })`,
|
|
552
|
+
409,
|
|
553
|
+
);
|
|
554
|
+
const linked = await link(found, url, actor?.startsWith('agent') ? 'agent' : 'user');
|
|
555
|
+
const state = linked.pullRequest?.state;
|
|
556
|
+
if (state === 'merged' || state === 'closed')
|
|
557
|
+
throw refused('pull_request_closed', `pull request ${url} is ${state}: there is nothing to watch`, 409);
|
|
558
|
+
// Watching again keeps what the last watch of this pull request told (`startWatch`).
|
|
559
|
+
// Checked again in the write: settled, stopped, unlinked or linked to another one during the read, it does not start.
|
|
560
|
+
const value = await change(found.id, (was) => {
|
|
561
|
+
if (was.settledAt)
|
|
562
|
+
throw refused('session_settled', `session ${found.id} is settled: un-settle it before watching`, 409);
|
|
563
|
+
if (deps.stops(found.id) !== stops)
|
|
564
|
+
throw refused('session_stopped', `session ${found.id} was stopped meanwhile: watch it again`, 409);
|
|
565
|
+
if (!was.pullRequest || was.pullRequest.url !== linked.pullRequest?.url)
|
|
566
|
+
throw refused('pull_request_changed', `session ${found.id}'s pull request changed meanwhile`, 409);
|
|
567
|
+
return was.pullRequest.watching
|
|
568
|
+
? was
|
|
569
|
+
: {
|
|
570
|
+
...was,
|
|
571
|
+
pullRequest: {
|
|
572
|
+
...was.pullRequest,
|
|
573
|
+
watching: true,
|
|
574
|
+
watch: startWatch(now(), was.pullRequest.watch),
|
|
575
|
+
failures: undefined,
|
|
576
|
+
},
|
|
577
|
+
};
|
|
578
|
+
});
|
|
579
|
+
deps.changed(found.id);
|
|
580
|
+
return { id: found.id, pullRequest: value.pullRequest };
|
|
581
|
+
},
|
|
582
|
+
);
|
|
583
|
+
deps.route(
|
|
584
|
+
'POST',
|
|
585
|
+
'/sessions/pull-request/unwatch',
|
|
586
|
+
"Stops watching a session's pull request (it stays linked): { id? }",
|
|
587
|
+
async ({ actor, body }) => {
|
|
588
|
+
const found = await target(actor, parse(idBody, body, 'POST /sessions/pull-request/unwatch takes { id? }'));
|
|
589
|
+
const value = await change(found.id, unwatched);
|
|
590
|
+
deps.changed(found.id);
|
|
591
|
+
return { id: found.id, pullRequest: value.pullRequest ?? null };
|
|
592
|
+
},
|
|
593
|
+
);
|
|
594
|
+
deps.route(
|
|
595
|
+
'POST',
|
|
596
|
+
'/sessions/pull-request/refresh',
|
|
597
|
+
"Reads a session's pull request again, or finds it from its branch (its page, as it opens): { id }",
|
|
598
|
+
async ({ actor, body }) => {
|
|
599
|
+
const found = await target(actor, parse(idBody, body, 'POST /sessions/pull-request/refresh takes { id }'));
|
|
600
|
+
await refresh(found.id);
|
|
601
|
+
return { id: found.id, pullRequest: (await get(found.id))?.value.pullRequest ?? null };
|
|
602
|
+
},
|
|
603
|
+
);
|
|
604
|
+
|
|
605
|
+
return { refresh, sweep, start, settleIfDone };
|
|
606
|
+
}
|