@inworld/cli 2.0.0 → 2.2.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
@@ -3374,7 +3374,7 @@ var init_retryify_async = __esm({
3374
3374
  throw error2;
3375
3375
  const delay = Math.round(interval * Math.random());
3376
3376
  if (delay > 0) {
3377
- const delayPromise = new Promise((resolve5) => setTimeout(resolve5, delay));
3377
+ const delayPromise = new Promise((resolve6) => setTimeout(resolve6, delay));
3378
3378
  return delayPromise.then(() => attempt.apply(void 0, args));
3379
3379
  } else {
3380
3380
  return attempt.apply(void 0, args);
@@ -6766,7 +6766,7 @@ var require_compile = __commonJS({
6766
6766
  const schOrFunc = root.refs[ref];
6767
6767
  if (schOrFunc)
6768
6768
  return schOrFunc;
6769
- let _sch = resolve5.call(this, root, ref);
6769
+ let _sch = resolve6.call(this, root, ref);
6770
6770
  if (_sch === void 0) {
6771
6771
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
6772
6772
  const { schemaId } = this.opts;
@@ -6793,7 +6793,7 @@ var require_compile = __commonJS({
6793
6793
  function sameSchemaEnv(s1, s2) {
6794
6794
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
6795
6795
  }
6796
- function resolve5(root, ref) {
6796
+ function resolve6(root, ref) {
6797
6797
  let sch;
6798
6798
  while (typeof (sch = this.refs[ref]) == "string")
6799
6799
  ref = sch;
@@ -7368,7 +7368,7 @@ var require_fast_uri = __commonJS({
7368
7368
  }
7369
7369
  return uri;
7370
7370
  }
7371
- function resolve5(baseURI, relativeURI, options) {
7371
+ function resolve6(baseURI, relativeURI, options) {
7372
7372
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
7373
7373
  const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
7374
7374
  schemelessOptions.skipEscape = true;
@@ -7595,7 +7595,7 @@ var require_fast_uri = __commonJS({
7595
7595
  var fastUri = {
7596
7596
  SCHEMES,
7597
7597
  normalize,
7598
- resolve: resolve5,
7598
+ resolve: resolve6,
7599
7599
  resolveComponent,
7600
7600
  equal,
7601
7601
  serialize: serialize2,
@@ -13961,7 +13961,7 @@ var require_compile2 = __commonJS({
13961
13961
  const schOrFunc = root.refs[ref];
13962
13962
  if (schOrFunc)
13963
13963
  return schOrFunc;
13964
- let _sch = resolve5.call(this, root, ref);
13964
+ let _sch = resolve6.call(this, root, ref);
13965
13965
  if (_sch === void 0) {
13966
13966
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
13967
13967
  const { schemaId } = this.opts;
@@ -13988,7 +13988,7 @@ var require_compile2 = __commonJS({
13988
13988
  function sameSchemaEnv(s1, s2) {
13989
13989
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
13990
13990
  }
13991
- function resolve5(root, ref) {
13991
+ function resolve6(root, ref) {
13992
13992
  let sch;
13993
13993
  while (typeof (sch = this.refs[ref]) == "string")
13994
13994
  ref = sch;
@@ -19583,7 +19583,7 @@ async function withCredentialsLock(work) {
19583
19583
  `The credential store is busy: another Inworld process holds ${lockPath}. Try again.`
19584
19584
  );
19585
19585
  }
19586
- await new Promise((resolve5) => setTimeout(resolve5, LOCK_RETRY_MS));
19586
+ await new Promise((resolve6) => setTimeout(resolve6, LOCK_RETRY_MS));
19587
19587
  }
19588
19588
  try {
19589
19589
  return await work();
@@ -19724,7 +19724,7 @@ var init_package = __esm({
19724
19724
  "package.json"() {
19725
19725
  package_default = {
19726
19726
  name: "@inworld/cli",
19727
- version: "2.0.0",
19727
+ version: "2.2.0",
19728
19728
  type: "module",
19729
19729
  main: "dist/index.js",
19730
19730
  bin: {
@@ -19957,7 +19957,7 @@ function gotrueErrorMessage(data, fallback) {
19957
19957
  }
19958
19958
  return fallback;
19959
19959
  }
19960
- async function gotrueToken(authUrl, grantType, body) {
19960
+ async function gotrueToken(authUrl, grantType, body, signal) {
19961
19961
  const url = `${authUrl}/token?grant_type=${grantType}`;
19962
19962
  const res = await fetch(url, {
19963
19963
  method: "POST",
@@ -19965,7 +19965,8 @@ async function gotrueToken(authUrl, grantType, body) {
19965
19965
  "Content-Type": "application/json",
19966
19966
  [CLIENT_INFO_HEADER]: CLIENT_INFO
19967
19967
  },
19968
- body: JSON.stringify(body)
19968
+ body: JSON.stringify(body),
19969
+ signal
19969
19970
  });
19970
19971
  const text = await res.text();
19971
19972
  let data = {};
@@ -20042,7 +20043,7 @@ function sameSecret(a2, b) {
20042
20043
  return x.length === y.length && timingSafeEqual(x, y);
20043
20044
  }
20044
20045
  function readForm(req) {
20045
- return new Promise((resolve5, reject) => {
20046
+ return new Promise((resolve6, reject) => {
20046
20047
  let size = 0;
20047
20048
  const chunks = [];
20048
20049
  req.on("data", (chunk) => {
@@ -20056,7 +20057,7 @@ function readForm(req) {
20056
20057
  });
20057
20058
  req.on(
20058
20059
  "end",
20059
- () => resolve5(new URLSearchParams(Buffer.concat(chunks).toString("utf8")))
20060
+ () => resolve6(new URLSearchParams(Buffer.concat(chunks).toString("utf8")))
20060
20061
  );
20061
20062
  req.on("error", reject);
20062
20063
  });
@@ -20076,27 +20077,59 @@ async function startLoopbackReceiver(options) {
20076
20077
  const state = base64url(randomBytes(32));
20077
20078
  const pageOrigin = new URL(options.pageUrl).origin;
20078
20079
  let settle;
20079
- const done = new Promise((resolve5, reject) => {
20080
- settle = { resolve: resolve5, reject };
20080
+ const done = new Promise((resolve6, reject) => {
20081
+ settle = { resolve: resolve6, reject };
20081
20082
  });
20082
20083
  let claimed = false;
20083
- const finish = (res, status, redeem) => {
20084
+ let ended = false;
20085
+ let failure2;
20086
+ const redemption = new AbortController();
20087
+ const end = (outcome) => {
20088
+ if (ended) return false;
20089
+ ended = true;
20084
20090
  claimed = true;
20085
- redeem().then(
20091
+ if (outcome instanceof Error) {
20092
+ failure2 = outcome;
20093
+ redemption.abort();
20094
+ settle.reject(outcome);
20095
+ } else {
20096
+ settle.resolve(outcome);
20097
+ }
20098
+ return true;
20099
+ };
20100
+ const finish = (redeem, answer = () => {
20101
+ }) => {
20102
+ claimed = true;
20103
+ redeem(redemption.signal).then(
20104
+ // A result after cancel or the timeout is dropped. Ending closes the
20105
+ // listener first, so a browser still waiting gets no result page: its
20106
+ // connection is reset, and `answer` finds it gone.
20086
20107
  (tokens) => {
20087
- res.writeHead(status, { Location: signInResultUrl(options.pageUrl) });
20088
- res.end();
20089
- settle.resolve(tokens);
20108
+ end(tokens);
20109
+ answer(signInResultUrl(options.pageUrl, failure2?.message));
20090
20110
  },
20091
20111
  (error2) => {
20092
- res.writeHead(status, {
20093
- Location: signInResultUrl(options.pageUrl, error2.message)
20094
- });
20095
- res.end();
20096
- settle.reject(error2);
20112
+ end(error2);
20113
+ answer(signInResultUrl(options.pageUrl, failure2?.message));
20097
20114
  }
20098
20115
  );
20099
20116
  };
20117
+ const answerWith = (res, status) => {
20118
+ return (location) => {
20119
+ if (res.headersSent || res.destroyed) return;
20120
+ res.writeHead(status, { Location: location });
20121
+ res.end();
20122
+ };
20123
+ };
20124
+ const redeemRedirect = (params) => {
20125
+ const error2 = params.get("error_description") ?? params.get("error");
20126
+ const code = params.get("code");
20127
+ if (error2 || !code) {
20128
+ const msg = error2 ?? "No authorization code in the redirect.";
20129
+ return () => Promise.reject(new Error(msg));
20130
+ }
20131
+ return (signal) => options.redeemCode(code, signal);
20132
+ };
20100
20133
  const handler = (req, res) => {
20101
20134
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
20102
20135
  if (url.pathname !== "/") {
@@ -20112,14 +20145,7 @@ async function startLoopbackReceiver(options) {
20112
20145
  res.writeHead(400).end("Unknown sign-in.");
20113
20146
  return;
20114
20147
  }
20115
- const error2 = url.searchParams.get("error_description") ?? url.searchParams.get("error");
20116
- const code = url.searchParams.get("code");
20117
- if (error2 || !code) {
20118
- const msg = error2 ?? "No authorization code in the redirect.";
20119
- finish(res, 302, () => Promise.reject(new Error(msg)));
20120
- return;
20121
- }
20122
- finish(res, 302, () => options.redeemCode(code));
20148
+ finish(redeemRedirect(url.searchParams), answerWith(res, 302));
20123
20149
  return;
20124
20150
  }
20125
20151
  if (req.method === "POST") {
@@ -20142,7 +20168,10 @@ async function startLoopbackReceiver(options) {
20142
20168
  res.writeHead(400).end("Missing refresh_token.");
20143
20169
  return;
20144
20170
  }
20145
- finish(res, 303, () => options.redeemRefreshToken(refreshToken));
20171
+ finish(
20172
+ (signal) => options.redeemRefreshToken(refreshToken, signal),
20173
+ answerWith(res, 303)
20174
+ );
20146
20175
  },
20147
20176
  () => {
20148
20177
  if (!res.headersSent) res.writeHead(413).end();
@@ -20153,28 +20182,47 @@ async function startLoopbackReceiver(options) {
20153
20182
  res.writeHead(405).end();
20154
20183
  };
20155
20184
  const server = http.createServer({ keepAlive: false }, handler);
20156
- await new Promise((resolve5, reject) => {
20185
+ await new Promise((resolve6, reject) => {
20157
20186
  server.once("error", reject);
20158
- server.listen(options.port, "127.0.0.1", () => resolve5());
20187
+ server.listen(options.port, "127.0.0.1", () => resolve6());
20159
20188
  });
20160
20189
  const { port } = server.address();
20161
- const timer = setTimeout(
20162
- () => settle.reject(
20190
+ const timer = setTimeout(() => {
20191
+ end(
20163
20192
  new Error(
20164
20193
  `Sign-in timed out after ${OAUTH_SIGN_IN_TIMEOUT_MS / 6e4} minutes. Run the login again.`
20165
20194
  )
20166
- ),
20167
- OAUTH_SIGN_IN_TIMEOUT_MS
20168
- );
20195
+ );
20196
+ }, OAUTH_SIGN_IN_TIMEOUT_MS);
20169
20197
  timer.unref();
20170
- const redirectTo = new URL(`http://127.0.0.1:${port}/`);
20171
- redirectTo.searchParams.set("state", state);
20198
+ const loopback = new URL(`http://127.0.0.1:${port}/`);
20199
+ loopback.searchParams.set("state", state);
20200
+ const pasteRedirect = (address) => {
20201
+ if (claimed) return false;
20202
+ let url;
20203
+ try {
20204
+ url = new URL(address.trim());
20205
+ } catch {
20206
+ return false;
20207
+ }
20208
+ if (url.origin !== loopback.origin || url.pathname !== loopback.pathname || !sameSecret(url.searchParams.get("state"), state) || !(url.searchParams.get("code") || url.searchParams.get("error") || url.searchParams.get("error_description"))) {
20209
+ return false;
20210
+ }
20211
+ finish(redeemRedirect(url.searchParams));
20212
+ return true;
20213
+ };
20214
+ const cancel = () => {
20215
+ end(new Error("Sign-in cancelled."));
20216
+ };
20172
20217
  return {
20173
20218
  state,
20174
20219
  port,
20175
- redirectTo: redirectTo.toString(),
20220
+ redirectTo: loopback.toString(),
20176
20221
  done,
20222
+ pasteRedirect,
20223
+ cancel,
20177
20224
  close: () => {
20225
+ claimed = true;
20178
20226
  clearTimeout(timer);
20179
20227
  server.close();
20180
20228
  server.closeAllConnections?.();
@@ -20186,13 +20234,18 @@ async function startBrowserSignIn(options) {
20186
20234
  const receiver = await startLoopbackReceiver({
20187
20235
  port: options.port ?? gotrueCallbackPort(),
20188
20236
  pageUrl: options.pageUrl,
20189
- redeemCode: (code) => gotrueToken(options.authUrl, "pkce", {
20190
- auth_code: code,
20191
- code_verifier: verifier
20192
- }),
20193
- redeemRefreshToken: (refreshToken) => gotrueToken(options.authUrl, "refresh_token", {
20194
- refresh_token: refreshToken
20195
- })
20237
+ redeemCode: (code, signal) => gotrueToken(
20238
+ options.authUrl,
20239
+ "pkce",
20240
+ { auth_code: code, code_verifier: verifier },
20241
+ signal
20242
+ ),
20243
+ redeemRefreshToken: (refreshToken, signal) => gotrueToken(
20244
+ options.authUrl,
20245
+ "refresh_token",
20246
+ { refresh_token: refreshToken },
20247
+ signal
20248
+ )
20196
20249
  });
20197
20250
  let url;
20198
20251
  if (options.oauthProvider) {
@@ -20210,7 +20263,12 @@ async function startBrowserSignIn(options) {
20210
20263
  page.searchParams.set("state", receiver.state);
20211
20264
  url = page.toString();
20212
20265
  }
20213
- return { url, done: receiver.done.finally(receiver.close) };
20266
+ return {
20267
+ url,
20268
+ done: receiver.done.finally(receiver.close),
20269
+ pasteRedirect: receiver.pasteRedirect,
20270
+ cancel: receiver.cancel
20271
+ };
20214
20272
  }
20215
20273
  var BEARER_TYPE_HEADER, IDENTITY_BEARER_TYPE, IDENTITY_AUTH_TYPE, GOTRUE_OAUTH_PROVIDERS, LEGACY_SIGN_IN_MESSAGE, base64url, OAUTH_SIGN_IN_TIMEOUT_MS, MAX_FORM_BYTES;
20216
20274
  var init_identity = __esm({
@@ -23063,10 +23121,10 @@ var require_adm_zip = __commonJS({
23063
23121
  * @param {function|string} [props.namefix] - optional function to help fix filename
23064
23122
  */
23065
23123
  addLocalFolderPromise: function(localPath2, props) {
23066
- return new Promise((resolve5, reject) => {
23124
+ return new Promise((resolve6, reject) => {
23067
23125
  this.addLocalFolderAsync2(Object.assign({ localPath: localPath2 }, props), (err, done) => {
23068
23126
  if (err) reject(err);
23069
- if (done) resolve5(this);
23127
+ if (done) resolve6(this);
23070
23128
  });
23071
23129
  });
23072
23130
  },
@@ -23253,12 +23311,12 @@ var require_adm_zip = __commonJS({
23253
23311
  keepOriginalPermission = get_Bool(false, keepOriginalPermission);
23254
23312
  overwrite = get_Bool(false, overwrite);
23255
23313
  if (!callback) {
23256
- return new Promise((resolve5, reject) => {
23314
+ return new Promise((resolve6, reject) => {
23257
23315
  this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function(err) {
23258
23316
  if (err) {
23259
23317
  reject(err);
23260
23318
  } else {
23261
- resolve5(this);
23319
+ resolve6(this);
23262
23320
  }
23263
23321
  });
23264
23322
  });
@@ -23356,11 +23414,11 @@ var require_adm_zip = __commonJS({
23356
23414
  */
23357
23415
  writeZipPromise: function(targetFileName, props) {
23358
23416
  const { overwrite, perm } = Object.assign({ overwrite: true }, props);
23359
- return new Promise((resolve5, reject) => {
23417
+ return new Promise((resolve6, reject) => {
23360
23418
  if (!targetFileName && opts.filename) targetFileName = opts.filename;
23361
23419
  if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing");
23362
23420
  this.toBufferPromise().then((zipData) => {
23363
- const ret = (done) => done ? resolve5(done) : reject("ADM-ZIP: Wasn't able to write zip file");
23421
+ const ret = (done) => done ? resolve6(done) : reject("ADM-ZIP: Wasn't able to write zip file");
23364
23422
  filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
23365
23423
  }, reject);
23366
23424
  });
@@ -23369,8 +23427,8 @@ var require_adm_zip = __commonJS({
23369
23427
  * @returns {Promise<Buffer>} A promise to the Buffer.
23370
23428
  */
23371
23429
  toBufferPromise: function() {
23372
- return new Promise((resolve5, reject) => {
23373
- _zip.toAsyncBuffer(resolve5, reject);
23430
+ return new Promise((resolve6, reject) => {
23431
+ _zip.toAsyncBuffer(resolve6, reject);
23374
23432
  });
23375
23433
  },
23376
23434
  /**
@@ -23488,12 +23546,12 @@ var require_isexe = __commonJS({
23488
23546
  if (typeof Promise !== "function") {
23489
23547
  throw new TypeError("callback not provided");
23490
23548
  }
23491
- return new Promise(function(resolve5, reject) {
23549
+ return new Promise(function(resolve6, reject) {
23492
23550
  isexe(path13, options || {}, function(er, is) {
23493
23551
  if (er) {
23494
23552
  reject(er);
23495
23553
  } else {
23496
- resolve5(is);
23554
+ resolve6(is);
23497
23555
  }
23498
23556
  });
23499
23557
  });
@@ -23559,27 +23617,27 @@ var require_which = __commonJS({
23559
23617
  opt = {};
23560
23618
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
23561
23619
  const found = [];
23562
- const step = (i2) => new Promise((resolve5, reject) => {
23620
+ const step = (i2) => new Promise((resolve6, reject) => {
23563
23621
  if (i2 === pathEnv.length)
23564
- return opt.all && found.length ? resolve5(found) : reject(getNotFoundError(cmd));
23622
+ return opt.all && found.length ? resolve6(found) : reject(getNotFoundError(cmd));
23565
23623
  const ppRaw = pathEnv[i2];
23566
23624
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
23567
23625
  const pCmd = path13.join(pathPart, cmd);
23568
23626
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
23569
- resolve5(subStep(p, i2, 0));
23627
+ resolve6(subStep(p, i2, 0));
23570
23628
  });
23571
- const subStep = (p, i2, ii) => new Promise((resolve5, reject) => {
23629
+ const subStep = (p, i2, ii) => new Promise((resolve6, reject) => {
23572
23630
  if (ii === pathExt.length)
23573
- return resolve5(step(i2 + 1));
23631
+ return resolve6(step(i2 + 1));
23574
23632
  const ext = pathExt[ii];
23575
23633
  isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
23576
23634
  if (!er && is) {
23577
23635
  if (opt.all)
23578
23636
  found.push(p + ext);
23579
23637
  else
23580
- return resolve5(p + ext);
23638
+ return resolve6(p + ext);
23581
23639
  }
23582
- return resolve5(subStep(p, i2, ii + 1));
23640
+ return resolve6(subStep(p, i2, ii + 1));
23583
23641
  });
23584
23642
  });
23585
23643
  return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
@@ -23891,6 +23949,203 @@ var require_cross_spawn = __commonJS({
23891
23949
  }
23892
23950
  });
23893
23951
 
23952
+ // src/mcp/auth/second_factor.ts
23953
+ function askHidden(prompt, input = process.stdin, output = process.stdout) {
23954
+ return new Promise((resolve6, reject) => {
23955
+ const raw = Boolean(input.isTTY && input.setRawMode);
23956
+ let typed = "";
23957
+ const finish = (settle) => {
23958
+ input.removeListener("data", onData);
23959
+ input.removeListener("end", onEnd);
23960
+ if (raw) input.setRawMode?.(false);
23961
+ input.pause();
23962
+ output.write("\n");
23963
+ settle();
23964
+ };
23965
+ const onData = (chunk) => {
23966
+ for (const ch of chunk.toString()) {
23967
+ if (ch === "\r" || ch === "\n") return finish(() => resolve6(typed));
23968
+ if (ch === "") {
23969
+ return finish(() => reject(new Error("Sign-in cancelled.")));
23970
+ }
23971
+ if (ch === "" && !typed) {
23972
+ return finish(() => reject(new Error(INPUT_ENDED_MESSAGE)));
23973
+ }
23974
+ if (ch === "\x7F" || ch === "\b") typed = typed.slice(0, -1);
23975
+ else typed += ch;
23976
+ }
23977
+ };
23978
+ const onEnd = () => finish(() => reject(new Error(INPUT_ENDED_MESSAGE)));
23979
+ if (raw) input.setRawMode?.(true);
23980
+ output.write(prompt);
23981
+ input.on("data", onData);
23982
+ input.on("end", onEnd);
23983
+ input.resume();
23984
+ });
23985
+ }
23986
+ function maskEmail(address) {
23987
+ const at = address.lastIndexOf("@");
23988
+ if (at < 1) return "your email address";
23989
+ return `${address[0]}***${address.slice(at)}`;
23990
+ }
23991
+ async function gotrueJson(url, init) {
23992
+ const res = await fetch(url, {
23993
+ method: init.method,
23994
+ headers: {
23995
+ Authorization: `Bearer ${init.accessToken}`,
23996
+ "Content-Type": "application/json",
23997
+ [CLIENT_INFO_HEADER]: CLIENT_INFO
23998
+ },
23999
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
24000
+ });
24001
+ const text = await res.text();
24002
+ let data = {};
24003
+ try {
24004
+ const parsed = text ? JSON.parse(text) : {};
24005
+ if (parsed && typeof parsed === "object") {
24006
+ data = parsed;
24007
+ }
24008
+ } catch {
24009
+ }
24010
+ return { status: res.status, data };
24011
+ }
24012
+ function failure(step, status, data) {
24013
+ return new Error(
24014
+ `${step} failed: ${gotrueErrorMessage(data, `HTTP ${status}`)}`
24015
+ );
24016
+ }
24017
+ function signedInIndependently(accessToken) {
24018
+ const amr = decodeJwtPayload(accessToken)?.amr;
24019
+ return Array.isArray(amr) && amr.some(
24020
+ (entry) => typeof entry === "object" && entry !== null && INDEPENDENT_FIRST_FACTORS.has(
24021
+ String(entry.method)
24022
+ )
24023
+ );
24024
+ }
24025
+ function chooseFactor(factors, accessToken) {
24026
+ const verified = factors.filter((f) => f.status === "verified");
24027
+ if (verified.length === 0) return null;
24028
+ const owed = verified.filter((f) => f.factor_type !== "recovery_code");
24029
+ const totp = owed.find((f) => f.factor_type === "totp");
24030
+ if (totp) return totp;
24031
+ const email2 = owed.find((f) => f.factor_type === "email");
24032
+ const onlyEmail = verified.every((f) => f.factor_type === "email");
24033
+ if (email2 && (onlyEmail || signedInIndependently(accessToken))) return email2;
24034
+ throw new Error(UNSUPPORTED_MESSAGE);
24035
+ }
24036
+ async function stepUpSecondFactor(source, tokens, io) {
24037
+ if (decodeJwtPayload(tokens.idToken)?.aal !== "aal1") return tokens;
24038
+ const accessToken = tokens.idToken;
24039
+ const user = await gotrueJson(`${source.authUrl}/user`, {
24040
+ method: "GET",
24041
+ accessToken
24042
+ });
24043
+ if (!succeeded(user.status)) {
24044
+ throw failure(
24045
+ "Reading the account's second factors",
24046
+ user.status,
24047
+ user.data
24048
+ );
24049
+ }
24050
+ const factor = chooseFactor(
24051
+ Array.isArray(user.data.factors) ? user.data.factors : [],
24052
+ accessToken
24053
+ );
24054
+ if (!factor) return tokens;
24055
+ const interactive = io.interactive ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY));
24056
+ if (!interactive) throw new Error(NO_TERMINAL_MESSAGE);
24057
+ const ask = io.ask ?? ((prompt2) => askHidden(prompt2));
24058
+ const address = typeof user.data.email === "string" ? user.data.email : tokens.email;
24059
+ const prompt = factor.factor_type === "email" ? `Enter the code we emailed to ${address ? maskEmail(address) : "your email address"}: ` : "Enter the 6-digit code from your authenticator app: ";
24060
+ const factorUrl = `${source.authUrl}/factors/${encodeURIComponent(factor.id)}`;
24061
+ io.print("This account has a second factor.");
24062
+ let wrongCodes = 0;
24063
+ for (let challenges = 0; challenges < MAX_CHALLENGES; challenges++) {
24064
+ const challenge = await gotrueJson(`${factorUrl}/challenge`, {
24065
+ method: "POST",
24066
+ accessToken,
24067
+ body: {}
24068
+ });
24069
+ const challengeId = challenge.data.id;
24070
+ if (!succeeded(challenge.status) || typeof challengeId !== "string") {
24071
+ throw failure(
24072
+ "Starting the second-factor challenge",
24073
+ challenge.status,
24074
+ challenge.data
24075
+ );
24076
+ }
24077
+ if (factor.factor_type === "email") io.print("We emailed you a code.");
24078
+ for (; ; ) {
24079
+ const code = (await ask(prompt)).replace(/\s+/g, "");
24080
+ if (!/^\d+$/.test(code)) {
24081
+ io.print("The code is digits only. Try again.");
24082
+ continue;
24083
+ }
24084
+ const verified = await gotrueJson(`${factorUrl}/verify`, {
24085
+ method: "POST",
24086
+ accessToken,
24087
+ body: { challenge_id: challengeId, code }
24088
+ });
24089
+ if (succeeded(verified.status)) {
24090
+ const { access_token, refresh_token } = verified.data;
24091
+ if (typeof access_token !== "string" || typeof refresh_token !== "string") {
24092
+ throw new Error(
24093
+ "Second-factor verification: response missing access or refresh token"
24094
+ );
24095
+ }
24096
+ const verifiedUser = verified.data.user;
24097
+ return {
24098
+ idToken: access_token,
24099
+ refreshToken: refresh_token,
24100
+ email: verifiedUser?.email ?? tokens.email
24101
+ };
24102
+ }
24103
+ if (verified.data.error_code === "mfa_challenge_expired") {
24104
+ io.print("That code expired. Sending a new one.");
24105
+ break;
24106
+ }
24107
+ if (isWrongCode(verified.status, verified.data)) {
24108
+ if (++wrongCodes >= MAX_CODE_ATTEMPTS) {
24109
+ throw new Error(
24110
+ "Too many incorrect codes. Run `inworld login` to try again."
24111
+ );
24112
+ }
24113
+ io.print("That code is not correct. Try again.");
24114
+ continue;
24115
+ }
24116
+ throw failure(
24117
+ "Second-factor verification",
24118
+ verified.status,
24119
+ verified.data
24120
+ );
24121
+ }
24122
+ }
24123
+ throw new Error(
24124
+ "The second-factor code expired too many times. Run `inworld login` to try again."
24125
+ );
24126
+ }
24127
+ var MAX_CODE_ATTEMPTS, MAX_CHALLENGES, NO_TERMINAL_MESSAGE, UNSUPPORTED_MESSAGE, INPUT_ENDED_MESSAGE, succeeded, isWrongCode, INDEPENDENT_FIRST_FACTORS;
24128
+ var init_second_factor = __esm({
24129
+ "src/mcp/auth/second_factor.ts"() {
24130
+ "use strict";
24131
+ init_client_info();
24132
+ init_identity();
24133
+ MAX_CODE_ATTEMPTS = 5;
24134
+ MAX_CHALLENGES = 5;
24135
+ NO_TERMINAL_MESSAGE = "This account needs a second-factor code; run `inworld login` in an interactive terminal.";
24136
+ UNSUPPORTED_MESSAGE = "This account's second factor cannot be completed in the CLI after this sign-in. Set up an authenticator app in your Inworld account settings and run `inworld login` again, or contact support.";
24137
+ INPUT_ENDED_MESSAGE = "Input ended before a code was entered.";
24138
+ succeeded = (status) => status >= 200 && status < 300;
24139
+ isWrongCode = (status, data) => data.error_code === "mfa_verification_failed" || status === 422 && !data.error_code;
24140
+ INDEPENDENT_FIRST_FACTORS = /* @__PURE__ */ new Set([
24141
+ "password",
24142
+ "sso/saml",
24143
+ "passkey",
24144
+ "web3"
24145
+ ]);
24146
+ }
24147
+ });
24148
+
23894
24149
  // src/mcp/auth/browser.ts
23895
24150
  import { execFile } from "node:child_process";
23896
24151
  import { promisify as promisify4 } from "node:util";
@@ -23911,6 +24166,78 @@ var init_browser = __esm({
23911
24166
  }
23912
24167
  });
23913
24168
 
24169
+ // src/mcp/auth/sign_in_prompt.ts
24170
+ import * as readline2 from "node:readline";
24171
+ async function promptForSignIn(signIn2, out) {
24172
+ const { url, done, pasteRedirect, cancel } = signIn2;
24173
+ const printLink2 = out.printLink ?? out.print;
24174
+ const printError2 = out.printError ?? out.print;
24175
+ out.print("Please visit the following URL to authenticate:");
24176
+ printLink2(url);
24177
+ out.print("");
24178
+ out.print(
24179
+ "Browser on another machine? Sign in there with Google, GitHub, Microsoft or SSO. It then fails to load an http://127.0.0.1 address: copy that address and paste it here. Email sign-in needs a browser on this machine."
24180
+ );
24181
+ out.print("");
24182
+ const terminal = readline2.createInterface({
24183
+ input: process.stdin,
24184
+ output: out.output
24185
+ });
24186
+ let closed = false;
24187
+ let opened = false;
24188
+ terminal.on("close", () => {
24189
+ closed = true;
24190
+ });
24191
+ terminal.on("SIGINT", () => {
24192
+ cancel();
24193
+ terminal.close();
24194
+ });
24195
+ const ask = (prompt) => {
24196
+ if (closed) return;
24197
+ terminal.setPrompt(prompt);
24198
+ terminal.prompt();
24199
+ };
24200
+ terminal.on("line", async (line) => {
24201
+ const address = line.trim();
24202
+ if (!address) {
24203
+ if (!opened) {
24204
+ opened = true;
24205
+ try {
24206
+ await openInBrowser(url);
24207
+ out.print("\u2713 Browser opened");
24208
+ } catch {
24209
+ out.print(
24210
+ "\u26A0 Could not open browser automatically. Please open the URL manually."
24211
+ );
24212
+ }
24213
+ out.print("");
24214
+ out.print("Waiting for authentication...");
24215
+ }
24216
+ ask("Paste the address here if the browser could not load it: ");
24217
+ return;
24218
+ }
24219
+ if (pasteRedirect(address)) {
24220
+ out.print("Finishing sign-in...");
24221
+ terminal.close();
24222
+ return;
24223
+ }
24224
+ printError2(
24225
+ "That is not this sign-in's address. Paste the whole address from the browser's address bar; it starts with http://127.0.0.1:"
24226
+ );
24227
+ ask("Paste the address: ");
24228
+ });
24229
+ ask("Press Enter to open your browser, or paste the address: ");
24230
+ await done.catch(() => {
24231
+ });
24232
+ terminal.close();
24233
+ }
24234
+ var init_sign_in_prompt = __esm({
24235
+ "src/mcp/auth/sign_in_prompt.ts"() {
24236
+ "use strict";
24237
+ init_browser();
24238
+ }
24239
+ });
24240
+
23914
24241
  // ../../node_modules/ms/index.js
23915
24242
  var require_ms = __commonJS({
23916
24243
  "../../node_modules/ms/index.js"(exports, module) {
@@ -24681,12 +25008,12 @@ var require_promisify = __commonJS({
24681
25008
  Object.defineProperty(exports, "__esModule", { value: true });
24682
25009
  function promisify5(fn) {
24683
25010
  return function(req, opts) {
24684
- return new Promise((resolve5, reject) => {
25011
+ return new Promise((resolve6, reject) => {
24685
25012
  fn.call(this, req, opts, (err, rtn) => {
24686
25013
  if (err) {
24687
25014
  reject(err);
24688
25015
  } else {
24689
- resolve5(rtn);
25016
+ resolve6(rtn);
24690
25017
  }
24691
25018
  });
24692
25019
  });
@@ -24890,7 +25217,7 @@ var require_parse_proxy_response = __commonJS({
24890
25217
  var debug_1 = __importDefault(require_src());
24891
25218
  var debug = debug_1.default("https-proxy-agent:parse-proxy-response");
24892
25219
  function parseProxyResponse(socket) {
24893
- return new Promise((resolve5, reject) => {
25220
+ return new Promise((resolve6, reject) => {
24894
25221
  let buffersLength = 0;
24895
25222
  const buffers = [];
24896
25223
  function read() {
@@ -24930,7 +25257,7 @@ var require_parse_proxy_response = __commonJS({
24930
25257
  const firstLine = buffered.toString("ascii", 0, buffered.indexOf("\r\n"));
24931
25258
  const statusCode = +firstLine.split(" ")[1];
24932
25259
  debug("got proxy server response: %o", firstLine);
24933
- resolve5({
25260
+ resolve6({
24934
25261
  statusCode,
24935
25262
  buffered
24936
25263
  });
@@ -24951,11 +25278,11 @@ var require_agent = __commonJS({
24951
25278
  "use strict";
24952
25279
  var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
24953
25280
  function adopt(value) {
24954
- return value instanceof P ? value : new P(function(resolve5) {
24955
- resolve5(value);
25281
+ return value instanceof P ? value : new P(function(resolve6) {
25282
+ resolve6(value);
24956
25283
  });
24957
25284
  }
24958
- return new (P || (P = Promise))(function(resolve5, reject) {
25285
+ return new (P || (P = Promise))(function(resolve6, reject) {
24959
25286
  function fulfilled(value) {
24960
25287
  try {
24961
25288
  step(generator.next(value));
@@ -24971,7 +25298,7 @@ var require_agent = __commonJS({
24971
25298
  }
24972
25299
  }
24973
25300
  function step(result) {
24974
- result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
25301
+ result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
24975
25302
  }
24976
25303
  step((generator = generator.apply(thisArg, _arguments || [])).next());
24977
25304
  });
@@ -30735,10 +31062,10 @@ var require_raw_body = __commonJS({
30735
31062
  if (done) {
30736
31063
  return readStream(stream, encoding, length, limit, wrap(done));
30737
31064
  }
30738
- return new Promise(function executor(resolve5, reject) {
31065
+ return new Promise(function executor(resolve6, reject) {
30739
31066
  readStream(stream, encoding, length, limit, function onRead2(err, buf) {
30740
31067
  if (err) return reject(err);
30741
- resolve5(buf);
31068
+ resolve6(buf);
30742
31069
  });
30743
31070
  });
30744
31071
  }
@@ -44073,7 +44400,7 @@ var require_view = __commonJS({
44073
44400
  var basename2 = path13.basename;
44074
44401
  var extname2 = path13.extname;
44075
44402
  var join6 = path13.join;
44076
- var resolve5 = path13.resolve;
44403
+ var resolve6 = path13.resolve;
44077
44404
  module.exports = View;
44078
44405
  function View(name, options) {
44079
44406
  var opts = options || {};
@@ -44107,7 +44434,7 @@ var require_view = __commonJS({
44107
44434
  debug('lookup "%s"', name);
44108
44435
  for (var i2 = 0; i2 < roots.length && !path14; i2++) {
44109
44436
  var root = roots[i2];
44110
- var loc = resolve5(root, name);
44437
+ var loc = resolve6(root, name);
44111
44438
  var dir = dirname3(loc);
44112
44439
  var file = basename2(loc);
44113
44440
  path14 = this.resolve(dir, file);
@@ -44132,7 +44459,7 @@ var require_view = __commonJS({
44132
44459
  });
44133
44460
  sync = false;
44134
44461
  };
44135
- View.prototype.resolve = function resolve6(dir, file) {
44462
+ View.prototype.resolve = function resolve7(dir, file) {
44136
44463
  var ext = this.ext;
44137
44464
  var path14 = join6(dir, file);
44138
44465
  var stat2 = tryStat(path14);
@@ -46287,7 +46614,7 @@ var require_application = __commonJS({
46287
46614
  var compileETag = require_utils6().compileETag;
46288
46615
  var compileQueryParser = require_utils6().compileQueryParser;
46289
46616
  var compileTrust = require_utils6().compileTrust;
46290
- var resolve5 = __require("node:path").resolve;
46617
+ var resolve6 = __require("node:path").resolve;
46291
46618
  var once9 = require_once();
46292
46619
  var Router = require_router();
46293
46620
  var slice = Array.prototype.slice;
@@ -46341,7 +46668,7 @@ var require_application = __commonJS({
46341
46668
  this.mountpath = "/";
46342
46669
  this.locals.settings = this.settings;
46343
46670
  this.set("view", View);
46344
- this.set("views", resolve5("views"));
46671
+ this.set("views", resolve6("views"));
46345
46672
  this.set("jsonp callback name", "callback");
46346
46673
  if (env3 === "production") {
46347
46674
  this.enable("view cache");
@@ -47846,7 +48173,7 @@ var require_send = __commonJS({
47846
48173
  var extname2 = path13.extname;
47847
48174
  var join6 = path13.join;
47848
48175
  var normalize = path13.normalize;
47849
- var resolve5 = path13.resolve;
48176
+ var resolve6 = path13.resolve;
47850
48177
  var sep = path13.sep;
47851
48178
  var BYTES_RANGE_REGEXP = /^ *bytes=/;
47852
48179
  var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
@@ -47875,7 +48202,7 @@ var require_send = __commonJS({
47875
48202
  this._maxage = opts.maxAge || opts.maxage;
47876
48203
  this._maxage = typeof this._maxage === "string" ? ms(this._maxage) : Number(this._maxage);
47877
48204
  this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0;
47878
- this._root = opts.root ? resolve5(opts.root) : null;
48205
+ this._root = opts.root ? resolve6(opts.root) : null;
47879
48206
  }
47880
48207
  util2.inherits(SendStream, Stream);
47881
48208
  SendStream.prototype.error = function error2(status, err) {
@@ -48024,7 +48351,7 @@ var require_send = __commonJS({
48024
48351
  return res;
48025
48352
  }
48026
48353
  parts = normalize(path14).split(sep);
48027
- path14 = resolve5(path14);
48354
+ path14 = resolve6(path14);
48028
48355
  }
48029
48356
  if (containsDotFile(parts)) {
48030
48357
  debug('%s dotfile "%s"', this._dotfiles, path14);
@@ -48402,7 +48729,7 @@ var require_response = __commonJS({
48402
48729
  var cookie = require_cookie();
48403
48730
  var send = require_send();
48404
48731
  var extname2 = path13.extname;
48405
- var resolve5 = path13.resolve;
48732
+ var resolve6 = path13.resolve;
48406
48733
  var vary = require_vary();
48407
48734
  var { Buffer: Buffer5 } = __require("node:buffer");
48408
48735
  var res = Object.create(http2.ServerResponse.prototype);
@@ -48608,7 +48935,7 @@ var require_response = __commonJS({
48608
48935
  }
48609
48936
  opts = Object.create(opts);
48610
48937
  opts.headers = headers;
48611
- var fullPath = !opts.root ? resolve5(path14) : path14;
48938
+ var fullPath = !opts.root ? resolve6(path14) : path14;
48612
48939
  return this.sendFile(fullPath, opts, done);
48613
48940
  };
48614
48941
  res.contentType = res.type = function contentType(type) {
@@ -48857,7 +49184,7 @@ var require_serve_static = __commonJS({
48857
49184
  var encodeUrl = require_encodeurl();
48858
49185
  var escapeHtml = require_escape_html();
48859
49186
  var parseUrl = require_parseurl();
48860
- var resolve5 = __require("path").resolve;
49187
+ var resolve6 = __require("path").resolve;
48861
49188
  var send = require_send();
48862
49189
  var url = __require("url");
48863
49190
  module.exports = serveStatic;
@@ -48876,7 +49203,7 @@ var require_serve_static = __commonJS({
48876
49203
  throw new TypeError("option setHeaders must be function");
48877
49204
  }
48878
49205
  opts.maxage = opts.maxage || opts.maxAge || 0;
48879
- opts.root = resolve5(root);
49206
+ opts.root = resolve6(root);
48880
49207
  var onDirectory = redirect ? createRedirectDirectoryListener() : createNotFoundDirectoryListener();
48881
49208
  return function serveStatic2(req, res, next) {
48882
49209
  if (req.method !== "GET" && req.method !== "HEAD") {
@@ -61839,7 +62166,7 @@ var init_protocol = __esm({
61839
62166
  return;
61840
62167
  }
61841
62168
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
61842
- await new Promise((resolve5) => setTimeout(resolve5, pollInterval));
62169
+ await new Promise((resolve6) => setTimeout(resolve6, pollInterval));
61843
62170
  options?.signal?.throwIfAborted();
61844
62171
  }
61845
62172
  } catch (error2) {
@@ -61856,7 +62183,7 @@ var init_protocol = __esm({
61856
62183
  */
61857
62184
  request(request, resultSchema, options) {
61858
62185
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
61859
- return new Promise((resolve5, reject) => {
62186
+ return new Promise((resolve6, reject) => {
61860
62187
  const earlyReject = (error2) => {
61861
62188
  reject(error2);
61862
62189
  };
@@ -61934,7 +62261,7 @@ var init_protocol = __esm({
61934
62261
  if (!parseResult.success) {
61935
62262
  reject(parseResult.error);
61936
62263
  } else {
61937
- resolve5(parseResult.data);
62264
+ resolve6(parseResult.data);
61938
62265
  }
61939
62266
  } catch (error2) {
61940
62267
  reject(error2);
@@ -62195,12 +62522,12 @@ var init_protocol = __esm({
62195
62522
  }
62196
62523
  } catch {
62197
62524
  }
62198
- return new Promise((resolve5, reject) => {
62525
+ return new Promise((resolve6, reject) => {
62199
62526
  if (signal.aborted) {
62200
62527
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
62201
62528
  return;
62202
62529
  }
62203
- const timeoutId = setTimeout(resolve5, interval);
62530
+ const timeoutId = setTimeout(resolve6, interval);
62204
62531
  signal.addEventListener("abort", () => {
62205
62532
  clearTimeout(timeoutId);
62206
62533
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -65192,7 +65519,7 @@ var require_compile3 = __commonJS({
65192
65519
  const schOrFunc = root.refs[ref];
65193
65520
  if (schOrFunc)
65194
65521
  return schOrFunc;
65195
- let _sch = resolve5.call(this, root, ref);
65522
+ let _sch = resolve6.call(this, root, ref);
65196
65523
  if (_sch === void 0) {
65197
65524
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
65198
65525
  const { schemaId } = this.opts;
@@ -65219,7 +65546,7 @@ var require_compile3 = __commonJS({
65219
65546
  function sameSchemaEnv(s1, s2) {
65220
65547
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
65221
65548
  }
65222
- function resolve5(root, ref) {
65549
+ function resolve6(root, ref) {
65223
65550
  let sch;
65224
65551
  while (typeof (sch = this.refs[ref]) == "string")
65225
65552
  ref = sch;
@@ -69109,7 +69436,7 @@ var init_mcp = __esm({
69109
69436
  let task = createTaskResult.task;
69110
69437
  const pollInterval = task.pollInterval ?? 5e3;
69111
69438
  while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
69112
- await new Promise((resolve5) => setTimeout(resolve5, pollInterval));
69439
+ await new Promise((resolve6) => setTimeout(resolve6, pollInterval));
69113
69440
  const updatedTask = await extra.taskStore.getTask(taskId);
69114
69441
  if (!updatedTask) {
69115
69442
  throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
@@ -69703,12 +70030,12 @@ var init_stdio2 = __esm({
69703
70030
  this.onclose?.();
69704
70031
  }
69705
70032
  send(message) {
69706
- return new Promise((resolve5) => {
70033
+ return new Promise((resolve6) => {
69707
70034
  const json = serializeMessage(message);
69708
70035
  if (this._stdout.write(json)) {
69709
- resolve5();
70036
+ resolve6();
69710
70037
  } else {
69711
- this._stdout.once("drain", resolve5);
70038
+ this._stdout.once("drain", resolve6);
69712
70039
  }
69713
70040
  });
69714
70041
  }
@@ -70212,7 +70539,7 @@ var init_dist5 = __esm({
70212
70539
  });
70213
70540
  if (!chunk) {
70214
70541
  if (i2 === 1) {
70215
- await new Promise((resolve5) => setTimeout(resolve5));
70542
+ await new Promise((resolve6) => setTimeout(resolve6));
70216
70543
  maxReadCount = 3;
70217
70544
  continue;
70218
70545
  }
@@ -70718,9 +71045,9 @@ data:
70718
71045
  const initRequest = messages.find((m) => isInitializeRequest(m));
70719
71046
  const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION;
70720
71047
  if (this._enableJsonResponse) {
70721
- return new Promise((resolve5) => {
71048
+ return new Promise((resolve6) => {
70722
71049
  this._streamMapping.set(streamId, {
70723
- resolveJson: resolve5,
71050
+ resolveJson: resolve6,
70724
71051
  cleanup: () => {
70725
71052
  this._streamMapping.delete(streamId);
70726
71053
  }
@@ -71940,7 +72267,7 @@ var init_api2 = __esm({
71940
72267
 
71941
72268
  // src/mcp/runtime/register.ts
71942
72269
  import { mkdir as mkdir2, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
71943
- import { dirname as dirname2, resolve as resolve2 } from "node:path";
72270
+ import { dirname as dirname2, resolve as resolve3 } from "node:path";
71944
72271
  function extensionForEncoding(encoding) {
71945
72272
  const map = {
71946
72273
  MP3: ".mp3",
@@ -72089,7 +72416,7 @@ function registerRuntimeTools(server) {
72089
72416
  method: "POST",
72090
72417
  body: JSON.stringify(body)
72091
72418
  });
72092
- let filePath = resolve2(output_file);
72419
+ let filePath = resolve3(output_file);
72093
72420
  if (!filePath.match(/\.\w{2,5}$/)) {
72094
72421
  filePath += extensionForEncoding(audio_encoding);
72095
72422
  }
@@ -72154,7 +72481,7 @@ function registerRuntimeTools(server) {
72154
72481
  prompts
72155
72482
  }) => {
72156
72483
  try {
72157
- const filePath = resolve2(input_file);
72484
+ const filePath = resolve3(input_file);
72158
72485
  const audioBytes = await readFile4(filePath);
72159
72486
  const audioBase64 = audioBytes.toString("base64");
72160
72487
  const transcribeConfig = {
@@ -72251,7 +72578,7 @@ function registerRuntimeTools(server) {
72251
72578
  try {
72252
72579
  const voiceSamples = await Promise.all(
72253
72580
  audio_files.map(async (filePath, i2) => {
72254
- const audioBytes = await readFile4(resolve2(filePath));
72581
+ const audioBytes = await readFile4(resolve3(filePath));
72255
72582
  const sample = {
72256
72583
  audioData: audioBytes.toString("base64")
72257
72584
  };
@@ -72339,7 +72666,7 @@ function registerRuntimeTools(server) {
72339
72666
  previewText: v.previewText
72340
72667
  };
72341
72668
  if (preview_output_dir) {
72342
- const dir = resolve2(preview_output_dir);
72669
+ const dir = resolve3(preview_output_dir);
72343
72670
  await mkdir2(dir, { recursive: true });
72344
72671
  const filePath = `${dir}/${v.voiceId}.mp3`;
72345
72672
  await writeFile4(filePath, Buffer.from(v.previewAudio, "base64"));
@@ -72472,7 +72799,7 @@ function registerRuntimeTools(server) {
72472
72799
  "No audio in response. Provider/router may not support audio output, or 'voice' is not a valid id."
72473
72800
  );
72474
72801
  }
72475
- const filePath = resolve2(output_file);
72802
+ const filePath = resolve3(output_file);
72476
72803
  await mkdir2(dirname2(filePath), { recursive: true });
72477
72804
  await writeFile4(filePath, Buffer.from(audio.data, "base64"));
72478
72805
  return textResult({
@@ -72903,39 +73230,6 @@ var init_schemas4 = __esm({
72903
73230
  });
72904
73231
 
72905
73232
  // src/mcp/cli/login.ts
72906
- import * as readline5 from "node:readline";
72907
- async function offerBrowser2(url, done) {
72908
- console.error("Please visit the following URL to authenticate:");
72909
- console.error(url);
72910
- console.error();
72911
- const readlineInterface = readline5.createInterface({
72912
- input: process.stdin,
72913
- output: process.stdout
72914
- });
72915
- const enter = new Promise((resolve5) => {
72916
- readlineInterface.question(
72917
- "Press Enter to open your browser...",
72918
- () => resolve5("enter")
72919
- );
72920
- });
72921
- const settled = done.then(
72922
- () => "done",
72923
- () => "done"
72924
- );
72925
- const first = await Promise.race([enter, settled]);
72926
- readlineInterface.close();
72927
- if (first === "done") return;
72928
- try {
72929
- await openInBrowser(url);
72930
- console.error("Browser opened.");
72931
- } catch {
72932
- console.error(
72933
- "Could not open browser automatically. Open the URL manually."
72934
- );
72935
- }
72936
- console.error();
72937
- console.error("Waiting for authentication...");
72938
- }
72939
73233
  async function runLogin() {
72940
73234
  const source = await resolveIdentitySource(PLATFORM_URL2);
72941
73235
  const oauthProvider = process.env.INWORLD_AUTH_OAUTH_PROVIDER || void 0;
@@ -72944,14 +73238,19 @@ async function runLogin() {
72944
73238
  `INWORLD_AUTH_OAUTH_PROVIDER=${oauthProvider} is not supported by inworld-mcp login (use ${GOTRUE_OAUTH_PROVIDERS.join(", ")}, or unset it to choose on the sign-in page).`
72945
73239
  );
72946
73240
  }
72947
- const { url, done } = await startBrowserSignIn({
73241
+ const signIn2 = await startBrowserSignIn({
72948
73242
  authUrl: source.authUrl,
72949
73243
  pageUrl: INWORLD_CLI_AUTH_URL2,
72950
73244
  version: CLI_VERSION,
72951
73245
  oauthProvider
72952
73246
  });
72953
- await offerBrowser2(url, done);
72954
- const tokens = await done;
73247
+ await promptForSignIn(signIn2, {
73248
+ print: (line) => console.error(line),
73249
+ output: process.stdout
73250
+ });
73251
+ const tokens = await stepUpSecondFactor(source, await signIn2.done, {
73252
+ print: (line) => console.error(line)
73253
+ });
72955
73254
  console.error();
72956
73255
  console.error("Exchanging for Inworld session...");
72957
73256
  const exchanged = await exchangeIdentityToken(tokens.idToken);
@@ -72988,12 +73287,13 @@ var init_login = __esm({
72988
73287
  "use strict";
72989
73288
  init_dist4();
72990
73289
  init_constants5();
72991
- init_browser();
72992
73290
  init_constants6();
72993
73291
  init_exchange();
72994
73292
  init_identity();
72995
73293
  init_paths();
73294
+ init_second_factor();
72996
73295
  init_session();
73296
+ init_sign_in_prompt();
72997
73297
  }
72998
73298
  });
72999
73299
 
@@ -73982,7 +74282,7 @@ async function runHttp() {
73982
74282
  })
73983
74283
  );
73984
74284
  });
73985
- await new Promise((resolve5, reject) => {
74285
+ await new Promise((resolve6, reject) => {
73986
74286
  const httpServer = app.listen(port, host, () => {
73987
74287
  console.error(
73988
74288
  `inworld (Streamable HTTP) at http://${host}:${port}${MCP_PATH}`
@@ -73992,7 +74292,7 @@ async function runHttp() {
73992
74292
  "Listening on all interfaces \u2014 use this machine\u2019s LAN or Tailscale IP from other hosts."
73993
74293
  );
73994
74294
  }
73995
- resolve5();
74295
+ resolve6();
73996
74296
  });
73997
74297
  httpServer.on("error", reject);
73998
74298
  });
@@ -74374,14 +74674,14 @@ __export(audio_player_exports, {
74374
74674
  cleanupTempFile: () => cleanupTempFile,
74375
74675
  playFile: () => playFile
74376
74676
  });
74377
- import { unlink } from "fs/promises";
74677
+ import { unlink as unlink2 } from "fs/promises";
74378
74678
  async function playFile(filePath) {
74379
74679
  try {
74380
74680
  const player = (await Promise.resolve().then(() => __toESM(require_play_sound(), 1))).default();
74381
- await new Promise((resolve5, reject) => {
74681
+ await new Promise((resolve6, reject) => {
74382
74682
  player.play(filePath, (err) => {
74383
74683
  if (err) reject(err);
74384
- else resolve5();
74684
+ else resolve6();
74385
74685
  });
74386
74686
  });
74387
74687
  return true;
@@ -74391,7 +74691,7 @@ async function playFile(filePath) {
74391
74691
  }
74392
74692
  async function cleanupTempFile(filepath) {
74393
74693
  try {
74394
- await unlink(filepath);
74694
+ await unlink2(filepath);
74395
74695
  } catch {
74396
74696
  }
74397
74697
  }
@@ -74844,18 +75144,18 @@ var proto = Object.defineProperties(() => {
74844
75144
  }
74845
75145
  }
74846
75146
  });
74847
- var createStyler = (open2, close, parent) => {
75147
+ var createStyler = (open3, close, parent) => {
74848
75148
  let openAll;
74849
75149
  let closeAll;
74850
75150
  if (parent === void 0) {
74851
- openAll = open2;
75151
+ openAll = open3;
74852
75152
  closeAll = close;
74853
75153
  } else {
74854
- openAll = parent.openAll + open2;
75154
+ openAll = parent.openAll + open3;
74855
75155
  closeAll = close + parent.closeAll;
74856
75156
  }
74857
75157
  return {
74858
- open: open2,
75158
+ open: open3,
74859
75159
  close,
74860
75160
  openAll,
74861
75161
  closeAll,
@@ -75813,7 +76113,7 @@ var TtsSession = class _TtsSession {
75813
76113
  });
75814
76114
  const sampleRateHertz = opts.sampleRateHertz ?? 48e3;
75815
76115
  try {
75816
- await new Promise((resolve5, reject) => {
76116
+ await new Promise((resolve6, reject) => {
75817
76117
  const cleanup = () => {
75818
76118
  clearTimeout(timer);
75819
76119
  ws.removeEventListener("open", onOpen);
@@ -75822,7 +76122,7 @@ var TtsSession = class _TtsSession {
75822
76122
  };
75823
76123
  const onOpen = () => {
75824
76124
  cleanup();
75825
- resolve5();
76125
+ resolve6();
75826
76126
  };
75827
76127
  const onError = (event) => {
75828
76128
  cleanup();
@@ -75992,7 +76292,7 @@ function maskCred(s) {
75992
76292
  return `${s.slice(0, 4)}\u2026${s.slice(-2)} (len=${s.length})`;
75993
76293
  }
75994
76294
  function waitForFrame(ws, predicate, send, idleMs = IDLE_TIMEOUT_MS, deadlineMs = SEGMENT_TIMEOUT_MS) {
75995
- return new Promise((resolve5, reject) => {
76295
+ return new Promise((resolve6, reject) => {
75996
76296
  const cleanup = () => {
75997
76297
  clearTimeout(idle);
75998
76298
  clearTimeout(deadline);
@@ -76012,7 +76312,7 @@ function waitForFrame(ws, predicate, send, idleMs = IDLE_TIMEOUT_MS, deadlineMs
76012
76312
  const r = predicate(frame);
76013
76313
  if (r.done) {
76014
76314
  cleanup();
76015
- resolve5();
76315
+ resolve6();
76016
76316
  } else if (frame.result?.audioChunk?.audioContent) {
76017
76317
  idle.refresh();
76018
76318
  }
@@ -76158,10 +76458,10 @@ function promptInput(prompt, defaultValue) {
76158
76458
  output: process.stdout
76159
76459
  });
76160
76460
  const displayPrompt = defaultValue ? `${prompt} [${defaultValue}]: ` : `${prompt}: `;
76161
- return new Promise((resolve5) => {
76461
+ return new Promise((resolve6) => {
76162
76462
  rl.question(displayPrompt, (answer) => {
76163
76463
  rl.close();
76164
- resolve5(answer.trim() || defaultValue || "");
76464
+ resolve6(answer.trim() || defaultValue || "");
76165
76465
  });
76166
76466
  });
76167
76467
  }
@@ -77163,11 +77463,11 @@ var replacements = Object.entries(specialMainSymbols);
77163
77463
  // ../../node_modules/yoctocolors/base.js
77164
77464
  import tty2 from "node:tty";
77165
77465
  var hasColors = tty2?.WriteStream?.prototype?.hasColors?.() ?? false;
77166
- var format = (open2, close) => {
77466
+ var format = (open3, close) => {
77167
77467
  if (!hasColors) {
77168
77468
  return (input) => input;
77169
77469
  }
77170
- const openCode = `\x1B[${open2}m`;
77470
+ const openCode = `\x1B[${open3}m`;
77171
77471
  const closeCode = `\x1B[${close}m`;
77172
77472
  return (input) => {
77173
77473
  const string3 = input + "";
@@ -78085,8 +78385,8 @@ var disconnect = (anyProcess) => {
78085
78385
  // node_modules/execa/lib/utils/deferred.js
78086
78386
  var createDeferred = () => {
78087
78387
  const methods = {};
78088
- const promise = new Promise((resolve5, reject) => {
78089
- Object.assign(methods, { resolve: resolve5, reject });
78388
+ const promise = new Promise((resolve6, reject) => {
78389
+ Object.assign(methods, { resolve: resolve6, reject });
78090
78390
  });
78091
78391
  return Object.assign(promise, methods);
78092
78392
  };
@@ -82728,11 +83028,11 @@ var addConcurrentStream = (concurrentStreams, stream, waitName) => {
82728
83028
  const promises = weakMap.get(stream);
82729
83029
  const promise = createDeferred();
82730
83030
  promises.push(promise);
82731
- const resolve5 = promise.resolve.bind(promise);
82732
- return { resolve: resolve5, promises };
83031
+ const resolve6 = promise.resolve.bind(promise);
83032
+ return { resolve: resolve6, promises };
82733
83033
  };
82734
- var waitForConcurrentStreams = async ({ resolve: resolve5, promises }, subprocess) => {
82735
- resolve5();
83034
+ var waitForConcurrentStreams = async ({ resolve: resolve6, promises }, subprocess) => {
83035
+ resolve6();
82736
83036
  const [isSubprocessExit] = await Promise.race([
82737
83037
  Promise.allSettled([true, subprocess]),
82738
83038
  Promise.all([false, ...promises])
@@ -84134,12 +84434,14 @@ var audiobookCommand = new Command("audiobook").description("Audiobook generatio
84134
84434
  });
84135
84435
 
84136
84436
  // src/commands/auth/login_command.ts
84137
- import * as readline3 from "readline";
84138
84437
  init_constants5();
84139
- init_browser();
84140
84438
  init_identity();
84439
+ init_second_factor();
84440
+ init_sign_in_prompt();
84141
84441
 
84142
84442
  // src/services/workspace_service.ts
84443
+ import { open as open2, unlink } from "node:fs/promises";
84444
+ import { resolve as resolve2 } from "node:path";
84143
84445
  init_constants5();
84144
84446
 
84145
84447
  // proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
@@ -84270,7 +84572,7 @@ var Workspaces = class {
84270
84572
  };
84271
84573
 
84272
84574
  // src/utils/selector.ts
84273
- import * as readline2 from "readline";
84575
+ import * as readline3 from "readline";
84274
84576
  async function selectItem(options) {
84275
84577
  const {
84276
84578
  items,
@@ -84295,11 +84597,11 @@ async function selectItem(options) {
84295
84597
  const displayName = getDisplayName(item);
84296
84598
  printListItem(`${idx + 1}. ${bright(displayName)}`);
84297
84599
  });
84298
- const rl = readline2.createInterface({
84600
+ const rl = readline3.createInterface({
84299
84601
  input: process.stdin,
84300
84602
  output: process.stdout
84301
84603
  });
84302
- const question = (query) => new Promise((resolve5) => rl.question(query, resolve5));
84604
+ const question = (query) => new Promise((resolve6) => rl.question(query, resolve6));
84303
84605
  let selectedItem = null;
84304
84606
  try {
84305
84607
  while (!selectedItem) {
@@ -84409,15 +84711,27 @@ Selecting workspace: ${source_default.whiteBright(workspaceId)}`);
84409
84711
  success("\nWorkspace selected.");
84410
84712
  }
84411
84713
  /**
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.
84714
+ * Creates an API key in the active workspace and prints it, or writes it to
84715
+ * `outputPath` as `INWORLD_API_KEY=<key>`. The platform returns the secret
84716
+ * only here, so it is shown once and never stored.
84717
+ *
84718
+ * The output file is created, readable by its owner only, before the key
84719
+ * exists, and an existing file is refused: a key whose secret cannot be
84720
+ * saved would be lost. Any failure removes the file.
84414
84721
  *
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.
84722
+ * @throws when no workspace is selected, the file cannot be created, no key
84723
+ * comes back or the write fails: the command must exit non-zero, or a
84724
+ * script would take a failed creation for success.
84417
84725
  * @param mode 'read' for read-only, 'write' for read/write voices & router
84418
84726
  * @param displayName Optional display name for the key
84727
+ * @param outputPath Optional new file to write the key to instead of printing it
84419
84728
  */
84420
- static async createApiKey(mode, displayName) {
84729
+ static async createApiKey(mode, displayName, outputPath) {
84730
+ if (outputPath !== void 0 && !outputPath.trim()) {
84731
+ throw new Error(
84732
+ "--output needs a file name, and the one given is empty. No key was created."
84733
+ );
84734
+ }
84421
84735
  const credentials = await authManager.getCredentials();
84422
84736
  if (!credentials?.workspace) {
84423
84737
  throw new Error(
@@ -84428,22 +84742,41 @@ Selecting workspace: ${source_default.whiteBright(workspaceId)}`);
84428
84742
  const baseScopes = ["api.rt::x", "api.ml::x", "api.ops::x"];
84429
84743
  const scopes = mode === "write" ? [...baseScopes, "api.dsgnt.voices::rw", "api.dsgnt.router::rw"] : [...baseScopes, "api.dsgnt.voices::r", "api.dsgnt.router::r"];
84430
84744
  const label = mode === "write" ? "read/write" : "read-only";
84431
- print(`Creating ${label} API key...`);
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.");
84745
+ const file = outputPath === void 0 ? void 0 : await createKeyFile(outputPath);
84746
+ let created;
84747
+ try {
84748
+ print(`Creating ${label} API key...`);
84749
+ created = await authenticatedInworldRequest(ApiKeys.GenerateApiKey, {
84750
+ parent,
84751
+ scopes,
84752
+ displayName,
84753
+ authTypes: [
84754
+ "API_KEY_AUTHORIZATION_TYPE_BASIC" /* API_KEY_AUTHORIZATION_TYPE_BASIC */,
84755
+ "API_KEY_AUTHORIZATION_TYPE_JWT" /* API_KEY_AUTHORIZATION_TYPE_JWT */
84756
+ ]
84757
+ });
84758
+ if (!created?.key || !created.secret) {
84759
+ throw new Error("The platform returned no key.");
84760
+ }
84761
+ } catch (error2) {
84762
+ const leftover = file ? await file.discard() : "";
84763
+ if (!leftover) throw error2;
84764
+ throw new Error(`${error2?.message || error2}${leftover}`);
84443
84765
  }
84444
84766
  const credential = Buffer.from(`${created.key}:${created.secret}`).toString(
84445
84767
  "base64"
84446
84768
  );
84769
+ if (file) {
84770
+ try {
84771
+ await file.write(`INWORLD_API_KEY=${credential}
84772
+ `);
84773
+ } catch (error2) {
84774
+ const leftover = await file.discard();
84775
+ throw new Error(
84776
+ `Key ${created.key} was created, but writing it to ${file.path} failed (${error2.message || error2}). Delete that key and try again.${leftover}`
84777
+ );
84778
+ }
84779
+ }
84447
84780
  const permissions = formatApiKeyScopes(created.scopes);
84448
84781
  success("\nAPI key created.");
84449
84782
  console.log();
@@ -84452,6 +84785,14 @@ Selecting workspace: ${source_default.whiteBright(workspaceId)}`);
84452
84785
  printListItem(`Display Name: ${displayName}`);
84453
84786
  }
84454
84787
  printListItem(`Permissions: ${permissions || label}`);
84788
+ if (file) {
84789
+ printListItem(`Saved to: ${file.path}`);
84790
+ console.log();
84791
+ print(
84792
+ `The file sets ${cyan("INWORLD_API_KEY")}; load it into your environment to use the key instead of your sign-in. The CLI does not keep it.`
84793
+ );
84794
+ return;
84795
+ }
84455
84796
  printListItem(`Key: ${credential}`);
84456
84797
  console.log();
84457
84798
  print(
@@ -84462,48 +84803,59 @@ Selecting workspace: ${source_default.whiteBright(workspaceId)}`);
84462
84803
  );
84463
84804
  }
84464
84805
  };
84465
-
84466
- // src/commands/auth/login_command.ts
84467
- var offerBrowser = async (url, done) => {
84468
- print("Please visit the following URL to authenticate:");
84469
- printLink(`${url}
84470
- `);
84471
- const readlineInterface = readline3.createInterface({
84472
- input: process.stdin,
84473
- output: process.stdout
84474
- });
84475
- const enterPromise = new Promise((resolve5) => {
84476
- readlineInterface.question("Press Enter to open your browser...", () => {
84477
- resolve5("enter");
84478
- });
84479
- });
84480
- const settled = done.then(
84481
- () => "done",
84482
- () => "done"
84483
- );
84484
- const first = await Promise.race([enterPromise, settled]);
84485
- readlineInterface.close();
84486
- if (first === "done") return;
84806
+ async function createKeyFile(path13) {
84807
+ const fullPath = resolve2(path13);
84808
+ let handle;
84487
84809
  try {
84488
- await openInBrowser(url);
84489
- success("\u2713 Browser opened");
84490
- } catch (_error) {
84491
- print(
84492
- "\u26A0 Could not open browser automatically. Please open the URL manually."
84493
- );
84810
+ handle = await open2(fullPath, "wx", 384);
84811
+ } catch (error2) {
84812
+ if (error2?.code === "EEXIST") {
84813
+ throw new Error(
84814
+ `${fullPath} already exists. Name a new file: the key is written only to a file the CLI creates.`
84815
+ );
84816
+ }
84817
+ throw new Error(`Cannot create ${fullPath}: ${error2.message || error2}`);
84494
84818
  }
84495
- console.log();
84496
- print("Waiting for authentication...");
84497
- };
84819
+ return {
84820
+ path: fullPath,
84821
+ async write(text) {
84822
+ try {
84823
+ await handle.writeFile(text);
84824
+ } finally {
84825
+ await handle.close();
84826
+ }
84827
+ },
84828
+ async discard() {
84829
+ await handle.close().catch(() => {
84830
+ });
84831
+ try {
84832
+ await unlink(fullPath);
84833
+ return "";
84834
+ } catch (error2) {
84835
+ if (error2?.code === "ENOENT") return "";
84836
+ return ` ${fullPath} could not be removed (${error2?.message || error2}); delete it.`;
84837
+ }
84838
+ }
84839
+ };
84840
+ }
84841
+
84842
+ // src/commands/auth/login_command.ts
84498
84843
  var signIn = async (source, provider) => {
84499
- const { url, done } = await startBrowserSignIn({
84844
+ const browserSignIn = await startBrowserSignIn({
84500
84845
  authUrl: source.authUrl,
84501
84846
  pageUrl: INWORLD_CLI_AUTH_URL,
84502
84847
  version: CLI_VERSION,
84503
84848
  oauthProvider: provider === "email" ? void 0 : provider
84504
84849
  });
84505
- await offerBrowser(url, done);
84506
- return done;
84850
+ await promptForSignIn(browserSignIn, {
84851
+ print,
84852
+ printLink,
84853
+ printError,
84854
+ output: process.stdout
84855
+ });
84856
+ return stepUpSecondFactor(source, await browserSignIn.done, {
84857
+ print
84858
+ });
84507
84859
  };
84508
84860
  var loginAction = async (options) => {
84509
84861
  try {
@@ -84610,23 +84962,23 @@ async function confirm(options) {
84610
84962
  input: process.stdin,
84611
84963
  output: process.stdout
84612
84964
  });
84613
- return new Promise((resolve5) => {
84965
+ return new Promise((resolve6) => {
84614
84966
  rl.question(message, (answer) => {
84615
84967
  rl.close();
84616
84968
  const trimmedAnswer = answer.trim().toLowerCase();
84617
84969
  if (trimmedAnswer === "y" || trimmedAnswer === "yes") {
84618
- resolve5(true);
84970
+ resolve6(true);
84619
84971
  return;
84620
84972
  }
84621
84973
  if (trimmedAnswer === "n" || trimmedAnswer === "no") {
84622
- resolve5(false);
84974
+ resolve6(false);
84623
84975
  return;
84624
84976
  }
84625
84977
  if (trimmedAnswer === "") {
84626
- resolve5(defaultValue);
84978
+ resolve6(defaultValue);
84627
84979
  return;
84628
84980
  }
84629
- resolve5(false);
84981
+ resolve6(false);
84630
84982
  });
84631
84983
  });
84632
84984
  }
@@ -84885,15 +85237,15 @@ var Analytics = class _Analytics {
84885
85237
  * Should be called before the CLI exits
84886
85238
  */
84887
85239
  flush() {
84888
- return new Promise((resolve5) => {
85240
+ return new Promise((resolve6) => {
84889
85241
  if (!this.initialized || !this.mixpanel) {
84890
- resolve5();
85242
+ resolve6();
84891
85243
  return;
84892
85244
  }
84893
- const timeout = setTimeout(() => resolve5(), 500);
85245
+ const timeout = setTimeout(() => resolve6(), 500);
84894
85246
  setTimeout(() => {
84895
85247
  clearTimeout(timeout);
84896
- resolve5();
85248
+ resolve6();
84897
85249
  }, 100);
84898
85250
  });
84899
85251
  }
@@ -85356,10 +85708,10 @@ var sttCommand = new Command("stt").description("Speech-to-text functionality").
85356
85708
 
85357
85709
  // src/commands/tts/tts_clone_command.ts
85358
85710
  import { readFile as readFile6 } from "fs/promises";
85359
- import { resolve as resolve3 } from "path";
85711
+ import { resolve as resolve4 } from "path";
85360
85712
  var cloneCommand = new Command("clone").description("Clone a voice from an audio file (5-15 seconds, max 4MB)").argument("<audioFile>", "Path to audio file (wav, mp3, webm)").requiredOption("-n, --name <name>", "Display name for the cloned voice").option("-l, --lang <code>", "Language code (e.g., EN_US)", "EN_US").option("-t, --transcription <text>", "Transcription of the audio").option("-d, --description <text>", "Description of the voice").option("--tags <tags>", "Comma-separated tags").option("--remove-noise", "Remove background noise from audio").option("-j, --json", "Output response as JSON").action(async (audioFile, options) => {
85361
85713
  try {
85362
- const filePath = resolve3(audioFile);
85714
+ const filePath = resolve4(audioFile);
85363
85715
  const audioData = await readFile6(filePath);
85364
85716
  if (audioData.length > 4 * 1024 * 1024) {
85365
85717
  console.error(source_default.red("Error: Audio file exceeds 4MB limit"));
@@ -85424,7 +85776,7 @@ Use this voice: inworld tts synthesize "Hello" -v ${voice.voiceId}`
85424
85776
  import { writeFile as writeFile5 } from "fs/promises";
85425
85777
  import { tmpdir as tmpdir3 } from "os";
85426
85778
  import { join as join5 } from "path";
85427
- import * as readline6 from "readline";
85779
+ import * as readline5 from "readline";
85428
85780
  init_audio_player();
85429
85781
  async function savePreviewsToTemp(previews) {
85430
85782
  const paths = [];
@@ -85533,11 +85885,11 @@ Generated ${previews.length} voice preview(s):
85533
85885
  Actions: [1-${previews.length}] play a preview, [p] publish, [r] regenerate, [q] quit`
85534
85886
  )
85535
85887
  );
85536
- const rl = readline6.createInterface({
85888
+ const rl = readline5.createInterface({
85537
85889
  input: process.stdin,
85538
85890
  output: process.stdout
85539
85891
  });
85540
- const ask = (q) => new Promise((resolve5) => rl.question(q, resolve5));
85892
+ const ask = (q) => new Promise((resolve6) => rl.question(q, resolve6));
85541
85893
  let action = null;
85542
85894
  while (true) {
85543
85895
  const answer = (await ask("> ")).trim().toLowerCase();
@@ -85820,7 +86172,7 @@ var previewCommand = new Command("preview").description(
85820
86172
 
85821
86173
  // src/commands/tts/tts_synthesize_command.ts
85822
86174
  import { writeFile as writeFile6 } from "fs/promises";
85823
- import { resolve as resolve4 } from "path";
86175
+ import { resolve as resolve5 } from "path";
85824
86176
  init_audio_player();
85825
86177
  var synthesizeCommand = addGenerationOptions(new Command("synthesize")).description(
85826
86178
  'Synthesize text to speech\n\nAudio markups supported in text:\n SSML breaks: <break time="1s" /> or <break time="500ms" />\n Emotions: [happy] [sad] [angry] [surprised] [fearful] [disgusted]\n Delivery: [laughing] [whispering]\n Vocalizations: [breathe] [clear_throat] [cough] [laugh] [sigh] [yawn]\n Pronunciation: /kri\u02D0t/ (IPA in forward slashes)'
@@ -85864,7 +86216,7 @@ var synthesizeCommand = addGenerationOptions(new Command("synthesize")).descript
85864
86216
  /[^a-zA-Z0-9_-]/g,
85865
86217
  "_"
85866
86218
  );
85867
- const outputPath = resolve4(
86219
+ const outputPath = resolve5(
85868
86220
  options.output || `${safeVoice}_${Date.now()}${fileExtension}`
85869
86221
  );
85870
86222
  let response;
@@ -86224,15 +86576,18 @@ var selectWorkspaceCommand = new Command("select").description("Select a workspa
86224
86576
  }
86225
86577
  });
86226
86578
  var addKeyCommand = new Command("add-key").description(
86227
- "Create a new API key and print it once (read-only by default, --write for read/write)"
86579
+ "Create a new API key and print it once, or write it to a file with --output (read-only by default, --write for read/write)"
86228
86580
  ).option(
86229
86581
  "-w, --write",
86230
86582
  "Create with read/write permissions for voices and router"
86231
- ).option("-n, --name <name>", "Display name for the API key").action(async (options) => {
86583
+ ).option("-n, --name <name>", "Display name for the API key").option(
86584
+ "-o, --output <file>",
86585
+ "Write the key to a new file as INWORLD_API_KEY=<key> instead of printing it (on macOS and Linux, readable only by you)"
86586
+ ).action(async (options) => {
86232
86587
  await requireAuth();
86233
86588
  try {
86234
86589
  const mode = options.write ? "write" : "read";
86235
- await WorkspaceService.createApiKey(mode, options.name);
86590
+ await WorkspaceService.createApiKey(mode, options.name, options.output);
86236
86591
  process.exit(0);
86237
86592
  } catch (error2) {
86238
86593
  printError(`
@@ -86468,7 +86823,7 @@ var InworldCLI = class {
86468
86823
  })
86469
86824
  ]);
86470
86825
  const timeoutPromise = new Promise(
86471
- (resolve5) => setTimeout(resolve5, 1e3)
86826
+ (resolve6) => setTimeout(resolve6, 1e3)
86472
86827
  );
86473
86828
  await Promise.race([initPromise, timeoutPromise]);
86474
86829
  }