@microvac/adapter-pi-local 0.0.0-stage → 0.1.0-rc.14

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.
Files changed (87) hide show
  1. package/LICENSE +22 -0
  2. package/dist/cli/format-event.d.ts +2 -0
  3. package/dist/cli/format-event.d.ts.map +1 -0
  4. package/dist/cli/format-event.js +99 -0
  5. package/dist/cli/format-event.js.map +1 -0
  6. package/dist/cli/index.d.ts +2 -0
  7. package/dist/cli/index.d.ts.map +1 -0
  8. package/dist/cli/index.js +2 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/index.d.ts +9 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +54 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/server/execute.d.ts +3 -0
  15. package/dist/server/execute.d.ts.map +1 -0
  16. package/dist/server/execute.js +784 -0
  17. package/dist/server/execute.js.map +1 -0
  18. package/dist/server/execute.remote.test.d.ts +2 -0
  19. package/dist/server/execute.remote.test.d.ts.map +1 -0
  20. package/dist/server/execute.remote.test.js +814 -0
  21. package/dist/server/execute.remote.test.js.map +1 -0
  22. package/dist/server/index.d.ts +8 -0
  23. package/dist/server/index.d.ts.map +1 -0
  24. package/dist/server/index.js +56 -0
  25. package/dist/server/index.js.map +1 -0
  26. package/dist/server/models.d.ts +20 -0
  27. package/dist/server/models.d.ts.map +1 -0
  28. package/dist/server/models.js +162 -0
  29. package/dist/server/models.js.map +1 -0
  30. package/dist/server/models.test.d.ts +2 -0
  31. package/dist/server/models.test.d.ts.map +1 -0
  32. package/dist/server/models.test.js +48 -0
  33. package/dist/server/models.test.js.map +1 -0
  34. package/dist/server/openrouter-extension.d.ts +7 -0
  35. package/dist/server/openrouter-extension.d.ts.map +1 -0
  36. package/dist/server/openrouter-extension.js +66 -0
  37. package/dist/server/openrouter-extension.js.map +1 -0
  38. package/dist/server/openrouter-extension.test.d.ts +2 -0
  39. package/dist/server/openrouter-extension.test.d.ts.map +1 -0
  40. package/dist/server/openrouter-extension.test.js +74 -0
  41. package/dist/server/openrouter-extension.test.js.map +1 -0
  42. package/dist/server/parse.d.ts +43 -0
  43. package/dist/server/parse.d.ts.map +1 -0
  44. package/dist/server/parse.js +220 -0
  45. package/dist/server/parse.js.map +1 -0
  46. package/dist/server/parse.test.d.ts +2 -0
  47. package/dist/server/parse.test.d.ts.map +1 -0
  48. package/dist/server/parse.test.js +272 -0
  49. package/dist/server/parse.test.js.map +1 -0
  50. package/dist/server/runtime-config.d.ts +12 -0
  51. package/dist/server/runtime-config.d.ts.map +1 -0
  52. package/dist/server/runtime-config.js +142 -0
  53. package/dist/server/runtime-config.js.map +1 -0
  54. package/dist/server/runtime-config.test.d.ts +2 -0
  55. package/dist/server/runtime-config.test.d.ts.map +1 -0
  56. package/dist/server/runtime-config.test.js +216 -0
  57. package/dist/server/runtime-config.test.js.map +1 -0
  58. package/dist/server/skills.d.ts +7 -0
  59. package/dist/server/skills.d.ts.map +1 -0
  60. package/dist/server/skills.js +69 -0
  61. package/dist/server/skills.js.map +1 -0
  62. package/dist/server/stdout-compaction.d.ts +27 -0
  63. package/dist/server/stdout-compaction.d.ts.map +1 -0
  64. package/dist/server/stdout-compaction.js +107 -0
  65. package/dist/server/stdout-compaction.js.map +1 -0
  66. package/dist/server/stdout-compaction.test.d.ts +2 -0
  67. package/dist/server/stdout-compaction.test.d.ts.map +1 -0
  68. package/dist/server/stdout-compaction.test.js +333 -0
  69. package/dist/server/stdout-compaction.test.js.map +1 -0
  70. package/dist/server/test.d.ts +3 -0
  71. package/dist/server/test.d.ts.map +1 -0
  72. package/dist/server/test.js +311 -0
  73. package/dist/server/test.js.map +1 -0
  74. package/dist/ui/build-config.d.ts +3 -0
  75. package/dist/ui/build-config.d.ts.map +1 -0
  76. package/dist/ui/build-config.js +39 -0
  77. package/dist/ui/build-config.js.map +1 -0
  78. package/dist/ui/index.d.ts +3 -0
  79. package/dist/ui/index.d.ts.map +1 -0
  80. package/dist/ui/index.js +3 -0
  81. package/dist/ui/index.js.map +1 -0
  82. package/dist/ui/parse-stdout.d.ts +4 -0
  83. package/dist/ui/parse-stdout.d.ts.map +1 -0
  84. package/dist/ui/parse-stdout.js +276 -0
  85. package/dist/ui/parse-stdout.js.map +1 -0
  86. package/package.json +51 -4
  87. package/README.md +0 -3
