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,766 @@
1
+ import { defineRpc } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+
4
+ /**
5
+ * Wire contract for the local bridge, shared by the HTTP endpoints and the
6
+ * Paseo surface. `CONTRACT.md` at the repository root is frozen; these schemas
7
+ * are its executable form, so change both or neither.
8
+ */
9
+
10
+ /** Advertised in `GET /v1/ping`. Keep in step with `package.json`. */
11
+ export const PLUGIN_NAME = "send-to-paseo";
12
+ export const PLUGIN_VERSION = "1.3.0";
13
+ /** Bumped only for an incompatible bridge API; the paths stay `/v1`. */
14
+ export const CONTRACT_VERSION = 1;
15
+
16
+ export const DEFAULT_PORT = 7788;
17
+ /** 64 KiB, per CONTRACT.md. */
18
+ export const MAX_BODY_BYTES = 64 * 1024;
19
+ /**
20
+ * Raised from 30: the extension re-pings before every resolve and send for its
21
+ * `contract`-mismatch gate, deliberately uncached, which costs 4 requests per
22
+ * completed send. `GET /v1/ping` stays counted rather than exempt — the limit is
23
+ * defence-in-depth on an endpoint that is already loopback-only and token-gated,
24
+ * so keeping the total bounded matters more than carving out one path.
25
+ */
26
+ export const RATE_LIMIT_MAX = 60;
27
+ export const RATE_LIMIT_WINDOW_MS = 10_000;
28
+ export const MAX_PROMPT_CHARS = 16_000;
29
+ /** `PR #942 · ` plus this many characters of the user's first line. */
30
+ export const MAX_TITLE_SUMMARY_CHARS = 60;
31
+
32
+ export const LABEL_PR = "send-to-paseo/pr";
33
+ export const LABEL_ORIGIN = "send-to-paseo/origin";
34
+
35
+ export const AgentDispatchSchema = z.enum(["new", "main"]);
36
+ export type AgentDispatch = z.infer<typeof AgentDispatchSchema>;
37
+
38
+ /**
39
+ * A user-declared HTTPS origin that fronts the loopback bridge.
40
+ *
41
+ * Keeping this as an origin (rather than an arbitrary URL) makes the matching
42
+ * rule unambiguous and prevents credentials, paths, queries, or fragments from
43
+ * being smuggled into what is ultimately a Host-header allowlist.
44
+ */
45
+ export function externalBridgeUrlProblem(value: string): string | null {
46
+ let parsed: URL;
47
+ try {
48
+ parsed = new URL(value.trim());
49
+ } catch {
50
+ return "Enter a complete HTTPS URL, for example https://devbox.example.ts.net.";
51
+ }
52
+ if (parsed.protocol !== "https:") return "Remote bridge URLs must use HTTPS.";
53
+ if (parsed.username !== "" || parsed.password !== "") {
54
+ return "Credentials are not allowed in the URL.";
55
+ }
56
+ if (parsed.pathname !== "/" || parsed.search !== "" || parsed.hash !== "") {
57
+ return "Enter only the origin, without a path, query, or fragment.";
58
+ }
59
+ return null;
60
+ }
61
+
62
+ export function normalizeExternalBridgeUrl(value: string): string {
63
+ const problem = externalBridgeUrlProblem(value);
64
+ if (problem !== null) throw new Error(problem);
65
+ return new URL(value.trim()).origin;
66
+ }
67
+
68
+ /** Exact Host-header authorities corresponding to one declared HTTPS origin. */
69
+ export function externalBridgeHostAuthorities(value: string | null): string[] {
70
+ if (value === null) return [];
71
+ const parsed = new URL(normalizeExternalBridgeUrl(value));
72
+ const host = parsed.host.toLowerCase();
73
+ // Some proxies preserve an explicit default port in Host even though URL.host
74
+ // canonicalizes it away. These are the same HTTPS authority, not a wildcard.
75
+ return parsed.port === "" ? [host, `${parsed.hostname.toLowerCase()}:443`] : [host];
76
+ }
77
+
78
+ export const ExternalBridgeUrlSchema = z
79
+ .string()
80
+ .trim()
81
+ .superRefine((value, context) => {
82
+ const problem = externalBridgeUrlProblem(value);
83
+ if (problem !== null) context.addIssue({ code: z.ZodIssueCode.custom, message: problem });
84
+ })
85
+ .transform((value) => new URL(value).origin);
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // HTTP request payloads
89
+ // ---------------------------------------------------------------------------
90
+
91
+ /** GitHub is the only forge in v1; the field exists so adding one is additive. */
92
+ export const ForgeSchema = z.literal("github");
93
+ export type Forge = z.infer<typeof ForgeSchema>;
94
+
95
+ /** Conservative on purpose: these become `gh` argv and a project id. */
96
+ const OwnerRepoSchema = z
97
+ .string()
98
+ .min(1)
99
+ .max(100)
100
+ .regex(/^[A-Za-z0-9._-]+$/, "must be a GitHub owner/repo segment");
101
+
102
+ export const PrRefSchema = z.object({
103
+ forge: ForgeSchema,
104
+ owner: OwnerRepoSchema,
105
+ repo: OwnerRepoSchema,
106
+ number: z.number().int().positive().max(10_000_000),
107
+ });
108
+ export type PrRef = z.infer<typeof PrRefSchema>;
109
+
110
+ export const ResolveRequestSchema = PrRefSchema.extend({
111
+ /** Sibling PRs in the Graphite stack, excluding this one. Best-effort. */
112
+ stackPrNumbers: z.array(z.number().int().positive().max(10_000_000)).max(64).optional(),
113
+ });
114
+ export type ResolveRequest = z.infer<typeof ResolveRequestSchema>;
115
+
116
+ export const SendTargetSchema = z.discriminatedUnion("kind", [
117
+ z.object({
118
+ kind: z.literal("existing"),
119
+ workspaceId: z.string().min(1).max(400),
120
+ /** Optional additional-machine route. Missing (and `local`) means this machine. */
121
+ routeId: z.string().min(1).max(200).optional(),
122
+ }),
123
+ z.object({ kind: z.literal("create"), routeId: z.string().min(1).max(200).optional() }),
124
+ ]);
125
+ export type SendTarget = z.infer<typeof SendTargetSchema>;
126
+
127
+ export const SendRequestSchema = PrRefSchema.extend({
128
+ /**
129
+ * Length is checked after trimming so the 400 carries a useful sentence
130
+ * rather than a raw Zod path.
131
+ */
132
+ prompt: z.string(),
133
+ target: SendTargetSchema,
134
+ provider: z.string().min(1).max(200).optional(),
135
+ /**
136
+ * Permission mode for the new agent, e.g. `auto` or `bypassPermissions`.
137
+ * Bounded exactly like `provider`. Mode ids are **per provider**, so this is
138
+ * only meaningful together with the provider the send resolves to; the bridge
139
+ * validates it against that provider's advertised modes and falls back rather
140
+ * than failing the send.
141
+ */
142
+ modeId: z.string().min(1).max(200).optional(),
143
+ pageUrl: z.string().max(2000).optional(),
144
+ });
145
+ export type SendRequest = z.infer<typeof SendRequestSchema>;
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // HTTP response payloads
149
+ // ---------------------------------------------------------------------------
150
+
151
+ export interface ErrorBody {
152
+ error: { code: string; message: string; hint?: string };
153
+ }
154
+
155
+ /** Every documented error code in CONTRACT.md, with its HTTP status. */
156
+ export const ERROR_STATUS = {
157
+ unauthorized: 401,
158
+ forbidden_origin: 403,
159
+ forbidden_host: 403,
160
+ bad_request: 400,
161
+ payload_too_large: 413,
162
+ rate_limited: 429,
163
+ project_not_found: 404,
164
+ pr_not_found: 404,
165
+ forge_unauthenticated: 502,
166
+ workspace_create_failed: 502,
167
+ agent_create_failed: 502,
168
+ daemon_unreachable: 503,
169
+ internal: 500,
170
+ } as const;
171
+
172
+ export type ErrorCode = keyof typeof ERROR_STATUS;
173
+
174
+ /**
175
+ * A failure the bridge is willing to describe to the caller. Anything else
176
+ * becomes `internal` with a generic message, so daemon internals and paths
177
+ * never leak to a browser extension.
178
+ */
179
+ export class BridgeError extends Error {
180
+ readonly code: ErrorCode;
181
+ readonly status: number;
182
+ readonly hint?: string;
183
+
184
+ constructor(code: ErrorCode, message: string, hint?: string) {
185
+ super(message);
186
+ this.name = "BridgeError";
187
+ this.code = code;
188
+ this.status = ERROR_STATUS[code];
189
+ if (hint !== undefined) this.hint = hint;
190
+ }
191
+
192
+ toBody(): ErrorBody {
193
+ return {
194
+ error: {
195
+ code: this.code,
196
+ message: this.message,
197
+ ...(this.hint === undefined ? {} : { hint: this.hint }),
198
+ },
199
+ };
200
+ }
201
+ }
202
+
203
+ export interface PingResponse {
204
+ ok: true;
205
+ name: string;
206
+ version: string;
207
+ contract: number;
208
+ daemon: { reachable: boolean; version: string | null; serverId: string | null };
209
+ /**
210
+ * The machine this bridge runs on. Additive optional field (CONTRACT.md
211
+ * "Additive fields"), so an older extension ignores it.
212
+ *
213
+ * `name` is `os.hostname()`, or `""` where the host has none. It exists so an
214
+ * extension paired with several Paseo machines can label them by name instead
215
+ * of by the interchangeable `127.0.0.1:<port>` each loopback tunnel presents.
216
+ */
217
+ machine: { name: string };
218
+ /** True when *this* request carried a valid bearer token. */
219
+ paired: boolean;
220
+ /** Populated only for an authenticated ping; `[]` otherwise. */
221
+ providers: ProviderOption[];
222
+ /** Same rule as `providers`: authenticated only. Flat, provider-tagged. */
223
+ modes: ModeOption[];
224
+ }
225
+
226
+ export interface PrPayload {
227
+ number: number;
228
+ title: string;
229
+ headBranch: string;
230
+ baseBranch: string;
231
+ state: string;
232
+ url: string;
233
+ }
234
+
235
+ export interface ProjectPayload {
236
+ projectId: string;
237
+ name: string;
238
+ path: string;
239
+ }
240
+
241
+ export type CandidateReason = "exact" | "stack" | "project" | "create";
242
+
243
+ /**
244
+ * State of the stack pull request a rank-2 candidate's branch belongs to.
245
+ *
246
+ * Three values, not GitHub's uppercase vocabulary, and `merged` is distinct
247
+ * from `closed` because the two mean different things to a user looking at a
248
+ * workspace: merged is history the stack has moved past, closed is work that
249
+ * was abandoned.
250
+ */
251
+ export type StackPrState = "open" | "merged" | "closed";
252
+
253
+ export interface ExistingCandidate {
254
+ kind: "existing";
255
+ workspaceId: string;
256
+ label: string;
257
+ branch: string | null;
258
+ cwd: string;
259
+ isolation: string;
260
+ rank: 1 | 2 | 3;
261
+ reason: "exact" | "stack" | "project";
262
+ agentCount: number;
263
+ /**
264
+ * Present only on `reason: "stack"`, and only when the branch actually has a
265
+ * pull request. A branch proved to be in the stack by local git ancestry may
266
+ * have none at all, and inventing a number there would be a lie.
267
+ */
268
+ stackPrNumber?: number;
269
+ /**
270
+ * State of the stack PR whose head branch this workspace is on. Present only
271
+ * alongside `stackPrNumber`, and omitted when it is `open`, which is the case
272
+ * an older extension already assumed. Additive field, so it does not bump
273
+ * `contract`.
274
+ */
275
+ stackPrState?: StackPrState;
276
+ /**
277
+ * Root agent the bridge would reuse when `agentDispatch` is `main`.
278
+ * Additive: older extensions simply omit the preview and the send still works.
279
+ */
280
+ mainAgent?: {
281
+ agentId: string;
282
+ title: string;
283
+ status: "error" | "initializing" | "idle" | "running" | "closed";
284
+ };
285
+ }
286
+
287
+ export interface CreateCandidate {
288
+ kind: "create";
289
+ label: string;
290
+ branch: string;
291
+ rank: 4;
292
+ reason: "create";
293
+ }
294
+
295
+ export type Candidate = ExistingCandidate | CreateCandidate;
296
+
297
+ export interface ProviderOption {
298
+ id: string;
299
+ label: string;
300
+ isDefault: boolean;
301
+ }
302
+
303
+ /**
304
+ * One selectable permission mode, flattened across providers exactly like
305
+ * `providers[]`.
306
+ *
307
+ * Mode ids are **per provider** — `claude` has `plan`/`default`/`acceptEdits`/
308
+ * `auto`/`bypassPermissions`, `codex` has `auto`/`auto-review`/`full-access` —
309
+ * so every entry carries the provider it belongs to and a consumer must filter
310
+ * by the provider it is actually going to send.
311
+ */
312
+ export interface ModeOption {
313
+ /** Bare provider id (`claude`), not the `provider/model` pair. */
314
+ provider: string;
315
+ id: string;
316
+ label: string;
317
+ /** True for this provider's own default mode, not for the whole list. */
318
+ isDefault: boolean;
319
+ /**
320
+ * The mode runs without asking for permission (Claude's "Bypass", Codex's
321
+ * "Full Access"). Present so a UI can mark it; deliberately NOT a reason to
322
+ * hide it.
323
+ */
324
+ isUnattended?: boolean;
325
+ /** Paseo's own visual tier: `safe`/`moderate`/`planning`/`dangerous`. */
326
+ colorTier?: string;
327
+ }
328
+
329
+ export interface LocalResolveResponse {
330
+ pr: PrPayload;
331
+ project: ProjectPayload;
332
+ candidates: Candidate[];
333
+ defaultCandidateIndex: number;
334
+ providers: ProviderOption[];
335
+ /** Every mode of every ready provider, tagged with its provider. */
336
+ modes: ModeOption[];
337
+ /**
338
+ * The mode a send would actually use right now for the provider flagged
339
+ * `isDefault`, after the whole resolution chain (profile -> plugin setting ->
340
+ * provider default). Null when nothing resolves and the field would be
341
+ * omitted from `agents.create` entirely.
342
+ */
343
+ resolvedModeId: string | null;
344
+ /**
345
+ * Whether this machine creates a fresh agent or reuses its workspace root agent.
346
+ * Additive: absent means the older `new` behavior.
347
+ */
348
+ agentDispatch?: AgentDispatch;
349
+ }
350
+
351
+ /** One Paseo machine reached through the primary machine's bridge. */
352
+ export interface ResolveRoute {
353
+ routeId: string;
354
+ routeLabel: string;
355
+ bridgeAuthority: string;
356
+ resolved: LocalResolveResponse | null;
357
+ error: ErrorBody["error"] | null;
358
+ }
359
+
360
+ export interface ResolveResponse extends LocalResolveResponse {
361
+ /**
362
+ * Additive router result. Older extensions ignore this and keep using the
363
+ * top-level local answer; newer ones show every route as a separate machine.
364
+ */
365
+ routes?: ResolveRoute[];
366
+ }
367
+
368
+ export interface SendResponse {
369
+ ok: true;
370
+ agentId: string;
371
+ workspaceId: string;
372
+ workspaceCreated: boolean;
373
+ workspaceLabel: string;
374
+ /**
375
+ * The branch actually checked out, which is not always `pr.headBranch`: when a
376
+ * local branch of that name already exists, Paseo's `checkout-pr` creates a
377
+ * uniquely suffixed local branch tracking `origin/<pr.headBranch>`.
378
+ */
379
+ branch: string | null;
380
+ deepLink: string;
381
+ title: string;
382
+ /** Additive. True when this send created an agent; false when it messaged an existing one. */
383
+ agentCreated?: boolean;
384
+ /** Additive. `main` is returned only when an existing main agent was messaged. */
385
+ dispatch?: AgentDispatch;
386
+ /** Always present. True only under `SEND_TO_PASEO_DRY_RUN=1`. */
387
+ dryRun: boolean;
388
+ }
389
+
390
+ // ---------------------------------------------------------------------------
391
+ // Surface RPC contracts
392
+ // ---------------------------------------------------------------------------
393
+
394
+ export const RecentSendSchema = z.object({
395
+ id: z.string(),
396
+ at: z.string(),
397
+ prLabel: z.string(),
398
+ prUrl: z.string(),
399
+ workspaceLabel: z.string(),
400
+ branch: z.string().nullable(),
401
+ agentId: z.string().nullable(),
402
+ deepLink: z.string().nullable(),
403
+ title: z.string(),
404
+ provider: z.string(),
405
+ /**
406
+ * Defaulted rather than required: history rows written before modes existed
407
+ * must keep validating, or `load()` would discard the file — and with it the
408
+ * user's pairing token.
409
+ */
410
+ modeId: z.string().nullable().default(null),
411
+ workspaceCreated: z.boolean(),
412
+ dryRun: z.boolean(),
413
+ outcome: z.enum(["ok", "failed"]),
414
+ error: z.string().nullable(),
415
+ });
416
+ export type RecentSend = z.infer<typeof RecentSendSchema>;
417
+
418
+ export const BridgeStatusSchema = z.object({
419
+ state: z.enum(["starting", "running", "failed", "stopped"]),
420
+ /** The port actually bound, or the configured port when not running. */
421
+ port: z.number(),
422
+ configuredPort: z.number(),
423
+ error: z.string().nullable(),
424
+ startedAt: z.string().nullable(),
425
+ lastRequestAt: z.string().nullable(),
426
+ requestCount: z.number(),
427
+ paired: z.boolean(),
428
+ dryRun: z.boolean(),
429
+ /** Never the token itself, so the surface can render before a reveal. */
430
+ tokenPreview: z.string(),
431
+ defaultProvider: z.string().nullable(),
432
+ /** Paseo agent profile the plugin follows, or null for "no profile". */
433
+ defaultProfileId: z.string().nullable(),
434
+ /** Explicit permission-mode override, or null to follow the chain. */
435
+ defaultModeId: z.string().nullable(),
436
+ agentDispatch: AgentDispatchSchema,
437
+ /** Explicit HTTPS origin allowed to front this loopback-only bridge. */
438
+ externalBridgeUrl: ExternalBridgeUrlSchema.nullable(),
439
+ daemon: z.object({
440
+ reachable: z.boolean(),
441
+ version: z.string().nullable(),
442
+ serverId: z.string().nullable(),
443
+ }),
444
+ });
445
+ export type BridgeStatus = z.infer<typeof BridgeStatusSchema>;
446
+
447
+ export const AdditionalMachineSchema = z.object({
448
+ id: z.string(),
449
+ /** Paseo daemon identity. Null only for a route imported before v1.2.0 and not yet pinged. */
450
+ serverId: z.string().nullable(),
451
+ label: z.string(),
452
+ bridgeUrl: ExternalBridgeUrlSchema,
453
+ enabled: z.boolean(),
454
+ machineName: z.string(),
455
+ /** Preview only. The actual token never leaves the server except inside a connection code. */
456
+ tokenPreview: z.string(),
457
+ });
458
+ export type AdditionalMachine = z.infer<typeof AdditionalMachineSchema>;
459
+
460
+ export const ProviderOptionSchema = z.object({
461
+ id: z.string(),
462
+ label: z.string(),
463
+ isDefault: z.boolean(),
464
+ });
465
+
466
+ export const ModeOptionSchema = z.object({
467
+ provider: z.string(),
468
+ id: z.string(),
469
+ label: z.string(),
470
+ isDefault: z.boolean(),
471
+ isUnattended: z.boolean().optional(),
472
+ colorTier: z.string().optional(),
473
+ });
474
+
475
+ /**
476
+ * One of the user's saved Paseo agent profiles (`daemon.agentProfiles`).
477
+ *
478
+ * There is no way to reference a profile by id at agent-create time — applying
479
+ * one is a field-by-field copy — so the plugin stores the id and re-reads the
480
+ * fields on every send. Change the profile in Paseo and the next send follows.
481
+ */
482
+ export const AgentProfileOptionSchema = z.object({
483
+ id: z.string(),
484
+ name: z.string(),
485
+ /** Bare provider id (`claude`). */
486
+ provider: z.string(),
487
+ model: z.string().nullable(),
488
+ modeId: z.string().nullable(),
489
+ thinkingOptionId: z.string().nullable(),
490
+ });
491
+ export type AgentProfileOption = z.infer<typeof AgentProfileOptionSchema>;
492
+
493
+ /**
494
+ * One external command the plugin uses. Surfaced so the most discoverable place
495
+ * in the product — the plugin's own settings screen — can answer "why is there
496
+ * no PR title?" without anyone reading a log.
497
+ */
498
+ export const DependencyReportSchema = z.object({
499
+ name: z.string(),
500
+ required: z.boolean(),
501
+ state: z.enum(["ok", "degraded", "missing"]),
502
+ path: z.string().nullable(),
503
+ version: z.string().nullable(),
504
+ detail: z.string(),
505
+ hint: z.string(),
506
+ });
507
+ export type DependencyReportPayload = z.infer<typeof DependencyReportSchema>;
508
+
509
+ const SurfaceTargetSchema = z.object({
510
+ /** Exact host owning this surface action; handlers reject a mismatched installation. */
511
+ serverId: z.string().min(1).max(200),
512
+ });
513
+
514
+ export const getStatus = defineRpc({
515
+ name: "send-to-paseo.status",
516
+ input: SurfaceTargetSchema,
517
+ output: z.object({
518
+ status: BridgeStatusSchema,
519
+ providers: z.array(ProviderOptionSchema),
520
+ providersError: z.string().nullable(),
521
+ modes: z.array(ModeOptionSchema),
522
+ profiles: z.array(AgentProfileOptionSchema),
523
+ profilesError: z.string().nullable(),
524
+ recentSends: z.array(RecentSendSchema),
525
+ dependencies: z.array(DependencyReportSchema),
526
+ additionalMachines: z.array(AdditionalMachineSchema),
527
+ }),
528
+ });
529
+
530
+ export const revealToken = defineRpc({
531
+ name: "send-to-paseo.token.reveal",
532
+ input: SurfaceTargetSchema,
533
+ output: z.object({ token: z.string() }),
534
+ });
535
+
536
+ export const regenerateToken = defineRpc({
537
+ name: "send-to-paseo.token.regenerate",
538
+ input: SurfaceTargetSchema,
539
+ output: z.object({ token: z.string() }),
540
+ });
541
+
542
+ export const updateConfig = defineRpc({
543
+ name: "send-to-paseo.config.update",
544
+ input: SurfaceTargetSchema.extend({
545
+ port: z.number().int().min(1).max(65535).optional(),
546
+ /** Null clears the override and falls back to the daemon's own default. */
547
+ defaultProvider: z.string().max(200).nullable().optional(),
548
+ /** Null stops following a profile. */
549
+ defaultProfileId: z.string().max(200).nullable().optional(),
550
+ /** Null clears the override and falls back to the mode chain. */
551
+ defaultModeId: z.string().max(200).nullable().optional(),
552
+ agentDispatch: AgentDispatchSchema.optional(),
553
+ /** Null removes the declared reverse-proxy origin. */
554
+ externalBridgeUrl: ExternalBridgeUrlSchema.nullable().optional(),
555
+ }),
556
+ output: z.object({ status: BridgeStatusSchema, error: z.string().nullable() }),
557
+ });
558
+
559
+ export const clearRecentSends = defineRpc({
560
+ name: "send-to-paseo.recent.clear",
561
+ input: SurfaceTargetSchema,
562
+ output: z.object({ removed: z.number() }),
563
+ });
564
+
565
+ export const addAdditionalMachine = defineRpc({
566
+ name: "send-to-paseo.machine.add",
567
+ input: SurfaceTargetSchema.extend({ connectionCode: z.string().trim().min(1).max(4096) }),
568
+ output: z.object({ machine: AdditionalMachineSchema }),
569
+ });
570
+
571
+ export const updateAdditionalMachine = defineRpc({
572
+ name: "send-to-paseo.machine.update",
573
+ input: SurfaceTargetSchema.extend({
574
+ id: z.string().min(1).max(200),
575
+ label: z.string().max(120).optional(),
576
+ enabled: z.boolean().optional(),
577
+ }),
578
+ output: z.object({ machine: AdditionalMachineSchema }),
579
+ });
580
+
581
+ export const removeAdditionalMachine = defineRpc({
582
+ name: "send-to-paseo.machine.remove",
583
+ input: SurfaceTargetSchema.extend({ id: z.string().min(1).max(200) }),
584
+ output: z.object({ removed: z.boolean() }),
585
+ });
586
+
587
+ export const testAdditionalMachine = defineRpc({
588
+ name: "send-to-paseo.machine.test",
589
+ input: SurfaceTargetSchema.extend({ id: z.string().min(1).max(200) }),
590
+ output: z.object({
591
+ ok: z.boolean(),
592
+ machineName: z.string().nullable(),
593
+ detail: z.string(),
594
+ }),
595
+ });
596
+
597
+ const ConnectionCodeResultSchema = z.object({
598
+ ready: z.boolean(),
599
+ code: z.string().nullable(),
600
+ bridgeUrl: ExternalBridgeUrlSchema.nullable(),
601
+ command: z.string(),
602
+ error: z.string().nullable(),
603
+ });
604
+
605
+ export const getConnectionCode = defineRpc({
606
+ name: "send-to-paseo.connection-code.get",
607
+ input: SurfaceTargetSchema,
608
+ output: ConnectionCodeResultSchema,
609
+ });
610
+
611
+ export const enablePrivateAccess = defineRpc({
612
+ name: "send-to-paseo.private-access.enable",
613
+ input: SurfaceTargetSchema,
614
+ output: ConnectionCodeResultSchema,
615
+ });
616
+
617
+ // ---------------------------------------------------------------------------
618
+ // Pure formatting shared by the bridge and the surface
619
+ // ---------------------------------------------------------------------------
620
+
621
+ /**
622
+ * The `paseo://` link that opens an agent in the Paseo app.
623
+ *
624
+ * A local reimplementation of `buildAgentDeepLink` from
625
+ * `@getpaseo/protocol/agent-deep-link`, transcribed from
626
+ * `packages/protocol/src/agent-deep-link.ts` in Paseo 0.7.0 and rechecked for
627
+ * the v0.8 migration (verified against the published package implementation, which is
628
+ * byte-identical in behaviour).
629
+ *
630
+ * It is copied rather than imported because `paseo plugin add` compiles a plugin
631
+ * with *no installed packages*: the only specifiers the host makes resolvable are
632
+ * its own SDK (`@getpaseo/plugin`, `@getpaseo/plugin/server`,
633
+ * `@getpaseo/plugin/client`, `@getpaseo/plugin/client/react-native`), `zod`, `react`, `react/jsx-runtime`,
634
+ * `react-native` and `@tanstack/react-query`. `@getpaseo/protocol` is not one of
635
+ * them, so a value import from it fails the install with
636
+ * `Could not resolve "@getpaseo/protocol/agent-deep-link"`. See
637
+ * `plugin/VERIFICATION.md`.
638
+ *
639
+ * The upstream format is `paseo:/` + `/h/<serverId>/agent/<agentId>`, i.e.
640
+ * `paseo://h/<serverId>/agent/<agentId>`, with each segment
641
+ * `encodeURIComponent`-escaped and trimmed first. Re-check this against the
642
+ * source above when bumping Paseo; a wrong format produces a link that opens
643
+ * nothing rather than an error.
644
+ */
645
+ export function buildAgentDeepLink(target: { serverId: string; agentId: string }): string {
646
+ const serverId = target.serverId.trim();
647
+ const agentId = target.agentId.trim();
648
+ if (!serverId || !agentId) {
649
+ throw new Error("Agent deep links require a server ID and agent ID.");
650
+ }
651
+ return `paseo://h/${encodeURIComponent(serverId)}/agent/${encodeURIComponent(agentId)}`;
652
+ }
653
+
654
+ /** `github:acmegizmos/gizmo-poc#942`, the value of the `send-to-paseo/pr` label. */
655
+ export function prLabelValue(ref: PrRef): string {
656
+ return `${ref.forge}:${ref.owner}/${ref.repo}#${ref.number}`;
657
+ }
658
+
659
+ /**
660
+ * Length of a prompt as CONTRACT.md measures it: Unicode code points, not
661
+ * UTF-16 code units, so an emoji or an astral-plane character counts once.
662
+ */
663
+ export function promptLength(prompt: string): number {
664
+ return [...prompt].length;
665
+ }
666
+
667
+ /** First line of the user's message, capped for the agent list. */
668
+ export function summarizePrompt(prompt: string): string {
669
+ const firstLine = prompt.split("\n", 1)[0]?.trim() ?? "";
670
+ if (firstLine.length <= MAX_TITLE_SUMMARY_CHARS) return firstLine;
671
+ return `${firstLine.slice(0, MAX_TITLE_SUMMARY_CHARS - 1)}…`;
672
+ }
673
+
674
+ /** `PR #942 · Fix merge conflicts`, per CONTRACT.md "Agent metadata". */
675
+ export function buildAgentTitle(number: number, prompt: string): string {
676
+ const summary = summarizePrompt(prompt);
677
+ return summary === "" ? `PR #${number}` : `PR #${number} · ${summary}`;
678
+ }
679
+
680
+ /**
681
+ * The context header prepended to the user's message, byte-for-byte as
682
+ * CONTRACT.md "Prompt composition" specifies. `pageUrl` is the one documented
683
+ * enrichment: CONTRACT.md says it is "used only to enrich the agent's opening
684
+ * prompt", so it appears as a trailing `Page:` line and is otherwise absent.
685
+ */
686
+ export function composePrompt(input: {
687
+ ref: PrRef;
688
+ pr: PrPayload;
689
+ prompt: string;
690
+ pageUrl?: string;
691
+ /** Branch the target workspace is actually on, when known. */
692
+ workspaceBranch?: string | null;
693
+ /**
694
+ * State of the stack pull request that owns `workspaceBranch`, when the
695
+ * bridge could establish it. Only `merged` and `closed` change the wording;
696
+ * see below for why they have to.
697
+ */
698
+ workspaceBranchState?: StackPrState | null;
699
+ /**
700
+ * Set only when `gh` could not describe the PR. The `Title:` and `Branch:`
701
+ * lines are then omitted rather than filled with placeholders — telling an
702
+ * agent it is on a branch nobody verified is how commits land in the wrong
703
+ * place — and this sentence explains the gap instead. Prompt text is
704
+ * behaviour, not wire shape, so this does not move `contract`.
705
+ */
706
+ prMetadataNote?: string;
707
+ }): string {
708
+ const { ref, pr } = input;
709
+ const note = input.prMetadataNote ?? "";
710
+ const degraded = note !== "";
711
+ const lines = [`[Sent from Graphite — ${ref.forge}/${ref.owner}/${ref.repo} PR #${ref.number}]`];
712
+ if (!degraded) {
713
+ lines.push(`Title: ${pr.title}`, `Branch: ${pr.headBranch} -> ${pr.baseBranch}`);
714
+ }
715
+ lines.push(`PR: ${pr.url}`);
716
+ if (input.pageUrl !== undefined && input.pageUrl.trim() !== "") {
717
+ lines.push(`Page: ${input.pageUrl.trim()}`);
718
+ }
719
+ if (degraded) {
720
+ const workspaceBranch = input.workspaceBranch;
721
+ if (typeof workspaceBranch === "string" && workspaceBranch !== "") {
722
+ // Stated as fact, with no claim about whether it is this PR's branch —
723
+ // without gh, nothing knows what this PR's branch is.
724
+ lines.push(`Workspace branch: ${workspaceBranch}`);
725
+ }
726
+ lines.push(note);
727
+ return `${lines.join("\n")}\n\n${input.prompt}`;
728
+ }
729
+ // One workspace per stack is a normal way to work, so an agent is often
730
+ // started in a worktree checked out to a *sibling* branch. Saying nothing
731
+ // would leave the agent believing it is on the PR branch — and committing
732
+ // there. Tell it the truth instead of guessing what it should do about it.
733
+ const workspaceBranch = input.workspaceBranch;
734
+ if (
735
+ typeof workspaceBranch === "string" &&
736
+ workspaceBranch !== "" &&
737
+ workspaceBranch !== pr.headBranch
738
+ ) {
739
+ // "a different branch of the same stack" reads as a live sibling, which is
740
+ // wrong — and misleading in a way that matters — once the bridge can offer
741
+ // a workspace sitting on a branch whose pull request is already merged or
742
+ // closed. An agent told it is on a live sibling assumes the branch is
743
+ // current; a merged branch is behind by construction, because the stack has
744
+ // been restacked past it. The advice ("check out the PR's branch") is the
745
+ // same in all three cases; only the description of where it is standing
746
+ // changes.
747
+ const state = input.workspaceBranchState ?? null;
748
+ const own =
749
+ state === "merged"
750
+ ? "; its own pull request is already merged"
751
+ : state === "closed"
752
+ ? "; its own pull request was closed without merging"
753
+ : "";
754
+ const where =
755
+ state === "merged"
756
+ ? "this worktree is on a branch of this stack whose pull request has already been merged, so it may be behind the rest of the stack"
757
+ : state === "closed"
758
+ ? "this worktree is on a branch of this stack whose pull request was closed without merging, so it may be behind the rest of the stack"
759
+ : "this worktree is on a different branch of the same stack";
760
+ lines.push(
761
+ `Workspace branch: ${workspaceBranch} (NOT this PR's branch${own})`,
762
+ `Note: ${where}. If your change belongs to PR #${ref.number}, check out ${pr.headBranch} first.`,
763
+ );
764
+ }
765
+ return `${lines.join("\n")}\n\n${input.prompt}`;
766
+ }