@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/diff.ts ADDED
@@ -0,0 +1,88 @@
1
+ // An edit as the conversation shows it: its added and removed line counts and its first changed lines with a little
2
+ // context, from the texts an agent gives (often only the part that changes). Lines are diffed with an LCS when both
3
+ // changed parts are small enough, else shown as all removed then all added.
4
+
5
+ import { cutText } from './text.ts';
6
+
7
+ /** One edit: `lines` start with `+`, `-` or a space (context); `more`, the changed lines past them. */
8
+ export interface Change {
9
+ path: string;
10
+ added: number;
11
+ removed: number;
12
+ lines: string[];
13
+ more?: number;
14
+ }
15
+
16
+ /** Lines shown per edit. */
17
+ const SHOWN = 40;
18
+ /** Context lines kept before and after the changed part. */
19
+ const CONTEXT = 2;
20
+ /** The largest old × new line product diffed with an LCS. */
21
+ const LCS_MAX = 250_000;
22
+ /** A line's longest shown part. */
23
+ const LINE_MAX = 400;
24
+
25
+ const split = (text: string) =>
26
+ text === '' ? [] : text.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
27
+
28
+ /** The middle parts as `+`/`-`/` ` lines: an LCS when small enough, else all removed then all added. */
29
+ const middle = (before: string[], after: string[]): string[] => {
30
+ if (!before.length || !after.length || before.length * after.length > LCS_MAX)
31
+ return [...before.map((line) => `-${line}`), ...after.map((line) => `+${line}`)];
32
+ const rows = before.length + 1;
33
+ const cols = after.length + 1;
34
+ const table = new Uint32Array(rows * cols);
35
+ for (let i = before.length - 1; i >= 0; i--) {
36
+ for (let j = after.length - 1; j >= 0; j--) {
37
+ table[i * cols + j] =
38
+ before[i] === after[j]
39
+ ? table[(i + 1) * cols + j + 1]! + 1
40
+ : Math.max(table[(i + 1) * cols + j]!, table[i * cols + j + 1]!);
41
+ }
42
+ }
43
+ const out: string[] = [];
44
+ let i = 0;
45
+ let j = 0;
46
+ while (i < before.length && j < after.length) {
47
+ if (before[i] === after[j]) {
48
+ out.push(` ${before[i]}`);
49
+ i++;
50
+ j++;
51
+ } else if (table[(i + 1) * cols + j]! >= table[i * cols + j + 1]!) out.push(`-${before[i++]}`);
52
+ else out.push(`+${after[j++]}`);
53
+ }
54
+ while (i < before.length) out.push(`-${before[i++]}`);
55
+ while (j < after.length) out.push(`+${after[j++]}`);
56
+ return out;
57
+ };
58
+
59
+ /** Edit `diff` as a `Change`. */
60
+ export function changeOf(diff: { path: string; oldText?: string; newText: string }): Change {
61
+ const before = split(diff.oldText ?? '');
62
+ const after = split(diff.newText);
63
+ let start = 0;
64
+ while (start < before.length && start < after.length && before[start] === after[start]) start++;
65
+ let end = 0;
66
+ while (
67
+ end < before.length - start &&
68
+ end < after.length - start &&
69
+ before[before.length - 1 - end] === after[after.length - 1 - end]
70
+ )
71
+ end++;
72
+ const changed = middle(
73
+ before.slice(start, before.length - end),
74
+ after.slice(start, after.length - end),
75
+ );
76
+ const added = changed.filter((line) => line[0] === '+').length;
77
+ const removed = changed.filter((line) => line[0] === '-').length;
78
+ const all = [
79
+ ...before.slice(Math.max(0, start - CONTEXT), start).map((line) => ` ${line}`),
80
+ ...changed,
81
+ ...before.slice(before.length - end, before.length - end + CONTEXT).map((line) => ` ${line}`),
82
+ ];
83
+ const lines = all
84
+ .slice(0, SHOWN)
85
+ .map((line) => (line.length > LINE_MAX ? `${cutText(line, LINE_MAX)}…` : line));
86
+ const more = all.slice(SHOWN).filter((line) => line[0] !== ' ').length;
87
+ return { path: diff.path, added, removed, lines, ...(more > 0 && { more }) };
88
+ }
@@ -0,0 +1,51 @@
1
+ ---
2
+ title: Images
3
+ description: Send images to the agent, see the images and videos it shows, and pin the ones to keep in the gallery.
4
+ status: implemented
5
+ ---
6
+
7
+ ## Send images with a message
8
+
9
+ Add up to 8 images to a message, each up to 10 MB (PNG, JPEG, GIF or WebP):
10
+
11
+ - select **+** in the composer and choose the files;
12
+ - drag them onto the composer;
13
+ - or paste them in the message field.
14
+
15
+ Each image shows as a thumbnail above the message field. Select one to see it
16
+ whole, or its **×** to remove it. The agent receives the images with your
17
+ message. Bridge keeps a copy of them with the session.
18
+
19
+ ## See the agent's images
20
+
21
+ When the agent shows an image or a video in its answer, it appears as a
22
+ thumbnail. A tool line where the agent looked at an image opens on that image,
23
+ unless the answer already shows it.
24
+
25
+ Select a thumbnail to open the viewer. Use the arrows or the arrow keys to go
26
+ through the images of a message, **Download** to save one, and **Esc** to
27
+ close.
28
+
29
+ Bridge does not copy the agent's images: they stay where the agent wrote them.
30
+ If the agent or you delete the file, the thumbnail becomes a link.
31
+
32
+ ## Keep an image or a video in the gallery
33
+
34
+ 1. Open the image in the viewer, or point at the video.
35
+ 2. Select **Pin to the gallery**.
36
+
37
+ Bridge copies the file itself, from where it is on the disk, so a large video
38
+ pins as fast as an image (up to 2 GB). It keeps the copy for good, even after
39
+ the session is archived or the original file is gone. A pinned image's
40
+ thumbnail shows a pin. Select **Unpin from the gallery** to let it go: Bridge
41
+ deletes its copy.
42
+
43
+ Bridge pins PNG, JPEG, GIF and WebP images, and MP4, WebM and MOV videos. It
44
+ never pins a file of its own folder outside the projects.
45
+
46
+ ## Browse the gallery
47
+
48
+ Select the image button in the session's header. The gallery shows the pinned
49
+ images and videos of the **Session**, its **Project**, or the whole
50
+ **Workspace**. Select one to see it whole or play it, unpin it, or open the
51
+ session it came from.
@@ -0,0 +1,22 @@
1
+ ---
2
+ title: Sessions
3
+ description: Work with an AI agent and return to the conversation when you need it.
4
+ status: implemented
5
+ ---
6
+
7
+ A session keeps your conversation with one agent, including its messages,
8
+ permission decisions and recorded file changes.
9
+
10
+ ## Where your session works
11
+
12
+ Project sessions use the project's folder. A workspace session works at the
13
+ workspace level. Choose the workspace or project before you start a conversation.
14
+
15
+ ## Choose a guide
16
+
17
+ Use these guides to start a conversation or organize work you've already started.
18
+
19
+ <Cards>
20
+ <Card title="Start a session" description="Choose an agent, send a message and handle a permission request." href="./start-a-session" icon="messages-square" />
21
+ <Card title="Organize sessions" description="Keep important work visible and put finished conversations aside." href="./organize-sessions" icon="list" />
22
+ </Cards>
@@ -0,0 +1,4 @@
1
+ {
2
+ "title": "English",
3
+ "pages": ["index", "start-a-session", "organize-sessions", "images"]
4
+ }
@@ -0,0 +1,53 @@
1
+ ---
2
+ title: Organize sessions
3
+ description: Pin ongoing work, settle finished conversations and return to them later.
4
+ status: implemented
5
+ ---
6
+
7
+ Use the session's action menu to change where it appears in the Sessions list.
8
+
9
+ ## Keep ongoing work visible
10
+
11
+ Pin a session you want to find again without searching through recent activity.
12
+
13
+ 1. Open the session's action menu in the Sessions list.
14
+ 2. Select **Pin**.
15
+
16
+ The session appears in **Pinned**. Select **Unpin** in its action menu to return
17
+ it to the normal list.
18
+
19
+ ## Put finished work aside
20
+
21
+ Wait until the agent's turn has stopped before settling a session.
22
+
23
+ 1. Open the session's action menu.
24
+ 2. Select **Settle**.
25
+
26
+ The conversation moves to **Settled** and keeps its history. Select **Un-settle**
27
+ to bring it back, or send a new message to resume it.
28
+
29
+ ## Choose the right action
30
+
31
+ These actions let you keep, postpone or hide a conversation.
32
+
33
+ | Action | Result |
34
+ | ------- | ----------------------------------------------------------- |
35
+ | Pin | Keep the session in Pinned. |
36
+ | Settle | Move it to Settled and clear its pin. |
37
+ | Snooze | Hide it until a chosen time; requires the scheduler plugin. |
38
+ | Archive | Hide it from the normal list; restore it from Archived. |
39
+
40
+ <Callout title="Snooze availability" type="info">
41
+ Snooze appears when the workspace has the scheduler service. You can't snooze
42
+ a session while it is waiting for a permission decision.
43
+ </Callout>
44
+
45
+ The Snooze menu lists its choices soonest first, then **Custom…** for any
46
+ other date and time. Change the choices in **Settings → Sessions → Snooze
47
+ choices**: each one is a delay (in minutes) or a time on a day (today,
48
+ tomorrow, or the next Monday to Sunday).
49
+
50
+ ## Next steps
51
+
52
+ [Start a session](./start-a-session) for another task, or return to the
53
+ [Sessions overview](./index) to choose a different guide.
@@ -0,0 +1,63 @@
1
+ ---
2
+ title: Start a session
3
+ description: Start a conversation in the workspace or project you want the agent to work on.
4
+ status: implemented
5
+ ---
6
+
7
+ Before you start, your workspace needs an available Profile and Model.
8
+ If the composer reports **Profile not ready**, resolve the reported issue first.
9
+
10
+ ## Send your first message
11
+
12
+ Your first message creates the session and starts the agent's turn.
13
+
14
+ 1. Open **Sessions** in the workspace or project you want to use.
15
+ 2. Select **New chat**.
16
+ 3. Choose a Profile (labeled with its Harness) and Model in the composer.
17
+ 4. Review **Permissions** when the harness offers permission modes.
18
+ 5. Write your request and select **Send**.
19
+
20
+ The conversation shows the agent's response. Once a session exists, you can
21
+ rename it using the title field above the conversation.
22
+
23
+ <Callout title="One agent per session" type="info">
24
+ The Profile ID and Model stay fixed for the session's life. Start another session
25
+ to use a different agent or model. You can change the permission mode when the
26
+ harness supports it.
27
+ </Callout>
28
+
29
+ ## Continue or stop a turn
30
+
31
+ While the agent is running, another message enters the queue. Bridge sends it
32
+ when the current turn completes. Select **Stop** to interrupt the running turn;
33
+ the queue then waits for your next message, also after Bridge restarts.
34
+
35
+ When Bridge restarts, reloads Sessions or the harness, or stops unexpectedly
36
+ during a turn, the agent continues that turn on its own once Bridge is back. It
37
+ is told that its last action may not have finished, and which commands and
38
+ sub-agents were cancelled. A message that had not reached the agent yet is sent
39
+ again. Bridge continues a session at most three times within five minutes; past
40
+ that, the session waits for you.
41
+
42
+ When the agent asks for permission, choose an answer in the conversation before
43
+ it can continue with that action.
44
+
45
+ ## Next steps
46
+
47
+ [Organize sessions](./organize-sessions) to pin a conversation or put completed
48
+ work in Settled. Return to the [Sessions overview](./index) to check where a
49
+ workspace or project session works.
50
+
51
+ ## Profiles and scopes
52
+
53
+ A Harness is execution software (Claude Code, Codex or Hermes); a Driver is its
54
+ Bridge adapter. A Profile configures that Harness with an account, environment,
55
+ default Model and permissions. Configure Profiles in System → Harness for
56
+ Bridge, or in Settings for a workspace or project. Inherited fields show their
57
+ origins; Save writes local changes, Hide affects that scope, and Reset removes
58
+ local overrides. Archived projects cannot be edited.
59
+
60
+ Existing sessions keep their Profile ID, history and resume reference. The
61
+ `harnesses` configuration key and stored session `harness` field remain compatibility
62
+ names; new APIs accept `profile` and still accept `harness` when both agree.
63
+ Agent memory/workflow and Skill execution are outside this release.
package/docs/meta.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "title": "Sessions",
3
+ "pages": ["en"]
4
+ }
package/git.ts ADDED
@@ -0,0 +1,223 @@
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
+ /** The branches of the repository at `folder` that have a folder, as git lists them (`git worktree list`): its own
36
+ * checkout first, then each worktree under its `.worktrees/` (research-083). A folder's name is never read as a branch's
37
+ * name (`feat/x` and `feat-x` share one). */
38
+ export const worktreesOf = async (run: Run, folder: string) => {
39
+ const { code, stdout } = await run(folder, ['worktree', 'list', '--porcelain']);
40
+ if (code !== 0) return [];
41
+ const all = stdout.split('\n\n').flatMap((block) => {
42
+ const path = /^worktree (.+)$/m.exec(block)?.[1];
43
+ const name = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
44
+ return path && name ? [{ name, folder: path }] : [];
45
+ });
46
+ const main = /^worktree (.+)$/m.exec(stdout)?.[1];
47
+ return all.filter(
48
+ (each) => each.folder === main || each.folder.startsWith(`${main}/.worktrees/`),
49
+ );
50
+ };
51
+
52
+ /** A branch name from a message (research-083): its first words, lowercase, joined by `-`; empty when it has none.
53
+ * A URL gives none of them (plugins#73). The fallback of a model's name (`typedBranch`). */
54
+ export const branchSlug = (text: string) =>
55
+ text
56
+ .replace(/\b[a-z][a-z0-9+.-]*:\/\/\S*/gi, ' ')
57
+ .toLowerCase()
58
+ .normalize('NFKD')
59
+ .replace(/[\u0300-\u036f'’]/g, '')
60
+ .split(/[^a-z0-9]+/)
61
+ .filter(Boolean)
62
+ .slice(0, 6)
63
+ // Whole words within 40 characters (a single longer word cut).
64
+ .reduce(
65
+ (name, word) =>
66
+ !name ? word.slice(0, 40) : name.length + 1 + word.length <= 40 ? `${name}-${word}` : name,
67
+ '',
68
+ );
69
+
70
+ /** A model's answer as a `type/topic` branch name (`fix/e2e-shards`), `undefined` when it is not one. */
71
+ export const typedBranch = (answer: string) => {
72
+ // Its first line: a model may go on after the name (plugins#84).
73
+ const name = (answer.trim().split('\n')[0] ?? '').trim().replace(/^`+|`+$/g, '');
74
+ return name.length <= 40 &&
75
+ /^(feat|fix|chore|ci|docs|refactor|test)\/[a-z0-9]+(-[a-z0-9]+)*$/.test(name)
76
+ ? name
77
+ : undefined;
78
+ };
79
+
80
+ /** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has. */
81
+ export const freeBranch = async (run: Run, folder: string, name: string) => {
82
+ const { stdout } = await run(folder, ['branch', '--list', '--format=%(refname:short)']);
83
+ const taken = new Set(stdout.split('\n'));
84
+ let free = name;
85
+ for (let n = 2; taken.has(free); n++) free = `${name}-${n}`;
86
+ return free;
87
+ };
88
+
89
+ /** The repository holding `cwd`: its top folder, and `cwd`'s path in it (`prefix`, `''` or ending with `/`); `undefined`
90
+ * outside one. */
91
+ export const repositoryAt = async (run: Run, cwd: string): Promise<Repository | undefined> => {
92
+ const { code, stdout } = await run(cwd, ['rev-parse', '--show-toplevel', '--show-prefix']);
93
+ const [top, prefix = ''] = stdout.split('\n');
94
+ return code === 0 && top ? { top, prefix } : undefined;
95
+ };
96
+ export interface Repository {
97
+ top: string;
98
+ prefix: string;
99
+ }
100
+
101
+ /** The files of `top` that differ (read as `owner`) from `HEAD` (untracked ones included, ignored ones not), each with a fingerprint of
102
+ * its content now (`deleted` when gone): two states compared give what changed between them. */
103
+ export const stateOf = async (owner: Context, run: Run, top: string) => {
104
+ const { code, stdout } = await run(top, [
105
+ 'status',
106
+ '--porcelain=v1',
107
+ '-z',
108
+ '--untracked-files=all',
109
+ // A rename (`git mv`) is its deletion and its addition: both paths are the session's, so both get committed.
110
+ '--no-renames',
111
+ ]);
112
+ if (code !== 0) return undefined;
113
+ const paths = stdout
114
+ .split('\0')
115
+ .filter((field) => field.length >= 4)
116
+ .map((field) => field.slice(3));
117
+ const state = new Map<string, string>();
118
+ await Promise.all(
119
+ paths.map(async (path) => state.set(path, await fingerprint(owner, join(top, path)))),
120
+ );
121
+ return state;
122
+ };
123
+
124
+ /** Read through the host (`ctx.fs`) as `owner`. */
125
+ const fingerprint = async (owner: Context, file: string) => {
126
+ try {
127
+ const info = await owner.fs.stat(owner, file);
128
+ if (!info) return 'deleted';
129
+ if (!info.isFile) return `other:${info.mtimeMs}`;
130
+ return createHash('sha1')
131
+ .update(await owner.fs.readFile(owner, file))
132
+ .digest('hex');
133
+ } catch {
134
+ return 'deleted';
135
+ }
136
+ };
137
+
138
+ /** The paths whose fingerprint differs between `before` and `after`. */
139
+ export const changed = (before: Map<string, string>, after: Map<string, string>) =>
140
+ [...new Set([...before.keys(), ...after.keys()])].filter(
141
+ (path) => before.get(path) !== after.get(path),
142
+ );
143
+
144
+ /** `path` (absolute, or relative to `folder`, a folder of `repository`) relative to the repository's top, `/`-separated
145
+ * (`''`: the top itself); `undefined` outside it. The top git gives may be another spelling of `folder`'s (symbolic links resolved): a path in
146
+ * `folder` goes through `prefix`. */
147
+ export const within = ({ top, prefix }: Repository, folder: string, path: string) => {
148
+ const inside = (base: string, file: string) => {
149
+ const rel = relative(base, file);
150
+ return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel.split(sep).join('/');
151
+ };
152
+ const file = isAbsolute(path) ? path : join(folder, path);
153
+ const local = inside(folder, file);
154
+ return local === undefined ? inside(top, file) : `${prefix}${local}`.replace(/\/$/, '');
155
+ };
156
+
157
+ /** `git diff` printing git's own patch whatever the person's config: no external tool or textconv, the `a/` and `b/`
158
+ * prefixes the Changes panel reads (not `diff.mnemonicPrefix`'s `w/`, `i/`…), paths not quoted for their non-ASCII. */
159
+ const PATCH = [
160
+ '-c',
161
+ 'core.quotePath=false',
162
+ 'diff',
163
+ '--no-color',
164
+ '--no-ext-diff',
165
+ '--no-textconv',
166
+ '--src-prefix=a/',
167
+ '--dst-prefix=b/',
168
+ ];
169
+
170
+ /** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. */
171
+ export const diffOf = async (run: Run, top: string, files: string[], max: number) => {
172
+ if (!files.length) return '';
173
+ const tracked = await run(top, [...PATCH, 'HEAD', '--', ...files]);
174
+ let text = tracked.stdout;
175
+ const listed = await run(top, [
176
+ 'ls-files',
177
+ '--others',
178
+ '--exclude-standard',
179
+ '-z',
180
+ '--',
181
+ ...files,
182
+ ]);
183
+ for (const path of listed.stdout.split('\0').filter(Boolean)) {
184
+ if (text.length > max) break;
185
+ const added = await run(top, [...PATCH, '--no-index', '--', '/dev/null', path]);
186
+ text += added.stdout;
187
+ }
188
+ return text.length > max ? `${cutText(text, max)}\n… [truncated]` : text;
189
+ };
190
+
191
+ /** Commits exactly `files` in `top` (their current content, deletions included; nothing else staged goes in), with
192
+ * `message` and the trailer `Bridge-Session: <session>`; resolves to the new commit's sha. */
193
+ export const commit = async (
194
+ run: Run,
195
+ top: string,
196
+ files: string[],
197
+ message: string,
198
+ session: string,
199
+ ) => {
200
+ // `commit --only` takes a tracked path's content from the disk, a deletion included (even one staged, as the old
201
+ // side of a `git mv`, which `add` would refuse as matching no file); only an untracked one needs adding first.
202
+ const untracked = (
203
+ await run(top, ['ls-files', '--others', '--exclude-standard', '-z', '--', ...files])
204
+ ).stdout
205
+ .split('\0')
206
+ .filter(Boolean);
207
+ if (untracked.length) {
208
+ const added = await run(top, ['add', '--', ...untracked]);
209
+ if (added.code !== 0) throw new Error(`git add failed: ${added.stderr.trim()}`);
210
+ }
211
+ const done = await run(top, [
212
+ 'commit',
213
+ '--only',
214
+ '-m',
215
+ message,
216
+ '--trailer',
217
+ `Bridge-Session: ${session}`,
218
+ '--',
219
+ ...files,
220
+ ]);
221
+ if (done.code !== 0) throw new Error(`git commit failed: ${(done.stderr || done.stdout).trim()}`);
222
+ return (await run(top, ['rev-parse', 'HEAD'])).stdout.trim();
223
+ };