@bridgebrew/sessions 0.0.21 → 0.0.27

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.
@@ -51,6 +51,20 @@ const unquote = (name: string | undefined) => {
51
51
  return new TextDecoder().decode(new Uint8Array(bytes));
52
52
  };
53
53
 
54
+ /** The path of a file whose diff has no `---`/`+++` lines (a binary file, a mode change): its rename's target, else its
55
+ * `diff --git` line's `b/` side, quoted, or unquoted and split where both sides name the same file (a space is in it). */
56
+ const gitLinePath = (lines: string[]) => {
57
+ const renamed = lines.find((line) => line.startsWith('rename to '));
58
+ if (renamed) return unquote(renamed.slice('rename to '.length));
59
+ const rest = lines[0]!.slice('diff --git '.length);
60
+ const quoted = /"(?:[^"\\]|\\.)*"$/.exec(rest)?.[0];
61
+ if (quoted) return unquote(quoted)?.replace(/^b\//, '');
62
+ const half = (rest.length - 1) / 2;
63
+ if (Number.isInteger(half) && rest.startsWith('a/') && rest.slice(half + 1).startsWith('b/') && rest.slice(2, half) === rest.slice(half + 3))
64
+ return rest.slice(half + 3);
65
+ return /^a\/(.*) b\//.exec(rest)?.[1];
66
+ };
67
+
54
68
  /** A `git diff` cut per file: its path (the new one, the old one for a deletion), its lines from its first hunk, and
55
69
  * its added and removed line counts. */
56
70
  export const diffFiles = (diff: string) =>
