transcribe-so 0.1.0 → 0.2.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/commands/core.ts","../src/config.ts","../src/api.ts","../src/commands/artifacts.ts","../src/commands/upload.ts"],"sourcesContent":["import yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport type { Argv } from 'yargs';\nimport { CLI_VERSION } from './version';\nimport {\n authStatus,\n me,\n pipelines,\n quote,\n create,\n wait,\n result,\n run,\n list,\n get,\n deleteTranscription,\n retry,\n} from './commands/core';\nimport { subtitles, ask } from './commands/artifacts';\nimport { upload } from './commands/upload';\n\nconst INCLUDE_DESCRIBE =\n 'Comma-separated result sections: chapters, acts, sections, qna, segments, posting_chapters, or all. Default chapters,sections,qna';\n\nfunction sourceOptions(y: Argv): Argv {\n return y\n .option('source', {\n describe: 'Input source',\n type: 'string',\n choices: ['youtube', 'external_url', 'platform_url', 'upload'],\n demandOption: true,\n })\n .option('url', {\n describe: 'Media URL (required for youtube / platform_url / external_url)',\n type: 'string',\n })\n .option('upload-id', {\n describe: 'upload_id from `transcribe-so upload` (required for source=upload)',\n type: 'string',\n })\n .option('duration', {\n describe: 'Media duration in seconds (required for upload; speeds up URL sources)',\n type: 'number',\n })\n .option('language', {\n describe: 'BCP-47 language code (en, ja, ko, ...) or auto (default)',\n type: 'string',\n })\n .option('callback-url', {\n describe: 'Public https URL that receives this job\\'s signed completed/failed webhook',\n type: 'string',\n })\n .option('idempotency-key', {\n describe: 'Override the auto-generated Idempotency-Key (max 128 chars)',\n type: 'string',\n })\n .check((argv: any) => {\n if (argv.source === 'upload') {\n if (!argv.uploadId) throw new Error('source=upload requires --upload-id');\n if (argv.duration === undefined)\n throw new Error('source=upload requires --duration <seconds>');\n } else if (!argv.url) {\n throw new Error(`source=${argv.source} requires --url`);\n }\n if (\n argv.duration !== undefined &&\n (!Number.isFinite(argv.duration) || argv.duration <= 0)\n ) {\n throw new Error('--duration must be a positive number of seconds');\n }\n return true;\n });\n}\n\nconst parser = yargs(hideBin(process.argv))\n .scriptName('transcribe-so')\n .usage('$0 <command> [options]\\n\\nPure-JSON stdout (subtitles excepted); progress goes to stderr.')\n .option('allow-custom-host', {\n describe:\n 'Allow sending the API key to a non-default TRANSCRIBE_API_URL host (refused otherwise)',\n type: 'boolean',\n default: false,\n global: true,\n })\n .command(\n 'auth:status',\n 'Check whether TRANSCRIBE_API_KEY authenticates against the API',\n {},\n authStatus as any\n )\n .command(\n 'me',\n 'Account, wallet balance, plan limits, API-key scopes and spend',\n (y: Argv) => y.example('$0 me | jq .wallet_balance_usd', 'Check the wallet balance'),\n me as any\n )\n .command(\n 'pipelines',\n 'Capability catalog: pricing per minute and supported languages',\n (y: Argv) =>\n y.example('$0 pipelines | jq \\'.pipelines[0].retail_usd_per_min\\'', 'Current per-minute rate'),\n pipelines as any\n )\n .command(\n 'quote',\n 'Preview the exact cost of a transcription (free, does not queue the job)',\n (y: Argv) =>\n sourceOptions(y)\n .example(\n '$0 quote --source youtube --url \"https://www.youtube.com/watch?v=jNQXAC9IVRw\"',\n 'Price a YouTube video'\n )\n .example(\n '$0 quote --source upload --upload-id up_abc --duration 1800',\n 'Price an uploaded file (30 min)'\n ),\n quote as any\n )\n .command(\n 'create',\n 'Submit a transcription (charges the wallet; prints the 202 body)',\n (y: Argv) =>\n sourceOptions(y)\n .example(\n '$0 create --source youtube --url \"https://youtu.be/jNQXAC9IVRw\"',\n 'Transcribe a YouTube video'\n )\n .example(\n '$0 create --source upload --upload-id up_abc --duration 1800',\n 'Transcribe an uploaded file'\n ),\n create as any\n )\n .command(\n 'wait <id>',\n 'Long-poll until the transcription completes or fails (server-side windows)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id from the create 202', type: 'number' })\n .option('timeout', {\n describe: 'Overall seconds to keep waiting',\n type: 'number',\n default: 1800,\n })\n .option('include', { describe: INCLUDE_DESCRIBE, type: 'string' })\n .example('$0 wait 4821', 'Wait for job 4821')\n .example('$0 wait 4821 --include all', 'Wait and inline the full result on completion'),\n wait as any\n )\n .command(\n 'result <id>',\n 'Fetch the result of a completed transcription',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('include', { describe: INCLUDE_DESCRIBE, type: 'string' })\n .example('$0 result 4821', 'Chapters, sections and Q&A')\n .example('$0 result 4821 --include segments | jq -r \\'.segments[].text\\'', 'Full verbatim text'),\n result as any\n )\n .command(\n 'run',\n 'quote, then create, wait, and fetch the result in one command (requires --max-usd)',\n (y: Argv) =>\n sourceOptions(y)\n .option('max-usd', {\n describe:\n 'Hard budget: refuse (exit 6) if the quote exceeds this many USD. Required; there is no default.',\n type: 'number',\n demandOption: true,\n })\n .option('timeout', {\n describe: 'Overall seconds to wait for completion',\n type: 'number',\n default: 1800,\n })\n .option('include', { describe: INCLUDE_DESCRIBE, type: 'string' })\n .check((argv: any) => {\n if (!Number.isFinite(argv.maxUsd) || argv.maxUsd < 0) {\n throw new Error('--max-usd must be a finite number >= 0 (e.g. --max-usd 2)');\n }\n return true;\n })\n .example(\n '$0 run --source youtube --url \"https://youtu.be/jNQXAC9IVRw\" --max-usd 2',\n 'Transcribe end to end, refusing if it would cost more than $2'\n ),\n run as any\n )\n .command(\n 'list',\n 'List transcriptions (newest first, cursor-paginated)',\n (y: Argv) =>\n y\n .option('limit', { describe: '1-200, default 50', type: 'number' })\n .option('cursor', { describe: 'next_cursor from the previous page', type: 'string' })\n .option('api-only', { describe: 'Only jobs created via API', type: 'boolean' })\n .example('$0 list --limit 5 | jq \\'.data[] | {id, status, title}\\'', 'Latest five jobs'),\n list as any\n )\n .command(\n 'get <id>',\n 'Get one transcription (status, stage, progress, charge)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .example('$0 get 4821 | jq .status', 'Check status'),\n get as any\n )\n .command(\n 'delete <id>',\n 'Permanently delete a transcription and all derived data (irreversible)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('yes', {\n describe: 'Required confirmation flag; deletion is irreversible',\n type: 'boolean',\n default: false,\n })\n .check((argv: any) => {\n if (!argv.yes) throw new Error('delete is irreversible; re-run with --yes to confirm');\n return true;\n })\n .example('$0 delete 4821 --yes', 'Delete transcription 4821'),\n deleteTranscription as any\n )\n .command(\n 'retry <id>',\n 'Retry a failed transcription (charges again from scratch)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('yes', {\n describe: 'Required confirmation flag; retry re-charges the wallet from scratch',\n type: 'boolean',\n default: false,\n })\n .option('idempotency-key', {\n describe: 'Override the auto-generated Idempotency-Key',\n type: 'string',\n })\n .check((argv: any) => {\n if (!argv.yes) throw new Error('retry re-charges from scratch; re-run with --yes to confirm');\n return true;\n })\n .example('$0 retry 4821 --yes', 'Re-run failed job 4821'),\n retry as any\n )\n .command(\n 'upload <file>',\n 'Upload a local media file; prints the upload_id to pass to create/run',\n (y: Argv) =>\n y\n .positional('file', { describe: 'Path to the audio/video file', type: 'string' })\n .option('duration', {\n describe: 'Duration in seconds (otherwise probed with ffprobe if installed)',\n type: 'number',\n })\n .option('content-type', {\n describe: 'Override the MIME type (must be on the API allowlist)',\n type: 'string',\n })\n .check((argv: any) => {\n if (\n argv.duration !== undefined &&\n (!Number.isFinite(argv.duration) || argv.duration <= 0)\n ) {\n throw new Error('--duration must be a positive number of seconds');\n }\n return true;\n })\n .example('$0 upload ./interview.mp3', 'Upload an MP3 (duration via ffprobe)')\n .example('$0 upload ./talk.mp4 --duration 1922', 'Upload with explicit duration'),\n upload as any\n )\n .command(\n 'subtitles <id>',\n 'Print the raw subtitle file (SRT/VTT/JSON) to stdout - the one non-JSON command',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('format', {\n describe: 'Subtitle format',\n type: 'string',\n choices: ['srt', 'vtt', 'vtt-karaoke', 'json'],\n })\n .option('preset', {\n describe: 'Platform line rules',\n type: 'string',\n choices: ['youtube', 'tiktok-shorts', 'instagram-reels', 'netflix', 'podcast', 'broadcast'],\n })\n .option('speaker-labels', { describe: 'Prefix cues with [Speaker]', type: 'boolean' })\n .option('mode', {\n describe: 'Cue timing',\n type: 'string',\n choices: ['auto', 'word', 'sentence'],\n })\n .option('source', {\n describe: 'Which cues to serve',\n type: 'string',\n choices: ['auto', 'generated', 'materialized'],\n })\n .example('$0 subtitles 4821 > talk.srt', 'Save the SRT')\n .example('$0 subtitles 4821 --format vtt --preset tiktok-shorts > talk.vtt', 'Vertical-video VTT'),\n subtitles as any\n )\n .command(\n 'ask <id>',\n 'Ask a question about one completed transcription (cited answer; daily Q&A allowance)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('question', {\n alias: 'q',\n describe: 'The question (1-500 chars)',\n type: 'string',\n demandOption: true,\n })\n .option('top-k', { describe: 'Retrieval candidates before rerank (10-100)', type: 'number' })\n .example('$0 ask 4821 -q \"What did the guest say about pricing?\"', 'Cited Q&A'),\n ask as any\n )\n .demandCommand(1, 'You need at least one command')\n .strict()\n .help()\n .alias('h', 'help')\n .version(CLI_VERSION)\n .alias('v', 'version')\n .wrap(Math.min(100, process.stdout.columns || 100))\n .epilogue(\n 'Authentication: export TRANSCRIBE_API_KEY=tsk_live_... (create one at https://transcribe.so/settings/api-keys)\\n' +\n 'Docs: https://transcribe.so/developers/docs | OpenAPI: https://transcribe.so/openapi.json'\n )\n .fail((msg, err, instance) => {\n // Handlers exit themselves (handleFailure/failLocal), so anything that\n // reaches here is a usage/validation problem: bad flags, missing args,\n // or a .check() throw. All of it is exit 2.\n if (err) {\n process.stderr.write(`${err.message}\\n`);\n process.exit(2);\n }\n instance.showHelp('error');\n process.stderr.write(`\\n${msg}\\n`);\n process.exit(2);\n });\n\nparser.parse();\n","// Injected at build time from package.json \"version\" via tsup `define`,\n// so the User-Agent can never drift from the published package version.\ndeclare const __CLI_VERSION__: string;\n\nexport const CLI_VERSION: string =\n typeof __CLI_VERSION__ !== 'undefined' ? __CLI_VERSION__ : '0.0.0-dev';\n","import { randomUUID } from 'crypto';\nimport { TranscribeAPI, handleFailure } from '../api';\nimport { EXIT, getConfig, printJson } from '../config';\n\nconst TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']);\n\nfunction apiFor(argv: any): TranscribeAPI {\n return new TranscribeAPI(getConfig({ allowCustomHost: argv.allowCustomHost }));\n}\n\nfunction printRaw(rawText: string): void {\n process.stdout.write(rawText.endsWith('\\n') ? rawText : rawText + '\\n');\n}\n\nexport interface SourceArgs {\n source: string;\n url?: string;\n uploadId?: string;\n duration?: number;\n language?: string;\n callbackUrl?: string;\n}\n\nfunction buildCreateBody(argv: SourceArgs): Record<string, unknown> {\n const body: Record<string, unknown> = { source: argv.source };\n if (argv.url !== undefined) body.url = argv.url;\n if (argv.uploadId !== undefined) body.upload_id = argv.uploadId;\n if (argv.duration !== undefined) body.duration_seconds = argv.duration;\n if (argv.language !== undefined) body.language = argv.language;\n if (argv.callbackUrl !== undefined) body.callback_url = argv.callbackUrl;\n return body;\n}\n\nexport async function authStatus(argv: any): Promise<void> {\n const config = getConfig({ allowCustomHost: argv.allowCustomHost });\n const api = new TranscribeAPI(config);\n try {\n const res = await api.request('/me');\n printJson({\n authenticated: true,\n api_url: config.apiUrl,\n email: res.json?.email ?? null,\n subscription_tier: res.json?.subscription_tier ?? null,\n wallet_balance_usd: res.json?.wallet_balance_usd ?? null,\n api_key: res.json?.api_key ?? null,\n });\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function me(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/me');\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function pipelines(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/pipelines');\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function quote(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/quotes', {\n method: 'POST',\n body: buildCreateBody(argv),\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function create(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/transcriptions', {\n method: 'POST',\n body: buildCreateBody(argv),\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\n// Shared long-poll loop over the server's /wait endpoint (45 s windows,\n// under Cloudflare's 120 s limit). Never hand-rolls short polling.\nexport async function waitLoop(\n api: TranscribeAPI,\n id: number,\n opts: { timeoutSec: number; include?: string }\n): Promise<{ body: any; rawText: string; timedOut: boolean; notAJob?: boolean }> {\n const deadline = Date.now() + opts.timeoutSec * 1000;\n let last: { body: any; rawText: string } | null = null;\n let quotedPolls = 0;\n\n for (;;) {\n const remaining = Math.ceil((deadline - Date.now()) / 1000);\n if (remaining <= 0) {\n return { body: last?.body ?? null, rawText: last?.rawText ?? 'null', timedOut: true };\n }\n const window = Math.min(45, Math.max(1, remaining));\n const res = await api.request(`/transcriptions/${id}/wait`, {\n query: { timeout: window, include: opts.include },\n });\n last = { body: res.json, rawText: res.rawText };\n const status = res.json?.status;\n if (TERMINAL_STATUSES.has(status)) {\n return { body: res.json, rawText: res.rawText, timedOut: false };\n }\n if (status === 'quoted') {\n // The wire reports concurrency-queued jobs as \"queued\"; a row that\n // shows \"quoted\" is a quote that was never started (createQuote's\n // transcription_id, not a create 202 id). It will never progress.\n quotedPolls++;\n process.stderr.write(\n 'this id looks like a quote, not a job; only the create 202 id is pollable\\n'\n );\n if (quotedPolls >= 2) {\n return { body: res.json, rawText: res.rawText, timedOut: false, notAJob: true };\n }\n } else if (status === 'queued') {\n // Concurrency cap: the job waits FIFO for a free slot. Expected\n // state, not an error; never re-create the job.\n process.stderr.write('waiting for a concurrency slot\\n');\n } else {\n const stage = res.json?.stage ?? '?';\n const progress = res.json?.progress ?? 0;\n process.stderr.write(`status=${status} stage=${stage} progress=${progress}%\\n`);\n }\n }\n}\n\nexport async function wait(argv: any): Promise<void> {\n const api = apiFor(argv);\n try {\n const result = await waitLoop(api, argv.id, {\n timeoutSec: argv.timeout,\n include: argv.include,\n });\n printRaw(result.rawText);\n if (result.notAJob) {\n process.stderr.write(\n `id ${argv.id} is a quote row (status=quoted), not a started job; pass the id from the create 202 response\\n`\n );\n process.exit(EXIT.ERROR);\n }\n if (result.timedOut) {\n process.stderr.write(`wait timed out after ${argv.timeout}s (job still running)\\n`);\n process.exit(EXIT.TRANSIENT);\n }\n if (result.body?.status !== 'completed') {\n process.stderr.write(`transcription ended with status=${result.body?.status}\\n`);\n process.exit(EXIT.ERROR);\n }\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function result(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}/result`, {\n query: { include: argv.include },\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\n// quote -> enforce --max-usd -> create -> wait -> result.\n// Uses ONLY the create 202 `id` for wait/result (the quote's\n// transcription_id is a different row and must never be polled).\nexport async function run(argv: any): Promise<void> {\n const api = apiFor(argv);\n try {\n const body = buildCreateBody(argv);\n const quoteRes = await api.request('/quotes', {\n method: 'POST',\n body,\n idempotencyKey: randomUUID(),\n });\n const retailUsd = Number(quoteRes.json?.retail_usd);\n const billedMinutes = quoteRes.json?.billed_minutes;\n process.stderr.write(`quote: $${retailUsd.toFixed(2)} for ${billedMinutes} billed minute(s)\\n`);\n\n // Belt and suspenders on top of the yargs .check(): a non-finite budget\n // must never let `retailUsd > maxUsd` evaluate false and slip through.\n if (\n !Number.isFinite(argv.maxUsd) ||\n !Number.isFinite(retailUsd) ||\n retailUsd > argv.maxUsd\n ) {\n printJson({\n error: {\n code: 'max_usd_exceeded',\n message: `Quoted price $${retailUsd} exceeds --max-usd ${argv.maxUsd}. Re-run with a higher --max-usd to proceed (this is a local budget refusal, not a balance problem; do not top up).`,\n quote: quoteRes.json,\n },\n });\n process.stderr.write(\n `Refusing to create: quoted $${retailUsd} > --max-usd ${argv.maxUsd}\\n`\n );\n process.exit(EXIT.BUDGET);\n }\n\n const createRes = await api.request('/transcriptions', {\n method: 'POST',\n body,\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n const id = createRes.json?.id;\n process.stderr.write(\n `created transcription ${id} (held $${createRes.json?.retail_usd})\\n`\n );\n\n const waited = await waitLoop(api, id, { timeoutSec: argv.timeout });\n if (waited.notAJob) {\n // Should be unreachable: run always polls the create 202 id.\n printRaw(waited.rawText);\n process.stderr.write(`transcription ${id} unexpectedly reports status=quoted\\n`);\n process.exit(EXIT.ERROR);\n }\n if (waited.timedOut) {\n printRaw(waited.rawText);\n process.stderr.write(\n `wait timed out after ${argv.timeout}s; resume with: transcribe-so wait ${id}\\n`\n );\n process.exit(EXIT.TRANSIENT);\n }\n if (waited.body?.status !== 'completed') {\n printRaw(waited.rawText);\n process.stderr.write(`transcription ${id} ended with status=${waited.body?.status}\\n`);\n process.exit(EXIT.ERROR);\n }\n\n const resultRes = await api.request(`/transcriptions/${id}/result`, {\n query: { include: argv.include },\n });\n printRaw(resultRes.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function list(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/transcriptions', {\n query: {\n limit: argv.limit,\n cursor: argv.cursor,\n api_only: argv.apiOnly ? true : undefined,\n },\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function get(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}`);\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function deleteTranscription(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}`, {\n method: 'DELETE',\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function retry(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}/retry`, {\n method: 'POST',\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n","export const DEFAULT_API_URL = 'https://transcribe.so';\n\nexport const EXIT = {\n OK: 0,\n ERROR: 1,\n USAGE: 2,\n AUTH: 3,\n PAYMENT: 4,\n TRANSIENT: 5,\n BUDGET: 6,\n} as const;\n\nexport interface CliConfig {\n apiKey: string;\n apiUrl: string;\n}\n\nexport function printJson(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + '\\n');\n}\n\n// Local (non-API) failure: JSON error envelope on stdout, human line on\n// stderr, mapped exit code. Mirrors the API envelope shape so agents can\n// always parse stdout the same way.\nexport function failLocal(\n exitCode: number,\n code: string,\n message: string\n): never {\n printJson({ error: { code, message } });\n process.stderr.write(`Error: ${message}\\n`);\n process.exit(exitCode);\n}\n\nexport function getConfig(argv: {\n allowCustomHost?: boolean;\n}): CliConfig {\n const rawUrl = (process.env.TRANSCRIBE_API_URL || DEFAULT_API_URL).replace(\n /\\/+$/,\n ''\n );\n\n if (rawUrl !== DEFAULT_API_URL) {\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n failLocal(\n EXIT.USAGE,\n 'invalid_api_url',\n `TRANSCRIBE_API_URL is not a valid URL: ${rawUrl}`\n );\n }\n const isDefaultHost =\n parsed.protocol === 'https:' && parsed.hostname === 'transcribe.so';\n if (!isDefaultHost && !argv.allowCustomHost) {\n failLocal(\n EXIT.USAGE,\n 'custom_host_refused',\n `Refusing to send your API key to ${rawUrl} (non-default or non-https host). ` +\n `If this is intentional, pass --allow-custom-host.`\n );\n }\n }\n\n const apiKey = process.env.TRANSCRIBE_API_KEY;\n if (!apiKey) {\n failLocal(\n EXIT.AUTH,\n 'missing_api_key',\n 'TRANSCRIBE_API_KEY is not set. Create a key at https://transcribe.so/settings/api-keys and export TRANSCRIBE_API_KEY=tsk_live_...'\n );\n }\n\n return { apiKey, apiUrl: rawUrl };\n}\n","import { CliConfig, EXIT } from './config';\nimport { CLI_VERSION } from './version';\n\nexport interface ApiResponse {\n status: number;\n headers: Headers;\n rawText: string;\n json: any;\n}\n\nexport class ApiError extends Error {\n status: number;\n rawText: string;\n envelope: any;\n retryAfterSeconds: number | null;\n\n constructor(status: number, rawText: string, retryAfterSeconds: number | null) {\n let envelope: any = null;\n try {\n envelope = JSON.parse(rawText);\n } catch {\n envelope = null;\n }\n const code = envelope?.error?.code ?? 'unknown_error';\n const message = envelope?.error?.message ?? rawText.slice(0, 500);\n super(`API error ${status} ${code}: ${message}`);\n this.status = status;\n this.rawText = rawText;\n this.envelope = envelope;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n\n get code(): string {\n return this.envelope?.error?.code ?? 'unknown_error';\n }\n}\n\n// Exit-code mapping: error.code FIRST, HTTP status second.\nexport function exitCodeFor(err: ApiError): number {\n switch (err.code) {\n case 'unauthenticated':\n case 'invalid_api_key':\n case 'scope_forbidden':\n return EXIT.AUTH;\n case 'insufficient_funds':\n case 'spend_cap_exceeded':\n return EXIT.PAYMENT;\n case 'rate_limited':\n case 'internal_error':\n return EXIT.TRANSIENT;\n // Not transient on a CLI timescale: the daily Q&A allowance frees up in\n // hours, not seconds. Plain error so agents stop asking, not retry.\n case 'qna_quota_exceeded':\n return EXIT.ERROR;\n }\n if (err.status === 401) return EXIT.AUTH;\n if (err.status === 402) return EXIT.PAYMENT;\n if (err.status === 429 || err.status >= 500) return EXIT.TRANSIENT;\n return EXIT.ERROR;\n}\n\n// Print the API error envelope to stdout VERBATIM, a human line to stderr,\n// then exit with the mapped code. Non-ApiError failures (network, bugs) get\n// a synthesized envelope and exit 1.\nexport function handleFailure(err: unknown): never {\n if (err instanceof ApiError) {\n if (err.envelope !== null) {\n process.stdout.write(err.rawText.endsWith('\\n') ? err.rawText : err.rawText + '\\n');\n } else {\n // Upstream body was not JSON (CF error page, empty 502, ...). Keep\n // stdout jq-safe with a synthesized envelope instead of raw HTML.\n process.stdout.write(\n JSON.stringify({\n error: {\n code: 'upstream_error',\n message: err.rawText.slice(0, 300),\n http_status: err.status,\n },\n }) + '\\n'\n );\n }\n process.stderr.write(`${err.message}\\n`);\n if (err.code === 'not_ready') {\n process.stderr.write(\n 'Hint: transcription not completed yet; run `transcribe-so wait <id>` first.\\n'\n );\n }\n process.exit(exitCodeFor(err));\n }\n const message = err instanceof Error ? err.message : String(err);\n process.stdout.write(\n JSON.stringify({ error: { code: 'cli_error', message } }) + '\\n'\n );\n process.stderr.write(`Error: ${message}\\n`);\n process.exit(EXIT.ERROR);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n idempotencyKey?: string;\n query?: Record<string, string | number | boolean | undefined>;\n}\n\nexport class TranscribeAPI {\n private apiKey: string;\n private apiUrl: string;\n\n constructor(config: CliConfig) {\n this.apiKey = config.apiKey;\n this.apiUrl = config.apiUrl;\n }\n\n buildUrl(path: string, query?: RequestOptions['query']): string {\n const url = new URL(`${this.apiUrl}/api/v1${path}`);\n for (const [key, value] of Object.entries(query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n return url.toString();\n }\n\n // Retry policy: decided on error.code, never on a bare 429 status.\n // Only per-minute `rate_limited` responses with a short, finite\n // Retry-After header are retried; fair-use / daily-allowance exhaustion\n // shares the code but carries no short Retry-After window. Job-creating\n // POSTs (create/retry) are never auto-retried at all — resubmitting a\n // charge is the caller's call, idempotency key or not.\n async request(path: string, options: RequestOptions = {}): Promise<ApiResponse> {\n const method = options.method ?? 'GET';\n const url = this.buildUrl(path, options.query);\n const maxAttempts = 3;\n const isJobCreatingPost =\n method === 'POST' &&\n (path === '/transcriptions' || /\\/retry$/.test(path));\n\n for (let attempt = 1; ; attempt++) {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n 'User-Agent': `transcribe-so-cli/${CLI_VERSION}`,\n Accept: 'application/json',\n };\n if (options.body !== undefined) headers['Content-Type'] = 'application/json';\n if (options.idempotencyKey) headers['Idempotency-Key'] = options.idempotencyKey;\n\n const response = await fetch(url, {\n method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n });\n const rawText = await response.text();\n\n if (response.ok) {\n let json: any = null;\n try {\n json = JSON.parse(rawText);\n } catch {\n json = null;\n }\n return { status: response.status, headers: response.headers, rawText, json };\n }\n\n const retryAfterHeader = response.headers.get('retry-after');\n const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : null;\n const err = new ApiError(response.status, rawText, retryAfterSeconds);\n\n const retryable =\n err.code === 'rate_limited' &&\n !isJobCreatingPost &&\n retryAfterSeconds !== null &&\n Number.isFinite(retryAfterSeconds) &&\n retryAfterSeconds <= 90;\n\n if (retryable && attempt < maxAttempts) {\n const waitSec = Math.max(1, retryAfterSeconds!);\n process.stderr.write(\n `rate limited; retrying in ${waitSec}s (attempt ${attempt}/${maxAttempts - 1})\\n`\n );\n await sleep(waitSec * 1000);\n continue;\n }\n throw err;\n }\n }\n\n // GET that returns the RAW body (subtitles). Errors keep the envelope.\n async requestRaw(path: string, query?: RequestOptions['query']): Promise<string> {\n const url = this.buildUrl(path, query);\n const response = await fetch(url, {\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'User-Agent': `transcribe-so-cli/${CLI_VERSION}`,\n },\n });\n const rawText = await response.text();\n if (!response.ok) {\n const retryAfterHeader = response.headers.get('retry-after');\n throw new ApiError(\n response.status,\n rawText,\n retryAfterHeader ? Number(retryAfterHeader) : null\n );\n }\n return rawText;\n }\n}\n","import { TranscribeAPI, handleFailure } from '../api';\nimport { getConfig } from '../config';\n\nfunction apiFor(argv: any): TranscribeAPI {\n return new TranscribeAPI(getConfig({ allowCustomHost: argv.allowCustomHost }));\n}\n\n// The ONE non-JSON command: prints the raw subtitle body (SRT/VTT/JSON)\n// so it can be piped straight to a file. Errors keep the JSON envelope.\nexport async function subtitles(argv: any): Promise<void> {\n try {\n const raw = await apiFor(argv).requestRaw(\n `/transcriptions/${argv.id}/subtitles`,\n {\n format: argv.format,\n preset: argv.preset,\n speaker_labels: argv.speakerLabels ? true : undefined,\n mode: argv.mode,\n source: argv.source,\n }\n );\n process.stdout.write(raw.endsWith('\\n') ? raw : raw + '\\n');\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function ask(argv: any): Promise<void> {\n try {\n const body: Record<string, unknown> = { question: argv.question };\n if (argv.topK !== undefined) body.top_k = argv.topK;\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}/ask`, {\n method: 'POST',\n body,\n });\n process.stdout.write(res.rawText.endsWith('\\n') ? res.rawText : res.rawText + '\\n');\n } catch (err) {\n handleFailure(err);\n }\n}\n","import { spawnSync } from 'child_process';\nimport { readFileSync, statSync } from 'fs';\nimport { basename, extname } from 'path';\nimport { TranscribeAPI, handleFailure } from '../api';\nimport { EXIT, failLocal, getConfig, printJson } from '../config';\n\n// Closed allowlist from the OpenAPI spec (UploadRequest.content_type).\nexport const CONTENT_TYPE_ALLOWLIST = [\n 'audio/mpeg',\n 'audio/mp3',\n 'audio/wav',\n 'audio/m4a',\n 'audio/mp4',\n 'audio/x-m4a',\n 'audio/aac',\n 'audio/ogg',\n 'audio/webm',\n 'audio/flac',\n 'video/mp4',\n 'video/webm',\n 'video/quicktime',\n 'video/x-msvideo',\n];\n\nconst EXTENSION_MAP: Record<string, string> = {\n '.mp3': 'audio/mpeg',\n '.mpga': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.m4a': 'audio/m4a',\n '.aac': 'audio/aac',\n '.ogg': 'audio/ogg',\n '.oga': 'audio/ogg',\n '.flac': 'audio/flac',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.mov': 'video/quicktime',\n '.avi': 'video/x-msvideo',\n};\n\nconst WARN_BYTES = 50 * 1024 * 1024;\nconst HARD_LIMIT_BYTES = 500 * 1024 * 1024;\n\nfunction resolveContentType(file: string, override?: string): string {\n if (override) {\n if (!CONTENT_TYPE_ALLOWLIST.includes(override)) {\n failLocal(\n EXIT.USAGE,\n 'unsupported_content_type',\n `--content-type ${override} is not accepted by the API. Allowed: ${CONTENT_TYPE_ALLOWLIST.join(', ')}`\n );\n }\n return override;\n }\n const ext = extname(file).toLowerCase();\n const type = EXTENSION_MAP[ext];\n if (!type) {\n failLocal(\n EXIT.USAGE,\n 'unsupported_content_type',\n `Cannot map extension \"${ext}\" to an accepted content type. Pass --content-type with one of: ${CONTENT_TYPE_ALLOWLIST.join(', ')}`\n );\n }\n return type;\n}\n\nfunction probeDurationSeconds(file: string): number | null {\n const probe = spawnSync(\n 'ffprobe',\n [\n '-v',\n 'error',\n '-show_entries',\n 'format=duration',\n '-of',\n 'default=noprint_wrappers=1:nokey=1',\n file,\n ],\n { encoding: 'utf8' }\n );\n if (probe.error || probe.status !== 0) return null;\n const seconds = parseFloat(probe.stdout.trim());\n return Number.isFinite(seconds) && seconds > 0 ? seconds : null;\n}\n\nexport async function upload(argv: any): Promise<void> {\n const file: string = argv.file;\n\n let size: number;\n try {\n size = statSync(file).size;\n } catch {\n failLocal(EXIT.USAGE, 'file_not_found', `File not found: ${file}`);\n }\n\n if (size > HARD_LIMIT_BYTES) {\n failLocal(\n EXIT.ERROR,\n 'file_too_large_for_presigned',\n `${file} is ${(size / (1024 * 1024)).toFixed(0)} MB; the CLI's single-shot presigned upload is capped at 500 MB. Use a resumable tus upload (POST /api/v1/uploads/tus with any tus 1.0 client) or upload via https://transcribe.so instead.`\n );\n }\n if (size > WARN_BYTES) {\n process.stderr.write(\n `warning: ${(size / (1024 * 1024)).toFixed(0)} MB single-shot upload; the presigned URL expires in 900s. For flaky networks prefer the resumable tus flow (POST /api/v1/uploads/tus) or the web app.\\n`\n );\n }\n\n const contentType = resolveContentType(file, argv.contentType);\n\n let durationSeconds: number | undefined = argv.duration;\n if (durationSeconds === undefined) {\n const probed = probeDurationSeconds(file);\n if (probed === null) {\n failLocal(\n EXIT.USAGE,\n 'duration_required',\n 'Duration is required for uploads and ffprobe is not available (or could not read this file). Either pass --duration <seconds> or install ffmpeg so ffprobe is on PATH.'\n );\n }\n durationSeconds = probed;\n process.stderr.write(`ffprobe duration: ${durationSeconds.toFixed(1)}s\\n`);\n }\n\n const api = new TranscribeAPI(getConfig({ allowCustomHost: argv.allowCustomHost }));\n try {\n const res = await api.request('/uploads', {\n method: 'POST',\n body: {\n filename: basename(file),\n content_type: contentType,\n file_size: size,\n },\n });\n const uploadUrl: string = res.json.upload_url;\n process.stderr.write(`uploading ${basename(file)} (${size} bytes)...\\n`);\n const putResponse = await fetch(uploadUrl, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body: readFileSync(file),\n });\n if (!putResponse.ok) {\n const text = await putResponse.text();\n printJson({\n error: {\n code: 'upload_put_failed',\n message: `PUT to presigned URL failed with ${putResponse.status}: ${text.slice(0, 300)}`,\n },\n });\n process.stderr.write(`upload PUT failed (${putResponse.status})\\n`);\n process.exit(EXIT.TRANSIENT);\n }\n printJson({\n upload_id: res.json.upload_id,\n duration_seconds: durationSeconds,\n filename: basename(file),\n file_size: size,\n content_type: contentType,\n next: `transcribe-so create --source upload --upload-id ${res.json.upload_id} --duration ${durationSeconds}`,\n });\n } catch (err) {\n handleFailure(err);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mBAAkB;AAClB,qBAAwB;;;ACGjB,IAAM,cACX,OAAyC,UAAkB;;;ACL7D,oBAA2B;;;ACApB,IAAM,kBAAkB;AAExB,IAAM,OAAO;AAAA,EAClB,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,QAAQ;AACV;AAOO,SAAS,UAAU,OAAsB;AAC9C,UAAQ,OAAO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CAAC,EACA,OAAO,kBAAkB,EAAE,UAAU,8BAA8B,MAAM,UAAU,CAAC,EACpF,OAAO,QAAQ;AAAA,IACd,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS,CAAC,QAAQ,QAAQ,UAAU;AAAA,EACtC,CAAC,EACA,OAAO,UAAU;AAAA,IAChB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,SAAS,CAAC,QAAQ,aAAa,cAAc;AAAA,EAC/C,CAAC,EACA,QAAQ,gCAAgC,cAAc,EACtD,QAAQ,oEAAoE,oBAAoB;AAAA,EACrG;AACF,EACC;AAAA,EACC;AAAA,EACA;AAAA,EACA,CAAC,MACC,EACG,WAAW,MAAM,EAAE,UAAU,oBAAoB,MAAM,SAAS,CAAC,EACjE,OAAO,YAAY;AAAA,IAClB,OAAO;AAAA,IACP,UAAU;AAAA,IACV,MAAM;AAAA,IACN,cAAc;AAAA,EAChB,CAAC,EACA,OAAO,SAAS,EAAE,UAAU,+CAA+C,MAAM,SAAS,CAAC,EAC3F,QAAQ,0DAA0D,WAAW;AAAA,EAClF;AACF,EACC,cAAc,GAAG,+BAA+B,EAChD,OAAO,EACP,KAAK,EACL,MAAM,KAAK,MAAM,EACjB,QAAQ,WAAW,EACnB,MAAM,KAAK,SAAS,EACpB,KAAK,KAAK,IAAI,KAAK,QAAQ,OAAO,WAAW,GAAG,CAAC,EACjD;AAAA,EACC;AAEF,EACC,KAAK,CAAC,KAAK,KAAK,aAAa;AAI5B,MAAI,KAAK;AACP,YAAQ,OAAO,MAAM,GAAG,IAAI,OAAO;AAAA,CAAI;AACvC,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,WAAS,SAAS,OAAO;AACzB,UAAQ,OAAO,MAAM;AAAA,EAAK,GAAG;AAAA,CAAI;AACjC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,OAAO,MAAM;","names":["result","apiFor","yargs"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/version.ts","../src/commands/core.ts","../src/config.ts","../src/catalog.ts","../src/api.ts","../src/commands/upload.ts","../src/commands/artifacts.ts"],"sourcesContent":["import yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\nimport type { Argv } from 'yargs';\nimport { CLI_VERSION } from './version';\nimport {\n authStatus,\n me,\n pipelines,\n quote,\n create,\n wait,\n result,\n run,\n list,\n get,\n deleteTranscription,\n retry,\n capabilities,\n} from './commands/core';\nimport { subtitles, ask, transcript, captions, search } from './commands/artifacts';\nimport { upload } from './commands/upload';\nimport {\n CAPTION_DESTINATION_NAMES,\n CAPTION_VARIANTS,\n TRANSCRIPT_FORMATS,\n} from './catalog';\n\nconst INCLUDE_DESCRIBE =\n 'Comma-separated result sections: chapters, acts, sections, qna, segments, posting_chapters, or all. Default chapters,sections,qna';\n\nfunction sourceOptions(y: Argv): Argv {\n return y\n .option('source', {\n describe: 'Input source',\n type: 'string',\n choices: ['youtube', 'external_url', 'platform_url', 'upload'],\n demandOption: true,\n })\n .option('url', {\n describe: 'Media URL (required for youtube / platform_url / external_url)',\n type: 'string',\n })\n .option('upload-id', {\n describe: 'upload_id from `transcribe-so upload` (required for source=upload)',\n type: 'string',\n })\n .option('duration', {\n describe: 'Media duration in seconds (required for upload; speeds up URL sources)',\n type: 'number',\n })\n .option('language', {\n describe: 'BCP-47 language code (en, ja, ko, ...) or auto (default)',\n type: 'string',\n })\n .option('callback-url', {\n describe: 'Public https URL that receives this job\\'s signed completed/failed webhook',\n type: 'string',\n })\n .option('idempotency-key', {\n describe: 'Override the auto-generated Idempotency-Key (max 128 chars)',\n type: 'string',\n })\n .check((argv: any) => {\n if (argv.source === 'upload') {\n if (!argv.uploadId) throw new Error('source=upload requires --upload-id');\n if (argv.duration === undefined)\n throw new Error('source=upload requires --duration <seconds>');\n } else if (!argv.url) {\n throw new Error(`source=${argv.source} requires --url`);\n }\n if (\n argv.duration !== undefined &&\n (!Number.isFinite(argv.duration) || argv.duration <= 0)\n ) {\n throw new Error('--duration must be a positive number of seconds');\n }\n return true;\n });\n}\n\n// Server-side charge ceiling. NOT the same thing as `run --max-usd`, which\n// is a local refusal decided from the free quote before anything is created.\n// This one travels with the request and is enforced at the wallet hold, so it\n// also covers a charge that moves between the quote and the hold.\nfunction maxChargeOption(y: Argv): Argv {\n return y\n .option('max-charge-usd', {\n describe:\n 'Server-side charge ceiling in USD. The API refuses with 402 max_charge_exceeded (exit 7) before holding anything if the computed charge is higher. A plan-covered job charges $0 and passes any ceiling, including 0.',\n type: 'number',\n })\n .check((argv: any) => {\n if (\n argv.maxChargeUsd !== undefined &&\n (!Number.isFinite(argv.maxChargeUsd) || argv.maxChargeUsd < 0)\n ) {\n throw new Error('--max-charge-usd must be a finite number >= 0');\n }\n return true;\n });\n}\n\nfunction segmentWindowOptions(y: Argv): Argv {\n return y\n .option('segments-offset', {\n describe: 'First segment to return, 0-based (only with --include segments|all)',\n type: 'number',\n })\n .option('segments-limit', {\n describe:\n 'How many segments to return (1-1000). Read segments_meta.has_more; for the whole transcript use `transcript <id>`, which is never capped.',\n type: 'number',\n });\n}\n\nconst parser = yargs(hideBin(process.argv))\n .scriptName('transcribe-so')\n .usage(\n '$0 <command> [options]\\n\\nPure-JSON stdout, except the three raw-output commands (subtitles, transcript,\\ncaptions) which print a body you can pipe to a file; progress goes to stderr.'\n )\n .option('allow-custom-host', {\n describe:\n 'Allow sending the API key to a non-default TRANSCRIBE_API_URL host (refused otherwise)',\n type: 'boolean',\n default: false,\n global: true,\n })\n .command(\n 'auth:status',\n 'Check whether TRANSCRIBE_API_KEY authenticates against the API',\n {},\n authStatus as any\n )\n .command(\n 'me',\n 'Account, wallet balance, plan limits, API-key scopes and spend',\n (y: Argv) => y.example('$0 me | jq .wallet_balance_usd', 'Check the wallet balance'),\n me as any\n )\n .command(\n 'pipelines',\n 'Capability catalog: pricing per minute and supported languages',\n (y: Argv) =>\n y.example('$0 pipelines | jq \\'.pipelines[0].retail_usd_per_min\\'', 'Current per-minute rate'),\n pipelines as any\n )\n .command(\n 'quote',\n 'Preview the exact cost of a transcription (free, does not queue the job)',\n (y: Argv) =>\n sourceOptions(y)\n .example(\n '$0 quote --source youtube --url \"https://www.youtube.com/watch?v=jNQXAC9IVRw\"',\n 'Price a YouTube video'\n )\n .example(\n '$0 quote --source upload --upload-id up_abc --duration 1800',\n 'Price an uploaded file (30 min)'\n ),\n quote as any\n )\n .command(\n 'create',\n 'Submit a transcription (charges the wallet; prints the 202 body)',\n (y: Argv) =>\n maxChargeOption(sourceOptions(y))\n .example(\n '$0 create --source youtube --url \"https://youtu.be/x\" --max-charge-usd 2',\n 'Refuse server-side (exit 7) if the charge would exceed $2'\n )\n .example(\n '$0 create --source youtube --url \"https://youtu.be/jNQXAC9IVRw\"',\n 'Transcribe a YouTube video'\n )\n .example(\n '$0 create --source upload --upload-id up_abc --duration 1800',\n 'Transcribe an uploaded file'\n ),\n create as any\n )\n .command(\n 'wait <id>',\n 'Long-poll until the transcription completes or fails (server-side windows)',\n (y: Argv) =>\n segmentWindowOptions(y)\n .positional('id', { describe: 'Transcription id from the create 202', type: 'number' })\n .option('timeout', {\n describe: 'Overall seconds to keep waiting',\n type: 'number',\n default: 1800,\n })\n .option('include', { describe: INCLUDE_DESCRIBE, type: 'string' })\n .example('$0 wait 4821', 'Wait for job 4821')\n .example('$0 wait 4821 --include all', 'Wait and inline the full result on completion'),\n wait as any\n )\n .command(\n 'result <id>',\n 'Fetch the result of a completed transcription',\n (y: Argv) =>\n segmentWindowOptions(y)\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('include', { describe: INCLUDE_DESCRIBE, type: 'string' })\n .example('$0 result 4821', 'Chapters, sections and Q&A')\n .example('$0 result 4821 --include segments | jq -r \\'.segments[].text\\'', 'One window of verbatim text')\n .example(\n '$0 result 4821 --include segments --segments-offset 1000 --segments-limit 1000',\n 'The next window (see segments_meta)'\n ),\n result as any\n )\n .command(\n 'run',\n 'quote, then create, wait, and fetch the result in one command (requires --max-usd)',\n (y: Argv) =>\n maxChargeOption(sourceOptions(y))\n .option('server-ceiling', {\n describe:\n 'Also send --max-usd (or --max-charge-usd) to the API as max_charge_usd, so the ceiling is enforced at the wallet hold too. Default true; --no-server-ceiling opts out.',\n type: 'boolean',\n default: true,\n })\n .option('max-usd', {\n describe:\n 'Hard budget: refuse (exit 6) if the quote exceeds this many USD. Required; there is no default.',\n type: 'number',\n demandOption: true,\n })\n .option('timeout', {\n describe: 'Overall seconds to wait for completion',\n type: 'number',\n default: 1800,\n })\n .option('include', { describe: INCLUDE_DESCRIBE, type: 'string' })\n .check((argv: any) => {\n if (!Number.isFinite(argv.maxUsd) || argv.maxUsd < 0) {\n throw new Error('--max-usd must be a finite number >= 0 (e.g. --max-usd 2)');\n }\n return true;\n })\n .example(\n '$0 run --source youtube --url \"https://youtu.be/jNQXAC9IVRw\" --max-usd 2',\n 'Transcribe end to end, refusing if it would cost more than $2'\n ),\n run as any\n )\n .command(\n 'list',\n 'List transcriptions (newest first, cursor-paginated)',\n (y: Argv) =>\n y\n .option('limit', { describe: '1-200, default 50', type: 'number' })\n .option('cursor', { describe: 'next_cursor from the previous page', type: 'string' })\n .option('api-only', { describe: 'Only jobs created via API', type: 'boolean' })\n .example('$0 list --limit 5 | jq \\'.data[] | {id, status, title}\\'', 'Latest five jobs'),\n list as any\n )\n .command(\n 'get <id>',\n 'Get one transcription (status, stage, progress, charge)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .example('$0 get 4821 | jq .status', 'Check status'),\n get as any\n )\n .command(\n 'delete <id>',\n 'Permanently delete a transcription and all derived data (irreversible)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('yes', {\n describe: 'Required confirmation flag; deletion is irreversible',\n type: 'boolean',\n default: false,\n })\n .check((argv: any) => {\n if (!argv.yes) throw new Error('delete is irreversible; re-run with --yes to confirm');\n return true;\n })\n .example('$0 delete 4821 --yes', 'Delete transcription 4821'),\n deleteTranscription as any\n )\n .command(\n 'retry <id>',\n 'Retry a failed transcription (charges again from scratch)',\n (y: Argv) =>\n maxChargeOption(y)\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('yes', {\n describe: 'Required confirmation flag; retry re-charges the wallet from scratch',\n type: 'boolean',\n default: false,\n })\n .option('idempotency-key', {\n describe: 'Override the auto-generated Idempotency-Key',\n type: 'string',\n })\n .check((argv: any) => {\n if (!argv.yes) throw new Error('retry re-charges from scratch; re-run with --yes to confirm');\n return true;\n })\n .example('$0 retry 4821 --yes --max-charge-usd 2', 'Re-run failed job 4821, capped at $2'),\n retry as any\n )\n .command(\n 'upload <file>',\n 'Upload a local media file; prints the upload_id to pass to create/run',\n (y: Argv) =>\n y\n .positional('file', { describe: 'Path to the audio/video file', type: 'string' })\n .option('duration', {\n describe: 'Duration in seconds (otherwise probed with ffprobe if installed)',\n type: 'number',\n })\n .option('content-type', {\n describe: 'Override the MIME type (must be on the API allowlist)',\n type: 'string',\n })\n .check((argv: any) => {\n if (\n argv.duration !== undefined &&\n (!Number.isFinite(argv.duration) || argv.duration <= 0)\n ) {\n throw new Error('--duration must be a positive number of seconds');\n }\n return true;\n })\n .example('$0 upload ./interview.mp3', 'Upload an MP3 (duration via ffprobe)')\n .example('$0 upload ./talk.mp4 --duration 1922', 'Upload with explicit duration'),\n upload as any\n )\n .command(\n 'subtitles <id>',\n 'Print the raw subtitle file (SRT/VTT/JSON) to stdout - a raw-output command',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('format', {\n describe: 'Subtitle format',\n type: 'string',\n choices: ['srt', 'vtt', 'vtt-karaoke', 'json'],\n })\n .option('preset', {\n describe: 'Platform line rules',\n type: 'string',\n choices: ['youtube', 'tiktok-shorts', 'instagram-reels', 'netflix', 'podcast', 'broadcast'],\n })\n .option('speaker-labels', { describe: 'Prefix cues with [Speaker]', type: 'boolean' })\n .option('mode', {\n describe: 'Cue timing',\n type: 'string',\n choices: ['auto', 'word', 'sentence'],\n })\n .option('source', {\n describe: 'Which cues to serve',\n type: 'string',\n choices: ['auto', 'generated', 'materialized'],\n })\n .example('$0 subtitles 4821 > talk.srt', 'Save the SRT')\n .example('$0 subtitles 4821 --format vtt --preset tiktok-shorts > talk.vtt', 'Vertical-video VTT'),\n subtitles as any\n )\n .command(\n 'transcript <id>',\n 'Print the COMPLETE transcript as raw text or Markdown (never capped) - a raw-output command',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('format', {\n describe: 'txt (transcript only) or md (title + chapter list + turns)',\n type: 'string',\n choices: [...TRANSCRIPT_FORMATS],\n default: 'txt',\n })\n .option('speaker-labels', {\n describe: 'Prefix each turn with its speaker label (default true; --no-speaker-labels to drop)',\n type: 'boolean',\n default: true,\n })\n .option('timestamps', {\n describe: 'Prefix each turn with its clock time (default true; --no-timestamps to drop)',\n type: 'boolean',\n default: true,\n })\n .option('out', { describe: 'Write to this file instead of stdout', type: 'string' })\n .option('wait-seconds', {\n describe:\n 'If the job is still processing (409 not_ready reason=transcription_processing), keep retrying on Retry-After for up to this many seconds. Default 0 = fail immediately. Every other not_ready reason exits non-zero without waiting.',\n type: 'number',\n default: 0,\n })\n .check((argv: any) => {\n if (!Number.isFinite(argv.waitSeconds) || argv.waitSeconds < 0) {\n throw new Error('--wait-seconds must be a finite number >= 0');\n }\n return true;\n })\n .example('$0 transcript 4821 > talk.txt', 'Whole transcript as text')\n .example('$0 transcript 4821 --format md --out talk.md', 'Timestamped Markdown export')\n .example('$0 transcript 4821 --no-timestamps --no-speaker-labels', 'Prose only'),\n transcript as any\n )\n .command(\n 'captions <id>',\n 'Paste-ready captions/timestamps for one destination - prints the text raw (--json for the envelope)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('for', {\n describe: 'Destination platform',\n type: 'string',\n choices: CAPTION_DESTINATION_NAMES,\n default: 'youtube',\n })\n .option('variant', {\n describe:\n 'Content: standard (chapter list), highlights (5-item text outline), clips (3 video ideas), quoted_sections (verbatim quotes), show_notes, original',\n type: 'string',\n choices: [...CAPTION_VARIANTS],\n default: 'standard',\n })\n .option('cta', {\n describe: 'Append the transcribe.so CTA footer (quoted_sections only). Off by default: the caption belongs to the user.',\n type: 'boolean',\n default: false,\n })\n .option('json', {\n describe: 'Print the full JSON envelope (warnings, ok_to_paste, thread[], constraints) instead of the raw text',\n type: 'boolean',\n default: false,\n })\n .option('regenerate', {\n describe:\n 'On 409 not_ready reason=artifact_missing, POST /timestamps/regenerate ONCE (30-90s) and retry. Without it the command prints the recovery and exits non-zero. Not free of side effects: it regenerates and REPLACES all four cached caption/chapter variants and burns 1 of the 10 regenerations allowed per transcription.',\n type: 'boolean',\n default: false,\n })\n .example('$0 captions 4821 --for instagram --variant highlights', 'IG caption outline')\n .example('$0 captions 4821 --for youtube > chapters.txt', 'YouTube chapter list')\n .example('$0 captions 4821 --for x --variant quoted_sections --json | jq -r \\'.thread[]\\'', 'Pre-split X thread'),\n captions as any\n )\n .command(\n 'search <q>',\n 'Search transcript segments (\"who said X, and when\") across the library or one transcription',\n (y: Argv) =>\n y\n .positional('q', { describe: 'Search terms (2-200 chars, case-insensitive substring)', type: 'string' })\n .option('id', {\n describe: 'Restrict to one transcription id (404s if it is not yours)',\n type: 'number',\n })\n .option('limit', { describe: 'Hits per page, 1-100 (default 20)', type: 'number' })\n .option('offset', { describe: '0-based offset, max 1000', type: 'number' })\n // Mirrors the server contract so a bad call fails locally (exit 2)\n // instead of spending a round-trip on a 400.\n .check((argv: any) => {\n if (typeof argv.q !== 'string' || argv.q.length < 2) {\n throw new Error('<q> must be at least 2 characters');\n }\n if (argv.limit !== undefined) {\n if (!Number.isInteger(argv.limit) || argv.limit < 1 || argv.limit > 100) {\n throw new Error('--limit must be an integer between 1 and 100');\n }\n }\n if (argv.offset !== undefined) {\n if (!Number.isInteger(argv.offset) || argv.offset < 0 || argv.offset > 1000) {\n throw new Error('--offset must be an integer between 0 and 1000');\n }\n }\n return true;\n })\n .example('$0 search \"pricing\" | jq -r \\'.hits[] | \"\\\\(.speaker): \\\\(.text)\"\\'', 'Who said it')\n .example('$0 search \"pricing\" --id 4821', 'Within one transcription'),\n search as any\n )\n .command(\n 'capabilities',\n 'One JSON object: this account (/me), the pipeline catalog (/pipelines), every format enum this CLI accepts, and the exit codes',\n (y: Argv) =>\n y.example('$0 capabilities | jq .formats.captions.destinations', 'Valid `captions --for` values'),\n capabilities as any\n )\n .command(\n 'ask <id>',\n 'Ask a question about one completed transcription (cited answer; daily Q&A allowance)',\n (y: Argv) =>\n y\n .positional('id', { describe: 'Transcription id', type: 'number' })\n .option('question', {\n alias: 'q',\n describe: 'The question (1-500 chars)',\n type: 'string',\n demandOption: true,\n })\n .option('top-k', { describe: 'Retrieval candidates before rerank (10-100)', type: 'number' })\n .example('$0 ask 4821 -q \"What did the guest say about pricing?\"', 'Cited Q&A'),\n ask as any\n )\n .demandCommand(1, 'You need at least one command')\n .strict()\n .help()\n .alias('h', 'help')\n .version(CLI_VERSION)\n .alias('v', 'version')\n .wrap(Math.min(100, process.stdout.columns || 100))\n .epilogue(\n 'Authentication: export TRANSCRIBE_API_KEY=tsk_live_... (create one at https://transcribe.so/settings/api-keys)\\n' +\n 'Docs: https://transcribe.so/developers/docs | OpenAPI: https://transcribe.so/openapi.json'\n )\n .fail((msg, err, instance) => {\n // Handlers exit themselves (handleFailure/failLocal), so anything that\n // reaches here is a usage/validation problem: bad flags, missing args,\n // or a .check() throw. All of it is exit 2.\n if (err) {\n process.stderr.write(`${err.message}\\n`);\n process.exit(2);\n }\n instance.showHelp('error');\n process.stderr.write(`\\n${msg}\\n`);\n process.exit(2);\n });\n\nparser.parse();\n","// Injected at build time from package.json \"version\" via tsup `define`,\n// so the User-Agent can never drift from the published package version.\ndeclare const __CLI_VERSION__: string;\n\nexport const CLI_VERSION: string =\n typeof __CLI_VERSION__ !== 'undefined' ? __CLI_VERSION__ : '0.0.0-dev';\n","import { randomUUID } from 'crypto';\nimport { TranscribeAPI, handleFailure } from '../api';\nimport {\n CAPTION_DESTINATIONS,\n CAPTION_DESTINATION_NAMES,\n CAPTION_VARIANTS,\n RESULT_INCLUDE_SECTIONS,\n SOURCES,\n SUBTITLE_FORMATS,\n SUBTITLE_MODES,\n SUBTITLE_PRESETS,\n SUBTITLE_SOURCES,\n TRANSCRIPT_FORMATS,\n} from '../catalog';\nimport { EXIT, getConfig, printJson } from '../config';\nimport { CLI_VERSION } from '../version';\nimport { CONTENT_TYPE_ALLOWLIST } from './upload';\n\nconst TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']);\n\nfunction apiFor(argv: any): TranscribeAPI {\n return new TranscribeAPI(getConfig({ allowCustomHost: argv.allowCustomHost }));\n}\n\nfunction printRaw(rawText: string): void {\n process.stdout.write(rawText.endsWith('\\n') ? rawText : rawText + '\\n');\n}\n\nexport interface SourceArgs {\n source: string;\n url?: string;\n uploadId?: string;\n duration?: number;\n language?: string;\n callbackUrl?: string;\n maxChargeUsd?: number;\n}\n\n// `withCeiling` is false for /quotes: a quote never charges, so a ceiling\n// there would only risk a refusal on the one call that is free and whose\n// whole job is to tell you the price.\nexport function buildCreateBody(\n argv: SourceArgs,\n withCeiling = false\n): Record<string, unknown> {\n const body: Record<string, unknown> = { source: argv.source };\n if (argv.url !== undefined) body.url = argv.url;\n if (argv.uploadId !== undefined) body.upload_id = argv.uploadId;\n if (argv.duration !== undefined) body.duration_seconds = argv.duration;\n if (argv.language !== undefined) body.language = argv.language;\n if (argv.callbackUrl !== undefined) body.callback_url = argv.callbackUrl;\n if (withCeiling && argv.maxChargeUsd !== undefined)\n body.max_charge_usd = argv.maxChargeUsd;\n return body;\n}\n\nexport async function authStatus(argv: any): Promise<void> {\n const config = getConfig({ allowCustomHost: argv.allowCustomHost });\n const api = new TranscribeAPI(config);\n try {\n const res = await api.request('/me');\n printJson({\n authenticated: true,\n api_url: config.apiUrl,\n email: res.json?.email ?? null,\n subscription_tier: res.json?.subscription_tier ?? null,\n wallet_balance_usd: res.json?.wallet_balance_usd ?? null,\n api_key: res.json?.api_key ?? null,\n });\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function me(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/me');\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function pipelines(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/pipelines');\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function quote(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/quotes', {\n method: 'POST',\n body: buildCreateBody(argv),\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function create(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/transcriptions', {\n method: 'POST',\n body: buildCreateBody(argv, true),\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\n// Shared long-poll loop over the server's /wait endpoint (45 s windows,\n// under Cloudflare's 120 s limit). Never hand-rolls short polling.\nexport async function waitLoop(\n api: TranscribeAPI,\n id: number,\n opts: {\n timeoutSec: number;\n include?: string;\n segmentsOffset?: number;\n segmentsLimit?: number;\n }\n): Promise<{ body: any; rawText: string; timedOut: boolean; notAJob?: boolean }> {\n const deadline = Date.now() + opts.timeoutSec * 1000;\n let last: { body: any; rawText: string } | null = null;\n let quotedPolls = 0;\n\n for (;;) {\n const remaining = Math.ceil((deadline - Date.now()) / 1000);\n if (remaining <= 0) {\n return { body: last?.body ?? null, rawText: last?.rawText ?? 'null', timedOut: true };\n }\n const window = Math.min(45, Math.max(1, remaining));\n const res = await api.request(`/transcriptions/${id}/wait`, {\n query: {\n timeout: window,\n include: opts.include,\n segments_offset: opts.segmentsOffset,\n segments_limit: opts.segmentsLimit,\n },\n });\n last = { body: res.json, rawText: res.rawText };\n const status = res.json?.status;\n if (TERMINAL_STATUSES.has(status)) {\n return { body: res.json, rawText: res.rawText, timedOut: false };\n }\n if (status === 'quoted') {\n // The wire reports concurrency-queued jobs as \"queued\"; a row that\n // shows \"quoted\" is a quote that was never started (createQuote's\n // transcription_id, not a create 202 id). It will never progress.\n quotedPolls++;\n process.stderr.write(\n 'this id looks like a quote, not a job; only the create 202 id is pollable\\n'\n );\n if (quotedPolls >= 2) {\n return { body: res.json, rawText: res.rawText, timedOut: false, notAJob: true };\n }\n } else if (status === 'queued') {\n // Concurrency cap: the job waits FIFO for a free slot. Expected\n // state, not an error; never re-create the job.\n process.stderr.write('waiting for a concurrency slot\\n');\n } else {\n const stage = res.json?.stage ?? '?';\n const progress = res.json?.progress ?? 0;\n process.stderr.write(`status=${status} stage=${stage} progress=${progress}%\\n`);\n }\n }\n}\n\nexport async function wait(argv: any): Promise<void> {\n const api = apiFor(argv);\n try {\n const result = await waitLoop(api, argv.id, {\n timeoutSec: argv.timeout,\n include: argv.include,\n segmentsOffset: argv.segmentsOffset,\n segmentsLimit: argv.segmentsLimit,\n });\n printRaw(result.rawText);\n noteSegmentsWindow(result.body, argv.id);\n if (result.notAJob) {\n process.stderr.write(\n `id ${argv.id} is a quote row (status=quoted), not a started job; pass the id from the create 202 response\\n`\n );\n process.exit(EXIT.ERROR);\n }\n if (result.timedOut) {\n process.stderr.write(`wait timed out after ${argv.timeout}s (job still running)\\n`);\n process.exit(EXIT.TRANSIENT);\n }\n if (result.body?.status !== 'completed') {\n process.stderr.write(`transcription ended with status=${result.body?.status}\\n`);\n process.exit(EXIT.ERROR);\n }\n } catch (err) {\n handleFailure(err);\n }\n}\n\n// `segments_meta` is the difference between a complete transcript and a\n// windowed one. Silently handing back a truncated transcript is the failure\n// mode this note exists to prevent.\nexport function noteSegmentsWindow(body: any, id: number | string): void {\n const meta = body?.segments_meta;\n if (!meta) return;\n process.stderr.write(\n `segments window: offset=${meta.offset} limit=${meta.limit} of ${meta.total} total, has_more=${meta.has_more}\\n`\n );\n if (meta.has_more) {\n process.stderr.write(\n `this is a PARTIAL transcript; continue with --segments-offset ${meta.offset + meta.limit}, ` +\n `or get the whole thing as text with: transcribe-so transcript ${id}\\n`\n );\n }\n}\n\nexport async function result(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}/result`, {\n query: {\n include: argv.include,\n segments_offset: argv.segmentsOffset,\n segments_limit: argv.segmentsLimit,\n },\n });\n printRaw(res.rawText);\n noteSegmentsWindow(res.json, argv.id);\n } catch (err) {\n handleFailure(err);\n }\n}\n\n// quote -> enforce --max-usd -> create -> wait -> result.\n// Uses ONLY the create 202 `id` for wait/result (the quote's\n// transcription_id is a different row and must never be polled).\n// `run` already has a local budget (`--max-usd`, enforced before the create\n// call). The server-side ceiling closes the gap the local check cannot: the\n// charge is recomputed at the wallet hold, and plan coverage or a probed\n// duration can move it between the quote and the hold. So by default the\n// local budget IS sent as `max_charge_usd` too. An explicit\n// `--max-charge-usd` wins; `--no-server-ceiling` opts out entirely.\nexport function resolveRunCeiling(argv: {\n maxUsd: number;\n maxChargeUsd?: number;\n serverCeiling?: boolean;\n}): number | undefined {\n if (argv.serverCeiling === false) return undefined;\n if (argv.maxChargeUsd !== undefined) return argv.maxChargeUsd;\n return argv.maxUsd;\n}\n\nexport async function run(argv: any): Promise<void> {\n const api = apiFor(argv);\n try {\n const body = buildCreateBody(argv);\n const quoteRes = await api.request('/quotes', {\n method: 'POST',\n body,\n idempotencyKey: randomUUID(),\n });\n const retailUsd = Number(quoteRes.json?.retail_usd);\n const billedMinutes = quoteRes.json?.billed_minutes;\n process.stderr.write(`quote: $${retailUsd.toFixed(2)} for ${billedMinutes} billed minute(s)\\n`);\n\n // Belt and suspenders on top of the yargs .check(): a non-finite budget\n // must never let `retailUsd > maxUsd` evaluate false and slip through.\n if (\n !Number.isFinite(argv.maxUsd) ||\n !Number.isFinite(retailUsd) ||\n retailUsd > argv.maxUsd\n ) {\n printJson({\n error: {\n code: 'max_usd_exceeded',\n message: `Quoted price $${retailUsd} exceeds --max-usd ${argv.maxUsd}. Re-run with a higher --max-usd to proceed (this is a local budget refusal, not a balance problem; do not top up).`,\n quote: quoteRes.json,\n },\n });\n process.stderr.write(\n `Refusing to create: quoted $${retailUsd} > --max-usd ${argv.maxUsd}\\n`\n );\n process.exit(EXIT.BUDGET);\n }\n\n const ceiling = resolveRunCeiling(argv);\n const createBody =\n ceiling === undefined ? body : { ...body, max_charge_usd: ceiling };\n if (ceiling !== undefined) {\n process.stderr.write(`server-side charge ceiling: $${ceiling}\\n`);\n }\n const createRes = await api.request('/transcriptions', {\n method: 'POST',\n body: createBody,\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n const id = createRes.json?.id;\n process.stderr.write(\n `created transcription ${id} (held $${createRes.json?.retail_usd})\\n`\n );\n\n const waited = await waitLoop(api, id, { timeoutSec: argv.timeout });\n if (waited.notAJob) {\n // Should be unreachable: run always polls the create 202 id.\n printRaw(waited.rawText);\n process.stderr.write(`transcription ${id} unexpectedly reports status=quoted\\n`);\n process.exit(EXIT.ERROR);\n }\n if (waited.timedOut) {\n printRaw(waited.rawText);\n process.stderr.write(\n `wait timed out after ${argv.timeout}s; resume with: transcribe-so wait ${id}\\n`\n );\n process.exit(EXIT.TRANSIENT);\n }\n if (waited.body?.status !== 'completed') {\n printRaw(waited.rawText);\n process.stderr.write(`transcription ${id} ended with status=${waited.body?.status}\\n`);\n process.exit(EXIT.ERROR);\n }\n\n const resultRes = await api.request(`/transcriptions/${id}/result`, {\n query: { include: argv.include },\n });\n printRaw(resultRes.rawText);\n noteSegmentsWindow(resultRes.json, id);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function list(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request('/transcriptions', {\n query: {\n limit: argv.limit,\n cursor: argv.cursor,\n api_only: argv.apiOnly ? true : undefined,\n },\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function get(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}`);\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function deleteTranscription(argv: any): Promise<void> {\n try {\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}`, {\n method: 'DELETE',\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\nexport async function retry(argv: any): Promise<void> {\n try {\n // A retry is a NEW paid attempt with its own hold: the create call's\n // ceiling does not carry over, so it has to be sent again here.\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}/retry`, {\n method: 'POST',\n body:\n argv.maxChargeUsd !== undefined\n ? { max_charge_usd: argv.maxChargeUsd }\n : undefined,\n idempotencyKey: argv.idempotencyKey ?? randomUUID(),\n });\n printRaw(res.rawText);\n } catch (err) {\n handleFailure(err);\n }\n}\n\n// One JSON object describing what this account and this CLI can do: the live\n// /me and /pipelines bodies, plus the CLI's own enums (every one of them a\n// real wire enum, not a schema language). Answers \"what can I ask for?\" in a\n// single call so an agent does not guess flag values.\nexport async function capabilities(argv: any): Promise<void> {\n const api = apiFor(argv);\n try {\n const [meRes, pipelinesRes] = await Promise.all([\n api.request('/me'),\n api.request('/pipelines'),\n ]);\n\n // Unauthenticated and cheap; the spec is public. A failure here must not\n // fail the command - the version is a nicety, the enums are the payload.\n let apiVersion: string | null = null;\n try {\n const specRes = await fetch(`${api.baseUrl}/openapi.json`, {\n headers: { Accept: 'application/json' },\n });\n if (specRes.ok) {\n const spec: any = await specRes.json();\n apiVersion = spec?.info?.version ?? null;\n }\n } catch {\n apiVersion = null;\n }\n\n printJson({\n cli_version: CLI_VERSION,\n api_url: api.baseUrl,\n api_version: apiVersion,\n account: meRes.json,\n pipelines: pipelinesRes.json?.pipelines ?? pipelinesRes.json,\n formats: {\n sources: SOURCES,\n result_include: RESULT_INCLUDE_SECTIONS,\n transcript_formats: TRANSCRIPT_FORMATS,\n subtitles: {\n formats: SUBTITLE_FORMATS,\n presets: SUBTITLE_PRESETS,\n modes: SUBTITLE_MODES,\n sources: SUBTITLE_SOURCES,\n },\n captions: {\n destinations: CAPTION_DESTINATION_NAMES,\n destination_to_api_format: CAPTION_DESTINATIONS,\n variants: CAPTION_VARIANTS,\n },\n upload_content_types: CONTENT_TYPE_ALLOWLIST,\n },\n exit_codes: EXIT,\n });\n } catch (err) {\n handleFailure(err);\n }\n}\n","export const DEFAULT_API_URL = 'https://transcribe.so';\n\nexport const EXIT = {\n OK: 0,\n ERROR: 1,\n USAGE: 2,\n AUTH: 3,\n PAYMENT: 4,\n TRANSIENT: 5,\n BUDGET: 6,\n // Server-side ceiling: the API refused with 402 `max_charge_exceeded`\n // because `max_charge_usd` was below the computed charge. Distinct from\n // 4 (the account cannot pay) and from 6 (the CLI's own local `--max-usd`\n // refusal, decided before any request that could charge).\n MAX_CHARGE: 7,\n} as const;\n\nexport interface CliConfig {\n apiKey: string;\n apiUrl: string;\n}\n\nexport function printJson(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + '\\n');\n}\n\n// Local (non-API) failure: JSON error envelope on stdout, human line on\n// stderr, mapped exit code. Mirrors the API envelope shape so agents can\n// always parse stdout the same way.\nexport function failLocal(\n exitCode: number,\n code: string,\n message: string\n): never {\n printJson({ error: { code, message } });\n process.stderr.write(`Error: ${message}\\n`);\n process.exit(exitCode);\n}\n\nexport function getConfig(argv: {\n allowCustomHost?: boolean;\n}): CliConfig {\n const rawUrl = (process.env.TRANSCRIBE_API_URL || DEFAULT_API_URL).replace(\n /\\/+$/,\n ''\n );\n\n if (rawUrl !== DEFAULT_API_URL) {\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n failLocal(\n EXIT.USAGE,\n 'invalid_api_url',\n `TRANSCRIBE_API_URL is not a valid URL: ${rawUrl}`\n );\n }\n const isDefaultHost =\n parsed.protocol === 'https:' && parsed.hostname === 'transcribe.so';\n if (!isDefaultHost && !argv.allowCustomHost) {\n failLocal(\n EXIT.USAGE,\n 'custom_host_refused',\n `Refusing to send your API key to ${rawUrl} (non-default or non-https host). ` +\n `If this is intentional, pass --allow-custom-host.`\n );\n }\n }\n\n const apiKey = process.env.TRANSCRIBE_API_KEY;\n if (!apiKey) {\n failLocal(\n EXIT.AUTH,\n 'missing_api_key',\n 'TRANSCRIBE_API_KEY is not set. Create a key at https://transcribe.so/settings/api-keys and export TRANSCRIBE_API_KEY=tsk_live_...'\n );\n }\n\n return { apiKey, apiUrl: rawUrl };\n}\n","// Static enums the CLI knows about, mirrored from the live OpenAPI spec.\n// Nothing here is invented: every list is an enum that exists on the wire.\n// `capabilities` prints these alongside the live /me and /pipelines bodies.\n\nexport const SOURCES = ['youtube', 'platform_url', 'external_url', 'upload'] as const;\n\nexport const TRANSCRIPT_FORMATS = ['txt', 'md'] as const;\n\nexport const SUBTITLE_FORMATS = ['srt', 'vtt', 'vtt-karaoke', 'json'] as const;\nexport const SUBTITLE_PRESETS = [\n 'youtube',\n 'tiktok-shorts',\n 'instagram-reels',\n 'netflix',\n 'podcast',\n 'broadcast',\n] as const;\nexport const SUBTITLE_MODES = ['auto', 'word', 'sentence'] as const;\nexport const SUBTITLE_SOURCES = ['auto', 'generated', 'materialized'] as const;\n\nexport const RESULT_INCLUDE_SECTIONS = [\n 'chapters',\n 'acts',\n 'sections',\n 'qna',\n 'segments',\n 'posting_chapters',\n 'all',\n] as const;\n\n// `captions --for <destination>`: friendly name -> the API's `format` value.\n// Only `instagram` differs from the wire name; the rest are identity so the\n// flag stays one vocabulary rather than two.\nexport const CAPTION_DESTINATIONS: Record<string, string> = {\n instagram: 'instagram_caption',\n x: 'x',\n threads: 'threads',\n linkedin: 'linkedin',\n youtube: 'youtube',\n spotify: 'spotify',\n apple_podcasts: 'apple_podcasts',\n markdown: 'markdown',\n plain: 'plain',\n};\n\nexport const CAPTION_DESTINATION_NAMES = Object.keys(CAPTION_DESTINATIONS);\n\nexport const CAPTION_VARIANTS = [\n 'standard',\n 'highlights',\n 'clips',\n 'quoted_sections',\n 'show_notes',\n 'original',\n] as const;\n\n// 409 not_ready reasons on /transcript and /timestamps. Only ONE resolves by\n// waiting; the rest need a different action, so the CLI must not back off on them.\nexport const NOT_READY_REASONS = [\n 'transcription_processing',\n 'transcription_failed',\n 'transcription_cancelled',\n 'not_started',\n 'artifact_missing',\n] as const;\n\nexport type NotReadyReason = (typeof NOT_READY_REASONS)[number];\n\nexport function captionFormatFor(destination: string): string {\n const format = CAPTION_DESTINATIONS[destination];\n if (!format) {\n throw new Error(\n `unknown caption destination \"${destination}\"; expected one of: ${CAPTION_DESTINATION_NAMES.join(', ')}`\n );\n }\n return format;\n}\n\n// Recovery line printed for every non-waitable not_ready reason. The strings\n// are the exact next action, not a restatement of the error.\nexport function notReadyRecovery(reason: string | undefined, id: number | string): string {\n switch (reason) {\n case 'transcription_processing':\n return `Still processing. Wait for it: transcribe-so wait ${id}`;\n case 'transcription_failed':\n return `The transcription failed; there is nothing to wait for. A retry is a NEW paid attempt: transcribe-so retry ${id} --yes --max-charge-usd <n>`;\n case 'transcription_cancelled':\n return `The transcription was cancelled; there is no transcript and waiting will not produce one.`;\n case 'not_started':\n return `This row is a quote (status=quoted) that was never started. Start a job with: transcribe-so create ... (the quote's transcription_id is not a job id)`;\n case 'artifact_missing':\n return `Completed, but the artifact was never generated. Retrying the same call will not help.`;\n default:\n return `Not ready (reason=${reason ?? 'unknown'}).`;\n }\n}\n\nexport function isWaitableNotReady(reason: string | undefined): boolean {\n return reason === 'transcription_processing';\n}\n","import { CliConfig, EXIT } from './config';\nimport { notReadyRecovery } from './catalog';\nimport { CLI_VERSION } from './version';\n\nexport interface ApiResponse {\n status: number;\n headers: Headers;\n rawText: string;\n json: any;\n}\n\nexport class ApiError extends Error {\n status: number;\n rawText: string;\n envelope: any;\n retryAfterSeconds: number | null;\n\n constructor(status: number, rawText: string, retryAfterSeconds: number | null) {\n let envelope: any = null;\n try {\n envelope = JSON.parse(rawText);\n } catch {\n envelope = null;\n }\n const code = envelope?.error?.code ?? 'unknown_error';\n const message = envelope?.error?.message ?? rawText.slice(0, 500);\n super(`API error ${status} ${code}: ${message}`);\n this.status = status;\n this.rawText = rawText;\n this.envelope = envelope;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n\n get code(): string {\n return this.envelope?.error?.code ?? 'unknown_error';\n }\n\n // Only set on 409 `not_ready` (transcript / timestamps). Decides whether\n // waiting can possibly help.\n get reason(): string | undefined {\n return this.envelope?.error?.reason;\n }\n}\n\n// `rate_limited` with no finite Retry-After is permanent on a CLI timescale:\n// nothing the agent can do makes the same call succeed later.\nexport function isPermanentRateLimit(err: ApiError): boolean {\n if (err.code !== 'rate_limited') return false;\n return !(err.retryAfterSeconds !== null && Number.isFinite(err.retryAfterSeconds));\n}\n\n// Exit-code mapping: error.code FIRST, HTTP status second.\nexport function exitCodeFor(err: ApiError): number {\n switch (err.code) {\n case 'unauthenticated':\n case 'invalid_api_key':\n case 'scope_forbidden':\n return EXIT.AUTH;\n case 'insufficient_funds':\n case 'spend_cap_exceeded':\n return EXIT.PAYMENT;\n // Also a 402, but the opposite remedy: nothing was held or charged and\n // the account is fine. Raising the ceiling is the user's call, never the\n // agent's, so it gets its own code instead of reading as \"top up\".\n case 'max_charge_exceeded':\n return EXIT.MAX_CHARGE;\n // A 429 with a Retry-After is a real throttle: wait it out. Without one it\n // is an exhausted allowance that never refills on its own - the\n // regeneration cap (\"Regeneration limit reached (10). Re-transcribe to\n // reset.\") is the live example - so it gets the plain error code and\n // agents stop looping.\n case 'rate_limited':\n return isPermanentRateLimit(err) ? EXIT.ERROR : EXIT.TRANSIENT;\n case 'internal_error':\n return EXIT.TRANSIENT;\n // Not transient on a CLI timescale: the daily Q&A allowance frees up in\n // hours, not seconds. Plain error so agents stop asking, not retry.\n case 'qna_quota_exceeded':\n return EXIT.ERROR;\n }\n if (err.status === 401) return EXIT.AUTH;\n if (err.status === 402) return EXIT.PAYMENT;\n if (err.status === 429 || err.status >= 500) return EXIT.TRANSIENT;\n return EXIT.ERROR;\n}\n\n// Print the API error envelope to stdout VERBATIM, a human line to stderr,\n// then exit with the mapped code. Non-ApiError failures (network, bugs) get\n// a synthesized envelope and exit 1.\nexport interface FailureContext {\n // The transcription id the failing call was about, so recovery lines can\n // name a real command instead of a placeholder.\n id?: number | string;\n // Set by callers that already printed their own, more specific Recovery\n // line; without it the generic not_ready hint prints the same advice twice.\n suppressNotReadyHint?: boolean;\n}\n\nexport function handleFailure(err: unknown, ctx: FailureContext = {}): never {\n if (err instanceof ApiError) {\n if (err.envelope !== null) {\n process.stdout.write(err.rawText.endsWith('\\n') ? err.rawText : err.rawText + '\\n');\n } else {\n // Upstream body was not JSON (CF error page, empty 502, ...). Keep\n // stdout jq-safe with a synthesized envelope instead of raw HTML.\n process.stdout.write(\n JSON.stringify({\n error: {\n code: 'upstream_error',\n message: err.rawText.slice(0, 300),\n http_status: err.status,\n },\n }) + '\\n'\n );\n }\n process.stderr.write(`${err.message}\\n`);\n if (err.code === 'not_ready' && !ctx.suppressNotReadyHint) {\n // `reason` is the whole point of this envelope: only\n // `transcription_processing` resolves by waiting.\n process.stderr.write(\n `Hint: ${notReadyRecovery(err.reason, ctx.id ?? '<id>')}\\n`\n );\n }\n if (isPermanentRateLimit(err)) {\n process.stderr.write(\n 'Hint: this allowance does not refill on a CLI timescale (no Retry-After was sent). ' +\n 'Re-transcribe to reset; retrying will not help.\\n'\n );\n }\n if (err.code === 'max_charge_exceeded') {\n const charge = err.envelope?.error?.charge_usd;\n // The envelope does not always echo the ceiling back; `$undefined` read\n // as a real number to agents.\n const ceiling = err.envelope?.error?.max_charge_usd ?? 'not sent';\n process.stderr.write(\n `Hint: nothing was charged and no job started. The real charge is $${charge} against a ceiling of $${ceiling}. ` +\n `Report the price and ask the user before raising --max-charge-usd; do not raise it on your own.\\n`\n );\n }\n process.exit(exitCodeFor(err));\n }\n const message = err instanceof Error ? err.message : String(err);\n process.stdout.write(\n JSON.stringify({ error: { code: 'cli_error', message } }) + '\\n'\n );\n process.stderr.write(`Error: ${message}\\n`);\n process.exit(EXIT.ERROR);\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n idempotencyKey?: string;\n query?: Record<string, string | number | boolean | undefined>;\n}\n\nexport class TranscribeAPI {\n private apiKey: string;\n private apiUrl: string;\n\n constructor(config: CliConfig) {\n this.apiKey = config.apiKey;\n this.apiUrl = config.apiUrl;\n }\n\n get baseUrl(): string {\n return this.apiUrl;\n }\n\n buildUrl(path: string, query?: RequestOptions['query']): string {\n const url = new URL(`${this.apiUrl}/api/v1${path}`);\n for (const [key, value] of Object.entries(query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n return url.toString();\n }\n\n // Retry policy: decided on error.code, never on a bare 429 status.\n // Only per-minute `rate_limited` responses with a short, finite\n // Retry-After header are retried; fair-use / daily-allowance exhaustion\n // shares the code but carries no short Retry-After window. Job-creating\n // POSTs (create/retry) are never auto-retried at all — resubmitting a\n // charge is the caller's call, idempotency key or not.\n async request(path: string, options: RequestOptions = {}): Promise<ApiResponse> {\n const method = options.method ?? 'GET';\n const url = this.buildUrl(path, options.query);\n const maxAttempts = 3;\n const isJobCreatingPost =\n method === 'POST' &&\n (path === '/transcriptions' || /\\/retry$/.test(path));\n\n for (let attempt = 1; ; attempt++) {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n 'User-Agent': `transcribe-so-cli/${CLI_VERSION}`,\n Accept: 'application/json',\n };\n if (options.body !== undefined) headers['Content-Type'] = 'application/json';\n if (options.idempotencyKey) headers['Idempotency-Key'] = options.idempotencyKey;\n\n const response = await fetch(url, {\n method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n });\n const rawText = await response.text();\n\n if (response.ok) {\n let json: any = null;\n try {\n json = JSON.parse(rawText);\n } catch {\n json = null;\n }\n return { status: response.status, headers: response.headers, rawText, json };\n }\n\n const retryAfterHeader = response.headers.get('retry-after');\n const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : null;\n const err = new ApiError(response.status, rawText, retryAfterSeconds);\n\n const retryable =\n err.code === 'rate_limited' &&\n !isJobCreatingPost &&\n retryAfterSeconds !== null &&\n Number.isFinite(retryAfterSeconds) &&\n retryAfterSeconds <= 90;\n\n if (retryable && attempt < maxAttempts) {\n const waitSec = Math.max(1, retryAfterSeconds!);\n process.stderr.write(\n `rate limited; retrying in ${waitSec}s (attempt ${attempt}/${maxAttempts - 1})\\n`\n );\n await sleep(waitSec * 1000);\n continue;\n }\n throw err;\n }\n }\n\n // GET that returns the RAW body (subtitles). Errors keep the envelope.\n async requestRaw(path: string, query?: RequestOptions['query']): Promise<string> {\n const url = this.buildUrl(path, query);\n const response = await fetch(url, {\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'User-Agent': `transcribe-so-cli/${CLI_VERSION}`,\n },\n });\n const rawText = await response.text();\n if (!response.ok) {\n const retryAfterHeader = response.headers.get('retry-after');\n throw new ApiError(\n response.status,\n rawText,\n retryAfterHeader ? Number(retryAfterHeader) : null\n );\n }\n return rawText;\n }\n}\n","import { spawnSync } from 'child_process';\nimport { readFileSync, statSync } from 'fs';\nimport { basename, extname } from 'path';\nimport { TranscribeAPI, handleFailure } from '../api';\nimport { EXIT, failLocal, getConfig, printJson } from '../config';\n\n// Closed allowlist from the OpenAPI spec (UploadRequest.content_type).\nexport const CONTENT_TYPE_ALLOWLIST = [\n 'audio/mpeg',\n 'audio/mp3',\n 'audio/wav',\n 'audio/m4a',\n 'audio/mp4',\n 'audio/x-m4a',\n 'audio/aac',\n 'audio/ogg',\n 'audio/webm',\n 'audio/flac',\n 'video/mp4',\n 'video/webm',\n 'video/quicktime',\n 'video/x-msvideo',\n];\n\nconst EXTENSION_MAP: Record<string, string> = {\n '.mp3': 'audio/mpeg',\n '.mpga': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.m4a': 'audio/m4a',\n '.aac': 'audio/aac',\n '.ogg': 'audio/ogg',\n '.oga': 'audio/ogg',\n '.flac': 'audio/flac',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.mov': 'video/quicktime',\n '.avi': 'video/x-msvideo',\n};\n\nconst WARN_BYTES = 50 * 1024 * 1024;\nconst HARD_LIMIT_BYTES = 500 * 1024 * 1024;\n\nfunction resolveContentType(file: string, override?: string): string {\n if (override) {\n if (!CONTENT_TYPE_ALLOWLIST.includes(override)) {\n failLocal(\n EXIT.USAGE,\n 'unsupported_content_type',\n `--content-type ${override} is not accepted by the API. Allowed: ${CONTENT_TYPE_ALLOWLIST.join(', ')}`\n );\n }\n return override;\n }\n const ext = extname(file).toLowerCase();\n const type = EXTENSION_MAP[ext];\n if (!type) {\n failLocal(\n EXIT.USAGE,\n 'unsupported_content_type',\n `Cannot map extension \"${ext}\" to an accepted content type. Pass --content-type with one of: ${CONTENT_TYPE_ALLOWLIST.join(', ')}`\n );\n }\n return type;\n}\n\nfunction probeDurationSeconds(file: string): number | null {\n const probe = spawnSync(\n 'ffprobe',\n [\n '-v',\n 'error',\n '-show_entries',\n 'format=duration',\n '-of',\n 'default=noprint_wrappers=1:nokey=1',\n file,\n ],\n { encoding: 'utf8' }\n );\n if (probe.error || probe.status !== 0) return null;\n const seconds = parseFloat(probe.stdout.trim());\n return Number.isFinite(seconds) && seconds > 0 ? seconds : null;\n}\n\nexport async function upload(argv: any): Promise<void> {\n const file: string = argv.file;\n\n let size: number;\n try {\n size = statSync(file).size;\n } catch {\n failLocal(EXIT.USAGE, 'file_not_found', `File not found: ${file}`);\n }\n\n if (size > HARD_LIMIT_BYTES) {\n failLocal(\n EXIT.ERROR,\n 'file_too_large_for_presigned',\n `${file} is ${(size / (1024 * 1024)).toFixed(0)} MB; the CLI's single-shot presigned upload is capped at 500 MB. Use a resumable tus upload (POST /api/v1/uploads/tus with any tus 1.0 client) or upload via https://transcribe.so instead.`\n );\n }\n if (size > WARN_BYTES) {\n process.stderr.write(\n `warning: ${(size / (1024 * 1024)).toFixed(0)} MB single-shot upload; the presigned URL expires in 900s. For flaky networks prefer the resumable tus flow (POST /api/v1/uploads/tus) or the web app.\\n`\n );\n }\n\n const contentType = resolveContentType(file, argv.contentType);\n\n let durationSeconds: number | undefined = argv.duration;\n if (durationSeconds === undefined) {\n const probed = probeDurationSeconds(file);\n if (probed === null) {\n failLocal(\n EXIT.USAGE,\n 'duration_required',\n 'Duration is required for uploads and ffprobe is not available (or could not read this file). Either pass --duration <seconds> or install ffmpeg so ffprobe is on PATH.'\n );\n }\n durationSeconds = probed;\n process.stderr.write(`ffprobe duration: ${durationSeconds.toFixed(1)}s\\n`);\n }\n\n const api = new TranscribeAPI(getConfig({ allowCustomHost: argv.allowCustomHost }));\n try {\n const res = await api.request('/uploads', {\n method: 'POST',\n body: {\n filename: basename(file),\n content_type: contentType,\n file_size: size,\n },\n });\n const uploadUrl: string = res.json.upload_url;\n process.stderr.write(`uploading ${basename(file)} (${size} bytes)...\\n`);\n const putResponse = await fetch(uploadUrl, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body: readFileSync(file),\n });\n if (!putResponse.ok) {\n const text = await putResponse.text();\n printJson({\n error: {\n code: 'upload_put_failed',\n message: `PUT to presigned URL failed with ${putResponse.status}: ${text.slice(0, 300)}`,\n },\n });\n process.stderr.write(`upload PUT failed (${putResponse.status})\\n`);\n process.exit(EXIT.TRANSIENT);\n }\n printJson({\n upload_id: res.json.upload_id,\n duration_seconds: durationSeconds,\n filename: basename(file),\n file_size: size,\n content_type: contentType,\n next: `transcribe-so create --source upload --upload-id ${res.json.upload_id} --duration ${durationSeconds}`,\n });\n } catch (err) {\n handleFailure(err);\n }\n}\n","import { writeFileSync } from 'fs';\nimport { ApiError, TranscribeAPI, handleFailure, sleep } from '../api';\nimport { EXIT, getConfig, printJson } from '../config';\nimport {\n captionFormatFor,\n isWaitableNotReady,\n notReadyRecovery,\n} from '../catalog';\n\nfunction apiFor(argv: any): TranscribeAPI {\n return new TranscribeAPI(getConfig({ allowCustomHost: argv.allowCustomHost }));\n}\n\nfunction writeRaw(raw: string): void {\n process.stdout.write(raw.endsWith('\\n') ? raw : raw + '\\n');\n}\n\n// The raw-output commands (`subtitles`, `transcript`, `captions`) print a\n// body, not JSON, so it can be piped to a file. Errors still print the JSON\n// envelope, so `| jq .` on a failure keeps working.\nexport async function subtitles(argv: any): Promise<void> {\n try {\n const raw = await apiFor(argv).requestRaw(\n `/transcriptions/${argv.id}/subtitles`,\n {\n format: argv.format,\n preset: argv.preset,\n speaker_labels: argv.speakerLabels ? true : undefined,\n mode: argv.mode,\n source: argv.source,\n }\n );\n writeRaw(raw);\n } catch (err) {\n handleFailure(err, { id: argv.id });\n }\n}\n\n// GET /transcript. The whole transcript as a raw body, never capped.\n//\n// 409 handling is the interesting part: `not_ready` carries a `reason` and\n// only `transcription_processing` can be fixed by waiting. Every other reason\n// exits non-zero immediately with the envelope on stdout, because retrying it\n// is a busy-loop that can never succeed.\nexport async function transcript(argv: any): Promise<void> {\n const api = apiFor(argv);\n const waitSeconds: number = argv.waitSeconds ?? 0;\n const deadline = Date.now() + waitSeconds * 1000;\n\n const query = {\n format: argv.format,\n // Both default to true server-side; only send the negation so the\n // request stays a plain GET of the documented default otherwise.\n speaker_labels: argv.speakerLabels === false ? false : undefined,\n timestamps: argv.timestamps === false ? false : undefined,\n };\n\n for (;;) {\n try {\n const raw = await api.requestRaw(`/transcriptions/${argv.id}/transcript`, query);\n if (argv.out) {\n writeFileSync(argv.out, raw.endsWith('\\n') ? raw : raw + '\\n');\n process.stderr.write(`wrote ${argv.out}\\n`);\n } else {\n writeRaw(raw);\n }\n return;\n } catch (err) {\n if (!(err instanceof ApiError) || err.code !== 'not_ready') handleFailure(err, { id: argv.id });\n const apiErr = err as ApiError;\n const remainingMs = deadline - Date.now();\n if (!isWaitableNotReady(apiErr.reason) || remainingMs <= 0) {\n // Non-waitable reason, or --wait-seconds exhausted (default 0).\n handleFailure(apiErr, { id: argv.id });\n }\n // Retry-After is only set for `transcription_processing`; 15s is the\n // server's documented value and the fallback if the header is missing.\n const retryAfter =\n apiErr.retryAfterSeconds && Number.isFinite(apiErr.retryAfterSeconds)\n ? Math.max(1, apiErr.retryAfterSeconds)\n : 15;\n const sleepSec = Math.min(retryAfter, Math.ceil(remainingMs / 1000));\n process.stderr.write(\n `not ready (status=${apiErr.envelope?.error?.status ?? '?'}); retrying in ${sleepSec}s ` +\n `(${Math.ceil(remainingMs / 1000)}s of --wait-seconds left)\\n`\n );\n await sleep(sleepSec * 1000);\n }\n }\n}\n\n// GET /timestamps, addressed by destination rather than by the wire's\n// `format` name. Prints `text` raw by default; `--json` prints the whole\n// envelope (warnings, ok_to_paste, thread[], constraints).\nexport async function captions(argv: any): Promise<void> {\n const api = apiFor(argv);\n let format: string;\n try {\n format = captionFormatFor(argv.for);\n } catch (err) {\n handleFailure(err, { id: argv.id });\n }\n\n const query = {\n format,\n variant: argv.variant,\n cta: argv.cta ? true : undefined,\n };\n\n const emit = (body: any, rawText: string): void => {\n if (argv.json) {\n writeRaw(rawText);\n return;\n }\n const text = body?.text;\n if (typeof text !== 'string') {\n printJson({\n error: {\n code: 'cli_error',\n message: 'the API response carried no `text` field; re-run with --json to see it',\n },\n });\n process.exit(EXIT.ERROR);\n }\n writeRaw(text);\n // Never let a silently shortened quote through unannounced: a truncated\n // quote is a misquote, and only stderr can carry that next to raw stdout.\n const warnings: string[] = Array.isArray(body?.warnings) ? body.warnings : [];\n for (const warning of warnings) process.stderr.write(`warning: ${warning}\\n`);\n if (body?.ok_to_paste === false) {\n process.stderr.write(\n 'warning: ok_to_paste=false - this output violates a hard platform rule; review before posting\\n'\n );\n }\n };\n\n let regenerated = false;\n for (;;) {\n try {\n const res = await api.request(`/transcriptions/${argv.id}/timestamps`, { query });\n emit(res.json, res.rawText);\n return;\n } catch (err) {\n if (!(err instanceof ApiError) || err.code !== 'not_ready') handleFailure(err, { id: argv.id });\n const apiErr = err as ApiError;\n if (apiErr.reason === 'artifact_missing' && argv.regenerate && !regenerated) {\n regenerated = true;\n process.stderr.write(\n `curated cache missing; regenerating once (POST /timestamps/regenerate, 30-90s)...\\n`\n );\n try {\n await api.request(`/transcriptions/${argv.id}/timestamps/regenerate`, {\n method: 'POST',\n });\n } catch (regenErr) {\n handleFailure(regenErr, { id: argv.id });\n }\n continue;\n }\n if (apiErr.reason === 'artifact_missing') {\n process.stderr.write(\n `Recovery: POST ${api.buildUrl(`/transcriptions/${argv.id}/timestamps/regenerate`)} once ` +\n `(or re-run with --regenerate), then retry this command.\\n`\n );\n } else {\n process.stderr.write(`Recovery: ${notReadyRecovery(apiErr.reason, argv.id)}\\n`);\n }\n // Both branches above already printed a Recovery line; the generic\n // not_ready hint would only repeat it.\n handleFailure(apiErr, { id: argv.id, suppressNotReadyHint: true });\n }\n }\n}\n\n// \"Who said X, and when.\" Library-wide by default; --id scopes it to one\n// transcription via the nested route (which 404s a foreign id instead of\n// silently returning nothing).\nexport async function search(argv: any): Promise<void> {\n const path =\n argv.id !== undefined ? `/transcriptions/${argv.id}/search` : '/search';\n try {\n const res = await apiFor(argv).request(path, {\n query: { q: argv.q, limit: argv.limit, offset: argv.offset },\n });\n writeRaw(res.rawText);\n if (res.json?.has_more) {\n const next = (res.json.offset ?? 0) + (res.json.limit ?? 0);\n process.stderr.write(\n `more hits available; continue with --offset ${next} (offset is capped at 1000 - narrow the query instead of deep-paging)\\n`\n );\n }\n } catch (err) {\n handleFailure(err, { id: argv.id });\n }\n}\n\nexport async function ask(argv: any): Promise<void> {\n try {\n const body: Record<string, unknown> = { question: argv.question };\n if (argv.topK !== undefined) body.top_k = argv.topK;\n const res = await apiFor(argv).request(`/transcriptions/${argv.id}/ask`, {\n method: 'POST',\n body,\n });\n writeRaw(res.rawText);\n } catch (err) {\n handleFailure(err, { id: argv.id });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mBAAkB;AAClB,qBAAwB;;;ACGjB,IAAM,cACX,OAAyC,UAAkB;;;ACL7D,oBAA2B;;;ACApB,IAAM,kBAAkB;AA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AAI;AACjC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,OAAO,MAAM;","names":["result","import_fs","apiFor","yargs"]}
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env bash
2
+ # Instagram caption from a finished transcription.
3
+ # Usage: ./ig-caption.sh <transcription-id> [variant]
4
+ # Requires: transcribe-so on PATH, TRANSCRIBE_API_KEY exported.
5
+ #
6
+ # `captions` prints the caption text RAW (like `subtitles` and `transcript`),
7
+ # so it pipes straight to a file. Warnings go to stderr — read them: a
8
+ # silently shortened quote is a misquote.
9
+
10
+ set -euo pipefail
11
+
12
+ ID="${1:?usage: ig-caption.sh <transcription-id> [variant]}"
13
+ # highlights = a 5-item text outline, the right shape for an IG caption.
14
+ # clips = 3 video clip ideas; quoted_sections = verbatim pull quotes.
15
+ VARIANT="${2:-highlights}"
16
+
17
+ # instagram maps to the API's `instagram_caption` format: no URLs, because
18
+ # Instagram does not make them clickable.
19
+ transcribe-so captions "$ID" --for instagram --variant "$VARIANT" > "ig-$ID.txt"
20
+
21
+ echo "wrote ig-$ID.txt" >&2
22
+ cat "ig-$ID.txt"
23
+
24
+ # If this exits non-zero with reason=artifact_missing, the curated cache was
25
+ # never generated for this transcription. One regeneration fixes it (30-90s):
26
+ #
27
+ # transcribe-so captions "$ID" --for instagram --variant "$VARIANT" --regenerate
28
+ #
29
+ # Other destinations, same command: x, threads, linkedin, youtube, spotify,
30
+ # apple_podcasts, markdown, plain. For X and Threads with
31
+ # --variant quoted_sections, --json gives you `thread[]` already split into
32
+ # per-post chunks:
33
+ #
34
+ # transcribe-so captions "$ID" --for x --variant quoted_sections --json \
35
+ # | jq -r '.thread[]'
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env bash
2
+ # "Who said X, and when" across every completed transcription in the library.
3
+ # Usage: ./who-said-what.sh "<query>" [transcription-id]
4
+ # Requires: transcribe-so on PATH, TRANSCRIBE_API_KEY exported, jq.
5
+ #
6
+ # Each hit is the SEGMENT containing the match, with its own speaker label and
7
+ # a deep-link url, so a quote is attributed to the line it came from rather
8
+ # than to the recording as a whole.
9
+
10
+ set -euo pipefail
11
+
12
+ QUERY="${1:?usage: who-said-what.sh \"<query>\" [transcription-id]}"
13
+ ID="${2:-}"
14
+
15
+ # Speaker labels are RECORDING-LOCAL: "SPEAKER_00" in one transcription is not
16
+ # the same person as "SPEAKER_00" in another, and null means unknown. Say
17
+ # "unknown speaker" rather than attributing the line.
18
+ fmt='.hits[] | "\(.transcription_id) \(.start_ms/1000 | floor)s \(.speaker // "unknown"): \(.text)\n \(.url)"'
19
+
20
+ if [ -n "$ID" ]; then
21
+ transcribe-so search "$QUERY" --id "$ID" --limit 20 | jq -r "$fmt"
22
+ else
23
+ transcribe-so search "$QUERY" --limit 20 | jq -r "$fmt"
24
+ fi
25
+
26
+ # Paging: there is no total count on purpose (counting every match is the
27
+ # expensive half of the query). Page on has_more:
28
+ #
29
+ # transcribe-so search "$QUERY" --limit 20 --offset 20
30
+ #
31
+ # offset is capped at 1000 — narrow the query or pass --id instead of deep
32
+ # paging. For the full text of one recording, `transcribe-so transcript <id>`
33
+ # returns every segment and is never capped.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "transcribe-so",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "transcribe.so CLI for agents and scripts: transcribe YouTube videos, podcasts, media URLs, and local files into speaker-labelled transcripts with chapters, sections, cited Q&A, and subtitles. Pure-JSON stdout.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -11,6 +11,7 @@
11
11
  "build": "tsup",
12
12
  "start": "node ./dist/index.js",
13
13
  "check:coverage": "npx -y tsx scripts/check-api-coverage.ts",
14
+ "test": "npx -y tsx scripts/test-units.ts",
14
15
  "prepublishOnly": "pnpm run build"
15
16
  },
16
17
  "files": [
@@ -18,6 +19,7 @@
18
19
  "examples",
19
20
  "README.md",
20
21
  "SKILL.md",
22
+ "CHANGELOG.md",
21
23
  "LICENSE"
22
24
  ],
23
25
  "keywords": [