send-to-paseo 2.4.1 → 2.5.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.
@@ -14,6 +14,7 @@ import {
14
14
  addAdditionalMachine,
15
15
  clearRecentSends,
16
16
  DEFAULT_PORT,
17
+ PLUGIN_VERSION,
17
18
  enablePrivateAccess,
18
19
  externalBridgeUrlProblem,
19
20
  getConnectionCode,
@@ -1186,6 +1187,7 @@ export function SendToPaseoSettings({ theme, host, layout, navigation }: PluginS
1186
1187
  </>
1187
1188
  ) : null}
1188
1189
 
1190
+ <Text selectable style={styles.muted}>Send to Paseo {PLUGIN_VERSION}</Text>
1189
1191
  </ScrollView>
1190
1192
  );
1191
1193
  }
package/index.server.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  updateConfig,
18
18
  } from "./shared/contracts";
19
19
  import { getBridgeStatus, restartBridge, runBridge } from "./server/bridge";
20
+ import { closeDaemon, warmDaemon } from "./server/daemon";
20
21
  import { dependencySnapshot } from "./server/deps";
21
22
  import {
22
23
  listAgentProfiles,
@@ -178,5 +179,8 @@ export default function contribute(server: PluginServerContext) {
178
179
  });
179
180
 
180
181
  const stopBridge = runBridge();
181
- return async () => { removeTools(); await stopBridge(); };
182
+ // Connect now, not on the first popover: the click path never pays for a daemon connect (warm-daemon-connection).
183
+ warmDaemon();
184
+ // The held daemon connection closes after the bridge has stopped serving requests.
185
+ return async () => { removeTools(); await stopBridge(); await closeDaemon(); };
182
186
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "send-to-paseo",
3
3
  "type": "module",
4
- "version": "2.4.1",
4
+ "version": "2.5.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": {
@@ -35,7 +35,7 @@
35
35
  },
36
36
  "scripts": {
37
37
  "typecheck": "tsc --noEmit",
38
- "test": "node check-deps.mjs && node --test client/hosts.test.mjs server/main-agent.test.mjs server/follow-up.test.mjs",
38
+ "test": "node check-deps.mjs && node --test client/hosts.test.mjs client/settings.test.mjs server/main-agent.test.mjs server/follow-up.test.mjs server/daemon-connection.test.mjs",
39
39
  "verify": "npm run typecheck && npm test && node --test --experimental-strip-types agent-tools.test.mjs shared/chat.test.mjs && node --test native-tools.test.mjs"
40
40
  },
