@bridgebrew/sessions 0.0.9 → 0.0.14

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.
@@ -1703,7 +1703,7 @@ const PendingDecision = React.memo(function PendingDecision({
1703
1703
  const deny = event.options?.find((option) => option.kind === 'deny');
1704
1704
  const allow = event.options?.find((option) => option.kind === 'allow');
1705
1705
  const label = decisionLabel(event);
1706
- // A question is read whole (its options mean nothing without it); a permission's title is its tool call's, one line.
1706
+ // 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
1707
  const question = label === 'Answer needed';
1708
1708
  // Its questions (an agent's question tool), each drawn with its own words: no title above them.
1709
1709
  const questions = questionsAsked(event);
@@ -1732,7 +1732,7 @@ const PendingDecision = React.memo(function PendingDecision({
1732
1732
  <span
1733
1733
  data-title
1734
1734
  className={cn(
1735
- 'min-w-0 truncate text-secondary',
1735
+ 'line-clamp-2 min-w-0 break-words text-secondary',
1736
1736
  title !== undefined && asked === title && 'sr-only',
1737
1737
  )}
1738
1738
  >
package/git.ts CHANGED
@@ -98,9 +98,18 @@ export interface Repository {
98
98
  prefix: string;
99
99
  }
100
100
 
101
+ /** Past this size a file's fingerprint is its size and mtime, not its content: a turn's snapshot never reads a huge file
102
+ * whole (#112). ponytail: an edit of such a file that keeps both is not seen. */
103
+ const HASH_MAX = 16 * 1024 * 1024;
104
+
101
105
  /** The files of `top` that differ (read as `owner`) from `HEAD` (untracked ones included, ignored ones not), each with a fingerprint of
102
106
  * 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) => {
107
+ export const stateOf = async (
108
+ owner: Context,
109
+ run: Run,
110
+ top: string,
111
+ { hashMax = HASH_MAX }: { hashMax?: number } = {},
112
+ ) => {
104
113
  const { code, stdout } = await run(top, [
105
114
  'status',
106
115
  '--porcelain=v1',
@@ -116,17 +125,19 @@ export const stateOf = async (owner: Context, run: Run, top: string) => {
116
125
  .map((field) => field.slice(3));
117
126
  const state = new Map<string, string>();
118
127
  await Promise.all(
119
- paths.map(async (path) => state.set(path, await fingerprint(owner, join(top, path)))),
128
+ paths.map(async (path) => state.set(path, await fingerprint(owner, join(top, path), hashMax))),
120
129
  );
121
130
  return state;
122
131
  };
123
132
 
124
133
  /** Read through the host (`ctx.fs`) as `owner`. */
125
- const fingerprint = async (owner: Context, file: string) => {
134
+ const fingerprint = async (owner: Context, file: string, hashMax: number) => {
126
135
  try {
127
136
  const info = await owner.fs.stat(owner, file);
128
137
  if (!info) return 'deleted';
129
138
  if (!info.isFile) return `other:${info.mtimeMs}`;
139
+ // Never a SHA-1: a file that crosses the limit during a turn shows as changed.
140
+ if (info.size > hashMax) return `meta:${info.size}:${info.mtimeMs}`;
130
141
  return createHash('sha1')
131
142
  .update(await owner.fs.readFile(owner, file))
132
143
  .digest('hex');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridgebrew/sessions",
3
- "version": "0.0.9",
3
+ "version": "0.0.14",
4
4
  "license": "MIT",
5
5
  "description": "Conversations with agents, in the workspace or in a project, through the Profile.",
6
6
  "keywords": [
@@ -31,6 +31,10 @@
31
31
  "storage": {},
32
32
  "harness": {}
33
33
  },
34
+ "dataVersions": {
35
+ "sessions": 1,
36
+ "pins": 1
37
+ },
34
38
  "needs": {
35
39
  "fs": [
36
40
  "data",
@@ -1021,5 +1025,8 @@
1021
1025
  "cordis": "4.0.0-rc.11",
1022
1026
  "react": "19.3.0"
1023
1027
  },
1024
- "releaseStage": "dev"
1028
+ "releaseStage": "dev",
1029
+ "engines": {
1030
+ "bridge": ">=0.0.1-nightly.20261113.1"
1031
+ }
1025
1032
  }
package/server.ts CHANGED
@@ -828,6 +828,11 @@ const IDLE_CAP_MS = 4 * 3_600_000;
828
828
  * `continuationWindowMs` per session (bridge#212 S5). */
829
829
  const CONTINUATIONS = 3;
830
830
  const CONTINUATION_WINDOW_MS = 5 * 60_000;
831
+ /** Lines a failed history append left in a session's outbox are tried again after this, doubling each failure up to
832
+ * `FLUSH_RETRY_MAX_MS`, not only at the session's next line (an idle session kept them in memory until Bridge
833
+ * stopped, and its one last try was all that stood between the page and a lost line; plugins#93). */
834
+ const FLUSH_RETRY_MS = 2_000;
835
+ const FLUSH_RETRY_MAX_MS = 60_000;
831
836
  /** A turn its harness driver's reload cut is continued once that driver is registered again, checked this often, for
832
837
  * this long at most (past it, the next start of Sessions continues it). */
833
838
  const DRIVER_POLL_MS = 1_000;
@@ -847,6 +852,7 @@ export interface Options {
847
852
  pullRequestWatchMs?: number;
848
853
  pullRequestSyncMs?: number;
849
854
  branchNameMs?: number;
855
+ flushRetryMs?: number;
850
856
  }
851
857
  /** `config`'s positive number `key`, else `fallback`. */
852
858
  const optionOf = (config: unknown, key: keyof Options, fallback: number) => {
@@ -1017,6 +1023,8 @@ const glanceText = (glance: Glance | undefined, mode: string | undefined) => {
1017
1023
  ]
1018
1024
  : []),
1019
1025
  'Discover and act on Bridge with the `bridge` MCP tools (`search_plugins`, `plugin_details`, `get_settings`/`set_setting`, `bridge_routes`/`bridge_read`/`bridge_write`, `bridge_link`, `show_view`); the shell is for code and files.',
1026
+ // #116: an agent wrote its own Playwright script where the Browser plugin, not installed, did it.
1027
+ 'Before you build a workaround (a script of your own, a tool to install, a long detour), look for a plugin that does it: `search_plugins` with one word of what you need (`browser`, `database`…; every word given must match, so try several one at a time) lists the plugins this workspace can install, not only the installed ones. One that is not installed: say so to the user and propose it with `install_plugin`: it installs, or becomes a request the user approves in one click.',
1020
1028
  ].join('\n');
1021
1029
  };
1022
1030
 
@@ -1138,6 +1146,7 @@ export async function apply(ctx: Context, config?: unknown) {
1138
1146
  const driverPollMs = optionOf(config, 'driverPollMs', DRIVER_POLL_MS);
1139
1147
  const driverWaitMs = optionOf(config, 'driverWaitMs', DRIVER_WAIT_MS);
1140
1148
  const branchNameMs = optionOf(config, 'branchNameMs', BRANCH_NAME_MS);
1149
+ const flushRetryMs = optionOf(config, 'flushRetryMs', FLUSH_RETRY_MS);
1141
1150
  // Cordis unloads independent effects in parallel. Group each storage release after the same
1142
1151
  // drain, so turn finalization can still update objects as well as append its closing history.
1143
1152
  let drain = async () => {};
@@ -1922,7 +1931,7 @@ export async function apply(ctx: Context, config?: unknown) {
1922
1931
  /** The running turns: `take` removes an open decision (`false` when it is not open), `record` stores its answer
1923
1932
  * (`null` with `expired`: no answer reached the agent), `expire` both for a decision past its `expiresAt`; `abort` closes the turn as this plugin disposes; `stop` closes
1924
1933
  * it `interrupted` while it is not prompting yet (its harness session still opening: an agent that never answers
1925
- * would otherwise hold the session busy). */
1934
+ * would otherwise hold the session busy), or with `force` while prompting (its agent could not be asked to stop). */
1926
1935
  const turns = new Map<
1927
1936
  string,
1928
1937
  {
@@ -1930,7 +1939,7 @@ export async function apply(ctx: Context, config?: unknown) {
1930
1939
  record: (decision: string, option: Answer, expired?: boolean, by?: string) => void;
1931
1940
  expire: (decision: string) => void;
1932
1941
  abort: () => void;
1933
- stop: () => void;
1942
+ stop: (force?: boolean) => void;
1934
1943
  /** Puts a message into this turn (bridge#212 S6): `unavailable` when its harness cannot steer, `declined` when the
1935
1944
  * turn cannot take it now (its agent not prompted yet, stopping, ended, or the agent said no), `steered` once the
1936
1945
  * agent took it, its `user/message {steered: true}` written where it entered the turn. */
@@ -2140,8 +2149,31 @@ export async function apply(ctx: Context, config?: unknown) {
2140
2149
  );
2141
2150
  return chosen?.efforts?.find((each) => each.id === effort);
2142
2151
  };
2152
+ /** Per session, the timer of the next try after a failed flush, and how many failed in a row. */
2153
+ const flushRetries = new Map<string, { timer: ReturnType<typeof setTimeout>; failures: number }>();
2154
+ const clearFlushRetry = (id: string) => {
2155
+ const retry = flushRetries.get(id);
2156
+ if (!retry) return;
2157
+ clearTimeout(retry.timer);
2158
+ flushRetries.delete(id);
2159
+ };
2160
+ /** After a failed flush of `id`: its next try, `flushRetryMs` doubled per failure in a row, up to the cap. */
2161
+ const scheduleFlushRetry = (id: string) => {
2162
+ if (disposed) return;
2163
+ const failures = (flushRetries.get(id)?.failures ?? 0) + 1;
2164
+ clearFlushRetry(id);
2165
+ const timer = setTimeout(
2166
+ () => {
2167
+ flushRetries.delete(id);
2168
+ void queueFlush(id);
2169
+ },
2170
+ Math.min(flushRetryMs * 2 ** (failures - 1), FLUSH_RETRY_MAX_MS),
2171
+ );
2172
+ timer.unref?.();
2173
+ flushRetries.set(id, { timer, failures });
2174
+ };
2143
2175
  /** Stores session `id`'s outbox in one append, `after` the `seq` before its first line; on a failure (logged) the
2144
- * lines stay for the next try. */
2176
+ * lines stay for the next try, which a timer brings (`scheduleFlushRetry`) when no new line does. */
2145
2177
  const flush = async (id: string) => {
2146
2178
  const pending = outbox.get(id);
2147
2179
  if (!pending?.length) return;
@@ -2155,6 +2187,7 @@ export async function apply(ctx: Context, config?: unknown) {
2155
2187
  );
2156
2188
  pending.splice(0, batch.length);
2157
2189
  if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
2190
+ clearFlushRetry(id);
2158
2191
  } catch (error) {
2159
2192
  ctx
2160
2193
  .logger('sessions')
@@ -2171,6 +2204,7 @@ export async function apply(ctx: Context, config?: unknown) {
2171
2204
  if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
2172
2205
  }
2173
2206
  }
2207
+ if (pending.length) scheduleFlushRetry(id);
2174
2208
  }
2175
2209
  };
2176
2210
  /** Queues `flush(id)` on session `id`'s chain, after its steps queued before. */
@@ -2224,6 +2258,7 @@ export async function apply(ctx: Context, config?: unknown) {
2224
2258
  // still in an outbox get one last try. The storage owner's grouped effects release only after this drain.
2225
2259
  drain = async () => {
2226
2260
  disposed = true;
2261
+ for (const id of [...flushRetries.keys()]) clearFlushRetry(id);
2227
2262
  for (const id of [...idleClose.keys()]) clearIdle(id);
2228
2263
  for (const turn of [...turns.values()]) turn.abort();
2229
2264
  for (const each of namings.values()) each.stop.abort('disposed');
@@ -2969,21 +3004,35 @@ export async function apply(ctx: Context, config?: unknown) {
2969
3004
  },
2970
3005
  });
2971
3006
 
2972
- /** Stops session `id` as the user's Stop does: its running turn asked to stop, its queue held. */
2973
3007
  /** How many times the user stopped each session, in memory (a watch asked before a Stop does not start after it). */
2974
3008
  const stopped = new Map<string, number>();
3009
+ /** Stops session `id`'s running turn: asked to its agent; when the agent cannot be asked (its interrupt rejects, a
3010
+ * closed query), the turn ends interrupted anyway and its harness session is closed, the next message opening a new
3011
+ * one. Never rejects. */
3012
+ const stopTurn = async (id: string) => {
3013
+ stopping.add(id);
3014
+ turns.get(id)?.stop();
3015
+ await open
3016
+ .get(id)
3017
+ ?.interrupt()
3018
+ .catch((error: unknown) => {
3019
+ log(`session ${id}: its agent not interrupted`)(error);
3020
+ turns.get(id)?.stop(true);
3021
+ void drop(id);
3022
+ });
3023
+ };
3024
+ /** Stops session `id` as the user's Stop does: its running turn asked to stop, its queue held. Never rejects: a Stop
3025
+ * goes on to its subtree whatever failed here (logged). */
2975
3026
  const stopSession = async (id: string) => {
2976
3027
  halt(id);
2977
3028
  stopNaming(id);
2978
3029
  stopped.set(id, (stopped.get(id) ?? 0) + 1);
3030
+ if (running.has(id)) await stopTurn(id);
2979
3031
  // The user's Stop ends its pull request's watch (research-086).
2980
- if ((await sessions.get(id))?.value.pullRequest?.watching)
2981
- await change(id, unwatched).catch(log(`session ${id}: watch not ended`));
2982
- if (running.has(id)) {
2983
- stopping.add(id);
2984
- turns.get(id)?.stop();
2985
- await open.get(id)?.interrupt();
2986
- }
3032
+ await sessions
3033
+ .get(id)
3034
+ .then((found) => found?.value.pullRequest?.watching && change(id, unwatched))
3035
+ .catch(log(`session ${id}: watch not ended`));
2987
3036
  };
2988
3037
  ctx.router.route(ctx, {
2989
3038
  method: 'POST',
@@ -3345,9 +3394,14 @@ export async function apply(ctx: Context, config?: unknown) {
3345
3394
  );
3346
3395
  };
3347
3396
  /** Adds `item` last in session `id`'s queue (`first`: first), its lock held. Its children's results and questions
3348
- * waiting there are beyond the limit: only the messages count. */
3397
+ * waiting there are beyond the limit: only the messages count. A scheduled task's prompt while one of that task
3398
+ * still waits there adds none: the waiting one is returned (#113). */
3349
3399
  const push = async (id: string, item: NonNullable<Session['queue']>[number], first = false) => {
3400
+ let waiting: typeof item | undefined;
3350
3401
  await change(id, (now) => {
3402
+ waiting =
3403
+ item.scheduled && now.queue?.find((each) => each.scheduled?.id === item.scheduled!.id);
3404
+ if (waiting) return now;
3351
3405
  const messages = (now.queue ?? []).filter((each) => !each.delegations && !each.questions);
3352
3406
  if (messages.length >= QUEUE_LIMIT)
3353
3407
  throw refused(
@@ -3357,18 +3411,16 @@ export async function apply(ctx: Context, config?: unknown) {
3357
3411
  );
3358
3412
  return { ...now, queue: first ? [item, ...(now.queue ?? [])] : [...(now.queue ?? []), item] };
3359
3413
  });
3414
+ if (waiting) return waiting;
3360
3415
  emit(id, { type: 'queue' });
3361
3416
  return item;
3362
3417
  };
3363
3418
  /** Stops session `id`'s running turn to send its queue's first message at once, when that turn ends. */
3364
3419
  const restartTurn = (id: string) => {
3420
+ // No turn left to stop: flags set now would cut the next turn before its prompt (#105).
3421
+ if (!running.has(id)) return;
3365
3422
  sendNow.add(id);
3366
- stopping.add(id);
3367
- turns.get(id)?.stop();
3368
- void open
3369
- .get(id)
3370
- ?.interrupt()
3371
- .catch(log(`session ${id}: its turn not stopped`));
3423
+ void stopTurn(id);
3372
3424
  };
3373
3425
  /** A new message: it starts a turn when the session is free; while one runs, `delivery` says what it does
3374
3426
  * (bridge#212 S6, `prompt_session`'s): `queue` (the default) goes last in the queue, a turn of its own after the
@@ -3424,10 +3476,16 @@ export async function apply(ctx: Context, config?: unknown) {
3424
3476
  ...(attachments.length && { attachments }),
3425
3477
  ...options,
3426
3478
  };
3427
- if (delivery !== 'restart') return { ok: true, queued: await push(id, item) };
3479
+ if (delivery !== 'restart') {
3480
+ const queued = await push(id, item);
3481
+ // A scheduled task's prompt already waiting: this one added none.
3482
+ return { ok: true, queued, ...(queued !== item && { waiting: true as const }) };
3483
+ }
3428
3484
  const queued = await push(id, item, true);
3429
3485
  unhalt(id);
3430
- restartTurn(id);
3486
+ // The turn may have ended during the write: then the message starts a turn of its own, after this lock.
3487
+ if (running.has(id)) restartTurn(id);
3488
+ else void dequeue(id).catch(log(`session ${id}: restart not sent`));
3431
3489
  return { ok: true, queued, restarted: true };
3432
3490
  };
3433
3491
  return serial(found.id, () =>
@@ -3880,8 +3938,8 @@ export async function apply(ctx: Context, config?: unknown) {
3880
3938
  aborted = true;
3881
3939
  finish({ reason: 'interrupted', message: 'Sessions stopped during this turn' });
3882
3940
  },
3883
- stop: () => {
3884
- if (!prompting) finish({ reason: 'interrupted' });
3941
+ stop: (force) => {
3942
+ if (force || !prompting) finish({ reason: 'interrupted' });
3885
3943
  },
3886
3944
  steerable: () => !!agent?.steer && steerOpen(),
3887
3945
  steer: async (message, attachments, options) => {
@@ -4641,20 +4699,22 @@ export async function apply(ctx: Context, config?: unknown) {
4641
4699
  );
4642
4700
  // Never a steer: no turn running starts one; one running takes the prompt in its queue.
4643
4701
  const scheduled = { id: task.taskId, title: task.title };
4702
+ // One queued prompt per task (#113): a run while its previous prompt still waits adds none.
4703
+ const waits = { summary: "Its previous prompt is still waiting in the session's queue" };
4644
4704
  try {
4645
- await sendOrQueue(found, prompt, [], { scheduled });
4705
+ const sent = await sendOrQueue(found, prompt, [], { scheduled });
4706
+ if (sent && 'waiting' in sent) return waits;
4646
4707
  } catch (error) {
4647
4708
  const code = (error as { code?: unknown } | undefined)?.code;
4648
4709
  // A restart, or a Stop as it started: the message waits in its queue, never lost.
4649
4710
  if (code !== 'restart_pending' && code !== 'turn_stopped') throw error;
4650
- await serial(id, () =>
4651
- push(id, {
4652
- id: crypto.randomUUID(),
4653
- text: prompt,
4654
- at: new Date().toISOString(),
4655
- scheduled,
4656
- }),
4657
- );
4711
+ const item = {
4712
+ id: crypto.randomUUID(),
4713
+ text: prompt,
4714
+ at: new Date().toISOString(),
4715
+ scheduled,
4716
+ };
4717
+ if ((await serial(id, () => push(id, item))) !== item) return waits;
4658
4718
  }
4659
4719
  },
4660
4720
  });
@@ -5063,12 +5123,8 @@ export async function apply(ctx: Context, config?: unknown) {
5063
5123
  if (!chosen) throw refused('not_found', `no queued message ${item}`, 404);
5064
5124
  return { ...now, queue: [chosen, ...(queue ?? []).filter((each) => each !== chosen)] };
5065
5125
  });
5066
- if (running.has(found.id)) {
5067
- sendNow.add(found.id);
5068
- stopping.add(found.id);
5069
- turns.get(found.id)?.stop();
5070
- await open.get(found.id)?.interrupt();
5071
- } else await dequeue(found.id);
5126
+ if (running.has(found.id)) restartTurn(found.id);
5127
+ else await dequeue(found.id);
5072
5128
  return { ok: true };
5073
5129
  },
5074
5130
  });
@@ -5386,9 +5442,7 @@ export async function apply(ctx: Context, config?: unknown) {
5386
5442
  : (async () => {
5387
5443
  if (!running.has(id)) return;
5388
5444
  // Its queue is not held, unlike the user's Stop: the next message starts at once.
5389
- stopping.add(id);
5390
- turns.get(id)?.stop();
5391
- await open.get(id)?.interrupt();
5445
+ await stopTurn(id);
5392
5446
  })();
5393
5447
  void next.catch(log(`session ${id}: handoff turn not ended`));
5394
5448
  }, 0);