@opencode/browse 0.0.15-dev.110 → 0.0.15-dev.112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{Undici-88kyhfpm.mjs → Undici-mxpvn7gy.mjs} +1 -1
  2. package/dist/{cli-ftng02ff.mjs → cli-k4ep9bqh.mjs} +134 -130
  3. package/dist/cli.mjs +13 -13
  4. package/dist/{helpers-xcy6tqv8.mjs → helpers-z9sm10dt.mjs} +2 -2
  5. package/dist/{index-yzz55kxm.mjs → index-6gkr235e.mjs} +1 -1
  6. package/dist/{main-x8sv1x9z.mjs → main-4gta7aqg.mjs} +59 -57
  7. package/dist/{main-2vk5mg8n.mjs → main-7925awaa.mjs} +4 -4
  8. package/dist/main-9t2s5ptx.mjs +5405 -0
  9. package/dist/{main-vgzr4689.mjs → main-azpzpy0x.mjs} +1 -1
  10. package/dist/main-b5v6hjvs.mjs +1255 -0
  11. package/dist/{main-w79fw3mt.mjs → main-bw7m61nw.mjs} +3 -3
  12. package/dist/main-dbyqkg36.mjs +1694 -0
  13. package/dist/{main-8z9d979q.mjs → main-er120rjm.mjs} +2 -2
  14. package/dist/{main-yf9xhpn4.mjs → main-ken6azcs.mjs} +2 -2
  15. package/dist/{main-pnhrdk7y.mjs → main-meec74m9.mjs} +2 -2
  16. package/dist/main-pgnhq60v.mjs +4 -0
  17. package/dist/{main-7p43gjgk.mjs → main-r5pwe9d8.mjs} +4 -4
  18. package/dist/{main-dghqndja.mjs → main-trj5w92c.mjs} +2 -2
  19. package/dist/{main-fpc5be6h.mjs → main-wsgfvvd6.mjs} +8 -8
  20. package/dist/{main-tyydn3xk.mjs → main-ydew87vm.mjs} +2 -2
  21. package/dist/{main-csnx585b.mjs → main-yf5j8g79.mjs} +2800 -8017
  22. package/dist/{mcp-mhms2jng.mjs → mcp-j7sd8vrv.mjs} +415 -411
  23. package/dist/{migrate-w1ted1w6.mjs → migrate-bqb73tpb.mjs} +5 -5
  24. package/dist/{relay-xhz6s81w.mjs → relay-thq3nwb4.mjs} +127 -123
  25. package/dist/{runtime-update-fm0me22e.mjs → runtime-update-6mh1x6rt.mjs} +7 -6
  26. package/dist/{setup-g3fpqzqe.mjs → setup-072zcfcw.mjs} +19 -10
  27. package/dist/{supervisor-40ckz6kf.mjs → supervisor-2vwykyf5.mjs} +3 -3
  28. package/dist/{update-83zpyvjn.mjs → update-h5swvj6m.mjs} +3 -3
  29. package/dist/{version-njstahmg.mjs → version-2qbk7aw2.mjs} +1 -1
  30. package/package.json +1 -1
  31. package/dist/main-rty99vp8.mjs +0 -4
  32. package/dist/main-tams6t1b.mjs +0 -2924
