@bridgebrew/sessions 0.0.23 → 0.0.28

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.
@@ -1,7 +1,7 @@
1
1
  // A session's branch from its page (research-083): its Git button (`@bridge/session-ui/git-actions`) acts on its branch's
2
2
  // folder, and archiving the branch's last session offers to delete that folder (never one with work not committed or not pushed; the git branch
3
- // stays). Both go through the project's Branches routes (`/_bridge/host/branches/…`, `project-branches.ts`), as the
4
- // Branches screen does: the same checks, the owner's page.
3
+ // stays). Both go through the project plugin's Branches routes (`/<slug>/api/project/branches/…`, bridgebrew/bridge#557),
4
+ // as the Branches screen does: the same checks, the owner's page.
5
5
  // ponytail: cleanup is asked, never automatic (merged, inactive, unchanged): its rules are bridge#348.
6
6
  import * as React from 'react';
7
7
  import {
@@ -18,11 +18,15 @@ import {
18
18
  } from '@bridge/ui';
19
19
  import {
20
20
  GitActions,
21
- branchesRoute,
22
21
  useBranch,
23
22
  type BranchesAnswer,
23
+ type BranchesRoute,
24
24
  } from '@bridge/session-ui/git-actions';
25
25
 
26
+ /** The project plugin's Branches route of project `node` in workspace `slug`, or one of its actions. */
27
+ export const branchesRoute: BranchesRoute = (slug, node, action) =>
28
+ `/${encodeURIComponent(slug)}/api/project/branches${action ? `/${action}` : ''}?node=${encodeURIComponent(node)}`;
29
+
26
30
  const post = async (slug: string, node: string, action: string, body: Record<string, unknown>) =>
27
31
  readJson(
28
32
  await fetch(branchesRoute(slug, node, action), {
@@ -53,7 +57,7 @@ export function BranchActions({
53
57
  pullRequestOpen?: boolean;
54
58
  onGitAnswer?: () => void;
55
59
  }) {
56
- const [state, take] = useBranch(slug, node, branch, refresh);
60
+ const [state, take] = useBranch(slug, node, branch, refresh, branchesRoute);
57
61
  if (!state) return null;
58
62
  return (
59
63
  <GitActions
@@ -61,6 +65,7 @@ export function BranchActions({
61
65
  node={node}
62
66
  branch={pullRequestOpen && !state.prOpen ? { ...state, prOpen: true } : state}
63
67
  session={session}
68
+ route={branchesRoute}
64
69
  onAnswer={(answer) => {
65
70
  take(answer);
66
71
  onGitAnswer?.();
@@ -85,7 +90,7 @@ export const cleanupOf = async (
85
90
  node: string,
86
91
  branch: string,
87
92
  ): Promise<Cleanup | undefined> => {
88
- // The host's own answer: typed once where it is read.
93
+ // The project plugin's own answer: typed once where it is read.
89
94
  const view = (await readJson(
90
95
  await fetch(branchesRoute(slug, node), { cache: 'no-store' }),
91
96
  )) as BranchesAnswer;
@@ -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,
package/browser/index.tsx CHANGED
@@ -224,7 +224,7 @@ const useBranches = (slug: string, node: string, startNew = false) => {
224
224
  choose(undefined);
225
225
  if (node === 'root') return;
226
226
  fetch(
227
- `/_bridge/host/branches?workspace=${encodeURIComponent(slug)}&node=${encodeURIComponent(node)}`,
227
+ `/${encodeURIComponent(slug)}/api/project/branches?node=${encodeURIComponent(node)}`,
228
228
  { cache: 'no-store' },
229
229
  )
230
230
  .then((res) => (res.ok ? readJson(res) : undefined))
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/sessions",
3
- "version": "0.0.23",
3
+ "version": "0.0.28",
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.2"
1031
1031
  }
1032
1032
  }
package/server.ts CHANGED
@@ -229,6 +229,11 @@ const attachment = z.strictObject({
229
229
  size: z.number().int().positive(),
230
230
  });
231
231
  type Attachment = z.infer<typeof attachment>;
232
+ /** The project plugin's `projectBranches` service (bridgebrew/bridge#557), never imported: what Sessions uses of it. */
233
+ interface ProjectBranches {
234
+ newBranch(input: { node: string; name: string; existing?: boolean }): Promise<{ name: string; folder: string }>;
235
+ branchForPlugins(input: { plugins: string[]; name: string }): Promise<{ repository: string; name: string; folder: string }>;
236
+ }
232
237
  /** What the gallery keeps, by a file's extension: the images and videos a browser shows (never SVG: it would run). */
233
238
  const PIN_TYPES = {
234
239
  '.png': 'image/png',
@@ -728,10 +733,16 @@ const modeBody = z.strictObject({
728
733
  harness: z.string().min(1).optional(),
729
734
  });
730
735
  const effortBody = z.strictObject({ effort: z.string().min(1) });
736
+ /** A message's text as the agent gets it: blank is empty, a slash command is trimmed as it always was, any other text
737
+ * keeps its own whitespace (an indented snippet's first line stays indented, #200). */
738
+ const messageText = (text: string) => {
739
+ const trimmed = text.trim();
740
+ return !trimmed || trimmed.startsWith('/') ? trimmed : text;
741
+ };
731
742
  /** A message: its text, its images; one of them at least. */
732
743
  const turnBody = z
733
744
  .strictObject({
734
- text: z.string().trim(),
745
+ text: z.string().transform(messageText),
735
746
  attachments: z.array(attachment).max(ATTACHMENTS_MAX).optional(),
736
747
  // Bridge's own words (the host telling the agent how a change it asked for went), never the user's.
737
748
  from: z.literal('bridge').optional(),
@@ -1244,10 +1255,13 @@ export async function apply(ctx: Context, config?: unknown) {
1244
1255
  /** A new branch `name` of the project on `node` (research-083), made by the host as the Branches screen makes one
1245
1256
  * (its worktree under `.worktrees/`, installed); `name` numbered when taken. */
1246
1257
  const makeBranch = async (node: string, name: string, temporary = false) => {
1247
- const service = bridgeMcp();
1258
+ const service = projectBranches();
1248
1259
  const project = node === 'root' ? undefined : await folderOf(node);
1249
1260
  if (!service || project === undefined)
1250
- throw refused('branches_unavailable', `node ${node} has no branches here`);
1261
+ throw refused(
1262
+ 'branches_unavailable',
1263
+ service ? `node ${node} has no branches here` : 'branches need Projects 0.0.2 or later in this workspace: install or update it (Plugins)',
1264
+ );
1251
1265
  try {
1252
1266
  const made = await service.newBranch({ node, name: await freeBranch(run, project, name) });
1253
1267
  return { ...made, ...(temporary && { temporary: true as const }) };
@@ -1478,7 +1492,7 @@ export async function apply(ctx: Context, config?: unknown) {
1478
1492
  const kept =
1479
1493
  project !== undefined &&
1480
1494
  (await run(project, ['branch', '--list', branch.name])).stdout.trim() !== '';
1481
- const service = bridgeMcp();
1495
+ const service = projectBranches();
1482
1496
  if (!kept || !service)
1483
1497
  throw new Error(
1484
1498
  `branch ${branch.name} is gone: its folder ${branch.folder}${kept ? ' cannot be made again here' : ' and its git branch were deleted'}; start a new session`,
@@ -1832,6 +1846,16 @@ export async function apply(ctx: Context, config?: unknown) {
1832
1846
  /** The host's per-session MCP tokens: optional (not in `inject`), so a host without them still loads this plugin, its
1833
1847
  * sessions' MCP calls then running as `agent`. */
1834
1848
  const bridgeMcp = () => ctx.get('bridgeMcp', false) as Context['bridgeMcp'] | undefined;
1849
+ /** The project plugin's branches (bridgebrew/bridge#557): a session's branch and a child's are made there. */
1850
+ const projectBranches = () => {
1851
+ const service: unknown = ctx.get('projectBranches', false);
1852
+ return isRecord(service) &&
1853
+ typeof service.newBranch === 'function' &&
1854
+ typeof service.branchForPlugins === 'function'
1855
+ ? // oxlint-disable-next-line bridge/no-new-unchecked-cast -- its two functions checked above, project's own service
1856
+ (service as unknown as ProjectBranches)
1857
+ : undefined;
1858
+ };
1835
1859
  /** A new MCP token for session `id`, `undefined` without the service or when the host refused (logged): the session
1836
1860
  * then opens without one. Not claimed yet (`claim`). */
1837
1861
  const issueToken = async (id: string, worktree?: string) => {
@@ -4418,9 +4442,14 @@ export async function apply(ctx: Context, config?: unknown) {
4418
4442
  // A child's own worktree (S7): added by the host, as `stage_add` adds one.
4419
4443
  addWorktree: async (input) => {
4420
4444
  const service = bridgeMcp();
4445
+ const branches = projectBranches();
4421
4446
  if (!service) throw refused('worktrees_unavailable', 'this Bridge cannot add a worktree');
4447
+ if (!branches)
4448
+ throw refused('worktrees_unavailable', "a child's own branch needs Projects 0.0.2 or later in this workspace: install or update it (Plugins)");
4422
4449
  try {
4423
- return await service.addWorktree(input);
4450
+ // Its branch made by the project plugin, in the checkout the plugins run from; the stage chooses it.
4451
+ const made = await branches.branchForPlugins({ plugins: input.plugins, name: input.branch });
4452
+ return await service.addWorktree({ branch: made.name, plugins: input.plugins, existing: true });
4424
4453
  } catch (error) {
4425
4454
  throw refused('worktree_refused', error instanceof Error ? error.message : String(error));
4426
4455
  }
@@ -4581,9 +4610,15 @@ export async function apply(ctx: Context, config?: unknown) {
4581
4610
 
4582
4611
  // Scheduled prompts (`sessions.prompt`): the scheduler's tasks own the schedule and call this action with a session
4583
4612
  // and a prompt. A run starts a turn or waits in the queue, marked with its task.
4613
+ // Required (blank is missing), kept as written: `messageText`.
4614
+ const scheduledPrompt = z
4615
+ .string()
4616
+ .max(PROMPT_MAX)
4617
+ .refine((text) => text.trim() !== '', 'is required')
4618
+ .transform(messageText);
4584
4619
  const promptInput = z.strictObject({
4585
4620
  session: z.string().min(1),
4586
- prompt: z.string().trim().min(1).max(PROMPT_MAX),
4621
+ prompt: scheduledPrompt,
4587
4622
  });
4588
4623
  /** A refused action input, named by its first wrong field (`prompt: is required`), so the form says it under it. */
4589
4624
  const inputRefusal = (error: z.ZodError) => {
@@ -4621,7 +4656,7 @@ export async function apply(ctx: Context, config?: unknown) {
4621
4656
  effort: z.string().trim().min(1).optional(),
4622
4657
  mode: z.string().trim().min(1).optional(),
4623
4658
  title: z.string().trim().max(200).optional(),
4624
- prompt: z.string().trim().min(1).max(PROMPT_MAX),
4659
+ prompt: scheduledPrompt,
4625
4660
  });
4626
4661
  const parseStart = (input: unknown) => {
4627
4662
  const parsed = startInput.safeParse(input);