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 +21 -0
- package/README.md +153 -2
- package/dist/cli-helpers.d.ts +6 -0
- package/dist/cli-helpers.js +103 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +390 -0
- package/dist/components.d.ts +9 -0
- package/dist/components.js +171 -0
- package/dist/hooks.d.ts +48 -0
- package/dist/hooks.js +260 -0
- package/dist/react.d.ts +3 -0
- package/dist/react.js +6 -0
- package/dist/server.d.ts +48 -0
- package/dist/server.js +152 -0
- package/dist/types.d.ts +72 -0
- package/dist/types.js +2 -0
- package/package.json +69 -4
- package/skill/SKILL.md +142 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type UtterProps = {
|
|
2
|
+
app?: string;
|
|
3
|
+
examples?: string[];
|
|
4
|
+
position?: "bottom-right" | "bottom-left";
|
|
5
|
+
voice?: boolean;
|
|
6
|
+
basePath?: string;
|
|
7
|
+
lang?: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function Utter({ app, examples, position, voice, basePath, lang }: UtterProps): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useRef, useState } from "react";
|
|
4
|
+
import { useUtter, useUtterStatus, useVoice, yesOrNo } from "./hooks.js";
|
|
5
|
+
const MUTE_KEY = "utter:muted";
|
|
6
|
+
export function Utter({ app, examples = [], position = "bottom-right", voice = true, basePath, lang }) {
|
|
7
|
+
const status = useUtterStatus({ basePath });
|
|
8
|
+
const u = useUtter({ basePath });
|
|
9
|
+
const v = useVoice({ lang });
|
|
10
|
+
const [open, setOpen] = useState(false);
|
|
11
|
+
const [text, setText] = useState("");
|
|
12
|
+
const [muted, setMuted] = useState(false);
|
|
13
|
+
const list = useRef(null);
|
|
14
|
+
const input = useRef(null);
|
|
15
|
+
const spoken = useRef(0);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
try {
|
|
18
|
+
setMuted(localStorage.getItem(MUTE_KEY) === "1");
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// Storage blocked: start unmuted.
|
|
22
|
+
}
|
|
23
|
+
}, []);
|
|
24
|
+
// Keeps the newest message in view.
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
list.current?.scrollTo({ top: list.current.scrollHeight, behavior: "smooth" });
|
|
27
|
+
}, [u.turns.length, u.state, v.interim]);
|
|
28
|
+
// Says each new reply out loud, once.
|
|
29
|
+
const last = u.turns[u.turns.length - 1];
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!last || last.role !== "assistant" || last.id === spoken.current)
|
|
32
|
+
return;
|
|
33
|
+
spoken.current = last.id;
|
|
34
|
+
if (open && voice && !muted && v.canSpeak)
|
|
35
|
+
void v.speak(last.text);
|
|
36
|
+
}, [last, open, voice, muted, v]);
|
|
37
|
+
// Escape closes the panel.
|
|
38
|
+
useEffect(() => {
|
|
39
|
+
if (!open)
|
|
40
|
+
return;
|
|
41
|
+
const onKey = (e) => {
|
|
42
|
+
if (e.key === "Escape")
|
|
43
|
+
close();
|
|
44
|
+
};
|
|
45
|
+
window.addEventListener("keydown", onKey);
|
|
46
|
+
return () => window.removeEventListener("keydown", onKey);
|
|
47
|
+
});
|
|
48
|
+
if (!status?.live)
|
|
49
|
+
return null;
|
|
50
|
+
const name = app || status.app;
|
|
51
|
+
const busy = u.state === "thinking";
|
|
52
|
+
const orbState = v.state === "listening" ? "listening" : v.state === "speaking" ? "speaking" : busy ? "thinking" : "idle";
|
|
53
|
+
function close() {
|
|
54
|
+
v.stopSpeaking();
|
|
55
|
+
v.stopListening();
|
|
56
|
+
setOpen(false);
|
|
57
|
+
}
|
|
58
|
+
// A short "yes" or "no" answers the plan that's waiting; anything else is a new request.
|
|
59
|
+
async function say(said) {
|
|
60
|
+
const t = said.trim();
|
|
61
|
+
if (!t || busy)
|
|
62
|
+
return;
|
|
63
|
+
const answer = u.pending ? yesOrNo(t) : null;
|
|
64
|
+
if (answer === "yes")
|
|
65
|
+
return void (await u.confirm());
|
|
66
|
+
if (answer === "no")
|
|
67
|
+
return void (await u.cancel());
|
|
68
|
+
await u.send(t);
|
|
69
|
+
}
|
|
70
|
+
async function onMic() {
|
|
71
|
+
if (v.state === "listening")
|
|
72
|
+
return v.stopListening();
|
|
73
|
+
const heard = await v.listen();
|
|
74
|
+
if (heard)
|
|
75
|
+
await say(heard);
|
|
76
|
+
}
|
|
77
|
+
function onSubmit(e) {
|
|
78
|
+
e.preventDefault();
|
|
79
|
+
const t = text;
|
|
80
|
+
setText("");
|
|
81
|
+
void say(t);
|
|
82
|
+
}
|
|
83
|
+
function toggleMute() {
|
|
84
|
+
const next = !muted;
|
|
85
|
+
setMuted(next);
|
|
86
|
+
if (next)
|
|
87
|
+
v.stopSpeaking();
|
|
88
|
+
try {
|
|
89
|
+
localStorage.setItem(MUTE_KEY, next ? "1" : "0");
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
// Storage blocked: the choice lasts until the page reloads.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return (_jsxs("div", { className: `utter utter-${position}`, children: [_jsx("style", { children: CSS }), open && (_jsxs("div", { className: "utter-panel", role: "dialog", "aria-label": `Talk to ${name}`, children: [_jsxs("div", { className: "utter-head", children: [_jsxs("span", { className: "utter-title", children: [_jsx(Orb, { state: orbState, size: 18 }), name] }), _jsxs("span", { className: "utter-head-buttons", children: [voice && v.canSpeak && (_jsx("button", { type: "button", className: "utter-icon", onClick: toggleMute, "aria-label": muted ? "Turn voice on" : "Mute voice", title: muted ? "Turn voice on" : "Mute voice", children: muted ? _jsx(IconMuted, {}) : _jsx(IconSound, {}) })), _jsx("button", { type: "button", className: "utter-icon", onClick: close, "aria-label": "Close", title: "Close", children: _jsx(IconClose, {}) })] })] }), _jsxs("div", { className: "utter-list", ref: list, "aria-live": "polite", children: [u.turns.length === 0 && (_jsxs("div", { className: "utter-empty", children: [_jsx("p", { className: "utter-hello", children: v.canListen ? "Press the mic and say what you need, or type it." : "Type what you need." }), examples.length > 0 && (_jsx("div", { className: "utter-examples", children: examples.slice(0, 3).map((ex) => (_jsx("button", { type: "button", className: "utter-example", onClick: () => void say(ex), children: ex }, ex))) }))] })), u.turns.map((t) => (_jsx(Message, { turn: t, busy: busy, onYes: () => void u.confirm(), onNo: () => void u.cancel() }, t.id))), v.interim && _jsx("div", { className: "utter-msg utter-user utter-interim", children: v.interim }), busy && (_jsxs("div", { className: "utter-msg utter-assistant utter-dots", "aria-label": "Working", children: [_jsx("i", {}), _jsx("i", {}), _jsx("i", {})] }))] }), v.error && _jsx("p", { className: "utter-error-line", children: v.error }), _jsxs("form", { className: "utter-input", onSubmit: onSubmit, children: [v.canListen && (_jsx("button", { type: "button", className: `utter-mic${v.state === "listening" ? " utter-mic-on" : ""}`, onClick: () => void onMic(), disabled: busy, "aria-label": v.state === "listening" ? "Stop listening" : "Talk", title: v.state === "listening" ? "Stop listening" : "Talk", children: _jsx(IconMic, {}) })), _jsx("input", { ref: input, className: "utter-text", value: text, onChange: (e) => setText(e.target.value), placeholder: v.state === "listening" ? "Listening…" : u.pending ? "Say yes or no, or ask something else" : "Type a request", "aria-label": "Type a request", disabled: v.state === "listening" }), _jsx("button", { type: "submit", className: "utter-send", disabled: busy || !text.trim(), "aria-label": "Send", title: "Send", children: _jsx(IconSend, {}) })] })] })), _jsxs("button", { type: "button", className: "utter-launcher", onClick: () => (open ? close() : (setOpen(true), setTimeout(() => input.current?.focus(), 50))), "aria-label": open ? "Close Utter" : `Talk to ${name}`, "aria-expanded": open, title: open ? "Close" : `Talk to ${name}`, children: [_jsx(Orb, { state: orbState, size: 56 }), _jsx("span", { className: "utter-launcher-icon", children: open ? _jsx(IconClose, {}) : _jsx(IconMic, {}) })] })] }));
|
|
96
|
+
}
|
|
97
|
+
function Message({ turn, busy, onYes, onNo }) {
|
|
98
|
+
const c = turn.confirm;
|
|
99
|
+
return (_jsxs("div", { className: `utter-msg utter-${turn.role}${turn.error ? " utter-msg-error" : ""}`, children: [_jsx("p", { children: turn.text }), turn.list && (_jsx("ul", { className: "utter-items", children: turn.list.map((x, i) => (_jsx("li", { children: x }, i))) })), c && (_jsxs("div", { className: "utter-confirm", children: [_jsxs("ul", { className: "utter-items", children: [c.steps.slice(0, 8).map((s, i) => (_jsx("li", { children: s }, i))), c.steps.length > 8 && _jsxs("li", { className: "utter-more", children: ["and ", c.steps.length - 8, " more"] })] }), c.state === "waiting" ? (_jsxs("div", { className: "utter-confirm-buttons", children: [_jsx("button", { type: "button", className: "utter-yes", onClick: onYes, disabled: busy, children: "Yes, do it" }), _jsx("button", { type: "button", className: "utter-no", onClick: onNo, disabled: busy, children: "No" })] })) : (_jsx("p", { className: "utter-confirm-state", children: c.state === "confirmed" ? "Confirmed" : "Cancelled" }))] }))] }));
|
|
100
|
+
}
|
|
101
|
+
function Orb({ state, size }) {
|
|
102
|
+
return (_jsxs("span", { className: "utter-orb", "data-state": state, style: { width: size, height: size }, "aria-hidden": true, children: [_jsx("i", {}), _jsx("i", {}), _jsx("i", {})] }));
|
|
103
|
+
}
|
|
104
|
+
const svg = { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true };
|
|
105
|
+
const IconMic = () => (_jsxs("svg", { ...svg, children: [_jsx("rect", { x: "9", y: "3", width: "6", height: "11", rx: "3" }), _jsx("path", { d: "M5 11a7 7 0 0 0 14 0M12 18v3" })] }));
|
|
106
|
+
const IconSend = () => (_jsx("svg", { ...svg, children: _jsx("path", { d: "M5 12h14M13 6l6 6-6 6" }) }));
|
|
107
|
+
const IconClose = () => (_jsx("svg", { ...svg, children: _jsx("path", { d: "M6 6l12 12M18 6L6 18" }) }));
|
|
108
|
+
const IconSound = () => (_jsx("svg", { ...svg, children: _jsx("path", { d: "M4 10v4h4l5 4V6L8 10H4zM16.5 8.5a5 5 0 0 1 0 7" }) }));
|
|
109
|
+
const IconMuted = () => (_jsx("svg", { ...svg, children: _jsx("path", { d: "M4 10v4h4l5 4V6L8 10H4zM17 9l5 6M22 9l-5 6" }) }));
|
|
110
|
+
const CSS = `
|
|
111
|
+
.utter{position:fixed;bottom:20px;z-index:2147483000;font-family:inherit;color:var(--utter-ink,#0b0b12);display:flex;flex-direction:column;gap:12px}
|
|
112
|
+
.utter-bottom-right{right:20px;align-items:flex-end}.utter-bottom-left{left:20px;align-items:flex-start}
|
|
113
|
+
.utter *{box-sizing:border-box}
|
|
114
|
+
.utter button{font:inherit;cursor:pointer}
|
|
115
|
+
.utter button:disabled{cursor:default;opacity:.55}
|
|
116
|
+
.utter :focus-visible{outline:2px solid var(--utter-accent,#3341ff);outline-offset:2px}
|
|
117
|
+
.utter-launcher{position:relative;width:56px;height:56px;padding:0;border:0;border-radius:9999px;background:none;box-shadow:0 10px 30px -8px rgba(51,65,255,.55)}
|
|
118
|
+
.utter-launcher-icon{position:absolute;inset:0;display:grid;place-items:center;color:#fff}
|
|
119
|
+
.utter-orb{position:relative;display:block;flex-shrink:0;border-radius:9999px;overflow:hidden;isolation:isolate;background:var(--utter-accent,#3341ff);box-shadow:inset 0 -8px 20px rgba(0,0,0,.18),inset 0 8px 16px rgba(255,255,255,.45)}
|
|
120
|
+
.utter-orb>i{position:absolute;inset:-30%;border-radius:9999px;filter:blur(10px)}
|
|
121
|
+
.utter-orb>i:nth-child(1){background:radial-gradient(circle at 30% 35%,var(--utter-o1,#2b37e8),transparent 55%);animation:utter-a 9s linear infinite}
|
|
122
|
+
.utter-orb>i:nth-child(2){background:radial-gradient(circle at 70% 60%,var(--utter-o2,#c3c9ff),transparent 55%);animation:utter-b 11s linear infinite}
|
|
123
|
+
.utter-orb>i:nth-child(3){background:radial-gradient(circle at 45% 75%,var(--utter-o3,#5aa0ff),transparent 50%);animation:utter-a 7s linear infinite reverse}
|
|
124
|
+
.utter-orb[data-state=listening]{animation:utter-breathe .9s ease-in-out infinite}
|
|
125
|
+
.utter-orb[data-state=speaking]{animation:utter-talk .5s ease-in-out infinite}
|
|
126
|
+
.utter-orb[data-state=thinking]>i{animation-duration:2.5s}
|
|
127
|
+
@keyframes utter-a{to{transform:rotate(360deg)}}
|
|
128
|
+
@keyframes utter-b{from{transform:rotate(120deg) scale(1.1)}to{transform:rotate(-240deg) scale(1.1)}}
|
|
129
|
+
@keyframes utter-breathe{50%{transform:scale(1.08)}}
|
|
130
|
+
@keyframes utter-talk{25%{transform:scale(1.05)}60%{transform:scale(.97)}}
|
|
131
|
+
.utter-panel{width:min(380px,calc(100vw - 32px));height:min(540px,calc(100vh - 110px));display:flex;flex-direction:column;background:var(--utter-bg,#fff);border:1px solid var(--utter-line,#dfe2ff);border-radius:22px;box-shadow:0 24px 60px -18px rgba(11,20,82,.35);overflow:hidden}
|
|
132
|
+
.utter-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 12px 12px 16px;border-bottom:1px solid var(--utter-line,#dfe2ff)}
|
|
133
|
+
.utter-title{display:flex;align-items:center;gap:8px;font-size:15px;font-weight:600;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
134
|
+
.utter-head-buttons{display:flex;gap:2px}
|
|
135
|
+
.utter-icon{display:grid;place-items:center;width:32px;height:32px;border:0;border-radius:9999px;background:none;color:var(--utter-muted,#5c5c6a)}
|
|
136
|
+
.utter-icon:hover{background:var(--utter-soft,#f4f4f6);color:var(--utter-ink,#0b0b12)}
|
|
137
|
+
.utter-list{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:10px;overscroll-behavior:contain}
|
|
138
|
+
.utter-empty{margin:auto 0;display:flex;flex-direction:column;gap:12px}
|
|
139
|
+
.utter-hello{margin:0;font-size:14px;color:var(--utter-muted,#5c5c6a);line-height:1.5}
|
|
140
|
+
.utter-examples{display:flex;flex-direction:column;align-items:flex-start;gap:6px}
|
|
141
|
+
.utter-example{border:1px solid var(--utter-line,#dfe2ff);background:var(--utter-bg,#fff);color:var(--utter-ink,#0b0b12);border-radius:9999px;padding:7px 12px;font-size:13px;text-align:left}
|
|
142
|
+
.utter-example:hover{border-color:var(--utter-accent,#3341ff);color:var(--utter-accent,#3341ff)}
|
|
143
|
+
.utter-msg{max-width:88%;padding:9px 13px;border-radius:16px;font-size:14px;line-height:1.45;word-wrap:break-word}
|
|
144
|
+
.utter-msg p{margin:0}
|
|
145
|
+
.utter-user{align-self:flex-end;background:var(--utter-accent,#3341ff);color:var(--utter-accent-ink,#fff);border-bottom-right-radius:6px}
|
|
146
|
+
.utter-assistant{align-self:flex-start;background:var(--utter-soft,#f4f4f6);border-bottom-left-radius:6px}
|
|
147
|
+
.utter-interim{opacity:.6}
|
|
148
|
+
.utter-msg-error{background:#fdeceb;color:#8a2416}
|
|
149
|
+
.utter-items{margin:8px 0 0;padding-left:18px;display:flex;flex-direction:column;gap:3px;font-size:13px}
|
|
150
|
+
.utter-more{list-style:none;margin-left:-18px;color:var(--utter-muted,#5c5c6a)}
|
|
151
|
+
.utter-confirm{margin-top:6px}
|
|
152
|
+
.utter-confirm-buttons{display:flex;gap:6px;margin-top:10px}
|
|
153
|
+
.utter-yes,.utter-no{border-radius:9999px;padding:7px 14px;font-size:13px;font-weight:500}
|
|
154
|
+
.utter-yes{border:1px solid var(--utter-accent,#3341ff);background:var(--utter-accent,#3341ff);color:var(--utter-accent-ink,#fff)}
|
|
155
|
+
.utter-no{border:1px solid var(--utter-line,#dfe2ff);background:var(--utter-bg,#fff);color:var(--utter-ink,#0b0b12)}
|
|
156
|
+
.utter-confirm-state{margin-top:8px!important;font-size:12px;color:var(--utter-muted,#5c5c6a)}
|
|
157
|
+
.utter-dots{display:flex;gap:4px;padding:13px 14px}
|
|
158
|
+
.utter-dots i{width:6px;height:6px;border-radius:9999px;background:var(--utter-muted,#5c5c6a);animation:utter-dot 1s ease-in-out infinite}
|
|
159
|
+
.utter-dots i:nth-child(2){animation-delay:.15s}.utter-dots i:nth-child(3){animation-delay:.3s}
|
|
160
|
+
@keyframes utter-dot{0%,80%,100%{opacity:.25}40%{opacity:1}}
|
|
161
|
+
.utter-error-line{margin:0;padding:0 16px 8px;font-size:12px;color:#8a2416}
|
|
162
|
+
.utter-input{display:flex;align-items:center;gap:6px;padding:10px;border-top:1px solid var(--utter-line,#dfe2ff)}
|
|
163
|
+
.utter-mic,.utter-send{display:grid;place-items:center;flex-shrink:0;width:38px;height:38px;border-radius:9999px}
|
|
164
|
+
.utter-mic{border:1px solid var(--utter-line,#dfe2ff);background:var(--utter-bg,#fff);color:var(--utter-accent,#3341ff)}
|
|
165
|
+
.utter-mic:hover{border-color:var(--utter-accent,#3341ff)}
|
|
166
|
+
.utter-mic-on{background:var(--utter-accent,#3341ff);border-color:var(--utter-accent,#3341ff);color:var(--utter-accent-ink,#fff);animation:utter-breathe .9s ease-in-out infinite}
|
|
167
|
+
.utter-send{border:0;background:var(--utter-accent,#3341ff);color:var(--utter-accent-ink,#fff)}
|
|
168
|
+
.utter-text{flex:1;min-width:0;height:38px;padding:0 14px;border:1px solid var(--utter-line,#dfe2ff);border-radius:9999px;background:var(--utter-bg,#fff);color:var(--utter-ink,#0b0b12);font:inherit;font-size:14px}
|
|
169
|
+
.utter-text:focus{outline:none;border-color:var(--utter-accent,#3341ff)}
|
|
170
|
+
@media (prefers-reduced-motion:reduce){.utter-orb>i,.utter-orb[data-state],.utter-mic-on,.utter-dots i{animation:none}}
|
|
171
|
+
`;
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export declare const CHANGED_EVENT = "utter:changed";
|
|
2
|
+
export type UtterStatus = {
|
|
3
|
+
live: boolean;
|
|
4
|
+
app: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function useUtterStatus({ basePath }?: {
|
|
7
|
+
basePath?: string;
|
|
8
|
+
}): UtterStatus | null;
|
|
9
|
+
export type UtterTurn = {
|
|
10
|
+
id: number;
|
|
11
|
+
role: "user" | "assistant";
|
|
12
|
+
text: string;
|
|
13
|
+
list?: string[];
|
|
14
|
+
confirm?: {
|
|
15
|
+
steps: string[];
|
|
16
|
+
plan: string;
|
|
17
|
+
sig: string;
|
|
18
|
+
state: "waiting" | "confirmed" | "cancelled";
|
|
19
|
+
};
|
|
20
|
+
error?: boolean;
|
|
21
|
+
};
|
|
22
|
+
export type UtterState = "idle" | "thinking";
|
|
23
|
+
export declare function useUtter({ basePath }?: {
|
|
24
|
+
basePath?: string;
|
|
25
|
+
}): {
|
|
26
|
+
turns: UtterTurn[];
|
|
27
|
+
state: UtterState;
|
|
28
|
+
pending: UtterTurn | null;
|
|
29
|
+
send: (text: string) => Promise<UtterTurn | null>;
|
|
30
|
+
confirm: () => Promise<UtterTurn | null>;
|
|
31
|
+
cancel: () => Promise<UtterTurn | null>;
|
|
32
|
+
reset: () => void;
|
|
33
|
+
};
|
|
34
|
+
export type VoiceState = "idle" | "listening" | "speaking";
|
|
35
|
+
export declare function useVoice({ lang }?: {
|
|
36
|
+
lang?: string;
|
|
37
|
+
}): {
|
|
38
|
+
canListen: boolean;
|
|
39
|
+
canSpeak: boolean;
|
|
40
|
+
state: VoiceState;
|
|
41
|
+
interim: string;
|
|
42
|
+
error: string;
|
|
43
|
+
listen: () => Promise<string>;
|
|
44
|
+
stopListening: () => void | undefined;
|
|
45
|
+
speak: (text: string) => Promise<void>;
|
|
46
|
+
stopSpeaking: () => void;
|
|
47
|
+
};
|
|
48
|
+
export declare function yesOrNo(text: string): "yes" | "no" | null;
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
// Hooks for a product's own screens. They talk to the product's own route
|
|
4
|
+
// (app/api/utter/[...path], from createUtter().handler), which signs the person in with the
|
|
5
|
+
// product's login and passes the request on to Utter. <Utter /> is built from these; use them
|
|
6
|
+
// directly for your own look.
|
|
7
|
+
const DEFAULT_BASE = "/api/utter";
|
|
8
|
+
// Sent on the page after Utter changed something, so the app can refresh what's on screen:
|
|
9
|
+
// window.addEventListener("utter:changed", () => router.refresh())
|
|
10
|
+
export const CHANGED_EVENT = "utter:changed";
|
|
11
|
+
async function req(base, path, body) {
|
|
12
|
+
const res = await fetch(`${base}${path}`, {
|
|
13
|
+
method: body === undefined ? "GET" : "POST",
|
|
14
|
+
headers: { "Content-Type": "application/json" },
|
|
15
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
16
|
+
});
|
|
17
|
+
const data = (await res.json().catch(() => ({})));
|
|
18
|
+
if (!res.ok)
|
|
19
|
+
throw new Error(data.error ?? `Request failed (HTTP ${res.status}).`);
|
|
20
|
+
return data;
|
|
21
|
+
}
|
|
22
|
+
// null while loading, or when the person isn't signed in or Utter can't be reached.
|
|
23
|
+
export function useUtterStatus({ basePath = DEFAULT_BASE } = {}) {
|
|
24
|
+
const [status, setStatus] = useState(null);
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
let alive = true;
|
|
27
|
+
req(basePath, "/status").then((s) => alive && setStatus(s), () => alive && setStatus(null));
|
|
28
|
+
return () => {
|
|
29
|
+
alive = false;
|
|
30
|
+
};
|
|
31
|
+
}, [basePath]);
|
|
32
|
+
return status;
|
|
33
|
+
}
|
|
34
|
+
let nextId = 1;
|
|
35
|
+
export function useUtter({ basePath = DEFAULT_BASE } = {}) {
|
|
36
|
+
const [turns, setTurns] = useState([]);
|
|
37
|
+
const [state, setState] = useState("idle");
|
|
38
|
+
const turnsRef = useRef(turns);
|
|
39
|
+
turnsRef.current = turns;
|
|
40
|
+
const add = (t) => {
|
|
41
|
+
const turn = { ...t, id: nextId++ };
|
|
42
|
+
setTurns((all) => [...all, turn]);
|
|
43
|
+
return turn;
|
|
44
|
+
};
|
|
45
|
+
const setConfirmState = (id, s) => setTurns((all) => all.map((t) => (t.id === id && t.confirm ? { ...t, confirm: { ...t.confirm, state: s } } : t)));
|
|
46
|
+
const pending = [...turns].reverse().find((t) => t.confirm?.state === "waiting") ?? null;
|
|
47
|
+
const finish = useCallback((id, kind) => {
|
|
48
|
+
const t = turnsRef.current.find((x) => x.id === id);
|
|
49
|
+
if (!t?.confirm || t.confirm.state !== "waiting")
|
|
50
|
+
return null;
|
|
51
|
+
setConfirmState(id, kind === "confirm" ? "confirmed" : "cancelled");
|
|
52
|
+
return t.confirm;
|
|
53
|
+
}, []);
|
|
54
|
+
// Says no to the plan that's waiting, if any. Nothing changes.
|
|
55
|
+
const cancel = useCallback(async () => {
|
|
56
|
+
const waiting = [...turnsRef.current].reverse().find((t) => t.confirm?.state === "waiting");
|
|
57
|
+
const c = waiting && finish(waiting.id, "cancel");
|
|
58
|
+
if (!c)
|
|
59
|
+
return null;
|
|
60
|
+
try {
|
|
61
|
+
const r = await req(basePath, "/cancel", { plan: c.plan, sig: c.sig });
|
|
62
|
+
return add({ role: "assistant", text: r.text });
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return add({ role: "assistant", text: "Okay, nothing changed." });
|
|
66
|
+
}
|
|
67
|
+
}, [basePath, finish]);
|
|
68
|
+
// Sends what the person said or typed. A plan that was still waiting is dropped first.
|
|
69
|
+
const send = useCallback(async (text) => {
|
|
70
|
+
const said = text.trim();
|
|
71
|
+
if (!said)
|
|
72
|
+
return null;
|
|
73
|
+
const waiting = [...turnsRef.current].reverse().find((t) => t.confirm?.state === "waiting");
|
|
74
|
+
if (waiting) {
|
|
75
|
+
const c = finish(waiting.id, "cancel");
|
|
76
|
+
if (c)
|
|
77
|
+
req(basePath, "/cancel", { plan: c.plan, sig: c.sig }).catch(() => { });
|
|
78
|
+
}
|
|
79
|
+
const history = turnsRef.current
|
|
80
|
+
.filter((t) => !t.error)
|
|
81
|
+
.slice(-11)
|
|
82
|
+
.map((t) => ({ role: t.role, text: t.text }));
|
|
83
|
+
add({ role: "user", text: said });
|
|
84
|
+
setState("thinking");
|
|
85
|
+
try {
|
|
86
|
+
const r = await req(basePath, "/ask", { conversation: [...history, { role: "user", text: said }] });
|
|
87
|
+
if (r.kind === "confirm") {
|
|
88
|
+
return add({ role: "assistant", text: r.text, confirm: { steps: r.steps, plan: r.plan, sig: r.sig, state: "waiting" } });
|
|
89
|
+
}
|
|
90
|
+
if (r.kind === "answer")
|
|
91
|
+
return add({ role: "assistant", text: r.text, list: r.list?.length ? r.list : undefined });
|
|
92
|
+
return add({ role: "assistant", text: r.text, error: r.kind === "error" });
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
return add({ role: "assistant", text: e.message || "Utter can't be reached right now.", error: true });
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
setState("idle");
|
|
99
|
+
}
|
|
100
|
+
}, [basePath, finish]);
|
|
101
|
+
// Says yes to the plan that's waiting. Fires "utter:changed" when anything changed.
|
|
102
|
+
const confirm = useCallback(async () => {
|
|
103
|
+
const waiting = [...turnsRef.current].reverse().find((t) => t.confirm?.state === "waiting");
|
|
104
|
+
const c = waiting && finish(waiting.id, "confirm");
|
|
105
|
+
if (!c)
|
|
106
|
+
return null;
|
|
107
|
+
setState("thinking");
|
|
108
|
+
try {
|
|
109
|
+
const r = await req(basePath, "/confirm", { plan: c.plan, sig: c.sig });
|
|
110
|
+
if (r.kind === "answer" && (r.done ?? 0) > 0 && typeof window !== "undefined")
|
|
111
|
+
window.dispatchEvent(new Event(CHANGED_EVENT));
|
|
112
|
+
return add({
|
|
113
|
+
role: "assistant",
|
|
114
|
+
text: r.text,
|
|
115
|
+
list: r.kind === "answer" && r.list?.length ? r.list : undefined,
|
|
116
|
+
error: r.kind === "error" || (r.kind === "answer" && (r.failed ?? 0) > 0),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
return add({ role: "assistant", text: e.message || "Utter can't be reached right now.", error: true });
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
setState("idle");
|
|
124
|
+
}
|
|
125
|
+
}, [basePath, finish]);
|
|
126
|
+
const reset = useCallback(() => setTurns([]), []);
|
|
127
|
+
return { turns, state, pending, send, confirm, cancel, reset };
|
|
128
|
+
}
|
|
129
|
+
function recognitionClass() {
|
|
130
|
+
if (typeof window === "undefined")
|
|
131
|
+
return null;
|
|
132
|
+
const w = window;
|
|
133
|
+
return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
|
|
134
|
+
}
|
|
135
|
+
// The most natural-sounding voice the browser has for the page's language.
|
|
136
|
+
function pickVoice(lang) {
|
|
137
|
+
const voices = window.speechSynthesis.getVoices();
|
|
138
|
+
const base = lang.split("-")[0].toLowerCase();
|
|
139
|
+
const same = voices.filter((v) => v.lang.toLowerCase().startsWith(base));
|
|
140
|
+
const pool = same.length ? same : voices;
|
|
141
|
+
const score = (v) => (v.lang.toLowerCase() === lang.toLowerCase() ? 4 : 0) +
|
|
142
|
+
(/natural|neural|online/i.test(v.name) ? 8 : 0) +
|
|
143
|
+
(/google|samantha|ava|aria|jenny|daniel|karen|moira/i.test(v.name) ? 3 : 0) +
|
|
144
|
+
(v.localService ? 0 : 1);
|
|
145
|
+
return [...pool].sort((a, b) => score(b) - score(a))[0] ?? null;
|
|
146
|
+
}
|
|
147
|
+
export function useVoice({ lang } = {}) {
|
|
148
|
+
const [canListen, setCanListen] = useState(false);
|
|
149
|
+
const [canSpeak, setCanSpeak] = useState(false);
|
|
150
|
+
const [state, setState] = useState("idle");
|
|
151
|
+
const [interim, setInterim] = useState("");
|
|
152
|
+
const [error, setError] = useState("");
|
|
153
|
+
const rec = useRef(null);
|
|
154
|
+
const language = useRef("en-US");
|
|
155
|
+
useEffect(() => {
|
|
156
|
+
language.current = lang || document.documentElement.lang || navigator.language || "en-US";
|
|
157
|
+
setCanListen(Boolean(recognitionClass()));
|
|
158
|
+
setCanSpeak("speechSynthesis" in window);
|
|
159
|
+
// Some browsers load their voices late; asking once starts that.
|
|
160
|
+
if ("speechSynthesis" in window)
|
|
161
|
+
window.speechSynthesis.getVoices();
|
|
162
|
+
return () => {
|
|
163
|
+
rec.current?.abort();
|
|
164
|
+
if ("speechSynthesis" in window)
|
|
165
|
+
window.speechSynthesis.cancel();
|
|
166
|
+
};
|
|
167
|
+
}, [lang]);
|
|
168
|
+
const stopSpeaking = useCallback(() => {
|
|
169
|
+
if (typeof window !== "undefined" && "speechSynthesis" in window)
|
|
170
|
+
window.speechSynthesis.cancel();
|
|
171
|
+
setState((s) => (s === "speaking" ? "idle" : s));
|
|
172
|
+
}, []);
|
|
173
|
+
// Listens until the person stops talking. Resolves with what they said ("" for nothing).
|
|
174
|
+
const listen = useCallback(() => {
|
|
175
|
+
const R = recognitionClass();
|
|
176
|
+
if (!R)
|
|
177
|
+
return Promise.resolve("");
|
|
178
|
+
stopSpeaking();
|
|
179
|
+
rec.current?.abort();
|
|
180
|
+
setError("");
|
|
181
|
+
setInterim("");
|
|
182
|
+
return new Promise((resolve) => {
|
|
183
|
+
const r = new R();
|
|
184
|
+
rec.current = r;
|
|
185
|
+
r.lang = language.current;
|
|
186
|
+
r.interimResults = true;
|
|
187
|
+
r.continuous = false;
|
|
188
|
+
r.maxAlternatives = 1;
|
|
189
|
+
let finalText = "";
|
|
190
|
+
r.onresult = (e) => {
|
|
191
|
+
let live = "";
|
|
192
|
+
for (let i = e.resultIndex; i < e.results.length; i++) {
|
|
193
|
+
const res = e.results[i];
|
|
194
|
+
if (res.isFinal)
|
|
195
|
+
finalText += res[0].transcript;
|
|
196
|
+
else
|
|
197
|
+
live += res[0].transcript;
|
|
198
|
+
}
|
|
199
|
+
setInterim((finalText + live).trim());
|
|
200
|
+
};
|
|
201
|
+
r.onerror = (e) => {
|
|
202
|
+
if (e.error === "not-allowed" || e.error === "service-not-allowed")
|
|
203
|
+
setError("Allow the microphone to talk to Utter, or type instead.");
|
|
204
|
+
else if (e.error !== "no-speech" && e.error !== "aborted")
|
|
205
|
+
setError("Couldn't hear that. Try again, or type instead.");
|
|
206
|
+
};
|
|
207
|
+
r.onend = () => {
|
|
208
|
+
if (rec.current === r)
|
|
209
|
+
rec.current = null;
|
|
210
|
+
setState((s) => (s === "listening" ? "idle" : s));
|
|
211
|
+
setInterim("");
|
|
212
|
+
resolve(finalText.trim());
|
|
213
|
+
};
|
|
214
|
+
setState("listening");
|
|
215
|
+
try {
|
|
216
|
+
r.start();
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
setState("idle");
|
|
220
|
+
resolve("");
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
}, [stopSpeaking]);
|
|
224
|
+
// Stops listening now; what was heard so far still comes back from listen().
|
|
225
|
+
const stopListening = useCallback(() => rec.current?.stop(), []);
|
|
226
|
+
// Says the text out loud. Resolves when it's done (or was stopped).
|
|
227
|
+
const speak = useCallback((text) => {
|
|
228
|
+
if (typeof window === "undefined" || !("speechSynthesis" in window) || !text.trim())
|
|
229
|
+
return Promise.resolve();
|
|
230
|
+
window.speechSynthesis.cancel();
|
|
231
|
+
return new Promise((resolve) => {
|
|
232
|
+
const u = new SpeechSynthesisUtterance(text);
|
|
233
|
+
u.lang = language.current;
|
|
234
|
+
const voice = pickVoice(language.current);
|
|
235
|
+
if (voice)
|
|
236
|
+
u.voice = voice;
|
|
237
|
+
u.rate = 1.04;
|
|
238
|
+
const done = () => {
|
|
239
|
+
setState((s) => (s === "speaking" ? "idle" : s));
|
|
240
|
+
resolve();
|
|
241
|
+
};
|
|
242
|
+
u.onend = done;
|
|
243
|
+
u.onerror = done;
|
|
244
|
+
setState("speaking");
|
|
245
|
+
window.speechSynthesis.speak(u);
|
|
246
|
+
});
|
|
247
|
+
}, []);
|
|
248
|
+
return { canListen, canSpeak, state, interim, error, listen, stopListening, speak, stopSpeaking };
|
|
249
|
+
}
|
|
250
|
+
// Is a short reply a yes or a no to the plan that's waiting? null when it's something else.
|
|
251
|
+
export function yesOrNo(text) {
|
|
252
|
+
const t = text.toLowerCase().replace(/[^a-z' ]/g, " ").replace(/\s+/g, " ").trim();
|
|
253
|
+
if (!t || t.split(" ").length > 5)
|
|
254
|
+
return null;
|
|
255
|
+
if (/^(no|nope|nah|cancel|stop|don't|do not|never mind|nevermind|wait|hold on)\b/.test(t))
|
|
256
|
+
return "no";
|
|
257
|
+
if (/^(yes|yeah|yep|yup|sure|ok|okay|go ahead|do it|confirm|please do|correct|sounds good|absolutely)\b/.test(t))
|
|
258
|
+
return "yes";
|
|
259
|
+
return null;
|
|
260
|
+
}
|
package/dist/react.d.ts
ADDED
package/dist/react.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
// Everything for a product's own screens: <Utter />, the ready-made mic button and panel, and the
|
|
3
|
+
// hooks it's built from (useUtter, useVoice, useUtterStatus) for your own look.
|
|
4
|
+
export * from "./types.js";
|
|
5
|
+
export * from "./hooks.js";
|
|
6
|
+
export * from "./components.js";
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ActivityEntry, AskResult, ConfirmResult, Manifest, Turn, Viewer } from "./types.ts";
|
|
2
|
+
export * from "./types.ts";
|
|
3
|
+
export type ActionContext = {
|
|
4
|
+
tenantId: string;
|
|
5
|
+
userId: string;
|
|
6
|
+
};
|
|
7
|
+
export type Action = (ctx: ActionContext, ...args: any[]) => Promise<unknown> | unknown;
|
|
8
|
+
export type UtterOptions = {
|
|
9
|
+
manifest: Manifest;
|
|
10
|
+
actions: Record<string, Action>;
|
|
11
|
+
isMember: (tenantId: string, userId: string) => Promise<boolean> | boolean;
|
|
12
|
+
getViewer?: (req: Request) => Promise<Viewer | null> | Viewer | null;
|
|
13
|
+
url?: string;
|
|
14
|
+
project?: string;
|
|
15
|
+
secret?: string;
|
|
16
|
+
};
|
|
17
|
+
export declare class UtterError extends Error {
|
|
18
|
+
}
|
|
19
|
+
export declare function createUtter(opts: UtterOptions): {
|
|
20
|
+
client: (viewer: Viewer) => {
|
|
21
|
+
status: () => Promise<{
|
|
22
|
+
live: boolean;
|
|
23
|
+
app: string;
|
|
24
|
+
}>;
|
|
25
|
+
ask: (conversation: Turn[]) => Promise<AskResult>;
|
|
26
|
+
confirm: (plan: string, sig: string) => Promise<ConfirmResult>;
|
|
27
|
+
cancel: (plan: string, sig: string) => Promise<ConfirmResult>;
|
|
28
|
+
activity: (o?: {
|
|
29
|
+
before?: string;
|
|
30
|
+
limit?: number;
|
|
31
|
+
}) => Promise<{
|
|
32
|
+
entries: ActivityEntry[];
|
|
33
|
+
next: string | null;
|
|
34
|
+
}>;
|
|
35
|
+
};
|
|
36
|
+
handler: {
|
|
37
|
+
GET: (req: Request, ctx: {
|
|
38
|
+
params: Promise<{
|
|
39
|
+
path?: string[];
|
|
40
|
+
}>;
|
|
41
|
+
}) => Promise<Response>;
|
|
42
|
+
POST: (req: Request, ctx: {
|
|
43
|
+
params: Promise<{
|
|
44
|
+
path?: string[];
|
|
45
|
+
}>;
|
|
46
|
+
}) => Promise<Response>;
|
|
47
|
+
};
|
|
48
|
+
};
|