send-to-paseo 2.0.0 → 2.2.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "send-to-paseo",
3
3
  "type": "module",
4
- "version": "2.0.0",
4
+ "version": "2.2.0",
5
5
  "license": "MIT",
6
6
  "description": "Local HTTP bridge that dispatches PR work to the right Paseo workspace and agent.",
7
7
  "repository": {
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "scripts": {
35
35
  "typecheck": "tsc --noEmit",
36
- "test": "node check-deps.mjs && node --test client/hosts.test.mjs server/main-agent.test.mjs",
36
+ "test": "node check-deps.mjs && node --test client/hosts.test.mjs server/main-agent.test.mjs server/follow-up.test.mjs",
37
37
  "verify": "npm run typecheck && npm test && node --test --experimental-strip-types agent-tools.test.mjs && node --test native-tools.test.mjs"
38
38
  },
39
39
  "devDependencies": {
package/server/bridge.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  import { handleSend, isDryRun, recordFailedSend } from "./send";
32
32
  import { previewToken, settings, tokenMatches } from "./settings";
33
33
  import { machineById, resolveOnMachine, sendToMachine } from "./peers";
34
+ import { browserExchange, exchangeBrowser } from "./browser-bridge";
34
35
 
35
36
  /**
36
37
  * The local HTTP bridge the Chrome extension talks to.
@@ -342,6 +343,7 @@ async function ping(authenticated: boolean): Promise<PingResponse> {
342
343
  name: PLUGIN_NAME,
343
344
  version: PLUGIN_VERSION,
344
345
  contract: CONTRACT_VERSION,
346
+ capabilities: { followUpRouting: true },
345
347
  daemon,
346
348
  machine: { name: machineName() },
347
349
  paired: authenticated,
@@ -368,7 +370,7 @@ async function route(
368
370
  return;
369
371
  }
370
372
 
371
- if (path === "/v1/resolve" || path === "/v1/send") {
373
+ if (path === "/v1/resolve" || path === "/v1/send" || path === "/follow-up/v1/exchange") {
372
374
  if (req.method !== "POST") throw methodNotAllowed();
373
375
  const { body, tooLarge } = await readBody(req);
374
376
  if (tooLarge) {
@@ -379,6 +381,12 @@ async function route(
379
381
  }
380
382
  await requireToken(req);
381
383
  const json = parseJsonBody(body);
384
+ if (path === "/follow-up/v1/exchange") {
385
+ const parsed = browserExchange.safeParse(json);
386
+ if (!parsed.success) throw badRequest(parsed.error.issues);
387
+ writeJson(res, 200, await exchangeBrowser(parsed.data, localOnly), cors);
388
+ return;
389
+ }
382
390
 
383
391
  if (path === "/v1/resolve") {
384
392
  const parsed = ResolveRequestSchema.safeParse(json);
@@ -0,0 +1,52 @@
1
+ import { z } from "zod";
2
+ import { callFollowUp, readDaemonStatus } from "./daemon";
3
+ import { exchangeBrowserOnMachine } from "./peers";
4
+ import { settings } from "./settings";
5
+
6
+ const repo = z.string().max(201).regex(/^[\w.-]+\/[\w.-]+$/);
7
+ const result = z.object({ routeId: z.string().min(1).max(200), id: z.string().min(1).max(200), nonce: z.string().min(1).max(200), outcome: z.enum(["completed", "failed", "uncertain"]), prs: z.array(z.object({ repo, number: z.number().int().positive(), head: z.string().min(1).max(200), state: z.enum(["OPEN", "CLOSED", "MERGED"]), mergeWhenReady: z.boolean(), merging: z.boolean() })).max(50), applied: z.array(z.number().int().positive()).max(50), error: z.string().max(500) });
8
+ export const browserExchange = z.object({
9
+ clientId: z.string().min(1).max(100),
10
+ routes: z.array(z.object({ routeId: z.string().min(1).max(200), serverId: z.string().min(1).max(200), repositories: z.array(repo).max(100) })).max(32),
11
+ ready: z.boolean(), acceptJobs: z.boolean(), results: z.array(result).max(10),
12
+ });
13
+ type Exchange = z.infer<typeof browserExchange>;
14
+ const turns = new Map<string, number>();
15
+ type Route = { routeId: string; serverId: string | null; label: string; available: boolean; repositories?: string[]; jobs: unknown[]; accepted: string[] };
16
+
17
+ /** Each route gets its own consent scopes. A proxy can never widen them. */
18
+ export async function exchangeBrowser(input: Exchange, localOnly: boolean) {
19
+ const configured = await settings.read();
20
+ const machines = localOnly ? [] : configured.additionalMachines.filter(m => m.enabled);
21
+ const eligible = ["local", ...machines.map(m => m.id)].filter(id => input.routes.some(r => r.routeId === id && r.repositories.length));
22
+ const turn = turns.get(input.clientId) ?? 0;
23
+ const selected = eligible[turn % eligible.length];
24
+ if (turns.size >= 100) turns.delete(turns.keys().next().value!);
25
+ turns.set(input.clientId, turn + 1);
26
+ const daemon = await readDaemonStatus();
27
+ const localScope = input.routes.find(r => r.routeId === "local" && r.serverId === daemon.serverId);
28
+ const local: Route = { routeId: "local", serverId: daemon.serverId, label: "This Paseo machine", available: false, jobs: [], accepted: [] };
29
+ try {
30
+ const answer = await callFollowUp("follow.browser-exchange", {
31
+ clientId: `send:${input.clientId}`, ready: input.ready && !!localScope?.repositories.length,
32
+ acceptJobs: input.acceptJobs && selected === "local", repositories: localScope?.repositories ?? [],
33
+ results: input.results.filter(r => r.routeId === "local").map(({ routeId: _, ...r }) => r),
34
+ }) as { jobs?: unknown[]; accepted?: string[]; repositories?: unknown };
35
+ local.available = true;
36
+ if (Array.isArray(answer.repositories)) local.repositories = [...new Set(answer.repositories.filter((r): r is string => repo.safeParse(r).success).map(r => r.toLowerCase()))].slice(0, 100);
37
+ local.jobs = Array.isArray(answer.jobs) ? answer.jobs : [];
38
+ local.accepted = Array.isArray(answer.accepted) ? answer.accepted : [];
39
+ } catch { /* Follow Up is optional, including older versions. */ }
40
+ // One fair lease slot across all routes; sleeping peers run within independent total budgets.
41
+ const remoteRoutes = await Promise.all(machines.map(async machine => {
42
+ const route: Route = { routeId: machine.id, serverId: null, label: machine.label, available: false, jobs: [], accepted: [] };
43
+ try {
44
+ const scope = input.routes.find(r => r.routeId === machine.id);
45
+ const response = await exchangeBrowserOnMachine(machine, { ...input, acceptJobs: input.acceptJobs && selected === machine.id, routes: scope ? [{ ...scope, routeId: "local" }] : [], results: input.results.filter(r => r.routeId === machine.id).map(r => ({ ...r, routeId: "local" })) }) as { routes?: Route[] };
46
+ const remote = response.routes?.find(r => r.routeId === "local");
47
+ if (remote) { route.serverId = remote.serverId; route.available = remote.available; route.repositories = remote.repositories; route.jobs = remote.jobs; route.accepted = remote.accepted; }
48
+ } catch { /* A sleeping peer cannot disable local sends. */ }
49
+ return route;
50
+ }));
51
+ return { routes: [local, ...remoteRoutes] };
52
+ }
package/server/daemon.ts CHANGED
@@ -136,6 +136,26 @@ async function resolvePassword(): Promise<string | undefined> {
136
136
  return resolveDaemonPassword(async () => (await settings.read()).daemonPassword);
137
137
  }
138
138
 
139
+ /** Optional companion RPCs always target this daemon, never a browser-selected host. */
140
+ export async function callFollowUp(method: "follow.pr-owner" | "follow.browser-exchange", input: unknown): Promise<unknown> {
141
+ const load = typeof require === "function" ? require : createRequire(join(process.cwd(), "noop.cjs"));
142
+ const { DaemonClient } = load(["@getpaseo", "client", "internal", "daemon-client"].join("/")) as {
143
+ DaemonClient: new (options: Record<string, unknown>) => {
144
+ connect(): Promise<void>; close(): Promise<void>; invokePluginRpc(plugin: string, method: string, input: unknown): Promise<unknown>;
145
+ };
146
+ };
147
+ const password = await resolvePassword();
148
+ const client = new DaemonClient({ url: await resolveUrl(), clientId: "send-to-paseo-follow-up", clientType: "cli", reconnect: { enabled: false }, connectTimeoutMs: 2_000, suppressSendErrors: true, ...(password ? { password } : {}) });
149
+ let timer: ReturnType<typeof setTimeout> | undefined;
150
+ try {
151
+ await client.connect();
152
+ return await Promise.race([
153
+ client.invokePluginRpc("follow-through", method, input),
154
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Optional Follow Up request timed out.")), 2_000); timer.unref?.(); }),
155
+ ]);
156
+ } finally { if (timer) clearTimeout(timer); await client.close().catch(() => undefined); }
157
+ }
158
+
139
159
  /** Runs `work` against an SDK connection that is always closed before returning. */
140
160
  export async function withPaseo<T>(work: (paseo: PaseoApi) => Promise<T>): Promise<T> {
141
161
  const { createPaseoClient } = loadClientModule();
@@ -0,0 +1,15 @@
1
+ import { z } from "zod";
2
+ import { callFollowUp } from "./daemon";
3
+ import type { ListedAgent } from "./main-agent";
4
+
5
+ const ownerReply = z.object({ owner: z.object({ workspaceId: z.string().min(1).max(200), agentId: z.string().min(1).max(200) }).nullable() });
6
+ export type PrOwner = NonNullable<z.infer<typeof ownerReply>["owner"]>;
7
+ export async function lookupPrOwner(owner: string, repo: string, number: number): Promise<PrOwner | null> {
8
+ // Missing, old, stopped or broken companions cannot break standalone sends.
9
+ try { return ownerReply.parse(await callFollowUp("follow.pr-owner", { repo: `${owner}/${repo}`, number })).owner; }
10
+ catch { return null; }
11
+ }
12
+ export function registeredAgent(agents: readonly ListedAgent[], owner: PrOwner | null, workspaceId: string): ListedAgent | null {
13
+ if (!owner || owner.workspaceId !== workspaceId) return null;
14
+ return agents.find(a => a.id === owner.agentId && a.workspaceId === workspaceId && a.archivedAt == null) ?? null;
15
+ }
package/server/peers.ts CHANGED
@@ -381,7 +381,10 @@ export async function sendToMachine(
381
381
  timeoutMs = SEND_ROUTE_TIMEOUT_MS,
382
382
  ): Promise<SendResponse> {
383
383
  const deadline = Date.now() + timeoutMs;
384
- await checkedPing(machine, deadline);
384
+ const ping = await checkedPing(machine, deadline);
385
+ if (request.followUpAgentId && ping.capabilities?.followUpRouting !== true) {
386
+ throw new BridgeError("bad_request", "Update Send to Paseo on the additional machine before sending to a registered Follow Up agent.");
387
+ }
385
388
  const target = { ...request.target };
386
389
  delete target.routeId;
387
390
  const json = await fetchJson(
@@ -402,3 +405,10 @@ export async function sendToMachine(
402
405
  export async function machineById(id: string): Promise<SavedMachine | null> {
403
406
  return (await settings.read()).additionalMachines.find((machine) => machine.id === id) ?? null;
404
407
  }
408
+
409
+ /** Companion transport shares the same authenticated machine-identity check as sends. */
410
+ export async function exchangeBrowserOnMachine(machine: SavedMachine, input: unknown): Promise<unknown> {
411
+ const deadline = Date.now() + 3_000;
412
+ await checkedPing(machine, deadline);
413
+ return fetchJson(machine, "/follow-up/v1/exchange?local=1", { method: "POST", body: JSON.stringify(input) }, remainingMs(deadline));
414
+ }
package/server/resolve.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  type StackPrState,
15
15
  } from "../shared/contracts";
16
16
  import { withPaseo } from "./daemon";
17
+ import { lookupPrOwner, registeredAgent, type PrOwner } from "./follow-up";
17
18
  import {
18
19
  ANCESTRY_STACK_DISTANCE,
19
20
  UNKNOWN_STACK_DISTANCE,
@@ -74,9 +75,16 @@ function sameRepo(a: { owner: string; repo: string }, b: { owner: string; repo:
74
75
  export async function resolveProject(
75
76
  paseo: PaseoApi,
76
77
  ref: Pick<PrRef, "owner" | "repo">,
78
+ preferredProjectId?: string,
77
79
  ): Promise<ProjectPayload> {
78
80
  const { projects } = await paseo.projects.list();
79
81
  const wanted = remoteProjectId(ref.owner, ref.repo).toLowerCase();
82
+ const preferred = projects.find(p => p.projectId === preferredProjectId);
83
+ if (preferred?.projectKind === "git" && preferred.projectRootPath) {
84
+ const fromId = /^remote:github\.com\/([^/]+)\/(.+)$/i.exec(preferred.projectId);
85
+ const identity = fromId?.[1] && fromId[2] ? { owner: fromId[1], repo: fromId[2] } : await readOriginOwnerRepo(preferred.projectRootPath);
86
+ if (identity && sameRepo(identity, ref)) return { projectId: preferred.projectId, name: preferred.projectDisplayName, path: preferred.projectRootPath };
87
+ }
80
88
 
81
89
  for (const project of projects) {
82
90
  if (project.projectId.toLowerCase() === wanted) {
@@ -229,6 +237,7 @@ export async function buildCandidates(input: {
229
237
  /** Non-null when `gh` could not be consulted; carried into the create label. */
230
238
  outage?: GhOutage | null;
231
239
  agents?: readonly ListedAgent[];
240
+ owner?: PrOwner | null;
232
241
  }): Promise<{ candidates: Candidate[]; defaultCandidateIndex: number }> {
233
242
  const { counts, agents } = await workspaceAgents(
234
243
  input.paseo,
@@ -261,16 +270,12 @@ export async function buildCandidates(input: {
261
270
  isolation: isolationOf(workspace),
262
271
  agentCount: counts.get(workspace.id) ?? 0,
263
272
  ...(() => {
273
+ const registered = registeredAgent(agents, input.owner ?? null, workspace.id);
264
274
  const main = selectMainAgent(agents, workspace.id);
265
- return main === null
266
- ? {}
267
- : {
268
- mainAgent: {
269
- agentId: main.id,
270
- title: agentDisplayTitle(main),
271
- status: main.status,
272
- },
273
- };
275
+ return {
276
+ ...(main ? { mainAgent: { agentId: main.id, title: agentDisplayTitle(main), status: main.status } } : {}),
277
+ ...(registered ? { followUpAgent: { agentId: registered.id, title: agentDisplayTitle(registered), status: registered.status } } : {}),
278
+ };
274
279
  })(),
275
280
  };
276
281
  if (branch !== null && branch === input.pr.headBranch) {
@@ -972,14 +977,20 @@ export async function handleResolve(request: ResolveRequest): Promise<ResolveRes
972
977
  // These sources are independent. Starting them together removes several
973
978
  // daemon/network round trips from the click path (and the extension now
974
979
  // starts this work before the popover opens).
975
- const [project, prLookup, currentSettings, profile, catalog, allWorkspaces] =
980
+ const workspacesPromise = paseo.workspaces.list();
981
+ const ownerPromise = lookupPrOwner(ref.owner, ref.repo, ref.number);
982
+ const projectPromise = Promise.all([workspacesPromise, ownerPromise]).then(([all, owner]) =>
983
+ resolveProject(paseo, ref, all.entries.find(w => w.id === owner?.workspaceId && w.archivingAt === null)?.projectId),
984
+ );
985
+ const [project, prLookup, currentSettings, profile, catalog, allWorkspaces, owner] =
976
986
  await Promise.all([
977
- resolveProject(paseo, ref),
987
+ projectPromise,
978
988
  lookupPr(ref),
979
989
  settings.read(),
980
990
  resolveSelectedProfile(paseo),
981
991
  listModes(paseo),
982
- paseo.workspaces.list(),
992
+ workspacesPromise,
993
+ ownerPromise,
983
994
  ]);
984
995
  // PR lookup degrades instead of failing when `gh` is unavailable: Paseo's
985
996
  // forge checkout still supports the create path.
@@ -1016,7 +1027,9 @@ export async function handleResolve(request: ResolveRequest): Promise<ResolveRes
1016
1027
  stackBranches,
1017
1028
  outage,
1018
1029
  agents: await agentsPromise,
1030
+ owner,
1019
1031
  });
1032
+ const ownerIndex = candidates.findIndex(c => c.kind === "existing" && c.followUpAgent !== undefined);
1020
1033
  const { providers } = await providersPromise;
1021
1034
  const effectiveProvider = providers.find((entry) => entry.isDefault)?.id ?? providers[0]?.id;
1022
1035
  const resolvedModeId =
@@ -1027,7 +1040,7 @@ export async function handleResolve(request: ResolveRequest): Promise<ResolveRes
1027
1040
  pr,
1028
1041
  project,
1029
1042
  candidates,
1030
- defaultCandidateIndex,
1043
+ defaultCandidateIndex: ownerIndex >= 0 ? ownerIndex : defaultCandidateIndex,
1031
1044
  providers,
1032
1045
  modes: catalog.modes,
1033
1046
  resolvedModeId: resolvedModeId ?? null,
package/server/send.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  resolveStackBranches,
30
30
  } from "./resolve";
31
31
  import { settings } from "./settings";
32
+ import { lookupPrOwner, registeredAgent } from "./follow-up";
32
33
  import {
33
34
  agentDisplayTitle,
34
35
  agentProvider,
@@ -214,7 +215,9 @@ export async function handleSend(request: SendRequest): Promise<SendResponse> {
214
215
  // daemon status are the slow inputs; starting them together avoids paying
215
216
  // their latency in series after the already-prefetched resolve.
216
217
  const [project, prLookup, serverId, currentSettings] = await Promise.all([
217
- resolveProject(paseo, ref),
218
+ request.target.kind === "existing"
219
+ ? paseo.workspaces.list().then(all => resolveProject(paseo, ref, all.entries.find(w => request.target.kind === "existing" && w.id === request.target.workspaceId && w.archivingAt === null)?.projectId))
220
+ : resolveProject(paseo, ref),
218
221
  lookupPr(ref),
219
222
  requireServerId(),
220
223
  settings.read(),
@@ -306,11 +309,17 @@ export async function handleSend(request: SendRequest): Promise<SendResponse> {
306
309
  let mainAgent: ListedAgent | null = null;
307
310
  if (agentDispatch === "main" && request.target.kind === "existing") {
308
311
  try {
309
- mainAgent = selectMainAgent(
310
- await listProjectAgents(paseo, project.projectId),
311
- workspaceId,
312
- );
312
+ const [agents, owner] = await Promise.all([
313
+ listProjectAgents(paseo, project.projectId),
314
+ request.followUpAgentId ? lookupPrOwner(ref.owner, ref.repo, ref.number) : Promise.resolve(null),
315
+ ]);
316
+ const registered = request.followUpAgentId ? registeredAgent(agents, owner, workspaceId) : null;
317
+ if (request.followUpAgentId && registered?.id !== request.followUpAgentId) {
318
+ throw new BridgeError("bad_request", "The Follow Up registration changed or is unavailable. Reopen the composer before sending.");
319
+ }
320
+ mainAgent = registered ?? selectMainAgent(agents, workspaceId);
313
321
  } catch (error) {
322
+ if (error instanceof BridgeError) throw error;
314
323
  throw new BridgeError(
315
324
  "agent_create_failed",
316
325
  `Paseo could not find the main agent in ${workspaceLabel}: ${
@@ -9,7 +9,7 @@ import { z } from "zod";
9
9
 
10
10
  /** Advertised in `GET /v1/ping`. Keep in step with `package.json`. */
11
11
  export const PLUGIN_NAME = "send-to-paseo";
12
- export const PLUGIN_VERSION = "2.0.0";
12
+ export const PLUGIN_VERSION = "2.2.0";
13
13
  /** Bumped only for an incompatible bridge API; the paths stay `/v1`. */
14
14
  export const CONTRACT_VERSION = 1;
15
15
 
@@ -133,6 +133,7 @@ export const SendRequestSchema = PrRefSchema.extend({
133
133
  target: SendTargetSchema,
134
134
  /** Per-send override. Missing preserves the plugin's saved preference. */
135
135
  agentDispatch: AgentDispatchSchema.optional(),
136
+ followUpAgentId: z.string().min(1).max(200).optional(),
136
137
  provider: z.string().min(1).max(200).optional(),
137
138
  /**
138
139
  * Permission mode for the new agent, e.g. `auto` or `bypassPermissions`.
@@ -203,6 +204,7 @@ export class BridgeError extends Error {
203
204
  }
204
205
 
205
206
  export interface PingResponse {
207
+ capabilities?: { followUpRouting?: boolean };
206
208
  ok: true;
207
209
  name: string;
208
210
  version: string;
@@ -284,6 +286,8 @@ export interface ExistingCandidate {
284
286
  title: string;
285
287
  status: "error" | "initializing" | "idle" | "running" | "closed";
286
288
  };
289
+ /** Explicit PR registration, independent of the workspace's root-agent heuristic. */
290
+ followUpAgent?: { agentId: string; title: string; status: string };
287
291
  }
288
292
 
289
293
  export interface CreateCandidate {
@@ -552,6 +556,7 @@ export const updateConfig = defineRpc({
552
556
  /** Null clears the override and falls back to the mode chain. */
553
557
  defaultModeId: z.string().max(200).nullable().optional(),
554
558
  agentDispatch: AgentDispatchSchema.optional(),
559
+ followUpAgentId: z.string().min(1).max(200).optional(),
555
560
  /** Null removes the declared reverse-proxy origin. */
556
561
  externalBridgeUrl: ExternalBridgeUrlSchema.nullable().optional(),
557
562
  }),