@mulmoclaude/core 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{atomic-C_7YpMiM.cjs → atomic-DhUk8uiM.cjs} +2 -2
- package/dist/{atomic-C_7YpMiM.cjs.map → atomic-DhUk8uiM.cjs.map} +1 -1
- package/dist/collection/registry/server/index.cjs +21 -26
- package/dist/collection/registry/server/index.cjs.map +1 -1
- package/dist/collection/registry/server/index.js +18 -23
- package/dist/collection/registry/server/index.js.map +1 -1
- package/dist/collection/server/index.cjs +2 -2
- package/dist/collection/server/index.js +2 -2
- package/dist/collection-watchers/index.cjs +3 -3
- package/dist/collection-watchers/index.cjs.map +1 -1
- package/dist/collection-watchers/index.js +3 -3
- package/dist/{discovery-DSLgRQhN.cjs → discovery-B_sHig7n.cjs} +5 -5
- package/dist/{discovery-DSLgRQhN.cjs.map → discovery-B_sHig7n.cjs.map} +1 -1
- package/dist/{discovery-BSedPW8A.js → discovery-BvnXyUel.js} +3 -3
- package/dist/{discovery-BSedPW8A.js.map → discovery-BvnXyUel.js.map} +1 -1
- package/dist/dist-CsgSfWwR.cjs.map +1 -1
- package/dist/dist-D8zokgGo.js.map +1 -1
- package/dist/feeds/paths.cjs +1 -1
- package/dist/feeds/server/index.cjs +5 -5
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +4 -4
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/file-change/index.cjs +1 -1
- package/dist/file-change/index.cjs.map +1 -1
- package/dist/files/index.cjs +3 -3
- package/dist/files/index.cjs.map +1 -1
- package/dist/global-config/index.cjs +69 -0
- package/dist/global-config/index.cjs.map +1 -0
- package/dist/global-config/index.d.ts +13 -0
- package/dist/global-config/index.js +63 -0
- package/dist/global-config/index.js.map +1 -0
- package/dist/global-config/paths.d.ts +2 -0
- package/dist/global-config/schema.d.ts +17 -0
- package/dist/google/index.cjs +11 -7
- package/dist/google/index.cjs.map +1 -1
- package/dist/google/index.js +9 -5
- package/dist/google/index.js.map +1 -1
- package/dist/google/paths.d.ts +2 -0
- package/dist/notifier/index.cjs +1 -1
- package/dist/notifier/index.js +1 -1
- package/dist/{notifier-CKFVVwDP.cjs → notifier-DZJj0sOh.cjs} +2 -2
- package/dist/{notifier-CKFVVwDP.cjs.map → notifier-DZJj0sOh.cjs.map} +1 -1
- package/dist/{notifier-CQD8NljP.js → notifier-DhnwR82U.js} +2 -2
- package/dist/{notifier-CQD8NljP.js.map → notifier-DhnwR82U.js.map} +1 -1
- package/dist/paths-CkJxNZ7T.js +13 -0
- package/dist/paths-CkJxNZ7T.js.map +1 -0
- package/dist/paths-ClV946_f.cjs +25 -0
- package/dist/paths-ClV946_f.cjs.map +1 -0
- package/dist/plugin-vue/i18n.cjs.map +1 -1
- package/dist/plugin-vue/index.cjs +39 -10
- package/dist/plugin-vue/index.cjs.map +1 -1
- package/dist/plugin-vue/index.js +39 -10
- package/dist/plugin-vue/index.js.map +1 -1
- package/dist/{relPath-CgGi4-Nv.cjs → relPath-CTAjGdCL.cjs} +2 -2
- package/dist/{relPath-CgGi4-Nv.cjs.map → relPath-CTAjGdCL.cjs.map} +1 -1
- package/dist/remote-host/server/index.cjs +3 -2
- package/dist/remote-host/server/index.cjs.map +1 -1
- package/dist/remote-host/server/index.js +3 -2
- package/dist/remote-host/server/index.js.map +1 -1
- package/dist/remote-host-CtQjagPt.cjs.map +1 -1
- package/dist/{rolldown-runtime-D6vf50IK.cjs → rolldown-runtime-VH7oDXx4.cjs} +1 -1
- package/dist/scheduler/index.cjs +6 -4
- package/dist/scheduler/index.cjs.map +1 -1
- package/dist/scheduler/index.js +5 -3
- package/dist/scheduler/index.js.map +1 -1
- package/dist/{server-B78f_bnY.js → server-DJt6USBQ.js} +11 -7
- package/dist/{server-B78f_bnY.js.map → server-DJt6USBQ.js.map} +1 -1
- package/dist/{server-By4oSql2.cjs → server-DoyGZMPS.cjs} +14 -10
- package/dist/{server-By4oSql2.cjs.map → server-DoyGZMPS.cjs.map} +1 -1
- package/dist/skill-bridge/index.cjs +1 -1
- package/dist/skill-bridge/index.cjs.map +1 -1
- package/dist/utils/fetch.cjs +1 -1
- package/dist/utils/fetch.cjs.map +1 -1
- package/dist/utils/fetch.js +1 -1
- package/dist/utils/fetch.js.map +1 -1
- package/dist/whisper/client.cjs.map +1 -1
- package/dist/whisper/client.js.map +1 -1
- package/dist/whisper/index.cjs +1 -1
- package/dist/whisper/index.cjs.map +1 -1
- package/dist/wiki/index.cjs +2 -1
- package/dist/wiki/index.cjs.map +1 -1
- package/dist/wiki/index.js +2 -1
- package/dist/wiki/index.js.map +1 -1
- package/dist/wiki/paths.cjs +1 -1
- package/dist/wiki/server/index.cjs +5 -3
- package/dist/wiki/server/index.cjs.map +1 -1
- package/dist/wiki/server/index.js +4 -2
- package/dist/wiki/server/index.js.map +1 -1
- package/dist/workspace-setup/index.js.map +1 -1
- package/package.json +12 -6
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_rolldown_runtime = require("../rolldown-runtime-
|
|
2
|
+
const require_rolldown_runtime = require("../rolldown-runtime-VH7oDXx4.cjs");
|
|
3
3
|
const require_templatePath = require("../templatePath-27vUZowm.cjs");
|
|
4
4
|
let node_fs = require("node:fs");
|
|
5
5
|
let node_path = require("node:path");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/skill-bridge/index.ts"],"sourcesContent":["// @mulmoclaude/core/skill-bridge — the skill staging→active mirror RULE, shared by\n// MulmoClaude and MulmoTerminal so the two hosts can't drift on what crosses the\n// `.claude/` permission gate.\n//\n// The agent writes skill drafts under `data/skills/<slug>/` (a plain data dir, no\n// `.claude/` permission special-case). This package decides which writes are\n// allowlisted and mirrors them 1:1 into `.claude/skills/<slug>/` so Claude CLI's\n// skill discovery + the collection engine pick them up. It also mirrors a\n// `rm -rf data/skills/<slug>` delete.\n//\n// What crosses — a FIXED ALLOWLIST, not the whole dir:\n// SKILL.md the skill body Claude CLI reads\n// schema.json the collection definition (a \"collection skill\" ships one)\n// templates/<path> action templates a schema's `actions` reference — exactly the\n// set the schema validator accepts (`isSafeActionTemplatePath`)\n// Everything else (README.md, assets/, arbitrary nesting) stays staging-side.\n//\n// Pure rule + fs ops, parameterized by `workspaceRoot` (passed in, not read from a\n// host module) so either host can call it. Each host wires this into its own hook /\n// PostToolUse path and triggers its own config refresh afterward.\nimport path from \"node:path\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { isSafeActionTemplatePath } from \"../collection/server/templatePath\";\n\nconst DATA_SKILLS_DIR = path.join(\"data\", \"skills\");\nconst CLAUDE_SKILLS_DIR = path.join(\".claude\", \"skills\");\nconst SKILL_FILENAME = \"SKILL.md\";\nconst SCHEMA_FILENAME = \"schema.json\";\n\n// Slugs follow Claude Code's skill-name convention: lowercase ASCII letters/digits\n// with single-hyphen separators. Strict so a typo / traversal never reaches the dest.\n// eslint-disable-next-line security/detect-unsafe-regex -- input is a basename slice ≤64 chars; bounded backtracking.\nconst SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n// `rm -rf data/skills/<slug>` matcher. `match[1]` is the flag run (must contain a\n// recursive flag); `match[2]` is the slug. Wildcards / the parent dir / non-recursive\n// `rm` are intentionally NOT matched (a non-recursive rm can't delete the dir anyway,\n// so mirroring would desync the trees).\n// eslint-disable-next-line security/detect-unsafe-regex -- single-line captured Bash command; bounded.\nconst RM_RE = /^\\s*rm\\s+((?:-[a-zA-Z]+\\s+)+)['\"]?data\\/skills\\/([a-z0-9-]+)\\/?['\"]?\\s*$/;\nconst RECURSIVE_FLAG_RE = /[rR]/;\n\n/** A staging file cleared to cross the `.claude/` gate. */\nexport interface BridgeTarget {\n /** The skill slug (the dir directly under data/skills/). */\n slug: string;\n /** Path segments BELOW the slug dir, e.g. `[\"SKILL.md\"]`, `[\"templates\",\"x.md\"]`.\n * Used verbatim for both source and destination so the mirror is 1:1. */\n relSegments: string[];\n}\n\n/** `<workspaceRoot>/data/skills/<slug>` — the staging dir for a skill. */\nexport function dataSkillDir(workspaceRoot: string, slug: string): string {\n return path.join(workspaceRoot, DATA_SKILLS_DIR, slug);\n}\n\n/** `<workspaceRoot>/.claude/skills/<slug>` — the active dir Claude CLI discovers. */\nexport function claudeSkillDir(workspaceRoot: string, slug: string): string {\n return path.join(workspaceRoot, CLAUDE_SKILLS_DIR, slug);\n}\n\n// Allowlist a path below the slug dir: SKILL.md / schema.json at the top, or a safe\n// `templates/<path>` (the same predicate the schema validator uses, so what a schema\n// can declare is exactly what crosses). Everything else → false.\nfunction isAllowlisted(relSegments: string[]): boolean {\n if (relSegments.length === 1) {\n return relSegments[0] === SKILL_FILENAME || relSegments[0] === SCHEMA_FILENAME;\n }\n return isSafeActionTemplatePath(relSegments.join(\"/\"));\n}\n\n/** Resolve a Write/Edit path to the staging file it mirrors, or null when it isn't a\n * bridged file (not under `data/skills/<slug>/`, bad slug, or off the allowlist). */\nexport function bridgeTargetFromDataPath(workspaceRoot: string, filePath: string): BridgeTarget | null {\n const staging = path.join(workspaceRoot, DATA_SKILLS_DIR);\n const rel = path.relative(staging, filePath);\n if (!rel || rel.startsWith(\"..\") || path.isAbsolute(rel)) return null;\n const [slug, ...relSegments] = rel.split(path.sep);\n if (!slug || relSegments.length === 0) return null; // need at least `<slug>/<file>`\n if (!SLUG_RE.test(slug)) return null;\n if (!isAllowlisted(relSegments)) return null;\n return { slug, relSegments };\n}\n\n/** Extract the slug from a Bash `rm -rf data/skills/<slug>` command, or null on any\n * mismatch (wildcards, paths outside staging, non-recursive `rm`). */\nexport function slugFromRmCommand(command: string): string | null {\n const match = RM_RE.exec(command);\n if (!match) return null;\n // Both groups are mandatory in RM_RE; the \"\" defaults fail both tests below,\n // i.e. they land on the same `null` a non-matching command already gets.\n const [, flags = \"\", slug = \"\"] = match;\n if (!RECURSIVE_FLAG_RE.test(flags)) return null;\n return SLUG_RE.test(slug) ? slug : null;\n}\n\n/** Atomic mirror of one allowlisted staging file → its active path: write a tmp file\n * in the dest dir, then rename onto the canonical path (atomic on POSIX; both paths\n * share a filesystem). A killed mid-write leaves a harmless tmp and the previous\n * SKILL.md intact. Returns the resolved src/dest for logging. */\nexport function mirrorSkillWrite(workspaceRoot: string, target: BridgeTarget): { src: string; dest: string } {\n const { slug, relSegments } = target;\n const src = path.join(dataSkillDir(workspaceRoot, slug), ...relSegments);\n const content = readFileSync(src, \"utf-8\");\n const dest = path.join(claudeSkillDir(workspaceRoot, slug), ...relSegments);\n const destDir = path.dirname(dest);\n mkdirSync(destDir, { recursive: true }); // covers templates/ + the slug dir on first install\n const tmp = path.join(destDir, `.${path.basename(dest)}.${process.pid}.tmp`);\n writeFileSync(tmp, content, \"utf-8\");\n renameSync(tmp, dest);\n return { src, dest };\n}\n\n/** Remove the active skill dir (mirrors a staging `rm -rf`). Returns the dest. */\nexport function mirrorSkillDelete(workspaceRoot: string, slug: string): { dest: string } {\n const dest = claudeSkillDir(workspaceRoot, slug);\n rmSync(dest, { recursive: true, force: true });\n return { dest };\n}\n"],"mappings":";;;;;;;AAwBA,IAAM,kBAAkB,UAAA,QAAK,KAAK,QAAQ,QAAQ;AAClD,IAAM,oBAAoB,UAAA,QAAK,KAAK,WAAW,QAAQ;AACvD,IAAM,iBAAiB;AACvB,IAAM,kBAAkB;AAKxB,IAAM,UAAU;AAOhB,IAAM,QAAQ;AACd,IAAM,oBAAoB;;AAY1B,SAAgB,aAAa,eAAuB,MAAsB;CACxE,OAAO,UAAA,QAAK,KAAK,eAAe,iBAAiB,IAAI;AACvD;;AAGA,SAAgB,eAAe,eAAuB,MAAsB;CAC1E,OAAO,UAAA,QAAK,KAAK,eAAe,mBAAmB,IAAI;AACzD;AAKA,SAAS,cAAc,aAAgC;CACrD,IAAI,YAAY,WAAW,GACzB,OAAO,YAAY,OAAO,kBAAkB,YAAY,OAAO;CAEjE,OAAO,qBAAA,yBAAyB,YAAY,KAAK,GAAG,CAAC;AACvD;;;AAIA,SAAgB,yBAAyB,eAAuB,UAAuC;CACrG,MAAM,UAAU,UAAA,QAAK,KAAK,eAAe,eAAe;CACxD,MAAM,MAAM,UAAA,QAAK,SAAS,SAAS,QAAQ;CAC3C,IAAI,CAAC,OAAO,IAAI,WAAW,IAAI,KAAK,UAAA,QAAK,WAAW,GAAG,GAAG,OAAO;CACjE,MAAM,CAAC,MAAM,GAAG,eAAe,IAAI,MAAM,UAAA,QAAK,GAAG;CACjD,IAAI,CAAC,QAAQ,YAAY,WAAW,GAAG,OAAO;CAC9C,IAAI,CAAC,QAAQ,KAAK,IAAI,GAAG,OAAO;CAChC,IAAI,CAAC,cAAc,WAAW,GAAG,OAAO;CACxC,OAAO;EAAE;EAAM;CAAY;AAC7B;;;AAIA,SAAgB,kBAAkB,SAAgC;CAChE,MAAM,QAAQ,MAAM,KAAK,OAAO;CAChC,IAAI,CAAC,OAAO,OAAO;CAGnB,MAAM,GAAG,QAAQ,IAAI,OAAO,MAAM;CAClC,IAAI,CAAC,kBAAkB,KAAK,KAAK,GAAG,OAAO;CAC3C,OAAO,QAAQ,KAAK,IAAI,IAAI,OAAO;AACrC;;;;;AAMA,SAAgB,iBAAiB,eAAuB,QAAqD;CAC3G,MAAM,EAAE,MAAM,gBAAgB;CAC9B,MAAM,MAAM,UAAA,QAAK,KAAK,aAAa,eAAe,IAAI,GAAG,GAAG,WAAW;CACvE,MAAM,WAAA,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/skill-bridge/index.ts"],"sourcesContent":["// @mulmoclaude/core/skill-bridge — the skill staging→active mirror RULE, shared by\n// MulmoClaude and MulmoTerminal so the two hosts can't drift on what crosses the\n// `.claude/` permission gate.\n//\n// The agent writes skill drafts under `data/skills/<slug>/` (a plain data dir, no\n// `.claude/` permission special-case). This package decides which writes are\n// allowlisted and mirrors them 1:1 into `.claude/skills/<slug>/` so Claude CLI's\n// skill discovery + the collection engine pick them up. It also mirrors a\n// `rm -rf data/skills/<slug>` delete.\n//\n// What crosses — a FIXED ALLOWLIST, not the whole dir:\n// SKILL.md the skill body Claude CLI reads\n// schema.json the collection definition (a \"collection skill\" ships one)\n// templates/<path> action templates a schema's `actions` reference — exactly the\n// set the schema validator accepts (`isSafeActionTemplatePath`)\n// Everything else (README.md, assets/, arbitrary nesting) stays staging-side.\n//\n// Pure rule + fs ops, parameterized by `workspaceRoot` (passed in, not read from a\n// host module) so either host can call it. Each host wires this into its own hook /\n// PostToolUse path and triggers its own config refresh afterward.\nimport path from \"node:path\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { isSafeActionTemplatePath } from \"../collection/server/templatePath\";\n\nconst DATA_SKILLS_DIR = path.join(\"data\", \"skills\");\nconst CLAUDE_SKILLS_DIR = path.join(\".claude\", \"skills\");\nconst SKILL_FILENAME = \"SKILL.md\";\nconst SCHEMA_FILENAME = \"schema.json\";\n\n// Slugs follow Claude Code's skill-name convention: lowercase ASCII letters/digits\n// with single-hyphen separators. Strict so a typo / traversal never reaches the dest.\n// eslint-disable-next-line security/detect-unsafe-regex -- input is a basename slice ≤64 chars; bounded backtracking.\nconst SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n// `rm -rf data/skills/<slug>` matcher. `match[1]` is the flag run (must contain a\n// recursive flag); `match[2]` is the slug. Wildcards / the parent dir / non-recursive\n// `rm` are intentionally NOT matched (a non-recursive rm can't delete the dir anyway,\n// so mirroring would desync the trees).\n// eslint-disable-next-line security/detect-unsafe-regex -- single-line captured Bash command; bounded.\nconst RM_RE = /^\\s*rm\\s+((?:-[a-zA-Z]+\\s+)+)['\"]?data\\/skills\\/([a-z0-9-]+)\\/?['\"]?\\s*$/;\nconst RECURSIVE_FLAG_RE = /[rR]/;\n\n/** A staging file cleared to cross the `.claude/` gate. */\nexport interface BridgeTarget {\n /** The skill slug (the dir directly under data/skills/). */\n slug: string;\n /** Path segments BELOW the slug dir, e.g. `[\"SKILL.md\"]`, `[\"templates\",\"x.md\"]`.\n * Used verbatim for both source and destination so the mirror is 1:1. */\n relSegments: string[];\n}\n\n/** `<workspaceRoot>/data/skills/<slug>` — the staging dir for a skill. */\nexport function dataSkillDir(workspaceRoot: string, slug: string): string {\n return path.join(workspaceRoot, DATA_SKILLS_DIR, slug);\n}\n\n/** `<workspaceRoot>/.claude/skills/<slug>` — the active dir Claude CLI discovers. */\nexport function claudeSkillDir(workspaceRoot: string, slug: string): string {\n return path.join(workspaceRoot, CLAUDE_SKILLS_DIR, slug);\n}\n\n// Allowlist a path below the slug dir: SKILL.md / schema.json at the top, or a safe\n// `templates/<path>` (the same predicate the schema validator uses, so what a schema\n// can declare is exactly what crosses). Everything else → false.\nfunction isAllowlisted(relSegments: string[]): boolean {\n if (relSegments.length === 1) {\n return relSegments[0] === SKILL_FILENAME || relSegments[0] === SCHEMA_FILENAME;\n }\n return isSafeActionTemplatePath(relSegments.join(\"/\"));\n}\n\n/** Resolve a Write/Edit path to the staging file it mirrors, or null when it isn't a\n * bridged file (not under `data/skills/<slug>/`, bad slug, or off the allowlist). */\nexport function bridgeTargetFromDataPath(workspaceRoot: string, filePath: string): BridgeTarget | null {\n const staging = path.join(workspaceRoot, DATA_SKILLS_DIR);\n const rel = path.relative(staging, filePath);\n if (!rel || rel.startsWith(\"..\") || path.isAbsolute(rel)) return null;\n const [slug, ...relSegments] = rel.split(path.sep);\n if (!slug || relSegments.length === 0) return null; // need at least `<slug>/<file>`\n if (!SLUG_RE.test(slug)) return null;\n if (!isAllowlisted(relSegments)) return null;\n return { slug, relSegments };\n}\n\n/** Extract the slug from a Bash `rm -rf data/skills/<slug>` command, or null on any\n * mismatch (wildcards, paths outside staging, non-recursive `rm`). */\nexport function slugFromRmCommand(command: string): string | null {\n const match = RM_RE.exec(command);\n if (!match) return null;\n // Both groups are mandatory in RM_RE; the \"\" defaults fail both tests below,\n // i.e. they land on the same `null` a non-matching command already gets.\n const [, flags = \"\", slug = \"\"] = match;\n if (!RECURSIVE_FLAG_RE.test(flags)) return null;\n return SLUG_RE.test(slug) ? slug : null;\n}\n\n/** Atomic mirror of one allowlisted staging file → its active path: write a tmp file\n * in the dest dir, then rename onto the canonical path (atomic on POSIX; both paths\n * share a filesystem). A killed mid-write leaves a harmless tmp and the previous\n * SKILL.md intact. Returns the resolved src/dest for logging. */\nexport function mirrorSkillWrite(workspaceRoot: string, target: BridgeTarget): { src: string; dest: string } {\n const { slug, relSegments } = target;\n const src = path.join(dataSkillDir(workspaceRoot, slug), ...relSegments);\n const content = readFileSync(src, \"utf-8\");\n const dest = path.join(claudeSkillDir(workspaceRoot, slug), ...relSegments);\n const destDir = path.dirname(dest);\n mkdirSync(destDir, { recursive: true }); // covers templates/ + the slug dir on first install\n const tmp = path.join(destDir, `.${path.basename(dest)}.${process.pid}.tmp`);\n writeFileSync(tmp, content, \"utf-8\");\n renameSync(tmp, dest);\n return { src, dest };\n}\n\n/** Remove the active skill dir (mirrors a staging `rm -rf`). Returns the dest. */\nexport function mirrorSkillDelete(workspaceRoot: string, slug: string): { dest: string } {\n const dest = claudeSkillDir(workspaceRoot, slug);\n rmSync(dest, { recursive: true, force: true });\n return { dest };\n}\n"],"mappings":";;;;;;;AAwBA,IAAM,kBAAkB,UAAA,QAAK,KAAK,QAAQ,QAAQ;AAClD,IAAM,oBAAoB,UAAA,QAAK,KAAK,WAAW,QAAQ;AACvD,IAAM,iBAAiB;AACvB,IAAM,kBAAkB;AAKxB,IAAM,UAAU;AAOhB,IAAM,QAAQ;AACd,IAAM,oBAAoB;;AAY1B,SAAgB,aAAa,eAAuB,MAAsB;CACxE,OAAO,UAAA,QAAK,KAAK,eAAe,iBAAiB,IAAI;AACvD;;AAGA,SAAgB,eAAe,eAAuB,MAAsB;CAC1E,OAAO,UAAA,QAAK,KAAK,eAAe,mBAAmB,IAAI;AACzD;AAKA,SAAS,cAAc,aAAgC;CACrD,IAAI,YAAY,WAAW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AAK,SAAS,IAAI,UAAA,QAAK,SAAS,IAAI,EAAE,GAAG,QAAQ,IAAI,KAAK;CAC3E,CAAA,GAAA,QAAA,cAAA,CAAc,KAAK,SAAS,OAAO;CACnC,CAAA,GAAA,QAAA,WAAA,CAAW,KAAK,IAAI;CACpB,OAAO;EAAE;EAAK;CAAK;AACrB;;AAGA,SAAgB,kBAAkB,eAAuB,MAAgC;CACvF,MAAM,OAAO,eAAe,eAAe,IAAI;CAC/C,CAAA,GAAA,QAAA,OAAA,CAAO,MAAM;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;CAC7C,OAAO,EAAE,KAAK;AAChB"}
|
package/dist/utils/fetch.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
var DEFAULT_FETCH_TIMEOUT_MS =
|
|
2
|
+
var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
|
|
3
3
|
/**
|
|
4
4
|
* `fetch` with a finite timeout. Rejects with a `TimeoutError` once `timeoutMs`
|
|
5
5
|
* elapses. Composes with a caller-supplied `signal` so external cancellation
|
package/dist/utils/fetch.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","names":[],"sources":["../../src/utils/fetch.ts"],"sourcesContent":["// Canonical `fetch` with a finite timeout for the whole monorepo. The host\n// (`server/utils/fetch.ts`), the collection registry engine and the Google\n// engine all re-export / import this one copy — before #2398 the same helper\n// existed three times, so #2221's caller-signal-composition fix could only land\n// in one of them. Server-only surface (`@mulmoclaude/core/fetch`).\n\nconst ONE_SECOND_MS = 1_000;\n\n// 10 s is long enough for a healthy round-trip (localhost or a healthy upstream)\n// but short enough that a stuck peer returns an error well before any client-side\n// tool-call timeout fires. Callers talking to slow external APIs override via\n// `timeoutMs`.\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10 * ONE_SECOND_MS;\n\n// `Parameters<typeof fetch>[1]` avoids referencing the ambient `RequestInit`\n// type, which ESLint's `no-undef` rule trips over in the server config. The\n// resulting type is identical to `RequestInit & { timeoutMs?: number }`.\nexport type FetchWithTimeoutInit = Parameters<typeof fetch>[1] & { timeoutMs?: number | undefined };\n\n/**\n * `fetch` with a finite timeout. Rejects with a `TimeoutError` once `timeoutMs`\n * elapses. Composes with a caller-supplied `signal` so external cancellation\n * still works (#2221 — do not overwrite the caller's signal).\n */\nexport async function fetchWithTimeout(url: string | URL, init: FetchWithTimeoutInit = {}): Promise<Response> {\n const { timeoutMs = DEFAULT_FETCH_TIMEOUT_MS, signal: callerSignal, ...rest } = init;\n\n // Surface an already-aborted caller signal before we touch the network at all,\n // so callers get a deterministic rejection and no fetch side-effects.\n if (callerSignal?.aborted) {\n throw callerSignal.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(new DOMException(`fetch timed out after ${timeoutMs}ms`, \"TimeoutError\"));\n }, timeoutMs);\n\n const unsubscribeCaller = bridgeExternalSignal(callerSignal, controller);\n\n try {\n return await fetch(url, { ...rest, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n unsubscribeCaller?.();\n }\n}\n\n// Propagate aborts from a caller-supplied signal into our internal controller.\n// Returns a disposer so the listener is removed on normal completion — otherwise\n// a long-lived caller signal would leak listeners across many fetches.\nfunction bridgeExternalSignal(external: AbortSignal | null | undefined, controller: AbortController): (() => void) | null {\n if (!external) return null;\n const onAbort = () => controller.abort(external.reason);\n external.addEventListener(\"abort\", onAbort, { once: true });\n return () => external.removeEventListener(\"abort\", onAbort);\n}\n"],"mappings":";AAYA,IAAa,2BAA2B
|
|
1
|
+
{"version":3,"file":"fetch.cjs","names":[],"sources":["../../src/utils/fetch.ts"],"sourcesContent":["// Canonical `fetch` with a finite timeout for the whole monorepo. The host\n// (`server/utils/fetch.ts`), the collection registry engine and the Google\n// engine all re-export / import this one copy — before #2398 the same helper\n// existed three times, so #2221's caller-signal-composition fix could only land\n// in one of them. Server-only surface (`@mulmoclaude/core/fetch`).\n\nconst ONE_SECOND_MS = 1_000;\n\n// 10 s is long enough for a healthy round-trip (localhost or a healthy upstream)\n// but short enough that a stuck peer returns an error well before any client-side\n// tool-call timeout fires. Callers talking to slow external APIs override via\n// `timeoutMs`.\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10 * ONE_SECOND_MS;\n\n// `Parameters<typeof fetch>[1]` avoids referencing the ambient `RequestInit`\n// type, which ESLint's `no-undef` rule trips over in the server config. The\n// resulting type is identical to `RequestInit & { timeoutMs?: number }`.\nexport type FetchWithTimeoutInit = Parameters<typeof fetch>[1] & { timeoutMs?: number | undefined };\n\n/**\n * `fetch` with a finite timeout. Rejects with a `TimeoutError` once `timeoutMs`\n * elapses. Composes with a caller-supplied `signal` so external cancellation\n * still works (#2221 — do not overwrite the caller's signal).\n */\nexport async function fetchWithTimeout(url: string | URL, init: FetchWithTimeoutInit = {}): Promise<Response> {\n const { timeoutMs = DEFAULT_FETCH_TIMEOUT_MS, signal: callerSignal, ...rest } = init;\n\n // Surface an already-aborted caller signal before we touch the network at all,\n // so callers get a deterministic rejection and no fetch side-effects.\n if (callerSignal?.aborted) {\n throw callerSignal.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(new DOMException(`fetch timed out after ${timeoutMs}ms`, \"TimeoutError\"));\n }, timeoutMs);\n\n const unsubscribeCaller = bridgeExternalSignal(callerSignal, controller);\n\n try {\n return await fetch(url, { ...rest, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n unsubscribeCaller?.();\n }\n}\n\n// Propagate aborts from a caller-supplied signal into our internal controller.\n// Returns a disposer so the listener is removed on normal completion — otherwise\n// a long-lived caller signal would leak listeners across many fetches.\nfunction bridgeExternalSignal(external: AbortSignal | null | undefined, controller: AbortController): (() => void) | null {\n if (!external) return null;\n const onAbort = () => controller.abort(external.reason);\n external.addEventListener(\"abort\", onAbort, { once: true });\n return () => external.removeEventListener(\"abort\", onAbort);\n}\n"],"mappings":";AAYA,IAAa,2BAA2B;;;;;;AAYxC,eAAsB,iBAAiB,KAAmB,OAA6B,CAAC,GAAsB;CAC5G,MAAM,EAAE,YAAY,0BAA0B,QAAQ,cAAc,GAAG,SAAS;CAIhF,IAAI,cAAc,SAChB,MAAM,aAAa,UAAU,IAAI,aAAa,WAAW,YAAY;CAGvE,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,QAAQ,iBAAiB;EAC7B,WAAW,MAAM,IAAI,aAAa,yBAAyB,UAAU,KAAK,cAAc,CAAC;CAC3F,GAAG,SAAS;CAEZ,MAAM,oBAAoB,qBAAqB,cAAc,UAAU;CAEvE,IAAI;EACF,OAAO,MAAM,MAAM,KAAK;GAAE,GAAG;GAAM,QAAQ,WAAW;EAAO,CAAC;CAChE,UAAU;EACR,aAAa,KAAK;EAClB,oBAAoB;CACtB;AACF;AAKA,SAAS,qBAAqB,UAA0C,YAAkD;CACxH,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,gBAAgB,WAAW,MAAM,SAAS,MAAM;CACtD,SAAS,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAC1D,aAAa,SAAS,oBAAoB,SAAS,OAAO;AAC5D"}
|
package/dist/utils/fetch.js
CHANGED
package/dist/utils/fetch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.js","names":[],"sources":["../../src/utils/fetch.ts"],"sourcesContent":["// Canonical `fetch` with a finite timeout for the whole monorepo. The host\n// (`server/utils/fetch.ts`), the collection registry engine and the Google\n// engine all re-export / import this one copy — before #2398 the same helper\n// existed three times, so #2221's caller-signal-composition fix could only land\n// in one of them. Server-only surface (`@mulmoclaude/core/fetch`).\n\nconst ONE_SECOND_MS = 1_000;\n\n// 10 s is long enough for a healthy round-trip (localhost or a healthy upstream)\n// but short enough that a stuck peer returns an error well before any client-side\n// tool-call timeout fires. Callers talking to slow external APIs override via\n// `timeoutMs`.\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10 * ONE_SECOND_MS;\n\n// `Parameters<typeof fetch>[1]` avoids referencing the ambient `RequestInit`\n// type, which ESLint's `no-undef` rule trips over in the server config. The\n// resulting type is identical to `RequestInit & { timeoutMs?: number }`.\nexport type FetchWithTimeoutInit = Parameters<typeof fetch>[1] & { timeoutMs?: number | undefined };\n\n/**\n * `fetch` with a finite timeout. Rejects with a `TimeoutError` once `timeoutMs`\n * elapses. Composes with a caller-supplied `signal` so external cancellation\n * still works (#2221 — do not overwrite the caller's signal).\n */\nexport async function fetchWithTimeout(url: string | URL, init: FetchWithTimeoutInit = {}): Promise<Response> {\n const { timeoutMs = DEFAULT_FETCH_TIMEOUT_MS, signal: callerSignal, ...rest } = init;\n\n // Surface an already-aborted caller signal before we touch the network at all,\n // so callers get a deterministic rejection and no fetch side-effects.\n if (callerSignal?.aborted) {\n throw callerSignal.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(new DOMException(`fetch timed out after ${timeoutMs}ms`, \"TimeoutError\"));\n }, timeoutMs);\n\n const unsubscribeCaller = bridgeExternalSignal(callerSignal, controller);\n\n try {\n return await fetch(url, { ...rest, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n unsubscribeCaller?.();\n }\n}\n\n// Propagate aborts from a caller-supplied signal into our internal controller.\n// Returns a disposer so the listener is removed on normal completion — otherwise\n// a long-lived caller signal would leak listeners across many fetches.\nfunction bridgeExternalSignal(external: AbortSignal | null | undefined, controller: AbortController): (() => void) | null {\n if (!external) return null;\n const onAbort = () => controller.abort(external.reason);\n external.addEventListener(\"abort\", onAbort, { once: true });\n return () => external.removeEventListener(\"abort\", onAbort);\n}\n"],"mappings":"AAYA,IAAa,2BAA2B
|
|
1
|
+
{"version":3,"file":"fetch.js","names":[],"sources":["../../src/utils/fetch.ts"],"sourcesContent":["// Canonical `fetch` with a finite timeout for the whole monorepo. The host\n// (`server/utils/fetch.ts`), the collection registry engine and the Google\n// engine all re-export / import this one copy — before #2398 the same helper\n// existed three times, so #2221's caller-signal-composition fix could only land\n// in one of them. Server-only surface (`@mulmoclaude/core/fetch`).\n\nconst ONE_SECOND_MS = 1_000;\n\n// 10 s is long enough for a healthy round-trip (localhost or a healthy upstream)\n// but short enough that a stuck peer returns an error well before any client-side\n// tool-call timeout fires. Callers talking to slow external APIs override via\n// `timeoutMs`.\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10 * ONE_SECOND_MS;\n\n// `Parameters<typeof fetch>[1]` avoids referencing the ambient `RequestInit`\n// type, which ESLint's `no-undef` rule trips over in the server config. The\n// resulting type is identical to `RequestInit & { timeoutMs?: number }`.\nexport type FetchWithTimeoutInit = Parameters<typeof fetch>[1] & { timeoutMs?: number | undefined };\n\n/**\n * `fetch` with a finite timeout. Rejects with a `TimeoutError` once `timeoutMs`\n * elapses. Composes with a caller-supplied `signal` so external cancellation\n * still works (#2221 — do not overwrite the caller's signal).\n */\nexport async function fetchWithTimeout(url: string | URL, init: FetchWithTimeoutInit = {}): Promise<Response> {\n const { timeoutMs = DEFAULT_FETCH_TIMEOUT_MS, signal: callerSignal, ...rest } = init;\n\n // Surface an already-aborted caller signal before we touch the network at all,\n // so callers get a deterministic rejection and no fetch side-effects.\n if (callerSignal?.aborted) {\n throw callerSignal.reason ?? new DOMException(\"Aborted\", \"AbortError\");\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(new DOMException(`fetch timed out after ${timeoutMs}ms`, \"TimeoutError\"));\n }, timeoutMs);\n\n const unsubscribeCaller = bridgeExternalSignal(callerSignal, controller);\n\n try {\n return await fetch(url, { ...rest, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n unsubscribeCaller?.();\n }\n}\n\n// Propagate aborts from a caller-supplied signal into our internal controller.\n// Returns a disposer so the listener is removed on normal completion — otherwise\n// a long-lived caller signal would leak listeners across many fetches.\nfunction bridgeExternalSignal(external: AbortSignal | null | undefined, controller: AbortController): (() => void) | null {\n if (!external) return null;\n const onAbort = () => controller.abort(external.reason);\n external.addEventListener(\"abort\", onAbort, { once: true });\n return () => external.removeEventListener(\"abort\", onAbort);\n}\n"],"mappings":"AAYA,IAAa,2BAA2B;;;;;;AAYxC,eAAsB,iBAAiB,KAAmB,OAA6B,CAAC,GAAsB;CAC5G,MAAM,EAAE,YAAY,0BAA0B,QAAQ,cAAc,GAAG,SAAS;CAIhF,IAAI,cAAc,SAChB,MAAM,aAAa,UAAU,IAAI,aAAa,WAAW,YAAY;CAGvE,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,QAAQ,iBAAiB;EAC7B,WAAW,MAAM,IAAI,aAAa,yBAAyB,UAAU,KAAK,cAAc,CAAC;CAC3F,GAAG,SAAS;CAEZ,MAAM,oBAAoB,qBAAqB,cAAc,UAAU;CAEvE,IAAI;EACF,OAAO,MAAM,MAAM,KAAK;GAAE,GAAG;GAAM,QAAQ,WAAW;EAAO,CAAC;CAChE,UAAU;EACR,aAAa,KAAK;EAClB,oBAAoB;CACtB;AACF;AAKA,SAAS,qBAAqB,UAA0C,YAAkD;CACxH,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,gBAAgB,WAAW,MAAM,SAAS,MAAM;CACtD,SAAS,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAC1D,aAAa,SAAS,oBAAoB,SAAS,OAAO;AAC5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":[],"sources":["../../src/whisper/client-helpers.ts","../../src/whisper/client.ts"],"sourcesContent":["// Pure, framework-neutral helpers for the browser voice-capture controller.\n// Kept separate from `client.ts` so the audio math and VAD state machine can be\n// unit-tested without a DOM / MediaRecorder / Web Audio environment.\n\nexport function computeRms(buffer: Float32Array): number {\n let sum = 0;\n for (const sample of buffer) sum += sample * sample;\n return Math.sqrt(sum / buffer.length);\n}\n\n/** The recorder mime can carry a codec suffix (`audio/webm;codecs=opus`); the\n * Blob container type is just the part before the `;`. */\nexport function containerTypeFromMime(mimeType: string): string {\n return mimeType.split(\";\")[0] || \"audio/webm\";\n}\n\nexport interface VadState {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n}\n\nexport interface VadConfig {\n readonly speechRms: number;\n readonly silenceMs: number;\n readonly maxSegmentMs: number;\n}\n\nexport interface VadDecision {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n readonly cut: boolean;\n}\n\nfunction isSpeech(rms: number, config: VadConfig): boolean {\n return rms > config.speechRms;\n}\n\nfunction nextSilenceStart(state: VadState, rms: number, nowMs: number, config: VadConfig): number | null {\n if (isSpeech(rms, config)) return null;\n if (state.hasSpeech && state.silenceStart === null) return nowMs;\n return state.silenceStart;\n}\n\nfunction silenceExceeded(state: VadState, rms: number, nowMs: number, config: VadConfig): boolean {\n if (isSpeech(rms, config) || !state.hasSpeech || state.silenceStart === null) return false;\n return nowMs - state.silenceStart > config.silenceMs;\n}\n\n/** Advance the pause-detector one tick: fold the current RMS/time into the\n * segment state and decide whether the segment should be force-cut (either a\n * long-enough silence after speech, or the max-segment length reached). */\nexport function evaluateVad(state: VadState, segmentStartMs: number, rms: number, nowMs: number, config: VadConfig): VadDecision {\n const hasSpeech = isSpeech(rms, config) || state.hasSpeech;\n const silenceStart = nextSilenceStart(state, rms, nowMs, config);\n const maxCut = hasSpeech && nowMs - segmentStartMs > config.maxSegmentMs;\n return { hasSpeech, silenceStart, cut: silenceExceeded(state, rms, nowMs, config) || maxCut };\n}\n","// @mulmoclaude/core/whisper/client — framework-neutral browser capture controller.\n// Records one utterance at a time with MediaRecorder, segments on pauses via a\n// Web Audio VAD, and sends each segment through an injected transport. State is\n// pushed via `onState`; the host wraps this into its own reactivity (Vue refs,\n// React state, …). No framework dependency. See plans/done/feat-extract-whisper-package.md.\n\nimport { computeRms, containerTypeFromMime, evaluateVad, type VadConfig } from \"./client-helpers.ts\";\n\n// Map a UI locale to a Whisper language code. UI language is a strong prior for\n// the spoken language; \"auto\" lets Whisper detect it from the audio.\nconst LOCALE_TO_WHISPER: Record<string, string> = {\n en: \"en\",\n ja: \"ja\",\n zh: \"zh\",\n ko: \"ko\",\n es: \"es\",\n \"pt-BR\": \"pt\",\n fr: \"fr\",\n de: \"de\",\n};\n\nexport function localeToWhisperLanguage(locale: string): string {\n return LOCALE_TO_WHISPER[locale] ?? \"auto\";\n}\n\n// VAD tuning. RMS over [-1,1] float samples; a pause is SILENCE_MS of\n// sub-threshold level after speech. MAX_SEGMENT_MS force-cuts a long unbroken\n// utterance so no clip exceeds Whisper's 30s window or the server's size cap.\nconst SPEECH_RMS = 0.015;\nconst SILENCE_MS = 800;\nconst MAX_SEGMENT_MS = 20_000;\nconst MONITOR_INTERVAL_MS = 100;\nconst AVAILABILITY_POLL_MS = 2_000;\nconst VAD_CONFIG: VadConfig = { speechRms: SPEECH_RMS, silenceMs: SILENCE_MS, maxSegmentMs: MAX_SEGMENT_MS };\n\nfunction pickRecorderMime(): string | undefined {\n const candidates = [\"audio/webm;codecs=opus\", \"audio/webm\", \"audio/mp4\"];\n if (typeof MediaRecorder === \"undefined\") return undefined;\n return candidates.find((type) => MediaRecorder.isTypeSupported(type));\n}\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n // eslint-disable-next-line @typescript-eslint/no-base-to-string -- FileReader.result is `string | ArrayBuffer | null`; readAsDataURL always yields the string branch, and the rule cannot narrow it.\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(reader.error ?? new Error(\"FileReader failed\"));\n reader.readAsDataURL(blob);\n });\n}\n\nfunction toMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nexport interface VoiceCaptureTransport {\n /** Transcribe one segment. Throws on failure. */\n transcribe: (dataUrl: string, language: string) => Promise<{ text: string }>;\n /** Current readiness. `downloading` true keeps the controller polling so it\n * flips to ready as soon as a model download finishes. */\n getStatus: () => Promise<{ ready: boolean; downloading: boolean }>;\n}\n\nexport interface VoiceCaptureState {\n available: boolean;\n listening: boolean;\n transcribing: boolean;\n}\n\nexport interface VoiceCaptureCallbacks {\n /** A recognized (non-empty) segment transcript. */\n onTranscript: (text: string) => void;\n /** A segment produced no speech. */\n onEmpty?: (() => void) | undefined;\n /** A recoverable error message (transport failure, permission denied, etc.). */\n onError?: ((message: string) => void) | undefined;\n /** Pushed whenever available/listening/transcribing changes. */\n onState?: ((state: VoiceCaptureState) => void) | undefined;\n}\n\nexport interface VoiceCapture {\n refreshAvailability: () => Promise<void>;\n start: () => Promise<boolean>;\n stop: () => void;\n dispose: () => void;\n}\n\nexport interface CaptureStateController {\n setAvailable: (value: boolean) => void;\n setListening: (value: boolean) => void;\n setPending: (delta: number) => void;\n isListening: () => boolean;\n}\n\n// Owns the three observable flags. Each setter emits only on an actual change so\n// the host's reactivity never churns on a no-op write. `pending` is a private\n// counter; `transcribing` is true exactly while at least one send is in flight.\nexport function createCaptureState(onState?: (state: VoiceCaptureState) => void): CaptureStateController {\n let available = false;\n let listening = false;\n let transcribing = false;\n let pending = 0;\n\n function emit(): void {\n onState?.({ available, listening, transcribing });\n }\n function setAvailable(value: boolean): void {\n if (available !== value) {\n available = value;\n emit();\n }\n }\n function setListening(value: boolean): void {\n if (listening !== value) {\n listening = value;\n emit();\n }\n }\n function setPending(delta: number): void {\n pending += delta;\n const next = pending > 0;\n if (transcribing !== next) {\n transcribing = next;\n emit();\n }\n }\n\n return { setAvailable, setListening, setPending, isListening: () => listening };\n}\n\nexport interface AvailabilityPoller {\n refresh: () => Promise<void>;\n stop: () => void;\n}\n\n// Owns the polling timer. `refresh` mirrors transport readiness into\n// `setAvailable`; while a model is downloading it self-schedules so `available`\n// flips as soon as the download finishes. A `getStatus` throw fails closed\n// (unavailable) and tears the timer down.\nexport function createAvailabilityPoller(transport: VoiceCaptureTransport, setAvailable: (value: boolean) => void): AvailabilityPoller {\n let availabilityPollHandle: number | null = null;\n\n function stop(): void {\n if (availabilityPollHandle !== null) {\n window.clearInterval(availabilityPollHandle);\n availabilityPollHandle = null;\n }\n }\n\n async function refresh(): Promise<void> {\n let status: { ready: boolean; downloading: boolean };\n try {\n status = await transport.getStatus();\n } catch {\n setAvailable(false);\n stop();\n return;\n }\n setAvailable(status.ready);\n if (status.downloading) {\n if (availabilityPollHandle === null) {\n availabilityPollHandle = window.setInterval(() => {\n void refresh();\n }, AVAILABILITY_POLL_MS);\n }\n } else {\n stop();\n }\n }\n\n return { refresh, stop };\n}\n\nexport interface SegmentQueueOptions {\n transport: VoiceCaptureTransport;\n language: () => string;\n callbacks: VoiceCaptureCallbacks;\n setPending: (delta: number) => void;\n // Read-only epoch seam: the queue never mutates the generation, it only reads\n // the parent's current value to drop segments captured under an older session.\n getGeneration: () => number;\n}\n\nexport interface SegmentQueue {\n enqueue: (blob: Blob, gen: number) => void;\n}\n\n// Owns the serialized send chain. Each blob is transcribed in capture order; the\n// generation is checked at entry and again after transcription so a segment\n// belonging to a session the user already left is dropped silently.\nexport function createSegmentQueue(options: SegmentQueueOptions): SegmentQueue {\n const { transport, language, callbacks, setPending, getGeneration } = options;\n let queue: Promise<void> = Promise.resolve();\n\n async function sendSegment(blob: Blob, gen: number): Promise<void> {\n if (gen !== getGeneration()) return;\n try {\n const dataUrl = await blobToDataUrl(blob);\n const result = await transport.transcribe(dataUrl, language());\n if (gen !== getGeneration()) return;\n const text = result.text.trim();\n if (text.length === 0) callbacks.onEmpty?.();\n else callbacks.onTranscript(text);\n } catch (err) {\n // Generation-guard the failure path too: a send rejected after stop()/\n // session change belongs to a session the user already left.\n if (gen === getGeneration()) callbacks.onError?.(toMessage(err));\n }\n }\n\n // Serialize sends so transcripts append in capture order; `pending` keeps\n // `transcribing` true from enqueue until the send resolves.\n function enqueue(blob: Blob, gen: number): void {\n setPending(1);\n queue = queue\n .then(() => sendSegment(blob, gen))\n .catch(() => undefined)\n .finally(() => setPending(-1));\n }\n\n return { enqueue };\n}\n\nexport interface AudioGraph {\n /** True between `attach()` and the next `teardown()`. */\n isAttached: () => boolean;\n /** Read the current PCM window into an internal buffer and return it.\n * Callers must not mutate the returned array. */\n sample: () => Float32Array;\n /** Live mic stream — the outer needs it to hand to MediaRecorder. */\n getStream: () => MediaStream | null;\n /** Attach a fresh mic stream: create AudioContext + AnalyserNode + VAD buffer,\n * connect the source. Called only by `bootstrapCapture` after the caller has\n * passed the stale-generation / permission checks. */\n attach: (stream: MediaStream) => void;\n /** Close the AudioContext, stop the mic tracks, null everything. Safe to\n * call before `attach()` or twice in a row. */\n teardown: () => void;\n}\n\n// Owns the browser-side audio pipeline: mic stream + AudioContext + AnalyserNode\n// + the reusable Float32 buffer VAD reads samples into. Separated from\n// `createVoiceCapture` so its four browser-API fields don't inflate the parent\n// factory's line count and so the setup/teardown ordering is in one place.\nfunction createAudioGraph(): AudioGraph {\n let stream: MediaStream | null = null;\n let audioCtx: AudioContext | null = null;\n let analyser: AnalyserNode | null = null;\n let vadBuffer = new Float32Array(0);\n\n function attach(nextStream: MediaStream): void {\n stream = nextStream;\n audioCtx = new AudioContext();\n analyser = audioCtx.createAnalyser();\n analyser.fftSize = 2048;\n vadBuffer = new Float32Array(analyser.fftSize);\n audioCtx.createMediaStreamSource(nextStream).connect(analyser);\n }\n\n function sample(): Float32Array {\n analyser?.getFloatTimeDomainData(vadBuffer);\n return vadBuffer;\n }\n\n function teardown(): void {\n if (audioCtx) {\n audioCtx.close().catch(() => undefined);\n audioCtx = null;\n }\n analyser = null;\n stream?.getTracks().forEach((track) => track.stop());\n stream = null;\n }\n\n return { isAttached: () => analyser !== null, sample, getStream: () => stream, attach, teardown };\n}\n\ninterface BootstrappedCapture {\n audioGraph: AudioGraph;\n mimeType: string;\n}\n\n// Acquire the mic + probe MediaRecorder support + wire an AudioGraph, returning\n// null (with `callbacks.onError` fired) on any recoverable failure. Deliberately\n// does NOT touch `state` or start the recorder — the caller commits the session\n// only after this resolves successfully, so a stale `generation` detected mid-\n// flight can drop the tracks and bail without partially publishing state.\nasync function bootstrapCapture(callbacks: VoiceCaptureCallbacks, generationAtStart: number, generationNow: () => number): Promise<BootstrappedCapture | null> {\n const mimeType = pickRecorderMime() ?? \"\";\n if (!mimeType || !navigator.mediaDevices?.getUserMedia) {\n callbacks.onError?.(\"unsupported\");\n return null;\n }\n let acquired: MediaStream;\n try {\n acquired = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch {\n callbacks.onError?.(\"permission-denied\");\n return null;\n }\n if (generationAtStart !== generationNow()) {\n acquired.getTracks().forEach((track) => track.stop());\n return null;\n }\n const audioGraph = createAudioGraph();\n try {\n audioGraph.attach(acquired);\n } catch (err) {\n // teardown() is null-safe and closes any half-created AudioContext AND\n // stops the mic tracks — the pre-refactor code only stopped tracks and\n // leaked the context (codex/CodeRabbit findings on this PR).\n audioGraph.teardown();\n throw err;\n }\n return { audioGraph, mimeType };\n}\n\nexport interface RecorderSession {\n isRecording: () => boolean;\n hadSpeech: () => boolean;\n markSpeech: () => void;\n /** Start a new segment on `stream`, tagged with `gen`. Resets per-segment\n * state (chunks + hadSpeech) synchronously so a subsequent VAD tick sees\n * a fresh window. */\n startNext: (stream: MediaStream, mimeType: string, gen: number) => void;\n /** Force-close the current segment (silence exceeded or MAX_SEGMENT_MS). */\n cut: () => void;\n}\n\ninterface RecorderSessionDeps {\n /** Fires each time a segment finishes. The parent decides whether to\n * restart (via `session.startNext`) and whether to enqueue the blob. */\n onSegmentEnd: (blob: Blob, hadSpeech: boolean, gen: number) => void;\n}\n\n// Owns MediaRecorder + its per-segment scratchpad (chunks, hadSpeech, gen,\n// mimeType). The parent keeps VAD state and the global generation, and calls\n// `startNext` on both initial-start and post-onstop restart paths.\nfunction createRecorderSession(deps: RecorderSessionDeps): RecorderSession {\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let segmentHasSpeech = false;\n let sessionGen = 0;\n let sessionMimeType = \"\";\n\n function onStop(): void {\n // Snapshot BEFORE the parent's onSegmentEnd callback runs; `startNext`\n // (if the parent chooses to restart) will clear chunks synchronously.\n const hadSpeech = segmentHasSpeech;\n const gen = sessionGen;\n const blob = new Blob(chunks, { type: containerTypeFromMime(sessionMimeType) });\n deps.onSegmentEnd(blob, hadSpeech, gen);\n }\n\n function startNext(stream: MediaStream, mimeType: string, gen: number): void {\n chunks = [];\n segmentHasSpeech = false;\n sessionGen = gen;\n sessionMimeType = mimeType;\n recorder = new MediaRecorder(stream, { mimeType });\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) chunks.push(event.data);\n };\n recorder.onstop = onStop;\n recorder.start();\n }\n\n return {\n isRecording: () => recorder?.state === \"recording\",\n hadSpeech: () => segmentHasSpeech,\n markSpeech: () => {\n segmentHasSpeech = true;\n },\n startNext,\n cut: () => {\n if (recorder?.state === \"recording\") recorder.stop();\n },\n };\n}\n\n// Zero-values used to seed a fresh `CaptureRuntime` at the top of every\n// `createVoiceCapture` call. Kept module-scope so the seed doesn't inflate the\n// factory's line count.\nconst INITIAL_RUNTIME: Readonly<CaptureRuntime> = {\n audioGraph: null,\n monitorHandle: null,\n mimeType: \"\",\n silenceStart: null,\n segmentStart: 0,\n generation: 0,\n startInFlight: false,\n};\n\n// Mutable capture-time state, kept as one object so module-scope helpers\n// (`stopCapture`, `monitorTick`) can be typed against one shape rather than\n// threading each field through their signatures.\ninterface CaptureRuntime {\n audioGraph: AudioGraph | null;\n monitorHandle: number | null;\n mimeType: string;\n silenceStart: number | null;\n segmentStart: number;\n /** Bumped on stop(); segments captured under an older value are dropped so a\n * late transcript never leaks across sessions. */\n generation: number;\n /** Single-flight guard on start() — true between entry and completion so a\n * second start can't race the first before `listening` flips. */\n startInFlight: boolean;\n}\n\n// Tear down the browser-side resources. `state.setListening(false)` MUST happen\n// BEFORE `session.cut()` so the parent's onSegmentEnd callback sees\n// isListening()===false and does NOT restart. The monitor interval MUST clear\n// BEFORE `audioGraph.teardown()` so a scheduled tick can't run against a\n// half-closed AudioContext.\nfunction stopCapture(runtime: CaptureRuntime, state: CaptureStateController, session: RecorderSession): void {\n runtime.generation += 1;\n state.setListening(false);\n if (runtime.monitorHandle !== null) {\n window.clearInterval(runtime.monitorHandle);\n runtime.monitorHandle = null;\n }\n session.cut();\n runtime.audioGraph?.teardown();\n runtime.audioGraph = null;\n}\n\n// One VAD tick against the audio graph's current window. No-op when the graph\n// is not attached (defensive: `stopCapture` clears `monitorHandle` before\n// `audioGraph.teardown()`, so this is the belt-and-braces for any late fire).\nfunction monitorTick(runtime: CaptureRuntime, session: RecorderSession): void {\n if (!runtime.audioGraph?.isAttached()) return;\n const rms = computeRms(runtime.audioGraph.sample());\n const {\n hasSpeech,\n silenceStart: nextSilence,\n cut,\n } = evaluateVad({ hasSpeech: session.hadSpeech(), silenceStart: runtime.silenceStart }, runtime.segmentStart, rms, Date.now(), VAD_CONFIG);\n if (hasSpeech) session.markSpeech();\n runtime.silenceStart = nextSilence;\n if (cut) session.cut();\n}\n\nexport function createVoiceCapture(transport: VoiceCaptureTransport, language: () => string, callbacks: VoiceCaptureCallbacks): VoiceCapture {\n const state = createCaptureState(callbacks.onState);\n const poller = createAvailabilityPoller(transport, state.setAvailable);\n const runtime: CaptureRuntime = { ...INITIAL_RUNTIME };\n const segments = createSegmentQueue({ transport, language, callbacks, setPending: state.setPending, getGeneration: () => runtime.generation });\n\n const session = createRecorderSession({ onSegmentEnd: handleSegmentEnd });\n\n function handleSegmentEnd(blob: Blob, hadSpeech: boolean, gen: number): void {\n // Restart FIRST so audio-loss between segments is minimal; the snapshot\n // in blob/hadSpeech/gen is already independent of session state.\n if (state.isListening()) startRecorder();\n if (hadSpeech && blob.size > 0 && gen === runtime.generation) segments.enqueue(blob, gen);\n }\n\n function startRecorder(): void {\n const stream = runtime.audioGraph?.getStream();\n if (!stream) return;\n runtime.silenceStart = null;\n runtime.segmentStart = Date.now();\n session.startNext(stream, runtime.mimeType, runtime.generation);\n }\n\n async function start(): Promise<boolean> {\n if (runtime.startInFlight || state.isListening()) return true;\n runtime.startInFlight = true;\n const startGen = runtime.generation;\n try {\n const capture = await bootstrapCapture(callbacks, startGen, () => runtime.generation);\n if (!capture) return false;\n runtime.audioGraph = capture.audioGraph;\n runtime.mimeType = capture.mimeType;\n state.setListening(true);\n startRecorder();\n runtime.monitorHandle = window.setInterval(() => monitorTick(runtime, session), MONITOR_INTERVAL_MS);\n return true;\n } finally {\n runtime.startInFlight = false;\n }\n }\n\n function stop(): void {\n stopCapture(runtime, state, session);\n }\n\n function dispose(): void {\n poller.stop();\n stop();\n }\n\n return { refreshAvailability: poller.refresh, start, stop, dispose };\n}\n"],"mappings":";;AAIA,SAAgB,WAAW,QAA8B;CACvD,IAAI,MAAM;CACV,KAAK,MAAM,UAAU,QAAQ,OAAO,SAAS;CAC7C,OAAO,KAAK,KAAK,MAAM,OAAO,MAAM;AACtC;;;AAIA,SAAgB,sBAAsB,UAA0B;CAC9D,OAAO,SAAS,MAAM,GAAG,CAAC,CAAC,MAAM;AACnC;AAmBA,SAAS,SAAS,KAAa,QAA4B;CACzD,OAAO,MAAM,OAAO;AACtB;AAEA,SAAS,iBAAiB,OAAiB,KAAa,OAAe,QAAkC;CACvG,IAAI,SAAS,KAAK,MAAM,GAAG,OAAO;CAClC,IAAI,MAAM,aAAa,MAAM,iBAAiB,MAAM,OAAO;CAC3D,OAAO,MAAM;AACf;AAEA,SAAS,gBAAgB,OAAiB,KAAa,OAAe,QAA4B;CAChG,IAAI,SAAS,KAAK,MAAM,KAAK,CAAC,MAAM,aAAa,MAAM,iBAAiB,MAAM,OAAO;CACrF,OAAO,QAAQ,MAAM,eAAe,OAAO;AAC7C;;;;AAKA,SAAgB,YAAY,OAAiB,gBAAwB,KAAa,OAAe,QAAgC;CAC/H,MAAM,YAAY,SAAS,KAAK,MAAM,KAAK,MAAM;CACjD,MAAM,eAAe,iBAAiB,OAAO,KAAK,OAAO,MAAM;CAC/D,MAAM,SAAS,aAAa,QAAQ,iBAAiB,OAAO;CAC5D,OAAO;EAAE;EAAW;EAAc,KAAK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O;GACrB,QAAQ,aAAa,QAAQ;GAC7B,QAAQ,WAAW,QAAQ;GAC3B,MAAM,aAAa,IAAI;GACvB,cAAc;GACd,QAAQ,gBAAgB,OAAO,kBAAkB,YAAY,SAAS,OAAO,GAAG,mBAAmB;GACnG,OAAO;EACT,UAAU;GACR,QAAQ,gBAAgB;EAC1B;CACF;CAEA,SAAS,OAAa;EACpB,YAAY,SAAS,OAAO,OAAO;CACrC;CAEA,SAAS,UAAgB;EACvB,OAAO,KAAK;EACZ,KAAK;CACP;CAEA,OAAO;EAAE,qBAAqB,OAAO;EAAS;EAAO;EAAM;CAAQ;AACrE"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":[],"sources":["../../src/whisper/client-helpers.ts","../../src/whisper/client.ts"],"sourcesContent":["// Pure, framework-neutral helpers for the browser voice-capture controller.\n// Kept separate from `client.ts` so the audio math and VAD state machine can be\n// unit-tested without a DOM / MediaRecorder / Web Audio environment.\n\nexport function computeRms(buffer: Float32Array): number {\n let sum = 0;\n for (const sample of buffer) sum += sample * sample;\n return Math.sqrt(sum / buffer.length);\n}\n\n/** The recorder mime can carry a codec suffix (`audio/webm;codecs=opus`); the\n * Blob container type is just the part before the `;`. */\nexport function containerTypeFromMime(mimeType: string): string {\n return mimeType.split(\";\")[0] || \"audio/webm\";\n}\n\nexport interface VadState {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n}\n\nexport interface VadConfig {\n readonly speechRms: number;\n readonly silenceMs: number;\n readonly maxSegmentMs: number;\n}\n\nexport interface VadDecision {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n readonly cut: boolean;\n}\n\nfunction isSpeech(rms: number, config: VadConfig): boolean {\n return rms > config.speechRms;\n}\n\nfunction nextSilenceStart(state: VadState, rms: number, nowMs: number, config: VadConfig): number | null {\n if (isSpeech(rms, config)) return null;\n if (state.hasSpeech && state.silenceStart === null) return nowMs;\n return state.silenceStart;\n}\n\nfunction silenceExceeded(state: VadState, rms: number, nowMs: number, config: VadConfig): boolean {\n if (isSpeech(rms, config) || !state.hasSpeech || state.silenceStart === null) return false;\n return nowMs - state.silenceStart > config.silenceMs;\n}\n\n/** Advance the pause-detector one tick: fold the current RMS/time into the\n * segment state and decide whether the segment should be force-cut (either a\n * long-enough silence after speech, or the max-segment length reached). */\nexport function evaluateVad(state: VadState, segmentStartMs: number, rms: number, nowMs: number, config: VadConfig): VadDecision {\n const hasSpeech = isSpeech(rms, config) || state.hasSpeech;\n const silenceStart = nextSilenceStart(state, rms, nowMs, config);\n const maxCut = hasSpeech && nowMs - segmentStartMs > config.maxSegmentMs;\n return { hasSpeech, silenceStart, cut: silenceExceeded(state, rms, nowMs, config) || maxCut };\n}\n","// @mulmoclaude/core/whisper/client — framework-neutral browser capture controller.\n// Records one utterance at a time with MediaRecorder, segments on pauses via a\n// Web Audio VAD, and sends each segment through an injected transport. State is\n// pushed via `onState`; the host wraps this into its own reactivity (Vue refs,\n// React state, …). No framework dependency. See plans/done/feat-extract-whisper-package.md.\n\nimport { computeRms, containerTypeFromMime, evaluateVad, type VadConfig } from \"./client-helpers.ts\";\n\n// Map a UI locale to a Whisper language code. UI language is a strong prior for\n// the spoken language; \"auto\" lets Whisper detect it from the audio.\nconst LOCALE_TO_WHISPER: Record<string, string> = {\n en: \"en\",\n ja: \"ja\",\n zh: \"zh\",\n ko: \"ko\",\n es: \"es\",\n \"pt-BR\": \"pt\",\n fr: \"fr\",\n de: \"de\",\n};\n\nexport function localeToWhisperLanguage(locale: string): string {\n return LOCALE_TO_WHISPER[locale] ?? \"auto\";\n}\n\n// VAD tuning. RMS over [-1,1] float samples; a pause is SILENCE_MS of\n// sub-threshold level after speech. MAX_SEGMENT_MS force-cuts a long unbroken\n// utterance so no clip exceeds Whisper's 30s window or the server's size cap.\nconst SPEECH_RMS = 0.015;\nconst SILENCE_MS = 800;\nconst MAX_SEGMENT_MS = 20_000;\nconst MONITOR_INTERVAL_MS = 100;\nconst AVAILABILITY_POLL_MS = 2_000;\nconst VAD_CONFIG: VadConfig = { speechRms: SPEECH_RMS, silenceMs: SILENCE_MS, maxSegmentMs: MAX_SEGMENT_MS };\n\nfunction pickRecorderMime(): string | undefined {\n const candidates = [\"audio/webm;codecs=opus\", \"audio/webm\", \"audio/mp4\"];\n if (typeof MediaRecorder === \"undefined\") return undefined;\n return candidates.find((type) => MediaRecorder.isTypeSupported(type));\n}\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n // eslint-disable-next-line @typescript-eslint/no-base-to-string -- FileReader.result is `string | ArrayBuffer | null`; readAsDataURL always yields the string branch, and the rule cannot narrow it.\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(reader.error ?? new Error(\"FileReader failed\"));\n reader.readAsDataURL(blob);\n });\n}\n\nfunction toMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nexport interface VoiceCaptureTransport {\n /** Transcribe one segment. Throws on failure. */\n transcribe: (dataUrl: string, language: string) => Promise<{ text: string }>;\n /** Current readiness. `downloading` true keeps the controller polling so it\n * flips to ready as soon as a model download finishes. */\n getStatus: () => Promise<{ ready: boolean; downloading: boolean }>;\n}\n\nexport interface VoiceCaptureState {\n available: boolean;\n listening: boolean;\n transcribing: boolean;\n}\n\nexport interface VoiceCaptureCallbacks {\n /** A recognized (non-empty) segment transcript. */\n onTranscript: (text: string) => void;\n /** A segment produced no speech. */\n onEmpty?: (() => void) | undefined;\n /** A recoverable error message (transport failure, permission denied, etc.). */\n onError?: ((message: string) => void) | undefined;\n /** Pushed whenever available/listening/transcribing changes. */\n onState?: ((state: VoiceCaptureState) => void) | undefined;\n}\n\nexport interface VoiceCapture {\n refreshAvailability: () => Promise<void>;\n start: () => Promise<boolean>;\n stop: () => void;\n dispose: () => void;\n}\n\nexport interface CaptureStateController {\n setAvailable: (value: boolean) => void;\n setListening: (value: boolean) => void;\n setPending: (delta: number) => void;\n isListening: () => boolean;\n}\n\n// Owns the three observable flags. Each setter emits only on an actual change so\n// the host's reactivity never churns on a no-op write. `pending` is a private\n// counter; `transcribing` is true exactly while at least one send is in flight.\nexport function createCaptureState(onState?: (state: VoiceCaptureState) => void): CaptureStateController {\n let available = false;\n let listening = false;\n let transcribing = false;\n let pending = 0;\n\n function emit(): void {\n onState?.({ available, listening, transcribing });\n }\n function setAvailable(value: boolean): void {\n if (available !== value) {\n available = value;\n emit();\n }\n }\n function setListening(value: boolean): void {\n if (listening !== value) {\n listening = value;\n emit();\n }\n }\n function setPending(delta: number): void {\n pending += delta;\n const next = pending > 0;\n if (transcribing !== next) {\n transcribing = next;\n emit();\n }\n }\n\n return { setAvailable, setListening, setPending, isListening: () => listening };\n}\n\nexport interface AvailabilityPoller {\n refresh: () => Promise<void>;\n stop: () => void;\n}\n\n// Owns the polling timer. `refresh` mirrors transport readiness into\n// `setAvailable`; while a model is downloading it self-schedules so `available`\n// flips as soon as the download finishes. A `getStatus` throw fails closed\n// (unavailable) and tears the timer down.\nexport function createAvailabilityPoller(transport: VoiceCaptureTransport, setAvailable: (value: boolean) => void): AvailabilityPoller {\n let availabilityPollHandle: number | null = null;\n\n function stop(): void {\n if (availabilityPollHandle !== null) {\n window.clearInterval(availabilityPollHandle);\n availabilityPollHandle = null;\n }\n }\n\n async function refresh(): Promise<void> {\n let status: { ready: boolean; downloading: boolean };\n try {\n status = await transport.getStatus();\n } catch {\n setAvailable(false);\n stop();\n return;\n }\n setAvailable(status.ready);\n if (status.downloading) {\n if (availabilityPollHandle === null) {\n availabilityPollHandle = window.setInterval(() => {\n void refresh();\n }, AVAILABILITY_POLL_MS);\n }\n } else {\n stop();\n }\n }\n\n return { refresh, stop };\n}\n\nexport interface SegmentQueueOptions {\n transport: VoiceCaptureTransport;\n language: () => string;\n callbacks: VoiceCaptureCallbacks;\n setPending: (delta: number) => void;\n // Read-only epoch seam: the queue never mutates the generation, it only reads\n // the parent's current value to drop segments captured under an older session.\n getGeneration: () => number;\n}\n\nexport interface SegmentQueue {\n enqueue: (blob: Blob, gen: number) => void;\n}\n\n// Owns the serialized send chain. Each blob is transcribed in capture order; the\n// generation is checked at entry and again after transcription so a segment\n// belonging to a session the user already left is dropped silently.\nexport function createSegmentQueue(options: SegmentQueueOptions): SegmentQueue {\n const { transport, language, callbacks, setPending, getGeneration } = options;\n let queue: Promise<void> = Promise.resolve();\n\n async function sendSegment(blob: Blob, gen: number): Promise<void> {\n if (gen !== getGeneration()) return;\n try {\n const dataUrl = await blobToDataUrl(blob);\n const result = await transport.transcribe(dataUrl, language());\n if (gen !== getGeneration()) return;\n const text = result.text.trim();\n if (text.length === 0) callbacks.onEmpty?.();\n else callbacks.onTranscript(text);\n } catch (err) {\n // Generation-guard the failure path too: a send rejected after stop()/\n // session change belongs to a session the user already left.\n if (gen === getGeneration()) callbacks.onError?.(toMessage(err));\n }\n }\n\n // Serialize sends so transcripts append in capture order; `pending` keeps\n // `transcribing` true from enqueue until the send resolves.\n function enqueue(blob: Blob, gen: number): void {\n setPending(1);\n queue = queue\n .then(() => sendSegment(blob, gen))\n .catch(() => undefined)\n .finally(() => setPending(-1));\n }\n\n return { enqueue };\n}\n\nexport interface AudioGraph {\n /** True between `attach()` and the next `teardown()`. */\n isAttached: () => boolean;\n /** Read the current PCM window into an internal buffer and return it.\n * Callers must not mutate the returned array. */\n sample: () => Float32Array;\n /** Live mic stream — the outer needs it to hand to MediaRecorder. */\n getStream: () => MediaStream | null;\n /** Attach a fresh mic stream: create AudioContext + AnalyserNode + VAD buffer,\n * connect the source. Called only by `bootstrapCapture` after the caller has\n * passed the stale-generation / permission checks. */\n attach: (stream: MediaStream) => void;\n /** Close the AudioContext, stop the mic tracks, null everything. Safe to\n * call before `attach()` or twice in a row. */\n teardown: () => void;\n}\n\n// Owns the browser-side audio pipeline: mic stream + AudioContext + AnalyserNode\n// + the reusable Float32 buffer VAD reads samples into. Separated from\n// `createVoiceCapture` so its four browser-API fields don't inflate the parent\n// factory's line count and so the setup/teardown ordering is in one place.\nfunction createAudioGraph(): AudioGraph {\n let stream: MediaStream | null = null;\n let audioCtx: AudioContext | null = null;\n let analyser: AnalyserNode | null = null;\n let vadBuffer = new Float32Array(0);\n\n function attach(nextStream: MediaStream): void {\n stream = nextStream;\n audioCtx = new AudioContext();\n analyser = audioCtx.createAnalyser();\n analyser.fftSize = 2048;\n vadBuffer = new Float32Array(analyser.fftSize);\n audioCtx.createMediaStreamSource(nextStream).connect(analyser);\n }\n\n function sample(): Float32Array {\n analyser?.getFloatTimeDomainData(vadBuffer);\n return vadBuffer;\n }\n\n function teardown(): void {\n if (audioCtx) {\n audioCtx.close().catch(() => undefined);\n audioCtx = null;\n }\n analyser = null;\n stream?.getTracks().forEach((track) => track.stop());\n stream = null;\n }\n\n return { isAttached: () => analyser !== null, sample, getStream: () => stream, attach, teardown };\n}\n\ninterface BootstrappedCapture {\n audioGraph: AudioGraph;\n mimeType: string;\n}\n\n// Acquire the mic + probe MediaRecorder support + wire an AudioGraph, returning\n// null (with `callbacks.onError` fired) on any recoverable failure. Deliberately\n// does NOT touch `state` or start the recorder — the caller commits the session\n// only after this resolves successfully, so a stale `generation` detected mid-\n// flight can drop the tracks and bail without partially publishing state.\nasync function bootstrapCapture(callbacks: VoiceCaptureCallbacks, generationAtStart: number, generationNow: () => number): Promise<BootstrappedCapture | null> {\n const mimeType = pickRecorderMime() ?? \"\";\n if (!mimeType || !navigator.mediaDevices?.getUserMedia) {\n callbacks.onError?.(\"unsupported\");\n return null;\n }\n let acquired: MediaStream;\n try {\n acquired = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch {\n callbacks.onError?.(\"permission-denied\");\n return null;\n }\n if (generationAtStart !== generationNow()) {\n acquired.getTracks().forEach((track) => track.stop());\n return null;\n }\n const audioGraph = createAudioGraph();\n try {\n audioGraph.attach(acquired);\n } catch (err) {\n // teardown() is null-safe and closes any half-created AudioContext AND\n // stops the mic tracks — the pre-refactor code only stopped tracks and\n // leaked the context (codex/CodeRabbit findings on this PR).\n audioGraph.teardown();\n throw err;\n }\n return { audioGraph, mimeType };\n}\n\nexport interface RecorderSession {\n isRecording: () => boolean;\n hadSpeech: () => boolean;\n markSpeech: () => void;\n /** Start a new segment on `stream`, tagged with `gen`. Resets per-segment\n * state (chunks + hadSpeech) synchronously so a subsequent VAD tick sees\n * a fresh window. */\n startNext: (stream: MediaStream, mimeType: string, gen: number) => void;\n /** Force-close the current segment (silence exceeded or MAX_SEGMENT_MS). */\n cut: () => void;\n}\n\ninterface RecorderSessionDeps {\n /** Fires each time a segment finishes. The parent decides whether to\n * restart (via `session.startNext`) and whether to enqueue the blob. */\n onSegmentEnd: (blob: Blob, hadSpeech: boolean, gen: number) => void;\n}\n\n// Owns MediaRecorder + its per-segment scratchpad (chunks, hadSpeech, gen,\n// mimeType). The parent keeps VAD state and the global generation, and calls\n// `startNext` on both initial-start and post-onstop restart paths.\nfunction createRecorderSession(deps: RecorderSessionDeps): RecorderSession {\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let segmentHasSpeech = false;\n let sessionGen = 0;\n let sessionMimeType = \"\";\n\n function onStop(): void {\n // Snapshot BEFORE the parent's onSegmentEnd callback runs; `startNext`\n // (if the parent chooses to restart) will clear chunks synchronously.\n const hadSpeech = segmentHasSpeech;\n const gen = sessionGen;\n const blob = new Blob(chunks, { type: containerTypeFromMime(sessionMimeType) });\n deps.onSegmentEnd(blob, hadSpeech, gen);\n }\n\n function startNext(stream: MediaStream, mimeType: string, gen: number): void {\n chunks = [];\n segmentHasSpeech = false;\n sessionGen = gen;\n sessionMimeType = mimeType;\n recorder = new MediaRecorder(stream, { mimeType });\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) chunks.push(event.data);\n };\n recorder.onstop = onStop;\n recorder.start();\n }\n\n return {\n isRecording: () => recorder?.state === \"recording\",\n hadSpeech: () => segmentHasSpeech,\n markSpeech: () => {\n segmentHasSpeech = true;\n },\n startNext,\n cut: () => {\n if (recorder?.state === \"recording\") recorder.stop();\n },\n };\n}\n\n// Zero-values used to seed a fresh `CaptureRuntime` at the top of every\n// `createVoiceCapture` call. Kept module-scope so the seed doesn't inflate the\n// factory's line count.\nconst INITIAL_RUNTIME: Readonly<CaptureRuntime> = {\n audioGraph: null,\n monitorHandle: null,\n mimeType: \"\",\n silenceStart: null,\n segmentStart: 0,\n generation: 0,\n startInFlight: false,\n};\n\n// Mutable capture-time state, kept as one object so module-scope helpers\n// (`stopCapture`, `monitorTick`) can be typed against one shape rather than\n// threading each field through their signatures.\ninterface CaptureRuntime {\n audioGraph: AudioGraph | null;\n monitorHandle: number | null;\n mimeType: string;\n silenceStart: number | null;\n segmentStart: number;\n /** Bumped on stop(); segments captured under an older value are dropped so a\n * late transcript never leaks across sessions. */\n generation: number;\n /** Single-flight guard on start() — true between entry and completion so a\n * second start can't race the first before `listening` flips. */\n startInFlight: boolean;\n}\n\n// Tear down the browser-side resources. `state.setListening(false)` MUST happen\n// BEFORE `session.cut()` so the parent's onSegmentEnd callback sees\n// isListening()===false and does NOT restart. The monitor interval MUST clear\n// BEFORE `audioGraph.teardown()` so a scheduled tick can't run against a\n// half-closed AudioContext.\nfunction stopCapture(runtime: CaptureRuntime, state: CaptureStateController, session: RecorderSession): void {\n runtime.generation += 1;\n state.setListening(false);\n if (runtime.monitorHandle !== null) {\n window.clearInterval(runtime.monitorHandle);\n runtime.monitorHandle = null;\n }\n session.cut();\n runtime.audioGraph?.teardown();\n runtime.audioGraph = null;\n}\n\n// One VAD tick against the audio graph's current window. No-op when the graph\n// is not attached (defensive: `stopCapture` clears `monitorHandle` before\n// `audioGraph.teardown()`, so this is the belt-and-braces for any late fire).\nfunction monitorTick(runtime: CaptureRuntime, session: RecorderSession): void {\n if (!runtime.audioGraph?.isAttached()) return;\n const rms = computeRms(runtime.audioGraph.sample());\n const {\n hasSpeech,\n silenceStart: nextSilence,\n cut,\n } = evaluateVad({ hasSpeech: session.hadSpeech(), silenceStart: runtime.silenceStart }, runtime.segmentStart, rms, Date.now(), VAD_CONFIG);\n if (hasSpeech) session.markSpeech();\n runtime.silenceStart = nextSilence;\n if (cut) session.cut();\n}\n\nexport function createVoiceCapture(transport: VoiceCaptureTransport, language: () => string, callbacks: VoiceCaptureCallbacks): VoiceCapture {\n const state = createCaptureState(callbacks.onState);\n const poller = createAvailabilityPoller(transport, state.setAvailable);\n const runtime: CaptureRuntime = { ...INITIAL_RUNTIME };\n const segments = createSegmentQueue({ transport, language, callbacks, setPending: state.setPending, getGeneration: () => runtime.generation });\n\n const session = createRecorderSession({ onSegmentEnd: handleSegmentEnd });\n\n function handleSegmentEnd(blob: Blob, hadSpeech: boolean, gen: number): void {\n // Restart FIRST so audio-loss between segments is minimal; the snapshot\n // in blob/hadSpeech/gen is already independent of session state.\n if (state.isListening()) startRecorder();\n if (hadSpeech && blob.size > 0 && gen === runtime.generation) segments.enqueue(blob, gen);\n }\n\n function startRecorder(): void {\n const stream = runtime.audioGraph?.getStream();\n if (!stream) return;\n runtime.silenceStart = null;\n runtime.segmentStart = Date.now();\n session.startNext(stream, runtime.mimeType, runtime.generation);\n }\n\n async function start(): Promise<boolean> {\n if (runtime.startInFlight || state.isListening()) return true;\n runtime.startInFlight = true;\n const startGen = runtime.generation;\n try {\n const capture = await bootstrapCapture(callbacks, startGen, () => runtime.generation);\n if (!capture) return false;\n runtime.audioGraph = capture.audioGraph;\n runtime.mimeType = capture.mimeType;\n state.setListening(true);\n startRecorder();\n runtime.monitorHandle = window.setInterval(() => monitorTick(runtime, session), MONITOR_INTERVAL_MS);\n return true;\n } finally {\n runtime.startInFlight = false;\n }\n }\n\n function stop(): void {\n stopCapture(runtime, state, session);\n }\n\n function dispose(): void {\n poller.stop();\n stop();\n }\n\n return { refreshAvailability: poller.refresh, start, stop, dispose };\n}\n"],"mappings":";;AAIA,SAAgB,WAAW,QAA8B;CACvD,IAAI,MAAM;CACV,KAAK,MAAM,UAAU,QAAQ,OAAO,SAAS;CAC7C,OAAO,KAAK,KAAK,MAAM,OAAO,MAAM;AACtC;;;AAIA,SAAgB,sBAAsB,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AAmB;EAAE;EAAW;EAAU;EAAW,YAAY,MAAM;EAAY,qBAAqB,QAAQ;CAAW,CAAC;CAE7I,MAAM,UAAU,sBAAsB,EAAE,cAAc,iBAAiB,CAAC;CAExE,SAAS,iBAAiB,MAAY,WAAoB,KAAmB;EAG3E,IAAI,MAAM,YAAY,GAAG,cAAc;EACvC,IAAI,aAAa,KAAK,OAAO,KAAK,QAAQ,QAAQ,YAAY,SAAS,QAAQ,MAAM,GAAG;CAC1F;CAEA,SAAS,gBAAsB;EAC7B,MAAM,SAAS,QAAQ,YAAY,UAAU;EAC7C,IAAI,CAAC,QAAQ;EACb,QAAQ,eAAe;EACvB,QAAQ,eAAe,KAAK,IAAI;EAChC,QAAQ,UAAU,QAAQ,QAAQ,UAAU,QAAQ,UAAU;CAChE;CAEA,eAAe,QAA0B;EACvC,IAAI,QAAQ,iBAAiB,MAAM,YAAY,GAAG,OAAO;EACzD,QAAQ,gBAAgB;EACxB,MAAM,WAAW,QAAQ;EACzB,IAAI;GACF,MAAM,UAAU,MAAM,iBAAiB,WAAW,gBAAgB,QAAQ,UAAU;GACpF,IAAI,CAAC,SAAS,OAAO;GACrB,QAAQ,aAAa,QAAQ;GAC7B,QAAQ,WAAW,QAAQ;GAC3B,MAAM,aAAa,IAAI;GACvB,cAAc;GACd,QAAQ,gBAAgB,OAAO,kBAAkB,YAAY,SAAS,OAAO,GAAG,mBAAmB;GACnG,OAAO;EACT,UAAU;GACR,QAAQ,gBAAgB;EAC1B;CACF;CAEA,SAAS,OAAa;EACpB,YAAY,SAAS,OAAO,OAAO;CACrC;CAEA,SAAS,UAAgB;EACvB,OAAO,KAAK;EACZ,KAAK;CACP;CAEA,OAAO;EAAE,qBAAqB,OAAO;EAAS;EAAO;EAAM;CAAQ;AACrE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/whisper/client-helpers.ts","../../src/whisper/client.ts"],"sourcesContent":["// Pure, framework-neutral helpers for the browser voice-capture controller.\n// Kept separate from `client.ts` so the audio math and VAD state machine can be\n// unit-tested without a DOM / MediaRecorder / Web Audio environment.\n\nexport function computeRms(buffer: Float32Array): number {\n let sum = 0;\n for (const sample of buffer) sum += sample * sample;\n return Math.sqrt(sum / buffer.length);\n}\n\n/** The recorder mime can carry a codec suffix (`audio/webm;codecs=opus`); the\n * Blob container type is just the part before the `;`. */\nexport function containerTypeFromMime(mimeType: string): string {\n return mimeType.split(\";\")[0] || \"audio/webm\";\n}\n\nexport interface VadState {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n}\n\nexport interface VadConfig {\n readonly speechRms: number;\n readonly silenceMs: number;\n readonly maxSegmentMs: number;\n}\n\nexport interface VadDecision {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n readonly cut: boolean;\n}\n\nfunction isSpeech(rms: number, config: VadConfig): boolean {\n return rms > config.speechRms;\n}\n\nfunction nextSilenceStart(state: VadState, rms: number, nowMs: number, config: VadConfig): number | null {\n if (isSpeech(rms, config)) return null;\n if (state.hasSpeech && state.silenceStart === null) return nowMs;\n return state.silenceStart;\n}\n\nfunction silenceExceeded(state: VadState, rms: number, nowMs: number, config: VadConfig): boolean {\n if (isSpeech(rms, config) || !state.hasSpeech || state.silenceStart === null) return false;\n return nowMs - state.silenceStart > config.silenceMs;\n}\n\n/** Advance the pause-detector one tick: fold the current RMS/time into the\n * segment state and decide whether the segment should be force-cut (either a\n * long-enough silence after speech, or the max-segment length reached). */\nexport function evaluateVad(state: VadState, segmentStartMs: number, rms: number, nowMs: number, config: VadConfig): VadDecision {\n const hasSpeech = isSpeech(rms, config) || state.hasSpeech;\n const silenceStart = nextSilenceStart(state, rms, nowMs, config);\n const maxCut = hasSpeech && nowMs - segmentStartMs > config.maxSegmentMs;\n return { hasSpeech, silenceStart, cut: silenceExceeded(state, rms, nowMs, config) || maxCut };\n}\n","// @mulmoclaude/core/whisper/client — framework-neutral browser capture controller.\n// Records one utterance at a time with MediaRecorder, segments on pauses via a\n// Web Audio VAD, and sends each segment through an injected transport. State is\n// pushed via `onState`; the host wraps this into its own reactivity (Vue refs,\n// React state, …). No framework dependency. See plans/done/feat-extract-whisper-package.md.\n\nimport { computeRms, containerTypeFromMime, evaluateVad, type VadConfig } from \"./client-helpers.ts\";\n\n// Map a UI locale to a Whisper language code. UI language is a strong prior for\n// the spoken language; \"auto\" lets Whisper detect it from the audio.\nconst LOCALE_TO_WHISPER: Record<string, string> = {\n en: \"en\",\n ja: \"ja\",\n zh: \"zh\",\n ko: \"ko\",\n es: \"es\",\n \"pt-BR\": \"pt\",\n fr: \"fr\",\n de: \"de\",\n};\n\nexport function localeToWhisperLanguage(locale: string): string {\n return LOCALE_TO_WHISPER[locale] ?? \"auto\";\n}\n\n// VAD tuning. RMS over [-1,1] float samples; a pause is SILENCE_MS of\n// sub-threshold level after speech. MAX_SEGMENT_MS force-cuts a long unbroken\n// utterance so no clip exceeds Whisper's 30s window or the server's size cap.\nconst SPEECH_RMS = 0.015;\nconst SILENCE_MS = 800;\nconst MAX_SEGMENT_MS = 20_000;\nconst MONITOR_INTERVAL_MS = 100;\nconst AVAILABILITY_POLL_MS = 2_000;\nconst VAD_CONFIG: VadConfig = { speechRms: SPEECH_RMS, silenceMs: SILENCE_MS, maxSegmentMs: MAX_SEGMENT_MS };\n\nfunction pickRecorderMime(): string | undefined {\n const candidates = [\"audio/webm;codecs=opus\", \"audio/webm\", \"audio/mp4\"];\n if (typeof MediaRecorder === \"undefined\") return undefined;\n return candidates.find((type) => MediaRecorder.isTypeSupported(type));\n}\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n // eslint-disable-next-line @typescript-eslint/no-base-to-string -- FileReader.result is `string | ArrayBuffer | null`; readAsDataURL always yields the string branch, and the rule cannot narrow it.\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(reader.error ?? new Error(\"FileReader failed\"));\n reader.readAsDataURL(blob);\n });\n}\n\nfunction toMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nexport interface VoiceCaptureTransport {\n /** Transcribe one segment. Throws on failure. */\n transcribe: (dataUrl: string, language: string) => Promise<{ text: string }>;\n /** Current readiness. `downloading` true keeps the controller polling so it\n * flips to ready as soon as a model download finishes. */\n getStatus: () => Promise<{ ready: boolean; downloading: boolean }>;\n}\n\nexport interface VoiceCaptureState {\n available: boolean;\n listening: boolean;\n transcribing: boolean;\n}\n\nexport interface VoiceCaptureCallbacks {\n /** A recognized (non-empty) segment transcript. */\n onTranscript: (text: string) => void;\n /** A segment produced no speech. */\n onEmpty?: (() => void) | undefined;\n /** A recoverable error message (transport failure, permission denied, etc.). */\n onError?: ((message: string) => void) | undefined;\n /** Pushed whenever available/listening/transcribing changes. */\n onState?: ((state: VoiceCaptureState) => void) | undefined;\n}\n\nexport interface VoiceCapture {\n refreshAvailability: () => Promise<void>;\n start: () => Promise<boolean>;\n stop: () => void;\n dispose: () => void;\n}\n\nexport interface CaptureStateController {\n setAvailable: (value: boolean) => void;\n setListening: (value: boolean) => void;\n setPending: (delta: number) => void;\n isListening: () => boolean;\n}\n\n// Owns the three observable flags. Each setter emits only on an actual change so\n// the host's reactivity never churns on a no-op write. `pending` is a private\n// counter; `transcribing` is true exactly while at least one send is in flight.\nexport function createCaptureState(onState?: (state: VoiceCaptureState) => void): CaptureStateController {\n let available = false;\n let listening = false;\n let transcribing = false;\n let pending = 0;\n\n function emit(): void {\n onState?.({ available, listening, transcribing });\n }\n function setAvailable(value: boolean): void {\n if (available !== value) {\n available = value;\n emit();\n }\n }\n function setListening(value: boolean): void {\n if (listening !== value) {\n listening = value;\n emit();\n }\n }\n function setPending(delta: number): void {\n pending += delta;\n const next = pending > 0;\n if (transcribing !== next) {\n transcribing = next;\n emit();\n }\n }\n\n return { setAvailable, setListening, setPending, isListening: () => listening };\n}\n\nexport interface AvailabilityPoller {\n refresh: () => Promise<void>;\n stop: () => void;\n}\n\n// Owns the polling timer. `refresh` mirrors transport readiness into\n// `setAvailable`; while a model is downloading it self-schedules so `available`\n// flips as soon as the download finishes. A `getStatus` throw fails closed\n// (unavailable) and tears the timer down.\nexport function createAvailabilityPoller(transport: VoiceCaptureTransport, setAvailable: (value: boolean) => void): AvailabilityPoller {\n let availabilityPollHandle: number | null = null;\n\n function stop(): void {\n if (availabilityPollHandle !== null) {\n window.clearInterval(availabilityPollHandle);\n availabilityPollHandle = null;\n }\n }\n\n async function refresh(): Promise<void> {\n let status: { ready: boolean; downloading: boolean };\n try {\n status = await transport.getStatus();\n } catch {\n setAvailable(false);\n stop();\n return;\n }\n setAvailable(status.ready);\n if (status.downloading) {\n if (availabilityPollHandle === null) {\n availabilityPollHandle = window.setInterval(() => {\n void refresh();\n }, AVAILABILITY_POLL_MS);\n }\n } else {\n stop();\n }\n }\n\n return { refresh, stop };\n}\n\nexport interface SegmentQueueOptions {\n transport: VoiceCaptureTransport;\n language: () => string;\n callbacks: VoiceCaptureCallbacks;\n setPending: (delta: number) => void;\n // Read-only epoch seam: the queue never mutates the generation, it only reads\n // the parent's current value to drop segments captured under an older session.\n getGeneration: () => number;\n}\n\nexport interface SegmentQueue {\n enqueue: (blob: Blob, gen: number) => void;\n}\n\n// Owns the serialized send chain. Each blob is transcribed in capture order; the\n// generation is checked at entry and again after transcription so a segment\n// belonging to a session the user already left is dropped silently.\nexport function createSegmentQueue(options: SegmentQueueOptions): SegmentQueue {\n const { transport, language, callbacks, setPending, getGeneration } = options;\n let queue: Promise<void> = Promise.resolve();\n\n async function sendSegment(blob: Blob, gen: number): Promise<void> {\n if (gen !== getGeneration()) return;\n try {\n const dataUrl = await blobToDataUrl(blob);\n const result = await transport.transcribe(dataUrl, language());\n if (gen !== getGeneration()) return;\n const text = result.text.trim();\n if (text.length === 0) callbacks.onEmpty?.();\n else callbacks.onTranscript(text);\n } catch (err) {\n // Generation-guard the failure path too: a send rejected after stop()/\n // session change belongs to a session the user already left.\n if (gen === getGeneration()) callbacks.onError?.(toMessage(err));\n }\n }\n\n // Serialize sends so transcripts append in capture order; `pending` keeps\n // `transcribing` true from enqueue until the send resolves.\n function enqueue(blob: Blob, gen: number): void {\n setPending(1);\n queue = queue\n .then(() => sendSegment(blob, gen))\n .catch(() => undefined)\n .finally(() => setPending(-1));\n }\n\n return { enqueue };\n}\n\nexport interface AudioGraph {\n /** True between `attach()` and the next `teardown()`. */\n isAttached: () => boolean;\n /** Read the current PCM window into an internal buffer and return it.\n * Callers must not mutate the returned array. */\n sample: () => Float32Array;\n /** Live mic stream — the outer needs it to hand to MediaRecorder. */\n getStream: () => MediaStream | null;\n /** Attach a fresh mic stream: create AudioContext + AnalyserNode + VAD buffer,\n * connect the source. Called only by `bootstrapCapture` after the caller has\n * passed the stale-generation / permission checks. */\n attach: (stream: MediaStream) => void;\n /** Close the AudioContext, stop the mic tracks, null everything. Safe to\n * call before `attach()` or twice in a row. */\n teardown: () => void;\n}\n\n// Owns the browser-side audio pipeline: mic stream + AudioContext + AnalyserNode\n// + the reusable Float32 buffer VAD reads samples into. Separated from\n// `createVoiceCapture` so its four browser-API fields don't inflate the parent\n// factory's line count and so the setup/teardown ordering is in one place.\nfunction createAudioGraph(): AudioGraph {\n let stream: MediaStream | null = null;\n let audioCtx: AudioContext | null = null;\n let analyser: AnalyserNode | null = null;\n let vadBuffer = new Float32Array(0);\n\n function attach(nextStream: MediaStream): void {\n stream = nextStream;\n audioCtx = new AudioContext();\n analyser = audioCtx.createAnalyser();\n analyser.fftSize = 2048;\n vadBuffer = new Float32Array(analyser.fftSize);\n audioCtx.createMediaStreamSource(nextStream).connect(analyser);\n }\n\n function sample(): Float32Array {\n analyser?.getFloatTimeDomainData(vadBuffer);\n return vadBuffer;\n }\n\n function teardown(): void {\n if (audioCtx) {\n audioCtx.close().catch(() => undefined);\n audioCtx = null;\n }\n analyser = null;\n stream?.getTracks().forEach((track) => track.stop());\n stream = null;\n }\n\n return { isAttached: () => analyser !== null, sample, getStream: () => stream, attach, teardown };\n}\n\ninterface BootstrappedCapture {\n audioGraph: AudioGraph;\n mimeType: string;\n}\n\n// Acquire the mic + probe MediaRecorder support + wire an AudioGraph, returning\n// null (with `callbacks.onError` fired) on any recoverable failure. Deliberately\n// does NOT touch `state` or start the recorder — the caller commits the session\n// only after this resolves successfully, so a stale `generation` detected mid-\n// flight can drop the tracks and bail without partially publishing state.\nasync function bootstrapCapture(callbacks: VoiceCaptureCallbacks, generationAtStart: number, generationNow: () => number): Promise<BootstrappedCapture | null> {\n const mimeType = pickRecorderMime() ?? \"\";\n if (!mimeType || !navigator.mediaDevices?.getUserMedia) {\n callbacks.onError?.(\"unsupported\");\n return null;\n }\n let acquired: MediaStream;\n try {\n acquired = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch {\n callbacks.onError?.(\"permission-denied\");\n return null;\n }\n if (generationAtStart !== generationNow()) {\n acquired.getTracks().forEach((track) => track.stop());\n return null;\n }\n const audioGraph = createAudioGraph();\n try {\n audioGraph.attach(acquired);\n } catch (err) {\n // teardown() is null-safe and closes any half-created AudioContext AND\n // stops the mic tracks — the pre-refactor code only stopped tracks and\n // leaked the context (codex/CodeRabbit findings on this PR).\n audioGraph.teardown();\n throw err;\n }\n return { audioGraph, mimeType };\n}\n\nexport interface RecorderSession {\n isRecording: () => boolean;\n hadSpeech: () => boolean;\n markSpeech: () => void;\n /** Start a new segment on `stream`, tagged with `gen`. Resets per-segment\n * state (chunks + hadSpeech) synchronously so a subsequent VAD tick sees\n * a fresh window. */\n startNext: (stream: MediaStream, mimeType: string, gen: number) => void;\n /** Force-close the current segment (silence exceeded or MAX_SEGMENT_MS). */\n cut: () => void;\n}\n\ninterface RecorderSessionDeps {\n /** Fires each time a segment finishes. The parent decides whether to\n * restart (via `session.startNext`) and whether to enqueue the blob. */\n onSegmentEnd: (blob: Blob, hadSpeech: boolean, gen: number) => void;\n}\n\n// Owns MediaRecorder + its per-segment scratchpad (chunks, hadSpeech, gen,\n// mimeType). The parent keeps VAD state and the global generation, and calls\n// `startNext` on both initial-start and post-onstop restart paths.\nfunction createRecorderSession(deps: RecorderSessionDeps): RecorderSession {\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let segmentHasSpeech = false;\n let sessionGen = 0;\n let sessionMimeType = \"\";\n\n function onStop(): void {\n // Snapshot BEFORE the parent's onSegmentEnd callback runs; `startNext`\n // (if the parent chooses to restart) will clear chunks synchronously.\n const hadSpeech = segmentHasSpeech;\n const gen = sessionGen;\n const blob = new Blob(chunks, { type: containerTypeFromMime(sessionMimeType) });\n deps.onSegmentEnd(blob, hadSpeech, gen);\n }\n\n function startNext(stream: MediaStream, mimeType: string, gen: number): void {\n chunks = [];\n segmentHasSpeech = false;\n sessionGen = gen;\n sessionMimeType = mimeType;\n recorder = new MediaRecorder(stream, { mimeType });\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) chunks.push(event.data);\n };\n recorder.onstop = onStop;\n recorder.start();\n }\n\n return {\n isRecording: () => recorder?.state === \"recording\",\n hadSpeech: () => segmentHasSpeech,\n markSpeech: () => {\n segmentHasSpeech = true;\n },\n startNext,\n cut: () => {\n if (recorder?.state === \"recording\") recorder.stop();\n },\n };\n}\n\n// Zero-values used to seed a fresh `CaptureRuntime` at the top of every\n// `createVoiceCapture` call. Kept module-scope so the seed doesn't inflate the\n// factory's line count.\nconst INITIAL_RUNTIME: Readonly<CaptureRuntime> = {\n audioGraph: null,\n monitorHandle: null,\n mimeType: \"\",\n silenceStart: null,\n segmentStart: 0,\n generation: 0,\n startInFlight: false,\n};\n\n// Mutable capture-time state, kept as one object so module-scope helpers\n// (`stopCapture`, `monitorTick`) can be typed against one shape rather than\n// threading each field through their signatures.\ninterface CaptureRuntime {\n audioGraph: AudioGraph | null;\n monitorHandle: number | null;\n mimeType: string;\n silenceStart: number | null;\n segmentStart: number;\n /** Bumped on stop(); segments captured under an older value are dropped so a\n * late transcript never leaks across sessions. */\n generation: number;\n /** Single-flight guard on start() — true between entry and completion so a\n * second start can't race the first before `listening` flips. */\n startInFlight: boolean;\n}\n\n// Tear down the browser-side resources. `state.setListening(false)` MUST happen\n// BEFORE `session.cut()` so the parent's onSegmentEnd callback sees\n// isListening()===false and does NOT restart. The monitor interval MUST clear\n// BEFORE `audioGraph.teardown()` so a scheduled tick can't run against a\n// half-closed AudioContext.\nfunction stopCapture(runtime: CaptureRuntime, state: CaptureStateController, session: RecorderSession): void {\n runtime.generation += 1;\n state.setListening(false);\n if (runtime.monitorHandle !== null) {\n window.clearInterval(runtime.monitorHandle);\n runtime.monitorHandle = null;\n }\n session.cut();\n runtime.audioGraph?.teardown();\n runtime.audioGraph = null;\n}\n\n// One VAD tick against the audio graph's current window. No-op when the graph\n// is not attached (defensive: `stopCapture` clears `monitorHandle` before\n// `audioGraph.teardown()`, so this is the belt-and-braces for any late fire).\nfunction monitorTick(runtime: CaptureRuntime, session: RecorderSession): void {\n if (!runtime.audioGraph?.isAttached()) return;\n const rms = computeRms(runtime.audioGraph.sample());\n const {\n hasSpeech,\n silenceStart: nextSilence,\n cut,\n } = evaluateVad({ hasSpeech: session.hadSpeech(), silenceStart: runtime.silenceStart }, runtime.segmentStart, rms, Date.now(), VAD_CONFIG);\n if (hasSpeech) session.markSpeech();\n runtime.silenceStart = nextSilence;\n if (cut) session.cut();\n}\n\nexport function createVoiceCapture(transport: VoiceCaptureTransport, language: () => string, callbacks: VoiceCaptureCallbacks): VoiceCapture {\n const state = createCaptureState(callbacks.onState);\n const poller = createAvailabilityPoller(transport, state.setAvailable);\n const runtime: CaptureRuntime = { ...INITIAL_RUNTIME };\n const segments = createSegmentQueue({ transport, language, callbacks, setPending: state.setPending, getGeneration: () => runtime.generation });\n\n const session = createRecorderSession({ onSegmentEnd: handleSegmentEnd });\n\n function handleSegmentEnd(blob: Blob, hadSpeech: boolean, gen: number): void {\n // Restart FIRST so audio-loss between segments is minimal; the snapshot\n // in blob/hadSpeech/gen is already independent of session state.\n if (state.isListening()) startRecorder();\n if (hadSpeech && blob.size > 0 && gen === runtime.generation) segments.enqueue(blob, gen);\n }\n\n function startRecorder(): void {\n const stream = runtime.audioGraph?.getStream();\n if (!stream) return;\n runtime.silenceStart = null;\n runtime.segmentStart = Date.now();\n session.startNext(stream, runtime.mimeType, runtime.generation);\n }\n\n async function start(): Promise<boolean> {\n if (runtime.startInFlight || state.isListening()) return true;\n runtime.startInFlight = true;\n const startGen = runtime.generation;\n try {\n const capture = await bootstrapCapture(callbacks, startGen, () => runtime.generation);\n if (!capture) return false;\n runtime.audioGraph = capture.audioGraph;\n runtime.mimeType = capture.mimeType;\n state.setListening(true);\n startRecorder();\n runtime.monitorHandle = window.setInterval(() => monitorTick(runtime, session), MONITOR_INTERVAL_MS);\n return true;\n } finally {\n runtime.startInFlight = false;\n }\n }\n\n function stop(): void {\n stopCapture(runtime, state, session);\n }\n\n function dispose(): void {\n poller.stop();\n stop();\n }\n\n return { refreshAvailability: poller.refresh, start, stop, dispose };\n}\n"],"mappings":";AAIA,SAAgB,WAAW,QAA8B;CACvD,IAAI,MAAM;CACV,KAAK,MAAM,UAAU,QAAQ,OAAO,SAAS;CAC7C,OAAO,KAAK,KAAK,MAAM,OAAO,MAAM;AACtC;;;AAIA,SAAgB,sBAAsB,UAA0B;CAC9D,OAAO,SAAS,MAAM,GAAG,CAAC,CAAC,MAAM;AACnC;AAmBA,SAAS,SAAS,KAAa,QAA4B;CACzD,OAAO,MAAM,OAAO;AACtB;AAEA,SAAS,iBAAiB,OAAiB,KAAa,OAAe,QAAkC;CACvG,IAAI,SAAS,KAAK,MAAM,GAAG,OAAO;CAClC,IAAI,MAAM,aAAa,MAAM,iBAAiB,MAAM,OAAO;CAC3D,OAAO,MAAM;AACf;AAEA,SAAS,gBAAgB,OAAiB,KAAa,OAAe,QAA4B;CAChG,IAAI,SAAS,KAAK,MAAM,KAAK,CAAC,MAAM,aAAa,MAAM,iBAAiB,MAAM,OAAO;CACrF,OAAO,QAAQ,MAAM,eAAe,OAAO;AAC7C;;;;AAKA,SAAgB,YAAY,OAAiB,gBAAwB,KAAa,O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vC,IAAI,QAAQ,iBAAiB,MAAM,YAAY,GAAG,OAAO;EACzD,QAAQ,gBAAgB;EACxB,MAAM,WAAW,QAAQ;EACzB,IAAI;GACF,MAAM,UAAU,MAAM,iBAAiB,WAAW,gBAAgB,QAAQ,UAAU;GACpF,IAAI,CAAC,SAAS,OAAO;GACrB,QAAQ,aAAa,QAAQ;GAC7B,QAAQ,WAAW,QAAQ;GAC3B,MAAM,aAAa,IAAI;GACvB,cAAc;GACd,QAAQ,gBAAgB,OAAO,kBAAkB,YAAY,SAAS,OAAO,GAAG,mBAAmB;GACnG,OAAO;EACT,UAAU;GACR,QAAQ,gBAAgB;EAC1B;CACF;CAEA,SAAS,OAAa;EACpB,YAAY,SAAS,OAAO,OAAO;CACrC;CAEA,SAAS,UAAgB;EACvB,OAAO,KAAK;EACZ,KAAK;CACP;CAEA,OAAO;EAAE,qBAAqB,OAAO;EAAS;EAAO;EAAM;CAAQ;AACrE"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/whisper/client-helpers.ts","../../src/whisper/client.ts"],"sourcesContent":["// Pure, framework-neutral helpers for the browser voice-capture controller.\n// Kept separate from `client.ts` so the audio math and VAD state machine can be\n// unit-tested without a DOM / MediaRecorder / Web Audio environment.\n\nexport function computeRms(buffer: Float32Array): number {\n let sum = 0;\n for (const sample of buffer) sum += sample * sample;\n return Math.sqrt(sum / buffer.length);\n}\n\n/** The recorder mime can carry a codec suffix (`audio/webm;codecs=opus`); the\n * Blob container type is just the part before the `;`. */\nexport function containerTypeFromMime(mimeType: string): string {\n return mimeType.split(\";\")[0] || \"audio/webm\";\n}\n\nexport interface VadState {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n}\n\nexport interface VadConfig {\n readonly speechRms: number;\n readonly silenceMs: number;\n readonly maxSegmentMs: number;\n}\n\nexport interface VadDecision {\n readonly hasSpeech: boolean;\n readonly silenceStart: number | null;\n readonly cut: boolean;\n}\n\nfunction isSpeech(rms: number, config: VadConfig): boolean {\n return rms > config.speechRms;\n}\n\nfunction nextSilenceStart(state: VadState, rms: number, nowMs: number, config: VadConfig): number | null {\n if (isSpeech(rms, config)) return null;\n if (state.hasSpeech && state.silenceStart === null) return nowMs;\n return state.silenceStart;\n}\n\nfunction silenceExceeded(state: VadState, rms: number, nowMs: number, config: VadConfig): boolean {\n if (isSpeech(rms, config) || !state.hasSpeech || state.silenceStart === null) return false;\n return nowMs - state.silenceStart > config.silenceMs;\n}\n\n/** Advance the pause-detector one tick: fold the current RMS/time into the\n * segment state and decide whether the segment should be force-cut (either a\n * long-enough silence after speech, or the max-segment length reached). */\nexport function evaluateVad(state: VadState, segmentStartMs: number, rms: number, nowMs: number, config: VadConfig): VadDecision {\n const hasSpeech = isSpeech(rms, config) || state.hasSpeech;\n const silenceStart = nextSilenceStart(state, rms, nowMs, config);\n const maxCut = hasSpeech && nowMs - segmentStartMs > config.maxSegmentMs;\n return { hasSpeech, silenceStart, cut: silenceExceeded(state, rms, nowMs, config) || maxCut };\n}\n","// @mulmoclaude/core/whisper/client — framework-neutral browser capture controller.\n// Records one utterance at a time with MediaRecorder, segments on pauses via a\n// Web Audio VAD, and sends each segment through an injected transport. State is\n// pushed via `onState`; the host wraps this into its own reactivity (Vue refs,\n// React state, …). No framework dependency. See plans/done/feat-extract-whisper-package.md.\n\nimport { computeRms, containerTypeFromMime, evaluateVad, type VadConfig } from \"./client-helpers.ts\";\n\n// Map a UI locale to a Whisper language code. UI language is a strong prior for\n// the spoken language; \"auto\" lets Whisper detect it from the audio.\nconst LOCALE_TO_WHISPER: Record<string, string> = {\n en: \"en\",\n ja: \"ja\",\n zh: \"zh\",\n ko: \"ko\",\n es: \"es\",\n \"pt-BR\": \"pt\",\n fr: \"fr\",\n de: \"de\",\n};\n\nexport function localeToWhisperLanguage(locale: string): string {\n return LOCALE_TO_WHISPER[locale] ?? \"auto\";\n}\n\n// VAD tuning. RMS over [-1,1] float samples; a pause is SILENCE_MS of\n// sub-threshold level after speech. MAX_SEGMENT_MS force-cuts a long unbroken\n// utterance so no clip exceeds Whisper's 30s window or the server's size cap.\nconst SPEECH_RMS = 0.015;\nconst SILENCE_MS = 800;\nconst MAX_SEGMENT_MS = 20_000;\nconst MONITOR_INTERVAL_MS = 100;\nconst AVAILABILITY_POLL_MS = 2_000;\nconst VAD_CONFIG: VadConfig = { speechRms: SPEECH_RMS, silenceMs: SILENCE_MS, maxSegmentMs: MAX_SEGMENT_MS };\n\nfunction pickRecorderMime(): string | undefined {\n const candidates = [\"audio/webm;codecs=opus\", \"audio/webm\", \"audio/mp4\"];\n if (typeof MediaRecorder === \"undefined\") return undefined;\n return candidates.find((type) => MediaRecorder.isTypeSupported(type));\n}\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n // eslint-disable-next-line @typescript-eslint/no-base-to-string -- FileReader.result is `string | ArrayBuffer | null`; readAsDataURL always yields the string branch, and the rule cannot narrow it.\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(reader.error ?? new Error(\"FileReader failed\"));\n reader.readAsDataURL(blob);\n });\n}\n\nfunction toMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nexport interface VoiceCaptureTransport {\n /** Transcribe one segment. Throws on failure. */\n transcribe: (dataUrl: string, language: string) => Promise<{ text: string }>;\n /** Current readiness. `downloading` true keeps the controller polling so it\n * flips to ready as soon as a model download finishes. */\n getStatus: () => Promise<{ ready: boolean; downloading: boolean }>;\n}\n\nexport interface VoiceCaptureState {\n available: boolean;\n listening: boolean;\n transcribing: boolean;\n}\n\nexport interface VoiceCaptureCallbacks {\n /** A recognized (non-empty) segment transcript. */\n onTranscript: (text: string) => void;\n /** A segment produced no speech. */\n onEmpty?: (() => void) | undefined;\n /** A recoverable error message (transport failure, permission denied, etc.). */\n onError?: ((message: string) => void) | undefined;\n /** Pushed whenever available/listening/transcribing changes. */\n onState?: ((state: VoiceCaptureState) => void) | undefined;\n}\n\nexport interface VoiceCapture {\n refreshAvailability: () => Promise<void>;\n start: () => Promise<boolean>;\n stop: () => void;\n dispose: () => void;\n}\n\nexport interface CaptureStateController {\n setAvailable: (value: boolean) => void;\n setListening: (value: boolean) => void;\n setPending: (delta: number) => void;\n isListening: () => boolean;\n}\n\n// Owns the three observable flags. Each setter emits only on an actual change so\n// the host's reactivity never churns on a no-op write. `pending` is a private\n// counter; `transcribing` is true exactly while at least one send is in flight.\nexport function createCaptureState(onState?: (state: VoiceCaptureState) => void): CaptureStateController {\n let available = false;\n let listening = false;\n let transcribing = false;\n let pending = 0;\n\n function emit(): void {\n onState?.({ available, listening, transcribing });\n }\n function setAvailable(value: boolean): void {\n if (available !== value) {\n available = value;\n emit();\n }\n }\n function setListening(value: boolean): void {\n if (listening !== value) {\n listening = value;\n emit();\n }\n }\n function setPending(delta: number): void {\n pending += delta;\n const next = pending > 0;\n if (transcribing !== next) {\n transcribing = next;\n emit();\n }\n }\n\n return { setAvailable, setListening, setPending, isListening: () => listening };\n}\n\nexport interface AvailabilityPoller {\n refresh: () => Promise<void>;\n stop: () => void;\n}\n\n// Owns the polling timer. `refresh` mirrors transport readiness into\n// `setAvailable`; while a model is downloading it self-schedules so `available`\n// flips as soon as the download finishes. A `getStatus` throw fails closed\n// (unavailable) and tears the timer down.\nexport function createAvailabilityPoller(transport: VoiceCaptureTransport, setAvailable: (value: boolean) => void): AvailabilityPoller {\n let availabilityPollHandle: number | null = null;\n\n function stop(): void {\n if (availabilityPollHandle !== null) {\n window.clearInterval(availabilityPollHandle);\n availabilityPollHandle = null;\n }\n }\n\n async function refresh(): Promise<void> {\n let status: { ready: boolean; downloading: boolean };\n try {\n status = await transport.getStatus();\n } catch {\n setAvailable(false);\n stop();\n return;\n }\n setAvailable(status.ready);\n if (status.downloading) {\n if (availabilityPollHandle === null) {\n availabilityPollHandle = window.setInterval(() => {\n void refresh();\n }, AVAILABILITY_POLL_MS);\n }\n } else {\n stop();\n }\n }\n\n return { refresh, stop };\n}\n\nexport interface SegmentQueueOptions {\n transport: VoiceCaptureTransport;\n language: () => string;\n callbacks: VoiceCaptureCallbacks;\n setPending: (delta: number) => void;\n // Read-only epoch seam: the queue never mutates the generation, it only reads\n // the parent's current value to drop segments captured under an older session.\n getGeneration: () => number;\n}\n\nexport interface SegmentQueue {\n enqueue: (blob: Blob, gen: number) => void;\n}\n\n// Owns the serialized send chain. Each blob is transcribed in capture order; the\n// generation is checked at entry and again after transcription so a segment\n// belonging to a session the user already left is dropped silently.\nexport function createSegmentQueue(options: SegmentQueueOptions): SegmentQueue {\n const { transport, language, callbacks, setPending, getGeneration } = options;\n let queue: Promise<void> = Promise.resolve();\n\n async function sendSegment(blob: Blob, gen: number): Promise<void> {\n if (gen !== getGeneration()) return;\n try {\n const dataUrl = await blobToDataUrl(blob);\n const result = await transport.transcribe(dataUrl, language());\n if (gen !== getGeneration()) return;\n const text = result.text.trim();\n if (text.length === 0) callbacks.onEmpty?.();\n else callbacks.onTranscript(text);\n } catch (err) {\n // Generation-guard the failure path too: a send rejected after stop()/\n // session change belongs to a session the user already left.\n if (gen === getGeneration()) callbacks.onError?.(toMessage(err));\n }\n }\n\n // Serialize sends so transcripts append in capture order; `pending` keeps\n // `transcribing` true from enqueue until the send resolves.\n function enqueue(blob: Blob, gen: number): void {\n setPending(1);\n queue = queue\n .then(() => sendSegment(blob, gen))\n .catch(() => undefined)\n .finally(() => setPending(-1));\n }\n\n return { enqueue };\n}\n\nexport interface AudioGraph {\n /** True between `attach()` and the next `teardown()`. */\n isAttached: () => boolean;\n /** Read the current PCM window into an internal buffer and return it.\n * Callers must not mutate the returned array. */\n sample: () => Float32Array;\n /** Live mic stream — the outer needs it to hand to MediaRecorder. */\n getStream: () => MediaStream | null;\n /** Attach a fresh mic stream: create AudioContext + AnalyserNode + VAD buffer,\n * connect the source. Called only by `bootstrapCapture` after the caller has\n * passed the stale-generation / permission checks. */\n attach: (stream: MediaStream) => void;\n /** Close the AudioContext, stop the mic tracks, null everything. Safe to\n * call before `attach()` or twice in a row. */\n teardown: () => void;\n}\n\n// Owns the browser-side audio pipeline: mic stream + AudioContext + AnalyserNode\n// + the reusable Float32 buffer VAD reads samples into. Separated from\n// `createVoiceCapture` so its four browser-API fields don't inflate the parent\n// factory's line count and so the setup/teardown ordering is in one place.\nfunction createAudioGraph(): AudioGraph {\n let stream: MediaStream | null = null;\n let audioCtx: AudioContext | null = null;\n let analyser: AnalyserNode | null = null;\n let vadBuffer = new Float32Array(0);\n\n function attach(nextStream: MediaStream): void {\n stream = nextStream;\n audioCtx = new AudioContext();\n analyser = audioCtx.createAnalyser();\n analyser.fftSize = 2048;\n vadBuffer = new Float32Array(analyser.fftSize);\n audioCtx.createMediaStreamSource(nextStream).connect(analyser);\n }\n\n function sample(): Float32Array {\n analyser?.getFloatTimeDomainData(vadBuffer);\n return vadBuffer;\n }\n\n function teardown(): void {\n if (audioCtx) {\n audioCtx.close().catch(() => undefined);\n audioCtx = null;\n }\n analyser = null;\n stream?.getTracks().forEach((track) => track.stop());\n stream = null;\n }\n\n return { isAttached: () => analyser !== null, sample, getStream: () => stream, attach, teardown };\n}\n\ninterface BootstrappedCapture {\n audioGraph: AudioGraph;\n mimeType: string;\n}\n\n// Acquire the mic + probe MediaRecorder support + wire an AudioGraph, returning\n// null (with `callbacks.onError` fired) on any recoverable failure. Deliberately\n// does NOT touch `state` or start the recorder — the caller commits the session\n// only after this resolves successfully, so a stale `generation` detected mid-\n// flight can drop the tracks and bail without partially publishing state.\nasync function bootstrapCapture(callbacks: VoiceCaptureCallbacks, generationAtStart: number, generationNow: () => number): Promise<BootstrappedCapture | null> {\n const mimeType = pickRecorderMime() ?? \"\";\n if (!mimeType || !navigator.mediaDevices?.getUserMedia) {\n callbacks.onError?.(\"unsupported\");\n return null;\n }\n let acquired: MediaStream;\n try {\n acquired = await navigator.mediaDevices.getUserMedia({ audio: true });\n } catch {\n callbacks.onError?.(\"permission-denied\");\n return null;\n }\n if (generationAtStart !== generationNow()) {\n acquired.getTracks().forEach((track) => track.stop());\n return null;\n }\n const audioGraph = createAudioGraph();\n try {\n audioGraph.attach(acquired);\n } catch (err) {\n // teardown() is null-safe and closes any half-created AudioContext AND\n // stops the mic tracks — the pre-refactor code only stopped tracks and\n // leaked the context (codex/CodeRabbit findings on this PR).\n audioGraph.teardown();\n throw err;\n }\n return { audioGraph, mimeType };\n}\n\nexport interface RecorderSession {\n isRecording: () => boolean;\n hadSpeech: () => boolean;\n markSpeech: () => void;\n /** Start a new segment on `stream`, tagged with `gen`. Resets per-segment\n * state (chunks + hadSpeech) synchronously so a subsequent VAD tick sees\n * a fresh window. */\n startNext: (stream: MediaStream, mimeType: string, gen: number) => void;\n /** Force-close the current segment (silence exceeded or MAX_SEGMENT_MS). */\n cut: () => void;\n}\n\ninterface RecorderSessionDeps {\n /** Fires each time a segment finishes. The parent decides whether to\n * restart (via `session.startNext`) and whether to enqueue the blob. */\n onSegmentEnd: (blob: Blob, hadSpeech: boolean, gen: number) => void;\n}\n\n// Owns MediaRecorder + its per-segment scratchpad (chunks, hadSpeech, gen,\n// mimeType). The parent keeps VAD state and the global generation, and calls\n// `startNext` on both initial-start and post-onstop restart paths.\nfunction createRecorderSession(deps: RecorderSessionDeps): RecorderSession {\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let segmentHasSpeech = false;\n let sessionGen = 0;\n let sessionMimeType = \"\";\n\n function onStop(): void {\n // Snapshot BEFORE the parent's onSegmentEnd callback runs; `startNext`\n // (if the parent chooses to restart) will clear chunks synchronously.\n const hadSpeech = segmentHasSpeech;\n const gen = sessionGen;\n const blob = new Blob(chunks, { type: containerTypeFromMime(sessionMimeType) });\n deps.onSegmentEnd(blob, hadSpeech, gen);\n }\n\n function startNext(stream: MediaStream, mimeType: string, gen: number): void {\n chunks = [];\n segmentHasSpeech = false;\n sessionGen = gen;\n sessionMimeType = mimeType;\n recorder = new MediaRecorder(stream, { mimeType });\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) chunks.push(event.data);\n };\n recorder.onstop = onStop;\n recorder.start();\n }\n\n return {\n isRecording: () => recorder?.state === \"recording\",\n hadSpeech: () => segmentHasSpeech,\n markSpeech: () => {\n segmentHasSpeech = true;\n },\n startNext,\n cut: () => {\n if (recorder?.state === \"recording\") recorder.stop();\n },\n };\n}\n\n// Zero-values used to seed a fresh `CaptureRuntime` at the top of every\n// `createVoiceCapture` call. Kept module-scope so the seed doesn't inflate the\n// factory's line count.\nconst INITIAL_RUNTIME: Readonly<CaptureRuntime> = {\n audioGraph: null,\n monitorHandle: null,\n mimeType: \"\",\n silenceStart: null,\n segmentStart: 0,\n generation: 0,\n startInFlight: false,\n};\n\n// Mutable capture-time state, kept as one object so module-scope helpers\n// (`stopCapture`, `monitorTick`) can be typed against one shape rather than\n// threading each field through their signatures.\ninterface CaptureRuntime {\n audioGraph: AudioGraph | null;\n monitorHandle: number | null;\n mimeType: string;\n silenceStart: number | null;\n segmentStart: number;\n /** Bumped on stop(); segments captured under an older value are dropped so a\n * late transcript never leaks across sessions. */\n generation: number;\n /** Single-flight guard on start() — true between entry and completion so a\n * second start can't race the first before `listening` flips. */\n startInFlight: boolean;\n}\n\n// Tear down the browser-side resources. `state.setListening(false)` MUST happen\n// BEFORE `session.cut()` so the parent's onSegmentEnd callback sees\n// isListening()===false and does NOT restart. The monitor interval MUST clear\n// BEFORE `audioGraph.teardown()` so a scheduled tick can't run against a\n// half-closed AudioContext.\nfunction stopCapture(runtime: CaptureRuntime, state: CaptureStateController, session: RecorderSession): void {\n runtime.generation += 1;\n state.setListening(false);\n if (runtime.monitorHandle !== null) {\n window.clearInterval(runtime.monitorHandle);\n runtime.monitorHandle = null;\n }\n session.cut();\n runtime.audioGraph?.teardown();\n runtime.audioGraph = null;\n}\n\n// One VAD tick against the audio graph's current window. No-op when the graph\n// is not attached (defensive: `stopCapture` clears `monitorHandle` before\n// `audioGraph.teardown()`, so this is the belt-and-braces for any late fire).\nfunction monitorTick(runtime: CaptureRuntime, session: RecorderSession): void {\n if (!runtime.audioGraph?.isAttached()) return;\n const rms = computeRms(runtime.audioGraph.sample());\n const {\n hasSpeech,\n silenceStart: nextSilence,\n cut,\n } = evaluateVad({ hasSpeech: session.hadSpeech(), silenceStart: runtime.silenceStart }, runtime.segmentStart, rms, Date.now(), VAD_CONFIG);\n if (hasSpeech) session.markSpeech();\n runtime.silenceStart = nextSilence;\n if (cut) session.cut();\n}\n\nexport function createVoiceCapture(transport: VoiceCaptureTransport, language: () => string, callbacks: VoiceCaptureCallbacks): VoiceCapture {\n const state = createCaptureState(callbacks.onState);\n const poller = createAvailabilityPoller(transport, state.setAvailable);\n const runtime: CaptureRuntime = { ...INITIAL_RUNTIME };\n const segments = createSegmentQueue({ transport, language, callbacks, setPending: state.setPending, getGeneration: () => runtime.generation });\n\n const session = createRecorderSession({ onSegmentEnd: handleSegmentEnd });\n\n function handleSegmentEnd(blob: Blob, hadSpeech: boolean, gen: number): void {\n // Restart FIRST so audio-loss between segments is minimal; the snapshot\n // in blob/hadSpeech/gen is already independent of session state.\n if (state.isListening()) startRecorder();\n if (hadSpeech && blob.size > 0 && gen === runtime.generation) segments.enqueue(blob, gen);\n }\n\n function startRecorder(): void {\n const stream = runtime.audioGraph?.getStream();\n if (!stream) return;\n runtime.silenceStart = null;\n runtime.segmentStart = Date.now();\n session.startNext(stream, runtime.mimeType, runtime.generation);\n }\n\n async function start(): Promise<boolean> {\n if (runtime.startInFlight || state.isListening()) return true;\n runtime.startInFlight = true;\n const startGen = runtime.generation;\n try {\n const capture = await bootstrapCapture(callbacks, startGen, () => runtime.generation);\n if (!capture) return false;\n runtime.audioGraph = capture.audioGraph;\n runtime.mimeType = capture.mimeType;\n state.setListening(true);\n startRecorder();\n runtime.monitorHandle = window.setInterval(() => monitorTick(runtime, session), MONITOR_INTERVAL_MS);\n return true;\n } finally {\n runtime.startInFlight = false;\n }\n }\n\n function stop(): void {\n stopCapture(runtime, state, session);\n }\n\n function dispose(): void {\n poller.stop();\n stop();\n }\n\n return { refreshAvailability: poller.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AO;EAAE,qBAAqB,OAAO;EAAS;EAAO;EAAM;CAAQ;AACrE"}
|
package/dist/whisper/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_rolldown_runtime = require("../rolldown-runtime-
|
|
2
|
+
const require_rolldown_runtime = require("../rolldown-runtime-VH7oDXx4.cjs");
|
|
3
3
|
const require_dist = require("../dist-CsgSfWwR.cjs");
|
|
4
4
|
let node_fs = require("node:fs");
|
|
5
5
|
let node_path = require("node:path");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/whisper/internal.ts","../../src/whisper/ffmpeg.ts","../../src/whisper/models.ts","../../src/whisper/sidecar-helpers.ts","../../src/whisper/sidecar.ts","../../src/whisper/whisper.ts"],"sourcesContent":["// Small self-contained utilities so the package has no host dependencies.\n\nexport const ONE_SECOND_MS = 1_000;\nexport const ONE_MINUTE_MS = 60_000;\n\nexport { errorMessage } from \"../utils/errors.js\";\n\n/** Minimal logger the host can inject; defaults to no-op so the package\n * is silent unless wired up. */\nexport interface WhisperLogger {\n info: (message: string, data?: unknown) => void;\n warn: (message: string, data?: unknown) => void;\n error: (message: string, data?: unknown) => void;\n}\n\nconst NOOP = (): void => undefined;\nexport const NOOP_LOGGER: WhisperLogger = { info: NOOP, warn: NOOP, error: NOOP };\n","// Thin wrapper around the system `ffmpeg` binary (provided by the host) for\n// converting a browser webm/opus clip to the 16 kHz mono 16-bit WAV whisper.cpp\n// requires.\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { ONE_MINUTE_MS } from \"./internal.ts\";\n\nconst execFileAsync = promisify(execFile);\n\n/** ffmpeg args to decode any input to 16 kHz mono signed-16-bit WAV. Pure +\n * exported for unit tests. */\nexport function buildWav16kArgs(inputPath: string, outputPath: string): string[] {\n return [\"-y\", \"-loglevel\", \"error\", \"-i\", inputPath, \"-ar\", \"16000\", \"-ac\", \"1\", \"-c:a\", \"pcm_s16le\", outputPath];\n}\n\n/** Convert `inputPath` to a 16 kHz mono WAV at `outputPath`. Throws on ffmpeg\n * failure or timeout. */\nexport async function convertToWav16k(inputPath: string, outputPath: string, ffmpegBinary = \"ffmpeg\"): Promise<void> {\n await execFileAsync(ffmpegBinary, buildWav16kArgs(inputPath, outputPath), {\n timeout: ONE_MINUTE_MS,\n });\n}\n","// Whisper GGML model registry + on-disk management. The host injects the models\n// directory (e.g. `{workspace}/models`); nothing here reads a host module.\n\nimport { createWriteStream, mkdirSync, renameSync, statSync, unlinkSync } from \"node:fs\";\nimport { once } from \"node:events\";\nimport path from \"node:path\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, type WhisperLogger } from \"./internal.ts\";\n\nexport interface WhisperModelSpec {\n /** GGML filename — identical on disk and in the Hugging Face repo. */\n readonly file: string;\n /** Download URL (Hugging Face whisper.cpp model repo). */\n readonly url: string;\n /** Conservative lower bound on the finished file size, in bytes — guards\n * against a truncated transfer or an HTML error page saved as the model\n * without pinning an exact checksum. */\n readonly minBytes: number;\n}\n\nconst HF_BASE = \"https://huggingface.co/ggerganov/whisper.cpp/resolve/main\";\n\n// large-v3-turbo: strong accuracy, near-real-time on Apple Silicon with Metal.\n// small/base are lighter fallbacks for low-RAM machines.\nexport const WHISPER_MODELS = {\n \"large-v3-turbo\": { file: \"ggml-large-v3-turbo.bin\", url: `${HF_BASE}/ggml-large-v3-turbo.bin`, minBytes: 1_000_000_000 },\n small: { file: \"ggml-small.bin\", url: `${HF_BASE}/ggml-small.bin`, minBytes: 300_000_000 },\n base: { file: \"ggml-base.bin\", url: `${HF_BASE}/ggml-base.bin`, minBytes: 100_000_000 },\n} as const satisfies Record<string, WhisperModelSpec>;\n\nexport type WhisperModelName = keyof typeof WHISPER_MODELS;\nexport const DEFAULT_WHISPER_MODEL: WhisperModelName = \"large-v3-turbo\";\n\nexport function isWhisperModelName(value: unknown): value is WhisperModelName {\n // Own-property check — `in` would accept inherited keys like \"toString\",\n // which then crash the `WHISPER_MODELS[name]` lookups instead of falling\n // back to the default.\n return typeof value === \"string\" && Object.prototype.hasOwnProperty.call(WHISPER_MODELS, value);\n}\n\n/** Resolve a possibly-unset / unknown model name to a valid one. */\nexport function resolveModelName(name: string | undefined): WhisperModelName {\n return isWhisperModelName(name) ? name : DEFAULT_WHISPER_MODEL;\n}\n\nexport function modelFilePath(modelsDir: string, name: WhisperModelName): string {\n return path.join(modelsDir, WHISPER_MODELS[name].file);\n}\n\n/** A model is \"ready\" when its file exists and meets the size floor. */\nexport function isModelReady(modelsDir: string, name: WhisperModelName): boolean {\n try {\n return statSync(modelFilePath(modelsDir, name)).size >= WHISPER_MODELS[name].minBytes;\n } catch {\n return false;\n }\n}\n\nexport type ModelDownloadState = \"idle\" | \"downloading\" | \"ready\" | \"error\";\n\nexport interface ModelStatus {\n state: ModelDownloadState;\n /** 0..1 — present only while downloading and Content-Length is known. */\n progress?: number;\n /** Present only in the \"error\" state. */\n error?: string;\n}\n\n/** Report status precedence: an in-flight download wins, then an on-disk ready\n * file, then the last transient state (idle if none). Pure so the precedence\n * is unit-testable without touching the filesystem. */\nexport function pickModelStatus(live: ModelStatus | undefined, isReady: boolean): ModelStatus {\n if (live?.state === \"downloading\") return live;\n if (isReady) return { state: \"ready\" };\n return live ?? { state: \"idle\" };\n}\n\n/** Parse a `Content-Length` header to a byte count; unknown / malformed → 0. */\nexport function parseContentLength(header: string | null): number {\n return Number(header) || 0;\n}\n\n// Abort a download if no bytes arrive for this long (stalled connection).\nconst DOWNLOAD_STALL_TIMEOUT_MS = ONE_MINUTE_MS;\n\nexport interface ModelDownloader {\n getStatus: (name: WhisperModelName) => ModelStatus;\n ensure: (name: WhisperModelName) => Promise<void>;\n}\n\ninterface StreamToFileDeps {\n downloadStatus: Map<WhisperModelName, ModelStatus>;\n onProgress: () => void;\n}\n\n/** Drain the response stream into the `.partial` file, resetting the stall\n * timer on every chunk and publishing progress once the total size is known. */\nasync function streamToFile(\n body: ReadableStream<Uint8Array>,\n partialPath: string,\n total: number,\n name: WhisperModelName,\n deps: StreamToFileDeps,\n): Promise<void> {\n const reader = body.getReader();\n const fileStream = createWriteStream(partialPath);\n let received = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n deps.onProgress();\n received += value.byteLength;\n if (!fileStream.write(value)) await once(fileStream, \"drain\");\n if (total > 0) deps.downloadStatus.set(name, { state: \"downloading\", progress: received / total });\n }\n fileStream.end();\n await once(fileStream, \"finish\");\n } catch (err) {\n // `createWriteStream` opens lazily. Destroying it while that open is still\n // in flight lets the open's own failure land later as an `error` event with\n // no listener — an uncaughtException that kills the process. `err` already\n // carries the real cause, so absorb the late one.\n fileStream.on(\"error\", () => {});\n fileStream.destroy();\n throw err;\n }\n}\n\n/** Fetch a model into a `.partial` file, reject a truncated transfer via the\n * size floor, then atomically rename it into place. */\nasync function downloadModel(name: WhisperModelName, modelsDir: string, downloadStatus: Map<WhisperModelName, ModelStatus>): Promise<void> {\n const spec = WHISPER_MODELS[name];\n mkdirSync(modelsDir, { recursive: true });\n const dest = modelFilePath(modelsDir, name);\n const partial = `${dest}.partial`;\n const controller = new AbortController();\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n const resetStall = () => {\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => controller.abort(), DOWNLOAD_STALL_TIMEOUT_MS);\n };\n try {\n const response = await fetch(spec.url, { signal: controller.signal });\n if (!response.ok || !response.body) {\n throw new Error(`download failed: HTTP ${response.status}`);\n }\n const total = parseContentLength(response.headers.get(\"content-length\"));\n resetStall();\n await streamToFile(response.body, partial, total, name, { downloadStatus, onProgress: resetStall });\n if (statSync(partial).size < spec.minBytes) {\n unlinkSync(partial);\n throw new Error(\"downloaded file is smaller than expected — likely truncated\");\n }\n renameSync(partial, dest);\n } finally {\n if (stallTimer) clearTimeout(stallTimer);\n }\n}\n\nexport function createModelDownloader(modelsDir: string, logger: WhisperLogger = NOOP_LOGGER): ModelDownloader {\n // A finished file on disk is the source of truth for \"ready\"; this map tracks\n // transient progress + the last error.\n const downloadStatus = new Map<WhisperModelName, ModelStatus>();\n\n function getStatus(name: WhisperModelName): ModelStatus {\n return pickModelStatus(downloadStatus.get(name), isModelReady(modelsDir, name));\n }\n\n // Fire-and-forget friendly: errors land in the status map, never thrown.\n // Idempotent — a second call while a download is in flight does nothing.\n async function ensure(name: WhisperModelName): Promise<void> {\n if (isModelReady(modelsDir, name)) {\n downloadStatus.set(name, { state: \"ready\" });\n return;\n }\n if (downloadStatus.get(name)?.state === \"downloading\") return;\n downloadStatus.set(name, { state: \"downloading\", progress: 0 });\n logger.info(\"model download: start\", { model: name });\n try {\n await downloadModel(name, modelsDir, downloadStatus);\n downloadStatus.set(name, { state: \"ready\" });\n logger.info(\"model download: ok\", { model: name });\n } catch (err) {\n const error = errorMessage(err);\n downloadStatus.set(name, { state: \"error\", error });\n logger.error(\"model download: failed\", { model: name, error });\n }\n }\n\n return { getStatus, ensure };\n}\n","// Pure helpers for the whisper-server sidecar. Kept separate from `sidecar.ts`\n// so the argv/response/stderr logic can be unit-tested without spawning a\n// process or opening a socket.\n\nimport { hasStringProp } from \"@mulmoclaude/common\";\n\n/** whisper-server CLI args to preload `modelPath` and bind to `host:port`. */\nexport function buildServerArgs(modelPath: string, host: string, port: number): string[] {\n return [\"--model\", modelPath, \"--host\", host, \"--port\", String(port)];\n}\n\n/** Append `chunk` to a bounded stderr tail, keeping only the last `maxChars`. */\nexport function appendStderrTail(previous: string, chunk: string, maxChars: number): string {\n return (previous + chunk).slice(-maxChars);\n}\n\n/** Extract the transcript from a whisper-server `/inference` JSON response.\n * Returns \"\" for any shape that lacks a string `text` field. */\nexport function parseInferenceText(data: unknown): string {\n return hasStringProp(data, \"text\") ? data.text : \"\";\n}\n","// whisper.cpp warm-model sidecar. Spawns `whisper-server` once with the model\n// preloaded and reuses it across transcriptions over its local HTTP API, so the\n// weights stay resident (no per-request reload). State is encapsulated per\n// instance via the factory closure.\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { createServer } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, ONE_SECOND_MS, type WhisperLogger } from \"./internal.ts\";\nimport { modelFilePath, type WhisperModelName } from \"./models.ts\";\nimport { appendStderrTail, buildServerArgs, parseInferenceText } from \"./sidecar-helpers.ts\";\n\nconst HOST = \"127.0.0.1\";\nconst READY_TIMEOUT_MS = 60 * ONE_SECOND_MS;\nconst READY_POLL_INTERVAL_MS = 500;\nconst INFERENCE_TIMEOUT_MS = 2 * ONE_MINUTE_MS;\nconst STDERR_TAIL_MAX_CHARS = 4_000;\n\nexport interface ActiveSidecar {\n readonly port: number;\n readonly proc: ChildProcess;\n readonly model: WhisperModelName;\n}\n\nexport interface Sidecar {\n transcribeWav: (wavPath: string, language: string, model: WhisperModelName) => Promise<string>;\n warmup: (model: WhisperModelName) => Promise<void>;\n shutdown: () => void;\n}\n\nasync function findFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer();\n srv.on(\"error\", reject);\n srv.listen(0, HOST, () => {\n const addr = srv.address();\n if (addr && typeof addr === \"object\") {\n const { port } = addr;\n srv.close(() => resolve(port));\n } else {\n srv.close(() => reject(new Error(\"could not determine a free port\")));\n }\n });\n });\n}\n\n/** Resolve once the server answers any HTTP request (any status = listener up),\n * or throw after the ready timeout. */\nasync function waitUntilReady(port: number): Promise<void> {\n const deadline = Date.now() + READY_TIMEOUT_MS;\n while (Date.now() < deadline) {\n try {\n await fetch(`http://${HOST}:${port}/`, { signal: AbortSignal.timeout(ONE_SECOND_MS) });\n return;\n } catch {\n await delay(READY_POLL_INTERVAL_MS);\n }\n }\n throw new Error(\"whisper-server did not become ready in time\");\n}\n\n// whisper-server logs verbosely to stderr; left unread the OS pipe buffer fills\n// and the child blocks on its next write. Drain into a small tail buffer.\nfunction drainStderr(proc: ChildProcess, tail: { text: string }): void {\n proc.stderr?.setEncoding(\"utf8\");\n proc.stderr?.on(\"data\", (chunk: string) => {\n tail.text = appendStderrTail(tail.text, chunk, STDERR_TAIL_MAX_CHARS);\n });\n}\n\n// Resolve when the server answers, or reject on spawn failure (e.g. ENOENT) /\n// early exit. Listeners are one-shot and removed once the race settles.\nfunction waitForReadyOrFailure(proc: ChildProcess, port: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let onError: (err: Error) => void = () => undefined;\n let onExit: (code: number | null) => void = () => undefined;\n const cleanup = () => {\n proc.removeListener(\"error\", onError);\n proc.removeListener(\"exit\", onExit);\n };\n onError = (err: Error) => {\n cleanup();\n reject(new Error(`spawn failed: ${errorMessage(err)}`));\n };\n onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`exited early (code ${code})`));\n };\n proc.once(\"error\", onError);\n proc.once(\"exit\", onExit);\n waitUntilReady(port)\n .then(() => {\n cleanup();\n resolve();\n })\n .catch((err: unknown) => {\n cleanup();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n });\n}\n\n// POST the wav to whisper-server's `/inference` and return the transcript.\n// Isolated from the lifecycle so the HTTP contract is unit-testable without a\n// live child (stub `fetch`, hand it a real wav path).\nexport async function postInference(port: number, wavPath: string, language: string): Promise<string> {\n const buf = await readFile(wavPath);\n const form = new FormData();\n form.append(\"file\", new Blob([buf], { type: \"audio/wav\" }), \"audio.wav\");\n form.append(\"response_format\", \"json\");\n form.append(\"language\", language || \"auto\");\n let res: Response;\n try {\n res = await fetch(`http://${HOST}:${port}/inference`, { method: \"POST\", body: form, signal: AbortSignal.timeout(INFERENCE_TIMEOUT_MS) });\n } catch (err) {\n throw new Error(`whisper-server request failed: ${errorMessage(err)}`);\n }\n if (!res.ok) throw new Error(`whisper-server returned HTTP ${res.status}`);\n return parseInferenceText(await res.json());\n}\n\n// The impure primitives the start lifecycle depends on, injected so the\n// cancellation / single-flight / model-switch logic can be driven with fakes.\nexport interface StartLifecycleDeps {\n /** Reserve a free TCP port for the next child — the sole async step of a start. */\n allocatePort: () => Promise<number>;\n /** Spawn the whisper-server child on `port`. MUST be synchronous so the spawn\n * and the `startingProc` handoff stay in one tick: `shutdown()` has to be able\n * to kill an in-flight child immediately, with no await gap after it exists. */\n spawnServer: (model: WhisperModelName, port: number) => ChildProcess;\n /** Resolve once the child answers HTTP, or reject on spawn failure / early exit. */\n waitReady: (proc: ChildProcess, port: number) => Promise<void>;\n logger: WhisperLogger;\n}\n\nexport interface StartLifecycle {\n ensureSidecar: (model: WhisperModelName) => Promise<ActiveSidecar>;\n shutdown: () => void;\n}\n\nexport function defaultSpawnServer(modelsDir: string, serverBinary: string, logger: WhisperLogger): StartLifecycleDeps[\"spawnServer\"] {\n return (model: WhisperModelName, port: number): ChildProcess => {\n const args = buildServerArgs(modelFilePath(modelsDir, model), HOST, port);\n logger.info(\"sidecar: spawning\", { model, port });\n return spawn(serverBinary, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n };\n}\n\n// Wires the three listeners every whisper-server child needs: stderr drain,\n// permanent `error` handler (an unhandled 'error' from ENOENT etc. would crash\n// the host), and `exit` handler that both logs and lets the caller decide\n// whether this proc is still the active one (identity check via `onExit` — a\n// stale process must not evict a newer live sidecar).\nfunction instrumentChildProcess(proc: ChildProcess, model: WhisperModelName, logger: WhisperLogger, onExit: (exited: ChildProcess) => void): { text: string } {\n const stderrTail = { text: \"\" };\n drainStderr(proc, stderrTail);\n proc.on(\"error\", (err) => logger.warn(\"sidecar: process error\", { model, error: errorMessage(err) }));\n proc.on(\"exit\", (code) => {\n logger.warn(\"sidecar: exited\", { model, code, stderrTail: stderrTail.text.slice(-500) });\n onExit(proc);\n });\n return stderrTail;\n}\n\n// Await server readiness; on failure, kill the child and surface both the\n// underlying error and the tail of stderr (whisper-server usually explains its\n// crash there). Kept at module scope so `startSidecar` stays under the\n// per-function line cap.\nasync function awaitReadyOrThrow(proc: ChildProcess, port: number, stderrTail: { text: string }, waitReady: StartLifecycleDeps[\"waitReady\"]): Promise<void> {\n try {\n await waitReady(proc, port);\n } catch (err) {\n proc.kill();\n throw new Error(`whisper-server failed to start: ${errorMessage(err)} — stderr: ${stderrTail.text.slice(-500)}`);\n }\n}\n\n// Abort a start that was raced by `shutdown()` (or a newer start). Compares\n// the token captured at start entry against the current token; if they differ,\n// kill the freshly-booted child rather than publish it after shutdown returned.\nfunction throwIfStartCancelled(startedToken: number, currentToken: number, proc: ChildProcess): void {\n if (startedToken !== currentToken) {\n proc.kill();\n throw new Error(\"whisper-server start cancelled\");\n }\n}\n\n// Owns the single warm child's lifecycle: which model is live, the in-flight\n// start, and the cancellation token. Kept as a factory closure so the mutable\n// state is encapsulated rather than threaded through parameters.\nexport function createStartLifecycle(deps: StartLifecycleDeps): StartLifecycle {\n const { allocatePort, spawnServer, waitReady, logger } = deps;\n let sidecar: ActiveSidecar | null = null;\n let starting: { model: WhisperModelName; promise: Promise<ActiveSidecar> } | null = null;\n // The child of an in-flight start (before it's published as `sidecar`), plus a\n // token that `shutdown()` bumps to cancel a start that's still booting — so\n // shutdown can't return with a child that then publishes itself afterwards.\n let startingProc: ChildProcess | null = null;\n let startToken = 0;\n\n function shutdown(): void {\n startToken += 1;\n startingProc?.kill();\n startingProc = null;\n sidecar?.proc.kill();\n sidecar = null;\n }\n\n async function startSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n const token = ++startToken;\n const port = await allocatePort();\n const proc = spawnServer(model, port);\n startingProc = proc;\n // onExit fires when THIS proc exits: only null out `sidecar` if it's still the live one.\n const stderrTail = instrumentChildProcess(proc, model, logger, (exited) => sidecar?.proc === exited && (sidecar = null));\n try {\n await awaitReadyOrThrow(proc, port, stderrTail, waitReady);\n } finally {\n if (startingProc === proc) startingProc = null;\n }\n throwIfStartCancelled(token, startToken, proc);\n sidecar = { port, proc, model };\n logger.info(\"sidecar: ready\", { model, port });\n return sidecar;\n }\n\n // Own function so it isn't a loop closure (no-loop-func). Only ever one start\n // is in flight at a time, so clearing `starting` on settle is safe.\n function beginStart(model: WhisperModelName): Promise<ActiveSidecar> {\n const promise = startSidecar(model).finally(() => (starting = null));\n starting = { model, promise };\n return promise;\n }\n\n async function ensureSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n // Loop so that after awaiting an in-flight start for a DIFFERENT model we\n // re-evaluate; the decision-to-spawn path (beginStart) has no await, so the\n // first waiter sets `starting` synchronously and siblings then reuse it.\n for (;;) {\n if (sidecar && sidecar.model === model && !sidecar.proc.killed) return sidecar;\n if (starting && starting.model === model) return starting.promise;\n if (starting) {\n await starting.promise.catch(() => undefined);\n continue;\n }\n if (sidecar && sidecar.model !== model) shutdown();\n return beginStart(model);\n }\n }\n\n return { ensureSidecar, shutdown };\n}\n\nexport function createSidecar(modelsDir: string, serverBinary = \"whisper-server\", logger: WhisperLogger = NOOP_LOGGER): Sidecar {\n const lifecycle = createStartLifecycle({\n allocatePort: findFreePort,\n spawnServer: defaultSpawnServer(modelsDir, serverBinary, logger),\n waitReady: waitForReadyOrFailure,\n logger,\n });\n\n async function warmup(model: WhisperModelName): Promise<void> {\n try {\n await lifecycle.ensureSidecar(model);\n } catch (err) {\n logger.warn(\"sidecar: warmup failed\", { model, error: errorMessage(err) });\n }\n }\n\n async function transcribeWav(wavPath: string, language: string, model: WhisperModelName): Promise<string> {\n const active = await lifecycle.ensureSidecar(model);\n return postInference(active.port, wavPath, language);\n }\n\n return { transcribeWav, warmup, shutdown: lifecycle.shutdown };\n}\n","// Public server-side façade: wires the model downloader, the warm sidecar, and\n// ffmpeg conversion into one host-agnostic service. The host injects the models\n// directory + a logger and gates capability itself (platform / binary presence);\n// this package assumes the binaries exist when called.\n\nimport { mkdirSync } from \"node:fs\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { NOOP_LOGGER, type WhisperLogger } from \"./internal.ts\";\nimport { convertToWav16k } from \"./ffmpeg.ts\";\nimport { createModelDownloader } from \"./models.ts\";\nimport { createSidecar } from \"./sidecar.ts\";\nimport { isModelReady, type ModelStatus, type WhisperModelName } from \"./models.ts\";\n\nexport interface WhisperOptions {\n /** Directory that holds the GGML model files (e.g. `{workspace}/models`). */\n modelsDir: string;\n logger?: WhisperLogger;\n /** Defaults to \"whisper-server\" / \"ffmpeg\" on PATH. */\n serverBinary?: string;\n ffmpegBinary?: string;\n}\n\nexport interface TranscribeRequest {\n base64: string;\n mimeType: string;\n language: string;\n model: WhisperModelName;\n}\n\nexport interface Whisper {\n isModelReady: (model: WhisperModelName) => boolean;\n getModelStatus: (model: WhisperModelName) => ModelStatus;\n /** Fire-and-forget friendly; never throws (errors land in the status). */\n ensureModelDownloaded: (model: WhisperModelName) => Promise<void>;\n warmup: (model: WhisperModelName) => Promise<void>;\n transcribe: (req: TranscribeRequest) => Promise<{ text: string }>;\n shutdown: () => void;\n}\n\n// whisper.cpp returns these sentinels for non-speech windows; treat them as\n// empty so the UI shows \"didn't catch that\" rather than a literal marker.\nconst BLANK_MARKERS = new Set([\"[blank_audio]\", \"[silence]\", \"(silence)\", \"[ inaudible ]\"]);\n\nfunction normalizeTranscript(raw: string): string {\n const trimmed = raw.trim().replace(/\\s+/g, \" \");\n return BLANK_MARKERS.has(trimmed.toLowerCase()) ? \"\" : trimmed;\n}\n\nexport function createWhisper(opts: WhisperOptions): Whisper {\n const { modelsDir } = opts;\n const logger = opts.logger ?? NOOP_LOGGER;\n const ffmpegBinary = opts.ffmpegBinary ?? \"ffmpeg\";\n const downloader = createModelDownloader(modelsDir, logger);\n const sidecar = createSidecar(modelsDir, opts.serverBinary ?? \"whisper-server\", logger);\n\n // Scratch dir for transient audio — a hidden subdir of the models dir so it\n // shares the (non-git) models tree. Files are deleted after each transcription.\n const scratchDir = path.join(modelsDir, \".scratch\");\n\n async function transcribe(req: TranscribeRequest): Promise<{ text: string }> {\n mkdirSync(scratchDir, { recursive: true });\n const clipId = randomUUID();\n const inputPath = path.join(scratchDir, `utterance-${clipId}.webm`);\n const wavPath = path.join(scratchDir, `utterance-${clipId}.wav`);\n try {\n await writeFile(inputPath, Buffer.from(req.base64, \"base64\"));\n await convertToWav16k(inputPath, wavPath, ffmpegBinary);\n const text = await sidecar.transcribeWav(wavPath, req.language, req.model);\n return { text: normalizeTranscript(text) };\n } finally {\n await rm(inputPath, { force: true });\n await rm(wavPath, { force: true });\n }\n }\n\n return {\n isModelReady: (model) => isModelReady(modelsDir, model),\n getModelStatus: (model) => downloader.getStatus(model),\n ensureModelDownloaded: (model) => downloader.ensure(model),\n warmup: (model) => sidecar.warmup(model),\n transcribe,\n shutdown: () => sidecar.shutdown(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAEA,IAAa,gBAAgB;AAC7B,IAAa,gBAAgB;AAY7B,IAAM,aAAmB,KAAA;AACzB,IAAa,cAA6B;CAAE,MAAM;CAAM,MAAM;CAAM,OAAO;AAAK;;;ACRhF,IAAM,iBAAA,GAAA,UAAA,UAAA,CAA0B,mBAAA,QAAQ;;;AAIxC,SAAgB,gBAAgB,WAAmB,YAA8B;CAC/E,OAAO;EAAC;EAAM;EAAa;EAAS;EAAM;EAAW;EAAO;EAAS;EAAO;EAAK;EAAQ;EAAa;CAAU;AAClH;;;AAIA,eAAsB,gBAAgB,WAAmB,YAAoB,eAAe,UAAyB;CACnH,MAAM,cAAc,cAAc,gBAAgB,WAAW,UAAU,GAAG,EACxE,SAAS,cACX,CAAC;AACH;;;ACHA,IAAM,UAAU;AAIhB,IAAa,iBAAiB;CAC5B,kBAAkB;EAAE,MAAM;EAA2B,KAAK,GAAG,QAAQ;EAA2B,UAAU;CAAc;CACxH,OAAO;EAAE,MAAM;EAAkB,KAAK,GAAG,QAAQ;EAAkB,UAAU;CAAY;CACzF,MAAM;EAAE,MAAM;EAAiB,KAAK,GAAG,QAAQ;EAAiB,UAAU;CAAY;AACxF;AAGA,IAAa,wBAA0C;AAEvD,SAAgB,mBAAmB,OAA2C;CAI5E,OAAO,OAAO,UAA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3D,MAAM,EAAE,cAAc;CACtB,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,eAAe,KAAK,gBAAgB;CAC1C,MAAM,aAAa,sBAAsB,WAAW,MAAM;CAC1D,MAAM,UAAU,cAAc,WAAW,KAAK,gBAAgB,kBAAkB,MAAM;CAItF,MAAM,aAAa,UAAA,QAAK,KAAK,WAAW,UAAU;CAElD,eAAe,WAAW,KAAmD;EAC3E,CAAA,GAAA,QAAA,UAAA,CAAU,YAAY,EAAE,WAAW,KAAK,CAAC;EACzC,MAAM,UAAA,GAAA,YAAA,WAAA,CAAoB;EAC1B,MAAM,YAAY,UAAA,QAAK,KAAK,YAAY,aAAa,OAAO,MAAM;EAClE,MAAM,UAAU,UAAA,QAAK,KAAK,YAAY,aAAa,OAAO,KAAK;EAC/D,IAAI;GACF,OAAA,GAAA,iBAAA,UAAA,CAAgB,WAAW,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC;GAC5D,MAAM,gBAAgB,WAAW,SAAS,YAAY;GAEtD,OAAO,EAAE,MAAM,oBAAoB,MADhB,QAAQ,cAAc,SAAS,IAAI,UAAU,IAAI,KAAK,CAClC,EAAE;EAC3C,UAAU;GACR,OAAA,GAAA,iBAAA,GAAA,CAAS,WAAW,EAAE,OAAO,KAAK,CAAC;GACnC,OAAA,GAAA,iBAAA,GAAA,CAAS,SAAS,EAAE,OAAO,KAAK,CAAC;EACnC;CACF;CAEA,OAAO;EACL,eAAe,UAAU,aAAa,WAAW,KAAK;EACtD,iBAAiB,UAAU,WAAW,UAAU,KAAK;EACrD,wBAAwB,UAAU,WAAW,OAAO,KAAK;EACzD,SAAS,UAAU,QAAQ,OAAO,KAAK;EACvC;EACA,gBAAgB,QAAQ,SAAS;CACnC;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/whisper/internal.ts","../../src/whisper/ffmpeg.ts","../../src/whisper/models.ts","../../src/whisper/sidecar-helpers.ts","../../src/whisper/sidecar.ts","../../src/whisper/whisper.ts"],"sourcesContent":["// Small self-contained utilities so the package has no host dependencies.\n\nexport const ONE_SECOND_MS = 1_000;\nexport const ONE_MINUTE_MS = 60_000;\n\nexport { errorMessage } from \"../utils/errors.js\";\n\n/** Minimal logger the host can inject; defaults to no-op so the package\n * is silent unless wired up. */\nexport interface WhisperLogger {\n info: (message: string, data?: unknown) => void;\n warn: (message: string, data?: unknown) => void;\n error: (message: string, data?: unknown) => void;\n}\n\nconst NOOP = (): void => undefined;\nexport const NOOP_LOGGER: WhisperLogger = { info: NOOP, warn: NOOP, error: NOOP };\n","// Thin wrapper around the system `ffmpeg` binary (provided by the host) for\n// converting a browser webm/opus clip to the 16 kHz mono 16-bit WAV whisper.cpp\n// requires.\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { ONE_MINUTE_MS } from \"./internal.ts\";\n\nconst execFileAsync = promisify(execFile);\n\n/** ffmpeg args to decode any input to 16 kHz mono signed-16-bit WAV. Pure +\n * exported for unit tests. */\nexport function buildWav16kArgs(inputPath: string, outputPath: string): string[] {\n return [\"-y\", \"-loglevel\", \"error\", \"-i\", inputPath, \"-ar\", \"16000\", \"-ac\", \"1\", \"-c:a\", \"pcm_s16le\", outputPath];\n}\n\n/** Convert `inputPath` to a 16 kHz mono WAV at `outputPath`. Throws on ffmpeg\n * failure or timeout. */\nexport async function convertToWav16k(inputPath: string, outputPath: string, ffmpegBinary = \"ffmpeg\"): Promise<void> {\n await execFileAsync(ffmpegBinary, buildWav16kArgs(inputPath, outputPath), {\n timeout: ONE_MINUTE_MS,\n });\n}\n","// Whisper GGML model registry + on-disk management. The host injects the models\n// directory (e.g. `{workspace}/models`); nothing here reads a host module.\n\nimport { createWriteStream, mkdirSync, renameSync, statSync, unlinkSync } from \"node:fs\";\nimport { once } from \"node:events\";\nimport path from \"node:path\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, type WhisperLogger } from \"./internal.ts\";\n\nexport interface WhisperModelSpec {\n /** GGML filename — identical on disk and in the Hugging Face repo. */\n readonly file: string;\n /** Download URL (Hugging Face whisper.cpp model repo). */\n readonly url: string;\n /** Conservative lower bound on the finished file size, in bytes — guards\n * against a truncated transfer or an HTML error page saved as the model\n * without pinning an exact checksum. */\n readonly minBytes: number;\n}\n\nconst HF_BASE = \"https://huggingface.co/ggerganov/whisper.cpp/resolve/main\";\n\n// large-v3-turbo: strong accuracy, near-real-time on Apple Silicon with Metal.\n// small/base are lighter fallbacks for low-RAM machines.\nexport const WHISPER_MODELS = {\n \"large-v3-turbo\": { file: \"ggml-large-v3-turbo.bin\", url: `${HF_BASE}/ggml-large-v3-turbo.bin`, minBytes: 1_000_000_000 },\n small: { file: \"ggml-small.bin\", url: `${HF_BASE}/ggml-small.bin`, minBytes: 300_000_000 },\n base: { file: \"ggml-base.bin\", url: `${HF_BASE}/ggml-base.bin`, minBytes: 100_000_000 },\n} as const satisfies Record<string, WhisperModelSpec>;\n\nexport type WhisperModelName = keyof typeof WHISPER_MODELS;\nexport const DEFAULT_WHISPER_MODEL: WhisperModelName = \"large-v3-turbo\";\n\nexport function isWhisperModelName(value: unknown): value is WhisperModelName {\n // Own-property check — `in` would accept inherited keys like \"toString\",\n // which then crash the `WHISPER_MODELS[name]` lookups instead of falling\n // back to the default.\n return typeof value === \"string\" && Object.prototype.hasOwnProperty.call(WHISPER_MODELS, value);\n}\n\n/** Resolve a possibly-unset / unknown model name to a valid one. */\nexport function resolveModelName(name: string | undefined): WhisperModelName {\n return isWhisperModelName(name) ? name : DEFAULT_WHISPER_MODEL;\n}\n\nexport function modelFilePath(modelsDir: string, name: WhisperModelName): string {\n return path.join(modelsDir, WHISPER_MODELS[name].file);\n}\n\n/** A model is \"ready\" when its file exists and meets the size floor. */\nexport function isModelReady(modelsDir: string, name: WhisperModelName): boolean {\n try {\n return statSync(modelFilePath(modelsDir, name)).size >= WHISPER_MODELS[name].minBytes;\n } catch {\n return false;\n }\n}\n\nexport type ModelDownloadState = \"idle\" | \"downloading\" | \"ready\" | \"error\";\n\nexport interface ModelStatus {\n state: ModelDownloadState;\n /** 0..1 — present only while downloading and Content-Length is known. */\n progress?: number;\n /** Present only in the \"error\" state. */\n error?: string;\n}\n\n/** Report status precedence: an in-flight download wins, then an on-disk ready\n * file, then the last transient state (idle if none). Pure so the precedence\n * is unit-testable without touching the filesystem. */\nexport function pickModelStatus(live: ModelStatus | undefined, isReady: boolean): ModelStatus {\n if (live?.state === \"downloading\") return live;\n if (isReady) return { state: \"ready\" };\n return live ?? { state: \"idle\" };\n}\n\n/** Parse a `Content-Length` header to a byte count; unknown / malformed → 0. */\nexport function parseContentLength(header: string | null): number {\n return Number(header) || 0;\n}\n\n// Abort a download if no bytes arrive for this long (stalled connection).\nconst DOWNLOAD_STALL_TIMEOUT_MS = ONE_MINUTE_MS;\n\nexport interface ModelDownloader {\n getStatus: (name: WhisperModelName) => ModelStatus;\n ensure: (name: WhisperModelName) => Promise<void>;\n}\n\ninterface StreamToFileDeps {\n downloadStatus: Map<WhisperModelName, ModelStatus>;\n onProgress: () => void;\n}\n\n/** Drain the response stream into the `.partial` file, resetting the stall\n * timer on every chunk and publishing progress once the total size is known. */\nasync function streamToFile(\n body: ReadableStream<Uint8Array>,\n partialPath: string,\n total: number,\n name: WhisperModelName,\n deps: StreamToFileDeps,\n): Promise<void> {\n const reader = body.getReader();\n const fileStream = createWriteStream(partialPath);\n let received = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n deps.onProgress();\n received += value.byteLength;\n if (!fileStream.write(value)) await once(fileStream, \"drain\");\n if (total > 0) deps.downloadStatus.set(name, { state: \"downloading\", progress: received / total });\n }\n fileStream.end();\n await once(fileStream, \"finish\");\n } catch (err) {\n // `createWriteStream` opens lazily. Destroying it while that open is still\n // in flight lets the open's own failure land later as an `error` event with\n // no listener — an uncaughtException that kills the process. `err` already\n // carries the real cause, so absorb the late one.\n fileStream.on(\"error\", () => {});\n fileStream.destroy();\n throw err;\n }\n}\n\n/** Fetch a model into a `.partial` file, reject a truncated transfer via the\n * size floor, then atomically rename it into place. */\nasync function downloadModel(name: WhisperModelName, modelsDir: string, downloadStatus: Map<WhisperModelName, ModelStatus>): Promise<void> {\n const spec = WHISPER_MODELS[name];\n mkdirSync(modelsDir, { recursive: true });\n const dest = modelFilePath(modelsDir, name);\n const partial = `${dest}.partial`;\n const controller = new AbortController();\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n const resetStall = () => {\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => controller.abort(), DOWNLOAD_STALL_TIMEOUT_MS);\n };\n try {\n const response = await fetch(spec.url, { signal: controller.signal });\n if (!response.ok || !response.body) {\n throw new Error(`download failed: HTTP ${response.status}`);\n }\n const total = parseContentLength(response.headers.get(\"content-length\"));\n resetStall();\n await streamToFile(response.body, partial, total, name, { downloadStatus, onProgress: resetStall });\n if (statSync(partial).size < spec.minBytes) {\n unlinkSync(partial);\n throw new Error(\"downloaded file is smaller than expected — likely truncated\");\n }\n renameSync(partial, dest);\n } finally {\n if (stallTimer) clearTimeout(stallTimer);\n }\n}\n\nexport function createModelDownloader(modelsDir: string, logger: WhisperLogger = NOOP_LOGGER): ModelDownloader {\n // A finished file on disk is the source of truth for \"ready\"; this map tracks\n // transient progress + the last error.\n const downloadStatus = new Map<WhisperModelName, ModelStatus>();\n\n function getStatus(name: WhisperModelName): ModelStatus {\n return pickModelStatus(downloadStatus.get(name), isModelReady(modelsDir, name));\n }\n\n // Fire-and-forget friendly: errors land in the status map, never thrown.\n // Idempotent — a second call while a download is in flight does nothing.\n async function ensure(name: WhisperModelName): Promise<void> {\n if (isModelReady(modelsDir, name)) {\n downloadStatus.set(name, { state: \"ready\" });\n return;\n }\n if (downloadStatus.get(name)?.state === \"downloading\") return;\n downloadStatus.set(name, { state: \"downloading\", progress: 0 });\n logger.info(\"model download: start\", { model: name });\n try {\n await downloadModel(name, modelsDir, downloadStatus);\n downloadStatus.set(name, { state: \"ready\" });\n logger.info(\"model download: ok\", { model: name });\n } catch (err) {\n const error = errorMessage(err);\n downloadStatus.set(name, { state: \"error\", error });\n logger.error(\"model download: failed\", { model: name, error });\n }\n }\n\n return { getStatus, ensure };\n}\n","// Pure helpers for the whisper-server sidecar. Kept separate from `sidecar.ts`\n// so the argv/response/stderr logic can be unit-tested without spawning a\n// process or opening a socket.\n\nimport { hasStringProp } from \"@mulmoclaude/common\";\n\n/** whisper-server CLI args to preload `modelPath` and bind to `host:port`. */\nexport function buildServerArgs(modelPath: string, host: string, port: number): string[] {\n return [\"--model\", modelPath, \"--host\", host, \"--port\", String(port)];\n}\n\n/** Append `chunk` to a bounded stderr tail, keeping only the last `maxChars`. */\nexport function appendStderrTail(previous: string, chunk: string, maxChars: number): string {\n return (previous + chunk).slice(-maxChars);\n}\n\n/** Extract the transcript from a whisper-server `/inference` JSON response.\n * Returns \"\" for any shape that lacks a string `text` field. */\nexport function parseInferenceText(data: unknown): string {\n return hasStringProp(data, \"text\") ? data.text : \"\";\n}\n","// whisper.cpp warm-model sidecar. Spawns `whisper-server` once with the model\n// preloaded and reuses it across transcriptions over its local HTTP API, so the\n// weights stay resident (no per-request reload). State is encapsulated per\n// instance via the factory closure.\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { createServer } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, ONE_SECOND_MS, type WhisperLogger } from \"./internal.ts\";\nimport { modelFilePath, type WhisperModelName } from \"./models.ts\";\nimport { appendStderrTail, buildServerArgs, parseInferenceText } from \"./sidecar-helpers.ts\";\n\nconst HOST = \"127.0.0.1\";\nconst READY_TIMEOUT_MS = 60 * ONE_SECOND_MS;\nconst READY_POLL_INTERVAL_MS = 500;\nconst INFERENCE_TIMEOUT_MS = 2 * ONE_MINUTE_MS;\nconst STDERR_TAIL_MAX_CHARS = 4_000;\n\nexport interface ActiveSidecar {\n readonly port: number;\n readonly proc: ChildProcess;\n readonly model: WhisperModelName;\n}\n\nexport interface Sidecar {\n transcribeWav: (wavPath: string, language: string, model: WhisperModelName) => Promise<string>;\n warmup: (model: WhisperModelName) => Promise<void>;\n shutdown: () => void;\n}\n\nasync function findFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer();\n srv.on(\"error\", reject);\n srv.listen(0, HOST, () => {\n const addr = srv.address();\n if (addr && typeof addr === \"object\") {\n const { port } = addr;\n srv.close(() => resolve(port));\n } else {\n srv.close(() => reject(new Error(\"could not determine a free port\")));\n }\n });\n });\n}\n\n/** Resolve once the server answers any HTTP request (any status = listener up),\n * or throw after the ready timeout. */\nasync function waitUntilReady(port: number): Promise<void> {\n const deadline = Date.now() + READY_TIMEOUT_MS;\n while (Date.now() < deadline) {\n try {\n await fetch(`http://${HOST}:${port}/`, { signal: AbortSignal.timeout(ONE_SECOND_MS) });\n return;\n } catch {\n await delay(READY_POLL_INTERVAL_MS);\n }\n }\n throw new Error(\"whisper-server did not become ready in time\");\n}\n\n// whisper-server logs verbosely to stderr; left unread the OS pipe buffer fills\n// and the child blocks on its next write. Drain into a small tail buffer.\nfunction drainStderr(proc: ChildProcess, tail: { text: string }): void {\n proc.stderr?.setEncoding(\"utf8\");\n proc.stderr?.on(\"data\", (chunk: string) => {\n tail.text = appendStderrTail(tail.text, chunk, STDERR_TAIL_MAX_CHARS);\n });\n}\n\n// Resolve when the server answers, or reject on spawn failure (e.g. ENOENT) /\n// early exit. Listeners are one-shot and removed once the race settles.\nfunction waitForReadyOrFailure(proc: ChildProcess, port: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let onError: (err: Error) => void = () => undefined;\n let onExit: (code: number | null) => void = () => undefined;\n const cleanup = () => {\n proc.removeListener(\"error\", onError);\n proc.removeListener(\"exit\", onExit);\n };\n onError = (err: Error) => {\n cleanup();\n reject(new Error(`spawn failed: ${errorMessage(err)}`));\n };\n onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`exited early (code ${code})`));\n };\n proc.once(\"error\", onError);\n proc.once(\"exit\", onExit);\n waitUntilReady(port)\n .then(() => {\n cleanup();\n resolve();\n })\n .catch((err: unknown) => {\n cleanup();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n });\n}\n\n// POST the wav to whisper-server's `/inference` and return the transcript.\n// Isolated from the lifecycle so the HTTP contract is unit-testable without a\n// live child (stub `fetch`, hand it a real wav path).\nexport async function postInference(port: number, wavPath: string, language: string): Promise<string> {\n const buf = await readFile(wavPath);\n const form = new FormData();\n form.append(\"file\", new Blob([buf], { type: \"audio/wav\" }), \"audio.wav\");\n form.append(\"response_format\", \"json\");\n form.append(\"language\", language || \"auto\");\n let res: Response;\n try {\n res = await fetch(`http://${HOST}:${port}/inference`, { method: \"POST\", body: form, signal: AbortSignal.timeout(INFERENCE_TIMEOUT_MS) });\n } catch (err) {\n throw new Error(`whisper-server request failed: ${errorMessage(err)}`);\n }\n if (!res.ok) throw new Error(`whisper-server returned HTTP ${res.status}`);\n return parseInferenceText(await res.json());\n}\n\n// The impure primitives the start lifecycle depends on, injected so the\n// cancellation / single-flight / model-switch logic can be driven with fakes.\nexport interface StartLifecycleDeps {\n /** Reserve a free TCP port for the next child — the sole async step of a start. */\n allocatePort: () => Promise<number>;\n /** Spawn the whisper-server child on `port`. MUST be synchronous so the spawn\n * and the `startingProc` handoff stay in one tick: `shutdown()` has to be able\n * to kill an in-flight child immediately, with no await gap after it exists. */\n spawnServer: (model: WhisperModelName, port: number) => ChildProcess;\n /** Resolve once the child answers HTTP, or reject on spawn failure / early exit. */\n waitReady: (proc: ChildProcess, port: number) => Promise<void>;\n logger: WhisperLogger;\n}\n\nexport interface StartLifecycle {\n ensureSidecar: (model: WhisperModelName) => Promise<ActiveSidecar>;\n shutdown: () => void;\n}\n\nexport function defaultSpawnServer(modelsDir: string, serverBinary: string, logger: WhisperLogger): StartLifecycleDeps[\"spawnServer\"] {\n return (model: WhisperModelName, port: number): ChildProcess => {\n const args = buildServerArgs(modelFilePath(modelsDir, model), HOST, port);\n logger.info(\"sidecar: spawning\", { model, port });\n return spawn(serverBinary, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n };\n}\n\n// Wires the three listeners every whisper-server child needs: stderr drain,\n// permanent `error` handler (an unhandled 'error' from ENOENT etc. would crash\n// the host), and `exit` handler that both logs and lets the caller decide\n// whether this proc is still the active one (identity check via `onExit` — a\n// stale process must not evict a newer live sidecar).\nfunction instrumentChildProcess(proc: ChildProcess, model: WhisperModelName, logger: WhisperLogger, onExit: (exited: ChildProcess) => void): { text: string } {\n const stderrTail = { text: \"\" };\n drainStderr(proc, stderrTail);\n proc.on(\"error\", (err) => logger.warn(\"sidecar: process error\", { model, error: errorMessage(err) }));\n proc.on(\"exit\", (code) => {\n logger.warn(\"sidecar: exited\", { model, code, stderrTail: stderrTail.text.slice(-500) });\n onExit(proc);\n });\n return stderrTail;\n}\n\n// Await server readiness; on failure, kill the child and surface both the\n// underlying error and the tail of stderr (whisper-server usually explains its\n// crash there). Kept at module scope so `startSidecar` stays under the\n// per-function line cap.\nasync function awaitReadyOrThrow(proc: ChildProcess, port: number, stderrTail: { text: string }, waitReady: StartLifecycleDeps[\"waitReady\"]): Promise<void> {\n try {\n await waitReady(proc, port);\n } catch (err) {\n proc.kill();\n throw new Error(`whisper-server failed to start: ${errorMessage(err)} — stderr: ${stderrTail.text.slice(-500)}`);\n }\n}\n\n// Abort a start that was raced by `shutdown()` (or a newer start). Compares\n// the token captured at start entry against the current token; if they differ,\n// kill the freshly-booted child rather than publish it after shutdown returned.\nfunction throwIfStartCancelled(startedToken: number, currentToken: number, proc: ChildProcess): void {\n if (startedToken !== currentToken) {\n proc.kill();\n throw new Error(\"whisper-server start cancelled\");\n }\n}\n\n// Owns the single warm child's lifecycle: which model is live, the in-flight\n// start, and the cancellation token. Kept as a factory closure so the mutable\n// state is encapsulated rather than threaded through parameters.\nexport function createStartLifecycle(deps: StartLifecycleDeps): StartLifecycle {\n const { allocatePort, spawnServer, waitReady, logger } = deps;\n let sidecar: ActiveSidecar | null = null;\n let starting: { model: WhisperModelName; promise: Promise<ActiveSidecar> } | null = null;\n // The child of an in-flight start (before it's published as `sidecar`), plus a\n // token that `shutdown()` bumps to cancel a start that's still booting — so\n // shutdown can't return with a child that then publishes itself afterwards.\n let startingProc: ChildProcess | null = null;\n let startToken = 0;\n\n function shutdown(): void {\n startToken += 1;\n startingProc?.kill();\n startingProc = null;\n sidecar?.proc.kill();\n sidecar = null;\n }\n\n async function startSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n const token = ++startToken;\n const port = await allocatePort();\n const proc = spawnServer(model, port);\n startingProc = proc;\n // onExit fires when THIS proc exits: only null out `sidecar` if it's still the live one.\n const stderrTail = instrumentChildProcess(proc, model, logger, (exited) => sidecar?.proc === exited && (sidecar = null));\n try {\n await awaitReadyOrThrow(proc, port, stderrTail, waitReady);\n } finally {\n if (startingProc === proc) startingProc = null;\n }\n throwIfStartCancelled(token, startToken, proc);\n sidecar = { port, proc, model };\n logger.info(\"sidecar: ready\", { model, port });\n return sidecar;\n }\n\n // Own function so it isn't a loop closure (no-loop-func). Only ever one start\n // is in flight at a time, so clearing `starting` on settle is safe.\n function beginStart(model: WhisperModelName): Promise<ActiveSidecar> {\n const promise = startSidecar(model).finally(() => (starting = null));\n starting = { model, promise };\n return promise;\n }\n\n async function ensureSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n // Loop so that after awaiting an in-flight start for a DIFFERENT model we\n // re-evaluate; the decision-to-spawn path (beginStart) has no await, so the\n // first waiter sets `starting` synchronously and siblings then reuse it.\n for (;;) {\n if (sidecar && sidecar.model === model && !sidecar.proc.killed) return sidecar;\n if (starting && starting.model === model) return starting.promise;\n if (starting) {\n await starting.promise.catch(() => undefined);\n continue;\n }\n if (sidecar && sidecar.model !== model) shutdown();\n return beginStart(model);\n }\n }\n\n return { ensureSidecar, shutdown };\n}\n\nexport function createSidecar(modelsDir: string, serverBinary = \"whisper-server\", logger: WhisperLogger = NOOP_LOGGER): Sidecar {\n const lifecycle = createStartLifecycle({\n allocatePort: findFreePort,\n spawnServer: defaultSpawnServer(modelsDir, serverBinary, logger),\n waitReady: waitForReadyOrFailure,\n logger,\n });\n\n async function warmup(model: WhisperModelName): Promise<void> {\n try {\n await lifecycle.ensureSidecar(model);\n } catch (err) {\n logger.warn(\"sidecar: warmup failed\", { model, error: errorMessage(err) });\n }\n }\n\n async function transcribeWav(wavPath: string, language: string, model: WhisperModelName): Promise<string> {\n const active = await lifecycle.ensureSidecar(model);\n return postInference(active.port, wavPath, language);\n }\n\n return { transcribeWav, warmup, shutdown: lifecycle.shutdown };\n}\n","// Public server-side façade: wires the model downloader, the warm sidecar, and\n// ffmpeg conversion into one host-agnostic service. The host injects the models\n// directory + a logger and gates capability itself (platform / binary presence);\n// this package assumes the binaries exist when called.\n\nimport { mkdirSync } from \"node:fs\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { NOOP_LOGGER, type WhisperLogger } from \"./internal.ts\";\nimport { convertToWav16k } from \"./ffmpeg.ts\";\nimport { createModelDownloader } from \"./models.ts\";\nimport { createSidecar } from \"./sidecar.ts\";\nimport { isModelReady, type ModelStatus, type WhisperModelName } from \"./models.ts\";\n\nexport interface WhisperOptions {\n /** Directory that holds the GGML model files (e.g. `{workspace}/models`). */\n modelsDir: string;\n logger?: WhisperLogger;\n /** Defaults to \"whisper-server\" / \"ffmpeg\" on PATH. */\n serverBinary?: string;\n ffmpegBinary?: string;\n}\n\nexport interface TranscribeRequest {\n base64: string;\n mimeType: string;\n language: string;\n model: WhisperModelName;\n}\n\nexport interface Whisper {\n isModelReady: (model: WhisperModelName) => boolean;\n getModelStatus: (model: WhisperModelName) => ModelStatus;\n /** Fire-and-forget friendly; never throws (errors land in the status). */\n ensureModelDownloaded: (model: WhisperModelName) => Promise<void>;\n warmup: (model: WhisperModelName) => Promise<void>;\n transcribe: (req: TranscribeRequest) => Promise<{ text: string }>;\n shutdown: () => void;\n}\n\n// whisper.cpp returns these sentinels for non-speech windows; treat them as\n// empty so the UI shows \"didn't catch that\" rather than a literal marker.\nconst BLANK_MARKERS = new Set([\"[blank_audio]\", \"[silence]\", \"(silence)\", \"[ inaudible ]\"]);\n\nfunction normalizeTranscript(raw: string): string {\n const trimmed = raw.trim().replace(/\\s+/g, \" \");\n return BLANK_MARKERS.has(trimmed.toLowerCase()) ? \"\" : trimmed;\n}\n\nexport function createWhisper(opts: WhisperOptions): Whisper {\n const { modelsDir } = opts;\n const logger = opts.logger ?? NOOP_LOGGER;\n const ffmpegBinary = opts.ffmpegBinary ?? \"ffmpeg\";\n const downloader = createModelDownloader(modelsDir, logger);\n const sidecar = createSidecar(modelsDir, opts.serverBinary ?? \"whisper-server\", logger);\n\n // Scratch dir for transient audio — a hidden subdir of the models dir so it\n // shares the (non-git) models tree. Files are deleted after each transcription.\n const scratchDir = path.join(modelsDir, \".scratch\");\n\n async function transcribe(req: TranscribeRequest): Promise<{ text: string }> {\n mkdirSync(scratchDir, { recursive: true });\n const clipId = randomUUID();\n const inputPath = path.join(scratchDir, `utterance-${clipId}.webm`);\n const wavPath = path.join(scratchDir, `utterance-${clipId}.wav`);\n try {\n await writeFile(inputPath, Buffer.from(req.base64, \"base64\"));\n await convertToWav16k(inputPath, wavPath, ffmpegBinary);\n const text = await sidecar.transcribeWav(wavPath, req.language, req.model);\n return { text: normalizeTranscript(text) };\n } finally {\n await rm(inputPath, { force: true });\n await rm(wavPath, { force: true });\n }\n }\n\n return {\n isModelReady: (model) => isModelReady(modelsDir, model),\n getModelStatus: (model) => downloader.getStatus(model),\n ensureModelDownloaded: (model) => downloader.ensure(model),\n warmup: (model) => sidecar.warmup(model),\n transcribe,\n shutdown: () => sidecar.shutdown(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAEA,IAAa,gBAAgB;AAC7B,IAAa,gBAAgB;AAY7B,IAAM,aAAmB,KAAA;AACzB,IAAa,cAA6B;CA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AA,CAAU,WAAW,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC;GAC5D,MAAM,gBAAgB,WAAW,SAAS,YAAY;GAEtD,OAAO,EAAE,MAAM,oBAAoB,MADhB,QAAQ,cAAc,SAAS,IAAI,UAAU,IAAI,KAAK,CAClC,EAAE;EAC3C,UAAU;GACR,OAAA,GAAM,iBAAA,GAAA,CAAG,WAAW,EAAE,OAAO,KAAK,CAAC;GACnC,OAAA,GAAM,iBAAA,GAAA,CAAG,SAAS,EAAE,OAAO,KAAK,CAAC;EACnC;CACF;CAEA,OAAO;EACL,eAAe,UAAU,aAAa,WAAW,KAAK;EACtD,iBAAiB,UAAU,WAAW,UAAU,KAAK;EACrD,wBAAwB,UAAU,WAAW,OAAO,KAAK;EACzD,SAAS,UAAU,QAAQ,OAAO,KAAK;EACvC;EACA,gBAAgB,QAAQ,SAAS;CACnC;AACF"}
|
package/dist/wiki/index.cjs
CHANGED
|
@@ -94,7 +94,8 @@ function renderWikiLinks(content) {
|
|
|
94
94
|
if (content[i] === "[" && content[i + 1] === "[") {
|
|
95
95
|
const closeStart = findNextCloseBrackets(content, i + 2);
|
|
96
96
|
if (closeStart !== -1) {
|
|
97
|
-
const
|
|
97
|
+
const inner = content.slice(i + 2, closeStart);
|
|
98
|
+
const { target, display } = require_graph.parseWikiLink(inner);
|
|
98
99
|
out.push(`<span class="wiki-link" data-page="${require_dist.escapeHtml(target)}">${require_dist.escapeHtml(display)}</span>`);
|
|
99
100
|
i = closeStart + 2;
|
|
100
101
|
continue;
|