@opencode/browse 0.0.18-dev.192 → 0.0.18-dev.198
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/dist/cli.mjs +62 -107
- package/package.json +13 -33
- package/dist/Runtime-tvxdkp60.mjs +0 -16
- package/dist/THIRD_PARTY_NOTICES.txt +0 -310
- package/dist/Undici-xgvbtsb1.mjs +0 -25295
- package/dist/cli-54nftqxr.mjs +0 -5939
- package/dist/coreBundle-mbshhes2.mjs +0 -8
- package/dist/helpers-yksnc17b.mjs +0 -70
- package/dist/index-kmxtpxxk.mjs +0 -13
- package/dist/legacy-runtime-e6y2jnc6.mjs +0 -134
- package/dist/main-4fw36c57.mjs +0 -160
- package/dist/main-4wycvga6.mjs +0 -797
- package/dist/main-c9qxrdzn.mjs +0 -73
- package/dist/main-d1th6z2h.mjs +0 -5395
- package/dist/main-de0xhbg0.mjs +0 -1269
- package/dist/main-dyya6jpy.mjs +0 -140
- package/dist/main-gexpjhk5.mjs +0 -32
- package/dist/main-h65pjrag.mjs +0 -11403
- package/dist/main-hh16893t.mjs +0 -5358
- package/dist/main-j98fzrvv.mjs +0 -68
- package/dist/main-jtgan144.mjs +0 -327
- package/dist/main-p44hff2a.mjs +0 -213
- package/dist/main-p8jk5985.mjs +0 -1750
- package/dist/main-p8q3wrpd.mjs +0 -342
- package/dist/main-pmfd055v.mjs +0 -63
- package/dist/main-q5w61fgh.mjs +0 -17
- package/dist/main-t8hspw29.mjs +0 -922
- package/dist/main-t8xtycpr.mjs +0 -227
- package/dist/main-tk4axre7.mjs +0 -39
- package/dist/main-w6180mxa.mjs +0 -161
- package/dist/main-wds0wcmt.mjs +0 -4
- package/dist/main-z4c819pg.mjs +0 -5512
- package/dist/main-zrjcdksk.mjs +0 -62
- package/dist/mcp-a2jkny55.mjs +0 -9466
- package/dist/migrate-p84kbr3y.mjs +0 -353
- package/dist/relay-e9q9hfc3.mjs +0 -18369
- package/dist/remove-stored-secrets-c90a5h72.mjs +0 -6
- package/dist/runtime-update-jj6pa7vd.mjs +0 -244
- package/dist/setup-p86ywb7k.mjs +0 -1051
- package/dist/update-rh24h3m1.mjs +0 -17
- package/dist/version-1p8wpyzk.mjs +0 -8
package/dist/main-de0xhbg0.mjs
DELETED
|
@@ -1,1269 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
browserUnresponsive,
|
|
3
|
-
extensionReconnectAlarmPeriodMs,
|
|
4
|
-
extensionProtocolAdvice,
|
|
5
|
-
compareVersions,
|
|
6
|
-
installedRuntime2,
|
|
7
|
-
installedVersion
|
|
8
|
-
} from "./main-4wycvga6.mjs";
|
|
9
|
-
import {
|
|
10
|
-
ensurePrivateDirectorySync,
|
|
11
|
-
SessionContainer,
|
|
12
|
-
SessionsContainer,
|
|
13
|
-
SessionDeleted,
|
|
14
|
-
SessionResetResponse,
|
|
15
|
-
SessionAdoptResponse,
|
|
16
|
-
ExecuteResponse,
|
|
17
|
-
AuthenticatedJsonOutcome,
|
|
18
|
-
TargetSummaries,
|
|
19
|
-
ExtensionStatus,
|
|
20
|
-
RelayVersion,
|
|
21
|
-
RelayShutdownRequest,
|
|
22
|
-
RelayShutdownResponse,
|
|
23
|
-
NetworkStatusResponse,
|
|
24
|
-
NetworkStopResponse,
|
|
25
|
-
NetworkCancelResponse,
|
|
26
|
-
RecordingStartResponse,
|
|
27
|
-
RecordingStopResponse,
|
|
28
|
-
RecordingStatusResponse,
|
|
29
|
-
TabsCleanupResponse,
|
|
30
|
-
SettingsGetResponse,
|
|
31
|
-
SettingsSetResponse,
|
|
32
|
-
RecordingCancelResponse,
|
|
33
|
-
RelayErrorCode,
|
|
34
|
-
ErrorEnvelope,
|
|
35
|
-
defaultPort2
|
|
36
|
-
} from "./main-t8hspw29.mjs";
|
|
37
|
-
import {
|
|
38
|
-
get,
|
|
39
|
-
post,
|
|
40
|
-
setHeader,
|
|
41
|
-
bodyJson,
|
|
42
|
-
HttpClient,
|
|
43
|
-
layerNodeHttp
|
|
44
|
-
} from "./main-hh16893t.mjs";
|
|
45
|
-
import {
|
|
46
|
-
opencodeBrowserBuildId2
|
|
47
|
-
} from "./main-wds0wcmt.mjs";
|
|
48
|
-
import {
|
|
49
|
-
relayAuthorization
|
|
50
|
-
} from "./main-c9qxrdzn.mjs";
|
|
51
|
-
import {
|
|
52
|
-
endpointForPort,
|
|
53
|
-
configuredRelayPort,
|
|
54
|
-
relayPortPinned,
|
|
55
|
-
readRelayState,
|
|
56
|
-
processAlive,
|
|
57
|
-
resolveRelayPort
|
|
58
|
-
} from "./main-p44hff2a.mjs";
|
|
59
|
-
import {
|
|
60
|
-
stateRoot,
|
|
61
|
-
compiledBinary,
|
|
62
|
-
scriptEntry,
|
|
63
|
-
cliCommand,
|
|
64
|
-
installCommand
|
|
65
|
-
} from "./main-dyya6jpy.mjs";
|
|
66
|
-
import {
|
|
67
|
-
Pointer,
|
|
68
|
-
passthrough,
|
|
69
|
-
transformEffect,
|
|
70
|
-
Transformation,
|
|
71
|
-
unknown,
|
|
72
|
-
applyToSelfOrLastLinkEncoding,
|
|
73
|
-
decodeTo,
|
|
74
|
-
toEncoded,
|
|
75
|
-
_is,
|
|
76
|
-
decodeUnknownEffect,
|
|
77
|
-
SchemaError,
|
|
78
|
-
decodeUnknownEffect2,
|
|
79
|
-
decodeUnknownOption,
|
|
80
|
-
make8,
|
|
81
|
-
optionalKey,
|
|
82
|
-
String3,
|
|
83
|
-
Number2,
|
|
84
|
-
Boolean3,
|
|
85
|
-
Struct,
|
|
86
|
-
NullOr,
|
|
87
|
-
BooleanLiterals,
|
|
88
|
-
Int2,
|
|
89
|
-
Defect,
|
|
90
|
-
TaggedError2,
|
|
91
|
-
toCodecStringTree
|
|
92
|
-
} from "./main-z4c819pg.mjs";
|
|
93
|
-
import {
|
|
94
|
-
__require
|
|
95
|
-
} from "./main-j98fzrvv.mjs";
|
|
96
|
-
import {
|
|
97
|
-
dual,
|
|
98
|
-
memoize,
|
|
99
|
-
isTagged,
|
|
100
|
-
assignProperty,
|
|
101
|
-
PipeInspectableProto,
|
|
102
|
-
Prototype2,
|
|
103
|
-
none,
|
|
104
|
-
some,
|
|
105
|
-
isSome,
|
|
106
|
-
getOrElse,
|
|
107
|
-
map2,
|
|
108
|
-
Service2,
|
|
109
|
-
Reference,
|
|
110
|
-
succeed,
|
|
111
|
-
fail2,
|
|
112
|
-
isFailure,
|
|
113
|
-
isSuccess,
|
|
114
|
-
map3,
|
|
115
|
-
isCanonicalArrayIndex,
|
|
116
|
-
effect,
|
|
117
|
-
provide2,
|
|
118
|
-
spaced,
|
|
119
|
-
succeed6,
|
|
120
|
-
suspend2,
|
|
121
|
-
sync2,
|
|
122
|
-
void_3,
|
|
123
|
-
fail6,
|
|
124
|
-
die3,
|
|
125
|
-
try_2,
|
|
126
|
-
fromResult,
|
|
127
|
-
flatMap3,
|
|
128
|
-
andThen2,
|
|
129
|
-
tap,
|
|
130
|
-
result,
|
|
131
|
-
map6,
|
|
132
|
-
asVoid2,
|
|
133
|
-
catch_,
|
|
134
|
-
catchDefect,
|
|
135
|
-
mapError2,
|
|
136
|
-
orDie,
|
|
137
|
-
tapError,
|
|
138
|
-
retry,
|
|
139
|
-
timeoutOrElse,
|
|
140
|
-
sleep,
|
|
141
|
-
raceFirst,
|
|
142
|
-
forever,
|
|
143
|
-
fnUntraced,
|
|
144
|
-
fn,
|
|
145
|
-
mapEager,
|
|
146
|
-
flatMapEager,
|
|
147
|
-
catchEager
|
|
148
|
-
} from "./main-d1th6z2h.mjs";
|
|
149
|
-
|
|
150
|
-
// node_modules/effect/dist/ConfigProvider.js
|
|
151
|
-
function makeValue(value) {
|
|
152
|
-
return {
|
|
153
|
-
_tag: "Value",
|
|
154
|
-
value
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
function makeRecord(keys, value) {
|
|
158
|
-
return {
|
|
159
|
-
_tag: "Record",
|
|
160
|
-
keys,
|
|
161
|
-
value
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
function makeArray(length, value) {
|
|
165
|
-
return {
|
|
166
|
-
_tag: "Array",
|
|
167
|
-
length,
|
|
168
|
-
value
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
var ConfigProvider = /* @__PURE__ */ Reference("effect/ConfigProvider", {
|
|
172
|
-
defaultValue: () => fromEnv()
|
|
173
|
-
});
|
|
174
|
-
var Proto = {
|
|
175
|
-
...PipeInspectableProto,
|
|
176
|
-
toJSON() {
|
|
177
|
-
return {
|
|
178
|
-
_id: "ConfigProvider"
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
var identityPath = (path) => path;
|
|
183
|
-
function makeProvider(load, mapInput) {
|
|
184
|
-
const self = Object.create(Proto);
|
|
185
|
-
self.load = load;
|
|
186
|
-
self.mapInput = mapInput;
|
|
187
|
-
return self;
|
|
188
|
-
}
|
|
189
|
-
function makeSource(get, transform) {
|
|
190
|
-
return makeProvider((path) => get(transform(path)), (f) => makeSource(get, (path) => f(transform(path))));
|
|
191
|
-
}
|
|
192
|
-
function make(get) {
|
|
193
|
-
return makeSource(get, identityPath);
|
|
194
|
-
}
|
|
195
|
-
function emptyStringAsMissing(value, preserveEmptyStrings) {
|
|
196
|
-
return value === "" && !preserveEmptyStrings ? undefined : value;
|
|
197
|
-
}
|
|
198
|
-
function fromEnvRecord(env, options) {
|
|
199
|
-
const preserveEmptyStrings = options?.preserveEmptyStrings === true;
|
|
200
|
-
const trie = buildEnvTrie(env);
|
|
201
|
-
return make((path) => succeed6(nodeAtEnv(trie, env, path, preserveEmptyStrings)));
|
|
202
|
-
}
|
|
203
|
-
function fromEnv(options) {
|
|
204
|
-
const env = options?.env ?? {
|
|
205
|
-
...globalThis.process?.env,
|
|
206
|
-
...import.meta?.env
|
|
207
|
-
};
|
|
208
|
-
return fromEnvRecord(env, {
|
|
209
|
-
preserveEmptyStrings: options?.preserveEmptyStrings
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
function buildEnvTrie(env) {
|
|
213
|
-
const trie = {};
|
|
214
|
-
for (const [name, value] of Object.entries(env)) {
|
|
215
|
-
if (value === undefined)
|
|
216
|
-
continue;
|
|
217
|
-
const segments = name.split("_");
|
|
218
|
-
let node = trie;
|
|
219
|
-
for (const seg of segments) {
|
|
220
|
-
const children = node.children ??= Object.create(null);
|
|
221
|
-
node = children[seg] ??= {};
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
return trie;
|
|
225
|
-
}
|
|
226
|
-
function nodeAtEnv(trie, env, path, preserveEmptyStrings) {
|
|
227
|
-
const key = path.map(String).join("_");
|
|
228
|
-
const leafValue = emptyStringAsMissing(Object.hasOwn(env, key) ? env[key] : undefined, preserveEmptyStrings);
|
|
229
|
-
const trieNode = trieNodeAt(trie, path);
|
|
230
|
-
const children = trieNode?.children ? Object.keys(trieNode.children) : [];
|
|
231
|
-
if (children.length === 0) {
|
|
232
|
-
return leafValue === undefined ? undefined : makeValue(leafValue);
|
|
233
|
-
}
|
|
234
|
-
const allNumeric = children.every(isCanonicalArrayIndex);
|
|
235
|
-
if (allNumeric) {
|
|
236
|
-
const length = Math.max(...children.map((k) => parseInt(k, 10))) + 1;
|
|
237
|
-
return makeArray(length, leafValue);
|
|
238
|
-
}
|
|
239
|
-
return makeRecord(new Set(children), leafValue);
|
|
240
|
-
}
|
|
241
|
-
function trieNodeAt(root, path) {
|
|
242
|
-
if (path.length === 0)
|
|
243
|
-
return root;
|
|
244
|
-
let node = root;
|
|
245
|
-
for (const seg of path) {
|
|
246
|
-
node = node?.children?.[String(seg)];
|
|
247
|
-
if (!node)
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
return node;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// node_modules/effect/dist/Config.js
|
|
254
|
-
var TypeId = "~effect/Config";
|
|
255
|
-
class ConfigError {
|
|
256
|
-
_tag = "ConfigError";
|
|
257
|
-
name = "ConfigError";
|
|
258
|
-
cause;
|
|
259
|
-
constructor(cause) {
|
|
260
|
-
this.cause = cause;
|
|
261
|
-
}
|
|
262
|
-
get message() {
|
|
263
|
-
return this.cause.toString();
|
|
264
|
-
}
|
|
265
|
-
toString() {
|
|
266
|
-
return `ConfigError(${this.message})`;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
var Proto2 = {
|
|
270
|
-
.../* @__PURE__ */ Prototype2({
|
|
271
|
-
label: "Config",
|
|
272
|
-
evaluate(fiber) {
|
|
273
|
-
return this.parse(fiber.getRef(ConfigProvider));
|
|
274
|
-
}
|
|
275
|
-
}),
|
|
276
|
-
[TypeId]: TypeId,
|
|
277
|
-
toJSON() {
|
|
278
|
-
return {
|
|
279
|
-
_id: "Config"
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
};
|
|
283
|
-
function make2(evaluator) {
|
|
284
|
-
const self = Object.create(Proto2);
|
|
285
|
-
self.evaluator = evaluator;
|
|
286
|
-
self.parse = (provider) => flatMapEager(evaluator(provider, []), fromResult);
|
|
287
|
-
return self;
|
|
288
|
-
}
|
|
289
|
-
var evaluateAt = (self, provider, pathPrefix) => self.evaluator(provider, pathPrefix);
|
|
290
|
-
var map = /* @__PURE__ */ dual(2, (self, f) => {
|
|
291
|
-
return make2((provider, pathPrefix) => map6(evaluateAt(self, provider, pathPrefix), map3(f)));
|
|
292
|
-
});
|
|
293
|
-
var withDefault = /* @__PURE__ */ dual(2, (self, defaultValue) => {
|
|
294
|
-
return make2((provider, pathPrefix) => mapEager(evaluateAt(self, provider, pathPrefix), (resolution) => isFailure(resolution) ? succeed(defaultValue) : resolution));
|
|
295
|
-
});
|
|
296
|
-
var option = (self) => self.pipe(map(some), withDefault(none()));
|
|
297
|
-
var isSourceError = (u) => isTagged(u, "SourceError");
|
|
298
|
-
var cursorToString = () => "<configuration>";
|
|
299
|
-
var loadCursor = (provider, path) => provider.load(path).pipe(orDie, mapEager((node) => ({
|
|
300
|
-
provider,
|
|
301
|
-
path,
|
|
302
|
-
node,
|
|
303
|
-
toString: cursorToString
|
|
304
|
-
})));
|
|
305
|
-
var loadChildCursor = (cursor, segment) => loadCursor(cursor.provider, [...cursor.path, segment]);
|
|
306
|
-
var decodeFromCursor = (ast, decode) => decodeTo(unknown, ast, new Transformation(transformEffect((input) => decode(input)), passthrough()));
|
|
307
|
-
var isScalarInput = (ast) => {
|
|
308
|
-
switch (ast._tag) {
|
|
309
|
-
case "Union":
|
|
310
|
-
return ast.types.every(isScalarInput);
|
|
311
|
-
case "Objects":
|
|
312
|
-
case "Arrays":
|
|
313
|
-
case "Suspend":
|
|
314
|
-
return false;
|
|
315
|
-
default:
|
|
316
|
-
return true;
|
|
317
|
-
}
|
|
318
|
-
};
|
|
319
|
-
var hasProviderInput = (ast, node) => {
|
|
320
|
-
switch (ast._tag) {
|
|
321
|
-
case "Objects":
|
|
322
|
-
return node?._tag === "Record";
|
|
323
|
-
case "Arrays":
|
|
324
|
-
return node?._tag === "Array";
|
|
325
|
-
case "Union":
|
|
326
|
-
return ast.types.some((ast) => hasProviderInput(ast, node));
|
|
327
|
-
case "Suspend":
|
|
328
|
-
return hasProviderInput(ast.thunk(), node);
|
|
329
|
-
default:
|
|
330
|
-
return node?.value !== undefined;
|
|
331
|
-
}
|
|
332
|
-
};
|
|
333
|
-
var toConfigCursorAST = /* @__PURE__ */ memoize((root) => {
|
|
334
|
-
const seen = new WeakSet;
|
|
335
|
-
const recur = applyToSelfOrLastLinkEncoding((ast) => {
|
|
336
|
-
seen.add(ast);
|
|
337
|
-
switch (ast._tag) {
|
|
338
|
-
case "Objects": {
|
|
339
|
-
const matchesIndex = ast.indexSignatures.map((is) => _is(is.parameter));
|
|
340
|
-
const materialize = fnUntraced(function* (cursor) {
|
|
341
|
-
if (cursor.node?._tag !== "Record") {
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
const node = cursor.node;
|
|
345
|
-
const keys = new Set;
|
|
346
|
-
for (const property of ast.propertySignatures) {
|
|
347
|
-
if (typeof property.name === "string")
|
|
348
|
-
keys.add(property.name);
|
|
349
|
-
}
|
|
350
|
-
if (matchesIndex.length > 0) {
|
|
351
|
-
for (const key of node.keys) {
|
|
352
|
-
if (matchesIndex.some((matches) => matches(key)))
|
|
353
|
-
keys.add(key);
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
const out = {};
|
|
357
|
-
for (const key of keys) {
|
|
358
|
-
const child = yield* loadChildCursor(cursor, key);
|
|
359
|
-
if (child.node !== undefined)
|
|
360
|
-
assignProperty(out, key, child);
|
|
361
|
-
}
|
|
362
|
-
return out;
|
|
363
|
-
});
|
|
364
|
-
return decodeFromCursor(ast.recur(recur, (ast) => ast), materialize);
|
|
365
|
-
}
|
|
366
|
-
case "Arrays": {
|
|
367
|
-
const materialize = fnUntraced(function* (cursor) {
|
|
368
|
-
if (cursor.node?._tag !== "Array") {
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
const out = [];
|
|
372
|
-
for (let i = 0;i < cursor.node.length; i++) {
|
|
373
|
-
out.push(yield* loadChildCursor(cursor, i));
|
|
374
|
-
}
|
|
375
|
-
return out;
|
|
376
|
-
});
|
|
377
|
-
return decodeFromCursor(ast.recur(recur), materialize);
|
|
378
|
-
}
|
|
379
|
-
case "Union":
|
|
380
|
-
for (const member of ast.types) {
|
|
381
|
-
recur(member);
|
|
382
|
-
}
|
|
383
|
-
if (!isScalarInput(ast))
|
|
384
|
-
return ast.recur(recur);
|
|
385
|
-
break;
|
|
386
|
-
case "Suspend": {
|
|
387
|
-
const target = ast.thunk();
|
|
388
|
-
if (!seen.has(target))
|
|
389
|
-
recur(target);
|
|
390
|
-
return ast.recur(recur);
|
|
391
|
-
}
|
|
392
|
-
case "Declaration":
|
|
393
|
-
case "Any":
|
|
394
|
-
throw new globalThis.Error("Config.schema does not support opaque StringTree encodings", {
|
|
395
|
-
cause: ast
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
return decodeFromCursor(ast, (cursor) => succeed6(cursor.node?.value));
|
|
399
|
-
});
|
|
400
|
-
return recur(root);
|
|
401
|
-
});
|
|
402
|
-
function schema(codec, path) {
|
|
403
|
-
const codecStringTree = toCodecStringTree(codec);
|
|
404
|
-
const encodedAst = toEncoded(codecStringTree.ast);
|
|
405
|
-
const decodeCursor = decodeUnknownEffect(make8(toConfigCursorAST(codecStringTree.ast)));
|
|
406
|
-
const localPath = typeof path === "string" ? [path] : path ?? [];
|
|
407
|
-
return make2((provider, pathPrefix) => {
|
|
408
|
-
const fullPath = [...pathPrefix, ...localPath];
|
|
409
|
-
return loadCursor(provider, fullPath).pipe(flatMapEager((cursor) => decodeCursor(cursor).pipe(mapEager(succeed), catchEager((issue) => {
|
|
410
|
-
const error = new ConfigError(new SchemaError(fullPath.length > 0 ? new Pointer(fullPath, issue) : issue));
|
|
411
|
-
return hasProviderInput(encodedAst, cursor.node) ? fail6(error) : succeed6(fail2(error));
|
|
412
|
-
}))), catchDefect((defect) => isSourceError(defect) ? fail6(new ConfigError(defect)) : die3(defect)));
|
|
413
|
-
});
|
|
414
|
-
}
|
|
415
|
-
function String2(name) {
|
|
416
|
-
return schema(String3, name);
|
|
417
|
-
}
|
|
418
|
-
function Int(name) {
|
|
419
|
-
return schema(Int2, name);
|
|
420
|
-
}
|
|
421
|
-
function Boolean2(name) {
|
|
422
|
-
return schema(BooleanLiterals, name);
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
// src/relay/lifecycle.ts
|
|
426
|
-
import { execFileSync, spawn } from "node:child_process";
|
|
427
|
-
import crypto from "node:crypto";
|
|
428
|
-
import path3 from "node:path";
|
|
429
|
-
import process3 from "node:process";
|
|
430
|
-
import { fileURLToPath } from "node:url";
|
|
431
|
-
// src/relay/client.ts
|
|
432
|
-
var portConfig = Int("OPENCODE_BROWSER_PORT").pipe(withDefault(defaultPort2));
|
|
433
|
-
var extensionOriginsConfig = String2("OPENCODE_BROWSER_EXTENSION_ORIGINS").pipe(withDefault(""));
|
|
434
|
-
var unknownRelayReadSeconds = 5;
|
|
435
|
-
var busyRelayReadSeconds = 30;
|
|
436
|
-
|
|
437
|
-
class RelayUnreachable extends TaggedError2()("RelayClient.RelayUnreachable", {
|
|
438
|
-
message: String3,
|
|
439
|
-
endpoint: String3,
|
|
440
|
-
path: String3,
|
|
441
|
-
cause: Defect()
|
|
442
|
-
}) {
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
class RelayRejected extends TaggedError2()("RelayClient.RelayRejected", {
|
|
446
|
-
message: String3,
|
|
447
|
-
status: Number2,
|
|
448
|
-
path: String3,
|
|
449
|
-
code: optionalKey(RelayErrorCode)
|
|
450
|
-
}) {
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
class RelayTimedOut extends TaggedError2()("RelayClient.RelayTimedOut", { message: String3, path: String3 }) {
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
class RelayDecodeFailed extends TaggedError2()("RelayClient.RelayDecodeFailed", {
|
|
457
|
-
message: String3,
|
|
458
|
-
path: String3,
|
|
459
|
-
cause: Defect()
|
|
460
|
-
}) {
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
class RelayEncodeFailed extends TaggedError2()("RelayClient.RelayEncodeFailed", {
|
|
464
|
-
message: String3,
|
|
465
|
-
path: String3,
|
|
466
|
-
cause: Defect()
|
|
467
|
-
}) {
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
class RelayConfigInvalid extends TaggedError2()("RelayClient.RelayConfigInvalid", {
|
|
471
|
-
message: String3,
|
|
472
|
-
cause: Defect()
|
|
473
|
-
}) {
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
class Service extends Service2()("opencode-browser-cli/RelayClient") {
|
|
477
|
-
}
|
|
478
|
-
var decodeErrorEnvelope = decodeUnknownOption(ErrorEnvelope);
|
|
479
|
-
var decodeErrorMessage = decodeUnknownOption(Struct({ error: String3 }));
|
|
480
|
-
var make3 = fn("RelayClient.make")(function* (options) {
|
|
481
|
-
yield* portConfig.pipe(mapError2((cause) => new RelayConfigInvalid({
|
|
482
|
-
message: `Invalid OPENCODE_BROWSER_PORT configuration: ${cause.message}`,
|
|
483
|
-
cause
|
|
484
|
-
})));
|
|
485
|
-
const currentEndpoint = () => options?.endpoint ?? endpointForPort(resolveRelayPort());
|
|
486
|
-
const relayPort = configuredRelayPort();
|
|
487
|
-
const httpClient = yield* HttpClient;
|
|
488
|
-
const readBody = (response, path) => response.json.pipe(mapError2((cause) => new RelayDecodeFailed({
|
|
489
|
-
message: `Relay returned an unreadable response for ${path}`,
|
|
490
|
-
path,
|
|
491
|
-
cause
|
|
492
|
-
})));
|
|
493
|
-
const handleResponse = (response, path, schema) => readBody(response, path).pipe(flatMap3((body) => {
|
|
494
|
-
if (response.status < 200 || response.status >= 300) {
|
|
495
|
-
const envelope = decodeErrorEnvelope(body);
|
|
496
|
-
const message = isSome(envelope) ? envelope.value.error : getOrElse(map2(decodeErrorMessage(body), (value) => value.error), () => `Relay responded with HTTP ${response.status} for ${path}`);
|
|
497
|
-
return fail6(new RelayRejected({
|
|
498
|
-
message,
|
|
499
|
-
status: response.status,
|
|
500
|
-
path,
|
|
501
|
-
...isSome(envelope) && envelope.value.code ? { code: envelope.value.code } : {}
|
|
502
|
-
}));
|
|
503
|
-
}
|
|
504
|
-
return decodeUnknownEffect2(schema)(body).pipe(mapError2((cause) => new RelayDecodeFailed({
|
|
505
|
-
message: `Relay response for ${path} did not match the expected shape: ${cause.message}`,
|
|
506
|
-
path,
|
|
507
|
-
cause
|
|
508
|
-
})));
|
|
509
|
-
}));
|
|
510
|
-
const transportError = (path, at) => (cause) => {
|
|
511
|
-
const endpoint = at ?? currentEndpoint();
|
|
512
|
-
return new RelayUnreachable({
|
|
513
|
-
message: `browse relay is not reachable at ${endpoint}. Relay-backed CLI commands start it automatically; use \`${cliCommand("serve")}\` only for foreground debugging.`,
|
|
514
|
-
endpoint,
|
|
515
|
-
path,
|
|
516
|
-
cause
|
|
517
|
-
});
|
|
518
|
-
};
|
|
519
|
-
const isRelayClientError = (error) => error instanceof RelayUnreachable || error instanceof RelayRejected || error instanceof RelayDecodeFailed || error instanceof RelayEncodeFailed || error instanceof RelayTimedOut;
|
|
520
|
-
let authorization;
|
|
521
|
-
const authorize = (request) => {
|
|
522
|
-
try {
|
|
523
|
-
authorization ??= relayAuthorization();
|
|
524
|
-
} catch {
|
|
525
|
-
return request;
|
|
526
|
-
}
|
|
527
|
-
const authorized = setHeader(request, "authorization", authorization);
|
|
528
|
-
return options?.clientPid === undefined ? authorized : setHeader(authorized, "opencode-browser-client-pid", String(options.clientPid));
|
|
529
|
-
};
|
|
530
|
-
let relayAnswered = false;
|
|
531
|
-
const executeUnauthorized = (path, request, at) => httpClient.execute(request).pipe(mapError2(transportError(path, at)), tap(() => sync2(() => {
|
|
532
|
-
relayAnswered = true;
|
|
533
|
-
})));
|
|
534
|
-
let verified;
|
|
535
|
-
const notBrowse = (endpoint, cause) => new RelayDecodeFailed({
|
|
536
|
-
message: `Relay port ${new URL(endpoint).port} is in use by another program (not a browse /version response).`,
|
|
537
|
-
path: "/version",
|
|
538
|
-
cause
|
|
539
|
-
});
|
|
540
|
-
const liveRelayState = () => {
|
|
541
|
-
try {
|
|
542
|
-
const state = readRelayState(stateRoot(), relayPort);
|
|
543
|
-
return state && state.configuredPort === relayPort && processAlive(state.pid) ? state : undefined;
|
|
544
|
-
} catch {
|
|
545
|
-
return;
|
|
546
|
-
}
|
|
547
|
-
};
|
|
548
|
-
const sameLiveState = (left, right) => left === undefined ? right === undefined : right !== undefined && left.port === right.port && left.instanceId === right.instanceId;
|
|
549
|
-
const verifyEndpoint = (endpoint, state = liveRelayState()) => suspend2(() => {
|
|
550
|
-
const seconds = relayAnswered ? busyRelayReadSeconds : unknownRelayReadSeconds;
|
|
551
|
-
return executeUnauthorized("/version", get(new URL("/version", endpoint)), endpoint).pipe(flatMap3((response) => readBody(response, "/version").pipe(mapError2((error) => state !== undefined && liveRelayState() === undefined ? transportError("/version", endpoint)(error) : error), map6((body) => ({ response, body })))), flatMap3(({ response, body }) => {
|
|
552
|
-
const reply = typeof body === "object" && body !== null ? body : undefined;
|
|
553
|
-
if (response.status === 503 && reply?.code === "relay-starting") {
|
|
554
|
-
const envelope = decodeErrorEnvelope(body);
|
|
555
|
-
return fail6(new RelayRejected({
|
|
556
|
-
message: isSome(envelope) ? envelope.value.error : "Relay responded with HTTP 503 for /version",
|
|
557
|
-
status: 503,
|
|
558
|
-
path: "/version",
|
|
559
|
-
code: "relay-starting"
|
|
560
|
-
}));
|
|
561
|
-
}
|
|
562
|
-
if (response.status !== 200 || typeof reply?.version !== "string" || typeof reply.instanceId !== "string")
|
|
563
|
-
return fail6(notBrowse(endpoint, body));
|
|
564
|
-
const after = liveRelayState();
|
|
565
|
-
if (state !== undefined && after === undefined)
|
|
566
|
-
return fail6(transportError("/version", endpoint)(body));
|
|
567
|
-
if (state !== undefined && !sameLiveState(state, after))
|
|
568
|
-
return fail6(notBrowse(endpoint, body));
|
|
569
|
-
if (after !== undefined && (after.port !== Number(new URL(endpoint).port) || after.instanceId !== reply.instanceId))
|
|
570
|
-
return fail6(notBrowse(endpoint, body));
|
|
571
|
-
return succeed6({ endpoint, instanceId: reply.instanceId, recorded: after?.instanceId });
|
|
572
|
-
}), timeoutOrElse({
|
|
573
|
-
duration: `${seconds} seconds`,
|
|
574
|
-
orElse: () => fail6(new RelayTimedOut({
|
|
575
|
-
message: `The relay on port ${new URL(endpoint).port} isn't answering (/version timed out after ${seconds}s).`,
|
|
576
|
-
path: "/version"
|
|
577
|
-
}))
|
|
578
|
-
}));
|
|
579
|
-
});
|
|
580
|
-
const ensureVerified = (endpoint) => {
|
|
581
|
-
const state = liveRelayState();
|
|
582
|
-
const port = Number(new URL(endpoint).port);
|
|
583
|
-
if (verified?.endpoint === endpoint && (state !== undefined && state.port === port && state.instanceId === verified.instanceId || state === undefined && verified.recorded === undefined))
|
|
584
|
-
return void_3;
|
|
585
|
-
return verifyEndpoint(endpoint, state).pipe(tap((value) => sync2(() => {
|
|
586
|
-
verified = value;
|
|
587
|
-
})), asVoid2);
|
|
588
|
-
};
|
|
589
|
-
const executeAuthorized = (endpoint, path, request) => suspend2(() => {
|
|
590
|
-
const target = new URL(request.url).origin;
|
|
591
|
-
if (target !== new URL(endpoint).origin) {
|
|
592
|
-
return fail6(new RelayDecodeFailed({
|
|
593
|
-
message: `Refusing to send the relay request for ${path} to ${target}: it was built for ${endpoint}.`,
|
|
594
|
-
path,
|
|
595
|
-
cause: request.url
|
|
596
|
-
}));
|
|
597
|
-
}
|
|
598
|
-
return ensureVerified(target).pipe(flatMap3(() => httpClient.execute(authorize(request))), mapError2((error) => isRelayClientError(error) ? error : transportError(path)(error)), tap(() => sync2(() => {
|
|
599
|
-
relayAnswered = true;
|
|
600
|
-
})), tapError((error) => sync2(() => {
|
|
601
|
-
if (error instanceof RelayUnreachable && verified?.endpoint === target)
|
|
602
|
-
verified = undefined;
|
|
603
|
-
})));
|
|
604
|
-
});
|
|
605
|
-
const requestJson = (path, schema) => suspend2(() => {
|
|
606
|
-
const endpoint = currentEndpoint();
|
|
607
|
-
const seconds = relayAnswered ? busyRelayReadSeconds : unknownRelayReadSeconds;
|
|
608
|
-
const request = get(new URL(path, endpoint));
|
|
609
|
-
const send = path === "/version" ? executeUnauthorized(path, request) : executeAuthorized(endpoint, path, request);
|
|
610
|
-
return send.pipe(flatMap3((response) => handleResponse(response, path, schema).pipe(map6((value) => ({ value, endpoint })))), timeoutOrElse({ duration: `${seconds} seconds`, orElse: () => fail6(new RelayTimedOut({
|
|
611
|
-
message: `The relay on port ${new URL(endpoint).port} isn't answering (${path} timed out after ${seconds}s).`,
|
|
612
|
-
path
|
|
613
|
-
})) }));
|
|
614
|
-
});
|
|
615
|
-
const getJson = (path, schema) => requestJson(path, schema).pipe(map6(({ value }) => value));
|
|
616
|
-
const checkWhileWaiting = sleep(30000).pipe(andThen2(getJson("/version", RelayVersion)), forever);
|
|
617
|
-
const postJson = (path, body, schema) => suspend2(() => {
|
|
618
|
-
const endpoint = currentEndpoint();
|
|
619
|
-
return post(new URL(path, endpoint)).pipe(bodyJson(body), mapError2((cause) => new RelayEncodeFailed({
|
|
620
|
-
message: `Could not encode relay request for ${path}`,
|
|
621
|
-
path,
|
|
622
|
-
cause
|
|
623
|
-
})), flatMap3((request) => executeAuthorized(endpoint, path, request).pipe(flatMap3((response) => handleResponse(response, path, schema)), raceFirst(checkWhileWaiting))));
|
|
624
|
-
});
|
|
625
|
-
const recordingTargetBody = (target) => ({
|
|
626
|
-
...target.sessionId ? { sessionId: target.sessionId } : {},
|
|
627
|
-
...target.tabId === undefined ? {} : { tabId: target.tabId }
|
|
628
|
-
});
|
|
629
|
-
const recordingTargetQuery = (target) => {
|
|
630
|
-
const searchParams = new URLSearchParams;
|
|
631
|
-
if (target.sessionId) {
|
|
632
|
-
searchParams.set("sessionId", target.sessionId);
|
|
633
|
-
}
|
|
634
|
-
if (target.tabId !== undefined) {
|
|
635
|
-
searchParams.set("tabId", String(target.tabId));
|
|
636
|
-
}
|
|
637
|
-
const text = searchParams.toString();
|
|
638
|
-
return text ? `?${text}` : "";
|
|
639
|
-
};
|
|
640
|
-
return Service.of({
|
|
641
|
-
get endpoint() {
|
|
642
|
-
return currentEndpoint();
|
|
643
|
-
},
|
|
644
|
-
version: suspend2(() => {
|
|
645
|
-
const state = liveRelayState();
|
|
646
|
-
const probed = currentEndpoint();
|
|
647
|
-
const probe = requestJson("/version", RelayVersion).pipe(mapError2((error) => {
|
|
648
|
-
if (!(error instanceof RelayDecodeFailed || error instanceof RelayRejected && !error.code && error.status === 404))
|
|
649
|
-
return error;
|
|
650
|
-
return state !== undefined && liveRelayState() === undefined ? transportError("/version", probed)(error) : notBrowse(probed, error);
|
|
651
|
-
}));
|
|
652
|
-
return probe.pipe(flatMap3(({ value: version, endpoint }) => {
|
|
653
|
-
const instanceId = version.instanceId;
|
|
654
|
-
if (typeof instanceId !== "string")
|
|
655
|
-
return fail6(notBrowse(endpoint, version));
|
|
656
|
-
const after = liveRelayState();
|
|
657
|
-
if (state !== undefined && after === undefined)
|
|
658
|
-
return fail6(transportError("/version", endpoint)(version));
|
|
659
|
-
if (state !== undefined && !sameLiveState(state, after))
|
|
660
|
-
return fail6(notBrowse(endpoint, version));
|
|
661
|
-
if (after !== undefined && (after.port !== Number(new URL(endpoint).port) || after.instanceId !== instanceId))
|
|
662
|
-
return fail6(notBrowse(endpoint, version));
|
|
663
|
-
return sync2(() => {
|
|
664
|
-
verified = { endpoint, instanceId, recorded: after?.instanceId };
|
|
665
|
-
return version;
|
|
666
|
-
});
|
|
667
|
-
}));
|
|
668
|
-
}),
|
|
669
|
-
shutdown: (request) => postJson("/shutdown", { ...request }, RelayShutdownResponse),
|
|
670
|
-
extensionStatus: getJson("/extension/status", ExtensionStatus),
|
|
671
|
-
targets: getJson("/json/list", TargetSummaries),
|
|
672
|
-
sessions: getJson("/cli/sessions", SessionsContainer).pipe(map6((container) => container.sessions)),
|
|
673
|
-
sessionNew: (id, options) => postJson("/cli/session/new", {
|
|
674
|
-
...id ? { id } : {},
|
|
675
|
-
...options?.readOnly ? { readOnly: true } : {},
|
|
676
|
-
...options?.allowedOrigins && options.allowedOrigins.length > 0 ? { allowedOrigins: [...options.allowedOrigins] } : {},
|
|
677
|
-
...options?.keepVisible ? { keepVisible: true } : {},
|
|
678
|
-
...options?.browser ? { browser: options.browser } : {}
|
|
679
|
-
}, SessionContainer).pipe(map6((container) => container.session)),
|
|
680
|
-
sessionAllowlist: (id, allowedOrigins) => postJson("/cli/session/allowlist", { id, allowedOrigins: [...allowedOrigins] }, SessionContainer).pipe(map6((container) => container.session)),
|
|
681
|
-
sessionEnsure: (id, options) => postJson("/v1/sessions/ensure", {
|
|
682
|
-
id,
|
|
683
|
-
...options?.readOnly === undefined ? {} : { readOnly: options.readOnly }
|
|
684
|
-
}, SessionContainer).pipe(map6((container) => container.session)),
|
|
685
|
-
sessionReset: (id) => postJson("/cli/session/reset", { id }, SessionResetResponse),
|
|
686
|
-
sessionAdopt: ({ sessionId, ...request }) => postJson("/cli/session/adopt", {
|
|
687
|
-
...request,
|
|
688
|
-
...sessionId ? { sessionId } : {}
|
|
689
|
-
}, SessionAdoptResponse),
|
|
690
|
-
sessionDelete: (id) => postJson("/cli/session/delete", { id }, SessionDeleted),
|
|
691
|
-
execute: ({ sessionId, ...request }) => postJson("/cli/execute", {
|
|
692
|
-
...request,
|
|
693
|
-
...sessionId ? { sessionId } : {}
|
|
694
|
-
}, ExecuteResponse),
|
|
695
|
-
authenticatedJson: (request) => postJson("/v1/authenticated-origin/json", { ...request }, AuthenticatedJsonOutcome),
|
|
696
|
-
networkStart: (request) => postJson("/network/start", { ...request }, NetworkStatusResponse),
|
|
697
|
-
networkStatus: (request) => postJson("/network/status", { ...request }, NetworkStatusResponse),
|
|
698
|
-
networkStop: (request) => postJson("/network/stop", { ...request }, NetworkStopResponse),
|
|
699
|
-
networkCancel: (request) => postJson("/network/cancel", { ...request }, NetworkCancelResponse),
|
|
700
|
-
recordingStart: ({ sessionId, tabId, ...request }) => postJson("/recording/start", { ...recordingTargetBody({ sessionId, tabId }), ...request }, RecordingStartResponse),
|
|
701
|
-
recordingStop: (target) => postJson("/recording/stop", recordingTargetBody(target), RecordingStopResponse),
|
|
702
|
-
recordingStatus: (target) => getJson(`/recording/status${recordingTargetQuery(target)}`, RecordingStatusResponse),
|
|
703
|
-
recordingCancel: (target) => postJson("/recording/cancel", recordingTargetBody(target), RecordingCancelResponse),
|
|
704
|
-
tabsCleanup: (idleMinutes, sessions) => postJson("/tabs/cleanup", { ...idleMinutes === undefined ? {} : { idleMinutes }, ...sessions ? { sessions } : {} }, TabsCleanupResponse),
|
|
705
|
-
settingsGet: getJson("/settings", SettingsGetResponse),
|
|
706
|
-
settingsSet: (changes) => postJson("/settings", { set: changes }, SettingsSetResponse)
|
|
707
|
-
});
|
|
708
|
-
});
|
|
709
|
-
var layer = effect(Service, make3());
|
|
710
|
-
var layerFetch = layer.pipe(provide2(layerNodeHttp));
|
|
711
|
-
function mcpClientPid() {
|
|
712
|
-
const supervisor = Number(process.env.OPENCODE_BROWSER_CLIENT_PID);
|
|
713
|
-
return Number.isSafeInteger(supervisor) && supervisor > 1 && supervisor === process.ppid ? supervisor : process.pid;
|
|
714
|
-
}
|
|
715
|
-
var layerFetchMcp = effect(Service, make3({ clientPid: mcpClientPid() })).pipe(provide2(layerNodeHttp));
|
|
716
|
-
|
|
717
|
-
// src/relay/log.ts
|
|
718
|
-
import fs from "node:fs";
|
|
719
|
-
import os from "node:os";
|
|
720
|
-
import path from "node:path";
|
|
721
|
-
var maxLogBytes = 1e6;
|
|
722
|
-
var maxEntryCharacters = 64000;
|
|
723
|
-
function managedRelayLogPath(home = os.homedir()) {
|
|
724
|
-
return path.join(stateRoot(home), "logs", "relay.log");
|
|
725
|
-
}
|
|
726
|
-
function appendManagedRelayProcessLog(message, home = os.homedir()) {
|
|
727
|
-
try {
|
|
728
|
-
const logPath = managedRelayLogPath(home);
|
|
729
|
-
ensurePrivateDirectorySync(path.dirname(logPath));
|
|
730
|
-
const entry = `${new Date().toISOString()} ${message.slice(0, maxEntryCharacters)}
|
|
731
|
-
`;
|
|
732
|
-
const stat = fs.statSync(logPath, { throwIfNoEntry: false });
|
|
733
|
-
if (stat && stat.size + Buffer.byteLength(entry) > maxLogBytes)
|
|
734
|
-
fs.renameSync(logPath, `${logPath}.1`);
|
|
735
|
-
fs.appendFileSync(logPath, entry, { encoding: "utf8", mode: 384 });
|
|
736
|
-
fs.chmodSync(logPath, 384);
|
|
737
|
-
} catch {}
|
|
738
|
-
}
|
|
739
|
-
function relayLog(event, fields = {}) {
|
|
740
|
-
const detail = Object.entries(fields).filter(([, value]) => value !== undefined).map(([key, value]) => `${key}=${typeof value === "string" && !/\s/.test(value) ? value : JSON.stringify(value)}`).join(" ");
|
|
741
|
-
appendManagedRelayProcessLog(detail ? `${event} ${detail}` : event);
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
// src/relay/windows-launch.ts
|
|
745
|
-
import { existsSync } from "node:fs";
|
|
746
|
-
import path2 from "node:path";
|
|
747
|
-
import process2 from "node:process";
|
|
748
|
-
var createNewProcessGroup = 512;
|
|
749
|
-
var createUnicodeEnvironment = 1024;
|
|
750
|
-
var createNoWindow = 134217728;
|
|
751
|
-
var startupInfoSize = 104;
|
|
752
|
-
var processInformationSize = 24;
|
|
753
|
-
var windowsAbsolutePath = /^(?:[A-Za-z]:[\\/]|\\\\)/;
|
|
754
|
-
var kernel32;
|
|
755
|
-
function kernel32Library() {
|
|
756
|
-
if (kernel32)
|
|
757
|
-
return kernel32;
|
|
758
|
-
const ffi = __require("bun:ffi");
|
|
759
|
-
kernel32 = ffi.dlopen("kernel32.dll", {
|
|
760
|
-
CreateProcessW: {
|
|
761
|
-
args: [
|
|
762
|
-
ffi.FFIType.ptr,
|
|
763
|
-
ffi.FFIType.ptr,
|
|
764
|
-
ffi.FFIType.ptr,
|
|
765
|
-
ffi.FFIType.ptr,
|
|
766
|
-
ffi.FFIType.i32,
|
|
767
|
-
ffi.FFIType.u32,
|
|
768
|
-
ffi.FFIType.ptr,
|
|
769
|
-
ffi.FFIType.ptr,
|
|
770
|
-
ffi.FFIType.ptr,
|
|
771
|
-
ffi.FFIType.ptr
|
|
772
|
-
],
|
|
773
|
-
returns: ffi.FFIType.i32
|
|
774
|
-
},
|
|
775
|
-
CloseHandle: { args: [ffi.FFIType.ptr], returns: ffi.FFIType.i32 },
|
|
776
|
-
GetLastError: { args: [], returns: ffi.FFIType.u32 }
|
|
777
|
-
});
|
|
778
|
-
return kernel32;
|
|
779
|
-
}
|
|
780
|
-
function resolveWindowsExecutable(executable, env, exists) {
|
|
781
|
-
if (!executable || executable.includes("\x00"))
|
|
782
|
-
return;
|
|
783
|
-
if (windowsAbsolutePath.test(executable))
|
|
784
|
-
return executable;
|
|
785
|
-
if (/[\\/:]/.test(executable))
|
|
786
|
-
return;
|
|
787
|
-
const searchPath = windowsPathVariable(env);
|
|
788
|
-
if (!searchPath)
|
|
789
|
-
return;
|
|
790
|
-
const names = path2.win32.extname(executable) ? [executable] : [`${executable}.exe`, `${executable}.com`];
|
|
791
|
-
for (const entry of searchPath.split(path2.win32.delimiter)) {
|
|
792
|
-
const trimmed = entry.trim();
|
|
793
|
-
const directory = trimmed.startsWith('"') && trimmed.endsWith('"') ? trimmed.slice(1, -1) : trimmed;
|
|
794
|
-
if (!windowsAbsolutePath.test(directory))
|
|
795
|
-
continue;
|
|
796
|
-
for (const name of names) {
|
|
797
|
-
const candidate = path2.win32.join(directory, name);
|
|
798
|
-
if (exists(candidate))
|
|
799
|
-
return candidate;
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
function windowsPathVariable(env) {
|
|
805
|
-
let value;
|
|
806
|
-
for (const [name, candidate] of Object.entries(env)) {
|
|
807
|
-
if (name.toUpperCase() === "PATH" && candidate !== undefined)
|
|
808
|
-
value = candidate;
|
|
809
|
-
}
|
|
810
|
-
return value;
|
|
811
|
-
}
|
|
812
|
-
function windowsLaunchProblem(launch, env) {
|
|
813
|
-
if (!launch.executable)
|
|
814
|
-
return "the executable is empty";
|
|
815
|
-
if (launch.executable.includes("\x00") || launch.args.some((argument) => argument.includes("\x00")))
|
|
816
|
-
return "the executable or an argument contains NUL";
|
|
817
|
-
if (Object.values(env).some((value) => value?.includes("\x00")))
|
|
818
|
-
return "an environment value contains NUL";
|
|
819
|
-
return;
|
|
820
|
-
}
|
|
821
|
-
function launchWindowsRelay(launch, env, onFallback) {
|
|
822
|
-
const fallback = (reason) => {
|
|
823
|
-
onFallback?.(reason);
|
|
824
|
-
return false;
|
|
825
|
-
};
|
|
826
|
-
const problem = windowsLaunchProblem(launch, env);
|
|
827
|
-
if (problem)
|
|
828
|
-
return fallback(problem);
|
|
829
|
-
if (!process2.versions.bun)
|
|
830
|
-
return fallback("this process is not running under Bun");
|
|
831
|
-
const executable = resolveWindowsExecutable(launch.executable, env, existsSync);
|
|
832
|
-
if (!executable)
|
|
833
|
-
return fallback(`could not resolve ${JSON.stringify(launch.executable)} through PATH`);
|
|
834
|
-
let started = false;
|
|
835
|
-
try {
|
|
836
|
-
const kernel32 = kernel32Library();
|
|
837
|
-
const startupInfo = new Uint8Array(startupInfoSize);
|
|
838
|
-
const startup = new DataView(startupInfo.buffer);
|
|
839
|
-
startup.setUint32(0, startupInfoSize, true);
|
|
840
|
-
startup.setUint32(60, 1, true);
|
|
841
|
-
startup.setUint16(64, 0, true);
|
|
842
|
-
const processInformation = new Uint8Array(processInformationSize);
|
|
843
|
-
const created = kernel32.symbols.CreateProcessW(wideZ(executable), wideZ(windowsCommandLine(executable, launch.args)), null, null, 0, createNoWindow | createNewProcessGroup | createUnicodeEnvironment, Buffer.from(windowsEnvironmentBlock(env), "utf16le"), null, startupInfo, processInformation);
|
|
844
|
-
if (!created) {
|
|
845
|
-
let code;
|
|
846
|
-
try {
|
|
847
|
-
code = kernel32.symbols.GetLastError();
|
|
848
|
-
} catch {}
|
|
849
|
-
return fallback(`CreateProcessW failed${code === undefined ? "" : ` (GetLastError() = ${code})`}`);
|
|
850
|
-
}
|
|
851
|
-
started = true;
|
|
852
|
-
const info = new DataView(processInformation.buffer);
|
|
853
|
-
kernel32.symbols.CloseHandle(info.getBigUint64(0, true));
|
|
854
|
-
kernel32.symbols.CloseHandle(info.getBigUint64(8, true));
|
|
855
|
-
return true;
|
|
856
|
-
} catch (error) {
|
|
857
|
-
if (started)
|
|
858
|
-
return true;
|
|
859
|
-
return fallback(error instanceof Error ? error.message : String(error));
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
function quoteWindowsArgument(argument) {
|
|
863
|
-
return `"${argument.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\+)$/, "$1$1")}"`;
|
|
864
|
-
}
|
|
865
|
-
function windowsCommandLine(executable, args) {
|
|
866
|
-
return [executable, ...args].map(quoteWindowsArgument).join(" ");
|
|
867
|
-
}
|
|
868
|
-
function windowsEnvironmentBlock(env) {
|
|
869
|
-
const entries = new Map;
|
|
870
|
-
for (const [name, value] of Object.entries(env)) {
|
|
871
|
-
if (value === undefined || name === "" || name.includes("=") || name.includes("\x00"))
|
|
872
|
-
continue;
|
|
873
|
-
entries.set(name.toUpperCase(), [name, value]);
|
|
874
|
-
}
|
|
875
|
-
const sorted = [...entries.values()].sort(([left], [right]) => {
|
|
876
|
-
const a = left.toUpperCase();
|
|
877
|
-
const b = right.toUpperCase();
|
|
878
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
879
|
-
});
|
|
880
|
-
return sorted.length === 0 ? "\x00\x00" : `${sorted.map(([name, value]) => `${name}=${value}\x00`).join("")}\x00`;
|
|
881
|
-
}
|
|
882
|
-
function wideZ(value) {
|
|
883
|
-
return Buffer.from(`${value}\x00`, "utf16le");
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
// src/relay/lifecycle.ts
|
|
887
|
-
var loadedCliEntrypoint = compiledBinary() ? process3.execPath : fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../main.ts" : "./cli.mjs", import.meta.url));
|
|
888
|
-
var clientInstanceId = crypto.randomUUID();
|
|
889
|
-
function shouldWaitForExtensionReconnect(readiness) {
|
|
890
|
-
return readiness.started || readiness.waitForReconnect === true;
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
class RelayStillRunning extends Error {
|
|
894
|
-
cutProbe;
|
|
895
|
-
constructor(message, cutProbe) {
|
|
896
|
-
super(message);
|
|
897
|
-
this.cutProbe = cutProbe;
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
class RelayStartFailed extends TaggedError2()("RelayLifecycle.RelayStartFailed", {
|
|
902
|
-
message: String3,
|
|
903
|
-
endpoint: String3,
|
|
904
|
-
cause: Defect()
|
|
905
|
-
}) {
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
class ExtensionDisconnected extends TaggedError2()("RelayLifecycle.ExtensionDisconnected", { message: String3, needsPairing: optionalKey(Boolean3), unresponsive: optionalKey(Boolean3) }) {
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
class ExtensionProtocolIncompatible extends TaggedError2()("RelayLifecycle.ExtensionProtocolIncompatible", {
|
|
912
|
-
message: String3,
|
|
913
|
-
protocolVersion: NullOr(Number2)
|
|
914
|
-
}) {
|
|
915
|
-
}
|
|
916
|
-
function supersededRuntime() {
|
|
917
|
-
try {
|
|
918
|
-
const runtime = installedRuntime2();
|
|
919
|
-
if (!runtime)
|
|
920
|
-
return false;
|
|
921
|
-
const onDisk = installedVersion(runtime);
|
|
922
|
-
return !!onDisk && compareVersions(onDisk, runtime.version) > 0;
|
|
923
|
-
} catch {
|
|
924
|
-
return false;
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
function relayBuildProblem(version, buildId = opencodeBrowserBuildId2) {
|
|
928
|
-
if (!version.buildId) {
|
|
929
|
-
return `Running relay does not report a build id; use \`${cliCommand("relay restart")}\` for upgrade guidance (${buildId}).`;
|
|
930
|
-
}
|
|
931
|
-
if (version.buildId !== buildId) {
|
|
932
|
-
if (isNewerBuild(version.buildId, buildId))
|
|
933
|
-
return;
|
|
934
|
-
return `Running relay build ${version.buildId} does not match CLI build ${buildId}; run \`${cliCommand("relay restart")}\` when no agent is using the browser. This leaves browser tabs open but resets in-memory JavaScript state.`;
|
|
935
|
-
}
|
|
936
|
-
return;
|
|
937
|
-
}
|
|
938
|
-
function relayIsNewerThanClient(version, buildId = opencodeBrowserBuildId2) {
|
|
939
|
-
return version.buildId !== undefined && version.buildId !== buildId && isNewerBuild(version.buildId, buildId);
|
|
940
|
-
}
|
|
941
|
-
function olderMcpClientAdvice(version, error, buildId = opencodeBrowserBuildId2) {
|
|
942
|
-
if (!relayIsNewerThanClient(version, buildId))
|
|
943
|
-
return;
|
|
944
|
-
const incompatible = error instanceof RelayDecodeFailed ? error.path !== "/version" : error instanceof RelayRejected && (error.status === 405 || error.status === 415 || error.status === 404 && error.code === undefined || error.status === 400 && error.code === "invalid-request" && error.message.startsWith("Invalid ") && error.message.includes(" request:"));
|
|
945
|
-
if (!incompatible)
|
|
946
|
-
return;
|
|
947
|
-
return "browse was updated, and the running relay can't serve this MCP server's older build. Reconnect browse in the agent so it starts the new version (in OpenCode: /mcps).";
|
|
948
|
-
}
|
|
949
|
-
var ensureRelay = fn("RelayLifecycle.ensureRelay")(function* (options) {
|
|
950
|
-
const buildId = options.buildId ?? opencodeBrowserBuildId2;
|
|
951
|
-
const found = (version, started) => {
|
|
952
|
-
const buildProblem = relayBuildProblem(version, buildId);
|
|
953
|
-
return { version, started, ...buildProblem ? { buildProblem } : {} };
|
|
954
|
-
};
|
|
955
|
-
const initial = yield* result(options.relay.version);
|
|
956
|
-
if (isSuccess(initial))
|
|
957
|
-
return found(initial.success, false);
|
|
958
|
-
const draining = relayDraining(initial.failure);
|
|
959
|
-
let relayWasAbsent = isRelayUnreachable(initial.failure) || isForeignListener(initial.failure, options.pinned);
|
|
960
|
-
if (!relayWasAbsent && !isRelayStarting(initial.failure) && !draining) {
|
|
961
|
-
return yield* initial.failure;
|
|
962
|
-
}
|
|
963
|
-
if (draining) {
|
|
964
|
-
const recorded = liveRelayInstanceId();
|
|
965
|
-
const replacement = recorded === undefined ? undefined : yield* startPastDrain(waitForRelayExitOrReplacement({ ...options, instanceId: recorded }), options.pinned);
|
|
966
|
-
if (replacement !== undefined)
|
|
967
|
-
return found(replacement, false);
|
|
968
|
-
relayWasAbsent = true;
|
|
969
|
-
}
|
|
970
|
-
if (relayWasAbsent) {
|
|
971
|
-
const autoStart = yield* Boolean2("OPENCODE_BROWSER_AUTOSTART").pipe(withDefault(true), mapError2((cause) => new Error("Invalid OPENCODE_BROWSER_AUTOSTART configuration", { cause })));
|
|
972
|
-
if (!autoStart) {
|
|
973
|
-
return yield* fail6(new Error(`Automatic relay startup is disabled; no relay is available at ${options.relay.endpoint}`));
|
|
974
|
-
}
|
|
975
|
-
if (!supersededRuntime())
|
|
976
|
-
yield* options.start ?? startManagedRelay();
|
|
977
|
-
}
|
|
978
|
-
const version = yield* waitForRelayReady(options);
|
|
979
|
-
return found(version, relayWasAbsent);
|
|
980
|
-
});
|
|
981
|
-
function waitForRelayReady(options) {
|
|
982
|
-
const retry2 = (error) => isRelayStartingOrUnreachable(error) || isForeignListener(error, options.pinned);
|
|
983
|
-
return options.relay.version.pipe(retry({
|
|
984
|
-
times: options.retryTimes ?? 200,
|
|
985
|
-
schedule: spaced(options.retryDelayMs ?? 50),
|
|
986
|
-
while: retry2
|
|
987
|
-
}), mapError2((error) => retry2(error) ? new RelayStartFailed({
|
|
988
|
-
message: `browse relay did not start at ${options.relay.endpoint}`,
|
|
989
|
-
endpoint: options.relay.endpoint,
|
|
990
|
-
cause: error
|
|
991
|
-
}) : error));
|
|
992
|
-
}
|
|
993
|
-
var restartRelay = fn("RelayLifecycle.restartRelay")(function* (options) {
|
|
994
|
-
const buildId = options.buildId ?? opencodeBrowserBuildId2;
|
|
995
|
-
const absent = (error) => isRelayUnreachable(error) || isForeignListener(error, options.pinned);
|
|
996
|
-
const initial = yield* result(options.relay.version);
|
|
997
|
-
let original;
|
|
998
|
-
let replacement;
|
|
999
|
-
let restartRequestId;
|
|
1000
|
-
if (isSuccess(initial)) {
|
|
1001
|
-
original = initial.success;
|
|
1002
|
-
} else if (isRelayStarting(initial.failure)) {
|
|
1003
|
-
original = yield* waitForRelayReady(options);
|
|
1004
|
-
} else {
|
|
1005
|
-
const recorded = relayDraining(initial.failure) ? liveRelayInstanceId() : undefined;
|
|
1006
|
-
if (recorded !== undefined) {
|
|
1007
|
-
replacement = yield* startPastDrain(waitForRelayExitOrReplacement({ ...options, instanceId: recorded }), options.pinned);
|
|
1008
|
-
} else if (!absent(initial.failure))
|
|
1009
|
-
return yield* initial.failure;
|
|
1010
|
-
}
|
|
1011
|
-
if (original) {
|
|
1012
|
-
if (original.managed !== true || !original.instanceId) {
|
|
1013
|
-
return yield* fail6(new Error(`Cannot restart a foreground or unidentified relay. Stop it manually, then run \`${cliCommand("relay restart")}\`.`));
|
|
1014
|
-
}
|
|
1015
|
-
if (original.shutdownProtocol !== 2) {
|
|
1016
|
-
return yield* fail6(new Error(`This legacy relay does not support safe shutdown protocol 2. Stop it manually once, then run \`${cliCommand("relay restart")}\` to upgrade; no shutdown request was sent.`));
|
|
1017
|
-
}
|
|
1018
|
-
if (!Number.isFinite(Date.parse(buildId)) || !original.buildId || !Number.isFinite(Date.parse(original.buildId))) {
|
|
1019
|
-
return yield* fail6(new Error("Cannot explicitly replace a source or unorderable relay build. Stop it manually, then launch the intended build."));
|
|
1020
|
-
}
|
|
1021
|
-
if (!options.otherBuild && isNewerBuild(original.buildId, buildId)) {
|
|
1022
|
-
return yield* fail6(new Error(`Refusing to downgrade relay build ${original.buildId} to ${buildId}; refresh or restart this CLI or MCP client.`));
|
|
1023
|
-
}
|
|
1024
|
-
const confirmed = yield* result(options.relay.version);
|
|
1025
|
-
if (isFailure(confirmed)) {
|
|
1026
|
-
const recorded = relayDraining(confirmed.failure) ? liveRelayInstanceId() : undefined;
|
|
1027
|
-
if (recorded !== undefined) {
|
|
1028
|
-
replacement = yield* startPastDrain(waitForRelayExitOrReplacement({ ...options, instanceId: recorded }), options.pinned);
|
|
1029
|
-
} else if (!absent(confirmed.failure))
|
|
1030
|
-
return yield* confirmed.failure;
|
|
1031
|
-
} else if (!isSameRelayInstance(original, confirmed.success)) {
|
|
1032
|
-
replacement = confirmed.success;
|
|
1033
|
-
} else {
|
|
1034
|
-
if (confirmed.success.managed !== true || confirmed.success.shutdownProtocol !== 2 || confirmed.success.buildId !== original.buildId) {
|
|
1035
|
-
return yield* fail6(new Error("Relay identity metadata changed during restart; no shutdown request was sent."));
|
|
1036
|
-
}
|
|
1037
|
-
const request = yield* RelayShutdownRequest.makeEffect({
|
|
1038
|
-
instanceId: original.instanceId,
|
|
1039
|
-
requestId: crypto.randomUUID(),
|
|
1040
|
-
reason: "explicit-restart",
|
|
1041
|
-
client: { kind: options.clientKind ?? "sdk", instanceId: clientInstanceId, buildId },
|
|
1042
|
-
...options.force ? { force: true } : {}
|
|
1043
|
-
});
|
|
1044
|
-
const shutdown = yield* result(options.relay.shutdown(request));
|
|
1045
|
-
if (isSuccess(shutdown)) {
|
|
1046
|
-
restartRequestId = request.requestId;
|
|
1047
|
-
if (options.onShutdownAccepted)
|
|
1048
|
-
yield* options.onShutdownAccepted;
|
|
1049
|
-
} else if (!isRelayUnreachable(shutdown.failure) && !isRelayInstanceChanged(shutdown.failure)) {
|
|
1050
|
-
return yield* shutdown.failure;
|
|
1051
|
-
}
|
|
1052
|
-
replacement = yield* waitForRelayExitOrReplacement({ ...options, instanceId: original.instanceId });
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
const started = replacement === undefined;
|
|
1056
|
-
if (started) {
|
|
1057
|
-
yield* options.start ?? startManagedRelay(undefined, undefined, undefined, { ...restartRequestId ? { restartRequestId } : {} });
|
|
1058
|
-
replacement = yield* waitForRelayReady(options);
|
|
1059
|
-
}
|
|
1060
|
-
if (!replacement || !replacement.instanceId || replacement.managed !== true || original && isSameRelayInstance(original, replacement)) {
|
|
1061
|
-
return yield* fail6(new Error("Relay restart did not produce a new managed instance; no further shutdown was attempted."));
|
|
1062
|
-
}
|
|
1063
|
-
const buildProblem = options.otherBuild ? undefined : relayBuildProblem(replacement, buildId);
|
|
1064
|
-
if (buildProblem)
|
|
1065
|
-
return yield* fail6(new Error(`${buildProblem} A competing relay was left untouched.`));
|
|
1066
|
-
return { version: replacement, started, waitForReconnect: true };
|
|
1067
|
-
});
|
|
1068
|
-
function waitForRelayExitOrReplacement(options) {
|
|
1069
|
-
const stillRecorded = () => relayRecorded(options.instanceId);
|
|
1070
|
-
return options.relay.version.pipe(flatMap3((version) => version.instanceId !== undefined && version.instanceId === options.instanceId ? fail6(new RelayStillRunning("browse relay is still draining; no replacement was started")) : succeed6(version)), catch_((error) => {
|
|
1071
|
-
if (isRelayUnreachable(error))
|
|
1072
|
-
return succeed6(undefined);
|
|
1073
|
-
if (error instanceof RelayDecodeFailed && stillRecorded()) {
|
|
1074
|
-
return fail6(new RelayStillRunning("browse relay is still draining; no replacement was started", error));
|
|
1075
|
-
}
|
|
1076
|
-
return isForeignListener(error, options.pinned) ? succeed6(undefined) : fail6(error);
|
|
1077
|
-
}), retry({
|
|
1078
|
-
times: options.retryTimes ?? 200,
|
|
1079
|
-
schedule: spaced(options.retryDelayMs ?? 50),
|
|
1080
|
-
while: (error) => error instanceof RelayStillRunning || isRelayStarting(error)
|
|
1081
|
-
}), mapError2((error) => error instanceof RelayStillRunning ? error.cutProbe ?? error : error));
|
|
1082
|
-
}
|
|
1083
|
-
function startPastDrain(drain, pinned) {
|
|
1084
|
-
return drain.pipe(catch_((error) => isForeignListener(error, pinned) ? succeed6(undefined) : fail6(error)));
|
|
1085
|
-
}
|
|
1086
|
-
function isSameRelayInstance(left, right) {
|
|
1087
|
-
return left.instanceId !== undefined && left.instanceId === right.instanceId;
|
|
1088
|
-
}
|
|
1089
|
-
function isNewerBuild(current, running) {
|
|
1090
|
-
if (!running)
|
|
1091
|
-
return false;
|
|
1092
|
-
const currentTime = Date.parse(current);
|
|
1093
|
-
const runningTime = Date.parse(running);
|
|
1094
|
-
return Number.isFinite(currentTime) && Number.isFinite(runningTime) && currentTime > runningTime;
|
|
1095
|
-
}
|
|
1096
|
-
function isRelayInstanceChanged(error) {
|
|
1097
|
-
return error instanceof RelayRejected && error.status === 409 && error.code === "invalid-request";
|
|
1098
|
-
}
|
|
1099
|
-
var extensionReconnectWaitMs = extensionReconnectAlarmPeriodMs + 5000;
|
|
1100
|
-
var extensionReconnectProbeMs = 200;
|
|
1101
|
-
var ensureExtensionConnected = fn("RelayLifecycle.ensureExtensionConnected")(function* (options) {
|
|
1102
|
-
const responsiveStatus = options.relay.extensionStatus.pipe(tap((status) => {
|
|
1103
|
-
const profile = status.sessions?.find((s) => s.id === options.sessionId)?.browser;
|
|
1104
|
-
if (status.browsers?.some((b) => b.unresponsive && (profile ? b.id === profile : !status.connected))) {
|
|
1105
|
-
return fail6(new ExtensionDisconnected({ message: browserUnresponsive, unresponsive: true }));
|
|
1106
|
-
}
|
|
1107
|
-
return void_3;
|
|
1108
|
-
}));
|
|
1109
|
-
const check = responsiveStatus.pipe(flatMap3((status) => {
|
|
1110
|
-
const bound = options.sessionId ? status.sessions?.find((session) => session.id === options.sessionId && session.browser) : undefined;
|
|
1111
|
-
if (bound) {
|
|
1112
|
-
const browser = status.browsers?.find((candidate) => candidate.id === bound.browser);
|
|
1113
|
-
if (!options.waitForReconnect || browser?.connected || status.protocolCompatible === false)
|
|
1114
|
-
return succeed6(status);
|
|
1115
|
-
return fail6(new ExtensionDisconnected({
|
|
1116
|
-
message: `Session ${bound.id} belongs to browser '${bound.browser}', which isn't connected. Reconnect it or start a new session.`,
|
|
1117
|
-
needsPairing: status.pairingState === "refused" || status.pairingState === "unpaired"
|
|
1118
|
-
}));
|
|
1119
|
-
}
|
|
1120
|
-
if (status.protocolCompatible === false) {
|
|
1121
|
-
return fail6(new ExtensionProtocolIncompatible({
|
|
1122
|
-
message: status.nextStep ?? extensionProtocolAdvice(status.protocolVersion, { install: installCommand() }),
|
|
1123
|
-
protocolVersion: status.protocolVersion ?? null
|
|
1124
|
-
}));
|
|
1125
|
-
}
|
|
1126
|
-
return status.connected ? succeed6(status) : fail6(new ExtensionDisconnected({
|
|
1127
|
-
message: status.nextStep ?? `browse extension is not connected. Open the browser with browse installed (\`${installCommand()}\`); it reconnects automatically after relay or browser startup.`,
|
|
1128
|
-
needsPairing: status.pairingState === "refused" || status.pairingState === "unpaired"
|
|
1129
|
-
}));
|
|
1130
|
-
}));
|
|
1131
|
-
if (!options.waitForReconnect) {
|
|
1132
|
-
return yield* check;
|
|
1133
|
-
}
|
|
1134
|
-
let waitAnnounced = false;
|
|
1135
|
-
return yield* check.pipe(tapError((error) => {
|
|
1136
|
-
if (waitAnnounced || !options.onWait || !(error instanceof ExtensionDisconnected))
|
|
1137
|
-
return void_3;
|
|
1138
|
-
waitAnnounced = true;
|
|
1139
|
-
return options.onWait;
|
|
1140
|
-
}), retry({
|
|
1141
|
-
times: options.retryTimes ?? Math.ceil(extensionReconnectWaitMs / extensionReconnectProbeMs),
|
|
1142
|
-
schedule: spaced(options.retryDelayMs ?? extensionReconnectProbeMs),
|
|
1143
|
-
while: (error) => error instanceof ExtensionDisconnected && !error.needsPairing && !error.unresponsive || isRelayStartingOrUnreachable(error)
|
|
1144
|
-
}));
|
|
1145
|
-
});
|
|
1146
|
-
function stoppedRelayStatus(endpoint) {
|
|
1147
|
-
return { endpoint, relay: { running: false }, extension: null, sessions: [], targets: [] };
|
|
1148
|
-
}
|
|
1149
|
-
function statusCollections(status) {
|
|
1150
|
-
return status.sessions && status.targets ? { sessions: status.sessions, targets: status.targets } : undefined;
|
|
1151
|
-
}
|
|
1152
|
-
function startManagedRelay(entrypoint = loadedCliEntrypoint, executable = process3.execPath, execArgv = process3.execArgv, options = {}) {
|
|
1153
|
-
return try_2({
|
|
1154
|
-
try: () => {
|
|
1155
|
-
if (!entrypoint) {
|
|
1156
|
-
throw new Error("Cannot locate the browse CLI entrypoint");
|
|
1157
|
-
}
|
|
1158
|
-
const launch = managedRelayLaunch(entrypoint, executable, execArgv);
|
|
1159
|
-
const env = Object.fromEntries(Object.entries(relayEnvironment(process3.env)).filter(([name]) => name.toUpperCase() !== "OPENCODE_BROWSER_RESTART_REQUEST_ID"));
|
|
1160
|
-
const childEnv = { ...env, OPENCODE_BROWSER_MANAGED_RELAY: "1", ...options.restartRequestId ? { OPENCODE_BROWSER_RESTART_REQUEST_ID: options.restartRequestId } : {} };
|
|
1161
|
-
if (process3.platform === "win32") {
|
|
1162
|
-
if (launchWindowsRelay(launch, childEnv, (reason) => relayLog("relay.launch.fallback", { executable: launch.executable, reason })))
|
|
1163
|
-
return;
|
|
1164
|
-
const args = launch.args.map(quoteWindowsArgument).join(" ");
|
|
1165
|
-
execFileSync(path3.join(process3.env.SystemRoot, "System32/WindowsPowerShell/v1.0/powershell.exe"), ["-NoProfile", "-NonInteractive", "-Command", "Start-Process -ErrorAction Stop -WindowStyle Hidden -FilePath $env:BROWSE_EXE -ArgumentList $env:BROWSE_ARGS"], { env: { ...childEnv, BROWSE_EXE: launch.executable, BROWSE_ARGS: args }, windowsHide: true, stdio: "ignore" });
|
|
1166
|
-
return;
|
|
1167
|
-
}
|
|
1168
|
-
const child = spawn(launch.executable, launch.args, {
|
|
1169
|
-
detached: true,
|
|
1170
|
-
stdio: "ignore",
|
|
1171
|
-
env: childEnv
|
|
1172
|
-
});
|
|
1173
|
-
child.unref();
|
|
1174
|
-
},
|
|
1175
|
-
catch: (cause) => cause instanceof Error ? cause : new Error("Failed to start browse relay", { cause })
|
|
1176
|
-
});
|
|
1177
|
-
}
|
|
1178
|
-
var relayEnvironmentNames = new Set([
|
|
1179
|
-
"PATH",
|
|
1180
|
-
"HOME",
|
|
1181
|
-
"USER",
|
|
1182
|
-
"LOGNAME",
|
|
1183
|
-
"SHELL",
|
|
1184
|
-
"TMPDIR",
|
|
1185
|
-
"TEMP",
|
|
1186
|
-
"TMP",
|
|
1187
|
-
"LANG",
|
|
1188
|
-
"LANGUAGE",
|
|
1189
|
-
"TZ",
|
|
1190
|
-
"XDG_DATA_HOME",
|
|
1191
|
-
"XDG_CONFIG_HOME",
|
|
1192
|
-
"XDG_STATE_HOME",
|
|
1193
|
-
"XDG_CACHE_HOME",
|
|
1194
|
-
"XDG_BIN_HOME",
|
|
1195
|
-
"XDG_RUNTIME_DIR",
|
|
1196
|
-
"DISPLAY",
|
|
1197
|
-
"WAYLAND_DISPLAY",
|
|
1198
|
-
"HTTP_PROXY",
|
|
1199
|
-
"HTTPS_PROXY",
|
|
1200
|
-
"NO_PROXY",
|
|
1201
|
-
"ALL_PROXY",
|
|
1202
|
-
"SSL_CERT_FILE",
|
|
1203
|
-
"SSL_CERT_DIR",
|
|
1204
|
-
"NODE_EXTRA_CA_CERTS",
|
|
1205
|
-
"SYSTEMROOT",
|
|
1206
|
-
"SYSTEMDRIVE",
|
|
1207
|
-
"WINDIR",
|
|
1208
|
-
"COMSPEC",
|
|
1209
|
-
"PATHEXT",
|
|
1210
|
-
"USERPROFILE",
|
|
1211
|
-
"APPDATA",
|
|
1212
|
-
"LOCALAPPDATA",
|
|
1213
|
-
"PROGRAMDATA",
|
|
1214
|
-
"PROGRAMFILES",
|
|
1215
|
-
"PROGRAMFILES(X86)",
|
|
1216
|
-
"HOMEDRIVE",
|
|
1217
|
-
"HOMEPATH",
|
|
1218
|
-
"USERNAME"
|
|
1219
|
-
]);
|
|
1220
|
-
var relayEnvironmentPrefixes = ["OPENCODE_BROWSER_", "LC_"];
|
|
1221
|
-
function relayEnvironment(env) {
|
|
1222
|
-
return Object.fromEntries(Object.entries(env).filter(([name, value]) => {
|
|
1223
|
-
if (value === undefined)
|
|
1224
|
-
return false;
|
|
1225
|
-
const upper = name.toUpperCase();
|
|
1226
|
-
return relayEnvironmentNames.has(upper) || relayEnvironmentPrefixes.some((prefix) => upper.startsWith(prefix));
|
|
1227
|
-
}));
|
|
1228
|
-
}
|
|
1229
|
-
function managedRelayLaunch(entrypoint = loadedCliEntrypoint, executable = process3.execPath, execArgv = process3.execArgv) {
|
|
1230
|
-
if (!scriptEntry(entrypoint))
|
|
1231
|
-
return { executable: entrypoint, args: ["serve"] };
|
|
1232
|
-
return {
|
|
1233
|
-
executable,
|
|
1234
|
-
args: [...execArgv, managedRelayEntrypoint(entrypoint), "serve"]
|
|
1235
|
-
};
|
|
1236
|
-
}
|
|
1237
|
-
function managedRelayEntrypoint(entrypoint) {
|
|
1238
|
-
const name = path3.basename(entrypoint);
|
|
1239
|
-
if (name === "index.ts" || name === "opencode-browser-client.ts" || name === "cli.ts")
|
|
1240
|
-
return path3.join(path3.dirname(entrypoint), "main.ts");
|
|
1241
|
-
return entrypoint;
|
|
1242
|
-
}
|
|
1243
|
-
function isRelayUnreachable(error) {
|
|
1244
|
-
return error instanceof RelayUnreachable;
|
|
1245
|
-
}
|
|
1246
|
-
function isRelayStarting(error) {
|
|
1247
|
-
return error instanceof RelayRejected && error.code === "relay-starting";
|
|
1248
|
-
}
|
|
1249
|
-
function isRelayStartingOrUnreachable(error) {
|
|
1250
|
-
return isRelayStarting(error) || isRelayUnreachable(error);
|
|
1251
|
-
}
|
|
1252
|
-
function liveRelayInstanceId() {
|
|
1253
|
-
const state = readRelayState();
|
|
1254
|
-
return state !== undefined && state.configuredPort === configuredRelayPort() && processAlive(state.pid) ? state.instanceId : undefined;
|
|
1255
|
-
}
|
|
1256
|
-
function relayRecorded(instanceId) {
|
|
1257
|
-
const live = liveRelayInstanceId();
|
|
1258
|
-
return live !== undefined && (instanceId === undefined || live === instanceId);
|
|
1259
|
-
}
|
|
1260
|
-
function relayDraining(error) {
|
|
1261
|
-
return error instanceof RelayDecodeFailed && relayRecorded();
|
|
1262
|
-
}
|
|
1263
|
-
function isForeignListener(error, pinned) {
|
|
1264
|
-
if (pinned ?? relayPortPinned())
|
|
1265
|
-
return false;
|
|
1266
|
-
return error instanceof RelayDecodeFailed;
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
export { map, withDefault, option, String2, Int, Boolean2, portConfig, extensionOriginsConfig, RelayUnreachable, RelayRejected, Service, layerFetch, layerFetchMcp, appendManagedRelayProcessLog, relayLog, shouldWaitForExtensionReconnect, relayBuildProblem, olderMcpClientAdvice, ensureRelay, restartRelay, extensionReconnectWaitMs, ensureExtensionConnected, stoppedRelayStatus, statusCollections, startManagedRelay };
|