vocnu 0.0.0-stage → 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.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # Vocnu CLI and MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ AI voice-over and subtitles for your videos ([vocnu.com](https://vocnu.com)), from your terminal and from AI
4
+ assistants such as Claude. Node.js 20 or newer.
5
+
6
+ ## Sign in
7
+
8
+ Create a token in the Vocnu app: **Settings → API & MCP** ([app.vocnu.com](https://app.vocnu.com)). Then:
9
+
10
+ ```sh
11
+ npx vocnu login # paste the token; it is saved in ~/.config/vocnu/credentials.json
12
+ ```
13
+
14
+ or set `VOCNU_TOKEN` in the environment.
15
+
16
+ ## Translate a file
17
+
18
+ ```sh
19
+ npx vocnu translate film.mkv --to lt
20
+ ```
21
+
22
+ Vocnu uploads the file (up to 10 GB), shows the price in credits and asks before it starts, follows the job with its
23
+ progress and time left, and saves the results next to the file. Options:
24
+
25
+ | Option | |
26
+ | --- | --- |
27
+ | `--output video\|audio\|subtitles` | the video with the voice-over (default for video files), the voice-over audio, or subtitles only |
28
+ | `--from <lang>` | spoken language (detected by default) |
29
+ | `--voice female\|male` | narrator voice |
30
+ | `--format mp4\|mkv\|mov\|webm\|avi` | video file format (default: the upload's own, else MP4) |
31
+ | `--audio-format m4a\|mp3\|wav\|flac\|ogg` | voice-over audio format |
32
+ | `--burn-subtitles` | subtitles burned into the picture |
33
+ | `--out <dir>` | where the results go |
34
+ | `--yes` | start without confirming the price |
35
+ | `--no-wait` | start the job and return its id |
36
+
37
+ Other commands: `vocnu credits`, `vocnu languages`, `vocnu jobs`, `vocnu status <job>`, `vocnu download <job>`,
38
+ `vocnu cancel <job>`, `vocnu logout`.
39
+
40
+ ## Use Vocnu from Claude (MCP)
41
+
42
+ Claude Code:
43
+
44
+ ```sh
45
+ claude mcp add vocnu -e VOCNU_TOKEN=vocnu_... -- npx -y vocnu mcp
46
+ ```
47
+
48
+ Claude Desktop (`claude_desktop_config.json`) and other MCP clients:
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "vocnu": {
54
+ "command": "npx",
55
+ "args": ["-y", "vocnu", "mcp"],
56
+ "env": { "VOCNU_TOKEN": "vocnu_..." }
57
+ }
58
+ }
59
+ }
60
+ ```
61
+
62
+ Then ask, for example, “Dub ~/Videos/film.mkv into Lithuanian with Vocnu”. The assistant uploads the file
63
+ (`vocnu_upload_media`), tells you the price, starts the job only after you agree (`vocnu_start_job`), checks on it
64
+ (`vocnu_job_status`) and saves the files (`vocnu_download_results`). Also: `vocnu_languages`, `vocnu_credits`,
65
+ `vocnu_list_jobs`, `vocnu_cancel_job`.
66
+
67
+ ## Development
68
+
69
+ ```sh
70
+ npm ci
71
+ npm test
72
+ ```
73
+
74
+ The CLI talks to the same product API as the app with a personal API token (backend ADR 0015); `VOCNU_URL` points
75
+ it at another deployment.
package/bin/vocnu.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js'
3
+
4
+ process.exitCode = await main(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "vocnu",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Vocnu from your terminal and your AI assistant: AI voice-over and subtitles for your videos (CLI and MCP server).",
5
+ "type": "module",
6
+ "bin": {
7
+ "vocnu": "bin/vocnu.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "scripts": {
18
+ "test": "node --test test/*.test.js"
19
+ },
20
+ "keywords": [
21
+ "vocnu",
22
+ "voice-over",
23
+ "dubbing",
24
+ "subtitles",
25
+ "translation",
26
+ "mcp",
27
+ "cli"
28
+ ],
29
+ "homepage": "https://vocnu.com",
30
+ "license": "UNLICENSED",
31
+ "dependencies": {
32
+ "@modelcontextprotocol/sdk": "^1.32.1",
33
+ "zod": "^3.25.0"
34
+ }
35
+ }
package/src/api.js ADDED
@@ -0,0 +1,210 @@
1
+ // A small client of the Vocnu product API, authenticated with a personal API token (backend ADR 0015). Uploads go
2
+ // straight to storage with the presigned URLs the API returns: one PUT, or 64 MiB parts for a large file.
3
+ import { createWriteStream, openAsBlob } from 'node:fs'
4
+ import { mkdir, stat } from 'node:fs/promises'
5
+ import { basename, join } from 'node:path'
6
+ import { Readable } from 'node:stream'
7
+ import { pipeline } from 'node:stream/promises'
8
+
9
+ import { contentType } from './media.js'
10
+
11
+ const PART_CONCURRENCY = 4
12
+ const PART_ATTEMPTS = 3
13
+ const RETRY_DELAY_MS = 1000
14
+ const POLL_MS = 2000
15
+
16
+ export class VocnuError extends Error {
17
+ constructor(message, { code = 'error', status = 0 } = {}) {
18
+ super(message)
19
+ this.name = 'VocnuError'
20
+ this.code = code
21
+ this.status = status
22
+ }
23
+ }
24
+
25
+ export class VocnuApi {
26
+ constructor({ url, token, fetch = globalThis.fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
27
+ this.url = url
28
+ this.token = token
29
+ this.fetch = fetch
30
+ this.sleep = sleep
31
+ }
32
+
33
+ async request(method, path, body) {
34
+ if (!this.token) {
35
+ throw new VocnuError('Not signed in: run `vocnu login` or set VOCNU_TOKEN.', { code: 'unauthenticated' })
36
+ }
37
+ const response = await this.fetch(`${this.url}/api/v1${path}`, {
38
+ body: body === undefined ? undefined : JSON.stringify(body),
39
+ headers: {
40
+ Accept: 'application/json',
41
+ Authorization: `Bearer ${this.token}`,
42
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
43
+ },
44
+ method,
45
+ })
46
+ if (response.status === 204) return null
47
+ const data = await response.json().catch(() => null)
48
+ if (!response.ok) {
49
+ const error = data?.error
50
+ const message = response.status === 401 && !error?.message
51
+ ? 'The token was not accepted: create a new one in the Vocnu app.'
52
+ : error?.message ?? `Vocnu answered ${response.status}.`
53
+ throw new VocnuError(message, { code: error?.code ?? 'http_error', status: response.status })
54
+ }
55
+ return data
56
+ }
57
+
58
+ catalog() {
59
+ return this.request('GET', '/catalog')
60
+ }
61
+
62
+ credits() {
63
+ return this.request('GET', '/credits')
64
+ }
65
+
66
+ async source(id) {
67
+ return (await this.request('GET', `/sources/${encodeURIComponent(id)}`)).source
68
+ }
69
+
70
+ async jobs() {
71
+ return (await this.request('GET', '/jobs')).jobs
72
+ }
73
+
74
+ async job(id) {
75
+ return (await this.request('GET', `/jobs/${encodeURIComponent(id)}`)).job
76
+ }
77
+
78
+ async cancel(id) {
79
+ return (await this.request('POST', `/jobs/${encodeURIComponent(id)}/cancel`)).job
80
+ }
81
+
82
+ async createJob(job) {
83
+ return this.request('POST', '/jobs', { job })
84
+ }
85
+
86
+ // Uploads a local file and returns its source (status `probing` until Vocnu has analysed it).
87
+ async upload(path, { onProgress = () => {} } = {}) {
88
+ const { size } = await stat(path)
89
+ const created = await this.request('POST', '/sources', {
90
+ source: { byte_size: size, content_type: contentType(path) ?? 'application/octet-stream', filename: basename(path), kind: 'upload' },
91
+ })
92
+ const blob = await openAsBlob(path)
93
+ onProgress(0)
94
+ if (created.upload.method === 'MULTIPART') {
95
+ await this.#uploadParts(blob, created.upload, onProgress)
96
+ } else {
97
+ await this.#put(created.upload.url, blob, created.upload.headers)
98
+ }
99
+ onProgress(1)
100
+ return (await this.request('POST', `/sources/${encodeURIComponent(created.source.id)}/complete_upload`)).source
101
+ }
102
+
103
+ // Polls a source until Vocnu has analysed it; the ready source carries the quote.
104
+ async waitForSource(id, { onTick = () => {} } = {}) {
105
+ for (;;) {
106
+ const source = await this.source(id)
107
+ onTick(source)
108
+ if (source.status === 'ready') return source
109
+ if (source.status === 'failed') {
110
+ throw new VocnuError(source.error?.message ?? 'Vocnu could not read this file.', { code: source.error?.code ?? 'failed' })
111
+ }
112
+ await this.sleep(POLL_MS)
113
+ }
114
+ }
115
+
116
+ // Saves every output of a completed job into `directory`; returns the paths.
117
+ async download(job, directory, { onFile = () => {} } = {}) {
118
+ await mkdir(directory, { recursive: true })
119
+ const saved = []
120
+ for (const output of job.outputs) {
121
+ // The API redirects to a short-lived storage URL; the token must not travel there.
122
+ const answer = await this.fetch(`${this.url}${output.download_path}`, {
123
+ headers: { Authorization: `Bearer ${this.token}` },
124
+ redirect: 'manual',
125
+ })
126
+ const location = answer.headers.get('location')
127
+ if (answer.status < 300 || answer.status >= 400 || !location) {
128
+ const data = await answer.json().catch(() => null)
129
+ throw new VocnuError(data?.error?.message ?? `Download failed (${answer.status}).`, { code: data?.error?.code ?? 'download_failed', status: answer.status })
130
+ }
131
+ const file = await this.fetch(location)
132
+ if (!file.ok || !file.body) throw new VocnuError(`Download failed (${file.status}).`, { code: 'download_failed', status: file.status })
133
+ const name = filenameFrom(file.headers.get('content-disposition')) ?? `${output.kind}${extensionOf(location)}`
134
+ const target = join(directory, name)
135
+ await pipeline(Readable.fromWeb(file.body), createWriteStream(target))
136
+ saved.push(target)
137
+ onFile(target)
138
+ }
139
+ return saved
140
+ }
141
+
142
+ async #uploadParts(blob, upload, onProgress) {
143
+ const stop = new AbortController()
144
+ let next = 0
145
+ let done = 0
146
+ const send = async () => {
147
+ while (next < upload.parts.length && !stop.signal.aborted) {
148
+ const part = upload.parts[next]
149
+ next += 1
150
+ const start = (part.number - 1) * upload.part_size
151
+ await this.#put(part.url, blob.slice(start, start + upload.part_size), {}, stop.signal)
152
+ done += 1
153
+ onProgress(done / upload.parts.length)
154
+ }
155
+ }
156
+ await Promise.all(Array.from({ length: Math.min(PART_CONCURRENCY, upload.parts.length) }, async () => {
157
+ try {
158
+ await send()
159
+ } catch (error) {
160
+ stop.abort()
161
+ throw error
162
+ }
163
+ }))
164
+ }
165
+
166
+ // PUT with up to PART_ATTEMPTS tries after network and server errors.
167
+ async #put(url, body, headers = {}, signal = undefined) {
168
+ for (let attempt = 1; ; attempt += 1) {
169
+ let status = 0
170
+ try {
171
+ const response = await this.fetch(url, { body, headers, method: 'PUT', signal })
172
+ status = response.status
173
+ await response.arrayBuffer().catch(() => null)
174
+ if (response.ok) return
175
+ } catch (error) {
176
+ if (signal?.aborted) throw new VocnuError('Upload stopped.', { code: 'aborted' })
177
+ if (attempt >= PART_ATTEMPTS) throw new VocnuError(`Upload failed: ${error.message}`, { code: 'upload_failed' })
178
+ }
179
+ const retryable = status === 0 || status === 408 || status === 429 || status >= 500
180
+ if (!retryable || attempt >= PART_ATTEMPTS) {
181
+ throw new VocnuError(`Upload failed (${status}).`, { code: 'upload_failed', status })
182
+ }
183
+ await this.sleep(RETRY_DELAY_MS * attempt)
184
+ }
185
+ }
186
+ }
187
+
188
+ // The file name a storage response suggests, without any directory part.
189
+ export function filenameFrom(disposition) {
190
+ if (!disposition) return null
191
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)
192
+ let name = null
193
+ if (encoded) {
194
+ try {
195
+ name = decodeURIComponent(encoded[1].trim())
196
+ } catch {
197
+ name = null
198
+ }
199
+ }
200
+ name ??= /filename="([^"]+)"/i.exec(disposition)?.[1] ?? null
201
+ if (!name) return null
202
+ const safe = basename(name.replaceAll('\\', '/')).replace(/[\u0000-\u001f]/g, '').trim()
203
+ return safe && safe !== '.' && safe !== '..' ? safe : null
204
+ }
205
+
206
+ function extensionOf(url) {
207
+ const path = new URL(url).pathname
208
+ const dot = path.lastIndexOf('.')
209
+ return dot > path.lastIndexOf('/') ? path.slice(dot) : ''
210
+ }
package/src/cli.js ADDED
@@ -0,0 +1,293 @@
1
+ // The `vocnu` command: sign in with a personal API token, translate a local file (upload, quote, start, follow,
2
+ // download), look after jobs, or run the MCP server for Claude and other AI assistants.
3
+ import { createInterface } from 'node:readline'
4
+ import { stat } from 'node:fs/promises'
5
+ import { basename, dirname, extname, join, resolve } from 'node:path'
6
+ import { parseArgs } from 'node:util'
7
+
8
+ import { VocnuApi, VocnuError } from './api.js'
9
+ import { credentialsPath, DEFAULT_URL, forgetCredentials, loadConfig, saveCredentials } from './config.js'
10
+ import { formatTimeLeft, secondsLeft } from './estimate.js'
11
+ import { AUDIO_FORMATS, contentType, defaultVideoFormat, isVideo, OUTPUTS, productsFor, quotedCredits, VIDEO_FORMATS } from './media.js'
12
+ import { VERSION } from './version.js'
13
+
14
+ const JOB_POLL_MS = 5000
15
+
16
+ const HELP = `Vocnu ${VERSION}: AI voice-over and subtitles for your videos (https://vocnu.com).
17
+
18
+ Usage:
19
+ vocnu login [--token <token>] Save an API token (app.vocnu.com → Settings → API & MCP)
20
+ vocnu logout Forget the saved token
21
+ vocnu credits Your credit balance
22
+ vocnu languages Languages you can translate into
23
+ vocnu translate <file> --to <lang> Upload, see the price, translate and download the results
24
+ --output video|audio|subtitles What you get (default: video for a video file, else audio)
25
+ --from <lang> Spoken language (default: detected)
26
+ --voice female|male Narrator voice (default: female)
27
+ --format mp4|mkv|mov|webm|avi Video file format (default: the upload's, else mp4)
28
+ --audio-format m4a|mp3|wav|flac|ogg
29
+ --burn-subtitles Subtitles burned into the picture
30
+ --out <directory> Where the results go (default: next to the file)
31
+ --yes Start without asking to confirm the price
32
+ --no-wait Start the job and return its id
33
+ vocnu jobs Your recent jobs
34
+ vocnu status <job> Progress, time left and files of a job
35
+ vocnu download <job> [--out <dir>] Save the files of a finished job
36
+ vocnu cancel <job> Cancel a job (its credits are refunded)
37
+ vocnu mcp Run the Vocnu MCP server (for Claude and other assistants)
38
+
39
+ The token can also come from VOCNU_TOKEN.`
40
+
41
+ export async function main(argv, { env = process.env, out = process.stdout, err = process.stderr, fetch } = {}) {
42
+ const [command, ...rest] = argv
43
+ const print = (line = '') => out.write(`${line}\n`)
44
+ try {
45
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
46
+ print(HELP)
47
+ return 0
48
+ }
49
+ if (command === '--version' || command === '-v') {
50
+ print(VERSION)
51
+ return 0
52
+ }
53
+ if (command === 'mcp') {
54
+ const { serve } = await import('./mcp.js')
55
+ await serve({ env })
56
+ return 0
57
+ }
58
+ const config = await loadConfig(env)
59
+ const api = new VocnuApi({ fetch, token: config.token, url: config.url })
60
+ switch (command) {
61
+ case 'login':
62
+ return await login(rest, { api, config, env, print })
63
+ case 'logout':
64
+ await forgetCredentials(env)
65
+ print('Signed out: the saved token is gone (revoke it in the app if it may have leaked).')
66
+ return 0
67
+ case 'credits': {
68
+ const { balance } = await api.credits()
69
+ print(`${balance} credits`)
70
+ return 0
71
+ }
72
+ case 'languages':
73
+ return await languages(api, print)
74
+ case 'translate':
75
+ return await translate(rest, { api, err, out, print })
76
+ case 'jobs':
77
+ return await jobs(api, print)
78
+ case 'status':
79
+ return await status(rest, { api, print })
80
+ case 'download':
81
+ return await download(rest, { api, print })
82
+ case 'cancel': {
83
+ const job = await api.cancel(required(rest[0], 'job id'))
84
+ print(`Cancelled ${job.id}; its credits were refunded.`)
85
+ return 0
86
+ }
87
+ default:
88
+ err.write(`Unknown command: ${command}\n\n${HELP}\n`)
89
+ return 2
90
+ }
91
+ } catch (error) {
92
+ err.write(`${error instanceof VocnuError || error instanceof UsageError ? error.message : error.stack}\n`)
93
+ return error instanceof UsageError ? 2 : 1
94
+ }
95
+ }
96
+
97
+ class UsageError extends Error {}
98
+
99
+ function required(value, what) {
100
+ if (!value) throw new UsageError(`Missing ${what}. Run \`vocnu help\`.`)
101
+ return value
102
+ }
103
+
104
+ function parse(args, options) {
105
+ try {
106
+ return parseArgs({ allowPositionals: true, args, options, strict: true })
107
+ } catch (error) {
108
+ throw new UsageError(error.message)
109
+ }
110
+ }
111
+
112
+ async function login(args, { api, config, env, print }) {
113
+ const { values } = parse(args, { token: { type: 'string' }, url: { type: 'string' } })
114
+ const token = (values.token ?? (await askHidden('API token (from app.vocnu.com → Settings → API & MCP): '))).trim()
115
+ if (!token) throw new UsageError('No token given.')
116
+ const url = (values.url ?? config.url ?? DEFAULT_URL).replace(/\/+$/, '')
117
+ const checked = new VocnuApi({ fetch: api.fetch, token, url })
118
+ const { balance } = await checked.credits()
119
+ const path = await saveCredentials({ token, url }, env)
120
+ print(`Signed in (${balance} credits). Token saved in ${path}.`)
121
+ return 0
122
+ }
123
+
124
+ async function languages(api, print) {
125
+ const catalog = await api.catalog()
126
+ for (const language of catalog.languages ?? []) {
127
+ print(`${language.code.padEnd(6)} ${language.native ?? language.name}${language.voiceover === false ? ' (subtitles only)' : ''}`)
128
+ }
129
+ return 0
130
+ }
131
+
132
+ async function translate(args, { api, err, out, print }) {
133
+ const { positionals, values } = parse(args, {
134
+ 'audio-format': { type: 'string' },
135
+ 'burn-subtitles': { type: 'boolean' },
136
+ format: { type: 'string' },
137
+ from: { type: 'string' },
138
+ 'no-wait': { type: 'boolean' },
139
+ out: { type: 'string' },
140
+ output: { type: 'string' },
141
+ to: { type: 'string' },
142
+ voice: { type: 'string' },
143
+ yes: { type: 'boolean' },
144
+ })
145
+ const path = resolve(required(positionals[0], 'file'))
146
+ const target = required(values.to, '--to <language>')
147
+ const output = values.output ?? (isVideo(path) ? 'video' : 'audio')
148
+ const videoFormat = values.format ?? defaultVideoFormat(path)
149
+ const audioFormat = values['audio-format'] ?? 'm4a'
150
+ const voice = values.voice ?? 'female'
151
+ if (!OUTPUTS.includes(output)) throw new UsageError(`--output is one of ${OUTPUTS.join(', ')}.`)
152
+ if (!VIDEO_FORMATS.includes(videoFormat)) throw new UsageError(`--format is one of ${VIDEO_FORMATS.join(', ')}.`)
153
+ if (!AUDIO_FORMATS.includes(audioFormat)) throw new UsageError(`--audio-format is one of ${AUDIO_FORMATS.join(', ')}.`)
154
+ if (!['female', 'male'].includes(voice)) throw new UsageError('--voice is female or male.')
155
+ if (output === 'video' && !isVideo(path)) throw new UsageError('This is an audio file: use --output audio or subtitles.')
156
+ if (!contentType(path)) throw new UsageError('Vocnu takes video and audio files (MP4, MOV, MKV, WebM, MP3, M4A, WAV...).')
157
+ const { size } = await stat(path)
158
+
159
+ const progress = progressLine(out)
160
+ progress(`Uploading ${basename(path)} (${formatSize(size)})`)
161
+ let source = await api.upload(path, { onProgress: (fraction) => progress(`Uploading ${basename(path)}: ${percent(fraction)}`) })
162
+ progress('Analysing the file…')
163
+ source = await api.waitForSource(source.id)
164
+ progress.done(`Ready: ${source.title ?? basename(path)}, ${formatDuration(source.duration_seconds)}`)
165
+
166
+ const credits = quotedCredits(source.quote, output, videoFormat, values['burn-subtitles'])
167
+ const { balance } = await api.credits()
168
+ print(`Price: ${credits} credits (${source.quote.minutes} min). Balance: ${balance} credits.`)
169
+ if (!values.yes) {
170
+ if (!process.stdin.isTTY) throw new UsageError('Add --yes to start without confirming the price.')
171
+ const answer = (await ask('Start? [y/N] ')).trim().toLowerCase()
172
+ if (answer !== 'y' && answer !== 'yes') {
173
+ print('Not started; nothing was charged.')
174
+ return 0
175
+ }
176
+ }
177
+ const created = await api.createJob({
178
+ audio_format: audioFormat,
179
+ products: productsFor(output, values['burn-subtitles']),
180
+ source_id: source.id,
181
+ source_language: values.from ?? 'auto',
182
+ target_language: target,
183
+ video_format: videoFormat,
184
+ voice,
185
+ })
186
+ print(`Started job ${created.job.id} (${created.credit_balance} credits left).`)
187
+ if (values['no-wait']) return 0
188
+
189
+ const job = await follow(api, created.job.id, progress)
190
+ if (job.status !== 'completed') {
191
+ err.write(`Job ${job.status}: ${job.error?.message ?? 'no details'} (credits refunded).\n`)
192
+ return 1
193
+ }
194
+ const directory = resolve(values.out ?? join(dirname(path), `${basename(path, extname(path))} (vocnu ${target})`))
195
+ for (const file of await api.download(job, directory)) print(`Saved ${file}`)
196
+ return 0
197
+ }
198
+
199
+ async function follow(api, id, progress) {
200
+ for (;;) {
201
+ const job = await api.job(id)
202
+ if (!['queued', 'running'].includes(job.status)) {
203
+ progress.done(`Job ${job.status}.`)
204
+ return job
205
+ }
206
+ const left = formatTimeLeft(secondsLeft(job))
207
+ progress(job.status === 'queued' ? 'Waiting for a free worker…' : `${percent(job.progress)} ${job.stage ?? ''}${left ? ` · ${left}` : ''}`)
208
+ await api.sleep(JOB_POLL_MS)
209
+ }
210
+ }
211
+
212
+ async function jobs(api, print) {
213
+ for (const job of await api.jobs()) {
214
+ print(`${job.id} ${job.status.padEnd(9)} ${job.target_language.padEnd(5)} ${job.source.title ?? ''}`)
215
+ }
216
+ return 0
217
+ }
218
+
219
+ async function status(args, { api, print }) {
220
+ const job = await api.job(required(args[0], 'job id'))
221
+ print(`${job.id}: ${job.status}${job.stage ? ` (${job.stage})` : ''}, ${percent(job.progress)}`)
222
+ const left = formatTimeLeft(secondsLeft(job))
223
+ if (left) print(left)
224
+ if (job.error) print(`Error: ${job.error.message}`)
225
+ for (const output of job.outputs ?? []) print(`File: ${output.kind} (${formatSize(output.byte_size ?? 0)})`)
226
+ return 0
227
+ }
228
+
229
+ async function download(args, { api, print }) {
230
+ const { positionals, values } = parse(args, { out: { type: 'string' } })
231
+ const job = await api.job(required(positionals[0], 'job id'))
232
+ if (job.status !== 'completed') throw new UsageError(`Job ${job.id} is ${job.status}; files come when it is completed.`)
233
+ for (const file of await api.download(job, resolve(values.out ?? `vocnu-${job.id}`))) print(`Saved ${file}`)
234
+ return 0
235
+ }
236
+
237
+ // One status line that rewrites itself on a terminal and prints each change elsewhere.
238
+ function progressLine(out) {
239
+ let last = ''
240
+ const write = (text) => {
241
+ if (text === last) return
242
+ last = text
243
+ out.write(out.isTTY ? `\r\u001b[2K${text}` : `${text}\n`)
244
+ }
245
+ write.done = (text) => {
246
+ if (out.isTTY) out.write(`\r\u001b[2K${text}\n`)
247
+ else out.write(`${text}\n`)
248
+ last = ''
249
+ }
250
+ return write
251
+ }
252
+
253
+ function percent(fraction) {
254
+ return `${Math.round(Math.min(Math.max(fraction ?? 0, 0), 1) * 100)}%`
255
+ }
256
+
257
+ function formatSize(bytes) {
258
+ const units = ['B', 'KB', 'MB', 'GB']
259
+ let value = bytes
260
+ let unit = 0
261
+ while (value >= 1000 && unit < units.length - 1) {
262
+ value /= 1000
263
+ unit += 1
264
+ }
265
+ return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`
266
+ }
267
+
268
+ function formatDuration(seconds) {
269
+ const total = Math.round(seconds ?? 0)
270
+ const minutes = Math.floor(total / 60)
271
+ return minutes >= 60 ? `${Math.floor(minutes / 60)} h ${minutes % 60} min` : `${minutes} min ${total % 60} s`
272
+ }
273
+
274
+ function ask(question) {
275
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
276
+ return new Promise((done) => rl.question(question, (answer) => {
277
+ rl.close()
278
+ done(answer)
279
+ }))
280
+ }
281
+
282
+ function askHidden(question) {
283
+ if (!process.stdin.isTTY) throw new UsageError('Pass the token with --token or VOCNU_TOKEN.')
284
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true })
285
+ rl._writeToOutput = (text) => {
286
+ if (text.includes(question)) process.stdout.write(question)
287
+ }
288
+ return new Promise((done) => rl.question(question, (answer) => {
289
+ rl.close()
290
+ process.stdout.write('\n')
291
+ done(answer)
292
+ }))
293
+ }
package/src/config.js ADDED
@@ -0,0 +1,38 @@
1
+ // Where the CLI and MCP server find the API and the user's token: VOCNU_TOKEN and VOCNU_URL win over the
2
+ // credentials file that `vocnu login` writes (readable by the user only).
3
+ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { homedir } from 'node:os'
5
+ import { dirname, join } from 'node:path'
6
+
7
+ export const DEFAULT_URL = 'https://app.vocnu.com'
8
+
9
+ export function credentialsPath(env = process.env) {
10
+ const base = env.XDG_CONFIG_HOME || join(homedir(), '.config')
11
+ return join(base, 'vocnu', 'credentials.json')
12
+ }
13
+
14
+ export async function loadConfig(env = process.env) {
15
+ let saved = {}
16
+ try {
17
+ saved = JSON.parse(await readFile(credentialsPath(env), 'utf8'))
18
+ } catch {
19
+ saved = {}
20
+ }
21
+ return {
22
+ token: env.VOCNU_TOKEN || saved.token || null,
23
+ url: (env.VOCNU_URL || saved.url || DEFAULT_URL).replace(/\/+$/, ''),
24
+ }
25
+ }
26
+
27
+ export async function saveCredentials({ token, url }, env = process.env) {
28
+ const path = credentialsPath(env)
29
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
30
+ const data = { token, ...(url && url !== DEFAULT_URL ? { url } : {}) }
31
+ await writeFile(path, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 })
32
+ await chmod(path, 0o600)
33
+ return path
34
+ }
35
+
36
+ export async function forgetCredentials(env = process.env) {
37
+ await rm(credentialsPath(env), { force: true })
38
+ }
@@ -0,0 +1,24 @@
1
+ // The time a running job still needs, as the Vocnu app tells it (platform job-presentation selectSecondsLeft): the
2
+ // measured expectation for the media length and products at first, the job's own pace from 30 % on.
3
+ const OWN_PACE_FROM = 0.3
4
+
5
+ export function secondsLeft(job, now = Date.now()) {
6
+ if (job.status !== 'running' || !job.started_at) return null
7
+ const progress = Math.min(Math.max(job.progress, 0), 0.99)
8
+ const elapsed = Math.max((now - Date.parse(job.started_at)) / 1000, 0)
9
+ const minutes = (job.source?.duration_seconds ?? 0) / 60
10
+ const voiceover = job.products?.voiceover_audio || job.products?.voiceover_video
11
+ const expected = voiceover ? 100 + 18 * minutes : 40 + 6.5 * minutes
12
+ const byExpectation = expected * (1 - progress)
13
+ const byPace = progress > 0 ? (elapsed * (1 - progress)) / progress : byExpectation
14
+ const weight = Math.min(progress / OWN_PACE_FROM, 1)
15
+ return (1 - weight) * byExpectation + weight * byPace
16
+ }
17
+
18
+ export function formatTimeLeft(seconds) {
19
+ if (seconds === null || seconds === undefined) return ''
20
+ if (seconds < 60) return 'less than a minute left'
21
+ const minutes = Math.ceil(seconds / 60)
22
+ if (minutes < 60) return `about ${minutes} min left`
23
+ return `about ${Math.floor(minutes / 60)} h ${minutes % 60} min left`
24
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,159 @@
1
+ // The Vocnu MCP server (stdio): lets Claude and other AI assistants upload a local file, show its price, start a
2
+ // translation, follow it and save the results. Spending credits is a separate tool, so the assistant can confirm the
3
+ // price with the user first. stdout carries the protocol only.
4
+ import { homedir } from 'node:os'
5
+ import { join, resolve } from 'node:path'
6
+
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
9
+ import { z } from 'zod'
10
+
11
+ import { VocnuApi } from './api.js'
12
+ import { loadConfig } from './config.js'
13
+ import { formatTimeLeft, secondsLeft } from './estimate.js'
14
+ import { AUDIO_FORMATS, defaultVideoFormat, isVideo, OUTPUTS, productsFor, quotedCredits, VIDEO_FORMATS } from './media.js'
15
+ import { VERSION } from './version.js'
16
+
17
+ export async function serve({ env = process.env, transport = new StdioServerTransport() } = {}) {
18
+ const server = createServer(new VocnuApi(await loadConfig(env)))
19
+ await server.connect(transport)
20
+ return server
21
+ }
22
+
23
+ export function createServer(api, { cwd = process.cwd() } = {}) {
24
+ const server = new McpServer({ name: 'vocnu', version: VERSION })
25
+ const tool = (name, config, handler) => server.registerTool(name, config, async (args) => {
26
+ try {
27
+ return text(await handler(args ?? {}))
28
+ } catch (error) {
29
+ return { content: [{ text: error.message, type: 'text' }], isError: true }
30
+ }
31
+ })
32
+ const where = (path) => resolve(cwd, path.replace(/^~(?=$|\/)/, homedir()))
33
+
34
+ tool('vocnu_languages', {
35
+ annotations: { readOnlyHint: true },
36
+ description: 'Languages Vocnu translates into (code and name); some take subtitles only.',
37
+ title: 'Vocnu languages',
38
+ }, async () => {
39
+ const catalog = await api.catalog()
40
+ return (catalog.languages ?? []).map((l) => ({ code: l.code, name: l.name, voiceover: l.voiceover !== false }))
41
+ })
42
+
43
+ tool('vocnu_credits', {
44
+ annotations: { readOnlyHint: true },
45
+ description: "The user's Vocnu credit balance. One credit is about one minute of subtitles; a voice-over costs more.",
46
+ title: 'Vocnu credits',
47
+ }, async () => ({ balance: (await api.credits()).balance }))
48
+
49
+ tool('vocnu_upload_media', {
50
+ description: 'Upload a local video or audio file (up to 10 GB) to Vocnu, wait until it is analysed and return its '
51
+ + 'source_id, length and price in credits for each output. Nothing is charged until vocnu_start_job. '
52
+ + 'Large files take minutes to upload.',
53
+ inputSchema: { path: z.string().describe('Path of the video or audio file on this computer') },
54
+ title: 'Upload media to Vocnu',
55
+ }, async ({ path }) => {
56
+ const file = where(path)
57
+ const uploaded = await api.upload(file)
58
+ const source = await api.waitForSource(uploaded.id)
59
+ const { balance } = await api.credits()
60
+ return {
61
+ balance,
62
+ duration_seconds: source.duration_seconds,
63
+ has_video: source.has_video,
64
+ price_credits: {
65
+ audio: source.quote.options.voiceover_audio,
66
+ subtitles: source.quote.options.subtitles,
67
+ video: source.has_video ? quotedCredits(source.quote, 'video', defaultVideoFormat(file)) : null,
68
+ video_with_burned_subtitles: source.has_video ? source.quote.options.voiceover_video_burned_subtitles : null,
69
+ },
70
+ source_id: source.id,
71
+ suggested_video_format: isVideo(file) ? defaultVideoFormat(file) : null,
72
+ title: source.title,
73
+ }
74
+ })
75
+
76
+ tool('vocnu_start_job', {
77
+ description: 'Start translating an uploaded file (source_id from vocnu_upload_media). Spends the quoted credits '
78
+ + '(refunded if the job fails or is cancelled): confirm the price with the user before calling. output "video" '
79
+ + 'is the video with the voice-over, "audio" the voice-over audio, "subtitles" subtitles only; every output '
80
+ + 'also includes subtitles.',
81
+ inputSchema: {
82
+ audio_format: z.enum(AUDIO_FORMATS).optional().describe('Voice-over audio format (default m4a)'),
83
+ burn_subtitles: z.boolean().optional().describe('Burn the subtitles into the picture (video only)'),
84
+ output: z.enum(OUTPUTS),
85
+ source_id: z.string(),
86
+ source_language: z.string().optional().describe('Spoken language code, if known (default: detected)'),
87
+ target_language: z.string().describe('Language code to translate into, e.g. lt, en, de (see vocnu_languages)'),
88
+ video_format: z.enum(VIDEO_FORMATS).optional().describe('Video file format (default mp4)'),
89
+ voice: z.enum(['female', 'male']).optional().describe('Narrator voice (default female)'),
90
+ },
91
+ title: 'Start a Vocnu translation',
92
+ }, async (input) => {
93
+ const created = await api.createJob({
94
+ audio_format: input.audio_format ?? 'm4a',
95
+ products: productsFor(input.output, input.burn_subtitles),
96
+ source_id: input.source_id,
97
+ source_language: input.source_language ?? 'auto',
98
+ target_language: input.target_language,
99
+ video_format: input.video_format ?? 'mp4',
100
+ voice: input.voice ?? 'female',
101
+ })
102
+ return { balance_after: created.credit_balance, job_id: created.job.id, status: created.job.status }
103
+ })
104
+
105
+ tool('vocnu_job_status', {
106
+ annotations: { readOnlyHint: true },
107
+ description: 'Status of a Vocnu job: progress, time left, error, and its files once completed. Jobs take '
108
+ + 'roughly a third of the media length; check again later rather than waiting in a loop.',
109
+ inputSchema: { job_id: z.string() },
110
+ title: 'Vocnu job status',
111
+ }, async ({ job_id }) => summary(await api.job(job_id)))
112
+
113
+ tool('vocnu_list_jobs', {
114
+ annotations: { readOnlyHint: true },
115
+ description: "The user's recent Vocnu jobs, newest first.",
116
+ title: 'Vocnu jobs',
117
+ }, async () => (await api.jobs()).map(summary))
118
+
119
+ tool('vocnu_download_results', {
120
+ description: 'Save the files of a completed Vocnu job into a directory on this computer and return their paths.',
121
+ inputSchema: {
122
+ directory: z.string().optional().describe('Where to save (default: ./vocnu-<job id>)'),
123
+ job_id: z.string(),
124
+ },
125
+ title: 'Download Vocnu results',
126
+ }, async ({ directory, job_id }) => {
127
+ const job = await api.job(job_id)
128
+ if (job.status !== 'completed') throw new Error(`Job ${job_id} is ${job.status}; its files come when it is completed.`)
129
+ return { files: await api.download(job, where(directory ?? join('.', `vocnu-${job_id}`))) }
130
+ })
131
+
132
+ tool('vocnu_cancel_job', {
133
+ annotations: { destructiveHint: true },
134
+ description: 'Cancel a queued or running Vocnu job; its credits are refunded.',
135
+ inputSchema: { job_id: z.string() },
136
+ title: 'Cancel a Vocnu job',
137
+ }, async ({ job_id }) => summary(await api.cancel(job_id)))
138
+
139
+ return server
140
+ }
141
+
142
+ function summary(job) {
143
+ return {
144
+ error: job.error,
145
+ files: (job.outputs ?? []).map((o) => ({ bytes: o.byte_size, kind: o.kind, language: o.language })),
146
+ job_id: job.id,
147
+ output: job.products?.voiceover_video ? 'video' : job.products?.voiceover_audio ? 'audio' : 'subtitles',
148
+ progress_percent: Math.round((job.progress ?? 0) * 100),
149
+ stage: job.stage,
150
+ status: job.status,
151
+ target_language: job.target_language,
152
+ time_left: formatTimeLeft(secondsLeft(job)) || null,
153
+ title: job.source?.title ?? null,
154
+ }
155
+ }
156
+
157
+ function text(data) {
158
+ return { content: [{ text: JSON.stringify(data, null, 2), type: 'text' }] }
159
+ }
package/src/media.js ADDED
@@ -0,0 +1,44 @@
1
+ // The media types the Vocnu API accepts, by file extension (backend SourcesController::MEDIA_EXTENSIONS).
2
+ import { extname } from 'node:path'
3
+
4
+ const TYPES = {
5
+ '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.mkv': 'video/x-matroska', '.webm': 'video/webm',
6
+ '.avi': 'video/x-msvideo', '.m4v': 'video/x-m4v', '.mpg': 'video/mpeg', '.mpeg': 'video/mpeg', '.ts': 'video/mp2t',
7
+ '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.aac': 'audio/aac', '.ogg': 'audio/ogg',
8
+ '.opus': 'audio/opus', '.flac': 'audio/flac', '.wma': 'audio/x-ms-wma',
9
+ }
10
+ export const VIDEO_FORMATS = ['mp4', 'mkv', 'mov', 'webm', 'avi']
11
+ export const AUDIO_FORMATS = ['m4a', 'mp3', 'wav', 'flac', 'ogg']
12
+ export const OUTPUTS = ['video', 'audio', 'subtitles']
13
+
14
+ export function contentType(path) {
15
+ return TYPES[extname(path).toLowerCase()] ?? null
16
+ }
17
+
18
+ export function isVideo(path) {
19
+ return (contentType(path) ?? '').startsWith('video/')
20
+ }
21
+
22
+ // The video container of the upload when it is one Vocnu can write (an MKV stays an MKV), else MP4.
23
+ export function defaultVideoFormat(path) {
24
+ const format = extname(path).slice(1).toLowerCase()
25
+ return VIDEO_FORMATS.includes(format) ? format : 'mp4'
26
+ }
27
+
28
+ // API products for an output: a video implies the voice-over audio and subtitles, as the API does.
29
+ export function productsFor(output, burnSubtitles = false) {
30
+ return {
31
+ burned_subtitles: output === 'video' && burnSubtitles,
32
+ subtitles: true,
33
+ voiceover_audio: output !== 'subtitles',
34
+ voiceover_video: output === 'video',
35
+ }
36
+ }
37
+
38
+ // Credits the quote asks for this output and video format.
39
+ export function quotedCredits(quote, output, videoFormat, burnSubtitles = false) {
40
+ if (output === 'subtitles') return quote.options.subtitles
41
+ if (output === 'audio') return quote.options.voiceover_audio
42
+ if (burnSubtitles) return quote.options.voiceover_video_burned_subtitles
43
+ return quote.video_formats?.[videoFormat]?.credits ?? quote.options.voiceover_video
44
+ }
package/src/version.js ADDED
@@ -0,0 +1,3 @@
1
+ import { createRequire } from 'node:module'
2
+
3
+ export const VERSION = createRequire(import.meta.url)('../package.json').version