send-to-paseo 2.6.1-beta.1 → 2.6.1
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/client/settings-feed/index.ts +1 -1
- package/package.json +5 -3
- package/server/daemon-connection.test.mjs +194 -0
- package/server/daemon-endpoint/index.d.mts +24 -0
- package/server/daemon-endpoint/index.mjs +145 -0
- package/server/daemon-endpoint.test.mjs +137 -0
- package/server/daemon.ts +7 -15
- package/server/follow-up.test.mjs +233 -0
- package/server/main-agent.test.mjs +115 -0
- package/server/settings-feed/index.ts +1 -1
- package/server/shared-daemon.ts +5 -8
- package/shared/contracts.ts +1 -1
- package/server/daemon-endpoint.ts +0 -143
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Vendored from paseo-plugin-kit v0.4.0-beta.
|
|
1
|
+
// Vendored from paseo-plugin-kit v0.4.0-beta.1 (settings-feed-client/index.ts). Do not edit; change the kit and run `paseo-kit vendor settings-feed-client <dir>`.
|
|
2
2
|
/** Push settings on current hosts; read once a minute while a feed is unavailable. */
|
|
3
3
|
type Handle = (() => void) & { ready?: Promise<unknown> };
|
|
4
4
|
type Clock = Pick<typeof globalThis, "setTimeout" | "clearTimeout" | "setInterval" | "clearInterval">;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "send-to-paseo",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2.6.1
|
|
4
|
+
"version": "2.6.1",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Local HTTP bridge that dispatches PR work to the right Paseo workspace and agent.",
|
|
7
7
|
"repository": {
|
|
@@ -27,6 +27,8 @@
|
|
|
27
27
|
"client/**/*.ts",
|
|
28
28
|
"client/**/*.tsx",
|
|
29
29
|
"server/**/*.ts",
|
|
30
|
+
"server/**/*.mjs",
|
|
31
|
+
"server/**/*.d.mts",
|
|
30
32
|
"shared/**/*.ts",
|
|
31
33
|
"docs/media/"
|
|
32
34
|
],
|
|
@@ -36,7 +38,7 @@
|
|
|
36
38
|
"scripts": {
|
|
37
39
|
"typecheck": "tsc --noEmit",
|
|
38
40
|
"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 server/daemon-endpoint.test.mjs",
|
|
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 && node --test display-feed.test.mjs && paseo-kit vendor --check settings-feed-client client/settings-feed && paseo-kit vendor --check settings-feed-server server/settings-feed"
|
|
41
|
+
"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 && node --test display-feed.test.mjs && paseo-kit vendor --check settings-feed-client client/settings-feed && paseo-kit vendor --check settings-feed-server server/settings-feed && paseo-kit vendor --check daemon-endpoint server/daemon-endpoint"
|
|
40
42
|
},
|
|
41
43
|
"devDependencies": {
|
|
42
44
|
"@getpaseo/client": "0.14.0",
|
|
@@ -46,7 +48,7 @@
|
|
|
46
48
|
"@types/node": "^22.10.2",
|
|
47
49
|
"@types/react": "~19.2.0",
|
|
48
50
|
"esbuild": "^0.28.2",
|
|
49
|
-
"paseo-plugin-kit": "github:tomgrin10/paseo-plugin-kit#v0.4.0-beta.
|
|
51
|
+
"paseo-plugin-kit": "github:tomgrin10/paseo-plugin-kit#v0.4.0-beta.1",
|
|
50
52
|
"react": "19.1.0",
|
|
51
53
|
"react-native": "0.81.5",
|
|
52
54
|
"typescript": "^5.9.3",
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// one-held-daemon-connection (AGENTS.md): every bridge request and every optional Follow Up call
|
|
2
|
+
// shares one held daemon connection, reopened only after a real drop. Before this each request
|
|
3
|
+
// opened its own: about 20 hellos a minute for each of two client names with a browser open.
|
|
4
|
+
import test from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { build } from "esbuild";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
const realRequire = createRequire(import.meta.url);
|
|
9
|
+
|
|
10
|
+
const counts = { built: 0, closed: 0, disposed: 0 };
|
|
11
|
+
class FakeClient {
|
|
12
|
+
constructor() { counts.built++; this.state = { status: "idle" }; this.listeners = new Set(); }
|
|
13
|
+
async connect() { this.set("connected"); }
|
|
14
|
+
async close() { counts.closed++; this.set("disposed"); }
|
|
15
|
+
set(status) { this.state = { status }; for (const l of this.listeners) l(this.state); }
|
|
16
|
+
getConnectionState() { return this.state; }
|
|
17
|
+
subscribeConnectionStatus(l) { this.listeners.add(l); return () => this.listeners.delete(l); }
|
|
18
|
+
async sendMessage(agentId, text, options) { assert.equal(this.state.status, "connected"); return { deliveryStatus: "queued", guidance: "After this turn", agentId, text, options }; }
|
|
19
|
+
async invokePluginRpc() { return { owner: null }; }
|
|
20
|
+
}
|
|
21
|
+
const api = () => ({ workspaces: { list: async () => ({ entries: [] }) }, dispose: async () => { counts.disposed++; } });
|
|
22
|
+
const fakeModules = {
|
|
23
|
+
"@getpaseo/client": {
|
|
24
|
+
createPaseoApi: () => api(),
|
|
25
|
+
// What the per-request code used; counted the same way so the old shape fails here too.
|
|
26
|
+
createPaseoClient: () => { const c = new FakeClient(); return { ...api(), connect: () => c.connect(), close: () => c.close() }; },
|
|
27
|
+
},
|
|
28
|
+
"@getpaseo/client/internal/daemon-client": { DaemonClient: FakeClient },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
async function load(path, stubs) {
|
|
32
|
+
const b = await build({ entryPoints: [path], bundle: true, write: false, platform: "node", format: "cjs", packages: "external", plugins: [{ name: "fixture", setup(b) { b.onResolve({ filter: /^\./ }, args => Object.hasOwn(stubs, args.path) ? { path: "fixture:" + args.path, external: true } : undefined); } }] });
|
|
33
|
+
const module = { exports: {} };
|
|
34
|
+
const req = id => id.startsWith("fixture:") ? stubs[id.slice(8)] : Object.hasOwn(fakeModules, id) ? fakeModules[id] : realRequire(id);
|
|
35
|
+
new Function("require", "module", "exports", b.outputFiles[0].text)(req, module, module.exports);
|
|
36
|
+
return module.exports;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
test("N bridge requests and Follow Up calls open one daemon connection, closed by closeDaemon", async () => {
|
|
40
|
+
process.env.PASEO_DAEMON_URL = "ws://127.0.0.1:1/ws";
|
|
41
|
+
const m = await load("server/daemon.ts", {
|
|
42
|
+
"./settings": { settings: { read: async () => ({}) } },
|
|
43
|
+
"./daemon-password": { resolveDaemonPassword: async () => undefined },
|
|
44
|
+
});
|
|
45
|
+
for (let i = 0; i < 5; i++) {
|
|
46
|
+
await m.withPaseo(paseo => paseo.workspaces.list());
|
|
47
|
+
await m.callFollowUp("follow.pr-owner", { repo: "example/app", number: 1 });
|
|
48
|
+
}
|
|
49
|
+
await Promise.all(Array.from({ length: 5 }, () => [m.withPaseo(p => p.workspaces.list()), m.callFollowUp("follow.browser-exchange", {})]).flat());
|
|
50
|
+
assert.equal(counts.built, 1, "20 requests should share one connection");
|
|
51
|
+
assert.equal(counts.closed, 0, "the connection is held between requests");
|
|
52
|
+
assert.equal(counts.disposed, 10, "each bridge request's scoped API is released");
|
|
53
|
+
assert.equal(typeof m.closeDaemon, "function");
|
|
54
|
+
await m.closeDaemon();
|
|
55
|
+
assert.equal(counts.closed, 1);
|
|
56
|
+
await assert.rejects(m.withPaseo(p => p.workspaces.list()), /stopping/);
|
|
57
|
+
assert.equal(counts.built, 1, "nothing opens after teardown");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("shared connection: drops, dead sockets, backoff and max age", async () => {
|
|
61
|
+
const { sharedDaemon } = await load("server/shared-daemon.ts", {});
|
|
62
|
+
let t = 0;
|
|
63
|
+
const made = [];
|
|
64
|
+
let up = true;
|
|
65
|
+
let attempts = 0;
|
|
66
|
+
const open = async () => { attempts++; if (!up) throw new Error("daemon down"); const c = new FakeClient(); await c.connect(); made.push(c); return c; };
|
|
67
|
+
const d = sharedDaemon(open, { now: () => t, maxMs: 10_000, backoffMs: 1_000, backoffMaxMs: 4_000 });
|
|
68
|
+
|
|
69
|
+
await Promise.all([d.run(async () => 1), d.run(async () => 1)]);
|
|
70
|
+
assert.equal(made.length, 1, "concurrent first calls join one open");
|
|
71
|
+
|
|
72
|
+
made[0].set("disconnected");
|
|
73
|
+
await d.run(async () => 1);
|
|
74
|
+
assert.equal(made.length, 2, "a real drop reopens once");
|
|
75
|
+
|
|
76
|
+
await assert.rejects(d.run(async () => { throw new Error("bad request"); }));
|
|
77
|
+
await d.run(async () => 1);
|
|
78
|
+
assert.equal(made.length, 2, "an error on a live socket keeps it");
|
|
79
|
+
await assert.rejects(d.run(async () => { made[1].state = { status: "disconnected" }; throw new Error("gone"); }));
|
|
80
|
+
up = false;
|
|
81
|
+
await assert.rejects(d.run(async () => 1), /daemon down/);
|
|
82
|
+
await assert.rejects(d.run(async () => 1), /daemon down/);
|
|
83
|
+
assert.equal(attempts, 3, "inside the backoff no new open");
|
|
84
|
+
up = true;
|
|
85
|
+
t = 1_000;
|
|
86
|
+
await d.run(async () => 1);
|
|
87
|
+
assert.equal(made.length, 3);
|
|
88
|
+
|
|
89
|
+
t = 11_000;
|
|
90
|
+
await d.run(async () => 1);
|
|
91
|
+
assert.equal(made.length, 4, "older than maxMs is replaced");
|
|
92
|
+
await new Promise(r => setImmediate(r));
|
|
93
|
+
assert.equal(made[2].state.status, "disposed");
|
|
94
|
+
await d.close();
|
|
95
|
+
assert.equal(made[3].state.status, "disposed");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// warm-daemon-connection + optional-lookup-never-silent (AGENTS.md). 2.4.1 live: a fresh connection per
|
|
99
|
+
// Follow-up call took 0.85-2.5 s against a 2 s budget; the timeout read as "not tracked" and the popover's
|
|
100
|
+
// "Workspace for this PR" section silently vanished.
|
|
101
|
+
async function loadEntry(contents, stubs) {
|
|
102
|
+
const b = await build({ stdin: { contents, resolveDir: process.cwd(), loader: "ts" }, bundle: true, write: false, platform: "node", format: "cjs", packages: "external", plugins: [{ name: "fixture", setup(b) { b.onResolve({ filter: /^\./ }, args => Object.hasOwn(stubs, args.path) ? { path: "fixture:" + args.path, external: true } : undefined); } }] });
|
|
103
|
+
const module = { exports: {} };
|
|
104
|
+
const req = id => id.startsWith("fixture:") ? stubs[id.slice(8)] : Object.hasOwn(slowModules, id) ? slowModules[id] : realRequire(id);
|
|
105
|
+
new Function("require", "module", "exports", b.outputFiles[0].text)(req, module, module.exports);
|
|
106
|
+
return module.exports;
|
|
107
|
+
}
|
|
108
|
+
const slow = { built: 0, connectMs: 2_300 };
|
|
109
|
+
class SlowClient extends FakeClient {
|
|
110
|
+
constructor() { super(); slow.built++; }
|
|
111
|
+
async connect() { await new Promise(r => setTimeout(r, slow.connectMs)); this.set("connected"); }
|
|
112
|
+
async invokePluginRpc(plugin, method) {
|
|
113
|
+
if (plugin !== "follow-up") throw new Error(`Plugin is not available: ${plugin}`);
|
|
114
|
+
assert.equal(method, "follow.pr-workspaces");
|
|
115
|
+
return { tracked: true, more: 0, workspaces: [{ workspaceId: "wks_1", agentId: "agt_1", title: "quiet-heron", agentStatus: "idle", group: "needs", state: "Needs you" }] };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const slowModules = { ...fakeModules, "@getpaseo/client/internal/daemon-client": { DaemonClient: SlowClient } };
|
|
119
|
+
|
|
120
|
+
test("a Follow-up behind a connect slower than its budget: cold says unknown at once, warm answers in time, never none", async () => {
|
|
121
|
+
process.env.PASEO_DAEMON_URL = "ws://127.0.0.1:1/ws";
|
|
122
|
+
const m = await loadEntry(`export { lookupPrWorkspaces } from "./server/follow-up"; export * from "./server/daemon";`, {
|
|
123
|
+
"./settings": { settings: { read: async () => ({}) } },
|
|
124
|
+
"./daemon-password": { resolveDaemonPassword: async () => undefined },
|
|
125
|
+
});
|
|
126
|
+
let t = Date.now();
|
|
127
|
+
assert.equal(await m.lookupPrWorkspaces("example", "app", 7), "unknown", "not connected yet: couldn't check, which is not 'not tracked'");
|
|
128
|
+
assert.ok(Date.now() - t < 500, `the click path must not wait on a connect (took ${Date.now() - t} ms)`);
|
|
129
|
+
|
|
130
|
+
m.warmDaemon(); // what plugin start does; joins the open the cold call already started
|
|
131
|
+
await new Promise(r => setTimeout(r, slow.connectMs + 200));
|
|
132
|
+
t = Date.now();
|
|
133
|
+
const warm = await m.lookupPrWorkspaces("example", "app", 7);
|
|
134
|
+
assert.deepEqual(warm?.workspaces?.map(w => w.workspaceId), ["wks_1"], "warm shared client: the owner arrives");
|
|
135
|
+
assert.ok(Date.now() - t < 500, `a warm lookup pays no connect (took ${Date.now() - t} ms)`);
|
|
136
|
+
assert.equal(slow.built, 1, "one held connection: no extra hellos per request");
|
|
137
|
+
await m.closeDaemon();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("kept warm: opens at start, reconnects in the background after a drop or failed open, rotates without a gap", async () => {
|
|
141
|
+
const { sharedDaemon } = await load("server/shared-daemon.ts", {});
|
|
142
|
+
const made = [];
|
|
143
|
+
let up = true;
|
|
144
|
+
let t = 0;
|
|
145
|
+
const open = async () => { if (!up) throw new Error("daemon down"); const c = new FakeClient(); await c.connect(); made.push(c); return c; };
|
|
146
|
+
const tick = (ms = 0) => new Promise(r => setTimeout(r, ms));
|
|
147
|
+
const d = sharedDaemon(open, { keepWarm: true, now: () => t, maxMs: 10_000, backoffMs: 0, backoffMaxMs: 0 });
|
|
148
|
+
|
|
149
|
+
await assert.rejects(d.run(async () => 1, { ifConnected: true }), e => e.code === "not_connected", "nothing connected yet: fail at once");
|
|
150
|
+
await tick();
|
|
151
|
+
assert.equal(made.length, 1, "...and that started the connect in the background");
|
|
152
|
+
d.warm();
|
|
153
|
+
await tick();
|
|
154
|
+
assert.equal(made.length, 1, "warm() joins what is open");
|
|
155
|
+
assert.equal(await d.run(async c => c === made[0], { ifConnected: true }), true);
|
|
156
|
+
|
|
157
|
+
made[0].set("disconnected");
|
|
158
|
+
await tick(5);
|
|
159
|
+
assert.equal(made.length, 2, "a drop reconnects in the background, before any request");
|
|
160
|
+
assert.equal(await d.run(async c => c === made[1], { ifConnected: true }), true, "and the next request finds it connected");
|
|
161
|
+
|
|
162
|
+
up = false;
|
|
163
|
+
made[1].set("disconnected");
|
|
164
|
+
await tick(5);
|
|
165
|
+
up = true;
|
|
166
|
+
await tick(5);
|
|
167
|
+
assert.equal(made.length, 3, "a failed background open retries on the backoff");
|
|
168
|
+
|
|
169
|
+
t = 11_000;
|
|
170
|
+
assert.equal(await d.run(async c => c === made[2], { ifConnected: true }), true, "an aged connection keeps serving while its replacement opens");
|
|
171
|
+
await tick(5);
|
|
172
|
+
assert.equal(made.length, 4, "the replacement opened");
|
|
173
|
+
assert.equal(await d.run(async c => c === made[3], { ifConnected: true }), true, "and took over");
|
|
174
|
+
await tick();
|
|
175
|
+
assert.equal(made[2].state.status, "disposed", "the aged one closed once idle");
|
|
176
|
+
|
|
177
|
+
await d.close();
|
|
178
|
+
made[3].set("disconnected");
|
|
179
|
+
await tick(5);
|
|
180
|
+
assert.equal(made.length, 4, "nothing reopens after teardown");
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
test("the held daemon sender preserves a receipt that the high-level SDK drops", async () => {
|
|
185
|
+
const m = await load("server/daemon.ts", {
|
|
186
|
+
"./settings": { settings: { read: async () => ({}) } },
|
|
187
|
+
"./daemon-password": { resolveDaemonPassword: async () => undefined },
|
|
188
|
+
});
|
|
189
|
+
try {
|
|
190
|
+
const reply = await m.withPaseo(async (_paseo, sendMessage) => sendMessage("agent", "Follow up", { activeTurnBehavior: "steer" }));
|
|
191
|
+
assert.equal(reply.deliveryStatus, "queued");
|
|
192
|
+
assert.equal(reply.guidance, "After this turn");
|
|
193
|
+
} finally { await m.closeDaemon(); }
|
|
194
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Vendored from paseo-plugin-kit v0.4.0-beta.1 (daemon-endpoint/index.d.mts). Do not edit; change the kit and run `paseo-kit vendor daemon-endpoint <dir>`.
|
|
2
|
+
export interface DaemonEndpoint {
|
|
3
|
+
/** What the WebSocket opens: `ws://host:port/ws`, or `ws+unix://<path>:/ws` for a socket. */
|
|
4
|
+
url: string;
|
|
5
|
+
/** The socket or pipe path, or null for TCP. */
|
|
6
|
+
socketPath: string | null;
|
|
7
|
+
/** Origin of the plain HTTP endpoints for TCP (`http://host:port`); unused for a socket. */
|
|
8
|
+
httpOrigin: string;
|
|
9
|
+
/** Safe to log: no credentials, no query. */
|
|
10
|
+
address: string;
|
|
11
|
+
}
|
|
12
|
+
export type WebSocketConstructor = new (address: string, protocols: string[] | undefined, options: Record<string, unknown>) => any;
|
|
13
|
+
export type WebSocketFactory = (url: string, options?: { headers?: Record<string, string>; protocols?: string[] }) => any;
|
|
14
|
+
export declare const DEFAULT_LISTEN: string;
|
|
15
|
+
export declare const CLIENT_SPECIFIER: string;
|
|
16
|
+
export declare function endpointFromListen(listen: string | undefined, home?: string): DaemonEndpoint;
|
|
17
|
+
export declare function endpointFromUrl(url: string, home?: string): DaemonEndpoint;
|
|
18
|
+
export declare function resolveEndpoint(listen: string | undefined, env: Record<string, string | undefined> | undefined, home?: string): DaemonEndpoint;
|
|
19
|
+
export declare function safeAddress(url: string): string;
|
|
20
|
+
export declare function findWebSocket(bases?: Array<() => string>): WebSocketConstructor | null;
|
|
21
|
+
export declare function webSocketFactory(WebSocket: WebSocketConstructor, endpoint: DaemonEndpoint): WebSocketFactory;
|
|
22
|
+
export declare function describeConnectFailure(endpoint: DaemonEndpoint, error: unknown): string;
|
|
23
|
+
export declare function failureLog(log?: (line: string) => void): { failed(line: string): void; opened(): void };
|
|
24
|
+
export declare function daemonHttpGet(endpoint: DaemonEndpoint, path: string, timeoutMs: number): Promise<{ status: number; body: string }>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Vendored from paseo-plugin-kit v0.4.0-beta.1 (daemon-endpoint/index.mjs). Do not edit; change the kit and run `paseo-kit vendor daemon-endpoint <dir>`.
|
|
2
|
+
// Where a plugin's own daemon connection goes, for every way Paseo can listen, and how it reports a failure.
|
|
3
|
+
//
|
|
4
|
+
// `daemon.listen` takes the forms Paseo's own `parseListenString` does: a socket path (`/…`, `~/…`, `unix://…`), a
|
|
5
|
+
// Windows pipe (`\\.\pipe\…`, `pipe://…`), a bare port, `host:port`, `[v6]:port`, and a comma list whose first entry is
|
|
6
|
+
// the main listener. A plugin builds its DaemonClient (`url` plus `webSocketFactory`) and its plain HTTP reads
|
|
7
|
+
// (`daemonHttpGet`) from the one endpoint, so a form works for both or neither.
|
|
8
|
+
//
|
|
9
|
+
// Plain JavaScript (types in index.d.mts) so it runs anywhere a plugin's code does: Paseo's plugin compiler, a
|
|
10
|
+
// standalone bridge script, `node` with no flags.
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { request as httpRequest } from "node:http";
|
|
13
|
+
import { request as httpsRequest } from "node:https";
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_LISTEN = "127.0.0.1:6767";
|
|
16
|
+
export const CLIENT_SPECIFIER = ["@getpaseo", "client", "internal", "daemon-client"].join("/");
|
|
17
|
+
|
|
18
|
+
const bracket = host => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
|
|
19
|
+
|
|
20
|
+
/** The socket or pipe a listen value names, or null for TCP. Same rules as Paseo's `parseSocketTarget`. */
|
|
21
|
+
function socketTarget(listen, home) {
|
|
22
|
+
if (listen.startsWith("\\\\.\\pipe\\")) return { path: listen, pipe: true };
|
|
23
|
+
if (listen.startsWith("pipe://")) return { path: listen.slice("pipe://".length), pipe: true };
|
|
24
|
+
const path = listen.startsWith("unix://") ? listen.slice("unix://".length) : listen.startsWith("/") || listen.startsWith("~") ? listen : null;
|
|
25
|
+
return path === null ? null : { path: home ? path.replace(/^~(?=[/\\]|$)/, home) : path, pipe: false };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function socketEndpoint(path, pipe) {
|
|
29
|
+
// Paseo's CLI addresses a pipe as ws://localhost/ws plus the path; a UNIX socket needs ws+unix.
|
|
30
|
+
return { url: pipe ? "ws://localhost/ws" : `ws+unix://${path}:/ws`, socketPath: path, httpOrigin: "http://localhost", address: path };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The endpoint for a `daemon.listen` value (undefined or blank is Paseo's default). `home` expands a leading `~`. */
|
|
34
|
+
export function endpointFromListen(listen, home) {
|
|
35
|
+
const raw = (typeof listen === "string" ? listen.trim() : "") || DEFAULT_LISTEN;
|
|
36
|
+
const socket = socketTarget(raw, home);
|
|
37
|
+
if (socket) return socketEndpoint(socket.path, socket.pipe);
|
|
38
|
+
const main = raw.split(",", 1)[0].trim();
|
|
39
|
+
let hostPort;
|
|
40
|
+
if (/^\d+$/.test(main)) hostPort = `127.0.0.1:${main}`;
|
|
41
|
+
else {
|
|
42
|
+
const colon = main.lastIndexOf(":");
|
|
43
|
+
if (colon < 0) throw new Error(`daemon.listen is not an address this plugin understands: ${main}`);
|
|
44
|
+
const host = main.slice(0, colon).replace(/^\[(.*)\]$/, "$1") || "127.0.0.1";
|
|
45
|
+
hostPort = `${bracket(host)}:${main.slice(colon + 1)}`;
|
|
46
|
+
}
|
|
47
|
+
return { url: `ws://${hostPort}/ws`, socketPath: null, httpOrigin: `http://${hostPort}`, address: hostPort };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A URL without credentials, query or fragment, for a log line or an error. */
|
|
51
|
+
export function safeAddress(url) {
|
|
52
|
+
return String(url).replace(/\/\/[^/@]*@/, "//").replace(/[?#].*$/, "");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The endpoint for a `PASEO_DAEMON_URL`-style URL: `ws://`/`wss://` as given, or `ws+unix://<path>:/ws`. */
|
|
56
|
+
export function endpointFromUrl(url, home) {
|
|
57
|
+
if (url.startsWith("ws+unix://")) {
|
|
58
|
+
const path = url.slice("ws+unix://".length).replace(/:\/ws$/, "");
|
|
59
|
+
return socketEndpoint(home ? path.replace(/^~(?=[/\\]|$)/, home) : path, false);
|
|
60
|
+
}
|
|
61
|
+
let httpOrigin = "http://127.0.0.1:6767";
|
|
62
|
+
try {
|
|
63
|
+
const parsed = new URL(url);
|
|
64
|
+
httpOrigin = `${parsed.protocol === "wss:" ? "https:" : "http:"}//${parsed.host}`;
|
|
65
|
+
} catch {
|
|
66
|
+
// An invalid URL fails at connect, with the client's own reason.
|
|
67
|
+
}
|
|
68
|
+
return { url, socketPath: null, httpOrigin, address: safeAddress(url) };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** `env.PASEO_DAEMON_URL` when set, else `daemon.listen`. */
|
|
72
|
+
export function resolveEndpoint(listen, env, home) {
|
|
73
|
+
const override = env?.PASEO_DAEMON_URL;
|
|
74
|
+
return override ? endpointFromUrl(override, home) : endpointFromListen(listen, home);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The `ws` package Paseo's client ships with, or null. Node's built-in WebSocket (DaemonClient's default) cannot open a
|
|
79
|
+
* UNIX socket or a pipe. `bases` are tried in order, each a function returning a path to resolve `ws` from; the
|
|
80
|
+
* default is Paseo's client as Paseo's plugin runner (`process.argv[1]`) resolves it. Inside a plugin process the
|
|
81
|
+
* plugin's own `require.resolve` does not find the host's client, so don't rely on it alone.
|
|
82
|
+
*/
|
|
83
|
+
export function findWebSocket(bases = [() => createRequire(process.argv[1]).resolve(CLIENT_SPECIFIER)]) {
|
|
84
|
+
for (const base of bases) {
|
|
85
|
+
try {
|
|
86
|
+
const ws = createRequire(base())("ws");
|
|
87
|
+
return ws.WebSocket ?? ws;
|
|
88
|
+
} catch {
|
|
89
|
+
// Next base.
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** DaemonClient's `webSocketFactory`: the `ws` package, given the socket path for a socket or pipe. */
|
|
96
|
+
export function webSocketFactory(WebSocket, endpoint) {
|
|
97
|
+
return (url, options) =>
|
|
98
|
+
new WebSocket(url, options?.protocols, {
|
|
99
|
+
headers: options?.headers,
|
|
100
|
+
...(endpoint.socketPath ? { socketPath: endpoint.socketPath } : {}),
|
|
101
|
+
maxPayload: 100 * 1024 * 1024,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A failed connect as one line: where (no credentials) and the client's own reason. */
|
|
106
|
+
export function describeConnectFailure(endpoint, error) {
|
|
107
|
+
// An Error, a bare string, or an event-like object with a message; anything else (an ErrorEvent with no message) is unknown.
|
|
108
|
+
const raw = typeof error === "string" ? error : typeof error?.message === "string" ? error.message : "";
|
|
109
|
+
const reason = raw.replace(/\s+/g, " ").trim().slice(0, 300);
|
|
110
|
+
return `can't connect to Paseo at ${endpoint.address}: ${reason || "unknown error"}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Logs a connection failure once per cause: `failed(line)` logs a line that differs from the last one logged,
|
|
115
|
+
* `opened()` forgets it, so the next outage is logged again. A reconnect loop stays quiet while the cause holds.
|
|
116
|
+
*/
|
|
117
|
+
export function failureLog(log = line => console.error(line)) {
|
|
118
|
+
let last = null;
|
|
119
|
+
return {
|
|
120
|
+
failed(line) { if (line !== last) { last = line; log(line); } },
|
|
121
|
+
opened() { last = null; },
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** GET one of the daemon's plain HTTP endpoints (`/api/status`, `/api/health`) over the endpoint. */
|
|
126
|
+
export function daemonHttpGet(endpoint, path, timeoutMs) {
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
128
|
+
const origin = new URL(endpoint.httpOrigin);
|
|
129
|
+
const request = origin.protocol === "https:" ? httpsRequest : httpRequest;
|
|
130
|
+
const req = request(
|
|
131
|
+
endpoint.socketPath
|
|
132
|
+
? { socketPath: endpoint.socketPath, path, method: "GET", headers: { host: "localhost" } }
|
|
133
|
+
: { protocol: origin.protocol, hostname: origin.hostname.replace(/^\[(.*)\]$/, "$1"), port: origin.port || undefined, path, method: "GET" },
|
|
134
|
+
res => {
|
|
135
|
+
const chunks = [];
|
|
136
|
+
res.on("data", chunk => chunks.push(chunk));
|
|
137
|
+
res.on("end", () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
|
|
138
|
+
res.on("error", reject);
|
|
139
|
+
},
|
|
140
|
+
);
|
|
141
|
+
req.setTimeout(timeoutMs, () => req.destroy(new Error(`timed out after ${timeoutMs} ms`)));
|
|
142
|
+
req.on("error", reject);
|
|
143
|
+
req.end();
|
|
144
|
+
});
|
|
145
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// daemon-connection-reaches-every-listener (AGENTS.md): the plugin's wiring of the vendored kit module
|
|
2
|
+
// (server/daemon-endpoint, whose listen forms are tested in paseo-plugin-kit): every way Paseo can listen
|
|
3
|
+
// reaches the same connection path, for the WebSocket and the HTTP status read alike, and a failed open
|
|
4
|
+
// logs its real cause once. Before this the plugin built ws://${listen}/ws and opened it with Node's built-in
|
|
5
|
+
// WebSocket, so a daemon on a UNIX socket (or a listener list) was never reached, silently.
|
|
6
|
+
import test from "node:test";
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { build } from "esbuild";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import { createServer } from "node:http";
|
|
11
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
12
|
+
import { tmpdir } from "node:os";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
const realRequire = createRequire(import.meta.url);
|
|
15
|
+
const { WebSocketServer } = realRequire("ws");
|
|
16
|
+
|
|
17
|
+
async function load(path, stubs = {}, fakeModules = {}) {
|
|
18
|
+
const b = await build({ entryPoints: [path], bundle: true, write: false, platform: "node", format: "cjs", packages: "external", plugins: [{ name: "fixture", setup(b) { b.onResolve({ filter: /^\./ }, args => Object.hasOwn(stubs, args.path) ? { path: "fixture:" + args.path, external: true } : undefined); } }] });
|
|
19
|
+
const module = { exports: {} };
|
|
20
|
+
const req = id => id.startsWith("fixture:") ? stubs[id.slice(8)] : Object.hasOwn(fakeModules, id) ? fakeModules[id] : realRequire(id);
|
|
21
|
+
// The real client's location, so `ws` resolves beside it the way it does inside Paseo.
|
|
22
|
+
req.resolve = id => realRequire.resolve(id);
|
|
23
|
+
new Function("require", "module", "exports", b.outputFiles[0].text)(req, module, module.exports);
|
|
24
|
+
return module.exports;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
/** A stand-in daemon: /api/status and /api/health over HTTP, and a WebSocket on /ws, on one listener. */
|
|
29
|
+
async function fakeDaemon(listenArgs) {
|
|
30
|
+
const opened = [];
|
|
31
|
+
const server = createServer((req, res) => {
|
|
32
|
+
if (req.url === "/api/status") { res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ version: "0.99.0", serverId: "srv-example" })); return; }
|
|
33
|
+
if (req.url === "/api/health") { res.end("ok"); return; }
|
|
34
|
+
res.statusCode = 404; res.end();
|
|
35
|
+
});
|
|
36
|
+
const wss = new WebSocketServer({ server, path: "/ws" });
|
|
37
|
+
wss.on("connection", (_socket, req) => opened.push(req.url));
|
|
38
|
+
await new Promise((r, j) => { server.once("error", j); server.listen(...listenArgs, r); });
|
|
39
|
+
const address = server.address();
|
|
40
|
+
return { opened, port: typeof address === "object" ? address.port : null, async close() { for (const c of wss.clients) c.terminate(); await new Promise(r => wss.close(() => r())); await new Promise(r => server.close(() => r())); } };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
test("the plugin's one DaemonClient and its status read reach a daemon on a UNIX socket (no PASEO_DAEMON_URL)", async (t) => {
|
|
45
|
+
const root = await mkdtemp(join(tmpdir(), "stp-ep-"));
|
|
46
|
+
const daemon = await fakeDaemon([join(root, "paseo.sock")]);
|
|
47
|
+
const saved = { home: process.env.PASEO_HOME, url: process.env.PASEO_DAEMON_URL };
|
|
48
|
+
t.after(async () => { await daemon.close(); await rm(root, { recursive: true, force: true }); process.env.PASEO_HOME = saved.home; if (saved.url === undefined) delete process.env.PASEO_DAEMON_URL; else process.env.PASEO_DAEMON_URL = saved.url; });
|
|
49
|
+
process.env.PASEO_HOME = root;
|
|
50
|
+
delete process.env.PASEO_DAEMON_URL;
|
|
51
|
+
await writeFile(join(root, "config.json"), JSON.stringify({ daemon: { listen: join(root, "paseo.sock") } }));
|
|
52
|
+
const built = [];
|
|
53
|
+
// A client that connects the way DaemonClient does: its webSocketFactory when given, else the global WebSocket.
|
|
54
|
+
class FakeClient {
|
|
55
|
+
constructor(options) { this.options = options; built.push(options); this.state = { status: "idle" }; }
|
|
56
|
+
async connect() {
|
|
57
|
+
const factory = this.options.webSocketFactory ?? ((url) => new globalThis.WebSocket(url));
|
|
58
|
+
await new Promise((resolve, reject) => {
|
|
59
|
+
let socket;
|
|
60
|
+
try { socket = factory(this.options.url, {}); } catch (error) { reject(error); return; }
|
|
61
|
+
const on = (name, fn) => socket.once ? socket.once(name, fn) : socket.addEventListener(name, fn, { once: true });
|
|
62
|
+
on("open", () => { this.socket = socket; resolve(); });
|
|
63
|
+
on("error", (e) => reject(e?.error ?? e));
|
|
64
|
+
});
|
|
65
|
+
this.state = { status: "connected" };
|
|
66
|
+
}
|
|
67
|
+
async close() { this.socket?.close(); this.state = { status: "disposed" }; }
|
|
68
|
+
getConnectionState() { return this.state; }
|
|
69
|
+
async invokePluginRpc() { return null; }
|
|
70
|
+
}
|
|
71
|
+
const m = await load("server/daemon.ts", {
|
|
72
|
+
"./settings": { settings: { read: async () => ({}) } },
|
|
73
|
+
"./daemon-password": { resolveDaemonPassword: async () => undefined },
|
|
74
|
+
}, {
|
|
75
|
+
"@getpaseo/client": { createPaseoApi: () => ({ dispose: async () => {} }) },
|
|
76
|
+
"@getpaseo/client/internal/daemon-client": { DaemonClient: FakeClient },
|
|
77
|
+
});
|
|
78
|
+
try {
|
|
79
|
+
await m.withPaseo(async () => 1);
|
|
80
|
+
assert.equal(built.length, 1);
|
|
81
|
+
assert.equal(built[0].url, `ws+unix://${join(root, "paseo.sock")}:/ws`);
|
|
82
|
+
assert.equal(typeof built[0].webSocketFactory, "function", "the client is given the ws package's WebSocket");
|
|
83
|
+
assert.deepEqual(daemon.opened, ["/ws"]);
|
|
84
|
+
const status = await m.readDaemonStatus();
|
|
85
|
+
assert.deepEqual(status, { reachable: true, version: "0.99.0", serverId: "srv-example" });
|
|
86
|
+
} finally { await m.closeDaemon(); m.clearDaemonCaches(); }
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("a failed open logs its real cause once, again after a recovery or a new cause", async () => {
|
|
90
|
+
const { sharedDaemon } = await load("server/shared-daemon.ts");
|
|
91
|
+
let t = 0;
|
|
92
|
+
let failure = new Error("connect ENOENT /tmp/missing.sock");
|
|
93
|
+
const lines = [];
|
|
94
|
+
const d = sharedDaemon(async () => { if (failure) throw failure; return { close: async () => {} }; }, {
|
|
95
|
+
now: () => t, backoffMs: 1, backoffMaxMs: 1,
|
|
96
|
+
describeFailure: (e) => `[send-to-paseo] can't connect: ${e.message}`,
|
|
97
|
+
log: (l) => lines.push(l),
|
|
98
|
+
});
|
|
99
|
+
for (let i = 0; i < 5; i++) { t += 10; await assert.rejects(d.run(async () => 1)); }
|
|
100
|
+
assert.deepEqual(lines, ["[send-to-paseo] can't connect: connect ENOENT /tmp/missing.sock"], "five retries, one line");
|
|
101
|
+
failure = new Error("Password required"); t += 10;
|
|
102
|
+
await assert.rejects(d.run(async () => 1));
|
|
103
|
+
assert.equal(lines.length, 2, "a new cause is logged");
|
|
104
|
+
failure = null; t += 10;
|
|
105
|
+
await d.run(async () => 1);
|
|
106
|
+
await d.close();
|
|
107
|
+
const again = sharedDaemon(async () => { throw new Error("connect ECONNREFUSED 127.0.0.1:6767"); }, { log: (l) => lines.push(l) });
|
|
108
|
+
await assert.rejects(again.run(async () => 1));
|
|
109
|
+
assert.equal(lines.at(-1), "connect ECONNREFUSED 127.0.0.1:6767", "the default line is the client's own reason");
|
|
110
|
+
await again.close();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("a failed open through daemon.ts names the address and the client's reason, never the password", async (t) => {
|
|
114
|
+
const root = await mkdtemp(join(tmpdir(), "stp-ep-"));
|
|
115
|
+
const saved = { home: process.env.PASEO_HOME, url: process.env.PASEO_DAEMON_URL };
|
|
116
|
+
t.after(async () => { await rm(root, { recursive: true, force: true }); process.env.PASEO_HOME = saved.home; if (saved.url === undefined) delete process.env.PASEO_DAEMON_URL; else process.env.PASEO_DAEMON_URL = saved.url; });
|
|
117
|
+
process.env.PASEO_HOME = root;
|
|
118
|
+
delete process.env.PASEO_DAEMON_URL;
|
|
119
|
+
await writeFile(join(root, "config.json"), JSON.stringify({ daemon: { listen: join(root, "gone.sock") } }));
|
|
120
|
+
class FailingClient { constructor(o) { this.o = o; } async connect() { throw new Error("connect ENOENT " + join(root, "gone.sock")); } async close() {} }
|
|
121
|
+
const m = await load("server/daemon.ts", {
|
|
122
|
+
"./settings": { settings: { read: async () => ({}) } },
|
|
123
|
+
"./daemon-password": { resolveDaemonPassword: async () => "hunter2-example" },
|
|
124
|
+
}, {
|
|
125
|
+
"@getpaseo/client": { createPaseoApi: () => ({ dispose: async () => {} }) },
|
|
126
|
+
"@getpaseo/client/internal/daemon-client": { DaemonClient: FailingClient },
|
|
127
|
+
});
|
|
128
|
+
const errors = [];
|
|
129
|
+
const original = console.error;
|
|
130
|
+
console.error = (...a) => errors.push(a.join(" "));
|
|
131
|
+
try {
|
|
132
|
+
for (let i = 0; i < 3; i++) await assert.rejects(m.withPaseo(async () => 1), /not reachable/);
|
|
133
|
+
} finally { console.error = original; await m.closeDaemon(); }
|
|
134
|
+
assert.equal(errors.length, 1, `logged once, got ${JSON.stringify(errors)}`);
|
|
135
|
+
assert.match(errors[0], /can't connect to Paseo at .*gone\.sock: connect ENOENT/);
|
|
136
|
+
assert.doesNotMatch(errors[0], /hunter2/);
|
|
137
|
+
});
|
package/server/daemon.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { resolveDaemonPassword } from "./daemon-password";
|
|
|
8
8
|
import { settings } from "./settings";
|
|
9
9
|
import { invokeFollowUp } from "./follow-up-id";
|
|
10
10
|
import { sharedDaemon } from "./shared-daemon";
|
|
11
|
-
import { daemonHttpGet, describeConnectFailure, resolveEndpoint, webSocketFactory, type DaemonEndpoint } from "./daemon-endpoint";
|
|
11
|
+
import { CLIENT_SPECIFIER, daemonHttpGet, describeConnectFailure, findWebSocket, resolveEndpoint, webSocketFactory, type DaemonEndpoint } from "./daemon-endpoint/index.mjs";
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* The plugin's one held daemon connection (one-held-daemon-connection, AGENTS.md).
|
|
@@ -87,20 +87,12 @@ function loadClientModule(): ClientModule {
|
|
|
87
87
|
clientModule = { createPaseoApi, DaemonClient };
|
|
88
88
|
// Resolved beside Paseo's own client, so the plugin still adds no dependency
|
|
89
89
|
// (daemon-connection-reaches-every-listener): Node's built-in WebSocket, the
|
|
90
|
-
// client's default, cannot open a UNIX socket or a pipe.
|
|
91
|
-
//
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
try {
|
|
97
|
-
const ws = createRequire(base())("ws") as { WebSocket?: new (...args: any[]) => unknown };
|
|
98
|
-
wsModule = ws.WebSocket ?? (ws as unknown as new (...args: any[]) => unknown);
|
|
99
|
-
break;
|
|
100
|
-
} catch {
|
|
101
|
-
// Try the next base; none means the client keeps its default WebSocket.
|
|
102
|
-
}
|
|
103
|
-
}
|
|
90
|
+
// client's default, cannot open a UNIX socket or a pipe. Paseo's plugin runner
|
|
91
|
+
// is the reliable base; the module's own require.resolve is the fallback.
|
|
92
|
+
wsModule = findWebSocket([
|
|
93
|
+
() => createRequire(process.argv[1] ?? join(process.cwd(), "noop.cjs")).resolve(CLIENT_SPECIFIER),
|
|
94
|
+
() => load.resolve(internal),
|
|
95
|
+
]);
|
|
104
96
|
} catch (error) {
|
|
105
97
|
throw new BridgeError(
|
|
106
98
|
"daemon_unreachable",
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { build } from "esbuild";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
const require = createRequire(import.meta.url);
|
|
6
|
+
async function load(path, stubs) {
|
|
7
|
+
const b = await build({ entryPoints: [path], bundle: true, write: false, platform: "node", format: "cjs", packages: "external", plugins: [{ name: "fixture", setup(b) { b.onResolve({ filter: /^\./ }, args => Object.hasOwn(stubs, args.path) ? { path: "fixture:" + args.path, external: true } : undefined); } }] });
|
|
8
|
+
const module = { exports: {} }; new Function("require", "module", "exports", b.outputFiles[0].text)(id => id.startsWith("fixture:") ? stubs[id.slice(8)] : require(id), module, module.exports); return module.exports;
|
|
9
|
+
}
|
|
10
|
+
const agent = (id, patch = {}) => ({ id, workspaceId: "owned-workspace", title: id, labels: {}, archivedAt: null, status: "idle", provider: "fixture", model: null, ...patch });
|
|
11
|
+
test("optional owner lookup fails closed for absent, old, broken or malformed companions", async () => {
|
|
12
|
+
for (const reply of [null, {}, { owner: { workspaceId: "w" } }, new Error("Plugin not installed")]) {
|
|
13
|
+
const m = await load("server/follow-up.ts", { "./daemon": { callFollowUp: async () => { if (reply instanceof Error) throw reply; return reply; } } });
|
|
14
|
+
assert.equal(await m.lookupPrOwner("example", "app", 1), null);
|
|
15
|
+
}
|
|
16
|
+
const m = await load("server/follow-up.ts", { "./daemon": { callFollowUp: async (method, input) => { assert.equal(method, "follow.pr-owner"); assert.deepEqual(input, { repo: "example/app", number: 1 }); return { owner: { workspaceId: "owned-workspace", agentId: "owner" } }; } } });
|
|
17
|
+
const owner = await m.lookupPrOwner("example", "app", 1);
|
|
18
|
+
assert.equal(m.registeredAgent([agent("owner"), agent("newest")], owner, "owned-workspace").id, "owner");
|
|
19
|
+
assert.equal(m.registeredAgent([agent("owner", { archivedAt: "yesterday" })], owner, "owned-workspace"), null);
|
|
20
|
+
assert.equal(m.registeredAgent([agent("owner")], owner, "foreign"), null);
|
|
21
|
+
});
|
|
22
|
+
test("send steers the registering agent ahead of a newer main agent, and explicit new-agent sends still work", async () => {
|
|
23
|
+
let owner = { workspaceId: "owned-workspace", agentId: "registered" };
|
|
24
|
+
let receipt = { deliveryStatus: "queued", guidance: "Queued for after the current turn." };
|
|
25
|
+
let agents = [agent("registered"), agent("newest-main", { title: "Main" })]; const sent = []; const created = [];
|
|
26
|
+
const workspace = { id: "owned-workspace", name: "Owned", workspaceDirectory: "/fixture", gitRuntime: { currentBranch: "feature" } };
|
|
27
|
+
const paseo = { agents: { ref: a => ({ send: async (prompt, options) => sent.push({ id: a.id, prompt, options }) }) }, workspaces: { list: async () => ({ entries: [workspace] }), ref: () => ({ agents: { create: async input => { created.push(input); return { id: "new-agent" }; } } }) } };
|
|
28
|
+
const m = await load("server/send.ts", {
|
|
29
|
+
"./daemon": { withPaseo: f => f(paseo, async (id, prompt, options) => { sent.push({ id, prompt, options }); return receipt; }), requireServerId: async () => "server" },
|
|
30
|
+
"./follow-up": { lookupPrOwner: async () => owner, registeredAgent: (all, o, w) => all.find(a => o && a.id === o.agentId && o.workspaceId === w && a.workspaceId === w && a.archivedAt == null) ?? null },
|
|
31
|
+
"./gh": { lookupPr: async () => ({ pr: { number: 1, title: "Fixture", headBranch: "feature", baseBranch: "main", state: "OPEN", url: "https://github.com/example/app/pull/1" }, outage: null }) },
|
|
32
|
+
"./settings": { settings: { read: async () => ({ agentDispatch: "new" }), recordSend: async () => {} } },
|
|
33
|
+
"./resolve": { resolveProject: async () => ({ projectId: "project", name: "app", path: "/fixture" }), listProjectWorkspaces: async () => [workspace], resolveSelectedProfile: async () => null, resolveDefaultProvider: async () => "fixture", resolveDefaultMode: async () => undefined, profileProviderId: () => null },
|
|
34
|
+
"./main-agent": { listProjectAgents: async () => agents, selectMainAgent: all => all.find(a => a.title === "Main") ?? null, agentDisplayTitle: a => a.title, agentProvider: a => a.provider },
|
|
35
|
+
});
|
|
36
|
+
const request = { forge: "github", owner: "example", repo: "app", number: 1, prompt: "Fix conflicts", target: { kind: "existing", workspaceId: workspace.id } };
|
|
37
|
+
const sentOwner = await m.handleSend({ ...request, agentDispatch: "main", followUpAgentId: "registered" }); assert.equal(sentOwner.agentId, "registered"); assert.equal(sent[0].options.activeTurnBehavior, "steer"); assert.equal(created.length, 0);
|
|
38
|
+
assert.equal(sentOwner.deliveryStatus, "queued"); assert.equal(sentOwner.guidance, receipt.guidance);
|
|
39
|
+
receipt = undefined;
|
|
40
|
+
const old = await m.handleSend({ ...request, agentDispatch: "main" });
|
|
41
|
+
assert.equal("deliveryStatus" in old, false); assert.equal("guidance" in old, false);
|
|
42
|
+
assert.equal((await m.handleSend({ ...request, agentDispatch: "new" })).agentId, "new-agent"); assert.equal(created.length, 1);
|
|
43
|
+
owner = null;
|
|
44
|
+
await assert.rejects(m.handleSend({ ...request, agentDispatch: "main", followUpAgentId: "registered" }), /registration changed/); assert.equal(sent.length, 2);
|
|
45
|
+
assert.equal((await m.handleSend(request)).agentId, "new-agent", "standalone default still creates a new agent");
|
|
46
|
+
assert.equal((await m.handleSend({ ...request, agentDispatch: "main" })).agentId, "newest-main");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("browser transport keeps repository grants and receipts on their exact route, with one fair lease slot", async () => {
|
|
50
|
+
const calls = [];
|
|
51
|
+
const m = await load("server/browser-bridge.ts", {
|
|
52
|
+
"./daemon": { readDaemonStatus: async () => ({ serverId: "local-server" }), callFollowUp: async (_method, input) => { calls.push({ route: "local", input }); return { jobs: [], accepted: input.results.map(r => r.id), repositories: ["example/local"] }; } },
|
|
53
|
+
"./settings": { settings: { read: async () => ({ additionalMachines: [{ id: "vm", label: "VM", enabled: true }, { id: "other", label: "Other", enabled: true }] }) } },
|
|
54
|
+
"./peers": { exchangeBrowserOnMachine: async (machine, input) => { calls.push({ route: machine.id, input }); return { routes: [{ routeId: "local", serverId: machine.id + "-server", available: true, repositories: ["example/remote"], jobs: [], accepted: [] }] }; } },
|
|
55
|
+
});
|
|
56
|
+
const input = { clientId: "browser", ready: true, acceptJobs: true, routes: [{ routeId: "local", serverId: "local-server", repositories: ["example/local"] }, { routeId: "vm", serverId: "vm-server", repositories: ["example/remote"] }], results: [{ routeId: "vm", id: "receipt", nonce: "nonce", outcome: "failed", prs: [], applied: [], error: "cancelled" }] };
|
|
57
|
+
const first = await m.exchangeBrowser(input, false);
|
|
58
|
+
assert.deepEqual(first.routes.map(r => r.routeId), ["local", "vm", "other"]);
|
|
59
|
+
assert.deepEqual(first.routes[0].repositories, ["example/local"]);
|
|
60
|
+
assert.deepEqual(first.routes[1].repositories, ["example/remote"]);
|
|
61
|
+
assert.equal(calls.filter(c => c.input.acceptJobs).length, 1); assert.equal(calls.find(c => c.input.acceptJobs).route, "local");
|
|
62
|
+
assert.deepEqual(calls.find(c => c.route === "local").input.repositories, ["example/local"]);
|
|
63
|
+
assert.equal(calls.find(c => c.route === "local").input.results.length, 0);
|
|
64
|
+
const remote = calls.find(c => c.route === "vm").input;
|
|
65
|
+
assert.deepEqual(remote.routes, [{ routeId: "local", serverId: "vm-server", repositories: ["example/remote"] }]);
|
|
66
|
+
assert.equal(remote.results[0].routeId, "local");
|
|
67
|
+
assert.deepEqual(calls.find(c => c.route === "other").input.routes, []);
|
|
68
|
+
calls.length = 0; await m.exchangeBrowser(input, false);
|
|
69
|
+
assert.equal(calls.filter(c => c.input.acceptJobs).length, 1); assert.equal(calls.find(c => c.input.acceptJobs).route, "vm");
|
|
70
|
+
calls.length = 0; await m.exchangeBrowser(input, true);
|
|
71
|
+
assert.deepEqual(calls.map(c => c.route), ["local"], "Additional daemons do not recurse");
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("the registered workspace may select a second clone of the same repository, while foreign projects stay excluded", async () => {
|
|
75
|
+
const first = { projectId: "prj_first", projectKind: "git", projectDisplayName: "First", projectRootPath: "/first" };
|
|
76
|
+
const owned = { projectId: "prj_owned", projectKind: "git", projectDisplayName: "Owned", projectRootPath: "/owned" };
|
|
77
|
+
const foreign = { projectId: "prj_foreign", projectKind: "git", projectDisplayName: "Foreign", projectRootPath: "/foreign" };
|
|
78
|
+
const m = await load("server/resolve.ts", { "./git": { readOriginOwnerRepo: async path => ({ owner: path === "/foreign" ? "foreign" : "example", repo: "app" }) }, "./daemon": {} });
|
|
79
|
+
const paseo = { projects: { list: async () => ({ projects: [first, owned, foreign] }) } };
|
|
80
|
+
const ref = { owner: "example", repo: "app" };
|
|
81
|
+
assert.equal((await m.resolveProject(paseo, ref, owned.projectId)).projectId, owned.projectId);
|
|
82
|
+
assert.equal((await m.resolveProject(paseo, ref, foreign.projectId)).projectId, first.projectId);
|
|
83
|
+
assert.equal((await m.resolveProject(paseo, ref, "deleted")).projectId, first.projectId);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("an Additional bridge downgrade refuses a registered-agent send before forwarding it", async () => {
|
|
87
|
+
const m = await load("server/peers.ts", {});
|
|
88
|
+
const original = globalThis.fetch; const paths = [];
|
|
89
|
+
globalThis.fetch = async url => {
|
|
90
|
+
paths.push(new URL(url).pathname);
|
|
91
|
+
return Response.json({ ok: true, name: "send-to-paseo", contract: 1, paired: true, daemon: { serverId: "additional" } });
|
|
92
|
+
};
|
|
93
|
+
try {
|
|
94
|
+
await assert.rejects(m.sendToMachine({ id: "vm", label: "Fixture", machineName: "Fixture", bridgeUrl: "https://fixture.invalid", token: "synthetic-token", serverId: "additional", enabled: true }, { forge: "github", owner: "example", repo: "app", number: 1, prompt: "Synthetic", target: { kind: "existing", workspaceId: "owned" }, agentDispatch: "main", followUpAgentId: "registered" }), /Update Send to Paseo/);
|
|
95
|
+
assert.deepEqual(paths, ["/v1/ping"]);
|
|
96
|
+
} finally { globalThis.fetch = original; }
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const view = (id, patch = {}) => ({ workspaceId: id, agentId: `agent-${id}`, title: `Follow-up ${id}`, agentStatus: "idle", group: "waiting", state: "Waiting on others", ...patch });
|
|
100
|
+
const unreachable = message => Object.assign(new Error(message), { code: "follow_up_unreachable" });
|
|
101
|
+
const isFollowUpUnreachable = e => e?.code === "follow_up_unreachable";
|
|
102
|
+
const workspacesModule = reply => load("server/follow-up.ts", { "./daemon": { isFollowUpUnreachable, callFollowUp: async (method, input, options) => {
|
|
103
|
+
assert.equal(method, "follow.pr-workspaces"); assert.deepEqual(input, { repo: "example/app", number: 7 });
|
|
104
|
+
assert.deepEqual(options, { ifConnected: true }, "the popover's lookup never waits on a daemon connect");
|
|
105
|
+
if (reply instanceof Error) throw reply; return reply;
|
|
106
|
+
} } });
|
|
107
|
+
test("PR workspaces lookup: owner found, several owners, none, repository not granted, Follow-up absent", async () => {
|
|
108
|
+
const one = await (await workspacesModule({ tracked: true, more: 0, workspaces: [view("w1", { group: "needs", state: "Needs you · Merge ready" })] })).lookupPrWorkspaces("example", "app", 7);
|
|
109
|
+
assert.deepEqual(one, { more: 0, workspaces: [view("w1", { group: "needs", state: "Needs you · Merge ready" })] });
|
|
110
|
+
const several = await (await workspacesModule({ tracked: true, more: 2, workspaces: [view("a"), view("b"), view("c")] })).lookupPrWorkspaces("example", "app", 7);
|
|
111
|
+
assert.deepEqual([several.workspaces.map(w => w.workspaceId), several.more], [["a", "b", "c"], 2]);
|
|
112
|
+
assert.deepEqual(await (await workspacesModule({ tracked: true, more: 0, workspaces: [] })).lookupPrWorkspaces("example", "app", 7), { workspaces: [], more: 0 }, "tracked repository, no owner: say so");
|
|
113
|
+
assert.equal(await (await workspacesModule({ tracked: false, more: 0, workspaces: [] })).lookupPrWorkspaces("example", "app", 7), null, "outside Follow-up's advertised scope: nothing");
|
|
114
|
+
for (const reply of [new Error("Plugin follow-up is not installed"), new Error("Unknown RPC follow.pr-workspaces"), null, {}, { tracked: true, more: 0, workspaces: [view("a"), view("b"), view("c"), view("d")] }, { tracked: true, more: 0, workspaces: [{ workspaceId: "w" }] }])
|
|
115
|
+
assert.equal(await (await workspacesModule(reply)).lookupPrWorkspaces("example", "app", 7), null, `fails closed for ${JSON.stringify(reply) ?? reply}`);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// follow-up-tone-passes-through (AGENTS.md): zod strips unknown keys, so a Follow-up row's `tone` never reached
|
|
119
|
+
// the browser and the page button would have had to parse Follow-up's English to colour itself.
|
|
120
|
+
test("PR workspaces lookup keeps Follow-up's tone, and drops an unknown one without dropping the row", async () => {
|
|
121
|
+
const toned = await (await workspacesModule({ tracked: true, more: 0, workspaces: [view("w1", { group: "needs", state: "Needs you · Conflict", tone: "danger" })] })).lookupPrWorkspaces("example", "app", 7);
|
|
122
|
+
assert.equal(toned.workspaces[0].tone, "danger");
|
|
123
|
+
const odd = await (await workspacesModule({ tracked: true, more: 0, workspaces: [view("w1", { tone: "chartreuse" })] })).lookupPrWorkspaces("example", "app", 7);
|
|
124
|
+
assert.deepEqual([odd.workspaces.length, "tone" in odd.workspaces[0] && odd.workspaces[0].tone !== undefined], [1, false]);
|
|
125
|
+
const m = await workspacesModule({ tracked: true, more: 0, workspaces: [] });
|
|
126
|
+
const out = m.followUpView({ more: 0, workspaces: [view("w1", { tone: "success" })] }, "srv", new Map());
|
|
127
|
+
assert.equal(out.workspaces[0].tone, "success", "the resolve answer carries it to the extension");
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// optional-lookup-never-silent (AGENTS.md): 2.4.1 turned a timed-out lookup into null, the same answer as
|
|
131
|
+
// "Follow-up absent", and the popover's "Workspace for this PR" section silently vanished.
|
|
132
|
+
test("PR workspaces lookup: couldn't ask in time is unknown, never none", async () => {
|
|
133
|
+
for (const error of [unreachable("Optional Follow Up request timed out."), unreachable("The Paseo daemon connection is not open yet."), unreachable("socket closed")])
|
|
134
|
+
assert.equal(await (await workspacesModule(error)).lookupPrWorkspaces("example", "app", 7), "unknown", error.message);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("resolve's Follow-up fields: unknown is said, and the registered owner still gets its Open link", async () => {
|
|
138
|
+
const m = await load("server/follow-up.ts", { "./daemon": { isFollowUpUnreachable, callFollowUp: async () => null } });
|
|
139
|
+
const names = new Map([["owned", "brawny-dodo"]]);
|
|
140
|
+
const owner = { workspaceId: "owned", agentId: "agt_reg" };
|
|
141
|
+
const candidate = { kind: "existing", workspaceId: "owned", label: "brawny-dodo", followUpAgent: { agentId: "agt_reg", title: "Registered", status: "idle" } };
|
|
142
|
+
const plain = { kind: "existing", workspaceId: "owned", label: "brawny-dodo" };
|
|
143
|
+
|
|
144
|
+
assert.deepEqual(m.followUpAnswer("unknown", owner, [candidate], "srv", names), {
|
|
145
|
+
followUpUnreachable: true,
|
|
146
|
+
followUp: { more: 0, workspaces: [{ workspaceId: "owned", agentId: "agt_reg", title: "brawny-dodo", agentStatus: "idle", group: "", state: "", deepLink: "paseo://h/srv/agent/agt_reg", webUrl: "https://app.paseo.sh/h/srv/agent/agt_reg" }] },
|
|
147
|
+
}, "unknown + a registered owner among the candidates: that owner's row with both links");
|
|
148
|
+
assert.deepEqual(m.followUpAnswer("unknown", null, [candidate], "srv", names), { followUpUnreachable: true }, "unknown, no owner: say unknown");
|
|
149
|
+
assert.deepEqual(m.followUpAnswer("unknown", owner, [plain], "srv", names), { followUpUnreachable: true }, "owner's agent is not a candidate: no row");
|
|
150
|
+
assert.deepEqual(m.followUpAnswer("unknown", owner, [candidate], null, names), { followUpUnreachable: true }, "no server id: no link, still unknown");
|
|
151
|
+
assert.deepEqual(m.followUpAnswer(null, owner, [candidate], "srv", names), {}, "Follow-up absent or repo untracked: no fields at all");
|
|
152
|
+
assert.deepEqual(m.followUpAnswer({ workspaces: [], more: 0 }, owner, [candidate], "srv", names), { followUp: { workspaces: [], more: 0 } }, "tracked, nothing owns it: the real none");
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test("the popover view carries Paseo's workspace name and both open links for this machine only", async () => {
|
|
156
|
+
const m = await load("server/follow-up.ts", { "./daemon": { callFollowUp: async () => null } });
|
|
157
|
+
const found = { more: 1, workspaces: [view("w1"), view("w2", { title: "" })] };
|
|
158
|
+
const out = m.followUpView(found, "srv/main", new Map([["w1", "brawny-dodo"]]));
|
|
159
|
+
assert.deepEqual(out.workspaces.map(w => [w.title, w.deepLink, w.webUrl]), [
|
|
160
|
+
["brawny-dodo", "paseo://h/srv%2Fmain/agent/agent-w1", "https://app.paseo.sh/h/srv%2Fmain/agent/agent-w1"],
|
|
161
|
+
["w2", "paseo://h/srv%2Fmain/agent/agent-w2", "https://app.paseo.sh/h/srv%2Fmain/agent/agent-w2"],
|
|
162
|
+
]);
|
|
163
|
+
assert.equal(out.more, 1);
|
|
164
|
+
assert.equal(m.followUpView(found, null, new Map()), undefined, "no server id, no links, no section");
|
|
165
|
+
assert.equal(m.followUpView(null, "srv", new Map()), undefined);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test("agent links: desktop deep link and web link share one encoded route", async () => {
|
|
169
|
+
const m = await load("shared/contracts.ts", {});
|
|
170
|
+
for (const [serverId, agentId, route] of [["srv_abc", "agt_1", "/h/srv_abc/agent/agt_1"], [" srv pad ", " a/b?c#d ", "/h/srv%20pad/agent/a%2Fb%3Fc%23d"]]) {
|
|
171
|
+
assert.equal(m.buildAgentDeepLink({ serverId, agentId }), `paseo:/${route}`);
|
|
172
|
+
assert.equal(m.buildAgentWebLink({ serverId, agentId }), `https://app.paseo.sh${route}`);
|
|
173
|
+
}
|
|
174
|
+
assert.throws(() => m.buildAgentWebLink({ serverId: " ", agentId: "a" }), /server ID/);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test("an Additional machine receives the Follow-up opt-in with the resolve it is asked", async () => {
|
|
178
|
+
const m = await load("server/peers.ts", {});
|
|
179
|
+
const original = globalThis.fetch; const bodies = [];
|
|
180
|
+
globalThis.fetch = async (url, init) => {
|
|
181
|
+
if (new URL(url).pathname === "/v1/ping") return Response.json({ ok: true, name: "send-to-paseo", contract: 1, paired: true, providers: [], daemon: { reachable: true, serverId: "additional" } });
|
|
182
|
+
bodies.push(JSON.parse(init.body));
|
|
183
|
+
return Response.json({ error: { code: "project_not_found", message: "Synthetic" } }, { status: 404 });
|
|
184
|
+
};
|
|
185
|
+
try {
|
|
186
|
+
await m.resolveOnMachine({ id: "vm", label: "Fixture", machineName: "Fixture", bridgeUrl: "https://fixture.invalid", token: "synthetic-token", serverId: "additional", enabled: true }, { forge: "github", owner: "example", repo: "app", number: 7, followUp: true });
|
|
187
|
+
assert.equal(bodies[0]?.followUp, true);
|
|
188
|
+
} finally { globalThis.fetch = original; }
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test("Follow-up's id: calls only follow-up and preserves the method and input", async () => {
|
|
192
|
+
const fresh = async () => (await load("server/follow-up-id.ts", {})).invokeFollowUp;
|
|
193
|
+
const calls = [];
|
|
194
|
+
const invoke = async (id, method, input) => { calls.push(id); return { id, method, input }; };
|
|
195
|
+
assert.deepEqual(await (await fresh())(invoke, "follow.pr-owner", { n: 1 }), { id: "follow-up", method: "follow.pr-owner", input: { n: 1 } });
|
|
196
|
+
assert.deepEqual(calls, ["follow-up"]);
|
|
197
|
+
calls.length = 0;
|
|
198
|
+
await assert.rejects((await fresh())(async id => { calls.push(id); throw new Error(`Plugin is not available: ${id}`); }, "m", {}), /not available: follow-up/);
|
|
199
|
+
assert.deepEqual(calls, ["follow-up"], "an absent plugin is probed only once");
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("Follow-up's id: repeated successful calls keep using follow-up", async () => {
|
|
203
|
+
const { invokeFollowUp } = await load("server/follow-up-id.ts", {});
|
|
204
|
+
const calls = [];
|
|
205
|
+
for (let n = 0; n < 20; n++) assert.equal(await invokeFollowUp(async id => { calls.push(id); return id; }, "m", {}), "follow-up");
|
|
206
|
+
assert.deepEqual(calls, Array(20).fill("follow-up"));
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("Follow-up's id: real errors are propagated and never cached as absence", async () => {
|
|
210
|
+
const { invokeFollowUp } = await load("server/follow-up-id.ts", {});
|
|
211
|
+
for (const error of [new Error("Unknown RPC"), new Error("Timed out")]) {
|
|
212
|
+
const calls = [];
|
|
213
|
+
for (let n = 0; n < 2; n++)
|
|
214
|
+
await assert.rejects(invokeFollowUp(async id => { calls.push(id); throw error; }, "m", {}), error);
|
|
215
|
+
assert.deepEqual(calls, ["follow-up", "follow-up"]);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("Follow-up's id: absence is cached briefly and recovers after the cache expires", async () => {
|
|
220
|
+
let clock = 1_000;
|
|
221
|
+
const { invokeFollowUp } = await load("server/follow-up-id.ts", {});
|
|
222
|
+
const calls = [];
|
|
223
|
+
let installed = false;
|
|
224
|
+
const invoke = async id => { calls.push(id); if (!installed) throw new Error(`Plugin is not available: ${id}`); return id; };
|
|
225
|
+
for (let n = 0; n < 10; n++) await assert.rejects(invokeFollowUp(invoke, "m", {}, () => clock), /not available/);
|
|
226
|
+
assert.deepEqual(calls, ["follow-up"]);
|
|
227
|
+
clock += 30_000;
|
|
228
|
+
await assert.rejects(invokeFollowUp(invoke, "m", {}, () => clock), /not available/);
|
|
229
|
+
assert.equal(calls.length, 2, "re-probed when the cache expires");
|
|
230
|
+
installed = true; clock += 30_000;
|
|
231
|
+
assert.equal(await invokeFollowUp(invoke, "m", {}, () => clock), "follow-up");
|
|
232
|
+
assert.equal(calls.length, 3);
|
|
233
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
|
|
4
|
+
import { agentDisplayTitle, agentProvider, selectMainAgent } from "./main-agent.ts";
|
|
5
|
+
|
|
6
|
+
function agent(id, overrides = {}) {
|
|
7
|
+
return {
|
|
8
|
+
id,
|
|
9
|
+
workspaceId: "wks_target",
|
|
10
|
+
title: id,
|
|
11
|
+
labels: {},
|
|
12
|
+
status: "idle",
|
|
13
|
+
archivedAt: null,
|
|
14
|
+
lastUserMessageAt: "2026-09-20T12:00:00.000Z",
|
|
15
|
+
updatedAt: "2026-09-20T12:00:00.000Z",
|
|
16
|
+
createdAt: "2026-09-20T12:00:00.000Z",
|
|
17
|
+
provider: "claude",
|
|
18
|
+
model: "claude-opus-5-5",
|
|
19
|
+
...overrides,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
test("main-agent selection excludes archived, foreign-workspace, and delegated agents", () => {
|
|
24
|
+
const picked = selectMainAgent(
|
|
25
|
+
[
|
|
26
|
+
agent("archived-main", { title: "Main", archivedAt: "2026-09-21T00:00:00.000Z" }),
|
|
27
|
+
agent("foreign-main", { title: "Main", workspaceId: "wks_other" }),
|
|
28
|
+
agent("delegated-main", {
|
|
29
|
+
title: "Main",
|
|
30
|
+
labels: { "paseo.parent-agent-id": "agt_parent" },
|
|
31
|
+
}),
|
|
32
|
+
agent("eligible-root"),
|
|
33
|
+
],
|
|
34
|
+
"wks_target",
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
assert.equal(picked?.id, "eligible-root");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("an explicitly named Main root agent is the strongest user signal", () => {
|
|
41
|
+
const picked = selectMainAgent(
|
|
42
|
+
[
|
|
43
|
+
agent("new-running", {
|
|
44
|
+
status: "running",
|
|
45
|
+
lastUserMessageAt: "2026-09-23T12:00:00.000Z",
|
|
46
|
+
}),
|
|
47
|
+
agent("named-main", {
|
|
48
|
+
title: " MAIN AGENT ",
|
|
49
|
+
status: "closed",
|
|
50
|
+
lastUserMessageAt: "2026-09-01T12:00:00.000Z",
|
|
51
|
+
}),
|
|
52
|
+
],
|
|
53
|
+
"wks_target",
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
assert.equal(picked?.id, "named-main");
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("an open Paseo tab wins when no agent is explicitly named Main", () => {
|
|
60
|
+
const picked = selectMainAgent(
|
|
61
|
+
[
|
|
62
|
+
agent("running", { status: "running" }),
|
|
63
|
+
agent("open-tab", {
|
|
64
|
+
status: "idle",
|
|
65
|
+
labels: { "paseo.open-agent-tab.window-1": "true" },
|
|
66
|
+
}),
|
|
67
|
+
],
|
|
68
|
+
"wks_target",
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
assert.equal(picked?.id, "open-tab");
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("runtime state, user activity, and id make the fallback deterministic", () => {
|
|
75
|
+
assert.equal(
|
|
76
|
+
selectMainAgent(
|
|
77
|
+
[agent("idle-newer", { status: "idle" }), agent("running-older", { status: "running" })],
|
|
78
|
+
"wks_target",
|
|
79
|
+
)?.id,
|
|
80
|
+
"running-older",
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
assert.equal(
|
|
84
|
+
selectMainAgent(
|
|
85
|
+
[
|
|
86
|
+
agent("older-message", { lastUserMessageAt: "2026-09-20T12:00:00.000Z" }),
|
|
87
|
+
agent("newer-message", { lastUserMessageAt: "2026-09-22T12:00:00.000Z" }),
|
|
88
|
+
],
|
|
89
|
+
"wks_target",
|
|
90
|
+
)?.id,
|
|
91
|
+
"newer-message",
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
assert.equal(
|
|
95
|
+
selectMainAgent([agent("agt_b"), agent("agt_a")], "wks_target")?.id,
|
|
96
|
+
"agt_a",
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("selection returns null when the workspace has no eligible root agent", () => {
|
|
101
|
+
assert.equal(
|
|
102
|
+
selectMainAgent(
|
|
103
|
+
[agent("subagent", { labels: { "paseo.parent-agent-id": "agt_parent" } })],
|
|
104
|
+
"wks_target",
|
|
105
|
+
),
|
|
106
|
+
null,
|
|
107
|
+
);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("agent display helpers preserve useful title and model information", () => {
|
|
111
|
+
assert.equal(agentDisplayTitle(agent("agt_123456789", { title: " Main " })), "Main");
|
|
112
|
+
assert.equal(agentDisplayTitle(agent("agt_123456789", { title: " " })), "Agent agt_123");
|
|
113
|
+
assert.equal(agentProvider(agent("with-model")), "claude/claude-opus-5-5");
|
|
114
|
+
assert.equal(agentProvider(agent("provider-only", { model: "" })), "claude");
|
|
115
|
+
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Vendored from paseo-plugin-kit v0.4.0-beta.
|
|
1
|
+
// Vendored from paseo-plugin-kit v0.4.0-beta.1 (settings-feed-server/index.ts). Do not edit; change the kit and run `paseo-kit vendor settings-feed-server <dir>`.
|
|
2
2
|
/** Bridge the host's settings notifications to plugin subscriptions, without a polling timer. */
|
|
3
3
|
type Push = (document: unknown) => Promise<void>;
|
|
4
4
|
type Context = { push: Push; signal: AbortSignal };
|
package/server/shared-daemon.ts
CHANGED
|
@@ -23,6 +23,8 @@
|
|
|
23
23
|
* connection opens or the cause changes. Callers see only "unreachable".
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import { failureLog } from "./daemon-endpoint/index.mjs";
|
|
27
|
+
|
|
26
28
|
export interface Closable {
|
|
27
29
|
close(): Promise<void>;
|
|
28
30
|
}
|
|
@@ -75,9 +77,7 @@ export function sharedDaemon<C extends Closable>(
|
|
|
75
77
|
const stopping = options.stopping ?? (() => new Error("Send to Paseo is stopping."));
|
|
76
78
|
const keepWarm = options.keepWarm === true;
|
|
77
79
|
const describeFailure = options.describeFailure ?? ((error: unknown) => (error instanceof Error ? error.message : String(error)));
|
|
78
|
-
const
|
|
79
|
-
/** The last failure line logged; cleared when a connection opens, so the next outage is logged again. */
|
|
80
|
-
let logged: string | null = null;
|
|
80
|
+
const failureLines = failureLog(options.log ?? ((line: string) => console.error(line)));
|
|
81
81
|
type Entry = { client: Promise<C>; ready: C | null; opened: number; users: number; retired: boolean; unsubscribe?: () => void };
|
|
82
82
|
let current: Entry | null = null;
|
|
83
83
|
/** The replacement for an aged `current`, opening while `current` keeps serving. */
|
|
@@ -122,7 +122,7 @@ export function sharedDaemon<C extends Closable>(
|
|
|
122
122
|
entry.client = open().then(
|
|
123
123
|
(client) => {
|
|
124
124
|
failures = 0;
|
|
125
|
-
|
|
125
|
+
failureLines.opened();
|
|
126
126
|
if (stopped) {
|
|
127
127
|
void client.close().catch(() => undefined);
|
|
128
128
|
throw stopping();
|
|
@@ -143,10 +143,7 @@ export function sharedDaemon<C extends Closable>(
|
|
|
143
143
|
(error: unknown) => {
|
|
144
144
|
failures++;
|
|
145
145
|
lastError = error;
|
|
146
|
-
if (!stopped)
|
|
147
|
-
const line = describeFailure(error);
|
|
148
|
-
if (line !== logged) { logged = line; log(line); }
|
|
149
|
-
}
|
|
146
|
+
if (!stopped) failureLines.failed(describeFailure(error));
|
|
150
147
|
retryAt = now() + Math.min(backoffMs * 2 ** (failures - 1), backoffMaxMs);
|
|
151
148
|
all.delete(entry);
|
|
152
149
|
if (current === entry) current = null;
|
package/shared/contracts.ts
CHANGED
|
@@ -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.6.1
|
|
12
|
+
export const PLUGIN_VERSION = "2.6.1";
|
|
13
13
|
/** Bumped only for an incompatible bridge API; the paths stay `/v1`. */
|
|
14
14
|
export const CONTRACT_VERSION = 1;
|
|
15
15
|
|
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
import { request as httpRequest } from "node:http";
|
|
2
|
-
import { request as httpsRequest } from "node:https";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Where the plugin's daemon connection goes, for every way Paseo can listen
|
|
6
|
-
* (daemon-connection-reaches-every-listener, AGENTS.md).
|
|
7
|
-
*
|
|
8
|
-
* `daemon.listen` takes the same forms Paseo's own `parseListenString` does: a
|
|
9
|
-
* socket path (`/…`, `~/…`, `unix://…`), a Windows pipe (`\\.\pipe\…`,
|
|
10
|
-
* `pipe://…`), a bare port, `host:port`, `[v6]:port`, and a comma list whose
|
|
11
|
-
* first entry is the main listener. Both halves of the connection, the
|
|
12
|
-
* WebSocket (`webSocketFactory`) and the HTTP status read (`daemonHttpGet`),
|
|
13
|
-
* are built from this one value, so a form either works for both or neither.
|
|
14
|
-
*
|
|
15
|
-
* Before this the plugin built `ws://${listen}/ws`, which a socket path turned
|
|
16
|
-
* into `ws:///…/paseo.sock/ws` (host "…", not a socket) and a listener list
|
|
17
|
-
* into a URL with a comma in its host, and it opened that with Node's built-in
|
|
18
|
-
* WebSocket, which cannot reach a socket at all (`ws+unix://` is refused with
|
|
19
|
-
* "expected a ws: or wss: url"). Paseo itself worked; the plugin never
|
|
20
|
-
* connected, and the failure was not logged.
|
|
21
|
-
*/
|
|
22
|
-
export interface DaemonEndpoint {
|
|
23
|
-
/** What the WebSocket opens: `ws://host:port/ws`, or `ws+unix://<path>:/ws` for a socket. */
|
|
24
|
-
url: string;
|
|
25
|
-
/** The socket or pipe path, or null for TCP. */
|
|
26
|
-
socketPath: string | null;
|
|
27
|
-
/** Origin of the plain HTTP endpoints for TCP (`http://host:port`); unused for a socket. */
|
|
28
|
-
httpOrigin: string;
|
|
29
|
-
/** Safe to log: no credentials, no query. */
|
|
30
|
-
address: string;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export const DEFAULT_LISTEN = "127.0.0.1:6767";
|
|
34
|
-
|
|
35
|
-
const bracket = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
|
|
36
|
-
|
|
37
|
-
/** The socket or pipe a listen value names, or null for TCP. Same rules as Paseo's `parseSocketTarget`. */
|
|
38
|
-
function socketTarget(listen: string, home: string): { path: string; pipe: boolean } | null {
|
|
39
|
-
if (listen.startsWith("\\\\.\\pipe\\")) return { path: listen, pipe: true };
|
|
40
|
-
if (listen.startsWith("pipe://")) return { path: listen.slice("pipe://".length), pipe: true };
|
|
41
|
-
const path = listen.startsWith("unix://") ? listen.slice("unix://".length) : listen.startsWith("/") || listen.startsWith("~") ? listen : null;
|
|
42
|
-
return path === null ? null : { path: path.replace(/^~(?=[/\\]|$)/, home), pipe: false };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function socketEndpoint(path: string, pipe: boolean): DaemonEndpoint {
|
|
46
|
-
// Paseo's CLI addresses a pipe as ws://localhost/ws plus the path; a UNIX socket needs ws+unix.
|
|
47
|
-
return { url: pipe ? "ws://localhost/ws" : `ws+unix://${path}:/ws`, socketPath: path, httpOrigin: "http://localhost", address: path };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** The endpoint for a `daemon.listen` value (undefined or blank is Paseo's default). */
|
|
51
|
-
export function endpointFromListen(listen: string | undefined, home: string): DaemonEndpoint {
|
|
52
|
-
const raw = listen?.trim() || DEFAULT_LISTEN;
|
|
53
|
-
const socket = socketTarget(raw, home);
|
|
54
|
-
if (socket) return socketEndpoint(socket.path, socket.pipe);
|
|
55
|
-
// Several listeners: the first is the main one (Paseo's getMainListenAddress); the rest are extra TCP addresses.
|
|
56
|
-
const main = raw.split(",", 1)[0]!.trim();
|
|
57
|
-
let hostPort: string;
|
|
58
|
-
if (/^\d+$/.test(main)) hostPort = `127.0.0.1:${main}`;
|
|
59
|
-
else {
|
|
60
|
-
const colon = main.lastIndexOf(":");
|
|
61
|
-
if (colon < 0) throw new Error(`Paseo's daemon.listen is not an address the plugin understands: ${main}`);
|
|
62
|
-
const host = main.slice(0, colon).replace(/^\[(.*)\]$/, "$1") || "127.0.0.1";
|
|
63
|
-
hostPort = `${bracket(host)}:${main.slice(colon + 1)}`;
|
|
64
|
-
}
|
|
65
|
-
return { url: `ws://${hostPort}/ws`, socketPath: null, httpOrigin: `http://${hostPort}`, address: hostPort };
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Strips credentials, query and fragment from a URL for a log line or an error. */
|
|
69
|
-
export function safeAddress(url: string): string {
|
|
70
|
-
return url.replace(/\/\/[^/@]*@/, "//").replace(/[?#].*$/, "");
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* The endpoint for a `PASEO_DAEMON_URL` override: `ws://`/`wss://` as given, or a
|
|
75
|
-
* `ws+unix://<path>:/ws` socket address (what Paseo's CLI uses).
|
|
76
|
-
*/
|
|
77
|
-
export function endpointFromUrl(url: string): DaemonEndpoint {
|
|
78
|
-
if (url.startsWith("ws+unix://")) {
|
|
79
|
-
const path = url.slice("ws+unix://".length).replace(/:\/ws$/, "");
|
|
80
|
-
return socketEndpoint(path, false);
|
|
81
|
-
}
|
|
82
|
-
let httpOrigin = "http://127.0.0.1:6767";
|
|
83
|
-
try {
|
|
84
|
-
const parsed = new URL(url);
|
|
85
|
-
httpOrigin = `${parsed.protocol === "wss:" ? "https:" : "http:"}//${parsed.host}`;
|
|
86
|
-
} catch {
|
|
87
|
-
// An invalid override fails at connect, with the client's own reason in the log.
|
|
88
|
-
}
|
|
89
|
-
return { url, socketPath: null, httpOrigin, address: safeAddress(url) };
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** The endpoint the plugin connects to: `PASEO_DAEMON_URL` when set, else `daemon.listen`. */
|
|
93
|
-
export function resolveEndpoint(listen: string | undefined, env: Record<string, string | undefined>, home: string): DaemonEndpoint {
|
|
94
|
-
const override = env.PASEO_DAEMON_URL;
|
|
95
|
-
return override ? endpointFromUrl(override) : endpointFromListen(listen, home);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
type WsConstructor = new (address: string, protocols: string[] | undefined, options: Record<string, unknown>) => unknown;
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* The WebSocket the daemon client opens: the `ws` package (the one Paseo's own
|
|
102
|
-
* client and CLI use), given the socket path for a socket or pipe. Node's
|
|
103
|
-
* built-in WebSocket, the client's default, cannot reach a socket.
|
|
104
|
-
*/
|
|
105
|
-
export function webSocketFactory(WebSocket: WsConstructor, endpoint: DaemonEndpoint) {
|
|
106
|
-
return (url: string, options?: { headers?: Record<string, string>; protocols?: string[] }) =>
|
|
107
|
-
new WebSocket(url, options?.protocols, {
|
|
108
|
-
headers: options?.headers,
|
|
109
|
-
...(endpoint.socketPath ? { socketPath: endpoint.socketPath } : {}),
|
|
110
|
-
maxPayload: 100 * 1024 * 1024,
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** A failed connect as one log line: where, and the client's own reason. */
|
|
115
|
-
export function describeConnectFailure(endpoint: DaemonEndpoint, error: unknown): string {
|
|
116
|
-
const reason = String(error instanceof Error ? error.message : error ?? "")
|
|
117
|
-
.replace(/\s+/g, " ")
|
|
118
|
-
.trim()
|
|
119
|
-
.slice(0, 300);
|
|
120
|
-
return `can't connect to Paseo at ${endpoint.address}: ${reason || "unknown error"}`;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/** GET a plain HTTP endpoint of the daemon (`/api/status`, `/api/health`) over the same endpoint. */
|
|
124
|
-
export function daemonHttpGet(endpoint: DaemonEndpoint, path: string, timeoutMs: number): Promise<{ status: number; body: string }> {
|
|
125
|
-
return new Promise((resolve, reject) => {
|
|
126
|
-
const origin = new URL(endpoint.httpOrigin);
|
|
127
|
-
const request = origin.protocol === "https:" ? httpsRequest : httpRequest;
|
|
128
|
-
const req = request(
|
|
129
|
-
endpoint.socketPath
|
|
130
|
-
? { socketPath: endpoint.socketPath, path, method: "GET", headers: { host: "localhost" } }
|
|
131
|
-
: { protocol: origin.protocol, hostname: origin.hostname.replace(/^\[(.*)\]$/, "$1"), port: origin.port || undefined, path, method: "GET" },
|
|
132
|
-
(res) => {
|
|
133
|
-
const chunks: Buffer[] = [];
|
|
134
|
-
res.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
135
|
-
res.on("end", () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
|
|
136
|
-
res.on("error", reject);
|
|
137
|
-
},
|
|
138
|
-
);
|
|
139
|
-
req.setTimeout(timeoutMs, () => req.destroy(new Error(`timed out after ${timeoutMs} ms`)));
|
|
140
|
-
req.on("error", reject);
|
|
141
|
-
req.end();
|
|
142
|
-
});
|
|
143
|
-
}
|