@@ -60,13 +74,19 @@ export const diffFiles = (diff: string) =>
60
74
  .map((chunk) => {
61
75
  const lines = chunk.replace(/\n$/, '').split('\n');
62
76
  const side = (prefix: string) => {
63
- const name = unquote(lines.find((line) => line.startsWith(prefix))?.slice(prefix.length));
77
+ // Git ends a name holding a space with a tab, outside its quotes: dropped before reading it (#197).
78
+ const name = unquote(
79
+ lines
80
+ .find((line) => line.startsWith(prefix))
81
+ ?.slice(prefix.length)
82
+ .replace(/\t$/, ''),
83
+ );
64
84
  return name && name !== '/dev/null' ? name.replace(/^[ab]\//, '') : undefined;
65
85
  };
66
86
  const hunk = lines.findIndex((line) => line.startsWith('@@'));
67
87
  const body = hunk < 0 ? lines.slice(1) : lines.slice(hunk);
68
88
  return {
69
- path: side('+++ ') ?? side('--- ') ?? /^diff --git a\/(.*) b\//.exec(lines[0]!)?.[1] ?? '',
89
+ path: side('+++ ') ?? side('--- ') ?? gitLinePath(lines) ?? '',
70
90
  lines: body,
71
91
  added: body.filter((line) => line[0] === '+').length,
72
92
  removed: body.filter((line) => line[0] === '-').length,
@@ -104,6 +124,9 @@ export function SessionDetails({
104
124
  const [picked, setPicked] = React.useState<Set<string>>(new Set());
105
125
  const [message, setMessage] = React.useState('');
106
126
  const [committing, setCommitting] = React.useState(false);
127
+ /** The nested repositories the last commit of `session` left out (plugins#145): another session's are not shown. */
128
+ const [left, setLeft] = React.useState<{ session: string; paths: string[] }>();
129
+ const leftOut = left?.session === session.id ? left.paths : [];
107
130
  /** Other sessions share the picked files: Commit asks again before it takes their changes. */
108
131
  const [confirming, setConfirming] = React.useState(false);
109
132
  const listId = React.useId();
@@ -167,13 +190,19 @@ export function SessionDetails({
167
190
  }
168
191
  setCommitting(true);
169
192
  setError('');
193
+ setLeft(undefined);
170
194
  try {
171
- await post('/commit', {
195
+ const done: unknown = await post('/commit', {
172
196
  id: session.id,
173
197
  message: message.trim(),
174
198
  files: [...picked],
175
199
  ...(confirming && { force: true }),
176
200
  });
201
+ const nested =
202
+ typeof done === 'object' && done !== null && 'left' in done && Array.isArray(done.left)
203
+ ? done.left.filter((path): path is string => typeof path === 'string')
204
+ : [];
205
+ setLeft({ session: session.id, paths: nested });
177
206
  setMessage('');
178
207
  onChanged();
179
208
  } catch (cause) {
@@ -405,6 +434,12 @@ export function SessionDetails({
405
434
  )}
406
435
  </>
407
436
  )}
437
+ {leftOut.length > 0 && (
438
+ <p role="status" className="text-xs text-warning">
439
+ Not committed: {leftOut.join(', ')} (
440
+ {leftOut.length === 1 ? 'a nested repository' : 'nested repositories'}).
441
+ </p>
442
+ )}
408
443
  {error && (
409
444
  <p role="alert" className="text-xs text-destructive">
410
445
  {error}
@@ -128,7 +128,7 @@ export interface Stored {
128
128
  interrupted?: boolean;
129
129
  input?: unknown;
130
130
  output?: unknown;
131
- options?: { id: string; label: string; kind?: string }[];
131
+ options?: { id: string; label: string; kind?: string; scope?: string }[];
132
132
  option?: string | null;
133
133
  expiresAt?: string;
134
134
  mode?: string;
@@ -1640,6 +1640,9 @@ const TurnView = React.memo(function TurnView({
1640
1640
 
1641
1641
  /** The label of open decision `event`: a question when its driver says so (or it asks questions, or none of its options
1642
1642
  * allows or denies), else a permission. */
1643
+ /** The option Enter picks: the first that allows this request only, never a lasting grant (`scope: 'always'`, plugins#171). */
1644
+ const primaryAllow = (options: Stored['options']) =>
1645
+ options?.find((option) => option.kind === 'allow' && option.scope !== 'always');
1643
1646
  const decisionLabel = (event: Stored) => {
1644
1647
  const asked = askedOf(event);
1645
1648
  return (
@@ -1701,7 +1704,7 @@ const PendingDecision = React.memo(function PendingDecision({
1701
1704
  };
1702
1705
  const asked = relative(event.title ?? '');
1703
1706
  const deny = event.options?.find((option) => option.kind === 'deny');
1704
- const allow = event.options?.find((option) => option.kind === 'allow');
1707
+ const allow = primaryAllow(event.options);
1705
1708
  const label = decisionLabel(event);
1706
1709
  // A question is read whole (its options mean nothing without it); a permission's title says what the agent wants, two lines at most.
1707
1710
  const question = label === 'Answer needed';
@@ -1784,6 +1787,7 @@ const PendingDecision = React.memo(function PendingDecision({
1784
1787
  ref={option === allow ? primary : undefined}
1785
1788
  data-primary={option === allow || undefined}
1786
1789
  data-option
1790
+ data-lasting={(option.kind === 'allow' && option.scope === 'always') || undefined}
1787
1791
  size="sm"
1788
1792
  variant={option === allow ? 'primary' : 'outline'}
1789
1793
  disabled={busy}
@@ -2097,10 +2101,10 @@ export function DecisionDock({
2097
2101
  onClick={() => {
2098
2102
  const row = document.querySelector<HTMLElement>(`[data-decision-row="${event.seq}"]`);
2099
2103
  row?.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
2100
- // Its allow option, else its first one (a question's).
2104
+ // Its allow option, else its first one (a question's) that is not a lasting grant (plugins#171).
2101
2105
  (
2102
2106
  row?.querySelector<HTMLElement>('[data-primary]') ??
2103
- row?.querySelector<HTMLElement>('[data-option]')
2107
+ row?.querySelector<HTMLElement>('[data-option]:not([data-lasting])')
2104
2108
  )?.focus({ preventScroll: true });
2105
2109
  }}
2106
2110
  >
@@ -2110,7 +2114,7 @@ export function DecisionDock({
2110
2114
  </section>
2111
2115
  );
2112
2116
  const deny = event.options?.find((option) => option.kind === 'deny');
2113
- const allow = event.options?.find((option) => option.kind === 'allow');
2117
+ const allow = primaryAllow(event.options);
2114
2118
  const questions = questionsAsked(event);
2115
2119
  if (questions)
2116
2120
  return (
package/delegations.ts CHANGED
@@ -578,30 +578,36 @@ const viewOf = (each: Delegation) => ({
578
578
  });
579
579
 
580
580
  const flag = z.boolean().optional();
581
+ /** An optional field an agent may send blank (`""`): blank is left out, so it takes its default (#199). */
582
+ const optional = <T extends z.ZodType>(schema: T) =>
583
+ z.preprocess(
584
+ (value) => (typeof value === 'string' && value.trim() === '' ? undefined : value),
585
+ schema.optional(),
586
+ );
581
587
  const delegateBody = z.strictObject({
582
588
  from: z.string().min(1),
583
589
  prompt: z.string().trim().min(1).max(PROMPT_MAX),
584
- title: z.string().trim().min(1).max(200).optional(),
585
- role: z.enum(ROLES).optional(),
590
+ title: optional(z.string().trim().min(1).max(200)),
591
+ role: optional(z.enum(ROLES)),
586
592
  target: z
587
593
  .strictObject({
588
- profile: z.string().min(1).optional(),
589
- model: z.string().min(1).optional(),
590
- effort: z.string().min(1).optional(),
594
+ profile: optional(z.string().min(1)),
595
+ model: optional(z.string().min(1)),
596
+ effort: optional(z.string().min(1)),
591
597
  options: z.strictObject({ plan: flag, auto: flag }).optional(),
592
- project: z.string().min(1).optional(),
598
+ project: optional(z.string().min(1)),
593
599
  })
594
600
  .optional(),
595
- mode: z.string().min(1).optional(),
596
- interaction: z.enum(['default', 'plan']).optional(),
597
- isolation: z.enum(['shared', 'worktree']).optional(),
601
+ mode: optional(z.string().min(1)),
602
+ interaction: optional(z.enum(['default', 'plan'])),
603
+ isolation: optional(z.enum(['shared', 'worktree'])),
598
604
  worktree: z
599
605
  .strictObject({
600
606
  plugins: z.array(z.string().min(1)).min(1).max(50),
601
- branch: z.string().trim().min(1).max(100).optional(),
607
+ branch: optional(z.string().trim().min(1).max(100)),
602
608
  })
603
609
  .optional(),
604
- wait: z.enum(['async', 'wait']).optional(),
610
+ wait: optional(z.enum(['async', 'wait'])),
605
611
  timeoutMs: z.number().int().min(0).optional(),
606
612
  clientRequestId: z.string().min(1).max(200),
607
613
  });
@@ -1814,6 +1820,9 @@ export function createDelegations<V extends Value>({
1814
1820
  * before it. */
1815
1821
  const check = (id: string) =>
1816
1822
  serial(id, async () => {
1823
+ // After its writes asked before: the record of the turn that just ended (`lastTurn`) lands before its delegation
1824
+ // ends, so a delegation never ends on a child whose turn shows no end yet.
1825
+ await written(id);
1817
1826
  if (running.has(id)) return;
1818
1827
  const found = await get(id);
1819
1828
  const parent = found?.value.parent;
package/git.ts CHANGED
@@ -236,8 +236,16 @@ export const within = ({ top, prefix }: Repository, folder: string, path: string
236
236
  const PATCH = ['--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
237
237
  const QUOTE = ['-c', 'core.quotePath=false'];
238
238
 
239
- /** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. */
240
- export const diffOf = async (run: Run, top: string, files: string[], max: number) => {
239
+ /** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. An
240
+ * untracked file `sizeOf` (bytes, from its path relative to `top`) puts past `max`, or whose size it does not know, is
241
+ * one placeholder line: git is never asked for its patch (plugins#145). ponytail: the tracked part has no such cap. */
242
+ export const diffOf = async (
243
+ run: Run,
244
+ top: string,
245
+ files: string[],
246
+ max: number,
247
+ sizeOf: (path: string) => Promise<number | undefined>,
248
+ ) => {
241
249
  if (!files.length) return '';
242
250
  // `diff-index`, not `diff`: `diff` refreshes the index of a file whose stat moved (a `touch`), rewriting it through
243
251
  // `index.lock` even under `GIT_OPTIONAL_LOCKS=0`, and the session's agent's own `git add` then fails on that lock.
@@ -253,6 +261,12 @@ export const diffOf = async (run: Run, top: string, files: string[], max: number
253
261
  ]);
254
262
  for (const path of listed.stdout.split('\0').filter(Boolean)) {
255
263
  if (text.length > max) break;
264
+ const size = await sizeOf(path);
265
+ if (size === undefined || size > max) {
266
+ const what = size === undefined ? 'of unknown size' : `of ${size} bytes`;
267
+ text += `diff --git a/${path} b/${path}\nnew file ${what}, not shown … [truncated]\n`;
268
+ continue;
269
+ }
256
270
  const added = await run(top, [...QUOTE, 'diff', ...PATCH, '--no-index', '--', '/dev/null', path]);
257
271
  text += added.stdout;
258
272
  }
@@ -260,7 +274,8 @@ export const diffOf = async (run: Run, top: string, files: string[], max: number
260
274
  };
261
275
 
262
276
  /** Commits exactly `files` in `top` (their current content, deletions included; nothing else staged goes in), with
263
- * `message` and the trailer `Bridge-Session: <session>`; resolves to the new commit's sha. */
277
+ * `message` and the trailer `Bridge-Session: <session>`; resolves to the new commit's sha, the files committed and the
278
+ * nested repositories `left` out. */
264
279
  export const commit = async (
265
280
  run: Run,
266
281
  top: string,
@@ -270,11 +285,19 @@ export const commit = async (
270
285
  ) => {
271
286
  // `commit --only` takes a tracked path's content from the disk, a deletion included (even one staged, as the old
272
287
  // side of a `git mv`, which `add` would refuse as matching no file); only an untracked one needs adding first.
273
- const untracked = (
288
+ const listed = (
274
289
  await run(top, ['ls-files', '--others', '--exclude-standard', '-z', '--', ...files])
275
290
  ).stdout
276
291
  .split('\0')
277
292
  .filter(Boolean);
293
+ // git lists a nested repository (and only one) as a folder, `sub/`: `add` would fail on an empty one and make a
294
+ // gitlink of another; it stays out of the commit (plugins#145).
295
+ const nested = new Set(listed.filter((path) => path.endsWith('/')));
296
+ const untracked = listed.filter((path) => !nested.has(path));
297
+ const left = files.filter((file) => nested.has(file) || nested.has(`${file}/`));
298
+ const kept = files.filter((file) => !left.includes(file));
299
+ // `commit --only` with no path would commit everything staged.
300
+ if (!kept.length) throw new Error(`nothing to commit: ${left.join(', ')} are nested repositories`);
278
301
  if (untracked.length) {
279
302
  const added = await run(top, ['add', '--', ...untracked]);
280
303
  if (added.code !== 0) throw new Error(`git add failed: ${added.stderr.trim()}`);
@@ -287,8 +310,8 @@ export const commit = async (
287
310
  '--trailer',
288
311
  `Bridge-Session: ${session}`,
289
312
  '--',
290
- ...files,
313
+ ...kept,
291
314
  ]);
292
315
  if (done.code !== 0) throw new Error(`git commit failed: ${(done.stderr || done.stdout).trim()}`);
293
- return (await run(top, ['rev-parse', 'HEAD'])).stdout.trim();
316
+ return { sha: (await run(top, ['rev-parse', 'HEAD'])).stdout.trim(), files: kept, left };
294
317
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/sessions",
3
- "version": "0.0.21",
3
+ "version": "0.0.27",
4
4
  "license": "MIT",
5
5
  "description": "Conversations with agents, in the workspace or in a project, through the Profile.",
6
6
  "keywords": [
@@ -1027,6 +1027,6 @@
1027
1027
  },
1028
1028
  "releaseStage": "dev",
1029
1029
  "engines": {
1030
- "bridge": ">=0.0.1-nightly.20261117.1"
1030
+ "bridge": ">=0.0.1-nightly.20261118.1"
1031
1031
  }
1032
1032
  }
@@ -211,9 +211,18 @@ export function evaluate(watch: WatchMemory, read: Read, now: number): Report {
211
211
  };
212
212
  }
213
213
 
214
+ /** A whole Markdown autolink, `<scheme:…>` or `<local@domain>`, never an HTML tag that holds a `:` or an `@`. */
215
+ const AUTOLINK = /^<(?:[a-z][\w+.-]*:[^\s<>"']*|[^\s<>"'@/]+@[^\s<>"'@]+)>$/i;
214
216
  const snippet = (body: string) => {
215
217
  const text = body
216
218
  .replaceAll(/<!--[\s\S]*?-->/g, ' ')
219
+ // A bot's HTML (`<details><summary>…`) quoted as its text (plugins#148); code (odd parts) is kept, and an autolink
220
+ // (`<https://…>`, `<user@host>`) too.
221
+ .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/)
222
+ .map((part, index) =>
223
+ index % 2 ? part : part.replaceAll(/<\/?[a-z][^<>]*>/gi, (tag) => (AUTOLINK.test(tag) ? tag : ' ')),
224
+ )
225
+ .join('')
217
226
  .replaceAll(/\s+/g, ' ')
218
227
  .trim();
219
228
  if (text.length <= SNIPPET) return text;
package/server.ts CHANGED
@@ -462,6 +462,7 @@ const session = z.strictObject({
462
462
  id: z.string(),
463
463
  label: z.string(),
464
464
  kind: z.enum(['allow', 'deny', 'other']),
465
+ scope: z.enum(['once', 'always']).optional(),
465
466
  }),
466
467
  ),
467
468
  tool: z.string().optional(),
@@ -727,10 +728,16 @@ const modeBody = z.strictObject({
727
728
  harness: z.string().min(1).optional(),
728
729
  });
729
730
  const effortBody = z.strictObject({ effort: z.string().min(1) });
731
+ /** A message's text as the agent gets it: blank is empty, a slash command is trimmed as it always was, any other text
732
+ * keeps its own whitespace (an indented snippet's first line stays indented, #200). */
733
+ const messageText = (text: string) => {
734
+ const trimmed = text.trim();
735
+ return !trimmed || trimmed.startsWith('/') ? trimmed : text;
736
+ };
730
737
  /** A message: its text, its images; one of them at least. */
731
738
  const turnBody = z
732
739
  .strictObject({
733
- text: z.string().trim(),
740
+ text: z.string().transform(messageText),
734
741
  attachments: z.array(attachment).max(ATTACHMENTS_MAX).optional(),
735
742
  // Bridge's own words (the host telling the agent how a change it asked for went), never the user's.
736
743
  from: z.literal('bridge').optional(),
@@ -4496,13 +4503,24 @@ export async function apply(ctx: Context, config?: unknown) {
4496
4503
  if (folder === undefined) return undefined;
4497
4504
  const head = await run(folder, ['rev-parse', '--abbrev-ref', 'HEAD']);
4498
4505
  const branch = head.code === 0 ? head.stdout.trim() : '';
4499
- // Detached, or the default branch: no pull request of its own.
4500
- const origin = (await run(folder, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])).stdout
4506
+ if (!branch || branch === 'HEAD') return undefined;
4507
+ // The branch's upstream remote, else `origin`, else the only one (as the host's Branches, plugins#148).
4508
+ const tracked = (await run(folder, ['config', '--get', `branch.${branch}.remote`])).stdout.trim();
4509
+ const names = (await run(folder, ['remote'])).stdout.split('\n').filter(Boolean);
4510
+ const name = names.includes(tracked)
4511
+ ? tracked
4512
+ : names.includes('origin')
4513
+ ? 'origin'
4514
+ : names.length === 1
4515
+ ? names[0]!
4516
+ : undefined;
4517
+ if (name === undefined) return undefined;
4518
+ // The default branch: no pull request of its own.
4519
+ const base = (await run(folder, ['symbolic-ref', '--short', `refs/remotes/${name}/HEAD`])).stdout
4501
4520
  .trim()
4502
- .replace(/^origin\//, '');
4503
- if (!branch || branch === 'HEAD' || branch === origin || branch === 'main' || branch === 'master')
4504
- return undefined;
4505
- const remote = await run(folder, ['remote', 'get-url', 'origin']);
4521
+ .slice(name.length + 1);
4522
+ if (branch === base || branch === 'main' || branch === 'master') return undefined;
4523
+ const remote = await run(folder, ['remote', 'get-url', name]);
4506
4524
  return remote.code === 0 && remote.stdout.trim()
4507
4525
  ? { branch, remote: await resolveRemote(remote.stdout.trim(), (alias) => hostOf(folder, alias)) }
4508
4526
  : undefined;
@@ -4569,9 +4587,15 @@ export async function apply(ctx: Context, config?: unknown) {
4569
4587
 
4570
4588
  // Scheduled prompts (`sessions.prompt`): the scheduler's tasks own the schedule and call this action with a session
4571
4589
  // and a prompt. A run starts a turn or waits in the queue, marked with its task.
4590
+ // Required (blank is missing), kept as written: `messageText`.
4591
+ const scheduledPrompt = z
4592
+ .string()
4593
+ .max(PROMPT_MAX)
4594
+ .refine((text) => text.trim() !== '', 'is required')
4595
+ .transform(messageText);
4572
4596
  const promptInput = z.strictObject({
4573
4597
  session: z.string().min(1),
4574
- prompt: z.string().trim().min(1).max(PROMPT_MAX),
4598
+ prompt: scheduledPrompt,
4575
4599
  });
4576
4600
  /** A refused action input, named by its first wrong field (`prompt: is required`), so the form says it under it. */
4577
4601
  const inputRefusal = (error: z.ZodError) => {
@@ -4609,7 +4633,7 @@ export async function apply(ctx: Context, config?: unknown) {
4609
4633
  effort: z.string().trim().min(1).optional(),
4610
4634
  mode: z.string().trim().min(1).optional(),
4611
4635
  title: z.string().trim().max(200).optional(),
4612
- prompt: z.string().trim().min(1).max(PROMPT_MAX),
4636
+ prompt: scheduledPrompt,
4613
4637
  });
4614
4638
  const parseStart = (input: unknown) => {
4615
4639
  const parsed = startInput.safeParse(input);
@@ -5761,7 +5785,13 @@ export async function apply(ctx: Context, config?: unknown) {
5761
5785
  files: files.map((path) => ({ path, pending: state.has(path) })),
5762
5786
  commits: value.commits ?? [],
5763
5787
  shared: await sharing(id, top, state, files),
5764
- diff: await diffOf(run, top, pending, DIFF_MAX),
5788
+ diff: await diffOf(
5789
+ run,
5790
+ top,
5791
+ pending,
5792
+ DIFF_MAX,
5793
+ async (path) => (await ctx.fs.stat(ctx, join(top, path)).catch(() => undefined))?.size,
5794
+ ),
5765
5795
  };
5766
5796
  },
5767
5797
  });
@@ -5802,16 +5832,17 @@ export async function apply(ctx: Context, config?: unknown) {
5802
5832
  `other sessions changed these files too: ${[...new Set(shared.flatMap((each) => each.files))].join(', ')}; commit with force to take their changes too`,
5803
5833
  409,
5804
5834
  );
5805
- const sha = await commit(run, top, files, message, id);
5835
+ // A nested repository among them stays out, and pending: `left` says so (plugins#145).
5836
+ const { sha, files: committed, left } = await commit(run, top, files, message, id);
5806
5837
  const at = new Date().toISOString();
5807
- const entry = { sha, at, message, files };
5838
+ const entry = { sha, at, message, files: committed };
5808
5839
  await change(id, (now) => ({
5809
- ...release(now, files),
5840
+ ...release(now, committed),
5810
5841
  commits: [...(now.commits ?? []), entry],
5811
5842
  }));
5812
5843
  await syncSeq(id);
5813
5844
  append(id, 'commit', entry);
5814
- return { id, node, ...entry, shared };
5845
+ return { id, node, ...entry, shared, ...(left.length && { left }) };
5815
5846
  });
5816
5847
  commits.set(top, done);
5817
5848
  void done