mcp-speechmatics-transcribe 0.1.21 → 0.1.23

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/.env.example CHANGED
@@ -13,12 +13,6 @@ SPEECHMATICS_DIARIZATION=speaker
13
13
  SPEECHMATICS_AUDIO_EVENTS=true
14
14
  # Upload and processing timeout, independent of recording duration.
15
15
  SPEECHMATICS_TIMEOUT_SECONDS=900
16
- # Shared MCP discovery cache lifetime in milliseconds; 0 disables caching.
17
- SPEECHMATICS_DISCOVERY_CACHE_TTL_MS=600000
18
- # Additional comma-separated environment names omitted from the cache key.
19
- # CODEX_TOOL_CALL_ID is always omitted from the key and still passed to the CLI.
20
- SPEECHMATICS_DISCOVERY_CACHE_KEY_EXCLUDE=
21
-
22
16
  # Silence removal is enabled by default; lower dB thresholds protect quiet speech.
23
17
  SPEECHMATICS_REMOVE_SILENCE=true
24
18
  SPEECHMATICS_SILENCE_THRESHOLD_DB=-40
package/README.md CHANGED
@@ -40,12 +40,16 @@ Logins are optional. Keep credentials outside the repository.
40
40
  }
41
41
  ```
42
42
 
43
+ > [!TIP]
44
+ > Optional [MCP Lazy Proxy](https://github.com/kucharskill/mcpLazyProxy) helps manage duplicated and orphaned stdio processes. When it starts a backend through `npx -y --prefer-online mcp-speechmatics-transcribe@latest`, each new backend start checks the current package version, including after an idle shutdown.
45
+
43
46
  On Windows, clients that require an executable path can use npx.cmd.
44
47
  For a local env file, append --env-file and its absolute path.
45
48
  With no file argument, the command starts the MCP server; the explicit mcp subcommand
46
- also works. New npx launches resolve the current published package. An already
47
- running MCP wrapper keeps its loaded code until restarted. For npx-managed
48
- installations, individual tool calls resolve the latest CLI through npx.
49
+ also works. CLI and MCP share tool definitions from the same installed package.
50
+ A running instance keeps that version until restarted. Discovery and token status
51
+ run in the MCP process; transcription uses a worker from the same installation so
52
+ cancellation can stop its media-processing children.
49
53
  Allow enough tool time for uploads and processing; the API timeout defaults to
50
54
  900 seconds.
51
55
 
@@ -101,12 +105,15 @@ audio extraction first tries stream copying where possible. Edited audio is enco
101
105
  to MP3. Prepared files stay in the output folder. Missing audio and conversion
102
106
  failures are reported before upload. System FFmpeg and FFprobe are not required.
103
107
  The shared mcp-ffmpeg-runtime library manages FFmpeg downloads and its binary
104
- cache. Both dependencies use the latest npm tag and are refreshed when preparing
108
+ cache. The runtime dependency requires ^0.1.4, and the screenshot library uses the latest
109
+ npm tag. Both are refreshed within their declared ranges when preparing
105
110
  a new release; the resolved versions are retained for reproducible release retries.
106
111
  The runtime checks and updates its FFmpeg build at media use and reuses the cached
107
- binary. FFMPEG_CACHE_DIR, FFMPEG_CHANNEL, FFMPEG_OFFLINE, and FFMPEG_PREFER_LOCAL
112
+ binary. FFMPEG_CACHE_DIR, FFMPEG_CHANNEL, FFMPEG_OFFLINE, and FFMPEG_PREFERRED_RUNTIME
108
113
  configure that runtime. The default uses its managed binary; offline and local
109
- preferences can opt out of downloading the current build. FFmpeg has its own licenses.
114
+ preferences can opt out of downloading the current build. The default omits a
115
+ runtime preference and uses latest. FFMPEG_PREFERRED_RUNTIME accepts latest, cached,
116
+ local, an npm semver range, or a build ID. FFmpeg has its own licenses.
110
117
 
111
118
  ## Configuration
112
119
 
package/mcp.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import { Server, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
2
2
  import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
3
- import { runCli, resolveCliLaunch, dumpStartupEnvironment } from "./modules/cli-process.js";
4
- import { createDiscoveryCache } from "./modules/discovery-cache.js";
3
+ import { dumpStartupEnvironment } from "./modules/startup-diagnostics.js";
4
+ import { executeTool, getToolManifest } from "./modules/tools.js";
5
+ import { runTranscription } from "./modules/transcription-worker.js";
5
6
 
6
7
  dumpStartupEnvironment();
7
- const launch = resolveCliLaunch();
8
- const discovery = createDiscoveryCache(launch, () => runCli("--tool-manifest", undefined, { launch }));
9
8
  let era;
10
- let invalidation = Promise.resolve();
9
+ const lifetime = new AbortController();
11
10
  class LocalTransport extends StdioServerTransport {
12
11
  async start() {
13
12
  const dispatch = this.onmessage;
@@ -19,7 +18,6 @@ class LocalTransport extends StdioServerTransport {
19
18
  return;
20
19
  }
21
20
  if (message.method === "notifications/tools/list_changed" && message.id === undefined) {
22
- invalidation = discovery.invalidate();
23
21
  return;
24
22
  }
25
23
  dispatch?.(message, extra);
@@ -30,19 +28,16 @@ class LocalTransport extends StdioServerTransport {
30
28
 
31
29
  async function createServer(context) {
32
30
  era = context.era;
33
- await invalidation;
34
- let manifest = await discovery.get();
31
+ let manifest = await getToolManifest();
35
32
  const server = new Server(manifest.serverInfo, {
36
33
  instructions: manifest.serverInfo.description,
37
34
  capabilities: { tools: { listChanged: true } },
38
35
  });
39
36
  server.setRequestHandler("tools/list", async () => {
40
- await invalidation;
41
- const latest = await discovery.get();
37
+ const latest = await getToolManifest();
42
38
  const changed = JSON.stringify(latest.tools) !== JSON.stringify(manifest.tools);
43
39
  manifest = latest;
44
40
  if (changed) {
45
- await discovery.invalidate();
46
41
  await server.sendToolListChanged();
47
42
  }
48
43
  const { protocol, serverInfo, ...result } = manifest;
@@ -50,9 +45,11 @@ async function createServer(context) {
50
45
  });
51
46
  server.setRequestHandler("tools/call", async ({ params }, context) => {
52
47
  try {
53
- return await runCli("--execute-tool", {
54
- protocol: 1, name: params.name, arguments: params.arguments ?? {},
55
- }, { signal: context?.mcpReq.signal });
48
+ const requestSignal = context?.mcpReq.signal;
49
+ const signal = requestSignal ? AbortSignal.any([requestSignal, lifetime.signal]) : lifetime.signal;
50
+ return params.name === "transcribe"
51
+ ? await runTranscription(params.arguments ?? {}, { signal })
52
+ : await executeTool(params.name, params.arguments ?? {}, { signal });
56
53
  } catch (error) {
57
54
  return { isError: true, content: [{ type: "text", text: JSON.stringify({ message: error.message }) }] };
58
55
  }
@@ -60,4 +57,11 @@ async function createServer(context) {
60
57
  return server;
61
58
  }
62
59
 
63
- serveStdio(createServer, { transport: new LocalTransport() });
60
+ const handle = serveStdio(createServer, { transport: new LocalTransport() });
61
+ process.stdin.once("end", () => lifetime.abort());
62
+ const stop = () => {
63
+ lifetime.abort();
64
+ handle.close().catch(() => {}).finally(() => process.stdin.pause());
65
+ };
66
+ process.once("SIGINT", stop);
67
+ process.once("SIGTERM", stop);
@@ -0,0 +1,13 @@
1
+ import { mkdirSync, appendFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ export function dumpStartupEnvironment(directory = join(tmpdir(), "transcription", "discovery")) {
6
+ const file = join(directory, "env-startup.jsonl");
7
+ try {
8
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
9
+ appendFileSync(file, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), env: process.env }) + "\n", { mode: 0o600 });
10
+ return file;
11
+ } catch { /* A diagnostic snapshot must not prevent MCP startup. */ }
12
+ }
13
+
@@ -4,7 +4,8 @@ import { readLog } from "./history.js";
4
4
  import { ApiError } from "./speechmatics.js";
5
5
  import { refreshUsage, lifetimeSince } from "./usage.js";
6
6
 
7
- export async function tokenStatus({ since, until } = {}) {
7
+ export async function tokenStatus({ since, until } = {}, { signal } = {}) {
8
+ signal?.throwIfAborted();
8
9
  const today = new Date().toISOString().slice(0, 10);
9
10
  since ??= lifetimeSince;
10
11
  until ??= today;
@@ -15,6 +16,7 @@ export async function tokenStatus({ since, until } = {}) {
15
16
  .map((entry) => entry.tokenSha256));
16
17
  const results = [];
17
18
  for (const { login, token } of tokens) {
19
+ signal?.throwIfAborted();
18
20
  const identity = login ? { login } : {
19
21
  token: token.length > 12 ? token.slice(0, 4) + "****" + token.slice(-4) : "****",
20
22
  };
@@ -24,9 +26,10 @@ export async function tokenStatus({ since, until } = {}) {
24
26
  continue;
25
27
  }
26
28
  try {
27
- const { since: start, until: end, summary, details } = await refreshUsage({ token, login }, since, until);
29
+ const { since: start, until: end, summary, details } = await refreshUsage({ token, login }, since, until, signal);
28
30
  results.push({ ...identity, status: "active", usage: { since: start, until: end, summary, details } });
29
31
  } catch (error) {
32
+ signal?.throwIfAborted();
30
33
  results.push({
31
34
  ...identity, status: "error",
32
35
  error: {
package/modules/tools.js CHANGED
@@ -54,9 +54,9 @@ export function createTools(configuredDefaults) {
54
54
  }),
55
55
  annotations: { readOnlyHint: false },
56
56
  },
57
- execute: async (options) => {
57
+ execute: async (options, { signal } = {}) => {
58
58
  try {
59
- const result = await tokenStatus(options);
59
+ const result = await tokenStatus(options, { signal });
60
60
  return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
61
61
  } catch (error) {
62
62
  return { isError: true, content: [{ type: "text", text: JSON.stringify({ message: error.message }) }] };
@@ -66,12 +66,12 @@ export function createTools(configuredDefaults) {
66
66
  };
67
67
  }
68
68
 
69
- export async function executeTool(name, args) {
69
+ export async function executeTool(name, args, context = {}) {
70
70
  const { options } = await loadConfig({}, { requireTokens: false });
71
71
  const tools = createTools(options);
72
72
  if (!Object.hasOwn(tools, name)) throw new Error("Unknown tool: " + name);
73
73
  const tool = tools[name];
74
- return tool.execute(tool.definition.inputSchema.parse(args));
74
+ return tool.execute(tool.definition.inputSchema.parse(args), context);
75
75
  }
76
76
 
77
77
  export async function getToolManifest() {
@@ -0,0 +1,54 @@
1
+ import { spawn, execFile } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+
4
+ // Isolate media processing so cancellation can stop the whole FFmpeg process tree.
5
+ export function runTranscription(args, { signal } = {}) {
6
+ signal?.throwIfAborted();
7
+ return new Promise((resolve, reject) => {
8
+ const child = spawn(process.execPath, [fileURLToPath(new URL("../cli.js", import.meta.url)), "--execute-tool"], {
9
+ shell: false, windowsHide: true, detached: process.platform !== "win32",
10
+ stdio: ["pipe", "pipe", "inherit"], env: { ...process.env }, cwd: process.cwd(),
11
+ });
12
+ let output = "", failure, closed = false, stopping = false, escalation;
13
+ const stop = (error) => {
14
+ failure ??= error;
15
+ if (closed || stopping) return;
16
+ stopping = true;
17
+ if (process.platform === "win32" && child.pid) {
18
+ execFile("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true }, () => {
19
+ if (!closed) child.kill();
20
+ });
21
+ } else if (child.pid) {
22
+ try { process.kill(-child.pid, "SIGTERM"); } catch { child.kill(); }
23
+ escalation = setTimeout(() => { try { process.kill(-child.pid, "SIGKILL"); } catch {} }, 500);
24
+ escalation.unref();
25
+ } else child.kill();
26
+ };
27
+ const abort = () => stop(signal.reason ?? new DOMException("Transcription was cancelled.", "AbortError"));
28
+ signal?.addEventListener("abort", abort, { once: true });
29
+ if (signal?.aborted) abort();
30
+ child.stdout.setEncoding("utf8");
31
+ child.stdout.on("data", (chunk) => {
32
+ output += chunk;
33
+ if (output.length > 1024 * 1024) stop(new Error("Transcription worker response exceeded 1 MiB."));
34
+ });
35
+ child.on("error", error => { failure ??= error; });
36
+ child.stdin.on("error", error => stop(error));
37
+ child.once("close", (code, exitSignal) => {
38
+ closed = true;
39
+ clearTimeout(escalation);
40
+ if (stopping && process.platform !== "win32" && child.pid) {
41
+ try { process.kill(-child.pid, "SIGKILL"); } catch {}
42
+ }
43
+ signal?.removeEventListener("abort", abort);
44
+ if (failure) { reject(failure); return; }
45
+ if (code !== 0) { reject(new Error(`CLI process exited with ${exitSignal ?? code}.`)); return; }
46
+ try {
47
+ const result = JSON.parse(output);
48
+ if (!Array.isArray(result?.content)) throw new Error("Missing tool content.");
49
+ resolve(result);
50
+ } catch { reject(new Error("Transcription worker returned an invalid response.")); }
51
+ });
52
+ child.stdin.end(JSON.stringify({ protocol: 1, name: "transcribe", arguments: args }));
53
+ });
54
+ }
package/modules/usage.js CHANGED
@@ -8,9 +8,10 @@ export function roundedUsage(usage) {
8
8
  return { ...usage, summary: usage.summary.map((row) => ({ ...row, duration_hrs: roundHours(row.duration_hrs) })), details: (usage.details ?? []).map((row) => ({ ...row, duration_hrs: roundHours(row.duration_hrs) })) };
9
9
  }
10
10
 
11
- export async function refreshUsage({ token, login }, since = lifetimeSince, until = new Date().toISOString().slice(0, 10)) {
11
+ export async function refreshUsage({ token, login }, since = lifetimeSince, until = new Date().toISOString().slice(0, 10), signal) {
12
12
  const requestedAt = new Date().toISOString();
13
- const result = await getUsage(token, since, until, AbortSignal.timeout(15000));
13
+ const timeout = AbortSignal.timeout(15000);
14
+ const result = await getUsage(token, since, until, signal ? AbortSignal.any([signal, timeout]) : timeout);
14
15
  if (result.since?.slice(0, 10) !== since || result.until?.slice(0, 10) !== until) throw new Error("Usage response does not cover the requested dates.");
15
16
  if (!Array.isArray(result.summary) || !result.summary.every((row) => Number.isFinite(row.duration_hrs) && row.duration_hrs >= 0 && Number.isInteger(row.count) && row.count >= 0)) throw new Error("Invalid usage statistics.");
16
17
  const durationSeconds = result.summary.reduce((total, row) => total + row.duration_hrs * 3600, 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-speechmatics-transcribe",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "Transcribe audio and video files with Speechmatics through a CLI and MCP server.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -50,7 +50,7 @@
50
50
  "commander": "^15.1.0",
51
51
  "dotenv": "^18.0.10",
52
52
  "mcp-extract-video-frames": "latest",
53
- "mcp-ffmpeg-runtime": "latest",
53
+ "mcp-ffmpeg-runtime": "^0.1.4",
54
54
  "proper-lockfile": "^4.1.2",
55
55
  "zod": "^4.6.7"
56
56
  },
@@ -1,83 +0,0 @@
1
- import { spawn, execFile } from "node:child_process";
2
- import { resolve, join } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { mkdirSync, appendFileSync } from "node:fs";
5
- import { tmpdir } from "node:os";
6
-
7
- export function dumpStartupEnvironment(directory = join(tmpdir(), "transcription", "discovery")) {
8
- const file = join(directory, "env-startup.jsonl");
9
- try {
10
- mkdirSync(directory, { recursive: true, mode: 0o700 });
11
- appendFileSync(file, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), env: process.env }) + "\n", { mode: 0o600 });
12
- return file;
13
- } catch { /* A diagnostic snapshot must not prevent MCP startup. */ }
14
- }
15
-
16
- // Keep arguments and credentials on stdin/environment, outside the shell command.
17
- export function resolveCliLaunch() {
18
- const modulePath = fileURLToPath(import.meta.url);
19
- const cachedPackage = /[\\/]_npx[\\/][^\\/]+[\\/]node_modules[\\/]mcp-speechmatics-transcribe[\\/]/i.test(modulePath);
20
- const npmExec = process.env.npm_command === "exec"
21
- || (!process.env.npm_command && process.env.npm_lifecycle_event === "npx");
22
- const useNpx = cachedPackage && npmExec;
23
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^npm_config_(package|call)$/i.test(key)));
24
- env.SPEECHMATICS_ENV_FILE = process.env.SPEECHMATICS_ENV_FILE
25
- ? resolve(process.env.SPEECHMATICS_ENV_FILE) : fileURLToPath(new URL("../.env", import.meta.url));
26
- return {
27
- command: useNpx ? "npx" : process.execPath,
28
- args: useNpx ? ["-y", "--prefer-online", "--package=mcp-speechmatics-transcribe@latest", "--", "mcp-speechmatics-transcribe"]
29
- : [fileURLToPath(new URL("../cli.js", import.meta.url))],
30
- cwd: process.cwd(), env, shell: useNpx && process.platform === "win32",
31
- };
32
- }
33
-
34
- export function runCli(mode, request, { launch = resolveCliLaunch(), signal } = {}) {
35
- return new Promise((done, reject) => {
36
- if (!["--tool-manifest", "--execute-tool"].includes(mode)) throw new Error("Unsupported CLI mode.");
37
- signal?.throwIfAborted();
38
- const launchArgs = [...launch.args, mode];
39
- const child = spawn(launch.shell ? launch.command + " " + launchArgs.join(" ") : launch.command, launch.shell ? [] : launchArgs, {
40
- shell: launch.shell, cwd: launch.cwd, windowsHide: true,
41
- stdio: ["pipe", "pipe", "inherit"], env: launch.env,
42
- });
43
- const abort = () => {
44
- if (launch.shell && process.platform === "win32" && child.pid) {
45
- execFile("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true }, () => {});
46
- } else child.kill();
47
- reject(new DOMException("CLI operation was cancelled.", "AbortError"));
48
- };
49
- signal?.addEventListener("abort", abort, { once: true });
50
- if (signal?.aborted) abort();
51
- let output = "";
52
- child.stdout.setEncoding("utf8");
53
- child.stdout.on("data", (chunk) => {
54
- output += chunk;
55
- if (output.length > 1024 * 1024) {
56
- child.kill();
57
- reject(new Error("CLI process response exceeded 1 MiB."));
58
- }
59
- });
60
- child.on("error", reject);
61
- child.stdin.on("error", reject);
62
- child.once("close", () => signal?.removeEventListener("abort", abort));
63
- child.on("close", (code, signal) => {
64
- if (code !== 0) {
65
- reject(new Error(`CLI process exited with ${signal ?? code}.`));
66
- return;
67
- }
68
- try {
69
- const result = JSON.parse(output);
70
- if (mode === "--tool-manifest") {
71
- if (result.protocol !== 1 || !Array.isArray(result.tools) || !result.serverInfo) throw new Error("Invalid tool manifest.");
72
- } else if (!Array.isArray(result?.content)) {
73
- throw new Error("Missing tool content.");
74
- }
75
- done(result);
76
- } catch {
77
- reject(new Error("CLI process returned an invalid response. Check npm connectivity and the published package version."));
78
- }
79
- });
80
- child.stdin.end(request ? JSON.stringify(request) : undefined);
81
- });
82
- }
83
-
@@ -1,86 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { z } from "zod";
6
-
7
- const object = z.record(z.string(), z.json());
8
- const manifestSchema = z.object({
9
- protocol: z.literal(1),
10
- serverInfo: z.object({ name: z.string().min(1), version: z.string().min(1), title: z.string().optional(), description: z.string().optional() }).passthrough(),
11
- tools: z.array(z.object({
12
- name: z.string().min(1), title: z.string().optional(), description: z.string().optional(),
13
- inputSchema: object.refine((value) => value.type === "object"),
14
- outputSchema: object.optional(),
15
- annotations: z.object({ title: z.string().optional(), readOnlyHint: z.boolean().optional(), destructiveHint: z.boolean().optional(), idempotentHint: z.boolean().optional(), openWorldHint: z.boolean().optional() }).passthrough().optional(),
16
- }).passthrough()).refine((tools) => new Set(tools.map((tool) => tool.name)).size === tools.length),
17
- }).passthrough();
18
-
19
- function validateManifest(value) {
20
- z.json().parse(value);
21
- manifestSchema.parse(value);
22
- return value;
23
- }
24
-
25
- // Request/session-bound discovery is returned intact but cannot be replayed.
26
- function hasRequestState(value) {
27
- if (!value || typeof value !== "object") return false;
28
- return Object.entries(value).some(([name, child]) =>
29
- /(?:^|\/)(?:sessionId|session_id|progressToken|requestId|requestState|inputRequests|relatedTask|related-task)$/i.test(name)
30
- || (name === "cacheScope" && child === "session")
31
- || hasRequestState(child));
32
- }
33
-
34
- export function discoveryKey(launch, platform = process.platform) {
35
- const normalize = (key) => platform === "win32" ? key.toUpperCase() : key;
36
- const excluded = new Set(["CODEX_TOOL_CALL_ID", ...(launch.env.SPEECHMATICS_DISCOVERY_CACHE_KEY_EXCLUDE ?? "").split(",").map((key) => key.trim()).filter(Boolean)].map(normalize));
37
- const env = Object.entries(launch.env).map(([key, value]) => [normalize(key), value])
38
- .filter(([key]) => !excluded.has(key) && !/^(?:CODEX_TOOL_CALL_ID$|PATH$|INIT_|NPM_)/i.test(key)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
39
- return createHash("sha256").update(JSON.stringify({ version: 1, command: launch.command, args: launch.args, cwd: launch.cwd, shell: launch.shell, env })).digest("hex");
40
- }
41
-
42
- export function createDiscoveryCache(launch, load, { directory = join(tmpdir(), "transcription", "discovery"), now = Date.now } = {}) {
43
- const raw = launch.env.SPEECHMATICS_DISCOVERY_CACHE_TTL_MS ?? "600000";
44
- if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error("SPEECHMATICS_DISCOVERY_CACHE_TTL_MS must be a nonnegative integer.");
45
- const ttl = Number(raw), key = discoveryKey(launch), file = join(directory, key + ".json");
46
- let pending, generation = 0;
47
- const invalidate = async () => { generation++; await rm(file, { force: true }).catch(() => {}); };
48
- return {
49
- file, invalidate,
50
- async get() {
51
- if (ttl) {
52
- try {
53
- const bytes = await readFile(file);
54
- if (bytes.length > 1024 * 1024) throw new Error("Oversized cache.");
55
- const entry = JSON.parse(bytes);
56
- if (entry.version !== 1 || entry.key !== key || !Number.isFinite(entry.createdAt) || !Number.isFinite(entry.expiresAt)
57
- || entry.createdAt > now() || entry.expiresAt <= now() || entry.expiresAt - entry.createdAt > ttl) throw new Error("Expired cache.");
58
- if (hasRequestState(entry.manifest)) throw new Error("Request-bound discovery.");
59
- return validateManifest(entry.manifest);
60
- } catch { /* Invalid or unavailable cache entries are misses. */ }
61
- }
62
- if (pending) return pending;
63
- const revision = generation;
64
- pending = (async () => {
65
- const manifest = validateManifest(await load());
66
- const serialized = JSON.stringify(manifest);
67
- const privateValues = Object.entries(launch.env).filter(([name]) => /token|secret|password|session|CODEX_TOOL_CALL_ID/i.test(name))
68
- .flatMap(([name, value]) => /SPEECHMATICS_TOKENS/i.test(name)
69
- ? [value, ...value.split(",").flatMap((entry) => entry.includes(":") ? [entry.slice(entry.indexOf(":") + 1)] : [entry])]
70
- : [value]).filter((value) => value.length >= 8);
71
- if (ttl && revision === generation && !hasRequestState(manifest) && !privateValues.some((value) => serialized.includes(value))) {
72
- const temporary = file + "." + randomUUID() + ".tmp";
73
- try {
74
- await mkdir(directory, { recursive: true, mode: 0o700 });
75
- const createdAt = now();
76
- await writeFile(temporary, JSON.stringify({ version: 1, key, createdAt, expiresAt: createdAt + ttl, manifest }), { mode: 0o600 });
77
- if (revision === generation) await rename(temporary, file);
78
- } catch { /* Discovery remains available when the cache is unwritable. */ }
79
- finally { await rm(temporary, { force: true }).catch(() => {}); }
80
- }
81
- return manifest;
82
- })();
83
- try { return await pending; } finally { pending = undefined; }
84
- },
85
- };
86
- }