@inworld/cli 1.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17316,8 +17316,8 @@ var require_semver = __commonJS({
17316
17316
  }
17317
17317
  // preminor will bump the version up to the next minor release, and immediately
17318
17318
  // down to pre-release. premajor and prepatch work the same way.
17319
- inc(release, identifier, identifierBase) {
17320
- if (release.startsWith("pre")) {
17319
+ inc(release2, identifier, identifierBase) {
17320
+ if (release2.startsWith("pre")) {
17321
17321
  if (!identifier && identifierBase === false) {
17322
17322
  throw new Error("invalid increment argument: identifier is empty");
17323
17323
  }
@@ -17328,7 +17328,7 @@ var require_semver = __commonJS({
17328
17328
  }
17329
17329
  }
17330
17330
  }
17331
- switch (release) {
17331
+ switch (release2) {
17332
17332
  case "premajor":
17333
17333
  this.prerelease.length = 0;
17334
17334
  this.patch = 0;
@@ -17419,7 +17419,7 @@ var require_semver = __commonJS({
17419
17419
  break;
17420
17420
  }
17421
17421
  default:
17422
- throw new Error(`invalid increment argument: ${release}`);
17422
+ throw new Error(`invalid increment argument: ${release2}`);
17423
17423
  }
17424
17424
  this.raw = this.format();
17425
17425
  if (this.build.length) {
@@ -17485,7 +17485,7 @@ var require_inc = __commonJS({
17485
17485
  "../../node_modules/semver/functions/inc.js"(exports, module) {
17486
17486
  "use strict";
17487
17487
  var SemVer = require_semver();
17488
- var inc = (version3, release, options, identifier, identifierBase) => {
17488
+ var inc = (version3, release2, options, identifier, identifierBase) => {
17489
17489
  if (typeof options === "string") {
17490
17490
  identifierBase = identifier;
17491
17491
  identifier = options;
@@ -17495,7 +17495,7 @@ var require_inc = __commonJS({
17495
17495
  return new SemVer(
17496
17496
  version3 instanceof SemVer ? version3.version : version3,
17497
17497
  options
17498
- ).inc(release, identifier, identifierBase).version;
17498
+ ).inc(release2, identifier, identifierBase).version;
17499
17499
  } catch (er) {
17500
17500
  return null;
17501
17501
  }
@@ -19401,20 +19401,22 @@ var init_source = __esm({
19401
19401
  });
19402
19402
 
19403
19403
  // ../inworld-auth-store/dist/index.js
19404
- import { createHash } from "node:crypto";
19405
- async function getKeyring() {
19406
- if (keyringLoadAttempted) {
19407
- return keyringModule;
19408
- }
19409
- keyringLoadAttempted = true;
19410
- try {
19411
- const module = await import("@zowe/secrets-for-zowe-sdk");
19412
- keyringModule = module.keyring;
19413
- return keyringModule;
19414
- } catch {
19415
- keyringModule = null;
19416
- return null;
19417
- }
19404
+ import { createHash, randomUUID } from "node:crypto";
19405
+ import {
19406
+ linkSync,
19407
+ mkdirSync,
19408
+ readFileSync,
19409
+ unlinkSync,
19410
+ writeFileSync as writeFileSync2
19411
+ } from "node:fs";
19412
+ import { homedir as homedir2 } from "node:os";
19413
+ import { dirname, join } from "node:path";
19414
+ function getKeyring() {
19415
+ keyringLoad ??= import("@zowe/secrets-for-zowe-sdk").then(
19416
+ (module) => module.keyring,
19417
+ () => null
19418
+ );
19419
+ return keyringLoad;
19418
19420
  }
19419
19421
  async function generateEncryptionKey() {
19420
19422
  const platform2 = process.platform;
@@ -19439,7 +19441,6 @@ async function getConf() {
19439
19441
  inworldToken: { type: "string" },
19440
19442
  expiresAt: { type: "number" },
19441
19443
  workspace: { type: "string" },
19442
- apiKey: { type: "string" },
19443
19444
  env: { type: "string" },
19444
19445
  authProvider: { type: "string" },
19445
19446
  authUrl: { type: "string" }
@@ -19450,6 +19451,30 @@ async function getConf() {
19450
19451
  }
19451
19452
  return confSingleton;
19452
19453
  }
19454
+ async function getRuntimeTokenConf() {
19455
+ if (!runtimeTokenConfSingleton) {
19456
+ const encryptionKey = await generateEncryptionKey();
19457
+ runtimeTokenConfSingleton = new Conf({
19458
+ projectName: "inworld-cli",
19459
+ configName: "runtime-token",
19460
+ encryptionKey,
19461
+ schema: {
19462
+ runtimeToken: {
19463
+ type: "object",
19464
+ properties: {
19465
+ user: { type: "string" },
19466
+ deployment: { type: "string" },
19467
+ workspace: { type: "string" },
19468
+ platformUrl: { type: "string" },
19469
+ token: { type: "string" },
19470
+ expiresAt: { type: "number" }
19471
+ }
19472
+ }
19473
+ }
19474
+ });
19475
+ }
19476
+ return runtimeTokenConfSingleton;
19477
+ }
19453
19478
  async function readStoredCredentials() {
19454
19479
  try {
19455
19480
  const keyring = await getKeyring();
@@ -19472,8 +19497,115 @@ async function readStoredCredentials() {
19472
19497
  throw new Error(`Failed to retrieve credentials: ${error2}`);
19473
19498
  }
19474
19499
  }
19500
+ function credentialsLockPath() {
19501
+ return join(homedir2(), ".config", "inworld-cli", "credentials.lock");
19502
+ }
19503
+ function lockText(path13) {
19504
+ try {
19505
+ return readFileSync(path13, "utf8");
19506
+ } catch {
19507
+ return null;
19508
+ }
19509
+ }
19510
+ function lockOwner(text) {
19511
+ try {
19512
+ const owner = JSON.parse(text ?? "");
19513
+ return typeof owner.pid === "number" && typeof owner.token === "string" ? { pid: owner.pid, token: owner.token } : null;
19514
+ } catch {
19515
+ return null;
19516
+ }
19517
+ }
19518
+ function isRunning(pid) {
19519
+ try {
19520
+ process.kill(pid, 0);
19521
+ return true;
19522
+ } catch (error2) {
19523
+ return error2.code === "EPERM";
19524
+ }
19525
+ }
19526
+ function isAbandoned(text) {
19527
+ const owner = lockOwner(text);
19528
+ return !owner || !isRunning(owner.pid);
19529
+ }
19530
+ function remove(path13) {
19531
+ try {
19532
+ unlinkSync(path13);
19533
+ } catch {
19534
+ }
19535
+ }
19536
+ function claim(path13, owner) {
19537
+ const draft = `${path13}.${owner.token}`;
19538
+ writeFileSync2(draft, JSON.stringify(owner));
19539
+ try {
19540
+ linkSync(draft, path13);
19541
+ return true;
19542
+ } catch (error2) {
19543
+ if (error2.code !== "EEXIST") throw error2;
19544
+ return false;
19545
+ } finally {
19546
+ remove(draft);
19547
+ }
19548
+ }
19549
+ function release(path13, owner) {
19550
+ if (lockOwner(lockText(path13))?.token === owner.token) remove(path13);
19551
+ }
19552
+ function clearAbandoned(path13, text, me) {
19553
+ const name = createHash("sha256").update(text).digest("hex").slice(0, 32);
19554
+ const arbiterPath = `${path13}.takeover.${name}`;
19555
+ if (!claim(arbiterPath, me)) {
19556
+ const arbiter = lockText(arbiterPath);
19557
+ if (arbiter !== null && isAbandoned(arbiter)) {
19558
+ clearAbandoned(arbiterPath, arbiter, me);
19559
+ }
19560
+ return;
19561
+ }
19562
+ try {
19563
+ if (lockText(path13) === text) remove(path13);
19564
+ } finally {
19565
+ release(arbiterPath, me);
19566
+ }
19567
+ }
19568
+ function tryLock(lockPath, me) {
19569
+ const text = lockText(lockPath);
19570
+ if (text === null) return claim(lockPath, me);
19571
+ if (!isAbandoned(text)) return false;
19572
+ clearAbandoned(lockPath, text, me);
19573
+ return claim(lockPath, me);
19574
+ }
19575
+ async function withCredentialsLock(work) {
19576
+ const lockPath = credentialsLockPath();
19577
+ mkdirSync(dirname(lockPath), { recursive: true });
19578
+ const me = { pid: process.pid, token: randomUUID() };
19579
+ const deadline = Date.now() + LOCK_WAIT_MS;
19580
+ while (!tryLock(lockPath, me)) {
19581
+ if (Date.now() > deadline) {
19582
+ throw new Error(
19583
+ `The credential store is busy: another Inworld process holds ${lockPath}. Try again.`
19584
+ );
19585
+ }
19586
+ await new Promise((resolve5) => setTimeout(resolve5, LOCK_RETRY_MS));
19587
+ }
19588
+ try {
19589
+ return await work();
19590
+ } finally {
19591
+ release(lockPath, me);
19592
+ }
19593
+ }
19475
19594
  async function writeStoredCredentials(credentials, options) {
19595
+ return withCredentialsLock(() => writeCredentials(credentials, options));
19596
+ }
19597
+ async function updateStoredCredentials(change, options) {
19598
+ return withCredentialsLock(async () => {
19599
+ const current = await readStoredCredentials();
19600
+ const next = change(current);
19601
+ if (next === void 0) return { credentials: current };
19602
+ const { saved } = await writeCredentials(next, options);
19603
+ return { credentials: withoutLegacyApiKey(next), saved };
19604
+ });
19605
+ }
19606
+ async function writeCredentials(credentials, options) {
19476
19607
  try {
19608
+ credentials = withoutLegacyApiKey(credentials);
19477
19609
  const keyring = await getKeyring();
19478
19610
  if (keyring) {
19479
19611
  try {
@@ -19495,22 +19627,80 @@ async function writeStoredCredentials(credentials, options) {
19495
19627
  throw new Error(`Failed to save credentials: ${error2}`);
19496
19628
  }
19497
19629
  }
19630
+ function withoutLegacyApiKey(credentials) {
19631
+ const { apiKey: _dropped, ...kept } = credentials;
19632
+ return kept;
19633
+ }
19498
19634
  async function clearStoredCredentials() {
19635
+ try {
19636
+ await withCredentialsLock(async () => {
19637
+ const keyring = await getKeyring();
19638
+ if (keyring) {
19639
+ try {
19640
+ await keyring.deletePassword(SERVICE_NAME, ACCOUNT_NAME);
19641
+ } catch {
19642
+ }
19643
+ }
19644
+ const conf = await getConf();
19645
+ conf.delete(CONFIG_KEY);
19646
+ });
19647
+ await clearStoredRuntimeToken();
19648
+ } catch (error2) {
19649
+ throw new Error(`Failed to clear credentials: ${error2}`);
19650
+ }
19651
+ }
19652
+ async function readStoredRuntimeToken() {
19499
19653
  try {
19500
19654
  const keyring = await getKeyring();
19501
19655
  if (keyring) {
19502
19656
  try {
19503
- await keyring.deletePassword(SERVICE_NAME, ACCOUNT_NAME);
19657
+ const json = await keyring.getPassword(
19658
+ SERVICE_NAME,
19659
+ RUNTIME_TOKEN_ACCOUNT_NAME
19660
+ );
19661
+ if (json) {
19662
+ return JSON.parse(json);
19663
+ }
19504
19664
  } catch {
19505
19665
  }
19506
19666
  }
19507
- const conf = await getConf();
19508
- conf.delete(CONFIG_KEY);
19509
- } catch (error2) {
19510
- throw new Error(`Failed to clear credentials: ${error2}`);
19667
+ const conf = await getRuntimeTokenConf();
19668
+ return conf.get(RUNTIME_TOKEN_CONFIG_KEY) ?? null;
19669
+ } catch {
19670
+ return null;
19671
+ }
19672
+ }
19673
+ async function writeStoredRuntimeToken(token) {
19674
+ const keyring = await getKeyring();
19675
+ if (keyring) {
19676
+ try {
19677
+ await keyring.setPassword(
19678
+ SERVICE_NAME,
19679
+ RUNTIME_TOKEN_ACCOUNT_NAME,
19680
+ JSON.stringify(token)
19681
+ );
19682
+ return;
19683
+ } catch {
19684
+ }
19685
+ }
19686
+ const conf = await getRuntimeTokenConf();
19687
+ conf.set(RUNTIME_TOKEN_CONFIG_KEY, token);
19688
+ }
19689
+ async function clearStoredRuntimeToken() {
19690
+ const keyring = await getKeyring();
19691
+ if (keyring) {
19692
+ try {
19693
+ await keyring.deletePassword(SERVICE_NAME, RUNTIME_TOKEN_ACCOUNT_NAME);
19694
+ } catch {
19695
+ }
19696
+ }
19697
+ try {
19698
+ const conf = await getRuntimeTokenConf();
19699
+ conf.delete(RUNTIME_TOKEN_CONFIG_KEY);
19700
+ } catch {
19511
19701
  }
19512
19702
  }
19513
- var SERVICE_NAME, ACCOUNT_NAME, CONFIG_KEY, confSingleton, keyringModule, keyringLoadAttempted;
19703
+ var SERVICE_NAME, ACCOUNT_NAME, CONFIG_KEY, RUNTIME_TOKEN_ACCOUNT_NAME, RUNTIME_TOKEN_CONFIG_KEY, LOCK_RETRY_MS, LOCK_WAIT_MS, confSingleton, runtimeTokenConfSingleton, keyringLoad;
19514
19704
  var init_dist4 = __esm({
19515
19705
  "../inworld-auth-store/dist/index.js"() {
19516
19706
  "use strict";
@@ -19518,9 +19708,13 @@ var init_dist4 = __esm({
19518
19708
  SERVICE_NAME = "InworldCLI";
19519
19709
  ACCOUNT_NAME = "default";
19520
19710
  CONFIG_KEY = "credentials";
19711
+ RUNTIME_TOKEN_ACCOUNT_NAME = "runtime-token";
19712
+ RUNTIME_TOKEN_CONFIG_KEY = "runtimeToken";
19713
+ LOCK_RETRY_MS = 20;
19714
+ LOCK_WAIT_MS = 1e4;
19521
19715
  confSingleton = null;
19522
- keyringModule = null;
19523
- keyringLoadAttempted = false;
19716
+ runtimeTokenConfSingleton = null;
19717
+ keyringLoad = null;
19524
19718
  }
19525
19719
  });
19526
19720
 
@@ -19530,7 +19724,7 @@ var init_package = __esm({
19530
19724
  "package.json"() {
19531
19725
  package_default = {
19532
19726
  name: "@inworld/cli",
19533
- version: "1.5.0",
19727
+ version: "2.0.0",
19534
19728
  type: "module",
19535
19729
  main: "dist/index.js",
19536
19730
  bin: {
@@ -19824,9 +20018,6 @@ async function revokeSession(source, refreshToken) {
19824
20018
  );
19825
20019
  }
19826
20020
  }
19827
- function signInWithPassword(authUrl, email2, password) {
19828
- return gotrueToken(authUrl, "password", { email: email2, password });
19829
- }
19830
20021
  function createPkcePair() {
19831
20022
  const verifier = base64url(randomBytes(32));
19832
20023
  const challenge = base64url(createHash2("sha256").update(verifier).digest());
@@ -20198,7 +20389,6 @@ async function hasUsableAuthCredentials() {
20198
20389
  try {
20199
20390
  const c3 = await readStoredCredentials();
20200
20391
  if (c3?.refreshToken?.trim() && identitySourceOfStore(c3)) return true;
20201
- if (c3?.apiKey?.trim()) return true;
20202
20392
  } catch {
20203
20393
  }
20204
20394
  return false;
@@ -20216,12 +20406,13 @@ var init_session = __esm({
20216
20406
 
20217
20407
  // src/mcp/auth/cli-store-bridge.ts
20218
20408
  async function persistRotatedRefreshToken(used, next) {
20219
- const c3 = await readStoredCredentials();
20220
- if (!c3?.refreshToken) return false;
20221
- if (used !== next && c3.refreshToken === used) {
20222
- await writeStoredCredentials({ ...c3, refreshToken: next });
20223
- }
20224
- return true;
20409
+ let signedIn = false;
20410
+ await updateStoredCredentials((c3) => {
20411
+ if (!c3?.refreshToken) return void 0;
20412
+ signedIn = true;
20413
+ return used !== next && c3.refreshToken === used ? { ...c3, refreshToken: next } : void 0;
20414
+ });
20415
+ return signedIn;
20225
20416
  }
20226
20417
  async function saveSessionUnlessLoggedOut(session) {
20227
20418
  saveSession(session);
@@ -20266,6 +20457,267 @@ var init_cli_store_bridge = __esm({
20266
20457
  }
20267
20458
  });
20268
20459
 
20460
+ // proto/generated/portal/fetch.pb.ts
20461
+ function b64Encode(buffer, start, end) {
20462
+ let parts = null;
20463
+ const chunk = [];
20464
+ let i2 = 0, j = 0, t;
20465
+ while (start < end) {
20466
+ const b = buffer[start++];
20467
+ switch (j) {
20468
+ case 0:
20469
+ chunk[i2++] = b64[b >> 2];
20470
+ t = (b & 3) << 4;
20471
+ j = 1;
20472
+ break;
20473
+ case 1:
20474
+ chunk[i2++] = b64[t | b >> 4];
20475
+ t = (b & 15) << 2;
20476
+ j = 2;
20477
+ break;
20478
+ case 2:
20479
+ chunk[i2++] = b64[t | b >> 6];
20480
+ chunk[i2++] = b64[b & 63];
20481
+ j = 0;
20482
+ break;
20483
+ }
20484
+ if (i2 > 8191) {
20485
+ (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
20486
+ i2 = 0;
20487
+ }
20488
+ }
20489
+ if (j) {
20490
+ chunk[i2++] = b64[t];
20491
+ chunk[i2++] = 61;
20492
+ if (j === 1) chunk[i2++] = 61;
20493
+ }
20494
+ if (parts) {
20495
+ if (i2) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2)));
20496
+ return parts.join("");
20497
+ }
20498
+ return String.fromCharCode.apply(String, chunk.slice(0, i2));
20499
+ }
20500
+ function replacer(key, value) {
20501
+ if (value && value.constructor === Uint8Array) {
20502
+ return b64Encode(value, 0, value.length);
20503
+ }
20504
+ return value;
20505
+ }
20506
+ function fetchReq(path13, init) {
20507
+ const { pathPrefix, ...req } = init || {};
20508
+ const url = pathPrefix ? `${pathPrefix}${path13}` : path13;
20509
+ return fetch(url, req).then(
20510
+ (r) => r.json().then((body) => {
20511
+ if (!r.ok) {
20512
+ throw body;
20513
+ }
20514
+ return body;
20515
+ })
20516
+ );
20517
+ }
20518
+ function isPlainObject(value) {
20519
+ const isObject4 = Object.prototype.toString.call(value).slice(8, -1) === "Object";
20520
+ const isObjLike = value !== null && isObject4;
20521
+ if (!isObjLike || !isObject4) {
20522
+ return false;
20523
+ }
20524
+ const proto2 = Object.getPrototypeOf(value);
20525
+ const hasObjectConstructor = typeof proto2 === "object" && proto2.constructor === Object.prototype.constructor;
20526
+ return hasObjectConstructor;
20527
+ }
20528
+ function isPrimitive(value) {
20529
+ return ["string", "number", "boolean"].some((t) => typeof value === t);
20530
+ }
20531
+ function isZeroValuePrimitive(value) {
20532
+ return value === false || value === 0 || value === "";
20533
+ }
20534
+ function flattenRequestPayload(requestPayload, path13 = "") {
20535
+ return Object.keys(requestPayload).reduce((acc, key) => {
20536
+ const value = requestPayload[key];
20537
+ const newPath = path13 ? [path13, key].join(".") : key;
20538
+ const isNonEmptyPrimitiveArray = Array.isArray(value) && value.every((v) => isPrimitive(v)) && value.length > 0;
20539
+ const isNonZeroValuePrimitive = isPrimitive(value) && !isZeroValuePrimitive(value);
20540
+ let objectToMerge = {};
20541
+ if (isPlainObject(value)) {
20542
+ objectToMerge = flattenRequestPayload(value, newPath);
20543
+ } else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
20544
+ objectToMerge = { [newPath]: value };
20545
+ }
20546
+ return { ...acc, ...objectToMerge };
20547
+ }, {});
20548
+ }
20549
+ function renderURLSearchParams(requestPayload, urlPathParams = []) {
20550
+ const flattenedRequestPayload = flattenRequestPayload(requestPayload);
20551
+ const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
20552
+ (acc, key) => {
20553
+ const value = flattenedRequestPayload[key];
20554
+ if (urlPathParams.find((f) => f === key)) {
20555
+ return acc;
20556
+ }
20557
+ return Array.isArray(value) ? [...acc, ...value.map((m) => [key, m.toString()])] : acc = [...acc, [key, value.toString()]];
20558
+ },
20559
+ []
20560
+ );
20561
+ return new URLSearchParams(urlSearchParams).toString();
20562
+ }
20563
+ var b64, s64;
20564
+ var init_fetch_pb = __esm({
20565
+ "proto/generated/portal/fetch.pb.ts"() {
20566
+ "use strict";
20567
+ b64 = new Array(64);
20568
+ s64 = new Array(123);
20569
+ for (let i2 = 0; i2 < 64; )
20570
+ s64[b64[i2] = i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 - 59 | 43] = i2++;
20571
+ }
20572
+ });
20573
+
20574
+ // proto/generated/portal/ai/inworld/studio/v1alpha/tokens.pb.ts
20575
+ var Tokens;
20576
+ var init_tokens_pb = __esm({
20577
+ "proto/generated/portal/ai/inworld/studio/v1alpha/tokens.pb.ts"() {
20578
+ "use strict";
20579
+ init_fetch_pb();
20580
+ Tokens = class {
20581
+ static GenerateSessionToken(req, initReq) {
20582
+ return fetchReq(
20583
+ `/v1alpha/tokens/sessionToken:generate`,
20584
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
20585
+ );
20586
+ }
20587
+ static GenerateDefaultSessionToken(req, initReq) {
20588
+ return fetchReq(
20589
+ `/v1alpha/${req["parent"]}/token:generate`,
20590
+ { ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
20591
+ );
20592
+ }
20593
+ };
20594
+ }
20595
+ });
20596
+
20597
+ // src/auth/runtime_credential.ts
20598
+ async function resolveRuntimeCredential(session) {
20599
+ const apiKey = apiKeyFromEnvironment();
20600
+ if (apiKey) return { scheme: "Basic", token: apiKey };
20601
+ return resolveSessionCredential(session);
20602
+ }
20603
+ function accountOf(platformToken) {
20604
+ try {
20605
+ const payload = platformToken?.split(".")[1] ?? "";
20606
+ const subject = JSON.parse(
20607
+ Buffer.from(payload, "base64url").toString("utf8")
20608
+ ).sub;
20609
+ return typeof subject === "string" && subject ? subject : null;
20610
+ } catch {
20611
+ return null;
20612
+ }
20613
+ }
20614
+ function apiKeyFromEnvironment() {
20615
+ return process.env.INWORLD_API_KEY?.trim() || void 0;
20616
+ }
20617
+ async function resolveSessionCredential(session) {
20618
+ return { scheme: "Bearer", token: await sessionToken(session) };
20619
+ }
20620
+ async function forgetSessionToken() {
20621
+ await clearStoredRuntimeToken().catch(() => {
20622
+ });
20623
+ }
20624
+ async function fetchWithRuntimeCredential(session, url, init = {}) {
20625
+ const send = (credential2) => fetch(url, {
20626
+ ...init,
20627
+ headers: {
20628
+ ...plainHeaders(init.headers),
20629
+ Authorization: `${credential2.scheme} ${credential2.token}`
20630
+ }
20631
+ });
20632
+ const credential = await resolveRuntimeCredential(session);
20633
+ const response = await send(credential);
20634
+ if (response.status !== 401 || credential.scheme !== "Bearer") {
20635
+ return response;
20636
+ }
20637
+ await forgetSessionToken();
20638
+ return send(await resolveRuntimeCredential(session));
20639
+ }
20640
+ function plainHeaders(headers) {
20641
+ if (!headers) return {};
20642
+ if (headers instanceof Headers) return Object.fromEntries(headers.entries());
20643
+ if (Array.isArray(headers)) return Object.fromEntries(headers);
20644
+ return headers;
20645
+ }
20646
+ async function sessionToken(session) {
20647
+ for (let reading = 1; reading <= 2; reading++) {
20648
+ const current = await session.current();
20649
+ if (!current) throw new RuntimeCredentialError(SIGNED_OUT);
20650
+ const workspace = current.workspace?.replace(/^workspaces\//, "");
20651
+ if (!workspace) throw new RuntimeCredentialError(NO_WORKSPACE);
20652
+ const owner = {
20653
+ user: current.user ?? "",
20654
+ deployment: current.deployment,
20655
+ workspace,
20656
+ platformUrl: PLATFORM_URL
20657
+ };
20658
+ if (current.user !== null) {
20659
+ const stored = await readStoredRuntimeToken();
20660
+ if (stored && isUsable(stored, owner)) return stored.token;
20661
+ }
20662
+ const auth = await session.platformAuth();
20663
+ if (!auth) throw new RuntimeCredentialError(SIGNED_OUT);
20664
+ const accountsKnown = current.user !== null && auth.user !== null;
20665
+ const sameSignIn = accountsKnown && auth.user === current.user && auth.deployment === current.deployment;
20666
+ if (accountsKnown && !sameSignIn) continue;
20667
+ const minted = await mint(owner, auth.headers);
20668
+ if (sameSignIn && isUsable(minted, owner)) {
20669
+ await writeStoredRuntimeToken(minted).catch(() => {
20670
+ });
20671
+ }
20672
+ return minted.token;
20673
+ }
20674
+ throw new RuntimeCredentialError(SIGN_IN_CHANGED);
20675
+ }
20676
+ function isUsable(token, owner) {
20677
+ return token.user === owner.user && token.deployment === owner.deployment && token.workspace === owner.workspace && token.platformUrl === owner.platformUrl && token.expiresAt - Date.now() > RENEW_MARGIN_MS;
20678
+ }
20679
+ async function mint(owner, userHeaders) {
20680
+ const refused = (reason) => new RuntimeCredentialError(
20681
+ `Could not get a session token for workspace ${owner.workspace}: ${reason}. Run \`inworld login\` if the sign-in has expired, or set INWORLD_API_KEY to use an API key.`
20682
+ );
20683
+ let response;
20684
+ try {
20685
+ response = await Tokens.GenerateDefaultSessionToken(
20686
+ { parent: `workspaces/${owner.workspace}` },
20687
+ {
20688
+ headers: { ...userHeaders, [CLIENT_INFO_HEADER]: CLIENT_INFO },
20689
+ pathPrefix: owner.platformUrl
20690
+ }
20691
+ );
20692
+ } catch (cause) {
20693
+ const message = cause?.message;
20694
+ throw refused(typeof message === "string" ? message : "request failed");
20695
+ }
20696
+ if (!response?.token) throw refused("the response carried no token");
20697
+ const expiresAt = Date.parse(String(response.expirationTime));
20698
+ return {
20699
+ ...owner,
20700
+ token: response.token,
20701
+ expiresAt: Number.isNaN(expiresAt) ? 0 : expiresAt
20702
+ };
20703
+ }
20704
+ var RuntimeCredentialError, RENEW_MARGIN_MS, SIGNED_OUT, NO_WORKSPACE, SIGN_IN_CHANGED;
20705
+ var init_runtime_credential = __esm({
20706
+ "src/auth/runtime_credential.ts"() {
20707
+ "use strict";
20708
+ init_dist4();
20709
+ init_constants5();
20710
+ init_client_info();
20711
+ init_tokens_pb();
20712
+ RuntimeCredentialError = class extends Error {
20713
+ };
20714
+ RENEW_MARGIN_MS = 2 * 60 * 1e3;
20715
+ SIGNED_OUT = "Not signed in. Run `inworld login`, or set INWORLD_API_KEY to use an API key.";
20716
+ NO_WORKSPACE = "No workspace selected. Run `inworld workspace select`, or set INWORLD_API_KEY to use an API key.";
20717
+ SIGN_IN_CHANGED = "The sign-in changed while this command was starting. Run it again.";
20718
+ }
20719
+ });
20720
+
20269
20721
  // src/services/tts_models.ts
20270
20722
  var LEGACY_MODELS, DEFAULT_TTS_MODEL, TTS_MODEL_HELP;
20271
20723
  var init_tts_models = __esm({
@@ -20590,7 +21042,7 @@ var require_utils2 = __commonJS({
20590
21042
  module.exports = Utils;
20591
21043
  Utils.prototype.makeDir = function(folder) {
20592
21044
  const self = this;
20593
- function mkdirSync(fpath) {
21045
+ function mkdirSync2(fpath) {
20594
21046
  let resolvedPath = fpath.split(self.sep)[0];
20595
21047
  fpath.split(self.sep).forEach(function(name) {
20596
21048
  if (!name || name.substr(-1, 1) === ":") return;
@@ -20608,7 +21060,7 @@ var require_utils2 = __commonJS({
20608
21060
  if (stat2 && stat2.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
20609
21061
  });
20610
21062
  }
20611
- mkdirSync(folder);
21063
+ mkdirSync2(folder);
20612
21064
  };
20613
21065
  Utils.prototype.writeFileTo = function(path13, content, overwrite, attr) {
20614
21066
  const self = this;
@@ -22215,8 +22667,8 @@ var require_adm_zip = __commonJS({
22215
22667
  return null;
22216
22668
  }
22217
22669
  function fixPath(zipPath) {
22218
- const { join: join5, normalize, sep } = pth.posix;
22219
- return join5(pth.isAbsolute(zipPath) ? "/" : ".", normalize(sep + zipPath.split("\\").join(sep) + sep));
22670
+ const { join: join6, normalize, sep } = pth.posix;
22671
+ return join6(pth.isAbsolute(zipPath) ? "/" : ".", normalize(sep + zipPath.split("\\").join(sep) + sep));
22220
22672
  }
22221
22673
  function filenameFilter(filterfn) {
22222
22674
  if (filterfn instanceof RegExp) {
@@ -43617,10 +44069,10 @@ var require_view = __commonJS({
43617
44069
  var debug = require_src()("express:view");
43618
44070
  var path13 = __require("node:path");
43619
44071
  var fs6 = __require("node:fs");
43620
- var dirname2 = path13.dirname;
44072
+ var dirname3 = path13.dirname;
43621
44073
  var basename2 = path13.basename;
43622
44074
  var extname2 = path13.extname;
43623
- var join5 = path13.join;
44075
+ var join6 = path13.join;
43624
44076
  var resolve5 = path13.resolve;
43625
44077
  module.exports = View;
43626
44078
  function View(name, options) {
@@ -43656,7 +44108,7 @@ var require_view = __commonJS({
43656
44108
  for (var i2 = 0; i2 < roots.length && !path14; i2++) {
43657
44109
  var root = roots[i2];
43658
44110
  var loc = resolve5(root, name);
43659
- var dir = dirname2(loc);
44111
+ var dir = dirname3(loc);
43660
44112
  var file = basename2(loc);
43661
44113
  path14 = this.resolve(dir, file);
43662
44114
  }
@@ -43682,12 +44134,12 @@ var require_view = __commonJS({
43682
44134
  };
43683
44135
  View.prototype.resolve = function resolve6(dir, file) {
43684
44136
  var ext = this.ext;
43685
- var path14 = join5(dir, file);
44137
+ var path14 = join6(dir, file);
43686
44138
  var stat2 = tryStat(path14);
43687
44139
  if (stat2 && stat2.isFile()) {
43688
44140
  return path14;
43689
44141
  }
43690
- path14 = join5(dir, basename2(file, ext), "index" + ext);
44142
+ path14 = join6(dir, basename2(file, ext), "index" + ext);
43691
44143
  stat2 = tryStat(path14);
43692
44144
  if (stat2 && stat2.isFile()) {
43693
44145
  return path14;
@@ -47392,7 +47844,7 @@ var require_send = __commonJS({
47392
47844
  var Stream = __require("stream");
47393
47845
  var util2 = __require("util");
47394
47846
  var extname2 = path13.extname;
47395
- var join5 = path13.join;
47847
+ var join6 = path13.join;
47396
47848
  var normalize = path13.normalize;
47397
47849
  var resolve5 = path13.resolve;
47398
47850
  var sep = path13.sep;
@@ -47564,7 +48016,7 @@ var require_send = __commonJS({
47564
48016
  return res;
47565
48017
  }
47566
48018
  parts = path14.split(sep);
47567
- path14 = normalize(join5(root, path14));
48019
+ path14 = normalize(join6(root, path14));
47568
48020
  } else {
47569
48021
  if (UP_PATH_REGEXP.test(path14)) {
47570
48022
  debug('malicious path "%s"', path14);
@@ -47697,7 +48149,7 @@ var require_send = __commonJS({
47697
48149
  if (err) return self.onStatError(err);
47698
48150
  return self.error(404);
47699
48151
  }
47700
- var p = join5(path14, self._index[i2]);
48152
+ var p = join6(path14, self._index[i2]);
47701
48153
  debug('stat "%s"', p);
47702
48154
  fs6.stat(p, function(err2, stat2) {
47703
48155
  if (err2) return next(err2);
@@ -70665,11 +71117,12 @@ async function currentRefreshToken(s, source) {
70665
71117
  const c3 = await readStoredCredentials();
70666
71118
  const stored = c3 ? identitySourceOfStore(c3) : null;
70667
71119
  if (c3?.refreshToken && stored?.authUrl === source.authUrl) {
70668
- return c3.refreshToken.trim();
71120
+ return { token: c3.refreshToken.trim(), email: c3.email };
70669
71121
  }
70670
71122
  } catch {
70671
71123
  }
70672
- return s.identityRefreshToken?.trim();
71124
+ const own = s.identityRefreshToken?.trim();
71125
+ return own ? { token: own, email: s.email } : void 0;
70673
71126
  }
70674
71127
  async function getValidSession() {
70675
71128
  const fromReq = getRequestSession();
@@ -70693,8 +71146,8 @@ async function getValidSession() {
70693
71146
  return isSessionActive(s) ? s : null;
70694
71147
  }
70695
71148
  try {
70696
- const rt = await refreshIdentityToken(source, refresh);
70697
- if (!await persistRotatedRefreshToken(refresh, rt.refreshToken)) {
71149
+ const rt = await refreshIdentityToken(source, refresh.token);
71150
+ if (!await persistRotatedRefreshToken(refresh.token, rt.refreshToken)) {
70698
71151
  return null;
70699
71152
  }
70700
71153
  const exchanged = await exchangeIdentityToken(rt.idToken);
@@ -70704,7 +71157,9 @@ async function getValidSession() {
70704
71157
  identityRefreshToken: rt.refreshToken,
70705
71158
  authProvider: "supabase",
70706
71159
  authUrl: source.authUrl,
70707
- email: s.email
71160
+ // Whose the redeemed refresh token was, which is not always the user of
71161
+ // the session being replaced.
71162
+ email: refresh.email || rt.email
70708
71163
  };
70709
71164
  if (!await saveSessionUnlessLoggedOut(merged)) return null;
70710
71165
  const next = loadSession();
@@ -70963,24 +71418,73 @@ var init_studio_config = __esm({
70963
71418
  }
70964
71419
  });
70965
71420
 
70966
- // src/mcp/inworld/studio-api.ts
70967
- async function readApiKey() {
70968
- const fromEnv = process.env.INWORLD_API_KEY?.trim();
70969
- if (fromEnv) return fromEnv;
70970
- try {
70971
- const creds = await readStoredCredentials();
70972
- return creds?.apiKey?.trim() || void 0;
70973
- } catch {
70974
- return void 0;
70975
- }
71421
+ // src/mcp/runtime/credential.ts
71422
+ function runtimeApiFetch(url, init) {
71423
+ return fetchWithRuntimeCredential(mcpSession, url, init);
70976
71424
  }
70977
- async function requireApiKey2() {
70978
- const key = await readApiKey();
70979
- if (key) return key;
70980
- throw new Error(
70981
- "No Inworld API key available. Set INWORLD_API_KEY in the environment, or run `inworld workspace select-key` from a terminal to bind one to the local credential store (shared with this MCP server)."
70982
- );
71425
+ async function hasRuntimeCredential() {
71426
+ if (process.env.INWORLD_API_KEY?.trim()) return true;
71427
+ const current = await mcpSession.current().catch(() => null);
71428
+ return Boolean(current?.workspace);
70983
71429
  }
71430
+ var PER_REQUEST_SIGN_IN, DIFFERENT_DEPLOYMENTS, mcpSession;
71431
+ var init_credential = __esm({
71432
+ "src/mcp/runtime/credential.ts"() {
71433
+ "use strict";
71434
+ init_dist4();
71435
+ init_runtime_credential();
71436
+ init_cli_store_bridge();
71437
+ init_identity();
71438
+ init_inworld_headers();
71439
+ init_request_session();
71440
+ init_session();
71441
+ init_session_refresh();
71442
+ PER_REQUEST_SIGN_IN = "This server signs in each request separately, and such a sign-in has no workspace for runtime tools. Set INWORLD_API_KEY on the server.";
71443
+ DIFFERENT_DEPLOYMENTS = "The MCP session and the CLI sign-in belong to different Inworld deployments, so runtime tools have no workspace to run in. Sign in to one deployment with `inworld login`, or set INWORLD_API_KEY.";
71444
+ mcpSession = {
71445
+ async current() {
71446
+ if (getRequestSession()) {
71447
+ throw new RuntimeCredentialError(PER_REQUEST_SIGN_IN);
71448
+ }
71449
+ const stored = await readStoredCredentials().catch(() => null);
71450
+ const signIn2 = stored ? identitySourceOfStore(stored) : null;
71451
+ if (!stored?.refreshToken?.trim() || !signIn2) return null;
71452
+ return {
71453
+ user: accountOf(stored.inworldToken),
71454
+ deployment: signIn2.authUrl,
71455
+ workspace: stored.workspace ?? null
71456
+ };
71457
+ },
71458
+ async platformAuth() {
71459
+ const stored = await readStoredCredentials().catch(() => null);
71460
+ const signIn2 = stored ? identitySourceOfStore(stored) : null;
71461
+ if (!stored || !signIn2) return null;
71462
+ const onDisk = loadSession();
71463
+ if (onDisk && identitySourceOfStore(onDisk)?.authUrl !== signIn2.authUrl) {
71464
+ throw new RuntimeCredentialError(DIFFERENT_DEPLOYMENTS);
71465
+ }
71466
+ let session = await getValidSession();
71467
+ if (!session) return null;
71468
+ if (identitySourceOfStore(session)?.authUrl !== signIn2.authUrl) {
71469
+ throw new RuntimeCredentialError(DIFFERENT_DEPLOYMENTS);
71470
+ }
71471
+ const signedInAccount = accountOf(stored.inworldToken);
71472
+ const sessionAccount = accountOf(session.token);
71473
+ if (signedInAccount !== null && sessionAccount !== null && sessionAccount !== signedInAccount) {
71474
+ session = await hydrateMcpSessionFromCliStore();
71475
+ if (!session) return null;
71476
+ }
71477
+ return {
71478
+ user: accountOf(session.token),
71479
+ deployment: signIn2.authUrl,
71480
+ headers: headersForInworldSession(session)
71481
+ };
71482
+ }
71483
+ };
71484
+ }
71485
+ });
71486
+
71487
+ // src/mcp/inworld/studio-api.ts
70984
71488
  function studioBase() {
70985
71489
  return getStudioApiUrl().replace(/\/$/, "");
70986
71490
  }
@@ -71006,13 +71510,11 @@ function extractMessage(data, fallbackStatus) {
71006
71510
  return `HTTP ${fallbackStatus}`;
71007
71511
  }
71008
71512
  async function studioApiGet(pathAndQuery, label = "Studio API") {
71009
- const apiKey = await requireApiKey2();
71010
71513
  const path13 = pathAndQuery.startsWith("/") ? pathAndQuery : `/${pathAndQuery}`;
71011
- const res = await fetch(`${studioBase()}${path13}`, {
71514
+ const res = await runtimeApiFetch(`${studioBase()}${path13}`, {
71012
71515
  method: "GET",
71013
71516
  headers: {
71014
71517
  [CLIENT_INFO_HEADER]: CLIENT_INFO,
71015
- Authorization: `Basic ${apiKey}`,
71016
71518
  Accept: "application/json"
71017
71519
  }
71018
71520
  });
@@ -71024,13 +71526,11 @@ async function studioApiGet(pathAndQuery, label = "Studio API") {
71024
71526
  return data;
71025
71527
  }
71026
71528
  async function studioApiPostJson(path13, body, label = "Studio API") {
71027
- const apiKey = await requireApiKey2();
71028
71529
  const p = path13.startsWith("/") ? path13 : `/${path13}`;
71029
- const res = await fetch(`${studioBase()}${p}`, {
71530
+ const res = await runtimeApiFetch(`${studioBase()}${p}`, {
71030
71531
  method: "POST",
71031
71532
  headers: {
71032
71533
  [CLIENT_INFO_HEADER]: CLIENT_INFO,
71033
- Authorization: `Basic ${apiKey}`,
71034
71534
  "Content-Type": "application/json",
71035
71535
  Accept: "application/json"
71036
71536
  },
@@ -71046,9 +71546,9 @@ async function studioApiPostJson(path13, body, label = "Studio API") {
71046
71546
  var init_studio_api = __esm({
71047
71547
  "src/mcp/inworld/studio-api.ts"() {
71048
71548
  "use strict";
71049
- init_dist4();
71050
71549
  init_client_info();
71051
71550
  init_studio_config();
71551
+ init_credential();
71052
71552
  }
71053
71553
  });
71054
71554
 
@@ -71408,17 +71908,12 @@ function runtimeSearchBase() {
71408
71908
  if (override) return override.replace(/\/+$/, "");
71409
71909
  return `${runtimeApiBase()}/api/v1/inworld-assistant`;
71410
71910
  }
71411
- async function hasApiKeyCredential() {
71412
- return Boolean(await readApiKey());
71413
- }
71414
- async function runtimeFetch(path13, options = {}) {
71415
- const apiKey = await requireApiKey2();
71911
+ async function runtimeFetch2(path13, options = {}) {
71416
71912
  const url = `${runtimeApiBase()}${path13}`;
71417
- const res = await fetch(url, {
71913
+ const res = await runtimeApiFetch(url, {
71418
71914
  ...options,
71419
71915
  headers: {
71420
71916
  [CLIENT_INFO_HEADER]: CLIENT_INFO,
71421
- Authorization: `Basic ${apiKey}`,
71422
71917
  "Content-Type": "application/json",
71423
71918
  ...options.headers
71424
71919
  }
@@ -71439,13 +71934,13 @@ var init_api2 = __esm({
71439
71934
  "use strict";
71440
71935
  init_client_info();
71441
71936
  init_studio_config();
71442
- init_studio_api();
71937
+ init_credential();
71443
71938
  }
71444
71939
  });
71445
71940
 
71446
71941
  // src/mcp/runtime/register.ts
71447
71942
  import { mkdir as mkdir2, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
71448
- import { dirname, resolve as resolve2 } from "node:path";
71943
+ import { dirname as dirname2, resolve as resolve2 } from "node:path";
71449
71944
  function extensionForEncoding(encoding) {
71450
71945
  const map = {
71451
71946
  MP3: ".mp3",
@@ -71496,7 +71991,7 @@ function registerRuntimeTools(server) {
71496
71991
  async ({ language, tags, description_match, custom_only }) => {
71497
71992
  try {
71498
71993
  const filter = language ? `?filter=language=${encodeURIComponent(language)}` : "";
71499
- const data = await runtimeFetch(
71994
+ const data = await runtimeFetch2(
71500
71995
  `/tts/v1/voices${filter}`
71501
71996
  );
71502
71997
  let voices = data.voices.map((v) => ({
@@ -71590,7 +72085,7 @@ function registerRuntimeTools(server) {
71590
72085
  if (delivery_mode && model_id === "inworld-tts-2") {
71591
72086
  body.deliveryMode = delivery_mode;
71592
72087
  }
71593
- const data = await runtimeFetch("/tts/v1/voice", {
72088
+ const data = await runtimeFetch2("/tts/v1/voice", {
71594
72089
  method: "POST",
71595
72090
  body: JSON.stringify(body)
71596
72091
  });
@@ -71599,7 +72094,7 @@ function registerRuntimeTools(server) {
71599
72094
  filePath += extensionForEncoding(audio_encoding);
71600
72095
  }
71601
72096
  const audioBuffer = Buffer.from(data.audioContent, "base64");
71602
- await mkdir2(dirname(filePath), { recursive: true });
72097
+ await mkdir2(dirname2(filePath), { recursive: true });
71603
72098
  await writeFile4(filePath, audioBuffer);
71604
72099
  const result = {
71605
72100
  file: filePath,
@@ -71681,7 +72176,7 @@ function registerRuntimeTools(server) {
71681
72176
  content: audioBase64
71682
72177
  }
71683
72178
  };
71684
- const data = await runtimeFetch(
72179
+ const data = await runtimeFetch2(
71685
72180
  "/stt/v1/transcribe",
71686
72181
  { method: "POST", body: JSON.stringify(body) }
71687
72182
  );
@@ -71774,7 +72269,7 @@ function registerRuntimeTools(server) {
71774
72269
  if (remove_background_noise) {
71775
72270
  body.audioProcessingConfig = { removeBackgroundNoise: true };
71776
72271
  }
71777
- const data = await runtimeFetch(
72272
+ const data = await runtimeFetch2(
71778
72273
  "/voices/v1/voices:clone",
71779
72274
  { method: "POST", body: JSON.stringify(body) }
71780
72275
  );
@@ -71825,7 +72320,7 @@ function registerRuntimeTools(server) {
71825
72320
  preview_output_dir
71826
72321
  }) => {
71827
72322
  try {
71828
- const data = await runtimeFetch(
72323
+ const data = await runtimeFetch2(
71829
72324
  "/voices/v1/voices:design",
71830
72325
  {
71831
72326
  method: "POST",
@@ -71880,7 +72375,7 @@ function registerRuntimeTools(server) {
71880
72375
  if (display_name) body.displayName = display_name;
71881
72376
  if (description) body.description = description;
71882
72377
  if (tags && tags.length > 0) body.tags = tags;
71883
- const data = await runtimeFetch(`/voices/v1/voices/${encodeURIComponent(voice_id)}:publish`, {
72378
+ const data = await runtimeFetch2(`/voices/v1/voices/${encodeURIComponent(voice_id)}:publish`, {
71884
72379
  method: "POST",
71885
72380
  body: JSON.stringify(body)
71886
72381
  });
@@ -71915,7 +72410,7 @@ function registerRuntimeTools(server) {
71915
72410
  const body = { model, messages };
71916
72411
  if (temperature !== void 0) body.temperature = temperature;
71917
72412
  if (max_tokens !== void 0) body.max_tokens = max_tokens;
71918
- const data = await runtimeFetch(
72413
+ const data = await runtimeFetch2(
71919
72414
  "/v1/chat/completions",
71920
72415
  { method: "POST", body: JSON.stringify(body) }
71921
72416
  );
@@ -71967,7 +72462,7 @@ function registerRuntimeTools(server) {
71967
72462
  };
71968
72463
  if (temperature !== void 0) body.temperature = temperature;
71969
72464
  if (max_tokens !== void 0) body.max_tokens = max_tokens;
71970
- const data = await runtimeFetch(
72465
+ const data = await runtimeFetch2(
71971
72466
  "/v1/chat/completions",
71972
72467
  { method: "POST", body: JSON.stringify(body) }
71973
72468
  );
@@ -71978,7 +72473,7 @@ function registerRuntimeTools(server) {
71978
72473
  );
71979
72474
  }
71980
72475
  const filePath = resolve2(output_file);
71981
- await mkdir2(dirname(filePath), { recursive: true });
72476
+ await mkdir2(dirname2(filePath), { recursive: true });
71982
72477
  await writeFile4(filePath, Buffer.from(audio.data, "base64"));
71983
72478
  return textResult({
71984
72479
  file: filePath,
@@ -72000,7 +72495,7 @@ function registerRuntimeTools(server) {
72000
72495
  },
72001
72496
  async () => {
72002
72497
  try {
72003
- const data = await runtimeFetch("/router/v1/routers");
72498
+ const data = await runtimeFetch2("/router/v1/routers");
72004
72499
  const routers = (data.routers ?? []).map((r) => ({
72005
72500
  name: r.name,
72006
72501
  displayName: r.displayName,
@@ -72036,7 +72531,7 @@ function registerSearchDocsTool(server) {
72036
72531
  params.set("indexes", indexes.join(","));
72037
72532
  if (top_k !== void 0) params.set("topK", String(top_k));
72038
72533
  const url = `${runtimeSearchBase()}/search?${params.toString()}`;
72039
- const apiKey = await readApiKey();
72534
+ const apiKey = process.env.INWORLD_API_KEY?.trim();
72040
72535
  const res = await fetch(url, {
72041
72536
  headers: {
72042
72537
  [CLIENT_INFO_HEADER]: CLIENT_INFO,
@@ -72050,7 +72545,7 @@ function registerSearchDocsTool(server) {
72050
72545
  }
72051
72546
  if (res.status === 401 || res.status === 403) {
72052
72547
  throw new Error(
72053
- apiKey ? "Inworld search rejected the API key. Check INWORLD_API_KEY, or re-bind one with `inworld workspace select-key`." : "Inworld search requires an API key. Set INWORLD_API_KEY in the environment, or run `inworld workspace select-key` from a terminal."
72548
+ apiKey ? "Inworld search rejected the API key. Check INWORLD_API_KEY." : "Inworld search requires an API key. Set INWORLD_API_KEY in the environment."
72054
72549
  );
72055
72550
  }
72056
72551
  if (!res.ok) {
@@ -72081,7 +72576,6 @@ var init_register = __esm({
72081
72576
  "use strict";
72082
72577
  init_zod();
72083
72578
  init_client_info();
72084
- init_studio_api();
72085
72579
  init_api2();
72086
72580
  VALID_ENCODINGS = [
72087
72581
  "MP3",
@@ -72480,6 +72974,7 @@ async function runLogin() {
72480
72974
  authProvider: "supabase",
72481
72975
  authUrl: source.authUrl
72482
72976
  });
72977
+ await clearStoredRuntimeToken();
72483
72978
  console.error();
72484
72979
  console.error("Signed in.");
72485
72980
  console.error(`Email: ${tokens.email}`);
@@ -72521,13 +73016,19 @@ async function hasSessionCapableCredentials() {
72521
73016
  return false;
72522
73017
  }
72523
73018
  }
72524
- async function detectToolModes() {
73019
+ async function detectToolModes(options = {}) {
72525
73020
  if (process.env.INWORLD_MCP_TOOLSET === "runtime") {
72526
73021
  return { runtime: true, session: false, runtimeOnly: true };
72527
73022
  }
72528
73023
  if (skipAuth()) return { runtime: true, session: true };
73024
+ if (options.perRequestSignIn) {
73025
+ return {
73026
+ runtime: Boolean(process.env.INWORLD_API_KEY?.trim()),
73027
+ session: true
73028
+ };
73029
+ }
72529
73030
  const [runtime, session] = await Promise.all([
72530
- hasApiKeyCredential(),
73031
+ hasRuntimeCredential(),
72531
73032
  hasSessionCapableCredentials()
72532
73033
  ]);
72533
73034
  return { runtime, session };
@@ -72788,7 +73289,7 @@ function createMcpServer(modes) {
72788
73289
  server.registerTool(
72789
73290
  "inworld_tts_voice_preview",
72790
73291
  {
72791
- description: "Fetch a short, server-side audio preview for an existing voice (GET /tts/v1/voice:preview). Not metered or billed \u2014 ideal for catalog browsing. Returns base64 MP3 audio. Uses the workspace API key (Basic auth); requires inworld auth login + inworld workspace select-key or INWORLD_API_KEY.",
73292
+ description: "Fetch a short, server-side audio preview for an existing voice (GET /tts/v1/voice:preview). Not metered or billed \u2014 ideal for catalog browsing. Returns base64 MP3 audio. Authenticates with INWORLD_API_KEY, or as the signed-in user.",
72792
73293
  inputSchema: external_exports.object({
72793
73294
  voiceId: external_exports.string().min(1).describe(
72794
73295
  "Voice ID (e.g. Ashley, Dennis). See inworld_voice_catalog_list."
@@ -72814,7 +73315,7 @@ function createMcpServer(modes) {
72814
73315
  server.registerTool(
72815
73316
  "inworld_voice_get",
72816
73317
  {
72817
- description: "Get a single voice's metadata by ID (GET /voices/v1/voices/{voiceId}). Read-only. Uses the workspace API key (Basic auth).",
73318
+ description: "Get a single voice's metadata by ID (GET /voices/v1/voices/{voiceId}). Read-only. Authenticates with INWORLD_API_KEY, or as the signed-in user.",
72818
73319
  inputSchema: external_exports.object({
72819
73320
  voiceId: external_exports.string().min(1).describe("Voice ID (e.g. Dennis or workspace_id__voice_name).")
72820
73321
  })
@@ -72837,7 +73338,7 @@ function createMcpServer(modes) {
72837
73338
  server.registerTool(
72838
73339
  "inworld_stt_transcribe",
72839
73340
  {
72840
- description: "Transcribe an audio clip via the Inworld Speech-to-Text API (POST /stt/v1/transcribe). The whole audio must fit in one request; for long files, chunk client-side. Pass base64-encoded audio bytes (no `data:` prefix). Uses the workspace API key (Basic auth).",
73341
+ description: "Transcribe an audio clip via the Inworld Speech-to-Text API (POST /stt/v1/transcribe). The whole audio must fit in one request; for long files, chunk client-side. Pass base64-encoded audio bytes (no `data:` prefix). Authenticates with INWORLD_API_KEY, or as the signed-in user.",
72841
73342
  inputSchema: external_exports.object({
72842
73343
  audioBase64: external_exports.string().min(1).describe("Base64-encoded audio bytes (raw \u2014 no data: prefix)."),
72843
73344
  language: external_exports.string().optional().describe("BCP-47 language code, e.g. en-US"),
@@ -72865,7 +73366,7 @@ function createMcpServer(modes) {
72865
73366
  server.registerTool(
72866
73367
  "inworld_llm_chat",
72867
73368
  {
72868
- description: "Generate a chat completion via the Inworld LLM Router (POST /llm/v1alpha/completions:completeChat). Non-streaming. Pass model id + service provider + a list of role/content messages. Uses the workspace API key (Basic auth).",
73369
+ description: "Generate a chat completion via the Inworld LLM Router (POST /llm/v1alpha/completions:completeChat). Non-streaming. Pass model id + service provider + a list of role/content messages. Authenticates with INWORLD_API_KEY, or as the signed-in user.",
72869
73370
  inputSchema: external_exports.object({
72870
73371
  model: external_exports.string().min(1).describe("Model id (e.g. gpt-4o-mini, gemini-2.5-flash)"),
72871
73372
  serviceProvider: external_exports.string().optional().describe(
@@ -72906,7 +73407,7 @@ function createMcpServer(modes) {
72906
73407
  server.registerTool(
72907
73408
  "inworld_llm_list_models",
72908
73409
  {
72909
- description: "List LLM models available to your account, with capabilities and pricing (GET /llm/v1alpha/models). Read-only. Uses the workspace API key (Basic auth).",
73410
+ description: "List LLM models available to your account, with capabilities and pricing (GET /llm/v1alpha/models). Read-only. Authenticates with INWORLD_API_KEY, or as the signed-in user.",
72910
73411
  inputSchema: external_exports.object({})
72911
73412
  },
72912
73413
  async () => {
@@ -73395,8 +73896,9 @@ async function runStdio() {
73395
73896
  async function runHttp() {
73396
73897
  const port = Number(process.env.PORT) || 3333;
73397
73898
  const host = process.env.HOST ?? "127.0.0.1";
73398
- const detected = await detectToolModes();
73399
- const modes = getMcpHttpAuthMode() === "bearer" ? { ...detected, session: true } : detected;
73899
+ const modes = await detectToolModes({
73900
+ perRequestSignIn: getMcpHttpAuthMode() === "bearer"
73901
+ });
73400
73902
  const app = createMcpExpressApp({ host });
73401
73903
  const handleMcpRequest = async (req, res) => {
73402
73904
  const server = createMcpServer(modes);
@@ -73522,7 +74024,7 @@ var init_mcp2 = __esm({
73522
74024
  init_chat();
73523
74025
  init_models();
73524
74026
  init_gateway2();
73525
- init_api2();
74027
+ init_credential();
73526
74028
  init_register();
73527
74029
  init_transcribe();
73528
74030
  init_preview();
@@ -74414,7 +74916,7 @@ var {
74414
74916
  // src/commands/audiobook/audiobook_generate_command.ts
74415
74917
  import { mkdir, readFile as readFile3, rename as rename2, rm } from "fs/promises";
74416
74918
  import { tmpdir as tmpdir2 } from "os";
74417
- import { join as join3, resolve } from "path";
74919
+ import { join as join4, resolve } from "path";
74418
74920
 
74419
74921
  // src/auth/manager.ts
74420
74922
  init_dist4();
@@ -74495,115 +74997,8 @@ function workspaceLink(workspaceId) {
74495
74997
  return link(`${PLATFORM_URL}/v2/workspaces/${workspaceId}`);
74496
74998
  }
74497
74999
 
74498
- // proto/generated/portal/fetch.pb.ts
74499
- var b64 = new Array(64);
74500
- var s64 = new Array(123);
74501
- for (let i2 = 0; i2 < 64; )
74502
- s64[b64[i2] = i2 < 26 ? i2 + 65 : i2 < 52 ? i2 + 71 : i2 < 62 ? i2 - 4 : i2 - 59 | 43] = i2++;
74503
- function b64Encode(buffer, start, end) {
74504
- let parts = null;
74505
- const chunk = [];
74506
- let i2 = 0, j = 0, t;
74507
- while (start < end) {
74508
- const b = buffer[start++];
74509
- switch (j) {
74510
- case 0:
74511
- chunk[i2++] = b64[b >> 2];
74512
- t = (b & 3) << 4;
74513
- j = 1;
74514
- break;
74515
- case 1:
74516
- chunk[i2++] = b64[t | b >> 4];
74517
- t = (b & 15) << 2;
74518
- j = 2;
74519
- break;
74520
- case 2:
74521
- chunk[i2++] = b64[t | b >> 6];
74522
- chunk[i2++] = b64[b & 63];
74523
- j = 0;
74524
- break;
74525
- }
74526
- if (i2 > 8191) {
74527
- (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
74528
- i2 = 0;
74529
- }
74530
- }
74531
- if (j) {
74532
- chunk[i2++] = b64[t];
74533
- chunk[i2++] = 61;
74534
- if (j === 1) chunk[i2++] = 61;
74535
- }
74536
- if (parts) {
74537
- if (i2) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2)));
74538
- return parts.join("");
74539
- }
74540
- return String.fromCharCode.apply(String, chunk.slice(0, i2));
74541
- }
74542
- function replacer(key, value) {
74543
- if (value && value.constructor === Uint8Array) {
74544
- return b64Encode(value, 0, value.length);
74545
- }
74546
- return value;
74547
- }
74548
- function fetchReq(path13, init) {
74549
- const { pathPrefix, ...req } = init || {};
74550
- const url = pathPrefix ? `${pathPrefix}${path13}` : path13;
74551
- return fetch(url, req).then(
74552
- (r) => r.json().then((body) => {
74553
- if (!r.ok) {
74554
- throw body;
74555
- }
74556
- return body;
74557
- })
74558
- );
74559
- }
74560
- function isPlainObject(value) {
74561
- const isObject4 = Object.prototype.toString.call(value).slice(8, -1) === "Object";
74562
- const isObjLike = value !== null && isObject4;
74563
- if (!isObjLike || !isObject4) {
74564
- return false;
74565
- }
74566
- const proto2 = Object.getPrototypeOf(value);
74567
- const hasObjectConstructor = typeof proto2 === "object" && proto2.constructor === Object.prototype.constructor;
74568
- return hasObjectConstructor;
74569
- }
74570
- function isPrimitive(value) {
74571
- return ["string", "number", "boolean"].some((t) => typeof value === t);
74572
- }
74573
- function isZeroValuePrimitive(value) {
74574
- return value === false || value === 0 || value === "";
74575
- }
74576
- function flattenRequestPayload(requestPayload, path13 = "") {
74577
- return Object.keys(requestPayload).reduce((acc, key) => {
74578
- const value = requestPayload[key];
74579
- const newPath = path13 ? [path13, key].join(".") : key;
74580
- const isNonEmptyPrimitiveArray = Array.isArray(value) && value.every((v) => isPrimitive(v)) && value.length > 0;
74581
- const isNonZeroValuePrimitive = isPrimitive(value) && !isZeroValuePrimitive(value);
74582
- let objectToMerge = {};
74583
- if (isPlainObject(value)) {
74584
- objectToMerge = flattenRequestPayload(value, newPath);
74585
- } else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
74586
- objectToMerge = { [newPath]: value };
74587
- }
74588
- return { ...acc, ...objectToMerge };
74589
- }, {});
74590
- }
74591
- function renderURLSearchParams(requestPayload, urlPathParams = []) {
74592
- const flattenedRequestPayload = flattenRequestPayload(requestPayload);
74593
- const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
74594
- (acc, key) => {
74595
- const value = flattenedRequestPayload[key];
74596
- if (urlPathParams.find((f) => f === key)) {
74597
- return acc;
74598
- }
74599
- return Array.isArray(value) ? [...acc, ...value.map((m) => [key, m.toString()])] : acc = [...acc, [key, value.toString()]];
74600
- },
74601
- []
74602
- );
74603
- return new URLSearchParams(urlSearchParams).toString();
74604
- }
74605
-
74606
75000
  // proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.ts
75001
+ init_fetch_pb();
74607
75002
  var AuthType = /* @__PURE__ */ ((AuthType2) => {
74608
75003
  AuthType2["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
74609
75004
  AuthType2["AUTH_TYPE_OCULUS_NONCE"] = "AUTH_TYPE_OCULUS_NONCE";
@@ -74668,20 +75063,40 @@ var Users = class {
74668
75063
  };
74669
75064
 
74670
75065
  // src/auth/manager.ts
75066
+ var SAVE_OPTIONS = {
75067
+ onKeychainWriteFailed: () => print(
75068
+ "\u26A0 Could not save to system keychain, using encrypted file storage"
75069
+ )
75070
+ };
75071
+ function reportSavedTo(saved) {
75072
+ if (saved === "conf") {
75073
+ success("\u2713 Credentials saved to encrypted configuration");
75074
+ }
75075
+ }
74671
75076
  var AuthManager = class {
74672
75077
  /**
74673
75078
  * Saves credentials securely
74674
75079
  */
74675
75080
  async saveCredentials(credentials) {
74676
75081
  try {
74677
- const { saved } = await writeStoredCredentials(credentials, {
74678
- onKeychainWriteFailed: () => print(
74679
- "\u26A0 Could not save to system keychain, using encrypted file storage"
74680
- )
74681
- });
74682
- if (saved === "conf") {
74683
- success("\u2713 Credentials saved to encrypted configuration");
74684
- }
75082
+ const { saved } = await writeStoredCredentials(credentials, SAVE_OPTIONS);
75083
+ reportSavedTo(saved);
75084
+ } catch (error2) {
75085
+ throw new Error(`Failed to save credentials: ${error2}`);
75086
+ }
75087
+ }
75088
+ /**
75089
+ * Changes the stored credentials in one step no other writer can come
75090
+ * between. Anything that depends on what is stored goes through here: a
75091
+ * read followed by {@link saveCredentials} can write a stale copy over the
75092
+ * credentials of someone who signed in meanwhile.
75093
+ *
75094
+ * @param change Returns the new credentials, or undefined to leave them.
75095
+ */
75096
+ async changeCredentials(change) {
75097
+ try {
75098
+ const { saved } = await updateStoredCredentials(change, SAVE_OPTIONS);
75099
+ reportSavedTo(saved);
74685
75100
  } catch (error2) {
74686
75101
  throw new Error(`Failed to save credentials: ${error2}`);
74687
75102
  }
@@ -74696,10 +75111,6 @@ var AuthManager = class {
74696
75111
  throw new Error(`Failed to retrieve credentials: ${error2}`);
74697
75112
  }
74698
75113
  }
74699
- async getApiKey() {
74700
- const credentials = await this.getCredentials();
74701
- return credentials?.apiKey || null;
74702
- }
74703
75114
  async getWorkspace() {
74704
75115
  const credentials = await this.getCredentials();
74705
75116
  return credentials?.workspace || null;
@@ -74707,23 +75118,24 @@ var AuthManager = class {
74707
75118
  /**
74708
75119
  * Updates the Inworld token and its expiration
74709
75120
  */
74710
- async updateInworldToken(token, expirationTime) {
74711
- const credentials = await this.getCredentials();
74712
- if (!credentials) {
74713
- throw new Error("No credentials found to update");
74714
- }
74715
- credentials.inworldToken = token;
74716
- credentials.expiresAt = new Date(expirationTime).getTime();
74717
- await this.saveCredentials(credentials);
75121
+ async updateInworldToken(token, expirationTime, signInRefreshToken) {
75122
+ await this.changeCredentials(
75123
+ (current) => current?.refreshToken === signInRefreshToken ? {
75124
+ ...current,
75125
+ inworldToken: token,
75126
+ expiresAt: new Date(expirationTime).getTime()
75127
+ } : void 0
75128
+ );
74718
75129
  }
74719
- async updateWorkspaceAndApiKey(workspace, apiKey) {
74720
- const credentials = await this.getCredentials();
74721
- if (!credentials) {
74722
- throw new Error("No credentials found to update");
74723
- }
74724
- credentials.workspace = workspace;
74725
- credentials.apiKey = apiKey;
74726
- await this.saveCredentials(credentials);
75130
+ /** Sets the workspace CLI commands run in. */
75131
+ async updateWorkspace(workspace) {
75132
+ let signedIn = false;
75133
+ await this.changeCredentials((current) => {
75134
+ if (!current) return void 0;
75135
+ signedIn = true;
75136
+ return { ...current, workspace };
75137
+ });
75138
+ if (!signedIn) throw new Error("No credentials found to update");
74727
75139
  }
74728
75140
  /**
74729
75141
  * Checks if the stored Inworld token is still valid
@@ -74798,7 +75210,8 @@ var AuthManager = class {
74798
75210
  if (inworldTokenResult) {
74799
75211
  await this.updateInworldToken(
74800
75212
  inworldTokenResult.token,
74801
- inworldTokenResult.expiresAt
75213
+ inworldTokenResult.expiresAt,
75214
+ refreshed.refreshToken
74802
75215
  );
74803
75216
  return inworldTokenResult.token;
74804
75217
  }
@@ -74848,6 +75261,7 @@ var AuthManager = class {
74848
75261
  authProvider: "supabase",
74849
75262
  authUrl: source.authUrl
74850
75263
  };
75264
+ await clearStoredRuntimeToken();
74851
75265
  await this.saveCredentials(credentials);
74852
75266
  return true;
74853
75267
  } catch (error2) {
@@ -74892,6 +75306,7 @@ You can run "inworld login --force" to login with the correct environment.`
74892
75306
  var authManager = new AuthManager();
74893
75307
 
74894
75308
  // src/auth/utils.ts
75309
+ init_runtime_credential();
74895
75310
  init_constants5();
74896
75311
  init_client_info();
74897
75312
  async function requireAuth() {
@@ -74915,22 +75330,40 @@ async function requireWorkspace() {
74915
75330
  }
74916
75331
  return workspaceResourceName2;
74917
75332
  }
74918
- async function requireApiKey() {
74919
- let apiKey;
74920
- if (process.env.INWORLD_API_KEY) {
74921
- apiKey = process.env.INWORLD_API_KEY;
74922
- } else {
74923
- apiKey = await authManager.getApiKey();
75333
+ var cliSession = {
75334
+ async current() {
75335
+ const credentials = await authManager.getCredentials();
75336
+ if (!credentials?.refreshToken) return null;
75337
+ return {
75338
+ user: accountOf(credentials.inworldToken),
75339
+ deployment: credentials.authUrl ?? "",
75340
+ workspace: credentials.workspace ?? null
75341
+ };
75342
+ },
75343
+ async platformAuth() {
75344
+ const token = await authManager.getValidToken();
75345
+ if (!token) return null;
75346
+ const credentials = await authManager.getCredentials();
75347
+ const signIn2 = credentials?.inworldToken === token ? credentials : null;
75348
+ return {
75349
+ user: accountOf(token),
75350
+ deployment: signIn2 ? signIn2.authUrl ?? "" : null,
75351
+ headers: {
75352
+ Authorization: `Bearer ${token}`,
75353
+ "Grpc-Metadata-X-Authorization-Bearer-Type": "inworld"
75354
+ }
75355
+ };
74924
75356
  }
74925
- if (!apiKey) {
75357
+ };
75358
+ async function runtimeFetch(url, init) {
75359
+ try {
75360
+ return await fetchWithRuntimeCredential(cliSession, url, init);
75361
+ } catch (error2) {
75362
+ if (!(error2 instanceof RuntimeCredentialError)) throw error2;
74926
75363
  console.log();
74927
- printError("\u274C API key required");
74928
- print(
74929
- 'Please export "INWORLD_API_KEY" to environment variable or run "inworld login" to login.'
74930
- );
75364
+ printError(`\u274C ${error2.message}`);
74931
75365
  process.exit(1);
74932
75366
  }
74933
- return apiKey;
74934
75367
  }
74935
75368
  var authenticatedInworldRequest = async (pb, req, inworldToken, signal) => {
74936
75369
  if (!inworldToken) {
@@ -74990,13 +75423,6 @@ var TimestampTransportStrategy = /* @__PURE__ */ ((TimestampTransportStrategy2)
74990
75423
  return TimestampTransportStrategy2;
74991
75424
  })(TimestampTransportStrategy || {});
74992
75425
  var TTSService = class {
74993
- apiKey = null;
74994
- async ensureApiKey() {
74995
- if (!this.apiKey) {
74996
- this.apiKey = await requireApiKey();
74997
- }
74998
- return this.apiKey;
74999
- }
75000
75426
  /** Builds the API base URL from the platform URL */
75001
75427
  get apiBaseUrl() {
75002
75428
  return PLATFORM_URL.replace("platform", "api");
@@ -75005,7 +75431,6 @@ var TTSService = class {
75005
75431
  * Makes an authenticated request to the Inworld API
75006
75432
  */
75007
75433
  async makeRequest(endpoint, options = {}, trackMetrics = false) {
75008
- const apiKey = await this.ensureApiKey();
75009
75434
  const url = `${this.apiBaseUrl}${endpoint}`;
75010
75435
  const metrics = trackMetrics ? {
75011
75436
  startTime: Date.now(),
@@ -75013,10 +75438,9 @@ var TTSService = class {
75013
75438
  totalTime: 0,
75014
75439
  responseSize: 0
75015
75440
  } : {};
75016
- const response = await fetch(url, {
75441
+ const response = await runtimeFetch(url, {
75017
75442
  ...options,
75018
75443
  headers: {
75019
- Authorization: `Basic ${apiKey}`,
75020
75444
  "Content-Type": "application/json",
75021
75445
  [CLIENT_INFO_HEADER]: CLIENT_INFO,
75022
75446
  ...options.headers
@@ -75038,9 +75462,9 @@ var TTSService = class {
75038
75462
  throw new Error(
75039
75463
  `${message}
75040
75464
 
75041
- Your API key does not have the required scopes for this operation.
75042
- Run "inworld ws select-key" to switch to a key with the correct permissions,
75043
- or "inworld ws add-key --write" to create a new one with read/write access.`
75465
+ The credential in use lacks a scope this operation needs.
75466
+ If INWORLD_API_KEY is set, unset it to run as your sign-in, or set a key
75467
+ created with "inworld ws add-key --write".`
75044
75468
  );
75045
75469
  }
75046
75470
  throw new Error(`TTS API Error [${code}]: ${message}`);
@@ -75110,7 +75534,6 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
75110
75534
  * Synthesizes speech using streaming API
75111
75535
  */
75112
75536
  async synthesizeSpeechStream(request, onChunk, trackMetrics = false) {
75113
- const apiKey = await this.ensureApiKey();
75114
75537
  const url = `${this.apiBaseUrl}/tts/v1/voice:stream`;
75115
75538
  const metrics = trackMetrics ? {
75116
75539
  startTime: Date.now(),
@@ -75122,10 +75545,9 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
75122
75545
  chunkIntervals: [],
75123
75546
  errorChunks: 0
75124
75547
  } : {};
75125
- const response = await fetch(url, {
75548
+ const response = await runtimeFetch(url, {
75126
75549
  method: "POST",
75127
75550
  headers: {
75128
- Authorization: `Basic ${apiKey}`,
75129
75551
  "Content-Type": "application/json",
75130
75552
  Connection: "keep-alive",
75131
75553
  [CLIENT_INFO_HEADER]: CLIENT_INFO
@@ -75140,9 +75562,9 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
75140
75562
  throw new Error(
75141
75563
  `${message}
75142
75564
 
75143
- Your API key does not have the required scopes for this operation.
75144
- Run "inworld ws select-key" to switch to a key with the correct permissions,
75145
- or "inworld ws add-key --write" to create a new one with read/write access.`
75565
+ The credential in use lacks a scope this operation needs.
75566
+ If INWORLD_API_KEY is set, unset it to run as your sign-in, or set a key
75567
+ created with "inworld ws add-key --write".`
75146
75568
  );
75147
75569
  }
75148
75570
  throw new Error(`TTS Stream API Error [${code}]: ${message}`);
@@ -75282,6 +75704,7 @@ or "inworld ws add-key --write" to create a new one with read/write access.`
75282
75704
  var ttsService = new TTSService();
75283
75705
 
75284
75706
  // src/services/tts_websocket.ts
75707
+ init_runtime_credential();
75285
75708
  import WebSocket from "ws";
75286
75709
  init_constants5();
75287
75710
  init_client_info();
@@ -75361,6 +75784,16 @@ var TtsSession = class _TtsSession {
75361
75784
  synthesizing = false;
75362
75785
  static async open(opts) {
75363
75786
  const credential = await resolveWsCredential();
75787
+ try {
75788
+ return await _TtsSession.connect(opts, credential);
75789
+ } catch (error2) {
75790
+ const refusedSessionToken = credential.scheme === "Bearer" && error2 instanceof Error && error2.message.includes("[401]");
75791
+ if (!refusedSessionToken) throw error2;
75792
+ await forgetSessionToken();
75793
+ return _TtsSession.connect(opts, await resolveWsCredential());
75794
+ }
75795
+ }
75796
+ static async connect(opts, credential) {
75364
75797
  const wsBase = PLATFORM_URL.replace("platform", "api").replace(
75365
75798
  /^https?:\/\//,
75366
75799
  (m) => m.startsWith("https") ? "wss://" : "ws://"
@@ -75371,9 +75804,6 @@ var TtsSession = class _TtsSession {
75371
75804
  authorization: `${credential.scheme} ${credential.token}`,
75372
75805
  [CLIENT_INFO_HEADER]: CLIENT_INFO
75373
75806
  };
75374
- if (credential.scheme === "Bearer") {
75375
- headers["grpc-metadata-x-authorization-bearer-type"] = "inworld";
75376
- }
75377
75807
  const ws = new WebSocket(url, {
75378
75808
  headers,
75379
75809
  handshakeTimeout: OPEN_TIMEOUT_MS,
@@ -75549,19 +75979,9 @@ async function resolveWsCredential() {
75549
75979
  warnedInvalidApiKey = true;
75550
75980
  }
75551
75981
  }
75552
- const storedKey = (await authManager.getApiKey().catch(() => null))?.trim();
75553
- if (storedKey) {
75554
- dlog("auth", `stored API key \u2192 Basic ${maskCred(storedKey)}`);
75555
- return { scheme: "Basic", token: storedKey };
75556
- }
75557
- const sessionToken = await authManager.getValidToken().catch(() => null) ?? "";
75558
- if (sessionToken) {
75559
- dlog("auth", `session token \u2192 Bearer ${maskCred(sessionToken)}`);
75560
- return { scheme: "Bearer", token: sessionToken };
75561
- }
75562
- throw new Error(
75563
- "No Inworld credential available for the TTS WebSocket. Set INWORLD_PUBLIC_KEY + INWORLD_PUBLIC_SECRET (preferred), or INWORLD_API_KEY=base64(key:secret), or run `inworld auth login`."
75564
- );
75982
+ const credential = await resolveSessionCredential(cliSession);
75983
+ dlog("auth", `session token \u2192 Bearer ${maskCred(credential.token)}`);
75984
+ return credential;
75565
75985
  }
75566
75986
  function looksLikeBase64(s) {
75567
75987
  if (s.length === 0 || s.length % 4 !== 0) return false;
@@ -75915,7 +76335,7 @@ function buildSynthesisRequest(text, options, explicitVoice = false) {
75915
76335
 
75916
76336
  // src/commands/audiobook/audiobook_metadata.ts
75917
76337
  import { readFile, writeFile } from "fs/promises";
75918
- import { basename, extname, join } from "path";
76338
+ import { basename, extname, join as join2 } from "path";
75919
76339
 
75920
76340
  // src/commands/audiobook/epub_reader.ts
75921
76341
  var import_adm_zip = __toESM(require_adm_zip(), 1);
@@ -76086,7 +76506,7 @@ async function resolveAudiobookMetadata(options) {
76086
76506
  language = meta.language;
76087
76507
  if (meta.cover && !options.coverOverride) {
76088
76508
  const ext = meta.cover.mediaType === "image/png" ? ".png" : meta.cover.mediaType === "image/jpeg" ? ".jpg" : extname(meta.cover.filename) || ".bin";
76089
- coverPath = join(options.workDir, `cover${ext}`);
76509
+ coverPath = join2(options.workDir, `cover${ext}`);
76090
76510
  await writeFile(coverPath, meta.cover.data);
76091
76511
  coverMediaType = meta.cover.mediaType;
76092
76512
  }
@@ -76102,7 +76522,7 @@ async function resolveAudiobookMetadata(options) {
76102
76522
  );
76103
76523
  }
76104
76524
  const ext = detected === "image/png" ? ".png" : ".jpg";
76105
- coverPath = join(options.workDir, `cover${ext}`);
76525
+ coverPath = join2(options.workDir, `cover${ext}`);
76106
76526
  await writeFile(coverPath, buf);
76107
76527
  coverMediaType = detected;
76108
76528
  }
@@ -79333,7 +79753,7 @@ var handleResult = (result, verboseInfo, { reject }) => {
79333
79753
  };
79334
79754
 
79335
79755
  // node_modules/execa/lib/stdio/handle-sync.js
79336
- import { readFileSync as readFileSync2 } from "node:fs";
79756
+ import { readFileSync as readFileSync3 } from "node:fs";
79337
79757
 
79338
79758
  // node_modules/execa/lib/stdio/type.js
79339
79759
  var getStdioItemType = (value, optionName) => {
@@ -79663,7 +80083,7 @@ var normalizeStdioSync = (stdioArray, buffer, verboseInfo) => stdioArray.map((st
79663
80083
  var isOutputPipeOnly = (stdioOption) => stdioOption === "pipe" || Array.isArray(stdioOption) && stdioOption.every((item) => item === "pipe");
79664
80084
 
79665
80085
  // node_modules/execa/lib/stdio/native.js
79666
- import { readFileSync } from "node:fs";
80086
+ import { readFileSync as readFileSync2 } from "node:fs";
79667
80087
  import tty3 from "node:tty";
79668
80088
  var handleNativeStream = ({ stdioItem, stdioItem: { type }, isStdioArray, fdNumber, direction, isSync }) => {
79669
80089
  if (!isStdioArray || type !== "native") {
@@ -79697,7 +80117,7 @@ var getTargetFd = ({ value, optionName, fdNumber, direction }) => {
79697
80117
  if (tty3.isatty(targetFdNumber)) {
79698
80118
  throw new TypeError(`The \`${optionName}: ${serializeOptionValue(value)}\` option is invalid: it cannot be a TTY with synchronous methods.`);
79699
80119
  }
79700
- return { type: "uint8Array", value: bufferToUint8Array(readFileSync(targetFdNumber)), optionName };
80120
+ return { type: "uint8Array", value: bufferToUint8Array(readFileSync2(targetFdNumber)), optionName };
79701
80121
  };
79702
80122
  var getTargetFdNumber = (value, fdNumber) => {
79703
80123
  if (value === "inherit") {
@@ -80030,8 +80450,8 @@ var addProperties = {
80030
80450
  var addPropertiesSync = {
80031
80451
  input: {
80032
80452
  ...addProperties,
80033
- fileUrl: ({ value }) => ({ contents: [bufferToUint8Array(readFileSync2(value))] }),
80034
- filePath: ({ value: { file } }) => ({ contents: [bufferToUint8Array(readFileSync2(file))] }),
80453
+ fileUrl: ({ value }) => ({ contents: [bufferToUint8Array(readFileSync3(value))] }),
80454
+ filePath: ({ value: { file } }) => ({ contents: [bufferToUint8Array(readFileSync3(file))] }),
80035
80455
  fileNumber: forbiddenIfSync,
80036
80456
  iterable: ({ value }) => ({ contents: [...value] }),
80037
80457
  string: ({ value }) => ({ contents: [value] }),
@@ -80377,7 +80797,7 @@ var validateSerializable = (newContents) => {
80377
80797
  };
80378
80798
 
80379
80799
  // node_modules/execa/lib/io/output-sync.js
80380
- import { writeFileSync as writeFileSync2, appendFileSync } from "node:fs";
80800
+ import { writeFileSync as writeFileSync3, appendFileSync } from "node:fs";
80381
80801
 
80382
80802
  // node_modules/execa/lib/verbose/output.js
80383
80803
  var shouldLogOutput = ({ stdioItems, encoding, verboseInfo, fdNumber }) => fdNumber !== "all" && isFullVerbose(verboseInfo, fdNumber) && !BINARY_ENCODINGS.has(encoding) && fdUsesVerbose(fdNumber) && (stdioItems.some(({ type, value }) => type === "native" && PIPED_STDIO_VALUES.has(value)) || stdioItems.every(({ type }) => TRANSFORM_TYPES.has(type)));
@@ -80504,7 +80924,7 @@ var writeToFiles = (serializedResult, stdioItems, outputFiles) => {
80504
80924
  appendFileSync(path13, serializedResult);
80505
80925
  } else {
80506
80926
  outputFiles.add(pathString);
80507
- writeFileSync2(path13, serializedResult);
80927
+ writeFileSync3(path13, serializedResult);
80508
80928
  }
80509
80929
  }
80510
80930
  };
@@ -83236,14 +83656,14 @@ async function writeChapterPcm(path13, segments, synthesize, chapterIndex, attem
83236
83656
  import { createHash as createHash3 } from "crypto";
83237
83657
  import { rename, writeFile as writeFile3 } from "fs/promises";
83238
83658
  import { readFile as readFile2 } from "fs/promises";
83239
- import { join as join2 } from "path";
83659
+ import { join as join3 } from "path";
83240
83660
  var STATE_FILE_NAME = "state.json";
83241
83661
  var STATE_FILE_VERSION = 1;
83242
83662
  function sha256(buffer) {
83243
83663
  return createHash3("sha256").update(buffer).digest("hex");
83244
83664
  }
83245
83665
  function statePath(workDir) {
83246
- return join2(workDir, STATE_FILE_NAME);
83666
+ return join3(workDir, STATE_FILE_NAME);
83247
83667
  }
83248
83668
  async function readStateFile(workDir) {
83249
83669
  try {
@@ -83405,7 +83825,7 @@ var audiobookGenerateCommand = addGenerationOptions(
83405
83825
  const resolvedInput = resolve(inputPath);
83406
83826
  const outputPath = resolve(options.output);
83407
83827
  const workDir = resolve(
83408
- options.workDir ?? join3(tmpdir2(), `inworld-audiobook-${Date.now()}`)
83828
+ options.workDir ?? join4(tmpdir2(), `inworld-audiobook-${Date.now()}`)
83409
83829
  );
83410
83830
  await mkdir(workDir, { recursive: true });
83411
83831
  const sourceBytes = await readFile3(resolvedInput);
@@ -83456,8 +83876,8 @@ var audiobookGenerateCommand = addGenerationOptions(
83456
83876
  idx: i2,
83457
83877
  chapter: ch,
83458
83878
  segments,
83459
- pcmFile: join3(workDir, `ch${idx}.pcm`),
83460
- mp3File: join3(workDir, `ch${idx}.mp3`)
83879
+ pcmFile: join4(workDir, `ch${idx}.pcm`),
83880
+ mp3File: join4(workDir, `ch${idx}.mp3`)
83461
83881
  };
83462
83882
  });
83463
83883
  if (options.force) {
@@ -83649,7 +84069,7 @@ var audiobookGenerateCommand = addGenerationOptions(
83649
84069
  authorOverride: options.author,
83650
84070
  coverOverride: options.cover
83651
84071
  });
83652
- const metadataFile = join3(workDir, "chapters.ffmeta");
84072
+ const metadataFile = join4(workDir, "chapters.ffmeta");
83653
84073
  await writeChaptersMetadata(marks, metadataFile, {
83654
84074
  title: bookMeta.title,
83655
84075
  artist: bookMeta.author,
@@ -83693,7 +84113,7 @@ var audiobookGenerateCommand = addGenerationOptions(
83693
84113
  console.error(source_default.red(msg));
83694
84114
  try {
83695
84115
  const workDir = resolve(
83696
- options.workDir ?? join3(tmpdir2(), `inworld-audiobook-${Date.now()}`)
84116
+ options.workDir ?? join4(tmpdir2(), `inworld-audiobook-${Date.now()}`)
83697
84117
  );
83698
84118
  const existing = await readStateFile(workDir);
83699
84119
  if (existing) {
@@ -83714,7 +84134,7 @@ var audiobookCommand = new Command("audiobook").description("Audiobook generatio
83714
84134
  });
83715
84135
 
83716
84136
  // src/commands/auth/login_command.ts
83717
- import * as readline4 from "readline";
84137
+ import * as readline3 from "readline";
83718
84138
  init_constants5();
83719
84139
  init_browser();
83720
84140
  init_identity();
@@ -83723,6 +84143,7 @@ init_identity();
83723
84143
  init_constants5();
83724
84144
 
83725
84145
  // proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
84146
+ init_fetch_pb();
83726
84147
  var ApiKeys = class {
83727
84148
  static ListApiKeys(req, initReq) {
83728
84149
  return fetchReq(
@@ -83763,6 +84184,7 @@ var ApiKeys = class {
83763
84184
  };
83764
84185
 
83765
84186
  // proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.ts
84187
+ init_fetch_pb();
83766
84188
  var Workspaces = class {
83767
84189
  static GetWorkspace(req, initReq) {
83768
84190
  return fetchReq(
@@ -83847,44 +84269,8 @@ var Workspaces = class {
83847
84269
  }
83848
84270
  };
83849
84271
 
83850
- // src/utils/confirm.ts
83851
- import * as readline2 from "readline";
83852
- var globalForceYes = false;
83853
- function setGlobalForceYes(value) {
83854
- globalForceYes = value;
83855
- }
83856
- async function confirm(options) {
83857
- const { message, forceYes, defaultValue = false } = options;
83858
- if (forceYes !== void 0 ? forceYes : globalForceYes) {
83859
- return true;
83860
- }
83861
- const rl = readline2.createInterface({
83862
- input: process.stdin,
83863
- output: process.stdout
83864
- });
83865
- return new Promise((resolve5) => {
83866
- rl.question(message, (answer) => {
83867
- rl.close();
83868
- const trimmedAnswer = answer.trim().toLowerCase();
83869
- if (trimmedAnswer === "y" || trimmedAnswer === "yes") {
83870
- resolve5(true);
83871
- return;
83872
- }
83873
- if (trimmedAnswer === "n" || trimmedAnswer === "no") {
83874
- resolve5(false);
83875
- return;
83876
- }
83877
- if (trimmedAnswer === "") {
83878
- resolve5(defaultValue);
83879
- return;
83880
- }
83881
- resolve5(false);
83882
- });
83883
- });
83884
- }
83885
-
83886
84272
  // src/utils/selector.ts
83887
- import * as readline3 from "readline";
84273
+ import * as readline2 from "readline";
83888
84274
  async function selectItem(options) {
83889
84275
  const {
83890
84276
  items,
@@ -83909,7 +84295,7 @@ async function selectItem(options) {
83909
84295
  const displayName = getDisplayName(item);
83910
84296
  printListItem(`${idx + 1}. ${bright(displayName)}`);
83911
84297
  });
83912
- const rl = readline3.createInterface({
84298
+ const rl = readline2.createInterface({
83913
84299
  input: process.stdin,
83914
84300
  output: process.stdout
83915
84301
  });
@@ -84004,39 +84390,10 @@ var WorkspaceService = class {
84004
84390
  return selectedWorkspace.name;
84005
84391
  }
84006
84392
  /**
84007
- * Prompts user to select an API key from available API keys
84008
- * @param apiKeys List of API keys to select from
84009
- * @param forceFirst If true, automatically selects the first API key
84010
- * @returns The selected API key or null if no selection was made
84011
- */
84012
- static async pickApiKey(apiKeys, forceFirst = false) {
84013
- return selectItemOrExit({
84014
- items: apiKeys,
84015
- getDisplayName: (apiKey) => {
84016
- const displayName = apiKey.displayName;
84017
- const label = displayName || trimBase64Key(apiKey.key || "unknown");
84018
- const createdAt = apiKey.createTime ? new Date(apiKey.createTime).toLocaleDateString() : "unknown date";
84019
- const permissions = formatApiKeyScopes(apiKey.scopes);
84020
- return `${label} (created: ${createdAt})${permissions ? ` ${permissions}` : ""}`;
84021
- },
84022
- getIdentifier: (apiKey) => apiKey.name?.split("/").pop() || "unknown",
84023
- prompt: "Enter the number of the API key to use:",
84024
- title: "Available API keys:",
84025
- forceFirst,
84026
- noItemsMessage: "No API keys found.",
84027
- invalidSelectionMessage: "Invalid selection. Please enter a valid number."
84028
- });
84029
- }
84030
- static returnBase64 = (key, secret) => {
84031
- const encodedKeySecret = new TextEncoder().encode(`${key}:${secret}`);
84032
- return btoa(String.fromCharCode.apply(null, Array.from(encodedKeySecret)));
84033
- };
84034
- /**
84035
- * Activates a workspace by selecting it and its associated API key.
84036
- * If no API key exists, prompts the user to generate one.
84393
+ * Selects the workspace the signed-in user's commands run in.
84037
84394
  *
84038
84395
  * @param options Configuration options
84039
- * @param options.forceFirst If true, automatically selects the first workspace and API key
84396
+ * @param options.forceFirst If true, automatically selects the first workspace
84040
84397
  */
84041
84398
  static async activateWorkspace({
84042
84399
  forceFirst
@@ -84048,228 +84405,60 @@ var WorkspaceService = class {
84048
84405
  print(`
84049
84406
  Selecting workspace: ${source_default.whiteBright(workspaceId)}`);
84050
84407
  print(`Selected workspace link: ${workspaceLink(workspaceId)}`);
84051
- let apiKey = null;
84052
- const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
84053
- parent: workspaceResourceName2,
84054
- pageSize: forceFirst ? 1 : WORKSPACES_LIST_SIZE
84055
- });
84056
- if (response?.apiKeys?.length) {
84057
- if (response.apiKeys.length === 1 || forceFirst) {
84058
- apiKey = response.apiKeys[0];
84059
- } else {
84060
- print(`Found ${response.apiKeys.length} API keys in the workspace.`);
84061
- apiKey = await this.pickApiKey(response.apiKeys, false);
84062
- }
84063
- } else {
84064
- const shouldGenerate = await confirm({
84065
- message: "No API keys found for this workspace. Would you like to generate one? (y/N): ",
84066
- defaultValue: false
84067
- });
84068
- if (shouldGenerate) {
84069
- print("Generating API key...");
84070
- const generateApiKeyResponse = await authenticatedInworldRequest(
84071
- ApiKeys.GenerateApiKey,
84072
- {
84073
- parent: workspaceResourceName2
84074
- }
84075
- );
84076
- if (!generateApiKeyResponse) {
84077
- printError("Failed to generate API key.");
84078
- process.exit(1);
84079
- }
84080
- apiKey = generateApiKeyResponse;
84081
- success("API key generated successfully.");
84082
- } else {
84083
- print("No API key will be generated.");
84084
- }
84085
- }
84086
- const base64Key = this.returnBase64(apiKey?.key, apiKey?.secret);
84087
- print(
84088
- `
84089
- Selecting API key: ${source_default.whiteBright(trimBase64Key(base64Key))}`
84090
- );
84091
- await authManager.updateWorkspaceAndApiKey(workspaceId, base64Key);
84092
- success("\nWorkspace and API key selected.");
84093
- }
84094
- /**
84095
- * Lists all API keys for the currently active workspace
84096
- */
84097
- static async listApiKeys() {
84098
- const credentials = await authManager.getCredentials();
84099
- if (!credentials?.workspace) {
84100
- printError(
84101
- 'No workspace activated. Please run "inworld workspace activate" first.'
84102
- );
84103
- return;
84104
- }
84105
- const parent = ensureWorkspaceResourceName(credentials.workspace);
84106
- const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
84107
- parent,
84108
- pageSize: WORKSPACES_LIST_SIZE
84109
- });
84110
- const apiKeys = response?.apiKeys || [];
84111
- if (apiKeys.length === 0) {
84112
- printError("No API keys found in the active workspace.");
84113
- return;
84114
- }
84115
- console.log();
84116
- printHeader(`API keys in workspace ${credentials.workspace}:`);
84117
- apiKeys.forEach((apiKey, idx) => {
84118
- const displayName = apiKey.displayName;
84119
- const label = displayName || trimBase64Key(apiKey.key || "unknown");
84120
- const createdAt = apiKey.createTime ? new Date(apiKey.createTime).toLocaleDateString() : "unknown date";
84121
- const state = apiKey.state || "unknown";
84122
- const permissions = formatApiKeyScopes(apiKey.scopes);
84123
- printListItem(
84124
- `${idx + 1}. ${label} (created: ${createdAt}, state: ${state})${permissions ? ` ${permissions}` : ""}`
84125
- );
84126
- });
84127
- }
84128
- /**
84129
- * Allows user to select and activate a different API key from the current workspace
84130
- */
84131
- static async selectApiKey() {
84132
- const credentials = await authManager.getCredentials();
84133
- if (!credentials?.workspace) {
84134
- printError(
84135
- 'No workspace activated. Please run "inworld workspace activate" first.'
84136
- );
84137
- return;
84138
- }
84139
- const parent = ensureWorkspaceResourceName(credentials.workspace);
84140
- const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
84141
- parent,
84142
- pageSize: WORKSPACES_LIST_SIZE
84143
- });
84144
- const apiKeys = response?.apiKeys || [];
84145
- if (apiKeys.length === 0) {
84146
- printError("No API keys found in the active workspace.");
84147
- const shouldGenerate = await confirm({
84148
- message: "Would you like to generate a new API key? (y/N): ",
84149
- defaultValue: false
84150
- });
84151
- if (shouldGenerate) {
84152
- await this.generateApiKey();
84153
- }
84154
- return;
84155
- }
84156
- if (apiKeys.length === 1) {
84157
- print("Only one API key found in the workspace.");
84158
- const apiKey = apiKeys[0];
84159
- const base64Key = this.returnBase64(apiKey?.key, apiKey?.secret);
84160
- await authManager.updateWorkspaceAndApiKey(
84161
- credentials.workspace,
84162
- base64Key
84163
- );
84164
- success("API key activated successfully.");
84165
- return;
84166
- }
84167
- const selectedApiKey = await this.pickApiKey(apiKeys, false);
84168
- if (selectedApiKey) {
84169
- const base64Key = this.returnBase64(
84170
- selectedApiKey.key,
84171
- selectedApiKey.secret
84172
- );
84173
- await authManager.updateWorkspaceAndApiKey(
84174
- credentials.workspace,
84175
- base64Key
84176
- );
84177
- success("API key activated successfully.");
84178
- }
84408
+ await authManager.updateWorkspace(workspaceId);
84409
+ success("\nWorkspace selected.");
84179
84410
  }
84180
84411
  /**
84181
- * Generates a new API key for the currently active workspace
84182
- */
84183
- static async generateApiKey() {
84184
- const credentials = await authManager.getCredentials();
84185
- if (!credentials?.workspace) {
84186
- printError(
84187
- 'No workspace activated. Please run "inworld workspace activate" first.'
84188
- );
84189
- return;
84190
- }
84191
- print("Generating new API key...");
84192
- const parent = ensureWorkspaceResourceName(credentials.workspace);
84193
- const generateApiKeyResponse = await authenticatedInworldRequest(
84194
- ApiKeys.GenerateApiKey,
84195
- {
84196
- parent
84197
- }
84198
- );
84199
- if (!generateApiKeyResponse) {
84200
- printError("Failed to generate API key.");
84201
- return;
84202
- }
84203
- const base64Key = this.returnBase64(
84204
- generateApiKeyResponse.key,
84205
- generateApiKeyResponse.secret
84206
- );
84207
- await authManager.updateWorkspaceAndApiKey(
84208
- credentials.workspace,
84209
- base64Key
84210
- );
84211
- success("API key activated successfully.");
84212
- success("API key generated and activated successfully.");
84213
- console.log();
84214
- printHeader("API Key details:");
84215
- printListItem(
84216
- `Name: ${generateApiKeyResponse.name?.split("/").pop() || "unknown"}`
84217
- );
84218
- printListItem(`Key: ${generateApiKeyResponse.key}`);
84219
- printListItem(`Base64: ${base64Key}`);
84220
- }
84221
- /**
84222
- * Creates a new API key with predefined scope preset and activates it.
84412
+ * Creates an API key in the active workspace and prints it. The platform
84413
+ * returns the secret only here, so it is shown once and never stored.
84414
+ *
84415
+ * @throws when no workspace is selected or no key comes back: the command
84416
+ * must exit non-zero, or a script would take a failed creation for success.
84223
84417
  * @param mode 'read' for read-only, 'write' for read/write voices & router
84224
84418
  * @param displayName Optional display name for the key
84225
84419
  */
84226
84420
  static async createApiKey(mode, displayName) {
84227
84421
  const credentials = await authManager.getCredentials();
84228
84422
  if (!credentials?.workspace) {
84229
- printError(
84230
- 'No workspace activated. Please run "inworld workspace activate" first.'
84423
+ throw new Error(
84424
+ 'No workspace selected. Please run "inworld workspace select" first.'
84231
84425
  );
84232
- return;
84233
84426
  }
84234
84427
  const parent = ensureWorkspaceResourceName(credentials.workspace);
84235
84428
  const baseScopes = ["api.rt::x", "api.ml::x", "api.ops::x"];
84236
84429
  const scopes = mode === "write" ? [...baseScopes, "api.dsgnt.voices::rw", "api.dsgnt.router::rw"] : [...baseScopes, "api.dsgnt.voices::r", "api.dsgnt.router::r"];
84237
84430
  const label = mode === "write" ? "read/write" : "read-only";
84238
84431
  print(`Creating ${label} API key...`);
84239
- const generateApiKeyResponse = await authenticatedInworldRequest(
84240
- ApiKeys.GenerateApiKey,
84241
- {
84242
- parent,
84243
- scopes,
84244
- displayName,
84245
- authTypes: [
84246
- "API_KEY_AUTHORIZATION_TYPE_BASIC" /* API_KEY_AUTHORIZATION_TYPE_BASIC */,
84247
- "API_KEY_AUTHORIZATION_TYPE_JWT" /* API_KEY_AUTHORIZATION_TYPE_JWT */
84248
- ]
84249
- }
84250
- );
84251
- if (!generateApiKeyResponse) {
84252
- printError("Failed to generate API key.");
84253
- return;
84432
+ const created = await authenticatedInworldRequest(ApiKeys.GenerateApiKey, {
84433
+ parent,
84434
+ scopes,
84435
+ displayName,
84436
+ authTypes: [
84437
+ "API_KEY_AUTHORIZATION_TYPE_BASIC" /* API_KEY_AUTHORIZATION_TYPE_BASIC */,
84438
+ "API_KEY_AUTHORIZATION_TYPE_JWT" /* API_KEY_AUTHORIZATION_TYPE_JWT */
84439
+ ]
84440
+ });
84441
+ if (!created?.key || !created.secret) {
84442
+ throw new Error("The platform returned no key to print.");
84254
84443
  }
84255
- const base64Key = this.returnBase64(
84256
- generateApiKeyResponse.key,
84257
- generateApiKeyResponse.secret
84444
+ const credential = Buffer.from(`${created.key}:${created.secret}`).toString(
84445
+ "base64"
84258
84446
  );
84259
- const workspaceId = credentials.workspace.replace(/^workspaces\//, "");
84260
- await authManager.updateWorkspaceAndApiKey(workspaceId, base64Key);
84261
- const permissions = formatApiKeyScopes(generateApiKeyResponse.scopes);
84262
- success("\nAPI key created and activated.");
84447
+ const permissions = formatApiKeyScopes(created.scopes);
84448
+ success("\nAPI key created.");
84263
84449
  console.log();
84264
84450
  printHeader("API Key details:");
84265
84451
  if (displayName) {
84266
84452
  printListItem(`Display Name: ${displayName}`);
84267
84453
  }
84268
84454
  printListItem(`Permissions: ${permissions || label}`);
84269
- printListItem(`Key: ${trimBase64Key(base64Key)}`);
84455
+ printListItem(`Key: ${credential}`);
84270
84456
  console.log();
84271
84457
  print(
84272
- `Run \`${cyan("inworld auth print-api-key")}\` to retrieve the full key.`
84458
+ "Copy it now: it is shown only this once, and the CLI does not keep it."
84459
+ );
84460
+ print(
84461
+ `Set it as ${cyan("INWORLD_API_KEY")} to use it instead of your sign-in.`
84273
84462
  );
84274
84463
  }
84275
84464
  };
@@ -84279,7 +84468,7 @@ var offerBrowser = async (url, done) => {
84279
84468
  print("Please visit the following URL to authenticate:");
84280
84469
  printLink(`${url}
84281
84470
  `);
84282
- const readlineInterface = readline4.createInterface({
84471
+ const readlineInterface = readline3.createInterface({
84283
84472
  input: process.stdin,
84284
84473
  output: process.stdout
84285
84474
  });
@@ -84306,35 +84495,12 @@ var offerBrowser = async (url, done) => {
84306
84495
  console.log();
84307
84496
  print("Waiting for authentication...");
84308
84497
  };
84309
- var ask = (question, hidden2 = false) => new Promise((resolve5) => {
84310
- const rl = readline4.createInterface({
84311
- input: process.stdin,
84312
- output: process.stdout,
84313
- terminal: true
84314
- });
84315
- if (hidden2) {
84316
- const out = rl;
84317
- out._writeToOutput = (s) => {
84318
- if (s.includes(question)) process.stdout.write(question);
84319
- };
84320
- }
84321
- rl.question(question, (answer) => {
84322
- rl.close();
84323
- if (hidden2) process.stdout.write("\n");
84324
- resolve5(answer.trim());
84325
- });
84326
- });
84327
84498
  var signIn = async (source, provider) => {
84328
- if (provider === "email") {
84329
- const email2 = await ask("Email: ");
84330
- const password = await ask("Password: ", true);
84331
- return signInWithPassword(source.authUrl, email2, password);
84332
- }
84333
84499
  const { url, done } = await startBrowserSignIn({
84334
84500
  authUrl: source.authUrl,
84335
84501
  pageUrl: INWORLD_CLI_AUTH_URL,
84336
84502
  version: CLI_VERSION,
84337
- oauthProvider: provider
84503
+ oauthProvider: provider === "email" ? void 0 : provider
84338
84504
  });
84339
84505
  await offerBrowser(url, done);
84340
84506
  return done;
@@ -84415,7 +84581,7 @@ var makeLoginCommand = (description) => {
84415
84581
  return new Command("login").description(description).option("-f, --force", "Force re-authentication even if already logged in").addOption(
84416
84582
  new Option(
84417
84583
  "-p, --provider <provider>",
84418
- "Skip the sign-in page: go straight to one OAuth provider, or sign in with email and password in the terminal"
84584
+ "Open an OAuth provider directly, or use email-link sign-in in the browser"
84419
84585
  ).choices([...GOTRUE_OAUTH_PROVIDERS, "email"]).default(process.env.INWORLD_AUTH_OAUTH_PROVIDER || void 0)
84420
84586
  ).action(loginAction);
84421
84587
  };
@@ -84429,6 +84595,42 @@ var loginCommandAlias = makeLoginCommand(
84429
84595
  // src/commands/auth/logout_command.ts
84430
84596
  init_identity();
84431
84597
 
84598
+ // src/utils/confirm.ts
84599
+ import * as readline4 from "readline";
84600
+ var globalForceYes = false;
84601
+ function setGlobalForceYes(value) {
84602
+ globalForceYes = value;
84603
+ }
84604
+ async function confirm(options) {
84605
+ const { message, forceYes, defaultValue = false } = options;
84606
+ if (forceYes !== void 0 ? forceYes : globalForceYes) {
84607
+ return true;
84608
+ }
84609
+ const rl = readline4.createInterface({
84610
+ input: process.stdin,
84611
+ output: process.stdout
84612
+ });
84613
+ return new Promise((resolve5) => {
84614
+ rl.question(message, (answer) => {
84615
+ rl.close();
84616
+ const trimmedAnswer = answer.trim().toLowerCase();
84617
+ if (trimmedAnswer === "y" || trimmedAnswer === "yes") {
84618
+ resolve5(true);
84619
+ return;
84620
+ }
84621
+ if (trimmedAnswer === "n" || trimmedAnswer === "no") {
84622
+ resolve5(false);
84623
+ return;
84624
+ }
84625
+ if (trimmedAnswer === "") {
84626
+ resolve5(defaultValue);
84627
+ return;
84628
+ }
84629
+ resolve5(false);
84630
+ });
84631
+ });
84632
+ }
84633
+
84432
84634
  // src/utils/mcp_session_file.ts
84433
84635
  import fs5 from "node:fs";
84434
84636
  import os4 from "node:os";
@@ -84503,17 +84705,19 @@ var logoutCommand = makeLogoutCommand(
84503
84705
  );
84504
84706
 
84505
84707
  // src/commands/auth/status_command.ts
84708
+ init_runtime_credential();
84506
84709
  var statusAction = async () => {
84507
84710
  try {
84508
84711
  const credentials = await authManager.getCredentials();
84712
+ const apiKey = apiKeyFromEnvironment();
84509
84713
  printHeader("\nInworld CLI Status\n");
84510
84714
  if (!credentials) {
84511
84715
  print("Not authenticated.");
84512
84716
  print(`Run \`${bold("inworld auth login")}\` to authenticate.`);
84513
- if (process.env.INWORLD_API_KEY) {
84717
+ if (apiKey) {
84514
84718
  print(
84515
84719
  `
84516
- INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KEY)} (active)`
84720
+ INWORLD_API_KEY environment variable: ${trimBase64Key(apiKey)} (active)`
84517
84721
  );
84518
84722
  }
84519
84723
  process.exit(0);
@@ -84543,22 +84747,17 @@ INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KE
84543
84747
  print(` Workspace link: ${workspaceLink(credentials.workspace)}`);
84544
84748
  } else {
84545
84749
  print(` No workspace activated`);
84546
- print(` Run "inworld workspace activate" to select a workspace`);
84750
+ print(` Run "inworld workspace select" to select a workspace`);
84547
84751
  }
84548
- printBright("\nAPI Key:");
84549
- if (process.env.INWORLD_API_KEY) {
84752
+ printBright("\nRuntime credential:");
84753
+ if (apiKey) {
84550
84754
  print(
84551
- ` INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KEY)} (active)`
84755
+ ` INWORLD_API_KEY environment variable: ${trimBase64Key(apiKey)} (active)`
84552
84756
  );
84553
- }
84554
- if (credentials.apiKey) {
84555
- const maskedKey = credentials.apiKey.length > 20 ? `${trimBase64Key(credentials.apiKey)}` : "***";
84556
- print(` Stored API Key: ${maskedKey}`);
84757
+ } else if (credentials.workspace) {
84758
+ print(` Your sign-in, in workspace ${credentials.workspace}`);
84557
84759
  } else {
84558
- print(` No API key configured`);
84559
- if (credentials.workspace) {
84560
- print(` Run "inworld apikey select" to choose an API key`);
84561
- }
84760
+ print(` None: select a workspace, or set INWORLD_API_KEY`);
84562
84761
  }
84563
84762
  console.log();
84564
84763
  process.exit(0);
@@ -84797,26 +84996,15 @@ var printAccessTokenAction = async () => {
84797
84996
  var printAccessTokenCommand = new Command("print-access-token").description("Print the current Inworld access token").action(printAccessTokenAction);
84798
84997
 
84799
84998
  // src/commands/auth/print_api_key_command.ts
84800
- var printApiKeyAction = async () => {
84801
- try {
84802
- if (process.env.INWORLD_API_KEY) {
84803
- console.log(process.env.INWORLD_API_KEY);
84804
- return;
84805
- }
84806
- const credentials = await authManager.getCredentials();
84807
- if (credentials?.apiKey) {
84808
- console.log(credentials.apiKey);
84809
- return;
84810
- }
84811
- process.exit(1);
84812
- } catch (_error) {
84813
- process.exit(1);
84814
- }
84815
- };
84816
- var printApiKeyCommand = new Command("print-api-key").description("Print the current API key").action(printApiKeyAction);
84999
+ var printApiKeyCommand = new Command("print-api-key").description("Removed: the CLI does not store an API key").action(() => {
85000
+ process.stderr.write(
85001
+ "`inworld auth print-api-key` was removed: the CLI does not store an API key.\nRuntime commands run as your sign-in. To use a key instead, create one with\n`inworld workspace add-key` and set it as INWORLD_API_KEY.\n"
85002
+ );
85003
+ process.exit(1);
85004
+ });
84817
85005
 
84818
85006
  // src/commands/auth_command.ts
84819
- var authCommand = new Command("auth").description("Manage Inworld authentication").addCommand(loginCommand).addCommand(loginCiCommand).addCommand(logoutCommand).addCommand(printAccessTokenCommand).addCommand(printApiKeyCommand).addCommand(statusCommand).addCommand(disableTelemetryCommand).addCommand(enableTelemetryCommand).action(() => {
85007
+ var authCommand = new Command("auth").description("Manage Inworld authentication").addCommand(loginCommand).addCommand(loginCiCommand).addCommand(logoutCommand).addCommand(printAccessTokenCommand).addCommand(printApiKeyCommand, { hidden: true }).addCommand(statusCommand).addCommand(disableTelemetryCommand).addCommand(enableTelemetryCommand).action(() => {
84820
85008
  authCommand.help();
84821
85009
  });
84822
85010
 
@@ -84824,20 +85012,13 @@ var authCommand = new Command("auth").description("Manage Inworld authentication
84824
85012
  init_constants5();
84825
85013
  init_client_info();
84826
85014
  var LLMService = class {
84827
- apiKey = null;
84828
- async ensureApiKey() {
84829
- if (!this.apiKey) this.apiKey = await requireApiKey();
84830
- return this.apiKey;
84831
- }
84832
85015
  get apiBaseUrl() {
84833
85016
  return PLATFORM_URL.replace("platform", "api");
84834
85017
  }
84835
85018
  async request(path13, init = {}) {
84836
- const apiKey = await this.ensureApiKey();
84837
- const res = await fetch(`${this.apiBaseUrl}${path13}`, {
85019
+ const res = await runtimeFetch(`${this.apiBaseUrl}${path13}`, {
84838
85020
  ...init,
84839
85021
  headers: {
84840
- Authorization: `Basic ${apiKey}`,
84841
85022
  Accept: "application/json",
84842
85023
  [CLIENT_INFO_HEADER]: CLIENT_INFO,
84843
85024
  ...init.body ? { "Content-Type": "application/json" } : {},
@@ -85078,11 +85259,6 @@ var STT_MODELS = {
85078
85259
  GROQ_WHISPER_LARGE_V3: "groq/whisper-large-v3"
85079
85260
  };
85080
85261
  var STTService = class {
85081
- apiKey = null;
85082
- async ensureApiKey() {
85083
- if (!this.apiKey) this.apiKey = await requireApiKey();
85084
- return this.apiKey;
85085
- }
85086
85262
  get apiBaseUrl() {
85087
85263
  return PLATFORM_URL.replace("platform", "api");
85088
85264
  }
@@ -85093,7 +85269,6 @@ var STTService = class {
85093
85269
  * shape the production gateway actually accepts.)
85094
85270
  */
85095
85271
  async transcribe(opts) {
85096
- const apiKey = await this.ensureApiKey();
85097
85272
  const body = {
85098
85273
  transcribeConfig: {
85099
85274
  modelId: opts.modelId ?? STT_MODELS.INWORLD_STT_1,
@@ -85102,10 +85277,9 @@ var STTService = class {
85102
85277
  },
85103
85278
  audioData: { content: opts.audioBase64 }
85104
85279
  };
85105
- const res = await fetch(`${this.apiBaseUrl}/stt/v1/transcribe`, {
85280
+ const res = await runtimeFetch(`${this.apiBaseUrl}/stt/v1/transcribe`, {
85106
85281
  method: "POST",
85107
85282
  headers: {
85108
- Authorization: `Basic ${apiKey}`,
85109
85283
  "Content-Type": "application/json",
85110
85284
  [CLIENT_INFO_HEADER]: CLIENT_INFO
85111
85285
  },
@@ -85249,14 +85423,14 @@ Use this voice: inworld tts synthesize "Hello" -v ${voice.voiceId}`
85249
85423
  // src/commands/tts/tts_design_command.ts
85250
85424
  import { writeFile as writeFile5 } from "fs/promises";
85251
85425
  import { tmpdir as tmpdir3 } from "os";
85252
- import { join as join4 } from "path";
85426
+ import { join as join5 } from "path";
85253
85427
  import * as readline6 from "readline";
85254
85428
  init_audio_player();
85255
85429
  async function savePreviewsToTemp(previews) {
85256
85430
  const paths = [];
85257
85431
  for (let i2 = 0; i2 < previews.length; i2++) {
85258
85432
  const safeId = previews[i2].voiceId.replace(/[^a-zA-Z0-9_-]/g, "_");
85259
- const tempPath = join4(tmpdir3(), `inworld-preview-${i2 + 1}-${safeId}.wav`);
85433
+ const tempPath = join5(tmpdir3(), `inworld-preview-${i2 + 1}-${safeId}.wav`);
85260
85434
  const buf = Buffer.from(previews[i2].previewAudio, "base64");
85261
85435
  await writeFile5(tempPath, buf);
85262
85436
  paths.push(tempPath);
@@ -85363,10 +85537,10 @@ Actions: [1-${previews.length}] play a preview, [p] publish, [r] regenerate, [q]
85363
85537
  input: process.stdin,
85364
85538
  output: process.stdout
85365
85539
  });
85366
- const ask2 = (q) => new Promise((resolve5) => rl.question(q, resolve5));
85540
+ const ask = (q) => new Promise((resolve5) => rl.question(q, resolve5));
85367
85541
  let action = null;
85368
85542
  while (true) {
85369
- const answer = (await ask2("> ")).trim().toLowerCase();
85543
+ const answer = (await ask("> ")).trim().toLowerCase();
85370
85544
  const idx = parseInt(answer, 10);
85371
85545
  if (!isNaN(idx) && idx >= 1 && idx <= previews.length) {
85372
85546
  console.log(
@@ -86049,19 +86223,8 @@ var selectWorkspaceCommand = new Command("select").description("Select a workspa
86049
86223
  process.exit(1);
86050
86224
  }
86051
86225
  });
86052
- var selectKeyCommand = new Command("select-key").description("Select an API key for the current workspace").action(async () => {
86053
- await requireAuth();
86054
- try {
86055
- await WorkspaceService.selectApiKey();
86056
- process.exit(0);
86057
- } catch (error2) {
86058
- printError(`
86059
- Failed to select API key: ${error2.message || error2}`);
86060
- process.exit(1);
86061
- }
86062
- });
86063
86226
  var addKeyCommand = new Command("add-key").description(
86064
- "Create a new API key (read-only by default, --write for read/write)"
86227
+ "Create a new API key and print it once (read-only by default, --write for read/write)"
86065
86228
  ).option(
86066
86229
  "-w, --write",
86067
86230
  "Create with read/write permissions for voices and router"
@@ -86077,7 +86240,7 @@ Failed to create API key: ${error2.message || error2}`);
86077
86240
  process.exit(1);
86078
86241
  }
86079
86242
  });
86080
- var workspaceCommand = new Command("workspace").description("Manage Inworld workspaces").alias("ws").addCommand(selectWorkspaceCommand).addCommand(selectKeyCommand).addCommand(addKeyCommand).action(() => {
86243
+ var workspaceCommand = new Command("workspace").description("Manage Inworld workspaces").alias("ws").addCommand(selectWorkspaceCommand).addCommand(addKeyCommand).action(() => {
86081
86244
  workspaceCommand.help();
86082
86245
  });
86083
86246
 
@@ -86210,12 +86373,21 @@ var UpdateChecker = class _UpdateChecker {
86210
86373
  };
86211
86374
  var updateChecker = new UpdateChecker();
86212
86375
 
86213
- // src/index.ts
86214
- var version2 = CLI_VERSION;
86376
+ // src/utils/machine_output.ts
86215
86377
  var MACHINE_OUTPUT_COMMANDS = [
86216
- ["auth", "print-api-key"],
86217
- ["auth", "print-access-token"]
86378
+ ["auth", "print-access-token"],
86379
+ ["auth", "print-api-key"]
86218
86380
  ];
86381
+ function isMachineOutputCommand(argv) {
86382
+ if (argv.includes("--json") || argv.includes("-j")) return true;
86383
+ const commandArgs = argv.slice(2).filter((arg) => !arg.startsWith("-"));
86384
+ return MACHINE_OUTPUT_COMMANDS.some(
86385
+ (path13) => path13.every((part, i2) => commandArgs[i2] === part)
86386
+ );
86387
+ }
86388
+
86389
+ // src/index.ts
86390
+ var version2 = CLI_VERSION;
86219
86391
  process.env.DISABLE_WELCOME_MESSAGE = "true";
86220
86392
  var InworldCLI = class {
86221
86393
  program;
@@ -86285,13 +86457,6 @@ var InworldCLI = class {
86285
86457
  this.program.help();
86286
86458
  });
86287
86459
  }
86288
- isMachineOutputCommand(argv) {
86289
- if (argv.includes("--json") || argv.includes("-j")) return true;
86290
- const commandArgs = argv.slice(2).filter((arg) => !arg.startsWith("-"));
86291
- return MACHINE_OUTPUT_COMMANDS.some(
86292
- (path13) => path13.every((part, i2) => commandArgs[i2] === part)
86293
- );
86294
- }
86295
86460
  async run(args) {
86296
86461
  try {
86297
86462
  const isMcpServer = (args ?? process.argv)[2] === "mcp";
@@ -86299,7 +86464,7 @@ var InworldCLI = class {
86299
86464
  const initPromise = Promise.all([
86300
86465
  analytics.initialize().catch(() => {
86301
86466
  }),
86302
- this.isMachineOutputCommand(args ?? process.argv) ? Promise.resolve() : updateChecker.checkAndNotify().catch(() => {
86467
+ isMachineOutputCommand(args ?? process.argv) ? Promise.resolve() : updateChecker.checkAndNotify().catch(() => {
86303
86468
  })
86304
86469
  ]);
86305
86470
  const timeoutPromise = new Promise(