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.
package/server/send.ts ADDED
@@ -0,0 +1,463 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
3
+ import {
4
+ BridgeError,
5
+ LABEL_ORIGIN,
6
+ LABEL_PR,
7
+ MAX_PROMPT_CHARS,
8
+ buildAgentDeepLink,
9
+ buildAgentTitle,
10
+ composePrompt,
11
+ prLabelValue,
12
+ promptLength,
13
+ type PrPayload,
14
+ type PrRef,
15
+ type SendRequest,
16
+ type SendResponse,
17
+ type StackPrState,
18
+ } from "../shared/contracts";
19
+ import { requireServerId, withPaseo } from "./daemon";
20
+ import { lookupPr, type GhOutage } from "./gh";
21
+ import { readBranch, requireGit } from "./git";
22
+ import {
23
+ listProjectWorkspaces,
24
+ profileProviderId,
25
+ resolveDefaultMode,
26
+ resolveDefaultProvider,
27
+ resolveProject,
28
+ resolveSelectedProfile,
29
+ resolveStackBranches,
30
+ } from "./resolve";
31
+ import { settings } from "./settings";
32
+ import {
33
+ agentDisplayTitle,
34
+ agentProvider,
35
+ listProjectAgents,
36
+ selectMainAgent,
37
+ type ListedAgent,
38
+ } from "./main-agent";
39
+
40
+ type PaseoApi = PluginHandlerContext["paseo"];
41
+ type PaseoWorkspace = Awaited<ReturnType<PaseoApi["workspaces"]["list"]>>["entries"][number];
42
+ type PaseoWorkspaceHandle = ReturnType<PaseoApi["workspaces"]["ref"]>;
43
+ type PaseoAgentConfig = Parameters<PaseoWorkspaceHandle["agents"]["create"]>[0]["config"];
44
+
45
+ /**
46
+ * The one mutating endpoint: ensure a workspace, then either start a new agent
47
+ * or dispatch to the workspace's best root agent, according to plugin settings.
48
+ */
49
+
50
+ /** A freshly checked-out worktree is normally ready on return; this is a guard. */
51
+ const WORKSPACE_READY_TIMEOUT_MS = 60_000;
52
+ const WORKSPACE_POLL_MS = 750;
53
+
54
+ /** `SEND_TO_PASEO_DRY_RUN=1` validates and resolves but creates nothing. */
55
+ export function isDryRun(): boolean {
56
+ return process.env.SEND_TO_PASEO_DRY_RUN === "1";
57
+ }
58
+
59
+ function syntheticId(prefix: string): string {
60
+ return `${prefix}_dryrun_${randomBytes(6).toString("hex")}`;
61
+ }
62
+
63
+ /**
64
+ * CONTRACT.md: required, 1..16000 Unicode code points after trim.
65
+ *
66
+ * Code points, not UTF-16 code units, so an emoji counts once. The 64 KiB byte
67
+ * cap on the body is independent and is applied earlier in `server/bridge`, so a
68
+ * prompt inside this limit that is too large as UTF-8 gets `payload_too_large`
69
+ * rather than `bad_request`.
70
+ */
71
+ function normalizePrompt(raw: string): string {
72
+ const prompt = raw.trim();
73
+ const length = promptLength(prompt);
74
+ if (length === 0) {
75
+ throw new BridgeError("bad_request", "A message is required.");
76
+ }
77
+ if (length > MAX_PROMPT_CHARS) {
78
+ throw new BridgeError(
79
+ "bad_request",
80
+ `A message may be at most ${MAX_PROMPT_CHARS} characters; this one is ${length}.`,
81
+ );
82
+ }
83
+ return prompt;
84
+ }
85
+
86
+ /**
87
+ * The one line an agent is told about a degraded lookup. The agent is the party
88
+ * that will otherwise wonder where the PR title went, and it can fetch the
89
+ * details itself if it needs them.
90
+ */
91
+ function promptNote(outage: GhOutage): string {
92
+ return (
93
+ `Note: the pull request title and branch names are missing from this header because ` +
94
+ `${outage.short}. Read them from the PR URL above if you need them.`
95
+ );
96
+ }
97
+
98
+ /**
99
+ * The state of the stack pull request that owns `branch`, or null.
100
+ *
101
+ * Only asked when the target workspace is on some *other* branch than the PR's
102
+ * own, which is the only case where the prompt says anything about it at all.
103
+ * The lookup reuses the resolve path's caches, and `/v1/resolve` ran seconds
104
+ * earlier when the popover opened, so in practice this is a cache read rather
105
+ * than a `gh` round trip. Best-effort throughout: a null answer just means the
106
+ * prompt keeps its generic "a different branch of the same stack" wording,
107
+ * which is never wrong, only less specific.
108
+ */
109
+ async function stackStateOfBranch(input: {
110
+ ref: PrRef;
111
+ pr: PrPayload;
112
+ projectRoot: string;
113
+ branch: string;
114
+ outage: GhOutage | null;
115
+ }): Promise<StackPrState | null> {
116
+ if (input.outage !== null) return null;
117
+ if (input.pr.headBranch === "" || input.branch === input.pr.headBranch) return null;
118
+ try {
119
+ const stack = await resolveStackBranches({
120
+ ref: input.ref,
121
+ headBranch: input.pr.headBranch,
122
+ hints: [],
123
+ outage: null,
124
+ projectRoot: input.projectRoot,
125
+ workspaceBranches: [input.branch],
126
+ });
127
+ return stack.get(input.branch)?.state ?? null;
128
+ } catch (error) {
129
+ console.error(
130
+ "[send-to-paseo] could not determine the stack state of the target branch",
131
+ String(error),
132
+ );
133
+ return null;
134
+ }
135
+ }
136
+
137
+ function labelOf(workspace: PaseoWorkspace): string {
138
+ const slug = workspace.worktreeSlug;
139
+ if (typeof slug === "string" && slug !== "") return slug;
140
+ return workspace.name === "" ? workspace.id : workspace.name;
141
+ }
142
+
143
+ async function createWorktreeWorkspace(
144
+ paseo: PaseoApi,
145
+ projectId: string,
146
+ ref: PrRef,
147
+ pr: PrPayload,
148
+ degraded: boolean,
149
+ ): Promise<{ workspace: PaseoWorkspace; handle: PaseoWorkspaceHandle }> {
150
+ // The only genuinely fatal dependency on this path, and the only place worth
151
+ // pre-flighting it: without git there is no worktree, and the daemon's own
152
+ // error for that is several layers away from the word "git".
153
+ await requireGit();
154
+ let handle;
155
+ try {
156
+ // Exactly the shape `paseo workspace create --isolation worktree
157
+ // --mode checkout-pr --pr-number N --forge github --project <id>` sends.
158
+ handle = await paseo.workspaces.create({
159
+ // Without `gh` the title is already `PR #942`; appending it to itself
160
+ // would read "PR #942: PR #942".
161
+ title: (degraded ? `PR #${ref.number}` : `PR #${ref.number}: ${pr.title}`).slice(0, 120),
162
+ source: {
163
+ kind: "worktree",
164
+ projectId,
165
+ action: "checkout",
166
+ checkoutSource: { kind: "change_request", forge: ref.forge, number: ref.number },
167
+ },
168
+ });
169
+ } catch (error) {
170
+ throw new BridgeError(
171
+ "workspace_create_failed",
172
+ `Paseo could not create a worktree for PR #${ref.number}: ${
173
+ error instanceof Error ? error.message : String(error)
174
+ }`,
175
+ );
176
+ }
177
+
178
+ const deadline = Date.now() + WORKSPACE_READY_TIMEOUT_MS;
179
+ let snapshot = handle.current();
180
+ while (Date.now() < deadline) {
181
+ if (snapshot !== null && snapshot.workspaceDirectory !== "") {
182
+ const branch = await readBranch(snapshot.workspaceDirectory);
183
+ if (branch !== null) return { workspace: snapshot, handle };
184
+ }
185
+ await new Promise((done) => {
186
+ const timer = setTimeout(done, WORKSPACE_POLL_MS);
187
+ // A pending poll must never hold the subprocess open during teardown.
188
+ timer.unref?.();
189
+ });
190
+ snapshot = await handle.refresh().catch(() => snapshot);
191
+ }
192
+ if (snapshot !== null && snapshot.workspaceDirectory !== "") {
193
+ return { workspace: snapshot, handle };
194
+ }
195
+ throw new BridgeError(
196
+ "workspace_create_failed",
197
+ `The worktree for PR #${ref.number} was created but never became ready.`,
198
+ );
199
+ }
200
+
201
+ /** Full `POST /v1/send` behaviour. */
202
+ export async function handleSend(request: SendRequest): Promise<SendResponse> {
203
+ const ref: PrRef = {
204
+ forge: request.forge,
205
+ owner: request.owner,
206
+ repo: request.repo,
207
+ number: request.number,
208
+ };
209
+ const prompt = normalizePrompt(request.prompt);
210
+ const dryRun = isDryRun();
211
+
212
+ return withPaseo(async (paseo) => {
213
+ // All four are read-only and independent. On a cold send, `gh` and the
214
+ // daemon status are the slow inputs; starting them together avoids paying
215
+ // their latency in series after the already-prefetched resolve.
216
+ const [project, prLookup, serverId, currentSettings] = await Promise.all([
217
+ resolveProject(paseo, ref),
218
+ lookupPr(ref),
219
+ requireServerId(),
220
+ settings.read(),
221
+ ]);
222
+ // Same degradation as resolve: a missing or unauthenticated `gh` costs the
223
+ // title, the branches and the stack note in the prompt, not the send.
224
+ const { pr, outage } = prLookup;
225
+ const title = buildAgentTitle(ref.number, prompt);
226
+ const configuredDispatch = currentSettings.agentDispatch;
227
+
228
+ let workspaceId: string;
229
+ let workspaceLabel: string;
230
+ let branch: string | null;
231
+ let workspaceCreated = false;
232
+ /**
233
+ * Null only in a dry run of a `create` target, where there is no workspace
234
+ * to attach to. Agents are always created through the workspace handle so
235
+ * they join that workspace record rather than getting a fresh one for the
236
+ * same directory.
237
+ */
238
+ let handle: PaseoWorkspaceHandle | null = null;
239
+
240
+ if (request.target.kind === "existing") {
241
+ const wanted = request.target.workspaceId;
242
+ const workspaces = await listProjectWorkspaces(paseo, project.projectId);
243
+ const workspace = workspaces.find((entry) => entry.id === wanted);
244
+ if (workspace === undefined) {
245
+ throw new BridgeError(
246
+ "bad_request",
247
+ `Workspace ${wanted} is no longer available in ${project.name}.`,
248
+ "Reopen the popover to refresh the workspace list.",
249
+ );
250
+ }
251
+ workspaceId = workspace.id;
252
+ workspaceLabel = labelOf(workspace);
253
+ branch =
254
+ workspace.gitRuntime?.currentBranch ??
255
+ workspace.project?.checkout?.currentBranch ??
256
+ (await readBranch(workspace.workspaceDirectory));
257
+ handle = paseo.workspaces.ref(workspace);
258
+ } else if (dryRun) {
259
+ // Resolution and validation ran; creating the worktree is the side effect
260
+ // dry run exists to skip.
261
+ workspaceId = syntheticId("wks");
262
+ workspaceLabel = `Create worktree for PR #${ref.number}`;
263
+ // Null, not "", when gh could not tell us the head branch: the contract
264
+ // says this field is the branch or nothing, and "" is neither.
265
+ branch = pr.headBranch === "" ? null : pr.headBranch;
266
+ workspaceCreated = true;
267
+ } else {
268
+ const created = await createWorktreeWorkspace(
269
+ paseo,
270
+ project.projectId,
271
+ ref,
272
+ pr,
273
+ outage !== null,
274
+ );
275
+ workspaceId = created.workspace.id;
276
+ workspaceLabel = labelOf(created.workspace);
277
+ branch = await readBranch(created.workspace.workspaceDirectory);
278
+ workspaceCreated = true;
279
+ handle = created.handle;
280
+ console.log(
281
+ `[send-to-paseo] created worktree workspace ${workspaceId} for PR #${ref.number} on ${branch ?? "unknown branch"}`,
282
+ );
283
+ }
284
+
285
+ const composedPrompt = composePrompt({
286
+ ref,
287
+ pr,
288
+ prompt,
289
+ workspaceBranch: branch,
290
+ workspaceBranchState:
291
+ branch === null || branch === ""
292
+ ? null
293
+ : await stackStateOfBranch({
294
+ ref,
295
+ pr,
296
+ projectRoot: project.path,
297
+ branch,
298
+ outage,
299
+ }),
300
+ ...(outage === null ? {} : { prMetadataNote: promptNote(outage) }),
301
+ ...(request.pageUrl === undefined ? {} : { pageUrl: request.pageUrl }),
302
+ });
303
+
304
+ let mainAgent: ListedAgent | null = null;
305
+ if (configuredDispatch === "main" && request.target.kind === "existing") {
306
+ try {
307
+ mainAgent = selectMainAgent(
308
+ await listProjectAgents(paseo, project.projectId),
309
+ workspaceId,
310
+ );
311
+ } catch (error) {
312
+ throw new BridgeError(
313
+ "agent_create_failed",
314
+ `Paseo could not find the main agent in ${workspaceLabel}: ${
315
+ error instanceof Error ? error.message : String(error)
316
+ }`,
317
+ );
318
+ }
319
+ }
320
+
321
+ let agentId: string;
322
+ let responseTitle = title;
323
+ let recordedProvider: string;
324
+ let recordedModeId: string | null;
325
+ let agentCreated = true;
326
+ let dispatch: "new" | "main" = "new";
327
+
328
+ if (mainAgent !== null) {
329
+ agentId = mainAgent.id;
330
+ responseTitle = agentDisplayTitle(mainAgent);
331
+ recordedProvider = agentProvider(mainAgent);
332
+ recordedModeId = mainAgent.currentModeId ?? null;
333
+ agentCreated = false;
334
+ dispatch = "main";
335
+ if (!dryRun) {
336
+ try {
337
+ // The public 0.9 SDK forwards this supported daemon option but omits
338
+ // it from PaseoAgentSendOptions. Steering preserves a running main
339
+ // agent's current turn instead of implicitly interrupting it.
340
+ await paseo.agents.ref(mainAgent).send(
341
+ composedPrompt,
342
+ { activeTurnBehavior: "steer" } as Parameters<
343
+ ReturnType<PaseoApi["agents"]["ref"]>["send"]
344
+ >[1] & { activeTurnBehavior: "steer" },
345
+ );
346
+ } catch (error) {
347
+ throw new BridgeError(
348
+ "agent_create_failed",
349
+ `Paseo refused to message the main agent: ${
350
+ error instanceof Error ? error.message : String(error)
351
+ }`,
352
+ );
353
+ }
354
+ }
355
+ } else {
356
+ // Provider/profile/mode resolution is needed only when an agent will be
357
+ // created. Reuse mode avoids those daemon round trips entirely.
358
+ const profile = await resolveSelectedProfile(paseo);
359
+ const provider = request.provider ?? (await resolveDefaultProvider(paseo, profile));
360
+ const modeId = await resolveDefaultMode(paseo, provider, {
361
+ requested: request.modeId,
362
+ profile,
363
+ });
364
+ const thinkingOptionId =
365
+ profileProviderId(profile) === provider ? (profile?.thinkingOptionId ?? null) : null;
366
+ const agentConfig: PaseoAgentConfig = {
367
+ provider,
368
+ ...(modeId === undefined ? {} : { modeId }),
369
+ ...(thinkingOptionId === null ? {} : { thinkingOptionId }),
370
+ };
371
+ recordedProvider = provider;
372
+ recordedModeId = modeId ?? null;
373
+
374
+ if (dryRun) {
375
+ agentId = syntheticId("agt");
376
+ } else if (handle === null) {
377
+ throw new BridgeError("internal", "No workspace was resolved for this send.");
378
+ } else {
379
+ try {
380
+ const agent = await handle.agents.create({
381
+ config: agentConfig,
382
+ title,
383
+ prompt: composedPrompt,
384
+ labels: {
385
+ [LABEL_PR]: prLabelValue(ref),
386
+ [LABEL_ORIGIN]: "graphite",
387
+ },
388
+ });
389
+ agentId = agent.id;
390
+ } catch (error) {
391
+ throw new BridgeError(
392
+ "agent_create_failed",
393
+ `Paseo refused to start the agent: ${error instanceof Error ? error.message : String(error)}`,
394
+ );
395
+ }
396
+ }
397
+ }
398
+
399
+ const deepLink = buildAgentDeepLink({ serverId, agentId });
400
+ // Never log the prompt: it is the user's message body.
401
+ console.log(
402
+ `[send-to-paseo] ${dryRun ? "dry-run " : ""}sent PR #${ref.number} to ${workspaceLabel} (${dispatch} agent ${agentId}, provider ${recordedProvider}, mode ${recordedModeId ?? "paseo default"})`,
403
+ );
404
+
405
+ await settings
406
+ .recordSend({
407
+ prLabel: `${ref.owner}/${ref.repo}#${ref.number}`,
408
+ prUrl: pr.url,
409
+ workspaceLabel,
410
+ branch,
411
+ agentId,
412
+ deepLink,
413
+ title: responseTitle,
414
+ provider: recordedProvider,
415
+ modeId: recordedModeId,
416
+ workspaceCreated,
417
+ dryRun,
418
+ outcome: "ok",
419
+ error: null,
420
+ })
421
+ .catch((error: unknown) => {
422
+ console.error("[send-to-paseo] could not record the send", String(error));
423
+ });
424
+
425
+ return {
426
+ ok: true,
427
+ agentId,
428
+ workspaceId,
429
+ workspaceCreated,
430
+ workspaceLabel,
431
+ branch,
432
+ deepLink,
433
+ title: responseTitle,
434
+ agentCreated,
435
+ dispatch,
436
+ dryRun,
437
+ };
438
+ });
439
+ }
440
+
441
+ /** Records a failed send so the surface can show what went wrong. */
442
+ export async function recordFailedSend(
443
+ request: SendRequest,
444
+ error: BridgeError | Error,
445
+ ): Promise<void> {
446
+ await settings
447
+ .recordSend({
448
+ prLabel: `${request.owner}/${request.repo}#${request.number}`,
449
+ prUrl: `https://github.com/${request.owner}/${request.repo}/pull/${request.number}`,
450
+ workspaceLabel: request.target.kind === "create" ? "new worktree" : request.target.workspaceId,
451
+ branch: null,
452
+ agentId: null,
453
+ deepLink: null,
454
+ title: buildAgentTitle(request.number, request.prompt.trim()),
455
+ provider: request.provider ?? "default",
456
+ modeId: request.modeId ?? null,
457
+ workspaceCreated: false,
458
+ dryRun: isDryRun(),
459
+ outcome: "failed",
460
+ error: error.message,
461
+ })
462
+ .catch(() => undefined);
463
+ }