@bridgebrew/sessions 0.0.34 → 0.0.43
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.
- package/branch-name.ts +45 -0
- package/browser/branch-actions.tsx +26 -47
- package/browser/conversation.tsx +123 -3
- package/browser/details.tsx +408 -0
- package/browser/index.tsx +685 -497
- package/browser/mobile.tsx +118 -8
- package/browser/pull-request.tsx +9 -6
- package/browser/session-scheduled.tsx +6 -3
- package/browser/subagent-view.tsx +2 -2
- package/contract.ts +6 -0
- package/delegations.ts +6 -7
- package/package.json +51 -10
- package/server.ts +642 -236
- package/text.ts +9 -0
- package/browser/changes.tsx +0 -464
- package/git.ts +0 -318
package/server.ts
CHANGED
|
@@ -68,11 +68,20 @@
|
|
|
68
68
|
// `{ id, tags }` (replacing them; an empty list removes them), the agent's `tag_session` tool; `GET /sessions/tags` →
|
|
69
69
|
// `{ tags: [{ tag, count }] }`, the workspace's, most used first. `files`: what the session changed in its git
|
|
70
70
|
// repository, relative to its top, kept from each turn (see `run` below). `POST /sessions/changes` `{ id }` → its
|
|
71
|
-
// `repository`, `files` (`pending`: still uncommitted), `commits`, `shared`
|
|
72
|
-
// are some of its own) and the `diff` of its pending files
|
|
73
|
-
//
|
|
74
|
-
// `
|
|
75
|
-
//
|
|
71
|
+
// `repository`, `files` (`pending`: still uncommitted; `added`/`removed`, its line counts when known), `commits`, `shared`
|
|
72
|
+
// (the other sessions whose uncommitted files are some of its own) and the `diff` of its pending files (past 50 of them,
|
|
73
|
+
// none and `byFile: true`; cut short past 24 KiB, `cut: true`); `{ id, path }` → one of its files' `diff` (`cut: true` past 24 KiB too; refused
|
|
74
|
+
// `not_its_file` for any other path); `POST /sessions/lines` `{ id, path, from, to }` → `lines` from–to (1-based) of one
|
|
75
|
+
// of its files as it is now (the diff's folds; refused `not_its_file` as above, `outside_repository` for a link out of
|
|
76
|
+
// it, `too_large` past 1 MB); git through the optional `git` plugin (`@bridgebrew/git`, bridge-plugins#256): without it,
|
|
77
|
+
// `/sessions/changes` answers `{ repository: null, git: 'missing' }` and the page offers to install it; its answer also
|
|
78
|
+
// gives the repository's `branch` (`name`, `isDefault`, `remote`, `upstream`, `unpushed`), the `others` uncommitted files
|
|
79
|
+
// of the repository that are not the session's, and whether `github` is there;
|
|
80
|
+
// `POST /sessions/commit` `{ id, message, files?, force? }` commits its pending files (or `files`, its own only) with
|
|
81
|
+
// the trailer `Bridge-Session: <id>`, refused 409 `files_shared` when another session changed one of them too (`force` commits anyway), `nothing_to_commit`,
|
|
82
|
+
// `session_busy` while a turn runs, `not_a_repository`, `conflict` while a merge leaves one of them unresolved, `stale_snapshot`
|
|
83
|
+
// when another git moved the branch meanwhile; through an index of its own (`git`'s): the real index is untouched while
|
|
84
|
+
// the agent writes the message; one commit at a time per repository; kept in `commits` and as a
|
|
76
85
|
// `commit` line. Before each turn's message the agent reads, besides a first turn's target: the session's id and the
|
|
77
86
|
// workspace's tags while the session has none (with the workspace's MCP server only, which has `tag_session`), and the
|
|
78
87
|
// sessions whose uncommitted files it shares (`session_changes` reads them); on its first turn, how to show an image or a video (`<bridge_media>`).
|
|
@@ -147,10 +156,10 @@
|
|
|
147
156
|
// (`bridgeMcp`, research-011 D5; optional: none without it), in its `bridge` MCP server's environment (`BRIDGE_MCP_TOKEN`), so its tool calls run as
|
|
148
157
|
// `agent:<session id>`; revoked as soon as its agent exits (`exited`, for drivers that know it), or when the harness
|
|
149
158
|
// session is dropped (closed, failed, archived, or as this plugin disposes), a new one at each open.
|
|
150
|
-
import { basename, dirname, extname, isAbsolute, join } from 'node:path';
|
|
159
|
+
import { basename, dirname, extname, isAbsolute, join, relative, sep } from 'node:path';
|
|
151
160
|
import type { Context } from 'cordis';
|
|
152
161
|
import { z } from 'zod';
|
|
153
|
-
import { cutText, isRecord, oneLine } from './text.ts';
|
|
162
|
+
import { cutText, isRecord, oneLine, tailText } from './text.ts';
|
|
154
163
|
import type { SessionsService, SessionView, Shown } from './contract.ts';
|
|
155
164
|
import {
|
|
156
165
|
apply as applyView,
|
|
@@ -161,23 +170,8 @@ import {
|
|
|
161
170
|
used as usedViewComponents,
|
|
162
171
|
type Preview,
|
|
163
172
|
} from './views/library.ts';
|
|
164
|
-
import {
|
|
165
|
-
|
|
166
|
-
commit,
|
|
167
|
-
diffOf,
|
|
168
|
-
repositoryAt,
|
|
169
|
-
resolveRemote,
|
|
170
|
-
runner,
|
|
171
|
-
sshHostname,
|
|
172
|
-
stateOf,
|
|
173
|
-
type Repository,
|
|
174
|
-
within,
|
|
175
|
-
worktreesOf,
|
|
176
|
-
branchSlug,
|
|
177
|
-
freeBranch,
|
|
178
|
-
typedBranch,
|
|
179
|
-
BRANCH_EXAMPLE,
|
|
180
|
-
} from './git.ts';
|
|
173
|
+
import type { GitService, Repository } from '@bridgebrew/git/contract.ts';
|
|
174
|
+
import { branchSlug, typedBranch, BRANCH_EXAMPLE } from './branch-name.ts';
|
|
181
175
|
import { changeOf, type Change } from './diff.ts';
|
|
182
176
|
import { active, actsAs, createPeers, release } from './peers.ts';
|
|
183
177
|
import {
|
|
@@ -375,8 +369,9 @@ const subagent = z.strictObject({
|
|
|
375
369
|
});
|
|
376
370
|
/** The most sub-agents a session's record keeps, the newest. */
|
|
377
371
|
const SUBAGENTS_MAX = 20;
|
|
378
|
-
/** A message waiting in a session's queue, sent one per turn after the running one.
|
|
379
|
-
|
|
372
|
+
/** A message waiting in a session's queue, sent one per turn after the running one. Loose, as the contract's other
|
|
373
|
+
* `sessions` plugins keep it: a field one of them wrote stays through a write that spreads the item. */
|
|
374
|
+
const queueItem = z.looseObject({
|
|
380
375
|
id: z.string(),
|
|
381
376
|
text: z.string(),
|
|
382
377
|
at: z.string(),
|
|
@@ -395,7 +390,7 @@ const queueItem = z.strictObject({
|
|
|
395
390
|
// The session whose agent sent it (`prompt_session`).
|
|
396
391
|
sender: z.string().optional(),
|
|
397
392
|
});
|
|
398
|
-
const
|
|
393
|
+
const sessionShape = {
|
|
399
394
|
title: z.string(),
|
|
400
395
|
harness: z.string(),
|
|
401
396
|
/** The worktree of this workspace the session works in (research-045): its agent works in that git checkout, its
|
|
@@ -434,8 +429,9 @@ const session = z.strictObject({
|
|
|
434
429
|
keepActive: z.literal(true).optional(),
|
|
435
430
|
lastVisitedAt: z.string().optional(),
|
|
436
431
|
wokeAt: z.string().optional(),
|
|
432
|
+
// Loose, as the queue's items: a part the contract shares with the other `sessions` plugins.
|
|
437
433
|
lastTurn: z
|
|
438
|
-
.
|
|
434
|
+
.looseObject({
|
|
439
435
|
endedAt: z.string(),
|
|
440
436
|
reason: z.enum(['completed', 'interrupted', 'failed']),
|
|
441
437
|
by: z.literal('bridge').optional(),
|
|
@@ -459,11 +455,11 @@ const session = z.strictObject({
|
|
|
459
455
|
// message closes them.
|
|
460
456
|
openDecisions: z
|
|
461
457
|
.array(
|
|
462
|
-
z.
|
|
458
|
+
z.looseObject({
|
|
463
459
|
id: z.string(),
|
|
464
460
|
title: z.string(),
|
|
465
461
|
options: z.array(
|
|
466
|
-
z.
|
|
462
|
+
z.looseObject({
|
|
467
463
|
id: z.string(),
|
|
468
464
|
label: z.string(),
|
|
469
465
|
kind: z.enum(['allow', 'deny', 'other']),
|
|
@@ -504,8 +500,16 @@ const session = z.strictObject({
|
|
|
504
500
|
// Its pull request (research-086, `pull-requests.ts`), and the urls unlinked from it (never found by branch again).
|
|
505
501
|
pullRequest: pullRequestRecord.optional(),
|
|
506
502
|
pullRequestUnlinked: z.array(z.string()).optional(),
|
|
507
|
-
|
|
508
|
-
|
|
503
|
+
/** The turn id (`turn/start`'s `turn`) of the last turn whose agent answered (its first harness event): a turn a crash
|
|
504
|
+
* cut with that id is not sent again, even when the lines that showed it were lost (plugins#239). */
|
|
505
|
+
delivered: z.string().optional(),
|
|
506
|
+
};
|
|
507
|
+
/** The record as stored, declared to storage: the fields Sessions knows checked, any other kept (the contract: "a record
|
|
508
|
+
* keeps every field it does not know", another `sessions` plugin's). */
|
|
509
|
+
const session = z.looseObject(sessionShape);
|
|
510
|
+
/** What Sessions writes (`change` checks it): a top-level field it does not declare is refused. */
|
|
511
|
+
const ownSession = z.strictObject(sessionShape);
|
|
512
|
+
type Session = z.infer<typeof ownSession>;
|
|
509
513
|
type Subagent = z.infer<typeof subagent>;
|
|
510
514
|
/** A history line as stored: every type, the new ones too (`commit`, `peer/*`, …), each with its `time`; its `seq` is
|
|
511
515
|
* the log's `n`. */
|
|
@@ -546,11 +550,13 @@ interface DraftView {
|
|
|
546
550
|
}
|
|
547
551
|
/** How long a request to show a page waits for the page showing the session to answer. */
|
|
548
552
|
const OPEN_LINK_WAIT_MS = 5000;
|
|
549
|
-
/** What a watch stream carries: the stored lines, a line just appended,
|
|
550
|
-
* session asked the browser to open (`request`: the id its
|
|
553
|
+
/** What a watch stream carries: the stored lines, a line just appended, the lines its log holds (`saved`, every one up
|
|
554
|
+
* to `seq`), a live event, a queue change, or a page the session asked the browser to open (`request`: the id its
|
|
555
|
+
* answer names, `POST /sessions/open-link/answer`). */
|
|
551
556
|
type WatchMessage =
|
|
552
557
|
| { type: 'open-link'; path: string; turn?: string; request: string }
|
|
553
558
|
| { type: 'queue' }
|
|
559
|
+
| { type: 'saved'; seq: number }
|
|
554
560
|
| { type: 'stored'; event: Line }
|
|
555
561
|
| { type: 'live'; event: HarnessEvent | DraftView };
|
|
556
562
|
/** The in-flight part of a running turn: what is not (yet) a settled line. */
|
|
@@ -635,6 +641,17 @@ const createBody = z.strictObject({
|
|
|
635
641
|
/** The branch a session works on, as the agent reads it before each message (research-083). */
|
|
636
642
|
const branchText = ({ name, folder }: { name: string; folder: string }) =>
|
|
637
643
|
`<bridge_branch>\nYou work on git branch \`${name}\`, in its worktree ${folder} (your working directory): read and change files there only, never in the project's own folder above it, which is another branch. Its dependencies are installed.\n</bridge_branch>\n\n`;
|
|
644
|
+
/** A message that starts with an agent's command (`/review …`). */
|
|
645
|
+
const COMMAND = /^\/[\w:.-]+(?:\s|$)/;
|
|
646
|
+
/** What the agent gets: `preface` before `message`, except a command's first line, which stays first so that every
|
|
647
|
+
* agent runs it; the preface follows it after a blank line. */
|
|
648
|
+
const prefaced = (preface: string, message: string) => {
|
|
649
|
+
if (!preface || !COMMAND.test(message)) return preface + message;
|
|
650
|
+
const end = message.indexOf('\n');
|
|
651
|
+
return end < 0
|
|
652
|
+
? `${message}\n\n${preface.trimEnd()}`
|
|
653
|
+
: `${message.slice(0, end)}\n\n${preface}${message.slice(end + 1)}`;
|
|
654
|
+
};
|
|
638
655
|
/** A session's target as the agent reads it before the first message: one `key: value` line per field. */
|
|
639
656
|
const targetText = (value: Record<string, unknown>) => {
|
|
640
657
|
const lines = Object.entries(value).map(
|
|
@@ -733,11 +750,12 @@ const modeBody = z.strictObject({
|
|
|
733
750
|
harness: z.string().min(1).optional(),
|
|
734
751
|
});
|
|
735
752
|
const effortBody = z.strictObject({ effort: z.string().min(1) });
|
|
736
|
-
/** A message's text as the agent gets it: blank is empty, a
|
|
737
|
-
* keeps its own whitespace (an indented snippet's first line stays indented, #200
|
|
753
|
+
/** A message's text as the agent gets it: blank is empty, a leading command (`COMMAND`) is trimmed as it always was,
|
|
754
|
+
* any other text keeps its own whitespace (an indented snippet's first line stays indented, #200; a leading path such
|
|
755
|
+
* as `/Users/…` is no command, #253). */
|
|
738
756
|
const messageText = (text: string) => {
|
|
739
757
|
const trimmed = text.trim();
|
|
740
|
-
return !trimmed ||
|
|
758
|
+
return !trimmed || COMMAND.test(trimmed) ? trimmed : text;
|
|
741
759
|
};
|
|
742
760
|
/** A message: its text, its images; one of them at least. */
|
|
743
761
|
const turnBody = z
|
|
@@ -754,6 +772,34 @@ const QUEUE_LIMIT = 20;
|
|
|
754
772
|
/** The most characters of a scheduled prompt, and of a title made from it (its first line, cut there). */
|
|
755
773
|
const PROMPT_MAX = 20_000;
|
|
756
774
|
const TITLE_FROM_PROMPT = 60;
|
|
775
|
+
/** The composer's menus (`GET /sessions/files`, `GET /sessions/commands`): the most files a search answers, the most
|
|
776
|
+
* a folder without git is walked for, the names the walk skips; how long an agent's commands are waited for and kept. */
|
|
777
|
+
const MENU_FILES_MAX = 50;
|
|
778
|
+
const FILES_WALK_MAX = 5_000;
|
|
779
|
+
/** The most folder entries the files walk reads (folders and files alike). */
|
|
780
|
+
const WALK_ENTRIES_MAX = 20_000;
|
|
781
|
+
const WALK_SKIPPED = new Set(['.git', 'node_modules', '.bridge']);
|
|
782
|
+
const COMMANDS_MS = 15_000;
|
|
783
|
+
const COMMANDS_TTL_MS = 5 * 60_000;
|
|
784
|
+
type Command = Awaited<ReturnType<NonNullable<Context['harness']['commands']>>>[number];
|
|
785
|
+
/** The files of `files` whose path holds `query` (any case), those whose name starts with it first, then those whose
|
|
786
|
+
* name holds it, the shorter path first; at most `MENU_FILES_MAX`. */
|
|
787
|
+
export const matchingFiles = (files: string[], query: string) => {
|
|
788
|
+
const wanted = query.toLowerCase();
|
|
789
|
+
const rankOf = (path: string) => {
|
|
790
|
+
const lower = path.toLowerCase();
|
|
791
|
+
const name = lower.slice(lower.lastIndexOf('/') + 1);
|
|
792
|
+
return name.startsWith(wanted) ? 0 : name.includes(wanted) ? 1 : lower.includes(wanted) ? 2 : 3;
|
|
793
|
+
};
|
|
794
|
+
return files
|
|
795
|
+
.map((path) => ({ path, rank: rankOf(path) }))
|
|
796
|
+
.filter((each) => each.rank < 3)
|
|
797
|
+
.sort(
|
|
798
|
+
(a, b) => a.rank - b.rank || a.path.length - b.path.length || a.path.localeCompare(b.path),
|
|
799
|
+
)
|
|
800
|
+
.slice(0, MENU_FILES_MAX)
|
|
801
|
+
.map((each) => each.path);
|
|
802
|
+
};
|
|
757
803
|
const harnessQuery = z
|
|
758
804
|
.strictObject({ profile: z.string().min(1).optional(), harness: z.string().min(1).optional() })
|
|
759
805
|
.refine((input) => !!(input.profile ?? input.harness), 'Choose a Profile ID');
|
|
@@ -822,16 +868,36 @@ const viewActivateBody = z.strictObject({
|
|
|
822
868
|
plugin: z.string().trim().min(1),
|
|
823
869
|
});
|
|
824
870
|
const tagsBody = z.strictObject({ id: z.string().min(1), tags: z.array(z.string()).max(TAGS_MAX) });
|
|
825
|
-
const
|
|
871
|
+
const changesBody = z.strictObject({ id: z.string().min(1), path: z.string().min(1).optional() });
|
|
872
|
+
const openBody = z.strictObject({
|
|
873
|
+
id: z.string().min(1),
|
|
874
|
+
path: z.string().min(1).optional(),
|
|
875
|
+
line: z.number().int().min(1).optional(),
|
|
876
|
+
column: z.number().int().min(1).optional(),
|
|
877
|
+
});
|
|
878
|
+
const linesBody = z.strictObject({
|
|
879
|
+
id: z.string().min(1),
|
|
880
|
+
path: z.string().min(1),
|
|
881
|
+
from: z.number().int().min(1),
|
|
882
|
+
to: z.number().int().min(1),
|
|
883
|
+
});
|
|
826
884
|
const commitBody = z.strictObject({
|
|
827
885
|
id: z.string().min(1),
|
|
828
|
-
|
|
886
|
+
/** Empty or left out: the session's agent writes it from the conversation and the diff (`POST /sessions/write`). */
|
|
887
|
+
message: z.string().trim().max(10_000).optional(),
|
|
829
888
|
files: z.array(z.string().min(1)).optional(),
|
|
830
889
|
force: z.boolean().optional(),
|
|
831
890
|
});
|
|
832
891
|
/** The most files a session keeps (its newest); the most characters of a changes diff. */
|
|
833
892
|
const FILES_MAX = 1000;
|
|
834
893
|
const DIFF_MAX = 24 * 1024;
|
|
894
|
+
/** Past this many pending files, `POST /sessions/changes` gives each one's counts but no diff: one file's is read
|
|
895
|
+
* with `path` (the diff of so many is cut past `DIFF_MAX` anyway, most files then without theirs). */
|
|
896
|
+
const DIFF_FILES_MAX = 50;
|
|
897
|
+
/** The most other uncommitted files of a session's repository `POST /sessions/changes` names. */
|
|
898
|
+
const OTHERS_MAX = 50;
|
|
899
|
+
/** How long the agent may take to write a commit message left empty. */
|
|
900
|
+
const WRITE_MS = 120_000;
|
|
835
901
|
/** Between auto-settle checks: an hour. */
|
|
836
902
|
const SWEEP_MS = 3_600_000;
|
|
837
903
|
const DAY_MS = 86_400_000;
|
|
@@ -868,6 +934,8 @@ export interface Options {
|
|
|
868
934
|
pullRequestSyncMs?: number;
|
|
869
935
|
branchNameMs?: number;
|
|
870
936
|
flushRetryMs?: number;
|
|
937
|
+
/** How long the composer's `/` menu waits for an agent's commands. */
|
|
938
|
+
commandsMs?: number;
|
|
871
939
|
}
|
|
872
940
|
/** `config`'s positive number `key`, else `fallback`. */
|
|
873
941
|
const optionOf = (config: unknown, key: keyof Options, fallback: number) => {
|
|
@@ -1144,6 +1212,41 @@ const disabledMessage = (harness: string) =>
|
|
|
1144
1212
|
`harness ${harness} is disabled: turn on Enabled in its entry of Settings → Harnesses and Profiles (\`enabled: true\` in the harness plugin's \`harnesses\` setting) to use it`;
|
|
1145
1213
|
const refused = (code: string, message: string, status = 400) =>
|
|
1146
1214
|
Object.assign(new Error(message), { code, status, [Symbol.for('bridge.clientError')]: true });
|
|
1215
|
+
/** The status a refusal of the `git` service is answered with, by its code. */
|
|
1216
|
+
const GIT_STATUS: Record<string, number> = {
|
|
1217
|
+
not_a_repository: 409,
|
|
1218
|
+
invalid_path: 400,
|
|
1219
|
+
outside_repository: 403,
|
|
1220
|
+
not_found: 404,
|
|
1221
|
+
too_large: 400,
|
|
1222
|
+
nothing_to_commit: 409,
|
|
1223
|
+
nothing_written: 409,
|
|
1224
|
+
conflict: 409,
|
|
1225
|
+
stale_snapshot: 409,
|
|
1226
|
+
busy: 409,
|
|
1227
|
+
timeout: 504,
|
|
1228
|
+
// No code editor on this computer (Open in editor, bridge-plugins#253).
|
|
1229
|
+
no_editor: 409,
|
|
1230
|
+
// git itself refused (a hook, a signer): its words reach the person.
|
|
1231
|
+
failed: 409,
|
|
1232
|
+
};
|
|
1233
|
+
/** A refusal of the `git` service as this plugin's own (its code kept); anything else as it is. */
|
|
1234
|
+
const fromGit = (error: unknown) =>
|
|
1235
|
+
isRecord(error) && typeof error.code === 'string' && GIT_STATUS[error.code] !== undefined
|
|
1236
|
+
? refused(error.code, error instanceof Error ? error.message : String(error), GIT_STATUS[error.code])
|
|
1237
|
+
: error;
|
|
1238
|
+
/** `path` (absolute, or relative to `folder`, a folder of `repository`) relative to the repository's top, `/`-separated
|
|
1239
|
+
* (`''`: the top itself); `undefined` outside it. The top git gives may be another spelling of `folder`'s (symbolic
|
|
1240
|
+
* links resolved): a path in `folder` goes through `prefix`. */
|
|
1241
|
+
const within = ({ top, prefix }: Pick<Repository, 'top' | 'prefix'>, folder: string, path: string) => {
|
|
1242
|
+
const inside = (base: string, file: string) => {
|
|
1243
|
+
const rel = relative(base, file);
|
|
1244
|
+
return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel.split(sep).join('/');
|
|
1245
|
+
};
|
|
1246
|
+
const file = isAbsolute(path) ? path : join(folder, path);
|
|
1247
|
+
const local = inside(folder, file);
|
|
1248
|
+
return local === undefined ? inside(top, file) : `${prefix}${local}`.replace(/\/$/, '');
|
|
1249
|
+
};
|
|
1147
1250
|
const parse = <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string): T => {
|
|
1148
1251
|
let parsed;
|
|
1149
1252
|
try {
|
|
@@ -1160,6 +1263,35 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1160
1263
|
const continuationWindowMs = optionOf(config, 'continuationWindowMs', CONTINUATION_WINDOW_MS);
|
|
1161
1264
|
const driverPollMs = optionOf(config, 'driverPollMs', DRIVER_POLL_MS);
|
|
1162
1265
|
const driverWaitMs = optionOf(config, 'driverWaitMs', DRIVER_WAIT_MS);
|
|
1266
|
+
/** The `git` plugin's service (`@bridgebrew/git`, bridge-plugins#256), optional: without it a session works as one
|
|
1267
|
+
* outside any repository (no changes, no commit, no branch of its own), and the page offers to install it. */
|
|
1268
|
+
const git = () => {
|
|
1269
|
+
const service: unknown = ctx.get('git', false);
|
|
1270
|
+
return isRecord(service) && typeof service.version === 'string' && service.version.startsWith('1.')
|
|
1271
|
+
? // oxlint-disable-next-line bridge/no-new-unchecked-cast -- the `git` plugin's own service, its contract's major checked above
|
|
1272
|
+
(service as unknown as GitService)
|
|
1273
|
+
: undefined;
|
|
1274
|
+
};
|
|
1275
|
+
/** The branches of the repository at `folder` that have a folder, as git lists them: its own checkout first, then
|
|
1276
|
+
* each worktree under its `.worktrees/` (research-083). A folder's name is never read as a branch's name (`feat/x`
|
|
1277
|
+
* and `feat-x` share one); a detached one is left out. */
|
|
1278
|
+
const worktreesOf = async (folder: string) => {
|
|
1279
|
+
const all = (await git()?.worktrees(folder).catch(() => undefined)) ?? [];
|
|
1280
|
+
const main = all[0]?.folder;
|
|
1281
|
+
return all.flatMap(({ branch, folder: path }) =>
|
|
1282
|
+
branch !== undefined && (path === main || path.startsWith(`${main}/.worktrees/`))
|
|
1283
|
+
? [{ name: branch, folder: path }]
|
|
1284
|
+
: [],
|
|
1285
|
+
);
|
|
1286
|
+
};
|
|
1287
|
+
/** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has, each read as its
|
|
1288
|
+
* full name (`heads/<name>` beside a tag of the same name: plugins#198). */
|
|
1289
|
+
const freeBranch = async (folder: string, name: string) => {
|
|
1290
|
+
const taken = new Set((await git()?.branchNames(folder).catch(() => undefined)) ?? []);
|
|
1291
|
+
let free = name;
|
|
1292
|
+
for (let n = 2; taken.has(free); n++) free = `${name}-${n}`;
|
|
1293
|
+
return free;
|
|
1294
|
+
};
|
|
1163
1295
|
const branchNameMs = optionOf(config, 'branchNameMs', BRANCH_NAME_MS);
|
|
1164
1296
|
const flushRetryMs = optionOf(config, 'flushRetryMs', FLUSH_RETRY_MS);
|
|
1165
1297
|
// Cordis unloads independent effects in parallel. Group each storage release after the same
|
|
@@ -1248,7 +1380,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1248
1380
|
* project's own for its checked-out branch, else its worktree under `.worktrees/`); refused when it has none. */
|
|
1249
1381
|
const branchOf = async (node: string, name: string) => {
|
|
1250
1382
|
const project = await folderOf(node);
|
|
1251
|
-
const found = project && (await worktreesOf(
|
|
1383
|
+
const found = project && (await worktreesOf(project)).find((each) => each.name === name);
|
|
1252
1384
|
if (!found) throw refused('branch_unknown', `no folder of branch ${name} in project ${node}`);
|
|
1253
1385
|
return { name, folder: found.folder };
|
|
1254
1386
|
};
|
|
@@ -1263,7 +1395,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1263
1395
|
service ? `node ${node} has no branches here` : 'branches need Projects 0.0.2 or later in this workspace: install or update it (Plugins)',
|
|
1264
1396
|
);
|
|
1265
1397
|
try {
|
|
1266
|
-
const made = await service.newBranch({ node, name: await freeBranch(
|
|
1398
|
+
const made = await service.newBranch({ node, name: await freeBranch(project, name) });
|
|
1267
1399
|
return { ...made, ...(temporary && { temporary: true as const }) };
|
|
1268
1400
|
} catch (error) {
|
|
1269
1401
|
throw refused('branch_refused', error instanceof Error ? error.message : String(error));
|
|
@@ -1350,11 +1482,9 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1350
1482
|
/** Each new branch named in the background now (plugins#76), by its folder: the session whose first message asked, the
|
|
1351
1483
|
* naming's stop (that session's Stop or archive, or this plugin's end) and its end. */
|
|
1352
1484
|
const namings = new Map<string, { id: string; stop: AbortController; done: Promise<void> }>();
|
|
1353
|
-
/** Whether branch `name` in `folder` was pushed: it has an upstream, or a remote branch of its name
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
(await run(folder, ['for-each-ref', '--format=%(refname)', `refs/remotes/*/${name}`])).stdout.trim() !==
|
|
1357
|
-
'';
|
|
1485
|
+
/** Whether branch `name` in `folder` was pushed: it has an upstream, or a remote branch of its name (git missing:
|
|
1486
|
+
* taken as pushed, its name kept). */
|
|
1487
|
+
const pushed = async (folder: string, name: string) => (await git()?.pushed(folder, name)) ?? true;
|
|
1358
1488
|
/** Session `id`'s new branch named for `text` (its first message) in the background, its turn not waiting
|
|
1359
1489
|
* (plugins#76): a `type/topic` name the model of `harness` writes (plugins#73), else the message's words when it
|
|
1360
1490
|
* writes none in `branchNameMs` or fails; then every session in its folder reads that name, `temporary` gone. Its
|
|
@@ -1405,10 +1535,13 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1405
1535
|
let name = branch.name;
|
|
1406
1536
|
if (wanted && (await pushed(branch.folder, branch.name))) warn('was pushed: its name is kept');
|
|
1407
1537
|
else if (wanted) {
|
|
1408
|
-
const free = await freeBranch(
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1538
|
+
const free = await freeBranch(branch.folder, wanted);
|
|
1539
|
+
await git()
|
|
1540
|
+
?.renameBranch(branch.folder, branch.name, free)
|
|
1541
|
+
.then(
|
|
1542
|
+
() => (name = free),
|
|
1543
|
+
(error: unknown) => warn(`not renamed ${free}: ${error instanceof Error ? error.message : String(error)}`),
|
|
1544
|
+
);
|
|
1412
1545
|
}
|
|
1413
1546
|
// The sessions that joined it read its name too.
|
|
1414
1547
|
await branchMoved(node, branch.folder, { name, folder: branch.folder });
|
|
@@ -1458,7 +1591,12 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1458
1591
|
.then(async () => {
|
|
1459
1592
|
const found = await sessions.get(id);
|
|
1460
1593
|
if (!found) throw refused('not_found', `no session ${id}`, 404);
|
|
1461
|
-
|
|
1594
|
+
// The fields another plugin wrote leave before `fn` and come back after: kept whatever `fn` returns.
|
|
1595
|
+
const own: Record<string, unknown> = {};
|
|
1596
|
+
const foreign: Record<string, unknown> = {};
|
|
1597
|
+
for (const [key, each] of Object.entries(found.value))
|
|
1598
|
+
(Object.hasOwn(sessionShape, key) ? own : foreign)[key] = each;
|
|
1599
|
+
const value = { ...foreign, ...ownSession.parse(fn(own as Session)) };
|
|
1462
1600
|
await sessions.update(ctx, id, value);
|
|
1463
1601
|
return value;
|
|
1464
1602
|
});
|
|
@@ -1490,8 +1628,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1490
1628
|
if (!branch || (await ctx.fs.stat(ctx, branch.folder))) return value;
|
|
1491
1629
|
const project = await folderOf(node);
|
|
1492
1630
|
const kept =
|
|
1493
|
-
project !== undefined &&
|
|
1494
|
-
(await run(project, ['branch', '--list', branch.name])).stdout.trim() !== '';
|
|
1631
|
+
project !== undefined && !!(await git()?.branchNames(project))?.includes(branch.name);
|
|
1495
1632
|
const service = projectBranches();
|
|
1496
1633
|
if (!kept || !service)
|
|
1497
1634
|
throw new Error(
|
|
@@ -1543,15 +1680,16 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1543
1680
|
// (`git.ts`), and keeps those that changed as the session's `files`; while another session's turn ran in the same
|
|
1544
1681
|
// repository meanwhile, only the ones its agent's tool calls named (`paths`) are its own. Outside a repository, the
|
|
1545
1682
|
// named ones only.
|
|
1546
|
-
|
|
1547
|
-
/** The repository of each session folder (`null`: none), asked once. */
|
|
1683
|
+
/** The repository of each session folder (`null`: none), asked once while the `git` plugin is there. */
|
|
1548
1684
|
const repositories = new Map<string, Promise<Repository | null>>();
|
|
1549
1685
|
const repositoryOf = (folder: string) => {
|
|
1686
|
+
const service = git();
|
|
1687
|
+
if (!service) return Promise.resolve(null);
|
|
1550
1688
|
let found = repositories.get(folder);
|
|
1551
1689
|
if (!found)
|
|
1552
1690
|
repositories.set(
|
|
1553
1691
|
folder,
|
|
1554
|
-
(found = repositoryAt(
|
|
1692
|
+
(found = service.repositoryAt(folder).then(
|
|
1555
1693
|
(each) => each ?? null,
|
|
1556
1694
|
() => null,
|
|
1557
1695
|
)),
|
|
@@ -1583,8 +1721,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1583
1721
|
}
|
|
1584
1722
|
return found;
|
|
1585
1723
|
};
|
|
1586
|
-
/** The commits running per repository: one at a time. */
|
|
1587
|
-
const commits = new Map<string, Promise<unknown>>();
|
|
1588
1724
|
/** The tags of the workspace's sessions (archived ones too), most used first. */
|
|
1589
1725
|
const tagsOf = async () => {
|
|
1590
1726
|
const counts = new Map<string, number>();
|
|
@@ -1604,6 +1740,11 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1604
1740
|
* of the chain stores them all with `after` the `seq` before the first, the log's last `n`; a failed one leaves them
|
|
1605
1741
|
* for the next, so a transient failure loses nothing and changes no number watchers saw. */
|
|
1606
1742
|
const outbox = new Map<string, Line[]>();
|
|
1743
|
+
/** Per session, its history log's last `n`, seeded at the start (after the repair below) and moved by each append that
|
|
1744
|
+
* lands: with the outbox, the only base of numbering (`seqOf`), so a line is never numbered from a stale count. */
|
|
1745
|
+
const saved = new Map<string, number>();
|
|
1746
|
+
/** The `seq` of session `id`'s newest line: the log's, then its outbox's. */
|
|
1747
|
+
const seqOf = (id: string) => (saved.get(id) ?? 0) + (outbox.get(id)?.length ?? 0);
|
|
1607
1748
|
/** Session `id`'s history after `seq` `after`, in order: what the log holds, then its outbox. */
|
|
1608
1749
|
const readEvents = async (id: string, after = 0) => {
|
|
1609
1750
|
const events: Line[] = [];
|
|
@@ -1737,8 +1878,11 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1737
1878
|
const start = String(turn[0]?.time ?? '');
|
|
1738
1879
|
if (crashed ? !!lastTurn && lastTurn.endedAt >= start : lastTurn?.endedAt === endedAt) return;
|
|
1739
1880
|
const message = turn.find(({ type }) => type === 'user/message');
|
|
1881
|
+
// Its agent got the message: a line past it shows it, or the record does when a failing disk lost those lines.
|
|
1740
1882
|
const resend =
|
|
1741
|
-
message &&
|
|
1883
|
+
message &&
|
|
1884
|
+
(turn[0]?.turn === undefined || found.value.delivered !== turn[0].turn) &&
|
|
1885
|
+
!turn.some(({ type }) => !BEFORE_AGENT.has(type))
|
|
1742
1886
|
? queueItem.safeParse(
|
|
1743
1887
|
Object.fromEntries(
|
|
1744
1888
|
Object.entries({
|
|
@@ -1790,6 +1934,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1790
1934
|
// it did not land. Each stream's tail is read back to its last `turn/start`, or to a `turn/end` met first (the last
|
|
1791
1935
|
// turn is closed), past it for one of Bridge's.
|
|
1792
1936
|
for (const { stream: id, last } of await allStreams()) {
|
|
1937
|
+
saved.set(id, last);
|
|
1793
1938
|
try {
|
|
1794
1939
|
const tail: Line[] = [];
|
|
1795
1940
|
let ended: Line | undefined;
|
|
@@ -1824,7 +1969,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1824
1969
|
by: 'bridge',
|
|
1825
1970
|
},
|
|
1826
1971
|
].map((line) => ({ time, ...line }));
|
|
1827
|
-
await history.append(ctx, id, lines, { after: last });
|
|
1972
|
+
saved.set(id, await history.append(ctx, id, lines, { after: last }));
|
|
1828
1973
|
await markCut(id, turn, time, true);
|
|
1829
1974
|
} catch (error) {
|
|
1830
1975
|
ctx
|
|
@@ -1832,6 +1977,9 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1832
1977
|
.error(
|
|
1833
1978
|
`session ${id}: open turn not closed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1834
1979
|
);
|
|
1980
|
+
// An append reported failed may be durable all the same: the next line goes after the log's real end.
|
|
1981
|
+
const end = await history.last(id).catch(() => undefined);
|
|
1982
|
+
if (end !== undefined) saved.set(id, end);
|
|
1835
1983
|
}
|
|
1836
1984
|
}
|
|
1837
1985
|
|
|
@@ -1952,8 +2100,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1952
2100
|
const live = new Map<string, Live>();
|
|
1953
2101
|
/** Each session's write queue: its last pending append (appends are chained, in `seq` order). */
|
|
1954
2102
|
const chains = new Map<string, Promise<void>>();
|
|
1955
|
-
/** The last `seq` queued per session, ahead of the log while appends are queued. */
|
|
1956
|
-
const lastSeq = new Map<string, number>();
|
|
1957
2103
|
/** Sessions whose running turn was asked to stop: one not yet prompting ends without its prompt. */
|
|
1958
2104
|
const stopping = new Set<string>();
|
|
1959
2105
|
/** The running turns: `take` removes an open decision (`false` when it is not open), `record` stores its answer
|
|
@@ -2207,7 +2353,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2207
2353
|
if (!pending?.length) return;
|
|
2208
2354
|
const batch = pending.slice();
|
|
2209
2355
|
try {
|
|
2210
|
-
await history.append(
|
|
2356
|
+
const last = await history.append(
|
|
2211
2357
|
ctx,
|
|
2212
2358
|
id,
|
|
2213
2359
|
batch.map(({ seq: _seq, ...line }) => line as z.infer<typeof historyLine>),
|
|
@@ -2215,21 +2361,26 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2215
2361
|
);
|
|
2216
2362
|
pending.splice(0, batch.length);
|
|
2217
2363
|
if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
|
|
2364
|
+
saved.set(id, last);
|
|
2365
|
+
emit(id, { type: 'saved', seq: last });
|
|
2218
2366
|
clearFlushRetry(id);
|
|
2219
2367
|
} catch (error) {
|
|
2368
|
+
// A conflict: the log ends elsewhere. With one writer numbering from the log's end, that is a rejected append
|
|
2369
|
+
// that was durable after all: the lines it holds leave the outbox, the next try goes on after them.
|
|
2370
|
+
const conflict = (error as { code?: unknown } | null)?.code === 'log_conflict';
|
|
2220
2371
|
ctx
|
|
2221
2372
|
.logger('sessions')
|
|
2222
2373
|
.error(
|
|
2223
|
-
`session ${id}: history not written (${batch.length} lines kept for the next try): ${error instanceof Error ? error.message : String(error)}`,
|
|
2374
|
+
`session ${id}: history not written (${conflict ? 'stored already, by an append reported failed' : `${batch.length} lines kept for the next try`}): ${error instanceof Error ? error.message : String(error)}`,
|
|
2224
2375
|
);
|
|
2225
|
-
|
|
2226
|
-
// the outbox, so the next try goes on after them.
|
|
2227
|
-
if ((error as { code?: unknown } | null)?.code === 'log_conflict') {
|
|
2376
|
+
if (conflict) {
|
|
2228
2377
|
const last = await history.last(id).catch(() => undefined);
|
|
2229
2378
|
if (last !== undefined) {
|
|
2230
2379
|
const kept = pending.filter(({ seq }) => seq > last);
|
|
2231
2380
|
pending.splice(0, pending.length, ...kept);
|
|
2232
2381
|
if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
|
|
2382
|
+
saved.set(id, last);
|
|
2383
|
+
emit(id, { type: 'saved', seq: last });
|
|
2233
2384
|
}
|
|
2234
2385
|
}
|
|
2235
2386
|
if (pending.length) scheduleFlushRetry(id);
|
|
@@ -2245,13 +2396,12 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2245
2396
|
chains.set(id, chain);
|
|
2246
2397
|
return chain;
|
|
2247
2398
|
};
|
|
2248
|
-
/** Queues one settled line of session `id`: its `seq` taken now (past
|
|
2249
|
-
* stored by the next step of its chain (with the lines a failed step left); watchers get it at once.
|
|
2399
|
+
/** Queues one settled line of session `id`: its `seq` taken now (`seqOf`, past the log and the outbox), the line put
|
|
2400
|
+
* in its outbox, stored by the next step of its chain (with the lines a failed step left); watchers get it at once.
|
|
2250
2401
|
* ponytail: watchers see a line before it is durable, which AD-14 does not allow for domain subscribers; change it
|
|
2251
2402
|
* only with the page's merge of `live` and `stored` messages. */
|
|
2252
2403
|
const append = (id: string, type: string, data: object = {}) => {
|
|
2253
|
-
const seq = (
|
|
2254
|
-
lastSeq.set(id, seq);
|
|
2404
|
+
const seq = seqOf(id) + 1;
|
|
2255
2405
|
const acc = live.get(id);
|
|
2256
2406
|
if (acc) acc.seq = seq;
|
|
2257
2407
|
const event = { seq, time: new Date().toISOString(), type, ...data } as Line;
|
|
@@ -2261,16 +2411,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2261
2411
|
void queueFlush(id);
|
|
2262
2412
|
emit(id, { type: 'stored', event: fit(event) });
|
|
2263
2413
|
};
|
|
2264
|
-
/** Once the appends of `id` queued now landed, sets `lastSeq` to its history's last `n` plus the lines its outbox
|
|
2265
|
-
* still holds, unless more were queued meanwhile (they number on); resolves to it. */
|
|
2266
|
-
const syncSeq = async (id: string) => {
|
|
2267
|
-
await chains.get(id);
|
|
2268
|
-
const last = await history.last(id);
|
|
2269
|
-
if (chains.has(id)) return lastSeq.get(id) ?? last;
|
|
2270
|
-
const seq = last + (outbox.get(id)?.length ?? 0);
|
|
2271
|
-
lastSeq.set(id, seq);
|
|
2272
|
-
return seq;
|
|
2273
|
-
};
|
|
2274
2414
|
const finalizing = new Map<string, Set<Promise<unknown>>>();
|
|
2275
2415
|
const finalize = (id: string, work: Promise<unknown>) => {
|
|
2276
2416
|
let tasks = finalizing.get(id);
|
|
@@ -2692,6 +2832,36 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2692
2832
|
},
|
|
2693
2833
|
});
|
|
2694
2834
|
|
|
2835
|
+
/** `prompt` written once (`writeOnce`) after the conversations of `ids` (what the user asked, what the agent
|
|
2836
|
+
* answered), in a throwaway session of the first one's profile. */
|
|
2837
|
+
const writeAfter = async (
|
|
2838
|
+
ids: string[],
|
|
2839
|
+
options: { node: string; cwd: string; prompt: string; signal?: AbortSignal },
|
|
2840
|
+
) => {
|
|
2841
|
+
const talk: string[] = [];
|
|
2842
|
+
let harness: string | undefined;
|
|
2843
|
+
for (const id of ids) {
|
|
2844
|
+
const found = await sessions.get(id);
|
|
2845
|
+
if (!found) continue;
|
|
2846
|
+
harness ??= found.value.harness;
|
|
2847
|
+
talk.push(`## Session “${found.value.title}”`);
|
|
2848
|
+
for (const line of await readEvents(id))
|
|
2849
|
+
if (typeof line.text !== 'string' || line.subagent !== undefined) continue;
|
|
2850
|
+
else if (line.type === 'user/message' && line.from === undefined)
|
|
2851
|
+
talk.push(`User: ${line.text}`);
|
|
2852
|
+
else if (line.type === 'assistant/message') talk.push(`Agent: ${line.text}`);
|
|
2853
|
+
}
|
|
2854
|
+
// The conversation's newest part when it is long.
|
|
2855
|
+
const conversation = tailText(talk.join('\n\n'), 40_000);
|
|
2856
|
+
return writeOnce({
|
|
2857
|
+
...options,
|
|
2858
|
+
...(harness !== undefined && { harness }),
|
|
2859
|
+
prompt: conversation
|
|
2860
|
+
? `The conversation of the work, for context:\n\n${conversation}\n\n---\n\n${options.prompt}`
|
|
2861
|
+
: options.prompt,
|
|
2862
|
+
});
|
|
2863
|
+
};
|
|
2864
|
+
|
|
2695
2865
|
/** `POST /sessions/write` (research-083): a text a model writes once for Bridge (a commit message, a pull request's
|
|
2696
2866
|
* title and description), `prompt` after the conversations of `sessions` (what the user asked, what the agent
|
|
2697
2867
|
* answered), in a throwaway session of the first session's profile (`writeOnce`). */
|
|
@@ -2712,29 +2882,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2712
2882
|
);
|
|
2713
2883
|
const cwd = await folderOf(node);
|
|
2714
2884
|
if (cwd === undefined) throw refused('not_a_project', `node ${node} is not a project`);
|
|
2715
|
-
|
|
2716
|
-
let harness: string | undefined;
|
|
2717
|
-
for (const id of input.sessions ?? []) {
|
|
2718
|
-
const found = await sessions.get(id);
|
|
2719
|
-
if (!found) continue;
|
|
2720
|
-
harness ??= found.value.harness;
|
|
2721
|
-
talk.push(`## Session “${found.value.title}”`);
|
|
2722
|
-
for (const line of await readEvents(id))
|
|
2723
|
-
if (typeof line.text !== 'string' || line.subagent !== undefined) continue;
|
|
2724
|
-
else if (line.type === 'user/message' && line.from === undefined)
|
|
2725
|
-
talk.push(`User: ${line.text}`);
|
|
2726
|
-
else if (line.type === 'assistant/message') talk.push(`Agent: ${line.text}`);
|
|
2727
|
-
}
|
|
2728
|
-
// The conversation's newest part when it is long.
|
|
2729
|
-
const conversation = talk.join('\n\n').slice(-40_000);
|
|
2730
|
-
return writeOnce({
|
|
2731
|
-
node,
|
|
2732
|
-
cwd,
|
|
2733
|
-
...(harness !== undefined && { harness }),
|
|
2734
|
-
prompt: conversation
|
|
2735
|
-
? `The conversation of the work, for context:\n\n${conversation}\n\n---\n\n${input.prompt}`
|
|
2736
|
-
: input.prompt,
|
|
2737
|
-
});
|
|
2885
|
+
return writeAfter(input.sessions ?? [], { node, cwd, prompt: input.prompt });
|
|
2738
2886
|
},
|
|
2739
2887
|
});
|
|
2740
2888
|
|
|
@@ -2788,6 +2936,138 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2788
2936
|
},
|
|
2789
2937
|
});
|
|
2790
2938
|
|
|
2939
|
+
// The composer's menus (plugins#239): `@` a file of the folder a session works in, `/` its agent's commands. Both
|
|
2940
|
+
// read the session's own folder (its branch's or worktree's: `id`), a new chat's its node's.
|
|
2941
|
+
/** The folder the menus read, and session `id` when given. */
|
|
2942
|
+
const menuFolder = async (node: string, id: string | undefined) => {
|
|
2943
|
+
const found = id === undefined ? undefined : await find(new URLSearchParams({ id }));
|
|
2944
|
+
const folder = found ? await sessionFolder(found.node, found.value) : await folderOf(node);
|
|
2945
|
+
if (folder === undefined)
|
|
2946
|
+
throw refused(
|
|
2947
|
+
'not_a_project',
|
|
2948
|
+
`node ${node} is not a project: sessions live in project nodes and on the workspace (root)`,
|
|
2949
|
+
);
|
|
2950
|
+
return { folder, found };
|
|
2951
|
+
};
|
|
2952
|
+
/** Every file below `folder`, relative: git's (tracked and untracked, ignored ones left out), else (no repository, or
|
|
2953
|
+
* git cannot run) a walk that skips `.git`, `node_modules` and `.bridge` and follows no symlinked folder (a cycle, a
|
|
2954
|
+
* link out of the folder). ponytail: the walk stops at `FILES_WALK_MAX` files or `WALK_ENTRIES_MAX` entries read, a
|
|
2955
|
+
* folder that large without git finds only its first ones. */
|
|
2956
|
+
const filesOf = async (folder: string) => {
|
|
2957
|
+
const listed = await git()
|
|
2958
|
+
?.files(folder)
|
|
2959
|
+
.catch(() => undefined);
|
|
2960
|
+
if (listed) return listed;
|
|
2961
|
+
const files: string[] = [];
|
|
2962
|
+
const top = await ctx.fs.realpath(ctx, folder).catch(() => folder);
|
|
2963
|
+
const queue = [''];
|
|
2964
|
+
let entries = 0;
|
|
2965
|
+
walk: while (queue.length) {
|
|
2966
|
+
const at = queue.shift()!;
|
|
2967
|
+
const names = await ctx.fs.readdir(ctx, join(folder, at)).catch((): string[] => []);
|
|
2968
|
+
for (const name of [...names].sort()) {
|
|
2969
|
+
if (files.length >= FILES_WALK_MAX || ++entries > WALK_ENTRIES_MAX) break walk;
|
|
2970
|
+
if (WALK_SKIPPED.has(name)) continue;
|
|
2971
|
+
const path = at ? `${at}/${name}` : name;
|
|
2972
|
+
const info = await ctx.fs.stat(ctx, join(folder, path)).catch(() => undefined);
|
|
2973
|
+
if (info?.isFile) files.push(path);
|
|
2974
|
+
// A folder is walked only where it really is: a symlinked one's real path is elsewhere.
|
|
2975
|
+
else if (
|
|
2976
|
+
info?.isDirectory &&
|
|
2977
|
+
(await ctx.fs.realpath(ctx, join(folder, path)).catch(() => undefined)) ===
|
|
2978
|
+
join(top, path)
|
|
2979
|
+
)
|
|
2980
|
+
queue.push(path);
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
return files;
|
|
2984
|
+
};
|
|
2985
|
+
ctx.router.route(ctx, {
|
|
2986
|
+
method: 'GET',
|
|
2987
|
+
path: '/sessions/files',
|
|
2988
|
+
description: `The files of the folder a session works in matching \`q\` (its name first), at most ${MENU_FILES_MAX}: [path relative to it]; \`id\` the session, without it the node's folder`,
|
|
2989
|
+
query: z.strictObject({ q: z.string().optional(), id: z.string().min(1).optional() }),
|
|
2990
|
+
handle: async ({ node, query }) => {
|
|
2991
|
+
const { folder } = await menuFolder(node, query.get('id') ?? undefined);
|
|
2992
|
+
return matchingFiles(await filesOf(folder), query.get('q') ?? '');
|
|
2993
|
+
},
|
|
2994
|
+
});
|
|
2995
|
+
const commandsMs = optionOf(config, 'commandsMs', COMMANDS_MS);
|
|
2996
|
+
/** Commands by profile and folder, with when they were read; a pending read is shared, a failed one not kept. */
|
|
2997
|
+
const commandLists = new Map<string, { at: number; list: Promise<Command[]> }>();
|
|
2998
|
+
ctx.router.route(ctx, {
|
|
2999
|
+
method: 'GET',
|
|
3000
|
+
path: '/sessions/commands',
|
|
3001
|
+
description:
|
|
3002
|
+
"The commands and skills a session's agent runs from a message starting with them: [{ name, description, kind: 'command' | 'skill', text? }] (`text`: what to write when not /<name>); `id` the session, else `profile` in the node's folder; [] when its harness cannot list them",
|
|
3003
|
+
query: z.strictObject({
|
|
3004
|
+
id: z.string().min(1).optional(),
|
|
3005
|
+
profile: z.string().min(1).optional(),
|
|
3006
|
+
harness: z.string().min(1).optional(),
|
|
3007
|
+
}),
|
|
3008
|
+
handle: async ({ node, query }) => {
|
|
3009
|
+
const { folder, found } = await menuFolder(node, query.get('id') ?? undefined);
|
|
3010
|
+
const harness =
|
|
3011
|
+
found?.value.harness ??
|
|
3012
|
+
profileAlias({
|
|
3013
|
+
profile: query.get('profile') ?? undefined,
|
|
3014
|
+
harness: query.get('harness') ?? undefined,
|
|
3015
|
+
});
|
|
3016
|
+
// A harness plugin older than `commands` has none: no menu, never an error.
|
|
3017
|
+
if (!ctx.harness.commands) return [];
|
|
3018
|
+
// By node too: a node may override the profile (its harness, its options).
|
|
3019
|
+
const at = found?.node ?? node;
|
|
3020
|
+
const key = `${harness}\n${at}\n${folder}`;
|
|
3021
|
+
const known = commandLists.get(key);
|
|
3022
|
+
if (known && Date.now() - known.at < COMMANDS_TTL_MS) return known.list;
|
|
3023
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
3024
|
+
// Never rejects, for every caller that shares it: an agent that cannot list them (not installed, slow, refused)
|
|
3025
|
+
// has no menu, said in the log, not to the user, and is asked again next time.
|
|
3026
|
+
const list: Promise<Command[]> = Promise.race([
|
|
3027
|
+
ctx.harness.commands({ harness, node: at, cwd: folder }),
|
|
3028
|
+
new Promise<never>((_, reject) => {
|
|
3029
|
+
timer = setTimeout(
|
|
3030
|
+
() => reject(new Error(`no commands within ${commandsMs / 1000} s`)),
|
|
3031
|
+
commandsMs,
|
|
3032
|
+
);
|
|
3033
|
+
}),
|
|
3034
|
+
])
|
|
3035
|
+
.catch((error: unknown) => {
|
|
3036
|
+
if (commandLists.get(key)?.list === list) commandLists.delete(key);
|
|
3037
|
+
ctx.logger('sessions').warn(
|
|
3038
|
+
`harness ${harness}: its commands could not be listed: ${error instanceof Error ? error.message : String(error)}`,
|
|
3039
|
+
);
|
|
3040
|
+
return [];
|
|
3041
|
+
})
|
|
3042
|
+
.finally(() => clearTimeout(timer));
|
|
3043
|
+
commandLists.set(key, { at: Date.now(), list });
|
|
3044
|
+
return list;
|
|
3045
|
+
},
|
|
3046
|
+
});
|
|
3047
|
+
|
|
3048
|
+
/** Session `id` follows the mode its open harness session `agent` runs when the agent took it itself (it left Plan
|
|
3049
|
+
* once its plan was approved): the record takes it, so the mode picker and the next open do, it is logged, and the
|
|
3050
|
+
* token is granted for it. The agent's change wins over the user's last pick. Read when it runs, on the queue lock
|
|
3051
|
+
* (a turn's start waits for it), so changes apply in order and the last one wins; nothing for a harness session no
|
|
3052
|
+
* longer open, or a mode its agent does not list (the next open would refuse it). */
|
|
3053
|
+
const followMode = (id: string, agent: HarnessSession) =>
|
|
3054
|
+
serial(id, async () => {
|
|
3055
|
+
const mode = agent.mode;
|
|
3056
|
+
const found = await sessions.get(id);
|
|
3057
|
+
if (mode === undefined || !found || found.value.mode === mode || open.get(id) !== agent)
|
|
3058
|
+
return;
|
|
3059
|
+
const path = await sessionFolder(found.node, found.value);
|
|
3060
|
+
if (path === undefined) return;
|
|
3061
|
+
const modes = await listOf('modes', found.value.harness, found.node, path);
|
|
3062
|
+
const known = modes.find((each) => each.id === mode);
|
|
3063
|
+
if (modes.length && !known) return;
|
|
3064
|
+
if (agent.mode !== mode || open.get(id) !== agent) return; // changed again: its own call follows
|
|
3065
|
+
const token = tokens.get(id);
|
|
3066
|
+
if (token !== undefined) await grant(id, token, found.value.harness, found.node, path, mode);
|
|
3067
|
+
await change(id, ({ options: _old, ...now }) => ({ ...now, mode }));
|
|
3068
|
+
append(id, 'mode/changed', { mode, name: known?.name ?? mode });
|
|
3069
|
+
});
|
|
3070
|
+
|
|
2791
3071
|
ctx.router.route(ctx, {
|
|
2792
3072
|
method: 'POST',
|
|
2793
3073
|
path: '/sessions/mode',
|
|
@@ -2850,7 +3130,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2850
3130
|
throw await notApplied(error);
|
|
2851
3131
|
}
|
|
2852
3132
|
}
|
|
2853
|
-
await syncSeq(id);
|
|
2854
3133
|
await change(id, (now) => {
|
|
2855
3134
|
const { options: _old, ...rest } = now;
|
|
2856
3135
|
return { ...rest, mode, ...(kept && { options: kept }) };
|
|
@@ -2860,6 +3139,9 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2860
3139
|
name: known?.name ?? mode,
|
|
2861
3140
|
...(kept && { options: kept }),
|
|
2862
3141
|
});
|
|
3142
|
+
// The agent took another mode right after this one: its event may have been followed before this write.
|
|
3143
|
+
if (harness && !harness.closed && harness.mode !== mode)
|
|
3144
|
+
finalize(id, followMode(id, harness).catch(log(`session ${id}: agent's mode not stored`)));
|
|
2863
3145
|
return { ok: true };
|
|
2864
3146
|
},
|
|
2865
3147
|
});
|
|
@@ -2901,7 +3183,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2901
3183
|
throw await notApplied(error);
|
|
2902
3184
|
}
|
|
2903
3185
|
}
|
|
2904
|
-
await syncSeq(id);
|
|
2905
3186
|
await change(id, (now) => ({ ...now, effort }));
|
|
2906
3187
|
append(id, 'effort/changed', { effort, name: known?.name ?? effort });
|
|
2907
3188
|
return { ok: true };
|
|
@@ -2955,6 +3236,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2955
3236
|
// One moment, synchronously: the lines stored before the first one queued meanwhile, those queued (not all
|
|
2956
3237
|
// stored yet), and the accumulator now; the live events queued meanwhile are in that copy already.
|
|
2957
3238
|
const pending = queue.splice(0);
|
|
3239
|
+
const held = saved.get(id) ?? 0;
|
|
2958
3240
|
const queued = pending.flatMap((message) =>
|
|
2959
3241
|
message.type === 'stored' ? [message.event!] : [],
|
|
2960
3242
|
);
|
|
@@ -3007,6 +3289,8 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3007
3289
|
type: 'snapshot',
|
|
3008
3290
|
events: events.slice(from),
|
|
3009
3291
|
live: snapshot,
|
|
3292
|
+
// The lines the log holds, those this stream sent at most: a page keeps them across a reconnect.
|
|
3293
|
+
saved: Math.min(held, last),
|
|
3010
3294
|
...(page && { more: page.more }),
|
|
3011
3295
|
};
|
|
3012
3296
|
for (const message of pending) if (message.type === 'open-link') yield message;
|
|
@@ -3133,8 +3417,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3133
3417
|
lastTurn: settledTurn(lastTurn),
|
|
3134
3418
|
};
|
|
3135
3419
|
});
|
|
3136
|
-
// Numbered after the stored lines: no turn ran since the start.
|
|
3137
|
-
await syncSeq(id);
|
|
3138
3420
|
append(id, 'decision/answered', {
|
|
3139
3421
|
id: decision,
|
|
3140
3422
|
...answeredLine(option),
|
|
@@ -3337,7 +3619,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3337
3619
|
return;
|
|
3338
3620
|
// It failed to start (an image gone): the queue waits for the user, as after a Stop.
|
|
3339
3621
|
halt(id);
|
|
3340
|
-
await syncSeq(id);
|
|
3341
3622
|
append(id, 'notice', {
|
|
3342
3623
|
text: `The queued message "${oneLine(item.text || imagesLabel(item.attachments ?? []), 60)}" was not sent: ${error instanceof Error ? error.message : String(error)}. It stays first in the queue: edit or remove it.`,
|
|
3343
3624
|
});
|
|
@@ -3605,7 +3886,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3605
3886
|
/** No line written yet: the agent gets the session's target with this message. */
|
|
3606
3887
|
let first = false;
|
|
3607
3888
|
try {
|
|
3608
|
-
first = (
|
|
3889
|
+
first = seqOf(id) === 0;
|
|
3609
3890
|
// 409: the router answers only a 4xx as it is (another status becomes a 500 `handler_error`).
|
|
3610
3891
|
if (disposed)
|
|
3611
3892
|
throw refused(
|
|
@@ -3652,7 +3933,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3652
3933
|
throw error;
|
|
3653
3934
|
}
|
|
3654
3935
|
const acc: Live = {
|
|
3655
|
-
seq:
|
|
3936
|
+
seq: seqOf(id),
|
|
3656
3937
|
text: '',
|
|
3657
3938
|
thought: '',
|
|
3658
3939
|
tools: {},
|
|
@@ -3787,13 +4068,14 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3787
4068
|
const named = [...touched]
|
|
3788
4069
|
.map((path) => within(scope, folder, path))
|
|
3789
4070
|
.filter((path): path is string => !!path);
|
|
4071
|
+
const service = git();
|
|
3790
4072
|
const after =
|
|
3791
|
-
repository && before && !disposed ? await
|
|
4073
|
+
repository && before && !disposed ? await service?.snapshot(repository.top) : undefined;
|
|
3792
4074
|
// Bridge's own data (these histories) when the workspace lies in the repository is no change of the session.
|
|
3793
4075
|
const data = repository && within(repository, folder, ctx.workspace.dataDir);
|
|
3794
4076
|
const files = (
|
|
3795
|
-
after
|
|
3796
|
-
? changed(before!, after).filter((path) => !turn.shared || named.includes(path))
|
|
4077
|
+
after && service
|
|
4078
|
+
? service.changed(before!, after).filter((path) => !turn.shared || named.includes(path))
|
|
3797
4079
|
: named
|
|
3798
4080
|
).filter((path) => !data || !`${path}/`.startsWith(`${data}/`));
|
|
3799
4081
|
if (files.length)
|
|
@@ -3957,8 +4239,10 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3957
4239
|
/** Whether the turn can take a message now: not stopping nor ending. */
|
|
3958
4240
|
const steerOpen = () =>
|
|
3959
4241
|
!ended && !aborted && !stopping.has(id) && !sendNow.has(id) && !halted.has(id);
|
|
4242
|
+
/** This turn's id, on its `turn/start` line and, once its agent answers, in the record (`delivered`). */
|
|
4243
|
+
const turnId = crypto.randomUUID();
|
|
3960
4244
|
turns.set(id, {
|
|
3961
|
-
turn:
|
|
4245
|
+
turn: turnId,
|
|
3962
4246
|
take,
|
|
3963
4247
|
record,
|
|
3964
4248
|
expire,
|
|
@@ -3998,8 +4282,29 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3998
4282
|
});
|
|
3999
4283
|
/** Each tool call's edits, as last given (an agent may give them before the result only). */
|
|
4000
4284
|
const edits = new Map<string, Change[]>();
|
|
4285
|
+
/** The agent answered (a first event): the record says so, for the start after a crash (`markCut`). */
|
|
4286
|
+
let delivered = false;
|
|
4001
4287
|
const onEvent = (received: HarnessEvent) => {
|
|
4002
4288
|
if (ended) return;
|
|
4289
|
+
if (!delivered) {
|
|
4290
|
+
delivered = true;
|
|
4291
|
+
finalize(
|
|
4292
|
+
id,
|
|
4293
|
+
change(id, (now) => ({ ...now, delivered: turnId })).catch(
|
|
4294
|
+
log(`session ${id}: delivery not stored`),
|
|
4295
|
+
),
|
|
4296
|
+
);
|
|
4297
|
+
}
|
|
4298
|
+
// The agent changed its mode itself: the record follows it (`followMode`).
|
|
4299
|
+
if (received.type === 'mode') {
|
|
4300
|
+
const emitter = agent;
|
|
4301
|
+
if (emitter)
|
|
4302
|
+
finalize(
|
|
4303
|
+
id,
|
|
4304
|
+
followMode(id, emitter).catch(log(`session ${id}: mode ${received.mode} not stored`)),
|
|
4305
|
+
);
|
|
4306
|
+
return;
|
|
4307
|
+
}
|
|
4003
4308
|
// A `show_view` call's input as the agent writes it goes live as `view/draft` (the program so far), never stored;
|
|
4004
4309
|
// another tool's draft goes nowhere (research-036 streaming).
|
|
4005
4310
|
if (received.type === 'draft') {
|
|
@@ -4047,7 +4352,13 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4047
4352
|
} else if (event.type === 'text') acc.text += event.text;
|
|
4048
4353
|
else if (event.type === 'thought') acc.thought += event.text;
|
|
4049
4354
|
else if (event.type === 'plan') acc.plan = event.entries;
|
|
4050
|
-
|
|
4355
|
+
// A driver may give its usage in parts (Claude: `used` per message, `size` alone on its result): each keeps the other.
|
|
4356
|
+
else if (event.type === 'usage')
|
|
4357
|
+
acc.usage = {
|
|
4358
|
+
...acc.usage,
|
|
4359
|
+
...(event.used !== undefined && { used: event.used }),
|
|
4360
|
+
...(event.size !== undefined && { size: event.size }),
|
|
4361
|
+
};
|
|
4051
4362
|
else if (event.type === 'decision-withdrawn') {
|
|
4052
4363
|
// Closed as an expiry is: stored, and a later answer refused (409). The stored line tells the pages.
|
|
4053
4364
|
expire(event.id);
|
|
@@ -4269,7 +4580,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4269
4580
|
return opened;
|
|
4270
4581
|
};
|
|
4271
4582
|
|
|
4272
|
-
write('turn/start', auto
|
|
4583
|
+
write('turn/start', { turn: turnId, ...(auto && { auto: true }) });
|
|
4273
4584
|
if (!auto) write('user/message', messageLine(text, attachments, options));
|
|
4274
4585
|
// The turn runs on its own: a page that goes away does not stop it, and its end is stored.
|
|
4275
4586
|
void (async () => {
|
|
@@ -4287,7 +4598,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4287
4598
|
if (folder === undefined) return;
|
|
4288
4599
|
const repository = await repositoryOf(folder);
|
|
4289
4600
|
const top = repository?.top;
|
|
4290
|
-
const before = top ? await
|
|
4601
|
+
const before = top ? await git()?.snapshot(top).catch(() => undefined) : undefined;
|
|
4291
4602
|
const turn = { shared: false };
|
|
4292
4603
|
if (top && !ended) {
|
|
4293
4604
|
let beside = turnsIn.get(top);
|
|
@@ -4308,19 +4619,15 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4308
4619
|
if (since && !auto) {
|
|
4309
4620
|
const touched =
|
|
4310
4621
|
top && now.files?.length
|
|
4311
|
-
? await
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
'--format=%h %s (%an, %ar)',
|
|
4315
|
-
'-n',
|
|
4316
|
-
'20',
|
|
4317
|
-
'--',
|
|
4318
|
-
...now.files,
|
|
4319
|
-
])
|
|
4622
|
+
? await git()
|
|
4623
|
+
?.history(top, { since, paths: now.files, max: 20 })
|
|
4624
|
+
.catch(() => undefined)
|
|
4320
4625
|
: undefined;
|
|
4321
4626
|
preface += environmentText(
|
|
4322
4627
|
since,
|
|
4323
|
-
touched
|
|
4628
|
+
(touched ?? []).map(
|
|
4629
|
+
({ sha, subject, author, relative: ago }) => `${sha.slice(0, 7)} ${subject} (${author}, ${ago})`,
|
|
4630
|
+
),
|
|
4324
4631
|
);
|
|
4325
4632
|
}
|
|
4326
4633
|
if (top && before && now.files?.length)
|
|
@@ -4342,7 +4649,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4342
4649
|
end = stopping.delete(id)
|
|
4343
4650
|
? { reason: 'interrupted' }
|
|
4344
4651
|
: await harness!.prompt(
|
|
4345
|
-
preface
|
|
4652
|
+
prefaced(preface, toldOf(text, images)),
|
|
4346
4653
|
onEvent,
|
|
4347
4654
|
images.map(({ path, type, name, data }) => ({ path, type, name, data })),
|
|
4348
4655
|
);
|
|
@@ -4363,10 +4670,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4363
4670
|
get: (id) => sessions.get(id),
|
|
4364
4671
|
query: () => sessions.query({ node: 'root', include: 'subtree', archived: true }),
|
|
4365
4672
|
change,
|
|
4366
|
-
append: async (id, type, data) =>
|
|
4367
|
-
if (!running.has(id)) await syncSeq(id);
|
|
4368
|
-
append(id, type, data);
|
|
4369
|
-
},
|
|
4673
|
+
append: async (id, type, data) => append(id, type, data),
|
|
4370
4674
|
running,
|
|
4371
4675
|
startTurn,
|
|
4372
4676
|
unsettle: reactivated,
|
|
@@ -4501,16 +4805,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4501
4805
|
log,
|
|
4502
4806
|
});
|
|
4503
4807
|
|
|
4504
|
-
// An ssh alias's host, once per alias: `ssh -G` reads ~/.ssh/config (plugins#114). A failure is asked again.
|
|
4505
|
-
const hosts = new Map<string, Promise<string | undefined>>();
|
|
4506
|
-
const hostOf = (folder: string, alias: string) => {
|
|
4507
|
-
let host = hosts.get(alias);
|
|
4508
|
-
if (!host) {
|
|
4509
|
-
hosts.set(alias, (host = sshHostname(ctx, folder, alias)));
|
|
4510
|
-
void host.then((name) => name || hosts.delete(alias));
|
|
4511
|
-
}
|
|
4512
|
-
return host;
|
|
4513
|
-
};
|
|
4514
4808
|
// A session's pull request (research-086): linked, read, settled on merge, watched; `pull-requests.ts`.
|
|
4515
4809
|
const pullRequests = createPullRequests<Session>({
|
|
4516
4810
|
route: (method, path, description, handle) =>
|
|
@@ -4524,33 +4818,24 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4524
4818
|
if (value.branch?.temporary) return undefined;
|
|
4525
4819
|
const folder = await sessionFolder(node, value);
|
|
4526
4820
|
if (folder === undefined) return undefined;
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
|
|
4531
|
-
|
|
4821
|
+
const service = git();
|
|
4822
|
+
if (!service) return undefined;
|
|
4823
|
+
// Its branch's own name (none when detached), never git's short form: `heads/<name>` beside a tag (plugins#198).
|
|
4824
|
+
const status = await service.tracking(folder).catch(() => undefined);
|
|
4825
|
+
// A branch with no commit yet (unborn, orphan), and the default branch, have no pull request of their own; `main`
|
|
4826
|
+
// and `master` neither, the default being only guessed (a remote never fetched: then it is the checked-out
|
|
4827
|
+
// branch, which is no reason to leave a work branch out).
|
|
4828
|
+
if (
|
|
4829
|
+
!status?.branch ||
|
|
4830
|
+
!status.head ||
|
|
4831
|
+
(status.isDefault && !status.base.guessed) ||
|
|
4832
|
+
['main', 'master'].includes(status.branch)
|
|
4833
|
+
)
|
|
4532
4834
|
return undefined;
|
|
4533
|
-
// The branch's upstream remote, else
|
|
4534
|
-
|
|
4535
|
-
const
|
|
4536
|
-
|
|
4537
|
-
? tracked
|
|
4538
|
-
: names.includes('origin')
|
|
4539
|
-
? 'origin'
|
|
4540
|
-
: names.length === 1
|
|
4541
|
-
? names[0]!
|
|
4542
|
-
: undefined;
|
|
4543
|
-
if (name === undefined) return undefined;
|
|
4544
|
-
// The default branch: no pull request of its own.
|
|
4545
|
-
// Read as a full ref: a local branch named `<remote>/main` makes the short form `remotes/<remote>/main`.
|
|
4546
|
-
const base = (await run(folder, ['symbolic-ref', `refs/remotes/${name}/HEAD`])).stdout
|
|
4547
|
-
.trim()
|
|
4548
|
-
.slice(`refs/remotes/${name}/`.length);
|
|
4549
|
-
if (branch === base || branch === 'main' || branch === 'master') return undefined;
|
|
4550
|
-
const remote = await run(folder, ['remote', 'get-url', name]);
|
|
4551
|
-
return remote.code === 0 && remote.stdout.trim()
|
|
4552
|
-
? { branch, remote: await resolveRemote(remote.stdout.trim(), (alias) => hostOf(folder, alias)) }
|
|
4553
|
-
: undefined;
|
|
4835
|
+
// The branch's upstream remote, else the only one, else `origin` (as the Branches screen); its URL with an ssh
|
|
4836
|
+
// alias read as its host (plugins#114).
|
|
4837
|
+
const remote = await service.remote(folder).catch(() => undefined);
|
|
4838
|
+
return remote ? { branch: status.branch, remote: remote.url } : undefined;
|
|
4554
4839
|
},
|
|
4555
4840
|
// A wake already in the queue: sent as after a turn (at once when none runs, held after the user's Stop).
|
|
4556
4841
|
deliver: (id) => {
|
|
@@ -4585,7 +4870,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4585
4870
|
});
|
|
4586
4871
|
if (!settled) return false;
|
|
4587
4872
|
await unsnooze(id);
|
|
4588
|
-
await syncSeq(id);
|
|
4589
4873
|
append(id, 'notice', { text: notice });
|
|
4590
4874
|
void closeIdle(id, true).catch(log(`session ${id}: harness not closed`));
|
|
4591
4875
|
return true;
|
|
@@ -5371,7 +5655,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5371
5655
|
throw refused('not_your_session', 'An agent asks about its own session', 403);
|
|
5372
5656
|
const found = await find(new URLSearchParams({ id }));
|
|
5373
5657
|
const project = found.node === 'root' ? undefined : await folderOf(found.node);
|
|
5374
|
-
const branches = project === undefined ? [] : await worktreesOf(
|
|
5658
|
+
const branches = project === undefined ? [] : await worktreesOf(project).catch(() => []);
|
|
5375
5659
|
// Where it works, as its agent's cwd: its branch's folder, else its stage's checkout of the project, else main.
|
|
5376
5660
|
const folder = await sessionFolder(found.node, found.value);
|
|
5377
5661
|
const real = folder && (await ctx.fs.realpath(ctx, folder).catch(() => folder));
|
|
@@ -5650,8 +5934,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5650
5934
|
);
|
|
5651
5935
|
if (whole.length > VIEW_MAX)
|
|
5652
5936
|
throw refused('invalid_view', `the merged view is over ${VIEW_MAX} characters`);
|
|
5653
|
-
// After a restart, the session's numbering comes from its history first (as a peer's line, a commit's).
|
|
5654
|
-
if (!running.has(id)) await syncSeq(id);
|
|
5655
5937
|
// The declaration of each plugin component it calls, so the page draws the view as the agent saw it (P2).
|
|
5656
5938
|
const called = usedViewComponents(whole, components);
|
|
5657
5939
|
const read = readAs(`agent:${id}`);
|
|
@@ -5705,7 +5987,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5705
5987
|
? { dynamic: true }
|
|
5706
5988
|
: { snapshot: snapshot ?? {}, at: new Date().toISOString() }),
|
|
5707
5989
|
});
|
|
5708
|
-
const seq =
|
|
5990
|
+
const seq = seqOf(id);
|
|
5709
5991
|
return { seq, errors, ...told };
|
|
5710
5992
|
},
|
|
5711
5993
|
});
|
|
@@ -5788,37 +6070,135 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5788
6070
|
const repositoryNow = async (id: string, node: string) => {
|
|
5789
6071
|
const folder = await sessionFolder(node, (await sessions.get(id))?.value);
|
|
5790
6072
|
const top = folder === undefined ? undefined : (await repositoryOf(folder))?.top;
|
|
5791
|
-
|
|
5792
|
-
|
|
6073
|
+
const service = git();
|
|
6074
|
+
if (!top || !service) throw refused('not_a_repository', `session ${id} works in no git repository`, 409);
|
|
6075
|
+
const state = await service.snapshot(top);
|
|
5793
6076
|
if (!state) throw refused('not_a_repository', `git status failed in ${top}`, 409);
|
|
5794
|
-
return { top, state };
|
|
6077
|
+
return { top, state, git: service, folder: folder! };
|
|
5795
6078
|
};
|
|
5796
6079
|
|
|
5797
6080
|
ctx.router.route(ctx, {
|
|
5798
6081
|
method: 'POST',
|
|
5799
6082
|
path: '/sessions/changes',
|
|
5800
6083
|
handle: async ({ body }) => {
|
|
5801
|
-
const { id } = parse(
|
|
6084
|
+
const { id, path } = parse(changesBody, body, 'POST /sessions/changes takes { id, path? }');
|
|
5802
6085
|
const { node, value } = await find(new URLSearchParams({ id }));
|
|
5803
|
-
|
|
6086
|
+
// Outside any git repository is a session's ordinary state, not a failure: the whole answer says so (`repository:
|
|
6087
|
+
// null`) for the panel that reads it on every session; one file's diff is still refused. Without the `git` plugin,
|
|
6088
|
+
// the same, saying so (`git: 'missing'`): the page offers to install it.
|
|
6089
|
+
const now = await repositoryNow(id, node).catch((error: unknown) => {
|
|
6090
|
+
if (path === undefined && isRecord(error) && error.code === 'not_a_repository') return undefined;
|
|
6091
|
+
throw error;
|
|
6092
|
+
});
|
|
6093
|
+
if (!now)
|
|
6094
|
+
return {
|
|
6095
|
+
id,
|
|
6096
|
+
node,
|
|
6097
|
+
title: value.title,
|
|
6098
|
+
repository: null,
|
|
6099
|
+
files: [],
|
|
6100
|
+
diff: '',
|
|
6101
|
+
...(!git() && { git: 'missing' as const }),
|
|
6102
|
+
};
|
|
6103
|
+
const { top, state, git: service, folder } = now;
|
|
5804
6104
|
const files = value.files ?? [];
|
|
5805
|
-
|
|
6105
|
+
try {
|
|
6106
|
+
// One file's diff: one the session changed, never another path (outside its repository, or another session's).
|
|
6107
|
+
if (path !== undefined) {
|
|
6108
|
+
if (!files.includes(path))
|
|
6109
|
+
throw refused('not_its_file', `session ${id} did not change ${path}`);
|
|
6110
|
+
const pending = state.has(path) ? [path] : [];
|
|
6111
|
+
const { patch: diff, cut } = await service.diff(top, { paths: pending, maxChars: DIFF_MAX });
|
|
6112
|
+
return { id, node, repository: top, path, diff, ...(cut && { cut: true }) };
|
|
6113
|
+
}
|
|
6114
|
+
const pending = files.filter((file) => state.has(file));
|
|
6115
|
+
const counts = await service.counts(top, pending);
|
|
6116
|
+
const whole = pending.length <= DIFF_FILES_MAX;
|
|
6117
|
+
const { patch: diff, cut } = whole
|
|
6118
|
+
? await service.diff(top, { paths: pending, maxChars: DIFF_MAX })
|
|
6119
|
+
: { patch: '', cut: false };
|
|
6120
|
+
const status = await service.tracking(folder).catch(() => undefined);
|
|
6121
|
+
const others = [...state.keys()].filter((file) => !files.includes(file));
|
|
6122
|
+
return {
|
|
6123
|
+
id,
|
|
6124
|
+
node,
|
|
6125
|
+
title: value.title,
|
|
6126
|
+
repository: top,
|
|
6127
|
+
running: running.has(id),
|
|
6128
|
+
files: files.map((file) => ({ path: file, pending: state.has(file), ...counts[file] })),
|
|
6129
|
+
commits: value.commits ?? [],
|
|
6130
|
+
shared: await sharing(id, top, state, files),
|
|
6131
|
+
// Past `DIFF_FILES_MAX` pending files: none, `byFile` says so (each one's with `path`).
|
|
6132
|
+
diff,
|
|
6133
|
+
...(!whole && { byFile: true }),
|
|
6134
|
+
// Cut short: its last file's patch is an excerpt, read whole with `path`.
|
|
6135
|
+
...(cut && { cut: true }),
|
|
6136
|
+
// Its repository's branch, for the panel (a root repository's too); none when detached.
|
|
6137
|
+
branch:
|
|
6138
|
+
status?.branch === undefined
|
|
6139
|
+
? null
|
|
6140
|
+
: {
|
|
6141
|
+
name: status.branch,
|
|
6142
|
+
isDefault: status.isDefault,
|
|
6143
|
+
remote: status.remote,
|
|
6144
|
+
upstream: !!status.upstream,
|
|
6145
|
+
unpushed: status.unpushed ?? 0,
|
|
6146
|
+
},
|
|
6147
|
+
// The repository's other uncommitted files: a commit of the session's leaves them out.
|
|
6148
|
+
others: others.slice(0, OTHERS_MAX),
|
|
6149
|
+
github: ctx.get('github', false) ? ('ready' as const) : ('missing' as const),
|
|
6150
|
+
};
|
|
6151
|
+
} catch (error) {
|
|
6152
|
+
throw fromGit(error);
|
|
6153
|
+
}
|
|
6154
|
+
},
|
|
6155
|
+
});
|
|
6156
|
+
|
|
6157
|
+
// Lines of a file the session changed, as its folder holds them now: the diff's folds expand with them.
|
|
6158
|
+
ctx.router.route(ctx, {
|
|
6159
|
+
method: 'POST',
|
|
6160
|
+
path: '/sessions/lines',
|
|
6161
|
+
handle: async ({ body }) => {
|
|
6162
|
+
const { id, path, from, to } = parse(
|
|
6163
|
+
linesBody,
|
|
6164
|
+
body,
|
|
6165
|
+
'POST /sessions/lines takes { id, path, from, to }',
|
|
6166
|
+
);
|
|
6167
|
+
const { node, value } = await find(new URLSearchParams({ id }));
|
|
6168
|
+
const { top, git: service } = await repositoryNow(id, node);
|
|
6169
|
+
// One file the session changed, never another path (outside its repository, or another session's).
|
|
6170
|
+
if (!(value.files ?? []).includes(path))
|
|
6171
|
+
throw refused('not_its_file', `session ${id} did not change ${path}`);
|
|
6172
|
+
return { id, path, lines: await service.lines(top, path, from, to).catch((error: unknown) => Promise.reject(fromGit(error))) };
|
|
6173
|
+
},
|
|
6174
|
+
});
|
|
6175
|
+
|
|
6176
|
+
// Open in editor (bridge-plugins#253): the session's folder, or a file in it or in its repository (a path relative to
|
|
6177
|
+
// the repository's top as the changes list it, or absolute as the conversation writes it), at a line; in the code
|
|
6178
|
+
// editor of the `git` plugin's setting, on this Bridge's computer. A person's action, never an agent's.
|
|
6179
|
+
ctx.router.route(ctx, {
|
|
6180
|
+
method: 'POST',
|
|
6181
|
+
path: '/sessions/open-in-editor',
|
|
6182
|
+
agent: false,
|
|
6183
|
+
handle: async ({ body, local }) => {
|
|
6184
|
+
// The host says whether the page runs on Bridge's own computer (from its connection): an editor opened from
|
|
6185
|
+
// another one would open here, out of its person's sight.
|
|
6186
|
+
if (local !== true)
|
|
6187
|
+
throw refused('not_local', 'Open in editor is not available yet from another computer', 403);
|
|
6188
|
+
const { id, path, line, column } = parse(openBody, body, 'POST /sessions/open-in-editor takes { id, path?, line?, column? }');
|
|
6189
|
+
const { node, value } = await find(new URLSearchParams({ id }));
|
|
6190
|
+
const service = git();
|
|
6191
|
+
if (typeof service?.openInEditor !== 'function')
|
|
6192
|
+
throw refused('no_editor', 'Open in editor needs the git plugin 0.0.3 or later: install or update Git', 409);
|
|
6193
|
+
const folder = await sessionFolder(node, value);
|
|
6194
|
+
if (folder === undefined) throw refused('not_found', `session ${id} works in no folder`, 404);
|
|
6195
|
+
const root = (await repositoryOf(folder))?.top ?? folder;
|
|
6196
|
+
const target = path === undefined ? folder : isAbsolute(path) ? path : join(root, path);
|
|
5806
6197
|
return {
|
|
5807
6198
|
id,
|
|
5808
|
-
|
|
5809
|
-
|
|
5810
|
-
|
|
5811
|
-
running: running.has(id),
|
|
5812
|
-
files: files.map((path) => ({ path, pending: state.has(path) })),
|
|
5813
|
-
commits: value.commits ?? [],
|
|
5814
|
-
shared: await sharing(id, top, state, files),
|
|
5815
|
-
diff: await diffOf(
|
|
5816
|
-
run,
|
|
5817
|
-
top,
|
|
5818
|
-
pending,
|
|
5819
|
-
DIFF_MAX,
|
|
5820
|
-
async (path) => (await ctx.fs.stat(ctx, join(top, path)).catch(() => undefined))?.size,
|
|
5821
|
-
),
|
|
6199
|
+
...(await service
|
|
6200
|
+
.openInEditor(root, target, { ...(line && { line }), ...(column && { column }) })
|
|
6201
|
+
.catch((error: unknown) => Promise.reject(fromGit(error)))),
|
|
5822
6202
|
};
|
|
5823
6203
|
},
|
|
5824
6204
|
});
|
|
@@ -5833,51 +6213,77 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5833
6213
|
message,
|
|
5834
6214
|
files: chosen,
|
|
5835
6215
|
force,
|
|
5836
|
-
} = parse(commitBody, body, 'POST /sessions/commit takes { id, message
|
|
6216
|
+
} = parse(commitBody, body, 'POST /sessions/commit takes { id, message?, files?, force? }');
|
|
5837
6217
|
const { node, value } = await find(new URLSearchParams({ id }));
|
|
5838
6218
|
if (running.has(id)) throw refused('session_busy', `session ${id} has a turn running`, 409);
|
|
5839
|
-
const { top } = await repositoryNow(id, node);
|
|
5840
|
-
const
|
|
5841
|
-
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
|
|
5845
|
-
|
|
5846
|
-
|
|
5847
|
-
|
|
5848
|
-
|
|
5849
|
-
|
|
5850
|
-
|
|
5851
|
-
|
|
5852
|
-
|
|
5853
|
-
|
|
5854
|
-
|
|
5855
|
-
|
|
5856
|
-
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
|
|
5861
|
-
);
|
|
5862
|
-
|
|
5863
|
-
|
|
5864
|
-
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
}
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
6219
|
+
const { top, git: service } = await repositoryNow(id, node);
|
|
6220
|
+
const own = new Set(value.files ?? []);
|
|
6221
|
+
if (chosen?.some((file) => !own.has(file)))
|
|
6222
|
+
throw refused(
|
|
6223
|
+
'not_its_file',
|
|
6224
|
+
`session ${id} did not change ${chosen.filter((file) => !own.has(file)).join(', ')}`,
|
|
6225
|
+
);
|
|
6226
|
+
let shared: Awaited<ReturnType<typeof sharing>> = [];
|
|
6227
|
+
try {
|
|
6228
|
+
// Its files, or the ones chosen, as `git` stages them in an index of its own (the real one untouched while the
|
|
6229
|
+
// message is written), one commit at a time per repository. Inside that queue, before staging and again once the
|
|
6230
|
+
// message is written: its turn, and who else changed them (`POST /sessions/changes`'s `shared` lists them;
|
|
6231
|
+
// `force` takes their changes too).
|
|
6232
|
+
// No message: the session's agent writes one from its conversation and what goes in, as the project plugin's
|
|
6233
|
+
// commit does; refused (`not_written`) when it cannot. A nested repository among them stays out, and pending:
|
|
6234
|
+
// `left` says so (plugins#145).
|
|
6235
|
+
const done = await service.commit(top, {
|
|
6236
|
+
scope: 'paths',
|
|
6237
|
+
paths: chosen ?? [...own],
|
|
6238
|
+
maxChars: DIFF_MAX,
|
|
6239
|
+
trailers: { 'Bridge-Session': id },
|
|
6240
|
+
preflight: async (files) => {
|
|
6241
|
+
if (running.has(id)) throw refused('session_busy', `session ${id} has a turn running`, 409);
|
|
6242
|
+
shared = await sharing(id, top, (await service.snapshot(top)) ?? new Map<string, string>(), files);
|
|
6243
|
+
if (shared.length && !force)
|
|
6244
|
+
throw refused(
|
|
6245
|
+
'files_shared',
|
|
6246
|
+
`other sessions changed these files too: ${[...new Set(shared.flatMap((each) => each.files))].join(', ')}; commit with force to take their changes too`,
|
|
6247
|
+
409,
|
|
6248
|
+
);
|
|
6249
|
+
},
|
|
6250
|
+
message:
|
|
6251
|
+
message ||
|
|
6252
|
+
(async ({ recent, diff, signal }) => {
|
|
6253
|
+
const written = await writeAfter([id], {
|
|
6254
|
+
node,
|
|
6255
|
+
cwd: top,
|
|
6256
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(WRITE_MS)]),
|
|
6257
|
+
prompt: [
|
|
6258
|
+
'Write the git commit message for the changes below.',
|
|
6259
|
+
'Answer with the message only: a subject line (under 72 characters), a blank line, then a short body saying what changed and why, wrapped at 100 columns. No code fence, no preamble.',
|
|
6260
|
+
`Follow the style of this repository's recent commits:\n${recent.join('\n')}`,
|
|
6261
|
+
`Diff:\n${diff}`,
|
|
6262
|
+
].join('\n\n'),
|
|
6263
|
+
});
|
|
6264
|
+
return written.text;
|
|
6265
|
+
}),
|
|
5879
6266
|
});
|
|
5880
|
-
|
|
6267
|
+
const at = new Date().toISOString();
|
|
6268
|
+
const entry = { sha: done.sha, at, message: done.message, files: done.files };
|
|
6269
|
+
await change(id, (now) => ({
|
|
6270
|
+
...release(now, done.files),
|
|
6271
|
+
commits: [...(now.commits ?? []), entry],
|
|
6272
|
+
}));
|
|
6273
|
+
append(id, 'commit', entry);
|
|
6274
|
+
return {
|
|
6275
|
+
id,
|
|
6276
|
+
node,
|
|
6277
|
+
...entry,
|
|
6278
|
+
shared,
|
|
6279
|
+
...(done.left.length && { left: done.left }),
|
|
6280
|
+
...(done.recovery && { recovery: done.recovery }),
|
|
6281
|
+
};
|
|
6282
|
+
} catch (error) {
|
|
6283
|
+
if (isRecord(error) && error.code === 'nothing_to_commit')
|
|
6284
|
+
throw refused('nothing_to_commit', `session ${id} has no uncommitted change`, 409);
|
|
6285
|
+
throw fromGit(error);
|
|
6286
|
+
}
|
|
5881
6287
|
},
|
|
5882
6288
|
});
|
|
5883
6289
|
|