heyquilt 0.3.147 → 0.3.148
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/RELEASES.md +5 -0
- package/package.json +1 -1
- package/src/account.js +19 -0
- package/src/api/http.js +5 -0
- package/src/api/routes/agent-wake.js +3 -1
- package/src/api/routes/voice.js +131 -3
- package/src/api/server.js +9 -4
- package/src/ui/app.css +2 -0
- package/src/ui/voice-call.js +62 -0
- package/src/ui/voice.js +20 -6
- package/src/ui-server.js +31 -2
- package/src/voice.js +8 -3
package/RELEASES.md
CHANGED
|
@@ -11,6 +11,11 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
|
|
|
11
11
|
Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
|
|
12
12
|
nothing else is.
|
|
13
13
|
|
|
14
|
+
## 0.3.148 — 2026-11-03
|
|
15
|
+
|
|
16
|
+
- **The call says when an agent can't hear you.** Name an agent that Quilt has no way to wake and the call says so, with its face greyed out, instead of showing it joining forever. A person's cloud AI counts as one that wakes by itself.
|
|
17
|
+
- **Agents' voices start sooner and sound like part of the call.** Speech now plays while it is still being made, starting with the first sentence. The voice hears what was said just before it speaks, so its tone fits the conversation. Each line is made once for everyone in the call instead of once per person.
|
|
18
|
+
|
|
14
19
|
## 0.3.147 — 2026-11-03
|
|
15
20
|
|
|
16
21
|
- **Agents join a call when you say their name.** A call starts with only the people in it. Say an agent's name in a transcribed call and it is pinged, with what was said just before: its face shows joining, it joins, says a few words straight away so you know it heard, then answers out loud. An agent that never comes drops out after two minutes. This is still only for Quilt run from source.
|
package/package.json
CHANGED
package/src/account.js
CHANGED
|
@@ -588,3 +588,22 @@ export async function transcribeVoice ({ token, audio, seconds, api = apiUrl(),
|
|
|
588
588
|
export async function speakVoice ({ token, text, by, agent, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
|
|
589
589
|
return call(fetchImpl, api, 'POST', '/v1/voice/speak', { text, by, ...(agent ? { agent } : {}) }, token)
|
|
590
590
|
}
|
|
591
|
+
|
|
592
|
+
/** The same line as speech that plays as it renders, with what was said before it (`before`): the API's response, its body PCM. */
|
|
593
|
+
export async function speakVoiceStream ({ token, text, by, agent, before = [], api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
|
|
594
|
+
let res
|
|
595
|
+
try {
|
|
596
|
+
res = await fetchImpl(api + '/v1/voice/speak', {
|
|
597
|
+
method: 'POST',
|
|
598
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
|
|
599
|
+
body: JSON.stringify({ text, by, stream: true, before, ...(agent ? { agent } : {}) })
|
|
600
|
+
})
|
|
601
|
+
} catch (err) {
|
|
602
|
+
throw new Error(`Couldn't reach Quilt (${err.cause?.code || err.message}).`)
|
|
603
|
+
}
|
|
604
|
+
if (!res.ok) {
|
|
605
|
+
const data = await res.json().catch(() => null)
|
|
606
|
+
throw Object.assign(new Error(data?.error || `Quilt answered ${res.status}.`), { status: res.status })
|
|
607
|
+
}
|
|
608
|
+
return res
|
|
609
|
+
}
|
package/src/api/http.js
CHANGED
|
@@ -28,6 +28,11 @@ export function cleanName (value, max, message) {
|
|
|
28
28
|
return s
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
/** A reply sent as it is made: `chunks` (an async iterable of Buffers), e.g. speech as it renders. */
|
|
32
|
+
export class Stream {
|
|
33
|
+
constructor (status, chunks, type, headers = {}) { this.status = status; this.chunks = chunks; this.type = type; this.headers = headers }
|
|
34
|
+
}
|
|
35
|
+
|
|
31
36
|
/** A non-JSON reply, e.g. the plain-text join instructions an AI reads. */
|
|
32
37
|
export class Raw {
|
|
33
38
|
constructor (status, body, type = 'text/markdown; charset=utf-8') { this.status = status; this.body = body; this.type = type }
|
|
@@ -83,7 +83,9 @@ export function agentWakeRoutes (ctx) {
|
|
|
83
83
|
const ids = (Array.isArray(body.accounts) ? body.accounts : []).slice(0, 200).map((a) => String(a).split(':')).filter(([k, id]) => k === 'agent' && /^[0-9a-f-]{36}$/i.test(id || '')).map(([, id]) => id)
|
|
84
84
|
const rows = await store.agentWakes(ids)
|
|
85
85
|
const by = new Map(rows.map((r) => [r.agentId, r]))
|
|
86
|
-
|
|
86
|
+
// A person's cloud AI wakes on its own machine, whatever it chose (relay-ai-vm.js).
|
|
87
|
+
const cloud = new Set((await Promise.all(ids.map(async (id) => (await store.aiVmByAgent(id).catch(() => null)) ? id : null))).filter(Boolean))
|
|
88
|
+
return { wakes: Object.fromEntries(ids.map((id) => { const w = by.get(id); return [`agent:${id}`, cloud.has(id) ? { method: 'cloud', label: 'wakes by itself (a cloud AI)' } : { method: (w && w.method) || null, label: wakeLabel(w) }] })) }
|
|
87
89
|
}],
|
|
88
90
|
['GET', /^\/v1\/agents\/me\/wake$/, async (req) => {
|
|
89
91
|
const { agent, cli, sandbox } = await agentCalling(req)
|
package/src/api/routes/voice.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
// And agents' voices: an agent in a call says a line, and each app in the call has it spoken here
|
|
6
6
|
// with Fluxions' text-to-speech, under a monthly cap of characters per account.
|
|
7
7
|
import crypto from 'node:crypto'
|
|
8
|
-
import
|
|
8
|
+
import WebSocket from 'ws'
|
|
9
|
+
import { HttpError, Stream } from '../http.js'
|
|
9
10
|
import { AGENT_VOICE_NAMES, pickAgentVoice } from '../agent-voices.js'
|
|
10
11
|
|
|
11
12
|
export const STUN = { urls: ['stun:stun.cloudflare.com:3478'] }
|
|
@@ -31,6 +32,76 @@ export const FALLBACK_VOICES = AGENT_VOICE_NAMES.map((n) => `${n}.h8ff7e07da`)
|
|
|
31
32
|
const VOICES_TTL_MS = 60 * 60 * 1000
|
|
32
33
|
// A line an agent says (voice.js MAX_LINE).
|
|
33
34
|
export const MAX_SPOKEN = 2000
|
|
35
|
+
// Fluxions' socket (plans/voice.md): a voice agent's replies, in conversation mode, as they render.
|
|
36
|
+
export const FLUXIONS_WS = 'wss://api.fluxions.ai/vui/v1/tts/ws'
|
|
37
|
+
// What it sends: s16le PCM, mono, 24 kHz.
|
|
38
|
+
export const SPEECH_TYPE = 'audio/L16; rate=24000; channels=1'
|
|
39
|
+
// What was said before a line, as the caller's turn: this many lines, each this long at most.
|
|
40
|
+
const BEFORE_LINES = 8
|
|
41
|
+
const BEFORE_CHARS = 500
|
|
42
|
+
// A rendered line is kept this long, so every app in the call gets the one render.
|
|
43
|
+
const RENDER_KEEP_MS = 10 * 60 * 1000
|
|
44
|
+
const RENDER_KEEP = 40
|
|
45
|
+
const SOCKET_TIMEOUT_MS = 30 * 1000
|
|
46
|
+
|
|
47
|
+
/** A line cut into its sentences: one speak each, so the first is heard while the rest render. */
|
|
48
|
+
export function sentences (text) {
|
|
49
|
+
const got = String(text || '').match(/[^.!?…]+[.!?…]+["'”’)\]]*\s*|[^.!?…]+$/g) || []
|
|
50
|
+
const out = got.map((s) => s.trim()).filter(Boolean)
|
|
51
|
+
return out.length ? out : [String(text || '').trim()].filter(Boolean)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The PCM in a WAV: what follows its data chunk's header (a plain 44-byte header when there's no data chunk). */
|
|
55
|
+
export function wavPcm (buf) {
|
|
56
|
+
const i = buf.indexOf('data', 12, 'latin1')
|
|
57
|
+
return i >= 0 && i + 8 <= buf.length ? buf.subarray(i + 8) : buf.subarray(Math.min(44, buf.length))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* `text` in `voice`, rendered on Fluxions' socket in conversation mode: what was said just before
|
|
62
|
+
* (`before`) is the caller's turn, so the reply carries on its tone, and each sentence is its own
|
|
63
|
+
* speak. Yields PCM as it arrives.
|
|
64
|
+
*/
|
|
65
|
+
export async function * fluxionsConversation ({ key, voice, before = [], text, socket = (url, opts) => new WebSocket(url, opts), timeoutMs = SOCKET_TIMEOUT_MS }) {
|
|
66
|
+
const ws = socket(FLUXIONS_WS, { headers: { authorization: key } })
|
|
67
|
+
const queue = []
|
|
68
|
+
let wake = null
|
|
69
|
+
let ended = false
|
|
70
|
+
let failure = null
|
|
71
|
+
const push = (item) => { queue.push(item); if (wake) { wake(); wake = null } }
|
|
72
|
+
const parts = sentences(text)
|
|
73
|
+
let dones = 0
|
|
74
|
+
const timer = setTimeout(() => push({ error: new Error('the speech service took too long') }), timeoutMs)
|
|
75
|
+
ws.on('open', () => {
|
|
76
|
+
ws.send(JSON.stringify({ type: 'session.update', voice, context: true }))
|
|
77
|
+
const said = before.map((l) => `${l.by}: ${l.text}`).join('\n').trim()
|
|
78
|
+
if (said) ws.send(JSON.stringify({ type: 'user', text: said }))
|
|
79
|
+
for (const p of parts) ws.send(JSON.stringify({ type: 'speak', input: p }))
|
|
80
|
+
})
|
|
81
|
+
ws.on('message', (data, isBinary) => {
|
|
82
|
+
if (isBinary) return push({ chunk: Buffer.from(data) })
|
|
83
|
+
let m
|
|
84
|
+
try { m = JSON.parse(String(data)) } catch { return }
|
|
85
|
+
if (m.type === 'error') push({ error: new Error(`${m.code || 'error'}: ${m.message || ''}`.trim()) })
|
|
86
|
+
else if (m.type === 'done' && ++dones >= parts.length) push({ end: true })
|
|
87
|
+
})
|
|
88
|
+
ws.on('error', (err) => push({ error: err }))
|
|
89
|
+
ws.on('close', () => push({ end: true }))
|
|
90
|
+
try {
|
|
91
|
+
while (!ended) {
|
|
92
|
+
if (!queue.length) await new Promise((resolve) => { wake = resolve })
|
|
93
|
+
const item = queue.shift()
|
|
94
|
+
if (item.error) { failure = item.error; break }
|
|
95
|
+
if (item.end) { ended = true; break }
|
|
96
|
+
yield item.chunk
|
|
97
|
+
}
|
|
98
|
+
if (failure) throw failure
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer)
|
|
101
|
+
try { ws.send(JSON.stringify({ type: 'session.close' })) } catch {}
|
|
102
|
+
try { ws.close() } catch {}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
34
105
|
|
|
35
106
|
/** The voice of a speaker with no registered voice (a chat link, a persona): the same one for the same name. */
|
|
36
107
|
export function voiceFor (name, voices) {
|
|
@@ -75,7 +146,7 @@ export function iceList (raw) {
|
|
|
75
146
|
return out
|
|
76
147
|
}
|
|
77
148
|
|
|
78
|
-
export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, voice = {}, fetch: fetchImpl = globalThis.fetch, makeLimiter }) {
|
|
149
|
+
export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, voice = {}, fetch: fetchImpl = globalThis.fetch, socket = null, makeLimiter }) {
|
|
79
150
|
const { turnKeyId = '', turnToken = '', accountId = '', aiToken = '', capMinutes = 600, fluxionsKey = '', speechCapChars = 300000 } = voice
|
|
80
151
|
const capSeconds = Math.max(0, Number(capMinutes) || 0) * 60
|
|
81
152
|
const capChars = Math.max(0, Number(speechCapChars) || 0)
|
|
@@ -109,6 +180,46 @@ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, vo
|
|
|
109
180
|
return list.find((id) => id.split('.')[0] === name) || ''
|
|
110
181
|
}
|
|
111
182
|
// Per person: ICE servers a few times an hour, clips about one every couple of seconds of a long talk.
|
|
183
|
+
// Each line is rendered once (renderKey) however many apps in the call ask for it: the apps that
|
|
184
|
+
// ask while it renders hear it as it comes.
|
|
185
|
+
const renders = new Map() // key -> { chunks, done, error, waiting, at }
|
|
186
|
+
const renderKey = (voice, text, before) => crypto.createHash('sha256').update(JSON.stringify([voice, text, before])).digest('hex')
|
|
187
|
+
function startRender (key, gen) {
|
|
188
|
+
for (const [k, r] of renders) if (r.done && now() - r.at > RENDER_KEEP_MS) renders.delete(k)
|
|
189
|
+
while (renders.size >= RENDER_KEEP) renders.delete(renders.keys().next().value)
|
|
190
|
+
const r = { chunks: [], done: false, error: null, waiting: new Set(), at: now() }
|
|
191
|
+
const tell = () => { for (const f of r.waiting) f(); r.waiting.clear() }
|
|
192
|
+
renders.set(key, r)
|
|
193
|
+
;(async () => {
|
|
194
|
+
try { for await (const c of gen) { r.chunks.push(c); tell() } } catch (err) { r.error = err } finally { r.done = true; r.at = now(); if (r.error) renders.delete(key); tell() }
|
|
195
|
+
})()
|
|
196
|
+
return r
|
|
197
|
+
}
|
|
198
|
+
async function * readRender (r) {
|
|
199
|
+
let i = 0
|
|
200
|
+
for (;;) {
|
|
201
|
+
while (i < r.chunks.length) yield r.chunks[i++]
|
|
202
|
+
if (r.done) { if (r.error && !i) throw r.error; return }
|
|
203
|
+
await new Promise((resolve) => r.waiting.add(resolve))
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const firstOf = (r) => r.chunks.length || r.done ? Promise.resolve() : new Promise((resolve) => r.waiting.add(resolve))
|
|
207
|
+
// The socket first; if it fails before any sound, the plain render.
|
|
208
|
+
async function * speech (voice, text, before) {
|
|
209
|
+
let heard = false
|
|
210
|
+
try {
|
|
211
|
+
for await (const c of fluxionsConversation({ key: fluxionsKey, voice, before, text, ...(socket ? { socket } : {}) })) { heard = true; yield c }
|
|
212
|
+
if (heard) return
|
|
213
|
+
log('voice speak: Fluxions socket closed with no sound')
|
|
214
|
+
} catch (err) {
|
|
215
|
+
log(`voice speak: Fluxions socket: ${err.message}`)
|
|
216
|
+
if (heard) throw err
|
|
217
|
+
}
|
|
218
|
+
const res = await fetchImpl(`${FLUXIONS}/v1/tts`, { method: 'POST', headers: { authorization: fluxionsKey, 'content-type': 'application/json' }, body: JSON.stringify({ voice, input: text, response_format: 'wav' }) })
|
|
219
|
+
if (!res.ok) throw new Error(`Fluxions answered ${res.status}`)
|
|
220
|
+
yield wavPcm(Buffer.from(await res.arrayBuffer()))
|
|
221
|
+
}
|
|
222
|
+
|
|
112
223
|
const limitIce = makeLimiter(30, 'too many requests for call servers; try again in a minute', { keyOf: (userId) => userId })
|
|
113
224
|
const limitClips = makeLimiter(60, 'too much speech at once; slow down', { keyOf: (userId) => userId })
|
|
114
225
|
|
|
@@ -179,8 +290,10 @@ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, vo
|
|
|
179
290
|
return { text, seconds: billed, used: total, cap: capSeconds }
|
|
180
291
|
}, { maxBody: MAX_CLIP_BODY + 4096 }],
|
|
181
292
|
|
|
182
|
-
// A line an agent said in a call, as speech: { text, by, agent? } in,
|
|
293
|
+
// A line an agent said in a call, as speech: { text, by, agent?, stream?, before? } in, in the
|
|
183
294
|
// agent's voice: the one it was given when it registered (`agent`, its id), else one from its name.
|
|
295
|
+
// `stream`: PCM as it renders, with what was said before (`before`: [{ by, text }]) as context;
|
|
296
|
+
// without it, a WAV (base64) in JSON, for apps from before 0.3.148.
|
|
184
297
|
['POST', /^\/v1\/voice\/speak$/, async (req, body) => {
|
|
185
298
|
const { userId } = await person(req)
|
|
186
299
|
if (!fluxionsKey) throw new HttpError(503, "Agents' voices are not set up on this server.")
|
|
@@ -194,6 +307,21 @@ export function voiceRoutes ({ store, person, now = Date.now, log = () => {}, vo
|
|
|
194
307
|
if (used >= capChars) throw new HttpError(429, "You've heard this month's share of agents speaking. Their lines still show in the call; their voices start again next month.")
|
|
195
308
|
const list = await voiceList()
|
|
196
309
|
const voice = (await registeredVoice(body.agent, list)) || voiceFor(by, list)
|
|
310
|
+
if (body.stream === true) {
|
|
311
|
+
const before = (Array.isArray(body.before) ? body.before : []).slice(-BEFORE_LINES)
|
|
312
|
+
.map((l) => ({ by: String(l?.by || '').slice(0, 80), text: String(l?.text || '').replace(/\s+/g, ' ').trim().slice(0, BEFORE_CHARS) }))
|
|
313
|
+
.filter((l) => l.by && l.text)
|
|
314
|
+
const key = renderKey(voice, text, before)
|
|
315
|
+
let r = renders.get(key)
|
|
316
|
+
// Only the first ask renders, and counts.
|
|
317
|
+
if (!r) { r = startRender(key, speech(voice, text, before)); await store.addVoiceSpeechChars(userId, month, text.length) }
|
|
318
|
+
await firstOf(r)
|
|
319
|
+
if (r.error && !r.chunks.length) {
|
|
320
|
+
log(`voice speak: ${r.error.message}`)
|
|
321
|
+
throw new HttpError(502, 'The speech service turned this line down.')
|
|
322
|
+
}
|
|
323
|
+
return new Stream(200, readRender(r), SPEECH_TYPE, { 'x-quilt-voice': voice })
|
|
324
|
+
}
|
|
197
325
|
let res
|
|
198
326
|
try {
|
|
199
327
|
res = await fetchImpl(`${FLUXIONS}/v1/tts`, {
|
package/src/api/server.js
CHANGED
|
@@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url'
|
|
|
10
10
|
import { newToken, hashToken, newUserCode, normalizeUserCode } from './tokens.js'
|
|
11
11
|
import { parsePublicKey, verifyDeviceLink, verifyDeviceResume } from '../identity.js'
|
|
12
12
|
import { signPass, passPublicKey, PASS_VERSION, PASS_TTL_MS } from '../passes.js'
|
|
13
|
-
import { HttpError, Raw } from './http.js'
|
|
13
|
+
import { HttpError, Raw, Stream } from './http.js'
|
|
14
14
|
import { DiskStore } from './file-store.js'
|
|
15
15
|
import { contentDisposition } from './file-paths.js'
|
|
16
16
|
import { orgRoutes } from './routes/orgs.js'
|
|
@@ -74,7 +74,7 @@ const MCP_TIMEOUT_MS = 30 * 1000
|
|
|
74
74
|
// a change to its grant reaches it as soon as it reaches a connected app.
|
|
75
75
|
const PASS_REUSE_MARGIN_MS = 5 * 60 * 1000
|
|
76
76
|
|
|
77
|
-
export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, siteUrl, apiUrl = 'https://api.heyquilt.com', mailer = { send: async () => { throw new Error('no mailer configured') } }, now = Date.now, log = () => {}, startLimit = 10, inviteLimit = 10, inviteSendLimit = 20, tokenLimit = 30, joinLimit = 20, trustProxy = false, maxStartKeys = 10_000, passKey = '', passLimit = 60, relayUrl = HOSTED_RELAY, mcpLimit = 600, reportKey = '', reportLimit = 10, slowMs = 2000, pruneEveryMs = 60 * 60 * 1000, keepEventsMs = 30 * 24 * 60 * 60 * 1000, keepIssuesMs = 90 * 24 * 60 * 60 * 1000, pruneStartMs = 10_000, relaySecret = '', workspaces = false, quiltSourceDefault = false, fileStore = null, maxFileBytes = 500 * 1024 * 1024, workspaceQuotaBytes = 5 * 1024 * 1024 * 1024, maxWorkspaceFiles = 2000, webhookFetch = globalThis.fetch, webhookLookup, allowLocalWebhooks = false, github = null, githubFetch = globalThis.fetch, fly = null, aiVmWaitMs = AI_VM_WAIT_MS, aiVmSpareSuspendMs, relayFetch = null, relayFly = null, heavy = null, relayTargets = null, clusterTiming = {}, vaultSecret = '', vaultUrl = 'https://vault.heyquilt.com', allowLocalUpstreams = false, secretWaitMs, voice = {}, voiceFetch = globalThis.fetch, mail = {}, mailFetch = globalThis.fetch, machineId = '', leaderTiming = {}, autoscaleTiming = {}, exit = () => process.exit(0), apiFly = null, maxMachines, seamUrl = 'https://api.seam.heyquilt.com', seamFetch = globalThis.fetch, seamClientId = '', seamSiteUrl = 'https://seam.heyquilt.com', seamConnectSecret = '', notifyEveryMs = NOTIFY_EVERY_MS }) {
|
|
77
|
+
export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, siteUrl, apiUrl = 'https://api.heyquilt.com', mailer = { send: async () => { throw new Error('no mailer configured') } }, now = Date.now, log = () => {}, startLimit = 10, inviteLimit = 10, inviteSendLimit = 20, tokenLimit = 30, joinLimit = 20, trustProxy = false, maxStartKeys = 10_000, passKey = '', passLimit = 60, relayUrl = HOSTED_RELAY, mcpLimit = 600, reportKey = '', reportLimit = 10, slowMs = 2000, pruneEveryMs = 60 * 60 * 1000, keepEventsMs = 30 * 24 * 60 * 60 * 1000, keepIssuesMs = 90 * 24 * 60 * 60 * 1000, pruneStartMs = 10_000, relaySecret = '', workspaces = false, quiltSourceDefault = false, fileStore = null, maxFileBytes = 500 * 1024 * 1024, workspaceQuotaBytes = 5 * 1024 * 1024 * 1024, maxWorkspaceFiles = 2000, webhookFetch = globalThis.fetch, webhookLookup, allowLocalWebhooks = false, github = null, githubFetch = globalThis.fetch, fly = null, aiVmWaitMs = AI_VM_WAIT_MS, aiVmSpareSuspendMs, relayFetch = null, relayFly = null, heavy = null, relayTargets = null, clusterTiming = {}, vaultSecret = '', vaultUrl = 'https://vault.heyquilt.com', allowLocalUpstreams = false, secretWaitMs, voice = {}, voiceFetch = globalThis.fetch, voiceSocket, mail = {}, mailFetch = globalThis.fetch, machineId = '', leaderTiming = {}, autoscaleTiming = {}, exit = () => process.exit(0), apiFly = null, maxMachines, seamUrl = 'https://api.seam.heyquilt.com', seamFetch = globalThis.fetch, seamClientId = '', seamSiteUrl = 'https://seam.heyquilt.com', seamConnectSecret = '', notifyEveryMs = NOTIFY_EVERY_MS }) {
|
|
78
78
|
// PASS_SIGNING_KEY. A bad one should stop the API at start, not fail every pass later.
|
|
79
79
|
if (passKey) passPublicKey(passKey)
|
|
80
80
|
const site = String(siteUrl || '').replace(/\/+$/, '')
|
|
@@ -397,7 +397,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
|
|
|
397
397
|
// Secrets (routes/secrets.js): off until the vault is set up (QUILT_VAULT_SECRET).
|
|
398
398
|
routes.push(...secretRoutes({ ...ctx, passKey, vaultSecret, vaultUrl, allowLocalUpstreams, ...(secretWaitMs ? { waitMs: secretWaitMs } : {}) }))
|
|
399
399
|
// Voice (routes/voice.js): call servers for everyone; transcripts once Workers AI is set up.
|
|
400
|
-
routes.push(...voiceRoutes({ ...ctx, voice, fetch: voiceFetch, makeLimiter }))
|
|
400
|
+
routes.push(...voiceRoutes({ ...ctx, voice, fetch: voiceFetch, socket: voiceSocket, makeLimiter }))
|
|
401
401
|
// Email for every session (routes/mail.js): mail that arrives is told to the relay machine
|
|
402
402
|
// holding the session, which writes it into the chat and wakes the session's email agents.
|
|
403
403
|
const tellRoom = async (room, arrived) => {
|
|
@@ -494,7 +494,12 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
|
|
|
494
494
|
const body = route[3]?.raw ? await readRaw(req, route[3]?.maxBody || MAX_BODY) : ['POST', 'PUT', 'PATCH'].includes(req.method) ? await readJson(req, route[3]?.maxBody || MAX_BODY) : {}
|
|
495
495
|
const out = await route[2](req, body, url.pathname.match(route[1]).slice(1).map(decodePart))
|
|
496
496
|
if (out instanceof Raw) send(out.status, out.body, out.type)
|
|
497
|
-
else if (
|
|
497
|
+
else if (out instanceof Stream) {
|
|
498
|
+
res.writeHead(out.status, { 'content-type': out.type, 'cache-control': 'no-store', ...out.headers, ...extra, ...cors(req) })
|
|
499
|
+
try { for await (const chunk of out.chunks) res.write(chunk) } catch (err) { log(`${pathname}: stream stopped: ${err.message}`) }
|
|
500
|
+
res.end()
|
|
501
|
+
recordOwn({ method: req.method, pathname, status: out.status, startedAt })
|
|
502
|
+
} else if (Array.isArray(out)) send(out[0], out[1])
|
|
498
503
|
else send(200, out)
|
|
499
504
|
} catch (err) {
|
|
500
505
|
// A unique index said no. Agents share one index on their public key; everything
|
package/src/ui/app.css
CHANGED
|
@@ -482,6 +482,8 @@ textarea.input { height: auto; padding: 10px 12px; resize: vertical; }
|
|
|
482
482
|
.call-ai { position: absolute; right: -4px; top: -4px; width: 12px; height: 12px; display: grid; place-items: center; border-radius: 50%; background: var(--violet); color: #fff; box-shadow: 0 0 0 1.5px var(--panel); }
|
|
483
483
|
.call-ai svg { width: 8px; height: 8px; }
|
|
484
484
|
.call-face.agent.joining > :first-child { animation: call-joining 1.4s ease-in-out infinite; }
|
|
485
|
+
.call-face.agent.unheard > :first-child { opacity: .45; }
|
|
486
|
+
.cp-agents { padding-bottom: 8px; }
|
|
485
487
|
@keyframes call-joining { 0%, 100% { box-shadow: 0 0 0 0 var(--violet); opacity: .55; } 50% { box-shadow: 0 0 0 3px var(--violet); opacity: 1; } }
|
|
486
488
|
@media (prefers-reduced-motion: reduce) { .call-face.agent.joining > :first-child { animation: none; opacity: .6; box-shadow: 0 0 0 2px var(--violet); } }
|
|
487
489
|
.call-tx { display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 8px; border: 1px solid var(--border); border-radius: 999px; background: none; color: var(--muted); font: 500 11.5px var(--sans); cursor: pointer; white-space: nowrap; }
|
package/src/ui/voice-call.js
CHANGED
|
@@ -47,6 +47,60 @@ export class VoiceCall {
|
|
|
47
47
|
return this.spoken
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
/**
|
|
51
|
+
* An agent's line as it renders (a fetch body of s16le PCM, mono, `rate` Hz), after any before it:
|
|
52
|
+
* each piece is scheduled straight after the last, so the line starts with its first sentence.
|
|
53
|
+
* The microphone is held the same way as in play().
|
|
54
|
+
*/
|
|
55
|
+
playStream (name, body, rate = 24000) {
|
|
56
|
+
this.spoken = this.spoken.then(() => this.playStreamNow(name, body, rate)).catch((err) => console.warn('agent voice', err.message))
|
|
57
|
+
return this.spoken
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async playStreamNow (name, body, rate) {
|
|
61
|
+
if (!this.in || !this.ctx) { body.cancel?.().catch(() => {}); return }
|
|
62
|
+
const reader = body.getReader()
|
|
63
|
+
const sources = []
|
|
64
|
+
let carry = null
|
|
65
|
+
let at = 0
|
|
66
|
+
let stopped = false
|
|
67
|
+
let wait = null
|
|
68
|
+
this.segmenter?.end()
|
|
69
|
+
this.agentTalking = name
|
|
70
|
+
this.onChange()
|
|
71
|
+
this.stopAgent = () => { stopped = true; for (const s of sources) { try { s.stop() } catch {} } reader.cancel().catch(() => {}); if (wait) wait() }
|
|
72
|
+
try {
|
|
73
|
+
while (!stopped) {
|
|
74
|
+
const { value, done } = await reader.read()
|
|
75
|
+
if (done || stopped) break
|
|
76
|
+
const bytes = carry ? concatBytes(carry, value) : value
|
|
77
|
+
const even = bytes.length - (bytes.length % 2)
|
|
78
|
+
carry = even < bytes.length ? bytes.slice(even) : null
|
|
79
|
+
if (!even || !this.in) continue
|
|
80
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, even)
|
|
81
|
+
const buf = this.ctx.createBuffer(1, even / 2, rate)
|
|
82
|
+
const ch = buf.getChannelData(0)
|
|
83
|
+
for (let i = 0; i < ch.length; i++) ch[i] = view.getInt16(i * 2, true) / 32768
|
|
84
|
+
const src = this.ctx.createBufferSource()
|
|
85
|
+
src.buffer = buf
|
|
86
|
+
src.connect(this.ctx.destination)
|
|
87
|
+
// A little lead on the first piece, so a slow second one doesn't leave a gap.
|
|
88
|
+
at = Math.max(at, this.ctx.currentTime + (sources.length ? 0.02 : 0.15))
|
|
89
|
+
src.start(at)
|
|
90
|
+
at += buf.duration
|
|
91
|
+
sources.push(src)
|
|
92
|
+
}
|
|
93
|
+
const left = at - (this.ctx ? this.ctx.currentTime : 0)
|
|
94
|
+
if (left > 0 && !stopped) await new Promise((resolve) => { wait = resolve; setTimeout(resolve, left * 1000) })
|
|
95
|
+
// The room's echo dies down before the microphone counts again.
|
|
96
|
+
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
97
|
+
} finally {
|
|
98
|
+
this.stopAgent = null
|
|
99
|
+
this.agentTalking = null
|
|
100
|
+
this.onChange()
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
50
104
|
async playNow (name, wav) {
|
|
51
105
|
if (!this.in || !this.ctx) return
|
|
52
106
|
const bytes = Uint8Array.from(atob(wav), (c) => c.charCodeAt(0))
|
|
@@ -338,3 +392,11 @@ function gathered (pc) {
|
|
|
338
392
|
pc.addEventListener('icegatheringstatechange', check)
|
|
339
393
|
})
|
|
340
394
|
}
|
|
395
|
+
|
|
396
|
+
/** Two byte arrays as one. */
|
|
397
|
+
function concatBytes (a, b) {
|
|
398
|
+
const out = new Uint8Array(a.length + b.length)
|
|
399
|
+
out.set(a, 0)
|
|
400
|
+
out.set(b, a.length)
|
|
401
|
+
return out
|
|
402
|
+
}
|
package/src/ui/voice.js
CHANGED
|
@@ -248,11 +248,17 @@ function speakAgents (id, view) {
|
|
|
248
248
|
heard.ids.add(l.id)
|
|
249
249
|
if (l.ts < heard.since - 2000) continue
|
|
250
250
|
const call = live.call
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
251
|
+
// Its speech plays as it renders (Fluxions' socket, on the API).
|
|
252
|
+
fetch(`/api/sessions/${id}/voice/speech-stream?line=${encodeURIComponent(l.id)}`, { headers: { 'x-quilt-token': TOKEN || '' } }).then(async (res) => {
|
|
253
|
+
if (!res.ok) {
|
|
254
|
+
const data = await res.json().catch(() => ({}))
|
|
255
|
+
throw Object.assign(new Error(data.error || `Request failed (${res.status})`), { status: res.status })
|
|
256
|
+
}
|
|
257
|
+
if (live && live.call === call && res.body) call.playStream(l.by, res.body)
|
|
258
|
+
else res.body?.cancel().catch(() => {})
|
|
259
|
+
}).catch((err) => {
|
|
254
260
|
// Once a call: voices not set up, or the month's share heard.
|
|
255
|
-
if (!heard.told && (err.status === 503 || err.status === 429 || err.status === 404)) { heard.told = true; toast(err.status === 404 ? "Agents' voices aren't on Quilt's servers yet: their lines show in the call." : err.message) }
|
|
261
|
+
if (!heard.told && (err.status === 503 || err.status === 429 || err.status === 404 || err.status === 502)) { heard.told = true; toast(err.status === 404 ? "Agents' voices aren't on Quilt's servers yet: their lines show in the call." : err.message) }
|
|
256
262
|
})
|
|
257
263
|
}
|
|
258
264
|
}
|
|
@@ -262,7 +268,7 @@ const face = (key, name, color, muted) => `<span class="call-face" data-face="${
|
|
|
262
268
|
// An agent in the call: like a person, with the agent mark, muted unless it is speaking; its ring
|
|
263
269
|
// lights while its line plays. One just named shows joining (a pulsing ring) until it comes.
|
|
264
270
|
const agentFace = (a, color, now) => {
|
|
265
|
-
if (a.state === 'joining') return `<span class="call-face agent joining" data-face="agent:${esc(a.name)}" title="${esc(a.name)}, an agent: joining (someone said its name)">${avatar(a.name, color)}<span class="call-ai" aria-hidden="true">${I.bot}</span
|
|
271
|
+
if (a.state === 'joining') return `<span class="call-face agent ${a.hears === 'no' ? 'unheard' : 'joining'}" data-face="agent:${esc(a.name)}" title="${esc(a.name)}, an agent: ${a.hears === 'no' ? "can't hear you (Quilt can't wake it)" : 'joining (someone said its name)'}">${avatar(a.name, color)}<span class="call-ai" aria-hidden="true">${I.bot}</span>${a.hears === 'no' ? `<span class="call-muted">${I.micOff}</span>` : ''}</span>`
|
|
266
272
|
const muted = !(a.until > now)
|
|
267
273
|
return `<span class="call-face agent" data-face="agent:${esc(a.name)}" title="${esc(a.name)}, an agent: ${muted ? 'in the call, muted' : 'speaking'}">${avatar(a.name, color)}<span class="call-ai" aria-hidden="true">${I.bot}</span>${muted ? `<span class="call-muted">${I.micOff}</span>` : ''}</span>`
|
|
268
274
|
}
|
|
@@ -321,10 +327,17 @@ export function renderCall () {
|
|
|
321
327
|
const agents = view.agents || []
|
|
322
328
|
redrawWhenMuted(agents, now)
|
|
323
329
|
const agentFaces = agents.map((a) => agentFace(a, colorOf(a.name), now)).join('')
|
|
324
|
-
const key = JSON.stringify([id, here, joining, asking, options, owner, elsewhere, view.transcribe, others.map((p) => [p.id, p.name, p.color, p.muted, p.transcribing, p.sharing]), agents.map((a) => [a.name, a.until > now]), me.name, me.color, c && [c.muted, c.transcribing, c.sharing], selfClosed, showing, minutes(view.since || Date.now())])
|
|
330
|
+
const key = JSON.stringify([id, here, joining, asking, options, owner, elsewhere, view.transcribe, others.map((p) => [p.id, p.name, p.color, p.muted, p.transcribing, p.sharing]), agents.map((a) => [a.name, a.state, a.hears, a.until > now]), me.name, me.color, c && [c.muted, c.transcribing, c.sharing], selfClosed, showing, minutes(view.since || Date.now())])
|
|
325
331
|
if (key === drawn && (pin.hidden || pin.childElementCount)) { paintLines(pin, lines); paintTalk(); return }
|
|
326
332
|
drawn = key
|
|
327
333
|
linesDrawn = null
|
|
334
|
+
// A named agent that can't hear its name, or will hear it only later: say so, so nobody waits on it.
|
|
335
|
+
const unheard = agents.filter((a) => a.state === 'joining' && a.hears === 'no').map((a) => a.name)
|
|
336
|
+
const later = agents.filter((a) => a.state === 'joining' && a.hears === 'later').map((a) => a.name)
|
|
337
|
+
const agentNote = [
|
|
338
|
+
unheard.length ? `<p class="cp-note cp-agents">${esc(names(unheard))} can't hear you: Quilt can't wake ${unheard.length === 1 ? 'it' : 'them'} until ${unheard.length === 1 ? 'it picks' : 'they pick'} a way with quilt_wake.</p>` : '',
|
|
339
|
+
later.length ? `<p class="cp-note cp-agents">${esc(names(later))} ${later.length === 1 ? 'checks' : 'check'} in now and then, so ${later.length === 1 ? 'its' : 'their'} answer may take a while.</p>` : ''
|
|
340
|
+
].join('')
|
|
328
341
|
if (pin.hidden) { pin.innerHTML = ''; return }
|
|
329
342
|
const dur = view.since ? minutes(view.since) : ''
|
|
330
343
|
if (joining) {
|
|
@@ -353,6 +366,7 @@ export function renderCall () {
|
|
|
353
366
|
<button type="button" class="call-ic" data-call-mute aria-pressed="${c.muted}" title="${c.muted ? 'Unmute' : 'Mute'}" aria-label="${c.muted ? 'Unmute' : 'Mute'}">${c.muted ? I.micOff : I.mic}</button>
|
|
354
367
|
<button type="button" class="call-ic bad" data-call-leave title="Leave the call" aria-label="Leave the call">${I.hangUp}</button></div>
|
|
355
368
|
<div class="cp-row"><span class="call-faces">${face('me', me.name, me.color, c.muted)}${others.map((p) => face(p.id, p.name, p.color, p.muted)).join('')}${agentFaces}</span>${tag}</div>
|
|
369
|
+
${agentNote}
|
|
356
370
|
${options ? `<div class="cp-opts">${myChoice}${ownerChoice}</div>` : ''}
|
|
357
371
|
${c.sharing ? `<div class="cp-share">${I.screenShare}<span class="cp-says">Sharing your screen</span>${selfClosed ? '<button type="button" class="btn sm ghost" data-self-share="open" title="Show what you share, in the corner">Show</button>' : ''}<button type="button" class="btn sm" data-call-share>Stop sharing</button></div>` : ''}
|
|
358
372
|
${others.filter((p) => p.sharing).map((p) => `<div class="cp-share">${I.screenShare}<span class="cp-says">${esc(p.name)} is sharing a screen</span>${p.id === showing ? '<span class="call-sub">in the middle</span>' : `<button type="button" class="btn sm" data-screen-show="${p.id}">Show</button>`}</div>`).join('')}
|
package/src/ui-server.js
CHANGED
|
@@ -20,7 +20,7 @@ import { autowork, autoConfig, publicConfig, AUTO_MODES } from './autowork.js'
|
|
|
20
20
|
import { migrateDir } from './legacy.js'
|
|
21
21
|
import { writePrivateJson } from './private-file.js'
|
|
22
22
|
import { autoToolFor } from './autowork-tools.js'
|
|
23
|
-
import { readAccount, saveAccount, clearAccount, clearAccountIf, resumeAccount, startLink, waitForLink, fetchMe, signOut, revokeToken, accountFromProfile, renameSession, createAgentInvite, listAgents, agentDetails, listAccessTypes, listCollaborators, listGrants, putGrant, deleteGrant, inviteToSession, listSessionInvites, cancelSessionInvite, listWorkspaces, listOrgs, createWorkspace, getWorkspace, updateWorkspace, deleteWorkspace, putWorkspaceMember, removeWorkspaceMember, getAgentPlacement, putAgentPlacement, listOrgAgents, putWorkspaceAgent, deleteWorkspaceAgent, createWorkspaceAgentInvite, excludeSessionAgent, listExcludedSessionAgents, listSessionAgents, includeSessionAgent, setSessionWorkspace, moveSessionToWorkspace, listWorkspaceInvites, inviteToWorkspace, cancelWorkspaceInvite, listMyInvites, answerMyInvite, announceSessionStarted, announceWhenReported, listWorkspaceFiles, createWorkspaceFile, confirmWorkspaceFile, workspaceFileDownload, updateWorkspaceFile, deleteWorkspaceFile, createWorkspaceFolder, listWorkspaceFileVersions, listSandboxKeys, createSandboxKey, rotateSandboxKey, revokeSandboxKey, removeSandboxKey, aiVmFollow, aiVmUnfollow, aiVmStatus, aiVmConnect, aiVmUpdate, aiVmSignIn, aiVmWake, aiVmDisconnect, voiceIce, transcribeVoice, speakVoice, apiUrl } from './account.js'
|
|
23
|
+
import { readAccount, saveAccount, clearAccount, clearAccountIf, resumeAccount, startLink, waitForLink, fetchMe, signOut, revokeToken, accountFromProfile, renameSession, createAgentInvite, listAgents, agentDetails, listAccessTypes, listCollaborators, listGrants, putGrant, deleteGrant, inviteToSession, listSessionInvites, cancelSessionInvite, listWorkspaces, listOrgs, createWorkspace, getWorkspace, updateWorkspace, deleteWorkspace, putWorkspaceMember, removeWorkspaceMember, getAgentPlacement, putAgentPlacement, listOrgAgents, putWorkspaceAgent, deleteWorkspaceAgent, createWorkspaceAgentInvite, excludeSessionAgent, listExcludedSessionAgents, listSessionAgents, includeSessionAgent, setSessionWorkspace, moveSessionToWorkspace, listWorkspaceInvites, inviteToWorkspace, cancelWorkspaceInvite, listMyInvites, answerMyInvite, announceSessionStarted, announceWhenReported, listWorkspaceFiles, createWorkspaceFile, confirmWorkspaceFile, workspaceFileDownload, updateWorkspaceFile, deleteWorkspaceFile, createWorkspaceFolder, listWorkspaceFileVersions, listSandboxKeys, createSandboxKey, rotateSandboxKey, revokeSandboxKey, removeSandboxKey, aiVmFollow, aiVmUnfollow, aiVmStatus, aiVmConnect, aiVmUpdate, aiVmSignIn, aiVmWake, aiVmDisconnect, voiceIce, transcribeVoice, speakVoice, speakVoiceStream, apiUrl } from './account.js'
|
|
24
24
|
import { aiName } from './persona.js'
|
|
25
25
|
import { effectiveAccess, builtinType } from './session-access.js'
|
|
26
26
|
import { cleanSessionName, BAD_SESSION_NAME, SESSION_NAME_MAX } from './session-name.js'
|
|
@@ -37,6 +37,9 @@ import { envFilesIn, knownEnvFile, envValues } from './secret-import.js'
|
|
|
37
37
|
import { appWorkspaces } from './app-workspaces.js'
|
|
38
38
|
import { guessTool } from './tool-guess.js'
|
|
39
39
|
|
|
40
|
+
// A route's answer that streams through instead of going as JSON (an agent's speech).
|
|
41
|
+
const STREAMED = Symbol('streamed')
|
|
42
|
+
|
|
40
43
|
const TOOL_NAMES = ['Claude Code', 'Cursor', 'Codex', 'xAI', 'Windsurf', 'GitHub Copilot', 'Zed', 'Aider', 'Other']
|
|
41
44
|
const MAX_WS_FILE_BYTES = 500 * 1024 * 1024
|
|
42
45
|
const COLOR_RE = /^#[0-9a-f]{6}$/i
|
|
@@ -248,7 +251,7 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
|
|
|
248
251
|
// below — it returns earlier — so it needs no entry here.)
|
|
249
252
|
const UNRECORDED = new Set(['POST /api/report'])
|
|
250
253
|
// Sent many times a call (call setup, each clip of speech): only kept when slow or failed.
|
|
251
|
-
const QUIET_WHEN_OK = new Set(['POST /api/sessions/:id/voice', 'POST /api/sessions/:id/voice/clip', 'GET /api/sessions/:id/voice/speech'])
|
|
254
|
+
const QUIET_WHEN_OK = new Set(['POST /api/sessions/:id/voice', 'POST /api/sessions/:id/voice/clip', 'GET /api/sessions/:id/voice/speech', 'GET /api/sessions/:id/voice/speech-stream'])
|
|
252
255
|
function recordRoute (key, { startedAt, status, body, error }) {
|
|
253
256
|
// The reporter's own `enabled()` is the single gate on the "report" setting.
|
|
254
257
|
if (UNRECORDED.has(key)) return
|
|
@@ -715,6 +718,25 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
|
|
|
715
718
|
return spoken.get(line.id)
|
|
716
719
|
}
|
|
717
720
|
|
|
721
|
+
// The same, as speech that plays as it renders: Fluxions hears what was said in the call just
|
|
722
|
+
// before (other people's lines since the agent last spoke), and the API renders it once for every
|
|
723
|
+
// app in the call. The PCM goes straight through to the window.
|
|
724
|
+
async function voiceSpeechStream (s, lineId) {
|
|
725
|
+
const v = s.voice()
|
|
726
|
+
if (!v.in) throw httpError(409, 'You are not in the call.')
|
|
727
|
+
const lines = s.voiceTranscript({ call: v.call, limit: 1000 }).lines
|
|
728
|
+
const i = lines.findIndex((l) => l.id === lineId)
|
|
729
|
+
const line = lines[i]
|
|
730
|
+
if (!line || !line.spoken || !v.agents.some((a) => a.name === line.by)) throw httpError(404, 'That is not an agent\'s line in this call.')
|
|
731
|
+
const key = (s.members || []).find((m) => m && m.kind === 'agent' && m.name === line.by)?.key || ''
|
|
732
|
+
const agent = /^agent:[0-9a-f-]{36}$/i.test(key) ? key.slice(6) : ''
|
|
733
|
+
const earlier = lines.slice(0, i)
|
|
734
|
+
const lastOwn = earlier.map((l) => l.by).lastIndexOf(line.by)
|
|
735
|
+
const before = earlier.slice(lastOwn + 1).filter((l) => l.by !== line.by).slice(-8).map((l) => ({ by: l.by, text: l.text }))
|
|
736
|
+
const res = await asAccount((token) => speakVoiceStream({ token, text: line.text, by: line.by, agent, before }))
|
|
737
|
+
return { [STREAMED]: true, type: res.headers.get('content-type') || 'audio/L16; rate=24000; channels=1', body: res.body }
|
|
738
|
+
}
|
|
739
|
+
|
|
718
740
|
// Agent invites and the list of your agents come from the accounts API, as this computer's account.
|
|
719
741
|
// A 401 there is checked against /v1/me before it counts: only a token the API no longer knows
|
|
720
742
|
// signs the app out (an older API that doesn't take the app's token for these yet just errors).
|
|
@@ -1056,6 +1078,7 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
|
|
|
1056
1078
|
'GET /api/voice/ice': () => voiceServers(),
|
|
1057
1079
|
// An agent's line in the call, as speech.
|
|
1058
1080
|
'GET /api/sessions/:id/voice/speech': (b, id, url) => voiceSpeech(get(id), url.searchParams.get('line') || ''),
|
|
1081
|
+
'GET /api/sessions/:id/voice/speech-stream': (b, id, url) => voiceSpeechStream(get(id), url.searchParams.get('line') || ''),
|
|
1059
1082
|
// The composer says while someone types (and stops when they clear it or send).
|
|
1060
1083
|
'POST /api/sessions/:id/typing': (b, id) => get(id).setTyping(b.on !== false, { to: b.to || null }),
|
|
1061
1084
|
'POST /api/sessions/:id/claim': (b, id) => get(id).claim(b.pattern, b.note),
|
|
@@ -1309,6 +1332,12 @@ export async function startUi ({ port = 7420, onShutdown, preview = false, repor
|
|
|
1309
1332
|
const startedAt = Date.now()
|
|
1310
1333
|
try {
|
|
1311
1334
|
const out = await handler(body, sid, url, fid || aid || iid)
|
|
1335
|
+
// A reply that streams (an agent's speech): straight through as it comes.
|
|
1336
|
+
if (out && out[STREAMED]) {
|
|
1337
|
+
res.writeHead(200, { 'content-type': out.type, 'cache-control': 'no-store' })
|
|
1338
|
+
Readable.fromWeb(out.body).on('error', () => res.destroy()).pipe(res)
|
|
1339
|
+
return recordRoute(key, { startedAt, status: 200, body })
|
|
1340
|
+
}
|
|
1312
1341
|
json(200, out)
|
|
1313
1342
|
return recordRoute(key, { startedAt, status: 200, body })
|
|
1314
1343
|
} catch (err) {
|
package/src/voice.js
CHANGED
|
@@ -183,10 +183,15 @@ function agentState (doc, call, name, lines, now) {
|
|
|
183
183
|
return { state: '' }
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
+
// Whether a named agent can hear its name, from how Quilt wakes it (the relay's member list,
|
|
187
|
+
// wake.js): 'yes' at once, 'later' (on a timer, or at its person's next turn), 'no' (nothing wakes
|
|
188
|
+
// it), or '' when the list doesn't say.
|
|
189
|
+
const hearsBy = (method) => method === undefined ? '' : !method || method === 'none' ? 'no' : method === 'schedule' || method === 'turns' ? 'later' : 'yes'
|
|
190
|
+
|
|
186
191
|
/**
|
|
187
192
|
* The agents in call `call` (the one going on), while it is transcribed: those that joined it, and
|
|
188
|
-
* those just named in it that are on their way ('joining', until `joinBy
|
|
189
|
-
* the call shows unmuted until then, while it speaks (0: muted).
|
|
193
|
+
* those just named in it that are on their way ('joining', until `joinBy`, with `hears`: whether
|
|
194
|
+
* Quilt can wake it). `until`: an agent in the call shows unmuted until then, while it speaks (0: muted).
|
|
190
195
|
*/
|
|
191
196
|
export function callAgents (doc, call, members = [], now = Date.now()) {
|
|
192
197
|
if (!call || !takesAgents(doc, call) || !transcribeSetting(doc, members).on) return []
|
|
@@ -198,7 +203,7 @@ export function callAgents (doc, call, members = [], now = Date.now()) {
|
|
|
198
203
|
seen.add(m.name)
|
|
199
204
|
const st = agentState(doc, call, m.name, lines, now)
|
|
200
205
|
if (st.state === 'in') out.push({ name: m.name, state: 'in', until: agentOpenUntil(lines, [m.name]) })
|
|
201
|
-
else if (st.state === 'joining') out.push({ name: m.name, state: 'joining', until: 0, joinBy: st.joinBy })
|
|
206
|
+
else if (st.state === 'joining') out.push({ name: m.name, state: 'joining', until: 0, joinBy: st.joinBy, ...(hearsBy(m.wakeMethod) ? { hears: hearsBy(m.wakeMethod) } : {}) })
|
|
202
207
|
}
|
|
203
208
|
return out.sort((a, b) => a.name.localeCompare(b.name))
|
|
204
209
|
}
|