@tensorpass/aiconnect 0.1.7 → 0.1.9

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.
@@ -13,7 +13,7 @@ import { compilePatterns } from "./policy.js";
13
13
  const ENVELOPE_TAG = /<\/?\s*(?:instructions?|tool-result|attachment|steering)-/i;
14
14
  const IMAGE = /!\[[^\]\n]*\]\(|<img\b/i;
15
15
  const EMAIL = /[^\s@<>()[\]"'`:]+@[^\s@<>()[\]"'`]+\.[a-z]{2,}/gi;
16
- const LINK_TARGET = /\]\(\s*<?([^)\s>]+)|\b(https?:\/\/[^\s)\]>"'`]+)|<a\b[^>]*\bhref\s*=\s*["']?([^"'\s>]+)|\b(www\.[^\s)\]>"'`]+)/gi;
16
+ const LINK_TARGET = /\]\(\s*<?([^)\s>]+)|\b(https?:\/\/[^\s)\]>"'`*]+)|<a\b[^>]*\bhref\s*=\s*["']?([^"'\s>]+)|\b(www\.[^\s)\]>"'`*]+)/gi;
17
17
  const TRAILING_PUNCTUATION = /[.,;:!?]+$/;
18
18
  // Stands for the page's origin where the guard runs without a page, such as a site's server.
19
19
  const NO_PAGE_ORIGIN = 'https://page.invalid';
