utter-sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js ADDED
@@ -0,0 +1,152 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ export * from "./types.js";
3
+ export class UtterError extends Error {
4
+ }
5
+ const MAX_AGE_MS = 5 * 60_000;
6
+ // Utter's address, unless UTTER_URL or the url option says otherwise.
7
+ const DEFAULT_URL = "https://app.utter.talk";
8
+ const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } });
9
+ export function createUtter(opts) {
10
+ const url = (opts.url ?? process.env.UTTER_URL ?? DEFAULT_URL).replace(/\/+$/, "");
11
+ const project = opts.project ?? process.env.UTTER_PROJECT ?? "";
12
+ const secret = opts.secret ?? process.env.UTTER_SECRET ?? "";
13
+ /* ---- Calling Utter for one signed-in person ---- */
14
+ // One session per person, reused until 5 minutes before Utter says it expires.
15
+ const sessions = new Map();
16
+ const sessionKey = (viewer) => `${viewer.tenant.id}:${viewer.user.id}`;
17
+ async function session(viewer) {
18
+ const key = sessionKey(viewer);
19
+ const hit = sessions.get(key);
20
+ if (hit && hit.until > Date.now())
21
+ return hit.token;
22
+ const res = await fetch(`${url}/api/v1/sessions`, {
23
+ method: "POST",
24
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${secret}`, "X-Utter-Project": project },
25
+ body: JSON.stringify(viewer),
26
+ cache: "no-store",
27
+ }).catch(() => null);
28
+ if (!res)
29
+ throw new UtterError("Utter is not reachable.");
30
+ const data = (await res.json().catch(() => ({})));
31
+ if (!res.ok || !data.token)
32
+ throw new UtterError(data.error ?? `Utter is not reachable (HTTP ${res.status}).`);
33
+ const until = (typeof data.expiresAt === "number" ? data.expiresAt : Date.now() + 3_600_000) - 5 * 60_000;
34
+ sessions.set(key, { token: data.token, until });
35
+ return data.token;
36
+ }
37
+ async function call(viewer, path, body, retried = false) {
38
+ const token = await session(viewer);
39
+ const res = await fetch(`${url}/api/v1${path}`, {
40
+ method: body === undefined ? "GET" : "POST",
41
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
42
+ body: body === undefined ? undefined : JSON.stringify(body),
43
+ cache: "no-store",
44
+ }).catch(() => null);
45
+ if (!res)
46
+ throw new UtterError("Utter is not reachable.");
47
+ // A session Utter no longer accepts: forget it and try once more with a new one.
48
+ if (res.status === 401 && !retried) {
49
+ sessions.delete(sessionKey(viewer));
50
+ return call(viewer, path, body, true);
51
+ }
52
+ const data = (await res.json().catch(() => ({})));
53
+ if (!res.ok)
54
+ throw new UtterError(data.error ?? `Utter error (HTTP ${res.status}).`);
55
+ return data;
56
+ }
57
+ function client(viewer) {
58
+ return {
59
+ status: () => call(viewer, "/status"),
60
+ ask: (conversation) => call(viewer, "/ask", { conversation }),
61
+ confirm: (plan, sig) => call(viewer, "/confirm", { plan, sig }),
62
+ cancel: (plan, sig) => call(viewer, "/cancel", { plan, sig }),
63
+ activity: (o = {}) => {
64
+ const q = new URLSearchParams();
65
+ if (o.before)
66
+ q.set("before", o.before);
67
+ if (o.limit)
68
+ q.set("limit", String(o.limit));
69
+ return call(viewer, `/activity${q.size ? `?${q}` : ""}`);
70
+ },
71
+ };
72
+ }
73
+ /* ---- Answering Utter, and the browser ---- */
74
+ function verified(req, body) {
75
+ const ts = req.headers.get("x-utter-timestamp") ?? "";
76
+ const sig = req.headers.get("x-utter-signature") ?? "";
77
+ if (!secret || !ts || !sig || Math.abs(Date.now() - Number(ts)) > MAX_AGE_MS)
78
+ return false;
79
+ const expected = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");
80
+ const a = Buffer.from(sig);
81
+ const b = Buffer.from(expected);
82
+ return a.length === b.length && timingSafeEqual(a, b);
83
+ }
84
+ // Utter runs one of the product's actions for one company and one of its people.
85
+ async function handleCall(req) {
86
+ const raw = await req.text();
87
+ if (!verified(req, raw))
88
+ return json({ ok: false, error: "Bad signature." }, 401);
89
+ let input;
90
+ try {
91
+ input = JSON.parse(raw);
92
+ }
93
+ catch {
94
+ return json({ ok: false, error: "Bad request." }, 400);
95
+ }
96
+ const { tenantId = "", userId = "", op = "", args = [] } = input;
97
+ if (!tenantId || !userId || !(await opts.isMember(tenantId, userId))) {
98
+ return json({ ok: false, error: "That person isn't part of that company." }, 403);
99
+ }
100
+ // Only actions that are both on the action list and implemented, never names every object has (like "constructor").
101
+ const listed = opts.manifest.actions.some((a) => a.name === op);
102
+ const action = listed && Object.hasOwn(opts.actions, op) ? opts.actions[op] : undefined;
103
+ if (!action)
104
+ return json({ ok: false, error: `Unknown action: ${op}` }, 400);
105
+ try {
106
+ const result = await action({ tenantId, userId }, ...(Array.isArray(args) ? args : []));
107
+ return json({ ok: true, result: JSON.parse(JSON.stringify(result ?? null)) });
108
+ }
109
+ catch (e) {
110
+ return json({ ok: false, error: e.message }, 400);
111
+ }
112
+ }
113
+ // Browser routes: the product's own screens, signed in with the product's own login.
114
+ async function handleBrowser(req, path, method) {
115
+ const viewer = opts.getViewer ? await opts.getViewer(req) : null;
116
+ if (!viewer)
117
+ return json({ error: "Not signed in." }, 401);
118
+ if (path.length !== 1)
119
+ return json({ error: "Not found." }, 404);
120
+ const c = client(viewer);
121
+ const b = method === "GET" ? {} : (await req.json().catch(() => ({})));
122
+ const [first] = path;
123
+ try {
124
+ if (method === "GET" && first === "status")
125
+ return json(await c.status());
126
+ if (method === "POST" && first === "ask")
127
+ return json(await c.ask(b.conversation ?? []));
128
+ if (method === "POST" && first === "confirm")
129
+ return json(await c.confirm(String(b.plan ?? ""), String(b.sig ?? "")));
130
+ if (method === "POST" && first === "cancel")
131
+ return json(await c.cancel(String(b.plan ?? ""), String(b.sig ?? "")));
132
+ if (method === "GET" && first === "activity") {
133
+ const q = new URL(req.url).searchParams;
134
+ return json(await c.activity({ before: q.get("before") ?? undefined, limit: Number(q.get("limit")) || undefined }));
135
+ }
136
+ return json({ error: "Not found." }, 404);
137
+ }
138
+ catch (e) {
139
+ return json({ error: e.message }, e instanceof UtterError ? 502 : 500);
140
+ }
141
+ }
142
+ const route = (method) => async (req, ctx) => {
143
+ const path = (await ctx.params).path ?? [];
144
+ if (method === "GET" && path[0] === "manifest" && path.length === 1) {
145
+ return verified(req, "") ? json(opts.manifest) : json({ error: "Bad signature." }, 401);
146
+ }
147
+ if (method === "POST" && path[0] === "call" && path.length === 1)
148
+ return handleCall(req);
149
+ return handleBrowser(req, path, method);
150
+ };
151
+ return { client, handler: { GET: route("GET"), POST: route("POST") } };
152
+ }
@@ -0,0 +1,72 @@
1
+ export type Viewer = {
2
+ tenant: {
3
+ id: string;
4
+ name: string;
5
+ };
6
+ user: {
7
+ id: string;
8
+ name: string;
9
+ title?: string | null;
10
+ };
11
+ };
12
+ export type ActionInfo = {
13
+ name: string;
14
+ description: string;
15
+ args: string;
16
+ returns: string;
17
+ writes?: boolean;
18
+ };
19
+ export type Manifest = {
20
+ app: string;
21
+ description: string;
22
+ types: string;
23
+ actions: ActionInfo[];
24
+ };
25
+ export type Turn = {
26
+ role: "user" | "assistant";
27
+ text: string;
28
+ };
29
+ export type AskResult = {
30
+ kind: "answer";
31
+ text: string;
32
+ list: string[];
33
+ } | {
34
+ kind: "question";
35
+ text: string;
36
+ } | {
37
+ kind: "confirm";
38
+ text: string;
39
+ steps: string[];
40
+ plan: string;
41
+ sig: string;
42
+ } | {
43
+ kind: "error";
44
+ text: string;
45
+ };
46
+ export type ConfirmResult = {
47
+ kind: "answer";
48
+ text: string;
49
+ list: string[];
50
+ done?: number;
51
+ failed?: number;
52
+ } | {
53
+ kind: "error";
54
+ text: string;
55
+ };
56
+ export type ActivityEntry = {
57
+ id: string;
58
+ at: string;
59
+ tenant: {
60
+ id: string;
61
+ name: string;
62
+ };
63
+ who: string;
64
+ asked: string;
65
+ kind: "answer" | "question" | "confirm" | "confirmed" | "cancelled" | "error";
66
+ ok: boolean;
67
+ reply: string | null;
68
+ summary: string;
69
+ changes: string[];
70
+ failed: string[];
71
+ ms: number | null;
72
+ };
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ // Types shared by the server and browser parts of utter-sdk. Safe to use anywhere.
2
+ export {};
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "utter-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "The voice button for your product: your users say what they want, and Utter does it inside your app.",
5
+ "license": "MIT",
6
+ "homepage": "https://www.utter.talk",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/uttertalk/sdk.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/uttertalk/sdk/issues"
13
+ },
14
+ "keywords": [
15
+ "saas",
16
+ "voice",
17
+ "assistant",
18
+ "ai",
19
+ "speech",
20
+ "react",
21
+ "nextjs",
22
+ "cli",
23
+ "claude-code",
24
+ "cursor"
25
+ ],
26
+ "type": "module",
27
+ "bin": {
28
+ "utter-sdk": "dist/cli.js"
29
+ },
30
+ "exports": {
31
+ "./server": {
32
+ "types": "./dist/server.d.ts",
33
+ "default": "./dist/server.js"
34
+ },
35
+ "./react": {
36
+ "types": "./dist/react.d.ts",
37
+ "default": "./dist/react.js"
38
+ },
39
+ "./types": {
40
+ "types": "./dist/types.d.ts",
41
+ "default": "./dist/types.js"
42
+ }
43
+ },
44
+ "files": [
45
+ "dist",
46
+ "skill",
47
+ "README.md",
48
+ "LICENSE"
49
+ ],
50
+ "scripts": {
51
+ "build": "tsc -p tsconfig.json",
52
+ "prepublishOnly": "npm run build",
53
+ "test": "npm run build && node --test test/server.test.mjs test/cli.test.mjs"
54
+ },
55
+ "engines": {
56
+ "node": ">=18"
57
+ },
58
+ "peerDependencies": {
59
+ "react": ">=18"
60
+ },
61
+ "peerDependenciesMeta": {
62
+ "react": {
63
+ "optional": true
64
+ }
65
+ },
66
+ "devDependencies": {
67
+ "@types/node": "^20",
68
+ "@types/react": "^19",
69
+ "typescript": "^5"
70
+ }
71
+ }
package/skill/SKILL.md ADDED
@@ -0,0 +1,142 @@
1
+ ---
2
+ name: utter
3
+ description: Connect this app to Utter (utter-sdk), the voice button for SaaS, so its users can say what they want and Utter does it inside the app. Use when asked to set up, finish, fix or extend Utter, the Utter button, the Utter action list, or lib/utter.ts.
4
+ ---
5
+
6
+ # Set up Utter in this app
7
+
8
+ Utter is a voice and typing button for this app. A signed-in person presses the mic (or types) and says what they want: "move my stale leads to Cold", "which deals close this month?". Utter answers out loud, or does it inside the app, as that person, using only the actions this app lists. Anything that changes data is shown to the person as a plan first and only runs after they say yes. Utter never sees the database or the code.
9
+
10
+ `npx utter-sdk init` already did the mechanical part: the keys are in the env file, the package is installed, and there's an `utter` file (usually `lib/utter.ts`) plus a catch-all route (`app/api/utter/[...path]/route.ts`). Your job is to fill in the `utter` file and put the button on screen. Work through the steps in order and show the developer what you changed.
11
+
12
+ ## 1. Learn the app
13
+
14
+ Before writing anything, find:
15
+
16
+ - **The data**: the ORM or database layer (Prisma, Drizzle, TypeORM, Mongoose, Supabase, SQL, an internal API) and the main records people work with (leads, orders, tickets, projects…).
17
+ - **Tenancy**: how a customer company is represented (`organizationId`, `workspaceId`, `teamId`, `accountId`…) and how a user belongs to one. Every action must be limited to one company.
18
+ - **Login**: how the server knows who is signed in (Auth.js/NextAuth `auth()`, Clerk `auth()`/`currentUser()`, Supabase `getUser()`, Lucia, iron-session, a custom cookie…).
19
+ - **The screens**: the signed-in layout (where the button goes) and how pages load their data (so they can refresh after Utter changes something).
20
+ - **What people do all day**: the tasks they repeat in this app. Those are the actions worth listing.
21
+
22
+ If something important is unclear (for example two possible tenant fields), ask the developer instead of guessing.
23
+
24
+ ## 2. Write the action list
25
+
26
+ The action list (`manifest`) is everything Utter's AI knows about the app. Keep it small and true.
27
+
28
+ ```ts
29
+ manifest: {
30
+ app: "Acme CRM", // the product's name
31
+ description: "A CRM for small sales teams.", // one or two plain sentences
32
+ types: `type Lead = { id: string; name: string; company: string; value: number; status: "new" | "qualified" | "won" | "lost"; ownerId: string | null; lastContactAt: string | null }
33
+ type User = { id: string; name: string }`,
34
+ actions: [
35
+ { name: "leads.list", description: "The company's leads, newest first, optionally filtered by status or a search", args: "(opts?: { status?: Lead[\"status\"]; q?: string })", returns: "Lead[]" },
36
+ { name: "leads.get", description: "One lead", args: "(id: string)", returns: "Lead | null" },
37
+ { name: "users.list", description: "The company's team (possible owners)", args: "()", returns: "User[]" },
38
+ { name: "leads.update", description: "Change a lead's status, value or owner", args: "(id: string, patch: { status?: Lead[\"status\"]; value?: number; ownerId?: string | null })", returns: "Lead", writes: true },
39
+ ],
40
+ }
41
+ ```
42
+
43
+ Rules:
44
+
45
+ - **Reading actions first.** Cover the main records with list and get actions, with simple filters (status, search, date range) so Utter doesn't have to read everything. These run right away and change nothing.
46
+ - **A few safe writes.** Add only actions that are safe and useful to do by voice: change a status, assign an owner, add a note, log a call, set a due date. Mark every action that changes data with `writes: true`. Utter shows those to the person as a plan and only runs them after a yes.
47
+ - **Leave out by default**: deleting anything, billing and payments, users, roles and permissions, sending email or messages to people outside the company, exports, and anything the developer wouldn't want done by voice. When unsure, leave it out and mention it.
48
+ - **types** are TypeScript types of what actions take and return, as plain JSON (dates as ISO strings). Only fields that are useful and safe to show. Leave out password hashes, tokens, internal notes, card numbers and anything secret.
49
+ - Names are `thing.verb` (`leads.list`, `notes.create`). `args` is the argument list in parentheses, `"()"` for none. Descriptions are one plain sentence; say what filters do and what order results come in.
50
+ - Lists should return a sensible amount (cap at a few hundred). Utter reads results, so smaller is faster and cheaper.
51
+
52
+ ## 3. Write the actions
53
+
54
+ One function per action in `actions`, using the app's own data layer. Each gets `{ tenantId, userId }` first, then the action's arguments.
55
+
56
+ ```ts
57
+ actions: {
58
+ "leads.list": ({ tenantId }, opts) => {
59
+ const o = (opts ?? {}) as { status?: string; q?: string };
60
+ return db.lead.findMany({
61
+ where: { orgId: tenantId, status: o.status, name: o.q ? { contains: String(o.q) } : undefined },
62
+ orderBy: { createdAt: "desc" },
63
+ take: 300,
64
+ });
65
+ },
66
+ "leads.update": async ({ tenantId }, id, patch) => {
67
+ const p = (patch ?? {}) as { status?: string; value?: number; ownerId?: string | null };
68
+ // Only the fields the action list promises, and only inside this company.
69
+ return db.lead.update({ where: { id: String(id), orgId: tenantId }, data: { status: p.status, value: p.value, ownerId: p.ownerId } });
70
+ },
71
+ },
72
+ ```
73
+
74
+ Rules:
75
+
76
+ - **Always filter by `tenantId`**, in reads and in writes. Never take a company id from the arguments.
77
+ - Treat arguments as untrusted input: check types, allow only the fields the action list describes, cap list sizes. Throw an `Error` with a plain message when something's wrong ("No lead with that id."); Utter reads it out.
78
+ - If the app has roles, check that `userId` may do this, the same way the app's own API does.
79
+ - Return plain JSON that matches `types`. Reuse the app's existing service functions where they exist, so its own rules (validation, audit logs, webhooks) still apply.
80
+
81
+ ## 4. Sign-in: getViewer and isMember
82
+
83
+ ```ts
84
+ // Is this person part of this company? Utter only acts as real members.
85
+ isMember: async (tenantId, userId) => Boolean(await db.membership.findFirst({ where: { orgId: tenantId, userId } })),
86
+
87
+ // Who is signed in, from the request, with the app's own login. null when nobody is.
88
+ getViewer: async (req) => {
89
+ const session = await auth(); // whatever the app already uses
90
+ if (!session?.user) return null;
91
+ return {
92
+ tenant: { id: session.user.orgId, name: session.user.orgName },
93
+ user: { id: session.user.id, name: session.user.name ?? session.user.email, title: session.user.role },
94
+ };
95
+ },
96
+ ```
97
+
98
+ Use the app's existing helper for the current user. `getViewer` receives the standard `Request`, so cookie- or header-based logins work too. The user's name and title help Utter talk naturally ("assign it to me").
99
+
100
+ ## 5. Put the button on screen
101
+
102
+ Once, in the signed-in layout, in a client component:
103
+
104
+ ```tsx
105
+ "use client";
106
+ import { useEffect } from "react";
107
+ import { useRouter } from "next/navigation";
108
+ import { Utter, CHANGED_EVENT } from "utter-sdk/react";
109
+
110
+ export function UtterButton() {
111
+ const router = useRouter();
112
+ // After Utter changes something, reload the page's data so the change shows.
113
+ useEffect(() => {
114
+ const refresh = () => router.refresh();
115
+ window.addEventListener(CHANGED_EVENT, refresh);
116
+ return () => window.removeEventListener(CHANGED_EVENT, refresh);
117
+ }, [router]);
118
+ return <Utter app="Acme CRM" examples={["Which deals close this month?", "Move my stale leads to Cold"]} />;
119
+ }
120
+ ```
121
+
122
+ - Write two or three `examples` that fit this app and work with the actions you listed.
123
+ - If pages load data on the client (SWR, React Query), refresh those instead of `router.refresh()` (for example `mutate()` or `queryClient.invalidateQueries()`).
124
+ - The button stays hidden until the owner switches Utter on in the dashboard, so it's safe to deploy first.
125
+ - Match the app's look with CSS variables on a parent: `--utter-accent`, `--utter-accent-ink`, `--utter-bg`, `--utter-ink`, `--utter-muted`, `--utter-line`, `--utter-soft`. `position="bottom-left"` moves it. Or build your own with the hooks `useUtter()`, `useVoice()` and `useUtterStatus()`.
126
+
127
+ ## 6. Check it
128
+
129
+ 1. Typecheck or build the app.
130
+ 2. Start the app and run `npx utter-sdk check`. It reads the keys from the env file, fetches the action list from the running app with a signed request, and checks it. Add `--app http://localhost:3001` if the app runs elsewhere, and `--tenant <id> --user <id>` (a real company and one of its members) to also run each reading action whose arguments are all optional.
131
+ 3. Fix whatever it reports and run it again.
132
+
133
+ ## 7. Hand back
134
+
135
+ Tell the developer, briefly:
136
+
137
+ - what Utter can read and change (the actions), and anything you left out on purpose
138
+ - which files you changed
139
+ - that Utter calls the app at the address set in the dashboard, so it must be public (https) for production; for local testing, a tunnel works
140
+ - that they switch it on in the Utter dashboard (app.utter.talk/dashboard), where the checklist shows what's left, then try it themselves: press the button and say one of the examples
141
+
142
+ Docs: https://app.utter.talk/docs · Setup guide: https://app.utter.talk/setup