@ractive-ch/tab-mcp-client 0.9.1 → 0.10.0

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.
@@ -1,21 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/icons.ts", "../../../../node_modules/.bun/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js", "../../../../node_modules/.bun/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js", "../../../../node_modules/.bun/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js", "../../../../node_modules/.bun/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js", "../../../../node_modules/.bun/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js", "../../../../node_modules/.bun/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js", "../../src/mapping.ts", "../../src/mcp.ts", "../../src/protocol.ts", "../../src/address.ts", "../../src/connection.ts"],
4
- "sourcesContent": [
5
- "/**\n * The page's icons for `serverInfo.icons` (MCP `Icon`): the AI app may show\n * them for this page's connector. Loaded with the connection, not the core.\n */\n\nimport type { Icon } from \"./types.ts\";\n\n/** At most this many icons; a URL up to 2 KiB, a `data:` URI up to 16 KiB. */\nconst MAX_ICONS = 8;\nconst MAX_URL = 2048;\nconst MAX_DATA = 16_384;\nconst SIZE = /^(?:\\d{1,4}x\\d{1,4}|any)$/;\n\n/**\n * An icon worth sending, with clean fields: an http(s) URL (rendering an SVG\n * safely is the AI app's job, as MCP says), or a raster `data:` URI; never\n * an inline SVG, which the app might put into its own page.\n */\nfunction clean(icon: Icon): Icon | undefined {\n\tconst { src, mimeType, sizes, theme } = icon;\n\tif (typeof src !== \"string\") return undefined;\n\tconst url = /^https?:/i.test(src) && src.length <= MAX_URL;\n\tconst data =\n\t\t/^data:image\\/(?:png|jpeg|gif|webp|x-icon|vnd\\.microsoft\\.icon)[;,]/i.test(\n\t\t\tsrc,\n\t\t) && src.length <= MAX_DATA;\n\tif (!url && !data) return undefined;\n\tconst out: Icon = { src };\n\tif (typeof mimeType === \"string\" && /^image\\/[\\w.+-]+$/i.test(mimeType)) {\n\t\tout.mimeType = mimeType.toLowerCase();\n\t}\n\tconst valid = Array.isArray(sizes)\n\t\t? sizes.map((s) => String(s).toLowerCase()).filter((s) => SIZE.test(s))\n\t\t: [];\n\tif (valid.length > 0) out.sizes = valid;\n\tif (theme === \"light\" || theme === \"dark\") out.theme = theme;\n\treturn out;\n}\n\n/** Icons as given (`server.icons`), cleaned and capped. */\nexport function cleanIcons(icons: readonly Icon[]): Icon[] {\n\tconst out: Icon[] = [];\n\tfor (const icon of icons) {\n\t\tconst c =\n\t\t\ttypeof icon === \"object\" && icon !== null ? clean(icon) : undefined;\n\t\tif (c !== undefined) out.push(c);\n\t\tif (out.length === MAX_ICONS) break;\n\t}\n\treturn out;\n}\n\n/**\n * The document's `<link rel=\"icon\">` and `<link rel=\"apple-touch-icon\">`,\n * with their `type`, `sizes` and a `prefers-color-scheme` media query as the\n * theme. Empty without a document.\n */\nexport function pageIcons(\n\tdoc: Document | undefined = globalThis.document,\n): Icon[] {\n\t// Icons are optional: whatever the document is, connecting goes on.\n\ttry {\n\t\tconst links = doc?.querySelectorAll<HTMLLinkElement>(\n\t\t\t'link[rel~=\"icon\" i], link[rel~=\"apple-touch-icon\" i]',\n\t\t);\n\t\treturn cleanIcons(\n\t\t\t// An empty href resolves to the page itself: no icon.\n\t\t\t[...(links ?? [])]\n\t\t\t\t.filter((link) => link.getAttribute(\"href\")?.trim())\n\t\t\t\t.map((link) => {\n\t\t\t\t\tconst icon: Icon = { src: link.href };\n\t\t\t\t\tif (link.type) icon.mimeType = link.type;\n\t\t\t\t\tconst sizes = link.getAttribute(\"sizes\");\n\t\t\t\t\tif (sizes) icon.sizes = sizes.trim().split(/\\s+/);\n\t\t\t\t\tconst scheme = /prefers-color-scheme:\\s*(light|dark)/i.exec(\n\t\t\t\t\t\tlink.media,\n\t\t\t\t\t);\n\t\t\t\t\tif (scheme) icon.theme = scheme[1]?.toLowerCase() as \"light\" | \"dark\";\n\t\t\t\t\treturn icon;\n\t\t\t\t}),\n\t\t);\n\t} catch {\n\t\treturn [];\n\t}\n}\n",
6
- "export function deepCompareStrict(a, b) {\n const typeofa = typeof a;\n if (typeofa !== typeof b) {\n return false;\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) {\n return false;\n }\n const length = a.length;\n if (length !== b.length) {\n return false;\n }\n for (let i = 0; i < length; i++) {\n if (!deepCompareStrict(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n if (typeofa === 'object') {\n if (!a || !b) {\n return a === b;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n const length = aKeys.length;\n if (length !== bKeys.length) {\n return false;\n }\n for (const k of aKeys) {\n if (!deepCompareStrict(a[k], b[k])) {\n return false;\n }\n }\n return true;\n }\n return a === b;\n}\n",
7
- "export function encodePointer(p) {\n return encodeURI(escapePointer(p));\n}\nexport function escapePointer(p) {\n return p.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n",
8
- "import { encodePointer } from './pointer.js';\nexport const schemaKeyword = {\n additionalItems: true,\n unevaluatedItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n unevaluatedProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\nexport const schemaArrayKeyword = {\n prefixItems: true,\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\nexport const schemaMapKeyword = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependentSchemas: true\n};\nexport const ignoredKeyword = {\n id: true,\n $id: true,\n $ref: true,\n $schema: true,\n $anchor: true,\n $vocabulary: true,\n $comment: true,\n default: true,\n enum: true,\n const: true,\n required: true,\n type: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\nexport let initialBaseURI = typeof self !== 'undefined' &&\n self.location &&\n self.location.origin !== 'null'\n ?\n new URL(self.location.origin + self.location.pathname + location.search)\n : new URL('https://github.com/cfworker');\nexport function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') {\n if (schema && typeof schema === 'object' && !Array.isArray(schema)) {\n const id = schema.$id || schema.id;\n if (id) {\n const url = new URL(id, baseURI.href);\n if (url.hash.length > 1) {\n lookup[url.href] = schema;\n }\n else {\n url.hash = '';\n if (basePointer === '') {\n baseURI = url;\n }\n else {\n dereference(schema, lookup, baseURI);\n }\n }\n }\n }\n else if (schema !== true && schema !== false) {\n return lookup;\n }\n const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : '');\n if (lookup[schemaURI] !== undefined) {\n throw new Error(`Duplicate schema URI \"${schemaURI}\".`);\n }\n lookup[schemaURI] = schema;\n if (schema === true || schema === false) {\n return lookup;\n }\n if (schema.__absolute_uri__ === undefined) {\n Object.defineProperty(schema, '__absolute_uri__', {\n enumerable: false,\n value: schemaURI\n });\n }\n if (schema.$ref && schema.__absolute_ref__ === undefined) {\n const url = new URL(schema.$ref, baseURI.href);\n url.hash = url.hash;\n Object.defineProperty(schema, '__absolute_ref__', {\n enumerable: false,\n value: url.href\n });\n }\n if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) {\n const url = new URL(schema.$recursiveRef, baseURI.href);\n url.hash = url.hash;\n Object.defineProperty(schema, '__absolute_recursive_ref__', {\n enumerable: false,\n value: url.href\n });\n }\n if (schema.$anchor) {\n const url = new URL('#' + schema.$anchor, baseURI.href);\n lookup[url.href] = schema;\n }\n for (let key in schema) {\n if (ignoredKeyword[key]) {\n continue;\n }\n const keyBase = `${basePointer}/${encodePointer(key)}`;\n const subSchema = schema[key];\n if (Array.isArray(subSchema)) {\n if (schemaArrayKeyword[key]) {\n const length = subSchema.length;\n for (let i = 0; i < length; i++) {\n dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`);\n }\n }\n }\n else if (schemaMapKeyword[key]) {\n for (let subKey in subSchema) {\n dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`);\n }\n }\n else {\n dereference(subSchema, lookup, baseURI, keyBase);\n }\n }\n return lookup;\n}\n",
9
- "const DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/;\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?(z|[+-]\\d\\d(?::?\\d\\d)?)?$/i;\nconst HOSTNAME = /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i;\nconst URIREF = /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(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d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-?)*[a-z\\u{00a1}-\\u{ffff}0-9]+)(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-?)*[a-z\\u{00a1}-\\u{ffff}0-9]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu;\nconst UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;\nconst JSON_POINTER = /^(?:\\/(?:[^~/]|~0|~1)*)*$/;\nconst JSON_POINTER_URI_FRAGMENT = /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;\nconst RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;\nconst EMAIL = (input) => {\n if (input[0] === '\"')\n return false;\n const [name, host, ...rest] = input.split('@');\n if (!name ||\n !host ||\n rest.length !== 0 ||\n name.length > 64 ||\n host.length > 253)\n return false;\n if (name[0] === '.' || name.endsWith('.') || name.includes('..'))\n return false;\n if (!/^[a-z0-9.-]+$/i.test(host) ||\n !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name))\n return false;\n return host\n .split('.')\n .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part));\n};\nconst IPV4 = /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/;\nconst IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i;\nconst DURATION = (input) => input.length > 1 &&\n input.length < 80 &&\n (/^P\\d+([.,]\\d+)?W$/.test(input) ||\n (/^P[\\dYMDTHS]*(\\d[.,]\\d+)?[YMDHS]$/.test(input) &&\n /^P([.,\\d]+Y)?([.,\\d]+M)?([.,\\d]+D)?(T([.,\\d]+H)?([.,\\d]+M)?([.,\\d]+S)?)?$/.test(input)));\nfunction bind(r) {\n return r.test.bind(r);\n}\nexport const format = {\n date,\n time: time.bind(undefined, false),\n 'date-time': date_time,\n duration: DURATION,\n uri,\n 'uri-reference': bind(URIREF),\n 'uri-template': bind(URITEMPLATE),\n url: bind(URL_),\n email: EMAIL,\n hostname: bind(HOSTNAME),\n ipv4: bind(IPV4),\n ipv6: bind(IPV6),\n regex: regex,\n uuid: bind(UUID),\n 'json-pointer': bind(JSON_POINTER),\n 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT),\n 'relative-json-pointer': bind(RELATIVE_JSON_POINTER)\n};\nfunction isLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\nfunction date(str) {\n const matches = str.match(DATE);\n if (!matches)\n return false;\n const year = +matches[1];\n const month = +matches[2];\n const day = +matches[3];\n return (month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction time(full, str) {\n const matches = str.match(TIME);\n if (!matches)\n return false;\n const hour = +matches[1];\n const minute = +matches[2];\n const second = +matches[3];\n const timeZone = !!matches[5];\n return (((hour <= 23 && minute <= 59 && second <= 59) ||\n (hour == 23 && minute == 59 && second == 60)) &&\n (!full || timeZone));\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction date_time(str) {\n const dateTime = str.split(DATE_TIME_SEPARATOR);\n return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]);\n}\nconst NOT_URI_FRAGMENT = /\\/|:/;\nconst URI_PATTERN = /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}: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N.test(str);\n}\nconst Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n if (Z_ANCHOR.test(str))\n return false;\n try {\n new RegExp(str, 'u');\n return true;\n }\n catch (e) {\n return false;\n }\n}\n",
10
- "export function ucs2length(s) {\n let result = 0;\n let length = s.length;\n let index = 0;\n let charCode;\n while (index < length) {\n result++;\n charCode = s.charCodeAt(index++);\n if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) {\n charCode = s.charCodeAt(index);\n if ((charCode & 0xfc00) == 0xdc00) {\n index++;\n }\n }\n }\n return result;\n}\n",
11
- "import { deepCompareStrict } from './deep-compare-strict.js';\nimport { dereference } from './dereference.js';\nimport { format } from './format.js';\nimport { encodePointer } from './pointer.js';\nimport { ucs2length } from './ucs2-length.js';\nexport function validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) {\n if (schema === true) {\n return { valid: true, errors: [] };\n }\n if (schema === false) {\n return {\n valid: false,\n errors: [\n {\n instanceLocation,\n keyword: 'false',\n keywordLocation: instanceLocation,\n error: 'False boolean schema.'\n }\n ]\n };\n }\n const rawInstanceType = typeof instance;\n let instanceType;\n switch (rawInstanceType) {\n case 'boolean':\n case 'number':\n case 'string':\n instanceType = rawInstanceType;\n break;\n case 'object':\n if (instance === null) {\n instanceType = 'null';\n }\n else if (Array.isArray(instance)) {\n instanceType = 'array';\n }\n else {\n instanceType = 'object';\n }\n break;\n default:\n throw new Error(`Instances of \"${rawInstanceType}\" type are not supported.`);\n }\n const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema;\n const errors = [];\n if ($recursiveAnchor === true && recursiveAnchor === null) {\n recursiveAnchor = schema;\n }\n if ($recursiveRef === '#') {\n const refSchema = recursiveAnchor === null\n ? lookup[__absolute_recursive_ref__]\n : recursiveAnchor;\n const keywordLocation = `${schemaLocation}/$recursiveRef`;\n const result = validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: '$recursiveRef',\n keywordLocation,\n error: 'A subschema had errors.'\n }, ...result.errors);\n }\n }\n if ($ref !== undefined) {\n const uri = __absolute_ref__ || $ref;\n const refSchema = lookup[uri];\n if (refSchema === undefined) {\n let message = `Unresolved $ref \"${$ref}\".`;\n if (__absolute_ref__ && __absolute_ref__ !== $ref) {\n message += ` Absolute URI \"${__absolute_ref__}\".`;\n }\n message += `\\nKnown schemas:\\n- ${Object.keys(lookup).join('\\n- ')}`;\n throw new Error(message);\n }\n const keywordLocation = `${schemaLocation}/$ref`;\n const result = validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: '$ref',\n keywordLocation,\n error: 'A subschema had errors.'\n }, ...result.errors);\n }\n if (draft === '4' || draft === '7') {\n return { valid: errors.length === 0, errors };\n }\n }\n if (Array.isArray($type)) {\n let length = $type.length;\n let valid = false;\n for (let i = 0; i < length; i++) {\n if (instanceType === $type[i] ||\n ($type[i] === 'integer' &&\n instanceType === 'number' &&\n instance % 1 === 0 &&\n instance === instance)) {\n valid = true;\n break;\n }\n }\n if (!valid) {\n errors.push({\n instanceLocation,\n keyword: 'type',\n keywordLocation: `${schemaLocation}/type`,\n error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type.join('\", \"')}\".`\n });\n }\n }\n else if ($type === 'integer') {\n if (instanceType !== 'number' || instance % 1 || instance !== instance) {\n errors.push({\n instanceLocation,\n keyword: 'type',\n keywordLocation: `${schemaLocation}/type`,\n error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type}\".`\n });\n }\n }\n else if ($type !== undefined && instanceType !== $type) {\n errors.push({\n instanceLocation,\n keyword: 'type',\n keywordLocation: `${schemaLocation}/type`,\n error: `Instance type \"${instanceType}\" is invalid. Expected \"${$type}\".`\n });\n }\n if ($const !== undefined) {\n if (instanceType === 'object' || instanceType === 'array') {\n if (!deepCompareStrict(instance, $const)) {\n errors.push({\n instanceLocation,\n keyword: 'const',\n keywordLocation: `${schemaLocation}/const`,\n error: `Instance does not match ${JSON.stringify($const)}.`\n });\n }\n }\n else if (instance !== $const) {\n errors.push({\n instanceLocation,\n keyword: 'const',\n keywordLocation: `${schemaLocation}/const`,\n error: `Instance does not match ${JSON.stringify($const)}.`\n });\n }\n }\n if ($enum !== undefined) {\n if (instanceType === 'object' || instanceType === 'array') {\n if (!$enum.some(value => deepCompareStrict(instance, value))) {\n errors.push({\n instanceLocation,\n keyword: 'enum',\n keywordLocation: `${schemaLocation}/enum`,\n error: `Instance does not match any of ${JSON.stringify($enum)}.`\n });\n }\n }\n else if (!$enum.some(value => instance === value)) {\n errors.push({\n instanceLocation,\n keyword: 'enum',\n keywordLocation: `${schemaLocation}/enum`,\n error: `Instance does not match any of ${JSON.stringify($enum)}.`\n });\n }\n }\n if ($not !== undefined) {\n const keywordLocation = `${schemaLocation}/not`;\n const result = validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation);\n if (result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'not',\n keywordLocation,\n error: 'Instance matched \"not\" schema.'\n });\n }\n }\n let subEvaluateds = [];\n if ($anyOf !== undefined) {\n const keywordLocation = `${schemaLocation}/anyOf`;\n const errorsLength = errors.length;\n let anyValid = false;\n for (let i = 0; i < $anyOf.length; i++) {\n const subSchema = $anyOf[i];\n const subEvaluated = Object.create(evaluated);\n const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n errors.push(...result.errors);\n anyValid = anyValid || result.valid;\n if (result.valid) {\n subEvaluateds.push(subEvaluated);\n }\n }\n if (anyValid) {\n errors.length = errorsLength;\n }\n else {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'anyOf',\n keywordLocation,\n error: 'Instance does not match any subschemas.'\n });\n }\n }\n if ($allOf !== undefined) {\n const keywordLocation = `${schemaLocation}/allOf`;\n const errorsLength = errors.length;\n let allValid = true;\n for (let i = 0; i < $allOf.length; i++) {\n const subSchema = $allOf[i];\n const subEvaluated = Object.create(evaluated);\n const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n errors.push(...result.errors);\n allValid = allValid && result.valid;\n if (result.valid) {\n subEvaluateds.push(subEvaluated);\n }\n }\n if (allValid) {\n errors.length = errorsLength;\n }\n else {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'allOf',\n keywordLocation,\n error: `Instance does not match every subschema.`\n });\n }\n }\n if ($oneOf !== undefined) {\n const keywordLocation = `${schemaLocation}/oneOf`;\n const errorsLength = errors.length;\n const matches = $oneOf.filter((subSchema, i) => {\n const subEvaluated = Object.create(evaluated);\n const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);\n errors.push(...result.errors);\n if (result.valid) {\n subEvaluateds.push(subEvaluated);\n }\n return result.valid;\n }).length;\n if (matches === 1) {\n errors.length = errorsLength;\n }\n else {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'oneOf',\n keywordLocation,\n error: `Instance does not match exactly one subschema (${matches} matches).`\n });\n }\n }\n if (instanceType === 'object' || instanceType === 'array') {\n Object.assign(evaluated, ...subEvaluateds);\n }\n if ($if !== undefined) {\n const keywordLocation = `${schemaLocation}/if`;\n const conditionResult = validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid;\n if (conditionResult) {\n if ($then !== undefined) {\n const thenResult = validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated);\n if (!thenResult.valid) {\n errors.push({\n instanceLocation,\n keyword: 'if',\n keywordLocation,\n error: `Instance does not match \"then\" schema.`\n }, ...thenResult.errors);\n }\n }\n }\n else if ($else !== undefined) {\n const elseResult = validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated);\n if (!elseResult.valid) {\n errors.push({\n instanceLocation,\n keyword: 'if',\n keywordLocation,\n error: `Instance does not match \"else\" schema.`\n }, ...elseResult.errors);\n }\n }\n }\n if (instanceType === 'object') {\n if ($required !== undefined) {\n for (const key of $required) {\n if (!(key in instance)) {\n errors.push({\n instanceLocation,\n keyword: 'required',\n keywordLocation: `${schemaLocation}/required`,\n error: `Instance does not have required property \"${key}\".`\n });\n }\n }\n }\n const keys = Object.keys(instance);\n if ($minProperties !== undefined && keys.length < $minProperties) {\n errors.push({\n instanceLocation,\n keyword: 'minProperties',\n keywordLocation: `${schemaLocation}/minProperties`,\n error: `Instance does not have at least ${$minProperties} properties.`\n });\n }\n if ($maxProperties !== undefined && keys.length > $maxProperties) {\n errors.push({\n instanceLocation,\n keyword: 'maxProperties',\n keywordLocation: `${schemaLocation}/maxProperties`,\n error: `Instance does not have at least ${$maxProperties} properties.`\n });\n }\n if ($propertyNames !== undefined) {\n const keywordLocation = `${schemaLocation}/propertyNames`;\n for (const key in instance) {\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'propertyNames',\n keywordLocation,\n error: `Property name \"${key}\" does not match schema.`\n }, ...result.errors);\n }\n }\n }\n if ($dependentRequired !== undefined) {\n const keywordLocation = `${schemaLocation}/dependantRequired`;\n for (const key in $dependentRequired) {\n if (key in instance) {\n const required = $dependentRequired[key];\n for (const dependantKey of required) {\n if (!(dependantKey in instance)) {\n errors.push({\n instanceLocation,\n keyword: 'dependentRequired',\n keywordLocation,\n error: `Instance has \"${key}\" but does not have \"${dependantKey}\".`\n });\n }\n }\n }\n }\n }\n if ($dependentSchemas !== undefined) {\n for (const key in $dependentSchemas) {\n const keywordLocation = `${schemaLocation}/dependentSchemas`;\n if (key in instance) {\n const result = validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'dependentSchemas',\n keywordLocation,\n error: `Instance has \"${key}\" but does not match dependant schema.`\n }, ...result.errors);\n }\n }\n }\n }\n if ($dependencies !== undefined) {\n const keywordLocation = `${schemaLocation}/dependencies`;\n for (const key in $dependencies) {\n if (key in instance) {\n const propsOrSchema = $dependencies[key];\n if (Array.isArray(propsOrSchema)) {\n for (const dependantKey of propsOrSchema) {\n if (!(dependantKey in instance)) {\n errors.push({\n instanceLocation,\n keyword: 'dependencies',\n keywordLocation,\n error: `Instance has \"${key}\" but does not have \"${dependantKey}\".`\n });\n }\n }\n }\n else {\n const result = validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`);\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'dependencies',\n keywordLocation,\n error: `Instance has \"${key}\" but does not match dependant schema.`\n }, ...result.errors);\n }\n }\n }\n }\n }\n const thisEvaluated = Object.create(null);\n let stop = false;\n if ($properties !== undefined) {\n const keywordLocation = `${schemaLocation}/properties`;\n for (const key in $properties) {\n if (!(key in instance)) {\n continue;\n }\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`);\n if (result.valid) {\n evaluated[key] = thisEvaluated[key] = true;\n }\n else {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'properties',\n keywordLocation,\n error: `Property \"${key}\" does not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n if (!stop && $patternProperties !== undefined) {\n const keywordLocation = `${schemaLocation}/patternProperties`;\n for (const pattern in $patternProperties) {\n const regex = new RegExp(pattern, 'u');\n const subSchema = $patternProperties[pattern];\n for (const key in instance) {\n if (!regex.test(key)) {\n continue;\n }\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`);\n if (result.valid) {\n evaluated[key] = thisEvaluated[key] = true;\n }\n else {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'patternProperties',\n keywordLocation,\n error: `Property \"${key}\" matches pattern \"${pattern}\" but does not match associated schema.`\n }, ...result.errors);\n }\n }\n }\n }\n if (!stop && $additionalProperties !== undefined) {\n const keywordLocation = `${schemaLocation}/additionalProperties`;\n for (const key in instance) {\n if (thisEvaluated[key]) {\n continue;\n }\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n if (result.valid) {\n evaluated[key] = true;\n }\n else {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'additionalProperties',\n keywordLocation,\n error: `Property \"${key}\" does not match additional properties schema.`\n }, ...result.errors);\n }\n }\n }\n else if (!stop && $unevaluatedProperties !== undefined) {\n const keywordLocation = `${schemaLocation}/unevaluatedProperties`;\n for (const key in instance) {\n if (!evaluated[key]) {\n const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n const result = validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);\n if (result.valid) {\n evaluated[key] = true;\n }\n else {\n errors.push({\n instanceLocation,\n keyword: 'unevaluatedProperties',\n keywordLocation,\n error: `Property \"${key}\" does not match unevaluated properties schema.`\n }, ...result.errors);\n }\n }\n }\n }\n }\n else if (instanceType === 'array') {\n if ($maxItems !== undefined && instance.length > $maxItems) {\n errors.push({\n instanceLocation,\n keyword: 'maxItems',\n keywordLocation: `${schemaLocation}/maxItems`,\n error: `Array has too many items (${instance.length} > ${$maxItems}).`\n });\n }\n if ($minItems !== undefined && instance.length < $minItems) {\n errors.push({\n instanceLocation,\n keyword: 'minItems',\n keywordLocation: `${schemaLocation}/minItems`,\n error: `Array has too few items (${instance.length} < ${$minItems}).`\n });\n }\n const length = instance.length;\n let i = 0;\n let stop = false;\n if ($prefixItems !== undefined) {\n const keywordLocation = `${schemaLocation}/prefixItems`;\n const length2 = Math.min($prefixItems.length, length);\n for (; i < length2; i++) {\n const result = validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'prefixItems',\n keywordLocation,\n error: `Items did not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n if ($items !== undefined) {\n const keywordLocation = `${schemaLocation}/items`;\n if (Array.isArray($items)) {\n const length2 = Math.min($items.length, length);\n for (; i < length2; i++) {\n const result = validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'items',\n keywordLocation,\n error: `Items did not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n else {\n for (; i < length; i++) {\n const result = validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'items',\n keywordLocation,\n error: `Items did not match schema.`\n }, ...result.errors);\n if (stop)\n break;\n }\n }\n }\n if (!stop && $additionalItems !== undefined) {\n const keywordLocation = `${schemaLocation}/additionalItems`;\n for (; i < length; i++) {\n const result = validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n evaluated[i] = true;\n if (!result.valid) {\n stop = shortCircuit;\n errors.push({\n instanceLocation,\n keyword: 'additionalItems',\n keywordLocation,\n error: `Items did not match additional items schema.`\n }, ...result.errors);\n }\n }\n }\n }\n if ($contains !== undefined) {\n if (length === 0 && $minContains === undefined) {\n errors.push({\n instanceLocation,\n keyword: 'contains',\n keywordLocation: `${schemaLocation}/contains`,\n error: `Array is empty. It must contain at least one item matching the schema.`\n });\n }\n else if ($minContains !== undefined && length < $minContains) {\n errors.push({\n instanceLocation,\n keyword: 'minContains',\n keywordLocation: `${schemaLocation}/minContains`,\n error: `Array has less items (${length}) than minContains (${$minContains}).`\n });\n }\n else {\n const keywordLocation = `${schemaLocation}/contains`;\n const errorsLength = errors.length;\n let contained = 0;\n for (let j = 0; j < length; j++) {\n const result = validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation);\n if (result.valid) {\n evaluated[j] = true;\n contained++;\n }\n else {\n errors.push(...result.errors);\n }\n }\n if (contained >= ($minContains || 0)) {\n errors.length = errorsLength;\n }\n if ($minContains === undefined &&\n $maxContains === undefined &&\n contained === 0) {\n errors.splice(errorsLength, 0, {\n instanceLocation,\n keyword: 'contains',\n keywordLocation,\n error: `Array does not contain item matching schema.`\n });\n }\n else if ($minContains !== undefined && contained < $minContains) {\n errors.push({\n instanceLocation,\n keyword: 'minContains',\n keywordLocation: `${schemaLocation}/minContains`,\n error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.`\n });\n }\n else if ($maxContains !== undefined && contained > $maxContains) {\n errors.push({\n instanceLocation,\n keyword: 'maxContains',\n keywordLocation: `${schemaLocation}/maxContains`,\n error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.`\n });\n }\n }\n }\n if (!stop && $unevaluatedItems !== undefined) {\n const keywordLocation = `${schemaLocation}/unevaluatedItems`;\n for (i; i < length; i++) {\n if (evaluated[i]) {\n continue;\n }\n const result = validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);\n evaluated[i] = true;\n if (!result.valid) {\n errors.push({\n instanceLocation,\n keyword: 'unevaluatedItems',\n keywordLocation,\n error: `Items did not match unevaluated items schema.`\n }, ...result.errors);\n }\n }\n }\n if ($uniqueItems) {\n for (let j = 0; j < length; j++) {\n const a = instance[j];\n const ao = typeof a === 'object' && a !== null;\n for (let k = 0; k < length; k++) {\n if (j === k) {\n continue;\n }\n const b = instance[k];\n const bo = typeof b === 'object' && b !== null;\n if (a === b || (ao && bo && deepCompareStrict(a, b))) {\n errors.push({\n instanceLocation,\n keyword: 'uniqueItems',\n keywordLocation: `${schemaLocation}/uniqueItems`,\n error: `Duplicate items at indexes ${j} and ${k}.`\n });\n j = Number.MAX_SAFE_INTEGER;\n k = Number.MAX_SAFE_INTEGER;\n }\n }\n }\n }\n }\n else if (instanceType === 'number') {\n if (draft === '4') {\n if ($minimum !== undefined &&\n (($exclusiveMinimum === true && instance <= $minimum) ||\n instance < $minimum)) {\n errors.push({\n instanceLocation,\n keyword: 'minimum',\n keywordLocation: `${schemaLocation}/minimum`,\n error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.`\n });\n }\n if ($maximum !== undefined &&\n (($exclusiveMaximum === true && instance >= $maximum) ||\n instance > $maximum)) {\n errors.push({\n instanceLocation,\n keyword: 'maximum',\n keywordLocation: `${schemaLocation}/maximum`,\n error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.`\n });\n }\n }\n else {\n if ($minimum !== undefined && instance < $minimum) {\n errors.push({\n instanceLocation,\n keyword: 'minimum',\n keywordLocation: `${schemaLocation}/minimum`,\n error: `${instance} is less than ${$minimum}.`\n });\n }\n if ($maximum !== undefined && instance > $maximum) {\n errors.push({\n instanceLocation,\n keyword: 'maximum',\n keywordLocation: `${schemaLocation}/maximum`,\n error: `${instance} is greater than ${$maximum}.`\n });\n }\n if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) {\n errors.push({\n instanceLocation,\n keyword: 'exclusiveMinimum',\n keywordLocation: `${schemaLocation}/exclusiveMinimum`,\n error: `${instance} is less than ${$exclusiveMinimum}.`\n });\n }\n if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) {\n errors.push({\n instanceLocation,\n keyword: 'exclusiveMaximum',\n keywordLocation: `${schemaLocation}/exclusiveMaximum`,\n error: `${instance} is greater than or equal to ${$exclusiveMaximum}.`\n });\n }\n }\n if ($multipleOf !== undefined) {\n const remainder = instance % $multipleOf;\n if (Math.abs(0 - remainder) >= 1.1920929e-7 &&\n Math.abs($multipleOf - remainder) >= 1.1920929e-7) {\n errors.push({\n instanceLocation,\n keyword: 'multipleOf',\n keywordLocation: `${schemaLocation}/multipleOf`,\n error: `${instance} is not a multiple of ${$multipleOf}.`\n });\n }\n }\n }\n else if (instanceType === 'string') {\n const length = $minLength === undefined && $maxLength === undefined\n ? 0\n : ucs2length(instance);\n if ($minLength !== undefined && length < $minLength) {\n errors.push({\n instanceLocation,\n keyword: 'minLength',\n keywordLocation: `${schemaLocation}/minLength`,\n error: `String is too short (${length} < ${$minLength}).`\n });\n }\n if ($maxLength !== undefined && length > $maxLength) {\n errors.push({\n instanceLocation,\n keyword: 'maxLength',\n keywordLocation: `${schemaLocation}/maxLength`,\n error: `String is too long (${length} > ${$maxLength}).`\n });\n }\n if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) {\n errors.push({\n instanceLocation,\n keyword: 'pattern',\n keywordLocation: `${schemaLocation}/pattern`,\n error: `String does not match pattern.`\n });\n }\n if ($format !== undefined &&\n format[$format] &&\n !format[$format](instance)) {\n errors.push({\n instanceLocation,\n keyword: 'format',\n keywordLocation: `${schemaLocation}/format`,\n error: `String does not match format \"${$format}\".`\n });\n }\n }\n return { valid: errors.length === 0, errors };\n}\n",
12
- "/**\n * WebMCP → MCP mapping of annotations (DEC-022) and results (DEC-023).\n */\n\nimport type { ToolAnnotations } from \"./types.ts\";\n\n/** `_meta` key that keeps the original WebMCP hints. */\nexport const ANNOTATIONS_META_KEY = \"ch.ractive.tab-mcp/annotations\";\n\nconst WEBMCP_HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\nconst MCP_ONLY_HINTS = [\n\t\"destructiveHint\",\n\t\"idempotentHint\",\n\t\"openWorldHint\",\n] as const;\n\nexport interface McpToolAnnotations {\n\tannotations?: Record<string, boolean>;\n\tmeta?: Record<string, boolean>;\n}\n\n/** MCP annotations plus the WebMCP originals for `_meta`. */\nexport function mapAnnotations(hints: ToolAnnotations): McpToolAnnotations {\n\tconst annotations: Record<string, boolean> = {};\n\tif (hints.readOnlyHint === true) {\n\t\tannotations[\"readOnlyHint\"] = true;\n\t\tannotations[\"destructiveHint\"] = false;\n\t} else if (hints.readOnlyHint === false) {\n\t\tannotations[\"readOnlyHint\"] = false;\n\t}\n\tif (hints.consequentialHint === true) annotations[\"destructiveHint\"] = true;\n\tif (hints.untrustedContentHint === true) annotations[\"openWorldHint\"] = true;\n\tfor (const key of MCP_ONLY_HINTS) {\n\t\tconst value = hints[key];\n\t\tif (value !== undefined) annotations[key] = value; // MCP hints win\n\t}\n\tconst meta: Record<string, boolean> = {};\n\tfor (const key of WEBMCP_HINTS) {\n\t\tconst value = hints[key];\n\t\tif (value !== undefined) meta[key] = value;\n\t}\n\tconst out: McpToolAnnotations = {};\n\tif (Object.keys(annotations).length > 0) out.annotations = annotations;\n\tif (Object.keys(meta).length > 0) out.meta = meta;\n\treturn out;\n}\n\nexport interface CallToolResult {\n\tcontent: unknown[];\n\tstructuredContent?: Record<string, unknown>;\n\tisError?: boolean;\n\t[key: string]: unknown;\n}\n\nexport function errorResult(message: string): CallToolResult {\n\treturn { content: [{ type: \"text\", text: message }], isError: true };\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * What `execute` returned → a `CallToolResult`: a string is one text block; an\n * object with a `content` array passes through; `undefined` is an empty\n * result; any other JSON value is a text block with its JSON, plus\n * `structuredContent` when it is an object.\n */\nexport function toCallToolResult(value: unknown): CallToolResult {\n\tif (typeof value === \"string\")\n\t\treturn { content: [{ type: \"text\", text: value }] };\n\tif (value === undefined) return { content: [] };\n\tif (isPlainObject(value) && Array.isArray(value[\"content\"])) {\n\t\treturn value as CallToolResult;\n\t}\n\tlet text: string | undefined;\n\ttry {\n\t\ttext = JSON.stringify(value);\n\t} catch {\n\t\t// cyclic or BigInt\n\t}\n\tif (text === undefined)\n\t\treturn errorResult(\"The tool returned a value that is not JSON.\");\n\tconst result: CallToolResult = { content: [{ type: \"text\", text }] };\n\tif (isPlainObject(value)) result.structuredContent = value;\n\treturn result;\n}\n\n/** A thrown value → an `isError` result with its message. */\nexport function thrownResult(error: unknown): CallToolResult {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn errorResult(message || \"The tool failed.\");\n}\n",
13
- "/**\n * The tab's MCP server: the stateless 2026-07-28 subset tab-mcp needs\n * (DEC-049), written for the page instead of bundling the SDK. It answers\n * `server/discover`, `tools/list`, `tools/call` (as SSE, DEC-020) and\n * `subscriptions/listen`, and applies the request checks of the 2026-07-28\n * Streamable HTTP transport (content type, JSON-RPC shape, `_meta` envelope,\n * `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name`). Status codes and error\n * codes follow the MCP TypeScript SDK's `createMcpHandler`; the conformance\n * tests compare the two.\n */\n\nimport {\n\tdereference,\n\ttype OutputUnit,\n\ttype Schema,\n\tvalidate as validateSchema,\n} from \"@cfworker/json-schema\";\nimport { cleanIcons } from \"./icons.ts\";\nimport {\n\tANNOTATIONS_META_KEY,\n\ttype CallToolResult,\n\terrorResult,\n\tmapAnnotations,\n\tthrownResult,\n\ttoCallToolResult,\n} from \"./mapping.ts\";\nimport type { GrantRef } from \"./protocol.ts\";\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type {\n\tConfirmRequest,\n\tServerInfo,\n\tToolCallClient,\n\tToolCallEnd,\n\tToolCallOutcome,\n\tToolCallStart,\n} from \"./types.ts\";\n\nexport const MCP_PROTOCOL_VERSION = \"2026-07-28\";\nconst META_VERSION = \"io.modelcontextprotocol/protocolVersion\";\nconst META_CAPABILITIES = \"io.modelcontextprotocol/clientCapabilities\";\nconst META_CLIENT_INFO = \"io.modelcontextprotocol/clientInfo\";\nconst META_SERVER_INFO = \"io.modelcontextprotocol/serverInfo\";\nconst META_SUBSCRIPTION = \"io.modelcontextprotocol/subscriptionId\";\n\nconst HEADER_MISMATCH = -32020;\nconst UNSUPPORTED_VERSION = -32022;\n\ntype Id = string | number;\ntype Json = Record<string, unknown>;\n\nexport interface ToolSource {\n\tlist(): RegisteredTool[];\n\tget(name: string): RegisteredTool | undefined;\n}\n\nexport interface McpHandlerOptions {\n\ttools: ToolSource;\n\tserver: ServerInfo;\n\t/** Ask the user before a consequential tool runs. */\n\tconfirm(request: ConfirmRequest): Promise<boolean>;\n\t/** The caller of a request, from its grant. */\n\tclient(grant: GrantRef): ToolCallClient;\n\t/** Told about every call of a known tool, as it starts and as it ends. */\n\tobserve?: {\n\t\tstart(call: ToolCallStart): void;\n\t\tend(call: ToolCallEnd): void;\n\t};\n}\n\n/** Tool call ids, unique in the page. */\nlet lastCallId = 0;\n\n/** Checks arguments against a tool's input schema. */\nexport type ArgumentValidator = (args: unknown) => {\n\tvalid: boolean;\n\terrors: OutputUnit[];\n};\n\nconst compiled = new WeakMap<RegisteredTool, ArgumentValidator>();\n\n/**\n * The validator of a tool's input schema, built once per tool. Throws what\n * the validator would throw at call time: a `$ref` that does not resolve\n * (the validator resolves one only when an argument reaches it, against the\n * base of the nearest `$id`), an `$id` that is not a URL, a duplicate one.\n * `compileRegistry` makes the registry call it at registration (DEC-086).\n */\nexport function compileTool(tool: RegisteredTool): ArgumentValidator {\n\tconst known = compiled.get(tool);\n\tif (known !== undefined) return known;\n\tconst schema = tool.inputSchema as Schema;\n\tlet lookup: Record<string, Schema | boolean>;\n\ttry {\n\t\tlookup = dereference(schema);\n\t} catch (error) {\n\t\t// Only the first line: the validator appends the URIs it knows.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(message.split(\"\\n\")[0]);\n\t}\n\tfor (const node of Object.values(lookup)) {\n\t\tif (typeof node !== \"object\" || node.$ref === undefined) continue;\n\t\tconst absolute = (node as { __absolute_ref__?: string }).__absolute_ref__;\n\t\tif (lookup[absolute ?? node.$ref] === undefined)\n\t\t\tthrow new Error(`$ref ${JSON.stringify(node.$ref)} does not resolve`);\n\t}\n\tconst validator: ArgumentValidator = (args) =>\n\t\tvalidateSchema(args, schema, \"2020-12\", lookup, false);\n\tcompiled.set(tool, validator);\n\treturn validator;\n}\n\nfunction schemaError(name: string, error: unknown, suffix = \"\"): TypeError {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn new TypeError(\n\t\t`registerTool: the inputSchema of ${name}: ${message}${suffix}`,\n\t);\n}\n\n/**\n * The validator is loaded (on `connect()`): compile the schemas of the tools\n * registered so far, before any AI app lists them, and from now on at\n * registration, so that `registerTool` rejects a schema the validator cannot\n * use. A tool registered before that it refuses is unregistered; the errors\n * are for the page's `error` event.\n */\nexport function compileRegistry(registry: ToolRegistry): TypeError[] {\n\tconst refused: TypeError[] = [];\n\tfor (const tool of registry.list()) {\n\t\ttry {\n\t\t\tcompileTool(tool);\n\t\t} catch (error) {\n\t\t\tregistry.remove(tool);\n\t\t\trefused.push(\n\t\t\t\tschemaError(tool.name, error, \"; the tool was unregistered\"),\n\t\t\t);\n\t\t}\n\t}\n\tregistry.setCompiler((tool) => {\n\t\ttry {\n\t\t\tcompileTool(tool);\n\t\t} catch (error) {\n\t\t\tthrow schemaError(tool.name, error);\n\t\t}\n\t});\n\treturn refused;\n}\n\n/** A deep copy for an event; the value itself when it cannot be cloned. */\nfunction copy<T>(value: T): T {\n\ttry {\n\t\treturn structuredClone(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\nexport interface McpRequestContext {\n\tgrant: GrantRef;\n\t/** The body as text when the caller already has it. */\n\tbody?: string;\n}\n\nexport interface McpHandler {\n\thandle(request: Request, context: McpRequestContext): Promise<Response>;\n\t/** The tool list changed: tell the listen streams. */\n\ttoolsChanged(): void;\n\t/** End every listen stream (the session is over). */\n\tclose(): void;\n}\n\nconst encoder = new TextEncoder();\n\nfunction isObject(v: unknown): v is Json {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction json(status: number, value: unknown): Response {\n\treturn new Response(JSON.stringify(value), {\n\t\tstatus,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t});\n}\n\nfunction rpcError(\n\tstatus: number,\n\tid: Id | null,\n\tcode: number,\n\tmessage: string,\n\tdata?: unknown,\n): Response {\n\tconst error: Json = { code, message };\n\tif (data !== undefined) error[\"data\"] = data;\n\treturn json(status, { jsonrpc: \"2.0\", id, error });\n}\n\nfunction mismatch(id: Id | null, header: string, body: string): Response {\n\treturn rpcError(\n\t\t400,\n\t\tid,\n\t\tHEADER_MISMATCH,\n\t\t`Bad Request: the request headers and body disagree: ${body}`,\n\t\t{\n\t\t\tmismatch: { header, body },\n\t\t},\n\t);\n}\n\nfunction sseEvent(message: unknown): Uint8Array {\n\treturn encoder.encode(`event: message\\ndata: ${JSON.stringify(message)}\\n\\n`);\n}\n\nconst SSE_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n};\n\n/** `application/json`, with or without parameters. */\nfunction isJsonContentType(value: string | null): boolean {\n\treturn (\n\t\t(value ?? \"\").split(\";\")[0]?.trim().toLowerCase() === \"application/json\"\n\t);\n}\n\n/** Decode the `=?base64?…?=` sentinel of SEP-2243 headers; `undefined` if malformed. */\nexport function decodeHeaderValue(value: string): string | undefined {\n\tif (!(value.startsWith(\"=?base64?\") && value.endsWith(\"?=\"))) return value;\n\tconst b64 = value.slice(9, -2);\n\tif (\n\t\t!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n\t\t\tb64,\n\t\t)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst bin = atob(b64);\n\t\tconst bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The first problem of a 2026-07-28 `_meta` envelope, or `undefined`. */\nfunction envelopeIssue(\n\tmeta: Json,\n): { key: string; problem: string } | undefined {\n\tif (!(META_VERSION in meta)) return { key: META_VERSION, problem: \"missing\" };\n\tif (!(META_CAPABILITIES in meta))\n\t\treturn { key: META_CAPABILITIES, problem: \"missing\" };\n\tif (typeof meta[META_VERSION] !== \"string\") {\n\t\treturn { key: META_VERSION, problem: \"expected a protocol version string\" };\n\t}\n\tif (!isObject(meta[META_CAPABILITIES]))\n\t\treturn { key: META_CAPABILITIES, problem: \"expected an object\" };\n\tconst info = meta[META_CLIENT_INFO];\n\tif (\n\t\tinfo !== undefined &&\n\t\t!(\n\t\t\tisObject(info) &&\n\t\t\ttypeof info[\"name\"] === \"string\" &&\n\t\t\ttypeof info[\"version\"] === \"string\"\n\t\t)\n\t) {\n\t\treturn { key: META_CLIENT_INFO, problem: \"expected {name, version}\" };\n\t}\n\treturn undefined;\n}\n\n/** Listen streams honour only the tool list (the tab has nothing else). */\nfunction honoured(params: Json): Json {\n\tconst requested = params[\"notifications\"];\n\treturn isObject(requested) && requested[\"toolsListChanged\"] === true\n\t\t? { toolsListChanged: true }\n\t\t: {};\n}\n\nexport function createMcpHandler(options: McpHandlerOptions): McpHandler {\n\tconst { tools, server } = options;\n\tconst serverInfo: Json = { name: server.name, version: server.version };\n\tif (server.title !== undefined) serverInfo[\"title\"] = server.title;\n\t// The icons only in server/discover: every other result carries\n\t// serverInfo too, and the app needs them once.\n\tconst icons = cleanIcons(server.icons ?? []);\n\tconst discoverInfo: Json =\n\t\ticons.length > 0 ? { ...serverInfo, icons } : serverInfo;\n\tconst listeners = new Set<{\n\t\tid: Id;\n\t\tsend(message: unknown): void;\n\t\tend(): void;\n\t}>();\n\tlet changeQueued = false;\n\n\tconst resultMeta = (extra: Json = {}) => ({\n\t\t...extra,\n\t\t[META_SERVER_INFO]: serverInfo,\n\t});\n\n\tfunction result(id: Id, value: Json, meta: Json = resultMeta()): Json {\n\t\treturn {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: { ...value, resultType: \"complete\", _meta: meta },\n\t\t};\n\t}\n\n\tfunction validate(tool: RegisteredTool, args: Json): string | undefined {\n\t\tlet outcome: ReturnType<ArgumentValidator>;\n\t\ttry {\n\t\t\toutcome = compileTool(tool)(args);\n\t\t} catch (error) {\n\t\t\t// Refused at registration through `TabMcp`; this is for any other registry.\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn `The input schema of tool ${tool.name} cannot be used: ${message}`;\n\t\t}\n\t\tif (outcome.valid) return undefined;\n\t\tconst detail = outcome.errors\n\t\t\t.filter((e) => e.keyword !== \"properties\" && e.keyword !== \"$ref\")\n\t\t\t.map((e) => `${e.instanceLocation} ${e.error}`)\n\t\t\t.slice(0, 5)\n\t\t\t.join(\"; \");\n\t\treturn `Input validation error: Invalid arguments for tool ${tool.name}: ${detail || \"the arguments do not match the schema\"}`;\n\t}\n\n\tfunction listTools(): Json[] {\n\t\treturn tools.list().map((tool) => {\n\t\t\tconst entry: Json = { name: tool.name };\n\t\t\tif (tool.title !== undefined) entry[\"title\"] = tool.title;\n\t\t\tentry[\"description\"] = tool.description;\n\t\t\tentry[\"inputSchema\"] = tool.inputSchema;\n\t\t\tconst { annotations, meta } = mapAnnotations(tool.annotations);\n\t\t\tif (annotations !== undefined) entry[\"annotations\"] = annotations;\n\t\t\tif (meta !== undefined) entry[\"_meta\"] = { [ANNOTATIONS_META_KEY]: meta };\n\t\t\treturn entry;\n\t\t});\n\t}\n\n\t/**\n\t * A call's outcome: a JSON-RPC error (`invalid`) or a result. Tagged, so\n\t * that a result's own keys never decide which (a tool may return any).\n\t */\n\ttype RunOutcome =\n\t\t| { kind: \"invalid\"; message: string }\n\t\t| { kind: \"result\"; result: CallToolResult };\n\n\tconst invalidParams = (message: string): RunOutcome => ({\n\t\tkind: \"invalid\",\n\t\tmessage,\n\t});\n\n\tasync function runTool(\n\t\tparams: Json,\n\t\tsignal: AbortSignal,\n\t\tgrant: GrantRef,\n\t): Promise<RunOutcome> {\n\t\tconst name = params[\"name\"];\n\t\tif (typeof name !== \"string\")\n\t\t\treturn invalidParams(\"Invalid params: name must be a string\");\n\t\tconst tool = tools.get(name);\n\t\tif (tool === undefined) return invalidParams(`Tool ${name} not found`);\n\t\tconst raw = params[\"arguments\"] ?? {};\n\t\tif (!isObject(raw))\n\t\t\treturn invalidParams(\"Invalid params: arguments must be an object\");\n\t\tconst client = options.client(grant);\n\t\t// Copies: a listener cannot change what the tool gets or the AI app receives.\n\t\tconst call: ToolCallStart = {\n\t\t\tid: ++lastCallId,\n\t\t\ttool: tool.name,\n\t\t\targuments: copy(raw),\n\t\t\tclient: { ...client },\n\t\t};\n\t\tif (tool.title !== undefined) call.title = tool.title;\n\t\tconst started = Date.now();\n\t\toptions.observe?.start(call);\n\t\t// Every start has its end, also when something fails outside the tool.\n\t\tlet outcome: ToolCallOutcome = \"error\";\n\t\tlet res: CallToolResult = errorResult(\"Internal error\");\n\t\ttry {\n\t\t\t[outcome, res] = await decideAndRun(tool, raw, signal, client);\n\t\t} finally {\n\t\t\toptions.observe?.end({\n\t\t\t\tid: call.id,\n\t\t\t\ttool: tool.name,\n\t\t\t\tclient: { ...client },\n\t\t\t\toutcome,\n\t\t\t\tresult: copy(res),\n\t\t\t\tdurationMs: Date.now() - started,\n\t\t\t});\n\t\t}\n\t\treturn { kind: \"result\", result: res };\n\t}\n\n\t/** Validate, confirm and run one call. */\n\tasync function decideAndRun(\n\t\ttool: RegisteredTool,\n\t\traw: Json,\n\t\tsignal: AbortSignal,\n\t\tclient: ToolCallClient,\n\t): Promise<[ToolCallOutcome, CallToolResult]> {\n\t\tconst invalid = validate(tool, raw);\n\t\tif (invalid !== undefined) return [\"error\", errorResult(invalid)];\n\t\tif (tool.annotations.consequentialHint === true) {\n\t\t\tconst question: ConfirmRequest = {\n\t\t\t\ttool: { name: tool.name, description: tool.description },\n\t\t\t\targuments: raw,\n\t\t\t\tclient,\n\t\t\t\tsignal,\n\t\t\t};\n\t\t\tif (tool.title !== undefined) question.tool.title = tool.title;\n\t\t\tlet allowed = false;\n\t\t\ttry {\n\t\t\t\tallowed = await options.confirm(question);\n\t\t\t} catch {\n\t\t\t\tallowed = false;\n\t\t\t}\n\t\t\tif (!allowed)\n\t\t\t\treturn [\n\t\t\t\t\tsignal.aborted ? \"cancelled\" : \"declined\",\n\t\t\t\t\terrorResult(\"The user declined\"),\n\t\t\t\t];\n\t\t}\n\t\tif (signal.aborted) return [\"cancelled\", errorResult(\"Cancelled\")];\n\t\t// Unregistered (or replaced) while the user was asked: not the tool\n\t\t// the user allowed, or one the page still offers.\n\t\tif (tools.get(tool.name) !== tool)\n\t\t\treturn [\"error\", errorResult(\"The tool is no longer available\")];\n\t\tlet res: CallToolResult;\n\t\ttry {\n\t\t\tres = toCallToolResult(await tool.execute(raw, { signal, client }));\n\t\t} catch (error) {\n\t\t\tres = thrownResult(error);\n\t\t}\n\t\t// Cancelled is cancelled, however the tool answered the abort.\n\t\tif (signal.aborted) return [\"cancelled\", res];\n\t\treturn [res.isError === true ? \"error\" : \"ok\", res];\n\t}\n\n\tfunction callTool(\n\t\tid: Id,\n\t\tparams: Json,\n\t\tsignal: AbortSignal,\n\t\tgrant: GrantRef,\n\t): Response {\n\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\tstart: (controller) => {\n\t\t\t\t/** Send the one answer and end the stream, whatever happens. */\n\t\t\t\tconst finish = (message: unknown) => {\n\t\t\t\t\tif (signal.aborted) return; // nobody listens any more\n\t\t\t\t\tlet event: Uint8Array;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tevent = sseEvent(message);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// e.g. a BigInt or a cycle inside a passed-through result\n\t\t\t\t\t\tevent = sseEvent(\n\t\t\t\t\t\t\tresult(\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\terrorResult(\"The tool returned a result that is not JSON.\"),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontroller.enqueue(event);\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// the stream was cancelled meanwhile\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\trunTool(params, signal, grant).then(\n\t\t\t\t\t(outcome) =>\n\t\t\t\t\t\tfinish(\n\t\t\t\t\t\t\toutcome.kind === \"invalid\"\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\terror: { code: -32602, message: outcome.message },\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: result(id, outcome.result),\n\t\t\t\t\t\t),\n\t\t\t\t\t() =>\n\t\t\t\t\t\tfinish({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\terror: { code: -32603, message: \"Internal error\" },\n\t\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t\treturn new Response(stream, { status: 200, headers: SSE_HEADERS });\n\t}\n\n\tfunction listen(id: Id, params: Json, signal: AbortSignal): Response {\n\t\tconst notifications = honoured(params);\n\t\tconst finalResult = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: {\n\t\t\t\tresultType: \"complete\",\n\t\t\t\t_meta: resultMeta({ [META_SUBSCRIPTION]: id }),\n\t\t\t},\n\t\t};\n\t\t// This stream's own listener: two AI apps may both use the same id.\n\t\tlet own: { id: Id; send(m: unknown): void; end(): void } | undefined;\n\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\tstart: (controller) => {\n\t\t\t\tcontroller.enqueue(\n\t\t\t\t\tsseEvent({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tmethod: \"notifications/subscriptions/acknowledged\",\n\t\t\t\t\t\tparams: { notifications, _meta: { [META_SUBSCRIPTION]: id } },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tif (Object.keys(notifications).length === 0) {\n\t\t\t\t\tcontroller.enqueue(sseEvent(finalResult));\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst listener = {\n\t\t\t\t\tid,\n\t\t\t\t\tsend: (message: unknown) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(sseEvent(message));\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tend: () => {\n\t\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(sseEvent(finalResult));\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// already cancelled\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\town = listener;\n\t\t\t\tlisteners.add(listener);\n\t\t\t\tsignal.addEventListener(\"abort\", () => {\n\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// already closed\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tif (own !== undefined) listeners.delete(own);\n\t\t\t},\n\t\t});\n\t\treturn new Response(stream, { status: 200, headers: SSE_HEADERS });\n\t}\n\n\t/** The request checks; a `Response` when the request is refused. */\n\tfunction check(\n\t\trequest: Request,\n\t\tbody: unknown,\n\t): Response | { id: Id; method: string; params: Json } | \"notification\" {\n\t\tif (Array.isArray(body)) {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: JSON-RPC batches are not supported by this endpoint\",\n\t\t\t);\n\t\t}\n\t\tif (!isObject(body) || body[\"jsonrpc\"] !== \"2.0\") {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t);\n\t\t}\n\t\tconst method = body[\"method\"];\n\t\tconst rawId = body[\"id\"];\n\t\tif (typeof method !== \"string\") {\n\t\t\treturn \"result\" in body || \"error\" in body\n\t\t\t\t? rpcError(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t\"Bad Request: JSON-RPC responses cannot be posted to this endpoint\",\n\t\t\t\t\t)\n\t\t\t\t: rpcError(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t\t\t);\n\t\t}\n\t\tconst headerVersion = request.headers.get(\"mcp-protocol-version\");\n\t\tconst headerMethod = request.headers.get(\"mcp-method\");\n\t\tconst params = isObject(body[\"params\"]) ? body[\"params\"] : {};\n\t\tconst meta = isObject(params[\"_meta\"]) ? params[\"_meta\"] : undefined;\n\t\tconst claim = meta !== undefined && META_VERSION in meta;\n\t\tconst claimed =\n\t\t\ttypeof meta?.[META_VERSION] === \"string\"\n\t\t\t\t? (meta[META_VERSION] as string)\n\t\t\t\t: undefined;\n\t\tconst headerModern =\n\t\t\theaderVersion !== null && headerVersion >= MCP_PROTOCOL_VERSION;\n\n\t\tif (rawId === undefined) {\n\t\t\t// A notification: nothing to answer, but the headers must agree.\n\t\t\tif (\n\t\t\t\tclaimed !== undefined &&\n\t\t\t\theaderVersion !== null &&\n\t\t\t\theaderVersion !== claimed\n\t\t\t) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tnull,\n\t\t\t\t\theaderVersion,\n\t\t\t\t\t`the notification envelope names protocol version ${claimed} but the MCP-Protocol-Version header names ${headerVersion}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(claim || headerModern) &&\n\t\t\t\theaderMethod !== null &&\n\t\t\t\theaderMethod !== method\n\t\t\t) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tnull,\n\t\t\t\t\theaderMethod,\n\t\t\t\t\t`the notification body names method ${method} but the Mcp-Method header names ${headerMethod}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn \"notification\";\n\t\t}\n\t\tif (typeof rawId !== \"string\" && typeof rawId !== \"number\") {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t);\n\t\t}\n\t\tconst id = rawId;\n\t\tif (\n\t\t\t!claim ||\n\t\t\t(method === \"initialize\" &&\n\t\t\t\t(claimed === undefined || claimed < MCP_PROTOCOL_VERSION))\n\t\t) {\n\t\t\tif (method === \"initialize\") {\n\t\t\t\tif (headerModern) {\n\t\t\t\t\treturn mismatch(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\theaderVersion,\n\t\t\t\t\t\t\"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst requested =\n\t\t\t\t\ttypeof params[\"protocolVersion\"] === \"string\"\n\t\t\t\t\t\t? params[\"protocolVersion\"]\n\t\t\t\t\t\t: undefined;\n\t\t\t\treturn unsupported(id, requested);\n\t\t\t}\n\t\t\tif (headerModern) {\n\t\t\t\tconst missing = meta === undefined ? [\"_meta\"] : [META_VERSION];\n\t\t\t\treturn rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\t-32602,\n\t\t\t\t\t`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(\", \")}`,\n\t\t\t\t\t{ envelope: { missing } },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn unsupported(id, headerVersion ?? undefined);\n\t\t}\n\t\tconst issue = envelopeIssue(meta);\n\t\tif (issue !== undefined) {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tid,\n\t\t\t\t-32602,\n\t\t\t\t`Invalid _meta envelope for protocol revision ${MCP_PROTOCOL_VERSION}: ${issue.key}: ${issue.problem}`,\n\t\t\t\t{ envelope: issue },\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\theaderVersion !== null &&\n\t\t\tclaimed !== undefined &&\n\t\t\theaderVersion !== claimed\n\t\t) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\theaderVersion,\n\t\t\t\t`the body envelope names protocol version ${claimed} but the MCP-Protocol-Version header names ${headerVersion}`,\n\t\t\t);\n\t\t}\n\t\tif (headerMethod !== null && headerMethod !== method) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\theaderMethod,\n\t\t\t\t`the body names method ${method} but the Mcp-Method header names ${headerMethod}`,\n\t\t\t);\n\t\t}\n\t\tif (claimed !== MCP_PROTOCOL_VERSION) return unsupported(id, claimed);\n\t\tif (headerVersion === null) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\t\"(missing)\",\n\t\t\t\t`the body envelope names protocol version ${claimed} but the required MCP-Protocol-Version header is absent`,\n\t\t\t);\n\t\t}\n\t\tif (headerMethod === null) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\t\"(missing)\",\n\t\t\t\t`the body names method ${method} but the required Mcp-Method header is absent`,\n\t\t\t);\n\t\t}\n\t\tif (method === \"tools/call\" && typeof params[\"name\"] === \"string\") {\n\t\t\tconst name = params[\"name\"];\n\t\t\tconst header = request.headers.get(\"mcp-name\");\n\t\t\tif (header === null) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\t\"(missing)\",\n\t\t\t\t\t`the body carries params.name=\"${name}\" but the required Mcp-Name header is absent`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst decoded = decodeHeaderValue(header);\n\t\t\tif (decoded === undefined) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\theader,\n\t\t\t\t\t\"the Mcp-Name header carries an invalid Base64 sentinel value\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (decoded !== name) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\theader,\n\t\t\t\t\t`the body carries params.name=\"${name}\" but the Mcp-Name header names \"${decoded}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { id, method, params };\n\t}\n\n\tfunction unsupported(id: Id, requested: string | undefined): Response {\n\t\treturn requested === undefined\n\t\t\t? rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\tUNSUPPORTED_VERSION,\n\t\t\t\t\t\"Unsupported protocol version: the request did not name a protocol version\",\n\t\t\t\t\t{ supported: [MCP_PROTOCOL_VERSION] },\n\t\t\t\t)\n\t\t\t: rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\tUNSUPPORTED_VERSION,\n\t\t\t\t\t`Unsupported protocol version: ${requested}`,\n\t\t\t\t\t{ supported: [MCP_PROTOCOL_VERSION], requested },\n\t\t\t\t);\n\t}\n\n\tasync function handle(\n\t\trequest: Request,\n\t\tcontext: McpRequestContext,\n\t): Promise<Response> {\n\t\tif (request.method.toUpperCase() !== \"POST\")\n\t\t\treturn rpcError(405, null, -32000, \"Method not allowed.\");\n\t\tif (!isJsonContentType(request.headers.get(\"content-type\"))) {\n\t\t\treturn rpcError(\n\t\t\t\t415,\n\t\t\t\tnull,\n\t\t\t\t-32000,\n\t\t\t\t\"Unsupported Media Type: Content-Type must be application/json\",\n\t\t\t);\n\t\t}\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = JSON.parse(context.body ?? (await request.text()));\n\t\t} catch {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32700,\n\t\t\t\t\"Parse error: the request body is not valid JSON\",\n\t\t\t);\n\t\t}\n\t\tconst checked = check(request, body);\n\t\tif (checked instanceof Response) return checked;\n\t\tif (checked === \"notification\") return new Response(null, { status: 202 });\n\t\tconst { id, method, params } = checked;\n\t\tswitch (method) {\n\t\t\tcase \"server/discover\": {\n\t\t\t\tconst discover: Json = {\n\t\t\t\t\tsupportedVersions: [MCP_PROTOCOL_VERSION],\n\t\t\t\t\tcapabilities: { tools: { listChanged: true } },\n\t\t\t\t};\n\t\t\t\tif (server.instructions !== undefined)\n\t\t\t\t\tdiscover[\"instructions\"] = server.instructions;\n\t\t\t\tdiscover[\"ttlMs\"] = 0;\n\t\t\t\tdiscover[\"cacheScope\"] = \"private\";\n\t\t\t\treturn json(\n\t\t\t\t\t200,\n\t\t\t\t\tresult(id, discover, { [META_SERVER_INFO]: discoverInfo }),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase \"tools/list\":\n\t\t\t\treturn json(\n\t\t\t\t\t200,\n\t\t\t\t\tresult(id, { tools: listTools(), ttlMs: 0, cacheScope: \"private\" }),\n\t\t\t\t);\n\t\t\tcase \"tools/call\":\n\t\t\t\treturn callTool(id, params, request.signal, context.grant);\n\t\t\tcase \"subscriptions/listen\":\n\t\t\t\treturn listen(id, params, request.signal);\n\t\t\tdefault:\n\t\t\t\treturn rpcError(404, id, -32601, \"Method not found\");\n\t\t}\n\t}\n\n\treturn {\n\t\thandle: (request, context) =>\n\t\t\thandle(request, context).catch(() =>\n\t\t\t\trpcError(500, null, -32603, \"Internal server error\"),\n\t\t\t),\n\t\ttoolsChanged() {\n\t\t\tif (changeQueued) return;\n\t\t\tchangeQueued = true;\n\t\t\t// Several registrations in one task produce one notification.\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tchangeQueued = false;\n\t\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t\tlistener.send({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tmethod: \"notifications/tools/list_changed\",\n\t\t\t\t\t\tparams: { _meta: { [META_SUBSCRIPTION]: listener.id } },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tfor (const listener of [...listeners]) listener.end();\n\t\t},\n\t};\n}\n",
14
- "/**\n * The tab↔relay protocol, version 1, as the tab speaks it\n * (`kb/design/protocol.md`). Internal: not part of the public API.\n */\n\nimport type { Grant, Limits } from \"./types.ts\";\n\nexport const SUBPROTOCOL = \"tab-mcp.v1\";\n\n/** Who is calling a tunnelled request (the relay's view of the grant). */\nexport interface GrantRef {\n\tgrantId: string;\n\tclientId: string;\n\tscopes: string[];\n}\n\n// Relay → tab\n\nexport interface SessionMessage {\n\ttype: \"session\";\n\tsessionId: string;\n\taddress: string;\n\torigin: string;\n\tappName?: string;\n\t/** How AI apps pair: `code` or `oidc` (identity binding). Older relays omit it. */\n\tpairing?: \"code\" | \"oidc\";\n\texpiresAt: string;\n\tlimits: Limits;\n\tgrants: Grant[];\n}\nexport interface PingMessage {\n\ttype: \"ping\";\n\tt: number;\n}\nexport interface ByeMessage {\n\ttype: \"bye\";\n\treason: string;\n}\nexport interface HttpRequestMessage {\n\ttype: \"http.request\";\n\tid: string;\n\tmethod: string;\n\tpath: string;\n\theaders: Record<string, string>;\n\tbody: string;\n\tgrant: GrantRef;\n}\nexport interface HttpCancelMessage {\n\ttype: \"http.cancel\";\n\tid: string;\n\treason: string;\n}\nexport interface PairingCodeMessage {\n\ttype: \"pairing.code\";\n\tcode: string;\n\texpiresAt: string;\n}\nexport interface GrantAddedMessage {\n\ttype: \"grant.added\";\n\tgrant: Grant;\n}\nexport interface GrantRemovedMessage {\n\ttype: \"grant.removed\";\n\tgrantId: string;\n\treason: string;\n}\nexport interface IdentityBoundMessage {\n\ttype: \"identity.bound\";\n\t/** The `round` of the `identity` this answers. */\n\tround?: number;\n}\nexport interface ErrorMessage {\n\ttype: \"error\";\n\tcode: string;\n\tmessage: string;\n\tid?: string;\n\t/** On `identity_refused`: the `round` of the `identity` it answers. */\n\tround?: number;\n}\nexport type RelayMessage =\n\t| SessionMessage\n\t| PingMessage\n\t| ByeMessage\n\t| HttpRequestMessage\n\t| HttpCancelMessage\n\t| PairingCodeMessage\n\t| GrantAddedMessage\n\t| GrantRemovedMessage\n\t| IdentityBoundMessage\n\t| ErrorMessage;\n\n// Tab → relay\n\nexport type TabMessage =\n\t| {\n\t\t\ttype: \"hello\";\n\t\t\tlibrary: { name: string; version: string };\n\t\t\tpage: { title: string };\n\t\t\tapp?: { name: string };\n\t\t\tsecret: string;\n\t\t\t/** Take the address back: the relay revokes its grants as it claims it (DEC-095). */\n\t\t\trevokeAll?: true;\n\t }\n\t| { type: \"pong\"; t: number }\n\t| { type: \"bye\"; reason: string }\n\t| {\n\t\t\ttype: \"http.response\";\n\t\t\tid: string;\n\t\t\tstatus: number;\n\t\t\theaders: Record<string, string>;\n\t\t\tbody: string;\n\t }\n\t| {\n\t\t\ttype: \"http.response.start\";\n\t\t\tid: string;\n\t\t\tstatus: number;\n\t\t\theaders: Record<string, string>;\n\t }\n\t| { type: \"http.response.chunk\"; id: string; data: string }\n\t| { type: \"http.response.end\"; id: string }\n\t| { type: \"pairing.start\" }\n\t| { type: \"pairing.stop\" }\n\t| { type: \"grant.revoke\"; grantId: string }\n\t| { type: \"grants.revokeAll\" }\n\t| { type: \"identity\"; assertion: string; round: number }\n\t| { type: \"identity.logout\" }\n\t| { type: \"error\"; code: string; message: string; id?: string };\n\ntype Json = Record<string, unknown>;\n\nfunction isObject(v: unknown): v is Json {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nconst str = (v: unknown): v is string => typeof v === \"string\";\n\nfunction isGrant(v: unknown): v is Grant {\n\tif (!isObject(v) || !str(v[\"grantId\"]) || !str(v[\"createdAt\"])) return false;\n\tconst c = v[\"client\"];\n\treturn isObject(c) && str(c[\"id\"]) && str(c[\"name\"]) && str(c[\"host\"]);\n}\n\nfunction isLimits(v: unknown): v is Limits {\n\tif (!isObject(v)) return false;\n\treturn [\n\t\t\"maxMessageBytes\",\n\t\t\"maxBodyBytes\",\n\t\t\"requestTimeoutMs\",\n\t\t\"idleTimeoutMs\",\n\t\t\"heartbeatMs\",\n\t\t\"keepAliveMs\",\n\t\t\"maxConcurrentRequests\",\n\t].every((k) => typeof v[k] === \"number\");\n}\n\nfunction isStringRecord(v: unknown): v is Record<string, string> {\n\treturn isObject(v) && Object.values(v).every(str);\n}\n\n/**\n * Parse one frame from the relay. Returns `undefined` for anything malformed\n * or unknown; the caller ignores it (forward compatibility).\n */\nexport function parseRelayMessage(text: string): RelayMessage | undefined {\n\tlet v: unknown;\n\ttry {\n\t\tv = JSON.parse(text);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isObject(v)) return undefined;\n\tswitch (v[\"type\"]) {\n\t\tcase \"session\":\n\t\t\treturn str(v[\"sessionId\"]) &&\n\t\t\t\tstr(v[\"address\"]) &&\n\t\t\t\tstr(v[\"origin\"]) &&\n\t\t\t\tstr(v[\"expiresAt\"]) &&\n\t\t\t\tisLimits(v[\"limits\"]) &&\n\t\t\t\tArray.isArray(v[\"grants\"]) &&\n\t\t\t\tv[\"grants\"].every(isGrant) &&\n\t\t\t\t(v[\"appName\"] === undefined || str(v[\"appName\"])) &&\n\t\t\t\t(v[\"pairing\"] === undefined || str(v[\"pairing\"]))\n\t\t\t\t? (v as unknown as SessionMessage)\n\t\t\t\t: undefined;\n\t\tcase \"ping\":\n\t\t\treturn typeof v[\"t\"] === \"number\"\n\t\t\t\t? (v as unknown as PingMessage)\n\t\t\t\t: undefined;\n\t\tcase \"bye\":\n\t\t\treturn { type: \"bye\", reason: str(v[\"reason\"]) ? v[\"reason\"] : \"\" };\n\t\tcase \"http.request\":\n\t\t\treturn str(v[\"id\"]) &&\n\t\t\t\tstr(v[\"method\"]) &&\n\t\t\t\tstr(v[\"path\"]) &&\n\t\t\t\tisStringRecord(v[\"headers\"]) &&\n\t\t\t\tstr(v[\"body\"]) &&\n\t\t\t\tisObject(v[\"grant\"]) &&\n\t\t\t\tstr(v[\"grant\"][\"grantId\"]) &&\n\t\t\t\tstr(v[\"grant\"][\"clientId\"])\n\t\t\t\t? (v as unknown as HttpRequestMessage)\n\t\t\t\t: undefined;\n\t\tcase \"http.cancel\":\n\t\t\treturn str(v[\"id\"]) ? (v as unknown as HttpCancelMessage) : undefined;\n\t\tcase \"pairing.code\":\n\t\t\treturn str(v[\"code\"]) && str(v[\"expiresAt\"])\n\t\t\t\t? (v as unknown as PairingCodeMessage)\n\t\t\t\t: undefined;\n\t\tcase \"grant.added\":\n\t\t\treturn isGrant(v[\"grant\"])\n\t\t\t\t? (v as unknown as GrantAddedMessage)\n\t\t\t\t: undefined;\n\t\tcase \"grant.removed\":\n\t\t\treturn str(v[\"grantId\"])\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"grant.removed\",\n\t\t\t\t\t\tgrantId: v[\"grantId\"],\n\t\t\t\t\t\treason: str(v[\"reason\"]) ? v[\"reason\"] : \"\",\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tcase \"identity.bound\":\n\t\t\treturn typeof v[\"round\"] === \"number\"\n\t\t\t\t? { type: \"identity.bound\", round: v[\"round\"] }\n\t\t\t\t: { type: \"identity.bound\" };\n\t\tcase \"error\":\n\t\t\treturn str(v[\"code\"]) ? (v as unknown as ErrorMessage) : undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n",
15
- "/**\n * The address id in the `/tab` URL (DEC-098): a load balancer in front of\n * several relays routes every request of one address to one instance by it.\n * Part of the lazily loaded chunk (DEC-035), not the core.\n */\n\nconst BASE32 = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/** RFC 4648 base32, lower case, without padding (the relay's address ids). */\nfunction base32(bytes: Uint8Array): string {\n\tlet out = \"\";\n\tlet buffer = 0;\n\tlet bits = 0;\n\tfor (const byte of bytes) {\n\t\tbuffer = (buffer << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tbits -= 5;\n\t\t\tout += BASE32[(buffer >>> bits) & 31];\n\t\t}\n\t\tbuffer &= (1 << bits) - 1;\n\t}\n\tif (bits > 0) out += BASE32[(buffer << (5 - bits)) & 31];\n\treturn out;\n}\n\n/**\n * The address id of a secret, as the relay derives it (DEC-027):\n * base32(sha256(secret)). `undefined` where Web Crypto is missing (`null`: a\n * page on plain http other than localhost) or fails; the URL then has no id,\n * which one relay accepts and only a load balancer cannot route.\n */\nexport async function addressIdOf(\n\tsecret: string,\n\tsubtle: SubtleCrypto | null = globalThis.crypto?.subtle ?? null,\n): Promise<string | undefined> {\n\tif (subtle === null) return undefined;\n\ttry {\n\t\tconst digest = await subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tnew TextEncoder().encode(secret),\n\t\t);\n\t\treturn base32(new Uint8Array(digest));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The `/tab` URL with `?a=<id>`. Never the secret: URLs end up in logs. */\nexport function withAddress(url: string, address: string | undefined): string {\n\tif (address === undefined) return url;\n\tconst u = new URL(url);\n\tu.searchParams.set(\"a\", address);\n\treturn u.href;\n}\n",
16
- "/**\n * The lazily loaded part (DEC-035): the WebSocket session with the relay, the\n * HTTP tunnel and the MCP handler. Loaded by `TabMcp.connect()`.\n */\n\nimport { pageIcons } from \"./icons.ts\";\nimport type { ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport { createMcpHandler } from \"./mcp.ts\";\nimport {\n\ttype HttpRequestMessage,\n\tparseRelayMessage,\n\ttype RelayMessage,\n\tSUBPROTOCOL,\n\ttype TabMessage,\n} from \"./protocol.ts\";\nimport type { DisconnectReason, SessionInfo } from \"./types.ts\";\n\n/** For the core: the address id in the `/tab` URL (DEC-098). */\nexport { addressIdOf, withAddress } from \"./address.ts\";\n/** For the core: compiles the schemas once this chunk (and the validator) is loaded. */\nexport { compileRegistry } from \"./mcp.ts\";\n\n/** How long `connect()` waits for the relay's `session`. */\nconst CONNECT_TIMEOUT_MS = 15_000;\n\nconst CLOSE_REASONS: Record<number, DisconnectReason> = {\n\t1000: \"closed\",\n\t1008: \"policy\",\n\t1009: \"too_large\",\n\t4001: \"expired\",\n\t4002: \"idle\",\n\t4003: \"heartbeat\",\n\t4004: \"shutdown\",\n\t4005: \"replaced\",\n\t4008: \"rate_limited\",\n\t/** The URL's address id is not the secret's (DEC-098): retrying cannot help. */\n\t4009: \"policy\",\n};\n\nconst BYE_REASONS: Record<string, DisconnectReason> = {\n\treplaced: \"replaced\",\n\texpired: \"expired\",\n\tidle: \"idle\",\n\tshutdown: \"shutdown\",\n};\n\n/**\n * An error of `ready` that says why the connection did not open, so that\n * reconnecting retries only what may get better (DEC-082).\n */\nfunction refused(message: string, reason: DisconnectReason): Error {\n\treturn Object.assign(new Error(message), { reason });\n}\n\n/** Response headers the relay passes on (it drops the rest). */\nconst RESPONSE_HEADERS = [\"content-type\", \"cache-control\"];\n\nfunction pageTitle(): string {\n\tconst title = (globalThis as { document?: { title?: unknown } }).document\n\t\t?.title;\n\treturn typeof title === \"string\" ? title.slice(0, 300) : \"\";\n}\n\nfunction frameInfo(text: string): { type: string; id?: string } | undefined {\n\ttry {\n\t\tconst v = JSON.parse(text) as Record<string, unknown>;\n\t\tif (typeof v !== \"object\" || v === null || typeof v[\"type\"] !== \"string\")\n\t\t\treturn undefined;\n\t\treturn typeof v[\"id\"] === \"string\"\n\t\t\t? { type: v[\"type\"], id: v[\"id\"] }\n\t\t\t: { type: v[\"type\"] };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nconst KNOWN_TYPES = new Set([\n\t\"session\",\n\t\"ping\",\n\t\"bye\",\n\t\"http.request\",\n\t\"http.cancel\",\n\t\"pairing.code\",\n\t\"grant.added\",\n\t\"grant.removed\",\n\t\"identity.bound\",\n\t\"error\",\n]);\n\n/**\n * Room for a message's envelope (`http.response` with its headers, or a\n * chunk) with an id of up to 128 characters (protocol limit).\n */\nconst ENVELOPE_BYTES = 512;\n/** Worst case per UTF-16 unit once JSON-encoded as UTF-8: `\\u0001` is 6 bytes. */\nconst WORST_BYTES_PER_UNIT = 6;\nconst MIN_CHUNK_UNITS = 64;\nexport const MIN_MESSAGE_BYTES: number =\n\tENVELOPE_BYTES + WORST_BYTES_PER_UNIT * MIN_CHUNK_UNITS;\n\n/**\n * The largest piece of body text (UTF-16 units) whose message cannot exceed\n * the relay's `maxMessageBytes`; `undefined` if the limit is too small to\n * frame anything useful.\n */\nexport function chunkSize(maxMessageBytes: number): number | undefined {\n\tconst units = Math.floor(\n\t\t(maxMessageBytes - ENVELOPE_BYTES) / WORST_BYTES_PER_UNIT,\n\t);\n\treturn units >= MIN_CHUNK_UNITS ? units : undefined;\n}\n\n/**\n * Split text into pieces of at most `max` UTF-16 units, never between the two\n * halves of a surrogate pair (a lone half would not survive JSON and UTF-8).\n */\nexport function* pieces(text: string, max: number): Generator<string> {\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tlet end = Math.min(i + max, text.length);\n\t\tconst last = text.charCodeAt(end - 1);\n\t\tif (end < text.length && last >= 0xd800 && last <= 0xdbff) {\n\t\t\tend += end - 1 > i ? -1 : 1; // keep the pair together\n\t\t}\n\t\tyield text.slice(i, end);\n\t\ti = end;\n\t}\n}\n\n/**\n * How long after a sibling tab's `claimed` a `replaced` counts as caused by\n * it (DEC-095). That tab posts it when the relay accepted its session, which\n * is when the relay ended this one.\n */\nexport const SIBLING_WINDOW_MS = 10_000;\n\n/**\n * How long a replaced tab that heard no `claimed` yet waits for one before it\n * reports `replaced`: the sibling's session and this tab's `bye` leave the\n * relay at about the same time, so the message usually comes after the `bye`.\n */\nexport const SIBLING_GRACE_MS = 1_000;\n\n/**\n * The tabs of one page (same relay, same secret) tell each other on a\n * `BroadcastChannel` when the relay accepted their claim of the address\n * (`claimed`, once their `session` arrived), so that a replaced tab can tell\n * a sibling from an impostor. A sibling whose `hello` failed says nothing.\n * Nothing else goes on the channel: no secret, no address. Without\n * `BroadcastChannel` nothing is heard, and every `replaced` counts as unknown.\n */\nfunction siblingTabs(name: string | undefined): {\n\tclaimed(): void;\n\t/** `true` once `claimed` was heard in the window, `false` after the grace. */\n\theard(): Promise<boolean>;\n\tclose(): void;\n} {\n\tlet channel: BroadcastChannel | undefined;\n\tlet at = Number.NEGATIVE_INFINITY;\n\tlet onClaim: (() => void) | undefined;\n\ttry {\n\t\tif (name !== undefined && typeof BroadcastChannel === \"function\") {\n\t\t\tchannel = new BroadcastChannel(name);\n\t\t\tchannel.onmessage = (event: MessageEvent) => {\n\t\t\t\tif ((event.data as { type?: unknown } | null)?.type !== \"claimed\")\n\t\t\t\t\treturn;\n\t\t\t\tat = Date.now();\n\t\t\t\tonClaim?.();\n\t\t\t};\n\t\t}\n\t} catch {\n\t\tchannel = undefined; // e.g. an opaque origin\n\t}\n\treturn {\n\t\tclaimed() {\n\t\t\ttry {\n\t\t\t\tchannel?.postMessage({ type: \"claimed\" });\n\t\t\t} catch {\n\t\t\t\t// closed or not allowed: the other tab counts it as unknown\n\t\t\t}\n\t\t},\n\t\theard() {\n\t\t\tif (Date.now() - at <= SIBLING_WINDOW_MS) return Promise.resolve(true);\n\t\t\tif (channel === undefined) return Promise.resolve(false);\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => resolve(false), SIBLING_GRACE_MS);\n\t\t\t\tonClaim = () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(true);\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tchannel?.close();\n\t\t},\n\t};\n}\n\n/**\n * Open the WebSocket and run the session. `revokeAll`: take the address back\n * (DEC-095); `ready` resolves only once the relay has no grant of the address\n * left, and rejects if the session ends first.\n */\nexport function openConnection(\n\thost: ConnectionHost,\n\turl: string,\n\tsecret: string,\n\trevokeAll = false,\n): ConnectionHandle {\n\tconst ws = new WebSocket(url, SUBPROTOCOL);\n\tconst inflight = new Map<string, AbortController>();\n\tlet state: \"opening\" | \"ready\" | \"closed\" = \"opening\";\n\tlet byeReason: DisconnectReason | undefined;\n\tlet maxChunk = 64 * 1024;\n\tlet heartbeat: ReturnType<typeof setTimeout> | undefined;\n\tlet heartbeatMs = 0;\n\tconst siblings = siblingTabs(host.tabs);\n\t/**\n\t * Taking the address back from a relay that ignored `hello.revokeAll` (0.4\n\t * and older): the grants still to go after `grants.revokeAll`, and the\n\t * session to resolve with then.\n\t */\n\tlet revoking: { left: Set<string>; session: SessionInfo } | undefined;\n\n\tlet resolveReady!: (session: SessionInfo) => void;\n\tlet rejectReady!: (error: Error) => void;\n\tconst ready = new Promise<SessionInfo>((resolve, reject) => {\n\t\tresolveReady = resolve;\n\t\trejectReady = reject;\n\t});\n\tready.catch(() => {}); // the caller handles it; never an unhandled rejection here\n\tconst connectTimer = setTimeout(() => {\n\t\tfail(refused(\"The relay did not answer in time.\", \"network\"));\n\t}, CONNECT_TIMEOUT_MS);\n\n\tconst handler = createMcpHandler({\n\t\ttools: host.registry,\n\t\t// Without `icons`, the page's own <link rel=\"icon\">, read now.\n\t\tserver: { ...host.server, icons: host.server.icons ?? pageIcons() },\n\t\tconfirm: (request) => host.confirm(request),\n\t\tclient: (grant) => host.clientFor(grant),\n\t\tobserve: {\n\t\t\tstart: (call) => host.toolCallStarted(call),\n\t\t\tend: (call) => host.toolCallEnded(call),\n\t\t},\n\t});\n\tconst stopWatching = host.registry.onChange(() => handler.toolsChanged());\n\n\tfunction send(message: TabMessage): boolean {\n\t\tif (ws.readyState !== WebSocket.OPEN) return false;\n\t\ttry {\n\t\t\tws.send(JSON.stringify(message));\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Two missed pings mean the connection is dead (protocol: heartbeat). */\n\tfunction armHeartbeat(): void {\n\t\tif (heartbeatMs <= 0) return;\n\t\tclearTimeout(heartbeat);\n\t\theartbeat = setTimeout(() => {\n\t\t\tbyeReason ??= \"heartbeat\";\n\t\t\tfinish(4003);\n\t\t\ttry {\n\t\t\t\tws.close();\n\t\t\t} catch {\n\t\t\t\t// already closing\n\t\t\t}\n\t\t}, heartbeatMs * 2.5);\n\t}\n\n\tfunction fail(error: Error): void {\n\t\tif (state !== \"opening\") return;\n\t\tfinish(0);\n\t\trejectReady(error);\n\t\ttry {\n\t\t\tws.close();\n\t\t} catch {\n\t\t\t// already closed\n\t\t}\n\t}\n\n\t/** The session is over: clean up once and tell the host. */\n\tfunction finish(code: number): void {\n\t\tif (state === \"closed\") return;\n\t\tconst wasReady = state === \"ready\";\n\t\tstate = \"closed\";\n\t\tclearTimeout(connectTimer);\n\t\tclearTimeout(heartbeat);\n\t\tstopWatching();\n\t\tfor (const controller of inflight.values()) controller.abort();\n\t\tinflight.clear();\n\t\thandler.close();\n\t\tif (wasReady) {\n\t\t\tconst reason =\n\t\t\t\tbyeReason ??\n\t\t\t\tCLOSE_REASONS[code] ??\n\t\t\t\t(code === 1006 ? \"network\" : \"closed\");\n\t\t\t// The grants of a taken-back address did not all go (DEC-095).\n\t\t\trejectReady(\n\t\t\t\trefused(\n\t\t\t\t\t\"The address was taken over again before its AI apps were disconnected.\",\n\t\t\t\t\treason,\n\t\t\t\t),\n\t\t\t);\n\t\t\t// Over at once; only the detail of `replaced` waits for a sibling's\n\t\t\t// `claimed`, which comes a moment after the `bye` (DEC-095).\n\t\t\thost.closed(reason, code);\n\t\t\tif (reason === \"replaced\") {\n\t\t\t\tvoid siblings.heard().then((sibling) => {\n\t\t\t\t\tsiblings.close();\n\t\t\t\t\thost.replaced({ sibling });\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tsiblings.close();\n\t}\n\n\tasync function tunnel(msg: HttpRequestMessage): Promise<void> {\n\t\tconst controller = new AbortController();\n\t\tinflight.set(msg.id, controller);\n\t\tconst live = () =>\n\t\t\tstate === \"ready\" &&\n\t\t\tinflight.get(msg.id) === controller &&\n\t\t\t!controller.signal.aborted;\n\t\ttry {\n\t\t\tconst request = new Request(`https://tab.invalid${msg.path}`, {\n\t\t\t\tmethod: msg.method,\n\t\t\t\theaders: msg.headers,\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t\tconst response = await handler.handle(request, {\n\t\t\t\tgrant: msg.grant,\n\t\t\t\tbody: msg.body,\n\t\t\t});\n\t\t\tif (!live()) {\n\t\t\t\tawait response.body?.cancel().catch(() => {});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst headers: Record<string, string> = {};\n\t\t\tfor (const name of RESPONSE_HEADERS) {\n\t\t\t\tconst value = response.headers.get(name);\n\t\t\t\tif (value !== null) headers[name] = value;\n\t\t\t}\n\t\t\tconst streamed = (headers[\"content-type\"] ?? \"\").startsWith(\n\t\t\t\t\"text/event-stream\",\n\t\t\t);\n\t\t\tif (!streamed || response.body === null) {\n\t\t\t\tconst body = await response.text();\n\t\t\t\tif (!live()) return;\n\t\t\t\tif (body.length <= maxChunk) {\n\t\t\t\t\tsend({\n\t\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Too big for one message: stream it (the relay passes it on whole).\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"http.response.start\",\n\t\t\t\t\tid: msg.id,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\tfor (const data of pieces(body, maxChunk)) {\n\t\t\t\t\tif (!live()) break;\n\t\t\t\t\tsend({ type: \"http.response.chunk\", id: msg.id, data });\n\t\t\t\t}\n\t\t\t\tif (live()) send({ type: \"http.response.end\", id: msg.id });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsend({\n\t\t\t\ttype: \"http.response.start\",\n\t\t\t\tid: msg.id,\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tcontroller.signal.addEventListener(\"abort\", () => {\n\t\t\t\treader.cancel().catch(() => {});\n\t\t\t});\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done || !live()) break;\n\t\t\t\tconst text = decoder.decode(value, { stream: true });\n\t\t\t\tfor (const data of pieces(text, maxChunk)) {\n\t\t\t\t\tsend({ type: \"http.response.chunk\", id: msg.id, data });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (live()) send({ type: \"http.response.end\", id: msg.id });\n\t\t} catch (error) {\n\t\t\tif (live()) {\n\t\t\t\thost.error(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\tid: msg.id,\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid: null,\n\t\t\t\t\t\terror: { code: -32603, message: \"Internal server error\" },\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tif (inflight.get(msg.id) === controller) inflight.delete(msg.id);\n\t\t}\n\t}\n\n\tfunction onMessage(message: RelayMessage): void {\n\t\tif (state === \"opening\") {\n\t\t\tif (message.type === \"session\") {\n\t\t\t\tconst chunk = chunkSize(message.limits.maxMessageBytes);\n\t\t\t\tif (chunk === undefined) {\n\t\t\t\t\tfail(\n\t\t\t\t\t\trefused(\n\t\t\t\t\t\t\t`The relay's message limit (${message.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${MIN_MESSAGE_BYTES}.`,\n\t\t\t\t\t\t\t\"policy\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxChunk = chunk;\n\t\t\t\tstate = \"ready\";\n\t\t\t\tclearTimeout(connectTimer);\n\t\t\t\theartbeatMs = message.limits.heartbeatMs;\n\t\t\t\tarmHeartbeat();\n\t\t\t\tsiblings.claimed();\n\t\t\t\tconst session = host.sessionStarted(message);\n\t\t\t\tif (revokeAll && message.grants.length > 0) {\n\t\t\t\t\t// A relay that ignored hello.revokeAll: revoke now, and wait until\n\t\t\t\t\t// it has removed every grant.\n\t\t\t\t\trevoking = {\n\t\t\t\t\t\tleft: new Set(message.grants.map((g) => g.grantId)),\n\t\t\t\t\t\tsession,\n\t\t\t\t\t};\n\t\t\t\t\tsend({ type: \"grants.revokeAll\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresolveReady(session);\n\t\t\t} else if (message.type === \"error\") {\n\t\t\t\tfail(\n\t\t\t\t\trefused(\n\t\t\t\t\t\t`The relay refused the connection: ${message.message || message.code}`,\n\t\t\t\t\t\tmessage.code === \"rate_limited\" ? \"rate_limited\" : \"policy\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (message.type === \"bye\") {\n\t\t\t\tfail(\n\t\t\t\t\trefused(\n\t\t\t\t\t\t`The relay ended the connection: ${message.reason}`,\n\t\t\t\t\t\tBYE_REASONS[message.reason] ?? \"closed\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (state !== \"ready\") return;\n\t\tswitch (message.type) {\n\t\t\tcase \"ping\":\n\t\t\t\tarmHeartbeat();\n\t\t\t\tsend({ type: \"pong\", t: message.t });\n\t\t\t\treturn;\n\t\t\tcase \"http.request\":\n\t\t\t\tvoid tunnel(message);\n\t\t\t\treturn;\n\t\t\tcase \"http.cancel\":\n\t\t\t\tinflight.get(message.id)?.abort();\n\t\t\t\tinflight.delete(message.id);\n\t\t\t\treturn;\n\t\t\tcase \"pairing.code\":\n\t\t\t\thost.pairingCode({ code: message.code, expiresAt: message.expiresAt });\n\t\t\t\treturn;\n\t\t\tcase \"grant.added\":\n\t\t\t\thost.grantAdded(message.grant);\n\t\t\t\treturn;\n\t\t\tcase \"grant.removed\":\n\t\t\t\thost.grantRemoved(message.grantId);\n\t\t\t\trevoking?.left.delete(message.grantId);\n\t\t\t\tif (revoking?.left.size === 0) resolveReady(revoking.session);\n\t\t\t\treturn;\n\t\t\tcase \"identity.bound\":\n\t\t\t\thost.identityResult(true, message.round);\n\t\t\t\treturn;\n\t\t\tcase \"bye\":\n\t\t\t\tbyeReason = BYE_REASONS[message.reason] ?? \"closed\";\n\t\t\t\t// Taken over: over at once, not when the socket closes (review of PR 39).\n\t\t\t\tif (byeReason === \"replaced\") finish(4005);\n\t\t\t\treturn;\n\t\t\tcase \"error\":\n\t\t\t\tif (message.code === \"identity_refused\") {\n\t\t\t\t\thost.identityResult(\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\ttypeof message.round === \"number\" ? message.round : undefined,\n\t\t\t\t\t\tmessage.message,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\thost.error(\n\t\t\t\t\tnew Error(`Relay error ${message.code}: ${message.message}`),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\tcase \"session\":\n\t\t\t\treturn; // only once\n\t\t}\n\t}\n\n\tws.addEventListener(\"open\", () => {\n\t\tif (ws.protocol !== \"\" && ws.protocol !== SUBPROTOCOL) {\n\t\t\tfail(\n\t\t\t\trefused(\n\t\t\t\t\t`The relay speaks ${ws.protocol}, not ${SUBPROTOCOL}.`,\n\t\t\t\t\t\"policy\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst hello: TabMessage = {\n\t\t\ttype: \"hello\",\n\t\t\tlibrary: host.library,\n\t\t\tpage: { title: pageTitle() },\n\t\t\tsecret,\n\t\t};\n\t\tif (host.appName !== undefined) hello.app = { name: host.appName };\n\t\tif (revokeAll) hello.revokeAll = true;\n\t\tsend(hello);\n\t});\n\tws.addEventListener(\"message\", (event: MessageEvent) => {\n\t\tif (typeof event.data !== \"string\") return;\n\t\tconst message = parseRelayMessage(event.data);\n\t\tif (message !== undefined) {\n\t\t\tif (state === \"ready\") armHeartbeat(); // any traffic shows the link is alive\n\t\t\tonMessage(message);\n\t\t\treturn;\n\t\t}\n\t\tconst info = frameInfo(event.data);\n\t\tif (info?.id !== undefined) {\n\t\t\tsend(\n\t\t\t\tKNOWN_TYPES.has(info.type)\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\tcode: \"bad_message\",\n\t\t\t\t\t\t\tmessage: `malformed ${info.type}`,\n\t\t\t\t\t\t\tid: info.id,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\tcode: \"unknown_type\",\n\t\t\t\t\t\t\tmessage: `unknown type ${info.type}`,\n\t\t\t\t\t\t\tid: info.id,\n\t\t\t\t\t\t},\n\t\t\t);\n\t\t}\n\t});\n\tws.addEventListener(\"close\", (event: CloseEvent) => {\n\t\tif (state === \"opening\") {\n\t\t\tfinish(event.code);\n\t\t\t// No WebSocket at all: browsers say 1006, Bun 1002. The page cannot\n\t\t\t// tell a refused origin from an unreachable relay (DEC-082).\n\t\t\tconst unreachable = event.code === 1006 || event.code === 1002;\n\t\t\trejectReady(\n\t\t\t\trefused(\n\t\t\t\t\tunreachable\n\t\t\t\t\t\t? \"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).\"\n\t\t\t\t\t\t: `The relay closed the connection (${event.code}${event.reason ? `: ${event.reason}` : \"\"}).`,\n\t\t\t\t\tCLOSE_REASONS[event.code] ?? (unreachable ? \"network\" : \"closed\"),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tfinish(event.code);\n\t});\n\n\treturn {\n\t\tready,\n\t\tsend,\n\t\tclose(reason: DisconnectReason) {\n\t\t\tif (state === \"closed\") return;\n\t\t\tif (state === \"opening\") {\n\t\t\t\tfail(\n\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\"The connection was cancelled\",\n\t\t\t\t\t\t\"AbortError\",\n\t\t\t\t\t) as Error,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbyeReason = reason;\n\t\t\tsend({ type: \"bye\", reason: \"user\" });\n\t\t\tfinish(1000);\n\t\t\ttry {\n\t\t\t\tws.close(1000, \"bye\");\n\t\t\t} catch {\n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U,SAAU,OACxB,GAAI,IAAU,UAAW,CACxB,EACC,IAAI,aACH,+BACA,YACD,CACD,EACA,OAED,EAAY,EACZ,EAAK,CAAE,KAAM,MAAO,OAAQ,MAAO,CAAC,EACpC,EAAO,IAAI,EACX,GAAI,CACH,EAAG,MAAM,KAAM,KAAK,EACnB,KAAM,GAIV",
19
- "debugId": "0B1EE263FE9616FD64756E2164756E21",
20
- "names": []
21
- }
@@ -1,11 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/always-allowed.ts", "../../src/ui.ts"],
4
- "sourcesContent": [
5
- "/**\n * The tools a user chose \"Always allow\" for, per grant (AI app). Kept in\n * memory for the page's lifetime; an entry goes when its grant goes or its\n * tool is unregistered, so a re-paired app or a new tool under the same name\n * is asked again.\n */\nexport class AlwaysAllowed {\n\treadonly #tools = new Map<string, Set<string>>();\n\n\thas(grantId: string, tool: string): boolean {\n\t\treturn this.#tools.get(grantId)?.has(tool) === true;\n\t}\n\n\tadd(grantId: string, tool: string): void {\n\t\tconst tools = this.#tools.get(grantId) ?? new Set();\n\t\ttools.add(tool);\n\t\tthis.#tools.set(grantId, tools);\n\t}\n\n\t/** Forget every grant not in `grantIds`. */\n\tkeepGrants(grantIds: Iterable<string>): void {\n\t\tconst keep = new Set(grantIds);\n\t\tfor (const grantId of this.#tools.keys()) {\n\t\t\tif (!keep.has(grantId)) this.#tools.delete(grantId);\n\t\t}\n\t}\n\n\t/** Forget every tool not in `names`. */\n\tkeepTools(names: Iterable<string>): void {\n\t\tconst keep = new Set(names);\n\t\tfor (const tools of this.#tools.values()) {\n\t\t\tfor (const tool of tools) if (!keep.has(tool)) tools.delete(tool);\n\t\t}\n\t}\n}\n",
6
- "/**\n * The default UI, loaded on demand: the \"Connect your AI app\" dialog\n * (DEC-028) and the confirmation of consequential tools. Plain `<dialog>`\n * elements, all text set with `textContent`, styled by one constructed\n * stylesheet (`DIALOG_CSS`) that pages adjust through `--tab-mcp-*` custom\n * properties or their own CSS. Pages with their own UI use the events and\n * methods of `TabMcp` instead.\n */\n\nimport { AlwaysAllowed } from \"./always-allowed.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tConfirmRequest,\n\tDisconnectDetail,\n\tGrant,\n\tSessionInfo,\n\tToolCallClient,\n} from \"./types.ts\";\n\nlet counter = 0;\n\nfunction el<K extends keyof HTMLElementTagNameMap>(\n\tdoc: Document,\n\ttag: K,\n\tprops: { className?: string; text?: string; id?: string } = {},\n\t...children: (Node | string)[]\n): HTMLElementTagNameMap[K] {\n\tconst node = doc.createElement(tag);\n\tif (props.className !== undefined) node.className = props.className;\n\tif (props.id !== undefined) node.id = props.id;\n\tif (props.text !== undefined) node.textContent = props.text;\n\tnode.append(...children);\n\treturn node;\n}\n\n/**\n * A button. `className` is its own class; `kind` marks the one next step\n * (`tab-mcp-primary`) or one that disconnects (`tab-mcp-danger`); without\n * one it is a plain, outlined button.\n */\nfunction button(\n\tdoc: Document,\n\ttext: string,\n\tonClick: () => void,\n\tclassName?: string,\n\tkind?: \"primary\" | \"danger\",\n): HTMLButtonElement {\n\tconst node = el(doc, \"button\", { text });\n\tnode.type = \"button\";\n\tif (className !== undefined) node.classList.add(className);\n\tif (kind !== undefined) node.classList.add(`tab-mcp-${kind}`);\n\tnode.addEventListener(\"click\", onClick);\n\treturn node;\n}\n\n/**\n * The look of both dialogs. Every selector has the specificity of one class\n * (the rest is in `:where()`), so rules of the page for elements, such as\n * `button { … }` or a reset's `* { border-width: 0 }`, do not change the\n * dialogs. The rules for states (hover, focus, disabled) and the primary\n * and danger buttons add two elements (`html dialog.…`, `html button.…`),\n * so `button:hover`, `button:focus` or `button:disabled` of the page do not\n * either. A rule with two classes, such as `.tab-mcp-dialog .tab-mcp-primary`,\n * wins over all of them. The `--tab-mcp-*`\n * custom properties (on `:root` or on `.tab-mcp-dialog`) change single\n * values; the library only reads them. The defaults use system colours and the\n * page's `color-scheme`, so the dialogs follow its light or dark scheme. The\n * `--_tab-mcp-*` properties are internal. Order matters among equals.\n */\nexport const DIALOG_CSS = `.tab-mcp-dialog {\n--_tab-mcp-fg: var(--tab-mcp-color, CanvasText);\n--_tab-mcp-bg: var(--tab-mcp-background, Canvas);\n--_tab-mcp-muted: var(--tab-mcp-muted, color-mix(in srgb, var(--_tab-mcp-fg) 72%, transparent));\n--_tab-mcp-line: color-mix(in srgb, var(--_tab-mcp-fg) 22%, transparent);\n--_tab-mcp-surface: var(--tab-mcp-surface, color-mix(in srgb, var(--_tab-mcp-fg) 6%, transparent));\n--_tab-mcp-danger: var(--tab-mcp-danger, light-dark(#b3261e, #ffb4ab));\n--_tab-mcp-mono: var(--tab-mcp-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);\n--_tab-mcp-small-radius: calc(var(--tab-mcp-radius, 0.75rem) * 0.6);\nbox-sizing: border-box; width: calc(100% - 2rem); max-width: var(--tab-mcp-max-width, 34rem); max-height: calc(100% - 2rem); overflow: auto;\nfont: var(--tab-mcp-font, inherit); line-height: 1.5; color: var(--_tab-mcp-fg); background: var(--_tab-mcp-bg);\nborder: var(--tab-mcp-border, 1px solid var(--_tab-mcp-line)); border-radius: var(--tab-mcp-radius, 0.75rem);\npadding: var(--tab-mcp-padding, clamp(1rem, 5vw, 1.5rem)); box-shadow: var(--tab-mcp-shadow, 0 1rem 3rem rgb(0 0 0 / 0.3));\n}\n.tab-mcp-dialog::backdrop { background: var(--tab-mcp-backdrop, rgb(0 0 0 / 0.4)); }\n.tab-mcp-dialog:where([open]) { display: flex; flex-direction: column; gap: 1rem; }\n.tab-mcp-dialog:where([open]) > * { flex-shrink: 0; }\n.tab-mcp-dialog :where([hidden]) { display: none !important; }\nhtml dialog.tab-mcp-dialog:where(:focus) { outline: none; }\n.tab-mcp-dialog :where(*) { box-sizing: border-box; }\n.tab-mcp-dialog :where(h2, h3, p, ul, li, pre) { margin: 0; }\n.tab-mcp-dialog :where(h2) { font-size: var(--tab-mcp-title-size, 1.25em); line-height: 1.3; font-weight: 600; overflow-wrap: anywhere; }\n.tab-mcp-dialog :where(h3) { font-size: 0.875em; font-weight: 600; color: var(--_tab-mcp-muted); margin-bottom: 0.5rem; }\n.tab-mcp-dialog :where(small) { font-size: 0.875em; }\n.tab-mcp-dialog :where(small, .tab-mcp-status, .tab-mcp-description, .tab-mcp-always-note, .tab-mcp-apps-note) { color: var(--_tab-mcp-muted); }\nhtml dialog.tab-mcp-dialog :where(:focus-visible) { outline: 2px solid var(--tab-mcp-focus, var(--_tab-mcp-fg)); outline-offset: 2px; }\n.tab-mcp-dialog :where(button) { font: inherit; font-size: 0.9375em; line-height: 1.25; min-height: 2.5rem; padding: 0.5rem 1rem; margin: 0; border: 1px solid color-mix(in srgb, currentColor 35%, transparent); border-radius: var(--_tab-mcp-small-radius); background: transparent; color: inherit; cursor: pointer; }\nhtml dialog.tab-mcp-dialog :where(button:hover:not(:disabled)) { color: inherit; background: color-mix(in srgb, currentColor 8%, transparent); }\nhtml dialog.tab-mcp-dialog :where(button:disabled) { opacity: 0.45; cursor: not-allowed; }\nhtml button.tab-mcp-primary { background: var(--tab-mcp-accent, var(--_tab-mcp-fg)); color: var(--tab-mcp-accent-text, var(--_tab-mcp-bg)); border-color: transparent; font-weight: 600; }\nhtml button.tab-mcp-primary:where(:hover:not(:disabled)) { background: var(--tab-mcp-accent, var(--_tab-mcp-fg)); opacity: 0.85; }\nhtml button.tab-mcp-danger { color: var(--_tab-mcp-danger); border-color: color-mix(in srgb, currentColor 45%, transparent); }\n.tab-mcp-copy { min-width: 6em; }\n.tab-mcp-close { font-size: 0.875em; }\n.tab-mcp-status { margin-top: -0.5rem; }\n.tab-mcp-description:where(:empty) { display: none; }\n.tab-mcp-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 0.5rem; }\n.tab-mcp-address { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }\n.tab-mcp-address :where(label) { flex-basis: 100%; font-weight: 600; }\n.tab-mcp-address :where(input) { flex: 1 1 12rem; min-width: 0; min-height: 2.5rem; margin: 0; padding: 0.5rem 0.625rem; font: 0.875em var(--_tab-mcp-mono); text-overflow: ellipsis; color: inherit; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-code { display: grid; grid-template-columns: 1fr auto; align-items: end; gap: 0.25rem 1rem; padding: 1rem; background: var(--_tab-mcp-surface); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-code > :where(span) { font-weight: 600; }\n.tab-mcp-code :where(br) { display: none; }\n.tab-mcp-code :where(small) { grid-column: 1 / -1; }\n.tab-mcp-code-value { display: block; font: 700 var(--tab-mcp-code-size, 2em) / 1.2 var(--_tab-mcp-mono); letter-spacing: 0.12em; font-variant-numeric: tabular-nums; }\n.tab-mcp-help { border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-help :where(summary) { padding: 0.75rem 1rem; font-weight: 600; cursor: pointer; }\n.tab-mcp-help > :where(:not(summary)) { margin-inline: 1rem; }\n.tab-mcp-help > :where(:last-child:not(summary)) { margin-bottom: 1rem; }\n.tab-mcp-dialog :where(.tab-mcp-help ul, .tab-mcp-apps ul) { list-style: none; padding: 0; display: grid; gap: 0.5rem; }\n.tab-mcp-help :where(ul) { margin-top: 0.25rem; margin-bottom: 0.75rem; gap: 0.75rem; }\n.tab-mcp-help :where(li) { overflow-wrap: anywhere; }\n.tab-mcp-help :where(strong) { display: block; font-weight: 600; }\n.tab-mcp-command { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: flex-start; gap: 0.5rem; margin-top: 0.375rem; }\n.tab-mcp-command > :where(pre) { flex: 1 1 16rem; min-width: 0; margin: 0; padding: 0.5rem 0.625rem; font: 0.8125em / 1.5 var(--_tab-mcp-mono); white-space: pre-wrap; word-break: break-all; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-command-note { display: block; margin-top: 0.375rem; }\n.tab-mcp-help :where(code) { font: 0.875em var(--_tab-mcp-mono); padding: 0.125em 0.375em; background: var(--_tab-mcp-surface); border-radius: 0.25rem; -webkit-box-decoration-break: clone; box-decoration-break: clone; }\n.tab-mcp-apps :where(li) { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; padding: 0.5rem 0.5rem 0.5rem 0.75rem; border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-app { min-width: 0; overflow-wrap: anywhere; }\n.tab-mcp-apps-note { margin-top: 0.5rem; }\n.tab-mcp-new-address-question { display: grid; gap: 0.75rem; padding: 1rem; border: 1px solid color-mix(in srgb, var(--_tab-mcp-danger) 50%, transparent); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-connect > :where(.tab-mcp-actions) { gap: 0.75rem; padding-top: 1rem; border-top: 1px solid var(--_tab-mcp-line); }\n.tab-mcp-close-note { flex: 1 1 12rem; }\n.tab-mcp-confirm :where(p bdi) { font-weight: 600; }\n.tab-mcp-arguments { box-sizing: content-box; font: 0.875em / 1.45 var(--_tab-mcp-mono); padding: 0.75rem; background: var(--_tab-mcp-surface); border: 1px solid var(--_tab-mcp-line); border-radius: var(--_tab-mcp-small-radius); }\n.tab-mcp-always-note { font-size: 0.875em; }\n@media (max-width: 30rem) { .tab-mcp-actions > :where(button) { flex: 1 1 auto; } .tab-mcp-connect > :where(.tab-mcp-actions) > :where(button) { flex: 0 0 auto; } }\n@media (prefers-reduced-motion: no-preference) { .tab-mcp-dialog:where([open]) { animation: tab-mcp-in 0.15s ease-out; } }\n@media (forced-colors: active) { html button.tab-mcp-primary { border-color: ButtonText; } }\n@keyframes tab-mcp-in { from { opacity: 0; transform: translateY(0.5rem); } }\n`;\n\nconst sheets = new WeakMap<Document, CSSStyleSheet>();\n\n/**\n * Adopts `DIALOG_CSS` into the document once, next to the page's own adopted\n * sheets. A constructed stylesheet needs no `style-src` exception under a\n * strict CSP. Where constructed stylesheets are not supported, the dialogs\n * keep the browser's default look and work the same.\n */\nfunction adoptStyles(doc: Document): void {\n\ttry {\n\t\tlet sheet = sheets.get(doc);\n\t\tif (sheet === undefined) {\n\t\t\tconst Sheet = (doc.defaultView as (Window & typeof globalThis) | null)\n\t\t\t\t?.CSSStyleSheet;\n\t\t\tif (Sheet === undefined || !Array.isArray(doc.adoptedStyleSheets)) return;\n\t\t\tsheet = new Sheet();\n\t\t\tsheet.replaceSync(DIALOG_CSS);\n\t\t\tsheets.set(doc, sheet);\n\t\t}\n\t\t// The page may have replaced the list since.\n\t\tif (!doc.adoptedStyleSheets.includes(sheet))\n\t\t\tdoc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet];\n\t} catch {\n\t\t// Not supported: the default look.\n\t}\n}\n\n/**\n * A Copy button for `value()`, read at click time. Shows \"Copied\" once the\n * clipboard took it; without a clipboard (or when it refuses) `select()` puts\n * the text in the selection for Ctrl+C instead. `noun` names it for assistive\n * technology (\"Copy code\"), as the dialog has more than one Copy; `announce`\n * says what happened (\"Code copied\", or that the text is selected).\n */\nfunction copyButton(\n\tdoc: Document,\n\tnoun: string,\n\tvalue: () => string,\n\tselect: () => void,\n\tannounce: (text: string) => void,\n\tclassName: string,\n\tkind?: \"primary\",\n): { button: HTMLButtonElement; reset: () => void } {\n\tconst node = button(\n\t\tdoc,\n\t\t\"Copy\",\n\t\t() => {\n\t\t\tconst done = () => {\n\t\t\t\tnode.textContent = \"Copied\";\n\t\t\t\tnode.setAttribute(\"aria-label\", `Copied ${noun}`);\n\t\t\t\tannounce(`${noun[0]?.toUpperCase()}${noun.slice(1)} copied`);\n\t\t\t};\n\t\t\tconst selected = () => {\n\t\t\t\tselect();\n\t\t\t\tannounce(\"Selected: copy it with Ctrl+C or ⌘C\");\n\t\t\t};\n\t\t\tconst clipboard = (doc.defaultView?.navigator as Navigator | undefined)\n\t\t\t\t?.clipboard;\n\t\t\tif (clipboard !== undefined)\n\t\t\t\tclipboard.writeText(value()).then(done, selected);\n\t\t\telse selected();\n\t\t},\n\t\tclassName,\n\t\tkind,\n\t);\n\t// The same width for \"Copy\" and \"Copied\": nothing moves.\n\tnode.classList.add(\"tab-mcp-copy\");\n\tconst reset = () => {\n\t\tnode.textContent = \"Copy\";\n\t\tnode.setAttribute(\"aria-label\", `Copy ${noun}`);\n\t};\n\treset();\n\treturn { button: node, reset };\n}\n\nfunction newDialog(\n\tdoc: Document,\n\tclassName: string,\n\ttitle: string,\n): { dialog: HTMLDialogElement; heading: HTMLHeadingElement } {\n\tconst id = `tab-mcp-${++counter}`;\n\tconst dialog = el(doc, \"dialog\", {\n\t\tclassName: `tab-mcp-dialog ${className}`,\n\t});\n\tdialog.setAttribute(\"aria-labelledby\", `${id}-title`);\n\tadoptStyles(doc);\n\tconst heading = el(doc, \"h2\", { id: `${id}-title`, text: title });\n\tdialog.append(heading);\n\treturn { dialog, heading };\n}\n\n/**\n * Characters that are invisible or change the direction of the text around\n * them: format characters (bidi controls and isolates, zero-width ones, tags),\n * the other default-ignorable ones (fillers, variation selectors), private-use\n * and unassigned code points, C1 controls, and line and paragraph separators.\n */\nconst INVISIBLE =\n\t/[\\p{Cf}\\p{Default_Ignorable_Code_Point}\\p{Co}\\p{Cn}\\u0080-\\u009F\\u2028\\u2029]/gu;\n\n/** Each such character as `\\uXXXX` (a pair for one beyond U+FFFF), as JSON would write it. */\nfunction visible(text: string): string {\n\treturn text.replace(INVISIBLE, (ch) => {\n\t\tlet escaped = \"\";\n\t\tfor (let i = 0; i < ch.length; i++)\n\t\t\tescaped += `\\\\u${ch.charCodeAt(i).toString(16).toUpperCase().padStart(4, \"0\")}`;\n\t\treturn escaped;\n\t});\n}\n\nfunction clientLabel(client: ToolCallClient | Grant[\"client\"]): string {\n\tconst host = visible(client.host || client.id);\n\treturn client.name !== undefined && client.name !== \"\"\n\t\t? `${visible(client.name)} (${host})`\n\t\t: host;\n}\n\n/** A name in a sentence, isolated so that it cannot reorder the words around it. */\nfunction name(doc: Document, text: string): HTMLElement {\n\tconst node = el(doc, \"bdi\", { text });\n\tnode.dir = \"ltr\";\n\treturn node;\n}\n\n/**\n * The arguments as text, in full: what the user approves must be visible.\n * (The relay caps a request at 1 MiB, so this stays bounded.) Invisible and\n * direction characters are shown as escapes, so the text is still JSON for\n * the same arguments; the tool gets them unchanged. `undefined` when they\n * cannot be shown, and then \"Allow\" is not offered.\n */\nfunction showArguments(args: Record<string, unknown>): string | undefined {\n\ttry {\n\t\treturn visible(JSON.stringify(args, null, 2));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** How long \"Allow\" stays disabled after the confirmation opens, and the floor. */\nexport const ALLOW_DELAY_MS = 750;\nexport const MIN_ALLOW_DELAY_MS = 500;\n\n/** The user's answer: \"always\" allows this tool for this AI app from now on. */\nexport type ConfirmAnswer = \"allow\" | \"always\" | \"deny\";\n\n/** `allowDelayMs` as a usable delay: the default unless a number of ms, never below the floor. */\nfunction allowDelay(ms: number | undefined): number {\n\tconst value =\n\t\ttypeof ms === \"number\" && Number.isFinite(ms) && ms < 2 ** 31\n\t\t\t? ms\n\t\t\t: ALLOW_DELAY_MS;\n\treturn Math.max(MIN_ALLOW_DELAY_MS, value);\n}\n\n/**\n * Ask whether a consequential tool may run. \"Always allow\" is offered only\n * with `alwaysAllow` (DEC-096). \"Allow\" and \"Always allow\" stay disabled\n * until the page has been visible and focused for `allowDelayMs` (default\n * 750, at least 500) while the dialog is open, so a click meant for the page,\n * or the click that brings the tab or window back, cannot approve. Leaving\n * the page disables them again. Everything else (Don't allow, Escape, an\n * aborted call) is \"deny\".\n */\nexport function confirmDialog(\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: { allowDelayMs?: number | undefined; alwaysAllow?: boolean } = {},\n): Promise<ConfirmAnswer> {\n\tconst delay = allowDelay(options.allowDelayMs);\n\tif (request.signal.aborted) return Promise.resolve(\"deny\");\n\tconst title = request.tool.title ?? request.tool.name;\n\tconst { dialog, heading } = newDialog(doc, \"tab-mcp-confirm\", \"\");\n\theading.append(\"Allow \", name(doc, title), \"?\");\n\tconst client = clientLabel(request.client);\n\t// The safe choice is the default: focused, and the one that stands out.\n\tconst deny = button(\n\t\tdoc,\n\t\t\"Don't allow\",\n\t\t() => dialog.close(\"deny\"),\n\t\t\"tab-mcp-deny\",\n\t\t\"primary\",\n\t);\n\tconst allow = button(\n\t\tdoc,\n\t\t\"Allow\",\n\t\t() => {\n\t\t\tif (!allow.disabled) dialog.close(\"allow\");\n\t\t},\n\t\t\"tab-mcp-allow\",\n\t);\n\t// The approving buttons: Allow, and Always allow when the page offers it.\n\tconst approve = [allow];\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tdeny,\n\t\t\" \",\n\t\tallow,\n\t);\n\tconst extra: HTMLElement[] = [];\n\tif (options.alwaysAllow === true) {\n\t\tconst always = button(\n\t\t\tdoc,\n\t\t\t\"Always allow\",\n\t\t\t() => {\n\t\t\t\tif (!always.disabled) dialog.close(\"always\");\n\t\t\t},\n\t\t\t\"tab-mcp-always\",\n\t\t);\n\t\tapprove.push(always);\n\t\tactions.append(\" \", always);\n\t\textra.push(\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"p\",\n\t\t\t\t{ className: \"tab-mcp-always-note\" },\n\t\t\t\t\"Always allow: \",\n\t\t\t\tname(doc, title),\n\t\t\t\t\" runs without asking for \",\n\t\t\t\tname(doc, client),\n\t\t\t\t\" until you reload this page or disconnect it.\",\n\t\t\t),\n\t\t);\n\t}\n\tconst enable = (on: boolean) => {\n\t\tfor (const b of approve) b.disabled = !on;\n\t};\n\tenable(false);\n\tconst shown = showArguments(request.arguments);\n\tconst args = el(doc, \"pre\", {\n\t\tclassName: \"tab-mcp-arguments\",\n\t\ttext:\n\t\t\tshown ?? \"The arguments cannot be shown, so this call cannot be allowed.\",\n\t});\n\tif (shown === undefined) {\n\t\tfor (const node of [...approve, ...extra]) node.hidden = true;\n\t}\n\targs.dir = \"ltr\";\n\t// Inline, so the arguments stay readable in full without the stylesheet:\n\t// wrapped (also a long word, at 360 px), scrolling when long.\n\targs.style.setProperty(\"white-space\", \"pre-wrap\");\n\targs.style.setProperty(\"overflow-wrap\", \"anywhere\");\n\targs.style.setProperty(\n\t\t\"max-height\",\n\t\t\"var(--tab-mcp-arguments-height, 12rem)\",\n\t);\n\targs.style.setProperty(\"overflow\", \"auto\");\n\targs.hidden = Object.keys(request.arguments).length === 0;\n\tdialog.append(\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"p\",\n\t\t\t{},\n\t\t\tname(doc, client),\n\t\t\t\" wants to run \",\n\t\t\tname(doc, title),\n\t\t\t\".\",\n\t\t),\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: request.tool.description,\n\t\t}),\n\t\targs,\n\t\tactions,\n\t\t...extra,\n\t);\n\tdoc.body.append(dialog);\n\tconst view = doc.defaultView;\n\treturn new Promise((resolve) => {\n\t\tconst onAbort = () => dialog.close(\"deny\");\n\t\trequest.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t// The delay counts only while the user can see the page: tools are\n\t\t// called while the user is in the AI app, so the dialog often opens in\n\t\t// a background tab or window. Any change starts it again from zero (DEC-087).\n\t\tconst arm = (event?: Event) => {\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tenable(false);\n\t\t\tif (\n\t\t\t\tevent?.type === \"blur\" ||\n\t\t\t\tdoc.visibilityState === \"hidden\" ||\n\t\t\t\t!doc.hasFocus()\n\t\t\t)\n\t\t\t\treturn;\n\t\t\ttimer = setTimeout(() => enable(true), delay);\n\t\t};\n\t\tdoc.addEventListener(\"visibilitychange\", arm);\n\t\tview?.addEventListener(\"focus\", arm);\n\t\tview?.addEventListener(\"blur\", arm);\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tdoc.removeEventListener(\"visibilitychange\", arm);\n\t\t\t\tview?.removeEventListener(\"focus\", arm);\n\t\t\t\tview?.removeEventListener(\"blur\", arm);\n\t\t\t\trequest.signal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tconst value = dialog.returnValue;\n\t\t\t\tdialog.remove();\n\t\t\t\tresolve(value === \"allow\" || value === \"always\" ? value : \"deny\");\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tdialog.showModal();\n\t\tdeny.focus(); // the safe choice is the default\n\t\t// Counted from when the dialog is shown, not from when it was built.\n\t\tarm();\n\t});\n}\n\n/** The tools a user chose \"Always allow\" for, per `TabMcp`. */\nconst allowedAlways = new WeakMap<TabMcp, AlwaysAllowed>();\n\n/**\n * `TabMcp.confirmInPage`: the confirmation, and the tools allowed always. An\n * entry goes when its grant goes or its tool is unregistered, so a re-paired\n * app or a new tool under the same name is asked again.\n */\nexport function confirmInPage(\n\tmcp: TabMcp,\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: { allowDelayMs?: number | undefined; alwaysAllow?: boolean },\n): Promise<boolean> {\n\tconst { grantId } = request.client;\n\tconst tool = request.tool.name;\n\tif (allowedAlways.get(mcp)?.has(grantId, tool)) return Promise.resolve(true);\n\treturn confirmDialog(request, doc, options).then((answer) => {\n\t\t// Only while the grant is still there: a revoked app gets nothing.\n\t\tif (answer === \"always\" && mcp.grants.some((g) => g.grantId === grantId)) {\n\t\t\tlet allowed = allowedAlways.get(mcp);\n\t\t\tif (allowed === undefined) {\n\t\t\t\tconst kept = new AlwaysAllowed();\n\t\t\t\tmcp.addEventListener(\"grantschange\", (e) =>\n\t\t\t\t\tkept.keepGrants(e.detail.grants.map((g) => g.grantId)),\n\t\t\t\t);\n\t\t\t\tmcp.addEventListener(\"toolschange\", (e) =>\n\t\t\t\t\tkept.keepTools(e.detail.tools),\n\t\t\t\t);\n\t\t\t\tallowedAlways.set(mcp, kept);\n\t\t\t\tallowed = kept;\n\t\t\t}\n\t\t\tallowed.add(grantId, tool);\n\t\t}\n\t\treturn answer !== \"deny\";\n\t});\n}\n\n/**\n * The server's name as a label that every shell (POSIX shells, PowerShell,\n * cmd.exe) reads as one plain word, so it needs no quoting: letters without\n * their marks (\"Bücher\" → \"bucher\"), lower case, each run of anything but\n * a-z, 0-9, _ and - as one \"-\", no \"-\" at either end (no option), at most 40\n * characters; \"tools\" when nothing is left. The page names its server, but\n * the command runs in the user's shell: nothing of the name may be quoted\n * text (review of PR 34).\n */\nexport function commandName(name: string): string {\n\tconst label = name\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/\\p{M}/gu, \"\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_-]+/g, \"-\")\n\t\t.replace(/-{2,}/g, \"-\")\n\t\t.replace(/^-+|-+$/g, \"\")\n\t\t.slice(0, 40)\n\t\t.replace(/-+$/, \"\");\n\treturn label === \"\" ? \"tools\" : label;\n}\n\n/**\n * The address for a command, only when all of it is plain in every shell\n * (http or https, letters, digits and . : [ ] / _ ~ -); else `undefined`, and\n * the help shows the steps without commands. The relay's addresses are.\n */\nexport function commandAddress(address: string): string | undefined {\n\ttry {\n\t\tconst href = new URL(address).href;\n\t\treturn /^https?:\\/\\/[A-Za-z0-9.:[\\]/_~-]+$/.test(href) ? href : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The guide for every AI app (docs/connecting.md, on ractive.ch). */\nconst GUIDE = \"https://ractive.ch/tab-mcp/connect/\";\n\n/** Codex's feature for MCP 2026-07-28, which the relay speaks; off by default in Codex 0.163. */\nconst CODEX_FEATURE = \"mcp_2026_07_28\";\n\n/**\n * Per AI app: its name, what to do, a command to run (one per line), and a\n * note after it, alternating text and code. `name` is the page's server name.\n */\nexport function instructions(\n\tname: string,\n\taddress: string,\n): [string, string, (string | undefined)?, string[]?][] {\n\tconst n = commandName(name);\n\tconst a = commandAddress(address);\n\treturn [\n\t\t[\n\t\t\t\"Claude (claude.ai and the desktop app)\",\n\t\t\t\"Settings → Connectors → Add custom connector, then paste the address.\",\n\t\t],\n\t\t[\n\t\t\t\"ChatGPT\",\n\t\t\t\"On chatgpt.com: Plugins, add an MCP server with the address. In the Mac app: Settings → Plugins → MCPs → Add, type Streamable HTTP; it needs the Codex feature below.\",\n\t\t],\n\t\ta === undefined\n\t\t\t? [\"Claude Code\", \"Add the address with claude mcp add --transport http.\"]\n\t\t\t: [\"Claude Code\", \"Run:\", `claude mcp add --transport http ${n} ${a}`],\n\t\t[\n\t\t\t\"Codex\",\n\t\t\t...((a === undefined\n\t\t\t\t? [\n\t\t\t\t\t\t`Run codex features enable ${CODEX_FEATURE}, then add the address with codex mcp add --url.`,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t]\n\t\t\t\t: [\n\t\t\t\t\t\t\"Run:\",\n\t\t\t\t\t\t`codex features enable ${CODEX_FEATURE}\\ncodex mcp add ${n} --url ${a}`,\n\t\t\t\t\t]) as [string, string | undefined]),\n\t\t\t[\n\t\t\t\t\"Start a new chat in Codex after it connects. The first line turns on a feature for all of Codex's MCP servers; \",\n\t\t\t\t`codex features disable ${CODEX_FEATURE}`,\n\t\t\t\t\" turns it off.\",\n\t\t\t],\n\t\t],\n\t];\n}\n\n/** \"A and B\", \"A, B and C\". */\nfunction listOf(items: string[]): string {\n\treturn items.length < 2\n\t\t? (items[0] ?? \"\")\n\t\t: `${items.slice(0, -1).join(\", \")} and ${items.at(-1)}`;\n}\n\n/** The document of the connect dialog per `TabMcp`, once it was opened. */\nconst watched = new WeakMap<TabMcp, Document>();\n\n/**\n * Once a page has opened the connect dialog, the default UI also says when\n * the page loses its address (`replaced`), in that dialog's document.\n */\nfunction watchReplaced(mcp: TabMcp, doc: Document): void {\n\tconst known = watched.has(mcp);\n\twatched.set(mcp, doc);\n\tif (known) return;\n\tmcp.addEventListener(\"replaced\", (event) => {\n\t\tconst current = watched.get(mcp);\n\t\t// Not when the page already went on (a New address or connect since).\n\t\tif (current !== undefined && mcp.state === \"disconnected\")\n\t\t\treplacedNotice(mcp, current, event.detail.sibling);\n\t});\n}\n\n/**\n * Says that the page lost its address (`replaced`, DEC-095). A sibling tab\n * that announced it: \"Opened in another tab\", nothing to do. Otherwise a\n * warning that another tab or program took over, with \"New address\", which\n * takes the address back, disconnects its apps, connects with a new one and\n * opens the connect dialog to add it to the AI apps again.\n */\nexport function replacedNotice(\n\tmcp: TabMcp,\n\tdoc: Document,\n\tsibling: boolean,\n): void {\n\t(\n\t\tdoc.querySelector(\"dialog.tab-mcp-replaced\") as HTMLDialogElement | null\n\t)?.close();\n\tconst { dialog } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-replaced\",\n\t\tsibling\n\t\t\t? \"Opened in another tab\"\n\t\t\t: \"Another tab or program took over this page\",\n\t);\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\tstatus.hidden = true;\n\tconst close = button(\n\t\tdoc,\n\t\t\"Close\",\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-replaced-close\",\n\t\tsibling ? \"primary\" : undefined,\n\t);\n\tconst actions = el(doc, \"div\", { className: \"tab-mcp-actions\" }, close);\n\tlet first = close;\n\tif (!sibling) {\n\t\tconst fresh = button(\n\t\t\tdoc,\n\t\t\t\"New address\",\n\t\t\t() => {\n\t\t\t\tfresh.disabled = true;\n\t\t\t\tstatus.hidden = false;\n\t\t\t\tstatus.textContent = \"Getting a new address…\";\n\t\t\t\tmcp.newAddress().then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tdialog.close();\n\t\t\t\t\t\tmcp.showConnectDialog({ document: doc }).catch(() => {});\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tfresh.disabled = false;\n\t\t\t\t\t\tstatus.textContent =\n\t\t\t\t\t\t\t(error as { reason?: unknown } | null)?.reason === \"replaced\"\n\t\t\t\t\t\t\t\t? \"It was taken over again before its AI apps were disconnected. Try again.\"\n\t\t\t\t\t\t\t\t: `Could not connect: ${error instanceof Error ? error.message : String(error)}. Try again, or close this.`;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t},\n\t\t\t\"tab-mcp-new-address\",\n\t\t\t\"primary\",\n\t\t);\n\t\tactions.append(\" \", fresh);\n\t\tfirst = fresh;\n\t}\n\tdialog.append(\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: sibling\n\t\t\t\t? \"This page is open in another tab, and your AI apps now use that one. To use them here, connect this page again.\"\n\t\t\t\t: \"Your AI apps now reach that tab or program instead of this page. If you did not open this page in another tab or browser, someone may have copied its address. A new address disconnects every AI app from the old one; then add the new address to your AI apps again.\",\n\t\t}),\n\t\tstatus,\n\t\tactions,\n\t);\n\tdialog.addEventListener(\"close\", () => dialog.remove(), { once: true });\n\tdoc.body.append(dialog);\n\tdialog.showModal();\n\tfirst.focus();\n}\n\n/**\n * The \"Connect your AI app\" dialog: the address with Copy and New address,\n * short instructions, the pairing code (with Copy) while the relay sends one,\n * and the connected apps with Disconnect. Pairing is on while it is open, so\n * closing it ends the code; the connection and the address stay. Until an app\n * connects, only a small Close (and Escape) close it; then a Done. New address\n * asks first when it would disconnect connected apps (`newAddress()` revokes\n * them). When the page loses its address (`replaced`), this dialog closes and\n * `replacedNotice` says why, from then on also while it is closed.\n */\nexport function showConnectDialog(\n\tmcp: TabMcp,\n\tconnecting: Promise<SessionInfo>,\n\tdoc: Document,\n\tserverName = \"tools\",\n): Promise<void> {\n\tconst { dialog } = newDialog(doc, \"tab-mcp-connect\", \"Connect your AI app\");\n\t// Focusable from script only, for the moment before the address is shown.\n\tdialog.tabIndex = -1;\n\tconst status = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-status\",\n\t\ttext: \"Connecting…\",\n\t});\n\tstatus.setAttribute(\"role\", \"status\");\n\t// What a Copy did, for assistive technology only; out of sight, also\n\t// without the stylesheet. The same message twice is still a change.\n\tconst live = el(doc, \"span\", { className: \"tab-mcp-announce\" });\n\tlive.setAttribute(\"aria-live\", \"polite\");\n\tfor (const [property, value] of [\n\t\t[\"position\", \"absolute\"],\n\t\t[\"width\", \"1px\"],\n\t\t[\"height\", \"1px\"],\n\t\t[\"overflow\", \"hidden\"],\n\t\t[\"clip-path\", \"inset(50%)\"],\n\t\t[\"white-space\", \"nowrap\"],\n\t])\n\t\tlive.style.setProperty(property as string, value as string);\n\tconst announce = (text: string) => {\n\t\tlive.textContent = live.textContent === text ? `${text}\\u00a0` : text;\n\t};\n\n\tconst addressId = `tab-mcp-${++counter}-address`;\n\tconst label = el(doc, \"label\", { text: \"Add this address to your AI app:\" });\n\tlabel.htmlFor = addressId;\n\tconst address = el(doc, \"input\", {\n\t\tid: addressId,\n\t\tclassName: \"tab-mcp-address-input\",\n\t});\n\taddress.readOnly = true;\n\t// Copying the address is the first step: the primary button.\n\tconst { button: copy, reset: resetCopy } = copyButton(\n\t\tdoc,\n\t\t\"address\",\n\t\t() => address.value,\n\t\t() => address.select(),\n\t\tannounce,\n\t\t\"tab-mcp-address-copy\",\n\t\t\"primary\",\n\t);\n\tconst fresh = button(\n\t\tdoc,\n\t\t\"New address\",\n\t\t() => askNewAddress(),\n\t\t\"tab-mcp-new-address\",\n\t);\n\tconst addressBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-address\" },\n\t\tlabel,\n\t\taddress,\n\t\t\" \",\n\t\tcopy,\n\t\t\" \",\n\t\tfresh,\n\t);\n\n\t// Asked in the dialog before New address disconnects connected apps.\n\tconst confirmId = `tab-mcp-${++counter}-new-address`;\n\tconst confirmText = el(doc, \"p\", { id: confirmId });\n\tconst cancelNew = button(doc, \"Cancel\", () => {\n\t\tconfirmBox.hidden = true;\n\t\tfresh.focus();\n\t});\n\tconst confirmNew = button(\n\t\tdoc,\n\t\t\"Disconnect and get new address\",\n\t\t() => getNewAddress(),\n\t\t\"tab-mcp-new-address-confirm\",\n\t\t\"danger\",\n\t);\n\tconst confirmBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-question\" },\n\t\tconfirmText,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-actions\" },\n\t\t\tcancelNew,\n\t\t\t\" \",\n\t\t\tconfirmNew,\n\t\t),\n\t);\n\tconfirmBox.setAttribute(\"role\", \"group\");\n\tconfirmBox.setAttribute(\"aria-labelledby\", confirmId);\n\tconfirmBox.hidden = true;\n\n\t// Large, in a monospace font: a new code takes the same room.\n\tconst code = el(doc, \"strong\", { className: \"tab-mcp-code-value\" });\n\t// One click selects the whole code; it stays plain, selectable text.\n\tcode.style.setProperty(\"user-select\", \"all\");\n\tcode.style.setProperty(\"-webkit-user-select\", \"all\");\n\t// Reads the code shown at click time, so a rotated code is copied as shown.\n\tconst { button: copyCode, reset: resetCopyCode } = copyButton(\n\t\tdoc,\n\t\t\"code\",\n\t\t() => code.textContent ?? \"\",\n\t\t() => doc.getSelection()?.selectAllChildren(code),\n\t\tannounce,\n\t\t\"tab-mcp-code-copy\",\n\t);\n\t// Only the sentence with the code is announced when the code changes,\n\t// not its Copy button's \"Copied\".\n\tconst codeSentence = el(doc, \"span\", {}, \"When asked, enter the code \", code);\n\tcodeSentence.setAttribute(\"aria-live\", \"polite\");\n\tconst codeLine = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ className: \"tab-mcp-code\" },\n\t\tcodeSentence,\n\t\t\" \",\n\t\tcopyCode,\n\t\tel(doc, \"br\"),\n\t\tel(doc, \"small\", {\n\t\t\tclassName: \"tab-mcp-code-note\",\n\t\t\ttext: \"A new code appears every 2 minutes and after each use.\",\n\t\t}),\n\t);\n\t// Identity binding: no code, the same account at the AI app's sign-in.\n\tconst signInLine = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-sign-in\",\n\t\ttext: \"When your AI app asks, sign in with the account you use on this page. No code is needed.\",\n\t});\n\n\tconst steps = el(doc, \"ul\");\n\tconst guide = el(doc, \"a\", {\n\t\ttext: \"Step by step, and what to do when it fails\",\n\t});\n\tguide.href = GUIDE;\n\tguide.target = \"_blank\";\n\tguide.rel = \"noopener noreferrer\";\n\tconst help = el(\n\t\tdoc,\n\t\t\"details\",\n\t\t{ className: \"tab-mcp-help\" },\n\t\tel(doc, \"summary\", { text: \"How do I add it?\" }),\n\t\tsteps,\n\t\tel(doc, \"p\", { className: \"tab-mcp-guide\" }, guide),\n\t);\n\n\tconst appList = el(doc, \"ul\");\n\tconst apps = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-apps\" },\n\t\tel(doc, \"h3\", { text: \"Connected\" }),\n\t\tappList,\n\t);\n\n\t// Until an app connects in this dialog, closing it is not the next step:\n\t// a small Close at the end, saying what closing does (the code stops, the\n\t// address stays). Once one connects, a prominent Done replaces both.\n\tconst closeNote = el(doc, \"small\", {\n\t\tclassName: \"tab-mcp-close-note\",\n\t\ttext: \"Closing this stops the code. The address stays the same: to connect later, open this again from the page.\",\n\t});\n\tconst close = button(doc, \"Close\", () => dialog.close(), \"tab-mcp-close\");\n\tconst done = button(\n\t\tdoc,\n\t\t\"Done\",\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-done\",\n\t\t\"primary\",\n\t);\n\tdone.hidden = true;\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tcloseNote,\n\t\t\" \",\n\t\tclose,\n\t\tdone,\n\t);\n\t// The note on the left, the button at the far right, apart from the code.\n\t// An app connected while this dialog is open (since the last new address),\n\t// and still connected: the grants that made it so.\n\tlet paired = false;\n\tconst pairedGrants = new Set<string>();\n\t// The note is about the code: only while one is shown and nothing paired.\n\tconst renderCloseNote = () => {\n\t\tcloseNote.hidden = paired || codeLine.hidden;\n\t};\n\tconst setPaired = (value: boolean) => {\n\t\tpaired = value;\n\t\tif (!paired) pairedGrants.clear();\n\t\tconst focused = doc.activeElement;\n\t\trenderCloseNote();\n\t\tclose.hidden = paired;\n\t\tdone.hidden = !paired;\n\t\t// Focus never stays on a control that was just hidden.\n\t\tif (paired && focused === close) done.focus();\n\t\tif (!paired && focused === done) close.focus();\n\t};\n\t// The visible button that closes the dialog.\n\tconst closer = () => (paired ? done : close);\n\n\tdialog.append(\n\t\tstatus,\n\t\taddressBox,\n\t\tconfirmBox,\n\t\tcodeLine,\n\t\tsignInLine,\n\t\thelp,\n\t\tapps,\n\t\tactions,\n\t\tlive,\n\t);\n\taddressBox.hidden = true;\n\tcodeLine.hidden = true;\n\tsignInLine.hidden = true;\n\thelp.hidden = true;\n\tapps.hidden = true;\n\n\t// Set while New address waits for the new session.\n\tlet renewing = false;\n\t// The question names the apps connected now; pairing goes on while it is open.\n\tconst renderQuestion = (): boolean => {\n\t\tconst names = mcp.grants.map((g) => clientLabel(g.client));\n\t\tif (names.length === 0) return false;\n\t\tconfirmText.textContent = `A new address disconnects ${listOf(names)}. To use this page again, add the new address to ${names.length === 1 ? \"it\" : \"them\"}.`;\n\t\treturn true;\n\t};\n\tconst askNewAddress = () => {\n\t\tif (mcp.state !== \"connected\") return;\n\t\tif (!renderQuestion()) {\n\t\t\tgetNewAddress();\n\t\t\treturn;\n\t\t}\n\t\tconfirmBox.hidden = false;\n\t\tcancelNew.focus(); // the safe choice is the default\n\t};\n\tconst getNewAddress = () => {\n\t\t// The apps are disconnected: the next one has to pair again.\n\t\tsetPaired(false);\n\t\t// Focus moves before the focused control is hidden.\n\t\tclose.focus();\n\t\tconfirmBox.hidden = true;\n\t\trenewing = true;\n\t\tstatus.textContent = \"Getting a new address…\";\n\t\t// Called from the click, so the reconnect has the user action it needs.\n\t\tmcp.newAddress().then(\n\t\t\t() => {\n\t\t\t\trenewing = false;\n\t\t\t\tstatus.textContent =\n\t\t\t\t\t\"This is a new address. Add it to your AI app again.\";\n\t\t\t\tcopy.focus();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\trenewing = false;\n\t\t\t\tstatus.textContent = `Could not connect: ${error instanceof Error ? error.message : String(error)}. Close this and connect again.`;\n\t\t\t\tcloser().focus();\n\t\t\t},\n\t\t);\n\t};\n\tconst renderSession = (session: SessionInfo | undefined) => {\n\t\tif (session === undefined) {\n\t\t\taddressBox.hidden = true;\n\t\t\tconfirmBox.hidden = true;\n\t\t\thelp.hidden = true;\n\t\t\treturn;\n\t\t}\n\t\taddress.value = session.address;\n\t\tresetCopy();\n\t\tconst appName = session.appName ?? mcp.appName;\n\t\tif (!renewing)\n\t\t\tstatus.textContent =\n\t\t\t\tappName !== undefined\n\t\t\t\t\t? `${appName} is ready for your AI app.`\n\t\t\t\t\t: \"This page is ready for your AI app.\";\n\t\tfresh.disabled = mcp.state !== \"connected\";\n\t\taddressBox.hidden = false;\n\t\t// Opened before the session was known: start at the address's Copy.\n\t\tif (doc.activeElement === dialog) copy.focus();\n\t\thelp.hidden = false;\n\t\tsteps.replaceChildren(\n\t\t\t...instructions(serverName, session.address).map(\n\t\t\t\t([app, how, command, note]) => {\n\t\t\t\t\tconst item = el(\n\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\"li\",\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tel(doc, \"strong\", { text: `${app}:` }),\n\t\t\t\t\t\t` ${how}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (command !== undefined) {\n\t\t\t\t\t\t// A block with its own Copy, like the code.\n\t\t\t\t\t\tconst text = el(doc, \"pre\", { text: command });\n\t\t\t\t\t\ttext.dir = \"ltr\";\n\t\t\t\t\t\tconst { button: copyCommand } = copyButton(\n\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t`${app} command`,\n\t\t\t\t\t\t\t() => text.textContent ?? \"\",\n\t\t\t\t\t\t\t() => doc.getSelection()?.selectAllChildren(text),\n\t\t\t\t\t\t\tannounce,\n\t\t\t\t\t\t\t\"tab-mcp-command-copy\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"div\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command\" },\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\tcopyCommand,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (note !== undefined)\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"small\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command-note\" },\n\t\t\t\t\t\t\t\t...note.map((part, i) =>\n\t\t\t\t\t\t\t\t\ti % 2 === 1 ? el(doc, \"code\", { text: part }) : part,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\treturn item;\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t};\n\tconst renderCode = () => {\n\t\tconst current = mcp.pairingCode;\n\t\tconst oidc = mcp.session?.pairing === \"oidc\";\n\t\t// A new code is not copied yet.\n\t\tif (code.textContent !== (current?.code ?? \"\")) resetCopyCode();\n\t\tcode.textContent = current?.code ?? \"\";\n\t\tcodeLine.hidden = oidc || current === undefined;\n\t\tsignInLine.hidden = !oidc;\n\t\trenderCloseNote();\n\t};\n\tconst appsNote = el(doc, \"p\", { className: \"tab-mcp-apps-note\" });\n\tapps.append(appsNote);\n\t// Grants that were there when the dialog opened; a new one is announced.\n\tconst known = new Set(mcp.grants.map((g) => g.grantId));\n\t// Grants that come with a (new) session were there before; only the ones\n\t// added during a session are new connections.\n\tlet session = mcp.session;\n\tconst renderGrants = () => {\n\t\tif (mcp.session !== session) {\n\t\t\tsession = mcp.session;\n\t\t\tfor (const grant of mcp.grants) known.add(grant.grantId);\n\t\t}\n\t\tfor (const grant of mcp.grants) {\n\t\t\tif (known.has(grant.grantId)) continue;\n\t\t\tknown.add(grant.grantId);\n\t\t\tstatus.textContent = `${clientLabel(grant.client)} is connected.`;\n\t\t\tpairedGrants.add(grant.grantId);\n\t\t\tif (!paired) setPaired(true);\n\t\t}\n\t\t// The app that connected here is gone again (Disconnect, or revoked):\n\t\t// back to Close and the note, the code still runs.\n\t\tif (paired && !mcp.grants.some((g) => pairedGrants.has(g.grantId))) {\n\t\t\tsetPaired(false);\n\t\t}\n\t\tconst connected = mcp.state === \"connected\";\n\t\tappList.replaceChildren(\n\t\t\t...mcp.grants.map((grant) => {\n\t\t\t\tconst disconnect = button(\n\t\t\t\t\tdoc,\n\t\t\t\t\t\"Disconnect\",\n\t\t\t\t\t() => {\n\t\t\t\t\t\tif (!mcp.revoke(grant.grantId)) renderGrants();\n\t\t\t\t\t},\n\t\t\t\t\t\"tab-mcp-disconnect\",\n\t\t\t\t\t\"danger\",\n\t\t\t\t);\n\t\t\t\t// Only the relay can revoke, so only while connected.\n\t\t\t\tdisconnect.disabled = !connected;\n\t\t\t\treturn el(\n\t\t\t\t\tdoc,\n\t\t\t\t\t\"li\",\n\t\t\t\t\t{},\n\t\t\t\t\tel(doc, \"span\", {\n\t\t\t\t\t\tclassName: \"tab-mcp-app\",\n\t\t\t\t\t\ttext: `${clientLabel(grant.client)} connected `,\n\t\t\t\t\t}),\n\t\t\t\t\tdisconnect,\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\t\tappsNote.textContent = connected\n\t\t\t? \"\"\n\t\t\t: \"To disconnect an app, connect this page again first.\";\n\t\tappsNote.hidden = connected;\n\t\tapps.hidden = mcp.grants.length === 0;\n\t\tif (!confirmBox.hidden && !renderQuestion()) {\n\t\t\t// Nobody left to disconnect: no question needed.\n\t\t\tconfirmBox.hidden = true;\n\t\t\tfresh.focus();\n\t\t}\n\t};\n\tconst onDisconnected = (event: CustomEvent<DisconnectDetail>) => {\n\t\tif (event.detail.reason !== \"new_address\")\n\t\t\tstatus.textContent =\n\t\t\t\t\"Disconnected. AI apps can use this page again after you connect.\";\n\t\trenderSession(undefined);\n\t\trenderGrants();\n\t\trenderCode();\n\t};\n\tconst onConnected = () => {\n\t\trenderSession(mcp.session);\n\t\trenderGrants();\n\t\trenderCode();\n\t};\n\n\t// The address was taken over: the notice says so instead of this dialog.\n\tconst onReplaced = () => dialog.close();\n\twatchReplaced(mcp, doc);\n\tmcp.addEventListener(\"pairingcode\", renderCode);\n\tmcp.addEventListener(\"grantschange\", renderGrants);\n\tmcp.addEventListener(\"connected\", onConnected);\n\tmcp.addEventListener(\"disconnected\", onDisconnected);\n\tmcp.addEventListener(\"replaced\", onReplaced);\n\tdoc.body.append(dialog);\n\tmcp.startPairing();\n\trenderGrants();\n\trenderCode();\n\trenderSession(mcp.session);\n\tconnecting.then(\n\t\t(session) => renderSession(session),\n\t\t(error: unknown) => {\n\t\t\tstatus.textContent = `Could not connect: ${error instanceof Error ? error.message : String(error)}`;\n\t\t},\n\t);\n\n\treturn new Promise((resolve) => {\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tmcp.stopPairing();\n\t\t\t\tmcp.removeEventListener(\"pairingcode\", renderCode);\n\t\t\t\tmcp.removeEventListener(\"grantschange\", renderGrants);\n\t\t\t\tmcp.removeEventListener(\"connected\", onConnected);\n\t\t\t\tmcp.removeEventListener(\"disconnected\", onDisconnected);\n\t\t\t\tmcp.removeEventListener(\"replaced\", onReplaced);\n\t\t\t\tdialog.remove();\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tdialog.showModal();\n\t\t// Start at the address's Copy; until the address is there, at the\n\t\t// dialog itself (its title is read out), not at Close.\n\t\tif (!addressBox.hidden) copy.focus();\n\t\telse dialog.focus();\n\t});\n}\n"
7
- ],
8
- "mappings": "AAMO,MAAM,CAAc,CACjB,GAAS,IAAI,IAEtB,GAAG,CAAC,EAAiB,EAAuB,CAC3C,OAAO,KAAK,GAAO,IAAI,CAAO,GAAG,IAAI,CAAI,IAAM,GAGhD,GAAG,CAAC,EAAiB,EAAoB,CACxC,IAAM,EAAQ,KAAK,GAAO,IAAI,CAAO,GAAK,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