@fungi.computer/parakeet 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import * as Result from "effect/Result";
|
|
2
|
+
declare const BrowserStorageUnavailable_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
3
|
+
readonly _tag: "BrowserStorageUnavailable";
|
|
4
|
+
} & Readonly<A>;
|
|
5
|
+
declare class BrowserStorageUnavailable extends BrowserStorageUnavailable_base<{
|
|
6
|
+
readonly cause: unknown;
|
|
7
|
+
}> {
|
|
8
|
+
}
|
|
9
|
+
/** Storage failure stays distinct from absence; a live visitor keeps its state. */
|
|
10
|
+
export declare const embedStorage: {
|
|
11
|
+
read: (key: string) => Result.Result<string | null, BrowserStorageUnavailable>;
|
|
12
|
+
write: (key: string, value: string) => Result.Result<void, BrowserStorageUnavailable>;
|
|
13
|
+
remove: (key: string) => Result.Result<void, BrowserStorageUnavailable>;
|
|
14
|
+
};
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import * as Data from "effect/Data";
|
|
2
|
+
import * as Result from "effect/Result";
|
|
3
|
+
class BrowserStorageUnavailable extends Data.TaggedError("BrowserStorageUnavailable") {
|
|
4
|
+
}
|
|
5
|
+
function describeCause(cause, depth = 0) {
|
|
6
|
+
if (!(cause instanceof Error))
|
|
7
|
+
return { name: "NonError" };
|
|
8
|
+
if (cause.cause !== undefined && depth < 3)
|
|
9
|
+
return {
|
|
10
|
+
name: cause.name,
|
|
11
|
+
cause: describeCause(cause.cause, depth + 1),
|
|
12
|
+
};
|
|
13
|
+
return { name: cause.name };
|
|
14
|
+
}
|
|
15
|
+
/** A blocked visitor iframe may refuse access to its partitioned local storage. */
|
|
16
|
+
function accessStorage(stage, operation) {
|
|
17
|
+
return Result.try({
|
|
18
|
+
try: () => operation(globalThis.localStorage),
|
|
19
|
+
catch: (cause) => {
|
|
20
|
+
const error = new BrowserStorageUnavailable({ cause });
|
|
21
|
+
console.warn(JSON.stringify({
|
|
22
|
+
event: "browser_storage_unavailable",
|
|
23
|
+
level: "warn",
|
|
24
|
+
code: "local",
|
|
25
|
+
stage,
|
|
26
|
+
cause: describeCause(error),
|
|
27
|
+
}));
|
|
28
|
+
return error;
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** Storage failure stays distinct from absence; a live visitor keeps its state. */
|
|
33
|
+
export const embedStorage = {
|
|
34
|
+
read: (key) => accessStorage("read", (storage) => storage.getItem(key)),
|
|
35
|
+
write: (key, value) => accessStorage("write", (storage) => {
|
|
36
|
+
storage.setItem(key, value);
|
|
37
|
+
}),
|
|
38
|
+
remove: (key) => accessStorage("remove", (storage) => {
|
|
39
|
+
storage.removeItem(key);
|
|
40
|
+
}),
|
|
41
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ParakeetSession } from "./session.js";
|
|
2
|
+
/** What a host adds to its visitors' first request. */
|
|
3
|
+
export type VisitorClientOptions = Readonly<{
|
|
4
|
+
/** A Turnstile token for a site that requires one; asked only to mint. */
|
|
5
|
+
challenge?: () => Promise<string>;
|
|
6
|
+
}>;
|
|
7
|
+
/** Only the host's iframe owns this binding's partitioned visitor credentials. */
|
|
8
|
+
export declare function createVisitorClient(siteKey: string, options?: VisitorClientOptions): ParakeetSession;
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import * as Schema from "effect/Schema";
|
|
2
|
+
import * as Option from "effect/Option";
|
|
3
|
+
import * as Result from "effect/Result";
|
|
4
|
+
import * as z from "zod";
|
|
5
|
+
import { EventSource } from "eventsource";
|
|
6
|
+
import { parseAccepted, parseWithdrawResult, parseLatestPendingPrompt, parseSessionSnapshot, parseSessionFrame, } from "@fungi.computer/shiitake/client";
|
|
7
|
+
import { embedStorage } from "./website-storage.js";
|
|
8
|
+
const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));
|
|
9
|
+
const credentialsSchema = z.strictObject({
|
|
10
|
+
visitorId: z.string(),
|
|
11
|
+
accessToken: z.string(),
|
|
12
|
+
accessExpiresAt: z.number(),
|
|
13
|
+
refreshSecret: z.string(),
|
|
14
|
+
});
|
|
15
|
+
const errorSchema = z.strictObject({ error: z.string() });
|
|
16
|
+
const refusals = new Map([
|
|
17
|
+
[
|
|
18
|
+
"party_daily_limit",
|
|
19
|
+
"You've reached today's message limit. Please come back tomorrow.",
|
|
20
|
+
],
|
|
21
|
+
["new_party_limit", "This chat is busy right now. Please try again shortly."],
|
|
22
|
+
["address_limit", "This chat is busy right now. Please try again shortly."],
|
|
23
|
+
["too_long", "That message is too long."],
|
|
24
|
+
["suspended", "This chat is offline."],
|
|
25
|
+
["banned", "This chat is not available."],
|
|
26
|
+
["turnstile_required", "Please finish the security check and try again."],
|
|
27
|
+
["turnstile_failed", "The security check did not pass. Please try again."],
|
|
28
|
+
[
|
|
29
|
+
"turnstile_unavailable",
|
|
30
|
+
"The security check is unavailable. Try again soon.",
|
|
31
|
+
],
|
|
32
|
+
]);
|
|
33
|
+
class EmbedError extends Error {
|
|
34
|
+
code;
|
|
35
|
+
constructor(code, options) {
|
|
36
|
+
super(refusals.get(code) ?? "Chat unavailable. Please try again.", options);
|
|
37
|
+
this.code = code;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function readStored(key) {
|
|
41
|
+
const raw = embedStorage.read(key);
|
|
42
|
+
if (Result.isFailure(raw) || raw.success === null)
|
|
43
|
+
return null;
|
|
44
|
+
const json = decodeJson(raw.success);
|
|
45
|
+
if (Option.isNone(json))
|
|
46
|
+
return null;
|
|
47
|
+
const parsed = credentialsSchema.safeParse(json.value);
|
|
48
|
+
return parsed.success ? parsed.data : null;
|
|
49
|
+
}
|
|
50
|
+
async function failure(response) {
|
|
51
|
+
const decoded = decodeJson(await response.text());
|
|
52
|
+
if (Option.isNone(decoded))
|
|
53
|
+
return new EmbedError(String(response.status));
|
|
54
|
+
const body = errorSchema.safeParse(decoded.value);
|
|
55
|
+
return new EmbedError(body.success ? body.data.error : String(response.status));
|
|
56
|
+
}
|
|
57
|
+
/** Only the host's iframe owns this binding's partitioned visitor credentials. */
|
|
58
|
+
export function createVisitorClient(siteKey, options = {}) {
|
|
59
|
+
const base = `/api/embed/v1/sites/${siteKey}`;
|
|
60
|
+
const key = `fungi-embed:${siteKey}`;
|
|
61
|
+
let credentials = readStored(key);
|
|
62
|
+
const store = (next) => {
|
|
63
|
+
credentials = next;
|
|
64
|
+
if (next === null)
|
|
65
|
+
embedStorage.remove(key);
|
|
66
|
+
else
|
|
67
|
+
embedStorage.write(key, JSON.stringify(next));
|
|
68
|
+
};
|
|
69
|
+
const issue = async (path, body, authorization) => {
|
|
70
|
+
const headers = new Headers({ "content-type": "application/json" });
|
|
71
|
+
if (authorization !== undefined)
|
|
72
|
+
headers.set("authorization", `Bearer ${authorization}`);
|
|
73
|
+
const response = await fetch(`${base}${path}`, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers,
|
|
76
|
+
body: JSON.stringify(body),
|
|
77
|
+
});
|
|
78
|
+
if (!response.ok)
|
|
79
|
+
throw await failure(response);
|
|
80
|
+
const issued = credentialsSchema.parse(await response.json());
|
|
81
|
+
store(issued);
|
|
82
|
+
return issued;
|
|
83
|
+
};
|
|
84
|
+
const token = async () => {
|
|
85
|
+
if (credentials !== null &&
|
|
86
|
+
credentials.accessExpiresAt - 60_000 > Date.now())
|
|
87
|
+
return credentials.accessToken;
|
|
88
|
+
if (credentials !== null) {
|
|
89
|
+
return (await issue("/visitors/refresh", {
|
|
90
|
+
refreshSecret: credentials.refreshSecret,
|
|
91
|
+
})).accessToken;
|
|
92
|
+
}
|
|
93
|
+
const turnstileToken = await options.challenge?.();
|
|
94
|
+
return (await issue("/visitors", turnstileToken === undefined ? {} : { turnstileToken })).accessToken;
|
|
95
|
+
};
|
|
96
|
+
const authorized = async (path, init = {}) => {
|
|
97
|
+
const headers = new Headers(init.headers);
|
|
98
|
+
headers.set("authorization", `Bearer ${await token()}`);
|
|
99
|
+
const response = await fetch(`${base}${path}`, { ...init, headers });
|
|
100
|
+
if (!response.ok)
|
|
101
|
+
throw await failure(response);
|
|
102
|
+
return response;
|
|
103
|
+
};
|
|
104
|
+
const read = async (options) => parseSessionSnapshot(await (await authorized("/session", {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: { "content-type": "application/json" },
|
|
107
|
+
body: JSON.stringify(options ?? {}),
|
|
108
|
+
})).text());
|
|
109
|
+
async function command(input) {
|
|
110
|
+
if (input.type !== "prompt" || (input.images?.length ?? 0) > 0)
|
|
111
|
+
throw new EmbedError("command_not_allowed");
|
|
112
|
+
try {
|
|
113
|
+
const response = await authorized("/messages", {
|
|
114
|
+
method: "POST",
|
|
115
|
+
headers: { "content-type": "application/json" },
|
|
116
|
+
body: JSON.stringify({
|
|
117
|
+
requestId: input.requestId,
|
|
118
|
+
text: input.text,
|
|
119
|
+
}),
|
|
120
|
+
});
|
|
121
|
+
const raw = await response.text();
|
|
122
|
+
const decoded = decodeJson(raw);
|
|
123
|
+
if (Option.isNone(decoded))
|
|
124
|
+
throw new EmbedError("invalid_response");
|
|
125
|
+
const recorded = z
|
|
126
|
+
.strictObject({
|
|
127
|
+
status: z.literal("recorded"),
|
|
128
|
+
delivery: z.enum(["new", "replay"]),
|
|
129
|
+
})
|
|
130
|
+
.safeParse(decoded.value);
|
|
131
|
+
return recorded.success ? { status: "recorded" } : parseAccepted(raw);
|
|
132
|
+
}
|
|
133
|
+
catch (cause) {
|
|
134
|
+
if (cause instanceof EmbedError)
|
|
135
|
+
throw new Error(refusals.get(cause.code) ?? "Chat is unavailable. Please try again.", { cause });
|
|
136
|
+
throw cause;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
address: new URL(`${base}/session`, window.location.origin).href,
|
|
141
|
+
command,
|
|
142
|
+
withdraw: async (requestId) => parseWithdrawResult(await (await authorized("/requests/withdraw", {
|
|
143
|
+
method: "POST",
|
|
144
|
+
headers: { "content-type": "application/json" },
|
|
145
|
+
body: JSON.stringify({ requestId }),
|
|
146
|
+
})).text()),
|
|
147
|
+
latestPending: async () => parseLatestPendingPrompt(await (await authorized("/conversation/pending/latest")).text()),
|
|
148
|
+
extension: () => ({
|
|
149
|
+
call: () => Promise.reject(new EmbedError("command_not_allowed")),
|
|
150
|
+
}),
|
|
151
|
+
read,
|
|
152
|
+
watch: async (options) => {
|
|
153
|
+
const snapshot = await read(options);
|
|
154
|
+
let controller;
|
|
155
|
+
let closed = false;
|
|
156
|
+
const changes = new ReadableStream({
|
|
157
|
+
start: (next) => {
|
|
158
|
+
controller = next;
|
|
159
|
+
},
|
|
160
|
+
}, { highWaterMark: 32 });
|
|
161
|
+
const source = new EventSource(new URL(`${base}/conversation/events`, window.location.origin), {
|
|
162
|
+
fetch: async (input, init) => {
|
|
163
|
+
const headers = new Headers(init.headers);
|
|
164
|
+
try {
|
|
165
|
+
headers.set("authorization", `Bearer ${await token()}`);
|
|
166
|
+
}
|
|
167
|
+
catch (cause) {
|
|
168
|
+
stop(new Error("Chat unavailable. Please try again.", { cause }));
|
|
169
|
+
return new Response("Chat unavailable", { status: 403 });
|
|
170
|
+
}
|
|
171
|
+
return fetch(input, { ...init, headers });
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
const stop = (cause) => {
|
|
175
|
+
if (closed)
|
|
176
|
+
return;
|
|
177
|
+
closed = true;
|
|
178
|
+
source.close();
|
|
179
|
+
controller?.error(cause);
|
|
180
|
+
};
|
|
181
|
+
source.addEventListener("session", (event) => {
|
|
182
|
+
if (closed)
|
|
183
|
+
return;
|
|
184
|
+
try {
|
|
185
|
+
const baseline = parseSessionSnapshot(z.string().parse(event.data));
|
|
186
|
+
if (baseline.sessionId !== snapshot.sessionId)
|
|
187
|
+
throw new EmbedError("invalid_response");
|
|
188
|
+
if ((controller?.desiredSize ?? 0) <= 0)
|
|
189
|
+
throw new EmbedError("stream_overflow");
|
|
190
|
+
controller?.enqueue({
|
|
191
|
+
kind: "reset",
|
|
192
|
+
reason: "history_unavailable",
|
|
193
|
+
cursor: baseline.cursor,
|
|
194
|
+
baseline,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
catch (cause) {
|
|
198
|
+
stop(cause);
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
source.addEventListener("frame", (event) => {
|
|
202
|
+
if (closed)
|
|
203
|
+
return;
|
|
204
|
+
try {
|
|
205
|
+
const frame = parseSessionFrame(z.string().parse(event.data));
|
|
206
|
+
if (frame.kind !== "heartbeat" &&
|
|
207
|
+
frame.kind !== "progress" &&
|
|
208
|
+
frame.kind !== "activity")
|
|
209
|
+
throw new EmbedError("invalid_response");
|
|
210
|
+
if ((controller?.desiredSize ?? 0) <= 0)
|
|
211
|
+
throw new EmbedError("stream_overflow");
|
|
212
|
+
controller?.enqueue(frame);
|
|
213
|
+
}
|
|
214
|
+
catch (cause) {
|
|
215
|
+
stop(cause);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
source.addEventListener("error", () => {
|
|
219
|
+
stop(new Error("Chat unavailable. Please try again."));
|
|
220
|
+
});
|
|
221
|
+
const reader = changes.getReader();
|
|
222
|
+
return {
|
|
223
|
+
snapshot,
|
|
224
|
+
changes: {
|
|
225
|
+
async *[Symbol.asyncIterator]() {
|
|
226
|
+
try {
|
|
227
|
+
for (;;) {
|
|
228
|
+
const next = await reader.read();
|
|
229
|
+
if (next.done)
|
|
230
|
+
return;
|
|
231
|
+
yield next.value;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
reader.releaseLock();
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
close: () => {
|
|
240
|
+
if (!closed) {
|
|
241
|
+
closed = true;
|
|
242
|
+
controller?.close();
|
|
243
|
+
}
|
|
244
|
+
source.close();
|
|
245
|
+
return Promise.resolve();
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fungi.computer/parakeet",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"author": "Levi <levi@technomancy.dev>",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "Standalone React composer for a typed Shiitake Session",
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"types": "./dist/agent-head.d.ts",
|
|
28
28
|
"import": "./dist/agent-head.js"
|
|
29
29
|
},
|
|
30
|
+
"./website-visitor-client": {
|
|
31
|
+
"types": "./dist/website-visitor-client.d.ts",
|
|
32
|
+
"import": "./dist/website-visitor-client.js"
|
|
33
|
+
},
|
|
30
34
|
"./slash": {
|
|
31
35
|
"types": "./dist/commands/slash.d.ts",
|
|
32
36
|
"import": "./dist/commands/slash.js"
|
|
@@ -62,7 +66,7 @@
|
|
|
62
66
|
"@fungi.computer/caps": "0.7.1",
|
|
63
67
|
"@fungi.computer/gills": "0.2.1",
|
|
64
68
|
"@fungi.computer/knapsack": "0.4.5",
|
|
65
|
-
"@fungi.computer/shiitake": "0.
|
|
69
|
+
"@fungi.computer/shiitake": "0.10.0",
|
|
66
70
|
"@fungi.computer/sigils": "0.3.0",
|
|
67
71
|
"@fungi.computer/sprite": "0.2.0",
|
|
68
72
|
"@fungi.computer/sprite-zdog": "0.3.0",
|
|
@@ -70,6 +74,7 @@
|
|
|
70
74
|
"@tanstack/markdown": "0.0.12",
|
|
71
75
|
"@tanstack/react-virtual": "3.14.10",
|
|
72
76
|
"diff": "8.0.4",
|
|
77
|
+
"effect": "4.0.2",
|
|
73
78
|
"eventsource": "5.1.1",
|
|
74
79
|
"jotai": "2.20.3",
|
|
75
80
|
"jotai-tanstack-query": "0.11.0",
|