Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ SONIOX_API_KEY=
XAI_API_KEY=
# on|off: off tells TeamHub this deployment cannot run voice (no LiveKit).
TEAMHUB_VOICE_MEDIA=on
# 1|0: with no Soniox key, dictation runs on SenseVoiceSmall int8, a speech
# model of about 230 MB that Node Services downloads once into AGENT_HOME, and
# the dictated text is rewritten on your connected CLI. 0 never downloads it.
VOICE_LOCAL_ASR=1
# Gateways that accept base64 PCM events require json; the direct provider
# uses binary microphone frames. The key must match the configured endpoint.
VOICE_RUNTIME_XAI_LIVE_WEBSOCKET_URL=wss://api.x.ai/v1/realtime
Expand Down
17 changes: 17 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,23 @@ third_party/licenses/.
TeamHub and Voice Runtime images include this file at /app/NOTICE and
the license texts at /app/third_party/licenses/.

8. SpeakMore (cnYui/SpeakMore)
Copyright (c) 2026 Yui. MIT License.
Source: https://github.com/cnYui/SpeakMore
The long-recording segmentation and the dictation rewrite rules in
apps/voice-runtime/src/sensevoice-segments.ts and
apps/teamhub/internal/voicedictation/voicedictation.go are adapted from it.
License text: third_party/licenses/speakmore-MIT.txt

9. SenseVoiceSmall speech model and sherpa-onnx
Not shipped in this repository: Node Services downloads the int8 ONNX export
(csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17 on Hugging
Face) of FunAudioLLM/SenseVoiceSmall when dictation has no Soniox key. The
model is under the FunASR Model Open Source License:
https://github.com/modelscope/FunASR/blob/main/MODEL_LICENSE
It runs through sherpa-onnx (Apache License 2.0), a package dependency:
https://github.com/k2-fsa/sherpa-onnx

README demo materials
Files: assets/linger-story.webp, assets/linger-story.mp4
Metal 011 by ambientCG, released under CC0 1.0 Universal.
Expand Down
5 changes: 4 additions & 1 deletion apps/desktop/scripts/build-native-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@ const PLATFORMS = {

// Packages the services load at runtime by a name esbuild cannot see:
// createRequire, require.resolve of data files, or a native binding.
export const RUNTIME_PACKAGES = ["@livekit/local-inference"];
export const RUNTIME_PACKAGES = [
"@livekit/local-inference",
"sherpa-onnx-node",
];
// Packages that are model data rather than code: the installer leaves them
// out and Node Services downloads them when a feature first needs them
// (apps/node-services/src/model-packages.ts). Local models install
Expand Down
7 changes: 5 additions & 2 deletions apps/desktop/src/main/build-native-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,8 +388,11 @@ it("prunes unused browser viewer and non-legacy subtrees from pdfjs-dist", async
}
});

