projectionlab-mcp 1.2.1 → 1.2.2
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/HOW-IT-WORKS.md +2 -2
- package/REFERENCE.md +2 -2
- package/dist/bridge.d.ts +6 -0
- package/dist/extensionBridge.d.ts +57 -4
- package/dist/extensionBridge.js +273 -25
- package/dist/extensionBridge.js.map +1 -1
- package/dist/planVersion.d.ts +6 -4
- package/dist/planVersion.js +6 -4
- package/dist/planVersion.js.map +1 -1
- package/dist/tools/clonePlan.js +1 -3
- package/dist/tools/clonePlan.js.map +1 -1
- package/dist/tools/deletePlan.js +1 -3
- package/dist/tools/deletePlan.js.map +1 -1
- package/dist/tools/restore.js +1 -3
- package/dist/tools/restore.js.map +1 -1
- package/dist/tools/snapshots.js +11 -5
- package/dist/tools/snapshots.js.map +1 -1
- package/dist/tools/updatePlanEvent.js +1 -3
- package/dist/tools/updatePlanEvent.js.map +1 -1
- package/dist/tools/updatePlanSection.js +2 -3
- package/dist/tools/updatePlanSection.js.map +1 -1
- package/dist/tools/updatePlanSettings.js +1 -3
- package/dist/tools/updatePlanSettings.js.map +1 -1
- package/dist/types/wire.d.ts +25 -1
- package/dist/types/wire.js +14 -0
- package/dist/types/wire.js.map +1 -1
- package/package.json +1 -1
- package/skills/projectionlab/SKILL.md +7 -3
package/HOW-IT-WORKS.md
CHANGED
|
@@ -18,7 +18,7 @@ The server opens a WebSocket listener on `127.0.0.1:<PL_WS_PORT>`. A browser-sid
|
|
|
18
18
|
|
|
19
19
|
`src/types/wire.ts` is the contract shared by the server and every executor:
|
|
20
20
|
|
|
21
|
-
- The executor connects and sends a `hello` frame with a shared token, the protocol version, and an `instanceId` (a stable id for the installation: the extension persists one UUID, the snippet generates one per page load). The server validates the `Origin` header (extension or app origin only), checks the token, and replies `helloAck`, or closes with code `4001` (auth), `4002` (version), `4003` (a takeover replaced this executor), or `4004` (busy: another executor holds the connection, retry later). The server keeps one active executor and the incumbent keeps it: a second authenticated executor is refused with `4004`, retries on a slow schedule, and connects by itself when the active one goes away. It takes over only by sending `takeover: true` in the hello (the extension does that when the user presses Save on its options page) or by repeating the incumbent's `instanceId`, which lets an executor replace its own stale socket. The `helloAck` carries the server's release version in `serverVersion` so the extension can show a mismatch line; executors that ignore the field are unaffected, and servers older than the field simply omit it.
|
|
21
|
+
- The executor connects and sends a `hello` frame with a shared token, the protocol version, and an `instanceId` (a stable id for the installation: the extension persists one UUID, the snippet generates one per page load). The server validates the `Origin` header (extension or app origin only), checks the token, and replies `helloAck`, or closes with code `4001` (auth), `4002` (version), `4003` (a takeover replaced this executor), or `4004` (busy: another executor holds the connection, retry later). The server keeps one active executor and the incumbent keeps it: a second authenticated executor is refused with `4004`, retries on a slow schedule, and connects by itself when the active one goes away. It takes over only by sending `takeover: true` in the hello (the extension does that when the user presses Save on its options page) or by repeating the incumbent's `instanceId`, which lets an executor replace its own stale socket. Several server instances (one per host session) can share the port the same way: one holds it and the others retry the bind. A waiting instance with an operation to run connects to the port and sends a `yield` frame carrying the token instead of a `hello`; the holder finishes its queued operations, releases the port, closes its executor with `1012` (an ordinary close, so the executor reconnects within seconds rather than standing by), and closes the yield socket with `4005`. The waiting instance binds the port at once and waits for the executor to reconnect. When several instances wait, the one that loses the bind asks the new holder in turn. A yield from a socket with an `Origin` header is refused, since only another server sends one. The `helloAck` carries the server's release version in `serverVersion` so the extension can show a mismatch line; executors that ignore the field are unaffected, and servers older than the field simply omit it.
|
|
22
22
|
- Requests are `{ id, method, params }`; responses are `{ id, ok, result | error }`. Methods map directly to Plugin API calls plus `describeApi`/`waitForApi`.
|
|
23
23
|
- A ~20 s `ping`/`pong` heartbeat keeps the connection healthy (and keeps a Manifest V3 service worker from being suspended).
|
|
24
24
|
|
|
@@ -50,7 +50,7 @@ The Plugin API provides a targeted `updateAccount` operation for Current Finance
|
|
|
50
50
|
1. **Dry-Run by Default:** without `confirm: true`, the tool returns a structured diff preview instead of mutating anything.
|
|
51
51
|
2. **Fresh State:** the tool requests an uncached export and validates the requested change against the current data.
|
|
52
52
|
3. **Auto-Snapshotting:** on `confirm: true`, the tool passes the affected current section to `SnapshotManager`, which writes a restore-safe local JSON snapshot with an ID and timestamp.
|
|
53
|
-
4. **Conflict Check:** because `restorePlans` replaces every plan, a plan write re-reads the plans just before writing and refuses with `PLAN_CONFLICT` if any plan was added, removed, or saved in ProjectionLab since the tool read them (`
|
|
53
|
+
4. **Conflict Check:** because `restorePlans` replaces every plan, a plan write re-reads the plans just before writing and refuses with `PLAN_CONFLICT` if any plan was added, removed, or saved in ProjectionLab since the tool read them (`restorePlansIfUnchanged` in `src/extensionBridge.ts`). The re-read and the write run as one operation on the bridge, so a port hand-over to another server instance cannot fall between them: of two instances writing plans at once, one write lands and the other is refused. `projectionlab_update_plan_section` also accepts the dry run's `planVersion` as `expectedPlanVersion` and refuses if the plan was saved after the preview.
|
|
54
54
|
5. **Execution:** only then does the bridge call `updateAccount()` or the appropriate `restore*()` method.
|
|
55
55
|
6. **Verification:** the tool performs a fresh re-read and checks that the requested change landed. A verification failure is reported with the snapshot retained for recovery.
|
|
56
56
|
|
package/REFERENCE.md
CHANGED
|
@@ -37,7 +37,7 @@ mcp_servers:
|
|
|
37
37
|
enabled: true
|
|
38
38
|
```
|
|
39
39
|
|
|
40
|
-
Only one server instance
|
|
40
|
+
Only one server instance holds the WebSocket port at a time, and the browser connects to that one. Hosts that start a server per session or window (Claude Desktop keeps one running for every open session) can have several on the same port. The instance in use takes the port: when a waiting instance gets a tool call, it asks the holder to hand over, the holder finishes the operations it has already queued and releases the port, and the browser reconnects to the new holder within a few seconds. Two agents working at once trade the connection back and forth, with that delay on each switch. A waiting instance also takes the port within a few seconds of the holder exiting. Holders older than this mechanism cannot hand over; `projectionlab_check_connection` says so, and closing that session or quitting its host frees the port. It also says when the port is held by a program that is not projectionlab-mcp, in which case set `PL_WS_PORT` to a free port and enter the same port on the extension's options page.
|
|
41
41
|
|
|
42
42
|
## Agent instructions
|
|
43
43
|
|
|
@@ -143,7 +143,7 @@ The server starts without `PL_API_KEY` so it can tell the agent what is missing;
|
|
|
143
143
|
|
|
144
144
|
Write operations (`update_*`, `restore_*`, `clone_plan`, `delete_plan`) default to **dry-run mode**. Pass `confirm: true` to execute. Before any confirmed mutation, the server automatically snapshots the affected data section to disk so you can roll back with `projectionlab_rollback`. Writes are disabled entirely unless `PL_READ_ONLY=false`.
|
|
145
145
|
|
|
146
|
-
Every write that replaces the plans array re-reads the plans just before writing and refuses with `PLAN_CONFLICT` if any plan was added, removed, or saved in ProjectionLab since the tool read them, so an edit made in the ProjectionLab UI is never silently overwritten. `projectionlab_update_plan_section` also returns a `planVersion` in its dry run; pass it back as `expectedPlanVersion` when confirming to refuse the write if the plan was saved after the preview.
|
|
146
|
+
Every write that replaces the plans array re-reads the plans just before writing and refuses with `PLAN_CONFLICT` if any plan was added, removed, or saved in ProjectionLab since the tool read them, so an edit made in the ProjectionLab UI, or a write by another agent's server instance, is never silently overwritten. `projectionlab_update_plan_section` also returns a `planVersion` in its dry run; pass it back as `expectedPlanVersion` when confirming to refuse the write if the plan was saved after the preview.
|
|
147
147
|
|
|
148
148
|
Plan reads hide secret values: a secret-named field (`apiKey`, `token`, `password`, …) comes back as `[REDACTED]`. A payload for `projectionlab_update_plan_section` or any `restore_*` tool that still holds that sentinel under a secret-named key is refused with `INVALID_INPUT`, dry runs included, naming the offending dot paths. Supply the real value, or change single fields with `projectionlab_update_plan_event` or `projectionlab_update_plan_settings`, which patch by path and never round-trip hidden values.
|
|
149
149
|
|
package/dist/bridge.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export interface Bridge {
|
|
|
24
24
|
updateAccount(accountId: string, data: Record<string, unknown>, force?: boolean): Promise<void>;
|
|
25
25
|
restoreCurrentFinances(state: unknown): Promise<void>;
|
|
26
26
|
restorePlans(plans: unknown[]): Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* Writes `plans` unless a plan was added, removed, or saved since `read`
|
|
29
|
+
* was taken, in which case it throws PLAN_CONFLICT and writes nothing. The
|
|
30
|
+
* re-read and the write are atomic: no other operation runs between them.
|
|
31
|
+
*/
|
|
32
|
+
restorePlansIfUnchanged(read: unknown[], plans: unknown[]): Promise<void>;
|
|
27
33
|
restoreProgress(progress: unknown): Promise<void>;
|
|
28
34
|
restoreSettings(settings: unknown): Promise<void>;
|
|
29
35
|
invalidateCache(): void;
|
|
@@ -12,6 +12,16 @@ export declare class ExtensionBridge implements Bridge {
|
|
|
12
12
|
private readonly token;
|
|
13
13
|
private portBusy;
|
|
14
14
|
private retryTimer;
|
|
15
|
+
/** While non-zero, bind retries run every TAKEOVER_RETRY_MS until this time. */
|
|
16
|
+
private fastBindUntil;
|
|
17
|
+
/** Why the last yield request failed; "" when none has. */
|
|
18
|
+
private yieldFailure;
|
|
19
|
+
/** The socket of a yield request in flight. */
|
|
20
|
+
private yieldPeer;
|
|
21
|
+
/** When this instance last released the port to another instance. */
|
|
22
|
+
private yieldedAt;
|
|
23
|
+
/** Callbacks run whenever the connection or port state changes. */
|
|
24
|
+
private readonly stateWaiters;
|
|
15
25
|
private closed;
|
|
16
26
|
private opChain;
|
|
17
27
|
private exportCache;
|
|
@@ -19,12 +29,17 @@ export declare class ExtensionBridge implements Bridge {
|
|
|
19
29
|
/** Reads or creates `~/.projectionlab-mcp/ws-token`, keeping the folder
|
|
20
30
|
* 0700 and the file 0600 even when they already existed with looser modes. */
|
|
21
31
|
private loadOrCreateToken;
|
|
32
|
+
private notifyState;
|
|
33
|
+
private scheduleListen;
|
|
22
34
|
/** Binds the WebSocket port. While another instance (another agent on
|
|
23
|
-
* this machine) holds it, retries every PORT_RETRY_MS
|
|
24
|
-
* that instance exits;
|
|
35
|
+
* this machine) holds it, retries every PORT_RETRY_MS, so it takes over
|
|
36
|
+
* once that instance exits; an operation arriving meanwhile asks the
|
|
37
|
+
* holder to yield (requestPort). Executors reconnect on their own
|
|
38
|
+
* schedule. */
|
|
25
39
|
private listen;
|
|
26
|
-
/** New sockets must send a valid hello
|
|
27
|
-
* runs once the first message
|
|
40
|
+
/** New sockets must send a valid hello (or, from another server instance,
|
|
41
|
+
* a yield) before anything else. `helloRead` runs once the first message
|
|
42
|
+
* arrives, whatever it holds. */
|
|
28
43
|
private awaitHello;
|
|
29
44
|
/**
|
|
30
45
|
* Decide whether an authenticated hello becomes the active executor. The
|
|
@@ -38,17 +53,51 @@ export declare class ExtensionBridge implements Bridge {
|
|
|
38
53
|
/** Promote an authenticated socket to the active connection. Replacing a
|
|
39
54
|
* live incumbent (takeover or same instance id) closes it with 4003. */
|
|
40
55
|
private adopt;
|
|
56
|
+
/**
|
|
57
|
+
* Hand the port to the server instance that sent a yield frame on `peer`.
|
|
58
|
+
* Runs on the operation chain, so an operation already sent to the
|
|
59
|
+
* browser finishes before the executor is dropped. The executor is closed
|
|
60
|
+
* with HANDED_OVER, an ordinary code, so it reconnects within seconds and
|
|
61
|
+
* reaches the new holder. This instance then waits for the port like any
|
|
62
|
+
* other, and asks for it back when its next operation arrives.
|
|
63
|
+
*/
|
|
64
|
+
private yieldPort;
|
|
65
|
+
/**
|
|
66
|
+
* Ask the instance holding the port to yield it. Resolves "yielded" when
|
|
67
|
+
* it closes the socket with YIELDED, and "free" when nothing accepts the
|
|
68
|
+
* connection or the holder drops it (it just exited). Otherwise resolves
|
|
69
|
+
* the failure: "refused" when the holder answers 4001 (a server that
|
|
70
|
+
* predates yield frames, or one with a different token), "slow" when a
|
|
71
|
+
* holder that accepted the socket does not release the port within
|
|
72
|
+
* YIELD_TIMEOUT_MS, and "foreign" when the holder does not complete a
|
|
73
|
+
* WebSocket upgrade (a process that is not projectionlab-mcp).
|
|
74
|
+
*/
|
|
75
|
+
private requestPort;
|
|
76
|
+
/** Resolves once `done()` holds, rechecked on every state change, or
|
|
77
|
+
* after `timeoutMs`. */
|
|
78
|
+
private waitForState;
|
|
79
|
+
/**
|
|
80
|
+
* The connected executor's socket. While another instance holds the port,
|
|
81
|
+
* asks it to yield, binds the port, and waits for the executor to
|
|
82
|
+
* reconnect here. When another waiting instance wins the bind instead, the
|
|
83
|
+
* next round asks that instance. Runs on the operation chain, so
|
|
84
|
+
* concurrent operations send one yield between them.
|
|
85
|
+
*/
|
|
86
|
+
private executorSocket;
|
|
41
87
|
private onFrame;
|
|
42
88
|
private settle;
|
|
43
89
|
private wireError;
|
|
44
90
|
private startHeartbeat;
|
|
45
91
|
/** Reject every in-flight request; the executor that was sent to is gone. */
|
|
46
92
|
private abandonRequests;
|
|
93
|
+
/** Forget the executor. With `closeCode`, the socket gets a close frame
|
|
94
|
+
* carrying that code; otherwise it is terminated. */
|
|
47
95
|
private dropConnection;
|
|
48
96
|
private serialize;
|
|
49
97
|
/** Why no executor can be reached, with the fix, for error messages. */
|
|
50
98
|
private notConnectedReason;
|
|
51
99
|
private requireApiKey;
|
|
100
|
+
/** Send one request to the executor. Call only from the operation chain. */
|
|
52
101
|
private request;
|
|
53
102
|
/** Tier 0: console snippet that turns a PL tab into the executor. */
|
|
54
103
|
bootstrapSnippet(): string;
|
|
@@ -62,6 +111,10 @@ export declare class ExtensionBridge implements Bridge {
|
|
|
62
111
|
private restoreCall;
|
|
63
112
|
restoreCurrentFinances(state: unknown): Promise<void>;
|
|
64
113
|
restorePlans(plans: unknown[]): Promise<void>;
|
|
114
|
+
/** Re-reads the plans and writes `plans` as one entry on the operation
|
|
115
|
+
* chain, so neither a hand-over to another instance nor another operation
|
|
116
|
+
* of this one can run between the conflict check and the write. */
|
|
117
|
+
restorePlansIfUnchanged(read: unknown[], plans: unknown[]): Promise<void>;
|
|
65
118
|
restoreProgress(progress: unknown): Promise<void>;
|
|
66
119
|
restoreSettings(settings: unknown): Promise<void>;
|
|
67
120
|
close(): Promise<void>;
|
package/dist/extensionBridge.js
CHANGED
|
@@ -6,6 +6,7 @@ import { buildBootstrapSnippet } from "./bootstrap.js";
|
|
|
6
6
|
import { config, USER_ENV_FILE } from "./config.js";
|
|
7
7
|
import { ProjectionLabError } from "./errors.js";
|
|
8
8
|
import { log } from "./logger.js";
|
|
9
|
+
import { planChanges, planConflictError } from "./planVersion.js";
|
|
9
10
|
import { VERSION } from "./version.js";
|
|
10
11
|
import { CLOSE_CODES, HEARTBEAT_INTERVAL_MS, MIN_EXTENSION_VERSION, PROTOCOL_VERSION, } from "./types/wire.js";
|
|
11
12
|
/** Origins allowed to open the WebSocket. Extensions plus the PL app itself
|
|
@@ -26,6 +27,23 @@ const HELLO_TIMEOUT_MS = 5_000;
|
|
|
26
27
|
const MAX_PRE_HELLO_BYTES = 64 * 1024;
|
|
27
28
|
/** How often to retry the WebSocket port while another instance holds it. */
|
|
28
29
|
const PORT_RETRY_MS = 3_000;
|
|
30
|
+
/** After the holder yields, how long and how often to retry the bind. The
|
|
31
|
+
* extension reconnects about 2 seconds after an ordinary close, so the port
|
|
32
|
+
* must be bound well before then. */
|
|
33
|
+
const TAKEOVER_BIND_MS = 2_000;
|
|
34
|
+
const TAKEOVER_RETRY_MS = 100;
|
|
35
|
+
/** After taking the port over, how long an operation waits for the executor
|
|
36
|
+
* to reconnect (the extension retries at about 2, 6, then 14 seconds). */
|
|
37
|
+
const EXECUTOR_WAIT_MS = 15_000;
|
|
38
|
+
/** How long to wait for the holder to yield. The holder first finishes its
|
|
39
|
+
* queued operations, each of which can take up to REQUEST_TIMEOUT_MS. */
|
|
40
|
+
const YIELD_TIMEOUT_MS = 75_000;
|
|
41
|
+
/** How long the holder has to answer the WebSocket upgrade on a yield socket.
|
|
42
|
+
* A process that does not is not projectionlab-mcp. */
|
|
43
|
+
const YIELD_HANDSHAKE_MS = 5_000;
|
|
44
|
+
/** How many times one operation asks for the port. Another waiting instance
|
|
45
|
+
* can win the bind after a yield; the next round asks that instance. */
|
|
46
|
+
const TAKEOVER_ROUNDS = 3;
|
|
29
47
|
const EXTENSION_HELP = "Install the MCP Bridge for ProjectionLab extension from the Chrome Web Store " +
|
|
30
48
|
"(https://chromewebstore.google.com/detail/mcp-bridge-for-projection/njgjmcihabchffonldcgfjiocjalpoaf) " +
|
|
31
49
|
"or Firefox Add-ons (https://addons.mozilla.org/en-US/firefox/addon/mcp-bridge-for-projectionlab/); " +
|
|
@@ -67,6 +85,16 @@ export class ExtensionBridge {
|
|
|
67
85
|
token;
|
|
68
86
|
portBusy = false;
|
|
69
87
|
retryTimer = null;
|
|
88
|
+
/** While non-zero, bind retries run every TAKEOVER_RETRY_MS until this time. */
|
|
89
|
+
fastBindUntil = 0;
|
|
90
|
+
/** Why the last yield request failed; "" when none has. */
|
|
91
|
+
yieldFailure = "";
|
|
92
|
+
/** The socket of a yield request in flight. */
|
|
93
|
+
yieldPeer = null;
|
|
94
|
+
/** When this instance last released the port to another instance. */
|
|
95
|
+
yieldedAt = 0;
|
|
96
|
+
/** Callbacks run whenever the connection or port state changes. */
|
|
97
|
+
stateWaiters = new Set();
|
|
70
98
|
closed = false;
|
|
71
99
|
// Serialize all operations and cache the last full export until a write
|
|
72
100
|
// invalidates it.
|
|
@@ -99,11 +127,26 @@ export class ExtensionBridge {
|
|
|
99
127
|
log.info("extension", `Generated WebSocket token at ${file}`);
|
|
100
128
|
return token;
|
|
101
129
|
}
|
|
130
|
+
notifyState() {
|
|
131
|
+
for (const waiter of [...this.stateWaiters])
|
|
132
|
+
waiter();
|
|
133
|
+
}
|
|
134
|
+
scheduleListen(delayMs) {
|
|
135
|
+
if (this.closed || this.retryTimer)
|
|
136
|
+
return;
|
|
137
|
+
this.retryTimer = setTimeout(() => {
|
|
138
|
+
this.retryTimer = null;
|
|
139
|
+
this.listen();
|
|
140
|
+
}, delayMs);
|
|
141
|
+
this.retryTimer.unref();
|
|
142
|
+
}
|
|
102
143
|
/** Binds the WebSocket port. While another instance (another agent on
|
|
103
|
-
* this machine) holds it, retries every PORT_RETRY_MS
|
|
104
|
-
* that instance exits;
|
|
144
|
+
* this machine) holds it, retries every PORT_RETRY_MS, so it takes over
|
|
145
|
+
* once that instance exits; an operation arriving meanwhile asks the
|
|
146
|
+
* holder to yield (requestPort). Executors reconnect on their own
|
|
147
|
+
* schedule. */
|
|
105
148
|
listen() {
|
|
106
|
-
if (this.closed)
|
|
149
|
+
if (this.closed || this.wss)
|
|
107
150
|
return;
|
|
108
151
|
const wss = new WebSocketServer({
|
|
109
152
|
host: "127.0.0.1",
|
|
@@ -115,23 +158,30 @@ export class ExtensionBridge {
|
|
|
115
158
|
log.info("extension", `Port ${config.wsPort} is free; took over the listener`);
|
|
116
159
|
}
|
|
117
160
|
this.portBusy = false;
|
|
161
|
+
this.fastBindUntil = 0;
|
|
162
|
+
this.yieldFailure = "";
|
|
163
|
+
// A yield request still out is moot once this instance holds the port.
|
|
164
|
+
this.yieldPeer?.terminate();
|
|
118
165
|
log.info("extension", `Listening on ws://127.0.0.1:${config.wsPort}`);
|
|
166
|
+
this.notifyState();
|
|
119
167
|
});
|
|
120
168
|
wss.on("error", (err) => {
|
|
121
169
|
if (err.code === "EADDRINUSE") {
|
|
122
170
|
if (!this.portBusy) {
|
|
123
171
|
log.warn("extension", `Port ${config.wsPort} is held by another process (usually another agent's ` +
|
|
124
|
-
`projectionlab-mcp). Retrying every ${PORT_RETRY_MS / 1000}s
|
|
172
|
+
`projectionlab-mcp). Retrying every ${PORT_RETRY_MS / 1000}s; an operation arriving ` +
|
|
173
|
+
"here asks the holder to hand the port over.");
|
|
125
174
|
}
|
|
126
175
|
this.portBusy = true;
|
|
127
176
|
if (this.wss === wss)
|
|
128
177
|
this.wss = null;
|
|
129
178
|
wss.close();
|
|
130
|
-
this.
|
|
131
|
-
|
|
132
|
-
this.
|
|
133
|
-
|
|
134
|
-
|
|
179
|
+
const fast = this.fastBindUntil > Date.now();
|
|
180
|
+
if (!fast && this.fastBindUntil !== 0) {
|
|
181
|
+
this.fastBindUntil = 0;
|
|
182
|
+
this.notifyState();
|
|
183
|
+
}
|
|
184
|
+
this.scheduleListen(fast ? TAKEOVER_RETRY_MS : PORT_RETRY_MS);
|
|
135
185
|
return;
|
|
136
186
|
}
|
|
137
187
|
log.error("extension", `WebSocket server error: ${err.message}`);
|
|
@@ -164,12 +214,14 @@ export class ExtensionBridge {
|
|
|
164
214
|
}
|
|
165
215
|
};
|
|
166
216
|
socket.on("data", countPreHelloBytes);
|
|
167
|
-
this.awaitHello(ws,
|
|
217
|
+
this.awaitHello(ws, wss, origin, () => socket.off("data", countPreHelloBytes));
|
|
168
218
|
});
|
|
169
219
|
}
|
|
170
|
-
/** New sockets must send a valid hello
|
|
171
|
-
* runs once the first message
|
|
172
|
-
|
|
220
|
+
/** New sockets must send a valid hello (or, from another server instance,
|
|
221
|
+
* a yield) before anything else. `helloRead` runs once the first message
|
|
222
|
+
* arrives, whatever it holds. */
|
|
223
|
+
awaitHello(ws, wss, rawOrigin, helloRead) {
|
|
224
|
+
const origin = rawOrigin ?? "(no origin)";
|
|
173
225
|
const timer = setTimeout(() => {
|
|
174
226
|
ws.close(CLOSE_CODES.AUTH_FAILED, "hello timeout");
|
|
175
227
|
}, HELLO_TIMEOUT_MS);
|
|
@@ -181,6 +233,17 @@ export class ExtensionBridge {
|
|
|
181
233
|
ws.close(CLOSE_CODES.AUTH_FAILED, "malformed hello");
|
|
182
234
|
return;
|
|
183
235
|
}
|
|
236
|
+
if (hello.type === "yield") {
|
|
237
|
+
// Only another server process sends a yield; a browser always sends
|
|
238
|
+
// an Origin header, so a socket carrying one is refused outright.
|
|
239
|
+
if (rawOrigin !== undefined || hello.token !== this.token) {
|
|
240
|
+
log.warn("extension", `Refused a yield request from ${origin}`);
|
|
241
|
+
ws.close(CLOSE_CODES.AUTH_FAILED, "yield refused");
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
this.yieldPort(ws);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
184
247
|
if (hello.type !== "hello" || hello.token !== this.token) {
|
|
185
248
|
log.warn("extension", `Auth failed for connection from ${origin}`);
|
|
186
249
|
ws.close(CLOSE_CODES.AUTH_FAILED, "bad token");
|
|
@@ -191,6 +254,13 @@ export class ExtensionBridge {
|
|
|
191
254
|
ws.close(CLOSE_CODES.VERSION_MISMATCH, "protocol version mismatch");
|
|
192
255
|
return;
|
|
193
256
|
}
|
|
257
|
+
// A socket accepted before this instance released the port must not
|
|
258
|
+
// become its executor: the browser belongs to the new holder. The
|
|
259
|
+
// ordinary close sends the executor there.
|
|
260
|
+
if (this.wss !== wss) {
|
|
261
|
+
ws.close(CLOSE_CODES.HANDED_OVER, "port handed over");
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
194
264
|
// Only authenticated hellos reach the connection decision, so an
|
|
195
265
|
// unauthenticated client can neither displace an executor nor learn
|
|
196
266
|
// that one is connected.
|
|
@@ -261,6 +331,145 @@ export class ExtensionBridge {
|
|
|
261
331
|
log.warn("extension", `Socket error from ${executor}: ${err.message}`);
|
|
262
332
|
});
|
|
263
333
|
this.startHeartbeat();
|
|
334
|
+
this.notifyState();
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Hand the port to the server instance that sent a yield frame on `peer`.
|
|
338
|
+
* Runs on the operation chain, so an operation already sent to the
|
|
339
|
+
* browser finishes before the executor is dropped. The executor is closed
|
|
340
|
+
* with HANDED_OVER, an ordinary code, so it reconnects within seconds and
|
|
341
|
+
* reaches the new holder. This instance then waits for the port like any
|
|
342
|
+
* other, and asks for it back when its next operation arrives.
|
|
343
|
+
*/
|
|
344
|
+
yieldPort(peer) {
|
|
345
|
+
log.info("extension", "Another projectionlab-mcp instance asked for the port");
|
|
346
|
+
void this.serialize(async () => {
|
|
347
|
+
const wss = this.wss;
|
|
348
|
+
if (this.closed || !wss || peer.readyState !== WebSocket.OPEN) {
|
|
349
|
+
// This instance no longer holds the port (it yielded to someone
|
|
350
|
+
// else meanwhile, or is shutting down), so the port is released as
|
|
351
|
+
// far as this peer is concerned.
|
|
352
|
+
peer.close(CLOSE_CODES.YIELDED, "port released");
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
this.wss = null;
|
|
356
|
+
wss.close();
|
|
357
|
+
this.dropConnection("handed the connection to another projectionlab-mcp instance", CLOSE_CODES.HANDED_OVER);
|
|
358
|
+
this.portBusy = true;
|
|
359
|
+
this.yieldedAt = Date.now();
|
|
360
|
+
peer.close(CLOSE_CODES.YIELDED, "port released");
|
|
361
|
+
log.info("extension", `Released port ${config.wsPort} to another projectionlab-mcp instance`);
|
|
362
|
+
this.scheduleListen(PORT_RETRY_MS);
|
|
363
|
+
this.notifyState();
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Ask the instance holding the port to yield it. Resolves "yielded" when
|
|
368
|
+
* it closes the socket with YIELDED, and "free" when nothing accepts the
|
|
369
|
+
* connection or the holder drops it (it just exited). Otherwise resolves
|
|
370
|
+
* the failure: "refused" when the holder answers 4001 (a server that
|
|
371
|
+
* predates yield frames, or one with a different token), "slow" when a
|
|
372
|
+
* holder that accepted the socket does not release the port within
|
|
373
|
+
* YIELD_TIMEOUT_MS, and "foreign" when the holder does not complete a
|
|
374
|
+
* WebSocket upgrade (a process that is not projectionlab-mcp).
|
|
375
|
+
*/
|
|
376
|
+
requestPort() {
|
|
377
|
+
return new Promise((resolve) => {
|
|
378
|
+
const peer = new WebSocket(`ws://127.0.0.1:${config.wsPort}`);
|
|
379
|
+
this.yieldPeer = peer;
|
|
380
|
+
let failure = "";
|
|
381
|
+
const giveUp = (why) => {
|
|
382
|
+
failure = why;
|
|
383
|
+
peer.terminate();
|
|
384
|
+
};
|
|
385
|
+
const handshakeTimer = setTimeout(() => giveUp("foreign"), YIELD_HANDSHAKE_MS);
|
|
386
|
+
const timer = setTimeout(() => giveUp("slow"), YIELD_TIMEOUT_MS);
|
|
387
|
+
handshakeTimer.unref();
|
|
388
|
+
timer.unref();
|
|
389
|
+
peer.on("open", () => {
|
|
390
|
+
clearTimeout(handshakeTimer);
|
|
391
|
+
peer.send(JSON.stringify({ type: "yield", token: this.token }));
|
|
392
|
+
});
|
|
393
|
+
peer.on("unexpected-response", () => giveUp("foreign"));
|
|
394
|
+
peer.on("error", (err) => {
|
|
395
|
+
log.debug("extension", `Yield request socket error: ${err.message}`);
|
|
396
|
+
});
|
|
397
|
+
peer.on("close", (code) => {
|
|
398
|
+
clearTimeout(handshakeTimer);
|
|
399
|
+
clearTimeout(timer);
|
|
400
|
+
if (this.yieldPeer === peer)
|
|
401
|
+
this.yieldPeer = null;
|
|
402
|
+
if (code === CLOSE_CODES.YIELDED)
|
|
403
|
+
resolve("yielded");
|
|
404
|
+
else if (code === CLOSE_CODES.AUTH_FAILED)
|
|
405
|
+
resolve("refused");
|
|
406
|
+
else
|
|
407
|
+
resolve(failure || "free");
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
/** Resolves once `done()` holds, rechecked on every state change, or
|
|
412
|
+
* after `timeoutMs`. */
|
|
413
|
+
waitForState(done, timeoutMs) {
|
|
414
|
+
return new Promise((resolve) => {
|
|
415
|
+
const finish = () => {
|
|
416
|
+
clearTimeout(timer);
|
|
417
|
+
this.stateWaiters.delete(check);
|
|
418
|
+
resolve();
|
|
419
|
+
};
|
|
420
|
+
const check = () => {
|
|
421
|
+
if (done())
|
|
422
|
+
finish();
|
|
423
|
+
};
|
|
424
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
425
|
+
this.stateWaiters.add(check);
|
|
426
|
+
check();
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* The connected executor's socket. While another instance holds the port,
|
|
431
|
+
* asks it to yield, binds the port, and waits for the executor to
|
|
432
|
+
* reconnect here. When another waiting instance wins the bind instead, the
|
|
433
|
+
* next round asks that instance. Runs on the operation chain, so
|
|
434
|
+
* concurrent operations send one yield between them.
|
|
435
|
+
*/
|
|
436
|
+
async executorSocket() {
|
|
437
|
+
for (let round = 0; round < TAKEOVER_ROUNDS && !this.conn && this.portBusy && !this.closed; round++) {
|
|
438
|
+
// Right after yielding, the new holder may not have bound the port
|
|
439
|
+
// yet; asking now would find it free and race that instance for it.
|
|
440
|
+
// Waiting out its bind window means the request reaches the new
|
|
441
|
+
// holder and becomes an ordinary yield.
|
|
442
|
+
const sinceYield = Date.now() - this.yieldedAt;
|
|
443
|
+
if (sinceYield < TAKEOVER_BIND_MS) {
|
|
444
|
+
await new Promise((r) => setTimeout(r, TAKEOVER_BIND_MS - sinceYield));
|
|
445
|
+
}
|
|
446
|
+
// The bind retry may have taken the port during that wait; a yield
|
|
447
|
+
// sent then would reach this instance's own listener.
|
|
448
|
+
if (this.portBusy && !this.closed) {
|
|
449
|
+
const outcome = await this.requestPort();
|
|
450
|
+
if (outcome !== "yielded" && outcome !== "free") {
|
|
451
|
+
this.yieldFailure = outcome;
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
if (this.portBusy && !this.closed) {
|
|
455
|
+
log.info("extension", `Taking over port ${config.wsPort}`);
|
|
456
|
+
this.yieldFailure = "";
|
|
457
|
+
this.fastBindUntil = Date.now() + TAKEOVER_BIND_MS;
|
|
458
|
+
if (this.retryTimer) {
|
|
459
|
+
clearTimeout(this.retryTimer);
|
|
460
|
+
this.retryTimer = null;
|
|
461
|
+
}
|
|
462
|
+
// An attempt in flight retries on the fast schedule from its error
|
|
463
|
+
// handler; otherwise start one now.
|
|
464
|
+
this.listen();
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
await this.waitForState(() => this.conn !== null || this.closed || (this.portBusy && this.fastBindUntil === 0), EXECUTOR_WAIT_MS);
|
|
468
|
+
}
|
|
469
|
+
if (!this.conn) {
|
|
470
|
+
throw new ProjectionLabError("EXTENSION_NOT_CONNECTED", "No browser-side executor is connected", this.notConnectedReason());
|
|
471
|
+
}
|
|
472
|
+
return this.conn;
|
|
264
473
|
}
|
|
265
474
|
onFrame(ws, raw) {
|
|
266
475
|
if (this.conn !== ws)
|
|
@@ -333,11 +542,16 @@ export class ExtensionBridge {
|
|
|
333
542
|
}
|
|
334
543
|
this.pending.clear();
|
|
335
544
|
}
|
|
336
|
-
|
|
545
|
+
/** Forget the executor. With `closeCode`, the socket gets a close frame
|
|
546
|
+
* carrying that code; otherwise it is terminated. */
|
|
547
|
+
dropConnection(reason, closeCode) {
|
|
337
548
|
// Close the socket if it's still live - wss.close() waits for all
|
|
338
549
|
// clients, so leaving it open would hang shutdown.
|
|
339
550
|
try {
|
|
340
|
-
|
|
551
|
+
if (closeCode === undefined)
|
|
552
|
+
this.conn?.terminate();
|
|
553
|
+
else
|
|
554
|
+
this.conn?.close(closeCode, reason);
|
|
341
555
|
}
|
|
342
556
|
catch {
|
|
343
557
|
// Already gone.
|
|
@@ -352,6 +566,7 @@ export class ExtensionBridge {
|
|
|
352
566
|
this.heartbeat = null;
|
|
353
567
|
}
|
|
354
568
|
this.abandonRequests(reason);
|
|
569
|
+
this.notifyState();
|
|
355
570
|
}
|
|
356
571
|
serialize(fn) {
|
|
357
572
|
const next = this.opChain.then(fn, fn);
|
|
@@ -360,11 +575,26 @@ export class ExtensionBridge {
|
|
|
360
575
|
}
|
|
361
576
|
/** Why no executor can be reached, with the fix, for error messages. */
|
|
362
577
|
notConnectedReason() {
|
|
578
|
+
if (this.portBusy && this.yieldFailure === "refused") {
|
|
579
|
+
return (`Port ${config.wsPort} is held by another process that did not hand it over. Usually that ` +
|
|
580
|
+
"is an older projectionlab-mcp started by another agent or session on this machine (older " +
|
|
581
|
+
"versions cannot hand the port over), or one started with a different PL_WS_TOKEN. Close " +
|
|
582
|
+
"that session or quit its MCP host (or update its projectionlab-mcp); this server takes " +
|
|
583
|
+
"over within seconds of the port coming free.");
|
|
584
|
+
}
|
|
585
|
+
if (this.portBusy && this.yieldFailure === "slow") {
|
|
586
|
+
return (`Port ${config.wsPort} is held by another projectionlab-mcp instance that is still busy ` +
|
|
587
|
+
"with its own operations and did not release the port in time. Try again shortly.");
|
|
588
|
+
}
|
|
589
|
+
if (this.portBusy && this.yieldFailure === "foreign") {
|
|
590
|
+
return (`Port ${config.wsPort} is held by a program that is not projectionlab-mcp. Stop that ` +
|
|
591
|
+
"program, or set PL_WS_PORT to a free port for this server and enter the same port on " +
|
|
592
|
+
"the extension's options page.");
|
|
593
|
+
}
|
|
363
594
|
if (this.portBusy) {
|
|
364
|
-
return (`Port ${config.wsPort} is held by another projectionlab-mcp instance
|
|
365
|
-
"
|
|
366
|
-
"
|
|
367
|
-
"once, set PL_WS_PORT to a free port here and point the extension at it.");
|
|
595
|
+
return (`Port ${config.wsPort} is held by another projectionlab-mcp instance, and handing it over ` +
|
|
596
|
+
"to this one did not complete. Try again; if it keeps failing, close the other agent's " +
|
|
597
|
+
"session or quit its MCP host.");
|
|
368
598
|
}
|
|
369
599
|
return `No browser-side executor is connected to ws://127.0.0.1:${config.wsPort}. ${EXTENSION_HELP}`;
|
|
370
600
|
}
|
|
@@ -375,11 +605,9 @@ export class ExtensionBridge {
|
|
|
375
605
|
}
|
|
376
606
|
return config.apiKey;
|
|
377
607
|
}
|
|
378
|
-
request
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
throw new ProjectionLabError("EXTENSION_NOT_CONNECTED", "No browser-side executor is connected", this.notConnectedReason());
|
|
382
|
-
}
|
|
608
|
+
/** Send one request to the executor. Call only from the operation chain. */
|
|
609
|
+
async request(method, params, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
610
|
+
const conn = await this.executorSocket();
|
|
383
611
|
const id = String(this.nextId++);
|
|
384
612
|
const frame = { type: "request", id, method, params };
|
|
385
613
|
return new Promise((resolve, reject) => {
|
|
@@ -416,7 +644,10 @@ export class ExtensionBridge {
|
|
|
416
644
|
result.errors.push(`${e.code}: ${e.message}. ${e.suggestion}`);
|
|
417
645
|
}
|
|
418
646
|
}
|
|
419
|
-
|
|
647
|
+
try {
|
|
648
|
+
await this.executorSocket();
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
420
651
|
result.errors.push(`EXTENSION_NOT_CONNECTED: ${this.notConnectedReason()}`);
|
|
421
652
|
return result;
|
|
422
653
|
}
|
|
@@ -504,6 +735,21 @@ export class ExtensionBridge {
|
|
|
504
735
|
async restorePlans(plans) {
|
|
505
736
|
await this.restoreCall("restorePlans", plans);
|
|
506
737
|
}
|
|
738
|
+
/** Re-reads the plans and writes `plans` as one entry on the operation
|
|
739
|
+
* chain, so neither a hand-over to another instance nor another operation
|
|
740
|
+
* of this one can run between the conflict check and the write. */
|
|
741
|
+
async restorePlansIfUnchanged(read, plans) {
|
|
742
|
+
await this.serialize(async () => {
|
|
743
|
+
const key = this.requireApiKey();
|
|
744
|
+
const data = (await this.request("exportData", [{ key }]));
|
|
745
|
+
const changes = planChanges(read, Array.isArray(data.plans) ? data.plans : []);
|
|
746
|
+
if (changes.length > 0)
|
|
747
|
+
throw planConflictError(changes);
|
|
748
|
+
log.info("extension", "Calling restorePlans");
|
|
749
|
+
await this.request("restorePlans", [plans, { key }]);
|
|
750
|
+
});
|
|
751
|
+
this.invalidateCache();
|
|
752
|
+
}
|
|
507
753
|
async restoreProgress(progress) {
|
|
508
754
|
await this.restoreCall("restoreProgress", progress);
|
|
509
755
|
}
|
|
@@ -516,6 +762,8 @@ export class ExtensionBridge {
|
|
|
516
762
|
clearTimeout(this.retryTimer);
|
|
517
763
|
this.retryTimer = null;
|
|
518
764
|
}
|
|
765
|
+
this.notifyState();
|
|
766
|
+
this.yieldPeer?.terminate();
|
|
519
767
|
this.dropConnection("server shutting down");
|
|
520
768
|
if (this.wss) {
|
|
521
769
|
log.info("extension", "Closing WebSocket server");
|