@@ -0,0 +1,814 @@
1
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
5
+ import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
6
+ const { runChildProcess, ensureCommandResolvable, resolveCommandForLogs, prepareWorkspaceForSshExecution, restoreWorkspaceFromSshExecution, runSshCommand, syncDirectoryToSsh, startAdapterExecutionTargetPaperclipBridge, } = vi.hoisted(() => ({
7
+ runChildProcess: vi.fn(async () => ({
8
+ exitCode: 0,
9
+ signal: null,
10
+ timedOut: false,
11
+ stdout: JSON.stringify({
12
+ type: "turn_end",
13
+ message: {
14
+ role: "assistant",
15
+ content: "done",
16
+ usage: {
17
+ input: 10,
18
+ output: 20,
19
+ cacheRead: 0,
20
+ cost: { total: 0.01 },
21
+ },
22
+ },
23
+ toolResults: [],
24
+ }),
25
+ stderr: "",
26
+ pid: 123,
27
+ startedAt: new Date().toISOString(),
28
+ })),
29
+ ensureCommandResolvable: vi.fn(async () => undefined),
30
+ resolveCommandForLogs: vi.fn(async () => "ssh://fixture@127.0.0.1:2222/remote/workspace :: pi"),
31
+ prepareWorkspaceForSshExecution: vi.fn(async () => ({ gitBacked: false })),
32
+ restoreWorkspaceFromSshExecution: vi.fn(async () => undefined),
33
+ runSshCommand: vi.fn(async () => ({
34
+ stdout: "",
35
+ stderr: "",
36
+ exitCode: 0,
37
+ })),
38
+ syncDirectoryToSsh: vi.fn(async () => undefined),
39
+ startAdapterExecutionTargetPaperclipBridge: vi.fn(async () => ({
40
+ env: {
41
+ PAPERCLIP_API_URL: "http://127.0.0.1:4310",
42
+ PAPERCLIP_API_KEY: "bridge-token",
43
+ PAPERCLIP_API_BRIDGE_MODE: "queue_v1",
44
+ },
45
+ stop: async () => { },
46
+ })),
47
+ }));
48
+ vi.mock("@paperclipai/adapter-utils/server-utils", async () => {
49
+ const actual = await vi.importActual("@paperclipai/adapter-utils/server-utils");
50
+ return {
51
+ ...actual,
52
+ ensureCommandResolvable,
53
+ resolveCommandForLogs,
54
+ runChildProcess,
55
+ };
56
+ });
57
+ vi.mock("@paperclipai/adapter-utils/ssh", async () => {
58
+ const actual = await vi.importActual("@paperclipai/adapter-utils/ssh");
59
+ return {
60
+ ...actual,
61
+ prepareWorkspaceForSshExecution,
62
+ restoreWorkspaceFromSshExecution,
63
+ runSshCommand,
64
+ syncDirectoryToSsh,
65
+ };
66
+ });
67
+ vi.mock("@paperclipai/adapter-utils/execution-target", async () => {
68
+ const actual = await vi.importActual("@paperclipai/adapter-utils/execution-target");
69
+ return {
70
+ ...actual,
71
+ startAdapterExecutionTargetPaperclipBridge,
72
+ };
73
+ });
74
+ vi.mock("./models.js", async () => {
75
+ const actual = await vi.importActual("./models.js");
76
+ return {
77
+ ...actual,
78
+ ensurePiModelConfiguredAndAvailable: vi.fn(async () => [
79
+ { id: "openai/gpt-5.4-mini", label: "openai/gpt-5.4-mini" },
80
+ ]),
81
+ };
82
+ });
83
+ import { execute } from "./execute.js";
84
+ describe("pi remote execution", () => {
85
+ const cleanupDirs = [];
86
+ afterEach(async () => {
87
+ vi.clearAllMocks();
88
+ while (cleanupDirs.length > 0) {
89
+ const dir = cleanupDirs.pop();
90
+ if (!dir)
91
+ continue;
92
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
93
+ }
94
+ });
95
+ it("prepares the workspace, syncs Pi skills, and restores workspace changes for remote SSH execution", async () => {
96
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-"));
97
+ cleanupDirs.push(rootDir);
98
+ const workspaceDir = path.join(rootDir, "workspace");
99
+ const alternateWorkspaceDir = path.join(rootDir, "workspace-other");
100
+ const managedRemoteWorkspace = "/remote/workspace/.paperclip-runtime/runs/run-1/workspace";
101
+ await mkdir(workspaceDir, { recursive: true });
102
+ await mkdir(alternateWorkspaceDir, { recursive: true });
103
+ const result = await execute({
104
+ runId: "run-1",
105
+ agent: {
106
+ id: "agent-1",
107
+ companyId: "company-1",
108
+ name: "Pi Builder",
109
+ adapterType: "pi_local",
110
+ adapterConfig: {},
111
+ },
112
+ runtime: {
113
+ sessionId: null,
114
+ sessionParams: null,
115
+ sessionDisplayId: null,
116
+ taskKey: null,
117
+ },
118
+ config: {
119
+ command: "pi",
120
+ model: "openai/gpt-5.4-mini",
121
+ },
122
+ context: {
123
+ paperclipWorkspace: {
124
+ cwd: workspaceDir,
125
+ source: "project_primary",
126
+ },
127
+ paperclipWorkspaces: [
128
+ {
129
+ workspaceId: "workspace-1",
130
+ cwd: workspaceDir,
131
+ repoUrl: "https://github.com/paperclipai/paperclip.git",
132
+ repoRef: "main",
133
+ },
134
+ {
135
+ workspaceId: "workspace-2",
136
+ cwd: alternateWorkspaceDir,
137
+ repoUrl: "https://github.com/paperclipai/paperclip.git",
138
+ repoRef: "feature/other",
139
+ },
140
+ ],
141
+ },
142
+ executionTransport: {
143
+ remoteExecution: {
144
+ host: "127.0.0.1",
145
+ port: 2222,
146
+ username: "fixture",
147
+ remoteWorkspacePath: "/remote/workspace",
148
+ remoteCwd: "/remote/workspace",
149
+ privateKey: "PRIVATE KEY",
150
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
151
+ strictHostKeyChecking: true,
152
+ },
153
+ },
154
+ onLog: async () => { },
155
+ });
156
+ expect(result.sessionParams).toMatchObject({
157
+ cwd: managedRemoteWorkspace,
158
+ remoteExecution: {
159
+ transport: "ssh",
160
+ host: "127.0.0.1",
161
+ port: 2222,
162
+ username: "fixture",
163
+ remoteCwd: managedRemoteWorkspace,
164
+ },
165
+ });
166
+ expect(String(result.sessionId)).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/`);
167
+ expect(prepareWorkspaceForSshExecution).toHaveBeenCalledTimes(1);
168
+ expect(syncDirectoryToSsh).toHaveBeenCalledTimes(2);
169
+ expect(syncDirectoryToSsh).toHaveBeenCalledWith(expect.objectContaining({
170
+ remoteDir: `${managedRemoteWorkspace}/.paperclip-runtime/pi/skills`,
171
+ followSymlinks: true,
172
+ }));
173
+ expect(runSshCommand).toHaveBeenCalledWith(expect.anything(), expect.stringContaining(".paperclip-runtime/pi/sessions"), expect.anything());
174
+ const call = runChildProcess.mock.calls[0];
175
+ expect(call?.[2]).toContain("--session");
176
+ expect(call?.[2]).toContain("--skill");
177
+ expect(call?.[2]).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/skills`);
178
+ expect(call?.[2]).toContain("--extension");
179
+ expect(call?.[2]).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/attribution/openrouter-attribution.mjs`);
180
+ expect(call?.[3].env.PAPERCLIP_WORKSPACE_CWD).toBe(managedRemoteWorkspace);
181
+ expect(JSON.parse(call?.[3].env.PAPERCLIP_WORKSPACES_JSON ?? "[]")).toEqual([
182
+ {
183
+ workspaceId: "workspace-1",
184
+ cwd: managedRemoteWorkspace,
185
+ repoUrl: "https://github.com/paperclipai/paperclip.git",
186
+ repoRef: "main",
187
+ },
188
+ {
189
+ workspaceId: "workspace-2",
190
+ repoUrl: "https://github.com/paperclipai/paperclip.git",
191
+ repoRef: "feature/other",
192
+ },
193
+ ]);
194
+ expect(call?.[3].env.PAPERCLIP_API_URL).toBe("http://127.0.0.1:4310");
195
+ expect(call?.[3].env.PAPERCLIP_API_BRIDGE_MODE).toBe("queue_v1");
196
+ expect(call?.[3].remoteExecution?.remoteCwd).toBe(managedRemoteWorkspace);
197
+ expect(startAdapterExecutionTargetPaperclipBridge).toHaveBeenCalledTimes(1);
198
+ expect(restoreWorkspaceFromSshExecution).toHaveBeenCalledTimes(1);
199
+ });
200
+ it("ships the managed Pi agent config and repoints PI_CODING_AGENT_DIR when PAPERCLIP_PI_PROVIDERS is set", async () => {
201
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-providers-"));
202
+ cleanupDirs.push(rootDir);
203
+ const workspaceDir = path.join(rootDir, "workspace");
204
+ const managedRemoteWorkspace = "/remote/workspace/.paperclip-runtime/runs/run-providers/workspace";
205
+ await mkdir(workspaceDir, { recursive: true });
206
+ const providers = {
207
+ tensorix: {
208
+ baseUrl: "http://gateway.example.svc.cluster.local:8080/anthropic",
209
+ apiKey: "{env:ANTHROPIC_API_KEY}",
210
+ api: "anthropic-messages",
211
+ models: [{ id: "deepseek/deepseek-chat-v3.1", name: "DeepSeek v3.1" }],
212
+ },
213
+ };
214
+ await execute({
215
+ runId: "run-providers",
216
+ agent: {
217
+ id: "agent-1",
218
+ companyId: "company-1",
219
+ name: "Pi Builder",
220
+ adapterType: "pi_local",
221
+ adapterConfig: {},
222
+ },
223
+ runtime: {
224
+ sessionId: null,
225
+ sessionParams: null,
226
+ sessionDisplayId: null,
227
+ taskKey: null,
228
+ },
229
+ config: {
230
+ command: "pi",
231
+ model: "tensorix/deepseek/deepseek-chat-v3.1",
232
+ env: {
233
+ PAPERCLIP_PI_PROVIDERS: JSON.stringify(providers),
234
+ ANTHROPIC_API_KEY: "sk-bf-REALVK",
235
+ },
236
+ },
237
+ context: {
238
+ paperclipWorkspace: {
239
+ cwd: workspaceDir,
240
+ source: "project_primary",
241
+ },
242
+ },
243
+ executionTransport: {
244
+ remoteExecution: {
245
+ host: "127.0.0.1",
246
+ port: 2222,
247
+ username: "fixture",
248
+ remoteWorkspacePath: "/remote/workspace",
249
+ remoteCwd: "/remote/workspace",
250
+ privateKey: "PRIVATE KEY",
251
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
252
+ strictHostKeyChecking: true,
253
+ },
254
+ },
255
+ onLog: async () => { },
256
+ });
257
+ expect(syncDirectoryToSsh).toHaveBeenCalledWith(expect.objectContaining({
258
+ remoteDir: `${managedRemoteWorkspace}/.paperclip-runtime/pi/agentConfig`,
259
+ }));
260
+ const call = runChildProcess.mock.calls[0];
261
+ expect(call?.[3].env.PI_CODING_AGENT_DIR).toBe(`${managedRemoteWorkspace}/.paperclip-runtime/pi/agentConfig`);
262
+ expect(call?.[2]).toContain("--provider");
263
+ expect(call?.[2]).toContain("tensorix");
264
+ expect(call?.[2]).toContain("--model");
265
+ expect(call?.[2]).toContain("deepseek/deepseek-chat-v3.1");
266
+ });
267
+ it.each([false, true])("resumes saved Pi sessions when the SSH identity matches (inPlace=%s)", async (inPlace) => {
268
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-resume-"));
269
+ cleanupDirs.push(rootDir);
270
+ const workspaceDir = path.join(rootDir, "workspace");
271
+ const managedRemoteWorkspace = inPlace ? workspaceDir : "/remote/workspace/.paperclip-runtime/runs/run-ssh-resume/workspace";
272
+ await mkdir(workspaceDir, { recursive: true });
273
+ runSshCommand.mockImplementation(async (...args) => {
274
+ const command = String(args[1] ?? "");
275
+ if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
276
+ return {
277
+ stdout: `${JSON.stringify({ type: "session", cwd: managedRemoteWorkspace })}\n`,
278
+ stderr: "",
279
+ exitCode: 0,
280
+ };
281
+ }
282
+ return {
283
+ stdout: "",
284
+ stderr: "",
285
+ exitCode: 0,
286
+ };
287
+ });
288
+ await execute({
289
+ runId: "run-ssh-resume",
290
+ executionTarget: inPlace ? {
291
+ kind: "remote", transport: "ssh", remoteCwd: managedRemoteWorkspace,
292
+ workspaceRealization: { mode: "in_place", authoritativeRoot: managedRemoteWorkspace, pathAliases: [], outboundRestorePaths: [] },
293
+ spec: { host: "127.0.0.1", port: 2222, username: "fixture", remoteWorkspacePath: "/remote/workspace",
294
+ remoteCwd: managedRemoteWorkspace, privateKey: "PRIVATE KEY", knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA", strictHostKeyChecking: true },
295
+ } : undefined,
296
+ agent: {
297
+ id: "agent-1",
298
+ companyId: "company-1",
299
+ name: "Pi Builder",
300
+ adapterType: "pi_local",
301
+ adapterConfig: {},
302
+ },
303
+ runtime: {
304
+ sessionId: `${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/session-123.jsonl`,
305
+ sessionParams: {
306
+ sessionId: `${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/session-123.jsonl`,
307
+ cwd: managedRemoteWorkspace,
308
+ remoteExecution: {
309
+ transport: "ssh",
310
+ host: "127.0.0.1",
311
+ port: 2222,
312
+ username: "fixture",
313
+ remoteCwd: managedRemoteWorkspace,
314
+ },
315
+ },
316
+ sessionDisplayId: "session-123",
317
+ taskKey: null,
318
+ },
319
+ config: {
320
+ command: "pi",
321
+ model: "openai/gpt-5.4-mini",
322
+ },
323
+ context: {
324
+ paperclipWorkspace: {
325
+ cwd: workspaceDir,
326
+ source: "project_primary",
327
+ },
328
+ },
329
+ executionTransport: {
330
+ remoteExecution: {
331
+ host: "127.0.0.1",
332
+ port: 2222,
333
+ username: "fixture",
334
+ remoteWorkspacePath: "/remote/workspace",
335
+ remoteCwd: "/remote/workspace",
336
+ privateKey: "PRIVATE KEY",
337
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
338
+ strictHostKeyChecking: true,
339
+ },
340
+ },
341
+ onLog: async () => { },
342
+ });
343
+ const call = runChildProcess.mock.calls[0];
344
+ expect(call?.[2]).toContain("--session");
345
+ expect(call?.[2]).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/session-123.jsonl`);
346
+ });
347
+ it("starts a fresh remote Pi session when the saved session header cwd points at a different workspace", async () => {
348
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-stale-session-"));
349
+ cleanupDirs.push(rootDir);
350
+ const workspaceDir = path.join(rootDir, "workspace");
351
+ await mkdir(workspaceDir, { recursive: true });
352
+ runSshCommand.mockImplementation(async (...args) => {
353
+ const command = String(args[1] ?? "");
354
+ if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
355
+ return {
356
+ stdout: `${JSON.stringify({ type: "session", cwd: "/remote/old-workspace" })}\n`,
357
+ stderr: "",
358
+ exitCode: 0,
359
+ };
360
+ }
361
+ return {
362
+ stdout: "",
363
+ stderr: "",
364
+ exitCode: 0,
365
+ };
366
+ });
367
+ await execute({
368
+ runId: "run-ssh-stale-session",
369
+ agent: {
370
+ id: "agent-1",
371
+ companyId: "company-1",
372
+ name: "Pi Builder",
373
+ adapterType: "pi_local",
374
+ adapterConfig: {},
375
+ },
376
+ runtime: {
377
+ sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
378
+ sessionParams: {
379
+ sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
380
+ cwd: "/remote/workspace",
381
+ remoteExecution: {
382
+ transport: "ssh",
383
+ host: "127.0.0.1",
384
+ port: 2222,
385
+ username: "fixture",
386
+ remoteCwd: "/remote/workspace",
387
+ },
388
+ },
389
+ sessionDisplayId: "session-123",
390
+ taskKey: null,
391
+ },
392
+ config: {
393
+ command: "pi",
394
+ model: "openai/gpt-5.4-mini",
395
+ },
396
+ context: {
397
+ paperclipWorkspace: {
398
+ cwd: workspaceDir,
399
+ source: "project_primary",
400
+ },
401
+ },
402
+ executionTransport: {
403
+ remoteExecution: {
404
+ host: "127.0.0.1",
405
+ port: 2222,
406
+ username: "fixture",
407
+ remoteWorkspacePath: "/remote/workspace",
408
+ remoteCwd: "/remote/workspace",
409
+ privateKey: "PRIVATE KEY",
410
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
411
+ strictHostKeyChecking: true,
412
+ },
413
+ },
414
+ onLog: async () => { },
415
+ });
416
+ const managedRemoteWorkspaceFresh = "/remote/workspace/.paperclip-runtime/runs/run-ssh-stale-session/workspace";
417
+ const call = runChildProcess.mock.calls[0];
418
+ const sessionIndex = call?.[2].indexOf("--session") ?? -1;
419
+ expect(sessionIndex).toBeGreaterThanOrEqual(0);
420
+ const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
421
+ expect(usedSession).toContain(`${managedRemoteWorkspaceFresh}/.paperclip-runtime/pi/sessions/`);
422
+ expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
423
+ });
424
+ it("starts a fresh remote Pi session when the saved session header is empty or unreadable", async () => {
425
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-empty-header-"));
426
+ cleanupDirs.push(rootDir);
427
+ const workspaceDir = path.join(rootDir, "workspace");
428
+ await mkdir(workspaceDir, { recursive: true });
429
+ runSshCommand.mockImplementation(async (...args) => {
430
+ const command = String(args[1] ?? "");
431
+ if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
432
+ return { stdout: "", stderr: "", exitCode: 0 };
433
+ }
434
+ return { stdout: "", stderr: "", exitCode: 0 };
435
+ });
436
+ await execute({
437
+ runId: "run-ssh-empty-header",
438
+ agent: {
439
+ id: "agent-1",
440
+ companyId: "company-1",
441
+ name: "Pi Builder",
442
+ adapterType: "pi_local",
443
+ adapterConfig: {},
444
+ },
445
+ runtime: {
446
+ sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
447
+ sessionParams: {
448
+ sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
449
+ cwd: "/remote/workspace",
450
+ remoteExecution: {
451
+ transport: "ssh",
452
+ host: "127.0.0.1",
453
+ port: 2222,
454
+ username: "fixture",
455
+ remoteCwd: "/remote/workspace",
456
+ },
457
+ },
458
+ sessionDisplayId: "session-123",
459
+ taskKey: null,
460
+ },
461
+ config: { command: "pi", model: "openai/gpt-5.4-mini" },
462
+ context: {
463
+ paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
464
+ },
465
+ executionTransport: {
466
+ remoteExecution: {
467
+ host: "127.0.0.1",
468
+ port: 2222,
469
+ username: "fixture",
470
+ remoteWorkspacePath: "/remote/workspace",
471
+ remoteCwd: "/remote/workspace",
472
+ privateKey: "PRIVATE KEY",
473
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
474
+ strictHostKeyChecking: true,
475
+ },
476
+ },
477
+ onLog: async () => { },
478
+ });
479
+ const call = runChildProcess.mock.calls[0];
480
+ const sessionIndex = call?.[2].indexOf("--session") ?? -1;
481
+ expect(sessionIndex).toBeGreaterThanOrEqual(0);
482
+ const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
483
+ expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
484
+ });
485
+ it("starts a fresh remote Pi session when the remote head command fails", async () => {
486
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-head-failure-"));
487
+ cleanupDirs.push(rootDir);
488
+ const workspaceDir = path.join(rootDir, "workspace");
489
+ await mkdir(workspaceDir, { recursive: true });
490
+ runSshCommand.mockImplementation(async (...args) => {
491
+ const command = String(args[1] ?? "");
492
+ if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
493
+ throw Object.assign(new Error("ssh: connect failed"), {
494
+ stdout: "",
495
+ stderr: "ssh: connect failed",
496
+ code: "ENOENT",
497
+ });
498
+ }
499
+ return { stdout: "", stderr: "", exitCode: 0 };
500
+ });
501
+ await execute({
502
+ runId: "run-ssh-head-failure",
503
+ agent: {
504
+ id: "agent-1",
505
+ companyId: "company-1",
506
+ name: "Pi Builder",
507
+ adapterType: "pi_local",
508
+ adapterConfig: {},
509
+ },
510
+ runtime: {
511
+ sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
512
+ sessionParams: {
513
+ sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
514
+ cwd: "/remote/workspace",
515
+ remoteExecution: {
516
+ transport: "ssh",
517
+ host: "127.0.0.1",
518
+ port: 2222,
519
+ username: "fixture",
520
+ remoteCwd: "/remote/workspace",
521
+ },
522
+ },
523
+ sessionDisplayId: "session-123",
524
+ taskKey: null,
525
+ },
526
+ config: { command: "pi", model: "openai/gpt-5.4-mini", bootstrapPromptTemplate: "BOOTSTRAP {{run.id}}" },
527
+ context: {
528
+ ...createPromptContextFixture(),
529
+ paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
530
+ },
531
+ executionTransport: {
532
+ remoteExecution: {
533
+ host: "127.0.0.1",
534
+ port: 2222,
535
+ username: "fixture",
536
+ remoteWorkspacePath: "/remote/workspace",
537
+ remoteCwd: "/remote/workspace",
538
+ privateKey: "PRIVATE KEY",
539
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
540
+ strictHostKeyChecking: true,
541
+ },
542
+ },
543
+ onLog: async () => { },
544
+ });
545
+ const call = runChildProcess.mock.calls[0];
546
+ const sessionIndex = call?.[2].indexOf("--session") ?? -1;
547
+ expect(sessionIndex).toBeGreaterThanOrEqual(0);
548
+ const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
549
+ expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
550
+ const prompt = String(call?.[2].at(-1) ?? "");
551
+ expect(prompt).toContain("## Owned assignment");
552
+ expect(prompt).toContain("BOOTSTRAP run-ssh-head-failure");
553
+ expect(prompt).toContain("comment-scope");
554
+ });
555
+ it("delivers the owned assignment and ordered wake comments through Pi's prompt", async () => {
556
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-context-ownership-"));
557
+ cleanupDirs.push(rootDir);
558
+ await mkdir(rootDir, { recursive: true });
559
+ const fixture = createPromptContextFixture();
560
+ let deliveredPrompt = "";
561
+ await execute({
562
+ runId: "run-context-ownership",
563
+ agent: {
564
+ id: "agent-1",
565
+ companyId: "company-1",
566
+ name: "Pi Builder",
567
+ adapterType: "pi_local",
568
+ adapterConfig: {},
569
+ },
570
+ runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
571
+ config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
572
+ context: { ...fixture, paperclipWorkspace: { cwd: rootDir, source: "project_primary" } },
573
+ onLog: async () => { },
574
+ });
575
+ const call = runChildProcess.mock.calls.at(-1);
576
+ deliveredPrompt = String(call?.[2].at(-1) ?? "");
577
+ expect(deliveredPrompt).toContain(fixture.paperclipTaskMarkdownAssignment);
578
+ expect(deliveredPrompt.indexOf("Append the same ledger entry.")).toBeLessThan(deliveredPrompt.lastIndexOf("Append the same ledger entry."));
579
+ expect(deliveredPrompt.indexOf("comment-first")).toBeLessThan(deliveredPrompt.indexOf("comment-second"));
580
+ expect(deliveredPrompt.indexOf("comment-second")).toBeLessThan(deliveredPrompt.indexOf("comment-scope"));
581
+ expect(deliveredPrompt).toContain("Change the final scope to the launch checklist.");
582
+ });
583
+ it("keeps the default Paperclip policy in the system carrier without duplicating it in user input", async () => {
584
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-default-policy-"));
585
+ cleanupDirs.push(rootDir);
586
+ await execute({
587
+ runId: "run-default-policy",
588
+ agent: {
589
+ id: "agent-1",
590
+ companyId: "company-1",
591
+ name: "Pi Builder",
592
+ adapterType: "pi_local",
593
+ adapterConfig: {},
594
+ },
595
+ runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
596
+ config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
597
+ context: {},
598
+ onLog: async () => { },
599
+ });
600
+ const call = runChildProcess.mock.calls.at(-1);
601
+ const args = call?.[2] ?? [];
602
+ const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
603
+ const userPrompt = args.at(-1) ?? "";
604
+ expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
605
+ expect(userPrompt).not.toContain("You are agent agent-1 (Pi Builder).");
606
+ });
607
+ it("preserves custom prompt templates in both configured carriers", async () => {
608
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-custom-policy-"));
609
+ cleanupDirs.push(rootDir);
610
+ await execute({
611
+ runId: "run-custom-policy",
612
+ agent: {
613
+ id: "agent-1",
614
+ companyId: "company-1",
615
+ name: "Pi Builder",
616
+ adapterType: "pi_local",
617
+ adapterConfig: {},
618
+ },
619
+ runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
620
+ config: {
621
+ command: "pi",
622
+ model: "openai/gpt-5.4-mini",
623
+ cwd: rootDir,
624
+ promptTemplate: "CUSTOM POLICY {{run.id}}",
625
+ },
626
+ context: {},
627
+ onLog: async () => { },
628
+ });
629
+ const call = runChildProcess.mock.calls.at(-1);
630
+ const args = call?.[2] ?? [];
631
+ const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
632
+ const userPrompt = args.at(-1) ?? "";
633
+ expect(systemPrompt).toBe("CUSTOM POLICY run-custom-policy");
634
+ expect(userPrompt).toBe("CUSTOM POLICY run-custom-policy");
635
+ });
636
+ it("keeps resumed default identity and connection guidance in the system carrier", async () => {
637
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-resumed-policy-"));
638
+ cleanupDirs.push(rootDir);
639
+ const sessionPath = path.join(rootDir, "session.jsonl");
640
+ await writeFile(sessionPath, `${JSON.stringify({ type: "session", cwd: rootDir })}\n`, "utf8");
641
+ await execute({
642
+ runId: "run-resumed-policy",
643
+ agent: {
644
+ id: "agent-1",
645
+ companyId: "company-1",
646
+ name: "Pi Builder",
647
+ adapterType: "pi_local",
648
+ adapterConfig: {},
649
+ },
650
+ runtime: {
651
+ sessionId: sessionPath,
652
+ sessionParams: { sessionId: sessionPath, cwd: rootDir },
653
+ sessionDisplayId: "session-resumed-policy",
654
+ taskKey: null,
655
+ },
656
+ config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
657
+ context: createPromptContextFixture(),
658
+ onLog: async () => { },
659
+ });
660
+ const call = runChildProcess.mock.calls.at(-1);
661
+ const args = call?.[2] ?? [];
662
+ const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
663
+ const userPrompt = args.at(-1) ?? "";
664
+ expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
665
+ expect(systemPrompt).toContain("Connection tools:");
666
+ expect(systemPrompt).not.toContain("Execution contract:");
667
+ expect(userPrompt).not.toContain("Execution contract:");
668
+ });
669
+ it("keeps default identity in system input when custom prompt uses loaded instructions", async () => {
670
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-instructions-policy-"));
671
+ cleanupDirs.push(rootDir);
672
+ const sessionPath = path.join(rootDir, "session.jsonl");
673
+ const instructionsPath = path.join(rootDir, "AGENTS.md");
674
+ await writeFile(sessionPath, `${JSON.stringify({ type: "session", cwd: rootDir })}\n`, "utf8");
675
+ await writeFile(instructionsPath, "Loaded instructions for this run.\n", "utf8");
676
+ await execute({
677
+ runId: "run-instructions-policy",
678
+ agent: {
679
+ id: "agent-1",
680
+ companyId: "company-1",
681
+ name: "Pi Builder",
682
+ adapterType: "pi_local",
683
+ adapterConfig: {},
684
+ },
685
+ runtime: {
686
+ sessionId: sessionPath,
687
+ sessionParams: { sessionId: sessionPath, cwd: rootDir },
688
+ sessionDisplayId: "session-instructions-policy",
689
+ taskKey: null,
690
+ },
691
+ config: {
692
+ command: "pi",
693
+ model: "openai/gpt-5.4-mini",
694
+ cwd: rootDir,
695
+ instructionsFilePath: "AGENTS.md",
696
+ promptTemplate: "CUSTOM POLICY {{run.id}}",
697
+ },
698
+ context: createPromptContextFixture(),
699
+ onLog: async () => { },
700
+ });
701
+ const call = runChildProcess.mock.calls.at(-1);
702
+ const args = call?.[2] ?? [];
703
+ const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
704
+ const userPrompt = args.at(-1) ?? "";
705
+ expect(systemPrompt).toContain("Loaded instructions for this run.");
706
+ expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
707
+ expect(systemPrompt).toContain("Connection tools:");
708
+ expect(systemPrompt).not.toContain("Execution contract:");
709
+ expect(userPrompt).not.toContain("CUSTOM POLICY run-instructions-policy");
710
+ expect(userPrompt).not.toContain("Execution contract:");
711
+ });
712
+ it("compacts streamed chunks while parsing the untouched raw stdout result", async () => {
713
+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-log-boundary-"));
714
+ cleanupDirs.push(rootDir);
715
+ const workspaceDir = path.join(rootDir, "workspace");
716
+ await mkdir(workspaceDir, { recursive: true });
717
+ const sessionLine = JSON.stringify({ type: "session", id: "session-boundary", cwd: "/remote/workspace" });
718
+ const messageLine = JSON.stringify({
719
+ type: "message_update",
720
+ message: {
721
+ role: "assistant",
722
+ content: [{ type: "text", text: "Hello 😀" }],
723
+ },
724
+ assistantMessageEvent: {
725
+ type: "text_delta",
726
+ contentIndex: 0,
727
+ delta: "Hello 😀",
728
+ partial: {
729
+ role: "assistant",
730
+ content: [{ type: "text", text: "Hello 😀" }],
731
+ },
732
+ },
733
+ });
734
+ const toolUpdateLine = JSON.stringify({
735
+ type: "tool_execution_update",
736
+ toolCallId: "tc-boundary",
737
+ toolName: "bash",
738
+ args: { command: "printf progress" },
739
+ partialResult: {
740
+ content: [{ type: "text", text: "large cumulative output".repeat(1_000) }],
741
+ details: {},
742
+ },
743
+ });
744
+ // CRLF on the passthrough session line, LF on the transformed message,
745
+ // and no newline on the final line exercise every buffering exit path.
746
+ const rawStdout = `${sessionLine}\r\n${messageLine}\n${toolUpdateLine}`;
747
+ runChildProcess.mockImplementationOnce(async (...args) => {
748
+ const options = args[3];
749
+ const emojiSplit = rawStdout.indexOf("😀") + 1;
750
+ await options.onLog?.("stdout", rawStdout.slice(0, emojiSplit));
751
+ await options.onLog?.("stderr", "diagnostic stderr\n");
752
+ await options.onLog?.("stdout", rawStdout.slice(emojiSplit));
753
+ return {
754
+ exitCode: 0,
755
+ signal: null,
756
+ timedOut: false,
757
+ stdout: rawStdout,
758
+ stderr: "diagnostic stderr\n",
759
+ pid: 456,
760
+ startedAt: new Date().toISOString(),
761
+ };
762
+ });
763
+ const logs = [];
764
+ const result = await execute({
765
+ runId: "run-log-boundary",
766
+ agent: {
767
+ id: "agent-1",
768
+ companyId: "company-1",
769
+ name: "Pi Builder",
770
+ adapterType: "pi_local",
771
+ adapterConfig: {},
772
+ },
773
+ runtime: {
774
+ sessionId: null,
775
+ sessionParams: null,
776
+ sessionDisplayId: null,
777
+ taskKey: null,
778
+ },
779
+ config: {
780
+ command: "pi",
781
+ model: "openai/gpt-5.4-mini",
782
+ stdoutLogMode: "compact",
783
+ },
784
+ context: {
785
+ paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
786
+ },
787
+ executionTransport: {
788
+ remoteExecution: {
789
+ host: "127.0.0.1",
790
+ port: 2222,
791
+ username: "fixture",
792
+ remoteWorkspacePath: "/remote/workspace",
793
+ remoteCwd: "/remote/workspace",
794
+ privateKey: "PRIVATE KEY",
795
+ knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
796
+ strictHostKeyChecking: true,
797
+ },
798
+ },
799
+ onLog: async (stream, chunk) => {
800
+ logs.push({ stream, chunk });
801
+ },
802
+ });
803
+ const stdoutLog = logs.filter((entry) => entry.stream === "stdout").map((entry) => entry.chunk).join("");
804
+ expect(stdoutLog).toContain(`${sessionLine}\r\n`);
805
+ expect(stdoutLog).toContain('"type":"message_update"');
806
+ expect(stdoutLog).toContain('"delta":"Hello 😀"');
807
+ expect(stdoutLog).toContain('"sourceEventType":"tool_execution_update"');
808
+ expect(stdoutLog).not.toContain("large cumulative output");
809
+ expect(logs).toContainEqual({ stream: "stderr", chunk: "diagnostic stderr\n" });
810
+ expect(result.summary).toBe("Hello 😀");
811
+ expect(result.resultJson).toEqual({ stdout: rawStdout, stderr: "diagnostic stderr\n" });
812
+ });
813
+ });
814
+ //# sourceMappingURL=execute.remote.test.js.map