@app-assistant/host 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mike Du
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,157 @@
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
+ **Scheduling (optional).** If your app can schedule posts, add the user's next free times to `context`, labelled
64
+ in their own time zone; the bot then picks one for each draft and shows a Schedule button:
65
+
66
+ ```ts
67
+ context: async (ws) => ({
68
+ language: "en",
69
+ post_times: (await freeSlots(ws, 5)).map((t) => ({ at: t.toISOString(), label: label(t, tzOf(ws)), why: "one of your best hours" })),
70
+ }),
71
+ saveDraft: async (ws, { text, thread, media, schedule_at }, key) => {
72
+ const draft = await db.drafts.findOrCreate({ ws, key, text, thread, media });
73
+ const answer = { draft_id: draft.id, edit_url: `https://shipnote.app/drafts/${draft.id}` };
74
+ if (!schedule_at) return answer; // Save draft
75
+ const ok = await schedule(draft.id, schedule_at); // the user tapped Schedule: that tap is their OK
76
+ return ok ? { ...answer, scheduled_at: schedule_at } : { ...answer, scheduled_at: null, schedule_note: "That time is taken now." };
77
+ },
78
+ ```
79
+
80
+ **`once.claim` must be atomic and must expire on its own** (at least 60 s; 2 minutes is a good choice). `release`
81
+ runs when a request ends, but not when the request is killed mid-work (a function timeout, a redeploy): a claim with
82
+ no expiry would then stay forever, and every repeat of that key would get 409 (the bot doesn't retry a 409, so that
83
+ draft could never be added). A failed `release` is reported to `onError` and never changes the answer. **Without
84
+ `once`**, two requests with the same key can run at the same time, so your functions must be idempotent per key on
85
+ their own (a unique index on the key, for example).
86
+
87
+ `handle` answers what the contract says for you: 401 `unauthorized` for a missing or bad token, 400 `invalid` for a
88
+ bad body or a missing `Idempotency-Key`, 402 `out_of_credits` with your sentence, 409 `in_flight`, and 500 `server`
89
+ when one of your functions throws (the error is logged with `console.error`, never sent).
90
+
91
+ ## The two routes
92
+
93
+ Send two routes to `assistant.handle(request)`: `{basePath}/*` (POST) and `/.well-known/app-assistant.json` (GET).
94
+ It answers `null` for any other request, so you can pass it on.
95
+
96
+ **Next.js (App Router)**
97
+
98
+ ```ts
99
+ // app/api/assistant/[endpoint]/route.ts and app/.well-known/app-assistant.json/route.ts
100
+ import { assistant } from "@/lib/assistant";
101
+
102
+ const handle = async (req: Request) => (await assistant.handle(req)) ?? new Response(null, { status: 404 });
103
+ export { handle as GET, handle as POST };
104
+ ```
105
+
106
+ **Cloudflare Workers, Hono**
107
+
108
+ ```ts
109
+ app.use("*", async (c, next) => (await assistant.handle(c.req.raw)) ?? next());
110
+ ```
111
+
112
+ **The session route** is yours, because only your app knows who is signed in. The chat window calls it with the
113
+ user's cookies:
114
+
115
+ ```ts
116
+ // app/api/assistant/session/route.ts
117
+ export async function POST() {
118
+ const user = await currentUser();
119
+ if (!user) return Response.json({ error: "unauthorized" }, { status: 401 });
120
+ return Response.json({ token: await assistant.signToken(user.workspaceId, "draft") });
121
+ }
122
+ ```
123
+
124
+ ## The chat window
125
+
126
+ ```tsx
127
+ import { AssistantChat } from "@app-assistant/host/react";
128
+
129
+ <AssistantChat app="shipnote" botUrl="https://bot.example.com" sessionUrl="/api/assistant/session" />;
130
+ ```
131
+
132
+ It loads the bot's `widget.js` once per page; the widget draws its own floating open button and panel. Optional:
133
+ `label` (the button's words), `position` (`"left"` or `"right"`), and `children` for an open button of your own
134
+ in the page (`className` styles it). `openAssistant()` opens the chat from anywhere.
135
+
136
+ Not on React? The same thing is one script tag:
137
+
138
+ ```html
139
+ <script src="https://bot.example.com/widget.js" data-app="shipnote" data-session-url="/api/assistant/session" async></script>
140
+ ```
141
+
142
+ ## More on the server
143
+
144
+ - `assistant.signToken(workspaceId, "draft" | "delete", ttlSeconds?)`: a token, 1 hour at most (the default).
145
+ - `assistant.botFetch(workspaceId, path, init?)`: `fetch(botUrl + path)` with a fresh token for that workspace. A
146
+ `DELETE /v1/apps/{app}/workspaces/{workspace}` gets a `delete` token: call it when a user deletes their account.
147
+ - `assistant.readEvents(response.body)`: the events of a message's stream, `{event, data}` with `data` parsed.
148
+
149
+ ```ts
150
+ const res = await assistant.botFetch(ws, "/v1/chat/shipnote/messages", {
151
+ method: "POST",
152
+ body: JSON.stringify({ thread_id: null, text: "We shipped dark mode", file_ids: [] }),
153
+ });
154
+ for await (const { event, data } of assistant.readEvents(res.body!)) if (event === "draft") console.log(data);
155
+ ```
156
+
157
+ - `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 AI". */
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,162 @@
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
+ * The user's next free times to post (at most 10, soonest first), when you can schedule a draft: `at` is an ISO
37
+ * time, `label` how the user reads it in their own time zone ("Tue 9:30 AM"), `why` a few words ("one of your best
38
+ * hours"). The bot picks one and the user can schedule the draft from the chat (`saveDraft`'s `schedule_at`).
39
+ */
40
+ post_times?: {
41
+ at: string;
42
+ label: string;
43
+ why?: string;
44
+ }[];
45
+ }
46
+ interface DraftInput {
47
+ /** The first post. */
48
+ text: string;
49
+ /** The posts after it (`[]` for a single post). */
50
+ thread: string[];
51
+ /** Pictures for the first post: signed links to the bot's storage, valid 5 minutes. Copy them at once. */
52
+ media: {
53
+ url: string;
54
+ alt: string;
55
+ mime: string;
56
+ }[];
57
+ /** Set when the user tapped Schedule: one of your `post_times`. Save the draft, then schedule it then. */
58
+ schedule_at?: string;
59
+ }
60
+ interface SavedDraft {
61
+ draft_id: string;
62
+ edit_url: string | null;
63
+ /** With `schedule_at`: the time you scheduled it, or `null` when you only saved it (say why in `schedule_note`). */
64
+ scheduled_at?: string | null;
65
+ /** Why it wasn't scheduled, in the user's words ("That time is taken now."). */
66
+ schedule_note?: string;
67
+ }
68
+ type ChargeResult = {
69
+ ok: true;
70
+ } | {
71
+ outOfCredits: string;
72
+ };
73
+ interface HostOptions {
74
+ /** Your app id: the bot's registry entry, your pack's `id`, your tokens' `iss`. */
75
+ appId: string;
76
+ /** The shared secret (server-only). */
77
+ secret: string;
78
+ /** The bot's address, for `botFetch`, e.g. `https://bot.example.com`. */
79
+ botUrl?: string;
80
+ /** Where the four endpoints are served. Default `/api/assistant`. */
81
+ basePath?: string;
82
+ /** Your pack, served at `/.well-known/app-assistant.json` (docs/app-assistant.schema.json). */
83
+ pack?: object;
84
+ /** The user's profile for the bot (`POST /context`). Keep it cheap: it runs on every turn. */
85
+ context(workspaceId: string): Promise<AppContext>;
86
+ /**
87
+ * Save a draft the user tapped Add on, never publish it. Same `key` again (per workspace) → the same draft: return
88
+ * the answer you gave the first time.
89
+ */
90
+ saveDraft(workspaceId: string, draft: DraftInput, key: string): Promise<SavedDraft>;
91
+ /** Keep the facts a draft was written from. Same `key` again → do nothing. */
92
+ saveMaterial(workspaceId: string, facts: string[], draftId: string | undefined, key: string): Promise<void>;
93
+ /**
94
+ * Take one model call's cost (US dollars) from the workspace's credits. Same `ref` again → `{ok: true}` with no
95
+ * second charge. No credits left → `{outOfCredits: "<a sentence for the user>"}`.
96
+ */
97
+ charge(workspaceId: string, costUsd: number, ref: string): Promise<ChargeResult>;
98
+ /**
99
+ * Two requests with the same Idempotency-Key at the same time. `claim(key)` must be **atomic** (one winner) and
100
+ * **expire on its own** after at least 60 s (2 minutes is a good choice): it answers false while the key is held
101
+ * (→ 409 `in_flight`). `release(key)` is called when the request ends, done or failed, but it never runs when the
102
+ * request is killed mid-work (a function timeout, a redeploy): without expiry that key would stay held forever and
103
+ * every repeat would get 409. A KV entry or a row with an expiry time works. The key is
104
+ * `{workspace}/{drafts|material|charge}/{Idempotency-Key}`. A request that outlives its claim can release a later
105
+ * holder's claim: harmless, because your functions replay a finished key's answer.
106
+ *
107
+ * Without `once`, two requests with one key can run at the same time: your functions must then be idempotent per
108
+ * key on their own (a unique index on the key, for example).
109
+ */
110
+ once?: {
111
+ claim(key: string): Promise<boolean>;
112
+ release?(key: string): Promise<void>;
113
+ };
114
+ /**
115
+ * Errors the package catches: one of your functions threw (`where` is `context`, `drafts`, `material` or `charge`;
116
+ * the bot gets 500 `server`), or `release` failed (`where` is `release <key>`; the answer is unchanged). Default:
117
+ * `console.error`.
118
+ */
119
+ onError?(error: unknown, where: string): void;
120
+ }
121
+
122
+ /**
123
+ * Session tokens (docs/integration.md, "Tokens"): HS256 JWTs with `iss` = app id, `sub` = workspace,
124
+ * `access` = "draft" | "delete", `exp - iat` at most an hour. Web Crypto only, so it runs on Workers, Node and Deno.
125
+ */
126
+ type Access = "draft" | "delete";
127
+ interface TokenClaims {
128
+ appId: string;
129
+ workspaceId: string;
130
+ access: Access;
131
+ /** How long the token lives, 1 to 3600 seconds. Default 3600. */
132
+ ttlSeconds?: number;
133
+ }
134
+ /** A token for `workspaceId`, signed with the app's shared secret. Sign on your server only. */
135
+ declare function signToken(secret: string, claims: TokenClaims): Promise<string>;
136
+ /**
137
+ * The workspace of a token, checked exactly as the bot checks it: the signature with `secret`, `iss` is `appId`,
138
+ * `access` is `access`, not expired, `exp - iat` at most an hour, a well-formed `sub`. `null` for any other token.
139
+ */
140
+ declare function verifyToken(secret: string, token: string, appId: string, access: Access): Promise<{
141
+ workspaceId: string;
142
+ } | null>;
143
+
144
+ /**
145
+ * `@app-assistant/host/server`: an app's side of the app-assistant contract (docs/integration.md) on Web
146
+ * Request/Response, for Cloudflare Workers, Next.js, Hono, Deno and Node 20+. Web Crypto and fetch only.
147
+ */
148
+
149
+ interface AssistantHost {
150
+ /** Your routes' answer, or `null` when the request isn't for `{basePath}/*` or the pack: pass it on. */
151
+ handle(req: Request): Promise<Response | null>;
152
+ /** A token for a signed-in user's workspace (`draft` to chat, `delete` to delete their data), 1 hour by default. */
153
+ signToken(workspaceId: string, access: Access, ttlSeconds?: number): Promise<string>;
154
+ /** `fetch(botUrl + path)` as the workspace: adds `Authorization: Bearer <a fresh token>`. */
155
+ botFetch(workspaceId: string, path: string, init?: RequestInit): Promise<Response>;
156
+ /** The events of a chat message's Server-Sent Events answer. */
157
+ readEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<BotEvent>;
158
+ }
159
+ declare function createAssistantHost(opts: HostOptions): AssistantHost;
160
+
161
+ export { createAssistantHost, readEvents, signToken, verifyToken };
162
+ export type { Access, AppContext, AssistantHost, BotEvent, ChargeResult, DraftInput, HostOptions, SavedDraft, TokenClaims };
@@ -0,0 +1,350 @@
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, schedule_at } = body;
282
+ if (!isText(text)) throw new Refused(400, "invalid", "The draft is empty.");
283
+ if (schedule_at !== void 0 && schedule_at !== null && !isText(schedule_at))
284
+ throw new Refused(400, "invalid", "schedule_at must be an ISO time.");
285
+ if (!isStrings(thread)) throw new Refused(400, "invalid", "thread must be a list of posts.");
286
+ const fields = ["url", "alt", "mime"];
287
+ if (!Array.isArray(media) || !media.every((m) => isObject(m) && fields.every((f) => typeof m[f] === "string")))
288
+ throw new Refused(400, "invalid", "media must be a list of {url, alt, mime}.");
289
+ const draft = {
290
+ text,
291
+ thread,
292
+ media: media.map((m) => ({ url: m.url, alt: m.alt, mime: m.mime }))
293
+ };
294
+ if (isText(schedule_at)) draft.schedule_at = schedule_at;
295
+ return async () => {
296
+ const saved = await opts.saveDraft(ws, draft, key);
297
+ if (!isObject(saved) || !isText(saved.draft_id))
298
+ throw new WrongAnswer("saveDraft() must return {draft_id, edit_url}");
299
+ const editUrl = saved.edit_url ?? null;
300
+ if (editUrl !== null && typeof editUrl !== "string")
301
+ throw new WrongAnswer("saveDraft()'s edit_url is a string or null");
302
+ const answer = { draft_id: saved.draft_id, edit_url: editUrl };
303
+ if (draft.schedule_at !== void 0) {
304
+ const at = saved.scheduled_at ?? null;
305
+ if (at !== null && !isText(at)) throw new WrongAnswer("saveDraft()'s scheduled_at is a string or null");
306
+ answer.scheduled_at = at;
307
+ if (at === null && isText(saved.schedule_note)) answer.schedule_note = saved.schedule_note;
308
+ }
309
+ return answer;
310
+ };
311
+ }
312
+ if (name === "material") {
313
+ const { facts, draft_id } = body;
314
+ if (!isStrings(facts)) throw new Refused(400, "invalid", "facts must be a list of sentences.");
315
+ if (draft_id !== void 0 && draft_id !== null && typeof draft_id !== "string")
316
+ throw new Refused(400, "invalid", "draft_id must be a string.");
317
+ return async () => {
318
+ await opts.saveMaterial(ws, facts, draft_id ?? void 0, key);
319
+ return { ok: true };
320
+ };
321
+ }
322
+ const { cost_usd, ref } = body;
323
+ if (typeof cost_usd !== "number" || !Number.isFinite(cost_usd) || cost_usd < 0)
324
+ throw new Refused(400, "invalid", "cost_usd must be a number, 0 or more.");
325
+ if (!isText(ref)) throw new Refused(400, "invalid", "ref is missing.");
326
+ return async () => {
327
+ const result = await opts.charge(ws, cost_usd, ref);
328
+ if (isObject(result) && result.ok === true) return { ok: true };
329
+ if (isObject(result) && isText(result.outOfCredits)) throw new Refused(402, "out_of_credits", result.outOfCredits);
330
+ throw new WrongAnswer("charge() must return {ok: true} or {outOfCredits: message}");
331
+ };
332
+ }
333
+
334
+ // src/server/index.ts
335
+ function createAssistantHost(opts) {
336
+ if (typeof opts.appId !== "string" || opts.appId === "") throw new TypeError("app-assistant: appId is empty");
337
+ if (typeof opts.secret !== "string" || opts.secret === "") throw new TypeError("app-assistant: secret is empty");
338
+ return {
339
+ handle: createHandler(opts),
340
+ signToken: (workspaceId, access, ttlSeconds) => signToken(opts.secret, { appId: opts.appId, workspaceId, access, ttlSeconds }),
341
+ botFetch: (workspaceId, path, init) => botFetch(opts, workspaceId, path, init),
342
+ readEvents
343
+ };
344
+ }
345
+ export {
346
+ createAssistantHost,
347
+ readEvents,
348
+ signToken,
349
+ verifyToken
350
+ };
package/package.json CHANGED
@@ -1,6 +1,59 @@
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.2.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": "MIT",
6
+ "homepage": "https://github.com/mikedutuandu/app-assistant/tree/main/sdk/js#readme",
7
+ "bugs": "https://github.com/mikedutuandu/app-assistant/issues",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mikedutuandu/app-assistant.git",
11
+ "directory": "sdk/js"
12
+ },
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "exports": {
19
+ "./server": {
20
+ "types": "./dist/server/index.d.ts",
21
+ "import": "./dist/server/index.js"
22
+ },
23
+ "./react": {
24
+ "types": "./dist/react/index.d.ts",
25
+ "import": "./dist/react/index.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "engines": {
30
+ "node": ">=20"
31
+ },
32
+ "scripts": {
33
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
34
+ "build": "tsup",
35
+ "test": "vitest run",
36
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
37
+ "prepublishOnly": "npm test && npm run build"
38
+ },
39
+ "peerDependencies": {
40
+ "react": ">=18"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "react": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "@testing-library/react": "^16.3.3",
49
+ "@types/node": "^22.20.5",
50
+ "@types/react": "^19.3.0",
51
+ "@types/react-dom": "^19.3.0",
52
+ "jsdom": "^31.0.1",
53
+ "react": "^19.3.1",
54
+ "react-dom": "^19.3.1",
55
+ "tsup": "^9.0.0",
56
+ "typescript": "~6.0.3",
57
+ "vitest": "^5.1.1"
58
+ }
59
+ }