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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Utter
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,154 @@
1
- # Temporary Holding Version
1
+ <img src="https://raw.githubusercontent.com/uttertalk/brand/main/cover.png" alt="Utter: the voice button for your product">
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
+ # utter-sdk
4
+
5
+ [![npm](https://img.shields.io/npm/v/utter-sdk?color=3341ff&labelColor=eceeff)](https://www.npmjs.com/package/utter-sdk)
6
+ ![Node](https://img.shields.io/badge/node-18%2B-3341ff?labelColor=eceeff)
7
+ ![React](https://img.shields.io/badge/react-18%2B-3341ff?labelColor=eceeff)
8
+ ![License: MIT](https://img.shields.io/badge/license-MIT-3341ff?labelColor=eceeff)
9
+ [![Tests](https://github.com/uttertalk/sdk/actions/workflows/test.yml/badge.svg)](https://github.com/uttertalk/sdk/actions/workflows/test.yml)
10
+
11
+ [Website](https://www.utter.talk) · [Setup guide](https://app.utter.talk/setup) · [Docs](https://app.utter.talk/docs) · [Example app](https://github.com/uttertalk/example-app)
12
+
13
+ The voice button for your product. Your users press the mic (or type) and say what they want. Utter does it inside
14
+ your app, as them, with only the actions you allow, and answers out loud. Anything that changes data waits for a yes.
15
+
16
+ ## Quick setup
17
+
18
+ ```
19
+ npx utter-sdk init
20
+ ```
21
+
22
+ Signs you in through the browser, saves the keys in `.env.local`, installs this package, creates `lib/utter.ts` and
23
+ the route, and adds an Utter skill for Claude Code, Codex and Cursor. Then ask your coding agent:
24
+ "Set up Utter in this app. Follow the utter skill." Check it with `npx utter-sdk check` and switch Utter on in the
25
+ dashboard.
26
+
27
+ The full guide, with the exact prompts to give your AI: https://app.utter.talk/setup
28
+
29
+ The steps below are the same setup by hand.
30
+
31
+ ```
32
+ npm install utter-sdk
33
+ ```
34
+
35
+ ## 1. Settings
36
+
37
+ Create a project at https://app.utter.talk/signup to get these. Keep the secret on your server.
38
+
39
+ ```
40
+ UTTER_PROJECT=your-project # your project id
41
+ UTTER_SECRET=... # signs every request between you and Utter
42
+ # UTTER_URL=... # only if you use a different Utter address
43
+ ```
44
+
45
+ ## 2. The action list and the route
46
+
47
+ ```ts
48
+ // lib/utter.ts
49
+ import { createUtter } from "utter-sdk/server";
50
+
51
+ export const utter = createUtter({
52
+ manifest: {
53
+ app: "Acme CRM",
54
+ description: "A CRM for small sales teams.",
55
+ types: "type Lead = { id: string; name: string; value: number; status: string; ownerId: string | null }",
56
+ actions: [
57
+ { name: "leads.list", description: "All leads", args: "()", returns: "Lead[]" },
58
+ { name: "leads.update", description: "Change a lead", args: "(id: string, patch: { status?: string })", returns: "Lead", writes: true },
59
+ ],
60
+ },
61
+ // Your own functions, run for one customer company (tenantId) and one person (userId).
62
+ actions: {
63
+ "leads.list": ({ tenantId }) => db.leads.findMany({ where: { tenantId } }),
64
+ "leads.update": ({ tenantId }, id, patch) => db.leads.update({ where: { id, tenantId }, data: patch }),
65
+ },
66
+ isMember: (tenantId, userId) => db.members.exists({ tenantId, userId }),
67
+ getViewer: async (req) => {
68
+ const user = await getSignedInUser(req);
69
+ return user && { tenant: { id: user.companyId, name: user.companyName }, user: { id: user.id, name: user.name } };
70
+ },
71
+ });
72
+ ```
73
+
74
+ ```ts
75
+ // app/api/utter/[...path]/route.ts
76
+ import { utter } from "@/lib/utter";
77
+ export const { GET, POST } = utter.handler;
78
+ ```
79
+
80
+ - Reading actions run right away. Actions with `writes: true` only run after the person says yes to a plan listing
81
+ every change.
82
+ - Every call from Utter is signed with your secret and checked here. Utter only acts as people `isMember` accepts,
83
+ inside their own company.
84
+
85
+ ## 3. The button
86
+
87
+ ```tsx
88
+ "use client";
89
+ import { Utter } from "utter-sdk/react";
90
+
91
+ <Utter app="Acme CRM" examples={["Which deals close this month?", "Move my stale leads to Cold"]} />
92
+ ```
93
+
94
+ Put it once in your signed-in layout. It stays hidden until you switch Utter on in the dashboard. Before that, only testers you pick there can see it.
95
+
96
+ After Utter changes something, the page gets a `utter:changed` event; refresh your data on it:
97
+
98
+ ```ts
99
+ window.addEventListener("utter:changed", () => router.refresh());
100
+ ```
101
+
102
+ Options: `app`, `examples`, `position` (`"bottom-right"` or `"bottom-left"`), `voice` (`false` to never speak),
103
+ `lang`, `basePath`. Colours: set `--utter-accent`, `--utter-accent-ink`, `--utter-bg`, `--utter-ink`,
104
+ `--utter-muted`, `--utter-line`, `--utter-soft` on a parent.
105
+
106
+ Your own look instead: `useUtter()` (turns, send, confirm, cancel), `useVoice()` (listen, speak) and
107
+ `useUtterStatus()`.
108
+
109
+ Voice uses the browser's own speech: listening works in Chrome, Edge and Safari; in other browsers the mic hides and
110
+ typing still works.
111
+
112
+ ## 4. Check it
113
+
114
+ ```
115
+ npx utter-sdk check --app http://localhost:3000 --tenant <company id> --user <user id>
116
+ ```
117
+
118
+ Checks the keys, reads your action list the way Utter does, and runs each reading action for that company and person.
119
+
120
+ ## How it works
121
+
122
+ 1. A signed-in person presses the button and speaks (or types). The browser turns speech into text.
123
+ 2. The button sends it to your route. Your route knows who is signed in through your login, and passes the request
124
+ on to Utter with a one-hour session for that person.
125
+ 3. Utter's AI reads your action list and runs reading actions right away, by calling your app back with a signed
126
+ request, as that person, inside their company.
127
+ 4. Actions that change data are never run at that point. Utter returns a plan listing every change, signed for that
128
+ person, and they say yes or no.
129
+ 5. On yes, Utter runs exactly those steps, once, and says what happened. Every request is logged in your dashboard.
130
+
131
+ ## Roadmap
132
+
133
+ Planned, not built yet:
134
+
135
+ - **Instant voice-to-voice**: answers in under half a second, with a natural voice you can interrupt
136
+ - **Every language**: talk to your app in 50+ languages and accents
137
+ - **Learns your app on its own**: no action list to write
138
+ - **Native mobile**: the same button in iOS and Android apps
139
+ - **Every backend**: server packages for Python, Ruby, Go, Java and PHP, next to Node
140
+
141
+ The full list, and how to help fund it, is on the [Utter GitHub page](https://github.com/uttertalk).
142
+
143
+ ## Development
144
+
145
+ ```
146
+ npm install
147
+ npm test # builds, then runs the tests against a fake Utter; no key needed
148
+ ```
149
+
150
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [SECURITY.md](SECURITY.md).
151
+
152
+ ## License
153
+
154
+ [MIT](LICENSE)
@@ -0,0 +1,6 @@
1
+ import type { Manifest } from "./types.ts";
2
+ export declare function parseEnv(text: string): Record<string, string>;
3
+ export declare function upsertEnv(text: string, values: Record<string, string>): string;
4
+ export declare function manifestProblems(m: Partial<Manifest> | null | undefined): string[];
5
+ export declare function canRunWithoutArgs(args: string): boolean;
6
+ export declare function signed(secret: string, body: string): Record<string, string>;
@@ -0,0 +1,103 @@
1
+ import { createHmac } from "node:crypto";
2
+ // Plain helpers for the command line (cli.ts), kept apart so the tests can use them.
3
+ // Reads KEY=value lines (quotes optional, # comments ignored).
4
+ export function parseEnv(text) {
5
+ const env = {};
6
+ for (const line of text.split(/\r?\n/)) {
7
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
8
+ if (!m)
9
+ continue;
10
+ let v = m[2];
11
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))
12
+ v = v.slice(1, -1);
13
+ else
14
+ v = v.replace(/\s+#.*$/, "");
15
+ env[m[1]] = v;
16
+ }
17
+ return env;
18
+ }
19
+ // Sets keys in an env file's text: replaces lines that are there, adds the rest at the end. Keeps everything else.
20
+ export function upsertEnv(text, values) {
21
+ const lines = text ? text.split(/\r?\n/) : [];
22
+ if (lines.length && lines[lines.length - 1] === "")
23
+ lines.pop();
24
+ const left = new Map(Object.entries(values));
25
+ const next = lines.map((line) => {
26
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
27
+ if (m && left.has(m[1])) {
28
+ const v = left.get(m[1]);
29
+ left.delete(m[1]);
30
+ return `${m[1]}=${v}`;
31
+ }
32
+ return line;
33
+ });
34
+ if (left.size) {
35
+ if (next.length && next[next.length - 1].trim() !== "")
36
+ next.push("");
37
+ next.push("# Utter (keep the secret out of git)");
38
+ for (const [k, v] of left)
39
+ next.push(`${k}=${v}`);
40
+ }
41
+ return `${next.join("\n")}\n`;
42
+ }
43
+ // What's wrong with an action list, in plain words. Empty when it's fine.
44
+ export function manifestProblems(m) {
45
+ if (!m || typeof m !== "object")
46
+ return ["The action list is missing."];
47
+ const p = [];
48
+ if (!m.app?.trim())
49
+ p.push("manifest.app is empty: give your product's name.");
50
+ if (!m.description?.trim())
51
+ p.push("manifest.description is empty: describe the app in a sentence or two.");
52
+ if (!m.types?.trim())
53
+ p.push("manifest.types is empty: add the TypeScript types your actions take and return.");
54
+ const actions = Array.isArray(m.actions) ? m.actions : [];
55
+ if (actions.length === 0)
56
+ p.push("manifest.actions is empty: list at least one action Utter may run.");
57
+ const names = new Set();
58
+ for (const a of actions) {
59
+ if (!a?.name) {
60
+ p.push("An action has no name.");
61
+ continue;
62
+ }
63
+ if (names.has(a.name))
64
+ p.push(`The action ${a.name} is listed twice.`);
65
+ names.add(a.name);
66
+ if (!a.description?.trim())
67
+ p.push(`The action ${a.name} has no description.`);
68
+ if (typeof a.args !== "string")
69
+ p.push(`The action ${a.name} needs args, like "()" or "(id: string)".`);
70
+ if (typeof a.returns !== "string" || !a.returns.trim())
71
+ p.push(`The action ${a.name} needs returns, like "Lead[]".`);
72
+ }
73
+ return p;
74
+ }
75
+ // Can an action with this argument list be called with no arguments? True for "()" and when every
76
+ // argument is optional, like "(opts?: { status?: string })".
77
+ export function canRunWithoutArgs(args) {
78
+ const inner = args.trim().replace(/^\(/, "").replace(/\)$/, "").trim();
79
+ if (!inner)
80
+ return true;
81
+ const params = [];
82
+ let depth = 0;
83
+ let current = "";
84
+ for (const ch of inner) {
85
+ if ("{[(<".includes(ch))
86
+ depth++;
87
+ if ("}])>".includes(ch))
88
+ depth--;
89
+ if (ch === "," && depth === 0) {
90
+ params.push(current);
91
+ current = "";
92
+ }
93
+ else
94
+ current += ch;
95
+ }
96
+ params.push(current);
97
+ return params.every((p) => /^\s*(\.\.\.)?[A-Za-z_$][\w$]*\s*\?/.test(p) || /^\s*\.\.\./.test(p));
98
+ }
99
+ export function signed(secret, body) {
100
+ const ts = String(Date.now());
101
+ const sig = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");
102
+ return { "X-Utter-Timestamp": ts, "X-Utter-Signature": sig };
103
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,390 @@
1
+ #!/usr/bin/env node
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs";
4
+ import { dirname, join, relative } from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { canRunWithoutArgs, manifestProblems, parseEnv, signed, upsertEnv } from "./cli-helpers.js";
7
+ // The command line for utter-sdk.
8
+ //
9
+ // npx utter-sdk init sign in, save the project's keys, install, add the route, add the agent skill
10
+ // npx utter-sdk check check the running app's action list (and optionally run its reading actions)
11
+ const DEFAULT_URL = "https://app.utter.talk";
12
+ const SKILL_FILE = new URL("../skill/SKILL.md", import.meta.url);
13
+ const out = (s = "") => process.stdout.write(`${s}\n`);
14
+ const bold = (s) => (process.stdout.isTTY ? `\x1b[1m${s}\x1b[0m` : s);
15
+ const dim = (s) => (process.stdout.isTTY ? `\x1b[2m${s}\x1b[0m` : s);
16
+ const good = (s) => out(` ${process.stdout.isTTY ? "\x1b[32m✓\x1b[0m" : "✓"} ${s}`);
17
+ const bad = (s) => out(` ${process.stdout.isTTY ? "\x1b[31m✗\x1b[0m" : "✗"} ${s}`);
18
+ const note = (s) => out(` ${dim("·")} ${s}`);
19
+ class Stop extends Error {
20
+ }
21
+ const stop = (msg) => {
22
+ throw new Stop(msg);
23
+ };
24
+ function readProject(root) {
25
+ const pkgPath = join(root, "package.json");
26
+ if (!existsSync(pkgPath))
27
+ stop("There's no package.json here. Run this in your app's folder.");
28
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
29
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
30
+ const next = Boolean(deps.next);
31
+ const base = existsSync(join(root, "src", "app")) || existsSync(join(root, "src", "pages")) ? "src" : "";
32
+ const appRouter = existsSync(join(root, base, "app"));
33
+ const envFile = existsSync(join(root, ".env.local")) || next ? ".env.local" : ".env";
34
+ return { root, pkg, ts: existsSync(join(root, "tsconfig.json")), next, base, appRouter, envFile };
35
+ }
36
+ function readEnv(root) {
37
+ const env = {};
38
+ for (const f of [".env", ".env.local"]) {
39
+ const p = join(root, f);
40
+ if (existsSync(p))
41
+ Object.assign(env, parseEnv(readFileSync(p, "utf8")));
42
+ }
43
+ return env;
44
+ }
45
+ function packageManager(root) {
46
+ if (existsSync(join(root, "pnpm-lock.yaml")))
47
+ return { cmd: "pnpm", add: ["add"] };
48
+ if (existsSync(join(root, "yarn.lock")))
49
+ return { cmd: "yarn", add: ["add"] };
50
+ if (existsSync(join(root, "bun.lockb")) || existsSync(join(root, "bun.lock")))
51
+ return { cmd: "bun", add: ["add"] };
52
+ return { cmd: "npm", add: ["install"] };
53
+ }
54
+ function writeNew(root, file, text) {
55
+ const p = join(root, file);
56
+ if (existsSync(p))
57
+ return false;
58
+ mkdirSync(dirname(p), { recursive: true });
59
+ writeFileSync(p, text);
60
+ return true;
61
+ }
62
+ /* ---- Signing in through the browser ---- */
63
+ function openBrowser(url) {
64
+ const [cmd, args] = process.platform === "win32"
65
+ ? ["cmd", ["/c", "start", '""', url]]
66
+ : process.platform === "darwin"
67
+ ? ["open", [url]]
68
+ : ["xdg-open", [url]];
69
+ try {
70
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true, windowsVerbatimArguments: process.platform === "win32" });
71
+ child.on("error", () => { });
72
+ child.unref();
73
+ }
74
+ catch {
75
+ // No browser to open (a server, a container): the link is printed anyway.
76
+ }
77
+ }
78
+ async function api(url, path, body, headers = {}) {
79
+ const res = await fetch(`${url}${path}`, {
80
+ method: "POST",
81
+ headers: { "Content-Type": "application/json", ...headers },
82
+ body: JSON.stringify(body),
83
+ }).catch(() => null);
84
+ if (!res)
85
+ stop(`Can't reach Utter at ${url}. Check your internet connection.`);
86
+ const data = (await res.json().catch(() => ({})));
87
+ return { status: res.status, data };
88
+ }
89
+ async function signIn(url, open) {
90
+ const { status, data } = await api(url, "/api/cli/start", {});
91
+ if (status !== 200 || !data.code || !data.url)
92
+ stop(data.error ?? `Utter couldn't start the sign-in (HTTP ${status}).`);
93
+ out(` Sign in and pick a project in your browser. Check it shows this code: ${bold(data.userCode)}`);
94
+ out(` ${dim(data.url)}`);
95
+ if (open)
96
+ openBrowser(data.url);
97
+ out();
98
+ const until = Date.now() + 10 * 60_000;
99
+ while (Date.now() < until) {
100
+ await new Promise((r) => setTimeout(r, 2000));
101
+ const poll = await api(url, "/api/cli/poll", { code: data.code });
102
+ if (poll.data.status === "approved" && poll.data.project)
103
+ return poll.data.project;
104
+ if (poll.data.status === "expired")
105
+ stop("The sign-in expired. Run the command again.");
106
+ if (poll.status >= 400 && poll.status !== 429)
107
+ stop(poll.data.error ?? `Utter said no (HTTP ${poll.status}).`);
108
+ }
109
+ return stop("The sign-in expired. Run the command again.");
110
+ }
111
+ /* ---- init ---- */
112
+ function libTemplate(p) {
113
+ const name = (p.pkg.name ?? "My app").replace(/^@[^/]+\//, "").replace(/[-_]+/g, " ");
114
+ const t = p.ts;
115
+ return `import { createUtter } from "utter-sdk/server";
116
+
117
+ // Connects this app to Utter: people press the mic (or type), and Utter does it here, as them,
118
+ // with only the actions listed below. Your AI coding agent can fill this in: ask it to
119
+ // "Set up Utter in this app. Follow the utter skill."
120
+ // Docs: https://app.utter.talk/docs
121
+ export const utter = createUtter({
122
+ manifest: {
123
+ app: ${JSON.stringify(name)},
124
+ // A sentence or two about the app.
125
+ description: "",
126
+ // Your data as TypeScript types, e.g. "type Lead = { id: string; name: string }".
127
+ types: "",
128
+ // What Utter may do. Mark actions that change data with writes: true; those always need a yes first.
129
+ actions: [],
130
+ },
131
+
132
+ // One function per action, always for one customer company (tenantId) and one person (userId).
133
+ actions: {},
134
+
135
+ // Is this person part of this company? Utter only acts as real members.
136
+ isMember: async (${t ? "_tenantId: string, _userId: string" : "_tenantId, _userId"}) => false,
137
+
138
+ // Who is signed in, with your own login. Return null when nobody is.
139
+ getViewer: async (${t ? "_req: Request" : "_req"}) => null,
140
+ });
141
+ `;
142
+ }
143
+ function routeTemplate(importPath) {
144
+ return `import { utter } from ${JSON.stringify(importPath)};
145
+
146
+ // Utter's signed calls (reading the action list, running actions) and your screens' calls.
147
+ export const { GET, POST } = utter.handler;
148
+ `;
149
+ }
150
+ const CURSOR_HEAD = `---
151
+ description: Connect this app to Utter (utter-sdk): the action list, sign-in and the voice button.
152
+ alwaysApply: false
153
+ ---
154
+
155
+ `;
156
+ function installSkill(root) {
157
+ const text = readFileSync(SKILL_FILE, "utf8");
158
+ const body = text.replace(/^---[\s\S]*?---\s*/, "");
159
+ const files = [
160
+ [".claude/skills/utter/SKILL.md", text],
161
+ [".agents/skills/utter/SKILL.md", text],
162
+ [".cursor/rules/utter.mdc", CURSOR_HEAD + body],
163
+ ];
164
+ for (const [f, t] of files) {
165
+ mkdirSync(dirname(join(root, f)), { recursive: true });
166
+ writeFileSync(join(root, f), t);
167
+ }
168
+ return files.map(([f]) => f);
169
+ }
170
+ // Makes sure the env file with the secret isn't committed.
171
+ function keepOutOfGit(root, envFile) {
172
+ const check = spawnSync("git", ["check-ignore", "-q", envFile], { cwd: root });
173
+ if (check.error || check.status === 128)
174
+ return "no-git";
175
+ if (check.status === 0)
176
+ return "ignored";
177
+ const gi = join(root, ".gitignore");
178
+ const text = existsSync(gi) ? readFileSync(gi, "utf8") : "";
179
+ appendFileSync(gi, `${text && !text.endsWith("\n") ? "\n" : ""}${envFile}\n`);
180
+ return "added";
181
+ }
182
+ async function init(flags) {
183
+ const root = process.cwd();
184
+ const p = readProject(root);
185
+ const env = readEnv(root);
186
+ const url = (flags.url ?? env.UTTER_URL ?? process.env.UTTER_URL ?? DEFAULT_URL).replace(/\/+$/, "");
187
+ out();
188
+ out(bold("Utter setup"));
189
+ out();
190
+ // 1. Keys
191
+ if (env.UTTER_PROJECT && env.UTTER_SECRET && !flags.relogin) {
192
+ good(`Already has keys for project ${env.UTTER_PROJECT} ${dim("(--relogin to pick another)")}`);
193
+ }
194
+ else {
195
+ const keys = await signIn(url, !flags["no-open"]);
196
+ const envPath = join(root, p.envFile);
197
+ const values = { UTTER_PROJECT: keys.id, UTTER_SECRET: keys.secret };
198
+ if (url !== DEFAULT_URL)
199
+ values.UTTER_URL = url;
200
+ writeFileSync(envPath, upsertEnv(existsSync(envPath) ? readFileSync(envPath, "utf8") : "", values));
201
+ good(`Connected to ${bold(keys.name)}: keys saved in ${p.envFile}`);
202
+ const git = keepOutOfGit(root, p.envFile);
203
+ if (git === "added")
204
+ good(`Added ${p.envFile} to .gitignore, so the secret stays out of git`);
205
+ }
206
+ // 2. Package
207
+ const has = Boolean(p.pkg.dependencies?.["utter-sdk"] || p.pkg.devDependencies?.["utter-sdk"]);
208
+ if (has)
209
+ good("utter-sdk is already installed");
210
+ else if (flags["no-install"])
211
+ note("Skipped installing: run npm install utter-sdk");
212
+ else {
213
+ const pm = packageManager(root);
214
+ out(` ${dim(`${pm.cmd} ${pm.add.join(" ")} utter-sdk`)}`);
215
+ const r = spawnSync(pm.cmd, [...pm.add, "utter-sdk"], { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
216
+ if (r.status === 0)
217
+ good("Installed utter-sdk");
218
+ else
219
+ bad(`Installing failed. Run ${pm.cmd} ${pm.add.join(" ")} utter-sdk yourself.`);
220
+ }
221
+ // 3. Files
222
+ const ext = p.ts ? "ts" : "js";
223
+ const lib = [p.base, "lib", `utter.${ext}`].filter(Boolean).join("/");
224
+ if (writeNew(root, lib, libTemplate(p)))
225
+ good(`Created ${lib}`);
226
+ else
227
+ good(`${lib} is already there`);
228
+ if (p.next && p.appRouter) {
229
+ const route = [p.base, "app", "api", "utter", "[...path]", `route.${ext}`].filter(Boolean).join("/");
230
+ let rel = relative(dirname(join(root, route)), join(root, lib)).replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
231
+ if (!rel.startsWith("."))
232
+ rel = `./${rel}`;
233
+ if (writeNew(root, route, routeTemplate(rel)))
234
+ good(`Created ${route}`);
235
+ else
236
+ good(`${route} is already there`);
237
+ }
238
+ else {
239
+ note(p.next
240
+ ? "This app uses the pages/ folder. Add an app/api/utter/[...path]/route file that exports utter.handler (see the docs)."
241
+ : "Not a Next.js app router project: serve utter.handler at /api/utter/* with your framework (see the docs).");
242
+ }
243
+ // 4. Agent skill
244
+ if (!flags["no-skill"]) {
245
+ installSkill(root);
246
+ good("Added the Utter skill for Claude Code, Codex and Cursor");
247
+ }
248
+ out();
249
+ out(bold("Next: ask your AI coding agent to finish it"));
250
+ out();
251
+ out(` ${bold("Set up Utter in this app. Follow the utter skill.")}`);
252
+ out();
253
+ out(" It reads your code and writes the actions Utter may run, hooks up your login, and puts the");
254
+ out(" Utter button on your screens. Then run npx utter-sdk check, and switch it on in the dashboard:");
255
+ out(` ${dim(`${url}/dashboard`)}`);
256
+ out();
257
+ }
258
+ /* ---- check ---- */
259
+ async function check(flags) {
260
+ const root = process.cwd();
261
+ const env = { ...readEnv(root), ...pick(process.env) };
262
+ const url = (flags.url ?? env.UTTER_URL ?? DEFAULT_URL).replace(/\/+$/, "");
263
+ const app = (flags.app ?? "http://localhost:3000").replace(/\/+$/, "");
264
+ let problems = 0;
265
+ const fail = (s) => {
266
+ problems++;
267
+ bad(s);
268
+ };
269
+ out();
270
+ out(bold("Utter check"));
271
+ out();
272
+ const project = env.UTTER_PROJECT;
273
+ const secret = env.UTTER_SECRET;
274
+ if (!project || !secret)
275
+ stop("UTTER_PROJECT and UTTER_SECRET aren't set in .env.local or .env. Run npx utter-sdk init first.");
276
+ // Are the keys right?
277
+ const v = await api(url, "/api/cli/verify", {}, {
278
+ Authorization: `Bearer ${secret}`,
279
+ "X-Utter-Project": project,
280
+ });
281
+ if (v.status === 200) {
282
+ good(`Keys work for ${bold(v.data.name ?? project)}`);
283
+ note(`Utter calls your app at ${v.data.hostUrl} (change it in the dashboard's Settings)`);
284
+ note(v.data.live ? "Switched on: your customers see the Utter button" : "Not switched on yet: your customers don't see the Utter button");
285
+ }
286
+ else
287
+ fail(v.data.error ?? `Utter didn't accept the keys (HTTP ${v.status}).`);
288
+ // The action list, from the running app, the way Utter asks for it.
289
+ let manifest = null;
290
+ const res = await fetch(`${app}/api/utter/manifest`, { headers: signed(secret, "") }).catch(() => null);
291
+ if (!res)
292
+ fail(`Can't reach your app at ${app}. Is it running? Use --app to point somewhere else.`);
293
+ else if (res.status === 401)
294
+ fail("Your app turned down the signed request: its UTTER_SECRET doesn't match. Restart it after changing .env files.");
295
+ else if (res.status === 404)
296
+ fail(`${app}/api/utter/manifest wasn't found. Is the route file in place?`);
297
+ else if (!res.ok)
298
+ fail(`Your app answered HTTP ${res.status} for the action list. Check its logs.`);
299
+ else {
300
+ manifest = (await res.json().catch(() => null));
301
+ const p = manifestProblems(manifest);
302
+ if (p.length === 0) {
303
+ const writes = manifest.actions.filter((a) => a.writes).length;
304
+ good(`The action list is complete: ${manifest.actions.length} actions, ${writes} of them change data`);
305
+ }
306
+ for (const x of p)
307
+ fail(x);
308
+ }
309
+ // Each reading action, for one real company and person. Actions that change data are never run here.
310
+ if (manifest && flags.tenant && flags.user) {
311
+ for (const a of manifest.actions) {
312
+ if (a.writes)
313
+ continue;
314
+ if (!canRunWithoutArgs(a.args)) {
315
+ note(`${a.name} needs arguments, so it's skipped`);
316
+ continue;
317
+ }
318
+ const body = JSON.stringify({ tenantId: flags.tenant, userId: flags.user, op: a.name, args: [] });
319
+ const r = await fetch(`${app}/api/utter/call`, {
320
+ method: "POST",
321
+ headers: { "Content-Type": "application/json", ...signed(secret, body) },
322
+ body,
323
+ }).catch(() => null);
324
+ const data = (await r?.json().catch(() => null));
325
+ if (!r || !data?.ok)
326
+ fail(`${a.name} failed: ${data?.error ?? (r ? `HTTP ${r.status}` : "no answer")}`);
327
+ else
328
+ good(`${a.name} works${Array.isArray(data.result) ? ` (${data.result.length} rows)` : ""}`);
329
+ }
330
+ }
331
+ else if (manifest) {
332
+ note("Add --tenant <company id> --user <user id> to also run each reading action");
333
+ }
334
+ out();
335
+ if (problems) {
336
+ out(`${problems} ${problems === 1 ? "problem" : "problems"} to fix.`);
337
+ process.exitCode = 1;
338
+ }
339
+ else
340
+ out("All good.");
341
+ out();
342
+ }
343
+ const pick = (e) => Object.fromEntries(Object.entries(e).filter(([k, v]) => k.startsWith("UTTER_") && v));
344
+ /* ---- main ---- */
345
+ const HELP = `
346
+ Usage: npx utter-sdk <command>
347
+
348
+ init Connect this app: sign in, save the keys, install, add the route and the AI agent skill
349
+ --relogin pick a project again even if keys are saved
350
+ --no-open don't open the browser, just print the link
351
+ --no-install don't install the package
352
+ --no-skill don't add the agent skill files
353
+ check Check the running app's action list and keys
354
+ --app <url> where the app runs (default http://localhost:3000)
355
+ --tenant <id> --user <id> also run each reading action for this company and person
356
+
357
+ --url <url> a different Utter address (default ${DEFAULT_URL})
358
+ `;
359
+ async function main() {
360
+ const { values, positionals } = parseArgs({
361
+ allowPositionals: true,
362
+ options: {
363
+ url: { type: "string" },
364
+ app: { type: "string" },
365
+ tenant: { type: "string" },
366
+ user: { type: "string" },
367
+ relogin: { type: "boolean" },
368
+ "no-open": { type: "boolean" },
369
+ "no-install": { type: "boolean" },
370
+ "no-skill": { type: "boolean" },
371
+ help: { type: "boolean", short: "h" },
372
+ },
373
+ });
374
+ const cmd = positionals[0];
375
+ if (values.help || !cmd)
376
+ return out(HELP);
377
+ if (cmd === "init")
378
+ return init(values);
379
+ if (cmd === "check")
380
+ return check(values);
381
+ out(`Unknown command: ${cmd}`);
382
+ out(HELP);
383
+ process.exitCode = 1;
384
+ }
385
+ main().catch((e) => {
386
+ out();
387
+ out(e instanceof Stop ? e.message : `Something went wrong: ${e.message}`);
388
+ out();
389
+ process.exitCode = 1;
390
+ });