@inworld/cli 1.1.0 → 1.3.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
@@ -7268,7 +7268,7 @@ var require_schemes = __commonJS({
7268
7268
  urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
7269
7269
  return urnComponent;
7270
7270
  }
7271
- var http3 = (
7271
+ var http4 = (
7272
7272
  /** @type {SchemeHandler} */
7273
7273
  {
7274
7274
  scheme: "http",
@@ -7281,7 +7281,7 @@ var require_schemes = __commonJS({
7281
7281
  /** @type {SchemeHandler} */
7282
7282
  {
7283
7283
  scheme: "https",
7284
- domainHost: http3.domainHost,
7284
+ domainHost: http4.domainHost,
7285
7285
  parse: httpParse,
7286
7286
  serialize: httpSerialize
7287
7287
  }
@@ -7325,7 +7325,7 @@ var require_schemes = __commonJS({
7325
7325
  var SCHEMES = (
7326
7326
  /** @type {Record<SchemeName, SchemeHandler>} */
7327
7327
  {
7328
- http: http3,
7328
+ http: http4,
7329
7329
  https,
7330
7330
  ws,
7331
7331
  wss,
@@ -19440,7 +19440,9 @@ async function getConf() {
19440
19440
  expiresAt: { type: "number" },
19441
19441
  workspace: { type: "string" },
19442
19442
  apiKey: { type: "string" },
19443
- env: { type: "string" }
19443
+ env: { type: "string" },
19444
+ authProvider: { type: "string" },
19445
+ authUrl: { type: "string" }
19444
19446
  }
19445
19447
  }
19446
19448
  }
@@ -19522,6 +19524,572 @@ var init_dist4 = __esm({
19522
19524
  }
19523
19525
  });
19524
19526
 
19527
+ // src/mcp/auth/constants.ts
19528
+ function getMcpHttpAuthMode() {
19529
+ const v = (process.env.INWORLD_MCP_HTTP_AUTH || "session").toLowerCase();
19530
+ if (v === "bearer") return "bearer";
19531
+ return "session";
19532
+ }
19533
+ var DEFAULT_PLATFORM_ENDPOINT2, resolvePlatformUrl2, INWORLD_ENV2, PLATFORM_URL2, FIREBASE_API_KEY2, INWORLD_CLI_AUTH_URL2, INWORLD_CLI_AUTH_CALLBACK_PORT2;
19534
+ var init_constants5 = __esm({
19535
+ "src/mcp/auth/constants.ts"() {
19536
+ "use strict";
19537
+ DEFAULT_PLATFORM_ENDPOINT2 = "https://platform.inworld.ai";
19538
+ resolvePlatformUrl2 = () => {
19539
+ if (process.env.INWORLD_PLATFORM_URL) {
19540
+ return process.env.INWORLD_PLATFORM_URL;
19541
+ }
19542
+ const env3 = (process.env.INWORLD_ENV || "").toUpperCase();
19543
+ switch (env3) {
19544
+ case "DEV":
19545
+ return "https://platform.dev.inworld.ai";
19546
+ case "STAGE":
19547
+ return "https://platform.stage.inworld.ai";
19548
+ case "PROD":
19549
+ return "https://platform.inworld.ai";
19550
+ default:
19551
+ return DEFAULT_PLATFORM_ENDPOINT2;
19552
+ }
19553
+ };
19554
+ INWORLD_ENV2 = process.env.INWORLD_ENV || "PROD";
19555
+ PLATFORM_URL2 = resolvePlatformUrl2();
19556
+ FIREBASE_API_KEY2 = process.env.INWORLD_FIREBASE_API_KEY || process.env.FIREBASE_API_KEY || "AIzaSyAPVBLVid0xPwjuU4Gmn_6_GyqxBq-SwQs";
19557
+ INWORLD_CLI_AUTH_URL2 = process.env.INWORLD_CLI_AUTH_URL || "https://cli.inworld.ai/login";
19558
+ INWORLD_CLI_AUTH_CALLBACK_PORT2 = parseInt(
19559
+ process.env.INWORLD_CLI_AUTH_CALLBACK_PORT || "8085",
19560
+ 10
19561
+ );
19562
+ }
19563
+ });
19564
+
19565
+ // src/mcp/auth/firebase-refresh.ts
19566
+ async function refreshFirebaseWithRefreshToken(refreshToken) {
19567
+ const url = `https://securetoken.googleapis.com/v1/token?key=${encodeURIComponent(FIREBASE_API_KEY2)}`;
19568
+ const body = new URLSearchParams({
19569
+ grant_type: "refresh_token",
19570
+ refresh_token: refreshToken
19571
+ });
19572
+ const res = await fetch(url, {
19573
+ method: "POST",
19574
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
19575
+ body: body.toString()
19576
+ });
19577
+ const text = await res.text();
19578
+ let data;
19579
+ try {
19580
+ data = text ? JSON.parse(text) : {};
19581
+ } catch {
19582
+ throw new Error(
19583
+ `Firebase token refresh: expected JSON (${res.status}): ${text.slice(0, 200)}`
19584
+ );
19585
+ }
19586
+ if (!res.ok) {
19587
+ const err = data.error;
19588
+ const msg = typeof err?.message === "string" ? err.message : typeof data.message === "string" ? data.message : text.slice(0, 300);
19589
+ throw new Error(`Firebase token refresh failed: ${msg}`);
19590
+ }
19591
+ const idToken = data.id_token;
19592
+ const newRefresh = data.refresh_token;
19593
+ if (typeof idToken !== "string") {
19594
+ throw new Error("Firebase token refresh: response missing id_token");
19595
+ }
19596
+ return {
19597
+ idToken,
19598
+ refreshToken: typeof newRefresh === "string" ? newRefresh : refreshToken,
19599
+ expiresIn: String(data.expires_in ?? "")
19600
+ };
19601
+ }
19602
+ var init_firebase_refresh = __esm({
19603
+ "src/mcp/auth/firebase-refresh.ts"() {
19604
+ "use strict";
19605
+ init_constants5();
19606
+ }
19607
+ });
19608
+
19609
+ // src/mcp/auth/identity.ts
19610
+ import { createHash as createHash2, randomBytes } from "node:crypto";
19611
+ import * as http from "node:http";
19612
+ function decodeJwtPayload(jwt) {
19613
+ const parts = jwt.split(".");
19614
+ if (parts.length < 2) return null;
19615
+ const b642 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
19616
+ try {
19617
+ const json = Buffer.from(b642, "base64").toString("utf8");
19618
+ return JSON.parse(json);
19619
+ } catch {
19620
+ return null;
19621
+ }
19622
+ }
19623
+ function tokenIssuer(idToken) {
19624
+ const iss = decodeJwtPayload(idToken)?.iss;
19625
+ return typeof iss === "string" ? iss.replace(/\/$/, "") : void 0;
19626
+ }
19627
+ function providerForToken(idToken) {
19628
+ const iss = tokenIssuer(idToken);
19629
+ return iss && /\/auth\/v1$/.test(iss) ? "supabase" : "firebase";
19630
+ }
19631
+ function isIssuedBy(idToken, source) {
19632
+ if (providerForToken(idToken) !== source.provider) return false;
19633
+ return source.provider !== "supabase" || tokenIssuer(idToken) === source.authUrl;
19634
+ }
19635
+ function bearerTypeFor(provider) {
19636
+ return provider === "supabase" ? "supabase" : "firebase";
19637
+ }
19638
+ function authTypeFor(provider) {
19639
+ return provider === "supabase" ? "AUTH_TYPE_SUPABASE" : "AUTH_TYPE_FIREBASE";
19640
+ }
19641
+ function parseConfigJs(text) {
19642
+ const pick2 = (key) => new RegExp(`["']?${key}["']?\\s*:\\s*["']([^"']+)["']`).exec(text)?.[1];
19643
+ return {
19644
+ authProvider: pick2("AUTH_PROVIDER"),
19645
+ supabaseUrl: pick2("SUPABASE_URL")
19646
+ };
19647
+ }
19648
+ async function resolveIdentitySource(platformUrl) {
19649
+ const base = platformUrl.replace(/\/$/, "");
19650
+ const override = process.env.INWORLD_AUTH_PROVIDER?.trim().toLowerCase();
19651
+ let config2 = {};
19652
+ if (override !== "firebase") {
19653
+ try {
19654
+ const res = await fetch(`${base}/config.js`, {
19655
+ signal: AbortSignal.timeout(5e3)
19656
+ });
19657
+ if (res.ok) config2 = parseConfigJs(await res.text());
19658
+ } catch {
19659
+ }
19660
+ }
19661
+ const provider = (override || config2.authProvider || "firebase").toLowerCase();
19662
+ if (provider !== "supabase") return { provider: "firebase" };
19663
+ const authUrl = process.env.INWORLD_AUTH_URL?.trim() || `${(config2.supabaseUrl || base).replace(/\/$/, "")}/auth/v1`;
19664
+ return { provider: "supabase", authUrl: authUrl.replace(/\/$/, "") };
19665
+ }
19666
+ function gotrueErrorMessage(data, fallback) {
19667
+ if (data && typeof data === "object") {
19668
+ const o2 = data;
19669
+ for (const key of ["error_description", "msg", "message", "error"]) {
19670
+ if (typeof o2[key] === "string" && o2[key]) return o2[key];
19671
+ }
19672
+ }
19673
+ return fallback;
19674
+ }
19675
+ async function gotrueToken(authUrl, grantType, body) {
19676
+ const url = `${authUrl}/token?grant_type=${grantType}`;
19677
+ const res = await fetch(url, {
19678
+ method: "POST",
19679
+ headers: { "Content-Type": "application/json" },
19680
+ body: JSON.stringify(body)
19681
+ });
19682
+ const text = await res.text();
19683
+ let data = {};
19684
+ try {
19685
+ data = text ? JSON.parse(text) : {};
19686
+ } catch {
19687
+ throw new Error(
19688
+ `Supabase token (${grantType}): expected JSON (${res.status}): ${text.slice(0, 200)}`
19689
+ );
19690
+ }
19691
+ if (!res.ok) {
19692
+ throw new Error(
19693
+ `Supabase token (${grantType}) failed: ${gotrueErrorMessage(data, `HTTP ${res.status}`)}`
19694
+ );
19695
+ }
19696
+ if (!data.access_token || !data.refresh_token) {
19697
+ throw new Error(
19698
+ `Supabase token (${grantType}): response missing access or refresh token`
19699
+ );
19700
+ }
19701
+ return {
19702
+ idToken: data.access_token,
19703
+ refreshToken: data.refresh_token,
19704
+ email: data.user?.email
19705
+ };
19706
+ }
19707
+ async function refreshIdentityToken(source, refreshToken) {
19708
+ if (source.provider === "supabase") {
19709
+ if (!source.authUrl) throw new Error("Supabase refresh needs an auth URL");
19710
+ return gotrueToken(source.authUrl, "refresh_token", {
19711
+ refresh_token: refreshToken
19712
+ });
19713
+ }
19714
+ const r = await refreshFirebaseWithRefreshToken(refreshToken);
19715
+ return { idToken: r.idToken, refreshToken: r.refreshToken };
19716
+ }
19717
+ async function revokeSession(source, refreshToken) {
19718
+ if (source.provider !== "supabase" || !source.authUrl) return false;
19719
+ const { idToken } = await refreshIdentityToken(source, refreshToken);
19720
+ const res = await fetch(`${source.authUrl}/logout?scope=local`, {
19721
+ method: "POST",
19722
+ headers: { Authorization: `Bearer ${idToken}` }
19723
+ });
19724
+ if (!res.ok) {
19725
+ const text = await res.text();
19726
+ let data = {};
19727
+ try {
19728
+ data = text ? JSON.parse(text) : {};
19729
+ } catch {
19730
+ }
19731
+ throw new Error(
19732
+ `Supabase logout failed: ${gotrueErrorMessage(data, `HTTP ${res.status}`)}`
19733
+ );
19734
+ }
19735
+ return true;
19736
+ }
19737
+ function signInWithPassword(authUrl, email2, password) {
19738
+ return gotrueToken(authUrl, "password", { email: email2, password });
19739
+ }
19740
+ function createPkcePair() {
19741
+ const verifier = base64url(randomBytes(32));
19742
+ const challenge = base64url(createHash2("sha256").update(verifier).digest());
19743
+ return { verifier, challenge };
19744
+ }
19745
+ function gotrueAuthorizeUrl(authUrl, oauthProvider, redirectTo, challenge) {
19746
+ const u2 = new URL(`${authUrl}/authorize`);
19747
+ u2.searchParams.set("provider", oauthProvider);
19748
+ u2.searchParams.set("redirect_to", redirectTo);
19749
+ u2.searchParams.set("code_challenge", challenge);
19750
+ u2.searchParams.set("code_challenge_method", "s256");
19751
+ return u2.toString();
19752
+ }
19753
+ function gotrueCallbackPort() {
19754
+ const fixed = process.env.INWORLD_CLI_AUTH_CALLBACK_PORT?.trim();
19755
+ return fixed ? parseInt(fixed, 10) : 0;
19756
+ }
19757
+ async function startCodeReceiver(port) {
19758
+ let settle;
19759
+ const code = new Promise((resolve4, reject) => {
19760
+ settle = { resolve: resolve4, reject };
19761
+ });
19762
+ const handler = (req, res) => {
19763
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
19764
+ if (url.pathname !== "/") {
19765
+ res.writeHead(404).end();
19766
+ return;
19767
+ }
19768
+ const error2 = url.searchParams.get("error_description") ?? url.searchParams.get("error");
19769
+ const authCode = url.searchParams.get("code");
19770
+ res.writeHead(error2 || !authCode ? 400 : 200, {
19771
+ "Content-Type": "text/html; charset=utf-8"
19772
+ });
19773
+ if (error2 || !authCode) {
19774
+ const msg = error2 ?? "No authorization code in the redirect.";
19775
+ res.end(resultPage("Sign-in failed", escapeHtml(msg)));
19776
+ settle.reject(new Error(`Sign-in failed: ${msg}`));
19777
+ return;
19778
+ }
19779
+ res.end(
19780
+ resultPage(
19781
+ "Signed in to Inworld CLI",
19782
+ "You can close this tab and return to the terminal."
19783
+ )
19784
+ );
19785
+ settle.resolve(authCode);
19786
+ };
19787
+ const server = http.createServer({ keepAlive: false }, handler);
19788
+ await new Promise((resolve4, reject) => {
19789
+ server.once("error", reject);
19790
+ server.listen(port, "127.0.0.1", () => resolve4());
19791
+ });
19792
+ const { port: boundPort } = server.address();
19793
+ const timer = setTimeout(
19794
+ () => settle.reject(
19795
+ new Error(
19796
+ `Sign-in timed out after ${OAUTH_SIGN_IN_TIMEOUT_MS / 6e4} minutes. Run the login again.`
19797
+ )
19798
+ ),
19799
+ OAUTH_SIGN_IN_TIMEOUT_MS
19800
+ );
19801
+ timer.unref();
19802
+ return {
19803
+ redirectTo: `http://127.0.0.1:${boundPort}`,
19804
+ code,
19805
+ close: () => {
19806
+ clearTimeout(timer);
19807
+ server.close();
19808
+ server.closeAllConnections?.();
19809
+ }
19810
+ };
19811
+ }
19812
+ async function startOAuthSignIn(options) {
19813
+ const { verifier, challenge } = createPkcePair();
19814
+ const receiver = await startCodeReceiver(
19815
+ options.port ?? gotrueCallbackPort()
19816
+ );
19817
+ const url = gotrueAuthorizeUrl(
19818
+ options.authUrl,
19819
+ options.oauthProvider,
19820
+ receiver.redirectTo,
19821
+ challenge
19822
+ );
19823
+ const done = receiver.code.then(
19824
+ (authCode) => gotrueToken(options.authUrl, "pkce", {
19825
+ auth_code: authCode,
19826
+ code_verifier: verifier
19827
+ })
19828
+ ).finally(receiver.close);
19829
+ return { url, done };
19830
+ }
19831
+ var BEARER_TYPE_HEADER, GOTRUE_OAUTH_PROVIDERS, base64url, resultPage, escapeHtml, OAUTH_SIGN_IN_TIMEOUT_MS;
19832
+ var init_identity = __esm({
19833
+ "src/mcp/auth/identity.ts"() {
19834
+ "use strict";
19835
+ init_firebase_refresh();
19836
+ BEARER_TYPE_HEADER = "Grpc-Metadata-X-Authorization-Bearer-Type";
19837
+ GOTRUE_OAUTH_PROVIDERS = ["google", "github", "azure"];
19838
+ base64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19839
+ resultPage = (title, detail) => `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title></head><body style="font-family:system-ui;margin:4rem auto;max-width:32rem;text-align:center"><h2>${title}</h2><p>${detail}</p></body></html>`;
19840
+ escapeHtml = (s) => s.replace(/[&<>"']/g, (c3) => `&#${c3.charCodeAt(0)};`);
19841
+ OAUTH_SIGN_IN_TIMEOUT_MS = 5 * 60 * 1e3;
19842
+ }
19843
+ });
19844
+
19845
+ // src/mcp/auth/exchange.ts
19846
+ function formatNetworkError(err, url) {
19847
+ if (err instanceof TypeError && err.message === "fetch failed") {
19848
+ const cause = err.cause;
19849
+ const code = cause?.code ?? "";
19850
+ const hint = "Set INWORLD_PLATFORM_URL or INWORLD_ENV (DEV/STAGE/PROD) to match your environment.";
19851
+ return new Error(
19852
+ `Cannot reach platform at ${url}${code ? ` (${code})` : ""}. ${hint}`
19853
+ );
19854
+ }
19855
+ return err instanceof Error ? err : new Error(String(err));
19856
+ }
19857
+ function extractGatewayErrorMessage(data, fallback) {
19858
+ if (data && typeof data === "object") {
19859
+ const o2 = data;
19860
+ if (typeof o2.message === "string" && o2.message.length > 0) {
19861
+ return o2.message;
19862
+ }
19863
+ const err = o2.error;
19864
+ if (err && typeof err === "object" && typeof err.message === "string") {
19865
+ return err.message;
19866
+ }
19867
+ }
19868
+ return fallback;
19869
+ }
19870
+ async function exchangeIdentityToken(identityToken) {
19871
+ const provider = providerForToken(identityToken);
19872
+ const base = PLATFORM_URL2.replace(/\/$/, "");
19873
+ const url = `${base}/v1alpha/users:generateTokenUser`;
19874
+ const body = JSON.stringify({
19875
+ type: authTypeFor(provider),
19876
+ token: identityToken
19877
+ });
19878
+ let res;
19879
+ try {
19880
+ res = await fetch(url, {
19881
+ method: "POST",
19882
+ headers: {
19883
+ "Content-Type": "application/json",
19884
+ Authorization: `Bearer ${identityToken}`,
19885
+ [BEARER_TYPE_HEADER]: bearerTypeFor(provider)
19886
+ },
19887
+ body
19888
+ });
19889
+ } catch (err) {
19890
+ throw formatNetworkError(err, url);
19891
+ }
19892
+ const text = await res.text();
19893
+ let data;
19894
+ try {
19895
+ data = text ? JSON.parse(text) : {};
19896
+ } catch {
19897
+ throw new Error(
19898
+ `generateTokenUser: response was not JSON (${res.status}): ${text.slice(0, 240)}`
19899
+ );
19900
+ }
19901
+ if (!res.ok) {
19902
+ const msg = extractGatewayErrorMessage(
19903
+ data,
19904
+ `HTTP ${res.status}: ${text.slice(0, 400)}`
19905
+ );
19906
+ throw new Error(`generateTokenUser failed: ${msg}`);
19907
+ }
19908
+ const session = data;
19909
+ if (!session.token || !session.type) {
19910
+ throw new Error(
19911
+ "generateTokenUser: success response missing token or type. Check INWORLD_PLATFORM_URL and environment."
19912
+ );
19913
+ }
19914
+ return session;
19915
+ }
19916
+ var init_exchange = __esm({
19917
+ "src/mcp/auth/exchange.ts"() {
19918
+ "use strict";
19919
+ init_constants5();
19920
+ init_identity();
19921
+ }
19922
+ });
19923
+
19924
+ // src/mcp/auth/paths.ts
19925
+ import fs3 from "node:fs";
19926
+ import os3 from "node:os";
19927
+ import path5 from "node:path";
19928
+ function getSessionFilePath() {
19929
+ const base = process.env.INWORLD_SESSION_FILE ?? path5.join(os3.homedir(), ".config", DIR_NAME, "session.json");
19930
+ return base;
19931
+ }
19932
+ function ensureSessionDir(filePath) {
19933
+ const dir = path5.dirname(filePath);
19934
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
19935
+ }
19936
+ var DIR_NAME;
19937
+ var init_paths = __esm({
19938
+ "src/mcp/auth/paths.ts"() {
19939
+ "use strict";
19940
+ DIR_NAME = "inworld-mcp";
19941
+ }
19942
+ });
19943
+
19944
+ // src/mcp/auth/session.ts
19945
+ import fs4 from "node:fs";
19946
+ function getExpirationMs(session) {
19947
+ const e = session.expirationTime;
19948
+ if (e == null) return null;
19949
+ if (typeof e === "string") {
19950
+ const t = new Date(e).getTime();
19951
+ return Number.isNaN(t) ? null : t;
19952
+ }
19953
+ if (typeof e === "object" && "seconds" in e) {
19954
+ const sec = Number(e.seconds ?? 0);
19955
+ const nanos = Number(e.nanos ?? 0);
19956
+ return sec * 1e3 + Math.floor(nanos / 1e6);
19957
+ }
19958
+ return null;
19959
+ }
19960
+ function isSessionActive(session) {
19961
+ const exp = getExpirationMs(session);
19962
+ if (exp == null) return false;
19963
+ return exp - Date.now() > TIME_DIFF_MS;
19964
+ }
19965
+ function loadSession() {
19966
+ const p = getSessionFilePath();
19967
+ try {
19968
+ const raw = fs4.readFileSync(p, "utf8");
19969
+ const data = JSON.parse(raw);
19970
+ if (!data?.token || !data?.type) return null;
19971
+ const { firebaseIdToken, firebaseRefreshToken, ...rest } = data;
19972
+ return {
19973
+ ...rest,
19974
+ identityToken: rest.identityToken ?? firebaseIdToken,
19975
+ identityRefreshToken: rest.identityRefreshToken ?? firebaseRefreshToken
19976
+ };
19977
+ } catch {
19978
+ return null;
19979
+ }
19980
+ }
19981
+ function saveSession(session) {
19982
+ const p = getSessionFilePath();
19983
+ ensureSessionDir(p);
19984
+ fs4.writeFileSync(p, JSON.stringify(session, null, 0), { mode: 384 });
19985
+ try {
19986
+ fs4.chmodSync(p, 384);
19987
+ } catch {
19988
+ }
19989
+ }
19990
+ function clearSession() {
19991
+ const p = getSessionFilePath();
19992
+ try {
19993
+ fs4.unlinkSync(p);
19994
+ } catch {
19995
+ }
19996
+ }
19997
+ function hasStoredCredentials() {
19998
+ const s = loadSession();
19999
+ if (!s?.token || !s?.type) return false;
20000
+ if (isSessionActive(s)) return true;
20001
+ return typeof s.identityRefreshToken === "string" && s.identityRefreshToken.length > 0;
20002
+ }
20003
+ async function hasUsableAuthCredentials() {
20004
+ if (process.env.INWORLD_API_KEY?.trim()) return true;
20005
+ if (hasStoredCredentials()) return true;
20006
+ try {
20007
+ const c3 = await readStoredCredentials();
20008
+ if (c3?.refreshToken?.trim()) return true;
20009
+ if (c3?.apiKey?.trim()) return true;
20010
+ } catch {
20011
+ }
20012
+ return false;
20013
+ }
20014
+ var TIME_DIFF_MS;
20015
+ var init_session = __esm({
20016
+ "src/mcp/auth/session.ts"() {
20017
+ "use strict";
20018
+ init_dist4();
20019
+ init_paths();
20020
+ TIME_DIFF_MS = 120 * 1e3;
20021
+ }
20022
+ });
20023
+
20024
+ // src/mcp/auth/cli-store-bridge.ts
20025
+ function identitySourceOfStore(c3) {
20026
+ return c3.authProvider === "supabase" ? { provider: "supabase", authUrl: c3.authUrl } : { provider: "firebase" };
20027
+ }
20028
+ async function persistRotatedRefreshToken(used, next) {
20029
+ const c3 = await readStoredCredentials();
20030
+ if (!c3?.refreshToken) return false;
20031
+ if (used !== next && c3.refreshToken === used) {
20032
+ await writeStoredCredentials({ ...c3, refreshToken: next });
20033
+ }
20034
+ return true;
20035
+ }
20036
+ async function saveSessionUnlessLoggedOut(session) {
20037
+ saveSession(session);
20038
+ const c3 = await readStoredCredentials().catch(() => null);
20039
+ if (c3?.refreshToken) return true;
20040
+ clearSession();
20041
+ return false;
20042
+ }
20043
+ async function hydrateMcpSessionFromCliStore() {
20044
+ const c3 = await readStoredCredentials();
20045
+ const refreshToken = c3?.refreshToken?.trim();
20046
+ if (!c3 || !refreshToken) {
20047
+ return null;
20048
+ }
20049
+ try {
20050
+ const source = identitySourceOfStore(c3);
20051
+ const rt = await refreshIdentityToken(source, refreshToken);
20052
+ if (!await persistRotatedRefreshToken(refreshToken, rt.refreshToken)) {
20053
+ return null;
20054
+ }
20055
+ const exchanged = await exchangeIdentityToken(rt.idToken);
20056
+ const merged = {
20057
+ ...exchanged,
20058
+ identityToken: rt.idToken,
20059
+ identityRefreshToken: rt.refreshToken,
20060
+ authProvider: source.provider,
20061
+ authUrl: source.authUrl,
20062
+ email: c3.email ?? exchanged.email
20063
+ };
20064
+ return await saveSessionUnlessLoggedOut(merged) ? merged : null;
20065
+ } catch {
20066
+ return null;
20067
+ }
20068
+ }
20069
+ var init_cli_store_bridge = __esm({
20070
+ "src/mcp/auth/cli-store-bridge.ts"() {
20071
+ "use strict";
20072
+ init_dist4();
20073
+ init_exchange();
20074
+ init_identity();
20075
+ init_session();
20076
+ }
20077
+ });
20078
+
20079
+ // src/services/tts_models.ts
20080
+ var LEGACY_MODELS, DEFAULT_TTS_MODEL, TTS_MODEL_HELP;
20081
+ var init_tts_models = __esm({
20082
+ "src/services/tts_models.ts"() {
20083
+ "use strict";
20084
+ LEGACY_MODELS = /* @__PURE__ */ new Set([
20085
+ "inworld-tts-1" /* INWORLD_TTS_1 */,
20086
+ "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */
20087
+ ]);
20088
+ DEFAULT_TTS_MODEL = "inworld-tts-2" /* INWORLD_TTS_2 */;
20089
+ TTS_MODEL_HELP = "TTS model (inworld-tts-2, inworld-tts-2-flash; deprecated: inworld-tts-1.5-mini, inworld-tts-1.5-max)";
20090
+ }
20091
+ });
20092
+
19525
20093
  // ../../node_modules/adm-zip/util/constants.js
19526
20094
  var require_constants2 = __commonJS({
19527
20095
  "../../node_modules/adm-zip/util/constants.js"(exports, module) {
@@ -22681,6 +23249,26 @@ var require_cross_spawn = __commonJS({
22681
23249
  }
22682
23250
  });
22683
23251
 
23252
+ // src/mcp/auth/browser.ts
23253
+ import { execFile } from "node:child_process";
23254
+ import { promisify as promisify4 } from "node:util";
23255
+ async function openInBrowser(url) {
23256
+ if (process.platform === "darwin") {
23257
+ await execFileAsync("open", [url]);
23258
+ } else if (process.platform === "win32") {
23259
+ await execFileAsync("rundll32", ["url.dll,FileProtocolHandler", url]);
23260
+ } else {
23261
+ await execFileAsync("xdg-open", [url]);
23262
+ }
23263
+ }
23264
+ var execFileAsync;
23265
+ var init_browser = __esm({
23266
+ "src/mcp/auth/browser.ts"() {
23267
+ "use strict";
23268
+ execFileAsync = promisify4(execFile);
23269
+ }
23270
+ });
23271
+
22684
23272
  // ../../node_modules/ms/index.js
22685
23273
  var require_ms = __commonJS({
22686
23274
  "../../node_modules/ms/index.js"(exports, module) {
@@ -23449,7 +24037,7 @@ var require_promisify = __commonJS({
23449
24037
  "../../node_modules/agent-base/dist/src/promisify.js"(exports) {
23450
24038
  "use strict";
23451
24039
  Object.defineProperty(exports, "__esModule", { value: true });
23452
- function promisify6(fn) {
24040
+ function promisify5(fn) {
23453
24041
  return function(req, opts) {
23454
24042
  return new Promise((resolve4, reject) => {
23455
24043
  fn.call(this, req, opts, (err, rtn) => {
@@ -23462,7 +24050,7 @@ var require_promisify = __commonJS({
23462
24050
  });
23463
24051
  };
23464
24052
  }
23465
- exports.default = promisify6;
24053
+ exports.default = promisify5;
23466
24054
  }
23467
24055
  });
23468
24056
 
@@ -24600,7 +25188,7 @@ var require_mixpanel_node = __commonJS({
24600
25188
  "../../node_modules/mixpanel/lib/mixpanel-node.js"(exports, module) {
24601
25189
  var querystring = __require("querystring");
24602
25190
  var Buffer5 = __require("buffer").Buffer;
24603
- var http3 = __require("http");
25191
+ var http4 = __require("http");
24604
25192
  var https = __require("https");
24605
25193
  var HttpsProxyAgent = require_dist2();
24606
25194
  var url = __require("url");
@@ -24631,9 +25219,9 @@ var require_mixpanel_node = __commonJS({
24631
25219
  };
24632
25220
  const { keepAlive } = metrics.config;
24633
25221
  const MAX_BATCH_SIZE = 50;
24634
- const REQUEST_LIBS = { http: http3, https };
25222
+ const REQUEST_LIBS = { http: http4, https };
24635
25223
  const REQUEST_AGENTS = {
24636
- http: new http3.Agent({ keepAlive }),
25224
+ http: new http4.Agent({ keepAlive }),
24637
25225
  https: new https.Agent({ keepAlive })
24638
25226
  };
24639
25227
  const proxyPath = process.env.HTTPS_PROXY || process.env.HTTP_PROXY;
@@ -42579,8 +43167,8 @@ var require_escape_html = __commonJS({
42579
43167
  "../../node_modules/escape-html/index.js"(exports, module) {
42580
43168
  "use strict";
42581
43169
  var matchHtmlRegExp = /["'&<>]/;
42582
- module.exports = escapeHtml;
42583
- function escapeHtml(string3) {
43170
+ module.exports = escapeHtml2;
43171
+ function escapeHtml2(string3) {
42584
43172
  var str = "" + string3;
42585
43173
  var match = matchHtmlRegExp.exec(str);
42586
43174
  if (!match) {
@@ -42711,13 +43299,13 @@ var require_finalhandler = __commonJS({
42711
43299
  "use strict";
42712
43300
  var debug = require_src()("finalhandler");
42713
43301
  var encodeUrl = require_encodeurl();
42714
- var escapeHtml = require_escape_html();
43302
+ var escapeHtml2 = require_escape_html();
42715
43303
  var onFinished = require_on_finished();
42716
43304
  var parseUrl = require_parseurl();
42717
43305
  var statuses = require_statuses();
42718
43306
  var isFinished = onFinished.isFinished;
42719
43307
  function createHtmlDocument(message) {
42720
- var body = escapeHtml(message).replaceAll("\n", "<br>").replaceAll(" ", " &nbsp;");
43308
+ var body = escapeHtml2(message).replaceAll("\n", "<br>").replaceAll(" ", " &nbsp;");
42721
43309
  return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>' + body + "</pre>\n</body>\n</html>\n";
42722
43310
  }
42723
43311
  module.exports = finalhandler;
@@ -45052,7 +45640,7 @@ var require_application = __commonJS({
45052
45640
  var finalhandler = require_finalhandler();
45053
45641
  var debug = require_src()("express:application");
45054
45642
  var View = require_view();
45055
- var http3 = __require("node:http");
45643
+ var http4 = __require("node:http");
45056
45644
  var methods = require_utils6().methods;
45057
45645
  var compileETag = require_utils6().compileETag;
45058
45646
  var compileQueryParser = require_utils6().compileQueryParser;
@@ -45285,7 +45873,7 @@ var require_application = __commonJS({
45285
45873
  tryRender(view, renderOptions, done);
45286
45874
  };
45287
45875
  app.listen = function listen() {
45288
- var server = http3.createServer(this);
45876
+ var server = http4.createServer(this);
45289
45877
  var args = slice.call(arguments);
45290
45878
  if (typeof args[args.length - 1] === "function") {
45291
45879
  var done = args[args.length - 1] = once9(args[args.length - 1]);
@@ -46060,12 +46648,12 @@ var require_request = __commonJS({
46060
46648
  var accepts = require_accepts();
46061
46649
  var isIP = __require("node:net").isIP;
46062
46650
  var typeis = require_type_is();
46063
- var http3 = __require("node:http");
46651
+ var http4 = __require("node:http");
46064
46652
  var fresh = require_fresh();
46065
46653
  var parseRange = require_range_parser();
46066
46654
  var parse3 = require_parseurl();
46067
46655
  var proxyaddr = require_proxy_addr();
46068
- var req = Object.create(http3.IncomingMessage.prototype);
46656
+ var req = Object.create(http4.IncomingMessage.prototype);
46069
46657
  module.exports = req;
46070
46658
  req.get = req.header = function header(name) {
46071
46659
  if (!name) {
@@ -46601,7 +47189,7 @@ var require_send = __commonJS({
46601
47189
  var createError = require_http_errors();
46602
47190
  var debug = require_src()("send");
46603
47191
  var encodeUrl = require_encodeurl();
46604
- var escapeHtml = require_escape_html();
47192
+ var escapeHtml2 = require_escape_html();
46605
47193
  var etag = require_etag();
46606
47194
  var fresh = require_fresh();
46607
47195
  var fs6 = __require("fs");
@@ -46654,7 +47242,7 @@ var require_send = __commonJS({
46654
47242
  }
46655
47243
  var res = this.res;
46656
47244
  var msg = statuses.message[status] || String(status);
46657
- var doc = createHtmlDocument("Error", escapeHtml(msg));
47245
+ var doc = createHtmlDocument("Error", escapeHtml2(msg));
46658
47246
  clearHeaders(res);
46659
47247
  if (err && err.headers) {
46660
47248
  setHeaders(res, err.headers);
@@ -46754,7 +47342,7 @@ var require_send = __commonJS({
46754
47342
  return;
46755
47343
  }
46756
47344
  var loc = encodeUrl(collapseLeadingSlashes(this.path + "/"));
46757
- var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc));
47345
+ var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
46758
47346
  res.statusCode = 301;
46759
47347
  res.setHeader("Content-Type", "text/html; charset=UTF-8");
46760
47348
  res.setHeader("Content-Length", Buffer.byteLength(doc));
@@ -47158,8 +47746,8 @@ var require_response = __commonJS({
47158
47746
  var createError = require_http_errors();
47159
47747
  var deprecate = require_depd()("express");
47160
47748
  var encodeUrl = require_encodeurl();
47161
- var escapeHtml = require_escape_html();
47162
- var http3 = __require("node:http");
47749
+ var escapeHtml2 = require_escape_html();
47750
+ var http4 = __require("node:http");
47163
47751
  var onFinished = require_on_finished();
47164
47752
  var mime = require_mime_types();
47165
47753
  var path13 = __require("node:path");
@@ -47175,7 +47763,7 @@ var require_response = __commonJS({
47175
47763
  var resolve4 = path13.resolve;
47176
47764
  var vary = require_vary();
47177
47765
  var { Buffer: Buffer5 } = __require("node:buffer");
47178
- var res = Object.create(http3.ServerResponse.prototype);
47766
+ var res = Object.create(http4.ServerResponse.prototype);
47179
47767
  module.exports = res;
47180
47768
  res.status = function status(code) {
47181
47769
  if (!Number.isInteger(code)) {
@@ -47497,7 +48085,7 @@ var require_response = __commonJS({
47497
48085
  body = statuses.message[status] + ". Redirecting to " + address;
47498
48086
  },
47499
48087
  html: function() {
47500
- var u2 = escapeHtml(address);
48088
+ var u2 = escapeHtml2(address);
47501
48089
  body = "<p>" + statuses.message[status] + ". Redirecting to " + u2 + "</p>";
47502
48090
  },
47503
48091
  default: function() {
@@ -47625,7 +48213,7 @@ var require_serve_static = __commonJS({
47625
48213
  "../../node_modules/serve-static/index.js"(exports, module) {
47626
48214
  "use strict";
47627
48215
  var encodeUrl = require_encodeurl();
47628
- var escapeHtml = require_escape_html();
48216
+ var escapeHtml2 = require_escape_html();
47629
48217
  var parseUrl = require_parseurl();
47630
48218
  var resolve4 = __require("path").resolve;
47631
48219
  var send = require_send();
@@ -47711,7 +48299,7 @@ var require_serve_static = __commonJS({
47711
48299
  originalUrl.path = null;
47712
48300
  originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/");
47713
48301
  var loc = encodeUrl(url.format(originalUrl));
47714
- var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc));
48302
+ var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml2(loc));
47715
48303
  res.statusCode = 301;
47716
48304
  res.setHeader("Content-Type", "text/html; charset=UTF-8");
47717
48305
  res.setHeader("Content-Length", Buffer.byteLength(doc));
@@ -52708,7 +53296,7 @@ function datetime(args) {
52708
53296
  const timeRegex2 = `${time3}(?:${opts.join("|")})`;
52709
53297
  return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
52710
53298
  }
52711
- var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname, e164, dateSource, date, string, integer, number, boolean, _null, lowercase, uppercase;
53299
+ var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url2, hostname, e164, dateSource, date, string, integer, number, boolean, _null, lowercase, uppercase;
52712
53300
  var init_regexes = __esm({
52713
53301
  "../../node_modules/zod/v4/core/regexes.js"() {
52714
53302
  cuid = /^[cC][^\s-]{8,}$/;
@@ -52731,7 +53319,7 @@ var init_regexes = __esm({
52731
53319
  cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
52732
53320
  cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
52733
53321
  base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
52734
- base64url = /^[A-Za-z0-9_-]*$/;
53322
+ base64url2 = /^[A-Za-z0-9_-]*$/;
52735
53323
  hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
52736
53324
  e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
52737
53325
  dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
@@ -53209,7 +53797,7 @@ function isValidBase64(data) {
53209
53797
  }
53210
53798
  }
53211
53799
  function isValidBase64URL(data) {
53212
- if (!base64url.test(data))
53800
+ if (!base64url2.test(data))
53213
53801
  return false;
53214
53802
  const base642 = data.replace(/[-_]/g, (c3) => c3 === "-" ? "+" : "/");
53215
53803
  const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
@@ -53704,7 +54292,7 @@ var init_schemas = __esm({
53704
54292
  };
53705
54293
  });
53706
54294
  $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
53707
- def.pattern ?? (def.pattern = base64url);
54295
+ def.pattern ?? (def.pattern = base64url2);
53708
54296
  $ZodStringFormat.init(inst, def);
53709
54297
  inst._zod.onattach.push((inst2) => {
53710
54298
  inst2._zod.bag.contentEncoding = "base64url";
@@ -69842,44 +70430,6 @@ var init_bearer = __esm({
69842
70430
  }
69843
70431
  });
69844
70432
 
69845
- // src/mcp/auth/constants.ts
69846
- function getMcpHttpAuthMode() {
69847
- const v = (process.env.INWORLD_MCP_HTTP_AUTH || "session").toLowerCase();
69848
- if (v === "bearer") return "bearer";
69849
- return "session";
69850
- }
69851
- var DEFAULT_PLATFORM_ENDPOINT2, resolvePlatformUrl2, INWORLD_ENV2, PLATFORM_URL2, FIREBASE_API_KEY2, INWORLD_CLI_AUTH_URL2, INWORLD_CLI_AUTH_CALLBACK_PORT2;
69852
- var init_constants5 = __esm({
69853
- "src/mcp/auth/constants.ts"() {
69854
- "use strict";
69855
- DEFAULT_PLATFORM_ENDPOINT2 = "https://platform.inworld.ai";
69856
- resolvePlatformUrl2 = () => {
69857
- if (process.env.INWORLD_PLATFORM_URL) {
69858
- return process.env.INWORLD_PLATFORM_URL;
69859
- }
69860
- const env3 = (process.env.INWORLD_ENV || "").toUpperCase();
69861
- switch (env3) {
69862
- case "DEV":
69863
- return "https://platform.dev.inworld.ai";
69864
- case "STAGE":
69865
- return "https://platform.stage.inworld.ai";
69866
- case "PROD":
69867
- return "https://platform.inworld.ai";
69868
- default:
69869
- return DEFAULT_PLATFORM_ENDPOINT2;
69870
- }
69871
- };
69872
- INWORLD_ENV2 = process.env.INWORLD_ENV || "PROD";
69873
- PLATFORM_URL2 = resolvePlatformUrl2();
69874
- FIREBASE_API_KEY2 = process.env.INWORLD_FIREBASE_API_KEY || process.env.FIREBASE_API_KEY || "AIzaSyAPVBLVid0xPwjuU4Gmn_6_GyqxBq-SwQs";
69875
- INWORLD_CLI_AUTH_URL2 = process.env.INWORLD_CLI_AUTH_URL || "https://cli.inworld.ai/login";
69876
- INWORLD_CLI_AUTH_CALLBACK_PORT2 = parseInt(
69877
- process.env.INWORLD_CLI_AUTH_CALLBACK_PORT || "8085",
69878
- 10
69879
- );
69880
- }
69881
- });
69882
-
69883
70433
  // src/mcp/auth/gate.ts
69884
70434
  function skipAuth() {
69885
70435
  const v = process.env.INWORLD_SKIP_AUTH;
@@ -69907,260 +70457,7 @@ var init_request_session = __esm({
69907
70457
  }
69908
70458
  });
69909
70459
 
69910
- // src/mcp/auth/paths.ts
69911
- import fs4 from "node:fs";
69912
- import os4 from "node:os";
69913
- import path11 from "node:path";
69914
- function getSessionFilePath() {
69915
- const base = process.env.INWORLD_SESSION_FILE ?? path11.join(os4.homedir(), ".config", DIR_NAME, "session.json");
69916
- return base;
69917
- }
69918
- function ensureSessionDir(filePath) {
69919
- const dir = path11.dirname(filePath);
69920
- fs4.mkdirSync(dir, { recursive: true, mode: 448 });
69921
- }
69922
- var DIR_NAME;
69923
- var init_paths = __esm({
69924
- "src/mcp/auth/paths.ts"() {
69925
- "use strict";
69926
- DIR_NAME = "inworld-mcp";
69927
- }
69928
- });
69929
-
69930
- // src/mcp/auth/session.ts
69931
- import fs5 from "node:fs";
69932
- function getExpirationMs(session) {
69933
- const e = session.expirationTime;
69934
- if (e == null) return null;
69935
- if (typeof e === "string") {
69936
- const t = new Date(e).getTime();
69937
- return Number.isNaN(t) ? null : t;
69938
- }
69939
- if (typeof e === "object" && "seconds" in e) {
69940
- const sec = Number(e.seconds ?? 0);
69941
- const nanos = Number(e.nanos ?? 0);
69942
- return sec * 1e3 + Math.floor(nanos / 1e6);
69943
- }
69944
- return null;
69945
- }
69946
- function isSessionActive(session) {
69947
- const exp = getExpirationMs(session);
69948
- if (exp == null) return false;
69949
- return exp - Date.now() > TIME_DIFF_MS;
69950
- }
69951
- function loadSession() {
69952
- const p = getSessionFilePath();
69953
- try {
69954
- const raw = fs5.readFileSync(p, "utf8");
69955
- const data = JSON.parse(raw);
69956
- if (!data?.token || !data?.type) return null;
69957
- return data;
69958
- } catch {
69959
- return null;
69960
- }
69961
- }
69962
- function saveSession(session) {
69963
- const p = getSessionFilePath();
69964
- ensureSessionDir(p);
69965
- fs5.writeFileSync(p, JSON.stringify(session, null, 0), { mode: 384 });
69966
- try {
69967
- fs5.chmodSync(p, 384);
69968
- } catch {
69969
- }
69970
- }
69971
- function hasStoredCredentials() {
69972
- const s = loadSession();
69973
- if (!s?.token || !s?.type) return false;
69974
- if (isSessionActive(s)) return true;
69975
- return typeof s.firebaseRefreshToken === "string" && s.firebaseRefreshToken.length > 0;
69976
- }
69977
- async function hasUsableAuthCredentials() {
69978
- if (process.env.INWORLD_API_KEY?.trim()) return true;
69979
- if (hasStoredCredentials()) return true;
69980
- try {
69981
- const c3 = await readStoredCredentials();
69982
- if (c3?.refreshToken?.trim()) return true;
69983
- if (c3?.apiKey?.trim()) return true;
69984
- } catch {
69985
- }
69986
- return false;
69987
- }
69988
- var TIME_DIFF_MS;
69989
- var init_session = __esm({
69990
- "src/mcp/auth/session.ts"() {
69991
- "use strict";
69992
- init_dist4();
69993
- init_paths();
69994
- TIME_DIFF_MS = 120 * 1e3;
69995
- }
69996
- });
69997
-
69998
- // src/mcp/auth/exchange.ts
69999
- function formatNetworkError(err, url) {
70000
- if (err instanceof TypeError && err.message === "fetch failed") {
70001
- const cause = err.cause;
70002
- const code = cause?.code ?? "";
70003
- const hint = "Set INWORLD_PLATFORM_URL or INWORLD_ENV (DEV/STAGE/PROD) to match your environment.";
70004
- return new Error(
70005
- `Cannot reach platform at ${url}${code ? ` (${code})` : ""}. ${hint}`
70006
- );
70007
- }
70008
- return err instanceof Error ? err : new Error(String(err));
70009
- }
70010
- function extractGatewayErrorMessage(data, fallback) {
70011
- if (data && typeof data === "object") {
70012
- const o2 = data;
70013
- if (typeof o2.message === "string" && o2.message.length > 0) {
70014
- return o2.message;
70015
- }
70016
- const err = o2.error;
70017
- if (err && typeof err === "object" && typeof err.message === "string") {
70018
- return err.message;
70019
- }
70020
- }
70021
- return fallback;
70022
- }
70023
- async function exchangeFirebaseIdToken(firebaseIdToken) {
70024
- const base = PLATFORM_URL2.replace(/\/$/, "");
70025
- const url = `${base}/v1alpha/users:generateTokenUser`;
70026
- const body = JSON.stringify({
70027
- type: "AUTH_TYPE_FIREBASE",
70028
- token: firebaseIdToken
70029
- });
70030
- let res;
70031
- try {
70032
- res = await fetch(url, {
70033
- method: "POST",
70034
- headers: {
70035
- "Content-Type": "application/json",
70036
- Authorization: `Bearer ${firebaseIdToken}`,
70037
- [BEARER_TYPE_HEADER]: "firebase"
70038
- },
70039
- body
70040
- });
70041
- } catch (err) {
70042
- throw formatNetworkError(err, url);
70043
- }
70044
- const text = await res.text();
70045
- let data;
70046
- try {
70047
- data = text ? JSON.parse(text) : {};
70048
- } catch {
70049
- throw new Error(
70050
- `generateTokenUser: response was not JSON (${res.status}): ${text.slice(0, 240)}`
70051
- );
70052
- }
70053
- if (!res.ok) {
70054
- const msg = extractGatewayErrorMessage(
70055
- data,
70056
- `HTTP ${res.status}: ${text.slice(0, 400)}`
70057
- );
70058
- throw new Error(`generateTokenUser failed: ${msg}`);
70059
- }
70060
- const session = data;
70061
- if (!session.token || !session.type) {
70062
- throw new Error(
70063
- "generateTokenUser: success response missing token or type. Check INWORLD_PLATFORM_URL and environment."
70064
- );
70065
- }
70066
- return session;
70067
- }
70068
- var BEARER_TYPE_HEADER;
70069
- var init_exchange = __esm({
70070
- "src/mcp/auth/exchange.ts"() {
70071
- "use strict";
70072
- init_constants5();
70073
- BEARER_TYPE_HEADER = "Grpc-Metadata-X-Authorization-Bearer-Type";
70074
- }
70075
- });
70076
-
70077
- // src/mcp/auth/firebase-refresh.ts
70078
- async function refreshFirebaseWithRefreshToken(refreshToken) {
70079
- const url = `https://securetoken.googleapis.com/v1/token?key=${encodeURIComponent(FIREBASE_API_KEY2)}`;
70080
- const body = new URLSearchParams({
70081
- grant_type: "refresh_token",
70082
- refresh_token: refreshToken
70083
- });
70084
- const res = await fetch(url, {
70085
- method: "POST",
70086
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
70087
- body: body.toString()
70088
- });
70089
- const text = await res.text();
70090
- let data;
70091
- try {
70092
- data = text ? JSON.parse(text) : {};
70093
- } catch {
70094
- throw new Error(
70095
- `Firebase token refresh: expected JSON (${res.status}): ${text.slice(0, 200)}`
70096
- );
70097
- }
70098
- if (!res.ok) {
70099
- const err = data.error;
70100
- const msg = typeof err?.message === "string" ? err.message : typeof data.message === "string" ? data.message : text.slice(0, 300);
70101
- throw new Error(`Firebase token refresh failed: ${msg}`);
70102
- }
70103
- const idToken = data.id_token;
70104
- const newRefresh = data.refresh_token;
70105
- if (typeof idToken !== "string") {
70106
- throw new Error("Firebase token refresh: response missing id_token");
70107
- }
70108
- return {
70109
- idToken,
70110
- refreshToken: typeof newRefresh === "string" ? newRefresh : refreshToken,
70111
- expiresIn: String(data.expires_in ?? "")
70112
- };
70113
- }
70114
- var init_firebase_refresh = __esm({
70115
- "src/mcp/auth/firebase-refresh.ts"() {
70116
- "use strict";
70117
- init_constants5();
70118
- }
70119
- });
70120
-
70121
- // src/mcp/auth/cli-store-bridge.ts
70122
- async function hydrateMcpSessionFromCliStore() {
70123
- const c3 = await readStoredCredentials();
70124
- if (!c3?.refreshToken?.trim()) {
70125
- return null;
70126
- }
70127
- try {
70128
- const rt = await refreshFirebaseWithRefreshToken(c3.refreshToken.trim());
70129
- const exchanged = await exchangeFirebaseIdToken(rt.idToken);
70130
- const merged = {
70131
- ...exchanged,
70132
- firebaseIdToken: rt.idToken,
70133
- firebaseRefreshToken: rt.refreshToken,
70134
- email: c3.email ?? exchanged.email
70135
- };
70136
- saveSession(merged);
70137
- return merged;
70138
- } catch {
70139
- return null;
70140
- }
70141
- }
70142
- var init_cli_store_bridge = __esm({
70143
- "src/mcp/auth/cli-store-bridge.ts"() {
70144
- "use strict";
70145
- init_dist4();
70146
- init_exchange();
70147
- init_firebase_refresh();
70148
- init_session();
70149
- }
70150
- });
70151
-
70152
70460
  // src/mcp/auth/session-refresh.ts
70153
- function decodeJwtPayload(jwt) {
70154
- const parts = jwt.split(".");
70155
- if (parts.length < 2) return null;
70156
- const b642 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
70157
- try {
70158
- const json = Buffer.from(b642, "base64").toString("utf8");
70159
- return JSON.parse(json);
70160
- } catch {
70161
- return null;
70162
- }
70163
- }
70164
70461
  function isJwtNearExpiry(jwt, marginMs) {
70165
70462
  const p = decodeJwtPayload(jwt);
70166
70463
  const exp = p?.exp;
@@ -70173,6 +70470,19 @@ function shouldRefreshInworld(s) {
70173
70470
  if (exp == null) return false;
70174
70471
  return exp - Date.now() < INWORLD_RENEW_MARGIN_MS;
70175
70472
  }
70473
+ async function currentRefreshToken(s, source) {
70474
+ if (source.provider === "supabase") {
70475
+ try {
70476
+ const c3 = await readStoredCredentials();
70477
+ const stored = c3 ? identitySourceOfStore(c3) : void 0;
70478
+ if (c3?.refreshToken && stored?.authUrl === source.authUrl) {
70479
+ return c3.refreshToken.trim();
70480
+ }
70481
+ } catch {
70482
+ }
70483
+ }
70484
+ return s.identityRefreshToken?.trim();
70485
+ }
70176
70486
  async function getValidSession() {
70177
70487
  const fromReq = getRequestSession();
70178
70488
  if (fromReq?.token && fromReq?.type) {
@@ -70183,25 +70493,31 @@ async function getValidSession() {
70183
70493
  s = await hydrateMcpSessionFromCliStore();
70184
70494
  }
70185
70495
  if (!s?.token || !s?.type) return null;
70186
- const refresh = s.firebaseRefreshToken?.trim();
70187
- const needFirebaseRefresh = typeof s.firebaseIdToken === "string" && s.firebaseIdToken.length > 0 && isJwtNearExpiry(s.firebaseIdToken, FIREBASE_RENEW_MARGIN_MS);
70496
+ const needIdentityRefresh = typeof s.identityToken === "string" && s.identityToken.length > 0 && isJwtNearExpiry(s.identityToken, IDENTITY_RENEW_MARGIN_MS);
70188
70497
  const needInworldRefresh = shouldRefreshInworld(s);
70189
- if (!needInworldRefresh && !needFirebaseRefresh) {
70498
+ if (!needInworldRefresh && !needIdentityRefresh) {
70190
70499
  return s;
70191
70500
  }
70501
+ const source = s.authProvider === "supabase" ? { provider: "supabase", authUrl: s.authUrl } : { provider: "firebase" };
70502
+ const refresh = await currentRefreshToken(s, source);
70192
70503
  if (!refresh) {
70193
70504
  return isSessionActive(s) ? s : null;
70194
70505
  }
70195
70506
  try {
70196
- const rt = await refreshFirebaseWithRefreshToken(refresh);
70197
- const exchanged = await exchangeFirebaseIdToken(rt.idToken);
70507
+ const rt = await refreshIdentityToken(source, refresh);
70508
+ if (!await persistRotatedRefreshToken(refresh, rt.refreshToken)) {
70509
+ return null;
70510
+ }
70511
+ const exchanged = await exchangeIdentityToken(rt.idToken);
70198
70512
  const merged = {
70199
70513
  ...exchanged,
70200
- firebaseIdToken: rt.idToken,
70201
- firebaseRefreshToken: rt.refreshToken,
70514
+ identityToken: rt.idToken,
70515
+ identityRefreshToken: rt.refreshToken,
70516
+ authProvider: source.provider,
70517
+ authUrl: source.authUrl,
70202
70518
  email: s.email
70203
70519
  };
70204
- saveSession(merged);
70520
+ if (!await saveSessionUnlessLoggedOut(merged)) return null;
70205
70521
  const next = loadSession();
70206
70522
  if (!next?.token || !next?.type) return null;
70207
70523
  return isSessionActive(next) ? next : null;
@@ -70209,16 +70525,17 @@ async function getValidSession() {
70209
70525
  return isSessionActive(s) ? s : null;
70210
70526
  }
70211
70527
  }
70212
- var FIREBASE_RENEW_MARGIN_MS, INWORLD_RENEW_MARGIN_MS;
70528
+ var IDENTITY_RENEW_MARGIN_MS, INWORLD_RENEW_MARGIN_MS;
70213
70529
  var init_session_refresh = __esm({
70214
70530
  "src/mcp/auth/session-refresh.ts"() {
70215
70531
  "use strict";
70532
+ init_dist4();
70216
70533
  init_cli_store_bridge();
70217
70534
  init_exchange();
70218
- init_firebase_refresh();
70535
+ init_identity();
70219
70536
  init_request_session();
70220
70537
  init_session();
70221
- FIREBASE_RENEW_MARGIN_MS = 10 * 60 * 1e3;
70538
+ IDENTITY_RENEW_MARGIN_MS = 10 * 60 * 1e3;
70222
70539
  INWORLD_RENEW_MARGIN_MS = 3 * 60 * 1e3;
70223
70540
  }
70224
70541
  });
@@ -70234,21 +70551,20 @@ function headersForInworldSession(session) {
70234
70551
  [GRPC_BEARER_TYPE_METADATA]: "inworld"
70235
70552
  };
70236
70553
  }
70237
- function headersForFirebaseIdToken(firebaseIdToken) {
70238
- if (!firebaseIdToken) {
70239
- throw new Error(
70240
- "Firebase ID token is required for workspace engine session"
70241
- );
70554
+ function headersForIdentityToken(identityToken) {
70555
+ if (!identityToken) {
70556
+ throw new Error("Identity token is required for workspace engine session");
70242
70557
  }
70243
70558
  return {
70244
- Authorization: `Bearer ${firebaseIdToken}`,
70245
- [GRPC_BEARER_TYPE_METADATA]: "firebase"
70559
+ Authorization: `Bearer ${identityToken}`,
70560
+ [GRPC_BEARER_TYPE_METADATA]: bearerTypeFor(providerForToken(identityToken))
70246
70561
  };
70247
70562
  }
70248
70563
  var GRPC_BEARER_TYPE_METADATA;
70249
70564
  var init_inworld_headers = __esm({
70250
70565
  "src/mcp/auth/inworld-headers.ts"() {
70251
70566
  "use strict";
70567
+ init_identity();
70252
70568
  GRPC_BEARER_TYPE_METADATA = "Grpc-Metadata-X-Authorization-Bearer-Type";
70253
70569
  }
70254
70570
  });
@@ -70664,10 +70980,10 @@ async function fetchWorkspaceEngineSession(workspaceId) {
70664
70980
  "Not signed in or session expired. Run: inworld-mcp login (bearer mode cannot use voice engine APIs without Firebase ID token)."
70665
70981
  );
70666
70982
  }
70667
- const firebaseIdToken = user.firebaseIdToken;
70668
- if (!firebaseIdToken) {
70983
+ const identityToken = user.identityToken;
70984
+ if (!identityToken) {
70669
70985
  throw new Error(
70670
- "Session has no Firebase ID token (needed for workspace engine session). Run `inworld-mcp login` again, or use session-file auth instead of bearer-only HTTP."
70986
+ "Session has no identity token (needed for workspace engine session). Run `inworld-mcp login` again, or use session-file auth instead of bearer-only HTTP."
70671
70987
  );
70672
70988
  }
70673
70989
  const base = PLATFORM_URL2.replace(/\/$/, "");
@@ -70678,7 +70994,7 @@ async function fetchWorkspaceEngineSession(workspaceId) {
70678
70994
  const res = await fetch(url, {
70679
70995
  method: "POST",
70680
70996
  headers: {
70681
- ...headersForFirebaseIdToken(firebaseIdToken),
70997
+ ...headersForIdentityToken(identityToken),
70682
70998
  "Content-Type": "application/json",
70683
70999
  Accept: "application/json"
70684
71000
  },
@@ -70911,12 +71227,11 @@ async function getVoicePreviewV1(voiceId, modelId = DEFAULT_TTS_MODEL) {
70911
71227
  const qs = new URLSearchParams({ voice_id: id, model_id: modelId });
70912
71228
  return studioApiGet(`/tts/v1/voice:preview?${qs.toString()}`, "TTS preview");
70913
71229
  }
70914
- var DEFAULT_TTS_MODEL;
70915
71230
  var init_preview = __esm({
70916
71231
  "src/mcp/tts/preview.ts"() {
70917
71232
  "use strict";
71233
+ init_tts_models();
70918
71234
  init_studio_api();
70919
- DEFAULT_TTS_MODEL = "inworld-tts-1.5-max";
70920
71235
  }
70921
71236
  });
70922
71237
 
@@ -71145,7 +71460,7 @@ var init_schemas4 = __esm({
71145
71460
  });
71146
71461
 
71147
71462
  // src/mcp/auth/callback-server.ts
71148
- import * as http2 from "http";
71463
+ import * as http3 from "http";
71149
71464
  async function createCallbackServer2(options = {}) {
71150
71465
  const {
71151
71466
  port = INWORLD_CLI_AUTH_CALLBACK_PORT2,
@@ -71153,7 +71468,7 @@ async function createCallbackServer2(options = {}) {
71153
71468
  firebaseApiKey = FIREBASE_API_KEY2
71154
71469
  } = options;
71155
71470
  return new Promise((resolve4, reject) => {
71156
- const httpServer = http2.createServer({ keepAlive: false }, (req, res) => {
71471
+ const httpServer = http3.createServer({ keepAlive: false }, (req, res) => {
71157
71472
  const origin = req.headers.origin;
71158
71473
  if (origin && allowedOrigins.includes(origin)) {
71159
71474
  res.setHeader("Access-Control-Allow-Origin", origin);
@@ -71269,85 +71584,112 @@ var init_callback_server = __esm({
71269
71584
  });
71270
71585
 
71271
71586
  // src/mcp/cli/login.ts
71272
- import { exec as exec2 } from "node:child_process";
71273
71587
  import * as readline5 from "node:readline";
71274
- import { promisify as promisify5 } from "node:util";
71275
- async function runLogin() {
71276
- const serverPromise = createCallbackServer2({
71277
- port: INWORLD_CLI_AUTH_CALLBACK_PORT2
71278
- });
71588
+ async function offerBrowser2(url, done) {
71279
71589
  console.error("Please visit the following URL to authenticate:");
71280
- console.error(INWORLD_CLI_AUTH_URL2);
71590
+ console.error(url);
71281
71591
  console.error();
71282
71592
  const readlineInterface = readline5.createInterface({
71283
71593
  input: process.stdin,
71284
71594
  output: process.stdout
71285
71595
  });
71286
- const enterPromise = new Promise((resolve4) => {
71287
- readlineInterface.question("Press Enter to open your browser...", () => {
71288
- resolve4();
71289
- });
71596
+ const enter = new Promise((resolve4) => {
71597
+ readlineInterface.question(
71598
+ "Press Enter to open your browser...",
71599
+ () => resolve4("enter")
71600
+ );
71290
71601
  });
71291
- const result = await Promise.race([
71292
- enterPromise.then(() => ({ type: "enter" })),
71293
- serverPromise.then((r) => ({ type: "auth", result: r }))
71294
- ]);
71602
+ const settled = done.then(
71603
+ () => "done",
71604
+ () => "done"
71605
+ );
71606
+ const first = await Promise.race([enter, settled]);
71295
71607
  readlineInterface.close();
71296
- let authServerResult;
71297
- if (result.type === "auth") {
71298
- authServerResult = result.result;
71299
- } else {
71300
- const openCommand = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
71301
- try {
71302
- await execAsync2(`${openCommand} ${INWORLD_CLI_AUTH_URL2}`);
71303
- console.error("Browser opened.");
71304
- } catch {
71305
- console.error(
71306
- "Could not open browser automatically. Open the URL manually."
71608
+ if (first === "done") return;
71609
+ try {
71610
+ await openInBrowser(url);
71611
+ console.error("Browser opened.");
71612
+ } catch {
71613
+ console.error(
71614
+ "Could not open browser automatically. Open the URL manually."
71615
+ );
71616
+ }
71617
+ console.error();
71618
+ console.error("Waiting for authentication...");
71619
+ }
71620
+ async function signInWithFirebase2() {
71621
+ const serverPromise = createCallbackServer2({
71622
+ port: INWORLD_CLI_AUTH_CALLBACK_PORT2
71623
+ });
71624
+ await offerBrowser2(INWORLD_CLI_AUTH_URL2, serverPromise);
71625
+ const result = await serverPromise;
71626
+ await stopCallbackServer2(result.server);
71627
+ return {
71628
+ idToken: result.token,
71629
+ refreshToken: result.refreshToken,
71630
+ email: result.email
71631
+ };
71632
+ }
71633
+ async function runLogin() {
71634
+ const source = await resolveIdentitySource(PLATFORM_URL2);
71635
+ let tokens;
71636
+ if (source.provider === "supabase") {
71637
+ const oauthProvider = process.env.INWORLD_AUTH_OAUTH_PROVIDER || "google";
71638
+ if (!GOTRUE_OAUTH_PROVIDERS.includes(oauthProvider)) {
71639
+ throw new Error(
71640
+ `INWORLD_AUTH_OAUTH_PROVIDER=${oauthProvider} is not supported by inworld-mcp login (use ${GOTRUE_OAUTH_PROVIDERS.join(", ")}). ` + (oauthProvider === "email" ? "For email/password, run `inworld login --provider email`; the MCP server reuses that session." : "")
71307
71641
  );
71308
71642
  }
71309
- console.error();
71310
- console.error("Waiting for authentication...");
71311
- authServerResult = await serverPromise;
71643
+ const { url, done } = await startOAuthSignIn({
71644
+ authUrl: source.authUrl,
71645
+ oauthProvider
71646
+ });
71647
+ await offerBrowser2(url, done);
71648
+ tokens = await done;
71649
+ } else {
71650
+ tokens = await signInWithFirebase2();
71312
71651
  }
71313
71652
  console.error();
71314
71653
  console.error("Exchanging for Inworld session...");
71315
- const exchanged = await exchangeFirebaseIdToken(authServerResult.token);
71654
+ const exchanged = await exchangeIdentityToken(tokens.idToken);
71316
71655
  const merged = {
71317
71656
  ...exchanged,
71318
- firebaseIdToken: authServerResult.token,
71319
- firebaseRefreshToken: authServerResult.refreshToken,
71320
- email: authServerResult.email
71657
+ identityToken: tokens.idToken,
71658
+ identityRefreshToken: tokens.refreshToken,
71659
+ authProvider: source.provider,
71660
+ authUrl: source.authUrl,
71661
+ email: tokens.email
71321
71662
  };
71322
71663
  saveSession(merged);
71323
71664
  const expiresAt = getExpirationMs(merged) ?? Date.now() + 36e5;
71324
71665
  await writeStoredCredentials({
71325
- refreshToken: authServerResult.refreshToken,
71326
- email: authServerResult.email,
71666
+ refreshToken: tokens.refreshToken,
71667
+ email: tokens.email ?? "",
71327
71668
  inworldToken: merged.token ?? "",
71328
71669
  expiresAt,
71329
- env: INWORLD_ENV2
71670
+ env: INWORLD_ENV2,
71671
+ authProvider: source.provider,
71672
+ authUrl: source.authUrl
71330
71673
  });
71331
- await stopCallbackServer2(authServerResult.server);
71332
71674
  console.error();
71333
71675
  console.error("Signed in.");
71334
- console.error(`Email: ${authServerResult.email}`);
71676
+ console.error(`Email: ${tokens.email}`);
71335
71677
  console.error(`Session saved: ${getSessionFilePath()}`);
71336
71678
  console.error(
71337
71679
  "CLI credentials updated \u2014 `inworld login` is not required separately."
71338
71680
  );
71339
71681
  }
71340
- var execAsync2;
71341
71682
  var init_login = __esm({
71342
71683
  "src/mcp/cli/login.ts"() {
71343
71684
  "use strict";
71344
71685
  init_dist4();
71686
+ init_browser();
71345
71687
  init_callback_server();
71346
71688
  init_constants5();
71347
71689
  init_exchange();
71690
+ init_identity();
71348
71691
  init_paths();
71349
71692
  init_session();
71350
- execAsync2 = promisify5(exec2);
71351
71693
  }
71352
71694
  });
71353
71695
 
@@ -71384,7 +71726,7 @@ function createMcpServer() {
71384
71726
  }
71385
71727
  const exp = getExpirationMs(s);
71386
71728
  const expLine = exp != null ? `Inworld access token expires approximately: ${new Date(exp).toISOString()} (UTC).` : "Inworld expiration time not present in session response.";
71387
- const refreshLine = s.firebaseRefreshToken ? "Automatic token refresh: enabled (Firebase refresh token on disk)." : "Automatic token refresh: not available until you run `inworld-mcp login` again (saves Firebase refresh token).";
71729
+ const refreshLine = s.identityRefreshToken ? "Automatic token refresh: enabled (refresh token on disk)." : "Automatic token refresh: not available until you run `inworld-mcp login` again (saves a refresh token).";
71388
71730
  return {
71389
71731
  content: [
71390
71732
  {
@@ -72587,7 +72929,7 @@ var require_shell_quote = __commonJS({
72587
72929
  // ../../node_modules/find-exec/index.js
72588
72930
  var require_find_exec = __commonJS({
72589
72931
  "../../node_modules/find-exec/index.js"(exports, module) {
72590
- var exec3 = __require("child_process").execSync;
72932
+ var exec = __require("child_process").execSync;
72591
72933
  var platform2 = __require("os").platform();
72592
72934
  var quote = require_shell_quote().quote;
72593
72935
  module.exports = function() {
@@ -72603,7 +72945,7 @@ var require_find_exec = __commonJS({
72603
72945
  };
72604
72946
  function isExec(command) {
72605
72947
  try {
72606
- exec3(quote(command.split(" ")), { stdio: "ignore" });
72948
+ exec(quote(command.split(" ")), { stdio: "ignore" });
72607
72949
  return true;
72608
72950
  } catch (_e) {
72609
72951
  return false;
@@ -73230,7 +73572,7 @@ init_dist4();
73230
73572
  // package.json
73231
73573
  var package_default = {
73232
73574
  name: "@inworld/cli",
73233
- version: "1.1.0",
73575
+ version: "1.3.0",
73234
73576
  type: "module",
73235
73577
  main: "dist/index.js",
73236
73578
  bin: {
@@ -73262,6 +73604,11 @@ var package_default = {
73262
73604
  author: "Inworld AI",
73263
73605
  license: "MIT",
73264
73606
  description: "Inworld CLI: auth, workspace, TTS, and MCP server entry point.",
73607
+ repository: {
73608
+ type: "git",
73609
+ url: "git+https://github.com/inworld-ai/inworld-cli.git",
73610
+ directory: "packages/cli"
73611
+ },
73265
73612
  devDependencies: {
73266
73613
  "@inworld/auth-store": "0.1.0",
73267
73614
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -73332,6 +73679,10 @@ var INWORLD_CLI_AUTH_CALLBACK_PORT = parseInt(
73332
73679
  var MIXPANEL_TOKEN = process.env.INWORLD_MIXPANEL_TOKEN || "2cf13116e9701343ac27ddc452adfbbc";
73333
73680
  var CLI_VERSION = package_default.version;
73334
73681
 
73682
+ // src/auth/manager.ts
73683
+ init_cli_store_bridge();
73684
+ init_identity();
73685
+
73335
73686
  // src/utils/ui.ts
73336
73687
  function printHeader(message) {
73337
73688
  console.log(source_default.bold(message));
@@ -73513,6 +73864,13 @@ function renderURLSearchParams(requestPayload, urlPathParams = []) {
73513
73864
  }
73514
73865
 
73515
73866
  // proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.ts
73867
+ var AuthType = /* @__PURE__ */ ((AuthType2) => {
73868
+ AuthType2["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
73869
+ AuthType2["AUTH_TYPE_OCULUS_NONCE"] = "AUTH_TYPE_OCULUS_NONCE";
73870
+ AuthType2["AUTH_TYPE_FIREBASE"] = "AUTH_TYPE_FIREBASE";
73871
+ AuthType2["AUTH_TYPE_SUPABASE"] = "AUTH_TYPE_SUPABASE";
73872
+ return AuthType2;
73873
+ })(AuthType || {});
73516
73874
  var Users = class {
73517
73875
  static GenerateTokenUser(req, initReq) {
73518
73876
  return fetchReq(
@@ -73641,19 +73999,20 @@ var AuthManager = class {
73641
73999
  return true;
73642
74000
  }
73643
74001
  /**
73644
- * Generates an Inworld token from a Firebase ID token
74002
+ * Generates an Inworld token from a Firebase ID token or GoTrue access token
73645
74003
  */
73646
- async generateInworldToken(firebaseToken) {
74004
+ async generateInworldToken(identityToken) {
74005
+ const provider = providerForToken(identityToken);
73647
74006
  try {
73648
74007
  const tokenResponse = await Users.GenerateTokenUser(
73649
74008
  {
73650
- type: "AUTH_TYPE_FIREBASE" /* AUTH_TYPE_FIREBASE */,
73651
- token: firebaseToken
74009
+ type: AuthType[authTypeFor(provider)],
74010
+ token: identityToken
73652
74011
  },
73653
74012
  {
73654
74013
  headers: {
73655
- Authorization: `Bearer ${firebaseToken}`,
73656
- "Grpc-Metadata-X-Authorization-Bearer-Type": "firebase"
74014
+ Authorization: `Bearer ${identityToken}`,
74015
+ [BEARER_TYPE_HEADER]: bearerTypeFor(provider)
73657
74016
  },
73658
74017
  pathPrefix: PLATFORM_URL
73659
74018
  }
@@ -73680,33 +74039,24 @@ var AuthManager = class {
73680
74039
  return null;
73681
74040
  }
73682
74041
  try {
73683
- const firebaseApiKey = FIREBASE_API_KEY;
73684
- if (!firebaseApiKey) {
73685
- throw new Error("FIREBASE_API_KEY environment variable not set");
73686
- }
73687
- const tokenFetchResponse = await fetch(
73688
- `https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
73689
- {
73690
- method: "POST",
73691
- body: new URLSearchParams({
73692
- grant_type: "refresh_token",
73693
- refresh_token: credentials.refreshToken
73694
- })
73695
- }
74042
+ const refreshed = await refreshIdentityToken(
74043
+ identitySourceOfStore(credentials),
74044
+ credentials.refreshToken
74045
+ );
74046
+ const stillSignedIn = await persistRotatedRefreshToken(
74047
+ credentials.refreshToken,
74048
+ refreshed.refreshToken
73696
74049
  );
73697
- const tokenResponse = await tokenFetchResponse.json();
73698
- if (tokenResponse?.id_token) {
73699
- const inworldTokenResult = await this.generateInworldToken(
73700
- tokenResponse.id_token
74050
+ if (!stillSignedIn) return null;
74051
+ const inworldTokenResult = await this.generateInworldToken(
74052
+ refreshed.idToken
74053
+ );
74054
+ if (inworldTokenResult) {
74055
+ await this.updateInworldToken(
74056
+ inworldTokenResult.token,
74057
+ inworldTokenResult.expiresAt
73701
74058
  );
73702
- if (inworldTokenResult) {
73703
- await this.updateInworldToken(
73704
- inworldTokenResult.token,
73705
- inworldTokenResult.expiresAt
73706
- );
73707
- return inworldTokenResult.token;
73708
- }
73709
- return null;
74059
+ return inworldTokenResult.token;
73710
74060
  }
73711
74061
  return null;
73712
74062
  } catch (error2) {
@@ -73726,11 +74076,19 @@ var AuthManager = class {
73726
74076
  return await this.refreshToken();
73727
74077
  }
73728
74078
  /**
73729
- * Authenticates and saves credentials from Firebase auth data
74079
+ * Authenticates and saves credentials from a Firebase ID token or GoTrue
74080
+ * access token. `source` is the configured deployment's identity stack; it,
74081
+ * not the token's own unverified issuer, decides where refreshes go.
73730
74082
  */
73731
- async authenticateAndSaveCredentials(firebaseToken, refreshToken, email2, workspace, env3) {
74083
+ async authenticateAndSaveCredentials(identityToken, refreshToken, email2, source, workspace, env3) {
73732
74084
  try {
73733
- const inworldTokenResult = await this.generateInworldToken(firebaseToken);
74085
+ if (!isIssuedBy(identityToken, source)) {
74086
+ printError(
74087
+ source.provider === "supabase" ? `Token was not issued by this deployment's auth server (${source.authUrl})` : "Token is not a Firebase token, but this deployment uses Firebase auth"
74088
+ );
74089
+ return false;
74090
+ }
74091
+ const inworldTokenResult = await this.generateInworldToken(identityToken);
73734
74092
  if (!inworldTokenResult) {
73735
74093
  printError("Failed to generate Inworld token");
73736
74094
  return false;
@@ -73742,7 +74100,9 @@ var AuthManager = class {
73742
74100
  inworldToken: inworldTokenResult.token,
73743
74101
  workspace,
73744
74102
  expiresAt,
73745
- env: env3
74103
+ env: env3,
74104
+ authProvider: source.provider,
74105
+ authUrl: source.authUrl
73746
74106
  };
73747
74107
  await this.saveCredentials(credentials);
73748
74108
  return true;
@@ -73855,10 +74215,25 @@ var ensureWorkspaceResourceName = (workspace) => {
73855
74215
  };
73856
74216
 
73857
74217
  // src/services/tts_service.ts
73858
- var LEGACY_MODELS = /* @__PURE__ */ new Set([
73859
- "inworld-tts-1" /* INWORLD_TTS_1 */,
73860
- "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */
73861
- ]);
74218
+ init_tts_models();
74219
+ init_tts_models();
74220
+ var TimestampType = /* @__PURE__ */ ((TimestampType2) => {
74221
+ TimestampType2["UNSPECIFIED"] = "TIMESTAMP_TYPE_UNSPECIFIED";
74222
+ TimestampType2["WORD"] = "WORD";
74223
+ TimestampType2["CHARACTER"] = "CHARACTER";
74224
+ return TimestampType2;
74225
+ })(TimestampType || {});
74226
+ var DeliveryMode = /* @__PURE__ */ ((DeliveryMode2) => {
74227
+ DeliveryMode2["STABLE"] = "STABLE";
74228
+ DeliveryMode2["BALANCED"] = "BALANCED";
74229
+ DeliveryMode2["CREATIVE"] = "CREATIVE";
74230
+ return DeliveryMode2;
74231
+ })(DeliveryMode || {});
74232
+ var TimestampTransportStrategy = /* @__PURE__ */ ((TimestampTransportStrategy2) => {
74233
+ TimestampTransportStrategy2["SYNC"] = "SYNC";
74234
+ TimestampTransportStrategy2["ASYNC"] = "ASYNC";
74235
+ return TimestampTransportStrategy2;
74236
+ })(TimestampTransportStrategy || {});
73862
74237
  var TTSService = class {
73863
74238
  apiKey = null;
73864
74239
  async ensureApiKey() {
@@ -73936,7 +74311,7 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
73936
74311
  * gateway, so we default to the current production model.
73937
74312
  * @see {@link https://docs.inworld.ai/api-reference/ttsAPI/texttospeech/get-voice-preview}
73938
74313
  */
73939
- async getVoicePreview(voiceId, modelId = "inworld-tts-1.5-max" /* INWORLD_TTS_1_5_MAX */) {
74314
+ async getVoicePreview(voiceId, modelId = DEFAULT_TTS_MODEL) {
73940
74315
  const qs = new URLSearchParams({ voice_id: voiceId, model_id: modelId });
73941
74316
  return this.makeRequest(
73942
74317
  `/tts/v1/voice:preview?${qs.toString()}`,
@@ -74086,7 +74461,7 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
74086
74461
  /**
74087
74462
  * Helper method to synthesize speech with simple parameters
74088
74463
  */
74089
- async synthesize(text, voiceId, modelId = "inworld-tts-1.5-max" /* INWORLD_TTS_1_5_MAX */) {
74464
+ async synthesize(text, voiceId, modelId = DEFAULT_TTS_MODEL) {
74090
74465
  return this.synthesizeSpeech({
74091
74466
  text,
74092
74467
  voiceId,
@@ -74151,6 +74526,63 @@ var ttsService = new TTSService();
74151
74526
 
74152
74527
  // src/services/tts_websocket.ts
74153
74528
  import WebSocket from "ws";
74529
+
74530
+ // src/utils/wav.ts
74531
+ function wavDataOffset(buf) {
74532
+ if (buf.length < 12 || buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE")
74533
+ return;
74534
+ let offset = 12;
74535
+ while (offset + 8 <= buf.length) {
74536
+ if (buf.toString("ascii", offset, offset + 4) === "data") return offset + 8;
74537
+ const size = buf.readUInt32LE(offset + 4);
74538
+ offset += 8 + size + size % 2;
74539
+ }
74540
+ }
74541
+ function stripWavHeader(buf) {
74542
+ const offset = wavDataOffset(buf);
74543
+ return offset === void 0 ? buf : buf.subarray(offset);
74544
+ }
74545
+ function wavDurationSeconds(buf) {
74546
+ const dataOffset = wavDataOffset(buf);
74547
+ if (dataOffset === void 0) return;
74548
+ for (let offset = 12; offset + 8 <= dataOffset; ) {
74549
+ const size = buf.readUInt32LE(offset + 4);
74550
+ if (buf.toString("ascii", offset, offset + 4) === "fmt ") {
74551
+ if (size < 16 || offset + 8 + size > buf.length) return;
74552
+ const byteRate = buf.readUInt32LE(offset + 16);
74553
+ const dataSize = Math.min(
74554
+ buf.readUInt32LE(dataOffset - 4),
74555
+ buf.length - dataOffset
74556
+ );
74557
+ return byteRate > 0 ? dataSize / byteRate : void 0;
74558
+ }
74559
+ offset += 8 + size + size % 2;
74560
+ }
74561
+ }
74562
+ function combineAudioChunks(chunks, format2) {
74563
+ const nonempty = chunks.filter((chunk) => chunk.length > 0);
74564
+ if (!nonempty.length) return Buffer.alloc(0);
74565
+ if (format2 !== "LINEAR16" && format2 !== "WAV") return Buffer.concat(nonempty);
74566
+ const offset = wavDataOffset(nonempty[0]);
74567
+ if (offset === void 0) throw new Error("Invalid WAV header in TTS stream");
74568
+ const header = Buffer.from(nonempty[0].subarray(0, offset));
74569
+ const audio = [
74570
+ nonempty[0].subarray(offset),
74571
+ ...nonempty.slice(1).map((chunk) => {
74572
+ if (format2 === "WAV") return chunk;
74573
+ const dataOffset = wavDataOffset(chunk);
74574
+ if (dataOffset === void 0)
74575
+ throw new Error("Invalid LINEAR16 chunk header in TTS stream");
74576
+ return chunk.subarray(dataOffset);
74577
+ })
74578
+ ];
74579
+ const dataSize = audio.reduce((n2, chunk) => n2 + chunk.length, 0);
74580
+ header.writeUInt32LE(header.length + dataSize - 8, 4);
74581
+ header.writeUInt32LE(dataSize, offset - 4);
74582
+ return Buffer.concat([header, ...audio]);
74583
+ }
74584
+
74585
+ // src/services/tts_websocket.ts
74154
74586
  var DEBUG = process.env.INWORLD_TTS_WS_DEBUG === "1";
74155
74587
  var warnedInvalidApiKey = false;
74156
74588
  function dlog(label, msg) {
@@ -74199,9 +74631,12 @@ var TtsSession = class _TtsSession {
74199
74631
  modelId: opts.modelId,
74200
74632
  audioConfig: {
74201
74633
  audioEncoding: opts.audioEncoding,
74202
- sampleRateHertz
74634
+ sampleRateHertz,
74635
+ speakingRate: opts.speakingRate
74203
74636
  },
74204
74637
  temperature: opts.temperature,
74638
+ language: opts.language,
74639
+ deliveryMode: opts.deliveryMode,
74205
74640
  ...opts.applyTextNormalization ? { applyTextNormalization: opts.applyTextNormalization } : {}
74206
74641
  }
74207
74642
  };
@@ -74374,20 +74809,12 @@ function waitForFrame(ws, predicate) {
74374
74809
  ws.addEventListener("error", onError, { once: true });
74375
74810
  });
74376
74811
  }
74377
- function stripWavHeader(buf) {
74378
- if (buf.length < 44) return buf;
74379
- for (let i2 = 12; i2 < Math.min(buf.length - 8, 256); i2++) {
74380
- if (buf[i2] === 100 && // d
74381
- buf[i2 + 1] === 97 && // a
74382
- buf[i2 + 2] === 116 && // t
74383
- buf[i2 + 3] === 97) {
74384
- return buf.subarray(i2 + 8);
74385
- }
74386
- }
74387
- return buf;
74388
- }
74812
+
74813
+ // src/commands/tts/tts_options.ts
74814
+ init_tts_models();
74389
74815
 
74390
74816
  // src/commands/tts/tts_utils.ts
74817
+ init_tts_models();
74391
74818
  import * as readline from "readline";
74392
74819
  function wrapText(text, maxWidth) {
74393
74820
  const words = text.split(" ");
@@ -74410,21 +74837,29 @@ function resolveModel(modelStr) {
74410
74837
  "inworld-tts-1-max": "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */,
74411
74838
  "inworld-tts-1.5-mini": "inworld-tts-1.5-mini" /* INWORLD_TTS_1_5_MINI */,
74412
74839
  "inworld-tts-1.5-max": "inworld-tts-1.5-max" /* INWORLD_TTS_1_5_MAX */,
74413
- "inworld-tts-2": "inworld-tts-2" /* INWORLD_TTS_2 */
74840
+ "inworld-tts-2": "inworld-tts-2" /* INWORLD_TTS_2 */,
74841
+ "inworld-tts-2-flash": "inworld-tts-2-flash" /* INWORLD_TTS_2_FLASH */
74842
+ };
74843
+ const legacySuccessors = {
74844
+ "inworld-tts-1": "inworld-tts-1.5-mini",
74845
+ "inworld-tts-1-max": "inworld-tts-1.5-max"
74414
74846
  };
74415
74847
  const model = modelMap[modelStr];
74416
74848
  if (!model) {
74849
+ const available = Object.keys(modelMap).filter(
74850
+ (m) => !(m in legacySuccessors)
74851
+ );
74417
74852
  console.error(
74418
74853
  source_default.red(
74419
- `Unknown model: ${modelStr}. Available: ${Object.keys(modelMap).join(", ")}`
74854
+ `Unknown model: ${modelStr}. Available: ${available.join(", ")}`
74420
74855
  )
74421
74856
  );
74422
74857
  process.exit(1);
74423
74858
  }
74424
74859
  if (LEGACY_MODELS.has(model)) {
74425
- console.log(
74860
+ console.error(
74426
74861
  source_default.yellow(
74427
- `Model "${modelStr}" is deprecated. Consider using "inworld-tts-1.5-mini", "inworld-tts-1.5-max", or "inworld-tts-2".`
74862
+ `Model "${modelStr}" was discontinued on June 15, 2026; requests are automatically routed to "${legacySuccessors[modelStr]}". We recommend "inworld-tts-2".`
74428
74863
  )
74429
74864
  );
74430
74865
  }
@@ -74444,6 +74879,23 @@ var VALID_FORMATS = Object.keys(FORMAT_EXTENSIONS);
74444
74879
  function getFileExtension(format2) {
74445
74880
  return FORMAT_EXTENSIONS[format2] || ".mp3";
74446
74881
  }
74882
+ function estimateAudioDuration(audio, config2) {
74883
+ switch (config2.audioEncoding) {
74884
+ case "MP3":
74885
+ case "OGG_OPUS":
74886
+ return audio.length * 8 / (config2.bitRate ?? 128e3);
74887
+ case "WAV":
74888
+ case "LINEAR16":
74889
+ return wavDurationSeconds(audio);
74890
+ case "PCM":
74891
+ return audio.length / ((config2.sampleRateHertz ?? 48e3) * 2);
74892
+ case "ALAW":
74893
+ case "MULAW":
74894
+ return audio.length / (config2.sampleRateHertz ?? 48e3);
74895
+ default:
74896
+ return void 0;
74897
+ }
74898
+ }
74447
74899
  function resolveFormat(format2, defaultFormat) {
74448
74900
  if (!format2) return defaultFormat;
74449
74901
  const normalized = format2.toUpperCase();
@@ -74470,6 +74922,173 @@ function promptInput(prompt, defaultValue) {
74470
74922
  });
74471
74923
  });
74472
74924
  }
74925
+ function appendWordAlignment(target, chunk) {
74926
+ const offset = target.words.length;
74927
+ target.words.push(...chunk.words ?? []);
74928
+ target.wordStartTimeSeconds.push(...chunk.wordStartTimeSeconds ?? []);
74929
+ target.wordEndTimeSeconds.push(...chunk.wordEndTimeSeconds ?? []);
74930
+ if (chunk.phoneticDetails?.length) {
74931
+ target.phoneticDetails ??= [];
74932
+ target.phoneticDetails.push(
74933
+ ...chunk.phoneticDetails.map(
74934
+ (detail) => "phoneSymbol" in detail ? detail : { ...detail, wordIndex: (detail.wordIndex ?? 0) + offset }
74935
+ )
74936
+ );
74937
+ }
74938
+ }
74939
+
74940
+ // src/commands/tts/tts_options.ts
74941
+ function addGenerationOptions(command) {
74942
+ return command.option("-m, --model <model>", TTS_MODEL_HELP, DEFAULT_TTS_MODEL).option(
74943
+ "-t, --temperature <temp>",
74944
+ "Temperature (0-2; 0 uses the API default; ignored by inworld-tts-2)",
74945
+ "1.1"
74946
+ ).option("--language <tag>", "BCP-47 language tag (omitted: auto-detect)").option(
74947
+ "--delivery-mode <mode>",
74948
+ "TTS-2 only: STABLE, BALANCED, or CREATIVE (omitted: BALANCED)"
74949
+ ).option("--speaking-rate <rate>", "Speaking speed, 0.5-1.5 (omitted: 1.0)").option("--normalize <mode>", "Text normalization: on, off, or auto");
74950
+ }
74951
+ function numberInRange(value, flag, min, max) {
74952
+ const n2 = Number(value);
74953
+ if (!value.trim() || !Number.isFinite(n2) || n2 < min || n2 > max) {
74954
+ throw new Error(`--${flag} must be a number between ${min} and ${max}`);
74955
+ }
74956
+ return n2;
74957
+ }
74958
+ function enumValue(value, flag, values) {
74959
+ const normalized = value.toUpperCase();
74960
+ if (!values.includes(normalized)) {
74961
+ throw new Error(`--${flag} must be one of: ${values.join(", ")}`);
74962
+ }
74963
+ return normalized;
74964
+ }
74965
+ function resolveLanguage(value) {
74966
+ if (value === void 0) return;
74967
+ const tag = value.trim().replace(/^([a-z]{2,3})_([a-z]{2}|\d{3})$/i, "$1-$2");
74968
+ try {
74969
+ Intl.getCanonicalLocales(tag);
74970
+ } catch {
74971
+ throw new Error(
74972
+ "--language must be a valid BCP-47 language tag (e.g. en-US)"
74973
+ );
74974
+ }
74975
+ return tag;
74976
+ }
74977
+ function resolveGenerationOptions(options) {
74978
+ const modelId = resolveModel(options.model);
74979
+ const temperature = numberInRange(options.temperature, "temperature", 0, 2);
74980
+ const deliveryMode = options.deliveryMode === void 0 ? void 0 : enumValue(
74981
+ options.deliveryMode,
74982
+ "delivery-mode",
74983
+ Object.values(DeliveryMode)
74984
+ );
74985
+ if (deliveryMode && modelId !== "inworld-tts-2" /* INWORLD_TTS_2 */) {
74986
+ throw new Error("--delivery-mode is supported only by inworld-tts-2");
74987
+ }
74988
+ const normalization = options.normalize?.toUpperCase();
74989
+ return {
74990
+ modelId,
74991
+ temperature,
74992
+ language: resolveLanguage(options.language),
74993
+ deliveryMode,
74994
+ speakingRate: options.speakingRate === void 0 ? void 0 : numberInRange(options.speakingRate, "speaking-rate", 0.5, 1.5),
74995
+ applyTextNormalization: normalization === void 0 ? void 0 : normalization === "AUTO" ? "APPLY_TEXT_NORMALIZATION_UNSPECIFIED" /* UNSPECIFIED */ : enumValue(normalization, "normalize", [
74996
+ "ON" /* ON */,
74997
+ "OFF" /* OFF */
74998
+ ])
74999
+ };
75000
+ }
75001
+ function buildSynthesisRequest(text, options, explicitVoice = false) {
75002
+ const limit = options.stream ? 4e3 : 2e3;
75003
+ if (!text.length || text.length > limit) {
75004
+ throw new Error(
75005
+ `Text must contain 1-${limit} UTF-16 code units (received ${text.length})`
75006
+ );
75007
+ }
75008
+ const { speakingRate, ...generation } = resolveGenerationOptions(options);
75009
+ const audioEncoding = resolveFormat(
75010
+ options.format,
75011
+ options.stream ? "LINEAR16" : "MP3"
75012
+ );
75013
+ const request = {
75014
+ text,
75015
+ voiceId: options.voice,
75016
+ ...generation,
75017
+ audioConfig: { audioEncoding, speakingRate }
75018
+ };
75019
+ if (options.voiceDesign !== void 0) {
75020
+ if (explicitVoice)
75021
+ throw new Error("--voice-design cannot be combined with --voice");
75022
+ if (generation.modelId !== "inworld-tts-2" /* INWORLD_TTS_2 */) {
75023
+ throw new Error("--voice-design is supported only by inworld-tts-2");
75024
+ }
75025
+ const designPrompt = options.voiceDesign.trim();
75026
+ if (designPrompt.length < 7 || designPrompt.length > 1024) {
75027
+ throw new Error(
75028
+ "--voice-design must contain 7-1024 characters after trimming"
75029
+ );
75030
+ }
75031
+ delete request.voiceId;
75032
+ request.voiceDesign = { designPrompt };
75033
+ }
75034
+ if (options.instruction !== void 0) {
75035
+ if (generation.modelId !== "inworld-tts-2" /* INWORLD_TTS_2 */) {
75036
+ throw new Error("--instruction is supported only by inworld-tts-2");
75037
+ }
75038
+ request.instruction = options.instruction;
75039
+ }
75040
+ if (options.enhanceGeneration) request.enhanceGeneration = true;
75041
+ if (options.previousText?.length) {
75042
+ if (options.previousText.reduce((n2, t) => n2 + t.length, 0) > 2e3) {
75043
+ throw new Error(
75044
+ "Combined --previous-text values must not exceed 2000 UTF-16 code units"
75045
+ );
75046
+ }
75047
+ request.synthesisContext = {
75048
+ previousRequests: options.previousText.map((text2) => ({ text: text2 }))
75049
+ };
75050
+ }
75051
+ if (options.sampleRate !== void 0) {
75052
+ const rate = Number(options.sampleRate);
75053
+ if (![8e3, 16e3, 22050, 24e3, 32e3, 44100, 48e3].includes(rate)) {
75054
+ throw new Error(
75055
+ "--sample-rate must be 8000, 16000, 22050, 24000, 32000, 44100, or 48000"
75056
+ );
75057
+ }
75058
+ request.audioConfig.sampleRateHertz = rate;
75059
+ }
75060
+ if (options.bitRate !== void 0) {
75061
+ if (audioEncoding !== "MP3" /* MP3 */ && audioEncoding !== "OGG_OPUS" /* OGG_OPUS */) {
75062
+ throw new Error("--bit-rate is supported only with MP3 or OGG_OPUS");
75063
+ }
75064
+ const rate = numberInRange(
75065
+ options.bitRate,
75066
+ "bit-rate",
75067
+ 32e3,
75068
+ audioEncoding === "MP3" /* MP3 */ ? 32e4 : 192e3
75069
+ );
75070
+ if (!Number.isInteger(rate))
75071
+ throw new Error("--bit-rate must be an integer");
75072
+ request.audioConfig.bitRate = rate;
75073
+ }
75074
+ if (options.timestamps !== void 0) {
75075
+ request.timestampType = enumValue(
75076
+ options.timestamps,
75077
+ "timestamps",
75078
+ Object.values(TimestampType)
75079
+ );
75080
+ }
75081
+ if (options.timestampTransport !== void 0) {
75082
+ if (!options.stream)
75083
+ throw new Error("--timestamp-transport requires --stream");
75084
+ request.timestampTransportStrategy = enumValue(
75085
+ options.timestampTransport,
75086
+ "timestamp-transport",
75087
+ Object.values(TimestampTransportStrategy)
75088
+ );
75089
+ }
75090
+ return request;
75091
+ }
74473
75092
 
74474
75093
  // src/commands/audiobook/audiobook_metadata.ts
74475
75094
  import { readFile, writeFile } from "fs/promises";
@@ -75520,12 +76139,12 @@ var handleCommand = (filePath, rawArguments, rawOptions) => {
75520
76139
 
75521
76140
  // node_modules/execa/lib/arguments/options.js
75522
76141
  var import_cross_spawn = __toESM(require_cross_spawn(), 1);
75523
- import path9 from "node:path";
76142
+ import path10 from "node:path";
75524
76143
  import process13 from "node:process";
75525
76144
 
75526
76145
  // node_modules/npm-run-path/index.js
75527
76146
  import process11 from "node:process";
75528
- import path6 from "node:path";
76147
+ import path7 from "node:path";
75529
76148
 
75530
76149
  // node_modules/path-key/index.js
75531
76150
  function pathKey(options = {}) {
@@ -75542,7 +76161,7 @@ function pathKey(options = {}) {
75542
76161
  // ../../node_modules/unicorn-magic/node.js
75543
76162
  import { promisify as promisify2 } from "node:util";
75544
76163
  import { execFile as execFileCallback, execFileSync as execFileSyncOriginal } from "node:child_process";
75545
- import path5 from "node:path";
76164
+ import path6 from "node:path";
75546
76165
  import { fileURLToPath as fileURLToPath2 } from "node:url";
75547
76166
  var execFileOriginal = promisify2(execFileCallback);
75548
76167
  function toPath(urlOrPath) {
@@ -75551,12 +76170,12 @@ function toPath(urlOrPath) {
75551
76170
  function traversePathUp(startPath) {
75552
76171
  return {
75553
76172
  *[Symbol.iterator]() {
75554
- let currentPath = path5.resolve(toPath(startPath));
76173
+ let currentPath = path6.resolve(toPath(startPath));
75555
76174
  let previousPath;
75556
76175
  while (previousPath !== currentPath) {
75557
76176
  yield currentPath;
75558
76177
  previousPath = currentPath;
75559
- currentPath = path5.resolve(currentPath, "..");
76178
+ currentPath = path6.resolve(currentPath, "..");
75560
76179
  }
75561
76180
  }
75562
76181
  };
@@ -75571,27 +76190,27 @@ var npmRunPath = ({
75571
76190
  execPath: execPath2 = process11.execPath,
75572
76191
  addExecPath = true
75573
76192
  } = {}) => {
75574
- const cwdPath = path6.resolve(toPath(cwd));
76193
+ const cwdPath = path7.resolve(toPath(cwd));
75575
76194
  const result = [];
75576
- const pathParts = pathOption.split(path6.delimiter);
76195
+ const pathParts = pathOption.split(path7.delimiter);
75577
76196
  if (preferLocal) {
75578
76197
  applyPreferLocal(result, pathParts, cwdPath);
75579
76198
  }
75580
76199
  if (addExecPath) {
75581
76200
  applyExecPath(result, pathParts, execPath2, cwdPath);
75582
76201
  }
75583
- return pathOption === "" || pathOption === path6.delimiter ? `${result.join(path6.delimiter)}${pathOption}` : [...result, pathOption].join(path6.delimiter);
76202
+ return pathOption === "" || pathOption === path7.delimiter ? `${result.join(path7.delimiter)}${pathOption}` : [...result, pathOption].join(path7.delimiter);
75584
76203
  };
75585
76204
  var applyPreferLocal = (result, pathParts, cwdPath) => {
75586
76205
  for (const directory of traversePathUp(cwdPath)) {
75587
- const pathPart = path6.join(directory, "node_modules/.bin");
76206
+ const pathPart = path7.join(directory, "node_modules/.bin");
75588
76207
  if (!pathParts.includes(pathPart)) {
75589
76208
  result.push(pathPart);
75590
76209
  }
75591
76210
  }
75592
76211
  };
75593
76212
  var applyExecPath = (result, pathParts, execPath2, cwdPath) => {
75594
- const pathPart = path6.resolve(cwdPath, toPath(execPath2), "..");
76213
+ const pathPart = path7.resolve(cwdPath, toPath(execPath2), "..");
75595
76214
  if (!pathParts.includes(pathPart)) {
75596
76215
  result.push(pathPart);
75597
76216
  }
@@ -76746,7 +77365,7 @@ var killAfterTimeout = async (subprocess, timeout, context, { signal }) => {
76746
77365
 
76747
77366
  // node_modules/execa/lib/methods/node.js
76748
77367
  import { execPath, execArgv } from "node:process";
76749
- import path7 from "node:path";
77368
+ import path8 from "node:path";
76750
77369
  var mapNode = ({ options }) => {
76751
77370
  if (options.node === false) {
76752
77371
  throw new TypeError('The "node" option cannot be false with `execaNode()`.');
@@ -76765,7 +77384,7 @@ var handleNodeOption = (file, commandArguments, {
76765
77384
  throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');
76766
77385
  }
76767
77386
  const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option');
76768
- const resolvedNodePath = path7.resolve(cwd, normalizedNodePath);
77387
+ const resolvedNodePath = path8.resolve(cwd, normalizedNodePath);
76769
77388
  const newOptions = {
76770
77389
  ...options,
76771
77390
  nodePath: resolvedNodePath,
@@ -76775,7 +77394,7 @@ var handleNodeOption = (file, commandArguments, {
76775
77394
  if (!shouldHandleNode) {
76776
77395
  return [file, commandArguments, newOptions];
76777
77396
  }
76778
- if (path7.basename(file, ".exe") === "node") {
77397
+ if (path8.basename(file, ".exe") === "node") {
76779
77398
  throw new TypeError('When the "node" option is true, the first argument does not need to be "node".');
76780
77399
  }
76781
77400
  return [
@@ -76865,11 +77484,11 @@ var serializeEncoding = (encoding) => typeof encoding === "string" ? `"${encodin
76865
77484
 
76866
77485
  // node_modules/execa/lib/arguments/cwd.js
76867
77486
  import { statSync } from "node:fs";
76868
- import path8 from "node:path";
77487
+ import path9 from "node:path";
76869
77488
  import process12 from "node:process";
76870
77489
  var normalizeCwd = (cwd = getDefaultCwd()) => {
76871
77490
  const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option');
76872
- return path8.resolve(cwdString);
77491
+ return path9.resolve(cwdString);
76873
77492
  };
76874
77493
  var getDefaultCwd = () => {
76875
77494
  try {
@@ -76916,7 +77535,7 @@ var normalizeOptions = (filePath, rawArguments, rawOptions) => {
76916
77535
  options.killSignal = normalizeKillSignal(options.killSignal);
76917
77536
  options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);
76918
77537
  options.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]);
76919
- if (process13.platform === "win32" && path9.basename(file, ".exe") === "cmd") {
77538
+ if (process13.platform === "win32" && path10.basename(file, ".exe") === "cmd") {
76920
77539
  commandArguments.unshift("/q");
76921
77540
  }
76922
77541
  return { file, commandArguments, options };
@@ -81722,14 +82341,14 @@ async function assertBinary(name) {
81722
82341
  }
81723
82342
 
81724
82343
  // src/commands/audiobook/state_file.ts
81725
- import { createHash as createHash2 } from "crypto";
82344
+ import { createHash as createHash3 } from "crypto";
81726
82345
  import { rename, writeFile as writeFile3 } from "fs/promises";
81727
82346
  import { readFile as readFile2 } from "fs/promises";
81728
82347
  import { join as join2 } from "path";
81729
82348
  var STATE_FILE_NAME = "state.json";
81730
82349
  var STATE_FILE_VERSION = 1;
81731
82350
  function sha256(buffer) {
81732
- return createHash2("sha256").update(buffer).digest("hex");
82351
+ return createHash3("sha256").update(buffer).digest("hex");
81733
82352
  }
81734
82353
  function statePath(workDir) {
81735
82354
  return join2(workDir, STATE_FILE_NAME);
@@ -81797,27 +82416,46 @@ function diffStateForResume(existing, current) {
81797
82416
  newValue: String(current.maxSegmentChars)
81798
82417
  });
81799
82418
  }
82419
+ const oldOptions = {
82420
+ language: existing.language ?? "",
82421
+ deliveryMode: existing.deliveryMode ?? "BALANCED" /* BALANCED */,
82422
+ speakingRate: existing.speakingRate ?? 1,
82423
+ applyTextNormalization: existing.applyTextNormalization ?? "APPLY_TEXT_NORMALIZATION_UNSPECIFIED" /* UNSPECIFIED */
82424
+ };
82425
+ const newOptions = {
82426
+ language: current.language ?? "",
82427
+ deliveryMode: current.deliveryMode ?? "BALANCED" /* BALANCED */,
82428
+ speakingRate: current.speakingRate ?? 1,
82429
+ applyTextNormalization: current.applyTextNormalization ?? "APPLY_TEXT_NORMALIZATION_UNSPECIFIED" /* UNSPECIFIED */
82430
+ };
82431
+ for (const field of Object.keys(oldOptions)) {
82432
+ if (oldOptions[field] !== newOptions[field]) {
82433
+ diffs.push({
82434
+ field,
82435
+ oldValue: String(oldOptions[field]),
82436
+ newValue: String(newOptions[field])
82437
+ });
82438
+ }
82439
+ }
81800
82440
  return diffs;
81801
82441
  }
81802
82442
 
81803
82443
  // src/commands/audiobook/audiobook_generate_command.ts
81804
82444
  var DEFAULT_MAX_SEGMENT_CHARS = 900;
81805
- var TTS_MAX_SEGMENT_CHARS = 1e3;
82445
+ var TTS_MAX_SEGMENT_CHARS = 2e3;
81806
82446
  var DEFAULT_CONCURRENCY = 10;
81807
82447
  var MAX_CONCURRENCY = 20;
81808
82448
  var DEFAULT_MAX_RETRIES = 4;
81809
82449
  var SAMPLE_RATE_HZ = 48e3;
81810
- var audiobookGenerateCommand = new Command("generate").description(
81811
- 'Generate an audiobook MP3 with chapter metadata from a .txt or .epub.\n\nFor .txt: chapters are split on Markdown headings (# ...) or lines like\n"Chapter 1", "Chapter II", "Part 3".\nFor .epub: chapters come from the EPUB spine; titles from each chapter\'s\nfirst <h1>-<h6>.\n\nEach chapter runs on its own TTS WebSocket session so the server\npreserves voice context across consecutive segments. Chapters run in\nparallel up to --concurrency; segments within a chapter are sequential.\n\nResume: every run writes <work-dir>/state.json with per-chapter progress.\nRe-running with the same --work-dir reads that file and skips chapters\nmarked `done` whose MP3 still exists on disk. If the source, voice,\nmodel, temperature, or --max-segment-chars differs from the previous\nrun the command refuses to continue (pass --force to override).'
82450
+ var audiobookGenerateCommand = addGenerationOptions(
82451
+ new Command("generate")
82452
+ ).description(
82453
+ 'Generate an audiobook MP3 with chapter metadata from a .txt or .epub.\n\nFor .txt: chapters are split on Markdown headings (# ...) or lines like\n"Chapter 1", "Chapter II", "Part 3".\nFor .epub: chapters come from the EPUB spine; titles from each chapter\'s\nfirst <h1>-<h6>.\n\nEach chapter runs on its own TTS WebSocket session so the server\npreserves voice context across consecutive segments. Chapters run in\nparallel up to --concurrency; segments within a chapter are sequential.\n\nResume: every run writes <work-dir>/state.json with per-chapter progress.\nRe-running with the same --work-dir reads that file and skips chapters\nmarked `done` whose MP3 still exists on disk. If the source, voice,\nmodel, generation settings, or --max-segment-chars differs from the previous\nrun the command refuses to continue (pass --force to override).'
81812
82454
  ).argument("<input>", "Path to a .txt or .epub file containing the book").option("-o, --output <file>", "Output MP3 file path", "audiobook.mp3").requiredOption(
81813
82455
  "-v, --voice <voiceId>",
81814
82456
  "Voice ID to use for synthesis",
81815
82457
  "Dennis"
81816
82458
  ).option(
81817
- "-m, --model <model>",
81818
- "TTS model (inworld-tts-1.5-mini, inworld-tts-1.5-max, or legacy)",
81819
- "inworld-tts-1.5-max"
81820
- ).option("-t, --temperature <temp>", "Temperature (0.0-2.0)", "1.1").option(
81821
82459
  "--max-segment-chars <n>",
81822
82460
  `Max characters per TTS WS send_text message (\u2264${TTS_MAX_SEGMENT_CHARS})`,
81823
82461
  String(DEFAULT_MAX_SEGMENT_CHARS)
@@ -81848,10 +82486,14 @@ var audiobookGenerateCommand = new Command("generate").description(
81848
82486
  try {
81849
82487
  await assertBinary("ffmpeg");
81850
82488
  await assertBinary("ffprobe");
81851
- const temperature = parseFloat(options.temperature);
81852
- if (!isFinite(temperature) || temperature < 0 || temperature > 2) {
81853
- throw new Error("--temperature must be between 0.0 and 2.0");
81854
- }
82489
+ const generation = resolveGenerationOptions(options);
82490
+ const {
82491
+ temperature,
82492
+ language,
82493
+ deliveryMode,
82494
+ speakingRate,
82495
+ applyTextNormalization
82496
+ } = generation;
81855
82497
  const maxSegmentChars = parseInt(options.maxSegmentChars, 10);
81856
82498
  if (!Number.isInteger(maxSegmentChars) || maxSegmentChars < 100 || maxSegmentChars > TTS_MAX_SEGMENT_CHARS) {
81857
82499
  throw new Error(
@@ -81868,7 +82510,6 @@ var audiobookGenerateCommand = new Command("generate").description(
81868
82510
  if (!Number.isInteger(maxRetries) || maxRetries < 1 || maxRetries > 10) {
81869
82511
  throw new Error("--max-retries must be an integer in [1, 10]");
81870
82512
  }
81871
- const modelId = resolveModel(options.model);
81872
82513
  const resolvedInput = resolve(inputPath);
81873
82514
  const outputPath = resolve(options.output);
81874
82515
  const workDir = resolve(
@@ -81891,6 +82532,10 @@ var audiobookGenerateCommand = new Command("generate").description(
81891
82532
  voice: options.voice,
81892
82533
  model: options.model,
81893
82534
  temperature,
82535
+ language,
82536
+ deliveryMode,
82537
+ speakingRate,
82538
+ applyTextNormalization,
81894
82539
  maxSegmentChars
81895
82540
  });
81896
82541
  if (diffs.length > 0) {
@@ -81941,6 +82586,10 @@ var audiobookGenerateCommand = new Command("generate").description(
81941
82586
  voice: options.voice,
81942
82587
  model: options.model,
81943
82588
  temperature,
82589
+ language,
82590
+ deliveryMode,
82591
+ speakingRate,
82592
+ applyTextNormalization,
81944
82593
  maxSegmentChars,
81945
82594
  status: "running",
81946
82595
  chaptersTotal: jobs.length,
@@ -82004,8 +82653,7 @@ var audiobookGenerateCommand = new Command("generate").description(
82004
82653
  async () => {
82005
82654
  const session = await TtsSession.open({
82006
82655
  voiceId: options.voice,
82007
- modelId,
82008
- temperature,
82656
+ ...generation,
82009
82657
  audioEncoding: "LINEAR16" /* LINEAR16 */,
82010
82658
  sampleRateHertz: SAMPLE_RATE_HZ
82011
82659
  });
@@ -82147,12 +82795,10 @@ var audiobookCommand = new Command("audiobook").description("Audiobook generatio
82147
82795
  });
82148
82796
 
82149
82797
  // src/commands/auth/login_command.ts
82150
- import { exec } from "child_process";
82151
82798
  import * as readline4 from "readline";
82152
- import { promisify as promisify4 } from "util";
82153
82799
 
82154
82800
  // src/auth/callback_server.ts
82155
- import * as http from "http";
82801
+ import * as http2 from "http";
82156
82802
  async function createCallbackServer(options = {}) {
82157
82803
  const {
82158
82804
  port = 8085,
@@ -82160,7 +82806,7 @@ async function createCallbackServer(options = {}) {
82160
82806
  firebaseApiKey = FIREBASE_API_KEY
82161
82807
  } = options;
82162
82808
  return new Promise((resolve4, reject) => {
82163
- const httpServer = http.createServer(
82809
+ const httpServer = http2.createServer(
82164
82810
  {
82165
82811
  keepAlive: false
82166
82812
  },
@@ -82272,6 +82918,10 @@ function stopCallbackServer(server) {
82272
82918
  });
82273
82919
  }
82274
82920
 
82921
+ // src/commands/auth/login_command.ts
82922
+ init_browser();
82923
+ init_identity();
82924
+
82275
82925
  // proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
82276
82926
  var ApiKeys = class {
82277
82927
  static ListApiKeys(req, initReq) {
@@ -82825,9 +83475,83 @@ Selecting API key: ${source_default.whiteBright(trimBase64Key(base64Key))}`
82825
83475
  };
82826
83476
 
82827
83477
  // src/commands/auth/login_command.ts
82828
- var execAsync = promisify4(exec);
83478
+ var offerBrowser = async (url, done) => {
83479
+ print("Please visit the following URL to authenticate:");
83480
+ printLink(`${url}
83481
+ `);
83482
+ const readlineInterface = readline4.createInterface({
83483
+ input: process.stdin,
83484
+ output: process.stdout
83485
+ });
83486
+ const enterPromise = new Promise((resolve4) => {
83487
+ readlineInterface.question("Press Enter to open your browser...", () => {
83488
+ resolve4("enter");
83489
+ });
83490
+ });
83491
+ const settled = done.then(
83492
+ () => "done",
83493
+ () => "done"
83494
+ );
83495
+ const first = await Promise.race([enterPromise, settled]);
83496
+ readlineInterface.close();
83497
+ if (first === "done") return;
83498
+ try {
83499
+ await openInBrowser(url);
83500
+ success("\u2713 Browser opened");
83501
+ } catch (_error) {
83502
+ print(
83503
+ "\u26A0 Could not open browser automatically. Please open the URL manually."
83504
+ );
83505
+ }
83506
+ console.log();
83507
+ print("Waiting for authentication...");
83508
+ };
83509
+ var ask = (question, hidden2 = false) => new Promise((resolve4) => {
83510
+ const rl = readline4.createInterface({
83511
+ input: process.stdin,
83512
+ output: process.stdout,
83513
+ terminal: true
83514
+ });
83515
+ if (hidden2) {
83516
+ const out = rl;
83517
+ out._writeToOutput = (s) => {
83518
+ if (s.includes(question)) process.stdout.write(question);
83519
+ };
83520
+ }
83521
+ rl.question(question, (answer) => {
83522
+ rl.close();
83523
+ if (hidden2) process.stdout.write("\n");
83524
+ resolve4(answer.trim());
83525
+ });
83526
+ });
83527
+ var signInWithFirebase = async () => {
83528
+ const serverPromise = createCallbackServer({
83529
+ port: INWORLD_CLI_AUTH_CALLBACK_PORT
83530
+ });
83531
+ await offerBrowser(INWORLD_CLI_AUTH_URL, serverPromise);
83532
+ const result = await serverPromise;
83533
+ await stopCallbackServer(result.server);
83534
+ return {
83535
+ idToken: result.token,
83536
+ refreshToken: result.refreshToken,
83537
+ email: result.email
83538
+ };
83539
+ };
83540
+ var signInWithSupabase = async (source, provider) => {
83541
+ const authUrl = source.authUrl;
83542
+ if (provider === "email") {
83543
+ const email2 = await ask("Email: ");
83544
+ const password = await ask("Password: ", true);
83545
+ return signInWithPassword(authUrl, email2, password);
83546
+ }
83547
+ const { url, done } = await startOAuthSignIn({
83548
+ authUrl,
83549
+ oauthProvider: provider
83550
+ });
83551
+ await offerBrowser(url, done);
83552
+ return done;
83553
+ };
82829
83554
  var loginAction = async (options) => {
82830
- let authServerResult = null;
82831
83555
  try {
82832
83556
  if (!options.force && await authManager.isAuthenticated()) {
82833
83557
  const credentials = await authManager.getCredentials();
@@ -82859,52 +83583,19 @@ var loginAction = async (options) => {
82859
83583
  print("Let's get you authenticated.");
82860
83584
  console.log();
82861
83585
  }
82862
- const serverPromise = createCallbackServer({
82863
- port: INWORLD_CLI_AUTH_CALLBACK_PORT
82864
- });
82865
- print("Please visit the following URL to authenticate:");
82866
- printLink(`${INWORLD_CLI_AUTH_URL}
82867
- `);
82868
- const readlineInterface = readline4.createInterface({
82869
- input: process.stdin,
82870
- output: process.stdout
82871
- });
82872
- const enterPromise = new Promise((resolve4) => {
82873
- readlineInterface.question("Press Enter to open your browser...", () => {
82874
- resolve4();
82875
- });
82876
- });
82877
- const result = await Promise.race([
82878
- enterPromise.then(() => ({ type: "enter" })),
82879
- serverPromise.then((result2) => ({ type: "auth", result: result2 }))
82880
- ]);
82881
- readlineInterface.close();
82882
- if (result.type === "auth") {
82883
- authServerResult = result.result;
82884
- } else {
82885
- const openCommand = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
82886
- try {
82887
- await execAsync(`${openCommand} ${INWORLD_CLI_AUTH_URL}`);
82888
- success("\u2713 Browser opened");
82889
- } catch (_error) {
82890
- print(
82891
- "\u26A0 Could not open browser automatically. Please open the URL manually."
82892
- );
82893
- }
82894
- console.log();
82895
- print("Waiting for authentication...");
82896
- authServerResult = await serverPromise;
82897
- }
83586
+ const source = await resolveIdentitySource(PLATFORM_URL);
83587
+ const tokens = source.provider === "supabase" ? await signInWithSupabase(source, options.provider) : await signInWithFirebase();
82898
83588
  console.log();
82899
83589
  success("\u2713 Authentication successful!");
82900
83590
  console.log();
82901
83591
  print("User information:");
82902
- printBright(`Email: ${authServerResult.email}
83592
+ printBright(`Email: ${tokens.email}
82903
83593
  `);
82904
83594
  const success2 = await authManager.authenticateAndSaveCredentials(
82905
- authServerResult.token,
82906
- authServerResult.refreshToken,
82907
- authServerResult.email,
83595
+ tokens.idToken,
83596
+ tokens.refreshToken,
83597
+ tokens.email ?? "",
83598
+ source,
82908
83599
  /* workspace */
82909
83600
  void 0,
82910
83601
  INWORLD_ENV
@@ -82913,7 +83604,6 @@ var loginAction = async (options) => {
82913
83604
  printError("\nFailed to complete authentication setup");
82914
83605
  print("You may need to login again.");
82915
83606
  }
82916
- stopCallbackServer(authServerResult.server);
82917
83607
  console.log();
82918
83608
  print("You are now authenticated with Inworld services.");
82919
83609
  print("Your credentials have been securely stored.");
@@ -82927,12 +83617,6 @@ var loginAction = async (options) => {
82927
83617
  print("\nAuthentication completed.");
82928
83618
  process.exit(0);
82929
83619
  } catch (error2) {
82930
- if (authServerResult?.server) {
82931
- try {
82932
- await stopCallbackServer(authServerResult.server);
82933
- } catch (_closeError) {
82934
- }
82935
- }
82936
83620
  console.log();
82937
83621
  printError("Authentication failed:");
82938
83622
  console.error(error2);
@@ -82940,7 +83624,12 @@ var loginAction = async (options) => {
82940
83624
  }
82941
83625
  };
82942
83626
  var makeLoginCommand = (description) => {
82943
- return new Command("login").description(description).option("-f, --force", "Force re-authentication even if already logged in").action(loginAction);
83627
+ return new Command("login").description(description).option("-f, --force", "Force re-authentication even if already logged in").addOption(
83628
+ new Option(
83629
+ "-p, --provider <provider>",
83630
+ "Sign-in method on Supabase-auth deployments (ignored on Firebase ones)"
83631
+ ).choices([...GOTRUE_OAUTH_PROVIDERS, "email"]).default(process.env.INWORLD_AUTH_OAUTH_PROVIDER || "google")
83632
+ ).action(loginAction);
82944
83633
  };
82945
83634
  var loginCommand = makeLoginCommand(
82946
83635
  "Authenticate with Inworld Platform"
@@ -82949,16 +83638,20 @@ var loginCommandAlias = makeLoginCommand(
82949
83638
  `Alias for "${bold("inworld auth login")}"`
82950
83639
  );
82951
83640
 
83641
+ // src/commands/auth/logout_command.ts
83642
+ init_cli_store_bridge();
83643
+ init_identity();
83644
+
82952
83645
  // src/utils/mcp_session_file.ts
82953
- import fs3 from "node:fs";
82954
- import os3 from "node:os";
82955
- import path10 from "node:path";
83646
+ import fs5 from "node:fs";
83647
+ import os4 from "node:os";
83648
+ import path11 from "node:path";
82956
83649
  function mcpSessionFilePath() {
82957
- return process.env.INWORLD_SESSION_FILE ?? path10.join(os3.homedir(), ".config", "inworld-mcp", "session.json");
83650
+ return process.env.INWORLD_SESSION_FILE ?? path11.join(os4.homedir(), ".config", "inworld-mcp", "session.json");
82958
83651
  }
82959
83652
  function clearMcpSessionFileIfPresent() {
82960
83653
  try {
82961
- fs3.unlinkSync(mcpSessionFilePath());
83654
+ fs5.unlinkSync(mcpSessionFilePath());
82962
83655
  } catch {
82963
83656
  }
82964
83657
  }
@@ -82988,6 +83681,20 @@ var logoutAction = async (options) => {
82988
83681
  }
82989
83682
  }
82990
83683
  console.log();
83684
+ if (credentials?.authProvider === "supabase" && credentials.refreshToken) {
83685
+ print("Ending the session on the server...");
83686
+ try {
83687
+ await revokeSession(
83688
+ identitySourceOfStore(credentials),
83689
+ credentials.refreshToken
83690
+ );
83691
+ success("\u2713 Session ended.");
83692
+ } catch (error2) {
83693
+ print(
83694
+ `\u26A0 Could not end the session on the server (${error2 instanceof Error ? error2.message : String(error2)}); clearing local credentials anyway.`
83695
+ );
83696
+ }
83697
+ }
82991
83698
  print("Clearing stored credentials...");
82992
83699
  await authManager.clearCredentials();
82993
83700
  clearMcpSessionFileIfPresent();
@@ -83243,17 +83950,19 @@ var enableTelemetryAction = async () => {
83243
83950
  var enableTelemetryCommand = new Command("enable_cli_telemetry").description("Enable anonymous CLI usage analytics").action(enableTelemetryAction);
83244
83951
 
83245
83952
  // src/commands/auth/login_ci_command.ts
83953
+ init_identity();
83246
83954
  var loginCiAction = async (options) => {
83247
83955
  try {
83248
83956
  setGlobalForceYes(true);
83249
83957
  console.log();
83250
- printHeader("\u{1F3AD} Authenticating with external Firebase token");
83958
+ printHeader("\u{1F3AD} Authenticating with external identity token");
83251
83959
  console.log();
83252
83960
  const success2 = await authManager.authenticateAndSaveCredentials(
83253
83961
  options.token,
83254
83962
  options.refreshToken || options.token,
83255
83963
  // Use token as fallback if no refresh token
83256
83964
  options.email,
83965
+ await resolveIdentitySource(PLATFORM_URL),
83257
83966
  /* workspace */
83258
83967
  void 0,
83259
83968
  INWORLD_ENV
@@ -83275,9 +83984,14 @@ var loginCiAction = async (options) => {
83275
83984
  process.exit(1);
83276
83985
  }
83277
83986
  };
83278
- var loginCiCommand = new Command("login-ci").description("Authenticate using Firebase token (for CI/testing)").requiredOption("-t, --token <token>", "Firebase ID token").requiredOption("-e, --email <email>", "Email address").option(
83987
+ var loginCiCommand = new Command("login-ci").description(
83988
+ "Authenticate using a Firebase ID token or Supabase access token (for CI/testing)"
83989
+ ).requiredOption(
83990
+ "-t, --token <token>",
83991
+ "Firebase ID token or Supabase (GoTrue) access token"
83992
+ ).requiredOption("-e, --email <email>", "Email address").option(
83279
83993
  "-r, --refresh-token <refreshToken>",
83280
- "Firebase refresh token (optional, enables token refresh)"
83994
+ "Matching refresh token (optional, enables token refresh)"
83281
83995
  ).action(loginCiAction);
83282
83996
 
83283
83997
  // src/commands/auth/print_access_token_command.ts
@@ -83856,10 +84570,10 @@ Actions: [1-${previews.length}] play a preview, [p] publish, [r] regenerate, [q]
83856
84570
  input: process.stdin,
83857
84571
  output: process.stdout
83858
84572
  });
83859
- const ask = (q) => new Promise((resolve4) => rl.question(q, resolve4));
84573
+ const ask2 = (q) => new Promise((resolve4) => rl.question(q, resolve4));
83860
84574
  let action = null;
83861
84575
  while (true) {
83862
- const answer = (await ask("> ")).trim().toLowerCase();
84576
+ const answer = (await ask2("> ")).trim().toLowerCase();
83863
84577
  const idx = parseInt(answer, 10);
83864
84578
  if (!isNaN(idx) && idx >= 1 && idx <= previews.length) {
83865
84579
  console.log(
@@ -84103,13 +84817,10 @@ ${flag} ${source_default.bold.yellow(lang.toUpperCase())} ${source_default.gray
84103
84817
  });
84104
84818
 
84105
84819
  // src/commands/tts/tts_preview_command.ts
84820
+ init_tts_models();
84106
84821
  var previewCommand = new Command("preview").description(
84107
84822
  "Get a short, non-billed voice preview for a voice ID (returns MP3)"
84108
- ).argument("<voiceId>", "Voice ID to preview (see `inworld tts list-voices`)").option(
84109
- "-m, --model <id>",
84110
- "TTS model id (e.g. inworld-tts-2)",
84111
- "inworld-tts-1.5-max"
84112
- ).option(
84823
+ ).argument("<voiceId>", "Voice ID to preview (see `inworld tts list-voices`)").option("-m, --model <id>", TTS_MODEL_HELP, DEFAULT_TTS_MODEL).option(
84113
84824
  "-o, --output <file>",
84114
84825
  "Output MP3 file path (default: preview-<voiceId>.mp3)"
84115
84826
  ).option("-p, --play", "Play the preview audio through speakers after saving").option("-j, --json", "Output raw JSON (includes base64 audio)").action(async (voiceId, options) => {
@@ -84144,91 +84855,72 @@ var previewCommand = new Command("preview").description(
84144
84855
  import { writeFile as writeFile6 } from "fs/promises";
84145
84856
  import { resolve as resolve3 } from "path";
84146
84857
  init_audio_player();
84147
- var synthesizeCommand = new Command("synthesize").description(
84858
+ var synthesizeCommand = addGenerationOptions(new Command("synthesize")).description(
84148
84859
  '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)'
84149
- ).argument("<text>", "Text to synthesize (max 2000 characters)").requiredOption(
84150
- "-v, --voice <voiceId>",
84151
- "Voice ID to use for synthesis",
84152
- "Dennis"
84153
- ).option("-o, --output <file>", "Output audio file path (default: output.mp3)").option(
84154
- "-m, --model <model>",
84155
- "TTS model (inworld-tts-1.5-mini, inworld-tts-1.5-max, or legacy inworld-tts-1, inworld-tts-1-max)",
84156
- "inworld-tts-1.5-max"
84157
- ).option(
84158
- "-t, --temperature <temp>",
84159
- "Temperature (0.0-2.0, default: 1.1)",
84160
- "1.1"
84161
- ).option(
84860
+ ).argument(
84861
+ "<text>",
84862
+ "Text to synthesize (max 2000 UTF-16 code units; 4000 with --stream)"
84863
+ ).option("-v, --voice <voiceId>", "Voice ID to use for synthesis", "Dennis").option("-o, --output <file>", "Output audio file path (default: output.mp3)").option(
84162
84864
  "--format <format>",
84163
84865
  "Audio format (MP3, LINEAR16, OGG_OPUS, FLAC, PCM, WAV, ALAW, MULAW). Default: MP3 (LINEAR16 for streaming)"
84164
- ).option("--timestamps <type>", "Include timestamps (WORD or CHARACTER)").option("--normalize <mode>", "Text normalization (on or off)").option("-j, --json", "Output response as JSON (includes base64 audio)").option("-p, --play", "Play the synthesized audio through speakers").option("--stats", "Show request performance statistics").option("--stream", "Use streaming API for synthesis").action(async (text, options) => {
84866
+ ).option("--timestamps <type>", "Include timestamps (WORD or CHARACTER)").option(
84867
+ "--sample-rate <hz>",
84868
+ "Audio sample rate: 8000, 16000, 22050, 24000, 32000, 44100, 48000"
84869
+ ).option("--bit-rate <bps>", "MP3/OGG_OPUS bit rate in bits per second").option(
84870
+ "--instruction <text>",
84871
+ "TTS-2 only: speaking-style instruction, written in English"
84872
+ ).option("--enhance-generation", "Denoise generated audio").option(
84873
+ "--previous-text <text>",
84874
+ "Previous synthesis text; repeat in chronological order (2000 code units total)",
84875
+ (text, previous = []) => [...previous, text]
84876
+ ).option(
84877
+ "--timestamp-transport <strategy>",
84878
+ "With --stream: SYNC or ASYNC timestamp delivery"
84879
+ ).option(
84880
+ "--voice-design <prompt>",
84881
+ "Preview: design a voice for this request (TTS-2 only; excludes --voice)"
84882
+ ).option("-j, --json", "Output response as JSON (includes base64 audio)").option("-p, --play", "Play the synthesized audio through speakers").option("--stats", "Show request performance statistics").option("--stream", "Use streaming API for synthesis").action(async (text, options, command) => {
84165
84883
  try {
84166
- if (text.length > 2e3) {
84167
- console.error(source_default.red("Error: Text exceeds 2000 character limit"));
84168
- console.log(source_default.gray(`Current length: ${text.length} characters`));
84169
- process.exit(1);
84170
- }
84171
- const temperature = parseFloat(options.temperature);
84172
- if (isNaN(temperature) || temperature < 0 || temperature > 2) {
84173
- console.error(
84174
- source_default.red("Error: Temperature must be between 0.0 and 2.0")
84175
- );
84176
- process.exit(1);
84177
- }
84178
- const modelId = resolveModel(options.model);
84179
- console.log(source_default.cyan("Synthesizing speech..."));
84180
- console.log(source_default.gray(`Voice: ${options.voice}`));
84181
- console.log(source_default.gray(`Model: ${options.model}`));
84182
- console.log(source_default.gray(`Text length: ${text.length} characters`));
84183
- const defaultFormat = options.stream ? "LINEAR16" : "MP3";
84184
- const format2 = resolveFormat(options.format, defaultFormat);
84884
+ const request = buildSynthesisRequest(
84885
+ text,
84886
+ options,
84887
+ command.getOptionValueSource("voice") === "cli"
84888
+ );
84889
+ const log = options.json ? console.error : console.log;
84890
+ log(source_default.cyan("Synthesizing speech..."));
84891
+ log(source_default.gray(`Voice: ${request.voiceId ?? "ad-hoc design"}`));
84892
+ log(source_default.gray(`Model: ${request.modelId}`));
84893
+ log(source_default.gray(`Text length: ${text.length} characters`));
84894
+ const format2 = request.audioConfig.audioEncoding;
84185
84895
  const fileExtension = getFileExtension(format2);
84186
- const safeVoice = options.voice.replace(/[^a-zA-Z0-9_-]/g, "_");
84896
+ const safeVoice = (request.voiceId ?? "designed-voice").replace(
84897
+ /[^a-zA-Z0-9_-]/g,
84898
+ "_"
84899
+ );
84187
84900
  const outputPath = resolve3(
84188
84901
  options.output || `${safeVoice}_${Date.now()}${fileExtension}`
84189
84902
  );
84190
- const request = {
84191
- text,
84192
- voiceId: options.voice,
84193
- modelId,
84194
- temperature,
84195
- audioConfig: { audioEncoding: format2 }
84196
- };
84197
- if (options.timestamps) {
84198
- request.timestampType = options.timestamps;
84199
- }
84200
- if (options.normalize) {
84201
- const mode = options.normalize.toUpperCase();
84202
- if (mode === "ON" || mode === "OFF") {
84203
- request.applyTextNormalization = mode;
84204
- } else {
84205
- console.error(source_default.red('Error: --normalize must be "on" or "off"'));
84206
- process.exit(1);
84207
- }
84208
- }
84209
84903
  let response;
84210
84904
  let audioBuffer;
84211
84905
  if (options.stream) {
84212
84906
  if (format2 === "MP3") {
84213
- console.log(
84907
+ log(
84214
84908
  source_default.yellow("Warning: MP3 streaming requires special handling.")
84215
84909
  );
84216
- console.log(
84217
- source_default.yellow(" Audio chunks may not concatenate perfectly.")
84218
- );
84219
- console.log(
84910
+ log(source_default.yellow(" Audio chunks may not concatenate perfectly."));
84911
+ log(
84220
84912
  source_default.yellow(
84221
84913
  " Consider using LINEAR16 or OGG_OPUS for better streaming."
84222
84914
  )
84223
84915
  );
84224
84916
  }
84225
- console.log(source_default.cyan("Using streaming synthesis..."));
84226
- console.log(source_default.gray(`Format: ${format2}${fileExtension}`));
84917
+ log(source_default.cyan("Using streaming synthesis..."));
84918
+ log(source_default.gray(`Format: ${format2}${fileExtension}`));
84227
84919
  const audioChunks = [];
84228
- let timestampInfo = null;
84920
+ let timestampInfo;
84921
+ let usage;
84229
84922
  let streamError = null;
84230
84923
  let chunkCount = 0;
84231
- let isFirstChunk = true;
84232
84924
  const allWordAlignments = {
84233
84925
  words: [],
84234
84926
  wordStartTimeSeconds: [],
@@ -84249,19 +84941,7 @@ var synthesizeCommand = new Command("synthesize").description(
84249
84941
  } else {
84250
84942
  if (chunk.audioContent) {
84251
84943
  const chunkBuffer = Buffer.from(chunk.audioContent, "base64");
84252
- if (format2 === "LINEAR16" || format2 === "WAV") {
84253
- if (!isFirstChunk) {
84254
- const headerSize = 44;
84255
- if (chunkBuffer.length > headerSize) {
84256
- audioChunks.push(chunkBuffer.slice(headerSize));
84257
- }
84258
- } else {
84259
- audioChunks.push(chunkBuffer);
84260
- isFirstChunk = false;
84261
- }
84262
- } else {
84263
- audioChunks.push(chunkBuffer);
84264
- }
84944
+ audioChunks.push(chunkBuffer);
84265
84945
  if (!options.json && !options.stats) {
84266
84946
  const chunkSizeKB = (chunkBuffer.length / 1024).toFixed(2);
84267
84947
  process.stdout.write(
@@ -84271,15 +84951,17 @@ var synthesizeCommand = new Command("synthesize").description(
84271
84951
  );
84272
84952
  }
84273
84953
  }
84954
+ if (chunk.usage) {
84955
+ usage = {
84956
+ modelId: chunk.usage.modelId,
84957
+ processedCharactersCount: (usage?.processedCharactersCount ?? 0) + (chunk.usage.processedCharactersCount ?? 0)
84958
+ };
84959
+ }
84274
84960
  if (chunk.timestampInfo) {
84275
84961
  if (chunk.timestampInfo.wordAlignment) {
84276
- const wa = chunk.timestampInfo.wordAlignment;
84277
- allWordAlignments.words.push(...wa.words || []);
84278
- allWordAlignments.wordStartTimeSeconds.push(
84279
- ...wa.wordStartTimeSeconds || []
84280
- );
84281
- allWordAlignments.wordEndTimeSeconds.push(
84282
- ...wa.wordEndTimeSeconds || []
84962
+ appendWordAlignment(
84963
+ allWordAlignments,
84964
+ chunk.timestampInfo.wordAlignment
84283
84965
  );
84284
84966
  }
84285
84967
  if (chunk.timestampInfo.characterAlignment) {
@@ -84305,7 +84987,7 @@ var synthesizeCommand = new Command("synthesize").description(
84305
84987
  if (streamError) {
84306
84988
  throw new Error(`Stream error: ${streamError.message}`);
84307
84989
  }
84308
- audioBuffer = Buffer.concat(audioChunks);
84990
+ audioBuffer = combineAudioChunks(audioChunks, format2);
84309
84991
  if (allWordAlignments.words.length > 0 || allCharacterAlignments.characters.length > 0) {
84310
84992
  timestampInfo = {};
84311
84993
  if (allWordAlignments.words.length > 0) {
@@ -84319,6 +85001,7 @@ var synthesizeCommand = new Command("synthesize").description(
84319
85001
  response = {
84320
85002
  audioContent: combinedAudioBase64,
84321
85003
  timestampInfo,
85004
+ usage,
84322
85005
  _metrics: streamResult._metrics
84323
85006
  };
84324
85007
  if (options.json) {
@@ -84327,6 +85010,7 @@ var synthesizeCommand = new Command("synthesize").description(
84327
85010
  {
84328
85011
  audioContent: combinedAudioBase64,
84329
85012
  timestampInfo,
85013
+ usage,
84330
85014
  streamMetrics: streamResult._metrics
84331
85015
  },
84332
85016
  null,
@@ -84335,22 +85019,22 @@ var synthesizeCommand = new Command("synthesize").description(
84335
85019
  );
84336
85020
  } else {
84337
85021
  await writeFile6(outputPath, audioBuffer);
84338
- console.log(source_default.green(`Audio saved to: ${outputPath}`));
84339
- console.log(
85022
+ log(source_default.green(`Audio saved to: ${outputPath}`));
85023
+ log(
84340
85024
  source_default.gray(
84341
85025
  `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
84342
85026
  )
84343
85027
  );
84344
- console.log(source_default.gray(`Chunks received: ${chunkCount}`));
85028
+ log(source_default.gray(`Chunks received: ${chunkCount}`));
84345
85029
  if (allWordAlignments.words.length > 0) {
84346
- console.log(
85030
+ log(
84347
85031
  source_default.gray(
84348
85032
  `Word timestamps collected: ${allWordAlignments.words.length}`
84349
85033
  )
84350
85034
  );
84351
85035
  }
84352
85036
  if (allCharacterAlignments.characters.length > 0) {
84353
- console.log(
85037
+ log(
84354
85038
  source_default.gray(
84355
85039
  `Character timestamps collected: ${allCharacterAlignments.characters.length}`
84356
85040
  )
@@ -84358,15 +85042,15 @@ var synthesizeCommand = new Command("synthesize").description(
84358
85042
  }
84359
85043
  }
84360
85044
  } else {
84361
- console.log(source_default.gray(`Format: ${format2}`));
85045
+ log(source_default.gray(`Format: ${format2}`));
84362
85046
  response = options.stats ? await ttsService.synthesizeSpeechWithMetrics(request) : await ttsService.synthesizeSpeech(request);
84363
85047
  audioBuffer = Buffer.from(response.audioContent, "base64");
84364
85048
  if (options.json) {
84365
85049
  console.log(JSON.stringify(response, null, 2));
84366
85050
  } else {
84367
85051
  await writeFile6(outputPath, audioBuffer);
84368
- console.log(source_default.green(`Audio saved to: ${outputPath}`));
84369
- console.log(
85052
+ log(source_default.green(`Audio saved to: ${outputPath}`));
85053
+ log(
84370
85054
  source_default.gray(
84371
85055
  `File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
84372
85056
  )
@@ -84378,7 +85062,7 @@ var synthesizeCommand = new Command("synthesize").description(
84378
85062
  return;
84379
85063
  }
84380
85064
  if (response.usage) {
84381
- console.log(
85065
+ log(
84382
85066
  source_default.gray(
84383
85067
  `Characters processed: ${response.usage.processedCharactersCount} (model: ${response.usage.modelId})`
84384
85068
  )
@@ -84387,34 +85071,48 @@ var synthesizeCommand = new Command("synthesize").description(
84387
85071
  if (options.stats && response._metrics) {
84388
85072
  const m = response._metrics;
84389
85073
  const isStreaming = "timeToFirstChunk" in m;
85074
+ const logAudioDuration = () => {
85075
+ const duration3 = audioBuffer ? estimateAudioDuration(audioBuffer, request.audioConfig) : void 0;
85076
+ log(
85077
+ source_default.white(" Audio Duration: ") + source_default.yellow(
85078
+ duration3 === void 0 ? "unavailable for this audio format" : `${duration3.toFixed(2)} seconds (estimated)`
85079
+ )
85080
+ );
85081
+ if (duration3 !== void 0 && m.totalTime > 0) {
85082
+ const realTimeRatio = duration3 / (m.totalTime / 1e3);
85083
+ log(
85084
+ source_default.white(" Real-time Factor: ") + (realTimeRatio > 1 ? source_default.green(`${realTimeRatio.toFixed(2)}x faster`) : source_default.yellow(`${realTimeRatio.toFixed(2)}x`))
85085
+ );
85086
+ }
85087
+ };
84390
85088
  if (isStreaming) {
84391
85089
  const sm = m;
84392
- console.log("\n" + source_default.cyan("Streaming Performance Statistics:"));
84393
- console.log(source_default.gray("\u2550".repeat(50)));
84394
- console.log(source_default.bold.white("\n Streaming Timeline:"));
84395
- console.log(source_default.gray(" \u2500".repeat(23)));
84396
- console.log(
85090
+ log("\n" + source_default.cyan("Streaming Performance Statistics:"));
85091
+ log(source_default.gray("\u2550".repeat(50)));
85092
+ log(source_default.bold.white("\n Streaming Timeline:"));
85093
+ log(source_default.gray(" \u2500".repeat(23)));
85094
+ log(
84397
85095
  source_default.white(" Time to First Chunk: ") + source_default.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`)
84398
85096
  );
84399
- console.log(
85097
+ log(
84400
85098
  source_default.white(" Total Stream Time: ") + source_default.bold.yellow(`${sm.totalTime.toFixed(0)} ms`)
84401
85099
  );
84402
- console.log(source_default.bold.white("\n Chunk Statistics:"));
84403
- console.log(source_default.gray(" \u2500".repeat(23)));
84404
- console.log(
85100
+ log(source_default.bold.white("\n Chunk Statistics:"));
85101
+ log(source_default.gray(" \u2500".repeat(23)));
85102
+ log(
84405
85103
  source_default.white(" Chunks Received: ") + source_default.yellow(`${sm.chunksReceived}`)
84406
85104
  );
84407
85105
  if (sm.errorChunks > 0) {
84408
- console.log(
85106
+ log(
84409
85107
  source_default.white(" Error Chunks: ") + source_default.red(`${sm.errorChunks}`)
84410
85108
  );
84411
85109
  }
84412
85110
  if (sm.chunkSizes.length > 0) {
84413
85111
  const avgChunkSize = sm.chunkSizes.reduce((a2, b) => a2 + b, 0) / sm.chunkSizes.length;
84414
- console.log(
85112
+ log(
84415
85113
  source_default.white(" Avg Chunk Size: ") + source_default.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`)
84416
85114
  );
84417
- console.log(
85115
+ log(
84418
85116
  source_default.gray(" Min/Max: ") + source_default.gray(
84419
85117
  `${(Math.min(...sm.chunkSizes) / 1024).toFixed(2)} - ${(Math.max(...sm.chunkSizes) / 1024).toFixed(2)} KB`
84420
85118
  )
@@ -84422,118 +85120,107 @@ var synthesizeCommand = new Command("synthesize").description(
84422
85120
  }
84423
85121
  if (sm.chunkIntervals.length > 0) {
84424
85122
  const avgInterval = sm.chunkIntervals.reduce((a2, b) => a2 + b, 0) / sm.chunkIntervals.length;
84425
- console.log(
85123
+ log(
84426
85124
  source_default.white(" Avg Chunk Interval: ") + source_default.yellow(`${avgInterval.toFixed(0)} ms`)
84427
85125
  );
84428
- console.log(
85126
+ log(
84429
85127
  source_default.gray(" Min/Max: ") + source_default.gray(
84430
85128
  `${Math.min(...sm.chunkIntervals).toFixed(0)} - ${Math.max(...sm.chunkIntervals).toFixed(0)} ms`
84431
85129
  )
84432
85130
  );
84433
85131
  }
84434
- console.log(source_default.bold.white("\n Data Transfer:"));
84435
- console.log(source_default.gray(" \u2500".repeat(23)));
84436
- console.log(
85132
+ log(source_default.bold.white("\n Data Transfer:"));
85133
+ log(source_default.gray(" \u2500".repeat(23)));
85134
+ log(
84437
85135
  source_default.white(" Total Data: ") + source_default.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`)
84438
85136
  );
84439
- console.log(
85137
+ log(
84440
85138
  source_default.white(" Audio File: ") + source_default.yellow(
84441
85139
  `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
84442
85140
  )
84443
85141
  );
84444
- console.log(source_default.bold.white("\n Performance Metrics:"));
84445
- console.log(source_default.gray(" \u2500".repeat(23)));
85142
+ log(source_default.bold.white("\n Performance Metrics:"));
85143
+ log(source_default.gray(" \u2500".repeat(23)));
84446
85144
  const throughputKBps = sm.totalBytes / 1024 / (sm.totalTime / 1e3);
84447
- console.log(
85145
+ log(
84448
85146
  source_default.white(" Stream Throughput: ") + source_default.yellow(`${throughputKBps.toFixed(2)} KB/s`)
84449
85147
  );
84450
- const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
84451
- const realTimeRatio = audioDuration / (sm.totalTime / 1e3);
84452
- console.log(
84453
- source_default.white(" Audio Duration: ") + source_default.yellow(`${audioDuration.toFixed(2)} seconds`)
84454
- );
84455
- console.log(
84456
- source_default.white(" Real-time Factor: ") + (realTimeRatio > 1 ? source_default.green(`${realTimeRatio.toFixed(2)}x faster`) : source_default.yellow(`${realTimeRatio.toFixed(2)}x`))
84457
- );
85148
+ logAudioDuration();
84458
85149
  const streamingEfficiency = (sm.totalTime - sm.timeToFirstChunk) / sm.totalTime * 100;
84459
- console.log(
85150
+ log(
84460
85151
  source_default.white(" Stream Efficiency: ") + source_default.yellow(`${streamingEfficiency.toFixed(1)}%`)
84461
85152
  );
84462
- console.log(source_default.gray("\u2550".repeat(50)));
85153
+ log(source_default.gray("\u2550".repeat(50)));
84463
85154
  } else {
84464
- console.log("\n" + source_default.cyan("Performance Statistics:"));
84465
- console.log(source_default.gray("\u2550".repeat(50)));
84466
- console.log(source_default.bold.white("\n Network Timing:"));
84467
- console.log(source_default.gray(" \u2500".repeat(23)));
84468
- console.log(
85155
+ log("\n" + source_default.cyan("Performance Statistics:"));
85156
+ log(source_default.gray("\u2550".repeat(50)));
85157
+ log(source_default.bold.white("\n Network Timing:"));
85158
+ log(source_default.gray(" \u2500".repeat(23)));
85159
+ log(
84469
85160
  source_default.white(" Time to First Byte: ") + source_default.yellow(`${m.ttfb.toFixed(0)} ms`)
84470
85161
  );
84471
85162
  if (m.downloadTime !== void 0) {
84472
- console.log(
85163
+ log(
84473
85164
  source_default.white(" Content Download: ") + source_default.yellow(`${m.downloadTime.toFixed(0)} ms`)
84474
85165
  );
84475
85166
  }
84476
- console.log(
85167
+ log(
84477
85168
  source_default.white(" Total Time: ") + source_default.bold.yellow(`${m.totalTime.toFixed(0)} ms`)
84478
85169
  );
84479
- console.log(source_default.bold.white("\n Data Transfer:"));
84480
- console.log(source_default.gray(" \u2500".repeat(23)));
85170
+ log(source_default.bold.white("\n Data Transfer:"));
85171
+ log(source_default.gray(" \u2500".repeat(23)));
84481
85172
  if (m.requestSize) {
84482
- console.log(
85173
+ log(
84483
85174
  source_default.white(" Request Size: ") + source_default.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`)
84484
85175
  );
84485
85176
  }
84486
- console.log(
85177
+ log(
84487
85178
  source_default.white(" Response Size: ") + source_default.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`)
84488
85179
  );
84489
- console.log(
85180
+ log(
84490
85181
  source_default.white(" Audio File: ") + source_default.yellow(
84491
85182
  `${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
84492
85183
  )
84493
85184
  );
84494
- console.log(source_default.bold.white("\n Performance Metrics:"));
84495
- console.log(source_default.gray(" \u2500".repeat(23)));
84496
- const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
84497
- const realTimeRatio = audioDuration / (m.totalTime / 1e3);
84498
- console.log(
85185
+ log(source_default.bold.white("\n Performance Metrics:"));
85186
+ log(source_default.gray(" \u2500".repeat(23)));
85187
+ log(
84499
85188
  source_default.white(" Server Processing: ") + source_default.yellow(`${Math.max(0, m.ttfb).toFixed(0)} ms`)
84500
85189
  );
84501
- console.log(
84502
- source_default.white(" Audio Duration: ") + source_default.yellow(`${audioDuration.toFixed(2)} seconds`)
84503
- );
84504
- console.log(
84505
- source_default.white(" Real-time Factor: ") + (realTimeRatio > 1 ? source_default.green(`${realTimeRatio.toFixed(2)}x faster`) : source_default.yellow(`${realTimeRatio.toFixed(2)}x`))
84506
- );
85190
+ logAudioDuration();
84507
85191
  const throughputMbps = (m.responseSize + (audioBuffer?.length || 0)) * 8 / (m.totalTime * 1e3);
84508
- console.log(
85192
+ log(
84509
85193
  source_default.white(" Throughput: ") + source_default.yellow(`${throughputMbps.toFixed(2)} Mbps`)
84510
85194
  );
84511
- console.log(source_default.gray("\u2550".repeat(50)));
85195
+ log(source_default.gray("\u2550".repeat(50)));
84512
85196
  }
84513
85197
  }
84514
85198
  if (response.timestampInfo?.wordAlignment) {
84515
85199
  const alignment = response.timestampInfo.wordAlignment;
84516
- console.log("\n" + source_default.cyan("Word Timestamps:"));
85200
+ log("\n" + source_default.cyan("Word Timestamps:"));
84517
85201
  alignment.words.forEach((word, i2) => {
84518
85202
  const start = alignment.wordStartTimeSeconds[i2].toFixed(3);
84519
85203
  const end = alignment.wordEndTimeSeconds[i2].toFixed(3);
84520
- console.log(source_default.gray(` ${start}s - ${end}s: ${word}`));
85204
+ log(source_default.gray(` ${start}s - ${end}s: ${word}`));
84521
85205
  });
84522
85206
  if (alignment.phoneticDetails && alignment.phoneticDetails.length > 0) {
84523
- console.log("\n" + source_default.cyan("Phonetic Details (IPA + Visemes):"));
85207
+ log("\n" + source_default.cyan("Phonetic Details (IPA + Visemes):"));
84524
85208
  for (const detail of alignment.phoneticDetails) {
84525
- const viseme = detail.visemeSymbol ? source_default.yellow(` [${detail.visemeSymbol}]`) : "";
84526
- console.log(
84527
- source_default.gray(
84528
- ` ${detail.startTimeSeconds.toFixed(3)}s +${detail.durationSeconds.toFixed(3)}s: /${detail.phoneSymbol}/${viseme}`
84529
- )
84530
- );
85209
+ const phones = "phoneSymbol" in detail ? [detail] : detail.phones ?? [];
85210
+ for (const phone of phones) {
85211
+ const viseme = phone.visemeSymbol ? source_default.yellow(` [${phone.visemeSymbol}]`) : "";
85212
+ log(
85213
+ source_default.gray(
85214
+ ` ${(phone.startTimeSeconds ?? 0).toFixed(3)}s +${(phone.durationSeconds ?? 0).toFixed(3)}s: /${phone.phoneSymbol}/${viseme}`
85215
+ )
85216
+ );
85217
+ }
84531
85218
  }
84532
85219
  }
84533
85220
  }
84534
85221
  if (response.timestampInfo?.characterAlignment) {
84535
- console.log("\n" + source_default.cyan("Character Timestamps:"));
84536
- console.log(
85222
+ log("\n" + source_default.cyan("Character Timestamps:"));
85223
+ log(
84537
85224
  source_default.gray(
84538
85225
  " (Too detailed to display - use --json to see full data)"
84539
85226
  )
@@ -84542,7 +85229,7 @@ var synthesizeCommand = new Command("synthesize").description(
84542
85229
  if (options.play && audioBuffer) {
84543
85230
  const played = await playFile(outputPath);
84544
85231
  if (!played) {
84545
- console.log(source_default.gray(`Playback unavailable. Open: ${outputPath}`));
85232
+ log(source_default.gray(`Playback unavailable. Open: ${outputPath}`));
84546
85233
  }
84547
85234
  }
84548
85235
  process.exit(0);
@@ -84725,6 +85412,10 @@ var updateChecker = new UpdateChecker();
84725
85412
 
84726
85413
  // src/index.ts
84727
85414
  var version2 = CLI_VERSION;
85415
+ var MACHINE_OUTPUT_COMMANDS = [
85416
+ ["auth", "print-api-key"],
85417
+ ["auth", "print-access-token"]
85418
+ ];
84728
85419
  process.env.DISABLE_WELCOME_MESSAGE = "true";
84729
85420
  var InworldCLI = class {
84730
85421
  program;
@@ -84765,10 +85456,11 @@ var InworldCLI = class {
84765
85456
  sanitizeOptions(options) {
84766
85457
  const sanitized = {};
84767
85458
  const sensitiveKeys = ["token", "apikey", "password", "secret", "key"];
85459
+ const contentKeys = ["instruction", "voicedesign", "previoustext"];
84768
85460
  for (const [key, value] of Object.entries(options)) {
84769
85461
  const lowerKey = key.toLowerCase();
84770
85462
  const isSensitive = sensitiveKeys.some((k) => lowerKey.includes(k));
84771
- if (isSensitive) {
85463
+ if (isSensitive || contentKeys.includes(lowerKey)) {
84772
85464
  sanitized[key] = "[REDACTED]";
84773
85465
  } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
84774
85466
  sanitized[key] = value;
@@ -84793,12 +85485,19 @@ var InworldCLI = class {
84793
85485
  this.program.help();
84794
85486
  });
84795
85487
  }
85488
+ isMachineOutputCommand(argv) {
85489
+ if (argv.includes("--json") || argv.includes("-j")) return true;
85490
+ const commandArgs = argv.slice(2).filter((arg) => !arg.startsWith("-"));
85491
+ return MACHINE_OUTPUT_COMMANDS.some(
85492
+ (path13) => path13.every((part, i2) => commandArgs[i2] === part)
85493
+ );
85494
+ }
84796
85495
  async run(args) {
84797
85496
  try {
84798
85497
  const initPromise = Promise.all([
84799
85498
  analytics.initialize().catch(() => {
84800
85499
  }),
84801
- updateChecker.checkAndNotify().catch(() => {
85500
+ this.isMachineOutputCommand(args ?? process.argv) ? Promise.resolve() : updateChecker.checkAndNotify().catch(() => {
84802
85501
  })
84803
85502
  ]);
84804
85503
  const timeoutPromise = new Promise(