@bridgebrew/sessions 0.0.33 → 0.0.38
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 +34 -0
- package/browser/branch-actions.tsx +26 -47
- package/browser/children.tsx +1 -1
- package/browser/conversation.tsx +45 -3
- package/browser/details.tsx +408 -0
- package/browser/gallery.tsx +1 -1
- package/browser/index.tsx +609 -498
- package/browser/media-origins.tsx +1 -1
- package/browser/mobile.tsx +120 -10
- package/browser/pull-request.tsx +9 -6
- package/browser/session-scheduled.tsx +6 -3
- package/browser/subagent-view.tsx +2 -2
- package/browser/subagents.tsx +1 -1
- package/contract.ts +6 -0
- package/delegations.ts +4 -3
- package/package.json +44 -7
- package/server.ts +563 -237
- 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,7 +156,7 @@
|
|
|
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
162
|
import { cutText, isRecord, oneLine } from './text.ts';
|
|
@@ -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,30 @@ 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 linesBody = z.strictObject({
|
|
873
|
+
id: z.string().min(1),
|
|
874
|
+
path: z.string().min(1),
|
|
875
|
+
from: z.number().int().min(1),
|
|
876
|
+
to: z.number().int().min(1),
|
|
877
|
+
});
|
|
826
878
|
const commitBody = z.strictObject({
|
|
827
879
|
id: z.string().min(1),
|
|
828
|
-
|
|
880
|
+
/** Empty or left out: the session's agent writes it from the conversation and the diff (`POST /sessions/write`). */
|
|
881
|
+
message: z.string().trim().max(10_000).optional(),
|
|
829
882
|
files: z.array(z.string().min(1)).optional(),
|
|
830
883
|
force: z.boolean().optional(),
|
|
831
884
|
});
|
|
832
885
|
/** The most files a session keeps (its newest); the most characters of a changes diff. */
|
|
833
886
|
const FILES_MAX = 1000;
|
|
834
887
|
const DIFF_MAX = 24 * 1024;
|
|
888
|
+
/** Past this many pending files, `POST /sessions/changes` gives each one's counts but no diff: one file's is read
|
|
889
|
+
* with `path` (the diff of so many is cut past `DIFF_MAX` anyway, most files then without theirs). */
|
|
890
|
+
const DIFF_FILES_MAX = 50;
|
|
891
|
+
/** The most other uncommitted files of a session's repository `POST /sessions/changes` names. */
|
|
892
|
+
const OTHERS_MAX = 50;
|
|
893
|
+
/** How long the agent may take to write a commit message left empty. */
|
|
894
|
+
const WRITE_MS = 120_000;
|
|
835
895
|
/** Between auto-settle checks: an hour. */
|
|
836
896
|
const SWEEP_MS = 3_600_000;
|
|
837
897
|
const DAY_MS = 86_400_000;
|
|
@@ -868,6 +928,8 @@ export interface Options {
|
|
|
868
928
|
pullRequestSyncMs?: number;
|
|
869
929
|
branchNameMs?: number;
|
|
870
930
|
flushRetryMs?: number;
|
|
931
|
+
/** How long the composer's `/` menu waits for an agent's commands. */
|
|
932
|
+
commandsMs?: number;
|
|
871
933
|
}
|
|
872
934
|
/** `config`'s positive number `key`, else `fallback`. */
|
|
873
935
|
const optionOf = (config: unknown, key: keyof Options, fallback: number) => {
|
|
@@ -1144,6 +1206,39 @@ const disabledMessage = (harness: string) =>
|
|
|
1144
1206
|
`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
1207
|
const refused = (code: string, message: string, status = 400) =>
|
|
1146
1208
|
Object.assign(new Error(message), { code, status, [Symbol.for('bridge.clientError')]: true });
|
|
1209
|
+
/** The status a refusal of the `git` service is answered with, by its code. */
|
|
1210
|
+
const GIT_STATUS: Record<string, number> = {
|
|
1211
|
+
not_a_repository: 409,
|
|
1212
|
+
invalid_path: 400,
|
|
1213
|
+
outside_repository: 403,
|
|
1214
|
+
not_found: 404,
|
|
1215
|
+
too_large: 400,
|
|
1216
|
+
nothing_to_commit: 409,
|
|
1217
|
+
nothing_written: 409,
|
|
1218
|
+
conflict: 409,
|
|
1219
|
+
stale_snapshot: 409,
|
|
1220
|
+
busy: 409,
|
|
1221
|
+
timeout: 504,
|
|
1222
|
+
// git itself refused (a hook, a signer): its words reach the person.
|
|
1223
|
+
failed: 409,
|
|
1224
|
+
};
|
|
1225
|
+
/** A refusal of the `git` service as this plugin's own (its code kept); anything else as it is. */
|
|
1226
|
+
const fromGit = (error: unknown) =>
|
|
1227
|
+
isRecord(error) && typeof error.code === 'string' && GIT_STATUS[error.code] !== undefined
|
|
1228
|
+
? refused(error.code, error instanceof Error ? error.message : String(error), GIT_STATUS[error.code])
|
|
1229
|
+
: error;
|
|
1230
|
+
/** `path` (absolute, or relative to `folder`, a folder of `repository`) relative to the repository's top, `/`-separated
|
|
1231
|
+
* (`''`: the top itself); `undefined` outside it. The top git gives may be another spelling of `folder`'s (symbolic
|
|
1232
|
+
* links resolved): a path in `folder` goes through `prefix`. */
|
|
1233
|
+
const within = ({ top, prefix }: Pick<Repository, 'top' | 'prefix'>, folder: string, path: string) => {
|
|
1234
|
+
const inside = (base: string, file: string) => {
|
|
1235
|
+
const rel = relative(base, file);
|
|
1236
|
+
return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel.split(sep).join('/');
|
|
1237
|
+
};
|
|
1238
|
+
const file = isAbsolute(path) ? path : join(folder, path);
|
|
1239
|
+
const local = inside(folder, file);
|
|
1240
|
+
return local === undefined ? inside(top, file) : `${prefix}${local}`.replace(/\/$/, '');
|
|
1241
|
+
};
|
|
1147
1242
|
const parse = <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string): T => {
|
|
1148
1243
|
let parsed;
|
|
1149
1244
|
try {
|
|
@@ -1160,6 +1255,35 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1160
1255
|
const continuationWindowMs = optionOf(config, 'continuationWindowMs', CONTINUATION_WINDOW_MS);
|
|
1161
1256
|
const driverPollMs = optionOf(config, 'driverPollMs', DRIVER_POLL_MS);
|
|
1162
1257
|
const driverWaitMs = optionOf(config, 'driverWaitMs', DRIVER_WAIT_MS);
|
|
1258
|
+
/** The `git` plugin's service (`@bridgebrew/git`, bridge-plugins#256), optional: without it a session works as one
|
|
1259
|
+
* outside any repository (no changes, no commit, no branch of its own), and the page offers to install it. */
|
|
1260
|
+
const git = () => {
|
|
1261
|
+
const service: unknown = ctx.get('git', false);
|
|
1262
|
+
return isRecord(service) && typeof service.version === 'string' && service.version.startsWith('1.')
|
|
1263
|
+
? // oxlint-disable-next-line bridge/no-new-unchecked-cast -- the `git` plugin's own service, its contract's major checked above
|
|
1264
|
+
(service as unknown as GitService)
|
|
1265
|
+
: undefined;
|
|
1266
|
+
};
|
|
1267
|
+
/** The branches of the repository at `folder` that have a folder, as git lists them: its own checkout first, then
|
|
1268
|
+
* each worktree under its `.worktrees/` (research-083). A folder's name is never read as a branch's name (`feat/x`
|
|
1269
|
+
* and `feat-x` share one); a detached one is left out. */
|
|
1270
|
+
const worktreesOf = async (folder: string) => {
|
|
1271
|
+
const all = (await git()?.worktrees(folder).catch(() => undefined)) ?? [];
|
|
1272
|
+
const main = all[0]?.folder;
|
|
1273
|
+
return all.flatMap(({ branch, folder: path }) =>
|
|
1274
|
+
branch !== undefined && (path === main || path.startsWith(`${main}/.worktrees/`))
|
|
1275
|
+
? [{ name: branch, folder: path }]
|
|
1276
|
+
: [],
|
|
1277
|
+
);
|
|
1278
|
+
};
|
|
1279
|
+
/** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has, each read as its
|
|
1280
|
+
* full name (`heads/<name>` beside a tag of the same name: plugins#198). */
|
|
1281
|
+
const freeBranch = async (folder: string, name: string) => {
|
|
1282
|
+
const taken = new Set((await git()?.branchNames(folder).catch(() => undefined)) ?? []);
|
|
1283
|
+
let free = name;
|
|
1284
|
+
for (let n = 2; taken.has(free); n++) free = `${name}-${n}`;
|
|
1285
|
+
return free;
|
|
1286
|
+
};
|
|
1163
1287
|
const branchNameMs = optionOf(config, 'branchNameMs', BRANCH_NAME_MS);
|
|
1164
1288
|
const flushRetryMs = optionOf(config, 'flushRetryMs', FLUSH_RETRY_MS);
|
|
1165
1289
|
// Cordis unloads independent effects in parallel. Group each storage release after the same
|
|
@@ -1248,7 +1372,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1248
1372
|
* project's own for its checked-out branch, else its worktree under `.worktrees/`); refused when it has none. */
|
|
1249
1373
|
const branchOf = async (node: string, name: string) => {
|
|
1250
1374
|
const project = await folderOf(node);
|
|
1251
|
-
const found = project && (await worktreesOf(
|
|
1375
|
+
const found = project && (await worktreesOf(project)).find((each) => each.name === name);
|
|
1252
1376
|
if (!found) throw refused('branch_unknown', `no folder of branch ${name} in project ${node}`);
|
|
1253
1377
|
return { name, folder: found.folder };
|
|
1254
1378
|
};
|
|
@@ -1263,7 +1387,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1263
1387
|
service ? `node ${node} has no branches here` : 'branches need Projects 0.0.2 or later in this workspace: install or update it (Plugins)',
|
|
1264
1388
|
);
|
|
1265
1389
|
try {
|
|
1266
|
-
const made = await service.newBranch({ node, name: await freeBranch(
|
|
1390
|
+
const made = await service.newBranch({ node, name: await freeBranch(project, name) });
|
|
1267
1391
|
return { ...made, ...(temporary && { temporary: true as const }) };
|
|
1268
1392
|
} catch (error) {
|
|
1269
1393
|
throw refused('branch_refused', error instanceof Error ? error.message : String(error));
|
|
@@ -1350,11 +1474,9 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1350
1474
|
/** Each new branch named in the background now (plugins#76), by its folder: the session whose first message asked, the
|
|
1351
1475
|
* naming's stop (that session's Stop or archive, or this plugin's end) and its end. */
|
|
1352
1476
|
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
|
-
'';
|
|
1477
|
+
/** Whether branch `name` in `folder` was pushed: it has an upstream, or a remote branch of its name (git missing:
|
|
1478
|
+
* taken as pushed, its name kept). */
|
|
1479
|
+
const pushed = async (folder: string, name: string) => (await git()?.pushed(folder, name)) ?? true;
|
|
1358
1480
|
/** Session `id`'s new branch named for `text` (its first message) in the background, its turn not waiting
|
|
1359
1481
|
* (plugins#76): a `type/topic` name the model of `harness` writes (plugins#73), else the message's words when it
|
|
1360
1482
|
* writes none in `branchNameMs` or fails; then every session in its folder reads that name, `temporary` gone. Its
|
|
@@ -1405,10 +1527,13 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1405
1527
|
let name = branch.name;
|
|
1406
1528
|
if (wanted && (await pushed(branch.folder, branch.name))) warn('was pushed: its name is kept');
|
|
1407
1529
|
else if (wanted) {
|
|
1408
|
-
const free = await freeBranch(
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1530
|
+
const free = await freeBranch(branch.folder, wanted);
|
|
1531
|
+
await git()
|
|
1532
|
+
?.renameBranch(branch.folder, branch.name, free)
|
|
1533
|
+
.then(
|
|
1534
|
+
() => (name = free),
|
|
1535
|
+
(error: unknown) => warn(`not renamed ${free}: ${error instanceof Error ? error.message : String(error)}`),
|
|
1536
|
+
);
|
|
1412
1537
|
}
|
|
1413
1538
|
// The sessions that joined it read its name too.
|
|
1414
1539
|
await branchMoved(node, branch.folder, { name, folder: branch.folder });
|
|
@@ -1458,7 +1583,12 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1458
1583
|
.then(async () => {
|
|
1459
1584
|
const found = await sessions.get(id);
|
|
1460
1585
|
if (!found) throw refused('not_found', `no session ${id}`, 404);
|
|
1461
|
-
|
|
1586
|
+
// The fields another plugin wrote leave before `fn` and come back after: kept whatever `fn` returns.
|
|
1587
|
+
const own: Record<string, unknown> = {};
|
|
1588
|
+
const foreign: Record<string, unknown> = {};
|
|
1589
|
+
for (const [key, each] of Object.entries(found.value))
|
|
1590
|
+
(Object.hasOwn(sessionShape, key) ? own : foreign)[key] = each;
|
|
1591
|
+
const value = { ...foreign, ...ownSession.parse(fn(own as Session)) };
|
|
1462
1592
|
await sessions.update(ctx, id, value);
|
|
1463
1593
|
return value;
|
|
1464
1594
|
});
|
|
@@ -1490,8 +1620,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1490
1620
|
if (!branch || (await ctx.fs.stat(ctx, branch.folder))) return value;
|
|
1491
1621
|
const project = await folderOf(node);
|
|
1492
1622
|
const kept =
|
|
1493
|
-
project !== undefined &&
|
|
1494
|
-
(await run(project, ['branch', '--list', branch.name])).stdout.trim() !== '';
|
|
1623
|
+
project !== undefined && !!(await git()?.branchNames(project))?.includes(branch.name);
|
|
1495
1624
|
const service = projectBranches();
|
|
1496
1625
|
if (!kept || !service)
|
|
1497
1626
|
throw new Error(
|
|
@@ -1543,15 +1672,16 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1543
1672
|
// (`git.ts`), and keeps those that changed as the session's `files`; while another session's turn ran in the same
|
|
1544
1673
|
// repository meanwhile, only the ones its agent's tool calls named (`paths`) are its own. Outside a repository, the
|
|
1545
1674
|
// named ones only.
|
|
1546
|
-
|
|
1547
|
-
/** The repository of each session folder (`null`: none), asked once. */
|
|
1675
|
+
/** The repository of each session folder (`null`: none), asked once while the `git` plugin is there. */
|
|
1548
1676
|
const repositories = new Map<string, Promise<Repository | null>>();
|
|
1549
1677
|
const repositoryOf = (folder: string) => {
|
|
1678
|
+
const service = git();
|
|
1679
|
+
if (!service) return Promise.resolve(null);
|
|
1550
1680
|
let found = repositories.get(folder);
|
|
1551
1681
|
if (!found)
|
|
1552
1682
|
repositories.set(
|
|
1553
1683
|
folder,
|
|
1554
|
-
(found = repositoryAt(
|
|
1684
|
+
(found = service.repositoryAt(folder).then(
|
|
1555
1685
|
(each) => each ?? null,
|
|
1556
1686
|
() => null,
|
|
1557
1687
|
)),
|
|
@@ -1583,8 +1713,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1583
1713
|
}
|
|
1584
1714
|
return found;
|
|
1585
1715
|
};
|
|
1586
|
-
/** The commits running per repository: one at a time. */
|
|
1587
|
-
const commits = new Map<string, Promise<unknown>>();
|
|
1588
1716
|
/** The tags of the workspace's sessions (archived ones too), most used first. */
|
|
1589
1717
|
const tagsOf = async () => {
|
|
1590
1718
|
const counts = new Map<string, number>();
|
|
@@ -1604,6 +1732,11 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1604
1732
|
* of the chain stores them all with `after` the `seq` before the first, the log's last `n`; a failed one leaves them
|
|
1605
1733
|
* for the next, so a transient failure loses nothing and changes no number watchers saw. */
|
|
1606
1734
|
const outbox = new Map<string, Line[]>();
|
|
1735
|
+
/** Per session, its history log's last `n`, seeded at the start (after the repair below) and moved by each append that
|
|
1736
|
+
* lands: with the outbox, the only base of numbering (`seqOf`), so a line is never numbered from a stale count. */
|
|
1737
|
+
const saved = new Map<string, number>();
|
|
1738
|
+
/** The `seq` of session `id`'s newest line: the log's, then its outbox's. */
|
|
1739
|
+
const seqOf = (id: string) => (saved.get(id) ?? 0) + (outbox.get(id)?.length ?? 0);
|
|
1607
1740
|
/** Session `id`'s history after `seq` `after`, in order: what the log holds, then its outbox. */
|
|
1608
1741
|
const readEvents = async (id: string, after = 0) => {
|
|
1609
1742
|
const events: Line[] = [];
|
|
@@ -1737,8 +1870,11 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1737
1870
|
const start = String(turn[0]?.time ?? '');
|
|
1738
1871
|
if (crashed ? !!lastTurn && lastTurn.endedAt >= start : lastTurn?.endedAt === endedAt) return;
|
|
1739
1872
|
const message = turn.find(({ type }) => type === 'user/message');
|
|
1873
|
+
// Its agent got the message: a line past it shows it, or the record does when a failing disk lost those lines.
|
|
1740
1874
|
const resend =
|
|
1741
|
-
message &&
|
|
1875
|
+
message &&
|
|
1876
|
+
(turn[0]?.turn === undefined || found.value.delivered !== turn[0].turn) &&
|
|
1877
|
+
!turn.some(({ type }) => !BEFORE_AGENT.has(type))
|
|
1742
1878
|
? queueItem.safeParse(
|
|
1743
1879
|
Object.fromEntries(
|
|
1744
1880
|
Object.entries({
|
|
@@ -1790,6 +1926,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1790
1926
|
// 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
1927
|
// turn is closed), past it for one of Bridge's.
|
|
1792
1928
|
for (const { stream: id, last } of await allStreams()) {
|
|
1929
|
+
saved.set(id, last);
|
|
1793
1930
|
try {
|
|
1794
1931
|
const tail: Line[] = [];
|
|
1795
1932
|
let ended: Line | undefined;
|
|
@@ -1824,7 +1961,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1824
1961
|
by: 'bridge',
|
|
1825
1962
|
},
|
|
1826
1963
|
].map((line) => ({ time, ...line }));
|
|
1827
|
-
await history.append(ctx, id, lines, { after: last });
|
|
1964
|
+
saved.set(id, await history.append(ctx, id, lines, { after: last }));
|
|
1828
1965
|
await markCut(id, turn, time, true);
|
|
1829
1966
|
} catch (error) {
|
|
1830
1967
|
ctx
|
|
@@ -1832,6 +1969,9 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1832
1969
|
.error(
|
|
1833
1970
|
`session ${id}: open turn not closed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1834
1971
|
);
|
|
1972
|
+
// An append reported failed may be durable all the same: the next line goes after the log's real end.
|
|
1973
|
+
const end = await history.last(id).catch(() => undefined);
|
|
1974
|
+
if (end !== undefined) saved.set(id, end);
|
|
1835
1975
|
}
|
|
1836
1976
|
}
|
|
1837
1977
|
|
|
@@ -1952,8 +2092,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
1952
2092
|
const live = new Map<string, Live>();
|
|
1953
2093
|
/** Each session's write queue: its last pending append (appends are chained, in `seq` order). */
|
|
1954
2094
|
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
2095
|
/** Sessions whose running turn was asked to stop: one not yet prompting ends without its prompt. */
|
|
1958
2096
|
const stopping = new Set<string>();
|
|
1959
2097
|
/** The running turns: `take` removes an open decision (`false` when it is not open), `record` stores its answer
|
|
@@ -2207,7 +2345,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2207
2345
|
if (!pending?.length) return;
|
|
2208
2346
|
const batch = pending.slice();
|
|
2209
2347
|
try {
|
|
2210
|
-
await history.append(
|
|
2348
|
+
const last = await history.append(
|
|
2211
2349
|
ctx,
|
|
2212
2350
|
id,
|
|
2213
2351
|
batch.map(({ seq: _seq, ...line }) => line as z.infer<typeof historyLine>),
|
|
@@ -2215,21 +2353,26 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2215
2353
|
);
|
|
2216
2354
|
pending.splice(0, batch.length);
|
|
2217
2355
|
if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
|
|
2356
|
+
saved.set(id, last);
|
|
2357
|
+
emit(id, { type: 'saved', seq: last });
|
|
2218
2358
|
clearFlushRetry(id);
|
|
2219
2359
|
} catch (error) {
|
|
2360
|
+
// A conflict: the log ends elsewhere. With one writer numbering from the log's end, that is a rejected append
|
|
2361
|
+
// that was durable after all: the lines it holds leave the outbox, the next try goes on after them.
|
|
2362
|
+
const conflict = (error as { code?: unknown } | null)?.code === 'log_conflict';
|
|
2220
2363
|
ctx
|
|
2221
2364
|
.logger('sessions')
|
|
2222
2365
|
.error(
|
|
2223
|
-
`session ${id}: history not written (${batch.length} lines kept for the next try): ${error instanceof Error ? error.message : String(error)}`,
|
|
2366
|
+
`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
2367
|
);
|
|
2225
|
-
|
|
2226
|
-
// the outbox, so the next try goes on after them.
|
|
2227
|
-
if ((error as { code?: unknown } | null)?.code === 'log_conflict') {
|
|
2368
|
+
if (conflict) {
|
|
2228
2369
|
const last = await history.last(id).catch(() => undefined);
|
|
2229
2370
|
if (last !== undefined) {
|
|
2230
2371
|
const kept = pending.filter(({ seq }) => seq > last);
|
|
2231
2372
|
pending.splice(0, pending.length, ...kept);
|
|
2232
2373
|
if (!pending.length && outbox.get(id) === pending) outbox.delete(id);
|
|
2374
|
+
saved.set(id, last);
|
|
2375
|
+
emit(id, { type: 'saved', seq: last });
|
|
2233
2376
|
}
|
|
2234
2377
|
}
|
|
2235
2378
|
if (pending.length) scheduleFlushRetry(id);
|
|
@@ -2245,13 +2388,12 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2245
2388
|
chains.set(id, chain);
|
|
2246
2389
|
return chain;
|
|
2247
2390
|
};
|
|
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.
|
|
2391
|
+
/** Queues one settled line of session `id`: its `seq` taken now (`seqOf`, past the log and the outbox), the line put
|
|
2392
|
+
* in its outbox, stored by the next step of its chain (with the lines a failed step left); watchers get it at once.
|
|
2250
2393
|
* ponytail: watchers see a line before it is durable, which AD-14 does not allow for domain subscribers; change it
|
|
2251
2394
|
* only with the page's merge of `live` and `stored` messages. */
|
|
2252
2395
|
const append = (id: string, type: string, data: object = {}) => {
|
|
2253
|
-
const seq = (
|
|
2254
|
-
lastSeq.set(id, seq);
|
|
2396
|
+
const seq = seqOf(id) + 1;
|
|
2255
2397
|
const acc = live.get(id);
|
|
2256
2398
|
if (acc) acc.seq = seq;
|
|
2257
2399
|
const event = { seq, time: new Date().toISOString(), type, ...data } as Line;
|
|
@@ -2261,16 +2403,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2261
2403
|
void queueFlush(id);
|
|
2262
2404
|
emit(id, { type: 'stored', event: fit(event) });
|
|
2263
2405
|
};
|
|
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
2406
|
const finalizing = new Map<string, Set<Promise<unknown>>>();
|
|
2275
2407
|
const finalize = (id: string, work: Promise<unknown>) => {
|
|
2276
2408
|
let tasks = finalizing.get(id);
|
|
@@ -2692,6 +2824,36 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2692
2824
|
},
|
|
2693
2825
|
});
|
|
2694
2826
|
|
|
2827
|
+
/** `prompt` written once (`writeOnce`) after the conversations of `ids` (what the user asked, what the agent
|
|
2828
|
+
* answered), in a throwaway session of the first one's profile. */
|
|
2829
|
+
const writeAfter = async (
|
|
2830
|
+
ids: string[],
|
|
2831
|
+
options: { node: string; cwd: string; prompt: string; signal?: AbortSignal },
|
|
2832
|
+
) => {
|
|
2833
|
+
const talk: string[] = [];
|
|
2834
|
+
let harness: string | undefined;
|
|
2835
|
+
for (const id of ids) {
|
|
2836
|
+
const found = await sessions.get(id);
|
|
2837
|
+
if (!found) continue;
|
|
2838
|
+
harness ??= found.value.harness;
|
|
2839
|
+
talk.push(`## Session “${found.value.title}”`);
|
|
2840
|
+
for (const line of await readEvents(id))
|
|
2841
|
+
if (typeof line.text !== 'string' || line.subagent !== undefined) continue;
|
|
2842
|
+
else if (line.type === 'user/message' && line.from === undefined)
|
|
2843
|
+
talk.push(`User: ${line.text}`);
|
|
2844
|
+
else if (line.type === 'assistant/message') talk.push(`Agent: ${line.text}`);
|
|
2845
|
+
}
|
|
2846
|
+
// The conversation's newest part when it is long.
|
|
2847
|
+
const conversation = talk.join('\n\n').slice(-40_000);
|
|
2848
|
+
return writeOnce({
|
|
2849
|
+
...options,
|
|
2850
|
+
...(harness !== undefined && { harness }),
|
|
2851
|
+
prompt: conversation
|
|
2852
|
+
? `The conversation of the work, for context:\n\n${conversation}\n\n---\n\n${options.prompt}`
|
|
2853
|
+
: options.prompt,
|
|
2854
|
+
});
|
|
2855
|
+
};
|
|
2856
|
+
|
|
2695
2857
|
/** `POST /sessions/write` (research-083): a text a model writes once for Bridge (a commit message, a pull request's
|
|
2696
2858
|
* title and description), `prompt` after the conversations of `sessions` (what the user asked, what the agent
|
|
2697
2859
|
* answered), in a throwaway session of the first session's profile (`writeOnce`). */
|
|
@@ -2712,29 +2874,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2712
2874
|
);
|
|
2713
2875
|
const cwd = await folderOf(node);
|
|
2714
2876
|
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
|
-
});
|
|
2877
|
+
return writeAfter(input.sessions ?? [], { node, cwd, prompt: input.prompt });
|
|
2738
2878
|
},
|
|
2739
2879
|
});
|
|
2740
2880
|
|
|
@@ -2788,6 +2928,115 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2788
2928
|
},
|
|
2789
2929
|
});
|
|
2790
2930
|
|
|
2931
|
+
// The composer's menus (plugins#239): `@` a file of the folder a session works in, `/` its agent's commands. Both
|
|
2932
|
+
// read the session's own folder (its branch's or worktree's: `id`), a new chat's its node's.
|
|
2933
|
+
/** The folder the menus read, and session `id` when given. */
|
|
2934
|
+
const menuFolder = async (node: string, id: string | undefined) => {
|
|
2935
|
+
const found = id === undefined ? undefined : await find(new URLSearchParams({ id }));
|
|
2936
|
+
const folder = found ? await sessionFolder(found.node, found.value) : await folderOf(node);
|
|
2937
|
+
if (folder === undefined)
|
|
2938
|
+
throw refused(
|
|
2939
|
+
'not_a_project',
|
|
2940
|
+
`node ${node} is not a project: sessions live in project nodes and on the workspace (root)`,
|
|
2941
|
+
);
|
|
2942
|
+
return { folder, found };
|
|
2943
|
+
};
|
|
2944
|
+
/** Every file below `folder`, relative: git's (tracked and untracked, ignored ones left out), else (no repository, or
|
|
2945
|
+
* git cannot run) a walk that skips `.git`, `node_modules` and `.bridge` and follows no symlinked folder (a cycle, a
|
|
2946
|
+
* link out of the folder). ponytail: the walk stops at `FILES_WALK_MAX` files or `WALK_ENTRIES_MAX` entries read, a
|
|
2947
|
+
* folder that large without git finds only its first ones. */
|
|
2948
|
+
const filesOf = async (folder: string) => {
|
|
2949
|
+
const listed = await git()
|
|
2950
|
+
?.files(folder)
|
|
2951
|
+
.catch(() => undefined);
|
|
2952
|
+
if (listed) return listed;
|
|
2953
|
+
const files: string[] = [];
|
|
2954
|
+
const top = await ctx.fs.realpath(ctx, folder).catch(() => folder);
|
|
2955
|
+
const queue = [''];
|
|
2956
|
+
let entries = 0;
|
|
2957
|
+
walk: while (queue.length) {
|
|
2958
|
+
const at = queue.shift()!;
|
|
2959
|
+
const names = await ctx.fs.readdir(ctx, join(folder, at)).catch((): string[] => []);
|
|
2960
|
+
for (const name of [...names].sort()) {
|
|
2961
|
+
if (files.length >= FILES_WALK_MAX || ++entries > WALK_ENTRIES_MAX) break walk;
|
|
2962
|
+
if (WALK_SKIPPED.has(name)) continue;
|
|
2963
|
+
const path = at ? `${at}/${name}` : name;
|
|
2964
|
+
const info = await ctx.fs.stat(ctx, join(folder, path)).catch(() => undefined);
|
|
2965
|
+
if (info?.isFile) files.push(path);
|
|
2966
|
+
// A folder is walked only where it really is: a symlinked one's real path is elsewhere.
|
|
2967
|
+
else if (
|
|
2968
|
+
info?.isDirectory &&
|
|
2969
|
+
(await ctx.fs.realpath(ctx, join(folder, path)).catch(() => undefined)) ===
|
|
2970
|
+
join(top, path)
|
|
2971
|
+
)
|
|
2972
|
+
queue.push(path);
|
|
2973
|
+
}
|
|
2974
|
+
}
|
|
2975
|
+
return files;
|
|
2976
|
+
};
|
|
2977
|
+
ctx.router.route(ctx, {
|
|
2978
|
+
method: 'GET',
|
|
2979
|
+
path: '/sessions/files',
|
|
2980
|
+
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`,
|
|
2981
|
+
query: z.strictObject({ q: z.string().optional(), id: z.string().min(1).optional() }),
|
|
2982
|
+
handle: async ({ node, query }) => {
|
|
2983
|
+
const { folder } = await menuFolder(node, query.get('id') ?? undefined);
|
|
2984
|
+
return matchingFiles(await filesOf(folder), query.get('q') ?? '');
|
|
2985
|
+
},
|
|
2986
|
+
});
|
|
2987
|
+
const commandsMs = optionOf(config, 'commandsMs', COMMANDS_MS);
|
|
2988
|
+
/** Commands by profile and folder, with when they were read; a pending read is shared, a failed one not kept. */
|
|
2989
|
+
const commandLists = new Map<string, { at: number; list: Promise<Command[]> }>();
|
|
2990
|
+
ctx.router.route(ctx, {
|
|
2991
|
+
method: 'GET',
|
|
2992
|
+
path: '/sessions/commands',
|
|
2993
|
+
description:
|
|
2994
|
+
"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",
|
|
2995
|
+
query: z.strictObject({
|
|
2996
|
+
id: z.string().min(1).optional(),
|
|
2997
|
+
profile: z.string().min(1).optional(),
|
|
2998
|
+
harness: z.string().min(1).optional(),
|
|
2999
|
+
}),
|
|
3000
|
+
handle: async ({ node, query }) => {
|
|
3001
|
+
const { folder, found } = await menuFolder(node, query.get('id') ?? undefined);
|
|
3002
|
+
const harness =
|
|
3003
|
+
found?.value.harness ??
|
|
3004
|
+
profileAlias({
|
|
3005
|
+
profile: query.get('profile') ?? undefined,
|
|
3006
|
+
harness: query.get('harness') ?? undefined,
|
|
3007
|
+
});
|
|
3008
|
+
// A harness plugin older than `commands` has none: no menu, never an error.
|
|
3009
|
+
if (!ctx.harness.commands) return [];
|
|
3010
|
+
// By node too: a node may override the profile (its harness, its options).
|
|
3011
|
+
const at = found?.node ?? node;
|
|
3012
|
+
const key = `${harness}\n${at}\n${folder}`;
|
|
3013
|
+
const known = commandLists.get(key);
|
|
3014
|
+
if (known && Date.now() - known.at < COMMANDS_TTL_MS) return known.list;
|
|
3015
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
3016
|
+
// Never rejects, for every caller that shares it: an agent that cannot list them (not installed, slow, refused)
|
|
3017
|
+
// has no menu, said in the log, not to the user, and is asked again next time.
|
|
3018
|
+
const list: Promise<Command[]> = Promise.race([
|
|
3019
|
+
ctx.harness.commands({ harness, node: at, cwd: folder }),
|
|
3020
|
+
new Promise<never>((_, reject) => {
|
|
3021
|
+
timer = setTimeout(
|
|
3022
|
+
() => reject(new Error(`no commands within ${commandsMs / 1000} s`)),
|
|
3023
|
+
commandsMs,
|
|
3024
|
+
);
|
|
3025
|
+
}),
|
|
3026
|
+
])
|
|
3027
|
+
.catch((error: unknown) => {
|
|
3028
|
+
if (commandLists.get(key)?.list === list) commandLists.delete(key);
|
|
3029
|
+
ctx.logger('sessions').warn(
|
|
3030
|
+
`harness ${harness}: its commands could not be listed: ${error instanceof Error ? error.message : String(error)}`,
|
|
3031
|
+
);
|
|
3032
|
+
return [];
|
|
3033
|
+
})
|
|
3034
|
+
.finally(() => clearTimeout(timer));
|
|
3035
|
+
commandLists.set(key, { at: Date.now(), list });
|
|
3036
|
+
return list;
|
|
3037
|
+
},
|
|
3038
|
+
});
|
|
3039
|
+
|
|
2791
3040
|
ctx.router.route(ctx, {
|
|
2792
3041
|
method: 'POST',
|
|
2793
3042
|
path: '/sessions/mode',
|
|
@@ -2850,7 +3099,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2850
3099
|
throw await notApplied(error);
|
|
2851
3100
|
}
|
|
2852
3101
|
}
|
|
2853
|
-
await syncSeq(id);
|
|
2854
3102
|
await change(id, (now) => {
|
|
2855
3103
|
const { options: _old, ...rest } = now;
|
|
2856
3104
|
return { ...rest, mode, ...(kept && { options: kept }) };
|
|
@@ -2901,7 +3149,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2901
3149
|
throw await notApplied(error);
|
|
2902
3150
|
}
|
|
2903
3151
|
}
|
|
2904
|
-
await syncSeq(id);
|
|
2905
3152
|
await change(id, (now) => ({ ...now, effort }));
|
|
2906
3153
|
append(id, 'effort/changed', { effort, name: known?.name ?? effort });
|
|
2907
3154
|
return { ok: true };
|
|
@@ -2955,6 +3202,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
2955
3202
|
// One moment, synchronously: the lines stored before the first one queued meanwhile, those queued (not all
|
|
2956
3203
|
// stored yet), and the accumulator now; the live events queued meanwhile are in that copy already.
|
|
2957
3204
|
const pending = queue.splice(0);
|
|
3205
|
+
const held = saved.get(id) ?? 0;
|
|
2958
3206
|
const queued = pending.flatMap((message) =>
|
|
2959
3207
|
message.type === 'stored' ? [message.event!] : [],
|
|
2960
3208
|
);
|
|
@@ -3007,6 +3255,8 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3007
3255
|
type: 'snapshot',
|
|
3008
3256
|
events: events.slice(from),
|
|
3009
3257
|
live: snapshot,
|
|
3258
|
+
// The lines the log holds, those this stream sent at most: a page keeps them across a reconnect.
|
|
3259
|
+
saved: Math.min(held, last),
|
|
3010
3260
|
...(page && { more: page.more }),
|
|
3011
3261
|
};
|
|
3012
3262
|
for (const message of pending) if (message.type === 'open-link') yield message;
|
|
@@ -3133,8 +3383,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3133
3383
|
lastTurn: settledTurn(lastTurn),
|
|
3134
3384
|
};
|
|
3135
3385
|
});
|
|
3136
|
-
// Numbered after the stored lines: no turn ran since the start.
|
|
3137
|
-
await syncSeq(id);
|
|
3138
3386
|
append(id, 'decision/answered', {
|
|
3139
3387
|
id: decision,
|
|
3140
3388
|
...answeredLine(option),
|
|
@@ -3337,7 +3585,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3337
3585
|
return;
|
|
3338
3586
|
// It failed to start (an image gone): the queue waits for the user, as after a Stop.
|
|
3339
3587
|
halt(id);
|
|
3340
|
-
await syncSeq(id);
|
|
3341
3588
|
append(id, 'notice', {
|
|
3342
3589
|
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
3590
|
});
|
|
@@ -3605,7 +3852,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3605
3852
|
/** No line written yet: the agent gets the session's target with this message. */
|
|
3606
3853
|
let first = false;
|
|
3607
3854
|
try {
|
|
3608
|
-
first = (
|
|
3855
|
+
first = seqOf(id) === 0;
|
|
3609
3856
|
// 409: the router answers only a 4xx as it is (another status becomes a 500 `handler_error`).
|
|
3610
3857
|
if (disposed)
|
|
3611
3858
|
throw refused(
|
|
@@ -3652,7 +3899,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3652
3899
|
throw error;
|
|
3653
3900
|
}
|
|
3654
3901
|
const acc: Live = {
|
|
3655
|
-
seq:
|
|
3902
|
+
seq: seqOf(id),
|
|
3656
3903
|
text: '',
|
|
3657
3904
|
thought: '',
|
|
3658
3905
|
tools: {},
|
|
@@ -3787,13 +4034,14 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3787
4034
|
const named = [...touched]
|
|
3788
4035
|
.map((path) => within(scope, folder, path))
|
|
3789
4036
|
.filter((path): path is string => !!path);
|
|
4037
|
+
const service = git();
|
|
3790
4038
|
const after =
|
|
3791
|
-
repository && before && !disposed ? await
|
|
4039
|
+
repository && before && !disposed ? await service?.snapshot(repository.top) : undefined;
|
|
3792
4040
|
// Bridge's own data (these histories) when the workspace lies in the repository is no change of the session.
|
|
3793
4041
|
const data = repository && within(repository, folder, ctx.workspace.dataDir);
|
|
3794
4042
|
const files = (
|
|
3795
|
-
after
|
|
3796
|
-
? changed(before!, after).filter((path) => !turn.shared || named.includes(path))
|
|
4043
|
+
after && service
|
|
4044
|
+
? service.changed(before!, after).filter((path) => !turn.shared || named.includes(path))
|
|
3797
4045
|
: named
|
|
3798
4046
|
).filter((path) => !data || !`${path}/`.startsWith(`${data}/`));
|
|
3799
4047
|
if (files.length)
|
|
@@ -3957,8 +4205,10 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3957
4205
|
/** Whether the turn can take a message now: not stopping nor ending. */
|
|
3958
4206
|
const steerOpen = () =>
|
|
3959
4207
|
!ended && !aborted && !stopping.has(id) && !sendNow.has(id) && !halted.has(id);
|
|
4208
|
+
/** This turn's id, on its `turn/start` line and, once its agent answers, in the record (`delivered`). */
|
|
4209
|
+
const turnId = crypto.randomUUID();
|
|
3960
4210
|
turns.set(id, {
|
|
3961
|
-
turn:
|
|
4211
|
+
turn: turnId,
|
|
3962
4212
|
take,
|
|
3963
4213
|
record,
|
|
3964
4214
|
expire,
|
|
@@ -3998,8 +4248,19 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
3998
4248
|
});
|
|
3999
4249
|
/** Each tool call's edits, as last given (an agent may give them before the result only). */
|
|
4000
4250
|
const edits = new Map<string, Change[]>();
|
|
4251
|
+
/** The agent answered (a first event): the record says so, for the start after a crash (`markCut`). */
|
|
4252
|
+
let delivered = false;
|
|
4001
4253
|
const onEvent = (received: HarnessEvent) => {
|
|
4002
4254
|
if (ended) return;
|
|
4255
|
+
if (!delivered) {
|
|
4256
|
+
delivered = true;
|
|
4257
|
+
finalize(
|
|
4258
|
+
id,
|
|
4259
|
+
change(id, (now) => ({ ...now, delivered: turnId })).catch(
|
|
4260
|
+
log(`session ${id}: delivery not stored`),
|
|
4261
|
+
),
|
|
4262
|
+
);
|
|
4263
|
+
}
|
|
4003
4264
|
// A `show_view` call's input as the agent writes it goes live as `view/draft` (the program so far), never stored;
|
|
4004
4265
|
// another tool's draft goes nowhere (research-036 streaming).
|
|
4005
4266
|
if (received.type === 'draft') {
|
|
@@ -4269,7 +4530,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4269
4530
|
return opened;
|
|
4270
4531
|
};
|
|
4271
4532
|
|
|
4272
|
-
write('turn/start', auto
|
|
4533
|
+
write('turn/start', { turn: turnId, ...(auto && { auto: true }) });
|
|
4273
4534
|
if (!auto) write('user/message', messageLine(text, attachments, options));
|
|
4274
4535
|
// The turn runs on its own: a page that goes away does not stop it, and its end is stored.
|
|
4275
4536
|
void (async () => {
|
|
@@ -4287,7 +4548,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4287
4548
|
if (folder === undefined) return;
|
|
4288
4549
|
const repository = await repositoryOf(folder);
|
|
4289
4550
|
const top = repository?.top;
|
|
4290
|
-
const before = top ? await
|
|
4551
|
+
const before = top ? await git()?.snapshot(top).catch(() => undefined) : undefined;
|
|
4291
4552
|
const turn = { shared: false };
|
|
4292
4553
|
if (top && !ended) {
|
|
4293
4554
|
let beside = turnsIn.get(top);
|
|
@@ -4308,19 +4569,15 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4308
4569
|
if (since && !auto) {
|
|
4309
4570
|
const touched =
|
|
4310
4571
|
top && now.files?.length
|
|
4311
|
-
? await
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
'--format=%h %s (%an, %ar)',
|
|
4315
|
-
'-n',
|
|
4316
|
-
'20',
|
|
4317
|
-
'--',
|
|
4318
|
-
...now.files,
|
|
4319
|
-
])
|
|
4572
|
+
? await git()
|
|
4573
|
+
?.history(top, { since, paths: now.files, max: 20 })
|
|
4574
|
+
.catch(() => undefined)
|
|
4320
4575
|
: undefined;
|
|
4321
4576
|
preface += environmentText(
|
|
4322
4577
|
since,
|
|
4323
|
-
touched
|
|
4578
|
+
(touched ?? []).map(
|
|
4579
|
+
({ sha, subject, author, relative: ago }) => `${sha.slice(0, 7)} ${subject} (${author}, ${ago})`,
|
|
4580
|
+
),
|
|
4324
4581
|
);
|
|
4325
4582
|
}
|
|
4326
4583
|
if (top && before && now.files?.length)
|
|
@@ -4342,7 +4599,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4342
4599
|
end = stopping.delete(id)
|
|
4343
4600
|
? { reason: 'interrupted' }
|
|
4344
4601
|
: await harness!.prompt(
|
|
4345
|
-
preface
|
|
4602
|
+
prefaced(preface, toldOf(text, images)),
|
|
4346
4603
|
onEvent,
|
|
4347
4604
|
images.map(({ path, type, name, data }) => ({ path, type, name, data })),
|
|
4348
4605
|
);
|
|
@@ -4363,10 +4620,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4363
4620
|
get: (id) => sessions.get(id),
|
|
4364
4621
|
query: () => sessions.query({ node: 'root', include: 'subtree', archived: true }),
|
|
4365
4622
|
change,
|
|
4366
|
-
append: async (id, type, data) =>
|
|
4367
|
-
if (!running.has(id)) await syncSeq(id);
|
|
4368
|
-
append(id, type, data);
|
|
4369
|
-
},
|
|
4623
|
+
append: async (id, type, data) => append(id, type, data),
|
|
4370
4624
|
running,
|
|
4371
4625
|
startTurn,
|
|
4372
4626
|
unsettle: reactivated,
|
|
@@ -4501,16 +4755,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4501
4755
|
log,
|
|
4502
4756
|
});
|
|
4503
4757
|
|
|
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
4758
|
// A session's pull request (research-086): linked, read, settled on merge, watched; `pull-requests.ts`.
|
|
4515
4759
|
const pullRequests = createPullRequests<Session>({
|
|
4516
4760
|
route: (method, path, description, handle) =>
|
|
@@ -4524,33 +4768,24 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4524
4768
|
if (value.branch?.temporary) return undefined;
|
|
4525
4769
|
const folder = await sessionFolder(node, value);
|
|
4526
4770
|
if (folder === undefined) return undefined;
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
|
|
4531
|
-
|
|
4771
|
+
const service = git();
|
|
4772
|
+
if (!service) return undefined;
|
|
4773
|
+
// Its branch's own name (none when detached), never git's short form: `heads/<name>` beside a tag (plugins#198).
|
|
4774
|
+
const status = await service.tracking(folder).catch(() => undefined);
|
|
4775
|
+
// A branch with no commit yet (unborn, orphan), and the default branch, have no pull request of their own; `main`
|
|
4776
|
+
// and `master` neither, the default being only guessed (a remote never fetched: then it is the checked-out
|
|
4777
|
+
// branch, which is no reason to leave a work branch out).
|
|
4778
|
+
if (
|
|
4779
|
+
!status?.branch ||
|
|
4780
|
+
!status.head ||
|
|
4781
|
+
(status.isDefault && !status.base.guessed) ||
|
|
4782
|
+
['main', 'master'].includes(status.branch)
|
|
4783
|
+
)
|
|
4532
4784
|
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;
|
|
4785
|
+
// The branch's upstream remote, else the only one, else `origin` (as the Branches screen); its URL with an ssh
|
|
4786
|
+
// alias read as its host (plugins#114).
|
|
4787
|
+
const remote = await service.remote(folder).catch(() => undefined);
|
|
4788
|
+
return remote ? { branch: status.branch, remote: remote.url } : undefined;
|
|
4554
4789
|
},
|
|
4555
4790
|
// A wake already in the queue: sent as after a turn (at once when none runs, held after the user's Stop).
|
|
4556
4791
|
deliver: (id) => {
|
|
@@ -4585,7 +4820,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
4585
4820
|
});
|
|
4586
4821
|
if (!settled) return false;
|
|
4587
4822
|
await unsnooze(id);
|
|
4588
|
-
await syncSeq(id);
|
|
4589
4823
|
append(id, 'notice', { text: notice });
|
|
4590
4824
|
void closeIdle(id, true).catch(log(`session ${id}: harness not closed`));
|
|
4591
4825
|
return true;
|
|
@@ -5371,7 +5605,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5371
5605
|
throw refused('not_your_session', 'An agent asks about its own session', 403);
|
|
5372
5606
|
const found = await find(new URLSearchParams({ id }));
|
|
5373
5607
|
const project = found.node === 'root' ? undefined : await folderOf(found.node);
|
|
5374
|
-
const branches = project === undefined ? [] : await worktreesOf(
|
|
5608
|
+
const branches = project === undefined ? [] : await worktreesOf(project).catch(() => []);
|
|
5375
5609
|
// Where it works, as its agent's cwd: its branch's folder, else its stage's checkout of the project, else main.
|
|
5376
5610
|
const folder = await sessionFolder(found.node, found.value);
|
|
5377
5611
|
const real = folder && (await ctx.fs.realpath(ctx, folder).catch(() => folder));
|
|
@@ -5650,8 +5884,6 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5650
5884
|
);
|
|
5651
5885
|
if (whole.length > VIEW_MAX)
|
|
5652
5886
|
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
5887
|
// The declaration of each plugin component it calls, so the page draws the view as the agent saw it (P2).
|
|
5656
5888
|
const called = usedViewComponents(whole, components);
|
|
5657
5889
|
const read = readAs(`agent:${id}`);
|
|
@@ -5705,7 +5937,7 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5705
5937
|
? { dynamic: true }
|
|
5706
5938
|
: { snapshot: snapshot ?? {}, at: new Date().toISOString() }),
|
|
5707
5939
|
});
|
|
5708
|
-
const seq =
|
|
5940
|
+
const seq = seqOf(id);
|
|
5709
5941
|
return { seq, errors, ...told };
|
|
5710
5942
|
},
|
|
5711
5943
|
});
|
|
@@ -5788,38 +6020,106 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5788
6020
|
const repositoryNow = async (id: string, node: string) => {
|
|
5789
6021
|
const folder = await sessionFolder(node, (await sessions.get(id))?.value);
|
|
5790
6022
|
const top = folder === undefined ? undefined : (await repositoryOf(folder))?.top;
|
|
5791
|
-
|
|
5792
|
-
|
|
6023
|
+
const service = git();
|
|
6024
|
+
if (!top || !service) throw refused('not_a_repository', `session ${id} works in no git repository`, 409);
|
|
6025
|
+
const state = await service.snapshot(top);
|
|
5793
6026
|
if (!state) throw refused('not_a_repository', `git status failed in ${top}`, 409);
|
|
5794
|
-
return { top, state };
|
|
6027
|
+
return { top, state, git: service, folder: folder! };
|
|
5795
6028
|
};
|
|
5796
6029
|
|
|
5797
6030
|
ctx.router.route(ctx, {
|
|
5798
6031
|
method: 'POST',
|
|
5799
6032
|
path: '/sessions/changes',
|
|
5800
6033
|
handle: async ({ body }) => {
|
|
5801
|
-
const { id } = parse(
|
|
6034
|
+
const { id, path } = parse(changesBody, body, 'POST /sessions/changes takes { id, path? }');
|
|
5802
6035
|
const { node, value } = await find(new URLSearchParams({ id }));
|
|
5803
|
-
|
|
6036
|
+
// Outside any git repository is a session's ordinary state, not a failure: the whole answer says so (`repository:
|
|
6037
|
+
// null`) for the panel that reads it on every session; one file's diff is still refused. Without the `git` plugin,
|
|
6038
|
+
// the same, saying so (`git: 'missing'`): the page offers to install it.
|
|
6039
|
+
const now = await repositoryNow(id, node).catch((error: unknown) => {
|
|
6040
|
+
if (path === undefined && isRecord(error) && error.code === 'not_a_repository') return undefined;
|
|
6041
|
+
throw error;
|
|
6042
|
+
});
|
|
6043
|
+
if (!now)
|
|
6044
|
+
return {
|
|
6045
|
+
id,
|
|
6046
|
+
node,
|
|
6047
|
+
title: value.title,
|
|
6048
|
+
repository: null,
|
|
6049
|
+
files: [],
|
|
6050
|
+
diff: '',
|
|
6051
|
+
...(!git() && { git: 'missing' as const }),
|
|
6052
|
+
};
|
|
6053
|
+
const { top, state, git: service, folder } = now;
|
|
5804
6054
|
const files = value.files ?? [];
|
|
5805
|
-
|
|
5806
|
-
|
|
5807
|
-
|
|
5808
|
-
|
|
5809
|
-
|
|
5810
|
-
|
|
5811
|
-
|
|
5812
|
-
|
|
5813
|
-
|
|
5814
|
-
|
|
5815
|
-
|
|
5816
|
-
|
|
5817
|
-
|
|
5818
|
-
pending,
|
|
5819
|
-
|
|
5820
|
-
|
|
5821
|
-
)
|
|
5822
|
-
|
|
6055
|
+
try {
|
|
6056
|
+
// One file's diff: one the session changed, never another path (outside its repository, or another session's).
|
|
6057
|
+
if (path !== undefined) {
|
|
6058
|
+
if (!files.includes(path))
|
|
6059
|
+
throw refused('not_its_file', `session ${id} did not change ${path}`);
|
|
6060
|
+
const pending = state.has(path) ? [path] : [];
|
|
6061
|
+
const { patch: diff, cut } = await service.diff(top, { paths: pending, maxChars: DIFF_MAX });
|
|
6062
|
+
return { id, node, repository: top, path, diff, ...(cut && { cut: true }) };
|
|
6063
|
+
}
|
|
6064
|
+
const pending = files.filter((file) => state.has(file));
|
|
6065
|
+
const counts = await service.counts(top, pending);
|
|
6066
|
+
const whole = pending.length <= DIFF_FILES_MAX;
|
|
6067
|
+
const { patch: diff, cut } = whole
|
|
6068
|
+
? await service.diff(top, { paths: pending, maxChars: DIFF_MAX })
|
|
6069
|
+
: { patch: '', cut: false };
|
|
6070
|
+
const status = await service.tracking(folder).catch(() => undefined);
|
|
6071
|
+
const others = [...state.keys()].filter((file) => !files.includes(file));
|
|
6072
|
+
return {
|
|
6073
|
+
id,
|
|
6074
|
+
node,
|
|
6075
|
+
title: value.title,
|
|
6076
|
+
repository: top,
|
|
6077
|
+
running: running.has(id),
|
|
6078
|
+
files: files.map((file) => ({ path: file, pending: state.has(file), ...counts[file] })),
|
|
6079
|
+
commits: value.commits ?? [],
|
|
6080
|
+
shared: await sharing(id, top, state, files),
|
|
6081
|
+
// Past `DIFF_FILES_MAX` pending files: none, `byFile` says so (each one's with `path`).
|
|
6082
|
+
diff,
|
|
6083
|
+
...(!whole && { byFile: true }),
|
|
6084
|
+
// Cut short: its last file's patch is an excerpt, read whole with `path`.
|
|
6085
|
+
...(cut && { cut: true }),
|
|
6086
|
+
// Its repository's branch, for the panel (a root repository's too); none when detached.
|
|
6087
|
+
branch:
|
|
6088
|
+
status?.branch === undefined
|
|
6089
|
+
? null
|
|
6090
|
+
: {
|
|
6091
|
+
name: status.branch,
|
|
6092
|
+
isDefault: status.isDefault,
|
|
6093
|
+
remote: status.remote,
|
|
6094
|
+
upstream: !!status.upstream,
|
|
6095
|
+
unpushed: status.unpushed ?? 0,
|
|
6096
|
+
},
|
|
6097
|
+
// The repository's other uncommitted files: a commit of the session's leaves them out.
|
|
6098
|
+
others: others.slice(0, OTHERS_MAX),
|
|
6099
|
+
github: ctx.get('github', false) ? ('ready' as const) : ('missing' as const),
|
|
6100
|
+
};
|
|
6101
|
+
} catch (error) {
|
|
6102
|
+
throw fromGit(error);
|
|
6103
|
+
}
|
|
6104
|
+
},
|
|
6105
|
+
});
|
|
6106
|
+
|
|
6107
|
+
// Lines of a file the session changed, as its folder holds them now: the diff's folds expand with them.
|
|
6108
|
+
ctx.router.route(ctx, {
|
|
6109
|
+
method: 'POST',
|
|
6110
|
+
path: '/sessions/lines',
|
|
6111
|
+
handle: async ({ body }) => {
|
|
6112
|
+
const { id, path, from, to } = parse(
|
|
6113
|
+
linesBody,
|
|
6114
|
+
body,
|
|
6115
|
+
'POST /sessions/lines takes { id, path, from, to }',
|
|
6116
|
+
);
|
|
6117
|
+
const { node, value } = await find(new URLSearchParams({ id }));
|
|
6118
|
+
const { top, git: service } = await repositoryNow(id, node);
|
|
6119
|
+
// One file the session changed, never another path (outside its repository, or another session's).
|
|
6120
|
+
if (!(value.files ?? []).includes(path))
|
|
6121
|
+
throw refused('not_its_file', `session ${id} did not change ${path}`);
|
|
6122
|
+
return { id, path, lines: await service.lines(top, path, from, to).catch((error: unknown) => Promise.reject(fromGit(error))) };
|
|
5823
6123
|
},
|
|
5824
6124
|
});
|
|
5825
6125
|
|
|
@@ -5833,51 +6133,77 @@ export async function apply(ctx: Context, config?: unknown) {
|
|
|
5833
6133
|
message,
|
|
5834
6134
|
files: chosen,
|
|
5835
6135
|
force,
|
|
5836
|
-
} = parse(commitBody, body, 'POST /sessions/commit takes { id, message
|
|
6136
|
+
} = parse(commitBody, body, 'POST /sessions/commit takes { id, message?, files?, force? }');
|
|
5837
6137
|
const { node, value } = await find(new URLSearchParams({ id }));
|
|
5838
6138
|
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
|
-
|
|
6139
|
+
const { top, git: service } = await repositoryNow(id, node);
|
|
6140
|
+
const own = new Set(value.files ?? []);
|
|
6141
|
+
if (chosen?.some((file) => !own.has(file)))
|
|
6142
|
+
throw refused(
|
|
6143
|
+
'not_its_file',
|
|
6144
|
+
`session ${id} did not change ${chosen.filter((file) => !own.has(file)).join(', ')}`,
|
|
6145
|
+
);
|
|
6146
|
+
let shared: Awaited<ReturnType<typeof sharing>> = [];
|
|
6147
|
+
try {
|
|
6148
|
+
// Its files, or the ones chosen, as `git` stages them in an index of its own (the real one untouched while the
|
|
6149
|
+
// message is written), one commit at a time per repository. Inside that queue, before staging and again once the
|
|
6150
|
+
// message is written: its turn, and who else changed them (`POST /sessions/changes`'s `shared` lists them;
|
|
6151
|
+
// `force` takes their changes too).
|
|
6152
|
+
// No message: the session's agent writes one from its conversation and what goes in, as the project plugin's
|
|
6153
|
+
// commit does; refused (`not_written`) when it cannot. A nested repository among them stays out, and pending:
|
|
6154
|
+
// `left` says so (plugins#145).
|
|
6155
|
+
const done = await service.commit(top, {
|
|
6156
|
+
scope: 'paths',
|
|
6157
|
+
paths: chosen ?? [...own],
|
|
6158
|
+
maxChars: DIFF_MAX,
|
|
6159
|
+
trailers: { 'Bridge-Session': id },
|
|
6160
|
+
preflight: async (files) => {
|
|
6161
|
+
if (running.has(id)) throw refused('session_busy', `session ${id} has a turn running`, 409);
|
|
6162
|
+
shared = await sharing(id, top, (await service.snapshot(top)) ?? new Map<string, string>(), files);
|
|
6163
|
+
if (shared.length && !force)
|
|
6164
|
+
throw refused(
|
|
6165
|
+
'files_shared',
|
|
6166
|
+
`other sessions changed these files too: ${[...new Set(shared.flatMap((each) => each.files))].join(', ')}; commit with force to take their changes too`,
|
|
6167
|
+
409,
|
|
6168
|
+
);
|
|
6169
|
+
},
|
|
6170
|
+
message:
|
|
6171
|
+
message ||
|
|
6172
|
+
(async ({ recent, diff, signal }) => {
|
|
6173
|
+
const written = await writeAfter([id], {
|
|
6174
|
+
node,
|
|
6175
|
+
cwd: top,
|
|
6176
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(WRITE_MS)]),
|
|
6177
|
+
prompt: [
|
|
6178
|
+
'Write the git commit message for the changes below.',
|
|
6179
|
+
'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.',
|
|
6180
|
+
`Follow the style of this repository's recent commits:\n${recent.join('\n')}`,
|
|
6181
|
+
`Diff:\n${diff}`,
|
|
6182
|
+
].join('\n\n'),
|
|
6183
|
+
});
|
|
6184
|
+
return written.text;
|
|
6185
|
+
}),
|
|
5879
6186
|
});
|
|
5880
|
-
|
|
6187
|
+
const at = new Date().toISOString();
|
|
6188
|
+
const entry = { sha: done.sha, at, message: done.message, files: done.files };
|
|
6189
|
+
await change(id, (now) => ({
|
|
6190
|
+
...release(now, done.files),
|
|
6191
|
+
commits: [...(now.commits ?? []), entry],
|
|
6192
|
+
}));
|
|
6193
|
+
append(id, 'commit', entry);
|
|
6194
|
+
return {
|
|
6195
|
+
id,
|
|
6196
|
+
node,
|
|
6197
|
+
...entry,
|
|
6198
|
+
shared,
|
|
6199
|
+
...(done.left.length && { left: done.left }),
|
|
6200
|
+
...(done.recovery && { recovery: done.recovery }),
|
|
6201
|
+
};
|
|
6202
|
+
} catch (error) {
|
|
6203
|
+
if (isRecord(error) && error.code === 'nothing_to_commit')
|
|
6204
|
+
throw refused('nothing_to_commit', `session ${id} has no uncommitted change`, 409);
|
|
6205
|
+
throw fromGit(error);
|
|
6206
|
+
}
|
|
5881
6207
|
},
|
|
5882
6208
|
});
|
|
5883
6209
|
|