@app-assistant/host 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # @app-assistant/host
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Host the app-assistant writing bot in a JavaScript app. It implements your side of
4
+ [contract 1](https://github.com/mikedutuandu/app-assistant/blob/main/docs/integration.md) on Web `Request`/`Response`,
5
+ so it runs on Cloudflare Workers, Next.js, Hono, Deno and Node 20+ (it needs the global Web Crypto).
6
+
7
+ - `@app-assistant/host/server`: verifies the user's token and serves the bot's four endpoints and your pack from four
8
+ functions you write; signs tokens for your signed-in users; calls the bot as a user. Web Crypto and `fetch` only.
9
+ - `@app-assistant/host/react`: `<AssistantChat>`, the chat window.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @app-assistant/host
15
+ ```
16
+
17
+ You need, from the bot's owner: your **app id** (lowercase, e.g. `shipnote`), the **shared secret** (`openssl rand
18
+ -hex 32`, kept in your server's environment, never in git or a browser) and the bot's address.
19
+
20
+ ## The server: four functions
21
+
22
+ ```ts
23
+ // lib/assistant.ts
24
+ import { createAssistantHost } from "@app-assistant/host/server";
25
+ import pack from "./app-assistant.json"; // your pack: docs/app-assistant.schema.json
26
+
27
+ export const assistant = createAssistantHost({
28
+ appId: "shipnote",
29
+ secret: process.env.ASSISTANT_SECRET!,
30
+ botUrl: "https://bot.example.com", // for botFetch only
31
+ pack, // served at /.well-known/app-assistant.json; checked when created
32
+ // basePath: "/api/assistant", // the default
33
+
34
+ // POST /context: the user's profile, on every turn. Only `language` is required.
35
+ context: async (ws) => ({ language: "en", name: await nameOf(ws), credits_left: await creditsOf(ws) }),
36
+
37
+ // POST /drafts: save the draft the user tapped Add on (never publish it). The same key again → the same answer.
38
+ saveDraft: async (ws, { text, thread, media }, key) => {
39
+ const draft = await db.drafts.findOrCreate({ ws, key, text, thread, media }); // copy media URLs now: they expire
40
+ return { draft_id: draft.id, edit_url: `https://shipnote.app/drafts/${draft.id}` };
41
+ },
42
+
43
+ // POST /material: keep the facts the draft was written from. The same key again → do nothing.
44
+ saveMaterial: async (ws, facts, draftId, key) => db.facts.insertOnce({ ws, key, facts, draftId }),
45
+
46
+ // POST /charge: one model call's cost in US dollars. The same ref again → no second charge.
47
+ charge: async (ws, costUsd, ref) => {
48
+ if (await db.charges.has(ws, ref)) return { ok: true };
49
+ if ((await creditsOf(ws)) <= 0) return { outOfCredits: "You're out of credits. Top up in Billing." };
50
+ await db.charges.take(ws, ref, costUsd);
51
+ return { ok: true };
52
+ },
53
+
54
+ // Optional: two requests with the same Idempotency-Key at once. claim → false while one is running (→ 409);
55
+ // release is called when it ends. The key is "{workspace}/{drafts|material|charge}/{Idempotency-Key}".
56
+ once: { claim: (key) => kv.setIfAbsent(key, "1", { ttlSeconds: 120 }), release: (key) => kv.delete(key) },
57
+
58
+ // Optional: where caught errors go (a function that threw, a release that failed). Default: console.error.
59
+ onError: (error, where) => log.error(where, error),
60
+ });
61
+ ```
62
+
63
+ **`once.claim` must be atomic and must expire on its own** (at least 60 s; 2 minutes is a good choice). `release`
64
+ runs when a request ends, but not when the request is killed mid-work (a function timeout, a redeploy): a claim with
65
+ no expiry would then stay forever, and every repeat of that key would get 409 (the bot doesn't retry a 409, so that
66
+ draft could never be added). A failed `release` is reported to `onError` and never changes the answer. **Without
67
+ `once`**, two requests with the same key can run at the same time, so your functions must be idempotent per key on
68
+ their own (a unique index on the key, for example).
69
+
70
+ `handle` answers what the contract says for you: 401 `unauthorized` for a missing or bad token, 400 `invalid` for a
71
+ bad body or a missing `Idempotency-Key`, 402 `out_of_credits` with your sentence, 409 `in_flight`, and 500 `server`
72
+ when one of your functions throws (the error is logged with `console.error`, never sent).
73
+
74
+ ## The two routes
75
+
76
+ Send two routes to `assistant.handle(request)`: `{basePath}/*` (POST) and `/.well-known/app-assistant.json` (GET).
77
+ It answers `null` for any other request, so you can pass it on.
78
+
79
+ **Next.js (App Router)**
80
+
81
+ ```ts
82
+ // app/api/assistant/[endpoint]/route.ts and app/.well-known/app-assistant.json/route.ts
83
+ import { assistant } from "@/lib/assistant";
84
+
85
+ const handle = async (req: Request) => (await assistant.handle(req)) ?? new Response(null, { status: 404 });
86
+ export { handle as GET, handle as POST };
87
+ ```
88
+
89
+ **Cloudflare Workers, Hono**
90
+
91
+ ```ts
92
+ app.use("*", async (c, next) => (await assistant.handle(c.req.raw)) ?? next());
93
+ ```
94
+
95
+ **The session route** is yours, because only your app knows who is signed in. The chat window calls it with the
96
+ user's cookies:
97
+
98
+ ```ts
99
+ // app/api/assistant/session/route.ts
100
+ export async function POST() {
101
+ const user = await currentUser();
102
+ if (!user) return Response.json({ error: "unauthorized" }, { status: 401 });
103
+ return Response.json({ token: await assistant.signToken(user.workspaceId, "draft") });
104
+ }
105
+ ```
106
+
107
+ ## The chat window
108
+
109
+ ```tsx
110
+ import { AssistantChat } from "@app-assistant/host/react";
111
+
112
+ <AssistantChat app="shipnote" botUrl="https://bot.example.com" sessionUrl="/api/assistant/session" />;
113
+ ```
114
+
115
+ It loads the bot's `widget.js` once per page; the widget draws its own floating open button and panel. Optional:
116
+ `label` (the button's words), `position` (`"left"` or `"right"`), and `children` for an open button of your own
117
+ in the page (`className` styles it). `openAssistant()` opens the chat from anywhere.
118
+
119
+ Not on React? The same thing is one script tag:
120
+
121
+ ```html
122
+ <script src="https://bot.example.com/widget.js" data-app="shipnote" data-session-url="/api/assistant/session" async></script>
123
+ ```
124
+
125
+ ## More on the server
126
+
127
+ - `assistant.signToken(workspaceId, "draft" | "delete", ttlSeconds?)`: a token, 1 hour at most (the default).
128
+ - `assistant.botFetch(workspaceId, path, init?)`: `fetch(botUrl + path)` with a fresh token for that workspace. A
129
+ `DELETE /v1/apps/{app}/workspaces/{workspace}` gets a `delete` token: call it when a user deletes their account.
130
+ - `assistant.readEvents(response.body)`: the events of a message's stream, `{event, data}` with `data` parsed.
131
+
132
+ ```ts
133
+ const res = await assistant.botFetch(ws, "/v1/chat/shipnote/messages", {
134
+ method: "POST",
135
+ body: JSON.stringify({ thread_id: null, text: "We shipped dark mode", file_ids: [] }),
136
+ });
137
+ for await (const { event, data } of assistant.readEvents(res.body!)) if (event === "draft") console.log(data);
138
+ ```
139
+
140
+ - `signToken(secret, claims)` and `verifyToken(secret, token, appId, access)` are exported on their own too.
@@ -0,0 +1,24 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+
4
+ interface AssistantChatProps {
5
+ /** Your app id. */
6
+ app: string;
7
+ /** The bot's address, e.g. `https://bot.example.com`. */
8
+ botUrl: string;
9
+ /** Your route that answers `{token}` for the signed-in user. Default `/api/assistant/session`. */
10
+ sessionUrl?: string;
11
+ /** The open button's words. The widget's default is "Write with me". */
12
+ label?: string;
13
+ position?: "left" | "right";
14
+ /** An open button of your own, in your page's flow, as well as the widget's floating one. */
15
+ children?: ReactNode;
16
+ /** The class of your open button. */
17
+ className?: string;
18
+ }
19
+ /** Opens the chat window (the widget listens for `assistant:open`). */
20
+ declare function openAssistant(): void;
21
+ declare function AssistantChat(props: AssistantChatProps): react.JSX.Element | null;
22
+
23
+ export { AssistantChat, openAssistant };
24
+ export type { AssistantChatProps };
@@ -0,0 +1,31 @@
1
+ "use client";
2
+
3
+ // src/react/index.tsx
4
+ import { useEffect } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ var MARK = "data-app-assistant-host";
7
+ function openAssistant() {
8
+ window.dispatchEvent(new Event("assistant:open"));
9
+ }
10
+ function loadWidget({ app, botUrl, sessionUrl, label, position }) {
11
+ if (document.querySelector(`script[${MARK}]`) || document.getElementById("assistant-widget")) return;
12
+ const script = document.createElement("script");
13
+ script.src = `${botUrl.replace(/\/+$/, "")}/widget.js`;
14
+ script.async = true;
15
+ script.setAttribute(MARK, "");
16
+ script.dataset.app = app;
17
+ script.dataset.sessionUrl = sessionUrl ?? "/api/assistant/session";
18
+ if (label) script.dataset.label = label;
19
+ if (position) script.dataset.position = position;
20
+ document.body.appendChild(script);
21
+ }
22
+ function AssistantChat(props) {
23
+ const { app, botUrl, sessionUrl, label, position, children, className } = props;
24
+ useEffect(() => loadWidget({ app, botUrl, sessionUrl, label, position }), [app, botUrl, sessionUrl, label, position]);
25
+ if (children === void 0 || children === null) return null;
26
+ return /* @__PURE__ */ jsx("button", { type: "button", className, onClick: openAssistant, children });
27
+ }
28
+ export {
29
+ AssistantChat,
30
+ openAssistant
31
+ };
@@ -0,0 +1,146 @@
1
+ /** Calling the bot from the app's server: `botFetch` with the user's token, `readEvents` for a message's stream. */
2
+ interface BotEvent {
3
+ /** The event's name (`thread`, `status`, `text`, `draft`, `saved`, `failed`, `done`, ...); `message` if unnamed. */
4
+ event: string;
5
+ /** The event's data, parsed as JSON; the raw text when it isn't JSON. */
6
+ data: unknown;
7
+ }
8
+ /**
9
+ * The events of a Server-Sent Events body, such as `POST /v1/chat/{app}/messages`'s answer. Follows the SSE spec:
10
+ * LF, CRLF or CR line ends, `data` lines joined with "\n", comments and unknown fields skipped, an event the stream
11
+ * ended in the middle of dropped. Breaking out of the loop cancels the stream.
12
+ */
13
+ declare function readEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<BotEvent>;
14
+
15
+ /**
16
+ * The app's side of contract 1 (docs/integration.md): `POST {basePath}/context|drafts|material|charge`, checked
17
+ * with the user's token, and the pack at `GET /.well-known/app-assistant.json`. Web Request/Response only.
18
+ */
19
+ /** What `/context` answers. Only `language` is required. */
20
+ interface AppContext {
21
+ /** An ISO code such as `en` or `vi`. */
22
+ language: string;
23
+ name?: string;
24
+ voice?: string;
25
+ topics?: string[];
26
+ recent_posts?: string[];
27
+ patterns?: string[];
28
+ kept_facts?: {
29
+ id: string;
30
+ text: string;
31
+ }[];
32
+ /** In your own unit; `null` or left out when you don't count credits. At 0 or below the turn stops. */
33
+ credits_left?: number | null;
34
+ out_of_credits_message?: string;
35
+ }
36
+ interface DraftInput {
37
+ /** The first post. */
38
+ text: string;
39
+ /** The posts after it (`[]` for a single post). */
40
+ thread: string[];
41
+ /** Pictures for the first post: signed links to the bot's storage, valid 5 minutes. Copy them at once. */
42
+ media: {
43
+ url: string;
44
+ alt: string;
45
+ mime: string;
46
+ }[];
47
+ }
48
+ interface SavedDraft {
49
+ draft_id: string;
50
+ edit_url: string | null;
51
+ }
52
+ type ChargeResult = {
53
+ ok: true;
54
+ } | {
55
+ outOfCredits: string;
56
+ };
57
+ interface HostOptions {
58
+ /** Your app id: the bot's registry entry, your pack's `id`, your tokens' `iss`. */
59
+ appId: string;
60
+ /** The shared secret (server-only). */
61
+ secret: string;
62
+ /** The bot's address, for `botFetch`, e.g. `https://bot.example.com`. */
63
+ botUrl?: string;
64
+ /** Where the four endpoints are served. Default `/api/assistant`. */
65
+ basePath?: string;
66
+ /** Your pack, served at `/.well-known/app-assistant.json` (docs/app-assistant.schema.json). */
67
+ pack?: object;
68
+ /** The user's profile for the bot (`POST /context`). Keep it cheap: it runs on every turn. */
69
+ context(workspaceId: string): Promise<AppContext>;
70
+ /**
71
+ * Save a draft the user tapped Add on, never publish it. Same `key` again (per workspace) → the same draft: return
72
+ * the answer you gave the first time.
73
+ */
74
+ saveDraft(workspaceId: string, draft: DraftInput, key: string): Promise<SavedDraft>;
75
+ /** Keep the facts a draft was written from. Same `key` again → do nothing. */
76
+ saveMaterial(workspaceId: string, facts: string[], draftId: string | undefined, key: string): Promise<void>;
77
+ /**
78
+ * Take one model call's cost (US dollars) from the workspace's credits. Same `ref` again → `{ok: true}` with no
79
+ * second charge. No credits left → `{outOfCredits: "<a sentence for the user>"}`.
80
+ */
81
+ charge(workspaceId: string, costUsd: number, ref: string): Promise<ChargeResult>;
82
+ /**
83
+ * Two requests with the same Idempotency-Key at the same time. `claim(key)` must be **atomic** (one winner) and
84
+ * **expire on its own** after at least 60 s (2 minutes is a good choice): it answers false while the key is held
85
+ * (→ 409 `in_flight`). `release(key)` is called when the request ends, done or failed, but it never runs when the
86
+ * request is killed mid-work (a function timeout, a redeploy): without expiry that key would stay held forever and
87
+ * every repeat would get 409. A KV entry or a row with an expiry time works. The key is
88
+ * `{workspace}/{drafts|material|charge}/{Idempotency-Key}`. A request that outlives its claim can release a later
89
+ * holder's claim: harmless, because your functions replay a finished key's answer.
90
+ *
91
+ * Without `once`, two requests with one key can run at the same time: your functions must then be idempotent per
92
+ * key on their own (a unique index on the key, for example).
93
+ */
94
+ once?: {
95
+ claim(key: string): Promise<boolean>;
96
+ release?(key: string): Promise<void>;
97
+ };
98
+ /**
99
+ * Errors the package catches: one of your functions threw (`where` is `context`, `drafts`, `material` or `charge`;
100
+ * the bot gets 500 `server`), or `release` failed (`where` is `release <key>`; the answer is unchanged). Default:
101
+ * `console.error`.
102
+ */
103
+ onError?(error: unknown, where: string): void;
104
+ }
105
+
106
+ /**
107
+ * Session tokens (docs/integration.md, "Tokens"): HS256 JWTs with `iss` = app id, `sub` = workspace,
108
+ * `access` = "draft" | "delete", `exp - iat` at most an hour. Web Crypto only, so it runs on Workers, Node and Deno.
109
+ */
110
+ type Access = "draft" | "delete";
111
+ interface TokenClaims {
112
+ appId: string;
113
+ workspaceId: string;
114
+ access: Access;
115
+ /** How long the token lives, 1 to 3600 seconds. Default 3600. */
116
+ ttlSeconds?: number;
117
+ }
118
+ /** A token for `workspaceId`, signed with the app's shared secret. Sign on your server only. */
119
+ declare function signToken(secret: string, claims: TokenClaims): Promise<string>;
120
+ /**
121
+ * The workspace of a token, checked exactly as the bot checks it: the signature with `secret`, `iss` is `appId`,
122
+ * `access` is `access`, not expired, `exp - iat` at most an hour, a well-formed `sub`. `null` for any other token.
123
+ */
124
+ declare function verifyToken(secret: string, token: string, appId: string, access: Access): Promise<{
125
+ workspaceId: string;
126
+ } | null>;
127
+
128
+ /**
129
+ * `@app-assistant/host/server`: an app's side of the app-assistant contract (docs/integration.md) on Web
130
+ * Request/Response, for Cloudflare Workers, Next.js, Hono, Deno and Node 20+. Web Crypto and fetch only.
131
+ */
132
+
133
+ interface AssistantHost {
134
+ /** Your routes' answer, or `null` when the request isn't for `{basePath}/*` or the pack: pass it on. */
135
+ handle(req: Request): Promise<Response | null>;
136
+ /** A token for a signed-in user's workspace (`draft` to chat, `delete` to delete their data), 1 hour by default. */
137
+ signToken(workspaceId: string, access: Access, ttlSeconds?: number): Promise<string>;
138
+ /** `fetch(botUrl + path)` as the workspace: adds `Authorization: Bearer <a fresh token>`. */
139
+ botFetch(workspaceId: string, path: string, init?: RequestInit): Promise<Response>;
140
+ /** The events of a chat message's Server-Sent Events answer. */
141
+ readEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<BotEvent>;
142
+ }
143
+ declare function createAssistantHost(opts: HostOptions): AssistantHost;
144
+
145
+ export { createAssistantHost, readEvents, signToken, verifyToken };
146
+ export type { Access, AppContext, AssistantHost, BotEvent, ChargeResult, DraftInput, HostOptions, SavedDraft, TokenClaims };
@@ -0,0 +1,340 @@
1
+ // src/server/token.ts
2
+ var MAX_TTL_SECONDS = 3600;
3
+ var LEEWAY_SECONDS = 30;
4
+ var WORKSPACE_ID = /^[A-Za-z0-9:_.-]{1,200}$/;
5
+ var ACCESS = ["draft", "delete"];
6
+ var encoder = new TextEncoder();
7
+ var decoder = new TextDecoder();
8
+ function base64url(bytes) {
9
+ let binary = "";
10
+ for (const b of bytes) binary += String.fromCharCode(b);
11
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12
+ }
13
+ function fromBase64url(text) {
14
+ if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null;
15
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - text.length % 4) % 4));
16
+ const bytes = new Uint8Array(binary.length);
17
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
18
+ return bytes;
19
+ }
20
+ function parseJson(bytes) {
21
+ if (!bytes) return null;
22
+ try {
23
+ const value = JSON.parse(decoder.decode(bytes));
24
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ function hmacKey(secret, usage) {
30
+ if (typeof secret !== "string" || secret === "") throw new TypeError("app-assistant: the shared secret is empty");
31
+ return crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
32
+ }
33
+ var isTime = (n) => typeof n === "number" && Number.isFinite(n);
34
+ var nowSeconds = () => Math.floor(Date.now() / 1e3);
35
+ async function signToken(secret, claims) {
36
+ const { appId, workspaceId, access, ttlSeconds = MAX_TTL_SECONDS } = claims;
37
+ if (typeof appId !== "string" || appId === "") throw new TypeError("app-assistant: appId is empty");
38
+ if (typeof workspaceId !== "string" || !WORKSPACE_ID.test(workspaceId))
39
+ throw new TypeError("app-assistant: a workspace id is 1-200 characters of A-Z a-z 0-9 : _ . -");
40
+ if (!ACCESS.includes(access)) throw new TypeError('app-assistant: access is "draft" or "delete"');
41
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > MAX_TTL_SECONDS)
42
+ throw new RangeError(`app-assistant: ttlSeconds is a whole number from 1 to ${MAX_TTL_SECONDS}`);
43
+ const key = await hmacKey(secret, "sign");
44
+ const iat = nowSeconds();
45
+ const head = [
46
+ { alg: "HS256", typ: "JWT" },
47
+ { iss: appId, sub: workspaceId, access, iat, exp: iat + ttlSeconds }
48
+ ].map((part) => base64url(encoder.encode(JSON.stringify(part)))).join(".");
49
+ const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(head)));
50
+ return `${head}.${base64url(signature)}`;
51
+ }
52
+ async function verifyToken(secret, token, appId, access) {
53
+ if (typeof token !== "string") return null;
54
+ const parts = token.split(".");
55
+ if (parts.length !== 3) return null;
56
+ const header = parseJson(fromBase64url(parts[0]));
57
+ const signature = fromBase64url(parts[2]);
58
+ if (!header || header.alg !== "HS256" || !signature) return null;
59
+ const key = await hmacKey(secret, "verify");
60
+ const valid = await crypto.subtle.verify("HMAC", key, signature, encoder.encode(`${parts[0]}.${parts[1]}`));
61
+ if (!valid) return null;
62
+ const claims = parseJson(fromBase64url(parts[1]));
63
+ if (!claims) return null;
64
+ const { iss, sub, iat, exp, nbf } = claims;
65
+ const now = Date.now() / 1e3;
66
+ if (!isTime(iat) || !isTime(exp) || typeof iss !== "string" || typeof sub !== "string") return null;
67
+ if (!WORKSPACE_ID.test(sub)) return null;
68
+ if (exp <= now || iat > now + LEEWAY_SECONDS) return null;
69
+ if (nbf !== void 0 && (!isTime(nbf) || nbf > now + LEEWAY_SECONDS)) return null;
70
+ if (iss !== appId || claims.access !== access) return null;
71
+ if (exp - iat > MAX_TTL_SECONDS) return null;
72
+ return { workspaceId: sub };
73
+ }
74
+
75
+ // src/server/bot.ts
76
+ var SERVER_TTL_SECONDS = 600;
77
+ async function botFetch(opts, workspaceId, path, init = {}) {
78
+ if (!opts.botUrl) throw new TypeError("app-assistant: botFetch needs botUrl in createAssistantHost's options");
79
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//"))
80
+ throw new TypeError(
81
+ `app-assistant: botFetch's path starts with one "/" (the bot's root), got ${JSON.stringify(path)}`
82
+ );
83
+ const method = (init.method ?? "GET").toUpperCase();
84
+ const access = method === "DELETE" && path.startsWith("/v1/apps/") ? "delete" : "draft";
85
+ const token = await signToken(opts.secret, {
86
+ appId: opts.appId,
87
+ workspaceId,
88
+ access,
89
+ ttlSeconds: SERVER_TTL_SECONDS
90
+ });
91
+ const headers = new Headers(init.headers);
92
+ headers.set("authorization", `Bearer ${token}`);
93
+ headers.delete("origin");
94
+ if (typeof init.body === "string" && !headers.has("content-type")) headers.set("content-type", "application/json");
95
+ return fetch(`${opts.botUrl.replace(/\/+$/, "")}${path}`, { ...init, method, headers });
96
+ }
97
+ async function* readEvents(body) {
98
+ const reader = body.getReader();
99
+ const decoder2 = new TextDecoder();
100
+ let buffer = "";
101
+ let event = "";
102
+ let data = [];
103
+ let finished = false;
104
+ function* lines(final) {
105
+ for (; ; ) {
106
+ const end = buffer.search(/\r\n|\r|\n/);
107
+ if (end < 0) break;
108
+ if (buffer[end] === "\r" && end === buffer.length - 1 && !final) break;
109
+ const width = buffer.startsWith("\r\n", end) ? 2 : 1;
110
+ yield buffer.slice(0, end);
111
+ buffer = buffer.slice(end + width);
112
+ }
113
+ }
114
+ function take(line) {
115
+ if (line === "") {
116
+ const out = data.length ? { event: event || "message", data: parse(data.join("\n")) } : null;
117
+ event = "";
118
+ data = [];
119
+ return out;
120
+ }
121
+ if (line.startsWith(":")) return null;
122
+ const colon = line.indexOf(":");
123
+ const field = colon < 0 ? line : line.slice(0, colon);
124
+ let value = colon < 0 ? "" : line.slice(colon + 1);
125
+ if (value.startsWith(" ")) value = value.slice(1);
126
+ if (field === "event") event = value;
127
+ else if (field === "data") data.push(value);
128
+ return null;
129
+ }
130
+ try {
131
+ for (; ; ) {
132
+ const { done, value } = await reader.read();
133
+ buffer += done ? decoder2.decode() : decoder2.decode(value, { stream: true });
134
+ for (const line of lines(done)) {
135
+ const out = take(line);
136
+ if (out) yield out;
137
+ }
138
+ if (done) {
139
+ finished = true;
140
+ return;
141
+ }
142
+ }
143
+ } finally {
144
+ if (finished) reader.releaseLock();
145
+ else await reader.cancel().catch(() => {
146
+ });
147
+ }
148
+ }
149
+ function parse(text) {
150
+ try {
151
+ return JSON.parse(text);
152
+ } catch {
153
+ return text;
154
+ }
155
+ }
156
+
157
+ // src/server/handle.ts
158
+ var PACK_PATH = "/.well-known/app-assistant.json";
159
+ var IN_FLIGHT = "Still saving that. Try again in a moment.";
160
+ var MAX_BODY_CHARS = 1e6;
161
+ var MAX_KEY_CHARS = 200;
162
+ var ENDPOINTS = ["context", "drafts", "material", "charge"];
163
+ var Refused = class extends Error {
164
+ constructor(status, code, userMessage) {
165
+ super(code);
166
+ this.status = status;
167
+ this.code = code;
168
+ this.userMessage = userMessage;
169
+ }
170
+ status;
171
+ code;
172
+ userMessage;
173
+ };
174
+ var WrongAnswer = class extends Error {
175
+ };
176
+ function json(status, body, headers = {}) {
177
+ return new Response(JSON.stringify(body), {
178
+ status,
179
+ headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers }
180
+ });
181
+ }
182
+ var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
183
+ var isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
184
+ var isText = (v) => typeof v === "string" && v.trim() !== "";
185
+ function checkPack(pack, appId) {
186
+ const p = pack;
187
+ const fail = (why) => {
188
+ throw new TypeError(`app-assistant: the pack ${why} (docs/app-assistant.schema.json)`);
189
+ };
190
+ if (!isObject(p)) fail("is not an object");
191
+ if (p.contract !== 1) fail('needs "contract": 1');
192
+ if (typeof p.id !== "string" || !/^[a-z0-9][a-z0-9_-]{0,39}$/.test(p.id)) fail("needs an id: lowercase, up to 40");
193
+ if (p.id !== appId) fail(`id ${JSON.stringify(p.id)} is not appId ${JSON.stringify(appId)}`);
194
+ if (!isText(p.name)) fail("needs a name");
195
+ if (typeof p.api_base !== "string" || !/^https?:\/\/[^/\s]+/.test(p.api_base)) fail("needs api_base, an http(s) URL");
196
+ if (!isStrings(p.allowed_origins) || !p.allowed_origins.every((o) => /^https?:\/\/[^/\s]+\/?$/.test(o)))
197
+ fail("needs allowed_origins, a list of scheme://host[:port]");
198
+ if (!isText(p.guide)) fail("needs a guide");
199
+ if (!Array.isArray(p.writes) || p.writes.length === 0 || !p.writes.every(isObject))
200
+ fail("needs writes, at least one");
201
+ if (!isObject(p.models)) fail("needs models");
202
+ if (typeof p.message_usd_cap !== "number" || !(p.message_usd_cap > 0)) fail("needs message_usd_cap, above 0");
203
+ }
204
+ function createHandler(opts) {
205
+ const trimmed = (opts.basePath ?? "/api/assistant").replace(/^\/+|\/+$/g, "");
206
+ const base = trimmed ? `/${trimmed}` : "";
207
+ const pack = opts.pack;
208
+ if (pack !== void 0) checkPack(pack, opts.appId);
209
+ const packBody = pack === void 0 ? "" : JSON.stringify(pack);
210
+ return async function handle(req) {
211
+ const path = new URL(req.url).pathname;
212
+ if (path === PACK_PATH) {
213
+ if (pack === void 0) return null;
214
+ if (req.method !== "GET" && req.method !== "HEAD") return json(405, { error: "invalid" }, { allow: "GET" });
215
+ return new Response(req.method === "HEAD" ? null : packBody, {
216
+ status: 200,
217
+ headers: { "content-type": "application/json; charset=utf-8", "cache-control": "public, max-age=300" }
218
+ });
219
+ }
220
+ if (!path.startsWith(`${base}/`)) return null;
221
+ const name = path.slice(base.length + 1);
222
+ if (!ENDPOINTS.includes(name)) return null;
223
+ if (req.method !== "POST") return json(405, { error: "invalid" }, { allow: "POST" });
224
+ try {
225
+ return json(200, await endpoint(opts, name, req));
226
+ } catch (e) {
227
+ if (e instanceof Refused)
228
+ return json(
229
+ e.status,
230
+ e.userMessage === void 0 ? { error: e.code } : { error: e.code, message: e.userMessage }
231
+ );
232
+ report(opts, e, name);
233
+ return json(500, { error: "server" });
234
+ }
235
+ };
236
+ }
237
+ function report(opts, error, where) {
238
+ try {
239
+ if (opts.onError) {
240
+ const out = opts.onError(error, where);
241
+ if (out && typeof out.then === "function")
242
+ Promise.resolve(out).catch((e) => console.error(`app-assistant: onError failed for ${where}`, e));
243
+ return;
244
+ }
245
+ } catch {
246
+ }
247
+ console.error(`app-assistant: ${where} failed`, error);
248
+ }
249
+ async function endpoint(opts, name, req) {
250
+ const [scheme, token] = (req.headers.get("authorization") ?? "").split(/\s+/, 2);
251
+ const session = scheme?.toLowerCase() === "bearer" && token ? await verifyToken(opts.secret, token, opts.appId, "draft") : null;
252
+ if (!session) throw new Refused(401, "unauthorized");
253
+ const ws = session.workspaceId;
254
+ const text = await req.text();
255
+ if (text.length > MAX_BODY_CHARS) throw new Refused(400, "invalid", "The body is too large.");
256
+ let body;
257
+ try {
258
+ body = JSON.parse(text);
259
+ } catch {
260
+ throw new Refused(400, "invalid", "The body is not JSON.");
261
+ }
262
+ if (!isObject(body)) throw new Refused(400, "invalid", "The body must be a JSON object.");
263
+ if (name === "context") {
264
+ const context = await opts.context(ws);
265
+ if (!isObject(context) || !isText(context.language)) throw new WrongAnswer("context() must return {language, ...}");
266
+ return context;
267
+ }
268
+ const key = req.headers.get("idempotency-key") ?? "";
269
+ if (!key || key.length > MAX_KEY_CHARS) throw new Refused(400, "invalid", "Idempotency-Key is missing or too long.");
270
+ const work = prepare(opts, name, ws, body, key);
271
+ const slot = `${ws}/${name}/${key}`;
272
+ if (opts.once && !await opts.once.claim(slot)) throw new Refused(409, "in_flight", IN_FLIGHT);
273
+ try {
274
+ return await work();
275
+ } finally {
276
+ await Promise.resolve().then(() => opts.once?.release?.(slot)).catch((e) => report(opts, e, `release ${slot}`));
277
+ }
278
+ }
279
+ function prepare(opts, name, ws, body, key) {
280
+ if (name === "drafts") {
281
+ const { text, thread, media } = body;
282
+ if (!isText(text)) throw new Refused(400, "invalid", "The draft is empty.");
283
+ if (!isStrings(thread)) throw new Refused(400, "invalid", "thread must be a list of posts.");
284
+ const fields = ["url", "alt", "mime"];
285
+ if (!Array.isArray(media) || !media.every((m) => isObject(m) && fields.every((f) => typeof m[f] === "string")))
286
+ throw new Refused(400, "invalid", "media must be a list of {url, alt, mime}.");
287
+ const draft = {
288
+ text,
289
+ thread,
290
+ media: media.map((m) => ({ url: m.url, alt: m.alt, mime: m.mime }))
291
+ };
292
+ return async () => {
293
+ const saved = await opts.saveDraft(ws, draft, key);
294
+ if (!isObject(saved) || !isText(saved.draft_id))
295
+ throw new WrongAnswer("saveDraft() must return {draft_id, edit_url}");
296
+ const editUrl = saved.edit_url ?? null;
297
+ if (editUrl !== null && typeof editUrl !== "string")
298
+ throw new WrongAnswer("saveDraft()'s edit_url is a string or null");
299
+ return { draft_id: saved.draft_id, edit_url: editUrl };
300
+ };
301
+ }
302
+ if (name === "material") {
303
+ const { facts, draft_id } = body;
304
+ if (!isStrings(facts)) throw new Refused(400, "invalid", "facts must be a list of sentences.");
305
+ if (draft_id !== void 0 && draft_id !== null && typeof draft_id !== "string")
306
+ throw new Refused(400, "invalid", "draft_id must be a string.");
307
+ return async () => {
308
+ await opts.saveMaterial(ws, facts, draft_id ?? void 0, key);
309
+ return { ok: true };
310
+ };
311
+ }
312
+ const { cost_usd, ref } = body;
313
+ if (typeof cost_usd !== "number" || !Number.isFinite(cost_usd) || cost_usd < 0)
314
+ throw new Refused(400, "invalid", "cost_usd must be a number, 0 or more.");
315
+ if (!isText(ref)) throw new Refused(400, "invalid", "ref is missing.");
316
+ return async () => {
317
+ const result = await opts.charge(ws, cost_usd, ref);
318
+ if (isObject(result) && result.ok === true) return { ok: true };
319
+ if (isObject(result) && isText(result.outOfCredits)) throw new Refused(402, "out_of_credits", result.outOfCredits);
320
+ throw new WrongAnswer("charge() must return {ok: true} or {outOfCredits: message}");
321
+ };
322
+ }
323
+
324
+ // src/server/index.ts
325
+ function createAssistantHost(opts) {
326
+ if (typeof opts.appId !== "string" || opts.appId === "") throw new TypeError("app-assistant: appId is empty");
327
+ if (typeof opts.secret !== "string" || opts.secret === "") throw new TypeError("app-assistant: secret is empty");
328
+ return {
329
+ handle: createHandler(opts),
330
+ signToken: (workspaceId, access, ttlSeconds) => signToken(opts.secret, { appId: opts.appId, workspaceId, access, ttlSeconds }),
331
+ botFetch: (workspaceId, path, init) => botFetch(opts, workspaceId, path, init),
332
+ readEvents
333
+ };
334
+ }
335
+ export {
336
+ createAssistantHost,
337
+ readEvents,
338
+ signToken,
339
+ verifyToken
340
+ };
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@app-assistant/host",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Host the app-assistant writing bot in a JavaScript app: the contract's four endpoints, its pack and tokens on Web Request/Response, and the chat window for React.",
5
+ "license": "UNLICENSED",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mikedutuandu/app-assistant.git",
9
+ "directory": "sdk/js"
10
+ },
11
+ "type": "module",
12
+ "sideEffects": false,
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "exports": {
17
+ "./server": {
18
+ "types": "./dist/server/index.d.ts",
19
+ "import": "./dist/server/index.js"
20
+ },
21
+ "./react": {
22
+ "types": "./dist/react/index.d.ts",
23
+ "import": "./dist/react/index.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "scripts": {
31
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
32
+ "build": "tsup",
33
+ "test": "vitest run",
34
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
35
+ "prepublishOnly": "npm test && npm run build"
36
+ },
37
+ "peerDependencies": {
38
+ "react": ">=18"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "react": {
42
+ "optional": true
43
+ }
44
+ },
45
+ "devDependencies": {
46
+ "@testing-library/react": "^16.3.3",
47
+ "@types/node": "^22.20.5",
48
+ "@types/react": "^19.3.0",
49
+ "@types/react-dom": "^19.3.0",
50
+ "jsdom": "^31.0.1",
51
+ "react": "^19.3.1",
52
+ "react-dom": "^19.3.1",
53
+ "tsup": "^9.0.0",
54
+ "typescript": "~6.0.3",
55
+ "vitest": "^5.1.1"
56
+ }
57
+ }