send-to-paseo 1.3.0

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.
@@ -0,0 +1,1041 @@
1
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
+ import {
3
+ BridgeError,
4
+ type AgentProfileOption,
5
+ type Candidate,
6
+ type ExistingCandidate,
7
+ type ModeOption,
8
+ type PrPayload,
9
+ type PrRef,
10
+ type ProjectPayload,
11
+ type ProviderOption,
12
+ type ResolveRequest,
13
+ type ResolveResponse,
14
+ type StackPrState,
15
+ } from "../shared/contracts";
16
+ import { withPaseo } from "./daemon";
17
+ import {
18
+ ANCESTRY_STACK_DISTANCE,
19
+ UNKNOWN_STACK_DISTANCE,
20
+ lookupPr,
21
+ repoDefaultBranch,
22
+ viewStackBranches,
23
+ viewStackGraph,
24
+ type GhOutage,
25
+ type StackGraph,
26
+ type StackMember,
27
+ } from "./gh";
28
+ import {
29
+ branchesContaining,
30
+ parseGithubRemote,
31
+ readBranch,
32
+ readOriginOwnerRepo,
33
+ readTrunkBranch,
34
+ } from "./git";
35
+ import { settings } from "./settings";
36
+ import {
37
+ agentDisplayTitle,
38
+ listProjectAgents,
39
+ selectMainAgent,
40
+ type ListedAgent,
41
+ } from "./main-agent";
42
+
43
+ type PaseoApi = PluginHandlerContext["paseo"];
44
+ type PaseoWorkspace = Awaited<ReturnType<PaseoApi["workspaces"]["list"]>>["entries"][number];
45
+
46
+ /**
47
+ * PR -> project -> workspace resolution, exactly the ladder in CONTRACT.md.
48
+ *
49
+ * This endpoint runs while the user is still typing, so it must be fast and it
50
+ * must never create anything.
51
+ */
52
+
53
+ /** OpenCode alone advertises 160+ models; a popover dropdown needs a bound. */
54
+ const PER_PROVIDER_MODEL_LIMIT = 24;
55
+
56
+ /** `owner/repo` -> the project id Paseo gives a GitHub remote. */
57
+ export function remoteProjectId(owner: string, repo: string): string {
58
+ return `remote:github.com/${owner}/${repo}`;
59
+ }
60
+
61
+ function sameRepo(a: { owner: string; repo: string }, b: { owner: string; repo: string }): boolean {
62
+ return (
63
+ a.owner.toLowerCase() === b.owner.toLowerCase() && a.repo.toLowerCase() === b.repo.toLowerCase()
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Step 1 of the ladder: find the Paseo project for a GitHub repository.
69
+ *
70
+ * The `remote:github.com/{owner}/{repo}` id is the fast path. The fallback
71
+ * matches a project whose `origin` parses to the same repository, which covers
72
+ * projects registered from a local clone with an SSH remote or a renamed repo.
73
+ */
74
+ export async function resolveProject(
75
+ paseo: PaseoApi,
76
+ ref: Pick<PrRef, "owner" | "repo">,
77
+ ): Promise<ProjectPayload> {
78
+ const { projects } = await paseo.projects.list();
79
+ const wanted = remoteProjectId(ref.owner, ref.repo).toLowerCase();
80
+
81
+ for (const project of projects) {
82
+ if (project.projectId.toLowerCase() === wanted) {
83
+ return {
84
+ projectId: project.projectId,
85
+ name: project.projectDisplayName,
86
+ path: project.projectRootPath,
87
+ };
88
+ }
89
+ }
90
+
91
+ for (const project of projects) {
92
+ if (project.projectKind !== "git" || project.projectRootPath === "") continue;
93
+ const fromId = /^remote:github\.com\/([^/]+)\/(.+)$/i.exec(project.projectId);
94
+ const candidate =
95
+ fromId?.[1] !== undefined && fromId[2] !== undefined
96
+ ? { owner: fromId[1], repo: fromId[2] }
97
+ : await readOriginOwnerRepo(project.projectRootPath);
98
+ if (candidate !== null && sameRepo(candidate, ref)) {
99
+ return {
100
+ projectId: project.projectId,
101
+ name: project.projectDisplayName,
102
+ path: project.projectRootPath,
103
+ };
104
+ }
105
+ }
106
+
107
+ throw new BridgeError(
108
+ "project_not_found",
109
+ `${ref.owner}/${ref.repo} is not a project in Paseo.`,
110
+ `Add it in Paseo, or run: paseo project add /path/to/${ref.repo}`,
111
+ );
112
+ }
113
+
114
+ /** Branch a workspace is on, preferring what the daemon already knows. */
115
+ async function workspaceBranch(workspace: PaseoWorkspace): Promise<string | null> {
116
+ const fromRuntime = workspace.gitRuntime?.currentBranch;
117
+ if (typeof fromRuntime === "string" && fromRuntime !== "") return fromRuntime;
118
+ const fromCheckout = workspace.project?.checkout?.currentBranch;
119
+ if (typeof fromCheckout === "string" && fromCheckout !== "") return fromCheckout;
120
+ // Descriptor had no branch (fresh worktree, or git snapshot not warm yet).
121
+ return readBranch(workspace.workspaceDirectory);
122
+ }
123
+
124
+ function workspaceLabel(workspace: PaseoWorkspace): string {
125
+ const slug = workspace.worktreeSlug;
126
+ if (typeof slug === "string" && slug !== "") return slug;
127
+ const name = workspace.name;
128
+ return typeof name === "string" && name !== "" ? name : workspace.id;
129
+ }
130
+
131
+ /** The vocabulary `paseo workspace ls` uses, so the two agree. */
132
+ function isolationOf(workspace: PaseoWorkspace): string {
133
+ return workspace.workspaceKind === "worktree" ? "worktree" : "local";
134
+ }
135
+
136
+ async function workspaceAgents(
137
+ paseo: PaseoApi,
138
+ projectId: string,
139
+ prefetched?: readonly ListedAgent[],
140
+ ): Promise<{ counts: Map<string, number>; agents: readonly ListedAgent[] }> {
141
+ const counts = new Map<string, number>();
142
+ try {
143
+ const agents = prefetched ?? (await listProjectAgents(paseo, projectId));
144
+ for (const agent of agents) {
145
+ const workspaceId = agent.workspaceId;
146
+ if (typeof workspaceId !== "string" || workspaceId === "") continue;
147
+ counts.set(workspaceId, (counts.get(workspaceId) ?? 0) + 1);
148
+ }
149
+ return { counts, agents };
150
+ } catch (error) {
151
+ // A count is decoration; never fail a resolve over it.
152
+ console.error("[send-to-paseo] could not count agents", String(error));
153
+ return { counts, agents: [] };
154
+ }
155
+ }
156
+
157
+ /** Workspaces of one project, freshest first, excluding ones being archived. */
158
+ export async function listProjectWorkspaces(
159
+ paseo: PaseoApi,
160
+ projectId: string,
161
+ ): Promise<PaseoWorkspace[]> {
162
+ const { entries } = await paseo.workspaces.list();
163
+ return entries.filter(
164
+ (workspace) => workspace.projectId === projectId && workspace.archivingAt === null,
165
+ );
166
+ }
167
+
168
+ /**
169
+ * A workspace with the branch it is on, read once.
170
+ *
171
+ * Stack discovery needs the branch list *before* it can decide whether the
172
+ * cheap open-PR graph was enough, and candidate building needs it again, so the
173
+ * read happens once and is passed around rather than repeated.
174
+ */
175
+ export interface WorkspaceBranch {
176
+ workspace: PaseoWorkspace;
177
+ branch: string | null;
178
+ }
179
+
180
+ export async function readWorkspaceBranches(
181
+ workspaces: readonly PaseoWorkspace[],
182
+ ): Promise<WorkspaceBranch[]> {
183
+ // Most descriptors already carry a branch, but cold worktrees fall back to
184
+ // one short git process apiece. Those reads are independent; serializing
185
+ // them made resolve latency grow with every workspace in the project.
186
+ return Promise.all(
187
+ workspaces.map(async (workspace) => ({
188
+ workspace,
189
+ branch: await workspaceBranch(workspace),
190
+ })),
191
+ );
192
+ }
193
+
194
+ /**
195
+ * Ordering weight for a rank-2 candidate's PR state.
196
+ *
197
+ * An open sibling outranks a merged or closed one *before* hop count is even
198
+ * considered: a workspace on a live sibling branch of the stack is somewhere
199
+ * work is still happening, while a merged branch is history the stack has
200
+ * already moved past. `null` — a stack branch with no PR at all, which only
201
+ * local ancestry can find — is the weakest claim of the four.
202
+ */
203
+ function stateWeight(state: StackPrState | null | undefined): number {
204
+ switch (state) {
205
+ case undefined:
206
+ case "open":
207
+ return 0;
208
+ case "merged":
209
+ return 1;
210
+ case "closed":
211
+ return 2;
212
+ default:
213
+ return 3;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Step 5 of the ladder. `candidates` is sorted ascending by rank and always
219
+ * ends with the synthetic `create` entry, so the extension can offer creating a
220
+ * worktree even when nothing matched.
221
+ */
222
+ export async function buildCandidates(input: {
223
+ paseo: PaseoApi;
224
+ projectId: string;
225
+ ref: PrRef;
226
+ pr: PrPayload;
227
+ workspaces: readonly WorkspaceBranch[];
228
+ stackBranches: Map<string, StackMember>;
229
+ /** Non-null when `gh` could not be consulted; carried into the create label. */
230
+ outage?: GhOutage | null;
231
+ agentDispatch?: "new" | "main";
232
+ agents?: readonly ListedAgent[];
233
+ }): Promise<{ candidates: Candidate[]; defaultCandidateIndex: number }> {
234
+ const { counts, agents } = await workspaceAgents(
235
+ input.paseo,
236
+ input.projectId,
237
+ input.agents,
238
+ );
239
+
240
+ const existing: ExistingCandidate[] = [];
241
+ /** Stack distance per candidate, used only for ordering. Not on the wire. */
242
+ const distanceOf = new Map<string, number>();
243
+ /**
244
+ * Stack PR state per candidate, for ordering. Read from here rather than from
245
+ * the candidate's `stackPrState`, because that field is omitted both for
246
+ * "open" and for a branch with no PR — two very different claims that must
247
+ * not sort as one.
248
+ */
249
+ const stateOf = new Map<string, StackPrState | null>();
250
+ for (const { workspace, branch } of input.workspaces) {
251
+ const member = branch === null ? undefined : input.stackBranches.get(branch);
252
+ if (member !== undefined) {
253
+ distanceOf.set(workspace.id, member.distance);
254
+ stateOf.set(workspace.id, member.state);
255
+ }
256
+ const base = {
257
+ kind: "existing" as const,
258
+ workspaceId: workspace.id,
259
+ label: workspaceLabel(workspace),
260
+ branch,
261
+ cwd: workspace.workspaceDirectory,
262
+ isolation: isolationOf(workspace),
263
+ agentCount: counts.get(workspace.id) ?? 0,
264
+ ...(input.agentDispatch === "main"
265
+ ? (() => {
266
+ const main = selectMainAgent(agents, workspace.id);
267
+ return main === null
268
+ ? {}
269
+ : {
270
+ mainAgent: {
271
+ agentId: main.id,
272
+ title: agentDisplayTitle(main),
273
+ status: main.status,
274
+ },
275
+ };
276
+ })()
277
+ : {}),
278
+ };
279
+ if (branch !== null && branch === input.pr.headBranch) {
280
+ existing.push({ ...base, rank: 1, reason: "exact" });
281
+ } else if (member !== undefined) {
282
+ existing.push({
283
+ ...base,
284
+ rank: 2,
285
+ reason: "stack",
286
+ // A member found by ancestry alone may have no PR of its own, so both
287
+ // wire fields are omitted rather than invented. `stackPrState` is
288
+ // additionally omitted for "open", which is the value an extension
289
+ // that predates this field already assumes.
290
+ ...(member.number === null ? {} : { stackPrNumber: member.number }),
291
+ ...(member.state === null || member.state === "open" ? {} : { stackPrState: member.state }),
292
+ });
293
+ } else {
294
+ existing.push({ ...base, rank: 3, reason: "project" });
295
+ }
296
+ }
297
+
298
+ existing.sort((a, b) => {
299
+ if (a.rank !== b.rank) return a.rank - b.rank;
300
+ if (a.rank === 2 && b.rank === 2) {
301
+ // Live siblings before history. See `stateWeight`.
302
+ const leftState = stateWeight(stateOf.get(a.workspaceId));
303
+ const rightState = stateWeight(stateOf.get(b.workspaceId));
304
+ if (leftState !== rightState) return leftState - rightState;
305
+ // Nearest in the stack first: the branch one hop from this PR is a far
306
+ // better guess than one at the other end of a nine-PR stack.
307
+ const leftHops = distanceOf.get(a.workspaceId) ?? UNKNOWN_STACK_DISTANCE;
308
+ const rightHops = distanceOf.get(b.workspaceId) ?? UNKNOWN_STACK_DISTANCE;
309
+ if (leftHops !== rightHops) return leftHops - rightHops;
310
+ const left = a.stackPrNumber ?? 0;
311
+ const right = b.stackPrNumber ?? 0;
312
+ if (left !== right) return left - right;
313
+ }
314
+ return a.label.localeCompare(b.label);
315
+ });
316
+
317
+ // The create candidate's label is the only user-visible string in the resolve
318
+ // response that the popover renders and that the bridge is free to word, so a
319
+ // degraded resolve says so there. CONTRACT.md has no notice/warning field and
320
+ // is frozen, so this and the agent's prompt are where the notice lives; see
321
+ // README "Requirements".
322
+ const outage = input.outage ?? null;
323
+ const createLabel =
324
+ outage === null
325
+ ? `Create worktree for PR #${input.ref.number}`
326
+ : `Create worktree for PR #${input.ref.number} (${outage.short})`;
327
+
328
+ const candidates: Candidate[] = [
329
+ ...existing,
330
+ {
331
+ kind: "create",
332
+ label: createLabel,
333
+ branch: input.pr.headBranch,
334
+ rank: 4,
335
+ reason: "create",
336
+ },
337
+ ];
338
+
339
+ // The default is the exact branch match, then the nearest workspace in the
340
+ // same stack, then creating a worktree.
341
+ //
342
+ // Preferring the stack match matters because one workspace per *stack* is a
343
+ // normal way to work: you open PR #4 of a stack while the worktree sits on
344
+ // PR #7's branch. Before this, that resolved to "create a worktree", which
345
+ // silently proposed a second checkout of a stack the user already had open.
346
+ // Rank 3 ("some other workspace in this project") is deliberately NOT a
347
+ // default — an unrelated workspace is a worse guess than a fresh worktree.
348
+ //
349
+ // `candidates` always ends with the synthetic create entry, so the fallback
350
+ // is always a valid index; CONTRACT.md requires it never point out of range.
351
+ const exactIndex = candidates.findIndex((candidate) => candidate.rank === 1);
352
+ const stackIndex = candidates.findIndex((candidate) => candidate.rank === 2);
353
+ const fallbackIndex = Math.max(candidates.length - 1, 0);
354
+ const preferred = exactIndex >= 0 ? exactIndex : stackIndex >= 0 ? stackIndex : fallbackIndex;
355
+ const defaultCandidateIndex =
356
+ preferred >= 0 && preferred < candidates.length ? preferred : fallbackIndex;
357
+ return { candidates, defaultCandidateIndex };
358
+ }
359
+
360
+ /**
361
+ * Selectable `provider/model` ids, with the plugin's configured default flagged.
362
+ */
363
+ export async function listProviders(
364
+ paseo: PaseoApi,
365
+ configuredDefault: string | null,
366
+ ): Promise<{ providers: ProviderOption[]; error: string | null }> {
367
+ let snapshot;
368
+ try {
369
+ snapshot = await paseo.providers.snapshot();
370
+ } catch (error) {
371
+ const message = error instanceof Error ? error.message : String(error);
372
+ return { providers: [], error: message };
373
+ }
374
+
375
+ interface Draft {
376
+ id: string;
377
+ modelLabel: string;
378
+ providerLabel: string;
379
+ isProviderDefault: boolean;
380
+ }
381
+ const drafts: Draft[] = [];
382
+ for (const entry of snapshot.entries) {
383
+ if (entry.enabled === false || entry.status !== "ready") continue;
384
+ const models = (entry.models ?? []).filter((model) => model.isSelectable !== false);
385
+ for (const model of models.slice(0, PER_PROVIDER_MODEL_LIMIT)) {
386
+ drafts.push({
387
+ id: `${entry.provider}/${model.id}`,
388
+ modelLabel: model.label === "" ? model.id : model.label,
389
+ providerLabel:
390
+ entry.label === undefined || entry.label === "" ? entry.provider : entry.label,
391
+ isProviderDefault: model.isDefault === true,
392
+ });
393
+ }
394
+ }
395
+
396
+ // "Fable 5" appears under more than one provider, so only disambiguate the
397
+ // labels that actually collide and leave the rest reading cleanly.
398
+ const labelCounts = new Map<string, number>();
399
+ for (const draft of drafts) {
400
+ labelCounts.set(draft.modelLabel, (labelCounts.get(draft.modelLabel) ?? 0) + 1);
401
+ }
402
+
403
+ const effectiveDefault =
404
+ configuredDefault !== null && drafts.some((draft) => draft.id === configuredDefault)
405
+ ? configuredDefault
406
+ : (drafts.find((draft) => draft.isProviderDefault)?.id ?? drafts[0]?.id ?? null);
407
+
408
+ const providers: ProviderOption[] = drafts.map((draft) => ({
409
+ id: draft.id,
410
+ label:
411
+ (labelCounts.get(draft.modelLabel) ?? 0) > 1
412
+ ? `${draft.providerLabel} · ${draft.modelLabel}`
413
+ : draft.modelLabel,
414
+ isDefault: draft.id === effectiveDefault,
415
+ }));
416
+
417
+ // A configured default the daemon no longer offers still has to be visible,
418
+ // or the surface would silently show no selection at all.
419
+ if (
420
+ configuredDefault !== null &&
421
+ !providers.some((provider) => provider.id === configuredDefault)
422
+ ) {
423
+ providers.unshift({ id: configuredDefault, label: configuredDefault, isDefault: true });
424
+ for (const provider of providers.slice(1)) provider.isDefault = false;
425
+ }
426
+
427
+ return { providers, error: null };
428
+ }
429
+
430
+ /**
431
+ * The bare provider id inside a `provider/model` pair.
432
+ *
433
+ * Everything on the wire that names a provider names a `provider/model` pair
434
+ * (`claude/claude-opus-5`), but modes are advertised per *provider*, so the two
435
+ * are joined here and nowhere else.
436
+ */
437
+ export function providerIdOf(providerModel: string): string {
438
+ const slash = providerModel.indexOf("/");
439
+ return slash === -1 ? providerModel : providerModel.slice(0, slash);
440
+ }
441
+
442
+ export interface ModeCatalog {
443
+ /** Flat, provider-tagged, exactly like `providers[]`. */
444
+ modes: ModeOption[];
445
+ /** Bare provider id -> the mode id that provider calls its default. */
446
+ defaultModeOf: Map<string, string>;
447
+ error: string | null;
448
+ }
449
+
450
+ /**
451
+ * Every permission mode Paseo advertises, flattened and tagged with its
452
+ * provider.
453
+ *
454
+ * `isUnattended` is derived from `colorTier === "dangerous"` rather than read
455
+ * from a field: `AgentMode` on the snapshot carries `colorTier` but not
456
+ * `isUnattended` — only the static provider manifest has that flag. Measured
457
+ * against `getUnattendedModeId()` from `@getpaseo/protocol/provider-manifest` on
458
+ * 2026-09-01, the two agree exactly for every ready provider
459
+ * (claude -> `bypassPermissions`, codex -> `full-access`, opencode -> none), so
460
+ * this reads the daemon's own answer instead of importing a second source of
461
+ * truth that could drift from it.
462
+ */
463
+ export async function listModes(paseo: PaseoApi): Promise<ModeCatalog> {
464
+ let snapshot;
465
+ try {
466
+ snapshot = await paseo.providers.snapshot();
467
+ } catch (error) {
468
+ const message = error instanceof Error ? error.message : String(error);
469
+ return { modes: [], defaultModeOf: new Map(), error: message };
470
+ }
471
+
472
+ const modes: ModeOption[] = [];
473
+ const defaultModeOf = new Map<string, string>();
474
+ for (const entry of snapshot.entries) {
475
+ if (entry.enabled === false || entry.status !== "ready") continue;
476
+ const advertised = entry.modes ?? [];
477
+ const fallback = entry.defaultModeId ?? null;
478
+ if (fallback !== null && advertised.some((mode) => mode.id === fallback)) {
479
+ defaultModeOf.set(entry.provider, fallback);
480
+ }
481
+ for (const mode of advertised) {
482
+ const dangerous = mode.colorTier === "dangerous";
483
+ modes.push({
484
+ provider: entry.provider,
485
+ id: mode.id,
486
+ label: mode.label === "" ? mode.id : mode.label,
487
+ isDefault: mode.id === fallback,
488
+ ...(dangerous ? { isUnattended: true } : {}),
489
+ ...(mode.colorTier === undefined ? {} : { colorTier: mode.colorTier }),
490
+ });
491
+ }
492
+ }
493
+ return { modes, defaultModeOf, error: null };
494
+ }
495
+
496
+ /** True when `provider` actually advertises `modeId`. */
497
+ function modeIsValid(catalog: ModeCatalog, provider: string, modeId: string): boolean {
498
+ return catalog.modes.some((mode) => mode.provider === provider && mode.id === modeId);
499
+ }
500
+
501
+ /**
502
+ * The user's saved Paseo agent profiles, read live from daemon config.
503
+ *
504
+ * There is no `profile` parameter on agent creation: applying a profile is a
505
+ * field-by-field copy of `provider`, `model`, `modeId` and `thinkingOptionId`.
506
+ * So the plugin stores only the id and re-reads the fields on every send —
507
+ * change the profile in Paseo and the next send follows it.
508
+ */
509
+ export async function listAgentProfiles(
510
+ paseo: PaseoApi,
511
+ ): Promise<{ profiles: AgentProfileOption[]; error: string | null }> {
512
+ try {
513
+ const { config } = await paseo.config.get();
514
+ const profiles = (config.agentProfiles ?? []).map((profile) => ({
515
+ id: profile.id,
516
+ name: profile.name,
517
+ provider: profile.provider,
518
+ model: profile.model ?? null,
519
+ modeId: profile.modeId ?? null,
520
+ thinkingOptionId: profile.thinkingOptionId ?? null,
521
+ }));
522
+ return { profiles, error: null };
523
+ } catch (error) {
524
+ return { profiles: [], error: error instanceof Error ? error.message : String(error) };
525
+ }
526
+ }
527
+
528
+ /**
529
+ * The profile the plugin is configured to follow, or null.
530
+ *
531
+ * Null is also the answer when the configured id no longer exists: a profile
532
+ * deleted in Paseo must cost the send its defaults, not the send itself.
533
+ */
534
+ export async function resolveSelectedProfile(
535
+ paseo: PaseoApi,
536
+ ): Promise<AgentProfileOption | null> {
537
+ const wanted = (await settings.read()).defaultProfileId;
538
+ if (wanted === null) return null;
539
+ const { profiles, error } = await listAgentProfiles(paseo);
540
+ if (error !== null) {
541
+ console.error("[send-to-paseo] could not read agent profiles", error);
542
+ return null;
543
+ }
544
+ const found = profiles.find((profile) => profile.id === wanted) ?? null;
545
+ if (found === null) {
546
+ console.log(
547
+ `[send-to-paseo] agent profile ${wanted} no longer exists in Paseo; ignoring it`,
548
+ );
549
+ }
550
+ return found;
551
+ }
552
+
553
+ /** `provider/model` for a profile, or null when it names no model. */
554
+ export function profileProviderId(profile: AgentProfileOption | null): string | null {
555
+ if (profile === null || profile.model === null || profile.model === "") return null;
556
+ return `${profile.provider}/${profile.model}`;
557
+ }
558
+
559
+ /**
560
+ * The `provider/model` a send uses when the request does not name one: the
561
+ * selected profile's model, else the configured default, else whatever the
562
+ * daemon calls default.
563
+ *
564
+ * A profile naming a model Paseo no longer offers is skipped rather than
565
+ * pinned, for the same reason a deleted profile is: stale configuration must
566
+ * not turn every send into `agent_create_failed`.
567
+ */
568
+ export async function resolveDefaultProvider(
569
+ paseo: PaseoApi,
570
+ profile: AgentProfileOption | null = null,
571
+ ): Promise<string> {
572
+ const configured = (await settings.read()).defaultProvider;
573
+ const { providers } = await listProviders(paseo, configured);
574
+ const fromProfile = profileProviderId(profile);
575
+ if (fromProfile !== null) {
576
+ if (providers.some((provider) => provider.id === fromProfile)) return fromProfile;
577
+ console.log(
578
+ `[send-to-paseo] profile "${profile?.name}" names ${fromProfile}, which Paseo does not offer; falling back`,
579
+ );
580
+ }
581
+ const chosen = providers.find((provider) => provider.isDefault)?.id ?? providers[0]?.id;
582
+ if (chosen === undefined) {
583
+ throw new BridgeError(
584
+ "agent_create_failed",
585
+ "No provider is available in Paseo, so an agent cannot be started.",
586
+ "Check Settings -> Providers in Paseo.",
587
+ );
588
+ }
589
+ return chosen;
590
+ }
591
+
592
+ /**
593
+ * The permission mode a send uses, in order. Mirrors `resolveDefaultProvider`:
594
+ * ordered candidates, every one validated before it is accepted, and a
595
+ * fall-through instead of a throw.
596
+ *
597
+ * 1. `modeId` on the request — the popover's explicit choice
598
+ * 2. the selected profile's `modeId`
599
+ * 3. the plugin's own configured `defaultModeId`
600
+ * 4. the chosen provider's `defaultModeId` from `providers.snapshot()`
601
+ * 5. `undefined` — the field is omitted and Paseo applies its own default
602
+ *
603
+ * Step 3 sits *below* the profile deliberately: decision 1 was "follow a saved
604
+ * profile, resolved live at send time", so a profile that carries a mode is
605
+ * what following it means. The plugin's own setting is the answer for people
606
+ * who follow no profile, or a profile that leaves the mode unset.
607
+ *
608
+ * Every candidate is checked against the provider's advertised `modes[]` before
609
+ * it is used, because mode ids are per-provider: `bypassPermissions` is a
610
+ * Claude id and means nothing to Codex. An id the provider does not advertise
611
+ * logs one line and falls through to the next step — before this, it would have
612
+ * turned every send into `agent_create_failed`.
613
+ */
614
+ export async function resolveDefaultMode(
615
+ paseo: PaseoApi,
616
+ providerModel: string,
617
+ input: {
618
+ /** `modeId` from the request body, when the caller sent one. */
619
+ requested?: string | undefined;
620
+ profile?: AgentProfileOption | null;
621
+ /** Pre-fetched, so one resolve does not hit `snapshot()` twice. */
622
+ catalog?: ModeCatalog;
623
+ } = {},
624
+ ): Promise<string | undefined> {
625
+ const provider = providerIdOf(providerModel);
626
+ const catalog = input.catalog ?? (await listModes(paseo));
627
+ if (catalog.error !== null) {
628
+ console.error("[send-to-paseo] could not list provider modes", catalog.error);
629
+ return undefined;
630
+ }
631
+
632
+ const candidates: { id: string; source: string }[] = [];
633
+ if (input.requested !== undefined && input.requested !== "") {
634
+ candidates.push({ id: input.requested, source: "the request" });
635
+ }
636
+ const fromProfile = input.profile?.modeId ?? null;
637
+ if (fromProfile !== null) {
638
+ candidates.push({ id: fromProfile, source: `profile "${input.profile?.name}"` });
639
+ }
640
+ const configured = (await settings.read()).defaultModeId;
641
+ if (configured !== null) {
642
+ candidates.push({ id: configured, source: "the plugin's default mode setting" });
643
+ }
644
+ const providerDefault = catalog.defaultModeOf.get(provider);
645
+ if (providerDefault !== undefined) {
646
+ candidates.push({ id: providerDefault, source: `${provider}'s own default` });
647
+ }
648
+
649
+ for (const candidate of candidates) {
650
+ if (modeIsValid(catalog, provider, candidate.id)) return candidate.id;
651
+ console.log(
652
+ `[send-to-paseo] mode "${candidate.id}" from ${candidate.source} is not offered by ${provider}; trying the next option`,
653
+ );
654
+ }
655
+ return undefined;
656
+ }
657
+
658
+ /**
659
+ * Providers with the plugin's *effective* default flagged, which is what the
660
+ * popover preselects: the followed profile's model when Paseo still offers it,
661
+ * else the `defaultProvider` setting, else the daemon's own default.
662
+ */
663
+ export async function listEffectiveProviders(
664
+ paseo: PaseoApi,
665
+ profile: AgentProfileOption | null,
666
+ ): Promise<{ providers: ProviderOption[]; error: string | null }> {
667
+ const configured = (await settings.read()).defaultProvider;
668
+ const result = await listProviders(paseo, configured);
669
+ const fromProfile = profileProviderId(profile);
670
+ if (fromProfile !== null && result.providers.some((provider) => provider.id === fromProfile)) {
671
+ for (const provider of result.providers) provider.isDefault = provider.id === fromProfile;
672
+ }
673
+ return result;
674
+ }
675
+
676
+ /**
677
+ * How many unplaced workspace branches the ancestry mechanism will test.
678
+ *
679
+ * `git branch -a --contains X` walks every ref in the repository, so it is the
680
+ * one read in this endpoint that is not O(1). Measured on a real 4,692-ref
681
+ * clone it costs 14-26ms per branch, so eight of them is ~0.15s worst case —
682
+ * cheap, but not free, and projects with dozens of workspaces exist. Unplaced
683
+ * workspaces beyond the cap stay rank 3, which is exactly the behaviour that
684
+ * existed before this mechanism, and the cap is logged rather than silent.
685
+ */
686
+ const ANCESTRY_WORKSPACE_LIMIT = 8;
687
+
688
+ /**
689
+ * Trunk's branch name: local refs first, GitHub second, null if neither knows.
690
+ *
691
+ * Local is free and offline (`refs/remotes/origin/HEAD`, written by
692
+ * `git clone`), but measurably not always present — 2 of 3 git projects on the
693
+ * development machine had it. So `gh repo view` is the fallback, cached for
694
+ * half an hour, and only ever reached on the slow path that already decided to
695
+ * spend a `gh` round trip.
696
+ */
697
+ async function resolveTrunk(
698
+ ref: Pick<PrRef, "owner" | "repo">,
699
+ projectRoot: string,
700
+ ): Promise<string | null> {
701
+ const local = projectRoot === "" ? null : await readTrunkBranch(projectRoot);
702
+ if (local !== null) return local;
703
+ return repoDefaultBranch(ref);
704
+ }
705
+
706
+ /**
707
+ * Stack membership for a branch proved by local git ancestry alone.
708
+ *
709
+ * WHY THIS EXISTS. When the bottom PR of a stack merges and its head branch is
710
+ * deleted, GitHub *retargets* the child PR's base to trunk. The base->head edge
711
+ * that used to join them is then gone from GitHub's data entirely, so no
712
+ * widening of `gh pr list` can rebuild the chain — the evidence has been
713
+ * destroyed, not hidden. The commits, however, have not: a stack branch below
714
+ * this PR is by definition an ancestor of it, so `git branch --contains` still
715
+ * answers the question, with no network call and no `gh`.
716
+ *
717
+ * WHY THE TRUNK GUARD IS NOT OPTIONAL. "B is an ancestor of a stack branch" is
718
+ * true of every branch that was merged into trunk at any point in the
719
+ * repository's history, because trunk is an ancestor of every branch cut from
720
+ * it. Without a guard, a workspace parked on trunk — or on a stale branch
721
+ * merged a year ago — would become a rank-2 stack candidate for *every* PR in
722
+ * the repository, and rank 2 can be the default. So a branch already contained
723
+ * in trunk is rejected, which leaves exactly the branches that carry commits
724
+ * trunk does not have yet:
725
+ *
726
+ * - a squash- or rebase-merged stack branch (the tip is not an ancestor of
727
+ * trunk, because the merge created new commits) whose child has not been
728
+ * restacked yet — the reported bug;
729
+ * - a stack branch with no PR at all, which `gh` cannot see.
730
+ *
731
+ * The cost of the guard is the true-merge-commit case: a branch merged with a
732
+ * real merge commit *is* an ancestor of trunk and is therefore rejected here.
733
+ * Mechanism 1 (the merged/closed `gh pr list`) is what covers that case, and it
734
+ * covers it whenever the head branch still exists so the base->head edge
735
+ * survives. Neither mechanism covers "true merge commit AND branch deleted AND
736
+ * child retargeted"; see plugin/README.md.
737
+ */
738
+ async function ancestryStackMembers(input: {
739
+ projectRoot: string;
740
+ trunk: string;
741
+ /** The PR's own head branch, plus every branch already known to be in the stack. */
742
+ stackRefNames: ReadonlySet<string>;
743
+ branches: readonly string[];
744
+ /** Head branch -> the PR that owns it, for attributing a number and a state. */
745
+ byHead: StackGraph["byHead"];
746
+ }): Promise<Map<string, StackMember>> {
747
+ const found = new Map<string, StackMember>();
748
+ const { trunk } = input;
749
+ const trunkRefs = new Set([trunk, `origin/${trunk}`]);
750
+
751
+ for (const branch of input.branches.slice(0, ANCESTRY_WORKSPACE_LIMIT)) {
752
+ if (trunkRefs.has(branch)) continue;
753
+ const containing = await branchesContaining(input.projectRoot, branch);
754
+ // Silent by design: git missing, an unknown ref, a directory that is not a
755
+ // repository and a timed-out walk are all "no answer", and a resolve is
756
+ // still correct without one.
757
+ if (containing === null) continue;
758
+ let inTrunk = false;
759
+ for (const ref of trunkRefs) if (containing.has(ref)) inTrunk = true;
760
+ if (inTrunk) continue;
761
+ let hit: string | null = null;
762
+ for (const name of input.stackRefNames) {
763
+ if (containing.has(name)) {
764
+ hit = name;
765
+ break;
766
+ }
767
+ }
768
+ if (hit === null) continue;
769
+ const pr = input.byHead.get(branch);
770
+ found.set(branch, {
771
+ number: pr?.number ?? null,
772
+ branch,
773
+ distance: ANCESTRY_STACK_DISTANCE,
774
+ state: pr?.state ?? null,
775
+ });
776
+ console.log(
777
+ `[send-to-paseo] ${branch} is an ancestor of ${hit} and not of ${trunk}, so it is in this stack` +
778
+ `${pr === undefined ? " (no pull request of its own)" : ` (${pr.state} PR #${pr.number})`}`,
779
+ );
780
+ }
781
+ return found;
782
+ }
783
+
784
+ /**
785
+ * Branches in this PR's stack, keyed by branch name.
786
+ *
787
+ * GitHub is the source of truth: one `gh pr list` rebuilds the whole stack, so
788
+ * this no longer depends on what Graphite's stack panel happened to render.
789
+ * That matters — the panel collapses long stacks ("3 of 9, 2 hidden"), and a
790
+ * hidden sibling used to mean the workspace sitting on it was never recognised
791
+ * as a stack match at all.
792
+ *
793
+ * `hints` are the PR numbers the extension scraped from the page. They are
794
+ * still honoured, but only for members the graph did not already find, which in
795
+ * practice means a stack PR that is closed or merged. Usually that is an empty
796
+ * set and costs nothing. On github.com the adapter deliberately sends `[]`, so
797
+ * there are no hints at all there and the mechanisms below are the only cover.
798
+ *
799
+ * THREE PASSES, IN INCREASING COST, EACH ONLY REACHED IF THE LAST LEFT A
800
+ * WORKSPACE UNEXPLAINED. `/v1/resolve` runs on every popover open while the
801
+ * user types, so the first pass — one cached `gh pr list --state open` — is
802
+ * what the common cases pay:
803
+ *
804
+ * 1. the open-PR graph, always;
805
+ * 2. merged and closed PRs (one more `gh pr list`, five-minute cache), only
806
+ * if a project workspace sits on a branch pass 1 could not place. This is
807
+ * what recognises a workspace parked directly on a merged stack branch,
808
+ * and it reconnects a chain whose merged head branch was not deleted;
809
+ * 3. local git ancestry (no network at all), only if a workspace is still
810
+ * unplaced. See `ancestryStackMembers` for what only this can answer.
811
+ *
812
+ * `workspaceBranches` is what makes 2 and 3 conditional. Passing an empty list
813
+ * pins the behaviour to pass 1, which is what a caller wanting the cheap answer
814
+ * should do.
815
+ */
816
+ export async function resolveStackBranches(input: {
817
+ ref: PrRef;
818
+ headBranch: string;
819
+ hints: readonly number[];
820
+ outage: GhOutage | null;
821
+ /** Absolute path of the project's main clone; "" disables the local reads. */
822
+ projectRoot: string;
823
+ /** Branches the project's workspaces are on. Drives passes 2 and 3. */
824
+ workspaceBranches: readonly string[];
825
+ }): Promise<Map<string, StackMember>> {
826
+ const { ref, headBranch, outage } = input;
827
+ const stack = new Map<string, StackMember>();
828
+
829
+ // Passes 1 and 2 need `gh`. When the PR lookup already established that `gh`
830
+ // cannot answer, skip them: retrying would add two more spawn attempts and
831
+ // two more log lines per resolve for a guaranteed failure.
832
+ //
833
+ // Pass 3 needs no `gh` — but it has nothing to work with either. It proves
834
+ // "this branch is an ancestor of a branch in the stack", and without `gh`
835
+ // there is no stack and no `pr.headBranch` to compare against. So a `gh`
836
+ // outage still means no rank-2 candidates at all; the ancestry mechanism
837
+ // narrows the gap when `gh` works, it does not close it when `gh` is down.
838
+ if (outage !== null) return stack;
839
+
840
+ let graph: StackGraph | null = null;
841
+ try {
842
+ graph = await viewStackGraph(ref, headBranch);
843
+ for (const [branch, member] of graph.members) stack.set(branch, member);
844
+ } catch (error) {
845
+ // Never fail a resolve over stack discovery: the exact match and the create
846
+ // option are both still correct without it.
847
+ console.error("[send-to-paseo] stack graph lookup failed", String(error));
848
+ }
849
+
850
+ const known = new Set([...stack.values()].map((member) => member.number));
851
+ const missing = [...new Set(input.hints)].filter(
852
+ (number) => number !== ref.number && !known.has(number),
853
+ );
854
+ if (missing.length > 0) {
855
+ for (const [branch, hint] of await viewStackBranches(ref, missing)) {
856
+ if (stack.has(branch)) continue;
857
+ stack.set(branch, {
858
+ number: hint.number,
859
+ branch,
860
+ distance: UNKNOWN_STACK_DISTANCE,
861
+ state: hint.state,
862
+ });
863
+ }
864
+ }
865
+
866
+ /** Workspace branches this PR's stack does not (yet) explain. */
867
+ const unplaced = (): string[] => [
868
+ ...new Set(
869
+ input.workspaceBranches.filter(
870
+ (branch) => branch !== "" && branch !== headBranch && !stack.has(branch),
871
+ ),
872
+ ),
873
+ ];
874
+
875
+ let outstanding = unplaced();
876
+ if (outstanding.length === 0) return withoutSelf(stack, headBranch);
877
+
878
+ // MEASURED SHORT-CIRCUIT. "Some workspace is unplaced" is nearly always true
879
+ // — the development machine's own project has 38 workspaces, 37 of them on
880
+ // branches unrelated to any given PR — so on its own it is too weak a
881
+ // trigger for a 1.5s pair of lookups. What actually matters is whether the
882
+ // *answer* can still change: a merged or closed member can never outrank an
883
+ // exact branch match or an open sibling (see `stateWeight`), so when one of
884
+ // those already exists, the default is settled and passes 2 and 3 would only
885
+ // relabel a candidate nobody is going to pick. Measured against the live
886
+ // bridge on that project: 2.07s -> 0.94s cold for a PR whose stack already
887
+ // had an open sibling workspace, 1.62s for one that matched nothing at all
888
+ // and still pays for the wider lookups, 0.01s once the lists are cached. The
889
+ // cost, recorded in VERIFICATION.md §19.6: a merged stack workspace reads
890
+ // rank 3 rather than rank 2 when an open sibling is also open in Paseo.
891
+ const settled =
892
+ input.workspaceBranches.includes(headBranch) ||
893
+ input.workspaceBranches.some((branch) => stack.get(branch)?.state === "open");
894
+ if (settled) return withoutSelf(stack, headBranch);
895
+
896
+ const trunk = await resolveTrunk(ref, input.projectRoot);
897
+
898
+ // Pass 2. Merged and closed PRs join the graph, so a chain whose merged head
899
+ // branch still exists reconnects, and a workspace sitting on a merged stack
900
+ // branch is recognised directly. An open PR still wins over a merged one for
901
+ // the same head branch — `viewStackGraph` orders the entries that way.
902
+ try {
903
+ const wide = await viewStackGraph(ref, headBranch, { includeNonOpen: true, trunk });
904
+ graph = wide;
905
+ for (const [branch, member] of wide.members) {
906
+ // The open-PR walk's answer is never overwritten: same hops, and its
907
+ // state is authoritative.
908
+ if (!stack.has(branch)) stack.set(branch, member);
909
+ }
910
+ } catch (error) {
911
+ console.error("[send-to-paseo] merged/closed stack lookup failed", String(error));
912
+ }
913
+
914
+ outstanding = unplaced();
915
+ if (outstanding.length === 0) return withoutSelf(stack, headBranch);
916
+
917
+ // Pass 3. Local, read-only, no network. Needs trunk to be nameable at all;
918
+ // without it every long-merged branch in the repository would qualify.
919
+ if (trunk === null) {
920
+ console.log(
921
+ "[send-to-paseo] no trunk branch could be determined, so the local ancestry " +
922
+ "check for merged stack branches was skipped",
923
+ );
924
+ return withoutSelf(stack, headBranch);
925
+ }
926
+ if (input.projectRoot === "") return withoutSelf(stack, headBranch);
927
+ if (outstanding.length > ANCESTRY_WORKSPACE_LIMIT) {
928
+ console.log(
929
+ `[send-to-paseo] ${outstanding.length} workspaces are on branches this stack does not ` +
930
+ `explain; only the first ${ANCESTRY_WORKSPACE_LIMIT} were checked for stack ancestry`,
931
+ );
932
+ }
933
+ // The PR's own head branch is in the target set deliberately, and is in fact
934
+ // the likeliest hit: a merged branch *below* this PR is an ancestor of this
935
+ // PR's branch, and `stack` never contains the PR's own branch.
936
+ const stackRefNames = new Set<string>();
937
+ for (const branch of [headBranch, ...stack.keys()]) {
938
+ if (branch === "") continue;
939
+ stackRefNames.add(branch);
940
+ // The stack branches were pushed from this clone, so their remote-tracking
941
+ // refs are normally present even when the local branch is not.
942
+ stackRefNames.add(`origin/${branch}`);
943
+ }
944
+ const byAncestry = await ancestryStackMembers({
945
+ projectRoot: input.projectRoot,
946
+ trunk,
947
+ stackRefNames,
948
+ branches: outstanding,
949
+ byHead: graph?.byHead ?? new Map(),
950
+ });
951
+ for (const [branch, member] of byAncestry) {
952
+ if (!stack.has(branch)) stack.set(branch, member);
953
+ }
954
+ return withoutSelf(stack, headBranch);
955
+ }
956
+
957
+ /** The PR's own branch is the exact match, not a sibling. */
958
+ function withoutSelf(
959
+ stack: Map<string, StackMember>,
960
+ headBranch: string,
961
+ ): Map<string, StackMember> {
962
+ stack.delete(headBranch);
963
+ return stack;
964
+ }
965
+
966
+ /** Full `POST /v1/resolve` behaviour. */
967
+ export async function handleResolve(request: ResolveRequest): Promise<ResolveResponse> {
968
+ const ref: PrRef = {
969
+ forge: request.forge,
970
+ owner: request.owner,
971
+ repo: request.repo,
972
+ number: request.number,
973
+ };
974
+ return withPaseo(async (paseo) => {
975
+ // These sources are independent. Starting them together removes several
976
+ // daemon/network round trips from the click path (and the extension now
977
+ // starts this work before the popover opens).
978
+ const [project, prLookup, currentSettings, profile, catalog, allWorkspaces] =
979
+ await Promise.all([
980
+ resolveProject(paseo, ref),
981
+ lookupPr(ref),
982
+ settings.read(),
983
+ resolveSelectedProfile(paseo),
984
+ listModes(paseo),
985
+ paseo.workspaces.list(),
986
+ ]);
987
+ // PR lookup degrades instead of failing when `gh` is unavailable: Paseo's
988
+ // forge checkout still supports the create path.
989
+ const { pr, outage } = prLookup;
990
+ const projectWorkspaces = allWorkspaces.entries.filter(
991
+ (workspace) => workspace.projectId === project.projectId && workspace.archivingAt === null,
992
+ );
993
+ const agentsPromise = listProjectAgents(paseo, project.projectId).catch((error) => {
994
+ console.error("[send-to-paseo] could not list agents", String(error));
995
+ return [] as ListedAgent[];
996
+ });
997
+ const providersPromise = listEffectiveProviders(paseo, profile);
998
+ // The workspace branches are read before stack discovery, not after,
999
+ // because they are what decides whether the cheap open-PR graph was enough:
1000
+ // a branch it could not place is the signal that this may be a merged stack
1001
+ // branch and worth paying for the wider lookups. Read once, used twice.
1002
+ const workspaces = await readWorkspaceBranches(projectWorkspaces);
1003
+ const stackBranches = await resolveStackBranches({
1004
+ ref,
1005
+ headBranch: pr.headBranch,
1006
+ hints: request.stackPrNumbers ?? [],
1007
+ outage,
1008
+ projectRoot: project.path,
1009
+ workspaceBranches: workspaces
1010
+ .map((entry) => entry.branch)
1011
+ .filter((branch): branch is string => branch !== null),
1012
+ });
1013
+ const { candidates, defaultCandidateIndex } = await buildCandidates({
1014
+ paseo,
1015
+ projectId: project.projectId,
1016
+ ref,
1017
+ pr,
1018
+ workspaces,
1019
+ stackBranches,
1020
+ outage,
1021
+ agentDispatch: currentSettings.agentDispatch,
1022
+ agents: await agentsPromise,
1023
+ });
1024
+ const { providers } = await providersPromise;
1025
+ const effectiveProvider = providers.find((entry) => entry.isDefault)?.id ?? providers[0]?.id;
1026
+ const resolvedModeId =
1027
+ effectiveProvider === undefined
1028
+ ? undefined
1029
+ : await resolveDefaultMode(paseo, effectiveProvider, { profile, catalog });
1030
+ return {
1031
+ pr,
1032
+ project,
1033
+ candidates,
1034
+ defaultCandidateIndex,
1035
+ providers,
1036
+ modes: catalog.modes,
1037
+ resolvedModeId: resolvedModeId ?? null,
1038
+ agentDispatch: currentSettings.agentDispatch,
1039
+ };
1040
+ });
1041
+ }