@tyvm/knowhow-app-sdk 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,142 @@
1
- # Temporary Holding Version
1
+ # @tyvm/knowhow-app-sdk
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
+ Ergonomic SDK for apps running inside Knowhow (iframe), or in a browser with the Knowhow extension.
4
+ **Bundle it with your app** (pin the version). Apps are served from their own per-app
5
+ usercontent origin (never the Knowhow origin), so browser storage is per-device and not shared with your
6
+ account: use `knowhow.kv` / `knowhow.db` for anything that should persist.
7
+
8
+ ```ts
9
+ import { knowhow } from "@tyvm/knowhow-app-sdk";
10
+
11
+ // knowhow.mock(); // in-memory provider for local dev (kv/files/ai; db needs a handler)
12
+ await knowhow.ready();
13
+ const session = await knowhow.connect(["db:app", "tools:expose"]);
14
+ await knowhow.db.exec("create table if not exists notes(id integer primary key, text text)");
15
+ await knowhow.db.exec("insert into notes(text) values (?)", ["hello"]);
16
+ const { rows } = await knowhow.db.query("select * from notes");
17
+ await knowhow.kv.set("theme", "dark");
18
+ const { content } = await knowhow.ai.complete({ messages: [{ role: "user", content: "Summarize…" }] });
19
+ // Speech-to-text (capability "ai:transcribe"): base64 / data-URL audio, <= 25 MB decoded
20
+ const t = await knowhow.ai.transcribe({ audio: "data:audio/mpeg;base64,...", fileName: "audio.mp3" });
21
+ // t = { text, language?, duration?, model, segments: [{start,end,text}], words: [{start,end,word}] }
22
+ // Image generation (capability "ai:image"): n <= 4
23
+ const { images } = await knowhow.ai.image({ prompt: "a cozy cabin at dusk", size: "1024x1792" });
24
+ // images[0] = { dataUrl?: "data:image/png;base64,...", url?, revisedPrompt? }
25
+ await knowhow.tools.register({
26
+ name: "notes_add", description: "Add a note",
27
+ parameters: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
28
+ handler: async ({ text }) => { await knowhow.db.exec("insert into notes(text) values (?)", [String(text)]); return { ok: true }; },
29
+ });
30
+ knowhow.on("sessionChanged", (s) => console.log(s));
31
+ ```
32
+
33
+ Single-file HTML apps can use the IIFE build: `<script src=".../knowhow-sdk.iife.js">` → `window.KnowhowSDK.knowhow`.
34
+
35
+ Provider discovery order: announced/injected provider → iframe handshake (`kh:hello` to `window.parent`,
36
+ host transfers a `MessagePort` in `kh:port`) → error (or mock if `knowhow.mock()` was called).
37
+ Calls auto-connect if there is no session yet, and feature-detect through `kh_protocol().methods`.
38
+
39
+ ## Connecting from a normal tab (extension / desktop)
40
+
41
+ Iframe hosts already know which app they loaded. Injected providers (Chrome extension, desktop shell)
42
+ don't, so the app must claim an app id or alias — it is resolved server-side and shown on the consent popup:
43
+
44
+ ```ts
45
+ knowhow.configure({ appId: "notes" }); // or <meta name="knowhow-app-id" content="notes">
46
+ const host = await knowhow.detect(); // "embedded" | "injected" | "none" | "mock" — never prompts
47
+ if (host.kind === "embedded") await knowhow.connect(caps);
48
+ else if (host.kind === "injected") showConnectButton(() => knowhow.connect(caps)); // user gesture → consent
49
+ else showOpenInKnowhowOrMock();
50
+ ```
51
+
52
+
53
+ ## Self-hosted sites (no Knowhow app entry)
54
+
55
+ Any website — your own domain, GitHub Pages, `localhost` — can use Knowhow AI for its *visitors* without
56
+ registering an app. Just don't claim an app id: with the Knowhow Chrome extension installed, `connect()`
57
+ opens a **site session** identified by the page's real origin (taken by the extension from Chrome, never from
58
+ the page).
59
+
60
+ ```ts
61
+ import { knowhow } from "@tyvm/knowhow-app-sdk";
62
+
63
+ if ((await knowhow.detect()).kind === "injected") {
64
+ // call from a click handler: the extension shows a consent popup for this origin
65
+ const s = await knowhow.connect(["ai:complete", "db:app"]); // no appId
66
+ console.log(s.site?.origin, s.appId); // "https://you.example", "site:https://you.example"
67
+ const r = await knowhow.ai.complete({ messages: [{ role: "user", content: "Summarize this page" }] });
68
+ await knowhow.kv.set("lastSummary", r.content); // private to (this visitor, this site)
69
+ }
70
+ ```
71
+
72
+ - The visitor sees "**<origin>** wants to use your Knowhow account" (labelled *unverified website*), can tick
73
+ "Remember for this site", and can revoke any time from the extension.
74
+ - Allowed capabilities: `ai:complete`, `ai:transcribe`, `ai:image` (billed to the **visitor**, subject to
75
+ per-site daily caps) and `db:app` (a private SQLite store per visitor + site). `tools:expose` works too (host
76
+ only; tool names are namespaced from the hostname, e.g. `app_blog_example_com_<tool>`), and `files:app`
77
+ (scoped storage, see "Files" below). Other capabilities are rejected with an invalid-params error.
78
+ - No capabilities requested → defaults to `["ai:complete", "db:app"]`.
79
+ - Check `session.site` to tell a site session from a registered app session; `session.appId` is `site:<origin>`.
80
+ - Daily caps return a rate-limited error (`ErrorCodes.RATE_LIMITED`, 4290) — handle it and tell the visitor.
81
+ - Iframe hosts (the Knowhow website) still require a registered app.
82
+
83
+ ## Outside servers (`network.connect`)
84
+
85
+ Apps hosted by Knowhow (`*.apps.tyvm-usercontent.com`) run under a strict Content-Security-Policy.
86
+ By default the page may only make requests (fetch/XHR/WebSocket, `<img>`, `<video>`/`<audio>`) to:
87
+
88
+ - its own origin, and
89
+ - Knowhow storage (the presigned URLs `knowhow.files.*` uploads to / downloads from).
90
+
91
+ `https:` in general is **not** allowed, not even for images, so an app can't quietly send
92
+ your users' data somewhere. If your app talks to its own API (or any other server), declare it in
93
+ `knowhow.app.json`:
94
+
95
+ ```json
96
+ {
97
+ "capabilities": ["db:app"],
98
+ "network": {
99
+ "connect": ["https://api.myapp.com", "wss://realtime.myapp.com", "https://*.cdn.myapp.com/images/"]
100
+ }
101
+ }
102
+ ```
103
+
104
+ - Entries are `https://` or `wss://` origins, optionally with a `*.` subdomain wildcard and/or a path
105
+ prefix. No `http:`, IPs, `localhost`, bare `*`, query strings, max 20 entries.
106
+ - Each user is asked once per server ("This app sends data to api.myapp.com"), can untick servers
107
+ they don't want, and can later allow / block / "ask again" per server under **Permissions**.
108
+ - Only servers the viewing user allowed are added to the CSP (`connect-src`; `https` ones also to
109
+ `img-src`/`media-src`). Blocked or undecided servers fail like any CSP violation (a network error).
110
+ - Decisions are about servers, not code: they carry over to new versions. A new version that adds a
111
+ server asks about that server only.
112
+ - The CSP is fixed when the page loads: changes apply on the next load.
113
+ - Scripts can never come from outside servers (`script-src 'self'`); bundle your dependencies.
114
+
115
+ ## Files (`files:app`) — app-sandboxed storage for registered apps and websites
116
+
117
+ ```ts
118
+ const info = await knowhow.files.put("media/clip.mp4", file, {
119
+ scope: "user", // "user" (default, private to you) | "org" (shared with the organization)
120
+ contentType: file.type,
121
+ onProgress: (loaded, total) => {},
122
+ });
123
+ const blob = await knowhow.files.get("media/clip.mp4", { range: { start: 0, end: 1023 } }); // range optional
124
+ const url = await knowhow.files.url("media/clip.mp4"); // presigned, e.g. <video src>
125
+ await knowhow.files.stat("media/clip.mp4"); // AppFileInfo | null
126
+ await knowhow.files.list("media", { scope: "user" }); // folder prefix, <= 1000 entries
127
+ await knowhow.files.delete("media/clip.mp4");
128
+ ```
129
+
130
+ - **Root.** Every path is relative to a root the backend derives from the verified session, never from the app:
131
+ a website gets `/apps/<host[:port]>[/<app-id>]` (the page's claimed app id is only a sub-folder label), a registered
132
+ app its own `<rootPath>/files`. The `user` scope is the same folder under `/users/<you>/…` and is stored as private
133
+ OrgFile rows. The consent dialog shows the root. `..`, absolute paths, backslashes/NULs are rejected (400); depth
134
+ <= 16, name <= 200 chars. OrgFile has no symlinks, so there is nothing to follow out of the root.
135
+ - **Large files.** `put` asks the backend for a presigned S3 PUT (`kh_files_upload_start`), PUTs the bytes straight to
136
+ S3 (XHR progress) and then verifies them (`kh_files_upload_complete`); nothing large goes through the provider.
137
+ `get` fetches a presigned URL (S3 Range requests work). Needs S3 CORS to allow the app's origin (PUT/GET/Range).
138
+ - **Limits.** One file <= 2^31-1 bytes (OrgFile.sizeBytes is a 32-bit int); each (scope, root) folder holds at most
139
+ 20 GiB (`KNOWHOW_APP_FILES_QUOTA_BYTES`); the org's normal storage billing/archival rules apply. Overwrites need
140
+ EDIT access and keep the previous version (OrgFile versions).
141
+ - `files.list(path)` **without** options and `files.read/write(text)` are the older text API on a registered app's
142
+ `data` folder (registered apps only).