@bridgebrew/sessions 0.0.34 → 0.0.38
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/branch-name.ts +34 -0
- package/browser/branch-actions.tsx +26 -47
- package/browser/conversation.tsx +43 -1
- package/browser/details.tsx +408 -0
- package/browser/index.tsx +606 -495
- package/browser/mobile.tsx +118 -8
- package/browser/pull-request.tsx +9 -6
- package/browser/session-scheduled.tsx +6 -3
- package/browser/subagent-view.tsx +2 -2
- package/contract.ts +6 -0
- package/delegations.ts +4 -3
- package/package.json +44 -7
- package/server.ts +563 -237
- package/browser/changes.tsx +0 -464
- package/git.ts +0 -318
package/git.ts
DELETED
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
// Git for the sessions plugin: what a turn changed in its project's repository, and a session's commit. Git runs
|
|
2
|
-
// through the host's `processes` (AD-27), never with the worker's own `child_process`; nothing is written to its stdin
|
|
3
|
-
// (the host's guard never closes it). Paths are relative to the repository's top folder, `/`-separated, as git prints
|
|
4
|
-
// them. A folder outside any repository, or without git, has no state: `undefined`.
|
|
5
|
-
import { createHash } from 'node:crypto';
|
|
6
|
-
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
7
|
-
import type { Context } from 'cordis';
|
|
8
|
-
import { cutText } from './text.ts';
|
|
9
|
-
|
|
10
|
-
export type Run = (
|
|
11
|
-
cwd: string,
|
|
12
|
-
args: string[],
|
|
13
|
-
) => Promise<{ code: number | null; stdout: string; stderr: string }>;
|
|
14
|
-
|
|
15
|
-
/** `git <args>` in `cwd`, through the host's processes, owned by `owner`. */
|
|
16
|
-
export const runner =
|
|
17
|
-
(owner: Context): Run =>
|
|
18
|
-
async (cwd, args) => {
|
|
19
|
-
const child = await owner.processes.spawn(owner, {
|
|
20
|
-
command: 'git',
|
|
21
|
-
args,
|
|
22
|
-
cwd,
|
|
23
|
-
env: { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },
|
|
24
|
-
});
|
|
25
|
-
let stdout = '';
|
|
26
|
-
let stderr = '';
|
|
27
|
-
child.onOutput((stream, chunk) => {
|
|
28
|
-
if (stream === 'stdout') stdout += chunk;
|
|
29
|
-
else stderr += chunk;
|
|
30
|
-
});
|
|
31
|
-
const { code } = await child.exited;
|
|
32
|
-
return { code, stdout, stderr };
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
/** How long `ssh -G` may take to name an alias's host before the remote is read as written. */
|
|
36
|
-
export const SSH_RESOLVE_MS = 5000;
|
|
37
|
-
|
|
38
|
-
/** The host name ssh connects to for `alias` (`ssh -G`, which reads `~/.ssh/config` and connects nowhere), run in
|
|
39
|
-
* `cwd` through the host's processes; `undefined` when ssh fails or has not answered within `timeoutMs`. */
|
|
40
|
-
export const sshHostname = async (owner: Context, cwd: string, alias: string, timeoutMs = SSH_RESOLVE_MS) => {
|
|
41
|
-
try {
|
|
42
|
-
const child = await owner.processes.spawn(owner, { command: 'ssh', args: ['-G', alias], cwd });
|
|
43
|
-
let stdout = '';
|
|
44
|
-
child.onOutput((stream, chunk) => {
|
|
45
|
-
if (stream === 'stdout') stdout += chunk;
|
|
46
|
-
});
|
|
47
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
48
|
-
const late = new Promise<'late'>((done) => {
|
|
49
|
-
timer = setTimeout(() => done('late'), timeoutMs);
|
|
50
|
-
});
|
|
51
|
-
const end = await Promise.race([child.exited, late]);
|
|
52
|
-
clearTimeout(timer);
|
|
53
|
-
if (end === 'late') {
|
|
54
|
-
void child.kill();
|
|
55
|
-
return undefined;
|
|
56
|
-
}
|
|
57
|
-
return end.code === 0 ? /^hostname (\S+)$/m.exec(stdout)?.[1] : undefined;
|
|
58
|
-
} catch {
|
|
59
|
-
return undefined;
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
/** `remote` with its ssh host alias replaced by the host `hostOf` resolves it to (`sshHostname`): a remote
|
|
64
|
-
* `git@github-work:o/r.git` whose `~/.ssh/config` says `HostName github.com` reads as GitHub's (plugins#114). Any other
|
|
65
|
-
* form (https, a path) and GitHub's own hosts come back as they are. */
|
|
66
|
-
export const resolveRemote = async (
|
|
67
|
-
remote: string,
|
|
68
|
-
hostOf: (alias: string) => Promise<string | undefined>,
|
|
69
|
-
) => {
|
|
70
|
-
const found =
|
|
71
|
-
/^(ssh:\/\/(?:[^@/]+@)?)([^/:@]+)(?::\d+)?\//i.exec(remote) ?? /^((?:[^@/:]+@)?)([^/:@]+):(?!\/)/.exec(remote);
|
|
72
|
-
const alias = found?.[2];
|
|
73
|
-
// A name only, never an option for ssh (`-…`).
|
|
74
|
-
if (!found || !alias || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(alias) || /^(?:ssh\.)?github\.com$/i.test(alias))
|
|
75
|
-
return remote;
|
|
76
|
-
const host = await hostOf(alias);
|
|
77
|
-
return host ? `${found[1]}${host}${remote.slice(found[1]!.length + alias.length)}` : remote;
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
/** The branches of the repository at `folder` that have a folder, as git lists them (`git worktree list`): its own
|
|
81
|
-
* checkout first, then each worktree under its `.worktrees/` (research-083). A folder's name is never read as a branch's
|
|
82
|
-
* name (`feat/x` and `feat-x` share one). */
|
|
83
|
-
export const worktreesOf = async (run: Run, folder: string) => {
|
|
84
|
-
const { code, stdout } = await run(folder, ['worktree', 'list', '--porcelain']);
|
|
85
|
-
if (code !== 0) return [];
|
|
86
|
-
const all = stdout.split('\n\n').flatMap((block) => {
|
|
87
|
-
const path = /^worktree (.+)$/m.exec(block)?.[1];
|
|
88
|
-
const name = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
|
|
89
|
-
return path && name ? [{ name, folder: path }] : [];
|
|
90
|
-
});
|
|
91
|
-
const main = /^worktree (.+)$/m.exec(stdout)?.[1];
|
|
92
|
-
return all.filter(
|
|
93
|
-
(each) => each.folder === main || each.folder.startsWith(`${main}/.worktrees/`),
|
|
94
|
-
);
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
/** A branch name from a message (research-083): its first words, lowercase, joined by `-`; empty when it has none.
|
|
98
|
-
* A URL gives none of them (plugins#73). The fallback of a model's name (`typedBranch`). */
|
|
99
|
-
export const branchSlug = (text: string) =>
|
|
100
|
-
text
|
|
101
|
-
.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S*/gi, ' ')
|
|
102
|
-
.toLowerCase()
|
|
103
|
-
.normalize('NFKD')
|
|
104
|
-
.replace(/[\u0300-\u036f'’]/g, '')
|
|
105
|
-
.split(/[^a-z0-9]+/)
|
|
106
|
-
.filter(Boolean)
|
|
107
|
-
.slice(0, 6)
|
|
108
|
-
// Whole words within 40 characters (a single longer word cut).
|
|
109
|
-
.reduce(
|
|
110
|
-
(name, word) =>
|
|
111
|
-
!name ? word.slice(0, 40) : name.length + 1 + word.length <= 40 ? `${name}-${word}` : name,
|
|
112
|
-
'',
|
|
113
|
-
);
|
|
114
|
-
|
|
115
|
-
/** The example of the prompt that asks a model for a branch name: never taken as its answer (plugins#110). */
|
|
116
|
-
export const BRANCH_EXAMPLE = 'fix/e2e-shards';
|
|
117
|
-
|
|
118
|
-
/** A model's answer as a `type/topic` branch name (`fix/login-timeout`), `undefined` when it is not one or is the prompt's
|
|
119
|
-
* own example (a model echoing it would name every branch the same). */
|
|
120
|
-
export const typedBranch = (answer: string) => {
|
|
121
|
-
// Its first line: a model may go on after the name (plugins#84).
|
|
122
|
-
const name = (answer.trim().split('\n')[0] ?? '').trim().replace(/^`+|`+$/g, '');
|
|
123
|
-
return name.length <= 40 &&
|
|
124
|
-
/^(feat|fix|chore|ci|docs|refactor|test)\/[a-z0-9]+(-[a-z0-9]+)*$/.test(name) &&
|
|
125
|
-
name !== BRANCH_EXAMPLE
|
|
126
|
-
? name
|
|
127
|
-
: undefined;
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
/** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has. Each read as its full
|
|
131
|
-
* name, not git's short form (`heads/<name>` beside a tag of the same name: plugins#198). */
|
|
132
|
-
export const freeBranch = async (run: Run, folder: string, name: string) => {
|
|
133
|
-
const { stdout } = await run(folder, ['branch', '--list', '--format=%(refname:lstrip=2)']);
|
|
134
|
-
const taken = new Set(stdout.split('\n'));
|
|
135
|
-
let free = name;
|
|
136
|
-
for (let n = 2; taken.has(free); n++) free = `${name}-${n}`;
|
|
137
|
-
return free;
|
|
138
|
-
};
|
|
139
|
-
|
|
140
|
-
/** The repository holding `cwd`: its top folder, and `cwd`'s path in it (`prefix`, `''` or ending with `/`); `undefined`
|
|
141
|
-
* outside one. */
|
|
142
|
-
export const repositoryAt = async (run: Run, cwd: string): Promise<Repository | undefined> => {
|
|
143
|
-
const { code, stdout } = await run(cwd, ['rev-parse', '--show-toplevel', '--show-prefix']);
|
|
144
|
-
const [top, prefix = ''] = stdout.split('\n');
|
|
145
|
-
return code === 0 && top ? { top, prefix } : undefined;
|
|
146
|
-
};
|
|
147
|
-
export interface Repository {
|
|
148
|
-
top: string;
|
|
149
|
-
prefix: string;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** Past this size a file's fingerprint is its size and mtime, not its content: a turn's snapshot never reads a huge file
|
|
153
|
-
* whole (#112). ponytail: an edit of such a file that keeps both is not seen. */
|
|
154
|
-
const HASH_MAX = 16 * 1024 * 1024;
|
|
155
|
-
/** A snapshot reads (stat and content) this many files at most, in `git status`'s order (tracked changes first): a
|
|
156
|
-
* folder of thousands of untracked files (a `node_modules` not ignored) costs no more (#121). The others are `unread`:
|
|
157
|
-
* one that appears or goes is still a change. ponytail: an edit of an unread file is not seen. */
|
|
158
|
-
const READ_MAX = 2_000;
|
|
159
|
-
|
|
160
|
-
/** The files of `top` that differ (read as `owner`) from `HEAD` (untracked ones included, ignored ones not), each with a fingerprint of
|
|
161
|
-
* its content now (`deleted` when gone): two states compared give what changed between them. */
|
|
162
|
-
export const stateOf = async (
|
|
163
|
-
owner: Context,
|
|
164
|
-
run: Run,
|
|
165
|
-
top: string,
|
|
166
|
-
{ hashMax = HASH_MAX, readMax = READ_MAX }: { hashMax?: number; readMax?: number } = {},
|
|
167
|
-
) => {
|
|
168
|
-
const { code, stdout } = await run(top, [
|
|
169
|
-
'status',
|
|
170
|
-
'--porcelain=v1',
|
|
171
|
-
'-z',
|
|
172
|
-
'--untracked-files=all',
|
|
173
|
-
// A rename (`git mv`) is its deletion and its addition: both paths are the session's, so both get committed.
|
|
174
|
-
'--no-renames',
|
|
175
|
-
]);
|
|
176
|
-
if (code !== 0) return undefined;
|
|
177
|
-
const paths = stdout
|
|
178
|
-
.split('\0')
|
|
179
|
-
.filter((field) => field.length >= 4)
|
|
180
|
-
.map((field) => field.slice(3));
|
|
181
|
-
const state = new Map<string, string>();
|
|
182
|
-
await Promise.all(
|
|
183
|
-
paths
|
|
184
|
-
.slice(0, readMax)
|
|
185
|
-
.map(async (path) => state.set(path, await fingerprint(owner, join(top, path), hashMax))),
|
|
186
|
-
);
|
|
187
|
-
for (const path of paths.slice(readMax)) state.set(path, 'unread');
|
|
188
|
-
return state;
|
|
189
|
-
};
|
|
190
|
-
|
|
191
|
-
/** Read through the host (`ctx.fs`) as `owner`. */
|
|
192
|
-
const fingerprint = async (owner: Context, file: string, hashMax: number) => {
|
|
193
|
-
try {
|
|
194
|
-
const info = await owner.fs.stat(owner, file);
|
|
195
|
-
if (!info) return 'deleted';
|
|
196
|
-
if (!info.isFile) return `other:${info.mtimeMs}`;
|
|
197
|
-
// Never a SHA-1: a file that crosses the limit during a turn shows as changed.
|
|
198
|
-
if (info.size > hashMax) return `meta:${info.size}:${info.mtimeMs}`;
|
|
199
|
-
return createHash('sha1')
|
|
200
|
-
.update(await owner.fs.readFile(owner, file))
|
|
201
|
-
.digest('hex');
|
|
202
|
-
} catch {
|
|
203
|
-
return 'deleted';
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
/** The paths whose fingerprint differs between `before` and `after`. An `unread` file's content is unknown: in both
|
|
208
|
-
* states and gone from neither, it is no change (a path that entered before the cap pushed it past, #121). */
|
|
209
|
-
export const changed = (before: Map<string, string>, after: Map<string, string>) =>
|
|
210
|
-
[...new Set([...before.keys(), ...after.keys()])].filter((path) => {
|
|
211
|
-
const was = before.get(path);
|
|
212
|
-
const now = after.get(path);
|
|
213
|
-
const unknown =
|
|
214
|
-
(was === 'unread' || now === 'unread') &&
|
|
215
|
-
was !== undefined &&
|
|
216
|
-
now !== undefined &&
|
|
217
|
-
was !== 'deleted' &&
|
|
218
|
-
now !== 'deleted';
|
|
219
|
-
return !unknown && was !== now;
|
|
220
|
-
});
|
|
221
|
-
|
|
222
|
-
/** `path` (absolute, or relative to `folder`, a folder of `repository`) relative to the repository's top, `/`-separated
|
|
223
|
-
* (`''`: the top itself); `undefined` outside it. The top git gives may be another spelling of `folder`'s (symbolic links resolved): a path in
|
|
224
|
-
* `folder` goes through `prefix`. */
|
|
225
|
-
export const within = ({ top, prefix }: Repository, folder: string, path: string) => {
|
|
226
|
-
const inside = (base: string, file: string) => {
|
|
227
|
-
const rel = relative(base, file);
|
|
228
|
-
return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel.split(sep).join('/');
|
|
229
|
-
};
|
|
230
|
-
const file = isAbsolute(path) ? path : join(folder, path);
|
|
231
|
-
const local = inside(folder, file);
|
|
232
|
-
return local === undefined ? inside(top, file) : `${prefix}${local}`.replace(/\/$/, '');
|
|
233
|
-
};
|
|
234
|
-
|
|
235
|
-
/** Git's own patch whatever the person's config: no external tool or textconv, the `a/` and `b/` prefixes the Changes
|
|
236
|
-
* panel reads (not `diff.mnemonicPrefix`'s `w/`, `i/`…), paths not quoted for their non-ASCII. */
|
|
237
|
-
const PATCH = ['--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
|
|
238
|
-
const QUOTE = ['-c', 'core.quotePath=false'];
|
|
239
|
-
|
|
240
|
-
/** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. An
|
|
241
|
-
* untracked file `sizeOf` (bytes, from its path relative to `top`) puts past `max`, or whose size it does not know, is
|
|
242
|
-
* one placeholder line: git is never asked for its patch (plugins#145). ponytail: the tracked part has no such cap. */
|
|
243
|
-
export const diffOf = async (
|
|
244
|
-
run: Run,
|
|
245
|
-
top: string,
|
|
246
|
-
files: string[],
|
|
247
|
-
max: number,
|
|
248
|
-
sizeOf: (path: string) => Promise<number | undefined>,
|
|
249
|
-
) => {
|
|
250
|
-
if (!files.length) return '';
|
|
251
|
-
// `diff-index`, not `diff`: `diff` refreshes the index of a file whose stat moved (a `touch`), rewriting it through
|
|
252
|
-
// `index.lock` even under `GIT_OPTIONAL_LOCKS=0`, and the session's agent's own `git add` then fails on that lock.
|
|
253
|
-
const tracked = await run(top, [...QUOTE, 'diff-index', '-p', ...PATCH, 'HEAD', '--', ...files]);
|
|
254
|
-
let text = tracked.stdout;
|
|
255
|
-
const listed = await run(top, [
|
|
256
|
-
'ls-files',
|
|
257
|
-
'--others',
|
|
258
|
-
'--exclude-standard',
|
|
259
|
-
'-z',
|
|
260
|
-
'--',
|
|
261
|
-
...files,
|
|
262
|
-
]);
|
|
263
|
-
for (const path of listed.stdout.split('\0').filter(Boolean)) {
|
|
264
|
-
if (text.length > max) break;
|
|
265
|
-
const size = await sizeOf(path);
|
|
266
|
-
if (size === undefined || size > max) {
|
|
267
|
-
const what = size === undefined ? 'of unknown size' : `of ${size} bytes`;
|
|
268
|
-
text += `diff --git a/${path} b/${path}\nnew file ${what}, not shown … [truncated]\n`;
|
|
269
|
-
continue;
|
|
270
|
-
}
|
|
271
|
-
const added = await run(top, [...QUOTE, 'diff', ...PATCH, '--no-index', '--', '/dev/null', path]);
|
|
272
|
-
text += added.stdout;
|
|
273
|
-
}
|
|
274
|
-
return text.length > max ? `${cutText(text, max)}\n… [truncated]` : text;
|
|
275
|
-
};
|
|
276
|
-
|
|
277
|
-
/** Commits exactly `files` in `top` (their current content, deletions included; nothing else staged goes in), with
|
|
278
|
-
* `message` and the trailer `Bridge-Session: <session>`; resolves to the new commit's sha, the files committed and the
|
|
279
|
-
* nested repositories `left` out. */
|
|
280
|
-
export const commit = async (
|
|
281
|
-
run: Run,
|
|
282
|
-
top: string,
|
|
283
|
-
files: string[],
|
|
284
|
-
message: string,
|
|
285
|
-
session: string,
|
|
286
|
-
) => {
|
|
287
|
-
// `commit --only` takes a tracked path's content from the disk, a deletion included (even one staged, as the old
|
|
288
|
-
// side of a `git mv`, which `add` would refuse as matching no file); only an untracked one needs adding first.
|
|
289
|
-
const listed = (
|
|
290
|
-
await run(top, ['ls-files', '--others', '--exclude-standard', '-z', '--', ...files])
|
|
291
|
-
).stdout
|
|
292
|
-
.split('\0')
|
|
293
|
-
.filter(Boolean);
|
|
294
|
-
// git lists a nested repository (and only one) as a folder, `sub/`: `add` would fail on an empty one and make a
|
|
295
|
-
// gitlink of another; it stays out of the commit (plugins#145).
|
|
296
|
-
const nested = new Set(listed.filter((path) => path.endsWith('/')));
|
|
297
|
-
const untracked = listed.filter((path) => !nested.has(path));
|
|
298
|
-
const left = files.filter((file) => nested.has(file) || nested.has(`${file}/`));
|
|
299
|
-
const kept = files.filter((file) => !left.includes(file));
|
|
300
|
-
// `commit --only` with no path would commit everything staged.
|
|
301
|
-
if (!kept.length) throw new Error(`nothing to commit: ${left.join(', ')} are nested repositories`);
|
|
302
|
-
if (untracked.length) {
|
|
303
|
-
const added = await run(top, ['add', '--', ...untracked]);
|
|
304
|
-
if (added.code !== 0) throw new Error(`git add failed: ${added.stderr.trim()}`);
|
|
305
|
-
}
|
|
306
|
-
const done = await run(top, [
|
|
307
|
-
'commit',
|
|
308
|
-
'--only',
|
|
309
|
-
'-m',
|
|
310
|
-
message,
|
|
311
|
-
'--trailer',
|
|
312
|
-
`Bridge-Session: ${session}`,
|
|
313
|
-
'--',
|
|
314
|
-
...kept,
|
|
315
|
-
]);
|
|
316
|
-
if (done.code !== 0) throw new Error(`git commit failed: ${(done.stderr || done.stdout).trim()}`);
|
|
317
|
-
return { sha: (await run(top, ['rev-parse', 'HEAD'])).stdout.trim(), files: kept, left };
|
|
318
|
-
};
|