@opentide/wasi-host 0.0.0 → 1.0.0-rc.4
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/LICENSE +21 -0
- package/README.md +43 -1
- package/dist/index.d.ts +185 -0
- package/dist/index.js +699 -0
- package/package.json +40 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) opentide contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,45 @@
|
|
|
1
1
|
# @opentide/wasi-host
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The extension host's half of opentide's `opentide/fetch`. The WASI build of opentide runs under VS Code's WASI host, which gives it no sockets. So its `opentide serve` asks the client to make each tenant request, and `FetchHost` makes them with Node's HTTP stack. That includes the tenant's TLS verification and CA bundles, its proxy, and its connect and read timeouts.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { FETCH_CAPABILITY, FetchHost } from "@opentide/wasi-host";
|
|
7
|
+
|
|
8
|
+
const host = new FetchHost((message) => serve.write(`${JSON.stringify(message)}\n`));
|
|
9
|
+
// For each JSON-RPC message the server sends:
|
|
10
|
+
if (!host.handle(message)) {
|
|
11
|
+
// not opentide/fetch: the client's own handling
|
|
12
|
+
}
|
|
13
|
+
// The first request:
|
|
14
|
+
serve.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: FETCH_CAPABILITY })}\n`);
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`opentide mcp start` asks the same way when it is started with `OPENTIDE_FETCH=stdio`: its requests are lines on its stdout, among its MCP messages, with ids `opentide-fetch-<token>-1`, `-2`, …, and the answers go in on its stdin. `McpFetchBridge` splits the two on the module's stdio pair, answers the requests with a `FetchHost`, and passes every MCP message through in order, one whole line at a time:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { MCP_FETCH_ENVIRONMENT, McpFetchBridge } from "@opentide/wasi-host";
|
|
21
|
+
|
|
22
|
+
// Start the module with { ...env, ...MCP_FETCH_ENVIRONMENT }.
|
|
23
|
+
const bridge = new McpFetchBridge({
|
|
24
|
+
toServer: (line) => module.stdin.write(line), // the client's messages and the host's answers
|
|
25
|
+
toClient: (line) => agent.write(line), // the module's MCP messages
|
|
26
|
+
});
|
|
27
|
+
module.stdout.on("data", (chunk) => bridge.fromServer(chunk));
|
|
28
|
+
agent.on("data", (chunk) => bridge.fromClient(chunk));
|
|
29
|
+
module.on("close", () => {
|
|
30
|
+
bridge.endServer();
|
|
31
|
+
bridge.dispose();
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The requests carry the tenant's credentials (`Authorization` and API-key headers, the body, CA bundles), and the module's stdout is not an MCP stream while `OPENTIDE_FETCH=stdio` is set (MCP's 2026-07-28 revision forbids server requests on stdout), so it must never reach an agent directly. The bridge enforces that:
|
|
36
|
+
|
|
37
|
+
- a line that mentions `opentide/fetch` and cannot be read as a request of the host's is dropped, never forwarded;
|
|
38
|
+
- a client line that is a response to an `opentide-fetch-` id, or that mentions the prefix and cannot be read, is dropped, so an agent cannot answer a tenant request itself;
|
|
39
|
+
- the module's response to a request the client cancelled is dropped (MCP has no response go out for a cancelled request);
|
|
40
|
+
- after `dispose()` no new tenant request is started.
|
|
41
|
+
- one line cannot cost the others: a line that raises (a batch nested past the module's 128-level limit, a sink that throws) is dropped, the lines after it are still handled, and nothing escapes `fromClient` or `fromServer`; pass `{ onError }` to hear of it.
|
|
42
|
+
|
|
43
|
+
The protocol is in [opentide serve](https://github.com/opentidehq/opentide/blob/development/docs/cli/serve.md#tenant-requests-the-client-makes-opentidefetch).
|
|
44
|
+
|
|
45
|
+
For `mcp start`, see [opentide mcp](https://github.com/opentidehq/opentide/blob/development/docs/cli/mcp.md#tenant-requests-over-stdio-opentide_fetch).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/** The method of the server's request. */
|
|
2
|
+
export declare const FETCH_METHOD = "opentide/fetch";
|
|
3
|
+
/** `initialize`'s params that ask the server to send its tenant requests here. */
|
|
4
|
+
export declare const FETCH_CAPABILITY: {
|
|
5
|
+
readonly capabilities: {
|
|
6
|
+
readonly fetch: true;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
/** The most redirects followed, as reqwest's default policy. */
|
|
10
|
+
export declare const MAX_REDIRECTS = 10;
|
|
11
|
+
/** One request the server asks the client to make (`opentide/fetch`'s params). */
|
|
12
|
+
export interface FetchParams {
|
|
13
|
+
/** The id of the `run` it belongs to. */
|
|
14
|
+
run: string | null;
|
|
15
|
+
platform: string;
|
|
16
|
+
tenant: string;
|
|
17
|
+
method: string;
|
|
18
|
+
url: string;
|
|
19
|
+
/** In the order written; a name may repeat. */
|
|
20
|
+
headers: [string, string][];
|
|
21
|
+
/** base64, or null for no body. */
|
|
22
|
+
body: string | null;
|
|
23
|
+
connect_timeout_ms: number;
|
|
24
|
+
read_timeout_ms: number;
|
|
25
|
+
tls: {
|
|
26
|
+
verify: boolean;
|
|
27
|
+
ca_bundles: string[];
|
|
28
|
+
};
|
|
29
|
+
/** The tenant's proxy URL (credentials included), or null to go direct. */
|
|
30
|
+
proxy: string | null;
|
|
31
|
+
}
|
|
32
|
+
/** The tenant's answer (`opentide/fetch`'s result). */
|
|
33
|
+
export interface FetchResult {
|
|
34
|
+
status: number;
|
|
35
|
+
headers: [string, string][];
|
|
36
|
+
/** After redirects. */
|
|
37
|
+
url: string;
|
|
38
|
+
/** base64. */
|
|
39
|
+
body: string;
|
|
40
|
+
/** From sending the request to the answer's headers. */
|
|
41
|
+
elapsed_ms: number;
|
|
42
|
+
}
|
|
43
|
+
/** Why there is no answer: `data.kind` of the error the server reads. */
|
|
44
|
+
export type FailureKind = "connect" | "timeout" | "aborted" | "unreachable" | "answer";
|
|
45
|
+
/** A failure with its kind, as `perform` rejects. */
|
|
46
|
+
export declare class FetchFailure extends Error {
|
|
47
|
+
readonly kind: FailureKind;
|
|
48
|
+
constructor(kind: FailureKind, message: string);
|
|
49
|
+
}
|
|
50
|
+
/** Makes one request: Node's HTTP stack by default, a stand-in in tests. */
|
|
51
|
+
export type Perform = (params: FetchParams, signal: AbortSignal) => Promise<FetchResult>;
|
|
52
|
+
/** What a `FetchHost` writes: one JSON-RPC message to the server. */
|
|
53
|
+
export type Send = (message: object) => void;
|
|
54
|
+
/**
|
|
55
|
+
* Answers a server's `opentide/fetch` requests. Hand it every message the
|
|
56
|
+
* server sends; it takes the ones that are its own.
|
|
57
|
+
*/
|
|
58
|
+
export declare class FetchHost {
|
|
59
|
+
private readonly send;
|
|
60
|
+
private readonly perform;
|
|
61
|
+
private readonly inFlight;
|
|
62
|
+
constructor(send: Send, options?: {
|
|
63
|
+
perform?: Perform;
|
|
64
|
+
});
|
|
65
|
+
/** The number of requests in flight. */
|
|
66
|
+
get pending(): number;
|
|
67
|
+
/**
|
|
68
|
+
* Takes *message* when it is the server's `opentide/fetch` or its
|
|
69
|
+
* withdrawal (`$/cancelRequest` from `opentide serve`, MCP's
|
|
70
|
+
* `notifications/cancelled` from `opentide mcp start`); whether it did.
|
|
71
|
+
*/
|
|
72
|
+
handle(message: unknown): boolean;
|
|
73
|
+
/** Aborts every request in flight, unanswered: the server has gone. */
|
|
74
|
+
dispose(): void;
|
|
75
|
+
private start;
|
|
76
|
+
}
|
|
77
|
+
/** *params* as `FetchParams`, or what is wrong with them. */
|
|
78
|
+
export declare function fetchParams(params: unknown): FetchParams | string;
|
|
79
|
+
/**
|
|
80
|
+
* Whether a redirect from *from* to *to* is followed, as the native
|
|
81
|
+
* transport's `follows_redirect`: on the same origin, or from `http` to
|
|
82
|
+
* `https` on the same host with default ports. Any other hop would carry a
|
|
83
|
+
* platform's own credential header (Carbon Black's `X-Auth-Token`,
|
|
84
|
+
* Bitdefender's `X-API-Key`) to another host, so it is not taken (#1142).
|
|
85
|
+
*/
|
|
86
|
+
export declare function followsRedirect(from: URL, to: URL): boolean;
|
|
87
|
+
/**
|
|
88
|
+
* Makes the request *params* describe with Node's HTTP stack, following
|
|
89
|
+
* redirects as the native transport does: at most `MAX_REDIRECTS`, and only
|
|
90
|
+
* those `followsRedirect` takes (any other is the answer); a 303, and a 301
|
|
91
|
+
* or 302 to a POST, become a GET without a body; the standard credentials
|
|
92
|
+
* are not sent to another origin (an http to https upgrade).
|
|
93
|
+
*/
|
|
94
|
+
export declare function performRequest(params: FetchParams, signal: AbortSignal): Promise<FetchResult>;
|
|
95
|
+
/** The variable that makes the WASI build's `opentide mcp start` ask its client for each tenant request. */
|
|
96
|
+
export declare const MCP_FETCH_VARIABLE = "OPENTIDE_FETCH";
|
|
97
|
+
/**
|
|
98
|
+
* The environment to start the WASI module's `opentide mcp start` with, added
|
|
99
|
+
* to whatever else it is given (the native build ignores it).
|
|
100
|
+
*/
|
|
101
|
+
export declare const MCP_FETCH_ENVIRONMENT: {
|
|
102
|
+
readonly OPENTIDE_FETCH: "stdio";
|
|
103
|
+
};
|
|
104
|
+
/** The prefix of the ids of `opentide mcp start`'s requests: no MCP client's id starts so by accident. */
|
|
105
|
+
export declare const MCP_FETCH_ID_PREFIX = "opentide-fetch-";
|
|
106
|
+
/** Where a `McpFetchBridge` writes: whole lines, each with its newline, ready for a pipe. */
|
|
107
|
+
export interface McpFetchSink {
|
|
108
|
+
/** To the module's stdin: the client's MCP messages and the answers to its tenant requests. */
|
|
109
|
+
toServer: (line: string) => void;
|
|
110
|
+
/** To the MCP client: the module's MCP messages, its tenant requests taken out. */
|
|
111
|
+
toClient: (line: string) => void;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Splits `opentide mcp start`'s tenant requests from its MCP messages on its
|
|
115
|
+
* stdio pair. Started with `MCP_FETCH_ENVIRONMENT`, the WASI module writes
|
|
116
|
+
* each tenant request as an `opentide/fetch` line on stdout among its MCP
|
|
117
|
+
* messages, and reads the answer on stdin among the client's. The bridge sits
|
|
118
|
+
* between the module and the MCP client:
|
|
119
|
+
*
|
|
120
|
+
* - `fromServer(chunk)`: the module's stdout. An `opentide/fetch` line (and
|
|
121
|
+
* the `notifications/cancelled` that withdraws one) is the host's, which
|
|
122
|
+
* answers it with `FetchHost`; every other line goes to `toClient`.
|
|
123
|
+
* - `fromClient(chunk)`: the client's messages, to `toServer` a whole line at
|
|
124
|
+
* a time, so an answer the host writes never lands inside one.
|
|
125
|
+
*
|
|
126
|
+
* Neither direction reorders anything: the MCP messages reach each side in the
|
|
127
|
+
* order they were written. `toServer` is called for answers asynchronously, as
|
|
128
|
+
* each request finishes.
|
|
129
|
+
*
|
|
130
|
+
* What the bridge keeps from the client, and from the agent behind it:
|
|
131
|
+
*
|
|
132
|
+
* - **A tenant request never reaches the client.** It carries the tenant's
|
|
133
|
+
* credentials (the `Authorization` and API-key headers, the CA bundles). A
|
|
134
|
+
* line that mentions `opentide/fetch` and cannot be read as a message of the
|
|
135
|
+
* host's is dropped, not forwarded: nothing that might hold a credential
|
|
136
|
+
* goes to `toClient` on a failure to understand it.
|
|
137
|
+
* - **The client cannot answer a tenant request.** A client line that is a
|
|
138
|
+
* response (it has no `method`) to an id with the `MCP_FETCH_ID_PREFIX`, or
|
|
139
|
+
* that mentions the prefix and cannot be read, is dropped: the module trusts
|
|
140
|
+
* an answer on its stdin for the request it asked, and an agent could
|
|
141
|
+
* otherwise forge the result of a deploy or a query.
|
|
142
|
+
* - **A response to a request the client cancelled is dropped.** The module may
|
|
143
|
+
* still finish a call it was told to cancel, and MCP has the receiver send
|
|
144
|
+
* no response for it.
|
|
145
|
+
* - **After `dispose()` no new tenant request is started.**
|
|
146
|
+
*/
|
|
147
|
+
export declare class McpFetchBridge {
|
|
148
|
+
private readonly sink;
|
|
149
|
+
private readonly host;
|
|
150
|
+
private readonly fromModule;
|
|
151
|
+
private readonly fromAgent;
|
|
152
|
+
/** Request ids the client cancelled (as their JSON text): their responses are dropped. */
|
|
153
|
+
private readonly cancelled;
|
|
154
|
+
private disposed;
|
|
155
|
+
/** Told of an error a line raised (the line is dropped); none by default. */
|
|
156
|
+
private readonly onError;
|
|
157
|
+
constructor(sink: McpFetchSink, options?: {
|
|
158
|
+
perform?: Perform;
|
|
159
|
+
onError?: (error: unknown) => void;
|
|
160
|
+
});
|
|
161
|
+
/** The number of tenant requests in flight. */
|
|
162
|
+
get pending(): number;
|
|
163
|
+
/** A chunk of the module's stdout. */
|
|
164
|
+
fromServer(chunk: string | Uint8Array): void;
|
|
165
|
+
/** A chunk of the client's messages for the module. */
|
|
166
|
+
fromClient(chunk: string | Uint8Array): void;
|
|
167
|
+
/** The module's stdout ended: a last line without its newline is delivered. */
|
|
168
|
+
endServer(): void;
|
|
169
|
+
/** The client's input ended: a last line without its newline is delivered. */
|
|
170
|
+
endClient(): void;
|
|
171
|
+
/** Aborts every request in flight, unanswered: the module has gone. */
|
|
172
|
+
dispose(): void;
|
|
173
|
+
/**
|
|
174
|
+
* Runs the handling of one line so that nothing it raises (a line that overflows the stack,
|
|
175
|
+
* a sink that throws) escapes into the host's data handler or costs the lines after it:
|
|
176
|
+
* the line is dropped, and `onError` is told.
|
|
177
|
+
*/
|
|
178
|
+
private isolated;
|
|
179
|
+
private clientLine;
|
|
180
|
+
private serverLine;
|
|
181
|
+
/** Whether *message* withdraws one of the module's tenant requests: the host's, handled. */
|
|
182
|
+
private takesWithdrawal;
|
|
183
|
+
/** Whether *line* is the response to a request the client cancelled; the id is then forgotten. */
|
|
184
|
+
private dropsCancelledResponse;
|
|
185
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
// @opentide/wasi-host: the extension host's half of `opentide/fetch` (W2,
|
|
2
|
+
// docs/engine/connector-transport.md).
|
|
3
|
+
//
|
|
4
|
+
// The WASI build of opentide runs under VS Code's WASI host, which gives it
|
|
5
|
+
// no sockets. Its `opentide serve` asks the client to make each tenant
|
|
6
|
+
// request: a server-to-client JSON-RPC request `opentide/fetch`, whose id is
|
|
7
|
+
// a string ("h1", "h2", ...). `FetchHost` answers those requests from the
|
|
8
|
+
// extension host, with Node's own HTTP stack: the tenant's TLS verification
|
|
9
|
+
// and CA bundles, its proxy (a CONNECT tunnel), its connect and read
|
|
10
|
+
// timeouts, redirects as the native transport follows them (on the tenant's
|
|
11
|
+
// origin only), and cancellation when the
|
|
12
|
+
// server withdraws a request (`$/cancelRequest`). VS Code's proxy support
|
|
13
|
+
// (`http.proxy`, the OS certificate store), which patches Node's `https`,
|
|
14
|
+
// applies as it does to any extension.
|
|
15
|
+
//
|
|
16
|
+
// The native `opentide serve` speaks the same protocol, so one client drives
|
|
17
|
+
// both builds.
|
|
18
|
+
//
|
|
19
|
+
// `opentide mcp start` in the WASI build asks the same way when it is started
|
|
20
|
+
// with OPENTIDE_FETCH=stdio: its `opentide/fetch` requests (ids
|
|
21
|
+
// "opentide-fetch-1", ...) are lines on its stdout among its MCP messages, and
|
|
22
|
+
// the answers go in on its stdin among the client's. `McpFetchBridge` splits
|
|
23
|
+
// the two on that stdio pair, so an extension that serves MCP to an agent
|
|
24
|
+
// bridges the module's stdio with it.
|
|
25
|
+
import * as http from "node:http";
|
|
26
|
+
import * as https from "node:https";
|
|
27
|
+
import * as net from "node:net";
|
|
28
|
+
import * as tls from "node:tls";
|
|
29
|
+
/** The method of the server's request. */
|
|
30
|
+
export const FETCH_METHOD = "opentide/fetch";
|
|
31
|
+
/** `initialize`'s params that ask the server to send its tenant requests here. */
|
|
32
|
+
export const FETCH_CAPABILITY = { capabilities: { fetch: true } };
|
|
33
|
+
/** The most redirects followed, as reqwest's default policy. */
|
|
34
|
+
export const MAX_REDIRECTS = 10;
|
|
35
|
+
/** A failure with its kind, as `perform` rejects. */
|
|
36
|
+
export class FetchFailure extends Error {
|
|
37
|
+
kind;
|
|
38
|
+
constructor(kind, message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.kind = kind;
|
|
41
|
+
this.name = "FetchFailure";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Answers a server's `opentide/fetch` requests. Hand it every message the
|
|
46
|
+
* server sends; it takes the ones that are its own.
|
|
47
|
+
*/
|
|
48
|
+
export class FetchHost {
|
|
49
|
+
send;
|
|
50
|
+
perform;
|
|
51
|
+
inFlight = new Map();
|
|
52
|
+
constructor(send, options = {}) {
|
|
53
|
+
this.send = send;
|
|
54
|
+
this.perform = options.perform ?? performRequest;
|
|
55
|
+
}
|
|
56
|
+
/** The number of requests in flight. */
|
|
57
|
+
get pending() {
|
|
58
|
+
return this.inFlight.size;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Takes *message* when it is the server's `opentide/fetch` or its
|
|
62
|
+
* withdrawal (`$/cancelRequest` from `opentide serve`, MCP's
|
|
63
|
+
* `notifications/cancelled` from `opentide mcp start`); whether it did.
|
|
64
|
+
*/
|
|
65
|
+
handle(message) {
|
|
66
|
+
if (!isObject(message)) {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
if (message.method === FETCH_METHOD && typeof message.id === "string") {
|
|
70
|
+
this.start(message.id, message.params);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
if ((message.method === "$/cancelRequest" || message.method === "notifications/cancelled") &&
|
|
74
|
+
isObject(message.params)) {
|
|
75
|
+
const id = message.method === "$/cancelRequest" ? message.params.id : message.params.requestId;
|
|
76
|
+
if (typeof id === "string" && this.inFlight.has(id)) {
|
|
77
|
+
this.inFlight.get(id)?.abort();
|
|
78
|
+
this.inFlight.delete(id);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
/** Aborts every request in flight, unanswered: the server has gone. */
|
|
85
|
+
dispose() {
|
|
86
|
+
for (const controller of this.inFlight.values()) {
|
|
87
|
+
controller.abort();
|
|
88
|
+
}
|
|
89
|
+
this.inFlight.clear();
|
|
90
|
+
}
|
|
91
|
+
start(id, params) {
|
|
92
|
+
const controller = new AbortController();
|
|
93
|
+
this.inFlight.set(id, controller);
|
|
94
|
+
const answered = (reply) => {
|
|
95
|
+
// A withdrawn request is not answered: the server has stopped waiting.
|
|
96
|
+
if (this.inFlight.get(id) === controller) {
|
|
97
|
+
this.inFlight.delete(id);
|
|
98
|
+
this.send({ jsonrpc: "2.0", id, ...reply });
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const checked = fetchParams(params);
|
|
102
|
+
if (typeof checked === "string") {
|
|
103
|
+
answered({ error: { code: -32602, message: checked, data: { kind: "unreachable" } } });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
this.perform(checked, controller.signal).then((result) => answered({ result }), (error) => {
|
|
107
|
+
const failure = asFailure(error, controller.signal);
|
|
108
|
+
answered({
|
|
109
|
+
error: { code: -32000, message: failure.message, data: { kind: failure.kind } },
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function isObject(value) {
|
|
115
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
116
|
+
}
|
|
117
|
+
/** *params* as `FetchParams`, or what is wrong with them. */
|
|
118
|
+
export function fetchParams(params) {
|
|
119
|
+
if (!isObject(params)) {
|
|
120
|
+
return "opentide/fetch takes an object";
|
|
121
|
+
}
|
|
122
|
+
const { method, url, headers, body, tls: settings } = params;
|
|
123
|
+
if (typeof method !== "string" || typeof url !== "string") {
|
|
124
|
+
return "opentide/fetch needs a method and a url";
|
|
125
|
+
}
|
|
126
|
+
if (!Array.isArray(headers) ||
|
|
127
|
+
!headers.every((pair) => Array.isArray(pair) && pair.length === 2 && pair.every((part) => typeof part === "string"))) {
|
|
128
|
+
return "opentide/fetch's headers are [name, value] pairs";
|
|
129
|
+
}
|
|
130
|
+
if (body !== null && body !== undefined && typeof body !== "string") {
|
|
131
|
+
return "opentide/fetch's body is base64 or null";
|
|
132
|
+
}
|
|
133
|
+
const number = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
134
|
+
const verify = isObject(settings) && settings.verify === false ? false : true;
|
|
135
|
+
const bundles = isObject(settings) && Array.isArray(settings.ca_bundles)
|
|
136
|
+
? settings.ca_bundles.filter((pem) => typeof pem === "string")
|
|
137
|
+
: [];
|
|
138
|
+
return {
|
|
139
|
+
run: typeof params.run === "string" ? params.run : null,
|
|
140
|
+
platform: typeof params.platform === "string" ? params.platform : "",
|
|
141
|
+
tenant: typeof params.tenant === "string" ? params.tenant : "",
|
|
142
|
+
method,
|
|
143
|
+
url,
|
|
144
|
+
headers: headers,
|
|
145
|
+
body: typeof body === "string" ? body : null,
|
|
146
|
+
connect_timeout_ms: number(params.connect_timeout_ms, 120_000),
|
|
147
|
+
read_timeout_ms: number(params.read_timeout_ms, 120_000),
|
|
148
|
+
tls: { verify, ca_bundles: bundles },
|
|
149
|
+
proxy: typeof params.proxy === "string" && params.proxy !== "" ? params.proxy : null,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** *error* as a failure of a kind the server reads. */
|
|
153
|
+
function asFailure(error, signal) {
|
|
154
|
+
if (signal.aborted) {
|
|
155
|
+
return new FetchFailure("aborted", "the request was withdrawn");
|
|
156
|
+
}
|
|
157
|
+
if (error instanceof FetchFailure) {
|
|
158
|
+
return error;
|
|
159
|
+
}
|
|
160
|
+
return new FetchFailure("unreachable", error instanceof Error ? error.message : String(error));
|
|
161
|
+
}
|
|
162
|
+
/** Error codes of a connection that could not be made. */
|
|
163
|
+
const CONNECT_CODES = new Set([
|
|
164
|
+
"ECONNREFUSED",
|
|
165
|
+
"ENOTFOUND",
|
|
166
|
+
"EAI_AGAIN",
|
|
167
|
+
"EHOSTUNREACH",
|
|
168
|
+
"ENETUNREACH",
|
|
169
|
+
"ECONNRESET",
|
|
170
|
+
"EPIPE",
|
|
171
|
+
"ETIMEDOUT",
|
|
172
|
+
"CERT_HAS_EXPIRED",
|
|
173
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
174
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
175
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
176
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
177
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
178
|
+
]);
|
|
179
|
+
/** A socket error before the answer's headers, as the server reads it. */
|
|
180
|
+
function connectFailure(error) {
|
|
181
|
+
const code = isObject(error) && typeof error.code === "string" ? error.code : "";
|
|
182
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
183
|
+
if (code === "" || CONNECT_CODES.has(code) || code.startsWith("ERR_TLS") || code.startsWith("ERR_SSL")) {
|
|
184
|
+
return new FetchFailure("connect", message);
|
|
185
|
+
}
|
|
186
|
+
return new FetchFailure("unreachable", message);
|
|
187
|
+
}
|
|
188
|
+
/** The CA certificates a tenant trusts: the default store and its bundles. */
|
|
189
|
+
function trusted(bundles) {
|
|
190
|
+
return bundles.length === 0 ? undefined : [...tls.rootCertificates, ...bundles];
|
|
191
|
+
}
|
|
192
|
+
/** A socket to *target* through the proxy *proxy* (HTTP CONNECT). */
|
|
193
|
+
function tunnel(proxy, target, signal) {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
const port = target.port || (target.protocol === "https:" ? "443" : "80");
|
|
196
|
+
const headers = { host: `${target.hostname}:${port}` };
|
|
197
|
+
if (proxy.username !== "") {
|
|
198
|
+
const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
|
|
199
|
+
headers["proxy-authorization"] = `Basic ${Buffer.from(credentials).toString("base64")}`;
|
|
200
|
+
}
|
|
201
|
+
const module = proxy.protocol === "https:" ? https : http;
|
|
202
|
+
const request = module.request({
|
|
203
|
+
host: proxy.hostname,
|
|
204
|
+
port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
|
|
205
|
+
method: "CONNECT",
|
|
206
|
+
path: `${target.hostname}:${port}`,
|
|
207
|
+
headers,
|
|
208
|
+
signal,
|
|
209
|
+
});
|
|
210
|
+
request.once("connect", (answer, socket) => {
|
|
211
|
+
if (answer.statusCode === 200) {
|
|
212
|
+
resolve(socket);
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
socket.destroy();
|
|
216
|
+
reject(new FetchFailure("connect", `the proxy answered the tunnel with HTTP ${answer.statusCode}`));
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
request.once("error", (error) => reject(connectFailure(error)));
|
|
220
|
+
request.end();
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/** Sends one request and reads its answer whole, within the tenant's limits. */
|
|
224
|
+
async function exchange(url, method, headers, body, params, signal) {
|
|
225
|
+
const secure = url.protocol === "https:";
|
|
226
|
+
if (!secure && url.protocol !== "http:") {
|
|
227
|
+
throw new FetchFailure("unreachable", `URL scheme is not allowed: ${url.protocol}`);
|
|
228
|
+
}
|
|
229
|
+
const proxy = params.proxy === null ? null : new URL(params.proxy.includes("://") ? params.proxy : `http://${params.proxy}`);
|
|
230
|
+
const started = Date.now();
|
|
231
|
+
// Through a proxy, an https request is tunnelled; an http one goes to the
|
|
232
|
+
// proxy with its absolute URL.
|
|
233
|
+
let socket;
|
|
234
|
+
if (proxy !== null && secure) {
|
|
235
|
+
socket = await withTimeout(tunnel(proxy, url, signal), params.connect_timeout_ms, "connect", signal);
|
|
236
|
+
}
|
|
237
|
+
// In the order written; a repeated name sends each of its values.
|
|
238
|
+
const outgoing = {};
|
|
239
|
+
for (const [name, value] of headers) {
|
|
240
|
+
const known = outgoing[name];
|
|
241
|
+
outgoing[name] = known === undefined ? value : [...(Array.isArray(known) ? known : [known]), value];
|
|
242
|
+
}
|
|
243
|
+
const options = {
|
|
244
|
+
method,
|
|
245
|
+
headers: outgoing,
|
|
246
|
+
signal,
|
|
247
|
+
rejectUnauthorized: params.tls.verify,
|
|
248
|
+
ca: trusted(params.tls.ca_bundles),
|
|
249
|
+
servername: net.isIP(url.hostname) === 0 ? url.hostname : undefined,
|
|
250
|
+
};
|
|
251
|
+
let target = url;
|
|
252
|
+
if (socket !== undefined) {
|
|
253
|
+
const tunnelled = socket;
|
|
254
|
+
options.createConnection = () => tls.connect({
|
|
255
|
+
socket: tunnelled,
|
|
256
|
+
servername: net.isIP(url.hostname) === 0 ? url.hostname : undefined,
|
|
257
|
+
rejectUnauthorized: params.tls.verify,
|
|
258
|
+
ca: trusted(params.tls.ca_bundles),
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
else if (proxy !== null) {
|
|
262
|
+
options.host = proxy.hostname;
|
|
263
|
+
options.port = proxy.port || 80;
|
|
264
|
+
options.path = url.href;
|
|
265
|
+
// The tenant's Host, not the proxy's, as requests sends it.
|
|
266
|
+
if (!Object.keys(outgoing).some((name) => name.toLowerCase() === "host")) {
|
|
267
|
+
outgoing.host = url.host;
|
|
268
|
+
}
|
|
269
|
+
target = `http://${proxy.host}`;
|
|
270
|
+
}
|
|
271
|
+
const module = secure ? https : http;
|
|
272
|
+
return new Promise((resolve, reject) => {
|
|
273
|
+
let settled = false;
|
|
274
|
+
const fail = (failure) => {
|
|
275
|
+
if (!settled) {
|
|
276
|
+
settled = true;
|
|
277
|
+
clearTimeout(connectTimer);
|
|
278
|
+
request.destroy();
|
|
279
|
+
reject(failure);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
const request = module.request(target, options);
|
|
283
|
+
// The connect limit runs until the connection (TLS included) is up; the
|
|
284
|
+
// read limit, from then on, for each wait on the answer.
|
|
285
|
+
const connectTimer = setTimeout(() => fail(new FetchFailure("connect", `no connection within ${params.connect_timeout_ms} ms`)), params.connect_timeout_ms);
|
|
286
|
+
request.once("socket", (opened) => {
|
|
287
|
+
const connected = () => {
|
|
288
|
+
clearTimeout(connectTimer);
|
|
289
|
+
opened.setTimeout(params.read_timeout_ms, () => fail(new FetchFailure("timeout", `no answer within ${params.read_timeout_ms} ms`)));
|
|
290
|
+
};
|
|
291
|
+
if (opened.connecting) {
|
|
292
|
+
opened.once(secure ? "secureConnect" : "connect", connected);
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
connected();
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
request.once("error", (error) => {
|
|
299
|
+
if (signal.aborted) {
|
|
300
|
+
fail(new FetchFailure("aborted", "the request was withdrawn"));
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
fail(connectFailure(error));
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
request.once("response", (answer) => {
|
|
307
|
+
const elapsed = Date.now() - started;
|
|
308
|
+
const pairs = [];
|
|
309
|
+
for (let index = 0; index + 1 < answer.rawHeaders.length; index += 2) {
|
|
310
|
+
pairs.push([answer.rawHeaders[index].toLowerCase(), answer.rawHeaders[index + 1]]);
|
|
311
|
+
}
|
|
312
|
+
const chunks = [];
|
|
313
|
+
answer.on("data", (chunk) => chunks.push(chunk));
|
|
314
|
+
answer.once("error", (error) => fail(signal.aborted ? new FetchFailure("aborted", "the request was withdrawn") : new FetchFailure("answer", error.message)));
|
|
315
|
+
answer.once("aborted", () => fail(new FetchFailure("answer", "the connection closed before the answer's end")));
|
|
316
|
+
answer.once("end", () => {
|
|
317
|
+
if (!settled) {
|
|
318
|
+
settled = true;
|
|
319
|
+
clearTimeout(connectTimer);
|
|
320
|
+
resolve({ status: answer.statusCode ?? 0, headers: pairs, body: Buffer.concat(chunks), elapsed });
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
if (body !== null) {
|
|
325
|
+
request.write(body);
|
|
326
|
+
}
|
|
327
|
+
request.end();
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
/** *work*, or a failure of *kind* after *ms*. */
|
|
331
|
+
function withTimeout(work, ms, kind, signal) {
|
|
332
|
+
return new Promise((resolve, reject) => {
|
|
333
|
+
const timer = setTimeout(() => reject(new FetchFailure(kind, `no connection within ${ms} ms`)), ms);
|
|
334
|
+
const aborted = () => {
|
|
335
|
+
clearTimeout(timer);
|
|
336
|
+
reject(new FetchFailure("aborted", "the request was withdrawn"));
|
|
337
|
+
};
|
|
338
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
339
|
+
work.then((value) => {
|
|
340
|
+
clearTimeout(timer);
|
|
341
|
+
signal.removeEventListener("abort", aborted);
|
|
342
|
+
resolve(value);
|
|
343
|
+
}, (error) => {
|
|
344
|
+
clearTimeout(timer);
|
|
345
|
+
signal.removeEventListener("abort", aborted);
|
|
346
|
+
reject(error);
|
|
347
|
+
});
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Whether a redirect from *from* to *to* is followed, as the native
|
|
352
|
+
* transport's `follows_redirect`: on the same origin, or from `http` to
|
|
353
|
+
* `https` on the same host with default ports. Any other hop would carry a
|
|
354
|
+
* platform's own credential header (Carbon Black's `X-Auth-Token`,
|
|
355
|
+
* Bitdefender's `X-API-Key`) to another host, so it is not taken (#1142).
|
|
356
|
+
*/
|
|
357
|
+
export function followsRedirect(from, to) {
|
|
358
|
+
if (from.origin === to.origin) {
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
return (from.protocol === "http:" &&
|
|
362
|
+
to.protocol === "https:" &&
|
|
363
|
+
from.hostname === to.hostname &&
|
|
364
|
+
from.port === "" &&
|
|
365
|
+
to.port === "");
|
|
366
|
+
}
|
|
367
|
+
/** Headers no redirect to another origin carries (as reqwest strips them). */
|
|
368
|
+
const SENSITIVE = new Set(["authorization", "cookie", "proxy-authorization", "www-authenticate"]);
|
|
369
|
+
/**
|
|
370
|
+
* Makes the request *params* describe with Node's HTTP stack, following
|
|
371
|
+
* redirects as the native transport does: at most `MAX_REDIRECTS`, and only
|
|
372
|
+
* those `followsRedirect` takes (any other is the answer); a 303, and a 301
|
|
373
|
+
* or 302 to a POST, become a GET without a body; the standard credentials
|
|
374
|
+
* are not sent to another origin (an http to https upgrade).
|
|
375
|
+
*/
|
|
376
|
+
export async function performRequest(params, signal) {
|
|
377
|
+
let url = new URL(params.url);
|
|
378
|
+
let method = params.method;
|
|
379
|
+
let headers = params.headers;
|
|
380
|
+
let body = params.body === null ? null : Buffer.from(params.body, "base64");
|
|
381
|
+
let elapsed;
|
|
382
|
+
for (let redirects = 0;; redirects += 1) {
|
|
383
|
+
const answer = await exchange(url, method, headers, body, params, signal);
|
|
384
|
+
elapsed ??= answer.elapsed;
|
|
385
|
+
const location = answer.headers.find(([name]) => name === "location")?.[1];
|
|
386
|
+
const next = location === undefined ? undefined : new URL(location, url);
|
|
387
|
+
const redirected = [301, 302, 303, 307, 308].includes(answer.status) && next !== undefined && followsRedirect(url, next);
|
|
388
|
+
if (!redirected || next === undefined || redirects >= MAX_REDIRECTS) {
|
|
389
|
+
return {
|
|
390
|
+
status: answer.status,
|
|
391
|
+
headers: answer.headers,
|
|
392
|
+
url: url.href,
|
|
393
|
+
body: answer.body.toString("base64"),
|
|
394
|
+
elapsed_ms: elapsed,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (answer.status === 303 || ((answer.status === 301 || answer.status === 302) && method === "POST")) {
|
|
398
|
+
method = "GET";
|
|
399
|
+
body = null;
|
|
400
|
+
headers = headers.filter(([name]) => !["content-type", "content-length"].includes(name.toLowerCase()));
|
|
401
|
+
}
|
|
402
|
+
if (next.origin !== url.origin) {
|
|
403
|
+
headers = headers.filter(([name]) => !SENSITIVE.has(name.toLowerCase()));
|
|
404
|
+
}
|
|
405
|
+
url = next;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
// ---- opentide mcp start, its tenant requests among its MCP messages ----
|
|
409
|
+
/** The variable that makes the WASI build's `opentide mcp start` ask its client for each tenant request. */
|
|
410
|
+
export const MCP_FETCH_VARIABLE = "OPENTIDE_FETCH";
|
|
411
|
+
/**
|
|
412
|
+
* The environment to start the WASI module's `opentide mcp start` with, added
|
|
413
|
+
* to whatever else it is given (the native build ignores it).
|
|
414
|
+
*/
|
|
415
|
+
export const MCP_FETCH_ENVIRONMENT = { [MCP_FETCH_VARIABLE]: "stdio" };
|
|
416
|
+
/** The prefix of the ids of `opentide mcp start`'s requests: no MCP client's id starts so by accident. */
|
|
417
|
+
export const MCP_FETCH_ID_PREFIX = "opentide-fetch-";
|
|
418
|
+
/** Splits a stream of chunks into lines, holding back a partial one. */
|
|
419
|
+
class LineSplitter {
|
|
420
|
+
decoder = new TextDecoder();
|
|
421
|
+
partial = "";
|
|
422
|
+
push(chunk) {
|
|
423
|
+
this.partial += typeof chunk === "string" ? chunk : this.decoder.decode(chunk, { stream: true });
|
|
424
|
+
const lines = [];
|
|
425
|
+
for (let end = this.partial.indexOf("\n"); end >= 0; end = this.partial.indexOf("\n")) {
|
|
426
|
+
lines.push(this.partial.slice(0, end + 1));
|
|
427
|
+
this.partial = this.partial.slice(end + 1);
|
|
428
|
+
}
|
|
429
|
+
return lines;
|
|
430
|
+
}
|
|
431
|
+
/** What is left when the stream ends: a last line without its newline. */
|
|
432
|
+
end() {
|
|
433
|
+
const rest = this.partial + this.decoder.decode();
|
|
434
|
+
this.partial = "";
|
|
435
|
+
return rest === "" ? undefined : `${rest}\n`;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Splits `opentide mcp start`'s tenant requests from its MCP messages on its
|
|
440
|
+
* stdio pair. Started with `MCP_FETCH_ENVIRONMENT`, the WASI module writes
|
|
441
|
+
* each tenant request as an `opentide/fetch` line on stdout among its MCP
|
|
442
|
+
* messages, and reads the answer on stdin among the client's. The bridge sits
|
|
443
|
+
* between the module and the MCP client:
|
|
444
|
+
*
|
|
445
|
+
* - `fromServer(chunk)`: the module's stdout. An `opentide/fetch` line (and
|
|
446
|
+
* the `notifications/cancelled` that withdraws one) is the host's, which
|
|
447
|
+
* answers it with `FetchHost`; every other line goes to `toClient`.
|
|
448
|
+
* - `fromClient(chunk)`: the client's messages, to `toServer` a whole line at
|
|
449
|
+
* a time, so an answer the host writes never lands inside one.
|
|
450
|
+
*
|
|
451
|
+
* Neither direction reorders anything: the MCP messages reach each side in the
|
|
452
|
+
* order they were written. `toServer` is called for answers asynchronously, as
|
|
453
|
+
* each request finishes.
|
|
454
|
+
*
|
|
455
|
+
* What the bridge keeps from the client, and from the agent behind it:
|
|
456
|
+
*
|
|
457
|
+
* - **A tenant request never reaches the client.** It carries the tenant's
|
|
458
|
+
* credentials (the `Authorization` and API-key headers, the CA bundles). A
|
|
459
|
+
* line that mentions `opentide/fetch` and cannot be read as a message of the
|
|
460
|
+
* host's is dropped, not forwarded: nothing that might hold a credential
|
|
461
|
+
* goes to `toClient` on a failure to understand it.
|
|
462
|
+
* - **The client cannot answer a tenant request.** A client line that is a
|
|
463
|
+
* response (it has no `method`) to an id with the `MCP_FETCH_ID_PREFIX`, or
|
|
464
|
+
* that mentions the prefix and cannot be read, is dropped: the module trusts
|
|
465
|
+
* an answer on its stdin for the request it asked, and an agent could
|
|
466
|
+
* otherwise forge the result of a deploy or a query.
|
|
467
|
+
* - **A response to a request the client cancelled is dropped.** The module may
|
|
468
|
+
* still finish a call it was told to cancel, and MCP has the receiver send
|
|
469
|
+
* no response for it.
|
|
470
|
+
* - **After `dispose()` no new tenant request is started.**
|
|
471
|
+
*/
|
|
472
|
+
export class McpFetchBridge {
|
|
473
|
+
sink;
|
|
474
|
+
host;
|
|
475
|
+
fromModule = new LineSplitter();
|
|
476
|
+
fromAgent = new LineSplitter();
|
|
477
|
+
/** Request ids the client cancelled (as their JSON text): their responses are dropped. */
|
|
478
|
+
cancelled = new Set();
|
|
479
|
+
disposed = false;
|
|
480
|
+
/** Told of an error a line raised (the line is dropped); none by default. */
|
|
481
|
+
onError;
|
|
482
|
+
constructor(sink, options = {}) {
|
|
483
|
+
this.sink = sink;
|
|
484
|
+
this.onError = options.onError ?? (() => { });
|
|
485
|
+
this.host = new FetchHost((message) => {
|
|
486
|
+
// After the module has gone there is nobody to answer.
|
|
487
|
+
if (!this.disposed) {
|
|
488
|
+
this.sink.toServer(`${JSON.stringify(message)}\n`);
|
|
489
|
+
}
|
|
490
|
+
}, options);
|
|
491
|
+
}
|
|
492
|
+
/** The number of tenant requests in flight. */
|
|
493
|
+
get pending() {
|
|
494
|
+
return this.host.pending;
|
|
495
|
+
}
|
|
496
|
+
/** A chunk of the module's stdout. */
|
|
497
|
+
fromServer(chunk) {
|
|
498
|
+
for (const line of this.fromModule.push(chunk)) {
|
|
499
|
+
this.isolated(() => this.serverLine(line));
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
/** A chunk of the client's messages for the module. */
|
|
503
|
+
fromClient(chunk) {
|
|
504
|
+
for (const line of this.fromAgent.push(chunk)) {
|
|
505
|
+
this.isolated(() => this.clientLine(line));
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** The module's stdout ended: a last line without its newline is delivered. */
|
|
509
|
+
endServer() {
|
|
510
|
+
const rest = this.fromModule.end();
|
|
511
|
+
if (rest !== undefined) {
|
|
512
|
+
this.isolated(() => this.serverLine(rest));
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/** The client's input ended: a last line without its newline is delivered. */
|
|
516
|
+
endClient() {
|
|
517
|
+
const rest = this.fromAgent.end();
|
|
518
|
+
if (rest !== undefined) {
|
|
519
|
+
this.isolated(() => this.clientLine(rest));
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
/** Aborts every request in flight, unanswered: the module has gone. */
|
|
523
|
+
dispose() {
|
|
524
|
+
this.disposed = true;
|
|
525
|
+
this.host.dispose();
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Runs the handling of one line so that nothing it raises (a line that overflows the stack,
|
|
529
|
+
* a sink that throws) escapes into the host's data handler or costs the lines after it:
|
|
530
|
+
* the line is dropped, and `onError` is told.
|
|
531
|
+
*/
|
|
532
|
+
isolated(handle) {
|
|
533
|
+
try {
|
|
534
|
+
handle();
|
|
535
|
+
}
|
|
536
|
+
catch (error) {
|
|
537
|
+
try {
|
|
538
|
+
this.onError(error);
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
// A reporter that throws is no reason to lose the lines that follow.
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
clientLine(line) {
|
|
546
|
+
// Decided on the parsed value, never on the text: JSON lets any character of
|
|
547
|
+
// an id or a key be written as a `\uXXXX` escape, which the module's parser
|
|
548
|
+
// decodes, so `"opentide-fetch-..."` can be written with no substring of it.
|
|
549
|
+
// Every line that could be a message is parsed (a client's lines are small).
|
|
550
|
+
let message;
|
|
551
|
+
try {
|
|
552
|
+
// The module's transport skips a byte-order mark; so does the bridge, to judge the same value.
|
|
553
|
+
message = JSON.parse(line.replace(/^\uFEFF/, ""));
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
// Fail closed: a line that looks like JSON (an object or a batch) and cannot be
|
|
557
|
+
// read is not passed on; the module would skip it as not JSON, and nothing it
|
|
558
|
+
// might hide is let through. Anything else (a blank line, a `Content-Length`
|
|
559
|
+
// header) is not a message and goes on.
|
|
560
|
+
if (/^\s*[{[]/.test(line)) {
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
this.sink.toServer(line);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (forgesAnAnswer(message)) {
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
const id = cancelledRequest(message);
|
|
570
|
+
if (id !== undefined) {
|
|
571
|
+
this.cancelled.add(id);
|
|
572
|
+
// Bounded: the oldest are forgotten (a cancelled request that was already answered).
|
|
573
|
+
while (this.cancelled.size > MAX_CANCELLED) {
|
|
574
|
+
const oldest = this.cancelled.values().next().value;
|
|
575
|
+
if (oldest === undefined)
|
|
576
|
+
break;
|
|
577
|
+
this.cancelled.delete(oldest);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
this.sink.toServer(line);
|
|
581
|
+
}
|
|
582
|
+
serverLine(line) {
|
|
583
|
+
// The module's own lines are the one place a substring test is sound: it writes
|
|
584
|
+
// compact `serde_json`, which escapes nothing in the ASCII text `"opentide/fetch"` or
|
|
585
|
+
// `notifications/cancelled` (the characters `/`, letters and digits are written
|
|
586
|
+
// as they are), and what the module writes is not the agent's to shape. (The client's
|
|
587
|
+
// lines are different: an agent can escape any character, see `clientLine`.) A line
|
|
588
|
+
// that mentions either is parsed and judged on its value; any other is passed on unread.
|
|
589
|
+
if (line.includes("opentide/fetch")) {
|
|
590
|
+
let message;
|
|
591
|
+
try {
|
|
592
|
+
message = JSON.parse(line);
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
// Fail closed: a line that mentions the method and cannot be read may
|
|
596
|
+
// hold a tenant's credentials, and is never forwarded.
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (!isObject(message) || message.method === "opentide/fetch") {
|
|
600
|
+
// A tenant request (or something shaped so it cannot be told from
|
|
601
|
+
// one): the host's alone, started only while the bridge is live.
|
|
602
|
+
if (!this.disposed && isObject(message)) {
|
|
603
|
+
this.host.handle(message);
|
|
604
|
+
}
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
// Valid JSON that is not a request: an MCP message that mentions the
|
|
608
|
+
// method in its text (a tool's result), passed on below.
|
|
609
|
+
}
|
|
610
|
+
if (line.includes("notifications/cancelled")) {
|
|
611
|
+
const message = parseObject(line);
|
|
612
|
+
if (message !== undefined && this.takesWithdrawal(message)) {
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (this.cancelled.size > 0 && this.dropsCancelledResponse(line)) {
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
this.sink.toClient(line);
|
|
620
|
+
}
|
|
621
|
+
/** Whether *message* withdraws one of the module's tenant requests: the host's, handled. */
|
|
622
|
+
takesWithdrawal(message) {
|
|
623
|
+
if (message.method !== "notifications/cancelled") {
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
const params = message.params;
|
|
627
|
+
if (!isObject(params) || typeof params.requestId !== "string" || !params.requestId.startsWith(MCP_FETCH_ID_PREFIX)) {
|
|
628
|
+
return false;
|
|
629
|
+
}
|
|
630
|
+
// A withdrawal of a request already answered has nothing to abort, and is not the client's either.
|
|
631
|
+
this.host.handle(message);
|
|
632
|
+
return true;
|
|
633
|
+
}
|
|
634
|
+
/** Whether *line* is the response to a request the client cancelled; the id is then forgotten. */
|
|
635
|
+
dropsCancelledResponse(line) {
|
|
636
|
+
for (const id of this.cancelled) {
|
|
637
|
+
if (!line.includes(`"id":${id}`)) {
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
const message = parseObject(line);
|
|
641
|
+
if (message !== undefined && message.method === undefined && JSON.stringify(message.id) === id) {
|
|
642
|
+
this.cancelled.delete(id);
|
|
643
|
+
return true;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return false;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/** How many cancelled request ids the bridge remembers. */
|
|
650
|
+
const MAX_CANCELLED = 256;
|
|
651
|
+
/** *line* as an object, or undefined. */
|
|
652
|
+
function parseObject(line) {
|
|
653
|
+
try {
|
|
654
|
+
const message = JSON.parse(line);
|
|
655
|
+
return isObject(message) ? message : undefined;
|
|
656
|
+
}
|
|
657
|
+
catch {
|
|
658
|
+
return undefined;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/** The id (as JSON text) of the request the parsed *message* cancels, if it is a `notifications/cancelled`. */
|
|
662
|
+
function cancelledRequest(message) {
|
|
663
|
+
if (!isObject(message) || message.method !== "notifications/cancelled" || !isObject(message.params)) {
|
|
664
|
+
return undefined;
|
|
665
|
+
}
|
|
666
|
+
const id = message.params.requestId;
|
|
667
|
+
return typeof id === "string" || typeof id === "number" ? JSON.stringify(id) : undefined;
|
|
668
|
+
}
|
|
669
|
+
/** How deep a batch may nest: `serde_json`'s recursion limit, past which the module refuses the line. */
|
|
670
|
+
const MAX_BATCH_DEPTH = 128;
|
|
671
|
+
/**
|
|
672
|
+
* Whether the client message *message* answers (or is shaped to look like an
|
|
673
|
+
* answer to) a request of the module's: a response, with no string `method`, to
|
|
674
|
+
* an id that starts with `MCP_FETCH_ID_PREFIX`. A batch holding one is one, to any
|
|
675
|
+
* depth up to the module's own limit; a batch nested deeper than that is dropped
|
|
676
|
+
* too (the module would refuse it, and walking it must not overflow the stack,
|
|
677
|
+
* so the walk is iterative).
|
|
678
|
+
*/
|
|
679
|
+
function forgesAnAnswer(message) {
|
|
680
|
+
const pending = [[message, 0]];
|
|
681
|
+
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
|
|
682
|
+
const [item, depth] = next;
|
|
683
|
+
if (Array.isArray(item)) {
|
|
684
|
+
if (depth >= MAX_BATCH_DEPTH) {
|
|
685
|
+
return true;
|
|
686
|
+
}
|
|
687
|
+
for (const element of item) {
|
|
688
|
+
pending.push([element, depth + 1]);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
else if (isObject(item) &&
|
|
692
|
+
typeof item.id === "string" &&
|
|
693
|
+
item.id.startsWith(MCP_FETCH_ID_PREFIX) &&
|
|
694
|
+
typeof item.method !== "string") {
|
|
695
|
+
return true;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return false;
|
|
699
|
+
}
|
package/package.json
CHANGED
|
@@ -1 +1,40 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@opentide/wasi-host",
|
|
3
|
+
"version": "1.0.0-rc.4",
|
|
4
|
+
"description": "The extension host's half of opentide's `opentide/fetch`: tenant HTTP for the WASI build of opentide, made with Node's HTTP stack.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "node --experimental-strip-types --test src/index.test.ts",
|
|
23
|
+
"build": "tsc -p tsconfig.json",
|
|
24
|
+
"prepack": "npm run build"
|
|
25
|
+
},
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/opentidehq/opentide.git",
|
|
30
|
+
"directory": "packages/wasi-host"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"provenance": true
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "26.6.6",
|
|
38
|
+
"typescript": "5.9.3"
|
|
39
|
+
}
|
|
40
|
+
}
|