@bridgebrew/sessions 0.0.21 → 0.0.23

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.
@@ -104,6 +104,9 @@ export function SessionDetails({
104
104
  const [picked, setPicked] = React.useState<Set<string>>(new Set());
105
105
  const [message, setMessage] = React.useState('');
106
106
  const [committing, setCommitting] = React.useState(false);
107
+ /** The nested repositories the last commit of `session` left out (plugins#145): another session's are not shown. */
108
+ const [left, setLeft] = React.useState<{ session: string; paths: string[] }>();
109
+ const leftOut = left?.session === session.id ? left.paths : [];
107
110
  /** Other sessions share the picked files: Commit asks again before it takes their changes. */
108
111
  const [confirming, setConfirming] = React.useState(false);
109
112
  const listId = React.useId();
@@ -167,13 +170,19 @@ export function SessionDetails({
167
170
  }
168
171
  setCommitting(true);
169
172
  setError('');
173
+ setLeft(undefined);
170
174
  try {
171
- await post('/commit', {
175
+ const done: unknown = await post('/commit', {
172
176
  id: session.id,
173
177
  message: message.trim(),
174
178
  files: [...picked],
175
179
  ...(confirming && { force: true }),
176
180
  });
181
+ const nested =
182
+ typeof done === 'object' && done !== null && 'left' in done && Array.isArray(done.left)
183
+ ? done.left.filter((path): path is string => typeof path === 'string')
184
+ : [];
185
+ setLeft({ session: session.id, paths: nested });
177
186
  setMessage('');
178
187
  onChanged();
179
188
  } catch (cause) {
@@ -405,6 +414,12 @@ export function SessionDetails({
405
414
  )}
406
415
  </>
407
416
  )}
417
+ {leftOut.length > 0 && (
418
+ <p role="status" className="text-xs text-warning">
419
+ Not committed: {leftOut.join(', ')} (
420
+ {leftOut.length === 1 ? 'a nested repository' : 'nested repositories'}).
421
+ </p>
422
+ )}
408
423
  {error && (
409
424
  <p role="alert" className="text-xs text-destructive">
410
425
  {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/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.23",
4
4
  "license": "MIT",
5
5
  "description": "Conversations with agents, in the workspace or in a project, through the Profile.",
6
6
  "keywords": [
@@ -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(),
@@ -4496,13 +4497,24 @@ export async function apply(ctx: Context, config?: unknown) {
4496
4497
  if (folder === undefined) return undefined;
4497
4498
  const head = await run(folder, ['rev-parse', '--abbrev-ref', 'HEAD']);
4498
4499
  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
4500
+ if (!branch || branch === 'HEAD') return undefined;
4501
+ // The branch's upstream remote, else `origin`, else the only one (as the host's Branches, plugins#148).
4502
+ const tracked = (await run(folder, ['config', '--get', `branch.${branch}.remote`])).stdout.trim();
4503
+ const names = (await run(folder, ['remote'])).stdout.split('\n').filter(Boolean);
4504
+ const name = names.includes(tracked)
4505
+ ? tracked
4506
+ : names.includes('origin')
4507
+ ? 'origin'
4508
+ : names.length === 1
4509
+ ? names[0]!
4510
+ : undefined;
4511
+ if (name === undefined) return undefined;
4512
+ // The default branch: no pull request of its own.
4513
+ const base = (await run(folder, ['symbolic-ref', '--short', `refs/remotes/${name}/HEAD`])).stdout
4501
4514
  .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']);
4515
+ .slice(name.length + 1);
4516
+ if (branch === base || branch === 'main' || branch === 'master') return undefined;
4517
+ const remote = await run(folder, ['remote', 'get-url', name]);
4506
4518
  return remote.code === 0 && remote.stdout.trim()
4507
4519
  ? { branch, remote: await resolveRemote(remote.stdout.trim(), (alias) => hostOf(folder, alias)) }
4508
4520
  : undefined;
@@ -5761,7 +5773,13 @@ export async function apply(ctx: Context, config?: unknown) {
5761
5773
  files: files.map((path) => ({ path, pending: state.has(path) })),
5762
5774
  commits: value.commits ?? [],
5763
5775
  shared: await sharing(id, top, state, files),
5764
- diff: await diffOf(run, top, pending, DIFF_MAX),
5776
+ diff: await diffOf(
5777
+ run,
5778
+ top,
5779
+ pending,
5780
+ DIFF_MAX,
5781
+ async (path) => (await ctx.fs.stat(ctx, join(top, path)).catch(() => undefined))?.size,
5782
+ ),
5765
5783
  };
5766
5784
  },
5767
5785
  });
@@ -5802,16 +5820,17 @@ export async function apply(ctx: Context, config?: unknown) {
5802
5820
  `other sessions changed these files too: ${[...new Set(shared.flatMap((each) => each.files))].join(', ')}; commit with force to take their changes too`,
5803
5821
  409,
5804
5822
  );
5805
- const sha = await commit(run, top, files, message, id);
5823
+ // A nested repository among them stays out, and pending: `left` says so (plugins#145).
5824
+ const { sha, files: committed, left } = await commit(run, top, files, message, id);
5806
5825
  const at = new Date().toISOString();
5807
- const entry = { sha, at, message, files };
5826
+ const entry = { sha, at, message, files: committed };
5808
5827
  await change(id, (now) => ({
5809
- ...release(now, files),
5828
+ ...release(now, committed),
5810
5829
  commits: [...(now.commits ?? []), entry],
5811
5830
  }));
5812
5831
  await syncSeq(id);
5813
5832
  append(id, 'commit', entry);
5814
- return { id, node, ...entry, shared };
5833
+ return { id, node, ...entry, shared, ...(left.length && { left }) };
5815
5834
  });
5816
5835
  commits.set(top, done);
5817
5836
  void done