@inworld/cli 1.0.0-rc.3 → 1.0.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 CHANGED
@@ -66816,13 +66816,15 @@ function hasStoredCredentials() {
66816
66816
  return typeof s.firebaseRefreshToken === "string" && s.firebaseRefreshToken.length > 0;
66817
66817
  }
66818
66818
  async function hasUsableAuthCredentials() {
66819
+ if (process.env.INWORLD_API_KEY?.trim()) return true;
66819
66820
  if (hasStoredCredentials()) return true;
66820
66821
  try {
66821
66822
  const c = await readStoredCredentials();
66822
- return !!c?.refreshToken?.trim();
66823
+ if (c?.refreshToken?.trim()) return true;
66824
+ if (c?.apiKey?.trim()) return true;
66823
66825
  } catch {
66824
- return false;
66825
66826
  }
66827
+ return false;
66826
66828
  }
66827
66829
  var TIME_DIFF_MS;
66828
66830
  var init_session = __esm({
@@ -67294,6 +67296,139 @@ var init_studio_config = __esm({
67294
67296
  }
67295
67297
  });
67296
67298
 
67299
+ // src/mcp/inworld/studio-api.ts
67300
+ async function requireApiKey2() {
67301
+ const fromEnv = process.env.INWORLD_API_KEY?.trim();
67302
+ if (fromEnv) return fromEnv;
67303
+ try {
67304
+ const creds = await readStoredCredentials();
67305
+ const k = creds?.apiKey?.trim();
67306
+ if (k) return k;
67307
+ } catch {
67308
+ }
67309
+ throw new Error(
67310
+ "No Inworld API key available. Set INWORLD_API_KEY in the environment, or run `inworld workspace select-key` from a terminal to bind one to the local credential store (shared with this MCP server)."
67311
+ );
67312
+ }
67313
+ function studioBase() {
67314
+ return getStudioApiUrl().replace(/\/$/, "");
67315
+ }
67316
+ function parseJson(text, label, status) {
67317
+ if (!text) return {};
67318
+ try {
67319
+ return JSON.parse(text);
67320
+ } catch {
67321
+ throw new Error(
67322
+ `${label}: expected JSON (HTTP ${status}): ${text.slice(0, 400)}`
67323
+ );
67324
+ }
67325
+ }
67326
+ function extractMessage(data, fallbackStatus) {
67327
+ if (data && typeof data === "object") {
67328
+ const o = data;
67329
+ if (typeof o.message === "string") return o.message;
67330
+ const inner = o.error;
67331
+ if (inner && typeof inner === "object" && typeof inner.message === "string") {
67332
+ return inner.message;
67333
+ }
67334
+ }
67335
+ return `HTTP ${fallbackStatus}`;
67336
+ }
67337
+ async function studioApiGet(pathAndQuery, label = "Studio API") {
67338
+ const apiKey = await requireApiKey2();
67339
+ const path8 = pathAndQuery.startsWith("/") ? pathAndQuery : `/${pathAndQuery}`;
67340
+ const res = await fetch(`${studioBase()}${path8}`, {
67341
+ method: "GET",
67342
+ headers: {
67343
+ Authorization: `Basic ${apiKey}`,
67344
+ Accept: "application/json"
67345
+ }
67346
+ });
67347
+ const text = await res.text();
67348
+ const data = parseJson(text, label, res.status);
67349
+ if (!res.ok) {
67350
+ throw new Error(`${label}: ${extractMessage(data, res.status)}`);
67351
+ }
67352
+ return data;
67353
+ }
67354
+ async function studioApiPostJson(path8, body, label = "Studio API") {
67355
+ const apiKey = await requireApiKey2();
67356
+ const p2 = path8.startsWith("/") ? path8 : `/${path8}`;
67357
+ const res = await fetch(`${studioBase()}${p2}`, {
67358
+ method: "POST",
67359
+ headers: {
67360
+ Authorization: `Basic ${apiKey}`,
67361
+ "Content-Type": "application/json",
67362
+ Accept: "application/json"
67363
+ },
67364
+ body: JSON.stringify(body)
67365
+ });
67366
+ const text = await res.text();
67367
+ const data = parseJson(text, label, res.status);
67368
+ if (!res.ok) {
67369
+ throw new Error(`${label}: ${extractMessage(data, res.status)}`);
67370
+ }
67371
+ return data;
67372
+ }
67373
+ var init_studio_api = __esm({
67374
+ "src/mcp/inworld/studio-api.ts"() {
67375
+ "use strict";
67376
+ init_dist4();
67377
+ init_studio_config();
67378
+ }
67379
+ });
67380
+
67381
+ // src/mcp/llm/chat.ts
67382
+ async function completeChat(req) {
67383
+ const model = req.model?.trim();
67384
+ if (!model) {
67385
+ throw new Error("model is required (e.g. 'gpt-4o-mini')");
67386
+ }
67387
+ if (!req.messages?.length) {
67388
+ throw new Error("messages array is required and must be non-empty");
67389
+ }
67390
+ const body = {
67391
+ servingId: {
67392
+ modelId: {
67393
+ model,
67394
+ serviceProvider: req.serviceProvider ?? "SERVICE_PROVIDER_OPENAI"
67395
+ },
67396
+ // The endpoint rejects requests with an empty user id; default to a
67397
+ // stable string when the caller doesn't provide one.
67398
+ userId: req.userId ?? "inworld-mcp"
67399
+ },
67400
+ messages: req.messages,
67401
+ textGenerationConfig: {
67402
+ ...req.maxTokens !== void 0 ? { maxTokens: req.maxTokens } : {},
67403
+ ...req.temperature !== void 0 ? { temperature: req.temperature } : {},
67404
+ ...req.topP !== void 0 ? { topP: req.topP } : {},
67405
+ stream: false
67406
+ }
67407
+ };
67408
+ return studioApiPostJson(
67409
+ "/llm/v1alpha/completions:completeChat",
67410
+ body,
67411
+ "LLM completeChat"
67412
+ );
67413
+ }
67414
+ var init_chat = __esm({
67415
+ "src/mcp/llm/chat.ts"() {
67416
+ "use strict";
67417
+ init_studio_api();
67418
+ }
67419
+ });
67420
+
67421
+ // src/mcp/llm/models.ts
67422
+ async function listModels() {
67423
+ return studioApiGet("/llm/v1alpha/models", "LLM listModels");
67424
+ }
67425
+ var init_models = __esm({
67426
+ "src/mcp/llm/models.ts"() {
67427
+ "use strict";
67428
+ init_studio_api();
67429
+ }
67430
+ });
67431
+
67297
67432
  // src/mcp/workspace/gateway.ts
67298
67433
  function workspaceResourceName(workspaceId) {
67299
67434
  const id = workspaceId.trim();
@@ -67418,12 +67553,12 @@ var init_engine_session = __esm({
67418
67553
  });
67419
67554
 
67420
67555
  // src/mcp/router/gateway.ts
67421
- function studioBase() {
67556
+ function studioBase2() {
67422
67557
  return getStudioApiUrl().replace(/\/$/, "");
67423
67558
  }
67424
67559
  async function studioEngineJson(workspaceId, method, path8, body) {
67425
67560
  const engine = await fetchWorkspaceEngineSession(workspaceId);
67426
- const url = `${studioBase()}${path8.startsWith("/") ? path8 : `/${path8}`}`;
67561
+ const url = `${studioBase2()}${path8.startsWith("/") ? path8 : `/${path8}`}`;
67427
67562
  const headers = {
67428
67563
  Authorization: `Bearer ${engine.token}`,
67429
67564
  Accept: "application/json"
@@ -67586,6 +67721,46 @@ var init_gateway2 = __esm({
67586
67721
  }
67587
67722
  });
67588
67723
 
67724
+ // src/mcp/stt/transcribe.ts
67725
+ async function transcribeSpeech(req) {
67726
+ if (!req.audioBase64 || !req.audioBase64.trim()) {
67727
+ throw new Error("audioBase64 is required (raw base64 \u2014 no data: prefix)");
67728
+ }
67729
+ const body = {
67730
+ transcribeConfig: {
67731
+ modelId: req.modelId ?? "inworld/inworld-stt-1",
67732
+ audioEncoding: req.audioEncoding ?? "AUTO_DETECT",
67733
+ ...req.language ? { language: req.language } : {}
67734
+ },
67735
+ audioData: { content: req.audioBase64.trim() }
67736
+ };
67737
+ return studioApiPostJson("/stt/v1/transcribe", body, "STT transcribe");
67738
+ }
67739
+ var init_transcribe = __esm({
67740
+ "src/mcp/stt/transcribe.ts"() {
67741
+ "use strict";
67742
+ init_studio_api();
67743
+ }
67744
+ });
67745
+
67746
+ // src/mcp/tts/preview.ts
67747
+ async function getVoicePreviewV1(voiceId, modelId = DEFAULT_TTS_MODEL) {
67748
+ const id = voiceId.trim();
67749
+ if (!id) {
67750
+ throw new Error("voiceId is required");
67751
+ }
67752
+ const qs = new URLSearchParams({ voice_id: id, model_id: modelId });
67753
+ return studioApiGet(`/tts/v1/voice:preview?${qs.toString()}`, "TTS preview");
67754
+ }
67755
+ var DEFAULT_TTS_MODEL;
67756
+ var init_preview = __esm({
67757
+ "src/mcp/tts/preview.ts"() {
67758
+ "use strict";
67759
+ init_studio_api();
67760
+ DEFAULT_TTS_MODEL = "inworld-tts-1.5-max";
67761
+ }
67762
+ });
67763
+
67589
67764
  // src/mcp/voice/design.ts
67590
67765
  async function designVoiceV1(workspaceId, request) {
67591
67766
  const parent = workspaceResourceName(workspaceId);
@@ -67673,6 +67848,24 @@ var init_design_response = __esm({
67673
67848
  }
67674
67849
  });
67675
67850
 
67851
+ // src/mcp/voice/get.ts
67852
+ async function getVoiceV1(voiceId) {
67853
+ const id = voiceId.trim();
67854
+ if (!id) {
67855
+ throw new Error("voiceId is required");
67856
+ }
67857
+ return studioApiGet(
67858
+ `/voices/v1/voices/${encodeURIComponent(id)}`,
67859
+ "Voice get"
67860
+ );
67861
+ }
67862
+ var init_get = __esm({
67863
+ "src/mcp/voice/get.ts"() {
67864
+ "use strict";
67865
+ init_studio_api();
67866
+ }
67867
+ });
67868
+
67676
67869
  // src/mcp/voice/list-v1.ts
67677
67870
  async function listVoicesV1(workspaceId) {
67678
67871
  const parent = workspaceResourceName(workspaceId);
@@ -68249,6 +68442,145 @@ function createMcpServer() {
68249
68442
  }
68250
68443
  }
68251
68444
  );
68445
+ server.registerTool(
68446
+ "inworld_tts_voice_preview",
68447
+ {
68448
+ description: "Fetch a short, server-side audio preview for an existing voice (GET /tts/v1/voice:preview). Not metered or billed \u2014 ideal for catalog browsing. Returns base64 MP3 audio. Uses the workspace API key (Basic auth); requires inworld auth login + inworld workspace select-key or INWORLD_API_KEY.",
68449
+ inputSchema: external_exports.object({
68450
+ voiceId: external_exports.string().min(1).describe(
68451
+ "Voice ID (e.g. Ashley, Dennis). See inworld_voice_catalog_list."
68452
+ ),
68453
+ modelId: external_exports.string().optional().describe("Optional TTS model id (e.g. inworld-tts-2)")
68454
+ })
68455
+ },
68456
+ async ({ voiceId, modelId }) => {
68457
+ try {
68458
+ const data = await getVoicePreviewV1(voiceId, modelId);
68459
+ return {
68460
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
68461
+ };
68462
+ } catch (e) {
68463
+ const msg = e instanceof Error ? e.message : String(e);
68464
+ return {
68465
+ content: [{ type: "text", text: `Error: ${msg}` }],
68466
+ isError: true
68467
+ };
68468
+ }
68469
+ }
68470
+ );
68471
+ server.registerTool(
68472
+ "inworld_voice_get",
68473
+ {
68474
+ description: "Get a single voice's metadata by ID (GET /voices/v1/voices/{voiceId}). Read-only. Uses the workspace API key (Basic auth).",
68475
+ inputSchema: external_exports.object({
68476
+ voiceId: external_exports.string().min(1).describe("Voice ID (e.g. Dennis or workspace_id__voice_name).")
68477
+ })
68478
+ },
68479
+ async ({ voiceId }) => {
68480
+ try {
68481
+ const data = await getVoiceV1(voiceId);
68482
+ return {
68483
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
68484
+ };
68485
+ } catch (e) {
68486
+ const msg = e instanceof Error ? e.message : String(e);
68487
+ return {
68488
+ content: [{ type: "text", text: `Error: ${msg}` }],
68489
+ isError: true
68490
+ };
68491
+ }
68492
+ }
68493
+ );
68494
+ server.registerTool(
68495
+ "inworld_stt_transcribe",
68496
+ {
68497
+ description: "Transcribe an audio clip via the Inworld Speech-to-Text API (POST /stt/v1/transcribe). The whole audio must fit in one request; for long files, chunk client-side. Pass base64-encoded audio bytes (no `data:` prefix). Uses the workspace API key (Basic auth).",
68498
+ inputSchema: external_exports.object({
68499
+ audioBase64: external_exports.string().min(1).describe("Base64-encoded audio bytes (raw \u2014 no data: prefix)."),
68500
+ language: external_exports.string().optional().describe("BCP-47 language code, e.g. en-US"),
68501
+ audioEncoding: external_exports.enum(["AUTO_DETECT", "LINEAR16", "MP3", "OGG_OPUS", "FLAC"]).optional().describe(
68502
+ "Audio encoding. Default AUTO_DETECT works for most self-describing formats."
68503
+ ),
68504
+ modelId: external_exports.string().optional().describe("STT model id (default: inworld/inworld-stt-1)")
68505
+ })
68506
+ },
68507
+ async (args) => {
68508
+ try {
68509
+ const data = await transcribeSpeech(args);
68510
+ return {
68511
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
68512
+ };
68513
+ } catch (e) {
68514
+ const msg = e instanceof Error ? e.message : String(e);
68515
+ return {
68516
+ content: [{ type: "text", text: `Error: ${msg}` }],
68517
+ isError: true
68518
+ };
68519
+ }
68520
+ }
68521
+ );
68522
+ server.registerTool(
68523
+ "inworld_llm_chat",
68524
+ {
68525
+ description: "Generate a chat completion via the Inworld LLM Router (POST /llm/v1alpha/completions:completeChat). Non-streaming. Pass model id + service provider + a list of role/content messages. Uses the workspace API key (Basic auth).",
68526
+ inputSchema: external_exports.object({
68527
+ model: external_exports.string().min(1).describe("Model id (e.g. gpt-4o-mini, gemini-2.5-flash)"),
68528
+ serviceProvider: external_exports.string().optional().describe(
68529
+ "Service provider (SERVICE_PROVIDER_OPENAI, SERVICE_PROVIDER_GOOGLE, ...). Default: SERVICE_PROVIDER_OPENAI."
68530
+ ),
68531
+ userId: external_exports.string().optional().describe("Stable user id for analytics/routing"),
68532
+ messages: external_exports.array(
68533
+ external_exports.object({
68534
+ role: external_exports.enum([
68535
+ "MESSAGE_ROLE_SYSTEM",
68536
+ "MESSAGE_ROLE_USER",
68537
+ "MESSAGE_ROLE_ASSISTANT",
68538
+ "MESSAGE_ROLE_TOOL"
68539
+ ]),
68540
+ content: external_exports.string()
68541
+ })
68542
+ ).min(1).describe("Conversation messages in order"),
68543
+ maxTokens: external_exports.number().int().positive().optional().describe("Maximum tokens in response"),
68544
+ temperature: external_exports.number().min(0).max(2).optional(),
68545
+ topP: external_exports.number().min(0).max(1).optional()
68546
+ })
68547
+ },
68548
+ async (args) => {
68549
+ try {
68550
+ const data = await completeChat(args);
68551
+ return {
68552
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
68553
+ };
68554
+ } catch (e) {
68555
+ const msg = e instanceof Error ? e.message : String(e);
68556
+ return {
68557
+ content: [{ type: "text", text: `Error: ${msg}` }],
68558
+ isError: true
68559
+ };
68560
+ }
68561
+ }
68562
+ );
68563
+ server.registerTool(
68564
+ "inworld_llm_list_models",
68565
+ {
68566
+ description: "List LLM models available to your account, with capabilities and pricing (GET /llm/v1alpha/models). Read-only. Uses the workspace API key (Basic auth).",
68567
+ inputSchema: external_exports.object({})
68568
+ },
68569
+ async () => {
68570
+ try {
68571
+ const data = await listModels();
68572
+ return {
68573
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
68574
+ };
68575
+ } catch (e) {
68576
+ const msg = e instanceof Error ? e.message : String(e);
68577
+ return {
68578
+ content: [{ type: "text", text: `Error: ${msg}` }],
68579
+ isError: true
68580
+ };
68581
+ }
68582
+ }
68583
+ );
68252
68584
  server.registerTool(
68253
68585
  "inworld_voice_catalog_list",
68254
68586
  {
@@ -68838,9 +69170,14 @@ var init_mcp2 = __esm({
68838
69170
  init_session();
68839
69171
  init_session_refresh();
68840
69172
  init_summary();
69173
+ init_chat();
69174
+ init_models();
68841
69175
  init_gateway2();
69176
+ init_transcribe();
69177
+ init_preview();
68842
69178
  init_design();
68843
69179
  init_design_response();
69180
+ init_get();
68844
69181
  init_list_v1();
68845
69182
  init_publish();
68846
69183
  init_studio_gateway();
@@ -69178,6 +69515,39 @@ var require_play_sound = __commonJS({
69178
69515
  }
69179
69516
  });
69180
69517
 
69518
+ // src/utils/audio_player.ts
69519
+ var audio_player_exports = {};
69520
+ __export(audio_player_exports, {
69521
+ cleanupTempFile: () => cleanupTempFile,
69522
+ playFile: () => playFile
69523
+ });
69524
+ import { unlink } from "fs/promises";
69525
+ async function playFile(filePath) {
69526
+ try {
69527
+ const player = (await Promise.resolve().then(() => __toESM(require_play_sound(), 1))).default();
69528
+ await new Promise((resolve3, reject) => {
69529
+ player.play(filePath, (err) => {
69530
+ if (err) reject(err);
69531
+ else resolve3();
69532
+ });
69533
+ });
69534
+ return true;
69535
+ } catch {
69536
+ return false;
69537
+ }
69538
+ }
69539
+ async function cleanupTempFile(filepath) {
69540
+ try {
69541
+ await unlink(filepath);
69542
+ } catch {
69543
+ }
69544
+ }
69545
+ var init_audio_player = __esm({
69546
+ "src/utils/audio_player.ts"() {
69547
+ "use strict";
69548
+ }
69549
+ });
69550
+
69181
69551
  // node_modules/chalk/source/vendor/ansi-styles/index.js
69182
69552
  var ANSI_BACKGROUND_OFFSET = 10;
69183
69553
  var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
@@ -69701,7 +70071,7 @@ import * as http from "http";
69701
70071
  // package.json
69702
70072
  var package_default = {
69703
70073
  name: "@inworld/cli",
69704
- version: "1.0.0-rc.3",
70074
+ version: "1.0.0",
69705
70075
  type: "module",
69706
70076
  main: "dist/index.js",
69707
70077
  bin: {
@@ -69717,6 +70087,9 @@ var package_default = {
69717
70087
  "build:types": "tsc --emitDeclarationOnly",
69718
70088
  "build:all": "npm run build && npm run build:types",
69719
70089
  prepublishOnly: "npm --prefix ../.. run build:all",
70090
+ test: "vitest run",
70091
+ "test:watch": "vitest",
70092
+ "test:coverage": "vitest run --coverage",
69720
70093
  start: "node dist/index.js",
69721
70094
  dev: "tsx src/index.ts"
69722
70095
  },
@@ -69739,10 +70112,12 @@ var package_default = {
69739
70112
  "@types/node": "^24.1.0",
69740
70113
  "@types/ora": "^3.1.0",
69741
70114
  "@types/semver": "^7.5.8",
70115
+ "@vitest/coverage-v8": "^2.1.4",
69742
70116
  chalk: "^5.3.0",
69743
70117
  commander: "^12.0.0",
69744
70118
  conf: "^14.0.0",
69745
70119
  esbuild: "^0.25.10",
70120
+ execa: "^9.5.1",
69746
70121
  "jwt-decode": "^4.0.0",
69747
70122
  mixpanel: "^0.18.1",
69748
70123
  ora: "^8.2.0",
@@ -69750,6 +70125,7 @@ var package_default = {
69750
70125
  semver: "^7.6.3",
69751
70126
  tsx: "^4.20.5",
69752
70127
  typescript: "^5.8.3",
70128
+ vitest: "^2.1.4",
69753
70129
  zod: "^3.24.2"
69754
70130
  },
69755
70131
  dependencies: {
@@ -71477,6 +71853,220 @@ var authCommand = new Command("auth").description("Manage Inworld authentication
71477
71853
  authCommand.help();
71478
71854
  });
71479
71855
 
71856
+ // src/services/llm_service.ts
71857
+ var LLMService = class {
71858
+ apiKey = null;
71859
+ async ensureApiKey() {
71860
+ if (!this.apiKey) this.apiKey = await requireApiKey();
71861
+ return this.apiKey;
71862
+ }
71863
+ get apiBaseUrl() {
71864
+ return PLATFORM_URL.replace("platform", "api");
71865
+ }
71866
+ async request(path8, init = {}) {
71867
+ const apiKey = await this.ensureApiKey();
71868
+ const res = await fetch(`${this.apiBaseUrl}${path8}`, {
71869
+ ...init,
71870
+ headers: {
71871
+ Authorization: `Basic ${apiKey}`,
71872
+ Accept: "application/json",
71873
+ ...init.body ? { "Content-Type": "application/json" } : {},
71874
+ ...init.headers
71875
+ }
71876
+ });
71877
+ const data = await res.json();
71878
+ if (!res.ok) {
71879
+ throw new Error(
71880
+ `LLM API Error [${data.code ?? res.status}]: ${data.message ?? "Unknown error"}`
71881
+ );
71882
+ }
71883
+ return data;
71884
+ }
71885
+ async completeChat(request) {
71886
+ return this.request(
71887
+ "/llm/v1alpha/completions:completeChat",
71888
+ { method: "POST", body: JSON.stringify(request) }
71889
+ );
71890
+ }
71891
+ async listModels() {
71892
+ return this.request("/llm/v1alpha/models", {
71893
+ method: "GET"
71894
+ });
71895
+ }
71896
+ };
71897
+ var llmService = new LLMService();
71898
+
71899
+ // src/utils/cli_arg_parsers.ts
71900
+ function parseIntInRange(flag, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
71901
+ return (raw) => {
71902
+ const n = Number.parseInt(raw, 10);
71903
+ if (!Number.isFinite(n)) {
71904
+ throw new InvalidArgumentError(
71905
+ `${flag} must be an integer; got "${raw}"`
71906
+ );
71907
+ }
71908
+ if (n < min || n > max) {
71909
+ throw new InvalidArgumentError(
71910
+ `${flag} must be between ${min} and ${max}; got ${n}`
71911
+ );
71912
+ }
71913
+ return n;
71914
+ };
71915
+ }
71916
+ function parseFloatInRange(flag, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
71917
+ return (raw) => {
71918
+ const n = Number.parseFloat(raw);
71919
+ if (!Number.isFinite(n)) {
71920
+ throw new InvalidArgumentError(`${flag} must be a number; got "${raw}"`);
71921
+ }
71922
+ if (n < min || n > max) {
71923
+ throw new InvalidArgumentError(
71924
+ `${flag} must be between ${min} and ${max}; got ${n}`
71925
+ );
71926
+ }
71927
+ return n;
71928
+ };
71929
+ }
71930
+
71931
+ // src/commands/llm/llm_chat_command.ts
71932
+ var chatCommand = new Command("chat").description("Send a chat completion request via the Inworld LLM Router").argument("<prompt>", "User prompt to send to the model").option(
71933
+ "-m, --model <id>",
71934
+ "Model id (e.g. gpt-4o-mini, gemini-2.5-flash)",
71935
+ "gpt-4o-mini"
71936
+ ).option(
71937
+ "-p, --provider <provider>",
71938
+ "Service provider (SERVICE_PROVIDER_OPENAI, SERVICE_PROVIDER_GOOGLE, ...)",
71939
+ "SERVICE_PROVIDER_OPENAI"
71940
+ ).option("-s, --system <text>", "Optional system prompt prepended to messages").option("-u, --user-id <id>", "Stable user id for analytics/routing", "cli").option(
71941
+ "-t, --max-tokens <n>",
71942
+ "Maximum tokens in response (1\u201332768)",
71943
+ parseIntInRange("--max-tokens", 1, 32768),
71944
+ 512
71945
+ ).option(
71946
+ "--temperature <n>",
71947
+ "Sampling temperature 0.0\u20132.0",
71948
+ parseFloatInRange("--temperature", 0, 2)
71949
+ ).option("-j, --json", "Output raw JSON response").action(async (prompt, options) => {
71950
+ try {
71951
+ const messages = [];
71952
+ if (options.system) {
71953
+ messages.push({ role: "MESSAGE_ROLE_SYSTEM", content: options.system });
71954
+ }
71955
+ messages.push({ role: "MESSAGE_ROLE_USER", content: prompt });
71956
+ const response = await llmService.completeChat({
71957
+ servingId: {
71958
+ modelId: {
71959
+ model: options.model,
71960
+ serviceProvider: options.provider
71961
+ },
71962
+ userId: options.userId
71963
+ },
71964
+ messages,
71965
+ textGenerationConfig: {
71966
+ maxTokens: options.maxTokens,
71967
+ ...options.temperature !== void 0 ? { temperature: options.temperature } : {},
71968
+ stream: false
71969
+ }
71970
+ });
71971
+ if (options.json) {
71972
+ console.log(JSON.stringify(response, null, 2));
71973
+ process.exit(0);
71974
+ return;
71975
+ }
71976
+ if (response.error) {
71977
+ console.error(source_default.red(`LLM error: ${response.error.message}`));
71978
+ process.exit(1);
71979
+ }
71980
+ const result = response.result;
71981
+ const text = result?.choices?.[0]?.message?.content ?? "";
71982
+ console.log(text);
71983
+ if (result?.usage) {
71984
+ const { promptTokens, completionTokens } = result.usage;
71985
+ console.error(
71986
+ source_default.gray(
71987
+ `
71988
+ (model=${result.model ?? options.model} prompt=${promptTokens ?? "?"} completion=${completionTokens ?? "?"} finish=${result.choices?.[0]?.finishReason ?? "?"})`
71989
+ )
71990
+ );
71991
+ }
71992
+ process.exit(0);
71993
+ } catch (error2) {
71994
+ console.error(
71995
+ source_default.red("Error in chat completion:"),
71996
+ error2 instanceof Error ? error2.message : error2
71997
+ );
71998
+ process.exit(1);
71999
+ }
72000
+ });
72001
+
72002
+ // src/commands/llm/llm_models_command.ts
72003
+ var modelsCommand = new Command("models").description("List LLM models available to your workspace").option("-j, --json", "Output as JSON").option("-c, --compact", "Compact output (model ids only)").option(
72004
+ "--supported-only",
72005
+ "Hide models flagged as not supported on your account"
72006
+ ).action(async (options) => {
72007
+ try {
72008
+ const response = await llmService.listModels();
72009
+ let models = response.models ?? [];
72010
+ if (options.supportedOnly) {
72011
+ models = models.filter((m) => m.isSupported !== false);
72012
+ }
72013
+ if (options.json) {
72014
+ console.log(JSON.stringify({ models }, null, 2));
72015
+ process.exit(0);
72016
+ return;
72017
+ }
72018
+ if (models.length === 0) {
72019
+ console.log(source_default.yellow("No models returned."));
72020
+ process.exit(0);
72021
+ return;
72022
+ }
72023
+ if (options.compact) {
72024
+ models.map((m) => m.model).sort().forEach((id) => console.log(id));
72025
+ process.exit(0);
72026
+ return;
72027
+ }
72028
+ console.log();
72029
+ console.log(source_default.bold.green("Available LLM Models"));
72030
+ console.log(source_default.gray(`Found ${models.length} models`));
72031
+ console.log(source_default.gray("\u2500".repeat(72)));
72032
+ const sorted = [...models].sort((a, b) => {
72033
+ const byProvider = (a.provider ?? "").localeCompare(b.provider ?? "");
72034
+ return byProvider !== 0 ? byProvider : a.model.localeCompare(b.model);
72035
+ });
72036
+ for (const m of sorted) {
72037
+ const flag = m.isSupported === false ? source_default.red("\u2717") : source_default.green("\u2713");
72038
+ const tier = m.modelCreator ? source_default.gray(` [${m.modelCreator}]`) : "";
72039
+ console.log(
72040
+ ` ${flag} ${source_default.cyan(m.model)}${tier}` + (m.provider ? source_default.gray(` via ${m.provider}`) : "")
72041
+ );
72042
+ if (m.pricing) {
72043
+ const p2 = m.pricing.prompt;
72044
+ const c = m.pricing.completion;
72045
+ if (p2 !== void 0 || c !== void 0) {
72046
+ console.log(
72047
+ source_default.gray(
72048
+ ` prompt: ${p2 ?? "?"} / completion: ${c ?? "?"} (per token)`
72049
+ )
72050
+ );
72051
+ }
72052
+ }
72053
+ }
72054
+ console.log();
72055
+ process.exit(0);
72056
+ } catch (error2) {
72057
+ console.error(
72058
+ source_default.red("Error listing models:"),
72059
+ error2 instanceof Error ? error2.message : error2
72060
+ );
72061
+ process.exit(1);
72062
+ }
72063
+ });
72064
+
72065
+ // src/commands/llm_commands.ts
72066
+ var llmCommand = new Command("llm").description("Inworld LLM Router: chat completions and model catalogue").addCommand(chatCommand).addCommand(modelsCommand).action(() => {
72067
+ llmCommand.help();
72068
+ });
72069
+
71480
72070
  // src/commands/mcp_command.ts
71481
72071
  var mcpCommand = new Command("mcp").description(
71482
72072
  "Run the Inworld Model Context Protocol server (same surface as `inworld-mcp`)"
@@ -71507,8 +72097,118 @@ var mcpCommand = new Command("mcp").description(
71507
72097
  await main2();
71508
72098
  });
71509
72099
 
71510
- // src/commands/tts/tts_clone_command.ts
72100
+ // src/commands/stt/stt_transcribe_command.ts
71511
72101
  import { readFile } from "fs/promises";
72102
+
72103
+ // src/services/stt_service.ts
72104
+ var STT_MODELS = {
72105
+ INWORLD_STT_1: "inworld/inworld-stt-1",
72106
+ GROQ_WHISPER_LARGE_V3: "groq/whisper-large-v3"
72107
+ };
72108
+ var STTService = class {
72109
+ apiKey = null;
72110
+ async ensureApiKey() {
72111
+ if (!this.apiKey) this.apiKey = await requireApiKey();
72112
+ return this.apiKey;
72113
+ }
72114
+ get apiBaseUrl() {
72115
+ return PLATFORM_URL.replace("platform", "api");
72116
+ }
72117
+ /**
72118
+ * POST /stt/v1/transcribe with the schema-correct body:
72119
+ * { transcribeConfig: { modelId, audioEncoding, language }, audioData: { content } }
72120
+ * (The published OpenAPI example nests audio differently; this is the
72121
+ * shape the production gateway actually accepts.)
72122
+ */
72123
+ async transcribe(opts) {
72124
+ const apiKey = await this.ensureApiKey();
72125
+ const body = {
72126
+ transcribeConfig: {
72127
+ modelId: opts.modelId ?? STT_MODELS.INWORLD_STT_1,
72128
+ audioEncoding: opts.audioEncoding ?? "AUTO_DETECT",
72129
+ ...opts.language ? { language: opts.language } : {}
72130
+ },
72131
+ audioData: { content: opts.audioBase64 }
72132
+ };
72133
+ const res = await fetch(`${this.apiBaseUrl}/stt/v1/transcribe`, {
72134
+ method: "POST",
72135
+ headers: {
72136
+ Authorization: `Basic ${apiKey}`,
72137
+ "Content-Type": "application/json"
72138
+ },
72139
+ body: JSON.stringify(body)
72140
+ });
72141
+ const data = await res.json();
72142
+ if (!res.ok) {
72143
+ throw new Error(
72144
+ `STT API Error [${data.code ?? res.status}]: ${data.message ?? "Unknown error"}`
72145
+ );
72146
+ }
72147
+ return data;
72148
+ }
72149
+ };
72150
+ var sttService = new STTService();
72151
+
72152
+ // src/commands/stt/stt_transcribe_command.ts
72153
+ var transcribeCommand = new Command("transcribe").description("Transcribe an audio file via the Inworld STT API").argument("<audioFile>", "Path to audio file (wav, mp3, flac, ogg, ...)").option("-l, --lang <code>", "Language code (BCP-47, e.g. en-US)", "en-US").option(
72154
+ "-e, --encoding <enc>",
72155
+ "Audio encoding (AUTO_DETECT, LINEAR16, MP3, OGG_OPUS, FLAC)",
72156
+ "AUTO_DETECT"
72157
+ ).option(
72158
+ "-m, --model <id>",
72159
+ "STT model id (default: inworld/inworld-stt-1)",
72160
+ "inworld/inworld-stt-1"
72161
+ ).option("-j, --json", "Output raw JSON response").action(async (audioFile, options) => {
72162
+ try {
72163
+ const buf = await readFile(audioFile);
72164
+ const audioBase64 = buf.toString("base64");
72165
+ const response = await sttService.transcribe({
72166
+ audioBase64,
72167
+ audioEncoding: options.encoding,
72168
+ modelId: options.model,
72169
+ language: options.lang
72170
+ });
72171
+ if (options.json) {
72172
+ console.log(JSON.stringify(response, null, 2));
72173
+ process.exit(0);
72174
+ return;
72175
+ }
72176
+ const transcript = response.transcription?.transcript ?? "";
72177
+ if (!transcript) {
72178
+ console.log(source_default.yellow("(no transcript returned)"));
72179
+ process.exit(0);
72180
+ return;
72181
+ }
72182
+ console.log();
72183
+ console.log(source_default.bold.green("Transcript"));
72184
+ console.log(source_default.gray("\u2500".repeat(60)));
72185
+ console.log(transcript);
72186
+ if (response.usage?.transcribedAudioMs !== void 0) {
72187
+ console.log(
72188
+ source_default.gray(
72189
+ `
72190
+ (audio: ${response.usage.transcribedAudioMs} ms, model: ${response.usage.modelId ?? "?"})`
72191
+ )
72192
+ );
72193
+ }
72194
+ console.log();
72195
+ process.exit(0);
72196
+ } catch (error2) {
72197
+ console.error(
72198
+ source_default.red("Error transcribing:"),
72199
+ error2 instanceof Error ? error2.message : error2
72200
+ );
72201
+ process.exit(1);
72202
+ }
72203
+ });
72204
+
72205
+ // src/commands/stt_commands.ts
72206
+ var sttCommand = new Command("stt").description("Speech-to-text functionality").addCommand(transcribeCommand).action(() => {
72207
+ sttCommand.help();
72208
+ });
72209
+
72210
+ // src/commands/tts/tts_clone_command.ts
72211
+ import { readFile as readFile2 } from "fs/promises";
71512
72212
  import { resolve } from "path";
71513
72213
 
71514
72214
  // src/services/tts_service.ts
@@ -71586,6 +72286,30 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
71586
72286
  method: "GET"
71587
72287
  });
71588
72288
  }
72289
+ /**
72290
+ * Fetches a short, server-side audio preview for an existing voice.
72291
+ * Not metered or billed — ideal for catalog browsing. Returns MP3.
72292
+ * `model_id` is documented as optional but de facto required by the
72293
+ * gateway, so we default to the current production model.
72294
+ * @see {@link https://docs.inworld.ai/api-reference/ttsAPI/texttospeech/get-voice-preview}
72295
+ */
72296
+ async getVoicePreview(voiceId, modelId = "inworld-tts-1.5-max" /* INWORLD_TTS_1_5_MAX */) {
72297
+ const qs = new URLSearchParams({ voice_id: voiceId, model_id: modelId });
72298
+ return this.makeRequest(
72299
+ `/tts/v1/voice:preview?${qs.toString()}`,
72300
+ { method: "GET" }
72301
+ );
72302
+ }
72303
+ /**
72304
+ * Gets a single voice's metadata by ID.
72305
+ * @see {@link https://docs.inworld.ai/api-reference/voiceAPI/voiceservice/get-voice}
72306
+ */
72307
+ async getVoice(voiceId) {
72308
+ return this.makeRequest(
72309
+ `/voices/v1/voices/${encodeURIComponent(voiceId)}`,
72310
+ { method: "GET" }
72311
+ );
72312
+ }
71589
72313
  /**
71590
72314
  * Synthesizes speech from text
71591
72315
  */
@@ -71786,7 +72510,7 @@ var ttsService = new TTSService();
71786
72510
  var cloneCommand = new Command("clone").description("Clone a voice from an audio file (5-15 seconds, max 4MB)").argument("<audioFile>", "Path to audio file (wav, mp3, webm)").requiredOption("-n, --name <name>", "Display name for the cloned voice").option("-l, --lang <code>", "Language code (e.g., EN_US)", "EN_US").option("-t, --transcription <text>", "Transcription of the audio").option("-d, --description <text>", "Description of the voice").option("--tags <tags>", "Comma-separated tags").option("--remove-noise", "Remove background noise from audio").option("-j, --json", "Output response as JSON").action(async (audioFile, options) => {
71787
72511
  try {
71788
72512
  const filePath = resolve(audioFile);
71789
- const audioData = await readFile(filePath);
72513
+ const audioData = await readFile2(filePath);
71790
72514
  if (audioData.length > 4 * 1024 * 1024) {
71791
72515
  console.error(source_default.red("Error: Audio file exceeds 4MB limit"));
71792
72516
  process.exit(1);
@@ -71851,29 +72575,7 @@ import { writeFile } from "fs/promises";
71851
72575
  import { tmpdir as tmpdir2 } from "os";
71852
72576
  import { join } from "path";
71853
72577
  import * as readline6 from "readline";
71854
-
71855
- // src/utils/audio_player.ts
71856
- import { unlink } from "fs/promises";
71857
- async function playFile(filePath) {
71858
- try {
71859
- const player = (await Promise.resolve().then(() => __toESM(require_play_sound(), 1))).default();
71860
- await new Promise((resolve3, reject) => {
71861
- player.play(filePath, (err) => {
71862
- if (err) reject(err);
71863
- else resolve3();
71864
- });
71865
- });
71866
- return true;
71867
- } catch {
71868
- return false;
71869
- }
71870
- }
71871
- async function cleanupTempFile(filepath) {
71872
- try {
71873
- await unlink(filepath);
71874
- } catch {
71875
- }
71876
- }
72578
+ init_audio_player();
71877
72579
 
71878
72580
  // src/commands/tts/tts_utils.ts
71879
72581
  import * as readline5 from "readline";
@@ -72182,6 +72884,40 @@ Use this voice: inworld tts synthesize "Hello" -v ${published.voiceId}`
72182
72884
  }
72183
72885
  });
72184
72886
 
72887
+ // src/commands/tts/tts_get_voice_command.ts
72888
+ var getVoiceCommand = new Command("get-voice").description("Get metadata for a single voice by ID").argument("<voiceId>", "Voice ID (e.g. Dennis or workspace__voicename)").option("-j, --json", "Output as JSON").action(async (voiceId, options) => {
72889
+ try {
72890
+ const voice = await ttsService.getVoice(voiceId);
72891
+ if (options.json) {
72892
+ console.log(JSON.stringify(voice, null, 2));
72893
+ process.exit(0);
72894
+ return;
72895
+ }
72896
+ console.log();
72897
+ console.log(source_default.bold.green("Voice"), source_default.cyan(voice.voiceId));
72898
+ console.log(source_default.gray("\u2500".repeat(50)));
72899
+ const row = (k, v) => {
72900
+ if (v === void 0 || Array.isArray(v) && v.length === 0) return;
72901
+ const val = Array.isArray(v) ? v.join(", ") : v;
72902
+ console.log(` ${source_default.gray(k.padEnd(14))} ${val}`);
72903
+ };
72904
+ row("Display name", voice.displayName);
72905
+ row("Language", voice.langCode);
72906
+ row("Description", voice.description);
72907
+ row("Tags", voice.tags);
72908
+ row("Source", voice.source);
72909
+ row("Resource", voice.name);
72910
+ console.log();
72911
+ process.exit(0);
72912
+ } catch (error2) {
72913
+ console.error(
72914
+ source_default.red("Error fetching voice:"),
72915
+ error2 instanceof Error ? error2.message : error2
72916
+ );
72917
+ process.exit(1);
72918
+ }
72919
+ });
72920
+
72185
72921
  // src/commands/tts/tts_list_voices_command.ts
72186
72922
  var listVoicesCommand = new Command("list-voices").description("List all available voices from the workspace").option("-f, --filter <filter>", 'Filter voices (e.g., "language=en")').option("-j, --json", "Output as JSON").option("-c, --compact", "Compact output (voice IDs only)").action(async (options) => {
72187
72923
  try {
@@ -72282,9 +73018,48 @@ ${flag} ${source_default.bold.yellow(lang.toUpperCase())} ${source_default.gray
72282
73018
  process.exit(0);
72283
73019
  });
72284
73020
 
73021
+ // src/commands/tts/tts_preview_command.ts
73022
+ var previewCommand = new Command("preview").description(
73023
+ "Get a short, non-billed voice preview for a voice ID (returns MP3)"
73024
+ ).argument("<voiceId>", "Voice ID to preview (see `inworld tts list-voices`)").option(
73025
+ "-m, --model <id>",
73026
+ "TTS model id (e.g. inworld-tts-2)",
73027
+ "inworld-tts-1.5-max"
73028
+ ).option(
73029
+ "-o, --output <file>",
73030
+ "Output MP3 file path (default: preview-<voiceId>.mp3)"
73031
+ ).option("-p, --play", "Play the preview audio through speakers after saving").option("-j, --json", "Output raw JSON (includes base64 audio)").action(async (voiceId, options) => {
73032
+ try {
73033
+ const response = await ttsService.getVoicePreview(voiceId, options.model);
73034
+ if (options.json) {
73035
+ console.log(JSON.stringify(response, null, 2));
73036
+ process.exit(0);
73037
+ return;
73038
+ }
73039
+ const outPath = options.output ?? `preview-${voiceId.replace(/[^a-zA-Z0-9_.-]/g, "_")}.mp3`;
73040
+ await ttsService.saveAudioToFile(response.audioContent, outPath);
73041
+ console.log(
73042
+ source_default.green("\u2713"),
73043
+ `Voice preview saved: ${source_default.cyan(outPath)}`
73044
+ );
73045
+ if (options.play) {
73046
+ const { playFile: playFile2 } = await Promise.resolve().then(() => (init_audio_player(), audio_player_exports));
73047
+ await playFile2(outPath);
73048
+ }
73049
+ process.exit(0);
73050
+ } catch (error2) {
73051
+ console.error(
73052
+ source_default.red("Error fetching voice preview:"),
73053
+ error2 instanceof Error ? error2.message : error2
73054
+ );
73055
+ process.exit(1);
73056
+ }
73057
+ });
73058
+
72285
73059
  // src/commands/tts/tts_synthesize_command.ts
72286
73060
  import { writeFile as writeFile2 } from "fs/promises";
72287
73061
  import { resolve as resolve2 } from "path";
73062
+ init_audio_player();
72288
73063
  var synthesizeCommand = new Command("synthesize").description(
72289
73064
  'Synthesize text to speech\n\nAudio markups supported in text:\n SSML breaks: <break time="1s" /> or <break time="500ms" />\n Emotions: [happy] [sad] [angry] [surprised] [fearful] [disgusted]\n Delivery: [laughing] [whispering]\n Vocalizations: [breathe] [clear_throat] [cough] [laugh] [sigh] [yawn]\n Pronunciation: /kri\u02D0t/ (IPA in forward slashes)'
72290
73065
  ).argument("<text>", "Text to synthesize (max 2000 characters)").requiredOption(
@@ -72695,7 +73470,7 @@ var synthesizeCommand = new Command("synthesize").description(
72695
73470
  });
72696
73471
 
72697
73472
  // src/commands/tts_commands.ts
72698
- var ttsCommand = new Command("tts").description("Text-to-speech functionality").addCommand(listVoicesCommand).addCommand(synthesizeCommand).addCommand(cloneCommand).addCommand(designCommand).action(() => {
73473
+ var ttsCommand = new Command("tts").description("Text-to-speech functionality").addCommand(listVoicesCommand).addCommand(getVoiceCommand).addCommand(previewCommand).addCommand(synthesizeCommand).addCommand(cloneCommand).addCommand(designCommand).action(() => {
72699
73474
  ttsCommand.help();
72700
73475
  });
72701
73476
 
@@ -72925,6 +73700,8 @@ var InworldCLI = class {
72925
73700
  this.program.addCommand(statusCommandAlias);
72926
73701
  this.program.addCommand(authCommand);
72927
73702
  this.program.addCommand(ttsCommand);
73703
+ this.program.addCommand(sttCommand);
73704
+ this.program.addCommand(llmCommand);
72928
73705
  this.program.addCommand(workspaceCommand);
72929
73706
  this.program.addCommand(mcpCommand);
72930
73707
  this.program.command("help").description("Display help information").action(() => {