@tensorpass/aiconnect 0.0.0-stage → 0.1.1
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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +18 -2
- package/dist/callback.d.ts +2 -0
- package/dist/callback.js +4 -0
- package/dist/callback.js.map +1 -0
- package/dist/chatContent.d.ts +9 -0
- package/dist/chatContent.js +23 -0
- package/dist/chatContent.js.map +1 -0
- package/dist/cli/loopbackSignIn.d.ts +11 -0
- package/dist/cli/loopbackSignIn.js +94 -0
- package/dist/cli/loopbackSignIn.js.map +1 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +41 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/cli/siteKeyCommand.d.ts +11 -0
- package/dist/cli/siteKeyCommand.js +31 -0
- package/dist/cli/siteKeyCommand.js.map +1 -0
- package/dist/cli/siteKeyPlacement.d.ts +3 -0
- package/dist/cli/siteKeyPlacement.js +56 -0
- package/dist/cli/siteKeyPlacement.js.map +1 -0
- package/dist/client.d.ts +43 -0
- package/dist/client.js +211 -0
- package/dist/client.js.map +1 -0
- package/dist/connectionState.d.ts +31 -0
- package/dist/connectionState.js +4 -0
- package/dist/connectionState.js.map +1 -0
- package/dist/guards/answerGuard.d.ts +14 -0
- package/dist/guards/answerGuard.js +189 -0
- package/dist/guards/answerGuard.js.map +1 -0
- package/dist/guards/chatGuard.d.ts +18 -0
- package/dist/guards/chatGuard.js +62 -0
- package/dist/guards/chatGuard.js.map +1 -0
- package/dist/guards/envelopes.d.ts +8 -0
- package/dist/guards/envelopes.js +49 -0
- package/dist/guards/envelopes.js.map +1 -0
- package/dist/guards/index.d.ts +8 -0
- package/dist/guards/index.js +8 -0
- package/dist/guards/index.js.map +1 -0
- package/dist/guards/policy.d.ts +28 -0
- package/dist/guards/policy.js +20 -0
- package/dist/guards/policy.js.map +1 -0
- package/dist/guards/questionGuard.d.ts +8 -0
- package/dist/guards/questionGuard.js +53 -0
- package/dist/guards/questionGuard.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/mcpToolSource.d.ts +13 -0
- package/dist/mcpToolSource.js +54 -0
- package/dist/mcpToolSource.js.map +1 -0
- package/dist/toolLoop.d.ts +18 -0
- package/dist/toolLoop.js +153 -0
- package/dist/toolLoop.js.map +1 -0
- package/dist/types.d.ts +98 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/visitorBrowser.d.ts +17 -0
- package/dist/visitorBrowser.js +72 -0
- package/dist/visitorBrowser.js.map +1 -0
- package/dist/walletProvider.d.ts +25 -0
- package/dist/walletProvider.js +42 -0
- package/dist/walletProvider.js.map +1 -0
- package/dist/webAccounts/finishSignIn.d.ts +2 -0
- package/dist/webAccounts/finishSignIn.js +46 -0
- package/dist/webAccounts/finishSignIn.js.map +1 -0
- package/dist/webAccounts/openAiCompatibleSession.d.ts +15 -0
- package/dist/webAccounts/openAiCompatibleSession.js +84 -0
- package/dist/webAccounts/openAiCompatibleSession.js.map +1 -0
- package/dist/webAccounts/openAiWire.d.ts +39 -0
- package/dist/webAccounts/openAiWire.js +133 -0
- package/dist/webAccounts/openAiWire.js.map +1 -0
- package/dist/webAccounts/openRouterAccount.d.ts +3 -0
- package/dist/webAccounts/openRouterAccount.js +64 -0
- package/dist/webAccounts/openRouterAccount.js.map +1 -0
- package/dist/webAccounts/pkce.d.ts +2 -0
- package/dist/webAccounts/pkce.js +17 -0
- package/dist/webAccounts/pkce.js.map +1 -0
- package/dist/webAccounts/serverSentEvents.d.ts +1 -0
- package/dist/webAccounts/serverSentEvents.js +62 -0
- package/dist/webAccounts/serverSentEvents.js.map +1 -0
- package/dist/webAccounts/signInWindow.d.ts +27 -0
- package/dist/webAccounts/signInWindow.js +164 -0
- package/dist/webAccounts/signInWindow.js.map +1 -0
- package/dist/webAccounts/tensorPassAccount.d.ts +9 -0
- package/dist/webAccounts/tensorPassAccount.js +128 -0
- package/dist/webAccounts/tensorPassAccount.js.map +1 -0
- package/dist/webAccounts/tensorPassPlan.d.ts +27 -0
- package/dist/webAccounts/tensorPassPlan.js +36 -0
- package/dist/webAccounts/tensorPassPlan.js.map +1 -0
- package/dist/webAccounts/webAccount.d.ts +30 -0
- package/dist/webAccounts/webAccount.js +19 -0
- package/dist/webAccounts/webAccount.js.map +1 -0
- package/dist/webAccounts/webAccountSource.d.ts +43 -0
- package/dist/webAccounts/webAccountSource.js +216 -0
- package/dist/webAccounts/webAccountSource.js.map +1 -0
- package/dist/webAccounts/webAccountStore.d.ts +27 -0
- package/dist/webAccounts/webAccountStore.js +84 -0
- package/dist/webAccounts/webAccountStore.js.map +1 -0
- package/dist/wireProtocols/anthropicMessages.d.ts +2 -0
- package/dist/wireProtocols/anthropicMessages.js +181 -0
- package/dist/wireProtocols/anthropicMessages.js.map +1 -0
- package/dist/wireProtocols/eventStream.d.ts +4 -0
- package/dist/wireProtocols/eventStream.js +32 -0
- package/dist/wireProtocols/eventStream.js.map +1 -0
- package/dist/wireProtocols/geminiContents.d.ts +2 -0
- package/dist/wireProtocols/geminiContents.js +201 -0
- package/dist/wireProtocols/geminiContents.js.map +1 -0
- package/dist/wireProtocols/openAiChat.d.ts +2 -0
- package/dist/wireProtocols/openAiChat.js +161 -0
- package/dist/wireProtocols/openAiChat.js.map +1 -0
- package/dist/wireProtocols/openAiResponses.d.ts +2 -0
- package/dist/wireProtocols/openAiResponses.js +226 -0
- package/dist/wireProtocols/openAiResponses.js.map +1 -0
- package/dist/wireProtocols/walletAnswer.d.ts +7 -0
- package/dist/wireProtocols/walletAnswer.js +50 -0
- package/dist/wireProtocols/walletAnswer.js.map +1 -0
- package/dist/wireProtocols/walletFetch.d.ts +3 -0
- package/dist/wireProtocols/walletFetch.js +101 -0
- package/dist/wireProtocols/walletFetch.js.map +1 -0
- package/dist/wireProtocols/wireProtocol.d.ts +31 -0
- package/dist/wireProtocols/wireProtocol.js +44 -0
- package/dist/wireProtocols/wireProtocol.js.map +1 -0
- package/package.json +61 -4
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ConnectionState } from './connectionState.ts';
|
|
2
|
+
import type { VisitorBrowser } from './visitorBrowser.ts';
|
|
3
|
+
import type { WebAccountOptions } from './webAccounts/webAccountSource.ts';
|
|
4
|
+
import type { PlanAccess } from './webAccounts/tensorPassPlan.ts';
|
|
5
|
+
import type { WebAccountId } from './webAccounts/webAccountStore.ts';
|
|
6
|
+
import type { WalletFetch } from './wireProtocols/walletFetch.ts';
|
|
7
|
+
export type { ConnectionState, WebSignInFailure } from './connectionState.ts';
|
|
8
|
+
export type AiConnectOptions = WebAccountOptions;
|
|
9
|
+
export interface SdkOptions {
|
|
10
|
+
apiKey: string;
|
|
11
|
+
fetch: WalletFetch;
|
|
12
|
+
dangerouslyAllowBrowser: true;
|
|
13
|
+
}
|
|
14
|
+
type Listener = (state: ConnectionState) => void;
|
|
15
|
+
export declare class AiConnect {
|
|
16
|
+
get browser(): VisitorBrowser;
|
|
17
|
+
get installUrl(): string;
|
|
18
|
+
readonly fetch: WalletFetch;
|
|
19
|
+
readonly sdkOptions: SdkOptions;
|
|
20
|
+
private readonly listeners;
|
|
21
|
+
private current;
|
|
22
|
+
private wallet;
|
|
23
|
+
private readonly web;
|
|
24
|
+
private walletMissing;
|
|
25
|
+
constructor(options?: AiConnectOptions);
|
|
26
|
+
get webAccounts(): WebAccountId[];
|
|
27
|
+
signIn(account: WebAccountId): Promise<void>;
|
|
28
|
+
cancelSignIn(): void;
|
|
29
|
+
planAccess(): PlanAccess | null;
|
|
30
|
+
signOut(): Promise<void>;
|
|
31
|
+
get state(): ConnectionState;
|
|
32
|
+
subscribe(listener: Listener): () => void;
|
|
33
|
+
connect(): Promise<void>;
|
|
34
|
+
disconnect(): Promise<void>;
|
|
35
|
+
private connectedSession;
|
|
36
|
+
private settled;
|
|
37
|
+
private findWallet;
|
|
38
|
+
private reconnect;
|
|
39
|
+
private walletGone;
|
|
40
|
+
private webChanged;
|
|
41
|
+
private apply;
|
|
42
|
+
private setState;
|
|
43
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// A site's connection to the visitor's AI, through the AI Wallet extension that holds the visitor's
|
|
2
|
+
// accounts. The site asks the wallet to connect, and the wallet asks the visitor the first time;
|
|
3
|
+
// the site then chats through the wallet, which answers with the account the visitor picked for
|
|
4
|
+
// this site. The site never sees a credential. A site the visitor approved connects on its own on
|
|
5
|
+
// later visits, and its state follows the account the visitor picks for it in the wallet.
|
|
6
|
+
// In a browser without the wallet, the visitor can sign in on the page to OpenRouter, or to TensorPass's
|
|
7
|
+
// plan when the site gave its site key (see webAccounts/webAccountSource.ts). The credential of such an
|
|
8
|
+
// account lives in the site's own storage, where the site's scripts can read it.
|
|
9
|
+
// `fetch` lets the AI SDK a site already uses answer through the same connection.
|
|
10
|
+
import { findWallet, WalletRequestError } from "./walletProvider.js";
|
|
11
|
+
import { visitorBrowser, walletInstallUrl } from "./visitorBrowser.js";
|
|
12
|
+
import { WebAccountSource } from "./webAccounts/webAccountSource.js";
|
|
13
|
+
import { createWalletFetch } from "./wireProtocols/walletFetch.js";
|
|
14
|
+
const SDK_API_KEY = 'aiwallet';
|
|
15
|
+
// The states a request waits through before it knows whether the site is connected.
|
|
16
|
+
const SETTLING = new Set(['checking', 'connecting', 'signingIn']);
|
|
17
|
+
const NOT_CONNECTED = {
|
|
18
|
+
noWallet: 'AI Wallet is not installed in this browser, and no account is signed in on this site',
|
|
19
|
+
disconnected: 'AI Wallet is not connected on this site',
|
|
20
|
+
};
|
|
21
|
+
function errorMessage(error) {
|
|
22
|
+
return error instanceof Error ? error.message : String(error);
|
|
23
|
+
}
|
|
24
|
+
const REFUSALS = new Set(['declined', 'closed', 'interrupted']);
|
|
25
|
+
// The error state of a connection that did not go through, with the reason the wallet gave. The
|
|
26
|
+
// error comes from the wallet's own copy of `WalletRequestError`, so its reason is read as a field.
|
|
27
|
+
function connectError(error) {
|
|
28
|
+
const reason = error?.reason;
|
|
29
|
+
return {
|
|
30
|
+
status: 'error',
|
|
31
|
+
message: errorMessage(error),
|
|
32
|
+
...(REFUSALS.has(reason) ? { reason: reason } : {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
// Hands each event the wallet streams to the request's hook for it.
|
|
36
|
+
function chatListener(request) {
|
|
37
|
+
return (event) => {
|
|
38
|
+
if (event.kind === 'start') {
|
|
39
|
+
request.onStart?.({ providerName: event.providerName, model: event.model });
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
request.onText?.(event.delta);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function walletSession(wallet, link) {
|
|
47
|
+
return {
|
|
48
|
+
providerId: 'aiwallet',
|
|
49
|
+
model: link.model ?? '',
|
|
50
|
+
chat: async (request) => {
|
|
51
|
+
const params = { messages: request.messages, tools: request.tools, options: request.options };
|
|
52
|
+
return (await wallet.request('chat', params, chatListener(request), request.signal));
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export class AiConnect {
|
|
57
|
+
// The visitor's browser, which names the install button.
|
|
58
|
+
get browser() {
|
|
59
|
+
return visitorBrowser();
|
|
60
|
+
}
|
|
61
|
+
// Where a visitor without the wallet adds it to this browser, for the connect window's link.
|
|
62
|
+
get installUrl() {
|
|
63
|
+
return walletInstallUrl(this.browser);
|
|
64
|
+
}
|
|
65
|
+
// A `fetch` for the AI SDKs: it answers their requests through the wallet, in their own protocol.
|
|
66
|
+
fetch = createWalletFetch(() => this.connectedSession());
|
|
67
|
+
sdkOptions = { apiKey: SDK_API_KEY, fetch: this.fetch, dangerouslyAllowBrowser: true };
|
|
68
|
+
listeners = new Set();
|
|
69
|
+
current = { status: 'checking' };
|
|
70
|
+
wallet = null;
|
|
71
|
+
web;
|
|
72
|
+
// Set once the page knows the wallet is missing: the web accounts then make the state.
|
|
73
|
+
walletMissing = false;
|
|
74
|
+
constructor(options = {}) {
|
|
75
|
+
this.web = new WebAccountSource({ options, onChange: () => this.webChanged() });
|
|
76
|
+
// A client built during a server render stays in the checking state, and so does a sign in's popup,
|
|
77
|
+
// which hands its answer to the page that opened it and closes.
|
|
78
|
+
if (typeof window !== 'undefined' && this.web.takeCallback() !== 'window') {
|
|
79
|
+
this.reconnect();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
// The accounts a visitor without the wallet can sign in to on this site: TensorPass with a site key,
|
|
83
|
+
// then OpenRouter.
|
|
84
|
+
get webAccounts() {
|
|
85
|
+
return this.web.ids;
|
|
86
|
+
}
|
|
87
|
+
// Signs the visitor in to a web account in a popup, or in the page where the browser blocks popups. Call
|
|
88
|
+
// it from the visitor's click. The state goes through `signingIn` to `connected`, or back to `noWallet`
|
|
89
|
+
// with the reason the sign in failed.
|
|
90
|
+
signIn(account) {
|
|
91
|
+
return this.web.signIn(account);
|
|
92
|
+
}
|
|
93
|
+
cancelSignIn() {
|
|
94
|
+
this.web.cancel();
|
|
95
|
+
}
|
|
96
|
+
// The TensorPass plan of the web account that answers, for the chat's offer to subscribe when the account
|
|
97
|
+
// has no plan yet; null for any other account.
|
|
98
|
+
planAccess() {
|
|
99
|
+
return this.web.planAccess();
|
|
100
|
+
}
|
|
101
|
+
// Removes the web account's credential from the site's storage, and ends a TensorPass sign in.
|
|
102
|
+
signOut() {
|
|
103
|
+
return this.web.signOut();
|
|
104
|
+
}
|
|
105
|
+
get state() {
|
|
106
|
+
return this.current;
|
|
107
|
+
}
|
|
108
|
+
subscribe(listener) {
|
|
109
|
+
this.listeners.add(listener);
|
|
110
|
+
return () => this.listeners.delete(listener);
|
|
111
|
+
}
|
|
112
|
+
// Asks the wallet to let this site use the visitor's AI. The wallet asks the visitor the first time.
|
|
113
|
+
async connect() {
|
|
114
|
+
const wallet = await this.findWallet();
|
|
115
|
+
if (!wallet) {
|
|
116
|
+
this.walletGone();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
this.setState({ status: 'connecting' });
|
|
120
|
+
try {
|
|
121
|
+
this.apply(wallet, (await wallet.request('connect')));
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
this.setState(connectError(error));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// Disconnects the wallet from this site, or signs the visitor out of the web account that answers.
|
|
128
|
+
async disconnect() {
|
|
129
|
+
if (this.current.status === 'connected' && this.current.account) {
|
|
130
|
+
await this.signOut();
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const wallet = await this.findWallet();
|
|
134
|
+
await wallet?.request('disconnect');
|
|
135
|
+
if (wallet) {
|
|
136
|
+
this.setState({ status: 'disconnected' });
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
this.walletGone();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// The session of the connected site, once the status check or the visitor's approval is over.
|
|
143
|
+
async connectedSession() {
|
|
144
|
+
if (typeof window === 'undefined') {
|
|
145
|
+
throw new WalletRequestError('AI Wallet answers in the browser only', 401);
|
|
146
|
+
}
|
|
147
|
+
const state = await this.settled();
|
|
148
|
+
if (state.status === 'connected') {
|
|
149
|
+
return state.session;
|
|
150
|
+
}
|
|
151
|
+
throw new WalletRequestError(state.status === 'error' ? state.message : NOT_CONNECTED[state.status], 401);
|
|
152
|
+
}
|
|
153
|
+
settled() {
|
|
154
|
+
if (!SETTLING.has(this.current.status)) {
|
|
155
|
+
return Promise.resolve(this.current);
|
|
156
|
+
}
|
|
157
|
+
return new Promise((resolve) => {
|
|
158
|
+
const unsubscribe = this.subscribe((state) => {
|
|
159
|
+
if (!SETTLING.has(state.status)) {
|
|
160
|
+
unsubscribe();
|
|
161
|
+
resolve(state);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
findWallet() {
|
|
167
|
+
this.wallet ??= findWallet().then((wallet) => {
|
|
168
|
+
wallet?.onLink((link) => this.apply(wallet, link));
|
|
169
|
+
return wallet;
|
|
170
|
+
});
|
|
171
|
+
return this.wallet;
|
|
172
|
+
}
|
|
173
|
+
// A site the visitor already approved connects without asking anything.
|
|
174
|
+
async reconnect() {
|
|
175
|
+
const wallet = await this.findWallet();
|
|
176
|
+
if (!wallet) {
|
|
177
|
+
this.walletGone();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
const link = await wallet.request('status').catch(() => ({ connected: false }));
|
|
181
|
+
this.apply(wallet, link);
|
|
182
|
+
}
|
|
183
|
+
walletGone() {
|
|
184
|
+
this.walletMissing = true;
|
|
185
|
+
this.setState(this.web.state());
|
|
186
|
+
}
|
|
187
|
+
webChanged() {
|
|
188
|
+
if (this.walletMissing) {
|
|
189
|
+
this.setState(this.web.state());
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
apply(wallet, link) {
|
|
193
|
+
if (!link.connected) {
|
|
194
|
+
this.setState({ status: 'disconnected' });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
this.setState({
|
|
198
|
+
status: 'connected',
|
|
199
|
+
providerName: link.providerName,
|
|
200
|
+
model: link.model,
|
|
201
|
+
session: walletSession(wallet, link),
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
setState(state) {
|
|
205
|
+
this.current = state;
|
|
206
|
+
for (const listener of this.listeners) {
|
|
207
|
+
listener(state);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,iGAAiG;AACjG,gGAAgG;AAChG,kGAAkG;AAClG,0FAA0F;AAC1F,yGAAyG;AACzG,wGAAwG;AACxG,iFAAiF;AACjF,kFAAkF;AAIlF,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,M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I, through the AI Wallet extension that holds the visitor's\n// accounts. The site asks the wallet to connect, and the wallet asks the visitor the first time;\n// the site then chats through the wallet, which answers with the account the visitor picked for\n// this site. The site never sees a credential. A site the visitor approved connects on its own on\n// later visits, and its state follows the account the visitor picks for it in the wallet.\n// In a browser without the wallet, the visitor can sign in on the page to OpenRouter, or to TensorPass's\n// plan when the site gave its site key (see webAccounts/webAccountSource.ts). The credential of such an\n// account lives in the site's own storage, where the site's scripts can read it.\n// `fetch` lets the AI SDK a site already uses answer through the same connection.\n\nimport type { ConnectionState } from './connectionState.ts';\nimport type { ChatRequest, ChatResponse, ProviderSession, WalletLink } from './types.ts';\nimport { findWallet, WalletRequestError } from './walletProvider.ts';\nimport type { ChatEvent, WalletChatParams, WalletProvider, WalletRefusal } from './walletProvider.ts';\nimport { visitorBrowser, walletInstallUrl } from './visitorBrowser.ts';\nimport type { VisitorBrowser } from './visitorBrowser.ts';\nimport { WebAccountSource } from './webAccounts/webAccountSource.ts';\nimport type { WebAccountOptions } from './webAccounts/webAccountSource.ts';\nimport type { PlanAccess } from './webAccounts/tensorPassPlan.ts';\nimport type { WebAccountId } from './webAccounts/webAccountStore.ts';\nimport { createWalletFetch } from './wireProtocols/walletFetch.ts';\nimport type { WalletFetch } from './wireProtocols/walletFetch.ts';\n\nexport type { ConnectionState, WebSignInFailure } from './connectionState.ts';\n\n// What a site sets on its client: its TensorPass site key, which offers the TensorPass plan's sign in to a\n// visitor without the wallet, and the models the web accounts answer with.\nexport type AiConnectOptions = WebAccountOptions;\n\n// The options an OpenAI or Anthropic SDK client takes to answer through the wallet. The SDKs\n// require an API key; the wallet never reads it, and the browser guard they keep for real keys\n// does not apply, since none reaches the page.\nexport interface SdkOptions {\n apiKey: string;\n fetch: WalletFetch;\n dangerouslyAllowBrowser: true;\n}\n\ntype Listener = (state: ConnectionState) => void;\n\nconst SDK_API_KEY = 'aiwallet';\n\n// The states a request waits through before it knows whether the site is connected.\nconst SETTLING = new Set<ConnectionState['status']>(['checking', 'connecting', 'signingIn']);\n\nconst NOT_CONNECTED: Record<string, string> = {\n noWallet: 'AI Wallet is not installed in this browser, and no account is signed in on this site',\n disconnected: 'AI Wallet is not connected on this site',\n};\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nconst REFUSALS = new Set<unknown>(['declined', 'closed', 'interrupted'] satisfies WalletRefusal[]);\n\n// The error state of a connection that did not go through, with the reason the wallet gave. The\n// error comes from the wallet's own copy of `WalletRequestError`, so its reason is read as a field.\nfunction connectError(error: unknown): ConnectionState {\n const reason = (error as { reason?: unknown } | null)?.reason;\n return {\n status: 'error',\n message: errorMessage(error),\n ...(REFUSALS.has(reason) ? { reason: reason as WalletRefusal } : {}),\n };\n}\n\n// Hands each event the wallet streams to the request's hook for it.\nfunction chatListener(request: ChatRequest): (event: ChatEvent) => void {\n return (event) => {\n if (event.kind === 'start') {\n request.onStart?.({ providerName: event.providerName, model: event.model });\n } else {\n request.onText?.(event.delta);\n }\n };\n}\n\nfunction walletSession(wallet: WalletProvider, link: Extract<WalletLink, { connected: true }>): ProviderSession {\n return {\n providerId: 'aiwallet',\n model: link.model ?? '',\n chat: async (request) => {\n const params: WalletChatParams = { messages: request.messages, tools: request.tools, options: request.options };\n return (await wallet.request('chat', params, chatListener(request), request.signal)) as ChatResponse;\n },\n };\n}\n\nexport class AiConnect {\n // The visitor's browser, which names the install button.\n get browser(): VisitorBrowser {\n return visitorBrowser();\n }\n\n // Where a visitor without the wallet adds it to this browser, for the connect window's link.\n get installUrl(): string {\n return walletInstallUrl(this.browser);\n }\n\n // A `fetch` for the AI SDKs: it answers their requests through the wallet, in their own protocol.\n readonly fetch: WalletFetch = createWalletFetch(() => this.connectedSession());\n readonly sdkOptions: SdkOptions = { apiKey: SDK_API_KEY, fetch: this.fetch, dangerouslyAllowBrowser: true };\n private readonly listeners = new Set<Listener>();\n private current: ConnectionState = { status: 'checking' };\n private wallet: Promise<WalletProvider | null> | null = null;\n private readonly web: WebAccountSource;\n // Set once the page knows the wallet is missing: the web accounts then make the state.\n private walletMissing = false;\n\n constructor(options: AiConnectOptions = {}) {\n this.web = new WebAccountSource({ options, onChange: () => this.webChanged() });\n // A client built during a server render stays in the checking state, and so does a sign in's popup,\n // which hands its answer to the page that opened it and closes.\n if (typeof window !== 'undefined' && this.web.takeCallback() !== 'window') {\n this.reconnect();\n }\n }\n\n // The accounts a visitor without the wallet can sign in to on this site: TensorPass with a site key,\n // then OpenRouter.\n get webAccounts(): WebAccountId[] {\n return this.web.ids;\n }\n\n // Signs the visitor in to a web account in a popup, or in the page where the browser blocks popups. Call\n // it from the visitor's click. The state goes through `signingIn` to `connected`, or back to `noWallet`\n // with the reason the sign in failed.\n signIn(account: WebAccountId): Promise<void> {\n return this.web.signIn(account);\n }\n\n cancelSignIn(): void {\n this.web.cancel();\n }\n\n // The TensorPass plan of the web account that answers, for the chat's offer to subscribe when the account\n // has no plan yet; null for any other account.\n planAccess(): PlanAccess | null {\n return this.web.planAccess();\n }\n\n // Removes the web account's credential from the site's storage, and ends a TensorPass sign in.\n signOut(): Promise<void> {\n return this.web.signOut();\n }\n\n get state(): ConnectionState {\n return this.current;\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n // Asks the wallet to let this site use the visitor's AI. The wallet asks the visitor the first time.\n async connect(): Promise<void> {\n const wallet = await this.findWallet();\n if (!wallet) {\n this.walletGone();\n return;\n }\n this.setState({ status: 'connecting' });\n try {\n this.apply(wallet, (await wallet.request('connect')) as WalletLink);\n } catch (error) {\n this.setState(connectError(error));\n }\n }\n\n // Disconnects the wallet from this site, or signs the visitor out of the web account that answers.\n async disconnect(): Promise<void> {\n if (this.current.status === 'connected' && this.current.account) {\n await this.signOut();\n return;\n }\n const wallet = await this.findWallet();\n await wallet?.request('disconnect');\n if (wallet) {\n this.setState({ status: 'disconnected' });\n } else {\n this.walletGone();\n }\n }\n\n // The session of the connected site, once the status check or the visitor's approval is over.\n private async connectedSession(): Promise<ProviderSession> {\n if (typeof window === 'undefined') {\n throw new WalletRequestError('AI Wallet answers in the browser only', 401);\n }\n const state = await this.settled();\n if (state.status === 'connected') {\n return state.session;\n }\n throw new WalletRequestError(state.status === 'error' ? state.message : NOT_CONNECTED[state.status], 401);\n }\n\n private settled(): Promise<ConnectionState> {\n if (!SETTLING.has(this.current.status)) {\n return Promise.resolve(this.current);\n }\n return new Promise((resolve) => {\n const unsubscribe = this.subscribe((state) => {\n if (!SETTLING.has(state.status)) {\n unsubscribe();\n resolve(state);\n }\n });\n });\n }\n\n private findWallet(): Promise<WalletProvider | null> {\n this.wallet ??= findWallet().then((wallet) => {\n wallet?.onLink((link) => this.apply(wallet, link));\n return wallet;\n });\n return this.wallet;\n }\n\n // A site the visitor already approved connects without asking anything.\n private async reconnect(): Promise<void> {\n const wallet = await this.findWallet();\n if (!wallet) {\n this.walletGone();\n return;\n }\n const link = await wallet.request('status').catch((): WalletLink => ({ connected: false }));\n this.apply(wallet, link as WalletLink);\n }\n\n private walletGone(): void {\n this.walletMissing = true;\n this.setState(this.web.state());\n }\n\n private webChanged(): void {\n if (this.walletMissing) {\n this.setState(this.web.state());\n }\n }\n\n private apply(wallet: WalletProvider, link: WalletLink): void {\n if (!link.connected) {\n this.setState({ status: 'disconnected' });\n return;\n }\n this.setState({\n status: 'connected',\n providerName: link.providerName,\n model: link.model,\n session: walletSession(wallet, link),\n });\n }\n\n private setState(state: ConnectionState): void {\n this.current = state;\n for (const listener of this.listeners) {\n listener(state);\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ProviderSession } from './types.ts';
|
|
2
|
+
import type { WalletRefusal } from './walletProvider.ts';
|
|
3
|
+
import type { WebAccountId } from './webAccounts/webAccountStore.ts';
|
|
4
|
+
export interface WebSignInFailure {
|
|
5
|
+
account: WebAccountId;
|
|
6
|
+
reason: 'declined' | 'failed' | 'expired';
|
|
7
|
+
message: string;
|
|
8
|
+
}
|
|
9
|
+
export type ConnectionState = {
|
|
10
|
+
status: 'checking';
|
|
11
|
+
} | {
|
|
12
|
+
status: 'noWallet';
|
|
13
|
+
signInFailure?: WebSignInFailure;
|
|
14
|
+
} | {
|
|
15
|
+
status: 'disconnected';
|
|
16
|
+
} | {
|
|
17
|
+
status: 'connecting';
|
|
18
|
+
} | {
|
|
19
|
+
status: 'signingIn';
|
|
20
|
+
account: WebAccountId;
|
|
21
|
+
} | {
|
|
22
|
+
status: 'connected';
|
|
23
|
+
providerName: string;
|
|
24
|
+
model?: string;
|
|
25
|
+
session: ProviderSession;
|
|
26
|
+
account?: WebAccountId;
|
|
27
|
+
} | {
|
|
28
|
+
status: 'error';
|
|
29
|
+
message: string;
|
|
30
|
+
reason?: WalletRefusal;
|
|
31
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connectionState.js","sourceRoot":"","sources":["../src/connectionState.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,sFAAsF","sourcesContent":["// What a site sees of its connection to the visitor's AI: the wallet being looked for, missing, asked or\n// connected, and, without the wallet, an account the visitor signs in to on the page.\n\nimport type { ProviderSession } from './types.ts';\nimport type { WalletRefusal } from './walletProvider.ts';\nimport type { WebAccountId } from './webAccounts/webAccountStore.ts';\n\n// Why a web sign in did not go through: the visitor cancelled it on the provider's page, it failed, or it\n// was left open longer than a sign in waits.\nexport interface WebSignInFailure {\n account: WebAccountId;\n reason: 'declined' | 'failed' | 'expired';\n message: string;\n}\n\nexport type ConnectionState =\n | { status: 'checking' }\n | { status: 'noWallet'; signInFailure?: WebSignInFailure }\n | { status: 'disconnected' }\n | { status: 'connecting' }\n | { status: 'signingIn'; account: WebAccountId }\n // `account` names the web account that answers; it is absent when the wallet answers.\n | { status: 'connected'; providerName: string; model?: string; session: ProviderSession; account?: WebAccountId }\n | { status: 'error'; message: string; reason?: WalletRefusal };\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AnswerVerdict, GuardPolicy } from './policy.ts';
|
|
2
|
+
export interface AnswerContext {
|
|
3
|
+
salt?: string;
|
|
4
|
+
policy?: GuardPolicy;
|
|
5
|
+
visitorText?: string;
|
|
6
|
+
toolResults?: readonly string[];
|
|
7
|
+
origin?: string;
|
|
8
|
+
partial?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function emailAllowed(email: string, context: AnswerContext): boolean;
|
|
11
|
+
export declare function leadsToSitePage(href: string, origin?: string): boolean;
|
|
12
|
+
export declare function linkAllowed(href: string, context: AnswerContext): boolean;
|
|
13
|
+
export declare function validateAnswer(text: string, context?: AnswerContext): AnswerVerdict;
|
|
14
|
+
export declare function checkToolResult(text: string, policy: GuardPolicy): AnswerVerdict;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// The guard on the model's answer, run as it streams and once it ends, before the visitor sees it. An
|
|
2
|
+
// answer stops on an envelope tag or the salt, which mean the model is repeating its instructions; on
|
|
3
|
+
// an image, which loads by itself and can carry the conversation to another server; on a link or an
|
|
4
|
+
// email address that comes from neither the site, its tools, nor the visitor; and on the site's own
|
|
5
|
+
// internal names and withheld content. A web address or an email address counts as the tools' own when
|
|
6
|
+
// a result gives it as a whole field, such as a restaurant's `website` or a shop's `email`: the result
|
|
7
|
+
// is read as JSON, and a string of it that is one address and nothing else is such a field. An address
|
|
8
|
+
// written inside free text, such as a review a third party planted, is none, whatever quotes surround
|
|
9
|
+
// it, and a result that is not JSON gives no address at all. While the answer streams, a link or an
|
|
10
|
+
// address still being written is left for the next check, so a host is judged once it is complete.
|
|
11
|
+
// Every address is read with the URL parser, which resolves it as the browser does on a click.
|
|
12
|
+
import { compilePatterns } from "./policy.js";
|
|
13
|
+
const ENVELOPE_TAG = /<\/?\s*(?:instructions?|tool-result|steering)-/i;
|
|
14
|
+
const IMAGE = /!\[[^\]\n]*\]\(|<img\b/i;
|
|
15
|
+
const EMAIL = /[^\s@<>()[\]"'`:]+@[^\s@<>()[\]"'`]+\.[a-z]{2,}/gi;
|
|
16
|
+
const LINK_TARGET = /\]\(\s*<?([^)\s>]+)|\b(https?:\/\/[^\s)\]>"'`]+)|<a\b[^>]*\bhref\s*=\s*["']?([^"'\s>]+)|\b(www\.[^\s)\]>"'`]+)/gi;
|
|
17
|
+
const TRAILING_PUNCTUATION = /[.,;:!?]+$/;
|
|
18
|
+
// Stands for the page's origin where the guard runs without a page, such as a site's server.
|
|
19
|
+
const NO_PAGE_ORIGIN = 'https://page.invalid';
|
|
20
|
+
const compiled = new WeakMap();
|
|
21
|
+
function patternsOf(policy) {
|
|
22
|
+
let patterns = compiled.get(policy);
|
|
23
|
+
if (!patterns) {
|
|
24
|
+
patterns = { deny: compilePatterns(policy.denyPatterns), withhold: compilePatterns(policy.withholdPatterns) };
|
|
25
|
+
compiled.set(policy, patterns);
|
|
26
|
+
}
|
|
27
|
+
return patterns;
|
|
28
|
+
}
|
|
29
|
+
// The values found, without the ones running to the end of a streaming answer, which are still being
|
|
30
|
+
// written.
|
|
31
|
+
function finished(found, text, partial = false) {
|
|
32
|
+
return found.filter((item) => !partial || item.end < text.length).map((item) => item.value);
|
|
33
|
+
}
|
|
34
|
+
function linkTargets(text) {
|
|
35
|
+
return [...text.matchAll(LINK_TARGET)].map((match) => {
|
|
36
|
+
const [, markdown, bare, anchor, www] = match;
|
|
37
|
+
const value = markdown ?? anchor ?? `${www ? 'https://' : ''}${(bare ?? www).replace(TRAILING_PUNCTUATION, '')}`;
|
|
38
|
+
return { value, end: match.index + match[0].length };
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function emails(text) {
|
|
42
|
+
return [...text.matchAll(EMAIL)].map((match) => ({
|
|
43
|
+
value: match[0].toLowerCase(),
|
|
44
|
+
end: match.index + match[0].length,
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
const withoutFinalSlash = (href) => href.replace(/\/+$/, '');
|
|
48
|
+
const WHOLE_ADDRESS = /^https?:\/\/\S+$/;
|
|
49
|
+
const WHOLE_EMAIL = /^[^\s@<>()[\]"'`:]+@[^\s@<>()[\]"'`]+\.[a-z]{2,}$/i;
|
|
50
|
+
// The strings of a parsed result, at any depth.
|
|
51
|
+
function stringsIn(value) {
|
|
52
|
+
if (typeof value === 'string') {
|
|
53
|
+
return [value];
|
|
54
|
+
}
|
|
55
|
+
return typeof value === 'object' && value !== null ? Object.values(value).flatMap(stringsIn) : [];
|
|
56
|
+
}
|
|
57
|
+
// The strings one tool result gives as fields. Only an object or a list has fields: a result that is
|
|
58
|
+
// free text, a tool error or a lone string gives none.
|
|
59
|
+
function fieldsOf(result) {
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(result);
|
|
62
|
+
return typeof parsed === 'object' ? stringsIn(parsed) : [];
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// What was read so far from each list of results.
|
|
69
|
+
const fieldsRead = new WeakMap();
|
|
70
|
+
// The web and email addresses the site's tools returned as whole fields of their results.
|
|
71
|
+
function toolFields(results = []) {
|
|
72
|
+
const read = fieldsRead.get(results) ?? { results: 0, addresses: new Set(), emails: new Set() };
|
|
73
|
+
fieldsRead.set(results, read);
|
|
74
|
+
for (; read.results < results.length; read.results += 1) {
|
|
75
|
+
for (const field of fieldsOf(results[read.results])) {
|
|
76
|
+
if (WHOLE_ADDRESS.test(field)) {
|
|
77
|
+
read.addresses.add(withoutFinalSlash(field));
|
|
78
|
+
}
|
|
79
|
+
else if (WHOLE_EMAIL.test(field)) {
|
|
80
|
+
read.emails.add(field.toLowerCase());
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return read;
|
|
85
|
+
}
|
|
86
|
+
// Whether an answer may give `email`: the visitor typed it, the policy lists it, or a tool returned it
|
|
87
|
+
// as a whole field.
|
|
88
|
+
export function emailAllowed(email, context) {
|
|
89
|
+
const address = email.toLowerCase();
|
|
90
|
+
const typed = (context.visitorText ?? '').toLowerCase().replace(/\s+/g, '');
|
|
91
|
+
const published = (context.policy?.allowedEmails ?? []).map((item) => item.toLowerCase());
|
|
92
|
+
return published.includes(address) || typed.includes(address) || toolFields(context.toolResults).emails.has(address);
|
|
93
|
+
}
|
|
94
|
+
// Whether `hostname` is the page's own host or one the policy allows. A page whose origin is opaque,
|
|
95
|
+
// such as the `null` of a sandboxed frame, has no host of its own.
|
|
96
|
+
function hostAllowed(hostname, context) {
|
|
97
|
+
const own = context.origin ? parsedUrl(context.origin)?.hostname : undefined;
|
|
98
|
+
return hostname === own || (context.policy?.allowedLinkHosts ?? [])
|
|
99
|
+
.some((host) => hostname === host || hostname.endsWith(`.${host}`));
|
|
100
|
+
}
|
|
101
|
+
function parsedUrl(address, base) {
|
|
102
|
+
try {
|
|
103
|
+
return new URL(address, base);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// The fields of a mailto: link that add addresses to send to (RFC 6068).
|
|
110
|
+
const RECIPIENT_FIELDS = new Set(['to', 'cc', 'bcc']);
|
|
111
|
+
// The addresses a mailto: link sends to, decoded as a mail client reads them: the one before the `?`
|
|
112
|
+
// and those of its to, cc and bcc fields. Written with escapes, as in `cc=a%40b%2Eexample`, they pass
|
|
113
|
+
// the email scan of the answer unseen. An escape that does not decode, such as `%E0%A4%A`, gives no
|
|
114
|
+
// address, and the link is refused.
|
|
115
|
+
function mailtoRecipients(href) {
|
|
116
|
+
const target = href.slice('mailto:'.length);
|
|
117
|
+
const question = target.indexOf('?');
|
|
118
|
+
const fields = question === -1 ? [] : target.slice(question + 1).split('&').map((field) => field.split('='));
|
|
119
|
+
try {
|
|
120
|
+
const added = fields.filter(([name]) => RECIPIENT_FIELDS.has(decodeURIComponent(name).toLowerCase()))
|
|
121
|
+
.map(([, ...value]) => decodeURIComponent(value.join('=')));
|
|
122
|
+
const path = decodeURIComponent(question === -1 ? target : target.slice(0, question));
|
|
123
|
+
return [path, ...added].filter((address) => address !== '');
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// Whether `href` is an address written without its site that leads to a page of `origin`, the page's
|
|
130
|
+
// own when none is given. `/returns`, `#top` and `../a` do. `//host`, `/\host` and an address with its
|
|
131
|
+
// own scheme lead elsewhere, whatever tabs, line breaks or encoding they are written with.
|
|
132
|
+
export function leadsToSitePage(href, origin = NO_PAGE_ORIGIN) {
|
|
133
|
+
const site = parsedUrl(origin);
|
|
134
|
+
const target = parsedUrl(href, origin);
|
|
135
|
+
return site !== null && target !== null && parsedUrl(href) === null && target.origin === site.origin;
|
|
136
|
+
}
|
|
137
|
+
// Whether an answer may link to `href`: a path of the site, a page of its origin or of an allowed host,
|
|
138
|
+
// an address a tool returned as a field, as it is, or a mailto: link whose every address the
|
|
139
|
+
// conversation allows.
|
|
140
|
+
export function linkAllowed(href, context) {
|
|
141
|
+
if (leadsToSitePage(href, context.origin)) {
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
if (/^mailto:/i.test(href)) {
|
|
145
|
+
const recipients = mailtoRecipients(href);
|
|
146
|
+
return recipients !== null && recipients.every((address) => emailAllowed(address, context));
|
|
147
|
+
}
|
|
148
|
+
const url = parsedUrl(href);
|
|
149
|
+
if (url?.protocol !== 'https:' && url?.protocol !== 'http:') {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
return hostAllowed(url.hostname, context) || toolFields(context.toolResults).addresses.has(withoutFinalSlash(href));
|
|
153
|
+
}
|
|
154
|
+
function patternStop(text, policy) {
|
|
155
|
+
const { deny, withhold } = patternsOf(policy);
|
|
156
|
+
const denied = deny.find((re) => re.test(text));
|
|
157
|
+
if (denied) {
|
|
158
|
+
return { ok: false, reason: 'denied', detail: denied.source };
|
|
159
|
+
}
|
|
160
|
+
return withhold.some((re) => re.test(text)) ? { ok: false, reason: 'withheld' } : { ok: true };
|
|
161
|
+
}
|
|
162
|
+
export function validateAnswer(text, context = {}) {
|
|
163
|
+
const { salt, partial } = context;
|
|
164
|
+
if (ENVELOPE_TAG.test(text)) {
|
|
165
|
+
return { ok: false, reason: 'envelope-tag' };
|
|
166
|
+
}
|
|
167
|
+
if (salt && text.includes(salt)) {
|
|
168
|
+
return { ok: false, reason: 'salt' };
|
|
169
|
+
}
|
|
170
|
+
if (IMAGE.test(text)) {
|
|
171
|
+
return { ok: false, reason: 'image' };
|
|
172
|
+
}
|
|
173
|
+
const link = finished(linkTargets(text), text, partial).find((href) => !linkAllowed(href, context));
|
|
174
|
+
if (link) {
|
|
175
|
+
return { ok: false, reason: 'link', detail: link };
|
|
176
|
+
}
|
|
177
|
+
const email = finished(emails(text), text, partial).find((address) => !emailAllowed(address, context));
|
|
178
|
+
if (email) {
|
|
179
|
+
return { ok: false, reason: 'email', detail: email };
|
|
180
|
+
}
|
|
181
|
+
return patternStop(text, context.policy ?? {});
|
|
182
|
+
}
|
|
183
|
+
// The guard a site's MCP server runs on each tool result before it leaves the server: the internal names
|
|
184
|
+
// and the withheld content of its policy. Anyone can call the server without the page, so these never
|
|
185
|
+
// leave it.
|
|
186
|
+
export function checkToolResult(text, policy) {
|
|
187
|
+
return patternStop(text, policy);
|
|
188
|
+
}
|
|
189
|
+
//# sourceMappingURL=answerGuard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"answerGuard.js","sourceRoot":"","sources":["../../src/guards/answerGuard.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,sGAAsG;AACtG,oGAAoG;AACpG,oGAAoG;AACpG,uGAAuG;AACvG,uGAAuG;AACvG,uGAAuG;AACvG,sGAAsG;AACtG,oGAAoG;AACpG,mGAAmG;AACnG,+FAA+F;AAE/F,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAsB9C,MAAM,YAAY,GAAG,iDAAiD,CAAC;AACvE,MAAM,KAAK,GAAG,yBAAyB,CAAC;AACxC,MAAM,KAAK,GAAG,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AI,GAAG,QAAQ,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACpG,IAAI,IAAI,EAAE,CAAC;QACT,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACrD,CAAC;IACD,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;IACvG,IAAI,KAAK,EAAE,CAAC;QACV,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IACvD,CAAC;IACD,OAAO,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;AACjD,CAAC;AAED,yGAAyG;AACzG,sGAAsG;AACtG,YAAY;AACZ,MAAM,UAAU,eAAe,CAAC,IAAY,EAAE,MAAmB;IAC/D,OAAO,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AACnC,CAAC","sourcesContent":["// The guard on the model's answer, run as it streams and once it ends, before the visitor sees it. An\n// answer stops on an envelope tag or the salt, which mean the model is repeating its instructions; on\n// an image, which loads by itself and can carry the conversation to another server; on a link or an\n// email address that comes from neither the site, its tools, nor the visitor; and on the site's own\n// internal names and withheld content. A web address or an email address counts as the tools' own when\n// a result gives it as a whole field, such as a restaurant's `website` or a shop's `email`: the result\n// is read as JSON, and a string of it that is one address and nothing else is such a field. An address\n// written inside free text, such as a review a third party planted, is none, whatever quotes surround\n// it, and a result that is not JSON gives no address at all. While the answer streams, a link or an\n// address still being written is left for the next check, so a host is judged once it is complete.\n// Every address is read with the URL parser, which resolves it as the browser does on a click.\n\nimport { compilePatterns } from './policy.ts';\nimport type { AnswerVerdict, GuardPolicy } from './policy.ts';\n\nexport interface AnswerContext {\n salt?: string;\n policy?: GuardPolicy;\n // Everything the visitor typed in the conversation.\n visitorText?: string;\n // Each result the site's tools returned in the conversation, as the tool gave it. A conversation\n // adds its results to the same list, which the guard reads once each.\n toolResults?: readonly string[];\n // The page's own origin, whose pages an answer may always link to.\n origin?: string;\n // The answer is still streaming.\n partial?: boolean;\n}\n\ninterface Found {\n value: string;\n end: number;\n}\n\nconst ENVELOPE_TAG = /<\\/?\\s*(?:instructions?|tool-result|steering)-/i;\nconst IMAGE = /!\\[[^\\]\\n]*\\]\\(|<img\\b/i;\nconst EMAIL = /[^\\s@<>()[\\]\"'`:]+@[^\\s@<>()[\\]\"'`]+\\.[a-z]{2,}/gi;\nconst LINK_TARGET = /\\]\\(\\s*<?([^)\\s>]+)|\\b(https?:\\/\\/[^\\s)\\]>\"'`]+)|<a\\b[^>]*\\bhref\\s*=\\s*[\"']?([^\"'\\s>]+)|\\b(www\\.[^\\s)\\]>\"'`]+)/gi;\nconst TRAILING_PUNCTUATION = /[.,;:!?]+$/;\n// Stands for the page's origin where the guard runs without a page, such as a site's server.\nconst NO_PAGE_ORIGIN = 'https://page.invalid';\n\nconst compiled = new WeakMap<GuardPolicy, { deny: RegExp[]; withhold: RegExp[] }>();\n\nfunction patternsOf(policy: GuardPolicy) {\n let patterns = compiled.get(policy);\n if (!patterns) {\n patterns = { deny: compilePatterns(policy.denyPatterns), withhold: compilePatterns(policy.withholdPatterns) };\n compiled.set(policy, patterns);\n }\n return patterns;\n}\n\n// The values found, without the ones running to the end of a streaming answer, which are still being\n// written.\nfunction finished(found: Found[], text: string, partial = false): string[] {\n return found.filter((item) => !partial || item.end < text.length).map((item) => item.value);\n}\n\nfunction linkTargets(text: string): Found[] {\n return [...text.matchAll(LINK_TARGET)].map((match) => {\n const [, markdown, bare, anchor, www] = match;\n const value = markdown ?? anchor ?? `${www ? 'https://' : ''}${(bare ?? www).replace(TRAILING_PUNCTUATION, '')}`;\n return { value, end: match.index + match[0].length };\n });\n}\n\nfunction emails(text: string): Found[] {\n return [...text.matchAll(EMAIL)].map((match) => ({\n value: match[0].toLowerCase(),\n end: match.index + match[0].length,\n }));\n}\n\nconst withoutFinalSlash = (href: string) => href.replace(/\\/+$/, '');\n\nconst WHOLE_ADDRESS = /^https?:\\/\\/\\S+$/;\nconst WHOLE_EMAIL = /^[^\\s@<>()[\\]\"'`:]+@[^\\s@<>()[\\]\"'`]+\\.[a-z]{2,}$/i;\n\n// The strings of a parsed result, at any depth.\nfunction stringsIn(value: unknown): string[] {\n if (typeof value === 'string') {\n return [value];\n }\n return typeof value === 'object' && value !== null ? Object.values(value).flatMap(stringsIn) : [];\n}\n\n// The strings one tool result gives as fields. Only an object or a list has fields: a result that is\n// free text, a tool error or a lone string gives none.\nfunction fieldsOf(result: string): string[] {\n try {\n const parsed: unknown = JSON.parse(result);\n return typeof parsed === 'object' ? stringsIn(parsed) : [];\n } catch {\n return [];\n }\n}\n\ninterface ToolFields {\n // How many results of the list were read.\n results: number;\n // The fields that are one web address and nothing else.\n addresses: Set<string>;\n // The fields that are one email address and nothing else, in lower case.\n emails: Set<string>;\n}\n\n// What was read so far from each list of results.\nconst fieldsRead = new WeakMap<readonly string[], ToolFields>();\n\n// The web and email addresses the site's tools returned as whole fields of their results.\nfunction toolFields(results: readonly string[] = []): ToolFields {\n const read = fieldsRead.get(results) ?? { results: 0, addresses: new Set<string>(), emails: new Set<string>() };\n fieldsRead.set(results, read);\n for (; read.results < results.length; read.results += 1) {\n for (const field of fieldsOf(results[read.results])) {\n if (WHOLE_ADDRESS.test(field)) {\n read.addresses.add(withoutFinalSlash(field));\n } else if (WHOLE_EMAIL.test(field)) {\n read.emails.add(field.toLowerCase());\n }\n }\n }\n return read;\n}\n\n// Whether an answer may give `email`: the visitor typed it, the policy lists it, or a tool returned it\n// as a whole field.\nexport function emailAllowed(email: string, context: AnswerContext): boolean {\n const address = email.toLowerCase();\n const typed = (context.visitorText ?? '').toLowerCase().replace(/\\s+/g, '');\n const published = (context.policy?.allowedEmails ?? []).map((item) => item.toLowerCase());\n return published.includes(address) || typed.includes(address) || toolFields(context.toolResults).emails.has(address);\n}\n\n// Whether `hostname` is the page's own host or one the policy allows. A page whose origin is opaque,\n// such as the `null` of a sandboxed frame, has no host of its own.\nfunction hostAllowed(hostname: string, context: AnswerContext): boolean {\n const own = context.origin ? parsedUrl(context.origin)?.hostname : undefined;\n return hostname === own || (context.policy?.allowedLinkHosts ?? [])\n .some((host) => hostname === host || hostname.endsWith(`.${host}`));\n}\n\nfunction parsedUrl(address: string, base?: string): URL | null {\n try {\n return new URL(address, base);\n } catch {\n return null;\n }\n}\n\n// The fields of a mailto: link that add addresses to send to (RFC 6068).\nconst RECIPIENT_FIELDS = new Set(['to', 'cc', 'bcc']);\n\n// The addresses a mailto: link sends to, decoded as a mail client reads them: the one before the `?`\n// and those of its to, cc and bcc fields. Written with escapes, as in `cc=a%40b%2Eexample`, they pass\n// the email scan of the answer unseen. An escape that does not decode, such as `%E0%A4%A`, gives no\n// address, and the link is refused.\nfunction mailtoRecipients(href: string): string[] | null {\n const target = href.slice('mailto:'.length);\n const question = target.indexOf('?');\n const fields = question === -1 ? [] : target.slice(question + 1).split('&').map((field) => field.split('='));\n try {\n const added = fields.filter(([name]) => RECIPIENT_FIELDS.has(decodeURIComponent(name).toLowerCase()))\n .map(([, ...value]) => decodeURIComponent(value.join('=')));\n const path = decodeURIComponent(question === -1 ? target : target.slice(0, question));\n return [path, ...added].filter((address) => address !== '');\n } catch {\n return null;\n }\n}\n\n// Whether `href` is an address written without its site that leads to a page of `origin`, the page's\n// own when none is given. `/returns`, `#top` and `../a` do. `//host`, `/\\host` and an address with its\n// own scheme lead elsewhere, whatever tabs, line breaks or encoding they are written with.\nexport function leadsToSitePage(href: string, origin = NO_PAGE_ORIGIN): boolean {\n const site = parsedUrl(origin);\n const target = parsedUrl(href, origin);\n return site !== null && target !== null && parsedUrl(href) === null && target.origin === site.origin;\n}\n\n// Whether an answer may link to `href`: a path of the site, a page of its origin or of an allowed host,\n// an address a tool returned as a field, as it is, or a mailto: link whose every address the\n// conversation allows.\nexport function linkAllowed(href: string, context: AnswerContext): boolean {\n if (leadsToSitePage(href, context.origin)) {\n return true;\n }\n if (/^mailto:/i.test(href)) {\n const recipients = mailtoRecipients(href);\n return recipients !== null && recipients.every((address) => emailAllowed(address, context));\n }\n const url = parsedUrl(href);\n if (url?.protocol !== 'https:' && url?.protocol !== 'http:') {\n return false;\n }\n return hostAllowed(url.hostname, context) || toolFields(context.toolResults).addresses.has(withoutFinalSlash(href));\n}\n\nfunction patternStop(text: string, policy: GuardPolicy): AnswerVerdict {\n const { deny, withhold } = patternsOf(policy);\n const denied = deny.find((re) => re.test(text));\n if (denied) {\n return { ok: false, reason: 'denied', detail: denied.source };\n }\n return withhold.some((re) => re.test(text)) ? { ok: false, reason: 'withheld' } : { ok: true };\n}\n\nexport function validateAnswer(text: string, context: AnswerContext = {}): AnswerVerdict {\n const { salt, partial } = context;\n if (ENVELOPE_TAG.test(text)) {\n return { ok: false, reason: 'envelope-tag' };\n }\n if (salt && text.includes(salt)) {\n return { ok: false, reason: 'salt' };\n }\n if (IMAGE.test(text)) {\n return { ok: false, reason: 'image' };\n }\n const link = finished(linkTargets(text), text, partial).find((href) => !linkAllowed(href, context));\n if (link) {\n return { ok: false, reason: 'link', detail: link };\n }\n const email = finished(emails(text), text, partial).find((address) => !emailAllowed(address, context));\n if (email) {\n return { ok: false, reason: 'email', detail: email };\n }\n return patternStop(text, context.policy ?? {});\n}\n\n// The guard a site's MCP server runs on each tool result before it leaves the server: the internal names\n// and the withheld content of its policy. Anyone can call the server without the page, so these never\n// leave it.\nexport function checkToolResult(text: string, policy: GuardPolicy): AnswerVerdict {\n return patternStop(text, policy);\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ChatMessage } from '../types.ts';
|
|
2
|
+
import type { AnswerStop, AnswerVerdict, GuardPolicy, QuestionStop, QuestionVerdict } from './policy.ts';
|
|
3
|
+
export interface ChatGuard {
|
|
4
|
+
readonly salt: string;
|
|
5
|
+
readonly policy: GuardPolicy;
|
|
6
|
+
forModel(messages: ChatMessage[]): ChatMessage[];
|
|
7
|
+
remember(messages: ChatMessage[]): void;
|
|
8
|
+
checkQuestion(question: string): QuestionVerdict;
|
|
9
|
+
checkAnswer(answer: string, partial?: boolean): AnswerVerdict;
|
|
10
|
+
linkAllowed(href: string): boolean;
|
|
11
|
+
toolVisible(name: string): boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare class GuardStop extends Error {
|
|
14
|
+
readonly stage: 'question' | 'answer';
|
|
15
|
+
readonly reason: QuestionStop | AnswerStop;
|
|
16
|
+
constructor(stage: 'question' | 'answer', reason: QuestionStop | AnswerStop);
|
|
17
|
+
}
|
|
18
|
+
export declare function createChatGuard(policy?: GuardPolicy): ChatGuard;
|