@tensorpass/aiconnect 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/attachments/attachmentPolicy.d.ts +31 -0
- package/dist/attachments/attachmentPolicy.js +72 -0
- package/dist/attachments/attachmentPolicy.js.map +1 -0
- package/dist/attachments/imagePrep.d.ts +13 -0
- package/dist/attachments/imagePrep.js +70 -0
- package/dist/attachments/imagePrep.js.map +1 -0
- package/dist/attachments/index.d.ts +5 -0
- package/dist/attachments/index.js +6 -0
- package/dist/attachments/index.js.map +1 -0
- package/dist/attachments/pdfModule.d.ts +1 -0
- package/dist/attachments/pdfModule.js +9 -0
- package/dist/attachments/pdfModule.js.map +1 -0
- package/dist/attachments/pdfPrep.d.ts +6 -0
- package/dist/attachments/pdfPrep.js +63 -0
- package/dist/attachments/pdfPrep.js.map +1 -0
- package/dist/attachments/preparedAttachment.d.ts +18 -0
- package/dist/attachments/preparedAttachment.js +52 -0
- package/dist/attachments/preparedAttachment.js.map +1 -0
- package/dist/chatContent.d.ts +7 -1
- package/dist/chatContent.js +29 -2
- package/dist/chatContent.js.map +1 -1
- package/dist/client.js +10 -0
- package/dist/client.js.map +1 -1
- package/dist/connectionState.d.ts +4 -1
- package/dist/connectionState.js.map +1 -1
- package/dist/dictation.d.ts +21 -0
- package/dist/dictation.js +7 -0
- package/dist/dictation.js.map +1 -0
- package/dist/guards/answerGuard.js +1 -1
- package/dist/guards/answerGuard.js.map +1 -1
- package/dist/guards/chatGuard.d.ts +2 -2
- package/dist/guards/chatGuard.js +38 -12
- package/dist/guards/chatGuard.js.map +1 -1
- package/dist/guards/envelopes.d.ts +1 -0
- package/dist/guards/envelopes.js +8 -0
- package/dist/guards/envelopes.js.map +1 -1
- package/dist/guards/index.d.ts +3 -3
- package/dist/guards/index.js +3 -3
- package/dist/guards/index.js.map +1 -1
- package/dist/guards/policy.d.ts +2 -0
- package/dist/guards/policy.js +1 -0
- package/dist/guards/policy.js.map +1 -1
- package/dist/guards/questionGuard.d.ts +2 -0
- package/dist/guards/questionGuard.js +38 -5
- package/dist/guards/questionGuard.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/toolLoop.js +1 -2
- package/dist/toolLoop.js.map +1 -1
- package/dist/types.d.ts +13 -1
- package/dist/types.js.map +1 -1
- package/dist/walletProvider.d.ts +2 -0
- package/dist/walletProvider.js.map +1 -1
- package/dist/webAccounts/openAiWire.js +12 -6
- package/dist/webAccounts/openAiWire.js.map +1 -1
- package/dist/wireProtocols/anthropicMessages.js +18 -3
- package/dist/wireProtocols/anthropicMessages.js.map +1 -1
- package/dist/wireProtocols/geminiContents.js +11 -7
- package/dist/wireProtocols/geminiContents.js.map +1 -1
- package/dist/wireProtocols/openAiChat.js +4 -1
- package/dist/wireProtocols/openAiChat.js.map +1 -1
- package/dist/wireProtocols/openAiResponses.js +4 -1
- package/dist/wireProtocols/openAiResponses.js.map +1 -1
- package/dist/wireProtocols/wireProtocol.d.ts +2 -1
- package/dist/wireProtocols/wireProtocol.js +13 -1
- package/dist/wireProtocols/wireProtocol.js.map +1 -1
- package/package.json +7 -2
|
@@ -2,8 +2,11 @@
|
|
|
2
2
|
// on long base64 blobs, and injection patterns in English, French and Hebrew. Up to three words may sit
|
|
3
3
|
// between a verb and its object, so "ignore all of the previous instructions" trips the same pattern as
|
|
4
4
|
// "ignore instructions". The patterns also read the question with invisible characters removed and
|
|
5
|
-
// digits used as letters read as letters, so "1gn0r3 y0ur rul3s" reads "ignore your rules".
|
|
6
|
-
|
|
5
|
+
// digits used as letters read as letters, so "1gn0r3 y0ur rul3s" reads "ignore your rules". The text of
|
|
6
|
+
// the files the visitor attached has its own length cap and meets the same patterns; the base64 block
|
|
7
|
+
// reads only what the visitor typed, since a CSV or a JSON file holds long tokens of its own.
|
|
8
|
+
import { attachedText, contentParts, textOf } from "../chatContent.js";
|
|
9
|
+
import { DEFAULT_MAX_ATTACHMENT_TEXT, DEFAULT_MAX_INPUT_LENGTH } from "./policy.js";
|
|
7
10
|
export const INJECTION_PATTERNS = [
|
|
8
11
|
{ name: 'ignore-instructions', re: /\bignor(?:e|ez|er)\s+(?:previous|all|any|your|the|my|toutes?|tous|les|tes|vos|ces)(?:\s+\S+){0,3}\s+(?:instructions?|rules?|prompts?|guidelines?|consignes?|règles?|directives?)/i },
|
|
9
12
|
{ name: 'forget-instructions', re: /\b(?:forget|oubli(?:e|ez|er))\s+(?:everything|tout|(?:your|all|the|toutes?|tes|vos|les)(?:\s+\S+){0,3}\s+(?:rules?|instructions?|prompts?|training|consignes?|règles?))/i },
|
|
@@ -18,7 +21,7 @@ export const INJECTION_PATTERNS = [
|
|
|
18
21
|
{ name: 'ask-instructions', re: /\b(?:what\s+are\s+your(?:\s+\S+){0,2}\s+(?:instructions?|rules?|prompts?)|quelles\s+sont\s+tes\s+(?:instructions|consignes|règles))/i },
|
|
19
22
|
{ name: 'jailbreak-dan', re: /\bDAN\b/ },
|
|
20
23
|
{ name: 'jailbreak-persona', re: /\b(?:developer\s+mode|jailbreak|no\s+restrictions?|mode\s+développeur|sans\s+(?:aucune\s+)?restrictions?)\b/i },
|
|
21
|
-
{ name: 'tag-spoof', re: /<\/?\s*(?:instructions?|system|tool-result|steering)\b[^>]*>/i },
|
|
24
|
+
{ name: 'tag-spoof', re: /<\/?\s*(?:instructions?|system|tool-result|attachment|steering)\b[^>]*>/i },
|
|
22
25
|
{ name: 'he-ignore-instructions', re: /(?:התעלם|התעלמי|התעלמו|תתעלם|שכח|שכחי|תשכח)\S*(?:\s+\S+){0,4}?\s+\S*(?:הוראות|הנחיות|כללים|פרומפט)/u },
|
|
23
26
|
{ name: 'he-reveal-prompt', re: /(?:הצג|תציג|הראה|תראה|חשוף|תחשוף|הדפס|תדפיס|כתוב|תכתוב)\S*(?:\s+\S+){0,3}?\s+\S*(?:הוראות|הנחיות|פרומפט)\S*\s+(?:שלך|שלכם|המערכת|מערכת)/u },
|
|
24
27
|
{ name: 'he-persona', re: /(?:מעכשיו\s+אתה|אתה\s+מעכשיו|תעמיד\s+פנים|העמד\s+פנים|תתנהג\s+כמו|מצב\s+מפתח|ללא\s+הגבלות|בלי\s+הגבלות)/u },
|
|
@@ -46,8 +49,38 @@ export function validateQuestion(raw, policy = {}) {
|
|
|
46
49
|
if (BASE64_BLOB.test(question)) {
|
|
47
50
|
return { ok: false, reason: 'injection', pattern: 'base64-blob' };
|
|
48
51
|
}
|
|
49
|
-
|
|
50
|
-
|
|
52
|
+
return matchInjection(question);
|
|
53
|
+
}
|
|
54
|
+
function matchInjection(text) {
|
|
55
|
+
const normalized = normalizeForMatching(text);
|
|
56
|
+
const hit = INJECTION_PATTERNS.find(({ re }) => re.test(text) || re.test(normalized));
|
|
51
57
|
return hit ? { ok: false, reason: 'injection', pattern: hit.name } : { ok: true };
|
|
52
58
|
}
|
|
59
|
+
function validateAttachedText(texts, policy) {
|
|
60
|
+
const length = texts.reduce((total, text) => total + text.length, 0);
|
|
61
|
+
if (length > (policy.maxAttachmentText ?? DEFAULT_MAX_ATTACHMENT_TEXT)) {
|
|
62
|
+
return { ok: false, reason: 'too-long' };
|
|
63
|
+
}
|
|
64
|
+
for (const text of texts) {
|
|
65
|
+
const verdict = matchInjection(text);
|
|
66
|
+
if (!verdict.ok) {
|
|
67
|
+
return verdict;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return { ok: true };
|
|
71
|
+
}
|
|
72
|
+
// A question with its attachments: the typed text under `validateQuestion`, and the attached text under
|
|
73
|
+
// its own cap and the injection patterns. An image or a file alone makes a question.
|
|
74
|
+
export function validateContent(content, policy = {}) {
|
|
75
|
+
const parts = contentParts(content);
|
|
76
|
+
const typed = textOf(parts);
|
|
77
|
+
const attached = parts.some((part) => part.type !== 'text');
|
|
78
|
+
if (typed.trim() || !attached) {
|
|
79
|
+
const verdict = validateQuestion(typed, policy);
|
|
80
|
+
if (!verdict.ok) {
|
|
81
|
+
return verdict;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return validateAttachedText(attachedText(parts), policy);
|
|
85
|
+
}
|
|
53
86
|
//# sourceMappingURL=questionGuard.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"questionGuard.js","sourceRoot":"","sources":["../../src/guards/questionGuard.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,wGAAwG;AACxG,wGAAwG;AACxG,mGAAmG;AACnG,4FAA4F;AAE5F,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAQvD,MAAM,CAAC,MAAM,kBAAkB,GAAuB;IACpD,EAAE,IAAI,EAAE,qBAAqB,EAAE,EAAE,EAAE,mLAAmL,EAAE;IACxN,EAAE,IAAI,EAAE,qBAAqB,EAAE,EAAE,EAAE,0KAA0K,EAAE;IAC/M,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,gDAAgD,EAAE;IAC3E,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,2GAA2G,EAAE;IACrI,EAAE,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,uCAAuC,EAAE;IACtE,EAAE,IAAI,EAAE,kBAAkB,EAAE,EAAE,EAAE,yGAAyG,EAAE;IAC3I,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,mFAAmF,EAAE;IAC5G,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,mTAAmT,EAAE;IAC3U,EAAE,IAAI,EAAE,aAAa,EAAE,EAAE,EAAE,kKAAkK,EAAE;IAC/L,EAAE,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,uNAAuN,EAAE;IACtP,EAAE,IAAI,EAAE,kBAAkB,EAAE,EAAE,EAAE,sIAAsI,EAAE;IACxK,EAAE,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,SAAS,EAAE;IACxC,EAAE,IAAI,EAAE,mBAAmB,EAAE,EAAE,EAAE,8GAA8G,EAAE;IAC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B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IACxC,CAAC;IACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,MAAM,CAAC,cAAc,IAAI,wBAAwB,CAAC,EAAE,CAAC;QAC1E,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAC3C,CAAC;IACD,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC;IACpE,CAAC;IACD,MAAM,UAAU,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IAClD,MAAM,GAAG,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAC1F,OAAO,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AACpF,CAAC","sourcesContent":["// The guard on the visitor's question, run before the question reaches the model: a length cap, a block\n// on long base64 blobs, and injection patterns in English, French and Hebrew. Up to three words may sit\n// between a verb and its object, so \"ignore all of the previous instructions\" trips the same pattern as\n// \"ignore instructions\". The patterns also read the question with invisible characters removed and\n// digits used as letters read as letters, so \"1gn0r3 y0ur rul3s\" reads \"ignore your rules\".\n\nimport { DEFAULT_MAX_INPUT_LENGTH } from './policy.ts';\nimport type { GuardPolicy, QuestionVerdict } from './policy.ts';\n\nexport interface InjectionPattern {\n name: string;\n re: RegExp;\n}\n\nexport const INJECTION_PATTERNS: InjectionPattern[] = [\n { name: 'ignore-instructions', re: /\\bignor(?:e|ez|er)\\s+(?:previous|all|any|your|the|my|toutes?|tous|les|tes|vos|ces)(?:\\s+\\S+){0,3}\\s+(?:instructions?|rules?|prompts?|guidelines?|consignes?|règles?|directives?)/i },\n { name: 'forget-instructions', re: /\\b(?:forget|oubli(?:e|ez|er))\\s+(?:everything|tout|(?:your|all|the|toutes?|tes|vos|les)(?:\\s+\\S+){0,3}\\s+(?:rules?|instructions?|prompts?|training|consignes?|règles?))/i },\n { name: 'disregard', re: /\\bdisregard\\s+(?:all|your|previous|the|any)\\b/i },\n { name: 'override', re: /\\boverride\\s+(?:your|the|all)(?:\\s+\\S+){0,3}\\s+(?:rules?|instructions?|behaviou?r|settings?|guidelines?)/i },\n { name: 'system-prefix', re: /^\\s*(?:system|syst[eè]me|מערכת)\\s*:/im },\n { name: 'new-instructions', re: /\\b(?:new\\s+(?:instructions?|rules?|directives?)|nouvelles?\\s+(?:instructions?|consignes?|règles?))\\s*:/i },\n { name: 'pretend', re: /\\b(?:pretend\\s+(?:you\\s+are|to\\s+be|you're)|fai(?:s|tes)\\s+semblant\\s+d['’]être)/i },\n { name: 'act-as', re: /\\b(?:act\\s+as\\s+(?:if\\s+you|an?\\s+(?:\\S+\\s+){0,2}?(?:assistant|ai|model|bot|chatbot|gpt|persona|character|hacker|developer|admin(?:istrator)?)\\b)|agi(?:s|ssez)\\s+comme\\s+(?:si\\s+(?:tu|vous)|une?\\s+(?:\\S+\\s+){0,2}?(?:assistant|ia|modèle|bot|chatbot|personnage|pirate|hacker|développeur|administrateur)\\b))/i },\n { name: 'you-are-now', re: /\\b(?:you\\s+are\\s+now|from\\s+now\\s+on\\s+you\\s+are|tu\\s+es\\s+(?:maintenant|désormais)|vous\\s+êtes\\s+(?:maintenant|désormais))\\s+(?:a|an|un|une|my|mon|ma|in|en)\\b/i },\n { name: 'reveal-prompt', re: /\\b(?:reveal|show|print|display|repeat|output|révèle|répète|affiche|montre|donne)(?:\\s+\\S+){0,2}?\\s+(?:your|tes|vos|ton|votre)(?:\\s+\\S+){0,2}?\\s+(?:system\\s+prompt|instructions?|prompts?|rules?|consignes?|règles?)/i },\n { name: 'ask-instructions', re: /\\b(?:what\\s+are\\s+your(?:\\s+\\S+){0,2}\\s+(?:instructions?|rules?|prompts?)|quelles\\s+sont\\s+tes\\s+(?:instructions|consignes|règles))/i },\n { name: 'jailbreak-dan', re: /\\bDAN\\b/ },\n { name: 'jailbreak-persona', re: /\\b(?:developer\\s+mode|jailbreak|no\\s+restrictions?|mode\\s+développeur|sans\\s+(?:aucune\\s+)?restrictions?)\\b/i },\n { name: 'tag-spoof', re: /<\\/?\\s*(?:instructions?|system|tool-result|steering)\\b[^>]*>/i },\n { name: 'he-ignore-instructions', re: /(?:התעלם|התעלמי|התעלמו|תתעלם|שכח|שכחי|תשכח)\\S*(?:\\s+\\S+){0,4}?\\s+\\S*(?:הוראות|הנחיות|כללים|פרומפט)/u },\n { name: 'he-reveal-prompt', re: /(?:הצג|תציג|הראה|תראה|חשוף|תחשוף|הדפס|תדפיס|כתוב|תכתוב)\\S*(?:\\s+\\S+){0,3}?\\s+\\S*(?:הוראות|הנחיות|פרומפט)\\S*\\s+(?:שלך|שלכם|המערכת|מערכת)/u },\n { name: 'he-persona', re: /(?:מעכשיו\\s+אתה|אתה\\s+מעכשיו|תעמיד\\s+פנים|העמד\\s+פנים|תתנהג\\s+כמו|מצב\\s+מפתח|ללא\\s+הגבלות|בלי\\s+הגבלות)/u },\n { name: 'he-new-instructions', re: /הוראות\\s+חדשות\\s*:/u },\n];\n\nconst BASE64_BLOB = /[A-Za-z0-9+/=]{100,}/;\nconst INVISIBLE = /[\\u200B-\\u200F\\u2060-\\u2064\\uFEFF\\u00AD]/g;\nconst LEET: Record<string, string> = { 0: 'o', 1: 'i', 3: 'e', 4: 'a', 5: 's', 7: 't', '@': 'a', $: 's' };\n\n// The text the patterns read: invisible characters removed, letters folded to their compatibility form,\n// and digits used as letters inside words read as those letters.\nexport function normalizeForMatching(text: string): string {\n const folded = text.normalize('NFKC').replace(INVISIBLE, '');\n return folded.replace(/\\S+/g, (word) => (/\\p{L}/u.test(word)\n ? word.replace(/[013457@$]/g, (character) => LEET[character])\n : word));\n}\n\nexport function validateQuestion(raw: string, policy: GuardPolicy = {}): QuestionVerdict {\n const question = raw.trim();\n if (!question) {\n return { ok: false, reason: 'empty' };\n }\n if (question.length > (policy.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH)) {\n return { ok: false, reason: 'too-long' };\n }\n if (BASE64_BLOB.test(question)) {\n return { ok: false, reason: 'injection', pattern: 'base64-blob' };\n }\n const normalized = normalizeForMatching(question);\n const hit = INJECTION_PATTERNS.find(({ re }) => re.test(question) || re.test(normalized));\n return hit ? { ok: false, reason: 'injection', pattern: hit.name } : { ok: true };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"questionGuard.js","sourceRoot":"","sources":["../../src/guards/questionGuard.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,wGAAwG;AACxG,wGAAwG;AACxG,mGAAmG;AACnG,wGAAwG;AACxG,sGAAsG;AACtG,8FAA8F;AAE9F,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEvE,OAAO,EAAE,2BAA2B,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAQpF,MAAM,CAAC,MAAM,kBAAkB,GAAuB;IACpD,EAAE,IAAI,EAAE,qBAAqB,EAAE,EAAE,EAAE,mLAAmL,EAAE;IACxN,EAAE,IAAI,EAAE,qBAAqB,EAAE,EAAE,EAAE,0KAA0K,EAAE;IAC/M,EAAE,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,gDAAgD,EAAE;IAC3E,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE,2GAA2G,EAAE;IACrI,EAAE,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,u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I,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,gBAAgB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAChD,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;YAChB,OAAO,OAAO,CAAC;QACjB,CAAC;IACH,CAAC;IACD,OAAO,oBAAoB,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["// The guard on the visitor's question, run before the question reaches the model: a length cap, a block\n// on long base64 blobs, and injection patterns in English, French and Hebrew. Up to three words may sit\n// between a verb and its object, so \"ignore all of the previous instructions\" trips the same pattern as\n// \"ignore instructions\". The patterns also read the question with invisible characters removed and\n// digits used as letters read as letters, so \"1gn0r3 y0ur rul3s\" reads \"ignore your rules\". The text of\n// the files the visitor attached has its own length cap and meets the same patterns; the base64 block\n// reads only what the visitor typed, since a CSV or a JSON file holds long tokens of its own.\n\nimport { attachedText, contentParts, textOf } from '../chatContent.ts';\nimport type { ContentPart } from '../types.ts';\nimport { DEFAULT_MAX_ATTACHMENT_TEXT, DEFAULT_MAX_INPUT_LENGTH } from './policy.ts';\nimport type { GuardPolicy, QuestionVerdict } from './policy.ts';\n\nexport interface InjectionPattern {\n name: string;\n re: RegExp;\n}\n\nexport const INJECTION_PATTERNS: InjectionPattern[] = [\n { name: 'ignore-instructions', re: /\\bignor(?:e|ez|er)\\s+(?:previous|all|any|your|the|my|toutes?|tous|les|tes|vos|ces)(?:\\s+\\S+){0,3}\\s+(?:instructions?|rules?|prompts?|guidelines?|consignes?|règles?|directives?)/i },\n { name: 'forget-instructions', re: /\\b(?:forget|oubli(?:e|ez|er))\\s+(?:everything|tout|(?:your|all|the|toutes?|tes|vos|les)(?:\\s+\\S+){0,3}\\s+(?:rules?|instructions?|prompts?|training|consignes?|règles?))/i },\n { name: 'disregard', re: /\\bdisregard\\s+(?:all|your|previous|the|any)\\b/i },\n { name: 'override', re: /\\boverride\\s+(?:your|the|all)(?:\\s+\\S+){0,3}\\s+(?:rules?|instructions?|behaviou?r|settings?|guidelines?)/i },\n { name: 'system-prefix', re: /^\\s*(?:system|syst[eè]me|מערכת)\\s*:/im },\n { name: 'new-instructions', re: /\\b(?:new\\s+(?:instructions?|rules?|directives?)|nouvelles?\\s+(?:instructions?|consignes?|règles?))\\s*:/i },\n { name: 'pretend', re: /\\b(?:pretend\\s+(?:you\\s+are|to\\s+be|you're)|fai(?:s|tes)\\s+semblant\\s+d['’]être)/i },\n { name: 'act-as', re: /\\b(?:act\\s+as\\s+(?:if\\s+you|an?\\s+(?:\\S+\\s+){0,2}?(?:assistant|ai|model|bot|chatbot|gpt|persona|character|hacker|developer|admin(?:istrator)?)\\b)|agi(?:s|ssez)\\s+comme\\s+(?:si\\s+(?:tu|vous)|une?\\s+(?:\\S+\\s+){0,2}?(?:assistant|ia|modèle|bot|chatbot|personnage|pirate|hacker|développeur|administrateur)\\b))/i },\n { name: 'you-are-now', re: /\\b(?:you\\s+are\\s+now|from\\s+now\\s+on\\s+you\\s+are|tu\\s+es\\s+(?:maintenant|désormais)|vous\\s+êtes\\s+(?:maintenant|désormais))\\s+(?:a|an|un|une|my|mon|ma|in|en)\\b/i },\n { name: 'reveal-prompt', re: /\\b(?:reveal|show|print|display|repeat|output|révèle|répète|affiche|montre|donne)(?:\\s+\\S+){0,2}?\\s+(?:your|tes|vos|ton|votre)(?:\\s+\\S+){0,2}?\\s+(?:system\\s+prompt|instructions?|prompts?|rules?|consignes?|règles?)/i },\n { name: 'ask-instructions', re: /\\b(?:what\\s+are\\s+your(?:\\s+\\S+){0,2}\\s+(?:instructions?|rules?|prompts?)|quelles\\s+sont\\s+tes\\s+(?:instructions|consignes|règles))/i },\n { name: 'jailbreak-dan', re: /\\bDAN\\b/ },\n { name: 'jailbreak-persona', re: /\\b(?:developer\\s+mode|jailbreak|no\\s+restrictions?|mode\\s+développeur|sans\\s+(?:aucune\\s+)?restrictions?)\\b/i },\n { name: 'tag-spoof', re: /<\\/?\\s*(?:instructions?|system|tool-result|attachment|steering)\\b[^>]*>/i },\n { name: 'he-ignore-instructions', re: /(?:התעלם|התעלמי|התעלמו|תתעלם|שכח|שכחי|תשכח)\\S*(?:\\s+\\S+){0,4}?\\s+\\S*(?:הוראות|הנחיות|כללים|פרומפט)/u },\n { name: 'he-reveal-prompt', re: /(?:הצג|תציג|הראה|תראה|חשוף|תחשוף|הדפס|תדפיס|כתוב|תכתוב)\\S*(?:\\s+\\S+){0,3}?\\s+\\S*(?:הוראות|הנחיות|פרומפט)\\S*\\s+(?:שלך|שלכם|המערכת|מערכת)/u },\n { name: 'he-persona', re: /(?:מעכשיו\\s+אתה|אתה\\s+מעכשיו|תעמיד\\s+פנים|העמד\\s+פנים|תתנהג\\s+כמו|מצב\\s+מפתח|ללא\\s+הגבלות|בלי\\s+הגבלות)/u },\n { name: 'he-new-instructions', re: /הוראות\\s+חדשות\\s*:/u },\n];\n\nconst BASE64_BLOB = /[A-Za-z0-9+/=]{100,}/;\nconst INVISIBLE = /[\\u200B-\\u200F\\u2060-\\u2064\\uFEFF\\u00AD]/g;\nconst LEET: Record<string, string> = { 0: 'o', 1: 'i', 3: 'e', 4: 'a', 5: 's', 7: 't', '@': 'a', $: 's' };\n\n// The text the patterns read: invisible characters removed, letters folded to their compatibility form,\n// and digits used as letters inside words read as those letters.\nexport function normalizeForMatching(text: string): string {\n const folded = text.normalize('NFKC').replace(INVISIBLE, '');\n return folded.replace(/\\S+/g, (word) => (/\\p{L}/u.test(word)\n ? word.replace(/[013457@$]/g, (character) => LEET[character])\n : word));\n}\n\nexport function validateQuestion(raw: string, policy: GuardPolicy = {}): QuestionVerdict {\n const question = raw.trim();\n if (!question) {\n return { ok: false, reason: 'empty' };\n }\n if (question.length > (policy.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH)) {\n return { ok: false, reason: 'too-long' };\n }\n if (BASE64_BLOB.test(question)) {\n return { ok: false, reason: 'injection', pattern: 'base64-blob' };\n }\n return matchInjection(question);\n}\n\nfunction matchInjection(text: string): QuestionVerdict {\n const normalized = normalizeForMatching(text);\n const hit = INJECTION_PATTERNS.find(({ re }) => re.test(text) || re.test(normalized));\n return hit ? { ok: false, reason: 'injection', pattern: hit.name } : { ok: true };\n}\n\nfunction validateAttachedText(texts: string[], policy: GuardPolicy): QuestionVerdict {\n const length = texts.reduce((total, text) => total + text.length, 0);\n if (length > (policy.maxAttachmentText ?? DEFAULT_MAX_ATTACHMENT_TEXT)) {\n return { ok: false, reason: 'too-long' };\n }\n for (const text of texts) {\n const verdict = matchInjection(text);\n if (!verdict.ok) {\n return verdict;\n }\n }\n return { ok: true };\n}\n\n// A question with its attachments: the typed text under `validateQuestion`, and the attached text under\n// its own cap and the injection patterns. An image or a file alone makes a question.\nexport function validateContent(content: string | ContentPart[], policy: GuardPolicy = {}): QuestionVerdict {\n const parts = contentParts(content);\n const typed = textOf(parts);\n const attached = parts.some((part) => part.type !== 'text');\n if (typed.trim() || !attached) {\n const verdict = validateQuestion(typed, policy);\n if (!verdict.ok) {\n return verdict;\n }\n }\n return validateAttachedText(attachedText(parts), policy);\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export type { AttachmentPolicy } from './attachments/attachmentPolicy.ts';
|
|
2
|
+
export { attachedText, contentParts, dataUrl, decodeBase64Text, encodeBase64Text, fileText, inlineData, isTextFile, PDF_TYPE, textOf, } from './chatContent.ts';
|
|
2
3
|
export type { InlineData } from './chatContent.ts';
|
|
3
4
|
export { AiConnect } from './client.ts';
|
|
4
5
|
export type { AiConnectOptions, ConnectionState, SdkOptions, WebSignInFailure } from './client.ts';
|
|
6
|
+
export { DICTATION_SAMPLE_RATE } from './dictation.ts';
|
|
7
|
+
export type { Dictation, DictationEvent, DictationRequest, DictationSession, DictationStart, } from './dictation.ts';
|
|
5
8
|
export * from './guards/index.ts';
|
|
6
9
|
export { McpToolSource } from './mcpToolSource.ts';
|
|
7
10
|
export type { McpFetch, McpToolSourceOptions } from './mcpToolSource.ts';
|
package/dist/index.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// through an account the visitor signs in to on the page, the conversation loop that runs the site's tools
|
|
3
3
|
// under the chat's guards, the site's tools read from its MCP server, and the `fetch` that lets the AI SDK a
|
|
4
4
|
// site already uses answer through the same connection.
|
|
5
|
-
export { contentParts, dataUrl, inlineData, textOf } from "./chatContent.js";
|
|
5
|
+
export { attachedText, contentParts, dataUrl, decodeBase64Text, encodeBase64Text, fileText, inlineData, isTextFile, PDF_TYPE, textOf, } from "./chatContent.js";
|
|
6
6
|
export { AiConnect } from "./client.js";
|
|
7
|
+
export { DICTATION_SAMPLE_RATE } from "./dictation.js";
|
|
7
8
|
export * from "./guards/index.js";
|
|
8
9
|
export { McpToolSource } from "./mcpToolSource.js";
|
|
9
10
|
export { BROWSER_NAMES, browserOf, visitorBrowser, walletInstallUrl, walletStore, WALLET_STORES, } from "./visitorBrowser.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,2GAA2G;AAC3G,6GAA6G;AAC7G,wDAAwD;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,2GAA2G;AAC3G,6GAA6G;AAC7G,wDAAwD;AAGxD,OAAO,EACL,YAAY,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EACnH,MAAM,GACP,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAIvD,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EACL,aAAa,EAAE,SAAS,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,GACvF,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAG7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAGzD,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAE7D,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAGlE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC","sourcesContent":["// The site's side of AI Connect: the connection to the visitor's AI through the AI Wallet or, without it,\n// through an account the visitor signs in to on the page, the conversation loop that runs the site's tools\n// under the chat's guards, the site's tools read from its MCP server, and the `fetch` that lets the AI SDK a\n// site already uses answer through the same connection.\n\nexport type { AttachmentPolicy } from './attachments/attachmentPolicy.ts';\nexport {\n attachedText, contentParts, dataUrl, decodeBase64Text, encodeBase64Text, fileText, inlineData, isTextFile, PDF_TYPE,\n textOf,\n} from './chatContent.ts';\nexport type { InlineData } from './chatContent.ts';\nexport { AiConnect } from './client.ts';\nexport type { AiConnectOptions, ConnectionState, SdkOptions, WebSignInFailure } from './client.ts';\nexport { DICTATION_SAMPLE_RATE } from './dictation.ts';\nexport type {\n Dictation, DictationEvent, DictationRequest, DictationSession, DictationStart,\n} from './dictation.ts';\nexport * from './guards/index.ts';\nexport { McpToolSource } from './mcpToolSource.ts';\nexport type { McpFetch, McpToolSourceOptions } from './mcpToolSource.ts';\nexport {\n BROWSER_NAMES, browserOf, visitorBrowser, walletInstallUrl, walletStore, WALLET_STORES,\n} from './visitorBrowser.ts';\nexport type { BrowserSignals, VisitorBrowser, WalletStore } from './visitorBrowser.ts';\nexport { finalAnswer, runConversation } from './toolLoop.ts';\nexport type { ConversationHooks, ConversationOptions } from './toolLoop.ts';\nexport type * from './types.ts';\nexport { WalletRequestError } from './walletProvider.ts';\nexport type { ChatEvent, WalletChatParams, WalletProvider, WalletRefusal } from './walletProvider.ts';\nexport type { WalletFetch } from './wireProtocols/walletFetch.ts';\nexport { finishSignIn } from './webAccounts/finishSignIn.ts';\nexport type { SignInReturn } from './webAccounts/finishSignIn.ts';\nexport { isSignInReturn } from './webAccounts/signInWindow.ts';\nexport { PLAN_GATEWAY } from './webAccounts/tensorPassAccount.ts';\nexport type { PlanAccess, PlanOffer, PlanPrice, PlanSubscription } from './webAccounts/tensorPassPlan.ts';\nexport type { PlanLevel } from './webAccounts/tensorPassAccount.ts';\nexport { WEB_ACCOUNT_NAMES } from './webAccounts/webAccount.ts';\nexport type { WebAccountId } from './webAccounts/webAccountStore.ts';\n"]}
|
package/dist/toolLoop.js
CHANGED
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
// the text stops reaching the page, the model's answer is cut, and the loop throws a `GuardStop`. The
|
|
8
8
|
// pieces before that one already reached the page, and the visitor's browser holds the whole answer:
|
|
9
9
|
// what must stay out of a visitor's reach is held back on the site's server (see `checkToolResult`).
|
|
10
|
-
import { textOf } from "./chatContent.js";
|
|
11
10
|
import { GuardStop } from "./guards/chatGuard.js";
|
|
12
11
|
const DEFAULT_MAX_STEPS = 6;
|
|
13
12
|
// The tool calls run for one answer of the model. The calls past it get a tool error.
|
|
@@ -43,7 +42,7 @@ function startRun(options) {
|
|
|
43
42
|
}
|
|
44
43
|
guard.remember(options.messages);
|
|
45
44
|
const question = options.messages.findLast((message) => message.role === 'user');
|
|
46
|
-
const verdict = question ? guard.checkQuestion(
|
|
45
|
+
const verdict = question ? guard.checkQuestion(question.content) : { ok: true };
|
|
47
46
|
if (!verdict.ok) {
|
|
48
47
|
throw new GuardStop('question', verdict.reason);
|
|
49
48
|
}
|
package/dist/toolLoop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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SAAS,CAAC;IAChE,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,iBAAiB,CAAC;IAEvD,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,QAAQ,EAAE,IAAI,IAAI,CAAC,EAAE,CAAC;QAC9C,+DAA+D;QAC/D,MAAM,OAAO,GAAG,IAAI,GAAG,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;QAC9D,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAC7C,IAAI,CAAC,KAAK,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;YACrD,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC;YACpC,OAAO,GAAG,CAAC,KAAK,CAAC;QACnB,CAAC;QACD,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACxB,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,eAAe,CAAC,GAAG,EAAE,OAAO,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;IAC5G,CAAC;IACD,OAAO,GAAG,CAAC,KAAK,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,QAAuB;IACjD,MAAM,IAAI,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC7B,OAAO,IAAI,EAAE,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AAClD,CAAC","sourcesContent":["// The agent loop run in the browser: the user's model answers or asks for tools, the site's tools\n// run, their results go back to the model, until it answers in plain text. A tool runs only when the\n// loop offered it to the model at that step: a call to any other name gets a tool error and stays out of\n// the site's tools. With the conversation's guards, the loop stops a question that tries to take over\n// the model before it leaves the page, sends the instructions and the tool results in their salted\n// envelopes, and checks the answer at each piece it streams: from the first piece that trips a guard,\n// the text stops reaching the page, the model's answer is cut, and the loop throws a `GuardStop`. The\n// pieces before that one already reached the page, and the visitor's browser holds the whole answer:\n// what must stay out of a visitor's reach is held back on the site's server (see `checkToolResult`).\n\nimport { textOf } from './chatContent.ts';\nimport { GuardStop } from './guards/chatGuard.ts';\nimport type { ChatGuard } from './guards/chatGuard.ts';\nimport type { AnswerStop } from './guards/policy.ts';\nimport type { AssistantMessage, ChatMessage, ProviderSession, ToolCall, ToolDefinition, ToolSource } from './types.ts';\n\nconst DEFAULT_MAX_STEPS = 6;\n// The tool calls run for one answer of the model. The calls past it get a tool error.\nconst DEFAULT_MAX_TOOL_CALLS = 8;\nconst NOT_OFFERED = 'Tool error: this tool is not available';\nconst TOO_MANY_CALLS = 'Tool error: too many tool calls in one answer';\n\nexport interface ConversationHooks {\n onText?: (delta: string) => void;\n onToolCall?: (call: ToolCall) => void;\n // The tool's own result, as the site's tool returned it, outside the envelope the model reads.\n onToolResult?: (call: ToolCall, result: string) => void;\n}\n\nexport interface ConversationOptions extends ConversationHooks {\n session: ProviderSession;\n messages: ChatMessage[];\n tools?: ToolSource;\n maxSteps?: number;\n maxToolCalls?: number;\n signal?: AbortSignal;\n // The guards of the conversation, from `createChatGuard`, kept for all its questions.\n guard?: ChatGuard;\n}\n\n// The answer's text as it streams, checked with everything streamed before it in the question.\ninterface StreamWatch {\n onText: (delta: string) => void;\n stopped: () => AnswerStop | null;\n}\n\ninterface ConversationRun {\n options: ConversationOptions;\n added: ChatMessage[];\n signal?: AbortSignal;\n watch?: StreamWatch;\n}\n\nfunction watchStream(guard: ChatGuard, onText: ConversationHooks['onText'], cut: () => void): StreamWatch {\n let streamed = '';\n let stop: AnswerStop | null = null;\n return {\n onText: (delta) => {\n if (stop) {\n return;\n }\n streamed += delta;\n const verdict = guard.checkAnswer(streamed, true);\n if (!verdict.ok) {\n stop = verdict.reason;\n cut();\n return;\n }\n onText?.(delta);\n },\n stopped: () => stop,\n };\n}\n\n// The guarded run of a question: its question checked, and a signal that also cuts the model's answer\n// when the stream trips a guard.\nfunction startRun(options: ConversationOptions): ConversationRun {\n const { guard } = options;\n if (!guard) {\n return { options, added: [], signal: options.signal };\n }\n guard.remember(options.messages);\n const question = options.messages.findLast((message) => message.role === 'user');\n const verdict = question ? guard.checkQuestion(textOf(question.content)) : { ok: true as const };\n if (!verdict.ok) {\n throw new GuardStop('question', verdict.reason);\n }\n const cut = new AbortController();\n const signal = options.signal ? AbortSignal.any([options.signal, cut.signal]) : cut.signal;\n return { options, added: [], signal, watch: watchStream(guard, options.onText, () => cut.abort()) };\n}\n\nasync function askModel(run: ConversationRun, tools?: ToolDefinition[]): Promise<AssistantMessage> {\n const { options, signal, watch } = run;\n const messages = [...options.messages, ...run.added];\n let message: AssistantMessage;\n try {\n ({ message } = await options.session.chat({\n messages: options.guard ? options.guard.forModel(messages) : messages,\n tools,\n signal,\n onText: watch ? watch.onText : options.onText,\n }));\n } catch (error) {\n const stop = watch?.stopped();\n throw stop ? new GuardStop('answer', stop) : error;\n }\n const stop = watch?.stopped();\n if (stop) {\n throw new GuardStop('answer', stop);\n }\n // A provider that answers in one piece streams nothing, so the whole answer is checked as well.\n const verdict = options.guard?.checkAnswer(message.content);\n if (verdict && !verdict.ok) {\n throw new GuardStop('answer', verdict.reason);\n }\n return message;\n}\n\nasync function runToolCall(tools: ToolSource, call: ToolCall, hooks: ConversationHooks): Promise<ChatMessage> {\n hooks.onToolCall?.(call);\n let content: string;\n try {\n content = await tools.callTool(call.name, call.arguments);\n } catch (error) {\n content = `Tool error: ${error instanceof Error ? error.message : String(error)}`;\n }\n hooks.onToolResult?.(call, content);\n return { role: 'tool', toolCallId: call.id, name: call.name, content };\n}\n\n// The tools of one step: the site's source and the definitions the model was offered at that step.\ninterface OfferedTools {\n source: ToolSource;\n definitions: ToolDefinition[];\n}\n\n// The tool error a call gets in place of its run: its tool was not offered, or the answer already ran\n// its share of tools. The words are fixed, since a name the model wrote is no tool result for an answer\n// to repeat.\nfunction refusalOf(call: ToolCall, offered: ToolDefinition[], hasRoom: boolean): ChatMessage | null {\n const refuse = (content: string): ChatMessage => ({ role: 'tool', toolCallId: call.id, name: call.name, content });\n if (!offered.some((definition) => definition.name === call.name)) {\n return refuse(NOT_OFFERED);\n }\n return hasRoom ? null : refuse(TOO_MANY_CALLS);\n}\n\n// Answers every call of one model answer, so each call keeps its result in the conversation. A stopped\n// conversation runs no further tool.\nasync function answerToolCalls(run: ConversationRun, calls: ToolCall[], tools: OfferedTools): Promise<ChatMessage[]> {\n const { options } = run;\n const limit = options.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS;\n const results: ChatMessage[] = [];\n let ran = 0;\n for (const call of calls) {\n run.signal?.throwIfAborted();\n const refusal = refusalOf(call, tools.definitions, ran < limit);\n if (refusal) {\n results.push(refusal);\n continue;\n }\n ran += 1;\n const result = await runToolCall(tools.source, call, options);\n options.guard?.remember([result]);\n results.push(result);\n }\n return results;\n}\n\n// The answer that ends the conversation. Tool calls made when no tool was offered are left out, so the\n// conversation ends on the model's text and a provider accepts it as it is.\nfunction concluding(message: AssistantMessage): AssistantMessage {\n return message.toolCalls?.length ? { role: 'assistant', content: message.content } : message;\n}\n\n// Returns the messages the conversation gained: assistant turns and tool results, ending with\n// the final assistant answer.\nexport async function runConversation(options: ConversationOptions): Promise<ChatMessage[]> {\n const run = startRun(options);\n const { tools } = options;\n const definitions = tools ? await tools.listTools() : undefined;\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n\n for (let step = 0; step < maxSteps; step += 1) {\n // The last step offers no tools, so the model has to conclude.\n const offered = step < maxSteps - 1 ? definitions : undefined;\n const message = await askModel(run, offered);\n if (!tools || !offered || !message.toolCalls?.length) {\n run.added.push(concluding(message));\n return run.added;\n }\n run.added.push(message);\n run.added.push(...await answerToolCalls(run, message.toolCalls, { source: tools, definitions: offered }));\n }\n return run.added;\n}\n\nexport function finalAnswer(messages: ChatMessage[]): AssistantMessage | null {\n const last = messages.at(-1);\n return last?.role === 'assistant' ? last : null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"toolLoop.js","sourceRoot":"","sources":["../src/toolLoop.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,qGAAqG;AACrG,yGAAyG;AACzG,sGAAsG;AACtG,mGAAmG;AACnG,sGAAsG;AACtG,sGAAsG;AACtG,qGAAqG;AACrG,qGAAqG;AAErG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAKlD,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,sFAAsF;AACtF,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,WAAW,GAAG,wCAAwC,CAAC;AAC7D,MAAM,cAAc,GAAG,+CAA+C,CAAC;AAiCvE,SAAS,WAAW,CAAC,KAAgB,EAAE,MAAmC,EAAE,GAAe;IACzF,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,IAAI,IAAI,GAAsB,IAAI,CAAC;IACnC,OAAO;QACL,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAChB,IAAI,IAAI,EAAE,CAAC;gBACT,OAAO;YACT,CAAC;YACD,QAAQ,IAAI,KAAK,CAAC;YAClB,MAAM,OAAO,GAAG,KAAK,CAAC,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;YAClD,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;gBAChB,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;gBACtB,GAAG,EAAE,CAAC;gBACN,OAAO;YACT,CAAC;YACD,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;QACD,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI;KACpB,CAAC;AACJ,CAAC;AAED,sGAAsG;AACtG,iCAAiC;AACjC,SAAS,QAAQ,CAAC,OAA4B;I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, their results go back to the model, until it answers in plain text. A tool runs only when the\n// loop offered it to the model at that step: a call to any other name gets a tool error and stays out of\n// the site's tools. With the conversation's guards, the loop stops a question that tries to take over\n// the model before it leaves the page, sends the instructions and the tool results in their salted\n// envelopes, and checks the answer at each piece it streams: from the first piece that trips a guard,\n// the text stops reaching the page, the model's answer is cut, and the loop throws a `GuardStop`. The\n// pieces before that one already reached the page, and the visitor's browser holds the whole answer:\n// what must stay out of a visitor's reach is held back on the site's server (see `checkToolResult`).\n\nimport { GuardStop } from './guards/chatGuard.ts';\nimport type { ChatGuard } from './guards/chatGuard.ts';\nimport type { AnswerStop } from './guards/policy.ts';\nimport type { AssistantMessage, ChatMessage, ProviderSession, ToolCall, ToolDefinition, ToolSource } from './types.ts';\n\nconst DEFAULT_MAX_STEPS = 6;\n// The tool calls run for one answer of the model. The calls past it get a tool error.\nconst DEFAULT_MAX_TOOL_CALLS = 8;\nconst NOT_OFFERED = 'Tool error: this tool is not available';\nconst TOO_MANY_CALLS = 'Tool error: too many tool calls in one answer';\n\nexport interface ConversationHooks {\n onText?: (delta: string) => void;\n onToolCall?: (call: ToolCall) => void;\n // The tool's own result, as the site's tool returned it, outside the envelope the model reads.\n onToolResult?: (call: ToolCall, result: string) => void;\n}\n\nexport interface ConversationOptions extends ConversationHooks {\n session: ProviderSession;\n messages: ChatMessage[];\n tools?: ToolSource;\n maxSteps?: number;\n maxToolCalls?: number;\n signal?: AbortSignal;\n // The guards of the conversation, from `createChatGuard`, kept for all its questions.\n guard?: ChatGuard;\n}\n\n// The answer's text as it streams, checked with everything streamed before it in the question.\ninterface StreamWatch {\n onText: (delta: string) => void;\n stopped: () => AnswerStop | null;\n}\n\ninterface ConversationRun {\n options: ConversationOptions;\n added: ChatMessage[];\n signal?: AbortSignal;\n watch?: StreamWatch;\n}\n\nfunction watchStream(guard: ChatGuard, onText: ConversationHooks['onText'], cut: () => void): StreamWatch {\n let streamed = '';\n let stop: AnswerStop | null = null;\n return {\n onText: (delta) => {\n if (stop) {\n return;\n }\n streamed += delta;\n const verdict = guard.checkAnswer(streamed, true);\n if (!verdict.ok) {\n stop = verdict.reason;\n cut();\n return;\n }\n onText?.(delta);\n },\n stopped: () => stop,\n };\n}\n\n// The guarded run of a question: its question checked, and a signal that also cuts the model's answer\n// when the stream trips a guard.\nfunction startRun(options: ConversationOptions): ConversationRun {\n const { guard } = options;\n if (!guard) {\n return { options, added: [], signal: options.signal };\n }\n guard.remember(options.messages);\n const question = options.messages.findLast((message) => message.role === 'user');\n const verdict = question ? guard.checkQuestion(question.content) : { ok: true as const };\n if (!verdict.ok) {\n throw new GuardStop('question', verdict.reason);\n }\n const cut = new AbortController();\n const signal = options.signal ? AbortSignal.any([options.signal, cut.signal]) : cut.signal;\n return { options, added: [], signal, watch: watchStream(guard, options.onText, () => cut.abort()) };\n}\n\nasync function askModel(run: ConversationRun, tools?: ToolDefinition[]): Promise<AssistantMessage> {\n const { options, signal, watch } = run;\n const messages = [...options.messages, ...run.added];\n let message: AssistantMessage;\n try {\n ({ message } = await options.session.chat({\n messages: options.guard ? options.guard.forModel(messages) : messages,\n tools,\n signal,\n onText: watch ? watch.onText : options.onText,\n }));\n } catch (error) {\n const stop = watch?.stopped();\n throw stop ? new GuardStop('answer', stop) : error;\n }\n const stop = watch?.stopped();\n if (stop) {\n throw new GuardStop('answer', stop);\n }\n // A provider that answers in one piece streams nothing, so the whole answer is checked as well.\n const verdict = options.guard?.checkAnswer(message.content);\n if (verdict && !verdict.ok) {\n throw new GuardStop('answer', verdict.reason);\n }\n return message;\n}\n\nasync function runToolCall(tools: ToolSource, call: ToolCall, hooks: ConversationHooks): Promise<ChatMessage> {\n hooks.onToolCall?.(call);\n let content: string;\n try {\n content = await tools.callTool(call.name, call.arguments);\n } catch (error) {\n content = `Tool error: ${error instanceof Error ? error.message : String(error)}`;\n }\n hooks.onToolResult?.(call, content);\n return { role: 'tool', toolCallId: call.id, name: call.name, content };\n}\n\n// The tools of one step: the site's source and the definitions the model was offered at that step.\ninterface OfferedTools {\n source: ToolSource;\n definitions: ToolDefinition[];\n}\n\n// The tool error a call gets in place of its run: its tool was not offered, or the answer already ran\n// its share of tools. The words are fixed, since a name the model wrote is no tool result for an answer\n// to repeat.\nfunction refusalOf(call: ToolCall, offered: ToolDefinition[], hasRoom: boolean): ChatMessage | null {\n const refuse = (content: string): ChatMessage => ({ role: 'tool', toolCallId: call.id, name: call.name, content });\n if (!offered.some((definition) => definition.name === call.name)) {\n return refuse(NOT_OFFERED);\n }\n return hasRoom ? null : refuse(TOO_MANY_CALLS);\n}\n\n// Answers every call of one model answer, so each call keeps its result in the conversation. A stopped\n// conversation runs no further tool.\nasync function answerToolCalls(run: ConversationRun, calls: ToolCall[], tools: OfferedTools): Promise<ChatMessage[]> {\n const { options } = run;\n const limit = options.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS;\n const results: ChatMessage[] = [];\n let ran = 0;\n for (const call of calls) {\n run.signal?.throwIfAborted();\n const refusal = refusalOf(call, tools.definitions, ran < limit);\n if (refusal) {\n results.push(refusal);\n continue;\n }\n ran += 1;\n const result = await runToolCall(tools.source, call, options);\n options.guard?.remember([result]);\n results.push(result);\n }\n return results;\n}\n\n// The answer that ends the conversation. Tool calls made when no tool was offered are left out, so the\n// conversation ends on the model's text and a provider accepts it as it is.\nfunction concluding(message: AssistantMessage): AssistantMessage {\n return message.toolCalls?.length ? { role: 'assistant', content: message.content } : message;\n}\n\n// Returns the messages the conversation gained: assistant turns and tool results, ending with\n// the final assistant answer.\nexport async function runConversation(options: ConversationOptions): Promise<ChatMessage[]> {\n const run = startRun(options);\n const { tools } = options;\n const definitions = tools ? await tools.listTools() : undefined;\n const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;\n\n for (let step = 0; step < maxSteps; step += 1) {\n // The last step offers no tools, so the model has to conclude.\n const offered = step < maxSteps - 1 ? definitions : undefined;\n const message = await askModel(run, offered);\n if (!tools || !offered || !message.toolCalls?.length) {\n run.added.push(concluding(message));\n return run.added;\n }\n run.added.push(message);\n run.added.push(...await answerToolCalls(run, message.toolCalls, { source: tools, definitions: offered }));\n }\n return run.added;\n}\n\nexport function finalAnswer(messages: ChatMessage[]): AssistantMessage | null {\n const last = messages.at(-1);\n return last?.role === 'assistant' ? last : null;\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -12,7 +12,12 @@ export interface ImagePart {
|
|
|
12
12
|
type: 'image';
|
|
13
13
|
url: string;
|
|
14
14
|
}
|
|
15
|
-
export
|
|
15
|
+
export interface FilePart {
|
|
16
|
+
type: 'file';
|
|
17
|
+
url: string;
|
|
18
|
+
name: string;
|
|
19
|
+
}
|
|
20
|
+
export type ContentPart = TextPart | ImagePart | FilePart;
|
|
16
21
|
export interface SystemMessage {
|
|
17
22
|
role: 'system';
|
|
18
23
|
content: string;
|
|
@@ -85,12 +90,19 @@ export interface ProviderSession {
|
|
|
85
90
|
model: string;
|
|
86
91
|
chat(request: ChatRequest): Promise<ChatResponse>;
|
|
87
92
|
}
|
|
93
|
+
export interface ReadableParts {
|
|
94
|
+
image: boolean;
|
|
95
|
+
pdf: boolean;
|
|
96
|
+
}
|
|
97
|
+
export type DictationMode = 'live' | 'file' | 'none';
|
|
88
98
|
export type WalletLink = {
|
|
89
99
|
connected: false;
|
|
90
100
|
} | {
|
|
91
101
|
connected: true;
|
|
92
102
|
providerName: string;
|
|
93
103
|
model?: string;
|
|
104
|
+
reads?: ReadableParts;
|
|
105
|
+
dictation?: DictationMode;
|
|
94
106
|
};
|
|
95
107
|
export interface ToolSource {
|
|
96
108
|
listTools(): Promise<ToolDefinition[]>;
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,8FAA8F;AAC9F,mGAAmG;AACnG,yBAAyB","sourcesContent":["// The vocabulary a site and the AI Wallet share: one chat format for every provider, the tools a\n// site offers, and what a site sees of the wallet. The wallet's connectors translate the chat\n// format to each provider's wire protocol and back; `AiConnect.fetch` translates the protocols the\n// AI SDKs speak into it.\n\nexport type JsonSchema = Record<string, unknown>;\n\nexport interface ToolCall {\n id: string;\n name: string;\n arguments: Record<string, unknown>;\n}\n\nexport interface TextPart {\n type: 'text';\n text: string;\n}\n\n// An image as a `data:` URL, or an https URL for the providers that fetch images themselves.\nexport interface ImagePart {\n type: 'image';\n url: string;\n}\n\nexport type ContentPart = TextPart | ImagePart;\n\nexport interface SystemMessage {\n role: 'system';\n content: string;\n}\n\nexport interface UserMessage {\n role: 'user';\n content: string | ContentPart[];\n}\n\nexport interface AssistantMessage {\n role: 'assistant';\n content: string;\n toolCalls?: ToolCall[];\n}\n\nexport interface ToolMessage {\n role: 'tool';\n toolCallId: string;\n name: string;\n content: string;\n}\n\nexport type ChatMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: JsonSchema;\n}\n\n// Whether the model may answer in text, must call a tool, or must call the named one.\nexport type ToolChoice = 'auto' | 'none' | 'required' | { name: string };\n\n// An answer in JSON, held to the schema when one is given. `strict` asks the providers that offer\n// it to refuse any schema they cannot enforce exactly.\nexport interface ResponseFormat {\n type: 'json';\n schema?: JsonSchema;\n name?: string;\n strict?: boolean;\n}\n\n// The settings an account may refuse: its connector leaves them out of the call.\nexport type GenerationHint = 'maxTokens' | 'temperature' | 'topP' | 'stop';\n\n// What the site asks of the answer. The hints above are left out where the account refuses them;\n// a tool choice and a response format always reach the provider.\nexport interface GenerationOptions {\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n stop?: string[];\n toolChoice?: ToolChoice;\n responseFormat?: ResponseFormat;\n}\n\n// Who answers a chat: the display name of the account, such as `Claude`, and the model the wallet\n// asks it for. A site on Auto learns it here, since the wallet picks the account for each answer.\nexport interface ChatStart {\n providerName: string;\n model: string;\n}\n\nexport interface ChatRequest {\n messages: ChatMessage[];\n tools?: ToolDefinition[];\n options?: GenerationOptions;\n signal?: AbortSignal;\n // On a site, the wallet's session calls it once, before the first text or the result.\n onStart?: (start: ChatStart) => void;\n onText?: (delta: string) => void;\n}\n\n// Why the answer ended: it was complete, it reached the token limit, it calls tools, or the\n// provider's filter stopped it.\nexport type FinishReason = 'stop' | 'length' | 'toolCalls' | 'contentFilter';\n\n// The tokens the provider counted for the call. `inputTokens` includes `cachedInputTokens`.\nexport interface Usage {\n inputTokens: number;\n outputTokens: number;\n cachedInputTokens: number;\n}\n\nexport interface ChatResponse {\n message: AssistantMessage;\n finishReason: FinishReason;\n // The model that answered, as the provider named it.\n model: string;\n // Absent when the provider reports no token counts.\n usage?: Usage;\n}\n\n// A chat session, ready to answer: on a site, the wallet answering with the user's account; in the\n// wallet, a connector calling the provider with the account's credential.\nexport interface ProviderSession {\n providerId: string;\n model: string;\n chat(request: ChatRequest): Promise<ChatResponse>;\n}\n\n// What a site sees of the wallet: whether it may use the visitor's AI, and then which account\n// answers it
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,8FAA8F;AAC9F,mGAAmG;AACnG,yBAAyB","sourcesContent":["// The vocabulary a site and the AI Wallet share: one chat format for every provider, the tools a\n// site offers, and what a site sees of the wallet. The wallet's connectors translate the chat\n// format to each provider's wire protocol and back; `AiConnect.fetch` translates the protocols the\n// AI SDKs speak into it.\n\nexport type JsonSchema = Record<string, unknown>;\n\nexport interface ToolCall {\n id: string;\n name: string;\n arguments: Record<string, unknown>;\n}\n\nexport interface TextPart {\n type: 'text';\n text: string;\n}\n\n// An image as a `data:` URL, or an https URL for the providers that fetch images themselves.\nexport interface ImagePart {\n type: 'image';\n url: string;\n}\n\n// A file the visitor attached, as a base64 `data:` URL with its name: a PDF, which an account that\n// reads PDFs receives whole, or a text file (plain text, Markdown, CSV, JSON), which the model reads\n// as text.\nexport interface FilePart {\n type: 'file';\n url: string;\n name: string;\n}\n\nexport type ContentPart = TextPart | ImagePart | FilePart;\n\nexport interface SystemMessage {\n role: 'system';\n content: string;\n}\n\nexport interface UserMessage {\n role: 'user';\n content: string | ContentPart[];\n}\n\nexport interface AssistantMessage {\n role: 'assistant';\n content: string;\n toolCalls?: ToolCall[];\n}\n\nexport interface ToolMessage {\n role: 'tool';\n toolCallId: string;\n name: string;\n content: string;\n}\n\nexport type ChatMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: JsonSchema;\n}\n\n// Whether the model may answer in text, must call a tool, or must call the named one.\nexport type ToolChoice = 'auto' | 'none' | 'required' | { name: string };\n\n// An answer in JSON, held to the schema when one is given. `strict` asks the providers that offer\n// it to refuse any schema they cannot enforce exactly.\nexport interface ResponseFormat {\n type: 'json';\n schema?: JsonSchema;\n name?: string;\n strict?: boolean;\n}\n\n// The settings an account may refuse: its connector leaves them out of the call.\nexport type GenerationHint = 'maxTokens' | 'temperature' | 'topP' | 'stop';\n\n// What the site asks of the answer. The hints above are left out where the account refuses them;\n// a tool choice and a response format always reach the provider.\nexport interface GenerationOptions {\n maxTokens?: number;\n temperature?: number;\n topP?: number;\n stop?: string[];\n toolChoice?: ToolChoice;\n responseFormat?: ResponseFormat;\n}\n\n// Who answers a chat: the display name of the account, such as `Claude`, and the model the wallet\n// asks it for. A site on Auto learns it here, since the wallet picks the account for each answer.\nexport interface ChatStart {\n providerName: string;\n model: string;\n}\n\nexport interface ChatRequest {\n messages: ChatMessage[];\n tools?: ToolDefinition[];\n options?: GenerationOptions;\n signal?: AbortSignal;\n // On a site, the wallet's session calls it once, before the first text or the result.\n onStart?: (start: ChatStart) => void;\n onText?: (delta: string) => void;\n}\n\n// Why the answer ended: it was complete, it reached the token limit, it calls tools, or the\n// provider's filter stopped it.\nexport type FinishReason = 'stop' | 'length' | 'toolCalls' | 'contentFilter';\n\n// The tokens the provider counted for the call. `inputTokens` includes `cachedInputTokens`.\nexport interface Usage {\n inputTokens: number;\n outputTokens: number;\n cachedInputTokens: number;\n}\n\nexport interface ChatResponse {\n message: AssistantMessage;\n finishReason: FinishReason;\n // The model that answered, as the provider named it.\n model: string;\n // Absent when the provider reports no token counts.\n usage?: Usage;\n}\n\n// A chat session, ready to answer: on a site, the wallet answering with the user's account; in the\n// wallet, a connector calling the provider with the account's credential.\nexport interface ProviderSession {\n providerId: string;\n model: string;\n chat(request: ChatRequest): Promise<ChatResponse>;\n}\n\n// What the model of an account reads besides text.\nexport interface ReadableParts {\n image: boolean;\n pdf: boolean;\n}\n\n// How the account transcribes the visitor's voice: `live` writes the words while they are spoken,\n// `file` transcribes the recording once it ends, and `none` leaves dictation to the browser.\nexport type DictationMode = 'live' | 'file' | 'none';\n\n// What a site sees of the wallet: whether it may use the visitor's AI, and then which account\n// answers it, on which model, what that model reads and how the account transcribes a voice. A\n// wallet older than attachments leaves `reads` and `dictation` out.\nexport type WalletLink =\n | { connected: false }\n | { connected: true; providerName: string; model?: string; reads?: ReadableParts; dictation?: DictationMode };\n\nexport interface ToolSource {\n listTools(): Promise<ToolDefinition[]>;\n callTool(name: string, args: Record<string, unknown>): Promise<string>;\n}\n"]}
|
package/dist/walletProvider.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { DictationStart } from './dictation.ts';
|
|
1
2
|
import type { ChatMessage, ChatStart, GenerationOptions, ToolDefinition, WalletLink } from './types.ts';
|
|
2
3
|
export interface WalletChatParams {
|
|
3
4
|
messages: ChatMessage[];
|
|
@@ -21,5 +22,6 @@ export interface WalletProvider {
|
|
|
21
22
|
isAIWallet: true;
|
|
22
23
|
request(method: string, params?: unknown, onEvent?: (event: ChatEvent) => void, signal?: AbortSignal): Promise<unknown>;
|
|
23
24
|
onLink(listener: (link: WalletLink) => void): () => void;
|
|
25
|
+
dictate?: DictationStart;
|
|
24
26
|
}
|
|
25
27
|
export declare function findWallet(): Promise<WalletProvider | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"walletProvider.js","sourceRoot":"","sources":["../src/walletProvider.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,+FAA+F;AAC/F,kDAAkD;
|
|
1
|
+
{"version":3,"file":"walletProvider.js","sourceRoot":"","sources":["../src/walletProvider.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,+FAA+F;AAC/F,kDAAkD;AAqBlD,+FAA+F;AAC/F,kGAAkG;AAClG,gGAAgG;AAChG,iGAAiG;AACjG,2DAA2D;AAC3D,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAClC,MAAM,CAAS;IACf,MAAM,CAAiB;IAChC,kGAAkG;IACzF,IAAI,CAAU;IAEvB,YAAY,OAAe,EAAE,MAAc,EAAE,MAAsB,EAAE,IAAa;QAChF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAgBD,iGAAiG;AACjG,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAI,UAA4C,CAAC,QAAQ,CAAC;IACvE,IAAI,OAAO,EAAE,UAAU,EAAE,CAAC;QACxB,OAAO,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,UAAU,GAAG,CAAC,KAAY,EAAE,EAAE;YAClC,MAAM,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;YAC5D,OAAO,CAAE,KAAqC,CAAC,MAAM,CAAC,CAAC;QACzD,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;QACzD,MAAM,CAAC,aAAa,CAAC,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC,CAAC;QACpD,UAAU,CAAC,GAAG,EAAE;YACd,MAAM,CAAC,mBAAmB,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;YAC5D,OAAO,CAAC,IAAI,CAAC,CAAC;QAChB,CAAC,EAAE,gBAAgB,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// The AI Wallet as a page sees it: `window.aiwallet`, which the extension announces to every page.\n// The extension's page script runs before the site's code, so the wallet is there on load; the\n// announce event covers a script that runs later.\n\nimport type { DictationStart } from './dictation.ts';\nimport type { ChatMessage, ChatStart, GenerationOptions, ToolDefinition, WalletLink } from './types.ts';\n\n// What a site sends with a `chat` request.\nexport interface WalletChatParams {\n messages: ChatMessage[];\n tools?: ToolDefinition[];\n options?: GenerationOptions;\n}\n\n// What a chat streams to the page before its result: one `start` naming who answers, sent before\n// the first text or, when the answer has no text, before the result; then each piece of text.\nexport type ChatEvent = ({ kind: 'start' } & ChatStart) | { kind: 'text'; delta: string };\n\n// Why a connection did not go through when the visitor's own step in the wallet says why: they\n// declined the site, closed the wallet's window before finishing, or the wallet stopped before it\n// answered. The site words each one in the page's language, with the next step.\nexport type WalletRefusal = 'declined' | 'closed' | 'interrupted';\n\n// A request the wallet refused or could not answer. `status` follows HTTP and is set where the\n// failure happens: the provider's own status for a provider error, 401 for a site the visitor has\n// not connected, 403 for a declined connection, a locked wallet or a wallet without an account,\n// 499 for an answer the visitor stopped in the wallet. `reason` says why a connection did not go\n// through, when the visitor's step in the wallet says why.\nexport class WalletRequestError extends Error {\n readonly status: number;\n readonly reason?: WalletRefusal;\n // The code a web account's provider gave its refusal, such as the plan gateway's `plan_inactive`.\n readonly code?: string;\n\n constructor(message: string, status: number, reason?: WalletRefusal, code?: string) {\n super(message);\n this.name = 'WalletRequestError';\n this.status = status;\n this.reason = reason;\n this.code = code;\n }\n}\n\nexport interface WalletProvider {\n isAIWallet: true;\n // A chat streams its events to `onEvent`. Aborting `signal` rejects the request with the signal's\n // reason, and the wallet stops the chat it runs for it.\n request(\n method: string, params?: unknown, onEvent?: (event: ChatEvent) => void, signal?: AbortSignal,\n ): Promise<unknown>;\n // Called when the visitor changes, in the wallet, the account or model this site answers with.\n onLink(listener: (link: WalletLink) => void): () => void;\n // Transcribes the visitor's voice with the account that answers, when the link's `dictation` is `live`\n // or `file`. A wallet older than dictation leaves it out.\n dictate?: DictationStart;\n}\n\n// How long a page waits for the wallet to announce itself before concluding it is not installed.\nconst ANNOUNCE_WAIT_MS = 300;\n\nexport function findWallet(): Promise<WalletProvider | null> {\n const present = (globalThis as { aiwallet?: WalletProvider }).aiwallet;\n if (present?.isAIWallet) {\n return Promise.resolve(present);\n }\n return new Promise((resolve) => {\n const onAnnounce = (event: Event) => {\n window.removeEventListener('aiwallet:announce', onAnnounce);\n resolve((event as CustomEvent<WalletProvider>).detail);\n };\n window.addEventListener('aiwallet:announce', onAnnounce);\n window.dispatchEvent(new Event('aiwallet:request'));\n setTimeout(() => {\n window.removeEventListener('aiwallet:announce', onAnnounce);\n resolve(null);\n }, ANNOUNCE_WAIT_MS);\n });\n}\n"]}
|
|
@@ -10,13 +10,19 @@ const FINISH_REASONS = {
|
|
|
10
10
|
function_call: 'toolCalls',
|
|
11
11
|
content_filter: 'contentFilter',
|
|
12
12
|
};
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
// Each part as OpenAI's chat completions write it. OpenRouter and the plan read a file part as OpenAI does.
|
|
14
|
+
function wirePart(part) {
|
|
15
|
+
switch (part.type) {
|
|
16
|
+
case 'text':
|
|
17
|
+
return { type: 'text', text: part.text };
|
|
18
|
+
case 'image':
|
|
19
|
+
return { type: 'image_url', image_url: { url: part.url } };
|
|
20
|
+
case 'file':
|
|
21
|
+
return { type: 'file', file: { filename: part.name, file_data: part.url } };
|
|
16
22
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
23
|
+
}
|
|
24
|
+
function wireContent(content) {
|
|
25
|
+
return typeof content === 'string' ? content : content.map(wirePart);
|
|
20
26
|
}
|
|
21
27
|
function wireMessage(message) {
|
|
22
28
|
if (message.role === 'tool') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openAiWire.js","sourceRoot":"","sources":["../../src/webAccounts/openAiWire.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,yGAAyG;AACzG,8DAA8D;AAO9D,mFAAmF;AACnF,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,MAAM,cAAc,GAAiC;IACnD,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,WAAW;IACvB,aAAa,EAAE,WAAW;IAC1B,cAAc,EAAE,eAAe;CAChC,CAAC;AAoBF,SAAS,WAAW,CAAC,OAA+B;IAClD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM;QAChD,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE;QACnC,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,WAAW,CAAC,OAAoB;IACvC,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC;IACtF,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,OAAO,CAAC,SAAS,EAAE,M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d,CAAC;IAED,QAAQ;QACN,MAAM,SAAS,GAAe,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;YACnF,EAAE,EAAE,OAAO,CAAC,EAAE,IAAI,QAAQ,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,SAAS,EAAE,cAAc,CAAC,OAAO,CAAC,SAAS,CAAC;SACpG,CAAC,CAAC,CAAC;QACJ,MAAM,YAAY,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,IAAI,MAAM,CAAC;QAClG,OAAO;YACL,OAAO,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE;YACjG,YAAY;YACZ,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC;SAC3B,CAAC;IACJ,CAAC;CACF;AAED,SAAS,OAAO,CAAC,KAA4B;IAC3C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,aAAa,IAAI,CAAC;QACrC,YAAY,EAAE,KAAK,CAAC,iBAAiB,IAAI,CAAC;QAC1C,iBAAiB,EAAE,KAAK,CAAC,qBAAqB,EAAE,aAAa,IAAI,CAAC;KACnE,CAAC;AACJ,CAAC","sourcesContent":["// The OpenAI chat completions protocol as a web account speaks it: the chat format written as a request\n// body, and the streamed chunks gathered back into one answer, its tool calls rebuilt from their deltas.\n// OpenRouter and TensorPass's plan gateway both answer in it.\n\nimport type {\n ChatMessage, ChatRequest, ChatResponse, ContentPart, FinishReason, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\n\n// The name OpenAI requires on a JSON schema, for a site that gave its schema none.\nconst SCHEMA_NAME = 'answer';\n\nconst FINISH_REASONS: Record<string, FinishReason> = {\n stop: 'stop',\n length: 'length',\n tool_calls: 'toolCalls',\n function_call: 'toolCalls',\n content_filter: 'contentFilter',\n};\n\ninterface ToolCallDelta {\n index: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n}\n\ninterface WireUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n}\n\nexport interface Chunk {\n model?: string;\n usage?: WireUsage;\n choices?: { delta?: { content?: string | null; tool_calls?: ToolCallDelta[] }; finish_reason?: string | null }[];\n}\n\nfunction wireContent(content: string | ContentPart[]) {\n if (typeof content === 'string') {\n return content;\n }\n return content.map((part) => (part.type === 'text'\n ? { type: 'text', text: part.text }\n : { type: 'image_url', image_url: { url: part.url } }));\n}\n\nfunction wireMessage(message: ChatMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content };\n }\n if (message.role === 'assistant' && message.toolCalls?.length) {\n return {\n role: 'assistant',\n content: message.content || null,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: JSON.stringify(call.arguments) },\n })),\n };\n }\n return { role: message.role, content: wireContent(message.content) };\n}\n\nfunction wireTool(tool: ToolDefinition): Record<string, unknown> {\n const { name, description, inputSchema } = tool;\n return { type: 'function', function: { name, description, parameters: inputSchema } };\n}\n\nfunction wireToolChoice(choice?: ToolChoice) {\n return typeof choice === 'object' ? { type: 'function', function: { name: choice.name } } : choice;\n}\n\nfunction wireResponseFormat(format?: ResponseFormat) {\n if (!format) {\n return undefined;\n }\n if (!format.schema) {\n return { type: 'json_object' };\n }\n const { name = SCHEMA_NAME, schema, strict } = format;\n return { type: 'json_schema', json_schema: { name, schema, strict } };\n}\n\n// Fields left undefined are dropped by the JSON encoding.\nexport function requestBody(model: string, request: ChatRequest): Record<string, unknown> {\n const options = request.options ?? {};\n return {\n model,\n stream: true,\n stream_options: { include_usage: true },\n messages: request.messages.map(wireMessage),\n tools: request.tools?.length ? request.tools.map(wireTool) : undefined,\n tool_choice: wireToolChoice(options.toolChoice),\n response_format: wireResponseFormat(options.responseFormat),\n max_tokens: options.maxTokens,\n temperature: options.temperature,\n top_p: options.topP,\n stop: options.stop?.length ? options.stop : undefined,\n };\n}\n\nfunction parseArguments(raw: string): Record<string, unknown> {\n if (!raw.trim()) {\n return {};\n }\n try {\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\n// The answer as its chunks arrive: the text, the tool calls, the finish reason, the model and the usage\n// the provider reports on its last chunk.\nexport class AnswerAssembly {\n content = '';\n model: string;\n private reason: string | undefined;\n private usage: WireUsage | undefined;\n private readonly partials: { id: string; name: string; arguments: string }[] = [];\n\n constructor(model: string) {\n this.model = model;\n }\n\n // Takes one chunk and returns the text it adds.\n add(chunk: Chunk): string {\n this.model = chunk.model || this.model;\n this.usage = chunk.usage ?? this.usage;\n const choice = chunk.choices?.[0];\n this.reason = choice?.finish_reason || this.reason;\n for (const delta of choice?.delta?.tool_calls ?? []) {\n const partial = (this.partials[delta.index] ??= { id: '', name: '', arguments: '' });\n partial.id ||= delta.id ?? '';\n partial.name += delta.function?.name ?? '';\n partial.arguments += delta.function?.arguments ?? '';\n }\n const text = choice?.delta?.content ?? '';\n this.content += text;\n return text;\n }\n\n response(): ChatResponse {\n const toolCalls: ToolCall[] = this.partials.filter(Boolean).map((partial, index) => ({\n id: partial.id || `call_${index}`, name: partial.name, arguments: parseArguments(partial.arguments),\n }));\n const finishReason = toolCalls.length ? 'toolCalls' : FINISH_REASONS[this.reason ?? ''] ?? 'stop';\n return {\n message: { role: 'assistant', content: this.content, ...(toolCalls.length ? { toolCalls } : {}) },\n finishReason,\n model: this.model,\n usage: usageOf(this.usage),\n };\n }\n}\n\nfunction usageOf(usage: WireUsage | undefined): Usage | undefined {\n if (!usage) {\n return undefined;\n }\n return {\n inputTokens: usage.prompt_tokens ?? 0,\n outputTokens: usage.completion_tokens ?? 0,\n cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"openAiWire.js","sourceRoot":"","sources":["../../src/webAccounts/openAiWire.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,yGAAyG;AACzG,8DAA8D;AAO9D,mFAAmF;AACnF,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,MAAM,cAAc,GAAiC;IACnD,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,WAAW;IACvB,aAAa,EAAE,WAAW;IAC1B,cAAc,EAAE,eAAe;CAChC,CAAC;AAoBF,4GAA4G;AAC5G,SAAS,QAAQ,CAAC,IAAiB;IACjC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;QAClB,KAAK,MAAM;YACT,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;QAC3C,KAAK,OAAO;YACV,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;QAC7D,KAAK,MAAM;YACT,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;IAChF,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,OAA+B;IAClD,OAAO,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,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CAAC;IACD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,aAAa,IAAI,CAAC;QACrC,YAAY,EAAE,KAAK,CAAC,iBAAiB,IAAI,CAAC;QAC1C,iBAAiB,EAAE,KAAK,CAAC,qBAAqB,EAAE,aAAa,IAAI,CAAC;KACnE,CAAC;AACJ,CAAC","sourcesContent":["// The OpenAI chat completions protocol as a web account speaks it: the chat format written as a request\n// body, and the streamed chunks gathered back into one answer, its tool calls rebuilt from their deltas.\n// OpenRouter and TensorPass's plan gateway both answer in it.\n\nimport type {\n ChatMessage, ChatRequest, ChatResponse, ContentPart, FinishReason, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\n\n// The name OpenAI requires on a JSON schema, for a site that gave its schema none.\nconst SCHEMA_NAME = 'answer';\n\nconst FINISH_REASONS: Record<string, FinishReason> = {\n stop: 'stop',\n length: 'length',\n tool_calls: 'toolCalls',\n function_call: 'toolCalls',\n content_filter: 'contentFilter',\n};\n\ninterface ToolCallDelta {\n index: number;\n id?: string;\n function?: { name?: string; arguments?: string };\n}\n\ninterface WireUsage {\n prompt_tokens?: number;\n completion_tokens?: number;\n prompt_tokens_details?: { cached_tokens?: number };\n}\n\nexport interface Chunk {\n model?: string;\n usage?: WireUsage;\n choices?: { delta?: { content?: string | null; tool_calls?: ToolCallDelta[] }; finish_reason?: string | null }[];\n}\n\n// Each part as OpenAI's chat completions write it. OpenRouter and the plan read a file part as OpenAI does.\nfunction wirePart(part: ContentPart): Record<string, unknown> {\n switch (part.type) {\n case 'text':\n return { type: 'text', text: part.text };\n case 'image':\n return { type: 'image_url', image_url: { url: part.url } };\n case 'file':\n return { type: 'file', file: { filename: part.name, file_data: part.url } };\n }\n}\n\nfunction wireContent(content: string | ContentPart[]) {\n return typeof content === 'string' ? content : content.map(wirePart);\n}\n\nfunction wireMessage(message: ChatMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content };\n }\n if (message.role === 'assistant' && message.toolCalls?.length) {\n return {\n role: 'assistant',\n content: message.content || null,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: JSON.stringify(call.arguments) },\n })),\n };\n }\n return { role: message.role, content: wireContent(message.content) };\n}\n\nfunction wireTool(tool: ToolDefinition): Record<string, unknown> {\n const { name, description, inputSchema } = tool;\n return { type: 'function', function: { name, description, parameters: inputSchema } };\n}\n\nfunction wireToolChoice(choice?: ToolChoice) {\n return typeof choice === 'object' ? { type: 'function', function: { name: choice.name } } : choice;\n}\n\nfunction wireResponseFormat(format?: ResponseFormat) {\n if (!format) {\n return undefined;\n }\n if (!format.schema) {\n return { type: 'json_object' };\n }\n const { name = SCHEMA_NAME, schema, strict } = format;\n return { type: 'json_schema', json_schema: { name, schema, strict } };\n}\n\n// Fields left undefined are dropped by the JSON encoding.\nexport function requestBody(model: string, request: ChatRequest): Record<string, unknown> {\n const options = request.options ?? {};\n return {\n model,\n stream: true,\n stream_options: { include_usage: true },\n messages: request.messages.map(wireMessage),\n tools: request.tools?.length ? request.tools.map(wireTool) : undefined,\n tool_choice: wireToolChoice(options.toolChoice),\n response_format: wireResponseFormat(options.responseFormat),\n max_tokens: options.maxTokens,\n temperature: options.temperature,\n top_p: options.topP,\n stop: options.stop?.length ? options.stop : undefined,\n };\n}\n\nfunction parseArguments(raw: string): Record<string, unknown> {\n if (!raw.trim()) {\n return {};\n }\n try {\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\n// The answer as its chunks arrive: the text, the tool calls, the finish reason, the model and the usage\n// the provider reports on its last chunk.\nexport class AnswerAssembly {\n content = '';\n model: string;\n private reason: string | undefined;\n private usage: WireUsage | undefined;\n private readonly partials: { id: string; name: string; arguments: string }[] = [];\n\n constructor(model: string) {\n this.model = model;\n }\n\n // Takes one chunk and returns the text it adds.\n add(chunk: Chunk): string {\n this.model = chunk.model || this.model;\n this.usage = chunk.usage ?? this.usage;\n const choice = chunk.choices?.[0];\n this.reason = choice?.finish_reason || this.reason;\n for (const delta of choice?.delta?.tool_calls ?? []) {\n const partial = (this.partials[delta.index] ??= { id: '', name: '', arguments: '' });\n partial.id ||= delta.id ?? '';\n partial.name += delta.function?.name ?? '';\n partial.arguments += delta.function?.arguments ?? '';\n }\n const text = choice?.delta?.content ?? '';\n this.content += text;\n return text;\n }\n\n response(): ChatResponse {\n const toolCalls: ToolCall[] = this.partials.filter(Boolean).map((partial, index) => ({\n id: partial.id || `call_${index}`, name: partial.name, arguments: parseArguments(partial.arguments),\n }));\n const finishReason = toolCalls.length ? 'toolCalls' : FINISH_REASONS[this.reason ?? ''] ?? 'stop';\n return {\n message: { role: 'assistant', content: this.content, ...(toolCalls.length ? { toolCalls } : {}) },\n finishReason,\n model: this.model,\n usage: usageOf(this.usage),\n };\n }\n}\n\nfunction usageOf(usage: WireUsage | undefined): Usage | undefined {\n if (!usage) {\n return undefined;\n }\n return {\n inputTokens: usage.prompt_tokens ?? 0,\n outputTokens: usage.completion_tokens ?? 0,\n cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,\n };\n}\n"]}
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
// content block per text and per tool call, then `message_delta` with the stop reason and the
|
|
4
4
|
// usage. `message_start` names the model of the account that answers, which the wallet tells
|
|
5
5
|
// before the first text, and counts nothing yet, since the wallet reports usage once the answer ends.
|
|
6
|
-
import { dataUrl, textOf } from "../chatContent.js";
|
|
7
|
-
import { EMPTY_PARAMETERS, errorType, toolNameOf, unsupported, userContent } from "./wireProtocol.js";
|
|
6
|
+
import { dataUrl, encodeBase64Text, textOf } from "../chatContent.js";
|
|
7
|
+
import { EMPTY_PARAMETERS, errorType, filePart, toolNameOf, unsupported, userContent } from "./wireProtocol.js";
|
|
8
8
|
const STOP_REASONS = {
|
|
9
9
|
stop: 'end_turn',
|
|
10
10
|
length: 'max_tokens',
|
|
@@ -31,6 +31,18 @@ function imageUrl(source) {
|
|
|
31
31
|
}
|
|
32
32
|
throw unsupported(`${source.type} image sources`);
|
|
33
33
|
}
|
|
34
|
+
// A document block: a PDF or a text file given as base64, or a text file given as its text.
|
|
35
|
+
function documentPart(block) {
|
|
36
|
+
const source = block.source;
|
|
37
|
+
if (source?.type === 'base64' && source.media_type && source.data) {
|
|
38
|
+
return filePart(dataUrl({ mediaType: source.media_type, data: source.data }), block.title);
|
|
39
|
+
}
|
|
40
|
+
if (source?.type === 'text' && typeof source.data === 'string') {
|
|
41
|
+
const mediaType = source.media_type ?? 'text/plain';
|
|
42
|
+
return filePart(dataUrl({ mediaType, data: encodeBase64Text(source.data) }), block.title);
|
|
43
|
+
}
|
|
44
|
+
throw unsupported(`${source?.type ?? 'untyped'} document sources`);
|
|
45
|
+
}
|
|
34
46
|
function partOf(block) {
|
|
35
47
|
if (block.type === 'text') {
|
|
36
48
|
return { type: 'text', text: block.text ?? '' };
|
|
@@ -38,13 +50,16 @@ function partOf(block) {
|
|
|
38
50
|
if (block.type === 'image' && block.source) {
|
|
39
51
|
return { type: 'image', url: imageUrl(block.source) };
|
|
40
52
|
}
|
|
53
|
+
if (block.type === 'document') {
|
|
54
|
+
return documentPart(block);
|
|
55
|
+
}
|
|
41
56
|
throw unsupported(`${block.type} content`);
|
|
42
57
|
}
|
|
43
58
|
// A tool result's content is text; images inside a result have no place in the shared format.
|
|
44
59
|
function resultText(block) {
|
|
45
60
|
const parts = blocksOf(block.content).map(partOf);
|
|
46
61
|
if (parts.some((part) => part.type !== 'text')) {
|
|
47
|
-
throw unsupported('images inside tool results');
|
|
62
|
+
throw unsupported('images or files inside tool results');
|
|
48
63
|
}
|
|
49
64
|
return textOf(parts);
|
|
50
65
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropicMessages.js","sourceRoot":"","sources":["../../src/wireProtocols/anthropicMessages.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,kGAAkG;AAClG,8FAA8F;AAC9F,6FAA6F;AA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Ac,EAAE,EAAE,cAAc,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,IAAI,CAAC,QAAsB,EAAE,OAAsB;IAC1D,OAAO,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;AAC7F,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAiB;IAC7C,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,KAAK,EAAE,SAAS;IAChB,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;CACrE,CAAC","sourcesContent":["// The Anthropic Messages protocol, as the Anthropic SDK, the Vercel AI SDK's `anthropic()` models\n// and LangChain's ChatAnthropic speak it. Streamed answers go as named events: `message_start`, a\n// content block per text and per tool call, then `message_delta` with the stop reason and the\n// usage. `message_start` names the model of the account that answers, which the wallet tells\n// before the first text, and counts nothing yet, since the wallet reports usage once the answer ends.\n\nimport { dataUrl, textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ToolCall, ToolChoice, ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport { EMPTY_PARAMETERS, errorType, toolNameOf, unsupported, userContent } from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WireBlock {\n type: string;\n text?: string;\n source?: { type: string; media_type?: string; data?: string; url?: string };\n id?: string;\n name?: string;\n input?: Record<string, unknown>;\n tool_use_id?: string;\n content?: string | WireBlock[];\n}\n\ninterface WireMessage {\n role: 'user' | 'assistant';\n content: string | WireBlock[];\n}\n\ninterface WireTool {\n type?: string;\n name: string;\n description?: string;\n input_schema?: JsonSchema;\n}\n\ninterface MessagesBody {\n system?: string | WireBlock[];\n messages?: WireMessage[];\n tools?: WireTool[];\n tool_choice?: { type: string; name?: string };\n output_config?: { format?: { type: string; schema?: JsonSchema } };\n output_format?: { type: string; schema?: JsonSchema };\n max_tokens?: number;\n temperature?: number;\n top_p?: number;\n stop_sequences?: string[];\n stream?: boolean;\n}\n\nconst STOP_REASONS: Record<FinishReason, string> = {\n stop: 'end_turn',\n length: 'max_tokens',\n toolCalls: 'tool_use',\n contentFilter: 'refusal',\n};\n\n// Thinking blocks hold the provider's own reasoning, which another account cannot read.\nconst SKIPPED_BLOCKS = new Set(['thinking', 'redacted_thinking']);\n\nconst TOOL_CHOICES: Record<string, ToolChoice> = { auto: 'auto', any: 'required', none: 'none' };\n\n// What `message_start` counts: nothing yet, the final counts come with `message_delta`.\nconst NOTHING_COUNTED = { input_tokens: 0, output_tokens: 0 };\n\nfunction blocksOf(content: string | WireBlock[] | undefined): WireBlock[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).filter((block) => !SKIPPED_BLOCKS.has(block.type));\n}\n\nfunction imageUrl(source: NonNullable<WireBlock['source']>): string {\n if (source.type === 'base64' && source.media_type && source.data) {\n return dataUrl({ mediaType: source.media_type, data: source.data });\n }\n if (source.type === 'url' && source.url) {\n return source.url;\n }\n throw unsupported(`${source.type} image sources`);\n}\n\nfunction partOf(block: WireBlock): ContentPart {\n if (block.type === 'text') {\n return { type: 'text', text: block.text ?? '' };\n }\n if (block.type === 'image' && block.source) {\n return { type: 'image', url: imageUrl(block.source) };\n }\n throw unsupported(`${block.type} content`);\n}\n\n// A tool result's content is text; images inside a result have no place in the shared format.\nfunction resultText(block: WireBlock): string {\n const parts = blocksOf(block.content).map(partOf);\n if (parts.some((part) => part.type !== 'text')) {\n throw unsupported('images inside tool results');\n }\n return textOf(parts);\n}\n\n// A user turn carries the results of the previous tool calls first, then what the user wrote.\nfunction readUser(blocks: WireBlock[], names: Map<string, string>): ChatMessage[] {\n const results = blocks.filter((block) => block.type === 'tool_result').map((block): ChatMessage => {\n const toolCallId = block.tool_use_id ?? '';\n return { role: 'tool', toolCallId, name: toolNameOf(names, toolCallId), content: resultText(block) };\n });\n const parts = blocks.filter((block) => block.type !== 'tool_result').map(partOf);\n return parts.length ? [...results, { role: 'user', content: userContent(parts) }] : results;\n}\n\nfunction readAssistant(blocks: WireBlock[], names: Map<string, string>): ChatMessage {\n const toolCalls: ToolCall[] = blocks.filter((block) => block.type === 'tool_use').map((block) => ({\n id: block.id ?? '', name: block.name ?? '', arguments: block.input ?? {},\n }));\n toolCalls.forEach((call) => names.set(call.id, call.name));\n const content = textOf(blocks.filter((block) => block.type !== 'tool_use').map(partOf));\n return { role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) };\n}\n\nfunction readMessages(body: MessagesBody): ChatMessage[] {\n const names = new Map<string, string>();\n const system = textOf(blocksOf(body.system).map(partOf));\n const conversation = (body.messages ?? []).flatMap((message) => (message.role === 'assistant'\n ? [readAssistant(blocksOf(message.content), names)]\n : readUser(blocksOf(message.content), names)));\n return system ? [{ role: 'system', content: system }, ...conversation] : conversation;\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type && tool.type !== 'custom') {\n throw unsupported(`the ${tool.type} tool`);\n }\n return { name: tool.name, description: tool.description ?? '', inputSchema: tool.input_schema ?? EMPTY_PARAMETERS };\n });\n}\n\nfunction readToolChoice(choice: MessagesBody['tool_choice']): ToolChoice | undefined {\n if (!choice) {\n return undefined;\n }\n return choice.type === 'tool' && choice.name ? { name: choice.name } : TOOL_CHOICES[choice.type];\n}\n\nfunction read(raw: Record<string, unknown>): WireRequest {\n const body = raw as MessagesBody;\n const format = body.output_config?.format ?? body.output_format;\n return {\n request: {\n messages: readMessages(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: body.max_tokens,\n temperature: body.temperature,\n topP: body.top_p,\n stop: body.stop_sequences,\n toolChoice: readToolChoice(body.tool_choice),\n responseFormat: format ? { type: 'json', schema: format.schema } : undefined,\n },\n },\n stream: body.stream === true,\n };\n}\n\n// The protocol counts cached input apart from the rest.\nfunction wireUsage(usage: Usage | undefined) {\n if (!usage) {\n return undefined;\n }\n return {\n input_tokens: usage.inputTokens - usage.cachedInputTokens,\n output_tokens: usage.outputTokens,\n cache_read_input_tokens: usage.cachedInputTokens,\n };\n}\n\nfunction contentBlocks({ message }: ChatResponse) {\n const text = message.content ? [{ type: 'text', text: message.content }] : [];\n const uses = (message.toolCalls ?? []).map((call) => ({\n type: 'tool_use', id: call.id, name: call.name, input: call.arguments,\n }));\n return [...text, ...uses];\n}\n\nfunction messageObject(context: AnswerContext, model: string, content: unknown[], response?: ChatResponse) {\n return {\n id: `msg_${context.id}`,\n type: 'message',\n role: 'assistant',\n model,\n content,\n stop_reason: response ? STOP_REASONS[response.finishReason] : null,\n stop_sequence: null,\n usage: response ? wireUsage(response.usage) : NOTHING_COUNTED,\n };\n}\n\nfunction writeToolUse(write: EventWriter, call: ToolCall, index: number): void {\n const contentBlock = { type: 'tool_use', id: call.id, name: call.name, input: {} };\n const delta = { type: 'input_json_delta', partial_json: JSON.stringify(call.arguments) };\n write.send({ type: 'content_block_start', index, content_block: contentBlock }, 'content_block_start');\n write.send({ type: 'content_block_delta', index, delta }, 'content_block_delta');\n write.send({ type: 'content_block_stop', index }, 'content_block_stop');\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const { model } = await answer.started;\n write.send({ type: 'message_start', message: messageObject(context, model, []) }, 'message_start');\n let streamed = false;\n for await (const text of answer.texts()) {\n if (!streamed) {\n const contentBlock = { type: 'text', text: '' };\n write.send({ type: 'content_block_start', index: 0, content_block: contentBlock }, 'content_block_start');\n streamed = true;\n }\n write.send({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }, 'content_block_delta');\n }\n const response = await answer.result;\n if (streamed) {\n write.send({ type: 'content_block_stop', index: 0 }, 'content_block_stop');\n }\n const offset = streamed ? 1 : 0;\n (response.message.toolCalls ?? []).forEach((call, index) => writeToolUse(write, call, index + offset));\n const delta = { stop_reason: STOP_REASONS[response.finishReason], stop_sequence: null };\n write.send({ type: 'message_delta', delta, usage: wireUsage(response.usage) }, 'message_delta');\n write.send({ type: 'message_stop' }, 'message_stop');\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n return messageObject(context, response.model, contentBlocks(response), response);\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { type: 'error', error: { type: errorType(error.status), message: error.message } };\n}\n\nexport const anthropicMessages: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({ data: errorBody(error), event: 'error' }),\n};\n"]}
|
|
1
|
+
{"version":3,"file":"anthropicMessages.js","sourceRoot":"","sources":["../../src/wireProtocols/anthropicMessages.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,kGAAkG;AAClG,8FAA8F;AAC9F,6FAA6F;AAC7F,sGAAsG;AAEtG,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAOtE,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAyChH,MAAM,YAAY,GAAiC;IACjD,IAAI,EAAE,UAAU;IAChB,MAAM,EAAE,YAAY;IACpB,SAAS,EAAE,UAAU;IACrB,aAAa,EAAE,SAAS;CACzB,CAAC;AAEF,wFAAwF;AACxF,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,UA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's `anthropic()` models\n// and LangChain's ChatAnthropic speak it. Streamed answers go as named events: `message_start`, a\n// content block per text and per tool call, then `message_delta` with the stop reason and the\n// usage. `message_start` names the model of the account that answers, which the wallet tells\n// before the first text, and counts nothing yet, since the wallet reports usage once the answer ends.\n\nimport { dataUrl, encodeBase64Text, textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ToolCall, ToolChoice, ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport { EMPTY_PARAMETERS, errorType, filePart, toolNameOf, unsupported, userContent } from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WireBlock {\n type: string;\n text?: string;\n source?: { type: string; media_type?: string; data?: string; url?: string };\n title?: string;\n id?: string;\n name?: string;\n input?: Record<string, unknown>;\n tool_use_id?: string;\n content?: string | WireBlock[];\n}\n\ninterface WireMessage {\n role: 'user' | 'assistant';\n content: string | WireBlock[];\n}\n\ninterface WireTool {\n type?: string;\n name: string;\n description?: string;\n input_schema?: JsonSchema;\n}\n\ninterface MessagesBody {\n system?: string | WireBlock[];\n messages?: WireMessage[];\n tools?: WireTool[];\n tool_choice?: { type: string; name?: string };\n output_config?: { format?: { type: string; schema?: JsonSchema } };\n output_format?: { type: string; schema?: JsonSchema };\n max_tokens?: number;\n temperature?: number;\n top_p?: number;\n stop_sequences?: string[];\n stream?: boolean;\n}\n\nconst STOP_REASONS: Record<FinishReason, string> = {\n stop: 'end_turn',\n length: 'max_tokens',\n toolCalls: 'tool_use',\n contentFilter: 'refusal',\n};\n\n// Thinking blocks hold the provider's own reasoning, which another account cannot read.\nconst SKIPPED_BLOCKS = new Set(['thinking', 'redacted_thinking']);\n\nconst TOOL_CHOICES: Record<string, ToolChoice> = { auto: 'auto', any: 'required', none: 'none' };\n\n// What `message_start` counts: nothing yet, the final counts come with `message_delta`.\nconst NOTHING_COUNTED = { input_tokens: 0, output_tokens: 0 };\n\nfunction blocksOf(content: string | WireBlock[] | undefined): WireBlock[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).filter((block) => !SKIPPED_BLOCKS.has(block.type));\n}\n\nfunction imageUrl(source: NonNullable<WireBlock['source']>): string {\n if (source.type === 'base64' && source.media_type && source.data) {\n return dataUrl({ mediaType: source.media_type, data: source.data });\n }\n if (source.type === 'url' && source.url) {\n return source.url;\n }\n throw unsupported(`${source.type} image sources`);\n}\n\n// A document block: a PDF or a text file given as base64, or a text file given as its text.\nfunction documentPart(block: WireBlock): ContentPart {\n const source = block.source;\n if (source?.type === 'base64' && source.media_type && source.data) {\n return filePart(dataUrl({ mediaType: source.media_type, data: source.data }), block.title);\n }\n if (source?.type === 'text' && typeof source.data === 'string') {\n const mediaType = source.media_type ?? 'text/plain';\n return filePart(dataUrl({ mediaType, data: encodeBase64Text(source.data) }), block.title);\n }\n throw unsupported(`${source?.type ?? 'untyped'} document sources`);\n}\n\nfunction partOf(block: WireBlock): ContentPart {\n if (block.type === 'text') {\n return { type: 'text', text: block.text ?? '' };\n }\n if (block.type === 'image' && block.source) {\n return { type: 'image', url: imageUrl(block.source) };\n }\n if (block.type === 'document') {\n return documentPart(block);\n }\n throw unsupported(`${block.type} content`);\n}\n\n// A tool result's content is text; images inside a result have no place in the shared format.\nfunction resultText(block: WireBlock): string {\n const parts = blocksOf(block.content).map(partOf);\n if (parts.some((part) => part.type !== 'text')) {\n throw unsupported('images or files inside tool results');\n }\n return textOf(parts);\n}\n\n// A user turn carries the results of the previous tool calls first, then what the user wrote.\nfunction readUser(blocks: WireBlock[], names: Map<string, string>): ChatMessage[] {\n const results = blocks.filter((block) => block.type === 'tool_result').map((block): ChatMessage => {\n const toolCallId = block.tool_use_id ?? '';\n return { role: 'tool', toolCallId, name: toolNameOf(names, toolCallId), content: resultText(block) };\n });\n const parts = blocks.filter((block) => block.type !== 'tool_result').map(partOf);\n return parts.length ? [...results, { role: 'user', content: userContent(parts) }] : results;\n}\n\nfunction readAssistant(blocks: WireBlock[], names: Map<string, string>): ChatMessage {\n const toolCalls: ToolCall[] = blocks.filter((block) => block.type === 'tool_use').map((block) => ({\n id: block.id ?? '', name: block.name ?? '', arguments: block.input ?? {},\n }));\n toolCalls.forEach((call) => names.set(call.id, call.name));\n const content = textOf(blocks.filter((block) => block.type !== 'tool_use').map(partOf));\n return { role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) };\n}\n\nfunction readMessages(body: MessagesBody): ChatMessage[] {\n const names = new Map<string, string>();\n const system = textOf(blocksOf(body.system).map(partOf));\n const conversation = (body.messages ?? []).flatMap((message) => (message.role === 'assistant'\n ? [readAssistant(blocksOf(message.content), names)]\n : readUser(blocksOf(message.content), names)));\n return system ? [{ role: 'system', content: system }, ...conversation] : conversation;\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type && tool.type !== 'custom') {\n throw unsupported(`the ${tool.type} tool`);\n }\n return { name: tool.name, description: tool.description ?? '', inputSchema: tool.input_schema ?? EMPTY_PARAMETERS };\n });\n}\n\nfunction readToolChoice(choice: MessagesBody['tool_choice']): ToolChoice | undefined {\n if (!choice) {\n return undefined;\n }\n return choice.type === 'tool' && choice.name ? { name: choice.name } : TOOL_CHOICES[choice.type];\n}\n\nfunction read(raw: Record<string, unknown>): WireRequest {\n const body = raw as MessagesBody;\n const format = body.output_config?.format ?? body.output_format;\n return {\n request: {\n messages: readMessages(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: body.max_tokens,\n temperature: body.temperature,\n topP: body.top_p,\n stop: body.stop_sequences,\n toolChoice: readToolChoice(body.tool_choice),\n responseFormat: format ? { type: 'json', schema: format.schema } : undefined,\n },\n },\n stream: body.stream === true,\n };\n}\n\n// The protocol counts cached input apart from the rest.\nfunction wireUsage(usage: Usage | undefined) {\n if (!usage) {\n return undefined;\n }\n return {\n input_tokens: usage.inputTokens - usage.cachedInputTokens,\n output_tokens: usage.outputTokens,\n cache_read_input_tokens: usage.cachedInputTokens,\n };\n}\n\nfunction contentBlocks({ message }: ChatResponse) {\n const text = message.content ? [{ type: 'text', text: message.content }] : [];\n const uses = (message.toolCalls ?? []).map((call) => ({\n type: 'tool_use', id: call.id, name: call.name, input: call.arguments,\n }));\n return [...text, ...uses];\n}\n\nfunction messageObject(context: AnswerContext, model: string, content: unknown[], response?: ChatResponse) {\n return {\n id: `msg_${context.id}`,\n type: 'message',\n role: 'assistant',\n model,\n content,\n stop_reason: response ? STOP_REASONS[response.finishReason] : null,\n stop_sequence: null,\n usage: response ? wireUsage(response.usage) : NOTHING_COUNTED,\n };\n}\n\nfunction writeToolUse(write: EventWriter, call: ToolCall, index: number): void {\n const contentBlock = { type: 'tool_use', id: call.id, name: call.name, input: {} };\n const delta = { type: 'input_json_delta', partial_json: JSON.stringify(call.arguments) };\n write.send({ type: 'content_block_start', index, content_block: contentBlock }, 'content_block_start');\n write.send({ type: 'content_block_delta', index, delta }, 'content_block_delta');\n write.send({ type: 'content_block_stop', index }, 'content_block_stop');\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const { model } = await answer.started;\n write.send({ type: 'message_start', message: messageObject(context, model, []) }, 'message_start');\n let streamed = false;\n for await (const text of answer.texts()) {\n if (!streamed) {\n const contentBlock = { type: 'text', text: '' };\n write.send({ type: 'content_block_start', index: 0, content_block: contentBlock }, 'content_block_start');\n streamed = true;\n }\n write.send({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }, 'content_block_delta');\n }\n const response = await answer.result;\n if (streamed) {\n write.send({ type: 'content_block_stop', index: 0 }, 'content_block_stop');\n }\n const offset = streamed ? 1 : 0;\n (response.message.toolCalls ?? []).forEach((call, index) => writeToolUse(write, call, index + offset));\n const delta = { stop_reason: STOP_REASONS[response.finishReason], stop_sequence: null };\n write.send({ type: 'message_delta', delta, usage: wireUsage(response.usage) }, 'message_delta');\n write.send({ type: 'message_stop' }, 'message_stop');\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n return messageObject(context, response.model, contentBlocks(response), response);\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { type: 'error', error: { type: errorType(error.status), message: error.message } };\n}\n\nexport const anthropicMessages: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({ data: errorBody(error), event: 'error' }),\n};\n"]}
|