transcribe-so 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +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,MAAM,KAAK,UAAU,OAAO,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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"]}
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env bash
2
+ # Batch-transcribe every audio/video file in a folder with transcribe-so.
3
+ # Usage: ./batch-transcribe.sh <folder> [max-usd-per-file]
4
+ # Requires: transcribe-so on PATH, TRANSCRIBE_API_KEY exported, jq.
5
+ # Sequential on purpose: at the concurrency cap, upload-sourced jobs are
6
+ # rejected (fair-use) rather than queued, so we run one job at a time.
7
+
8
+ set -euo pipefail
9
+
10
+ FOLDER="${1:?usage: batch-transcribe.sh <folder> [max-usd-per-file]}"
11
+ MAX_USD="${2:-5}"
12
+ OUT_DIR="$FOLDER/transcripts"
13
+ mkdir -p "$OUT_DIR"
14
+
15
+ for file in "$FOLDER"/*.{mp3,m4a,wav,flac,ogg,mp4,mov,webm,avi}; do
16
+ [ -e "$file" ] || continue
17
+ base=$(basename "$file")
18
+ out="$OUT_DIR/${base%.*}.json"
19
+ if [ -s "$out" ]; then
20
+ echo "skip (already done): $base" >&2
21
+ continue
22
+ fi
23
+
24
+ echo "uploading: $base" >&2
25
+ up=$(transcribe-so upload "$file")
26
+ upload_id=$(echo "$up" | jq -r .upload_id)
27
+ duration=$(echo "$up" | jq -r .duration_seconds)
28
+
29
+ echo "transcribing: $base (${duration}s, budget \$$MAX_USD)" >&2
30
+ if transcribe-so run --source upload \
31
+ --upload-id "$upload_id" \
32
+ --duration "$duration" \
33
+ --max-usd "$MAX_USD" > "$out"; then
34
+ echo "done: $out" >&2
35
+ else
36
+ code=$?
37
+ rm -f "$out"
38
+ # 6 = local budget refusal (raise MAX_USD), 4 = wallet/spend cap,
39
+ # 5 = transient (retry later). Stop on payment problems, keep going otherwise.
40
+ echo "failed ($code): $base" >&2
41
+ if [ "$code" -eq 4 ]; then
42
+ echo "wallet/spend-cap problem; stopping" >&2
43
+ exit 4
44
+ fi
45
+ fi
46
+ done
@@ -0,0 +1,14 @@
1
+ {
2
+ "_comment": "OpenClaw heartbeat entry: watch a folder and transcribe anything new on a schedule. Pair with examples/batch-transcribe.sh (idempotent: finished files are skipped via their transcripts/ output).",
3
+ "name": "transcribe-watch-folder",
4
+ "schedule": "*/15 * * * *",
5
+ "command": "bash examples/batch-transcribe.sh ~/Recordings 5",
6
+ "env": {
7
+ "TRANSCRIBE_API_KEY": "tsk_live_..."
8
+ },
9
+ "requires": {
10
+ "bins": ["transcribe-so", "jq"],
11
+ "env": ["TRANSCRIBE_API_KEY"]
12
+ },
13
+ "on_failure": "Exit 4 means the wallet or key spend cap needs attention; exit 5 is transient, retry next tick; exit 6 means raise the per-file budget in the command."
14
+ }
@@ -0,0 +1,42 @@
1
+ # Local file upload flow
2
+
3
+ `create` never accepts a filesystem path. Local files are uploaded first via a
4
+ short-lived presigned PUT, then submitted with `--source upload`.
5
+
6
+ ```bash
7
+ export TRANSCRIBE_API_KEY=tsk_live_...
8
+
9
+ # 1. Upload. Duration comes from --duration, or from ffprobe when installed.
10
+ # Files over 50 MB warn on stderr; over 500 MB the CLI refuses and points
11
+ # at the resumable tus flow (POST /api/v1/uploads/tus) or the web app.
12
+ UP=$(transcribe-so upload ./interview.mp3)
13
+ UPLOAD_ID=$(echo "$UP" | jq -r .upload_id)
14
+ DURATION=$(echo "$UP" | jq -r .duration_seconds)
15
+
16
+ # 2. Price it (free). Note: the quote's transcription_id is NOT the job id.
17
+ transcribe-so quote --source upload --upload-id "$UPLOAD_ID" --duration "$DURATION" \
18
+ | jq '{billed_minutes, retail_usd}'
19
+
20
+ # 3. Transcribe under an explicit budget (quote -> create -> wait -> result).
21
+ transcribe-so run --source upload \
22
+ --upload-id "$UPLOAD_ID" \
23
+ --duration "$DURATION" \
24
+ --max-usd 5 \
25
+ > result.json
26
+
27
+ jq '.chapters[] | {title, start_seconds}' result.json
28
+
29
+ # 4. Subtitles, if wanted (the one command that prints raw text, not JSON).
30
+ ID=$(jq -r .id result.json)
31
+ transcribe-so subtitles "$ID" --format srt > interview.srt
32
+ ```
33
+
34
+ Notes:
35
+
36
+ - The presigned URL expires in 900 seconds; `upload` PUTs immediately, so this
37
+ only matters if you script the raw API yourself.
38
+ - At the account's concurrency cap, `source=upload` jobs are REJECTED with a
39
+ fair-use error instead of queueing (URL sources queue FIFO). Wait for a
40
+ running job to finish, then submit again; do not hammer retry.
41
+ - Step 3's `run` uses only the create 202 id internally; you never touch the
42
+ quote's `transcription_id`.
@@ -0,0 +1,6 @@
1
+ {
2
+ "_comment": "Request body the CLI sends for `transcribe-so create --source youtube --url ... --language auto`. Same shape for POST /api/v1/quotes and POST /api/v1/transcriptions.",
3
+ "source": "youtube",
4
+ "url": "https://www.youtube.com/watch?v=jNQXAC9IVRw",
5
+ "language": "auto"
6
+ }
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "transcribe-so",
3
+ "version": "0.1.0",
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
+ "main": "dist/index.js",
6
+ "bin": {
7
+ "transcribe-so": "dist/index.js"
8
+ },
9
+ "scripts": {
10
+ "dev": "tsup --watch",
11
+ "build": "tsup",
12
+ "start": "node ./dist/index.js",
13
+ "check:coverage": "npx -y tsx scripts/check-api-coverage.ts",
14
+ "prepublishOnly": "pnpm run build"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "examples",
19
+ "README.md",
20
+ "SKILL.md",
21
+ "LICENSE"
22
+ ],
23
+ "keywords": [
24
+ "transcription",
25
+ "speech-to-text",
26
+ "asr",
27
+ "subtitles",
28
+ "srt",
29
+ "vtt",
30
+ "youtube",
31
+ "podcast",
32
+ "diarization",
33
+ "speaker-labels",
34
+ "chapters",
35
+ "cli",
36
+ "ai-agent",
37
+ "transcribe"
38
+ ],
39
+ "author": {
40
+ "name": "transcribe.so",
41
+ "email": "support@transcribe.so",
42
+ "url": "https://transcribe.so"
43
+ },
44
+ "license": "MIT",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/shsunmoonlee/transcribe-agent.git"
48
+ },
49
+ "homepage": "https://transcribe.so/agent",
50
+ "bugs": {
51
+ "url": "https://github.com/shsunmoonlee/transcribe-agent/issues"
52
+ },
53
+ "engines": {
54
+ "node": ">=18.0.0"
55
+ },
56
+ "packageManager": "pnpm@9.15.9",
57
+ "dependencies": {
58
+ "yargs": "^17.7.2"
59
+ },
60
+ "devDependencies": {
61
+ "@types/node": "^20.11.19",
62
+ "@types/yargs": "^17.0.32",
63
+ "tsup": "^8.5.1",
64
+ "typescript": "^5.3.3"
65
+ }
66
+ }