@@ -1 +1 @@
1
- {"version":3,"file":"answerGuard.js","sourceRoot":"","sources":["../../src/guards/answerGuard.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,sGAAsG;AACtG,oGAAoG;AACpG,oGAAoG;AACpG,uGAAuG;AACvG,uGAAuG;AACvG,uGAAuG;AACvG,sGAAsG;AACtG,oGAAoG;AACpG,mGAAmG;AACnG,+FAA+F;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAsB9C,MAAM,YAAY,GAAG,4DAA4D,CAAC;AAClF,MAAM,KAAK,GAAG,yBAAyB,CAAC;AACxC,MAAM,KAAK,GAAG,mDAAmD,CAAC;AAClE,MAAM,WAAW,GAAG,kHAAkH,CAAC;AACvI,MAAM,oBAAoB,GAAG,YAAY,CA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,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACpG,IAAI,IAAI,EAAE,CAAC;QACT,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACrD,CAAC;IACD,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;IACvG,IAAI,KAAK,EAAE,CAAC;QACV,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IACvD,CAAC;IACD,OAAO,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;AACjD,CAAC;AAED,yGAAyG;AACzG,sGAAsG;AACtG,YAAY;AACZ,MAAM,UAAU,eAAe,CAAC,IAAY,EAAE,MAAmB;IAC/D,OAAO,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["// The guard on the model's answer, run as it streams and once it ends, before the visitor sees it. An\n// answer stops on an envelope tag or the salt, which mean the model is repeating its instructions; on\n// an image, which loads by itself and can carry the conversation to another server; on a link or an\n// email address that comes from neither the site, its tools, nor the visitor; and on the site's own\n// internal names and withheld content. A web address or an email address counts as the tools' own when\n// a result gives it as a whole field, such as a restaurant's `website` or a shop's `email`: the result\n// is read as JSON, and a string of it that is one address and nothing else is such a field. An address\n// written inside free text, such as a review a third party planted, is none, whatever quotes surround\n// it, and a result that is not JSON gives no address at all. While the answer streams, a link or an\n// address still being written is left for the next check, so a host is judged once it is complete.\n// Every address is read with the URL parser, which resolves it as the browser does on a click.\n\nimport { compilePatterns } from './policy.ts';\nimport type { AnswerVerdict, GuardPolicy } from './policy.ts';\n\nexport interface AnswerContext {\n salt?: string;\n policy?: GuardPolicy;\n // Everything the visitor typed in the conversation.\n visitorText?: string;\n // Each result the site's tools returned in the conversation, as the tool gave it. A conversation\n // adds its results to the same list, which the guard reads once each.\n toolResults?: readonly string[];\n // The page's own origin, whose pages an answer may always link to.\n origin?: string;\n // The answer is still streaming.\n partial?: boolean;\n}\n\ninterface Found {\n value: string;\n end: number;\n}\n\nconst ENVELOPE_TAG = /<\\/?\\s*(?:instructions?|tool-result|attachment|steering)-/i;\nconst IMAGE = /!\\[[^\\]\\n]*\\]\\(|<img\\b/i;\nconst EMAIL = /[^\\s@<>()[\\]\"'`:]+@[^\\s@<>()[\\]\"'`]+\\.[a-z]{2,}/gi;\nconst LINK_TARGET = /\\]\\(\\s*<?([^)\\s>]+)|\\b(https?:\\/\\/[^\\s)\\]>\"'`]+)|<a\\b[^>]*\\bhref\\s*=\\s*[\"']?([^\"'\\s>]+)|\\b(www\\.[^\\s)\\]>\"'`]+)/gi;\nconst TRAILING_PUNCTUATION = /[.,;:!?]+$/;\n// Stands for the page's origin where the guard runs without a page, such as a site's server.\nconst NO_PAGE_ORIGIN = 'https://page.invalid';\n\nconst compiled = new WeakMap<GuardPolicy, { deny: RegExp[]; withhold: RegExp[] }>();\n\nfunction patternsOf(policy: GuardPolicy) {\n let patterns = compiled.get(policy);\n if (!patterns) {\n patterns = { deny: compilePatterns(policy.denyPatterns), withhold: compilePatterns(policy.withholdPatterns) };\n compiled.set(policy, patterns);\n }\n return patterns;\n}\n\n// The values found, without the ones running to the end of a streaming answer, which are still being\n// written.\nfunction finished(found: Found[], text: string, partial = false): string[] {\n return found.filter((item) => !partial || item.end < text.length).map((item) => item.value);\n}\n\nfunction linkTargets(text: string): Found[] {\n return [...text.matchAll(LINK_TARGET)].map((match) => {\n const [, markdown, bare, anchor, www] = match;\n const value = markdown ?? anchor ?? `${www ? 'https://' : ''}${(bare ?? www).replace(TRAILING_PUNCTUATION, '')}`;\n return { value, end: match.index + match[0].length };\n });\n}\n\nfunction emails(text: string): Found[] {\n return [...text.matchAll(EMAIL)].map((match) => ({\n value: match[0].toLowerCase(),\n end: match.index + match[0].length,\n }));\n}\n\nconst withoutFinalSlash = (href: string) => href.replace(/\\/+$/, '');\n\nconst WHOLE_ADDRESS = /^https?:\\/\\/\\S+$/;\nconst WHOLE_EMAIL = /^[^\\s@<>()[\\]\"'`:]+@[^\\s@<>()[\\]\"'`]+\\.[a-z]{2,}$/i;\n\n// The strings of a parsed result, at any depth.\nfunction stringsIn(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n return typeof value === 'object' && value !== null ? Object.values(value).flatMap(stringsIn) : [];\n}\n\n// The strings one tool result gives as fields. Only an object or a list has fields: a result that is\n// free text, a tool error or a lone string gives none.\nfunction fieldsOf(result: string): string[] {\n try {\n const parsed: unknown = JSON.parse(result);\n return typeof parsed === 'object' ? stringsIn(parsed) : [];\n } catch {\n return [];\n }\n}\n\ninterface ToolFields {\n // How many results of the list were read.\n results: number;\n // The fields that are one web address and nothing else.\n addresses: Set<string>;\n // The fields that are one email address and nothing else, in lower case.\n emails: Set<string>;\n}\n\n// What was read so far from each list of results.\nconst fieldsRead = new WeakMap<readonly string[], ToolFields>();\n\n// The web and email addresses the site's tools returned as whole fields of their results.\nfunction toolFields(results: readonly string[] = []): ToolFields {\n const read = fieldsRead.get(results) ?? { results: 0, addresses: new Set<string>(), emails: new Set<string>() };\n fieldsRead.set(results, read);\n for (; read.results < results.length; read.results += 1) {\n for (const field of fieldsOf(results[read.results])) {\n if (WHOLE_ADDRESS.test(field)) {\n read.addresses.add(withoutFinalSlash(field));\n } else if (WHOLE_EMAIL.test(field)) {\n read.emails.add(field.toLowerCase());\n }\n }\n }\n return read;\n}\n\n// Whether an answer may give `email`: the visitor typed it, the policy lists it, or a tool returned it\n// as a whole field.\nexport function emailAllowed(email: string, context: AnswerContext): boolean {\n const address = email.toLowerCase();\n const typed = (context.visitorText ?? '').toLowerCase().replace(/\\s+/g, '');\n const published = (context.policy?.allowedEmails ?? []).map((item) => item.toLowerCase());\n return published.includes(address) || typed.includes(address) || toolFields(context.toolResults).emails.has(address);\n}\n\n// Whether `hostname` is the page's own host or one the policy allows. A page whose origin is opaque,\n// such as the `null` of a sandboxed frame, has no host of its own.\nfunction hostAllowed(hostname: string, context: AnswerContext): boolean {\n const own = context.origin ? parsedUrl(context.origin)?.hostname : undefined;\n return hostname === own || (context.policy?.allowedLinkHosts ?? [])\n .some((host) => hostname === host || hostname.endsWith(`.${host}`));\n}\n\nfunction parsedUrl(address: string, base?: string): URL | null {\n try {\n return new URL(address, base);\n } catch {\n return null;\n }\n}\n\n// The fields of a mailto: link that add addresses to send to (RFC 6068).\nconst RECIPIENT_FIELDS = new Set(['to', 'cc', 'bcc']);\n\n// The addresses a mailto: link sends to, decoded as a mail client reads them: the one before the `?`\n// and those of its to, cc and bcc fields. Written with escapes, as in `cc=a%40b%2Eexample`, they pass\n// the email scan of the answer unseen. An escape that does not decode, such as `%E0%A4%A`, gives no\n// address, and the link is refused.\nfunction mailtoRecipients(href: string): string[] | null {\n const target = href.slice('mailto:'.length);\n const question = target.indexOf('?');\n const fields = question === -1 ? [] : target.slice(question + 1).split('&').map((field) => field.split('='));\n try {\n const added = fields.filter(([name]) => RECIPIENT_FIELDS.has(decodeURIComponent(name).toLowerCase()))\n .map(([, ...value]) => decodeURIComponent(value.join('=')));\n const path = decodeURIComponent(question === -1 ? target : target.slice(0, question));\n return [path, ...added].filter((address) => address !== '');\n } catch {\n return null;\n }\n}\n\n// Whether `href` is an address written without its site that leads to a page of `origin`, the page's\n// own when none is given. `/returns`, `#top` and `../a` do. `//host`, `/\\host` and an address with its\n// own scheme lead elsewhere, whatever tabs, line breaks or encoding they are written with.\nexport function leadsToSitePage(href: string, origin = NO_PAGE_ORIGIN): boolean {\n const site = parsedUrl(origin);\n const target = parsedUrl(href, origin);\n return site !== null && target !== null && parsedUrl(href) === null && target.origin === site.origin;\n}\n\n// Whether an answer may link to `href`: a path of the site, a page of its origin or of an allowed host,\n// an address a tool returned as a field, as it is, or a mailto: link whose every address the\n// conversation allows.\nexport function linkAllowed(href: string, context: AnswerContext): boolean {\n if (leadsToSitePage(href, context.origin)) {\n return true;\n }\n if (/^mailto:/i.test(href)) {\n const recipients = mailtoRecipients(href);\n return recipients !== null && recipients.every((address) => emailAllowed(address, context));\n }\n const url = parsedUrl(href);\n if (url?.protocol !== 'https:' && url?.protocol !== 'http:') {\n return false;\n }\n return hostAllowed(url.hostname, context) || toolFields(context.toolResults).addresses.has(withoutFinalSlash(href));\n}\n\nfunction patternStop(text: string, policy: GuardPolicy): AnswerVerdict {\n const { deny, withhold } = patternsOf(policy);\n const denied = deny.find((re) => re.test(text));\n if (denied) {\n return { ok: false, reason: 'denied', detail: denied.source };\n }\n return withhold.some((re) => re.test(text)) ? { ok: false, reason: 'withheld' } : { ok: true };\n}\n\nexport function validateAnswer(text: string, context: AnswerContext = {}): AnswerVerdict {\n const { salt, partial } = context;\n if (ENVELOPE_TAG.test(text)) {\n return { ok: false, reason: 'envelope-tag' };\n }\n if (salt && text.includes(salt)) {\n return { ok: false, reason: 'salt' };\n }\n if (IMAGE.test(text)) {\n return { ok: false, reason: 'image' };\n }\n const link = finished(linkTargets(text), text, partial).find((href) => !linkAllowed(href, context));\n if (link) {\n return { ok: false, reason: 'link', detail: link };\n }\n const email = finished(emails(text), text, partial).find((address) => !emailAllowed(address, context));\n if (email) {\n return { ok: false, reason: 'email', detail: email };\n }\n return patternStop(text, context.policy ?? {});\n}\n\n// The guard a site's MCP server runs on each tool result before it leaves the server: the internal names\n// and the withheld content of its policy. Anyone can call the server without the page, so these never\n// leave it.\nexport function checkToolResult(text: string, policy: GuardPolicy): AnswerVerdict {\n return patternStop(text, policy);\n}\n"]}
1
+ {"version":3,"file":"answerGuard.js","sourceRoot":"","sources":["../../src/guards/answerGuard.ts"],"names":[],"mappings":"AAAA,sGA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visitor sees it. An\n// answer stops on an envelope tag or the salt, which mean the model is repeating its instructions; on\n// an image, which loads by itself and can carry the conversation to another server; on a link or an\n// email address that comes from neither the site, its tools, nor the visitor; and on the site's own\n// internal names and withheld content. A web address or an email address counts as the tools' own when\n// a result gives it as a whole field, such as a restaurant's `website` or a shop's `email`: the result\n// is read as JSON, and a string of it that is one address and nothing else is such a field. An address\n// written inside free text, such as a review a third party planted, is none, whatever quotes surround\n// it, and a result that is not JSON gives no address at all. While the answer streams, a link or an\n// address still being written is left for the next check, so a host is judged once it is complete.\n// Every address is read with the URL parser, which resolves it as the browser does on a click.\n\nimport { compilePatterns } from './policy.ts';\nimport type { AnswerVerdict, GuardPolicy } from './policy.ts';\n\nexport interface AnswerContext {\n salt?: string;\n policy?: GuardPolicy;\n // Everything the visitor typed in the conversation.\n visitorText?: string;\n // Each result the site's tools returned in the conversation, as the tool gave it. A conversation\n // adds its results to the same list, which the guard reads once each.\n toolResults?: readonly string[];\n // The page's own origin, whose pages an answer may always link to.\n origin?: string;\n // The answer is still streaming.\n partial?: boolean;\n}\n\ninterface Found {\n value: string;\n end: number;\n}\n\nconst ENVELOPE_TAG = /<\\/?\\s*(?:instructions?|tool-result|attachment|steering)-/i;\nconst IMAGE = /!\\[[^\\]\\n]*\\]\\(|<img\\b/i;\nconst EMAIL = /[^\\s@<>()[\\]\"'`:]+@[^\\s@<>()[\\]\"'`]+\\.[a-z]{2,}/gi;\nconst LINK_TARGET = /\\]\\(\\s*<?([^)\\s>]+)|\\b(https?:\\/\\/[^\\s)\\]>\"'`*]+)|<a\\b[^>]*\\bhref\\s*=\\s*[\"']?([^\"'\\s>]+)|\\b(www\\.[^\\s)\\]>\"'`*]+)/gi;\nconst TRAILING_PUNCTUATION = /[.,;:!?]+$/;\n// Stands for the page's origin where the guard runs without a page, such as a site's server.\nconst NO_PAGE_ORIGIN = 'https://page.invalid';\n\nconst compiled = new WeakMap<GuardPolicy, { deny: RegExp[]; withhold: RegExp[] }>();\n\nfunction patternsOf(policy: GuardPolicy) {\n let patterns = compiled.get(policy);\n if (!patterns) {\n patterns = { deny: compilePatterns(policy.denyPatterns), withhold: compilePatterns(policy.withholdPatterns) };\n compiled.set(policy, patterns);\n }\n return patterns;\n}\n\n// The values found, without the ones running to the end of a streaming answer, which are still being\n// written.\nfunction finished(found: Found[], text: string, partial = false): string[] {\n return found.filter((item) => !partial || item.end < text.length).map((item) => item.value);\n}\n\nfunction linkTargets(text: string): Found[] {\n return [...text.matchAll(LINK_TARGET)].map((match) => {\n const [, markdown, bare, anchor, www] = match;\n const value = markdown ?? anchor ?? `${www ? 'https://' : ''}${(bare ?? www).replace(TRAILING_PUNCTUATION, '')}`;\n return { value, end: match.index + match[0].length };\n });\n}\n\nfunction emails(text: string): Found[] {\n return [...text.matchAll(EMAIL)].map((match) => ({\n value: match[0].toLowerCase(),\n end: match.index + match[0].length,\n }));\n}\n\nconst withoutFinalSlash = (href: string) => href.replace(/\\/+$/, '');\n\nconst WHOLE_ADDRESS = /^https?:\\/\\/\\S+$/;\nconst WHOLE_EMAIL = /^[^\\s@<>()[\\]\"'`:]+@[^\\s@<>()[\\]\"'`]+\\.[a-z]{2,}$/i;\n\n// The strings of a parsed result, at any depth.\nfunction stringsIn(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n return typeof value === 'object' && value !== null ? Object.values(value).flatMap(stringsIn) : [];\n}\n\n// The strings one tool result gives as fields. Only an object or a list has fields: a result that is\n// free text, a tool error or a lone string gives none.\nfunction fieldsOf(result: string): string[] {\n try {\n const parsed: unknown = JSON.parse(result);\n return typeof parsed === 'object' ? stringsIn(parsed) : [];\n } catch {\n return [];\n }\n}\n\ninterface ToolFields {\n // How many results of the list were read.\n results: number;\n // The fields that are one web address and nothing else.\n addresses: Set<string>;\n // The fields that are one email address and nothing else, in lower case.\n emails: Set<string>;\n}\n\n// What was read so far from each list of results.\nconst fieldsRead = new WeakMap<readonly string[], ToolFields>();\n\n// The web and email addresses the site's tools returned as whole fields of their results.\nfunction toolFields(results: readonly string[] = []): ToolFields {\n const read = fieldsRead.get(results) ?? { results: 0, addresses: new Set<string>(), emails: new Set<string>() };\n fieldsRead.set(results, read);\n for (; read.results < results.length; read.results += 1) {\n for (const field of fieldsOf(results[read.results])) {\n if (WHOLE_ADDRESS.test(field)) {\n read.addresses.add(withoutFinalSlash(field));\n } else if (WHOLE_EMAIL.test(field)) {\n read.emails.add(field.toLowerCase());\n }\n }\n }\n return read;\n}\n\n// Whether an answer may give `email`: the visitor typed it, the policy lists it, or a tool returned it\n// as a whole field.\nexport function emailAllowed(email: string, context: AnswerContext): boolean {\n const address = email.toLowerCase();\n const typed = (context.visitorText ?? '').toLowerCase().replace(/\\s+/g, '');\n const published = (context.policy?.allowedEmails ?? []).map((item) => item.toLowerCase());\n return published.includes(address) || typed.includes(address) || toolFields(context.toolResults).emails.has(address);\n}\n\n// Whether `hostname` is the page's own host or one the policy allows. A page whose origin is opaque,\n// such as the `null` of a sandboxed frame, has no host of its own.\nfunction hostAllowed(hostname: string, context: AnswerContext): boolean {\n const own = context.origin ? parsedUrl(context.origin)?.hostname : undefined;\n return hostname === own || (context.policy?.allowedLinkHosts ?? [])\n .some((host) => hostname === host || hostname.endsWith(`.${host}`));\n}\n\nfunction parsedUrl(address: string, base?: string): URL | null {\n try {\n return new URL(address, base);\n } catch {\n return null;\n }\n}\n\n// The fields of a mailto: link that add addresses to send to (RFC 6068).\nconst RECIPIENT_FIELDS = new Set(['to', 'cc', 'bcc']);\n\n// The addresses a mailto: link sends to, decoded as a mail client reads them: the one before the `?`\n// and those of its to, cc and bcc fields. Written with escapes, as in `cc=a%40b%2Eexample`, they pass\n// the email scan of the answer unseen. An escape that does not decode, such as `%E0%A4%A`, gives no\n// address, and the link is refused.\nfunction mailtoRecipients(href: string): string[] | null {\n const target = href.slice('mailto:'.length);\n const question = target.indexOf('?');\n const fields = question === -1 ? [] : target.slice(question + 1).split('&').map((field) => field.split('='));\n try {\n const added = fields.filter(([name]) => RECIPIENT_FIELDS.has(decodeURIComponent(name).toLowerCase()))\n .map(([, ...value]) => decodeURIComponent(value.join('=')));\n const path = decodeURIComponent(question === -1 ? target : target.slice(0, question));\n return [path, ...added].filter((address) => address !== '');\n } catch {\n return null;\n }\n}\n\n// Whether `href` is an address written without its site that leads to a page of `origin`, the page's\n// own when none is given. `/returns`, `#top` and `../a` do. `//host`, `/\\host` and an address with its\n// own scheme lead elsewhere, whatever tabs, line breaks or encoding they are written with.\nexport function leadsToSitePage(href: string, origin = NO_PAGE_ORIGIN): boolean {\n const site = parsedUrl(origin);\n const target = parsedUrl(href, origin);\n return site !== null && target !== null && parsedUrl(href) === null && target.origin === site.origin;\n}\n\n// Whether an answer may link to `href`: a path of the site, a page of its origin or of an allowed host,\n// an address a tool returned as a field, as it is, or a mailto: link whose every address the\n// conversation allows.\nexport function linkAllowed(href: string, context: AnswerContext): boolean {\n if (leadsToSitePage(href, context.origin)) {\n return true;\n }\n if (/^mailto:/i.test(href)) {\n const recipients = mailtoRecipients(href);\n return recipients !== null && recipients.every((address) => emailAllowed(address, context));\n }\n const url = parsedUrl(href);\n if (url?.protocol !== 'https:' && url?.protocol !== 'http:') {\n return false;\n }\n return hostAllowed(url.hostname, context) || toolFields(context.toolResults).addresses.has(withoutFinalSlash(href));\n}\n\nfunction patternStop(text: string, policy: GuardPolicy): AnswerVerdict {\n const { deny, withhold } = patternsOf(policy);\n const denied = deny.find((re) => re.test(text));\n if (denied) {\n return { ok: false, reason: 'denied', detail: denied.source };\n }\n return withhold.some((re) => re.test(text)) ? { ok: false, reason: 'withheld' } : { ok: true };\n}\n\nexport function validateAnswer(text: string, context: AnswerContext = {}): AnswerVerdict {\n const { salt, partial } = context;\n if (ENVELOPE_TAG.test(text)) {\n return { ok: false, reason: 'envelope-tag' };\n }\n if (salt && text.includes(salt)) {\n return { ok: false, reason: 'salt' };\n }\n if (IMAGE.test(text)) {\n return { ok: false, reason: 'image' };\n }\n const link = finished(linkTargets(text), text, partial).find((href) => !linkAllowed(href, context));\n if (link) {\n return { ok: false, reason: 'link', detail: link };\n }\n const email = finished(emails(text), text, partial).find((address) => !emailAllowed(address, context));\n if (email) {\n return { ok: false, reason: 'email', detail: email };\n }\n return patternStop(text, context.policy ?? {});\n}\n\n// The guard a site's MCP server runs on each tool result before it leaves the server: the internal names\n// and the withheld content of its policy. Anyone can call the server without the page, so these never\n// leave it.\nexport function checkToolResult(text: string, policy: GuardPolicy): AnswerVerdict {\n return patternStop(text, policy);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tensorpass/aiconnect",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Headless SDK: connect a visitor's own AI account and run the site's tools with it.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -18,6 +18,10 @@
18
18
  "types": "./dist/guards/index.d.ts",
19
19
  "default": "./dist/guards/index.js"
20
20
  },
21
+ "./mcp": {
22
+ "types": "./dist/mcpToolSource.d.ts",
23
+ "default": "./dist/mcpToolSource.js"
24
+ },
21
25
  "./attachments": {
22
26
  "types": "./dist/attachments/index.d.ts",
23
27
  "default": "./dist/attachments/index.js"