@@ -1,2924 +0,0 @@
1
- import {
2
- SessionDeleted,
3
- ExecuteLogEntry,
4
- ExecuteLogSummary,
5
- ExecuteAftermath,
6
- ExtensionStatus,
7
- RelayVersion,
8
- AuthProfileSummary,
9
- RecordingQuality,
10
- SettingsGetResponse,
11
- SettingsSetResponse,
12
- parseTargetSelection2,
13
- getObject2,
14
- getString2
15
- } from "./main-x8sv1x9z.mjs";
16
- import {
17
- isNodeError,
18
- writeJsonFileAtomically
19
- } from "./main-vgzr4689.mjs";
20
- import {
21
- getStackTraceLimit,
22
- setStackTraceLimit,
23
- withFiber,
24
- none,
25
- some,
26
- isSome,
27
- fromUndefinedOr,
28
- flatMap,
29
- Service2,
30
- makeUnsafe2,
31
- empty,
32
- make4,
33
- add,
34
- getOrUndefinedUnsafe,
35
- merge,
36
- TaggedError,
37
- getCurrentFiber,
38
- succeed2,
39
- sync,
40
- suspend,
41
- succeedNone,
42
- void_,
43
- callback,
44
- asSome,
45
- flatMap2,
46
- onExitPrimitive,
47
- uninterruptibleMask,
48
- StackTrace,
49
- effectContext,
50
- isEffect,
51
- promise,
52
- tryPromise,
53
- succeed6,
54
- sync2,
55
- callback2,
56
- gen,
57
- fail5,
58
- try_,
59
- option2,
60
- catchIf,
61
- mapError,
62
- context2,
63
- contextWith,
64
- provide3,
65
- acquireUseRelease,
66
- fnUntraced,
67
- fn,
68
- passthrough,
69
- transformOptional,
70
- withDefault2,
71
- declare,
72
- decodeUnknownEffect2,
73
- decodeUnknownSync,
74
- encodeUnknownOption,
75
- make8,
76
- isSchema,
77
- optionalKey,
78
- optional,
79
- toType,
80
- Literal,
81
- TemplateLiteral,
82
- Never,
83
- Any,
84
- Unknown,
85
- String3,
86
- Number2,
87
- Boolean3,
88
- Void,
89
- Struct,
90
- fieldsAssign,
91
- Record,
92
- StructWithRest,
93
- ArraySchema,
94
- Union,
95
- Literals,
96
- UndefinedOr,
97
- decodeTo2,
98
- decode2,
99
- withConstructorDefault,
100
- tag2,
101
- Opaque,
102
- makeFilter,
103
- isPattern,
104
- Finite,
105
- isBetween,
106
- Int2,
107
- Defect,
108
- Uint8ArrayFromBase64,
109
- Exit,
110
- Class2,
111
- Error2,
112
- TaggedError2,
113
- toJsonSchemaDocument,
114
- Json,
115
- JsonObject,
116
- isStream,
117
- provideContext2
118
- } from "./main-csnx585b.mjs";
119
- import {
120
- pipeArguments,
121
- identity,
122
- constTrue,
123
- constFalse,
124
- constUndefined,
125
- isString,
126
- isNumber,
127
- isBoolean,
128
- isObject,
129
- hasProperty
130
- } from "./main-yf9xhpn4.mjs";
131
- import {
132
- dataRoot,
133
- cliCommand
134
- } from "./main-fpc5be6h.mjs";
135
-
136
- // node_modules/effect/dist/Semaphore.js
137
- var makeUnsafe = (permits) => new SemaphoreImpl(permits);
138
- var waitForPermits = (self, n, effect) => callback((resume) => {
139
- if (self.free >= n)
140
- return resume(effect);
141
- const observer = () => {
142
- if (self.free < n)
143
- return;
144
- self.waiters.delete(observer);
145
- resume(effect);
146
- };
147
- self.waiters.add(observer);
148
- return sync(() => {
149
- self.waiters.delete(observer);
150
- });
151
- });
152
-
153
- class SemaphoreImpl {
154
- waiters = /* @__PURE__ */ new Set;
155
- taken = 0;
156
- permits;
157
- constructor(permits) {
158
- this.permits = permits;
159
- }
160
- get free() {
161
- return this.permits - this.taken;
162
- }
163
- take(n) {
164
- const take = suspend(() => {
165
- if (this.free < n) {
166
- return waitForPermits(this, n, take);
167
- }
168
- this.taken += n;
169
- return succeed2(n);
170
- });
171
- return take;
172
- }
173
- takeIfAvailable(n) {
174
- return suspend(() => {
175
- if (this.free < n)
176
- return succeed2(false);
177
- this.taken += n;
178
- return succeed2(true);
179
- });
180
- }
181
- releaseUnsafe(fiber, n) {
182
- this.taken -= n;
183
- if (this.waiters.size > 0) {
184
- fiber.currentDispatcher.scheduleTask(() => {
185
- for (const observer of this.waiters) {
186
- if (this.free <= 0)
187
- break;
188
- observer();
189
- }
190
- }, 0);
191
- }
192
- return this.free;
193
- }
194
- resize(permits) {
195
- return withFiber((fiber) => {
196
- this.permits = permits;
197
- if (this.free < 0)
198
- return void_;
199
- this.releaseUnsafe(fiber, 0);
200
- return void_;
201
- });
202
- }
203
- release(n) {
204
- return withFiber((fiber) => succeed2(this.releaseUnsafe(fiber, n)));
205
- }
206
- get releaseAll() {
207
- return withFiber((fiber) => succeed2(this.releaseUnsafe(fiber, this.taken)));
208
- }
209
- withPermits(n) {
210
- return (self) => uninterruptibleMask((restore) => {
211
- const acquire = suspend(() => {
212
- if (this.free < n) {
213
- const wait = waitForPermits(this, n, void_);
214
- return flatMap2(restore(wait), () => acquire);
215
- }
216
- this.taken += n;
217
- return onExitPrimitive(restore(self), () => {
218
- this.releaseUnsafe(getCurrentFiber(), n);
219
- return;
220
- }, true);
221
- });
222
- return acquire;
223
- });
224
- }
225
- withPermit = /* @__PURE__ */ this.withPermits(1);
226
- withPermitsIfAvailable(n) {
227
- return (self) => uninterruptibleMask((restore) => {
228
- if (this.free < n)
229
- return succeedNone;
230
- this.taken += n;
231
- return onExitPrimitive(restore(asSome(self)), () => {
232
- this.releaseUnsafe(getCurrentFiber(), n);
233
- return;
234
- }, true);
235
- });
236
- }
237
- }
238
- var make = (permits) => sync(() => new SemaphoreImpl(permits));
239
-
240
- // node_modules/effect/dist/PrimaryKey.js
241
- var symbol = "~effect/PrimaryKey";
242
- // node_modules/effect/dist/rpc/RpcSchema.js
243
- var StreamSchemaTypeId = "~effect/rpc/RpcSchema/StreamSchema";
244
- function isStreamSchema(schema) {
245
- return hasProperty(schema, StreamSchemaTypeId);
246
- }
247
- function getStreamSchemas(schema) {
248
- return isStreamSchema(schema) ? some({
249
- success: schema.success,
250
- error: schema.error
251
- }) : none();
252
- }
253
- var schema = /* @__PURE__ */ declare(isStream);
254
- function Stream(success, error) {
255
- return make8(schema.ast, {
256
- [StreamSchemaTypeId]: StreamSchemaTypeId,
257
- success,
258
- error
259
- });
260
- }
261
-
262
- class ClientAbort extends (/* @__PURE__ */ Service2()("effect/rpc/RpcSchema/ClientAbort")) {
263
- static annotation = /* @__PURE__ */ this.context(true).pipe(/* @__PURE__ */ add(StackTrace, {
264
- name: "ClientAbort",
265
- stack: constUndefined,
266
- parent: undefined
267
- }));
268
- }
269
-
270
- // node_modules/effect/dist/rpc/Rpc.js
271
- var TypeId = "~effect/rpc/Rpc";
272
- class ServerClient {
273
- id;
274
- annotations;
275
- constructor(id) {
276
- this.id = id;
277
- this.annotations = empty();
278
- }
279
- annotate(tag, value) {
280
- this.annotations = add(this.annotations, tag, value);
281
- return this;
282
- }
283
- }
284
- var Proto = {
285
- [TypeId]: TypeId,
286
- pipe() {
287
- return pipeArguments(this, arguments);
288
- },
289
- setSuccess(successSchema) {
290
- return makeProto({
291
- _tag: this._tag,
292
- payloadSchema: this.payloadSchema,
293
- successSchema,
294
- errorSchema: this.errorSchema,
295
- defectSchema: this.defectSchema,
296
- annotations: this.annotations,
297
- middlewares: this.middlewares
298
- });
299
- },
300
- setError(errorSchema) {
301
- return makeProto({
302
- _tag: this._tag,
303
- payloadSchema: this.payloadSchema,
304
- successSchema: this.successSchema,
305
- errorSchema,
306
- defectSchema: this.defectSchema,
307
- annotations: this.annotations,
308
- middlewares: this.middlewares
309
- });
310
- },
311
- setPayload(payloadSchema) {
312
- return makeProto({
313
- _tag: this._tag,
314
- payloadSchema: isSchema(payloadSchema) ? payloadSchema : Struct(payloadSchema),
315
- successSchema: this.successSchema,
316
- errorSchema: this.errorSchema,
317
- defectSchema: this.defectSchema,
318
- annotations: this.annotations,
319
- middlewares: this.middlewares
320
- });
321
- },
322
- middleware(middleware) {
323
- return makeProto({
324
- _tag: this._tag,
325
- payloadSchema: this.payloadSchema,
326
- successSchema: this.successSchema,
327
- errorSchema: this.errorSchema,
328
- defectSchema: this.defectSchema,
329
- annotations: this.annotations,
330
- middlewares: new Set([...this.middlewares, middleware])
331
- });
332
- },
333
- prefix(prefix) {
334
- return makeProto({
335
- _tag: `${prefix}${this._tag}`,
336
- payloadSchema: this.payloadSchema,
337
- successSchema: this.successSchema,
338
- errorSchema: this.errorSchema,
339
- defectSchema: this.defectSchema,
340
- annotations: this.annotations,
341
- middlewares: this.middlewares
342
- });
343
- },
344
- annotate(tag, value) {
345
- return makeProto({
346
- _tag: this._tag,
347
- payloadSchema: this.payloadSchema,
348
- successSchema: this.successSchema,
349
- errorSchema: this.errorSchema,
350
- defectSchema: this.defectSchema,
351
- middlewares: this.middlewares,
352
- annotations: add(this.annotations, tag, value)
353
- });
354
- },
355
- annotateMerge(context) {
356
- return makeProto({
357
- _tag: this._tag,
358
- payloadSchema: this.payloadSchema,
359
- successSchema: this.successSchema,
360
- errorSchema: this.errorSchema,
361
- defectSchema: this.defectSchema,
362
- middlewares: this.middlewares,
363
- annotations: merge(this.annotations, context)
364
- });
365
- }
366
- };
367
- var makeProto = (options) => {
368
- function Rpc() {}
369
- Object.setPrototypeOf(Rpc, Proto);
370
- Object.assign(Rpc, options);
371
- Rpc.key = `effect/rpc/Rpc/${options._tag}`;
372
- return Rpc;
373
- };
374
- var make2 = (tag, options) => {
375
- const successSchema = options?.success ?? Void;
376
- const errorSchema = options?.error ?? Never;
377
- const defectSchema = options?.defect ?? Defect();
378
- let payloadSchema;
379
- if (options?.primaryKey) {
380
- payloadSchema = class Payload extends Class2(`effect/rpc/Rpc/${tag}`)(options.payload) {
381
- [symbol]() {
382
- return options.primaryKey(this);
383
- }
384
- };
385
- } else {
386
- payloadSchema = isSchema(options?.payload) ? options?.payload : options?.payload ? Struct(options?.payload) : Void;
387
- }
388
- return makeProto({
389
- _tag: tag,
390
- payloadSchema,
391
- successSchema: options?.stream ? Stream(successSchema, errorSchema) : successSchema,
392
- errorSchema: options?.stream ? Never : errorSchema,
393
- defectSchema,
394
- annotations: empty(),
395
- middlewares: new Set
396
- });
397
- };
398
- var exitSchemaCache = /* @__PURE__ */ new WeakMap;
399
- var exitSchema = (self) => {
400
- if (exitSchemaCache.has(self)) {
401
- return exitSchemaCache.get(self);
402
- }
403
- const rpc = self;
404
- const failures = new Set([rpc.errorSchema]);
405
- const streamSchemas = getStreamSchemas(rpc.successSchema);
406
- if (isSome(streamSchemas)) {
407
- failures.add(streamSchemas.value.error);
408
- }
409
- for (const middleware of rpc.middlewares) {
410
- failures.add(middleware.error);
411
- }
412
- const schema = Exit(isSome(streamSchemas) ? Void : rpc.successSchema, Union([...failures]), rpc.defectSchema);
413
- exitSchemaCache.set(self, schema);
414
- return schema;
415
- };
416
- var WrapperTypeId = "~effect/rpc/Rpc/Wrapper";
417
- var isWrapper = (u) => (WrapperTypeId in u);
418
-
419
- // node_modules/effect/dist/rpc/RpcGroup.js
420
- var RpcGroupProto = {
421
- add(...rpcs) {
422
- const requests = new Map(this.requests);
423
- for (const rpc of rpcs) {
424
- requests.set(rpc._tag, rpc);
425
- }
426
- return makeProto2({
427
- requests,
428
- annotations: this.annotations
429
- });
430
- },
431
- merge(...groups) {
432
- const requests = new Map(this.requests);
433
- const annotations = new Map(this.annotations.mapUnsafe);
434
- for (const group of groups) {
435
- for (const [tag, rpc] of group.requests) {
436
- requests.set(tag, rpc);
437
- }
438
- for (const [key, value] of group.annotations.mapUnsafe) {
439
- annotations.set(key, value);
440
- }
441
- }
442
- return makeProto2({
443
- requests,
444
- annotations: makeUnsafe2(annotations)
445
- });
446
- },
447
- omit(...tags) {
448
- const requests = new Map(this.requests);
449
- for (const tag of tags) {
450
- requests.delete(tag);
451
- }
452
- return makeProto2({
453
- requests,
454
- annotations: this.annotations
455
- });
456
- },
457
- middleware(middleware) {
458
- const requests = new Map;
459
- for (const [tag, rpc] of this.requests) {
460
- requests.set(tag, rpc.middleware(middleware));
461
- }
462
- return makeProto2({
463
- requests,
464
- annotations: this.annotations
465
- });
466
- },
467
- toHandlers(build) {
468
- const self = this;
469
- return gen(function* () {
470
- const services = yield* context2();
471
- const handlers = isEffect(build) ? yield* build : build;
472
- const contextMap = new Map;
473
- self.requests.forEach((rpc, tag) => {
474
- contextMap.set(rpc.key, {
475
- tag: rpc._tag,
476
- handler: handlers[tag],
477
- context: services
478
- });
479
- });
480
- return makeUnsafe2(contextMap);
481
- });
482
- },
483
- prefix(prefix) {
484
- const requests = new Map;
485
- for (const rpc of this.requests.values()) {
486
- const newRpc = rpc.prefix(prefix);
487
- requests.set(newRpc._tag, newRpc);
488
- }
489
- return makeProto2({
490
- requests,
491
- annotations: this.annotations
492
- });
493
- },
494
- toLayer(build) {
495
- return effectContext(this.toHandlers(build));
496
- },
497
- of: identity,
498
- toLayerHandler(service, build) {
499
- const self = this;
500
- return effectContext(gen(function* () {
501
- const services = yield* context2();
502
- const handler = isEffect(build) ? yield* build : build;
503
- const contextMap = new Map;
504
- const rpc = self.requests.get(service);
505
- contextMap.set(rpc.key, {
506
- handler,
507
- context: services
508
- });
509
- return makeUnsafe2(contextMap);
510
- }));
511
- },
512
- accessHandler(service) {
513
- return contextWith((parentContext) => {
514
- const rpc = this.requests.get(service);
515
- const {
516
- handler,
517
- context
518
- } = getOrUndefinedUnsafe(parentContext, rpc.key);
519
- return succeed6((payload, options) => {
520
- options.rpc = rpc;
521
- const result = handler(payload, options);
522
- const effectOrStream = isWrapper(result) ? result.value : result;
523
- return isEffect(effectOrStream) ? provide3(effectOrStream, context) : provideContext2(effectOrStream, context);
524
- });
525
- });
526
- },
527
- annotate(service, value) {
528
- return makeProto2({
529
- requests: this.requests,
530
- annotations: add(this.annotations, service, value)
531
- });
532
- },
533
- annotateRpcs(service, value) {
534
- return this.annotateRpcsMerge(make4(service, value));
535
- },
536
- annotateMerge(context) {
537
- return makeProto2({
538
- requests: this.requests,
539
- annotations: merge(this.annotations, context)
540
- });
541
- },
542
- annotateRpcsMerge(context) {
543
- const requests = new Map;
544
- for (const [tag, rpc] of this.requests) {
545
- requests.set(tag, rpc.annotateMerge(merge(context, rpc.annotations)));
546
- }
547
- return makeProto2({
548
- requests,
549
- annotations: this.annotations
550
- });
551
- }
552
- };
553
- var makeProto2 = (options) => Object.assign(function() {}, RpcGroupProto, {
554
- requests: options.requests,
555
- annotations: options.annotations
556
- });
557
- var make3 = (...rpcs) => makeProto2({
558
- requests: new Map(rpcs.map((rpc) => [rpc._tag, rpc])),
559
- annotations: empty()
560
- });
561
-
562
- // node_modules/effect/dist/rpc/RpcMiddleware.js
563
- var TypeId2 = "~effect/rpc/RpcMiddleware";
564
- var Service = () => (id, options) => {
565
- const limit = getStackTraceLimit();
566
- let creationError;
567
- if (limit !== 0) {
568
- setStackTraceLimit(2);
569
- creationError = new globalThis.Error;
570
- setStackTraceLimit(limit);
571
- }
572
- function ServiceClass() {}
573
- const ServiceClass_ = ServiceClass;
574
- Object.setPrototypeOf(ServiceClass, Object.getPrototypeOf(Service2(id)));
575
- ServiceClass.key = id;
576
- Object.defineProperty(ServiceClass, "stack", {
577
- get() {
578
- return creationError?.stack;
579
- }
580
- });
581
- ServiceClass_[TypeId2] = TypeId2;
582
- ServiceClass_.error = options?.error ?? Never;
583
- ServiceClass_.requiredForClient = options?.requiredForClient ?? false;
584
- return ServiceClass;
585
- };
586
-
587
- // node_modules/effect/dist/ai/McpSchema.js
588
- var optionalWithDefault = (schema, defaultValue) => {
589
- const effect = sync2(defaultValue);
590
- return optionalKey(schema).pipe(decode2({
591
- decode: withDefault2(effect),
592
- encode: passthrough()
593
- }), withConstructorDefault(effect));
594
- };
595
- var optional2 = (schema) => optionalKey(schema).pipe(decodeTo2(toType(optional(schema)), {
596
- decode: passthrough(),
597
- encode: transformOptional(flatMap(fromUndefinedOr))
598
- }));
599
- var RequestId = /* @__PURE__ */ Union([String3, Finite]);
600
- var ProgressToken = /* @__PURE__ */ Union([String3, Finite]);
601
-
602
- class RequestMeta extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
603
- _meta: /* @__PURE__ */ optional2(/* @__PURE__ */ StructWithRest(/* @__PURE__ */ Struct({
604
- progressToken: /* @__PURE__ */ optional2(ProgressToken)
605
- }), [JsonObject]))
606
- }))) {
607
- }
608
-
609
- class ResultMeta extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
610
- _meta: /* @__PURE__ */ optional2(JsonObject)
611
- }))) {
612
- }
613
-
614
- class NotificationMeta extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
615
- _meta: /* @__PURE__ */ optional2(JsonObject)
616
- }))) {
617
- }
618
- var Cursor = String3;
619
-
620
- class PaginatedRequestMeta extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
621
- ...RequestMeta.fields,
622
- cursor: /* @__PURE__ */ optional2(Cursor)
623
- }))) {
624
- }
625
-
626
- class PaginatedResultMeta extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
627
- ...ResultMeta.fields,
628
- nextCursor: /* @__PURE__ */ optional2(Cursor)
629
- }))) {
630
- }
631
- var Role = /* @__PURE__ */ Literals(["user", "assistant"]);
632
-
633
- class Annotations extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
634
- audience: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(Role)),
635
- priority: /* @__PURE__ */ optional2(/* @__PURE__ */ Finite.check(/* @__PURE__ */ isBetween({
636
- minimum: 0,
637
- maximum: 1
638
- }))),
639
- lastModified: /* @__PURE__ */ optional2(String3)
640
- }))) {
641
- }
642
-
643
- class Icon extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/Icon")({
644
- src: String3,
645
- mimeType: /* @__PURE__ */ optional2(String3),
646
- sizes: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3)),
647
- theme: /* @__PURE__ */ optional2(/* @__PURE__ */ Literals(["light", "dark"]))
648
- })) {
649
- }
650
-
651
- class Implementation extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
652
- name: String3,
653
- title: /* @__PURE__ */ optional2(String3),
654
- version: String3,
655
- icons: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(Icon)),
656
- description: /* @__PURE__ */ optional2(String3),
657
- websiteUrl: /* @__PURE__ */ optional2(String3)
658
- }))) {
659
- }
660
-
661
- class ClientCapabilities extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ClientCapabilities")({
662
- experimental: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(String3, /* @__PURE__ */ Struct({}))),
663
- extensions: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(/* @__PURE__ */ TemplateLiteral([String3, "/", String3]), Json)),
664
- roots: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({
665
- listChanged: /* @__PURE__ */ optional2(Boolean3)
666
- })),
667
- sampling: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({
668
- context: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({})),
669
- tools: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({}))
670
- })),
671
- elicitation: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({
672
- form: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({})),
673
- url: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({}))
674
- }))
675
- })) {
676
- }
677
-
678
- class ServerCapabilities extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
679
- experimental: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(String3, /* @__PURE__ */ Struct({}))),
680
- extensions: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(/* @__PURE__ */ TemplateLiteral([String3, "/", String3]), Json)),
681
- logging: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({})),
682
- completions: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({})),
683
- prompts: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({
684
- listChanged: /* @__PURE__ */ optional2(Boolean3)
685
- })),
686
- resources: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({
687
- subscribe: /* @__PURE__ */ optional2(Boolean3),
688
- listChanged: /* @__PURE__ */ optional2(Boolean3)
689
- })),
690
- tools: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct({
691
- listChanged: /* @__PURE__ */ optional2(Boolean3)
692
- }))
693
- }))) {
694
- }
695
-
696
- class McpErrorBase extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/McpErrorBase")({
697
- code: Int2,
698
- message: String3,
699
- data: /* @__PURE__ */ optional2(Any)
700
- })) {
701
- }
702
- var INVALID_REQUEST_ERROR_CODE = -32600;
703
- var METHOD_NOT_FOUND_ERROR_CODE = -32601;
704
- var INVALID_PARAMS_ERROR_CODE = -32602;
705
- var INTERNAL_ERROR_CODE = -32603;
706
- var PARSE_ERROR_CODE = -32700;
707
- var HEADER_MISMATCH_ERROR_CODE = -32020;
708
-
709
- class ParseError extends (/* @__PURE__ */ Error2("effect/ai/McpSchema/ParseError")({
710
- ...McpErrorBase.fields,
711
- _tag: /* @__PURE__ */ tag2("ParseError"),
712
- code: /* @__PURE__ */ tag2(PARSE_ERROR_CODE)
713
- })) {
714
- }
715
-
716
- class InvalidRequest extends (/* @__PURE__ */ Error2("effect/ai/McpSchema/InvalidRequest")({
717
- ...McpErrorBase.fields,
718
- _tag: /* @__PURE__ */ tag2("InvalidRequest"),
719
- code: /* @__PURE__ */ tag2(INVALID_REQUEST_ERROR_CODE)
720
- })) {
721
- }
722
-
723
- class MethodNotFound extends (/* @__PURE__ */ Error2("effect/ai/McpSchema/MethodNotFound")({
724
- ...McpErrorBase.fields,
725
- _tag: /* @__PURE__ */ tag2("MethodNotFound"),
726
- code: /* @__PURE__ */ tag2(METHOD_NOT_FOUND_ERROR_CODE)
727
- })) {
728
- }
729
-
730
- class InvalidParams extends (/* @__PURE__ */ Error2("effect/ai/McpSchema/InvalidParams")({
731
- ...McpErrorBase.fields,
732
- _tag: /* @__PURE__ */ tag2("InvalidParams"),
733
- code: /* @__PURE__ */ tag2(INVALID_PARAMS_ERROR_CODE)
734
- })) {
735
- }
736
-
737
- class InternalError extends (/* @__PURE__ */ Error2("effect/ai/McpSchema/InternalError")({
738
- ...McpErrorBase.fields,
739
- _tag: /* @__PURE__ */ tag2("InternalError"),
740
- code: /* @__PURE__ */ tag2(INTERNAL_ERROR_CODE)
741
- })) {
742
- static notImplemented = /* @__PURE__ */ new InternalError({
743
- message: "Not implemented"
744
- });
745
- }
746
- var McpError = /* @__PURE__ */ Union([ParseError, InvalidRequest, MethodNotFound, InvalidParams, InternalError, McpErrorBase]);
747
-
748
- class Ping extends (/* @__PURE__ */ make2("ping", {
749
- success: /* @__PURE__ */ Struct({}),
750
- error: McpError,
751
- payload: /* @__PURE__ */ UndefinedOr(RequestMeta)
752
- })) {
753
- }
754
-
755
- class InitializeResult extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
756
- ...ResultMeta.fields,
757
- protocolVersion: String3,
758
- capabilities: ServerCapabilities,
759
- serverInfo: Implementation,
760
- instructions: /* @__PURE__ */ optional2(String3)
761
- }))) {
762
- }
763
-
764
- class Initialize extends (/* @__PURE__ */ make2("initialize", {
765
- success: InitializeResult,
766
- error: McpError,
767
- payload: {
768
- ...RequestMeta.fields,
769
- protocolVersion: String3,
770
- capabilities: ClientCapabilities,
771
- clientInfo: Implementation
772
- }
773
- })) {
774
- }
775
- class CancelledNotification extends (/* @__PURE__ */ make2("notifications/cancelled", {
776
- payload: {
777
- ...NotificationMeta.fields,
778
- requestId: RequestId,
779
- reason: /* @__PURE__ */ optional2(String3)
780
- }
781
- })) {
782
- }
783
-
784
- class ProgressNotification extends (/* @__PURE__ */ make2("notifications/progress", {
785
- payload: {
786
- ...NotificationMeta.fields,
787
- progressToken: ProgressToken,
788
- progress: Finite,
789
- total: /* @__PURE__ */ optional2(Finite),
790
- message: /* @__PURE__ */ optional2(String3)
791
- }
792
- })) {
793
- }
794
-
795
- class Resource extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/Resource")({
796
- uri: String3,
797
- name: String3,
798
- title: /* @__PURE__ */ optional2(String3),
799
- description: /* @__PURE__ */ optional2(String3),
800
- mimeType: /* @__PURE__ */ optional2(String3),
801
- annotations: /* @__PURE__ */ optional2(Annotations),
802
- icons: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(Icon)),
803
- size: /* @__PURE__ */ optional2(Int2),
804
- _meta: /* @__PURE__ */ optional2(JsonObject)
805
- })) {
806
- }
807
-
808
- class ResourceTemplate extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ResourceTemplate")({
809
- uriTemplate: String3,
810
- name: String3,
811
- title: /* @__PURE__ */ optional2(String3),
812
- description: /* @__PURE__ */ optional2(String3),
813
- mimeType: /* @__PURE__ */ optional2(String3),
814
- annotations: /* @__PURE__ */ optional2(Annotations),
815
- icons: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(Icon)),
816
- _meta: /* @__PURE__ */ optional2(JsonObject)
817
- })) {
818
- }
819
-
820
- class ResourceContents extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
821
- uri: String3,
822
- mimeType: /* @__PURE__ */ optional2(String3),
823
- _meta: /* @__PURE__ */ optional2(JsonObject)
824
- }))) {
825
- }
826
-
827
- class TextResourceContents extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
828
- ...ResourceContents.fields,
829
- text: String3
830
- }))) {
831
- }
832
-
833
- class BlobResourceContents extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
834
- ...ResourceContents.fields,
835
- blob: Uint8ArrayFromBase64
836
- }))) {
837
- }
838
-
839
- class ListResourcesResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ListResourcesResult")({
840
- ...PaginatedResultMeta.fields,
841
- resources: /* @__PURE__ */ ArraySchema(Resource)
842
- })) {
843
- }
844
- class ListResourceTemplatesResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ListResourceTemplatesResult")({
845
- ...PaginatedResultMeta.fields,
846
- resourceTemplates: /* @__PURE__ */ ArraySchema(ResourceTemplate)
847
- })) {
848
- }
849
- class ReadResourceResult extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
850
- ...ResultMeta.fields,
851
- contents: /* @__PURE__ */ ArraySchema(/* @__PURE__ */ Union([TextResourceContents, BlobResourceContents]))
852
- }))) {
853
- }
854
-
855
- class ReadResource extends (/* @__PURE__ */ make2("resources/read", {
856
- success: ReadResourceResult,
857
- error: McpError,
858
- payload: {
859
- ...RequestMeta.fields,
860
- uri: String3
861
- }
862
- })) {
863
- }
864
-
865
- class ResourceListChangedNotification extends (/* @__PURE__ */ make2("notifications/resources/list_changed", {
866
- payload: /* @__PURE__ */ UndefinedOr(NotificationMeta)
867
- })) {
868
- }
869
-
870
- class Subscribe extends (/* @__PURE__ */ make2("resources/subscribe", {
871
- success: /* @__PURE__ */ Struct({}),
872
- error: McpError,
873
- payload: {
874
- ...RequestMeta.fields,
875
- uri: String3
876
- }
877
- })) {
878
- }
879
-
880
- class Unsubscribe extends (/* @__PURE__ */ make2("resources/unsubscribe", {
881
- success: /* @__PURE__ */ Struct({}),
882
- error: McpError,
883
- payload: {
884
- ...RequestMeta.fields,
885
- uri: String3
886
- }
887
- })) {
888
- }
889
-
890
- class ResourceUpdatedNotification extends (/* @__PURE__ */ make2("notifications/resources/updated", {
891
- payload: {
892
- ...NotificationMeta.fields,
893
- uri: String3
894
- }
895
- })) {
896
- }
897
-
898
- class PromptArgument extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
899
- name: String3,
900
- title: /* @__PURE__ */ optional2(String3),
901
- description: /* @__PURE__ */ optional2(String3),
902
- required: /* @__PURE__ */ optional2(Boolean3)
903
- }))) {
904
- }
905
-
906
- class Prompt extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/Prompt")({
907
- name: String3,
908
- title: /* @__PURE__ */ optional2(String3),
909
- description: /* @__PURE__ */ optional2(String3),
910
- arguments: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(PromptArgument)),
911
- icons: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(Icon)),
912
- _meta: /* @__PURE__ */ optional2(JsonObject)
913
- })) {
914
- }
915
-
916
- class TextContent extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
917
- type: /* @__PURE__ */ tag2("text"),
918
- text: String3,
919
- annotations: /* @__PURE__ */ optional2(Annotations),
920
- _meta: /* @__PURE__ */ optional2(JsonObject)
921
- }))) {
922
- }
923
-
924
- class ImageContent extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
925
- type: /* @__PURE__ */ tag2("image"),
926
- data: Uint8ArrayFromBase64,
927
- mimeType: String3,
928
- annotations: /* @__PURE__ */ optional2(Annotations),
929
- _meta: /* @__PURE__ */ optional2(JsonObject)
930
- }))) {
931
- }
932
-
933
- class AudioContent extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
934
- type: /* @__PURE__ */ tag2("audio"),
935
- data: Uint8ArrayFromBase64,
936
- mimeType: String3,
937
- annotations: /* @__PURE__ */ optional2(Annotations),
938
- _meta: /* @__PURE__ */ optional2(JsonObject)
939
- }))) {
940
- }
941
-
942
- class EmbeddedResource extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
943
- type: /* @__PURE__ */ tag2("resource"),
944
- resource: /* @__PURE__ */ Union([TextResourceContents, BlobResourceContents]),
945
- annotations: /* @__PURE__ */ optional2(Annotations),
946
- _meta: /* @__PURE__ */ optional2(JsonObject)
947
- }))) {
948
- }
949
-
950
- class ResourceLink extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
951
- ...Resource.fields,
952
- type: /* @__PURE__ */ tag2("resource_link")
953
- }))) {
954
- }
955
- var ContentBlock = /* @__PURE__ */ Union([TextContent, ImageContent, AudioContent, EmbeddedResource, ResourceLink]);
956
-
957
- class PromptMessage extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
958
- role: Role,
959
- content: ContentBlock
960
- }))) {
961
- }
962
-
963
- class ListPromptsResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ListPromptsResult")({
964
- ...PaginatedResultMeta.fields,
965
- prompts: /* @__PURE__ */ ArraySchema(Prompt)
966
- })) {
967
- }
968
- class GetPromptResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/GetPromptResult")({
969
- ...ResultMeta.fields,
970
- messages: /* @__PURE__ */ ArraySchema(PromptMessage),
971
- description: /* @__PURE__ */ optional2(String3)
972
- })) {
973
- }
974
-
975
- class GetPrompt extends (/* @__PURE__ */ make2("prompts/get", {
976
- success: GetPromptResult,
977
- error: McpError,
978
- payload: {
979
- ...RequestMeta.fields,
980
- name: String3,
981
- title: /* @__PURE__ */ optional2(String3),
982
- arguments: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(String3, String3))
983
- }
984
- })) {
985
- }
986
-
987
- class PromptListChangedNotification extends (/* @__PURE__ */ make2("notifications/prompts/list_changed", {
988
- payload: /* @__PURE__ */ UndefinedOr(NotificationMeta)
989
- })) {
990
- }
991
-
992
- class ToolAnnotations extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
993
- title: /* @__PURE__ */ optional2(String3),
994
- readOnlyHint: /* @__PURE__ */ optionalWithDefault(Boolean3, constFalse),
995
- destructiveHint: /* @__PURE__ */ optionalWithDefault(Boolean3, constTrue),
996
- idempotentHint: /* @__PURE__ */ optionalWithDefault(Boolean3, constFalse),
997
- openWorldHint: /* @__PURE__ */ optionalWithDefault(Boolean3, constTrue)
998
- }))) {
999
- }
1000
- var ToolJson = /* @__PURE__ */ StructWithRest(/* @__PURE__ */ Struct({
1001
- type: /* @__PURE__ */ Literal("object"),
1002
- properties: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(String3, JsonObject)),
1003
- required: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3))
1004
- }), [JsonObject]);
1005
- var ToolOutputJson = JsonObject;
1006
-
1007
- class Tool extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/Tool")({
1008
- name: String3,
1009
- title: /* @__PURE__ */ optional2(String3),
1010
- description: /* @__PURE__ */ optional2(String3),
1011
- inputSchema: ToolJson,
1012
- outputSchema: /* @__PURE__ */ optional2(ToolOutputJson),
1013
- annotations: /* @__PURE__ */ optional2(ToolAnnotations),
1014
- icons: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(Icon)),
1015
- _meta: /* @__PURE__ */ optional2(JsonObject)
1016
- })) {
1017
- }
1018
-
1019
- class ListToolsResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ListToolsResult")({
1020
- ...PaginatedResultMeta.fields,
1021
- tools: /* @__PURE__ */ ArraySchema(Tool)
1022
- })) {
1023
- }
1024
- class CallToolResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/CallToolResult")({
1025
- ...ResultMeta.fields,
1026
- content: /* @__PURE__ */ ArraySchema(ContentBlock),
1027
- structuredContent: /* @__PURE__ */ optional2(Json),
1028
- isError: /* @__PURE__ */ optional2(Boolean3)
1029
- })) {
1030
- }
1031
-
1032
- class CallTool extends (/* @__PURE__ */ make2("tools/call", {
1033
- success: CallToolResult,
1034
- error: McpError,
1035
- payload: {
1036
- ...RequestMeta.fields,
1037
- name: String3,
1038
- arguments: /* @__PURE__ */ optionalWithDefault(/* @__PURE__ */ Record(String3, Any), () => ({}))
1039
- }
1040
- })) {
1041
- }
1042
-
1043
- class ToolListChangedNotification extends (/* @__PURE__ */ make2("notifications/tools/list_changed", {
1044
- payload: /* @__PURE__ */ UndefinedOr(NotificationMeta)
1045
- })) {
1046
- }
1047
- var LoggingLevel = /* @__PURE__ */ Literals(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
1048
-
1049
- class SetLevel extends (/* @__PURE__ */ make2("logging/setLevel", {
1050
- payload: {
1051
- ...RequestMeta.fields,
1052
- level: LoggingLevel
1053
- },
1054
- success: /* @__PURE__ */ Struct({}),
1055
- error: McpError
1056
- })) {
1057
- }
1058
-
1059
- class LoggingMessageNotification extends (/* @__PURE__ */ make2("notifications/message", {
1060
- payload: /* @__PURE__ */ Struct({
1061
- ...NotificationMeta.fields,
1062
- level: LoggingLevel,
1063
- logger: /* @__PURE__ */ optional2(String3),
1064
- data: Any
1065
- })
1066
- })) {
1067
- }
1068
-
1069
- class ToolUseContent extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ToolUseContent")({
1070
- type: /* @__PURE__ */ tag2("tool_use"),
1071
- id: String3,
1072
- name: String3,
1073
- input: /* @__PURE__ */ Record(String3, Unknown),
1074
- _meta: /* @__PURE__ */ optional2(JsonObject)
1075
- })) {
1076
- }
1077
-
1078
- class ToolResultContent extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ToolResultContent")({
1079
- type: /* @__PURE__ */ tag2("tool_result"),
1080
- toolUseId: String3,
1081
- content: /* @__PURE__ */ ArraySchema(ContentBlock),
1082
- structuredContent: /* @__PURE__ */ optional2(Json),
1083
- isError: /* @__PURE__ */ optional2(Boolean3),
1084
- _meta: /* @__PURE__ */ optional2(JsonObject)
1085
- })) {
1086
- }
1087
- var SamplingMessageContentBlock = /* @__PURE__ */ Union([TextContent, ImageContent, AudioContent, ToolUseContent, ToolResultContent]);
1088
-
1089
- class SamplingMessage extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
1090
- role: Role,
1091
- content: /* @__PURE__ */ Union([SamplingMessageContentBlock, /* @__PURE__ */ ArraySchema(SamplingMessageContentBlock)]),
1092
- _meta: /* @__PURE__ */ optional2(JsonObject)
1093
- }))) {
1094
- }
1095
-
1096
- class ToolChoice extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ToolChoice")({
1097
- mode: /* @__PURE__ */ optional2(/* @__PURE__ */ Literals(["auto", "required", "none"]))
1098
- })) {
1099
- }
1100
-
1101
- class ModelHint extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
1102
- name: /* @__PURE__ */ optional2(String3)
1103
- }))) {
1104
- }
1105
-
1106
- class ModelPreferences extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ModelPreferences")({
1107
- hints: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(ModelHint)),
1108
- costPriority: /* @__PURE__ */ optional2(/* @__PURE__ */ Finite.check(/* @__PURE__ */ isBetween({
1109
- minimum: 0,
1110
- maximum: 1
1111
- }))),
1112
- speedPriority: /* @__PURE__ */ optional2(/* @__PURE__ */ Finite.check(/* @__PURE__ */ isBetween({
1113
- minimum: 0,
1114
- maximum: 1
1115
- }))),
1116
- intelligencePriority: /* @__PURE__ */ optional2(/* @__PURE__ */ Finite.check(/* @__PURE__ */ isBetween({
1117
- minimum: 0,
1118
- maximum: 1
1119
- })))
1120
- })) {
1121
- }
1122
-
1123
- class CreateMessageResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/CreateMessageResult")({
1124
- role: Role,
1125
- content: /* @__PURE__ */ Union([SamplingMessageContentBlock, /* @__PURE__ */ ArraySchema(SamplingMessageContentBlock)]),
1126
- _meta: /* @__PURE__ */ optional2(JsonObject),
1127
- model: String3,
1128
- stopReason: /* @__PURE__ */ optional2(String3)
1129
- })) {
1130
- }
1131
-
1132
- class CreateMessage extends (/* @__PURE__ */ make2("sampling/createMessage", {
1133
- success: CreateMessageResult,
1134
- error: McpError,
1135
- payload: {
1136
- messages: /* @__PURE__ */ ArraySchema(SamplingMessage),
1137
- modelPreferences: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct(ModelPreferences.fields)),
1138
- systemPrompt: /* @__PURE__ */ optional2(String3),
1139
- includeContext: /* @__PURE__ */ optional2(/* @__PURE__ */ Literals(["none", "thisServer", "allServers"])),
1140
- temperature: /* @__PURE__ */ optional2(Finite),
1141
- maxTokens: Int2,
1142
- stopSequences: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3)),
1143
- metadata: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(String3, Unknown)),
1144
- tools: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(/* @__PURE__ */ Struct(Tool.fields))),
1145
- toolChoice: /* @__PURE__ */ optional2(/* @__PURE__ */ Struct(ToolChoice.fields))
1146
- }
1147
- })) {
1148
- }
1149
- class CompleteResult extends (/* @__PURE__ */ Opaque()(/* @__PURE__ */ Struct({
1150
- ...ResultMeta.fields,
1151
- completion: /* @__PURE__ */ Struct({
1152
- values: /* @__PURE__ */ ArraySchema(String3),
1153
- total: /* @__PURE__ */ optional2(Int2),
1154
- hasMore: /* @__PURE__ */ optional2(Boolean3)
1155
- })
1156
- }))) {
1157
- static empty = /* @__PURE__ */ CompleteResult.make({
1158
- completion: {
1159
- values: [],
1160
- total: 0,
1161
- hasMore: false
1162
- }
1163
- });
1164
- }
1165
- class Root extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/Root")({
1166
- uri: String3,
1167
- name: /* @__PURE__ */ optional2(String3),
1168
- _meta: /* @__PURE__ */ optional2(JsonObject)
1169
- })) {
1170
- }
1171
-
1172
- class ListRootsResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ListRootsResult")({
1173
- roots: /* @__PURE__ */ ArraySchema(Root)
1174
- })) {
1175
- }
1176
-
1177
- class ListRoots extends (/* @__PURE__ */ make2("roots/list", {
1178
- success: ListRootsResult,
1179
- error: McpError,
1180
- payload: /* @__PURE__ */ UndefinedOr(RequestMeta)
1181
- })) {
1182
- }
1183
- class ElicitationString extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitationString")({
1184
- type: /* @__PURE__ */ tag2("string"),
1185
- title: /* @__PURE__ */ optional2(String3),
1186
- description: /* @__PURE__ */ optional2(String3),
1187
- minLength: /* @__PURE__ */ optional2(Int2),
1188
- maxLength: /* @__PURE__ */ optional2(Int2),
1189
- format: /* @__PURE__ */ optional2(/* @__PURE__ */ Literals(["email", "uri", "date", "date-time"])),
1190
- default: /* @__PURE__ */ optional2(String3)
1191
- })) {
1192
- }
1193
-
1194
- class ElicitationNumber extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitationNumber")({
1195
- type: /* @__PURE__ */ Literals(["number", "integer"]),
1196
- title: /* @__PURE__ */ optional2(String3),
1197
- description: /* @__PURE__ */ optional2(String3),
1198
- minimum: /* @__PURE__ */ optional2(Finite),
1199
- maximum: /* @__PURE__ */ optional2(Finite),
1200
- default: /* @__PURE__ */ optional2(Finite)
1201
- })) {
1202
- }
1203
-
1204
- class ElicitationBoolean extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitationBoolean")({
1205
- type: /* @__PURE__ */ tag2("boolean"),
1206
- title: /* @__PURE__ */ optional2(String3),
1207
- description: /* @__PURE__ */ optional2(String3),
1208
- default: /* @__PURE__ */ optional2(Boolean3)
1209
- })) {
1210
- }
1211
-
1212
- class UntitledSingleSelectEnum extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/UntitledSingleSelectEnum")({
1213
- type: /* @__PURE__ */ tag2("string"),
1214
- title: /* @__PURE__ */ optional2(String3),
1215
- description: /* @__PURE__ */ optional2(String3),
1216
- enum: /* @__PURE__ */ ArraySchema(String3),
1217
- default: /* @__PURE__ */ optional2(String3)
1218
- })) {
1219
- }
1220
-
1221
- class TitledSingleSelectEnum extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/TitledSingleSelectEnum")({
1222
- type: /* @__PURE__ */ tag2("string"),
1223
- title: /* @__PURE__ */ optional2(String3),
1224
- description: /* @__PURE__ */ optional2(String3),
1225
- oneOf: /* @__PURE__ */ ArraySchema(/* @__PURE__ */ Struct({
1226
- const: String3,
1227
- title: String3
1228
- })),
1229
- default: /* @__PURE__ */ optional2(String3)
1230
- })) {
1231
- }
1232
- var SingleSelectEnum = /* @__PURE__ */ Union([UntitledSingleSelectEnum, TitledSingleSelectEnum]);
1233
-
1234
- class UntitledMultiSelectEnum extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/UntitledMultiSelectEnum")({
1235
- type: /* @__PURE__ */ tag2("array"),
1236
- title: /* @__PURE__ */ optional2(String3),
1237
- description: /* @__PURE__ */ optional2(String3),
1238
- minItems: /* @__PURE__ */ optional2(Int2),
1239
- maxItems: /* @__PURE__ */ optional2(Int2),
1240
- items: /* @__PURE__ */ Struct({
1241
- type: /* @__PURE__ */ tag2("string"),
1242
- enum: /* @__PURE__ */ ArraySchema(String3)
1243
- }),
1244
- default: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3))
1245
- })) {
1246
- }
1247
-
1248
- class TitledMultiSelectEnum extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/TitledMultiSelectEnum")({
1249
- type: /* @__PURE__ */ tag2("array"),
1250
- title: /* @__PURE__ */ optional2(String3),
1251
- description: /* @__PURE__ */ optional2(String3),
1252
- minItems: /* @__PURE__ */ optional2(Int2),
1253
- maxItems: /* @__PURE__ */ optional2(Int2),
1254
- items: /* @__PURE__ */ Struct({
1255
- anyOf: /* @__PURE__ */ ArraySchema(/* @__PURE__ */ Struct({
1256
- const: String3,
1257
- title: String3
1258
- }))
1259
- }),
1260
- default: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3))
1261
- })) {
1262
- }
1263
- var MultiSelectEnum = /* @__PURE__ */ Union([UntitledMultiSelectEnum, TitledMultiSelectEnum]);
1264
-
1265
- class LegacyTitledEnum extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/LegacyTitledEnum")({
1266
- type: /* @__PURE__ */ tag2("string"),
1267
- title: /* @__PURE__ */ optional2(String3),
1268
- description: /* @__PURE__ */ optional2(String3),
1269
- enum: /* @__PURE__ */ ArraySchema(String3),
1270
- enumNames: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3)),
1271
- default: /* @__PURE__ */ optional2(String3)
1272
- })) {
1273
- }
1274
- var ElicitationEnum = /* @__PURE__ */ Union([LegacyTitledEnum, SingleSelectEnum, MultiSelectEnum]);
1275
- var PrimitiveSchemaDefinition = /* @__PURE__ */ Union([ElicitationEnum, ElicitationString, ElicitationNumber, ElicitationBoolean]);
1276
- var ElicitationForm = /* @__PURE__ */ Struct({
1277
- $schema: /* @__PURE__ */ optional2(String3),
1278
- type: /* @__PURE__ */ tag2("object"),
1279
- properties: /* @__PURE__ */ Record(String3, PrimitiveSchemaDefinition),
1280
- required: /* @__PURE__ */ optional2(/* @__PURE__ */ ArraySchema(String3))
1281
- });
1282
-
1283
- class ElicitRequestFormParams extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitRequestFormParams")({
1284
- ...RequestMeta.fields,
1285
- mode: /* @__PURE__ */ optional2(/* @__PURE__ */ Literal("form")),
1286
- message: String3,
1287
- requestedSchema: ElicitationForm
1288
- })) {
1289
- }
1290
-
1291
- class ElicitRequestURLParams extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitRequestURLParams")({
1292
- ...RequestMeta.fields,
1293
- mode: /* @__PURE__ */ Literal("url"),
1294
- message: String3,
1295
- elicitationId: String3,
1296
- url: String3
1297
- })) {
1298
- }
1299
- var ElicitRequestParams = /* @__PURE__ */ Union([ElicitRequestFormParams, ElicitRequestURLParams]);
1300
-
1301
- class ElicitAcceptResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitAcceptResult")({
1302
- ...ResultMeta.fields,
1303
- action: /* @__PURE__ */ Literal("accept"),
1304
- content: /* @__PURE__ */ optional2(/* @__PURE__ */ Record(String3, /* @__PURE__ */ Union([String3, Finite, Boolean3, /* @__PURE__ */ ArraySchema(String3)])))
1305
- })) {
1306
- }
1307
-
1308
- class ElicitDeclineResult extends (/* @__PURE__ */ Class2("@effect/ai/McpSchema/ElicitDeclineResult")({
1309
- ...ResultMeta.fields,
1310
- action: /* @__PURE__ */ Literals(["cancel", "decline"])
1311
- })) {
1312
- }
1313
- var ElicitResult = /* @__PURE__ */ Union([ElicitAcceptResult, ElicitDeclineResult]);
1314
- class Elicit extends (/* @__PURE__ */ make2("elicitation/create", {
1315
- success: ElicitResult,
1316
- error: McpError,
1317
- payload: ElicitRequestParams
1318
- })) {
1319
- }
1320
-
1321
- class ElicitationCompleteNotification extends (/* @__PURE__ */ make2("notifications/elicitation/complete", {
1322
- payload: {
1323
- elicitationId: String3
1324
- }
1325
- })) {
1326
- }
1327
-
1328
- class ElicitationDeclined extends (/* @__PURE__ */ Error2("@effect/ai/McpSchema/ElicitationDeclined")({
1329
- _tag: /* @__PURE__ */ tag2("ElicitationDeclined"),
1330
- request: Elicit.payloadSchema,
1331
- cause: /* @__PURE__ */ optional2(/* @__PURE__ */ Defect())
1332
- })) {
1333
- }
1334
-
1335
- class McpReverseOperationUnsupported extends (/* @__PURE__ */ TaggedError("McpReverseOperationUnsupported")) {
1336
- }
1337
-
1338
- class McpReverseOperationError extends (/* @__PURE__ */ TaggedError("McpReverseOperationError")) {
1339
- }
1340
-
1341
- class McpRequestContext extends (/* @__PURE__ */ Service2()("effect/ai/McpSchema/McpRequestContext")) {
1342
- }
1343
-
1344
- class McpServerClient extends (/* @__PURE__ */ Service2()("effect/ai/McpSchema/McpServerClient")) {
1345
- }
1346
-
1347
- class McpServerClientMiddleware extends (/* @__PURE__ */ Service()("effect/ai/McpSchema/McpServerClientMiddleware")) {
1348
- }
1349
- class ServerNotificationRpcs extends (/* @__PURE__ */ make3(CancelledNotification, ProgressNotification, LoggingMessageNotification, ResourceUpdatedNotification, ResourceListChangedNotification, ToolListChangedNotification, PromptListChangedNotification, ElicitationCompleteNotification)) {
1350
- }
1351
- class EnabledWhen extends (/* @__PURE__ */ Service2()("effect/ai/McpSchema/EnabledWhen")) {
1352
- }
1353
- // src/relay/user-settings.ts
1354
- var settingKeys = ["window", "grouping", "idleMinutes", "cursor", "humanInput", "handoffNotifications", "autoUpdate"];
1355
- var relaySettingKeys = ["autoUpdate"];
1356
- var settingSpecs = {
1357
- window: { label: "Where agents open their tabs (current: the user's window; separate: an unfocused window of their own)", values: ["current", "separate"], variable: "OPENCODE_BROWSER_AGENT_WINDOW" },
1358
- grouping: { label: "How agent tabs are grouped (one shared group, one group per session, or none)", values: ["shared", "session", "none"] },
1359
- idleMinutes: { label: "Close agent tabs untouched for this many minutes", values: [10, 30, 60, "never"] },
1360
- cursor: { label: "Agent cursor on agent tabs outside recordings (pages can detect it)", values: ["off", "always"], variable: "OPENCODE_BROWSER_GHOST_CURSOR" },
1361
- humanInput: { label: "Human-like input (off is faster, but easier for sites to flag)", values: ["on", "off"], variable: "OPENCODE_BROWSER_HUMAN_INPUT" },
1362
- handoffNotifications: { label: "System notification on a handoff (only while recorded, or every handoff)", values: ["recording", "always"] },
1363
- autoUpdate: { label: "installs: install updates automatically when idle, only notify, or never check", values: ["on", "notify", "off"], variable: "OPENCODE_BROWSER_AUTO_UPDATE" }
1364
- };
1365
- var securityVariables = [
1366
- "OPENCODE_BROWSER_ALLOW_NODE",
1367
- "OPENCODE_BROWSER_ALLOW_ALL_COOKIES",
1368
- "OPENCODE_BROWSER_ALLOW_FOREGROUND",
1369
- "OPENCODE_BROWSER_ALLOW_ALL_STORAGE",
1370
- "OPENCODE_BROWSER_ALLOW_FILE_URLS",
1371
- "OPENCODE_BROWSER_UPDATE_CHECK"
1372
- ];
1373
-
1374
- class SettingsInputError extends Error {
1375
- }
1376
- var allowed = (key) => settingSpecs[key].values.map(String).join(", ");
1377
- function parseSettingChanges(input) {
1378
- if (input === null || typeof input !== "object" || Array.isArray(input))
1379
- throw new SettingsInputError('Pass the settings to change as an object, for example { grouping: "shared" }.');
1380
- const problems = [];
1381
- const changes = {};
1382
- for (const [key, raw] of Object.entries(input)) {
1383
- if (!settingKeys.includes(key)) {
1384
- problems.push(/allow|update|security|node|cookie|foreground|storage|file/i.test(key) ? `"${key}" is not a setting: security switches (${securityVariables.join(", ")}) are set only in the relay's environment, never here.` : `Unknown setting "${key}". Settings: ${settingKeys.join(", ")}.`);
1385
- continue;
1386
- }
1387
- const setting = key;
1388
- const value = setting === "idleMinutes" ? idleValue(raw) : raw;
1389
- if (value === undefined || !settingSpecs[setting].values.includes(value)) {
1390
- problems.push(`${setting} must be one of ${allowed(setting)} (got ${JSON.stringify(raw)}).`);
1391
- continue;
1392
- }
1393
- changes[setting] = value;
1394
- }
1395
- if (problems.length)
1396
- throw new SettingsInputError(problems.join(" "));
1397
- if (!Object.keys(changes).length)
1398
- throw new SettingsInputError(`Nothing to change. Settings: ${settingKeys.join(", ")}.`);
1399
- return changes;
1400
- }
1401
- function idleValue(raw) {
1402
- if (raw === "never" || raw === 0 || raw === "0")
1403
- return "never";
1404
- if (typeof raw === "number")
1405
- return raw;
1406
- if (typeof raw === "string" && /^\d+$/.test(raw))
1407
- return Number(raw);
1408
- return;
1409
- }
1410
- function settingsFromExtension(wire) {
1411
- const values = wire && typeof wire.settings === "object" && wire.settings !== null && !Array.isArray(wire.settings) ? wire.settings : undefined;
1412
- if (!values)
1413
- throw new Error("The extension answered settings without them");
1414
- const settings = {};
1415
- for (const key of settingKeys) {
1416
- const value = values[key];
1417
- if (relaySettingKeys.includes(key))
1418
- settings[key] = String(settingSpecs[key].values[0]);
1419
- else if (key === "idleMinutes")
1420
- settings[key] = value === 0 ? "never" : typeof value === "number" ? value : 10;
1421
- else
1422
- settings[key] = typeof value === "string" ? value : String(settingSpecs[key].values[0]);
1423
- }
1424
- return settings;
1425
- }
1426
- function settingsToExtension(changes) {
1427
- return Object.fromEntries(Object.entries(changes).filter(([key]) => !relaySettingKeys.includes(key)).map(([key, value]) => [key, key === "idleMinutes" && value === "never" ? 0 : value]));
1428
- }
1429
- function report(stored, overrides) {
1430
- return Object.fromEntries(settingKeys.map((key) => {
1431
- const override = overrides[key];
1432
- return [key, {
1433
- value: stored[key],
1434
- effective: override?.value ?? stored[key],
1435
- allowed: settingSpecs[key].values,
1436
- description: settingSpecs[key].label,
1437
- ...override ? { overriddenBy: override.variable } : {}
1438
- }];
1439
- }));
1440
- }
1441
- var securityNote = `Security switches (${securityVariables.join(", ")}) are environment-only and can't be read or changed here.`;
1442
- function describeSettings(stored, overrides) {
1443
- return { settings: report(stored, overrides), note: securityNote };
1444
- }
1445
- function describeChanges(options) {
1446
- const changed = [];
1447
- const unchanged = [];
1448
- const overridden = [];
1449
- for (const [key, value] of Object.entries(options.requested)) {
1450
- const override = options.overrides[key];
1451
- if (override)
1452
- overridden.push({ key, requested: value, variable: override.variable, effective: override.value });
1453
- else if (options.before[key] === options.after[key])
1454
- unchanged.push(key);
1455
- else
1456
- changed.push({ key, from: options.before[key], to: options.after[key] });
1457
- }
1458
- const lines = [];
1459
- if (changed.length)
1460
- lines.push(`Changed ${changed.map((item) => `${item.key} from ${item.from} to ${item.to}`).join(", ")}. Tell the user what you changed; they can change it back on the extension's options page.`);
1461
- if (unchanged.length)
1462
- lines.push(`Already set: ${unchanged.map((key) => `${key} is ${options.after[key]}`).join(", ")}.`);
1463
- for (const item of overridden)
1464
- lines.push(`Not changed: ${item.key} is fixed to ${item.effective} by ${item.variable} in the relay's environment, so this setting has no effect. Tell the user; to change it they remove or edit ${item.variable} where opencode starts, then run \`${cliCommand("relay restart")}\`.`);
1465
- return { changed, unchanged, overridden, settings: report(options.after, options.overrides), message: lines.join(" ") };
1466
- }
1467
- function formatSettings(settings) {
1468
- const width = Math.max(...settingKeys.map((key) => key.length));
1469
- return settingKeys.map((key) => {
1470
- const item = settings[key];
1471
- const override = item.overriddenBy ? ` (in effect: ${item.effective}, set by ${item.overriddenBy} on the relay)` : "";
1472
- return `${key.padEnd(width)} ${String(item.value).padEnd(9)} one of ${item.allowed.join(", ")}${override}`;
1473
- });
1474
- }
1475
-
1476
- // src/mcp/schema.ts
1477
- function mcpUpdateNote2(notice) {
1478
- return `Note: browse has an update: ${notice.summary}. Tell the user they can run \`${notice.command}\` and then restart opencode, or ask you to run it for them.`;
1479
- }
1480
- function objectSchema(properties, required = []) {
1481
- return {
1482
- type: "object",
1483
- properties,
1484
- required: [...required],
1485
- additionalProperties: false
1486
- };
1487
- }
1488
- var emptyInputSchema = objectSchema({});
1489
- var sessionSchemaProperty = {
1490
- type: "string",
1491
- description: "Optional session id. Defaults to this MCP server's current session."
1492
- };
1493
- var sessionAliasSchemaProperty = { type: "string", description: "Same as id." };
1494
- var sessionOnlyInputSchema = objectSchema({
1495
- session: sessionSchemaProperty
1496
- });
1497
- var ExecuteToolOutput = Struct({
1498
- session: String3,
1499
- value: optionalKey(Unknown),
1500
- logs: optionalKey(ArraySchema(ExecuteLogEntry)),
1501
- logSummary: optionalKey(ExecuteLogSummary),
1502
- warnings: optionalKey(ArraySchema(String3)),
1503
- diagnostic: optionalKey(String3),
1504
- aftermath: optionalKey(ExecuteAftermath),
1505
- notice: optionalKey(String3)
1506
- });
1507
- var StatusToolOutput = Struct({
1508
- endpoint: String3,
1509
- currentSession: String3,
1510
- version: RelayVersion,
1511
- status: ExtensionStatus,
1512
- buildProblem: optionalKey(String3),
1513
- update: optionalKey(Json),
1514
- autoUpdate: Json
1515
- });
1516
- var CurrentSessionToolOutput = Struct({
1517
- currentSession: String3
1518
- });
1519
- var SessionDeleteToolOutput = SessionDeleted.pipe(fieldsAssign({
1520
- currentSession: String3
1521
- }));
1522
- var NetworkToolOutput = Struct({
1523
- action: Literals(["start", "status", "stop", "cancel"]),
1524
- session: String3,
1525
- active: optionalKey(Boolean3),
1526
- startedAt: optionalKey(String3),
1527
- entryCount: optionalKey(Number2),
1528
- responseCount: optionalKey(Number2),
1529
- failureCount: optionalKey(Number2),
1530
- capturedBodyBytes: optionalKey(Number2),
1531
- truncatedBodyCount: optionalKey(Number2),
1532
- droppedEntryCount: optionalKey(Number2),
1533
- urlFilter: optionalKey(String3),
1534
- resourceTypes: optionalKey(ArraySchema(String3)),
1535
- content: optionalKey(Literals(["omit", "embed"])),
1536
- secrets: optionalKey(String3),
1537
- endsAt: optionalKey(String3),
1538
- ended: optionalKey(String3),
1539
- stoppedAt: optionalKey(String3),
1540
- outputPath: optionalKey(String3),
1541
- authProfile: optionalKey(AuthProfileSummary),
1542
- updatedSecretRefs: optionalKey(ArraySchema(String3)),
1543
- observedSecretRefs: optionalKey(ArraySchema(String3)),
1544
- endpoints: optionalKey(ArraySchema(Struct({
1545
- method: String3,
1546
- url: String3,
1547
- status: optionalKey(Number2),
1548
- count: Number2,
1549
- requestHeaders: optionalKey(ArraySchema(String3)),
1550
- requestKeys: optionalKey(ArraySchema(String3)),
1551
- responseKeys: optionalKey(ArraySchema(String3))
1552
- }))),
1553
- cancelled: optionalKey(Boolean3)
1554
- });
1555
- var RecordingToolOutput = Struct({
1556
- action: Literals(["start", "stop", "status", "cancel"]),
1557
- session: String3,
1558
- success: optionalKey(Boolean3),
1559
- tabId: optionalKey(Number2),
1560
- startedAt: optionalKey(Number2),
1561
- path: optionalKey(String3),
1562
- mimeType: optionalKey(String3),
1563
- mode: optionalKey(Literals(["tab-capture", "cdp"])),
1564
- artifactType: optionalKey(Literals(["webm", "mp4"])),
1565
- frameRate: optionalKey(Number2),
1566
- duration: optionalKey(Number2),
1567
- size: optionalKey(Number2),
1568
- frameCount: optionalKey(Number2),
1569
- quality: optionalKey(RecordingQuality),
1570
- isRecording: optionalKey(Boolean3),
1571
- error: optionalKey(String3)
1572
- });
1573
- var FlightRecorderToolOutput = Struct({
1574
- action: Literals(["start", "status", "save_last", "cancel"]),
1575
- session: String3,
1576
- active: optionalKey(Boolean3),
1577
- tabId: optionalKey(Number2),
1578
- sessionId: optionalKey(String3),
1579
- startedAt: optionalKey(Number2),
1580
- retentionMs: optionalKey(Number2),
1581
- retainedDurationMs: optionalKey(Number2),
1582
- frameRate: optionalKey(Number2),
1583
- bufferedFrames: optionalKey(Number2),
1584
- bufferedBytes: optionalKey(Number2),
1585
- sourceFrameCount: optionalKey(Number2),
1586
- droppedFrameCount: optionalKey(Number2),
1587
- saving: optionalKey(Boolean3),
1588
- path: optionalKey(String3),
1589
- durationMs: optionalKey(Number2),
1590
- frameCount: optionalKey(Number2),
1591
- cancelled: optionalKey(Boolean3)
1592
- });
1593
- var agentSettingKeys = settingKeys.filter((key) => key !== "autoUpdate");
1594
- var AgentSettingValue = Union([String3, Number2]);
1595
- var AgentSettingReport = Struct({
1596
- value: AgentSettingValue,
1597
- effective: AgentSettingValue,
1598
- allowed: ArraySchema(AgentSettingValue),
1599
- description: String3,
1600
- overriddenBy: optionalKey(String3)
1601
- });
1602
- var AgentSettings = Record(Literals(agentSettingKeys), AgentSettingReport);
1603
- var SettingsToolOutput = Struct({
1604
- settings: AgentSettings,
1605
- note: optionalKey(SettingsGetResponse.fields.note),
1606
- changed: optionalKey(SettingsSetResponse.fields.changed),
1607
- unchanged: optionalKey(SettingsSetResponse.fields.unchanged),
1608
- overridden: optionalKey(SettingsSetResponse.fields.overridden),
1609
- message: optionalKey(SettingsSetResponse.fields.message)
1610
- });
1611
- var SecretsListToolOutput = Struct({
1612
- secrets: ArraySchema(Struct({
1613
- name: String3,
1614
- kind: Literals(["password", "totp"]),
1615
- allowedOrigins: ArraySchema(String3),
1616
- createdAt: String3,
1617
- updatedAt: String3
1618
- }))
1619
- });
1620
- function toolOutputJson(schema) {
1621
- const document = toJsonSchemaDocument(schema);
1622
- const json = Object.keys(document.definitions).length === 0 ? document.schema : { ...document.schema, $defs: document.definitions };
1623
- return json;
1624
- }
1625
- function logSummaryHasContent(summary) {
1626
- return summary !== undefined && (summary.totalCount > 0 || summary.returnedCount > 0 || summary.repeatedCount > 0 || summary.omittedCount > 0);
1627
- }
1628
- function aftermathHasContent(aftermath) {
1629
- return aftermath !== undefined && (aftermath.startUrl !== aftermath.endUrl || aftermath.navigations.length > 0 || aftermath.consoleErrorCount > 0 || aftermath.pageErrorCount > 0 || aftermath.handoffs > 0 || aftermath.challenge !== undefined);
1630
- }
1631
- function executeToolOutput(result) {
1632
- return {
1633
- session: result.session.id,
1634
- ...result.value === undefined ? {} : { value: result.value },
1635
- ...result.logs.length > 0 ? { logs: result.logs } : {},
1636
- ...logSummaryHasContent(result.logSummary) ? { logSummary: result.logSummary } : {},
1637
- ...result.warnings && result.warnings.length > 0 ? { warnings: result.warnings } : {},
1638
- ...result.diagnostic ? { diagnostic: result.diagnostic } : {},
1639
- ...aftermathHasContent(result.aftermath) ? { aftermath: result.aftermath } : {},
1640
- ...result.notice ? { notice: result.notice } : {}
1641
- };
1642
- }
1643
- function executeToolText(result) {
1644
- const text = result.isError ? result.text : isString(result.value) ? result.value : result.value === undefined ? result.text : JSON.stringify(result.value);
1645
- return result.notice ? `${text}
1646
-
1647
- ${result.notice}` : text;
1648
- }
1649
- function executeToolResult(value) {
1650
- const result = value;
1651
- if (result.media && result.media.length > 0) {
1652
- return new CallToolResult({
1653
- content: [
1654
- TextContent.make({ text: result.text }),
1655
- ...result.media.map((image) => ImageContent.make({
1656
- data: new Uint8Array(Buffer.from(image.data, "base64")),
1657
- mimeType: image.mimeType
1658
- }))
1659
- ],
1660
- isError: result.isError
1661
- });
1662
- }
1663
- return toolResultForValue2(executeToolOutput(result), {
1664
- outputSchema: ExecuteToolOutput,
1665
- text: executeToolText(result),
1666
- isError: result.isError
1667
- });
1668
- }
1669
- var ensureSessionExists = fnUntraced(function* (relay, id) {
1670
- const sessions = yield* relay.sessions;
1671
- const exists = sessions.some((session) => {
1672
- return session.id === id;
1673
- });
1674
- if (!exists) {
1675
- return yield* fail5(new Error(`Session not found: ${id}`));
1676
- }
1677
- });
1678
- function parseExecuteArguments(input) {
1679
- const object = requireObject(input);
1680
- const code = requiredStringField(object, "code");
1681
- const session = optionalStringField(object, "session");
1682
- const timeoutMs = optionalNonNegativeIntegerField(object, "timeoutMs");
1683
- const targetSelection = parseMcpTargetSelection(object);
1684
- const browser = optionalStringField(object, "browser");
1685
- return {
1686
- code,
1687
- ...session ? { session } : {},
1688
- ...timeoutMs === undefined ? {} : { timeoutMs },
1689
- ...targetSelection ? { targetSelection } : {},
1690
- ...browser ? { browser } : {}
1691
- };
1692
- }
1693
- function parseAdoptArguments(input) {
1694
- const object = requireObject(input);
1695
- const session = optionalStringField(object, "session");
1696
- const targetSelection = parseMcpTargetSelection(object);
1697
- const tabId = typeof object.tabId === "number" && Number.isInteger(object.tabId) ? object.tabId : undefined;
1698
- if (tabId !== undefined && targetSelection)
1699
- throw new Error("Use only one of tabId, targetUrl, or targetIndex");
1700
- return {
1701
- ...session ? { session } : {},
1702
- ...targetSelection ? { targetSelection } : {},
1703
- ...tabId === undefined ? {} : { tabId }
1704
- };
1705
- }
1706
- function parseMcpTargetSelection(input) {
1707
- const urlIncludes = optionalStringField(input, "targetUrl");
1708
- const selection = parseTargetSelection2({
1709
- ...urlIncludes ? { urlIncludes } : {},
1710
- ...input.targetIndex === undefined ? {} : { index: input.targetIndex }
1711
- });
1712
- return selection?.urlIncludes || selection?.index !== undefined ? selection : undefined;
1713
- }
1714
- function requiredStringField(input, field) {
1715
- const value = optionalStringField(input, field);
1716
- if (!value) {
1717
- throw new Error(`${field} is required`);
1718
- }
1719
- return value;
1720
- }
1721
- function requiredAction(input, actions) {
1722
- const action = optionalStringField(input, "action");
1723
- if (!action || !actions.includes(action)) {
1724
- throw new Error(`action must be one of ${actions.join(", ")}`);
1725
- }
1726
- return action;
1727
- }
1728
- function optionalStringField(input, field) {
1729
- const value = getString2(requireObject(input), field);
1730
- return value ? value : undefined;
1731
- }
1732
- function optionalBooleanField(input, field) {
1733
- const value = requireObject(input)[field];
1734
- return isBoolean(value) ? value : undefined;
1735
- }
1736
- function optionalPositiveIntegerField(input, field) {
1737
- const value = requireObject(input)[field];
1738
- if (value === undefined)
1739
- return;
1740
- if (!isNumber(value) || !Number.isInteger(value) || value <= 0) {
1741
- throw new Error(`${field} must be a positive integer`);
1742
- }
1743
- return value;
1744
- }
1745
- function optionalNonNegativeIntegerField(input, field) {
1746
- const value = requireObject(input)[field];
1747
- if (value === undefined)
1748
- return;
1749
- if (!isNumber(value) || !Number.isInteger(value) || value < 0) {
1750
- throw new Error(`${field} must be a non-negative integer`);
1751
- }
1752
- return value;
1753
- }
1754
- function optionalStringArrayField(input, field) {
1755
- const value = requireObject(input)[field];
1756
- if (value === undefined)
1757
- return;
1758
- if (!Array.isArray(value) || !value.every((item) => isString(item) && item.length > 0)) {
1759
- throw new Error(`${field} must be an array of non-empty strings`);
1760
- }
1761
- return value;
1762
- }
1763
- function requireObject(input) {
1764
- const object = getObject2(input);
1765
- if (!object) {
1766
- throw new Error("Expected arguments object");
1767
- }
1768
- return object;
1769
- }
1770
- function stringifyResult(value) {
1771
- if (isString(value)) {
1772
- return value;
1773
- }
1774
- return JSON.stringify(value);
1775
- }
1776
- function encodedStructuredContent(value, schema) {
1777
- if (!schema)
1778
- return value;
1779
- const encoded = encodeUnknownOption(schema)(value);
1780
- return isSome(encoded) ? encoded.value : undefined;
1781
- }
1782
- function toolResultForValue2(value, options = {}) {
1783
- const object = getObject2(value);
1784
- const isError = options.isError ?? object?.isError === true;
1785
- const media = Array.isArray(object?.media) ? object.media.flatMap((item) => {
1786
- const image = getObject2(item);
1787
- const mimeType = getString2(image, "mimeType");
1788
- const data = getString2(image, "data");
1789
- return image?.type === "image" && mimeType !== undefined && data !== undefined ? [{ data, mimeType }] : [];
1790
- }) : [];
1791
- const errorText = isError ? getString2(object, "text") : undefined;
1792
- if (media.length > 0) {
1793
- const { media: _media, ...rest } = object ?? {};
1794
- const text = options.text ?? errorText ?? stringifyResult(rest);
1795
- return new CallToolResult({
1796
- content: [
1797
- TextContent.make({ text }),
1798
- ...media.map((image) => ImageContent.make({
1799
- data: new Uint8Array(Buffer.from(image.data, "base64")),
1800
- mimeType: image.mimeType
1801
- }))
1802
- ],
1803
- isError
1804
- });
1805
- }
1806
- const text = options.text ?? errorText ?? stringifyResult(value);
1807
- const structuredContent = object ? encodedStructuredContent(object, options.outputSchema) : undefined;
1808
- return toolResult({
1809
- text,
1810
- ...structuredContent === undefined ? {} : { structuredContent },
1811
- isError
1812
- });
1813
- }
1814
- function mcpErrorMessage2(tool, message) {
1815
- if (!message.startsWith("Session not found:")) {
1816
- return message;
1817
- }
1818
- return tool === "execute" || tool === "session_adopt" ? `${message} Create it with session_new first, or omit the explicit session id to use the MCP current session.` : `${message} Create it with session_new first.`;
1819
- }
1820
- function toolResult(options) {
1821
- return new CallToolResult({
1822
- content: [TextContent.make({ text: options.text })],
1823
- structuredContent: options.structuredContent,
1824
- isError: options.isError
1825
- });
1826
- }
1827
-
1828
- // src/auth/site-secrets.ts
1829
- import crypto from "node:crypto";
1830
- import fs2 from "node:fs/promises";
1831
- import path2 from "node:path";
1832
-
1833
- // src/auth/profile.ts
1834
- import { spawn } from "node:child_process";
1835
- import fs from "node:fs/promises";
1836
- import path from "node:path";
1837
-
1838
- // src/update/child-process.ts
1839
- async function terminateChildProcess(options) {
1840
- const isExited = options.isExited ?? (() => options.child.exitCode !== null || options.child.signalCode !== null);
1841
- if (isExited())
1842
- return;
1843
- signalChildProcess(options.child, "SIGTERM");
1844
- let timeout;
1845
- await Promise.race([
1846
- options.exit,
1847
- new Promise((resolve) => {
1848
- timeout = setTimeout(resolve, options.graceMs);
1849
- })
1850
- ]);
1851
- if (timeout)
1852
- clearTimeout(timeout);
1853
- if (isExited())
1854
- return;
1855
- signalChildProcess(options.child, "SIGKILL");
1856
- await options.exit;
1857
- }
1858
- function signalChildProcess(child, signal) {
1859
- if (process.platform !== "win32" && child.pid !== undefined) {
1860
- try {
1861
- process.kill(-child.pid, signal);
1862
- return;
1863
- } catch {}
1864
- }
1865
- child.kill(signal);
1866
- }
1867
-
1868
- // src/network-capture/redaction.ts
1869
- var secretNamePattern = /auth(?:orization)?|cookie|credential|csrf|xsrf|token|secret|session|password|passwd|pwd|passcode|otp|(?:^|[-_.])code(?:$|[-_.])|(?:api|access|refresh)[-_.]?key|signature|(?:^|[-_.])sig(?:$|[-_.])/i;
1870
- var oneTimeFieldPattern = /pass(?:word|wd|code|phrase)|(?:^|[-_.])pwd(?:$|[-_.])|otp|totp|(?:^|[-_.])(?:mfa_?|2fa_?|verification_?|auth_?)?code(?:$|[-_.])|(?:^|[-_.])pin(?:$|[-_.])/i;
1871
- var referencePattern = String.raw`BC_(?:SECRET|REDACTED)_\d+`;
1872
- var secretHeaders = new Set([
1873
- "authorization",
1874
- "proxy-authorization",
1875
- "x-api-key",
1876
- "api-key",
1877
- "x-csrf-token",
1878
- "csrf-token",
1879
- "x-xsrf-token"
1880
- ]);
1881
-
1882
- class SecretCollector {
1883
- slotsByRef = new Map;
1884
- refsByValue = new Map;
1885
- refsBySource = new Map;
1886
- retiredRefsByValue = new Map;
1887
- redactedRefsByValue = new Map;
1888
- nextRedactedRef = 1;
1889
- nextRef = 1;
1890
- updated = new Set;
1891
- observed = new Set;
1892
- constructor(existing = []) {
1893
- for (const slot of existing) {
1894
- const copy = {
1895
- ref: slot.ref,
1896
- value: slot.value,
1897
- sources: [...slot.sources],
1898
- ...slot.expiresAt ? { expiresAt: slot.expiresAt } : {}
1899
- };
1900
- this.slotsByRef.set(copy.ref, copy);
1901
- this.refsByValue.set(copy.value, copy.ref);
1902
- for (const source of copy.sources) {
1903
- this.refsBySource.set(source, copy.ref);
1904
- }
1905
- const number = /^BC_SECRET_(\d+)$/.exec(copy.ref)?.[1];
1906
- if (number)
1907
- this.nextRef = Math.max(this.nextRef, Number(number) + 1);
1908
- }
1909
- }
1910
- protectHeaders(headers, location, requestScope = "") {
1911
- const occurrences = new Map;
1912
- return headers.map(({ name, value }) => {
1913
- const lowerName = name.toLowerCase();
1914
- const occurrence = occurrences.get(lowerName) ?? 0;
1915
- occurrences.set(lowerName, occurrence + 1);
1916
- return {
1917
- name,
1918
- value: this.protectHeader(name, value, sourceName(requestScope, `${location}.header.${lowerName}`, occurrence))
1919
- };
1920
- });
1921
- }
1922
- protectUrl(rawUrl, requestScope = "") {
1923
- const fragmentStart = rawUrl.indexOf("#");
1924
- const base = fragmentStart < 0 ? rawUrl : rawUrl.slice(0, fragmentStart);
1925
- const protectQuery = (name, value, occurrence) => this.reference(value, sourceName(requestScope, `query.${name}`, occurrence));
1926
- const protectPath = (pathname) => protectPathSegments(pathname, (segment) => this.redactionReference(segment));
1927
- let protectedUrl;
1928
- try {
1929
- const url = new URL(base);
1930
- url.pathname = protectPath(url.pathname);
1931
- url.search = protectSearchParams(url.searchParams, protectQuery).toString();
1932
- protectedUrl = restoreReferencePlaceholders(url.toString());
1933
- } catch {
1934
- protectedUrl = protectRelativeUrl(base, protectQuery, protectPath);
1935
- }
1936
- if (fragmentStart < 0)
1937
- return protectedUrl;
1938
- const fragment = protectFragment(rawUrl.slice(fragmentStart + 1), (name, value, occurrence) => this.reference(value, sourceName(requestScope, `fragment.${name}`, occurrence)));
1939
- return `${protectedUrl}#${fragment}`;
1940
- }
1941
- protectBody(body, contentType, location, requestScope = "") {
1942
- const type = contentType?.toLowerCase() ?? "";
1943
- if (type.includes("json")) {
1944
- try {
1945
- return JSON.stringify(this.protectJson(JSON.parse(body), sourceName(requestScope, location)));
1946
- } catch {
1947
- return;
1948
- }
1949
- }
1950
- if (type.includes("application/x-www-form-urlencoded")) {
1951
- const protectedParams = protectSearchParams(new URLSearchParams(body), (name, value, occurrence) => this.reference(value, sourceName(requestScope, `${location}.form.${name}`, occurrence)));
1952
- return restoreReferencePlaceholders(protectedParams.toString());
1953
- }
1954
- if (type.includes("multipart/form-data")) {
1955
- return this.protectMultipart(body, contentType ?? "", location, requestScope);
1956
- }
1957
- return;
1958
- }
1959
- slots() {
1960
- return Array.from(this.slotsByRef.values()).sort((left, right) => left.ref.localeCompare(right.ref, undefined, { numeric: true })).map((slot) => ({ ...slot, sources: [...slot.sources] }));
1961
- }
1962
- updatedRefs() {
1963
- return Array.from(this.updated).sort();
1964
- }
1965
- observedRefs() {
1966
- return Array.from(this.observed).sort();
1967
- }
1968
- redactText(text) {
1969
- return redactKnownValues(text, this.redactionSlots());
1970
- }
1971
- redactValue(value) {
1972
- return redactKnownValue(value, this.redactionSlots());
1973
- }
1974
- redactExactValue(value, minimumLength) {
1975
- if (!isString(value) && !isNumber(value) && !isBoolean(value))
1976
- return value;
1977
- const serialized = String(value);
1978
- if (serialized.length < minimumLength)
1979
- return value;
1980
- const ref = this.refsByValue.get(serialized) ?? this.retiredRefsByValue.get(serialized) ?? this.redactedRefsByValue.get(serialized);
1981
- return ref ? `\${${ref}}` : value;
1982
- }
1983
- redactKnownSubstrings(text, minimumLength) {
1984
- const slots = this.redactionSlots().filter((slot) => slot.value.length >= minimumLength);
1985
- const encoded = slots.flatMap((slot) => {
1986
- const variant = encodeURIComponent(slot.value);
1987
- return variant === slot.value ? [] : [{ ref: slot.ref, value: variant }];
1988
- });
1989
- return redactKnownValues(text, [...slots, ...encoded]);
1990
- }
1991
- redactionSlots() {
1992
- return [
1993
- ...this.slotsByRef.values(),
1994
- ...Array.from(this.retiredRefsByValue, ([value, ref]) => ({ ref, value })),
1995
- ...Array.from(this.redactedRefsByValue, ([value, ref]) => ({ ref, value }))
1996
- ];
1997
- }
1998
- addRedactionOnly(value) {
1999
- if (value)
2000
- this.redactionReference(value);
2001
- }
2002
- redactValuesEverywhere(text, values) {
2003
- const slots = [];
2004
- for (const value of values) {
2005
- if (!value)
2006
- continue;
2007
- const ref = /^\$\{(.+)\}$/.exec(this.redactionReference(value))?.[1] ?? "BC_REDACTED_0";
2008
- for (const variant of new Set([value, encodeURIComponent(value), new URLSearchParams({ v: value }).toString().slice(2)])) {
2009
- slots.push({ ref, value: variant });
2010
- }
2011
- }
2012
- return redactKnownValues(text, slots);
2013
- }
2014
- redactionReference(value) {
2015
- const persisted = this.refsByValue.get(value);
2016
- if (persisted) {
2017
- this.observed.add(persisted);
2018
- return `\${${persisted}}`;
2019
- }
2020
- let ref = this.redactedRefsByValue.get(value);
2021
- if (!ref) {
2022
- ref = `BC_REDACTED_${this.nextRedactedRef++}`;
2023
- this.redactedRefsByValue.set(value, ref);
2024
- }
2025
- return `\${${ref}}`;
2026
- }
2027
- protectHeader(name, value, source) {
2028
- if (!value)
2029
- return value;
2030
- const lower = name.toLowerCase();
2031
- if (lower === "cookie" || lower === "set-cookie") {
2032
- const cookieOccurrences = new Map;
2033
- return value.split(/;\s*/).map((part, index) => {
2034
- const separator = part.indexOf("=");
2035
- if (separator < 1)
2036
- return part;
2037
- const cookieName = part.slice(0, separator).trim();
2038
- const cookieValue = part.slice(separator + 1);
2039
- if (lower === "set-cookie" && index > 0 && /^(domain|path|expires|max-age|samesite)$/i.test(cookieName)) {
2040
- return part;
2041
- }
2042
- if (!cookieValue)
2043
- return part;
2044
- const occurrence = cookieOccurrences.get(cookieName) ?? 0;
2045
- cookieOccurrences.set(cookieName, occurrence + 1);
2046
- return `${cookieName}=${this.reference(cookieValue, sourceName("", `${source}.${cookieName}`, occurrence))}`;
2047
- }).join("; ");
2048
- }
2049
- if (lower === "location" || lower === "referer" || lower === "referrer") {
2050
- return this.protectUrl(value, `${source}.url`);
2051
- }
2052
- if (lower === "authorization" || lower === "proxy-authorization") {
2053
- const match = /^(\S+)\s+(.+)$/.exec(value);
2054
- if (match)
2055
- return `${match[1]} ${this.reference(match[2] ?? "", source)}`;
2056
- }
2057
- if (secretHeaders.has(lower) || secretNamePattern.test(lower)) {
2058
- return this.reference(value, source);
2059
- }
2060
- return value;
2061
- }
2062
- protectJson(value, location, path = [], inSecret = false) {
2063
- if (Array.isArray(value)) {
2064
- return value.map((item, index) => this.protectJson(item, location, [...path, String(index)], inSecret));
2065
- }
2066
- if (isObject(value)) {
2067
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
2068
- key,
2069
- this.protectJson(item, location, [...path, key], inSecret || secretNamePattern.test(key))
2070
- ]));
2071
- }
2072
- if (!inSecret || value === null || value === "")
2073
- return value;
2074
- return this.reference(String(value), `${location}.json.${path.join(".")}`);
2075
- }
2076
- protectMultipart(body, contentType, location, requestScope) {
2077
- const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType)?.slice(1).find(Boolean);
2078
- if (!boundary)
2079
- return;
2080
- const delimiter = `--${boundary}`;
2081
- const parts = body.split(delimiter);
2082
- if (parts.length < 3)
2083
- return;
2084
- const occurrences = new Map;
2085
- for (let index = 1;index < parts.length - 1; index += 1) {
2086
- const part = parts[index];
2087
- if (!part?.startsWith(`\r
2088
- `))
2089
- return;
2090
- const headerEnd = part.indexOf(`\r
2091
- \r
2092
- `);
2093
- if (headerEnd < 0 || !part.endsWith(`\r
2094
- `))
2095
- return;
2096
- const headers = part.slice(2, headerEnd);
2097
- const disposition = headers.split(`\r
2098
- `).find((line) => /^content-disposition:/i.test(line));
2099
- if (!disposition || /;\s*filename\*?=/i.test(disposition))
2100
- return;
2101
- const name = /;\s*name="([^"]+)"/i.exec(disposition)?.[1];
2102
- if (!name)
2103
- return;
2104
- const valueStart = headerEnd + 4;
2105
- const valueEnd = part.length - 2;
2106
- const value = part.slice(valueStart, valueEnd);
2107
- if (!value || !secretNamePattern.test(name))
2108
- continue;
2109
- const occurrence = occurrences.get(name) ?? 0;
2110
- occurrences.set(name, occurrence + 1);
2111
- const reference = this.reference(value, sourceName(requestScope, `${location}.multipart.${name}`, occurrence));
2112
- parts[index] = `${part.slice(0, valueStart)}${reference}${part.slice(valueEnd)}`;
2113
- }
2114
- return parts.join(delimiter);
2115
- }
2116
- reference(value, source) {
2117
- if (oneTimeFieldPattern.test(sourceFieldName(source)))
2118
- return this.redactionReference(value);
2119
- const sourceRef = this.refsBySource.get(source);
2120
- if (sourceRef) {
2121
- const slot = this.slotsByRef.get(sourceRef);
2122
- if (slot) {
2123
- if (slot.value === value) {
2124
- this.observed.add(sourceRef);
2125
- return `\${${sourceRef}}`;
2126
- }
2127
- if (slot.sources.length === 1) {
2128
- this.retiredRefsByValue.set(slot.value, slot.ref);
2129
- if (this.refsByValue.get(slot.value) === sourceRef)
2130
- this.refsByValue.delete(slot.value);
2131
- slot.value = value;
2132
- const expiresAt = jwtExpiration(value);
2133
- if (expiresAt)
2134
- slot.expiresAt = expiresAt;
2135
- else
2136
- delete slot.expiresAt;
2137
- this.refsByValue.set(value, sourceRef);
2138
- this.updated.add(sourceRef);
2139
- this.observed.add(sourceRef);
2140
- return `\${${sourceRef}}`;
2141
- }
2142
- const sourceIndex = slot.sources.indexOf(source);
2143
- if (sourceIndex >= 0)
2144
- slot.sources.splice(sourceIndex, 1);
2145
- const replacementRef = this.refsByValue.get(value);
2146
- if (replacementRef) {
2147
- this.refsBySource.set(source, replacementRef);
2148
- this.addSource(replacementRef, source);
2149
- this.updated.add(replacementRef);
2150
- this.observed.add(replacementRef);
2151
- return `\${${replacementRef}}`;
2152
- }
2153
- }
2154
- }
2155
- const valueRef = this.refsByValue.get(value);
2156
- if (valueRef) {
2157
- this.observed.add(valueRef);
2158
- this.addSource(valueRef, source);
2159
- return `\${${valueRef}}`;
2160
- }
2161
- const ref = `BC_SECRET_${this.nextRef++}`;
2162
- const expiresAt = jwtExpiration(value);
2163
- this.slotsByRef.set(ref, { ref, value, sources: [source], ...expiresAt ? { expiresAt } : {} });
2164
- this.refsByValue.set(value, ref);
2165
- this.refsBySource.set(source, ref);
2166
- this.updated.add(ref);
2167
- this.observed.add(ref);
2168
- return `\${${ref}}`;
2169
- }
2170
- addSource(ref, source) {
2171
- const slot = this.slotsByRef.get(ref);
2172
- if (!slot || slot.sources.includes(source))
2173
- return;
2174
- slot.sources.push(source);
2175
- this.refsBySource.set(source, ref);
2176
- }
2177
- }
2178
- function restoreReferencePlaceholders(value) {
2179
- return value.replace(/(?:%24|\$)%7B(BC_(?:SECRET|REDACTED)_\d+)%7D/gi, (_match, ref) => `\${${ref}}`);
2180
- }
2181
- function sourceFieldName(source) {
2182
- const segments = source.split(".");
2183
- for (let index = segments.length - 1;index >= 0; index -= 1) {
2184
- const segment = segments[index] ?? "";
2185
- if (!/^\d+$/.test(segment))
2186
- return segment;
2187
- }
2188
- return "";
2189
- }
2190
- var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2191
- function looksLikeTokenSegment(segment) {
2192
- if (segment.length < 24 || uuidPattern.test(segment) || segment.includes("${"))
2193
- return false;
2194
- if (/^eyJ[\w-]+\.[\w-]+\.[\w-]*$/.test(segment))
2195
- return true;
2196
- if (/^[0-9a-f]{32,}$/i.test(segment))
2197
- return true;
2198
- if (!/^[A-Za-z0-9_~+/-]+={0,2}$/.test(segment))
2199
- return false;
2200
- if (/^[a-z]+(?:[-_][a-z]+)+$/i.test(segment))
2201
- return false;
2202
- const hasDigit = /\d/.test(segment);
2203
- const hasLower = /[a-z]/.test(segment);
2204
- const hasUpper = /[A-Z]/.test(segment);
2205
- return new Set(segment).size >= 12 && hasDigit && (hasLower || hasUpper) && (hasLower && hasUpper || segment.length >= 32);
2206
- }
2207
- function protectPathSegments(pathname, protect) {
2208
- return pathname.split("/").map((segment) => {
2209
- let decoded;
2210
- try {
2211
- decoded = decodeURIComponent(segment);
2212
- } catch {
2213
- decoded = segment;
2214
- }
2215
- return looksLikeTokenSegment(decoded) ? protect(decoded) : segment;
2216
- }).join("/");
2217
- }
2218
- function protectRelativeUrl(rawUrl, protect, protectPath) {
2219
- const queryStart = rawUrl.indexOf("?");
2220
- if (queryStart < 0)
2221
- return protectPath(rawUrl);
2222
- const protectedQuery = protectSearchParams(new URLSearchParams(rawUrl.slice(queryStart + 1)), protect).toString();
2223
- return restoreReferencePlaceholders(`${protectPath(rawUrl.slice(0, queryStart))}?${protectedQuery}`);
2224
- }
2225
- function protectSearchParams(params, protect) {
2226
- const result = new URLSearchParams;
2227
- const occurrences = new Map;
2228
- for (const [name, value] of params) {
2229
- const occurrence = occurrences.get(name) ?? 0;
2230
- occurrences.set(name, occurrence + 1);
2231
- result.append(name, value && secretNamePattern.test(name) ? protect(name, value, occurrence) : value);
2232
- }
2233
- return result;
2234
- }
2235
- function protectFragment(fragment, protect) {
2236
- const occurrences = new Map;
2237
- return fragment.split("&").map((part) => {
2238
- const separator = part.indexOf("=");
2239
- if (separator < 1)
2240
- return part;
2241
- const entry = new URLSearchParams(part).entries().next().value;
2242
- if (!entry)
2243
- return part;
2244
- const [name, value] = entry;
2245
- if (!/^[\w.-]+$/.test(name) || !secretNamePattern.test(name))
2246
- return part;
2247
- const occurrence = occurrences.get(name) ?? 0;
2248
- occurrences.set(name, occurrence + 1);
2249
- return value ? `${part.slice(0, separator + 1)}${protect(name, value, occurrence)}` : part;
2250
- }).join("&");
2251
- }
2252
- function sourceName(requestScope, location, occurrence = 0) {
2253
- const base = requestScope ? `${requestScope}.${location}` : location;
2254
- return occurrence === 0 ? base : `${base}.${occurrence}`;
2255
- }
2256
- function redactKnownValues(text, slots) {
2257
- return [...slots].sort((left, right) => right.value.length - left.value.length).reduce((output, slot) => replaceOutsideReferences(output, slot.value, `\${${slot.ref}}`), text);
2258
- }
2259
- function redactKnownValue(value, slots) {
2260
- if (isString(value))
2261
- return redactKnownValues(value, slots);
2262
- if (isNumber(value) || isBoolean(value)) {
2263
- const slot = slots.find((candidate) => candidate.value === String(value));
2264
- return slot ? `\${${slot.ref}}` : value;
2265
- }
2266
- if (Array.isArray(value))
2267
- return value.map((item) => redactKnownValue(item, slots));
2268
- if (!isObject(value))
2269
- return value;
2270
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [
2271
- key,
2272
- secretNamePattern.test(key) ? redactSecretValue(item) : redactKnownValue(item, slots)
2273
- ]));
2274
- }
2275
- function redactSecretValue(value) {
2276
- if (Array.isArray(value))
2277
- return value.map(redactSecretValue);
2278
- if (isObject(value)) {
2279
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactSecretValue(item)]));
2280
- }
2281
- return value === null || value === "" ? value : "[REDACTED]";
2282
- }
2283
- function replaceOutsideReferences(text, value, replacement) {
2284
- if (!value)
2285
- return text;
2286
- const references = new RegExp(String.raw`\$\{${referencePattern}\}`, "g");
2287
- let output = "";
2288
- let offset = 0;
2289
- for (const match of text.matchAll(references)) {
2290
- const index = match.index ?? 0;
2291
- output += text.slice(offset, index).split(value).join(replacement);
2292
- output += match[0];
2293
- offset = index + match[0].length;
2294
- }
2295
- return output + text.slice(offset).split(value).join(replacement);
2296
- }
2297
- function jwtExpiration(value) {
2298
- const parts = value.split(".");
2299
- if (parts.length !== 3 || !parts[1])
2300
- return;
2301
- try {
2302
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2303
- return isNumber(payload.exp) ? new Date(payload.exp * 1000).toISOString() : undefined;
2304
- } catch {
2305
- return;
2306
- }
2307
- }
2308
-
2309
- // src/auth/profile.ts
2310
- var StoredCredentialSlot = Struct({
2311
- ref: String3.check(isPattern(/^BC_SECRET_[1-9][0-9]*$/)),
2312
- value: String3,
2313
- sources: ArraySchema(String3),
2314
- expiresAt: optionalKey(String3)
2315
- });
2316
- var StoredAuthProfile = Struct({
2317
- version: Literal(1),
2318
- name: String3,
2319
- createdAt: String3,
2320
- updatedAt: String3,
2321
- slots: ArraySchema(StoredCredentialSlot)
2322
- }).check(makeFilter((profile) => {
2323
- const refs = profile.slots.map((slot) => slot.ref);
2324
- if (new Set(refs).size !== refs.length)
2325
- return "Auth profile refs must be unique";
2326
- const sources = profile.slots.flatMap((slot) => slot.sources);
2327
- return new Set(sources).size === sources.length ? undefined : "Auth profile sources must be unique";
2328
- }));
2329
-
2330
- class AuthProfileError extends TaggedError2()("AuthProfile.Error", {
2331
- message: String3,
2332
- operation: String3,
2333
- reason: Literals(["invalid-name", "not-found", "read-failed", "invalid-json", "invalid-profile", "write-failed", "run-failed"]),
2334
- cause: optionalKey(Defect())
2335
- }) {
2336
- }
2337
- var defaultBaseDir = () => path.join(dataRoot(), "secrets");
2338
- var writeLock = makeUnsafe(1);
2339
- var profileLockTimeoutMs = 30000;
2340
- var staleProfileLockMs = 60000;
2341
- var maximumRunOutputBytes = 1e7;
2342
- var maximumTimeoutMs = 2147483647;
2343
- var read = fn("AuthProfile.read")(function* (name, options = {}) {
2344
- const filePath = yield* profilePath(options.baseDir ?? defaultBaseDir(), name);
2345
- const text = yield* tryPromise({
2346
- try: () => fs.readFile(filePath, "utf8"),
2347
- catch: (cause) => isNodeError(cause) && cause.code === "ENOENT" ? new AuthProfileError({ message: `Auth profile not found: ${name}`, operation: "read", reason: "not-found", cause }) : new AuthProfileError({ message: `Could not read auth profile: ${name}`, operation: "read", reason: "read-failed", cause })
2348
- });
2349
- return yield* decodeUnknownEffect2(StoredAuthProfile)(yield* try_({
2350
- try: () => JSON.parse(text),
2351
- catch: (cause) => new AuthProfileError({ message: `Auth profile is not valid JSON: ${name}`, operation: "read", reason: "invalid-json", cause })
2352
- })).pipe(mapError((cause) => cause instanceof AuthProfileError ? cause : new AuthProfileError({ message: `Auth profile has an invalid shape: ${name}`, operation: "read", reason: "invalid-profile", cause })));
2353
- });
2354
- var readOptional = fn("AuthProfile.readOptional")(function* (name, options = {}) {
2355
- return yield* read(name, options).pipe(catchIf((error) => error.reason === "not-found", () => succeed6(undefined)));
2356
- });
2357
- function withLock(name, options, effect) {
2358
- const baseDir = options.baseDir ?? defaultBaseDir();
2359
- const acquire = gen(function* () {
2360
- const filePath = yield* profilePath(baseDir, name);
2361
- const lockPath = `${filePath}.lock`;
2362
- yield* tryPromise({
2363
- try: async () => {
2364
- await fs.mkdir(baseDir, { recursive: true, mode: 448 });
2365
- await fs.chmod(baseDir, 448);
2366
- const deadline = Date.now() + profileLockTimeoutMs;
2367
- while (true) {
2368
- try {
2369
- const handle = await fs.open(lockPath, "wx", 384);
2370
- let written = false;
2371
- try {
2372
- await handle.writeFile(`${process.pid}
2373
- `);
2374
- written = true;
2375
- } finally {
2376
- await handle.close();
2377
- if (!written)
2378
- await fs.unlink(lockPath).catch(() => {});
2379
- }
2380
- return;
2381
- } catch (cause) {
2382
- if (!isNodeError(cause) || cause.code !== "EEXIST")
2383
- throw cause;
2384
- const stat = await fs.stat(lockPath).catch(() => {
2385
- return;
2386
- });
2387
- if (stat && Date.now() - stat.mtimeMs > staleProfileLockMs) {
2388
- await fs.unlink(lockPath).catch(() => {});
2389
- continue;
2390
- }
2391
- if (Date.now() >= deadline)
2392
- throw new Error(`Timed out waiting for auth profile lock: ${name}`);
2393
- await new Promise((resolve) => setTimeout(resolve, 25));
2394
- }
2395
- }
2396
- },
2397
- catch: (cause) => new AuthProfileError({ message: `Could not lock auth profile: ${name}`, operation: "lock", reason: "write-failed", cause })
2398
- });
2399
- return lockPath;
2400
- });
2401
- return acquireUseRelease(acquire, () => effect, (lockPath) => tryPromise({
2402
- try: () => fs.unlink(lockPath).catch(() => {}).then(() => {}),
2403
- catch: (cause) => new AuthProfileError({ message: `Could not release auth profile lock: ${name}`, operation: "lock", reason: "write-failed", cause })
2404
- }));
2405
- }
2406
- var writeProfile = fnUntraced(function* (options) {
2407
- const baseDir = options.baseDir ?? defaultBaseDir();
2408
- const filePath = yield* profilePath(baseDir, options.name);
2409
- const existing = yield* readOptional(options.name, { baseDir });
2410
- const now = new Date().toISOString();
2411
- const profile = {
2412
- version: 1,
2413
- name: options.name,
2414
- createdAt: existing?.createdAt ?? now,
2415
- updatedAt: now,
2416
- slots: options.slots.map((slot) => ({
2417
- ref: slot.ref,
2418
- value: slot.value,
2419
- sources: [...slot.sources],
2420
- ...slot.expiresAt ? { expiresAt: slot.expiresAt } : {}
2421
- }))
2422
- };
2423
- yield* decodeUnknownEffect2(StoredAuthProfile)(profile).pipe(mapError((cause) => new AuthProfileError({ message: `Auth profile has an invalid shape: ${options.name}`, operation: "write", reason: "invalid-profile", cause })));
2424
- if (existing && sameSlots(existing.slots, profile.slots))
2425
- return summary(existing);
2426
- yield* tryPromise({
2427
- try: () => writeJsonFileAtomically(filePath, profile, { dirMode: 448 }),
2428
- catch: (cause) => new AuthProfileError({ message: `Could not write auth profile: ${options.name}`, operation: "write", reason: "write-failed", cause })
2429
- });
2430
- return summary(profile);
2431
- });
2432
- var write = fn("AuthProfile.write")(function* (options) {
2433
- return yield* writeLock.withPermit(writeProfile(options));
2434
- });
2435
- var status = fn("AuthProfile.status")(function* (name, options = {}) {
2436
- return summary(yield* read(name, options));
2437
- });
2438
- var run = fn("AuthProfile.run")(function* (options) {
2439
- if (!options.command.trim()) {
2440
- return yield* new AuthProfileError({ message: "Auth command must not be empty", operation: "run", reason: "run-failed" });
2441
- }
2442
- const timeoutMs = options.timeoutMs ?? 120000;
2443
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > maximumTimeoutMs) {
2444
- return yield* new AuthProfileError({ message: `Auth command timeout must be an integer between 1 and ${maximumTimeoutMs} milliseconds`, operation: "run", reason: "run-failed" });
2445
- }
2446
- const maxOutputBytes = options.maxOutputBytes ?? 1e6;
2447
- if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0 || maxOutputBytes > maximumRunOutputBytes) {
2448
- return yield* new AuthProfileError({ message: `Auth command output limit must be an integer between 0 and ${maximumRunOutputBytes} bytes`, operation: "run", reason: "run-failed" });
2449
- }
2450
- const profile = yield* read(options.name, { ...options.baseDir ? { baseDir: options.baseDir } : {} });
2451
- const startedAt = Date.now();
2452
- const maxSecretBytes = profile.slots.reduce((max, slot) => Math.max(max, Buffer.byteLength(slot.value)), 0);
2453
- const result = yield* runChild({
2454
- command: options.command,
2455
- args: options.args ?? [],
2456
- ...options.cwd ? { cwd: options.cwd } : {},
2457
- timeoutMs,
2458
- maxOutputBytes: maxOutputBytes + maxSecretBytes,
2459
- env: Object.fromEntries(profile.slots.map((slot) => [slot.ref, slot.value]))
2460
- }).pipe(mapError((cause) => new AuthProfileError({ message: `Could not run command with auth profile ${options.name}`, operation: "run", reason: "run-failed", cause })));
2461
- const stdout = redactOutput(result.stdout, profile.slots, maxOutputBytes);
2462
- const stderr = redactOutput(result.stderr, profile.slots, maxOutputBytes);
2463
- return {
2464
- ...result,
2465
- stdout: stdout.text,
2466
- stderr: stderr.text,
2467
- stdoutTruncated: result.stdoutTruncated || stdout.truncated,
2468
- stderrTruncated: result.stderrTruncated || stderr.truncated,
2469
- durationMs: Date.now() - startedAt
2470
- };
2471
- });
2472
- function summary(profile) {
2473
- const now = Date.now();
2474
- return {
2475
- name: profile.name,
2476
- createdAt: profile.createdAt,
2477
- updatedAt: profile.updatedAt,
2478
- slotCount: profile.slots.length,
2479
- slots: profile.slots.map((slot) => ({
2480
- ref: slot.ref,
2481
- sources: [...slot.sources],
2482
- ...slot.expiresAt ? { expiresAt: slot.expiresAt } : {},
2483
- expired: slot.expiresAt ? Date.parse(slot.expiresAt) <= now : false
2484
- }))
2485
- };
2486
- }
2487
- var profileNamePattern = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
2488
- function profilePath(baseDir, name) {
2489
- return profileNamePattern.test(name) ? succeed6(path.join(baseDir, `${name}.json`)) : fail5(new AuthProfileError({ message: `Invalid auth profile name: ${name}`, operation: "path", reason: "invalid-name" }));
2490
- }
2491
- function sameSlots(left, right) {
2492
- return JSON.stringify(left) === JSON.stringify(right);
2493
- }
2494
- function redactOutput(text, slots, maxBytes) {
2495
- const bytes = Buffer.from(text);
2496
- let cutoff = Math.min(bytes.length, maxBytes);
2497
- let changed = true;
2498
- while (changed) {
2499
- changed = false;
2500
- for (const slot of slots) {
2501
- if (!slot.value)
2502
- continue;
2503
- const secret = Buffer.from(slot.value);
2504
- let start = bytes.indexOf(secret);
2505
- while (start >= 0 && start < cutoff) {
2506
- if (start + secret.length > cutoff) {
2507
- cutoff = start;
2508
- changed = true;
2509
- break;
2510
- }
2511
- start = bytes.indexOf(secret, start + secret.length);
2512
- }
2513
- }
2514
- }
2515
- return {
2516
- text: redactKnownValues(bytes.subarray(0, cutoff).toString("utf8"), slots),
2517
- truncated: cutoff < bytes.length
2518
- };
2519
- }
2520
- function runChild(options) {
2521
- return callback2((resume) => {
2522
- const child = spawn(options.command, [...options.args], {
2523
- ...options.cwd ? { cwd: options.cwd } : {},
2524
- env: childEnvironment(options.env),
2525
- detached: process.platform !== "win32",
2526
- stdio: ["ignore", "pipe", "pipe"]
2527
- });
2528
- const stdout = [];
2529
- const stderr = [];
2530
- let stdoutBytes = 0;
2531
- let stderrBytes = 0;
2532
- let stdoutTruncated = false;
2533
- let stderrTruncated = false;
2534
- const append = (chunks, chunk, currentBytes) => {
2535
- const remaining = options.maxOutputBytes - currentBytes;
2536
- if (remaining <= 0)
2537
- return currentBytes;
2538
- chunks.push(chunk.subarray(0, remaining));
2539
- return currentBytes + Math.min(chunk.length, remaining);
2540
- };
2541
- child.stdout.on("data", (chunk) => {
2542
- const next = append(stdout, chunk, stdoutBytes);
2543
- stdoutTruncated ||= next - stdoutBytes < chunk.length;
2544
- stdoutBytes = next;
2545
- });
2546
- child.stderr.on("data", (chunk) => {
2547
- const next = append(stderr, chunk, stderrBytes);
2548
- stderrTruncated ||= next - stderrBytes < chunk.length;
2549
- stderrBytes = next;
2550
- });
2551
- let closed = false;
2552
- let settled = false;
2553
- let closePromiseResolve;
2554
- const closePromise = new Promise((resolve) => {
2555
- closePromiseResolve = resolve;
2556
- });
2557
- const timeout = setTimeout(() => {
2558
- terminateChildProcess({ child, exit: closePromise, graceMs: 1000, isExited: () => closed });
2559
- }, options.timeoutMs);
2560
- child.once("error", (cause) => {
2561
- clearTimeout(timeout);
2562
- closed = true;
2563
- closePromiseResolve?.();
2564
- if (settled)
2565
- return;
2566
- settled = true;
2567
- resume(fail5(cause));
2568
- });
2569
- child.once("close", (code, signal) => {
2570
- clearTimeout(timeout);
2571
- closed = true;
2572
- closePromiseResolve?.();
2573
- if (settled)
2574
- return;
2575
- settled = true;
2576
- resume(succeed6({
2577
- exitCode: code ?? 1,
2578
- signal,
2579
- stdout: Buffer.concat(stdout).toString("utf8"),
2580
- stderr: Buffer.concat(stderr).toString("utf8"),
2581
- stdoutTruncated,
2582
- stderrTruncated
2583
- }));
2584
- });
2585
- return promise(() => terminateChildProcess({ child, exit: closePromise, graceMs: 1000, isExited: () => closed }));
2586
- });
2587
- }
2588
- function childEnvironment(profile) {
2589
- const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^BC_SECRET_[1-9][0-9]*$/.test(name)));
2590
- return { ...inherited, ...profile };
2591
- }
2592
-
2593
- // src/auth/domain-policy.ts
2594
- import dns from "node:dns/promises";
2595
- import net from "node:net";
2596
-
2597
- class OriginPatternError extends Error {
2598
- name = "OriginPatternError";
2599
- }
2600
- var maxPatterns = 100;
2601
- function parseOriginPattern(raw) {
2602
- const pattern = raw.trim();
2603
- if (!pattern)
2604
- throw new OriginPatternError("Empty origin pattern");
2605
- if (pattern === "*" || pattern === "*.*")
2606
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} allows every site; leave the allowlist unset instead`);
2607
- const schemeMatch = /^([a-z][a-z0-9+.-]*):\/\//i.exec(pattern);
2608
- const scheme = schemeMatch?.[1]?.toLowerCase();
2609
- if (scheme !== undefined && scheme !== "http" && scheme !== "https") {
2610
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: only http and https origins can be allowed`);
2611
- }
2612
- let rest = schemeMatch ? pattern.slice(schemeMatch[0].length) : pattern;
2613
- if (/[/?#]/.test(rest.replace(/\/$/, "")))
2614
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} must be a host or origin, without a path`);
2615
- rest = rest.replace(/\/$/, "");
2616
- const wildcard = rest.startsWith("*.");
2617
- if (wildcard)
2618
- rest = rest.slice(2);
2619
- if (rest.includes("*"))
2620
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: a wildcard is only allowed as a leading "*."`);
2621
- let parsed;
2622
- try {
2623
- parsed = new URL(`${scheme ?? "http"}://${rest}`);
2624
- } catch {
2625
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} is not a valid host or origin`);
2626
- }
2627
- if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || !parsed.hostname) {
2628
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)} must be a host or origin`);
2629
- }
2630
- const host = unbracket(parsed.hostname.toLowerCase());
2631
- if (wildcard && net.isIP(host))
2632
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: wildcards don't apply to IP addresses`);
2633
- if (wildcard && !host.includes("."))
2634
- throw new OriginPatternError(`Origin pattern ${JSON.stringify(raw)}: "*." needs a domain with a dot, like *.example.com`);
2635
- const port = parsed.port || (scheme ? scheme === "https" ? "443" : "80" : undefined);
2636
- return {
2637
- pattern,
2638
- ...scheme ? { scheme: `${scheme}:` } : {},
2639
- host,
2640
- wildcard,
2641
- ...port ? { port } : {}
2642
- };
2643
- }
2644
- function parseOriginPatterns(raw) {
2645
- if (raw.length > maxPatterns)
2646
- throw new OriginPatternError(`At most ${maxPatterns} origin patterns are allowed`);
2647
- return raw.map(parseOriginPattern);
2648
- }
2649
- function normalizeOriginPatterns(raw) {
2650
- return Array.from(new Set(parseOriginPatterns(raw.flatMap((entry) => entry.split(",")).map((entry) => entry.trim()).filter(Boolean)).map((rule) => rule.pattern.toLowerCase())));
2651
- }
2652
- function unbracket(host) {
2653
- return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
2654
- }
2655
- function ipv4ToNumber(ip) {
2656
- return ip.split(".").reduce((value, part) => value * 256 + Number(part), 0);
2657
- }
2658
- var privateIpv4Ranges = [
2659
- ["0.0.0.0", 8],
2660
- ["10.0.0.0", 8],
2661
- ["100.64.0.0", 10],
2662
- ["127.0.0.0", 8],
2663
- ["169.254.0.0", 16],
2664
- ["172.16.0.0", 12],
2665
- ["192.0.0.0", 24],
2666
- ["192.0.2.0", 24],
2667
- ["192.168.0.0", 16],
2668
- ["198.18.0.0", 15],
2669
- ["198.51.100.0", 24],
2670
- ["203.0.113.0", 24],
2671
- ["224.0.0.0", 4],
2672
- ["240.0.0.0", 4]
2673
- ];
2674
- function isPrivateAddress(address) {
2675
- const ip = unbracket(address.toLowerCase()).replace(/%.*$/, "");
2676
- if (net.isIPv4(ip)) {
2677
- const value = ipv4ToNumber(ip);
2678
- return privateIpv4Ranges.some(([base, bits]) => {
2679
- const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
2680
- return (value & mask) >>> 0 === (ipv4ToNumber(base) & mask) >>> 0;
2681
- });
2682
- }
2683
- if (net.isIPv6(ip)) {
2684
- if (ip === "::" || ip === "::1")
2685
- return true;
2686
- const mapped = /^(?:0*:)*:?ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(ip) ?? /^::(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
2687
- if (mapped?.[1])
2688
- return isPrivateAddress(mapped[1]);
2689
- const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(ip);
2690
- if (hexMapped?.[1] && hexMapped[2]) {
2691
- const high = parseInt(hexMapped[1], 16);
2692
- const low = parseInt(hexMapped[2], 16);
2693
- return isPrivateAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
2694
- }
2695
- const first = parseInt(ip.split(":")[0] || "0", 16);
2696
- if ((first & 65024) === 64512 || (first & 65472) === 65152 || (first & 65280) === 65280)
2697
- return true;
2698
- if (ip.startsWith("64:ff9b::"))
2699
- return true;
2700
- return false;
2701
- }
2702
- return false;
2703
- }
2704
- function isLocalhostName(host) {
2705
- return host === "localhost" || host.endsWith(".localhost") || host === "localhost.localdomain";
2706
- }
2707
- function isPrivateHost(host) {
2708
- const bare = unbracket(host.toLowerCase());
2709
- return isLocalhostName(bare) || net.isIP(bare) !== 0 && isPrivateAddress(bare);
2710
- }
2711
- function defaultPort(protocol) {
2712
- return protocol === "https:" ? "443" : "80";
2713
- }
2714
- function ruleMatches(rule, url, host, options) {
2715
- if (rule.scheme !== undefined && rule.scheme !== url.protocol)
2716
- return false;
2717
- if (rule.scheme === undefined && options.httpsOnlyWithoutScheme && url.protocol !== "https:" && !isPrivateHost(host))
2718
- return false;
2719
- if (rule.port !== undefined && rule.port !== (url.port || defaultPort(url.protocol)))
2720
- return false;
2721
- if (rule.wildcard)
2722
- return host === rule.host || host.endsWith(`.${rule.host}`);
2723
- return host === rule.host;
2724
- }
2725
- function explicitlyAllowsHost(rules, url) {
2726
- try {
2727
- const parsed = new URL(url);
2728
- const host = unbracket(parsed.hostname.toLowerCase());
2729
- return rules.some((rule) => !rule.wildcard && ruleMatches(rule, parsed, host, {}));
2730
- } catch {
2731
- return false;
2732
- }
2733
- }
2734
- var neutralSchemes = new Set(["about:", "data:", "blob:"]);
2735
- function checkUrl(rawUrl, rules, options = {}) {
2736
- let url;
2737
- try {
2738
- url = new URL(rawUrl);
2739
- } catch {
2740
- return { allowed: false, reason: `${JSON.stringify(rawUrl.slice(0, 200))} is not a valid URL` };
2741
- }
2742
- if (neutralSchemes.has(url.protocol))
2743
- return { allowed: true };
2744
- if (url.protocol !== "http:" && url.protocol !== "https:") {
2745
- return { allowed: false, reason: `${url.protocol} URLs are not allowed for this session` };
2746
- }
2747
- const host = unbracket(url.hostname.toLowerCase());
2748
- const matching = rules.filter((rule) => ruleMatches(rule, url, host, options));
2749
- if (matching.length === 0) {
2750
- return { allowed: false, reason: `${url.host} is not in the allowed origins (${rules.map((rule) => rule.pattern).join(", ") || "none"})` };
2751
- }
2752
- const explicit = matching.some((rule) => !rule.wildcard);
2753
- if (isPrivateHost(host) && !explicit) {
2754
- return { allowed: false, reason: `${url.host} is a private, loopback or local address; allow it by naming that exact host` };
2755
- }
2756
- return { allowed: true, host, explicit };
2757
- }
2758
- async function resolvesToPrivateAddress(host, timeoutMs = 2000) {
2759
- const bare = unbracket(host);
2760
- if (net.isIP(bare) || isLocalhostName(bare))
2761
- return isPrivateHost(bare) ? bare : undefined;
2762
- let timer;
2763
- try {
2764
- const addresses = await Promise.race([
2765
- dns.lookup(bare, { all: true, verbatim: true }),
2766
- new Promise((_, reject) => {
2767
- timer = setTimeout(() => reject(new Error("DNS lookup timed out")), timeoutMs);
2768
- })
2769
- ]);
2770
- return addresses.find((entry) => isPrivateAddress(entry.address))?.address;
2771
- } catch {
2772
- return;
2773
- } finally {
2774
- if (timer)
2775
- clearTimeout(timer);
2776
- }
2777
- }
2778
- async function checkNavigationUrl(rawUrl, rules) {
2779
- const decision = checkUrl(rawUrl, rules);
2780
- if (!decision.allowed || decision.host === undefined || decision.explicit)
2781
- return decision;
2782
- const privateAddress = await resolvesToPrivateAddress(decision.host);
2783
- if (privateAddress) {
2784
- return { allowed: false, reason: `${decision.host} resolves to the private address ${privateAddress}; allow it by naming that exact host` };
2785
- }
2786
- return decision;
2787
- }
2788
-
2789
- // src/auth/site-secrets.ts
2790
- var StoredSiteSecret = Struct({
2791
- version: Literal(1),
2792
- name: String3,
2793
- kind: Literals(["password", "totp"]),
2794
- value: String3,
2795
- allowedOrigins: ArraySchema(String3),
2796
- createdAt: String3,
2797
- updatedAt: String3
2798
- });
2799
-
2800
- class SiteSecretError extends TaggedError2()("SiteSecret.Error", {
2801
- message: String3,
2802
- reason: Literals(["invalid-name", "invalid-origins", "invalid-value", "not-found", "read-failed", "write-failed"]),
2803
- cause: optionalKey(Defect())
2804
- }) {
2805
- }
2806
- var defaultSiteSecretsDir = () => path2.join(dataRoot(), "site-secrets");
2807
- function secretPath(baseDir, name) {
2808
- return profileNamePattern.test(name) ? succeed6(path2.join(baseDir, `${name}.json`)) : fail5(new SiteSecretError({ message: `Invalid secret name: ${name} (letters, digits, ".", "_" and "-", up to 64)`, reason: "invalid-name" }));
2809
- }
2810
- function summary2(secret) {
2811
- return { name: secret.name, kind: secret.kind, allowedOrigins: [...secret.allowedOrigins], createdAt: secret.createdAt, updatedAt: secret.updatedAt };
2812
- }
2813
- var readSecret = fn("SiteSecrets.read")(function* (name, options = {}) {
2814
- const filePath = yield* secretPath(options.baseDir ?? defaultSiteSecretsDir(), name);
2815
- const text = yield* tryPromise({
2816
- try: () => fs2.readFile(filePath, "utf8"),
2817
- catch: (cause) => isNodeError(cause) && cause.code === "ENOENT" ? new SiteSecretError({ message: `Secret not found: ${name}. Ask the user to add it with \`${cliCommand(`secrets add ${name} --origin <origin>`)}\`.`, reason: "not-found" }) : new SiteSecretError({ message: `Could not read secret ${name}`, reason: "read-failed", cause })
2818
- });
2819
- return yield* try_({
2820
- try: () => decodeUnknownSync(StoredSiteSecret)(JSON.parse(text)),
2821
- catch: (cause) => new SiteSecretError({ message: `Secret ${name} is not a valid secret file`, reason: "read-failed", cause })
2822
- });
2823
- });
2824
- var addSecret = fn("SiteSecrets.add")(function* (options) {
2825
- const baseDir = options.baseDir ?? defaultSiteSecretsDir();
2826
- const filePath = yield* secretPath(baseDir, options.name);
2827
- const kind = options.kind ?? "password";
2828
- const allowedOrigins = yield* try_({
2829
- try: () => normalizeOriginPatterns(options.allowedOrigins),
2830
- catch: (cause) => new SiteSecretError({ message: cause instanceof Error ? cause.message : "Invalid origins", reason: "invalid-origins", cause })
2831
- });
2832
- if (allowedOrigins.length === 0) {
2833
- return yield* new SiteSecretError({ message: "A secret needs at least one allowed origin (--origin https://example.com)", reason: "invalid-origins" });
2834
- }
2835
- const value = kind === "totp" ? options.value.trim() : options.value.replace(/\r?\n$/, "");
2836
- if (!value)
2837
- return yield* new SiteSecretError({ message: "The secret value is empty", reason: "invalid-value" });
2838
- if (kind === "totp")
2839
- yield* try_({
2840
- try: () => totpCode(value),
2841
- catch: (cause) => new SiteSecretError({ message: `Not a TOTP seed or otpauth:// URI: ${cause instanceof Error ? cause.message : "invalid"}`, reason: "invalid-value", cause })
2842
- });
2843
- const write = gen(function* () {
2844
- const existing = yield* readSecret(options.name, { baseDir }).pipe(catchIf((error) => error.reason === "not-found", () => succeed6(undefined)));
2845
- const now = new Date().toISOString();
2846
- const secret = { version: 1, name: options.name, kind, value, allowedOrigins: [...allowedOrigins], createdAt: existing?.createdAt ?? now, updatedAt: now };
2847
- yield* tryPromise({
2848
- try: () => writeJsonFileAtomically(filePath, secret, { dirMode: 448 }),
2849
- catch: (cause) => new SiteSecretError({ message: `Could not write secret ${options.name}`, reason: "write-failed", cause })
2850
- });
2851
- return summary2(secret);
2852
- });
2853
- return yield* withLock(options.name, { baseDir }, write).pipe(mapError((error) => error instanceof SiteSecretError ? error : new SiteSecretError({ message: error.message, reason: "write-failed", cause: error })));
2854
- });
2855
- var listSecrets = fn("SiteSecrets.list")(function* (options = {}) {
2856
- const baseDir = options.baseDir ?? defaultSiteSecretsDir();
2857
- const names = yield* tryPromise({
2858
- try: () => fs2.readdir(baseDir).catch((cause) => isNodeError(cause) && cause.code === "ENOENT" ? [] : Promise.reject(cause)),
2859
- catch: (cause) => new SiteSecretError({ message: "Could not list secrets", reason: "read-failed", cause })
2860
- });
2861
- const secrets = [];
2862
- for (const file of names.filter((entry) => entry.endsWith(".json")).sort()) {
2863
- const secret = yield* readSecret(file.slice(0, -".json".length), { baseDir }).pipe(option2);
2864
- if (secret._tag === "Some")
2865
- secrets.push(summary2(secret.value));
2866
- }
2867
- return secrets;
2868
- });
2869
- var removeSecret = fn("SiteSecrets.remove")(function* (name, options = {}) {
2870
- const baseDir = options.baseDir ?? defaultSiteSecretsDir();
2871
- const filePath = yield* secretPath(baseDir, name);
2872
- return yield* withLock(name, { baseDir }, tryPromise({
2873
- try: () => fs2.rm(filePath).then(() => true, (cause) => isNodeError(cause) && cause.code === "ENOENT" ? false : Promise.reject(cause)),
2874
- catch: (cause) => new SiteSecretError({ message: `Could not remove secret ${name}`, reason: "write-failed", cause })
2875
- })).pipe(mapError((error) => error instanceof SiteSecretError ? error : new SiteSecretError({ message: error.message, reason: "write-failed", cause: error })));
2876
- });
2877
- function base32Decode(input) {
2878
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2879
- const clean = input.toUpperCase().replace(/[\s=-]/g, "");
2880
- if (!clean || /[^A-Z2-7]/.test(clean))
2881
- throw new Error("the seed must be base32");
2882
- let bits = 0;
2883
- let value = 0;
2884
- const bytes = [];
2885
- for (const char of clean) {
2886
- value = value << 5 | alphabet.indexOf(char);
2887
- bits += 5;
2888
- if (bits >= 8) {
2889
- bytes.push(value >>> bits - 8 & 255);
2890
- bits -= 8;
2891
- }
2892
- }
2893
- return Buffer.from(bytes);
2894
- }
2895
- function totpParameters(seed) {
2896
- if (/^otpauth:\/\//i.test(seed)) {
2897
- const url = new URL(seed);
2898
- const secret = url.searchParams.get("secret");
2899
- if (!secret)
2900
- throw new Error("the otpauth URI has no secret");
2901
- const digits = Number(url.searchParams.get("digits") ?? 6);
2902
- const period = Number(url.searchParams.get("period") ?? 30);
2903
- const algorithm = (url.searchParams.get("algorithm") ?? "SHA1").toLowerCase();
2904
- if (![6, 7, 8].includes(digits) || !Number.isInteger(period) || period <= 0 || !["sha1", "sha256", "sha512"].includes(algorithm)) {
2905
- throw new Error("unsupported otpauth parameters");
2906
- }
2907
- return { key: base32Decode(secret), digits, period, algorithm };
2908
- }
2909
- return { key: base32Decode(seed), digits: 6, period: 30, algorithm: "sha1" };
2910
- }
2911
- function totpCode(seed, now = Date.now()) {
2912
- const { key, digits, period, algorithm } = totpParameters(seed);
2913
- const counter = Buffer.alloc(8);
2914
- counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / period)));
2915
- const hmac = crypto.createHmac(algorithm, key).update(counter).digest();
2916
- const offset = hmac[hmac.length - 1] & 15;
2917
- const binary = (hmac.readUInt32BE(offset) & 2147483647) % 10 ** digits;
2918
- return String(binary).padStart(digits, "0");
2919
- }
2920
- function secretText(secret) {
2921
- return secret.kind === "totp" ? totpCode(secret.value) : secret.value;
2922
- }
2923
-
2924
- export { makeUnsafe, make, settingKeys, settingSpecs, securityVariables, SettingsInputError, parseSettingChanges, settingsFromExtension, settingsToExtension, describeSettings, describeChanges, formatSettings, isStreamSchema, getStreamSchemas, ClientAbort, ServerClient, make2, exitSchema, isWrapper, make3, Implementation, ClientCapabilities, INVALID_REQUEST_ERROR_CODE, METHOD_NOT_FOUND_ERROR_CODE, INVALID_PARAMS_ERROR_CODE, INTERNAL_ERROR_CODE, HEADER_MISMATCH_ERROR_CODE, ParseError, InvalidRequest, MethodNotFound, InvalidParams, InternalError, McpError, Ping, Initialize, CancelledNotification, ProgressNotification, ResourceListChangedNotification, ResourceUpdatedNotification, Prompt, TextContent, PromptListChangedNotification, Tool, CallToolResult, ToolListChangedNotification, LoggingLevel, LoggingMessageNotification, CreateMessage, ListRootsResult, ListRoots, Elicit, McpReverseOperationUnsupported, McpReverseOperationError, McpRequestContext, McpServerClient, McpServerClientMiddleware, ServerNotificationRpcs, EnabledWhen, mcpUpdateNote2, objectSchema, emptyInputSchema, sessionSchemaProperty, sessionAliasSchemaProperty, sessionOnlyInputSchema, ExecuteToolOutput, StatusToolOutput, CurrentSessionToolOutput, SessionDeleteToolOutput, NetworkToolOutput, RecordingToolOutput, FlightRecorderToolOutput, agentSettingKeys, SettingsToolOutput, SecretsListToolOutput, toolOutputJson, executeToolResult, ensureSessionExists, parseExecuteArguments, parseAdoptArguments, requiredStringField, requiredAction, optionalStringField, optionalBooleanField, optionalPositiveIntegerField, optionalStringArrayField, requireObject, toolResultForValue2, mcpErrorMessage2, toolResult, terminateChildProcess, SecretCollector, looksLikeTokenSegment, AuthProfileError, read, readOptional, withLock, write, status, run, OriginPatternError, parseOriginPatterns, normalizeOriginPatterns, isPrivateAddress, explicitlyAllowsHost, checkUrl, checkNavigationUrl, readSecret, addSecret, listSecrets, removeSecret, secretText };