it("bundles word-extractor and ignores optional tesseract.js and canvas imports", () => {
expect(RUNTIME_PACKAGES).toEqual(["@livekit/local-inference"]);
it("copies native voice packages and ignores optional OCR and canvas imports", () => {
expect(RUNTIME_PACKAGES).toEqual([
"@livekit/local-inference",
"sherpa-onnx-node",
]);
expect(OPTIONAL_IMPORTS.has("tesseract.js")).toBe(true);
expect(OPTIONAL_IMPORTS.has("canvas")).toBe(true);
});
2 changes: 1 addition & 1 deletion apps/node-services/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
a producer may reuse its backing buffer before delivering the next chunk.
- The `document` role keeps its own port (4321 by default) on its own worker
thread (`src/document/main.ts`) because it installs jsdom globals and
replaces the global `Request`/`Response`. The `voice` role supervises separate ASR, recorder and Live child processes, each on a health port the system offers when it starts (`VOICE_WORKER_PORT`); it does not run audio jobs on the main thread. Voice workers follow TeamHub's effective provider keys (`GET /internal/v1/voice/provider-keys` with the `voice-runtime` credential): a Soniox key runs ASR and recorder, an xAI key runs Live. The role reconciles at startup, on TeamHub's `POST /v1/voice/workers:reconcile` (`node-services-internal` bearer), and every 60 seconds, so workers start, drain, or restart with a new key without restarting node-services. The reconcile route answers `{ready}` only after every wanted worker's health port reports it registered with LiveKit, or after 20 seconds, so TeamHub answers a key save once a voice session can be dispatched. Keys reach a worker only through its environment; a failed key fetch leaves the running workers unchanged. Other roles run on the main thread
replaces the global `Request`/`Response`. The `voice` role supervises separate ASR, recorder and Live child processes, each on a health port the system offers when it starts (`VOICE_WORKER_PORT`); it does not run audio jobs on the main thread. Voice workers follow TeamHub's effective provider keys (`GET /internal/v1/voice/provider-keys` with the `voice-runtime` credential): a Soniox key runs ASR and recorder, an xAI key runs Live. Without a Soniox key (and unless `VOICE_LOCAL_ASR=0`), the role downloads the SenseVoiceSmall int8 model into `AGENT_HOME/models/sensevoice-small-int8` (`src/voice/local-asr-model.ts`: resumable, region-ordered mirrors, pinned SHA-256) and runs the ASR worker on it for dictation only, with no recorder; `/voice/health` reports `local_asr` (`disabled`, `idle`, `downloading` or `ready`), which TeamHub reads to offer dictation. The role reconciles at startup, on TeamHub's `POST /v1/voice/workers:reconcile` (`node-services-internal` bearer), and every 60 seconds, so workers start, drain, or restart with a new key without restarting node-services. The reconcile route answers `{ready}` only after every wanted worker's health port reports it registered with LiveKit, or after 20 seconds, so TeamHub answers a key save once a voice session can be dispatched. Keys reach a worker only through its environment; a failed key fetch leaves the running workers unchanged. Other roles run on the main thread
and must not install process globals.
- `NODE_SERVICES_ROLES` selects roles as a comma-separated list. An unset or
empty value starts every role; an unknown role fails startup. Selected roles
Expand Down
7 changes: 7 additions & 0 deletions apps/node-services/src/agent/executor/http/model-call-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export interface ModelCallHttpRequest extends TextModelCallRequest {
}

const OUTPUT_NAME = /^[A-Za-z0-9_-]{1,64}$/u;
/** What the claude CLI takes after --model: it starts with a letter or digit,
* so it can never read as another flag. */
const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:/[\]-]*$/u;
/** Instructions and input share one character budget that keeps the prompt
* under the 3 MiB invocation limit even at three UTF-8 bytes per UTF-16 unit;
* Skill-based instructions such as the Profile prompt run past 200,000. */
Expand All @@ -44,6 +47,7 @@ export function readModelCallRequest(
"key",
"owner",
"effort",
"model",
"instructions",
"input",
"output",
Expand All @@ -63,6 +67,8 @@ export function readModelCallRequest(
(body.timeoutMs as number) < 1_000 ||
(body.timeoutMs as number) > 600_000)) ||
(body.sessionKey !== undefined && !isText(body.sessionKey, 1, 200)) ||
(body.model !== undefined &&
!(isText(body.model, 1, 100) && MODEL_NAME.test(body.model))) ||
(body.runOperationId !== undefined &&
(body.kind !== "approval" || !isText(body.runOperationId, 1, 200)))
)
Expand Down Expand Up @@ -100,6 +106,7 @@ export function readModelCallRequest(
...(body.effort === undefined
? {}
: { effort: body.effort as ModelCallEffort }),
...(body.model === undefined ? {} : { model: body.model }),
...(body.instructions === undefined
? {}
: { instructions: body.instructions }),
Expand Down
9 changes: 9 additions & 0 deletions apps/node-services/src/model-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const modelCallKinds = [
"wiki",
"profile",
"insight",
"dictation_polish",
] as const;
export type ModelCallKind = (typeof modelCallKinds)[number];

Expand Down Expand Up @@ -141,6 +142,14 @@ export const modelCallPolicies: Readonly<
attempts: 1,
timeoutMs: 60_000,
},
// The text goes into the Message box its author is about to send, so it
// waits its turn beside their chat and never swaps a Run out.
dictation_polish: {
priority: runPriorities.chat,
interactive: true,
attempts: 1,
timeoutMs: 9_000,
},
agent_memory: {
priority: 30,
interactive: false,
Expand Down
19 changes: 16 additions & 3 deletions apps/node-services/src/runtime-model-call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ export interface ModelPrompt {
readonly effort?: ModelCallEffort;
readonly instructions?: string;
readonly input: string;
/** The model a Claude Runtime runs the call on: an alias such as haiku or a
* catalog id. Omitted, the Runtime's default. Another Runtime, or a Computer
* release that cannot take it, ignores it. */
readonly model?: string;
/** One Runtime attempt, each retry and correction getting its own;
* omitted, the kind's default. */
readonly timeoutMs?: number;
Expand Down Expand Up @@ -485,6 +489,7 @@ interface CallRequest {
readonly effort?: ModelCallEffort;
readonly instructions?: string;
readonly input: string;
readonly model?: string;
readonly timeoutMs?: number;
readonly maxOutputChars?: number;
readonly schemaName?: string;
Expand Down Expand Up @@ -604,6 +609,7 @@ function callId(call: CallRequest): string {
call.effort ?? "low",
call.instructions ?? "",
call.input,
call.model ?? null,
call.schemaName ?? null,
call.outputSchema ?? null,
call.sessionKey ?? null,
Expand Down Expand Up @@ -925,10 +931,16 @@ async function invokeAttempt(
placement.computerId,
runtimeType,
);
// A call that names its model (dictation's rewrite) runs on it when the
// Runtime is Claude, whose CLI takes an alias such as haiku; the Gateway
// leaves the model off for a Computer that cannot decode it. Any other
// Runtime keeps the placed Agent's model.
const wireModel =
runtimeType === resolved.runtimeType
? resolved.wireModel
: defaultRuntimeModel(runtimeModels)?.runtimeModel;
call.model && runtimeType === "claude"
? call.model
: runtimeType === resolved.runtimeType
? resolved.wireModel
: defaultRuntimeModel(runtimeModels)?.runtimeModel;
const policy = modelCallPolicies[call.kind];
const breakerKey = backgroundBreakerKey(placement.computerId, runtimeType);
const modelsFingerprint = `${wireModel ?? ""}\n${runtimeModelsFingerprint(runtimeModels)}`;
Expand Down Expand Up @@ -1334,6 +1346,7 @@ function callRequest(
...(request.effort ? { effort: request.effort } : {}),
...(request.instructions ? { instructions: request.instructions } : {}),
input: request.input,
...(request.model ? { model: request.model } : {}),
...(request.timeoutMs === undefined
? {}
: { timeoutMs: request.timeoutMs }),
Expand Down
6 changes: 6 additions & 0 deletions apps/node-services/src/voice/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export interface VoiceConfig {
* packages come from its registry first. Global when unset.
*/
readonly region: Region;
/**
* Whether a deployment without a Soniox key downloads and runs the local
* speech model for dictation (VOICE_LOCAL_ASR, on unless "0").
*/
readonly localAsr: boolean;
}

export function readVoiceConfig(environment: NodeJS.ProcessEnv): VoiceConfig {
Expand All @@ -24,5 +29,6 @@ export function readVoiceConfig(environment: NodeJS.ProcessEnv): VoiceConfig {
environment,
),
region: environment.SIMPLEX_REGION === "cn" ? "cn" : "global",
localAsr: environment.VOICE_LOCAL_ASR?.trim() !== "0",
});
}
169 changes: 169 additions & 0 deletions apps/node-services/src/voice/local-asr-model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { createHash } from "node:crypto";
import {
createReadStream,
createWriteStream,
existsSync,
readFileSync,
statSync,
} from "node:fs";
import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import type { ReadableStream as WebReadableStream } from "node:stream/web";
import { pipeline } from "node:stream/promises";
import { orderByRegion, type Region } from "@linger/service-kit";

import { mirrorHome } from "../paths.js";

// SenseVoiceSmall int8 for sherpa-onnx, pinned to one revision so the bytes
// and the checksums below never drift apart.
const REPOSITORY =
"csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17";
const REVISION = "2365baeacb507f821a0c8120fcee3d484dba7a07";
// The second host serves the same files inside mainland China.
const HOSTS = ["https://huggingface.co", "https://hf-mirror.com"];
const COMPLETE = ".simplex-local-asr-model.json";
const DOWNLOAD_TIMEOUT_MS = 30 * 60_000;

export interface LocalAsrModelFile {
readonly name: string;
readonly bytes: number;
readonly sha256: string;
}

export const localAsrModelFiles: readonly LocalAsrModelFile[] = [
{
name: "model.int8.onnx",
bytes: 239_233_841,
sha256: "c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51",
},
{
name: "tokens.txt",
bytes: 315_894,
sha256: "f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc",
},
];

/** Where the model lives: beside the other downloaded model data. */
export function localAsrModelDirectory(
environment: NodeJS.ProcessEnv = process.env,
): string {
return path.join(mirrorHome(environment), "models", "sensevoice-small-int8");
}

/** Whether every model file was downloaded and checked. */
export function localAsrModelInstalled(
environment: NodeJS.ProcessEnv = process.env,
): boolean {
const directory = localAsrModelDirectory(environment);
try {
if (
readFileSync(path.join(directory, COMPLETE), "utf8") !==
JSON.stringify(localAsrModelFiles)
)
return false;
return localAsrModelFiles.every(
(file) => statSync(path.join(directory, file.name)).size === file.bytes,
);
} catch {
return false;
}
}

/**
* Downloads and checks the model files that are missing and returns the
* directory. An interrupted download resumes where it stopped, and a file
* already in the directory is kept when its checksum matches, so a copy from
* another install needs no download.
*/
export async function installLocalAsrModel(
environment: NodeJS.ProcessEnv,
options: { region: Region; signal?: AbortSignal; fetch?: typeof fetch },
): Promise<string> {
const directory = localAsrModelDirectory(environment);
const signal = options.signal ?? new AbortController().signal;
await mkdir(directory, { recursive: true });
for (const file of localAsrModelFiles)
await fetchModelFile(
file,
directory,
options.region,
options.fetch ?? fetch,
signal,
);
await writeFile(
path.join(directory, COMPLETE),
JSON.stringify(localAsrModelFiles),
);
return directory;
}

async function fetchModelFile(
file: LocalAsrModelFile,
directory: string,
region: Region,
fetchImpl: typeof fetch,
signal: AbortSignal,
) {
const target = path.join(directory, file.name);
if (existsSync(target) && (await checksum(target)) === file.sha256) return;
const partial = `${target}.part`;
let failure: unknown;
for (const url of orderByRegion(
region,
HOSTS.map(
(host) => `${host}/${REPOSITORY}/resolve/${REVISION}/${file.name}`,
),
)) {
try {
await fetchInto(url, partial, file.bytes, fetchImpl, signal);
if ((await checksum(partial)) !== file.sha256) {
await rm(partial, { force: true });
throw new Error(`${file.name} failed its checksum`);
}
await rename(partial, target);
return;
} catch (error) {
signal.throwIfAborted();
failure = error;
}
}
throw failure;
}

async function fetchInto(
url: string,
partial: string,
bytes: number,
fetchImpl: typeof fetch,
signal: AbortSignal,
) {
let have = (await stat(partial).catch(() => undefined))?.size ?? 0;
if (have > bytes) {
await rm(partial, { force: true });
have = 0;
}
// A partial that already has every byte is left to the checksum.
if (have === bytes) return;
const response = await fetchImpl(url, {
headers: have ? { range: `bytes=${have}-` } : {},
signal: AbortSignal.any([signal, AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)]),
});
if ((response.status !== 200 && response.status !== 206) || !response.body) {
await response.body?.cancel().catch(() => undefined);
throw new Error(`Model download answered ${response.status}`);
}
// A host that ignores the range sends the whole file again.
await pipeline(
Readable.fromWeb(response.body as WebReadableStream),
createWriteStream(partial, { flags: response.status === 206 ? "a" : "w" }),
{ signal },
);
}

async function checksum(file: string): Promise<string> {
const hash = createHash("sha256");
for await (const chunk of createReadStream(file))
hash.update(chunk as Buffer);
return hash.digest("hex");
}
Loading