41
41
  "devDependencies": {
package/server/daemon.ts CHANGED
@@ -7,20 +7,30 @@ import { BridgeError } from "../shared/contracts";
7
7
  import { resolveDaemonPassword } from "./daemon-password";
8
8
  import { settings } from "./settings";
9
9
  import { invokeFollowUp } from "./follow-up-id";
10
+ import { sharedDaemon } from "./shared-daemon";
10
11
 
11
12
  /**
12
- * Short-lived Paseo SDK connections for the HTTP bridge.
13
+ * The plugin's one held daemon connection (one-held-daemon-connection, AGENTS.md).
13
14
  *
14
15
  * Only RPC handlers receive a `paseo` handle, and the bridge serves requests
15
- * that arrive long before any surface is opened, so it opens its own SDK
16
- * connection per request and closes it again. That is deliberate on two counts:
17
- * a long-lived reconnecting socket in this subprocess would keep the event loop
18
- * alive and hang Paseo's "Stopping plugin" step, and a per-request connection
19
- * cannot go stale between sends.
16
+ * that arrive long before any surface is opened, so it keeps its own
17
+ * connection. Every bridge request (`withPaseo`) and every optional Follow Up
18
+ * call (`callFollowUp`) runs on the same held DaemonClient: a request gets a
19
+ * scoped SDK view (`createPaseoApi`) that is disposed when it ends, never a new
20
+ * socket. A drop retires the connection and the next request opens one fresh;
21
+ * `closeDaemon` in the plugin's teardown closes it, so a held socket never
22
+ * hangs Paseo's "Stopping plugin" step. 2026-11-17 live: a connection per
23
+ * request meant about 20 hellos a minute for each of the two client names
24
+ * while a browser had the extension open.
20
25
  */
21
26
 
22
27
  const CONNECT_TIMEOUT_MS = 10_000;
23
28
  const STATUS_TIMEOUT_MS = 2_000;
29
+ /**
30
+ * An optional Follow Up call gives up after this long. The popover's lookups never spend it on a
31
+ * connect (they run only on a connected client, warm-daemon-connection), so it covers the RPC alone.
32
+ */
33
+ const FOLLOW_UP_TIMEOUT_MS = 2_000;
24
34
  const STATUS_TTL_MS = 15_000;
25
35
 
26
36
  function timeoutSignal(ms: number): AbortSignal {
@@ -33,45 +43,55 @@ function timeoutSignal(ms: number): AbortSignal {
33
43
 
34
44
  type PaseoApi = PluginHandlerContext["paseo"];
35
45
 
46
+ /** The subset of Paseo's DaemonClient this plugin uses. */
47
+ interface DaemonClient {
48
+ connect(): Promise<void>;
49
+ close(): Promise<void>;
50
+ invokePluginRpc(plugin: string, method: string, input: unknown): Promise<unknown>;
51
+ getConnectionState?(): { status: string };
52
+ }
53
+
36
54
  interface ClientModule {
37
- createPaseoClient(options: {
55
+ createPaseoApi(client: DaemonClient): PaseoApi & { dispose(): Promise<void> };
56
+ DaemonClient: new (options: {
38
57
  url: string;
39
58
  clientId: string;
59
+ clientType: "cli";
40
60
  reconnect: { enabled: boolean };
41
61
  connectTimeoutMs: number;
42
62
  suppressSendErrors: boolean;
43
63
  password?: string;
44
- }): PaseoApi & {
45
- connect(): Promise<void>;
46
- close(): Promise<void>;
47
- };
64
+ }) => DaemonClient;
48
65
  }
49
66
 
50
67
  let clientModule: ClientModule | null = null;
51
68
 
52
69
  /**
53
- * Borrows Paseo's own SDK from the host at runtime.
70
+ * Borrows Paseo's own SDK and daemon client from the host at runtime.
54
71
  *
55
- * The specifier is assembled rather than written as a literal so the plugin
56
- * compiler cannot resolve it at build time. That keeps the plugin installable
72
+ * The specifiers are assembled rather than written as literals so the plugin
73
+ * compiler cannot resolve them at build time. That keeps the plugin installable
57
74
  * from a directory or from Git without a package manager step, and it removes
58
75
  * any chance of a protocol version skew between a bundled copy of the SDK and
59
76
  * the daemon actually running.
60
77
  */
61
78
  function loadClientModule(): ClientModule {
62
79
  if (clientModule !== null) return clientModule;
63
- const specifier = ["@getpaseo", "client"].join("/");
80
+ const sdk = ["@getpaseo", "client"].join("/");
81
+ const internal = [sdk, "internal", "daemon-client"].join("/");
64
82
  // Paseo compiles plugin backends to CommonJS, so `require` is normally right
65
83
  // here. `createRequire` keeps this working if a host ever loads the module as
66
84
  // real ESM instead, where `require` is not defined.
67
85
  const load: NodeRequire =
68
86
  typeof require === "function" ? require : createRequire(join(process.cwd(), "noop.cjs"));
69
87
  try {
70
- clientModule = load(specifier) as ClientModule;
88
+ const { createPaseoApi } = load(sdk) as Pick<ClientModule, "createPaseoApi">;
89
+ const { DaemonClient } = load(internal) as Pick<ClientModule, "DaemonClient">;
90
+ clientModule = { createPaseoApi, DaemonClient };
71
91
  } catch (error) {
72
92
  throw new BridgeError(
73
93
  "daemon_unreachable",
74
- `This Paseo host does not expose its client SDK (${specifier}), which the Send to Paseo bridge needs: ${
94
+ `This Paseo host does not expose its client SDK (${sdk}), which the Send to Paseo bridge needs: ${
75
95
  error instanceof Error ? error.message : String(error)
76
96
  }`,
77
97
  );
@@ -137,33 +157,17 @@ async function resolvePassword(): Promise<string | undefined> {
137
157
  return resolveDaemonPassword(async () => (await settings.read()).daemonPassword);
138
158
  }
139
159
 
140
- /** Optional companion RPCs always target this daemon, never a browser-selected host. */
141
- export async function callFollowUp(method: "follow.pr-owner" | "follow.pr-workspaces" | "follow.browser-exchange", input: unknown): Promise<unknown> {
142
- const load = typeof require === "function" ? require : createRequire(join(process.cwd(), "noop.cjs"));
143
- const { DaemonClient } = load(["@getpaseo", "client", "internal", "daemon-client"].join("/")) as {
144
- DaemonClient: new (options: Record<string, unknown>) => {
145
- connect(): Promise<void>; close(): Promise<void>; invokePluginRpc(plugin: string, method: string, input: unknown): Promise<unknown>;
146
- };
147
- };
148
- const password = await resolvePassword();
149
- 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 } : {}) });
150
- let timer: ReturnType<typeof setTimeout> | undefined;
151
- try {
152
- await client.connect();
153
- return await Promise.race([
154
- invokeFollowUp((plugin, m, i) => client.invokePluginRpc(plugin, m, i), method, input),
155
- new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Optional Follow Up request timed out.")), 2_000); timer.unref?.(); }),
156
- ]);
157
- } finally { if (timer) clearTimeout(timer); await client.close().catch(() => undefined); }
158
- }
159
-
160
- /** Runs `work` against an SDK connection that is always closed before returning. */
161
- export async function withPaseo<T>(work: (paseo: PaseoApi) => Promise<T>): Promise<T> {
162
- const { createPaseoClient } = loadClientModule();
160
+ /**
161
+ * Builds and connects the one client. The only place a DaemonClient is built;
162
+ * a failure here is a `daemon_unreachable` BridgeError.
163
+ */
164
+ async function openDaemon(): Promise<DaemonClient> {
165
+ const { DaemonClient } = loadClientModule();
163
166
  const password = await resolvePassword();
164
- const client = createPaseoClient({
167
+ const client = new DaemonClient({
165
168
  url: await resolveUrl(),
166
- clientId: "send-to-paseo-bridge",
169
+ clientId: "send-to-paseo",
170
+ clientType: "cli",
167
171
  reconnect: { enabled: false },
168
172
  connectTimeoutMs: CONNECT_TIMEOUT_MS,
169
173
  suppressSendErrors: true,
@@ -173,6 +177,7 @@ export async function withPaseo<T>(work: (paseo: PaseoApi) => Promise<T>): Promi
173
177
  });
174
178
  try {
175
179
  await client.connect();
180
+ return client;
176
181
  } catch (error) {
177
182
  await client.close().catch(() => undefined);
178
183
  const detail = error instanceof Error ? error.message : String(error);
@@ -191,12 +196,74 @@ export async function withPaseo<T>(work: (paseo: PaseoApi) => Promise<T>): Promi
191
196
  detail,
192
197
  );
193
198
  }
199
+ }
200
+
201
+ const shared = sharedDaemon(openDaemon, { keepWarm: true });
202
+
203
+ /** Opens the held connection in the background. The plugin calls it at start so no popover pays for the connect. */
204
+ export function warmDaemon(): void {
205
+ shared.warm();
206
+ }
207
+
208
+ /** Closes the held connection. The plugin's teardown runs it after the bridge stops. */
209
+ export function closeDaemon(): Promise<void> {
210
+ return shared.close();
211
+ }
212
+
213
+ /**
214
+ * Thrown when Follow-up could not be asked: no connected client yet, the call outran its budget, or
215
+ * the socket went away. That is "couldn't check", never "Follow-up has nothing" (AGENTS.md,
216
+ * optional-lookup-never-silent). Follow-up's own answers, absence included, are thrown as they are.
217
+ */
218
+ export class FollowUpUnreachableError extends Error {
219
+ readonly code = "follow_up_unreachable";
220
+ }
221
+ export const isFollowUpUnreachable = (error: unknown): boolean =>
222
+ (error as { code?: unknown } | null)?.code === "follow_up_unreachable";
223
+
224
+ /**
225
+ * Optional companion RPCs always target this daemon, never a browser-selected host. With
226
+ * `ifConnected` (the popover's lookups) the call never waits on a connect: no connected client
227
+ * means unreachable at once, and the background warm-up is already reconnecting.
228
+ */
229
+ export async function callFollowUp(method: "follow.pr-owner" | "follow.pr-workspaces" | "follow.browser-exchange", input: unknown, options: { ifConnected?: boolean } = {}): Promise<unknown> {
230
+ let timer: ReturnType<typeof setTimeout> | undefined;
231
+ let reached = false;
194
232
  try {
195
- return await work(client);
196
- } finally {
197
- // Teardown must not mask the original result or error.
198
- await client.close().catch(() => undefined);
199
- }
233
+ return await Promise.race([
234
+ shared.run(async (client) => {
235
+ reached = true;
236
+ try {
237
+ return await invokeFollowUp((plugin, m, i) => client.invokePluginRpc(plugin, m, i), method, input);
238
+ } catch (error) {
239
+ // The socket went away under the call: the question never got its answer.
240
+ const status = client.getConnectionState?.().status;
241
+ if (status !== undefined && status !== "connected") throw new FollowUpUnreachableError(error instanceof Error ? error.message : String(error));
242
+ throw error;
243
+ }
244
+ }, { ifConnected: options.ifConnected === true }),
245
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new FollowUpUnreachableError("Optional Follow Up request timed out.")), FOLLOW_UP_TIMEOUT_MS); timer.unref?.(); }),
246
+ ]);
247
+ } catch (error) {
248
+ if (isFollowUpUnreachable(error)) throw error;
249
+ // Never reached a connected client (not connected, failed open, backoff): couldn't check.
250
+ if (!reached) throw new FollowUpUnreachableError(error instanceof Error ? error.message : String(error));
251
+ throw error;
252
+ } finally { if (timer) clearTimeout(timer); }
253
+ }
254
+
255
+ /** Runs `work` against a scoped SDK view of the held connection, released before returning. */
256
+ export async function withPaseo<T>(work: (paseo: PaseoApi) => Promise<T>): Promise<T> {
257
+ const { createPaseoApi } = loadClientModule();
258
+ return shared.run(async (client) => {
259
+ const paseo = createPaseoApi(client);
260
+ try {
261
+ return await work(paseo);
262
+ } finally {
263
+ // Releases this request's handles and listeners, never the socket.
264
+ await paseo.dispose().catch(() => undefined);
265
+ }
266
+ });
200
267
  }
201
268
 
202
269
  export interface DaemonStatus {
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
- import { callFollowUp } from "./daemon";
2
+ import { callFollowUp, isFollowUpUnreachable } from "./daemon";
3
3
  import type { ListedAgent } from "./main-agent";
4
- import { buildAgentDeepLink, buildAgentWebLink, type FollowUpView } from "../shared/contracts";
4
+ import { buildAgentDeepLink, buildAgentWebLink, type Candidate, type FollowUpView } from "../shared/contracts";
5
5
 
6
6
  const ownerReply = z.object({ owner: z.object({ workspaceId: z.string().min(1).max(200), agentId: z.string().min(1).max(200) }).nullable() });
7
7
  export type PrOwner = NonNullable<z.infer<typeof ownerReply>["owner"]>;
@@ -21,15 +21,20 @@ const workspacesReply = z.object({
21
21
  workspaces: z.array(z.object({ workspaceId: text(200).min(1), agentId: text(200).min(1), title: text(200), agentStatus: text(40), group: text(20), state: text(200) })).max(3),
22
22
  });
23
23
  export type PrWorkspaces = Omit<z.infer<typeof workspacesReply>, "tracked">;
24
+ /** Follow-up could not be asked in time (not connected, budget spent, socket gone). Not "none". */
25
+ export const FOLLOW_UP_UNKNOWN = "unknown" as const;
24
26
  /**
25
- * Follow-up's owners of a PR, or null when there is nothing to show: Follow-up absent, older than this RPC,
26
- * broken, or the repository outside the scope it tracks (and therefore advertises to the browser).
27
+ * Follow-up's owners of a PR; null when there is nothing to show (Follow-up absent, older than this RPC,
28
+ * broken, or the repository outside the scope it tracks and therefore advertises to the browser); or
29
+ * `"unknown"` when it could not be asked. Unknown must never read as none (optional-lookup-never-silent).
30
+ * Never waits on a daemon connect: the popover's click path does not pay for one (warm-daemon-connection).
27
31
  */
28
- export async function lookupPrWorkspaces(owner: string, repo: string, number: number): Promise<PrWorkspaces | null> {
29
- try {
30
- const reply = workspacesReply.parse(await callFollowUp("follow.pr-workspaces", { repo: `${owner}/${repo}`, number }));
31
- return reply.tracked ? { workspaces: reply.workspaces, more: reply.more } : null;
32
- } catch { return null; }
32
+ export async function lookupPrWorkspaces(owner: string, repo: string, number: number): Promise<PrWorkspaces | null | typeof FOLLOW_UP_UNKNOWN> {
33
+ let raw: unknown;
34
+ try { raw = await callFollowUp("follow.pr-workspaces", { repo: `${owner}/${repo}`, number }, { ifConnected: true }); }
35
+ catch (error) { return isFollowUpUnreachable(error) ? FOLLOW_UP_UNKNOWN : null; }
36
+ const reply = workspacesReply.safeParse(raw);
37
+ return reply.success && reply.data.tracked ? { workspaces: reply.data.workspaces, more: reply.data.more } : null;
33
38
  }
34
39
  /** Adds this machine's open links and Paseo's own workspace names. Without a server id no link can be built, so nothing is shown. */
35
40
  export function followUpView(found: PrWorkspaces | null, serverId: string | null, names: ReadonlyMap<string, string>): FollowUpView | undefined {
@@ -39,3 +44,23 @@ export function followUpView(found: PrWorkspaces | null, serverId: string | null
39
44
  workspaces: found.workspaces.map(w => ({ ...w, title: names.get(w.workspaceId) || w.title || w.workspaceId, deepLink: buildAgentDeepLink({ serverId, agentId: w.agentId }), webUrl: buildAgentWebLink({ serverId, agentId: w.agentId }) })),
40
45
  };
41
46
  }
47
+ /**
48
+ * The resolve answer's Follow-up fields. When the workspaces lookup is unknown it says so
49
+ * (`followUpUnreachable`), and still offers the registered owner from `follow.pr-owner` when that
50
+ * owner's agent is one of this PR's candidates, with the same open links as `followUpView`.
51
+ */
52
+ export function followUpAnswer(
53
+ found: PrWorkspaces | null | typeof FOLLOW_UP_UNKNOWN,
54
+ owner: PrOwner | null,
55
+ candidates: readonly Candidate[],
56
+ serverId: string | null,
57
+ names: ReadonlyMap<string, string>,
58
+ ): { followUp?: FollowUpView; followUpUnreachable?: true } {
59
+ if (found !== FOLLOW_UP_UNKNOWN) { const view = followUpView(found, serverId, names); return view ? { followUp: view } : {}; }
60
+ const registered = owner ? candidates.find(c => c.kind === "existing" && c.workspaceId === owner.workspaceId && c.followUpAgent?.agentId === owner.agentId) : undefined;
61
+ const agent = registered?.kind === "existing" ? registered.followUpAgent : undefined;
62
+ const fallback = owner && agent
63
+ ? followUpView({ more: 0, workspaces: [{ workspaceId: owner.workspaceId, agentId: owner.agentId, title: "", agentStatus: agent.status, group: "", state: "" }] }, serverId, names)
64
+ : undefined;
65
+ return { followUpUnreachable: true, ...(fallback ? { followUp: fallback } : {}) };
66
+ }
package/server/resolve.ts CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  type StackPrState,
15
15
  } from "../shared/contracts";
16
16
  import { requireServerId, withPaseo } from "./daemon";
17
- import { followUpView, lookupPrOwner, lookupPrWorkspaces, registeredAgent, type PrOwner } from "./follow-up";
17
+ import { followUpAnswer, lookupPrOwner, lookupPrWorkspaces, registeredAgent, type PrOwner } from "./follow-up";
18
18
  import {
19
19
  ANCESTRY_STACK_DISTANCE,
20
20
  UNKNOWN_STACK_DISTANCE,
@@ -979,7 +979,8 @@ export async function handleResolve(request: ResolveRequest): Promise<ResolveRes
979
979
  // starts this work before the popover opens).
980
980
  const workspacesPromise = paseo.workspaces.list();
981
981
  const ownerPromise = lookupPrOwner(ref.owner, ref.repo, ref.number);
982
- // Asked for only by an extension with Follow-up browser access on; absent or failing is "no section".
982
+ // Asked for only by an extension with Follow-up browser access on. Absent is "no section"; not
983
+ // reached in time is `followUpUnreachable`, never "no section" (optional-lookup-never-silent).
983
984
  const followUpPromise = request.followUp === true
984
985
  ? Promise.all([lookupPrWorkspaces(ref.owner, ref.repo, ref.number), requireServerId().catch(() => null)])
985
986
  : Promise.resolve([null, null] as const);
@@ -1041,9 +1042,12 @@ export async function handleResolve(request: ResolveRequest): Promise<ResolveRes
1041
1042
  ? undefined
1042
1043
  : await resolveDefaultMode(paseo, effectiveProvider, { profile, catalog });
1043
1044
  const [ownersFound, serverId] = await followUpPromise;
1044
- const followUp = followUpView(ownersFound, serverId, new Map(allWorkspaces.entries.map(w => [w.id, typeof w.name === "string" ? w.name : ""])));
1045
+ // Unknown (Follow-up not asked in time) is said, never dropped into "no section".
1046
+ const followUp = request.followUp === true
1047
+ ? followUpAnswer(ownersFound, owner, candidates, serverId, new Map(allWorkspaces.entries.map(w => [w.id, typeof w.name === "string" ? w.name : ""])))
1048
+ : {};
1045
1049
  return {
1046
- ...(followUp ? { followUp } : {}),
1050
+ ...followUp,
1047
1051
  pr,
1048
1052
  project,
1049
1053
  candidates,
@@ -0,0 +1,191 @@
1
+ /**
2
+ * One held daemon connection, shared by every caller in this process
3
+ * (one-held-daemon-connection, AGENTS.md).
4
+ *
5
+ * Concurrent callers join the open in flight. A real drop (the client's own
6
+ * connection status, or a call that failed on a socket no longer `connected`)
7
+ * retires it, and the next call opens one fresh connection. A failed open backs
8
+ * off, and calls inside that window fail fast with the same error. A connection
9
+ * older than `maxMs` is replaced once its in-flight calls finish. `close()` is
10
+ * the plugin's teardown: nothing opens afterwards, so the subprocess can exit.
11
+ *
12
+ * With `keepWarm` the connection is also kept open between requests
13
+ * (warm-daemon-connection, AGENTS.md), so the popover's click path never pays
14
+ * for a connect: `warm()` opens it at plugin start, a drop or a failed open
15
+ * reconnects in the background on the same backoff, and an aged connection
16
+ * keeps serving until its replacement is connected. `run(work, { ifConnected:
17
+ * true })` never waits on a connect: with no connected client it starts one and
18
+ * fails at once with `code: "not_connected"`.
19
+ */
20
+
21
+ export interface Closable {
22
+ close(): Promise<void>;
23
+ }
24
+
25
+ type ConnectionStatus = { status: string };
26
+ type StatusSource = {
27
+ getConnectionState?(): ConnectionStatus;
28
+ subscribeConnectionStatus?(listener: (state: ConnectionStatus) => void): () => void;
29
+ };
30
+
31
+ export interface RunOptions {
32
+ /** Fail at once (`code: "not_connected"`) instead of waiting for a connect. */
33
+ ifConnected?: boolean;
34
+ }
35
+
36
+ export interface SharedDaemon<C extends Closable> {
37
+ run<T>(work: (client: C) => Promise<T>, options?: RunOptions): Promise<T>;
38
+ /** Opens the connection in the background if none is open or opening. Never throws. */
39
+ warm(): void;
40
+ close(): Promise<void>;
41
+ }
42
+
43
+ export const SHARED_CLIENT_MAX_MS = 30 * 60_000;
44
+ export const OPEN_BACKOFF_MS = 1_000;
45
+ export const OPEN_BACKOFF_MAX_MS = 30_000;
46
+
47
+ export class NotConnectedError extends Error {
48
+ readonly code = "not_connected";
49
+ constructor() { super("The Paseo daemon connection is not open yet."); }
50
+ }
51
+
52
+ export function sharedDaemon<C extends Closable>(
53
+ open: () => Promise<C>,
54
+ options: { maxMs?: number; now?: () => number; backoffMs?: number; backoffMaxMs?: number; stopping?: () => Error; keepWarm?: boolean } = {},
55
+ ): SharedDaemon<C> {
56
+ const maxMs = options.maxMs ?? SHARED_CLIENT_MAX_MS;
57
+ const now = options.now ?? Date.now;
58
+ const backoffMs = options.backoffMs ?? OPEN_BACKOFF_MS;
59
+ const backoffMaxMs = options.backoffMaxMs ?? OPEN_BACKOFF_MAX_MS;
60
+ const stopping = options.stopping ?? (() => new Error("Send to Paseo is stopping."));
61
+ const keepWarm = options.keepWarm === true;
62
+ type Entry = { client: Promise<C>; ready: C | null; opened: number; users: number; retired: boolean; unsubscribe?: () => void };
63
+ let current: Entry | null = null;
64
+ /** The replacement for an aged `current`, opening while `current` keeps serving. */
65
+ let next: Entry | null = null;
66
+ let stopped = false;
67
+ let failures = 0;
68
+ let retryAt = 0;
69
+ let lastError: unknown = null;
70
+ // A one-shot, unref'd timer for the background reconnect, cleared in close(): it never keeps
71
+ // the subprocess alive and never outlives teardown (AGENTS.md forbids live timers here).
72
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
73
+ const all = new Set<Entry>();
74
+
75
+ const live = (client: C) => {
76
+ const status = (client as unknown as StatusSource).getConnectionState?.().status;
77
+ return status === undefined || status === "connected";
78
+ };
79
+ const shut = async (entry: Entry) => {
80
+ all.delete(entry);
81
+ if (current === entry) current = null;
82
+ if (next === entry) next = null;
83
+ entry.unsubscribe?.();
84
+ const client = await entry.client.catch(() => null);
85
+ if (client) await client.close().catch(() => undefined);
86
+ };
87
+ const scheduleWarm = () => {
88
+ if (!keepWarm || stopped || retryTimer) return;
89
+ retryTimer = setTimeout(() => { retryTimer = null; warm(); }, Math.max(0, retryAt - now()));
90
+ retryTimer.unref?.();
91
+ };
92
+ const retire = (entry: Entry) => {
93
+ if (entry.retired) return;
94
+ entry.retired = true;
95
+ if (current === entry) current = null;
96
+ if (next === entry) next = null;
97
+ if (entry.users === 0) void shut(entry);
98
+ if (!current && !next) scheduleWarm();
99
+ };
100
+
101
+ const start = (): Entry => {
102
+ const entry = { opened: now(), users: 0, retired: false, ready: null } as Entry;
103
+ entry.client = open().then(
104
+ (client) => {
105
+ failures = 0;
106
+ if (stopped) {
107
+ void client.close().catch(() => undefined);
108
+ throw stopping();
109
+ }
110
+ entry.ready = client;
111
+ entry.unsubscribe = (client as unknown as StatusSource).subscribeConnectionStatus?.((state) => {
112
+ if (state.status === "disconnected" || state.status === "disposed") retire(entry);
113
+ });
114
+ if (next === entry) {
115
+ // The replacement is connected: it takes over, and the aged one closes once idle.
116
+ next = null;
117
+ const aged = current;
118
+ current = entry;
119
+ if (aged) retire(aged);
120
+ }
121
+ return client;
122
+ },
123
+ (error: unknown) => {
124
+ failures++;
125
+ lastError = error;
126
+ retryAt = now() + Math.min(backoffMs * 2 ** (failures - 1), backoffMaxMs);
127
+ all.delete(entry);
128
+ if (current === entry) current = null;
129
+ if (next === entry) next = null;
130
+ if (!current) scheduleWarm();
131
+ throw error;
132
+ },
133
+ );
134
+ // A background open's failure is recorded above; nobody else awaits it.
135
+ entry.client.catch(() => undefined);
136
+ all.add(entry);
137
+ return entry;
138
+ };
139
+
140
+ /** The entry a call should use now, opening or rotating as needed. Null inside the open backoff. */
141
+ const select = (): Entry | null => {
142
+ if (current && now() - current.opened >= maxMs) {
143
+ if (keepWarm && current.ready && live(current.ready)) {
144
+ // Rotate without a gap: keep serving on the aged connection until the new one is up.
145
+ if (!next && !(failures > 0 && now() < retryAt)) next = start();
146
+ } else {
147
+ retire(current);
148
+ }
149
+ }
150
+ if (!current) {
151
+ if (failures > 0 && now() < retryAt) return null;
152
+ current = start();
153
+ }
154
+ return current;
155
+ };
156
+
157
+ function warm(): void {
158
+ if (stopped) return;
159
+ try { select(); } catch { /* recorded by start() */ }
160
+ }
161
+
162
+ const run = async <T>(work: (client: C) => Promise<T>, runOptions: RunOptions = {}): Promise<T> => {
163
+ if (stopped) throw stopping();
164
+ const entry = select();
165
+ if (!entry) {
166
+ if (runOptions.ifConnected) throw new NotConnectedError();
167
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
168
+ }
169
+ if (runOptions.ifConnected && !(entry.ready && live(entry.ready))) throw new NotConnectedError();
170
+ entry.users++;
171
+ try {
172
+ const client = await entry.client;
173
+ try {
174
+ return await work(client);
175
+ } catch (error) {
176
+ if (!live(client)) retire(entry);
177
+ throw error;
178
+ }
179
+ } finally {
180
+ entry.users--;
181
+ if (entry.retired && entry.users === 0 && all.has(entry)) void shut(entry);
182
+ }
183
+ };
184
+
185
+ const close = async () => {
186
+ stopped = true;
187
+ if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
188
+ await Promise.allSettled([...all].map((entry) => shut(entry)));
189
+ };
190
+ return { run, warm, close };
191
+ }
@@ -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.4.1";
12
+ export const PLUGIN_VERSION = "2.5.0";
13
13
  /** Bumped only for an incompatible bridge API; the paths stay `/v1`. */
14
14
  export const CONTRACT_VERSION = 1;
15
15
 
@@ -365,6 +365,12 @@ export interface LocalResolveResponse {
365
365
  * advertises to the browser). Absent otherwise; never an error.
366
366
  */
367
367
  followUp?: FollowUpView;
368
+ /**
369
+ * Additive. Present (true) when the request asked for the Follow-up view and Follow-up could not
370
+ * be asked in time: "couldn't check", which is not "none". `followUp`, when also present, then
371
+ * holds only the registered owner from `follow.pr-owner`.
372
+ */
373
+ followUpUnreachable?: true;
368
374
  }
369
375
 
370
376
  /** One workspace that owns the PR, as the popover shows it. Titles, ids, status and one line: nothing else. */