@inworld/cli 0.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/index.js +3893 -0
- package/dist/index.js.map +7 -0
- package/dist/src/templates/llm_tts/README.md +161 -0
- package/dist/src/templates/llm_tts/graph.ts +30 -0
- package/dist/src/templates/llm_tts/metadata.json +41 -0
- package/dist/src/templates/simple/README.md +106 -0
- package/dist/src/templates/simple/graph.ts +32 -0
- package/dist/src/templates/simple/metadata.json +26 -0
- package/dist/templates/llm_tts/README.md +155 -0
- package/dist/templates/llm_tts/graph.ts +30 -0
- package/dist/templates/llm_tts/metadata.json +41 -0
- package/dist/templates/simple/README.md +106 -0
- package/dist/templates/simple/graph.ts +32 -0
- package/dist/templates/simple/metadata.json +26 -0
- package/package.json +46 -0
- package/src/templates/llm_tts/README.md +155 -0
- package/src/templates/llm_tts/graph.ts +30 -0
- package/src/templates/llm_tts/metadata.json +41 -0
- package/src/templates/simple/README.md +106 -0
- package/src/templates/simple/graph.ts +32 -0
- package/src/templates/simple/metadata.json +26 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3893 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
// index.ts
|
|
5
|
+
import chalk14 from "chalk";
|
|
6
|
+
import { Command as Command19 } from "commander";
|
|
7
|
+
|
|
8
|
+
// src/commands/auth/login_command.ts
|
|
9
|
+
import chalk3 from "chalk";
|
|
10
|
+
import { exec } from "child_process";
|
|
11
|
+
import { Command } from "commander";
|
|
12
|
+
import * as readline2 from "readline";
|
|
13
|
+
import { promisify } from "util";
|
|
14
|
+
|
|
15
|
+
// src/auth/callback-server.ts
|
|
16
|
+
import * as http from "http";
|
|
17
|
+
|
|
18
|
+
// src/constants.ts
|
|
19
|
+
var DEFAULT_PLATFORM_ENDPOINT = "https://platform.inworld.ai";
|
|
20
|
+
var resolvePlatformUrl = () => {
|
|
21
|
+
if (process.env.INWORLD_PLATFORM_URL) {
|
|
22
|
+
return process.env.INWORLD_PLATFORM_URL;
|
|
23
|
+
}
|
|
24
|
+
const env = (process.env.INWORLD_ENV || "").toUpperCase();
|
|
25
|
+
switch (env) {
|
|
26
|
+
case "DEV":
|
|
27
|
+
return "https://platform.dev.inworld.ai";
|
|
28
|
+
case "STAGE":
|
|
29
|
+
return "https://platform.stage.inworld.ai";
|
|
30
|
+
case "PROD":
|
|
31
|
+
return "https://platform.inworld.ai";
|
|
32
|
+
default:
|
|
33
|
+
return DEFAULT_PLATFORM_ENDPOINT;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var INWORLD_ENV = process.env.INWORLD_ENV || "PROD";
|
|
37
|
+
var WORKSPACES_LIST_SIZE = 100;
|
|
38
|
+
var PLATFORM_URL = resolvePlatformUrl();
|
|
39
|
+
var FIREBASE_API_KEY = process.env.INWORLD_FIREBASE_API_KEY || "AIzaSyAPVBLVid0xPwjuU4Gmn_6_GyqxBq-SwQs";
|
|
40
|
+
var INWORLD_CLI_AUTH_URL = process.env.INWORLD_CLI_AUTH_URL || "https://cli.inworld.ai/login";
|
|
41
|
+
var INWORLD_CLI_AUTH_CALLBACK_PORT = parseInt(
|
|
42
|
+
process.env.INWORLD_CLI_AUTH_CALLBACK_PORT || "8085",
|
|
43
|
+
10
|
|
44
|
+
);
|
|
45
|
+
var RUNTIME_VERSION = "0.6.3";
|
|
46
|
+
var CLI_VERSION = "0.2.15";
|
|
47
|
+
|
|
48
|
+
// src/utils/ui.ts
|
|
49
|
+
import chalk from "chalk";
|
|
50
|
+
function header(message) {
|
|
51
|
+
console.log(chalk.bold(message));
|
|
52
|
+
}
|
|
53
|
+
function print(message) {
|
|
54
|
+
console.log(chalk.dim.gray(message));
|
|
55
|
+
}
|
|
56
|
+
function printBright(message) {
|
|
57
|
+
console.log(chalk.white(message));
|
|
58
|
+
}
|
|
59
|
+
function printLink(message) {
|
|
60
|
+
console.log(chalk.dim.underline.cyan(message));
|
|
61
|
+
}
|
|
62
|
+
function printError(message) {
|
|
63
|
+
console.error(chalk.dim.red(message));
|
|
64
|
+
}
|
|
65
|
+
function success(message) {
|
|
66
|
+
console.log(chalk.dim.green(message));
|
|
67
|
+
}
|
|
68
|
+
function listItem(message) {
|
|
69
|
+
console.log("\u2514 " + chalk.gray(message));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/auth/callback-server.ts
|
|
73
|
+
async function createCallbackServer(options = {}) {
|
|
74
|
+
const {
|
|
75
|
+
port = 8085,
|
|
76
|
+
allowedOrigins = ["http://localhost:3001", "https://cli.inworld.ai"],
|
|
77
|
+
firebaseApiKey = FIREBASE_API_KEY
|
|
78
|
+
} = options;
|
|
79
|
+
return new Promise((resolve2, reject) => {
|
|
80
|
+
const httpServer = http.createServer(
|
|
81
|
+
{
|
|
82
|
+
keepAlive: false
|
|
83
|
+
},
|
|
84
|
+
(req, res) => {
|
|
85
|
+
const origin = req.headers.origin;
|
|
86
|
+
if (origin && allowedOrigins.includes(origin)) {
|
|
87
|
+
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
88
|
+
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
|
89
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
90
|
+
res.setHeader("Access-Control-Max-Age", "86400");
|
|
91
|
+
}
|
|
92
|
+
if (req.url?.startsWith("/callback") && req.method === "OPTIONS") {
|
|
93
|
+
res.writeHead(204);
|
|
94
|
+
res.end();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (req.url?.startsWith("/callback") && req.method === "POST") {
|
|
98
|
+
let body = "";
|
|
99
|
+
req.on("data", (chunk) => {
|
|
100
|
+
body += chunk.toString();
|
|
101
|
+
});
|
|
102
|
+
req.on("end", async () => {
|
|
103
|
+
try {
|
|
104
|
+
const data = JSON.parse(body);
|
|
105
|
+
console.log();
|
|
106
|
+
print("Received authentication data...");
|
|
107
|
+
const refreshToken = data.refreshToken;
|
|
108
|
+
const email = data.email;
|
|
109
|
+
print("Exchanging tokens...");
|
|
110
|
+
if (!firebaseApiKey) {
|
|
111
|
+
throw new Error("FIREBASE_API_KEY is not set");
|
|
112
|
+
}
|
|
113
|
+
const tokenFetchResponse = await fetch(
|
|
114
|
+
`https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
|
|
115
|
+
{
|
|
116
|
+
method: "POST",
|
|
117
|
+
body: new URLSearchParams({
|
|
118
|
+
grant_type: "refresh_token",
|
|
119
|
+
refresh_token: data.refreshToken
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
);
|
|
123
|
+
const tokenResponse = await tokenFetchResponse.json();
|
|
124
|
+
if (tokenResponse.error) {
|
|
125
|
+
throw new Error(
|
|
126
|
+
`Token exchange failed: ${tokenResponse.error.message}`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
if (tokenResponse?.id_token) {
|
|
130
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
131
|
+
res.end(JSON.stringify({ success: true }));
|
|
132
|
+
resolve2({
|
|
133
|
+
server: httpServer,
|
|
134
|
+
token: tokenResponse.id_token,
|
|
135
|
+
refreshToken,
|
|
136
|
+
email
|
|
137
|
+
});
|
|
138
|
+
} else {
|
|
139
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
140
|
+
res.end(JSON.stringify({ error: "No idToken provided" }));
|
|
141
|
+
}
|
|
142
|
+
} catch (error) {
|
|
143
|
+
printError("Callback processing error:");
|
|
144
|
+
console.error(error);
|
|
145
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
146
|
+
res.end(
|
|
147
|
+
JSON.stringify({
|
|
148
|
+
error: error instanceof Error ? error.message : "Invalid request"
|
|
149
|
+
})
|
|
150
|
+
);
|
|
151
|
+
if (error instanceof Error && error.message.includes("JSON")) {
|
|
152
|
+
print(
|
|
153
|
+
"Invalid JSON received, waiting for valid callback..."
|
|
154
|
+
);
|
|
155
|
+
} else {
|
|
156
|
+
reject(error);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
req.on("error", (error) => {
|
|
161
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
162
|
+
res.end(JSON.stringify({ error: "Server error" }));
|
|
163
|
+
reject(error);
|
|
164
|
+
});
|
|
165
|
+
} else if (req.url?.startsWith("/callback")) {
|
|
166
|
+
res.writeHead(405, { "Content-Type": "application/json" });
|
|
167
|
+
res.end(JSON.stringify({ error: "Method not allowed. Use POST." }));
|
|
168
|
+
} else {
|
|
169
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
170
|
+
res.end(JSON.stringify({ error: "Not found" }));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
httpServer.on("error", (error) => {
|
|
175
|
+
reject(error);
|
|
176
|
+
});
|
|
177
|
+
httpServer.listen(port, "localhost");
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
function stopCallbackServer(server) {
|
|
181
|
+
return new Promise((resolve2, reject) => {
|
|
182
|
+
server.close((err) => {
|
|
183
|
+
if (err) {
|
|
184
|
+
reject(err);
|
|
185
|
+
} else {
|
|
186
|
+
resolve2();
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// src/auth/manager.ts
|
|
193
|
+
import Conf from "conf";
|
|
194
|
+
import { createHash } from "crypto";
|
|
195
|
+
|
|
196
|
+
// proto/generated/portal/fetch.pb.ts
|
|
197
|
+
var b64 = new Array(64);
|
|
198
|
+
var s64 = new Array(123);
|
|
199
|
+
for (let i = 0; i < 64; )
|
|
200
|
+
s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
|
|
201
|
+
function b64Encode(buffer, start, end) {
|
|
202
|
+
let parts = null;
|
|
203
|
+
const chunk = [];
|
|
204
|
+
let i = 0, j = 0, t;
|
|
205
|
+
while (start < end) {
|
|
206
|
+
const b = buffer[start++];
|
|
207
|
+
switch (j) {
|
|
208
|
+
case 0:
|
|
209
|
+
chunk[i++] = b64[b >> 2];
|
|
210
|
+
t = (b & 3) << 4;
|
|
211
|
+
j = 1;
|
|
212
|
+
break;
|
|
213
|
+
case 1:
|
|
214
|
+
chunk[i++] = b64[t | b >> 4];
|
|
215
|
+
t = (b & 15) << 2;
|
|
216
|
+
j = 2;
|
|
217
|
+
break;
|
|
218
|
+
case 2:
|
|
219
|
+
chunk[i++] = b64[t | b >> 6];
|
|
220
|
+
chunk[i++] = b64[b & 63];
|
|
221
|
+
j = 0;
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
if (i > 8191) {
|
|
225
|
+
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
|
|
226
|
+
i = 0;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (j) {
|
|
230
|
+
chunk[i++] = b64[t];
|
|
231
|
+
chunk[i++] = 61;
|
|
232
|
+
if (j === 1) chunk[i++] = 61;
|
|
233
|
+
}
|
|
234
|
+
if (parts) {
|
|
235
|
+
if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
|
|
236
|
+
return parts.join("");
|
|
237
|
+
}
|
|
238
|
+
return String.fromCharCode.apply(String, chunk.slice(0, i));
|
|
239
|
+
}
|
|
240
|
+
function replacer(key, value) {
|
|
241
|
+
if (value && value.constructor === Uint8Array) {
|
|
242
|
+
return b64Encode(value, 0, value.length);
|
|
243
|
+
}
|
|
244
|
+
return value;
|
|
245
|
+
}
|
|
246
|
+
function fetchReq(path6, init) {
|
|
247
|
+
const { pathPrefix, ...req } = init || {};
|
|
248
|
+
const url = pathPrefix ? `${pathPrefix}${path6}` : path6;
|
|
249
|
+
return fetch(url, req).then(
|
|
250
|
+
(r) => r.json().then((body) => {
|
|
251
|
+
if (!r.ok) {
|
|
252
|
+
throw body;
|
|
253
|
+
}
|
|
254
|
+
return body;
|
|
255
|
+
})
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
function isPlainObject(value) {
|
|
259
|
+
const isObject = Object.prototype.toString.call(value).slice(8, -1) === "Object";
|
|
260
|
+
const isObjLike = value !== null && isObject;
|
|
261
|
+
if (!isObjLike || !isObject) {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
const proto = Object.getPrototypeOf(value);
|
|
265
|
+
const hasObjectConstructor = typeof proto === "object" && proto.constructor === Object.prototype.constructor;
|
|
266
|
+
return hasObjectConstructor;
|
|
267
|
+
}
|
|
268
|
+
function isPrimitive(value) {
|
|
269
|
+
return ["string", "number", "boolean"].some((t) => typeof value === t);
|
|
270
|
+
}
|
|
271
|
+
function isZeroValuePrimitive(value) {
|
|
272
|
+
return value === false || value === 0 || value === "";
|
|
273
|
+
}
|
|
274
|
+
function flattenRequestPayload(requestPayload, path6 = "") {
|
|
275
|
+
return Object.keys(requestPayload).reduce((acc, key) => {
|
|
276
|
+
const value = requestPayload[key];
|
|
277
|
+
const newPath = path6 ? [path6, key].join(".") : key;
|
|
278
|
+
const isNonEmptyPrimitiveArray = Array.isArray(value) && value.every((v) => isPrimitive(v)) && value.length > 0;
|
|
279
|
+
const isNonZeroValuePrimitive = isPrimitive(value) && !isZeroValuePrimitive(value);
|
|
280
|
+
let objectToMerge = {};
|
|
281
|
+
if (isPlainObject(value)) {
|
|
282
|
+
objectToMerge = flattenRequestPayload(value, newPath);
|
|
283
|
+
} else if (isNonZeroValuePrimitive || isNonEmptyPrimitiveArray) {
|
|
284
|
+
objectToMerge = { [newPath]: value };
|
|
285
|
+
}
|
|
286
|
+
return { ...acc, ...objectToMerge };
|
|
287
|
+
}, {});
|
|
288
|
+
}
|
|
289
|
+
function renderURLSearchParams(requestPayload, urlPathParams = []) {
|
|
290
|
+
const flattenedRequestPayload = flattenRequestPayload(requestPayload);
|
|
291
|
+
const urlSearchParams = Object.keys(flattenedRequestPayload).reduce(
|
|
292
|
+
(acc, key) => {
|
|
293
|
+
const value = flattenedRequestPayload[key];
|
|
294
|
+
if (urlPathParams.find((f) => f === key)) {
|
|
295
|
+
return acc;
|
|
296
|
+
}
|
|
297
|
+
return Array.isArray(value) ? [...acc, ...value.map((m) => [key, m.toString()])] : acc = [...acc, [key, value.toString()]];
|
|
298
|
+
},
|
|
299
|
+
[]
|
|
300
|
+
);
|
|
301
|
+
return new URLSearchParams(urlSearchParams).toString();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// proto/generated/portal/ai/inworld/studio/v1alpha/users.pb.ts
|
|
305
|
+
var Users = class {
|
|
306
|
+
static GenerateTokenUser(req, initReq) {
|
|
307
|
+
return fetchReq(
|
|
308
|
+
`/v1alpha/users:generateTokenUser`,
|
|
309
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
static LinkAccountUser(req, initReq) {
|
|
313
|
+
return fetchReq(
|
|
314
|
+
`/v1alpha/${req["name"]}:link`,
|
|
315
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
static GetUser(req, initReq) {
|
|
319
|
+
return fetchReq(
|
|
320
|
+
`/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["nameusers"])}`,
|
|
321
|
+
{ ...initReq, method: "GET" }
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
static UpdateUser(req, initReq) {
|
|
325
|
+
return fetchReq(
|
|
326
|
+
`/v1alpha/${req["user"]["name"]}`,
|
|
327
|
+
{
|
|
328
|
+
...initReq,
|
|
329
|
+
method: "PATCH",
|
|
330
|
+
body: JSON.stringify(req["user"], replacer)
|
|
331
|
+
}
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
static AcceptTos(req, initReq) {
|
|
335
|
+
return fetchReq(
|
|
336
|
+
`/v1alpha/${req["user"]}:acceptTos`,
|
|
337
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
static DeleteUser(req, initReq) {
|
|
341
|
+
return fetchReq(
|
|
342
|
+
`/v1alpha/${req["name"]}`,
|
|
343
|
+
{ ...initReq, method: "DELETE" }
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
static ResolveAzureMarketplaceOfferToken(req, initReq) {
|
|
347
|
+
return fetchReq(
|
|
348
|
+
`/v1alpha/users:resolveAzureMarketplaceOfferToken?${renderURLSearchParams(req, [])}`,
|
|
349
|
+
{ ...initReq, method: "GET" }
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
static ActivateAzureMarketplaceSubscription(req, initReq) {
|
|
353
|
+
return fetchReq(`/v1alpha/users:activateAzureMarketplaceSubscription`, {
|
|
354
|
+
...initReq,
|
|
355
|
+
method: "POST",
|
|
356
|
+
body: JSON.stringify(req, replacer)
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
// src/auth/manager.ts
|
|
362
|
+
var AuthManager = class _AuthManager {
|
|
363
|
+
static SERVICE_NAME = "InworldCLI";
|
|
364
|
+
static ACCOUNT_NAME = "default";
|
|
365
|
+
static CONFIG_KEY = "credentials";
|
|
366
|
+
conf = null;
|
|
367
|
+
keyringModule = null;
|
|
368
|
+
keyringLoadAttempted = false;
|
|
369
|
+
keyringAvailable = false;
|
|
370
|
+
constructor() {
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Lazily loads the keyring module with fallback if unavailable
|
|
374
|
+
*/
|
|
375
|
+
async getKeyring() {
|
|
376
|
+
if (this.keyringLoadAttempted) {
|
|
377
|
+
return this.keyringModule;
|
|
378
|
+
}
|
|
379
|
+
this.keyringLoadAttempted = true;
|
|
380
|
+
try {
|
|
381
|
+
const module = await import("@zowe/secrets-for-zowe-sdk");
|
|
382
|
+
this.keyringModule = module.keyring;
|
|
383
|
+
return this.keyringModule;
|
|
384
|
+
} catch (error) {
|
|
385
|
+
print(`\u26A0\uFE0F Failed to load keychain: ${error.message}`);
|
|
386
|
+
this.keyringModule = null;
|
|
387
|
+
this.keyringAvailable = false;
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Lazily initializes the Conf instance with encrypted storage
|
|
393
|
+
*/
|
|
394
|
+
async getConf() {
|
|
395
|
+
if (!this.conf) {
|
|
396
|
+
const encryptionKey = await this.generateEncryptionKey();
|
|
397
|
+
this.conf = new Conf({
|
|
398
|
+
projectName: "inworld-cli",
|
|
399
|
+
encryptionKey,
|
|
400
|
+
schema: {
|
|
401
|
+
credentials: {
|
|
402
|
+
type: "object",
|
|
403
|
+
properties: {
|
|
404
|
+
refreshToken: { type: "string" },
|
|
405
|
+
email: { type: "string" },
|
|
406
|
+
inworldToken: { type: "string" },
|
|
407
|
+
expiresAt: { type: "number" },
|
|
408
|
+
workspace: { type: "string" }
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
return this.conf;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Generates a machine-specific encryption key for the configuration file
|
|
418
|
+
*/
|
|
419
|
+
async generateEncryptionKey() {
|
|
420
|
+
const platform = process.platform;
|
|
421
|
+
const arch = process.arch;
|
|
422
|
+
const hostname = (await import("os")).hostname();
|
|
423
|
+
const username = (await import("os")).userInfo().username;
|
|
424
|
+
const data = `${platform}-${arch}-${hostname}-${username}-inworld-cli`;
|
|
425
|
+
return createHash("sha256").update(data).digest("hex").substring(0, 32);
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Saves credentials securely
|
|
429
|
+
*/
|
|
430
|
+
async saveCredentials(credentials) {
|
|
431
|
+
try {
|
|
432
|
+
const keyring = await this.getKeyring();
|
|
433
|
+
if (keyring) {
|
|
434
|
+
try {
|
|
435
|
+
const credentialsJsonString = JSON.stringify(credentials);
|
|
436
|
+
await keyring.setPassword(
|
|
437
|
+
_AuthManager.SERVICE_NAME,
|
|
438
|
+
_AuthManager.ACCOUNT_NAME,
|
|
439
|
+
credentialsJsonString
|
|
440
|
+
);
|
|
441
|
+
return;
|
|
442
|
+
} catch (_keychainError) {
|
|
443
|
+
print(
|
|
444
|
+
"\u26A0 Could not save to system keychain, using encrypted file storage"
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const conf = await this.getConf();
|
|
449
|
+
conf.set(_AuthManager.CONFIG_KEY, credentials);
|
|
450
|
+
success("\u2713 Credentials saved to encrypted configuration");
|
|
451
|
+
} catch (error) {
|
|
452
|
+
throw new Error(`Failed to save credentials: ${error}`);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Retrieves stored credentials
|
|
457
|
+
*/
|
|
458
|
+
async getCredentials() {
|
|
459
|
+
try {
|
|
460
|
+
const keyring = await this.getKeyring();
|
|
461
|
+
if (keyring) {
|
|
462
|
+
try {
|
|
463
|
+
const credentialsJson = await keyring.getPassword(
|
|
464
|
+
_AuthManager.SERVICE_NAME,
|
|
465
|
+
_AuthManager.ACCOUNT_NAME
|
|
466
|
+
);
|
|
467
|
+
if (credentialsJson) {
|
|
468
|
+
return JSON.parse(credentialsJson);
|
|
469
|
+
}
|
|
470
|
+
} catch (_keychainError) {
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const conf = await this.getConf();
|
|
474
|
+
const credentials = conf.get(_AuthManager.CONFIG_KEY);
|
|
475
|
+
return credentials || null;
|
|
476
|
+
} catch (error) {
|
|
477
|
+
throw new Error(`Failed to retrieve credentials: ${error}`);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async getApiKey() {
|
|
481
|
+
const credentials = await this.getCredentials();
|
|
482
|
+
return credentials?.apiKey || null;
|
|
483
|
+
}
|
|
484
|
+
async getWorkspace() {
|
|
485
|
+
const credentials = await this.getCredentials();
|
|
486
|
+
return credentials?.workspace || null;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Updates the Inworld token and its expiration
|
|
490
|
+
*/
|
|
491
|
+
async updateInworldToken(token, expirationTime) {
|
|
492
|
+
const credentials = await this.getCredentials();
|
|
493
|
+
if (!credentials) {
|
|
494
|
+
throw new Error("No credentials found to update");
|
|
495
|
+
}
|
|
496
|
+
credentials.inworldToken = token;
|
|
497
|
+
credentials.expiresAt = new Date(expirationTime).getTime();
|
|
498
|
+
await this.saveCredentials(credentials);
|
|
499
|
+
}
|
|
500
|
+
async updateWorkspaceAndApiKey(workspace, apiKey) {
|
|
501
|
+
const credentials = await this.getCredentials();
|
|
502
|
+
if (!credentials) {
|
|
503
|
+
throw new Error("No credentials found to update");
|
|
504
|
+
}
|
|
505
|
+
credentials.workspace = workspace;
|
|
506
|
+
credentials.apiKey = apiKey;
|
|
507
|
+
await this.saveCredentials(credentials);
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Checks if the stored Inworld token is still valid
|
|
511
|
+
*/
|
|
512
|
+
async isTokenValid() {
|
|
513
|
+
const credentials = await this.getCredentials();
|
|
514
|
+
if (!credentials || !credentials.inworldToken) {
|
|
515
|
+
return false;
|
|
516
|
+
}
|
|
517
|
+
if (credentials.expiresAt) {
|
|
518
|
+
return Date.now() < credentials.expiresAt;
|
|
519
|
+
}
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Generates an Inworld token from a Firebase ID token
|
|
524
|
+
*
|
|
525
|
+
* @param firebaseToken The Firebase ID token
|
|
526
|
+
* @returns The generated Inworld token or null if generation fails
|
|
527
|
+
*/
|
|
528
|
+
async generateInworldToken(firebaseToken) {
|
|
529
|
+
try {
|
|
530
|
+
print("Generating Inworld token...");
|
|
531
|
+
const tokenResponse = await Users.GenerateTokenUser(
|
|
532
|
+
{
|
|
533
|
+
type: "AUTH_TYPE_FIREBASE" /* AUTH_TYPE_FIREBASE */,
|
|
534
|
+
token: firebaseToken
|
|
535
|
+
},
|
|
536
|
+
{
|
|
537
|
+
headers: {
|
|
538
|
+
Authorization: `Bearer ${firebaseToken}`,
|
|
539
|
+
"Grpc-Metadata-X-Authorization-Bearer-Type": "firebase"
|
|
540
|
+
},
|
|
541
|
+
pathPrefix: PLATFORM_URL
|
|
542
|
+
}
|
|
543
|
+
);
|
|
544
|
+
if (tokenResponse?.token) {
|
|
545
|
+
return {
|
|
546
|
+
token: tokenResponse.token,
|
|
547
|
+
expiresAt: tokenResponse.expirationTime
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
return null;
|
|
551
|
+
} catch (error) {
|
|
552
|
+
printError("Failed to generate Inworld token:");
|
|
553
|
+
console.error(error);
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Refreshes the Inworld token using the stored refresh token
|
|
559
|
+
*/
|
|
560
|
+
async refreshToken() {
|
|
561
|
+
const credentials = await this.getCredentials();
|
|
562
|
+
if (!credentials || !credentials.refreshToken) {
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
try {
|
|
566
|
+
const firebaseApiKey = FIREBASE_API_KEY;
|
|
567
|
+
if (!firebaseApiKey) {
|
|
568
|
+
throw new Error("FIREBASE_API_KEY environment variable not set");
|
|
569
|
+
}
|
|
570
|
+
const tokenFetchResponse = await fetch(
|
|
571
|
+
`https://securetoken.googleapis.com/v1/token?key=${firebaseApiKey}`,
|
|
572
|
+
{
|
|
573
|
+
method: "POST",
|
|
574
|
+
body: new URLSearchParams({
|
|
575
|
+
grant_type: "refresh_token",
|
|
576
|
+
refresh_token: credentials.refreshToken
|
|
577
|
+
})
|
|
578
|
+
}
|
|
579
|
+
);
|
|
580
|
+
const tokenResponse = await tokenFetchResponse.json();
|
|
581
|
+
if (tokenResponse?.id_token) {
|
|
582
|
+
const inworldTokenResult = await this.generateInworldToken(
|
|
583
|
+
tokenResponse.id_token
|
|
584
|
+
);
|
|
585
|
+
if (inworldTokenResult) {
|
|
586
|
+
await this.updateInworldToken(
|
|
587
|
+
inworldTokenResult.token,
|
|
588
|
+
inworldTokenResult.expiresAt
|
|
589
|
+
);
|
|
590
|
+
return inworldTokenResult.token;
|
|
591
|
+
}
|
|
592
|
+
return null;
|
|
593
|
+
}
|
|
594
|
+
return null;
|
|
595
|
+
} catch (error) {
|
|
596
|
+
printError("Failed to refresh token:");
|
|
597
|
+
console.error(error);
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Gets a valid Inworld token, refreshing if necessary
|
|
603
|
+
*/
|
|
604
|
+
async getValidToken() {
|
|
605
|
+
if (await this.isTokenValid()) {
|
|
606
|
+
const credentials = await this.getCredentials();
|
|
607
|
+
return credentials?.inworldToken || null;
|
|
608
|
+
}
|
|
609
|
+
print("Token expired, refreshing...");
|
|
610
|
+
return await this.refreshToken();
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Authenticates and saves credentials from Firebase auth data
|
|
614
|
+
* This is typically called after successful Firebase authentication
|
|
615
|
+
*
|
|
616
|
+
* @param firebaseToken The Firebase ID token
|
|
617
|
+
* @param refreshToken The Firebase refresh token
|
|
618
|
+
* @param email The user's email address
|
|
619
|
+
* @returns true if successful, false otherwise
|
|
620
|
+
*/
|
|
621
|
+
async authenticateAndSaveCredentials(firebaseToken, refreshToken, email, workspace, env) {
|
|
622
|
+
try {
|
|
623
|
+
const inworldTokenResult = await this.generateInworldToken(firebaseToken);
|
|
624
|
+
if (!inworldTokenResult) {
|
|
625
|
+
printError("Failed to generate Inworld token");
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
628
|
+
const expiresAt = new Date(inworldTokenResult.expiresAt).getTime();
|
|
629
|
+
const credentials = {
|
|
630
|
+
refreshToken,
|
|
631
|
+
email,
|
|
632
|
+
inworldToken: inworldTokenResult.token,
|
|
633
|
+
workspace,
|
|
634
|
+
expiresAt,
|
|
635
|
+
env
|
|
636
|
+
};
|
|
637
|
+
await this.saveCredentials(credentials);
|
|
638
|
+
return true;
|
|
639
|
+
} catch (error) {
|
|
640
|
+
printError("Failed to authenticate and save credentials:");
|
|
641
|
+
console.error(error);
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Clears all stored credentials
|
|
647
|
+
*/
|
|
648
|
+
async clearCredentials() {
|
|
649
|
+
try {
|
|
650
|
+
const keyring = await this.getKeyring();
|
|
651
|
+
if (keyring) {
|
|
652
|
+
try {
|
|
653
|
+
await keyring.deletePassword(
|
|
654
|
+
_AuthManager.SERVICE_NAME,
|
|
655
|
+
_AuthManager.ACCOUNT_NAME
|
|
656
|
+
);
|
|
657
|
+
} catch (_keychainError) {
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const conf = await this.getConf();
|
|
661
|
+
conf.delete(_AuthManager.CONFIG_KEY);
|
|
662
|
+
success("\u2713 Credentials cleared");
|
|
663
|
+
} catch (error) {
|
|
664
|
+
throw new Error(`Failed to clear credentials: ${error}`);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Checks if user is authenticated
|
|
669
|
+
*/
|
|
670
|
+
async isAuthenticated() {
|
|
671
|
+
const credentials = await this.getCredentials();
|
|
672
|
+
if (credentials?.env && credentials?.env !== INWORLD_ENV) {
|
|
673
|
+
print(
|
|
674
|
+
`Warning: Currently saved credentials might not match current Inworld CLI environment.
|
|
675
|
+
|
|
676
|
+
Current Inworld CLI environment is ${INWORLD_ENV}
|
|
677
|
+
Environment of current credentials is ${credentials?.env}
|
|
678
|
+
|
|
679
|
+
You can run "inworld login --force" to login with the correct environment.`
|
|
680
|
+
);
|
|
681
|
+
}
|
|
682
|
+
return credentials !== null && !!credentials.refreshToken;
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
var authManager = new AuthManager();
|
|
686
|
+
|
|
687
|
+
// src/utils/array.ts
|
|
688
|
+
function isArrayOfType(arr, typeGuard) {
|
|
689
|
+
return typeof arr !== "undefined" && Array.isArray(arr) && arr.every(typeGuard);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// src/grpc/core/statusCodes.ts
|
|
693
|
+
var GrpcStatusCode = /* @__PURE__ */ ((GrpcStatusCode2) => {
|
|
694
|
+
GrpcStatusCode2[GrpcStatusCode2["OK"] = 0] = "OK";
|
|
695
|
+
GrpcStatusCode2[GrpcStatusCode2["CANCELLED"] = 1] = "CANCELLED";
|
|
696
|
+
GrpcStatusCode2[GrpcStatusCode2["UNKNOWN"] = 2] = "UNKNOWN";
|
|
697
|
+
GrpcStatusCode2[GrpcStatusCode2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
|
|
698
|
+
GrpcStatusCode2[GrpcStatusCode2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
|
|
699
|
+
GrpcStatusCode2[GrpcStatusCode2["NOT_FOUND"] = 5] = "NOT_FOUND";
|
|
700
|
+
GrpcStatusCode2[GrpcStatusCode2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
|
|
701
|
+
GrpcStatusCode2[GrpcStatusCode2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
|
|
702
|
+
GrpcStatusCode2[GrpcStatusCode2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
|
|
703
|
+
GrpcStatusCode2[GrpcStatusCode2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
|
|
704
|
+
GrpcStatusCode2[GrpcStatusCode2["ABORTED"] = 10] = "ABORTED";
|
|
705
|
+
GrpcStatusCode2[GrpcStatusCode2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
|
|
706
|
+
GrpcStatusCode2[GrpcStatusCode2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
|
|
707
|
+
GrpcStatusCode2[GrpcStatusCode2["INTERNAL"] = 13] = "INTERNAL";
|
|
708
|
+
GrpcStatusCode2[GrpcStatusCode2["UNAVAILABLE"] = 14] = "UNAVAILABLE";
|
|
709
|
+
GrpcStatusCode2[GrpcStatusCode2["DATA_LOSS"] = 15] = "DATA_LOSS";
|
|
710
|
+
GrpcStatusCode2[GrpcStatusCode2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
|
|
711
|
+
return GrpcStatusCode2;
|
|
712
|
+
})(GrpcStatusCode || {});
|
|
713
|
+
function isGrpcStatusCode(value) {
|
|
714
|
+
return Object.values(GrpcStatusCode).includes(value);
|
|
715
|
+
}
|
|
716
|
+
var CommonRetryableGrpcStatusCodes = [
|
|
717
|
+
2 /* UNKNOWN */,
|
|
718
|
+
10 /* ABORTED */,
|
|
719
|
+
1 /* CANCELLED */,
|
|
720
|
+
4 /* DEADLINE_EXCEEDED */,
|
|
721
|
+
13 /* INTERNAL */,
|
|
722
|
+
8 /* RESOURCE_EXHAUSTED */,
|
|
723
|
+
14 /* UNAVAILABLE */
|
|
724
|
+
];
|
|
725
|
+
|
|
726
|
+
// src/grpc/core/InworldError.ts
|
|
727
|
+
function isBadRequestDetails(obj) {
|
|
728
|
+
return typeof obj === "object" && obj !== null && "@type" in obj && typeof obj["@type"] === "string" && "fieldViolations" in obj && (obj.fieldViolations === void 0 || Array.isArray(obj.fieldViolations)) && (typeof obj.requestIndex === "string" || obj.requestIndex === void 0) && (typeof obj.message === "string" || obj.message === void 0);
|
|
729
|
+
}
|
|
730
|
+
function isInworldErrorContract(obj) {
|
|
731
|
+
return (typeof obj === "object" || obj instanceof InworldError) && obj !== null && "code" in obj && "message" in obj && "details" in obj && isArrayOfType(obj.details, isBadRequestDetails);
|
|
732
|
+
}
|
|
733
|
+
function isGrpcError(obj) {
|
|
734
|
+
return (typeof obj === "object" || obj instanceof InworldError) && obj !== null && "code" in obj && isGrpcStatusCode(obj.code);
|
|
735
|
+
}
|
|
736
|
+
var InworldError = class _InworldError extends Error {
|
|
737
|
+
code;
|
|
738
|
+
details;
|
|
739
|
+
metadata;
|
|
740
|
+
constructor(error, metadata) {
|
|
741
|
+
super(error.message);
|
|
742
|
+
if (isInworldErrorContract(error)) {
|
|
743
|
+
this.message = error.message;
|
|
744
|
+
this.code = error.code;
|
|
745
|
+
this.details = error.details;
|
|
746
|
+
} else {
|
|
747
|
+
this.code = 2 /* UNKNOWN */;
|
|
748
|
+
this.details = [];
|
|
749
|
+
}
|
|
750
|
+
this.metadata = metadata;
|
|
751
|
+
Object.setPrototypeOf(this, _InworldError.prototype);
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
// proto/generated/portal/ai/inworld/studio/v1/operations.pb.ts
|
|
756
|
+
var Operations = class {
|
|
757
|
+
static ListOperations(req, initReq) {
|
|
758
|
+
return fetchReq(
|
|
759
|
+
`/studio/v1/${req["name"]}/operations?${renderURLSearchParams(req, ["nameworkspaces"])}`,
|
|
760
|
+
{ ...initReq, method: "GET" }
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
static GetOperation(req, initReq) {
|
|
764
|
+
return fetchReq(
|
|
765
|
+
`/studio/v1/${req["nameworkspacescharactersoperations"]}?${renderURLSearchParams(req, ["nameworkspacescharactersoperations"])}`,
|
|
766
|
+
{ ...initReq, method: "GET" }
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
// src/utils/long_running_operations.ts
|
|
772
|
+
var isOperationError = (obj) => typeof obj === "object" && obj !== null && typeof obj.code === "number" && typeof obj.message === "string" && ("details" in obj ? Array.isArray(obj.details) : true);
|
|
773
|
+
var isLongRunningOperationResponse = (obj) => typeof obj === "object" && obj !== null && typeof obj.name === "string" && typeof obj.done === "boolean" && ("error" in obj ? isOperationError(obj.error) : true);
|
|
774
|
+
var CHECK_LIMIT = 60;
|
|
775
|
+
var CHECK_TIMEOUT = 2e3;
|
|
776
|
+
var checkLRO = async ({
|
|
777
|
+
operationName,
|
|
778
|
+
signal,
|
|
779
|
+
checkLimit,
|
|
780
|
+
checkTimeout,
|
|
781
|
+
pollOptions,
|
|
782
|
+
returnWithMetadata
|
|
783
|
+
}) => {
|
|
784
|
+
let checkResponse;
|
|
785
|
+
checkLimit = checkLimit ?? CHECK_LIMIT;
|
|
786
|
+
checkTimeout = checkTimeout ?? CHECK_TIMEOUT;
|
|
787
|
+
if (pollOptions?.startCallback) {
|
|
788
|
+
pollOptions.startCallback(operationName);
|
|
789
|
+
}
|
|
790
|
+
for (let i = pollOptions?.currentIteration ?? 0; i < checkLimit; i++) {
|
|
791
|
+
signal?.throwIfAborted();
|
|
792
|
+
try {
|
|
793
|
+
checkResponse = await check(operationName, signal, returnWithMetadata);
|
|
794
|
+
if (checkResponse?.done) {
|
|
795
|
+
if (checkResponse?.error || checkResponse?.metadata?.error) {
|
|
796
|
+
pollOptions?.errorCallback?.(
|
|
797
|
+
operationName,
|
|
798
|
+
checkResponse.error || checkResponse?.metadata?.error
|
|
799
|
+
);
|
|
800
|
+
throw checkResponse.error || checkResponse?.metadata?.error;
|
|
801
|
+
}
|
|
802
|
+
pollOptions?.doneCallback?.(operationName, checkResponse?.response);
|
|
803
|
+
return returnWithMetadata ? checkResponse : checkResponse?.response;
|
|
804
|
+
} else {
|
|
805
|
+
pollOptions?.iterationCallback?.(operationName, checkResponse, {
|
|
806
|
+
checkIteration: i,
|
|
807
|
+
checkLimit,
|
|
808
|
+
checkTimeout
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
} catch (error) {
|
|
812
|
+
pollOptions?.errorCallback?.(operationName, error);
|
|
813
|
+
throw error;
|
|
814
|
+
}
|
|
815
|
+
await new Promise((resolve2) => setTimeout(resolve2, checkTimeout));
|
|
816
|
+
}
|
|
817
|
+
throw new Error(
|
|
818
|
+
`Operation timeout. Max number of checks reached ${checkLimit}`
|
|
819
|
+
);
|
|
820
|
+
};
|
|
821
|
+
var check = async (operationName, signal, returnWithMetadata) => retryableAuthenticatedInworldRequest(
|
|
822
|
+
Operations.GetOperation,
|
|
823
|
+
{
|
|
824
|
+
nameworkspacescharactersoperations: operationName
|
|
825
|
+
},
|
|
826
|
+
returnWithMetadata ? {
|
|
827
|
+
withMetadata: true,
|
|
828
|
+
maxRetries: 1,
|
|
829
|
+
backoffFactor: 2,
|
|
830
|
+
minTimeout: 300
|
|
831
|
+
} : void 0,
|
|
832
|
+
signal
|
|
833
|
+
);
|
|
834
|
+
|
|
835
|
+
// src/auth/utils.ts
|
|
836
|
+
async function requireAuth() {
|
|
837
|
+
const isAuthenticated2 = await authManager.isAuthenticated();
|
|
838
|
+
if (!isAuthenticated2) {
|
|
839
|
+
console.log();
|
|
840
|
+
printError("\u274C Authentication required");
|
|
841
|
+
print("You must be logged in to use this command.");
|
|
842
|
+
console.log();
|
|
843
|
+
print("Run: inworld login");
|
|
844
|
+
process.exit(1);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
async function requireWorkspace() {
|
|
848
|
+
const workspaceResourceName = await authManager.getWorkspace();
|
|
849
|
+
if (!workspaceResourceName) {
|
|
850
|
+
console.log();
|
|
851
|
+
printError("\u274C Workspace required");
|
|
852
|
+
print('Please run "inworld ws select" to select a workspace.');
|
|
853
|
+
process.exit(1);
|
|
854
|
+
}
|
|
855
|
+
return workspaceResourceName;
|
|
856
|
+
}
|
|
857
|
+
async function requireApiKey() {
|
|
858
|
+
let apiKey;
|
|
859
|
+
if (process.env.INWORLD_API_KEY) {
|
|
860
|
+
apiKey = process.env.INWORLD_API_KEY;
|
|
861
|
+
} else {
|
|
862
|
+
apiKey = await authManager.getApiKey();
|
|
863
|
+
}
|
|
864
|
+
if (!apiKey) {
|
|
865
|
+
console.log();
|
|
866
|
+
printError("\u274C API key required");
|
|
867
|
+
print(
|
|
868
|
+
'Please export "INWORLD_API_KEY" to environment variable or run "inworld login" to login.'
|
|
869
|
+
);
|
|
870
|
+
process.exit(1);
|
|
871
|
+
}
|
|
872
|
+
return apiKey;
|
|
873
|
+
}
|
|
874
|
+
var InworldError2 = class _InworldError extends Error {
|
|
875
|
+
code;
|
|
876
|
+
details;
|
|
877
|
+
metadata;
|
|
878
|
+
constructor(error, metadata) {
|
|
879
|
+
super(error.message);
|
|
880
|
+
if (isInworldErrorContract(error)) {
|
|
881
|
+
this.message = error.message;
|
|
882
|
+
this.code = error.code;
|
|
883
|
+
this.details = error.details;
|
|
884
|
+
} else {
|
|
885
|
+
this.code = 2 /* UNKNOWN */;
|
|
886
|
+
this.details = [];
|
|
887
|
+
}
|
|
888
|
+
this.metadata = metadata;
|
|
889
|
+
Object.setPrototypeOf(this, _InworldError.prototype);
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
async function retryableAuthenticatedInworldRequest(pb, req, options = {
|
|
893
|
+
maxRetries: 5,
|
|
894
|
+
backoffFactor: 2,
|
|
895
|
+
minTimeout: 300
|
|
896
|
+
}, signal) {
|
|
897
|
+
const maxRetries = options.maxRetries;
|
|
898
|
+
const backoffFactor = options.backoffFactor;
|
|
899
|
+
const minTimeout = options.minTimeout;
|
|
900
|
+
const maxTimeout = options.maxTimeout ?? minTimeout * backoffFactor ** maxRetries * 2;
|
|
901
|
+
const retryRequest = async (currentAttempt, signal2) => {
|
|
902
|
+
signal2?.throwIfAborted();
|
|
903
|
+
try {
|
|
904
|
+
const response = await authenticatedInworldRequest(pb, req);
|
|
905
|
+
if (isLongRunningOperationResponse(response) && response?.done) {
|
|
906
|
+
if ((response?.error || response?.metadata?.error) && options.withMetadata) {
|
|
907
|
+
throw response;
|
|
908
|
+
}
|
|
909
|
+
if (response?.error) {
|
|
910
|
+
throw response.error;
|
|
911
|
+
}
|
|
912
|
+
return response;
|
|
913
|
+
}
|
|
914
|
+
return response;
|
|
915
|
+
} catch (cause) {
|
|
916
|
+
const error = cause;
|
|
917
|
+
const isGrpcGatewayError = isGrpcError(cause);
|
|
918
|
+
const allowRetry = isGrpcGatewayError && CommonRetryableGrpcStatusCodes.includes(error.code) || !isGrpcGatewayError;
|
|
919
|
+
if (allowRetry && currentAttempt < maxRetries) {
|
|
920
|
+
const timeout = Math.min(
|
|
921
|
+
minTimeout * Math.pow(backoffFactor, currentAttempt),
|
|
922
|
+
maxTimeout
|
|
923
|
+
);
|
|
924
|
+
return new Promise((resolve2) => {
|
|
925
|
+
setTimeout(() => {
|
|
926
|
+
resolve2(retryRequest(currentAttempt + 1));
|
|
927
|
+
}, timeout);
|
|
928
|
+
});
|
|
929
|
+
} else {
|
|
930
|
+
throw new InworldError2(
|
|
931
|
+
error.metadata ? error.error : error,
|
|
932
|
+
error.metadata
|
|
933
|
+
);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
return retryRequest(1, signal);
|
|
938
|
+
}
|
|
939
|
+
var authenticatedInworldRequest = async (pb, req, inworldToken, signal) => {
|
|
940
|
+
if (!inworldToken) {
|
|
941
|
+
requireAuth();
|
|
942
|
+
inworldToken = await authManager.getValidToken() || "";
|
|
943
|
+
}
|
|
944
|
+
if (inworldToken) {
|
|
945
|
+
const request = {
|
|
946
|
+
...{
|
|
947
|
+
headers: {
|
|
948
|
+
Authorization: `Bearer ${inworldToken}`,
|
|
949
|
+
"Grpc-Metadata-X-Authorization-Bearer-Type": "inworld"
|
|
950
|
+
}
|
|
951
|
+
},
|
|
952
|
+
pathPrefix: PLATFORM_URL,
|
|
953
|
+
signal
|
|
954
|
+
};
|
|
955
|
+
return pb(req, request);
|
|
956
|
+
}
|
|
957
|
+
};
|
|
958
|
+
|
|
959
|
+
// src/services/workspace_service.ts
|
|
960
|
+
import chalk2 from "chalk";
|
|
961
|
+
|
|
962
|
+
// proto/generated/portal/ai/inworld/studio/v1alpha/apikeys.pb.ts
|
|
963
|
+
var ApiKeys = class {
|
|
964
|
+
static ListApiKeys(req, initReq) {
|
|
965
|
+
return fetchReq(
|
|
966
|
+
`/v1alpha/${req["parent"]}/apikeys?${renderURLSearchParams(req, ["parent"])}`,
|
|
967
|
+
{ ...initReq, method: "GET" }
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
static SuspendApiKey(req, initReq) {
|
|
971
|
+
return fetchReq(
|
|
972
|
+
`/v1alpha/${req["name"]}:suspend`,
|
|
973
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
static ActivateApiKey(req, initReq) {
|
|
977
|
+
return fetchReq(
|
|
978
|
+
`/v1alpha/${req["name"]}:activate`,
|
|
979
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
static DeleteApiKey(req, initReq) {
|
|
983
|
+
return fetchReq(
|
|
984
|
+
`/v1alpha/${req["name"]}`,
|
|
985
|
+
{ ...initReq, method: "DELETE" }
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
static GenerateApiKey(req, initReq) {
|
|
989
|
+
return fetchReq(
|
|
990
|
+
`/v1alpha/${req["parent"]}/apikey:generate`,
|
|
991
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
static ListAuthScopes(req, initReq) {
|
|
995
|
+
return fetchReq(
|
|
996
|
+
`/v1alpha/${req["parent"]}/auth-scopes?${renderURLSearchParams(req, ["parent"])}`,
|
|
997
|
+
{ ...initReq, method: "GET" }
|
|
998
|
+
);
|
|
999
|
+
}
|
|
1000
|
+
};
|
|
1001
|
+
|
|
1002
|
+
// proto/generated/portal/ai/inworld/studio/v1alpha/workspaces.pb.ts
|
|
1003
|
+
var Workspaces = class {
|
|
1004
|
+
static GetWorkspace(req, initReq) {
|
|
1005
|
+
return fetchReq(
|
|
1006
|
+
`/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["nameworkspaces"])}`,
|
|
1007
|
+
{ ...initReq, method: "GET" }
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
static ListWorkspaces(req, initReq) {
|
|
1011
|
+
return fetchReq(
|
|
1012
|
+
`/v1alpha/workspaces?${renderURLSearchParams(req, [])}`,
|
|
1013
|
+
{ ...initReq, method: "GET" }
|
|
1014
|
+
);
|
|
1015
|
+
}
|
|
1016
|
+
static UpdateWorkspace(req, initReq) {
|
|
1017
|
+
return fetchReq(
|
|
1018
|
+
`/v1alpha/${req["workspace"]["name"]}`,
|
|
1019
|
+
{
|
|
1020
|
+
...initReq,
|
|
1021
|
+
method: "PATCH",
|
|
1022
|
+
body: JSON.stringify(req["workspace"], replacer)
|
|
1023
|
+
}
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
static CreateWorkspace(req, initReq) {
|
|
1027
|
+
return fetchReq(
|
|
1028
|
+
`/v1alpha/workspaces`,
|
|
1029
|
+
{
|
|
1030
|
+
...initReq,
|
|
1031
|
+
method: "POST",
|
|
1032
|
+
body: JSON.stringify(req["workspace"], replacer)
|
|
1033
|
+
}
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
static DeleteWorkspace(req, initReq) {
|
|
1037
|
+
return fetchReq(
|
|
1038
|
+
`/v1alpha/${req["name"]}`,
|
|
1039
|
+
{ ...initReq, method: "DELETE" }
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
static CloneWorkspace(req, initReq) {
|
|
1043
|
+
return fetchReq(
|
|
1044
|
+
`/v1alpha/${req["name"]}:clone`,
|
|
1045
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
1046
|
+
);
|
|
1047
|
+
}
|
|
1048
|
+
static ShareWorkspace(req, initReq) {
|
|
1049
|
+
return fetchReq(
|
|
1050
|
+
`/v1alpha/${req["name"]}:share`,
|
|
1051
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
1054
|
+
static generateResourceName(req, initReq) {
|
|
1055
|
+
return fetchReq(`/v1alpha/${req["workspace"]}:generateResourceName`, {
|
|
1056
|
+
...initReq,
|
|
1057
|
+
method: "POST",
|
|
1058
|
+
body: JSON.stringify(req, replacer)
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
static GetWorkspaceShareInfo(req, initReq) {
|
|
1062
|
+
return fetchReq(
|
|
1063
|
+
`/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
|
|
1064
|
+
{ ...initReq, method: "GET" }
|
|
1065
|
+
);
|
|
1066
|
+
}
|
|
1067
|
+
static GetWorkspaceLimitInfo(req, initReq) {
|
|
1068
|
+
return fetchReq(
|
|
1069
|
+
`/v1alpha/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
|
|
1070
|
+
{ ...initReq, method: "GET" }
|
|
1071
|
+
);
|
|
1072
|
+
}
|
|
1073
|
+
static RemainWorkspaceLimitInfo(req, initReq) {
|
|
1074
|
+
return fetchReq(
|
|
1075
|
+
`/v1alpha/${req["name"]}:remain?${renderURLSearchParams(req, ["name"])}`,
|
|
1076
|
+
{ ...initReq, method: "GET" }
|
|
1077
|
+
);
|
|
1078
|
+
}
|
|
1079
|
+
static SendImpressionEvent(req, initReq) {
|
|
1080
|
+
return fetchReq(
|
|
1081
|
+
`/v1alpha/${req["name"]}:impression`,
|
|
1082
|
+
{ ...initReq, method: "POST", body: JSON.stringify(req, replacer) }
|
|
1083
|
+
);
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
// src/utils/resource_name_helper.ts
|
|
1088
|
+
var parseWorkspaceResourceName = (resourceName) => {
|
|
1089
|
+
const [collection, workspaceId] = resourceName.split("/");
|
|
1090
|
+
if (collection !== "workspaces") {
|
|
1091
|
+
throw new Error(`Invalid workspace resource name: ${resourceName}`);
|
|
1092
|
+
}
|
|
1093
|
+
return { workspaceId };
|
|
1094
|
+
};
|
|
1095
|
+
var getGraphResourceName = (workspaceId, graphId) => {
|
|
1096
|
+
return `workspaces/${workspaceId}/graphs/${graphId}`;
|
|
1097
|
+
};
|
|
1098
|
+
var getGraphVariantResourceName = (workspaceId, graphId, variantId) => {
|
|
1099
|
+
return `${getGraphResourceName(workspaceId, graphId)}/variants/${variantId}`;
|
|
1100
|
+
};
|
|
1101
|
+
var getWorkspaceResourceName = (workspaceId) => {
|
|
1102
|
+
return `workspaces/${workspaceId}`;
|
|
1103
|
+
};
|
|
1104
|
+
|
|
1105
|
+
// src/utils/selector.ts
|
|
1106
|
+
import * as readline from "readline";
|
|
1107
|
+
async function selectItem(options) {
|
|
1108
|
+
const {
|
|
1109
|
+
items,
|
|
1110
|
+
getDisplayName,
|
|
1111
|
+
getIdentifier,
|
|
1112
|
+
prompt,
|
|
1113
|
+
title,
|
|
1114
|
+
forceFirst = false,
|
|
1115
|
+
noItemsMessage = "No items found.",
|
|
1116
|
+
invalidSelectionMessage = "Invalid selection. Please enter a valid number or identifier."
|
|
1117
|
+
} = options;
|
|
1118
|
+
if (items.length === 0) {
|
|
1119
|
+
printError(noItemsMessage);
|
|
1120
|
+
return null;
|
|
1121
|
+
}
|
|
1122
|
+
if (forceFirst) {
|
|
1123
|
+
return items[0];
|
|
1124
|
+
}
|
|
1125
|
+
console.log();
|
|
1126
|
+
header(title);
|
|
1127
|
+
items.forEach((item, idx) => {
|
|
1128
|
+
const displayName = getDisplayName(item);
|
|
1129
|
+
const identifier = getIdentifier(item);
|
|
1130
|
+
listItem(`${idx + 1}. ${displayName} (ID: ${identifier})`);
|
|
1131
|
+
});
|
|
1132
|
+
const rl = readline.createInterface({
|
|
1133
|
+
input: process.stdin,
|
|
1134
|
+
output: process.stdout
|
|
1135
|
+
});
|
|
1136
|
+
const question = (query) => new Promise((resolve2) => rl.question(query, resolve2));
|
|
1137
|
+
let selectedItem = null;
|
|
1138
|
+
try {
|
|
1139
|
+
while (!selectedItem) {
|
|
1140
|
+
const answer = (await question(`
|
|
1141
|
+
${prompt} `)).trim();
|
|
1142
|
+
const idx = parseInt(answer, 10);
|
|
1143
|
+
if (!isNaN(idx) && idx >= 1 && idx <= items.length) {
|
|
1144
|
+
selectedItem = items[idx - 1];
|
|
1145
|
+
} else {
|
|
1146
|
+
selectedItem = items.find((item) => {
|
|
1147
|
+
const identifier = getIdentifier(item);
|
|
1148
|
+
return identifier === answer || identifier.split("/").pop() === answer;
|
|
1149
|
+
}) || null;
|
|
1150
|
+
}
|
|
1151
|
+
if (!selectedItem) {
|
|
1152
|
+
printError(invalidSelectionMessage);
|
|
1153
|
+
break;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
} finally {
|
|
1157
|
+
rl.close();
|
|
1158
|
+
}
|
|
1159
|
+
return selectedItem;
|
|
1160
|
+
}
|
|
1161
|
+
async function selectItemOrExit(options) {
|
|
1162
|
+
const { exitOnFailure = true, ...selectorOptions } = options;
|
|
1163
|
+
const selected = await selectItem(selectorOptions);
|
|
1164
|
+
if (!selected && exitOnFailure) {
|
|
1165
|
+
process.exit(1);
|
|
1166
|
+
}
|
|
1167
|
+
return selected;
|
|
1168
|
+
}
|
|
1169
|
+
function trimBase64Key(key) {
|
|
1170
|
+
return key.substring(0, 10) + "..." + key.substring(key.length - 10);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// src/services/workspace_service.ts
|
|
1174
|
+
var WorkspaceService = class {
|
|
1175
|
+
/**
|
|
1176
|
+
* Prompts user to select a workspace from available workspaces
|
|
1177
|
+
* @param forceFirst If true, automatically selects the first workspace
|
|
1178
|
+
* @returns The resource name of the selected workspace
|
|
1179
|
+
*/
|
|
1180
|
+
static async pickWorkspace(forceFirst = false) {
|
|
1181
|
+
const listWorkspacesResponse = await authenticatedInworldRequest(
|
|
1182
|
+
Workspaces.ListWorkspaces,
|
|
1183
|
+
{
|
|
1184
|
+
pageSize: forceFirst ? 1 : WORKSPACES_LIST_SIZE
|
|
1185
|
+
}
|
|
1186
|
+
);
|
|
1187
|
+
const workspaces = listWorkspacesResponse?.workspaces || [];
|
|
1188
|
+
const selectedWorkspace = await selectItemOrExit({
|
|
1189
|
+
items: workspaces,
|
|
1190
|
+
getDisplayName: (ws) => ws.displayName || ws.name?.split("/").pop() || "unknown",
|
|
1191
|
+
getIdentifier: (ws) => ws.name?.split("/").pop() || "unknown",
|
|
1192
|
+
prompt: "Enter the number or resource name of the workspace to activate:",
|
|
1193
|
+
title: "Available workspaces:",
|
|
1194
|
+
forceFirst,
|
|
1195
|
+
noItemsMessage: "No workspaces found.",
|
|
1196
|
+
invalidSelectionMessage: "Invalid selection. Please enter a valid number or workspace resource name."
|
|
1197
|
+
});
|
|
1198
|
+
return selectedWorkspace.name;
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Prompts user to select an API key from available API keys
|
|
1202
|
+
* @param apiKeys List of API keys to select from
|
|
1203
|
+
* @param forceFirst If true, automatically selects the first API key
|
|
1204
|
+
* @returns The selected API key or null if no selection was made
|
|
1205
|
+
*/
|
|
1206
|
+
static async pickApiKey(apiKeys, forceFirst = false) {
|
|
1207
|
+
return selectItemOrExit({
|
|
1208
|
+
items: apiKeys,
|
|
1209
|
+
getDisplayName: (apiKey) => {
|
|
1210
|
+
const name = apiKey.name?.split("/").pop() || "unknown";
|
|
1211
|
+
const createdAt = apiKey.createTime ? new Date(apiKey.createTime).toLocaleDateString() : "unknown date";
|
|
1212
|
+
return `${name} (created: ${createdAt})`;
|
|
1213
|
+
},
|
|
1214
|
+
getIdentifier: (apiKey) => apiKey.name?.split("/").pop() || "unknown",
|
|
1215
|
+
prompt: "Enter the number or resource name of the API key to use:",
|
|
1216
|
+
title: "Available API keys:",
|
|
1217
|
+
forceFirst,
|
|
1218
|
+
noItemsMessage: "No API keys found.",
|
|
1219
|
+
invalidSelectionMessage: "Invalid selection. Please enter a valid number or API key resource name."
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
static returnBase64 = (key, secret) => {
|
|
1223
|
+
const encodedKeySecret = new TextEncoder().encode(`${key}:${secret}`);
|
|
1224
|
+
return btoa(String.fromCharCode.apply(null, Array.from(encodedKeySecret)));
|
|
1225
|
+
};
|
|
1226
|
+
/**
|
|
1227
|
+
* Activates a workspace by selecting it and its associated API key.
|
|
1228
|
+
* If no API key exists, prompts the user to generate one.
|
|
1229
|
+
*
|
|
1230
|
+
* @param options Configuration options
|
|
1231
|
+
* @param options.forceFirst If true, automatically selects the first workspace and API key
|
|
1232
|
+
*/
|
|
1233
|
+
static async activateWorkspace({
|
|
1234
|
+
forceFirst
|
|
1235
|
+
} = {}) {
|
|
1236
|
+
const workspaceResourceName = await this.pickWorkspace(forceFirst);
|
|
1237
|
+
const workspaceId = parseWorkspaceResourceName(
|
|
1238
|
+
workspaceResourceName
|
|
1239
|
+
).workspaceId;
|
|
1240
|
+
print(`
|
|
1241
|
+
Selecting workspace: ${chalk2.white(workspaceId)}...`);
|
|
1242
|
+
let apiKey = null;
|
|
1243
|
+
const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
|
|
1244
|
+
parent: workspaceResourceName,
|
|
1245
|
+
pageSize: forceFirst ? 1 : WORKSPACES_LIST_SIZE
|
|
1246
|
+
});
|
|
1247
|
+
if (response?.apiKeys?.length) {
|
|
1248
|
+
if (response.apiKeys.length === 1 || forceFirst) {
|
|
1249
|
+
apiKey = response.apiKeys[0];
|
|
1250
|
+
} else {
|
|
1251
|
+
print(`Found ${response.apiKeys.length} API keys in the workspace.`);
|
|
1252
|
+
apiKey = await this.pickApiKey(response.apiKeys, false);
|
|
1253
|
+
}
|
|
1254
|
+
} else {
|
|
1255
|
+
const readline5 = await import("readline");
|
|
1256
|
+
const rl = readline5.createInterface({
|
|
1257
|
+
input: process.stdin,
|
|
1258
|
+
output: process.stdout
|
|
1259
|
+
});
|
|
1260
|
+
await new Promise((resolve2) => {
|
|
1261
|
+
rl.question(
|
|
1262
|
+
"No API keys found for this workspace. Would you like to generate one? (y/N): ",
|
|
1263
|
+
async (answer) => {
|
|
1264
|
+
if (answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes") {
|
|
1265
|
+
print("Generating API key...");
|
|
1266
|
+
const generateApiKeyResponse = await authenticatedInworldRequest(
|
|
1267
|
+
ApiKeys.GenerateApiKey,
|
|
1268
|
+
{
|
|
1269
|
+
parent: workspaceResourceName
|
|
1270
|
+
}
|
|
1271
|
+
);
|
|
1272
|
+
if (!generateApiKeyResponse) {
|
|
1273
|
+
printError("Failed to generate API key.");
|
|
1274
|
+
process.exit(1);
|
|
1275
|
+
}
|
|
1276
|
+
apiKey = generateApiKeyResponse;
|
|
1277
|
+
success("API key generated successfully.");
|
|
1278
|
+
} else {
|
|
1279
|
+
print("No API key will be generated.");
|
|
1280
|
+
}
|
|
1281
|
+
rl.close();
|
|
1282
|
+
resolve2();
|
|
1283
|
+
}
|
|
1284
|
+
);
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
const base64Key = this.returnBase64(apiKey?.key, apiKey?.secret);
|
|
1288
|
+
print(`Selecting API key: ${chalk2.white(trimBase64Key(base64Key))}...`);
|
|
1289
|
+
await authManager.updateWorkspaceAndApiKey(workspaceId, base64Key);
|
|
1290
|
+
success("\nWorkspace and API key selected.");
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Lists all API keys for the currently active workspace
|
|
1294
|
+
*/
|
|
1295
|
+
static async listApiKeys() {
|
|
1296
|
+
const credentials = await authManager.getCredentials();
|
|
1297
|
+
if (!credentials?.workspace) {
|
|
1298
|
+
printError(
|
|
1299
|
+
'No workspace activated. Please run "inworld workspace activate" first.'
|
|
1300
|
+
);
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
|
|
1304
|
+
parent: credentials.workspace,
|
|
1305
|
+
pageSize: WORKSPACES_LIST_SIZE
|
|
1306
|
+
});
|
|
1307
|
+
const apiKeys = response?.apiKeys || [];
|
|
1308
|
+
if (apiKeys.length === 0) {
|
|
1309
|
+
printError("No API keys found in the active workspace.");
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
console.log();
|
|
1313
|
+
header(`API keys in workspace ${credentials.workspace}:`);
|
|
1314
|
+
apiKeys.forEach((apiKey, idx) => {
|
|
1315
|
+
const name = apiKey.name?.split("/").pop() || "unknown";
|
|
1316
|
+
const createdAt = apiKey.createTime ? new Date(apiKey.createTime).toLocaleDateString() : "unknown date";
|
|
1317
|
+
const state = apiKey.state || "unknown";
|
|
1318
|
+
listItem(
|
|
1319
|
+
`${idx + 1}. ${name} (created: ${createdAt}, state: ${state})`
|
|
1320
|
+
);
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Allows user to select and activate a different API key from the current workspace
|
|
1325
|
+
*/
|
|
1326
|
+
static async selectApiKey() {
|
|
1327
|
+
const credentials = await authManager.getCredentials();
|
|
1328
|
+
if (!credentials?.workspace) {
|
|
1329
|
+
printError(
|
|
1330
|
+
'No workspace activated. Please run "inworld workspace activate" first.'
|
|
1331
|
+
);
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
const response = await authenticatedInworldRequest(ApiKeys.ListApiKeys, {
|
|
1335
|
+
parent: credentials.workspace,
|
|
1336
|
+
pageSize: WORKSPACES_LIST_SIZE
|
|
1337
|
+
});
|
|
1338
|
+
const apiKeys = response?.apiKeys || [];
|
|
1339
|
+
if (apiKeys.length === 0) {
|
|
1340
|
+
printError("No API keys found in the active workspace.");
|
|
1341
|
+
const readline5 = await import("readline");
|
|
1342
|
+
const rl = readline5.createInterface({
|
|
1343
|
+
input: process.stdin,
|
|
1344
|
+
output: process.stdout
|
|
1345
|
+
});
|
|
1346
|
+
await new Promise((resolve2) => {
|
|
1347
|
+
rl.question(
|
|
1348
|
+
"Would you like to generate a new API key? (y/N): ",
|
|
1349
|
+
async (answer) => {
|
|
1350
|
+
if (answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes") {
|
|
1351
|
+
rl.close();
|
|
1352
|
+
resolve2();
|
|
1353
|
+
await this.generateApiKey();
|
|
1354
|
+
} else {
|
|
1355
|
+
rl.close();
|
|
1356
|
+
resolve2();
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
);
|
|
1360
|
+
});
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
if (apiKeys.length === 1) {
|
|
1364
|
+
print("Only one API key found in the workspace.");
|
|
1365
|
+
const apiKey = apiKeys[0];
|
|
1366
|
+
const base64Key = this.returnBase64(apiKey?.key, apiKey?.secret);
|
|
1367
|
+
await authManager.updateWorkspaceAndApiKey(
|
|
1368
|
+
credentials.workspace,
|
|
1369
|
+
base64Key
|
|
1370
|
+
);
|
|
1371
|
+
success("API key activated successfully.");
|
|
1372
|
+
return;
|
|
1373
|
+
}
|
|
1374
|
+
const selectedApiKey = await this.pickApiKey(apiKeys, false);
|
|
1375
|
+
if (selectedApiKey) {
|
|
1376
|
+
const base64Key = this.returnBase64(
|
|
1377
|
+
selectedApiKey.key,
|
|
1378
|
+
selectedApiKey.secret
|
|
1379
|
+
);
|
|
1380
|
+
await authManager.updateWorkspaceAndApiKey(
|
|
1381
|
+
credentials.workspace,
|
|
1382
|
+
base64Key
|
|
1383
|
+
);
|
|
1384
|
+
success("API key activated successfully.");
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* Generates a new API key for the currently active workspace
|
|
1389
|
+
*/
|
|
1390
|
+
static async generateApiKey() {
|
|
1391
|
+
const credentials = await authManager.getCredentials();
|
|
1392
|
+
if (!credentials?.workspace) {
|
|
1393
|
+
printError(
|
|
1394
|
+
'No workspace activated. Please run "inworld workspace activate" first.'
|
|
1395
|
+
);
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
print("Generating new API key...");
|
|
1399
|
+
const generateApiKeyResponse = await authenticatedInworldRequest(
|
|
1400
|
+
ApiKeys.GenerateApiKey,
|
|
1401
|
+
{
|
|
1402
|
+
parent: credentials.workspace
|
|
1403
|
+
}
|
|
1404
|
+
);
|
|
1405
|
+
if (!generateApiKeyResponse) {
|
|
1406
|
+
printError("Failed to generate API key.");
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
const base64Key = this.returnBase64(
|
|
1410
|
+
generateApiKeyResponse.key,
|
|
1411
|
+
generateApiKeyResponse.secret
|
|
1412
|
+
);
|
|
1413
|
+
await authManager.updateWorkspaceAndApiKey(
|
|
1414
|
+
credentials.workspace,
|
|
1415
|
+
base64Key
|
|
1416
|
+
);
|
|
1417
|
+
success("API key activated successfully.");
|
|
1418
|
+
success("API key generated and activated successfully.");
|
|
1419
|
+
console.log();
|
|
1420
|
+
header("API Key details:");
|
|
1421
|
+
listItem(
|
|
1422
|
+
`Name: ${generateApiKeyResponse.name?.split("/").pop() || "unknown"}`
|
|
1423
|
+
);
|
|
1424
|
+
listItem(`Key: ${generateApiKeyResponse.key}`);
|
|
1425
|
+
listItem(`Base64: ${base64Key}`);
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
|
|
1429
|
+
// src/commands/auth/login_command.ts
|
|
1430
|
+
var execAsync = promisify(exec);
|
|
1431
|
+
var loginAction = async (options) => {
|
|
1432
|
+
let authServerResult = null;
|
|
1433
|
+
try {
|
|
1434
|
+
if (!options.force && await authManager.isAuthenticated()) {
|
|
1435
|
+
const credentials = await authManager.getCredentials();
|
|
1436
|
+
const email = credentials?.email || "Unknown";
|
|
1437
|
+
console.log();
|
|
1438
|
+
print("\u26A0 You are already authenticated");
|
|
1439
|
+
print(`Current account: ${email}`);
|
|
1440
|
+
console.log();
|
|
1441
|
+
print("Use --force flag to re-authenticate:");
|
|
1442
|
+
print(" inworld login --force");
|
|
1443
|
+
const isValid = await authManager.isTokenValid();
|
|
1444
|
+
if (!isValid) {
|
|
1445
|
+
console.log();
|
|
1446
|
+
print(
|
|
1447
|
+
"Note: Your token has expired but will be automatically refreshed when needed."
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
process.exit(0);
|
|
1451
|
+
}
|
|
1452
|
+
console.log();
|
|
1453
|
+
header("\u{1F3AD} Welcome to Inworld CLI!");
|
|
1454
|
+
if (options.force && await authManager.isAuthenticated()) {
|
|
1455
|
+
const credentials = await authManager.getCredentials();
|
|
1456
|
+
const email = credentials?.email || "Unknown";
|
|
1457
|
+
print(`Currently logged in as: ${email}`);
|
|
1458
|
+
print("Proceeding with re-authentication...");
|
|
1459
|
+
console.log();
|
|
1460
|
+
} else {
|
|
1461
|
+
print("Let's get you authenticated.");
|
|
1462
|
+
console.log();
|
|
1463
|
+
}
|
|
1464
|
+
const serverPromise = createCallbackServer({
|
|
1465
|
+
port: INWORLD_CLI_AUTH_CALLBACK_PORT
|
|
1466
|
+
});
|
|
1467
|
+
print("Please visit the following URL to authenticate:");
|
|
1468
|
+
printLink(`${INWORLD_CLI_AUTH_URL}
|
|
1469
|
+
`);
|
|
1470
|
+
const readlineInterface = readline2.createInterface({
|
|
1471
|
+
input: process.stdin,
|
|
1472
|
+
output: process.stdout
|
|
1473
|
+
});
|
|
1474
|
+
const enterPromise = new Promise((resolve2) => {
|
|
1475
|
+
readlineInterface.question("Press Enter to open your browser...", () => {
|
|
1476
|
+
resolve2();
|
|
1477
|
+
});
|
|
1478
|
+
});
|
|
1479
|
+
const result = await Promise.race([
|
|
1480
|
+
enterPromise.then(() => ({ type: "enter" })),
|
|
1481
|
+
serverPromise.then((result2) => ({ type: "auth", result: result2 }))
|
|
1482
|
+
]);
|
|
1483
|
+
readlineInterface.close();
|
|
1484
|
+
if (result.type === "auth") {
|
|
1485
|
+
authServerResult = result.result;
|
|
1486
|
+
} else {
|
|
1487
|
+
const openCommand = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
|
|
1488
|
+
try {
|
|
1489
|
+
await execAsync(`${openCommand} ${INWORLD_CLI_AUTH_URL}`);
|
|
1490
|
+
success("\u2713 Browser opened");
|
|
1491
|
+
} catch (_error) {
|
|
1492
|
+
print(
|
|
1493
|
+
"\u26A0 Could not open browser automatically. Please open the URL manually."
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1496
|
+
console.log();
|
|
1497
|
+
print("Waiting for authentication...");
|
|
1498
|
+
authServerResult = await serverPromise;
|
|
1499
|
+
}
|
|
1500
|
+
console.log();
|
|
1501
|
+
success("\u2713 Authentication successful!");
|
|
1502
|
+
console.log();
|
|
1503
|
+
print("User information:");
|
|
1504
|
+
printBright(`Email: ${authServerResult.email}
|
|
1505
|
+
`);
|
|
1506
|
+
const success2 = await authManager.authenticateAndSaveCredentials(
|
|
1507
|
+
authServerResult.token,
|
|
1508
|
+
authServerResult.refreshToken,
|
|
1509
|
+
authServerResult.email,
|
|
1510
|
+
/* workspace */
|
|
1511
|
+
void 0,
|
|
1512
|
+
INWORLD_ENV
|
|
1513
|
+
);
|
|
1514
|
+
if (!success2) {
|
|
1515
|
+
printError("\nFailed to complete authentication setup");
|
|
1516
|
+
print("You may need to login again.");
|
|
1517
|
+
}
|
|
1518
|
+
stopCallbackServer(authServerResult.server);
|
|
1519
|
+
console.log();
|
|
1520
|
+
print("You are now authenticated with Inworld services.");
|
|
1521
|
+
print("Your credentials have been securely stored.");
|
|
1522
|
+
await WorkspaceService.activateWorkspace({ forceFirst: true });
|
|
1523
|
+
print("\nIf you want to change the workspace, you can run command:");
|
|
1524
|
+
printBright("inworld workspace select");
|
|
1525
|
+
print(
|
|
1526
|
+
"\nIf you want to see authentication status, you can run command:"
|
|
1527
|
+
);
|
|
1528
|
+
printBright("inworld auth status");
|
|
1529
|
+
print("\nAuthentication completed.");
|
|
1530
|
+
process.exit(0);
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
if (authServerResult?.server) {
|
|
1533
|
+
try {
|
|
1534
|
+
await stopCallbackServer(authServerResult.server);
|
|
1535
|
+
} catch (_closeError) {
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
console.log();
|
|
1539
|
+
printError("Authentication failed:");
|
|
1540
|
+
console.error(error);
|
|
1541
|
+
process.exit(1);
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
var makeLoginCommand = (description) => {
|
|
1545
|
+
return new Command("login").description(description).option("-f, --force", "Force re-authentication even if already logged in").action(loginAction);
|
|
1546
|
+
};
|
|
1547
|
+
var loginCommand = makeLoginCommand(
|
|
1548
|
+
"Authenticate with Inworld Platform"
|
|
1549
|
+
);
|
|
1550
|
+
var loginCommandAlias = makeLoginCommand(
|
|
1551
|
+
`Alias for "${chalk3.bold("inworld auth login")}"`
|
|
1552
|
+
);
|
|
1553
|
+
|
|
1554
|
+
// src/commands/auth/logout_command.ts
|
|
1555
|
+
import chalk4 from "chalk";
|
|
1556
|
+
import { Command as Command2 } from "commander";
|
|
1557
|
+
import * as readline3 from "readline";
|
|
1558
|
+
var logoutAction = async (options) => {
|
|
1559
|
+
try {
|
|
1560
|
+
const isAuthenticated2 = await authManager.isAuthenticated();
|
|
1561
|
+
if (!isAuthenticated2) {
|
|
1562
|
+
print("You are not currently authenticated.");
|
|
1563
|
+
process.exit(0);
|
|
1564
|
+
}
|
|
1565
|
+
const credentials = await authManager.getCredentials();
|
|
1566
|
+
const email = credentials?.email || "Unknown user";
|
|
1567
|
+
console.log();
|
|
1568
|
+
header("\u{1F3AD} Inworld CLI - Logout");
|
|
1569
|
+
print(`Current account: ${email}`);
|
|
1570
|
+
if (!options.force) {
|
|
1571
|
+
const rl = readline3.createInterface({
|
|
1572
|
+
input: process.stdin,
|
|
1573
|
+
output: process.stdout
|
|
1574
|
+
});
|
|
1575
|
+
const confirmed = await new Promise((resolve2) => {
|
|
1576
|
+
rl.question("\nAre you sure you want to logout? (y/N): ", (answer) => {
|
|
1577
|
+
rl.close();
|
|
1578
|
+
resolve2(
|
|
1579
|
+
answer.toLowerCase() === "y" || answer.toLowerCase() === "yes"
|
|
1580
|
+
);
|
|
1581
|
+
});
|
|
1582
|
+
});
|
|
1583
|
+
if (!confirmed) {
|
|
1584
|
+
console.log();
|
|
1585
|
+
print("Logout cancelled.");
|
|
1586
|
+
process.exit(0);
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
console.log();
|
|
1590
|
+
print("Clearing stored credentials...");
|
|
1591
|
+
await authManager.clearCredentials();
|
|
1592
|
+
success("\u2713 Successfully logged out.");
|
|
1593
|
+
print("You will need to authenticate again to use Inworld services.");
|
|
1594
|
+
process.exit(0);
|
|
1595
|
+
} catch (error) {
|
|
1596
|
+
console.log();
|
|
1597
|
+
printError("Failed to logout:");
|
|
1598
|
+
console.error(error);
|
|
1599
|
+
process.exit(1);
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
var makeLogoutCommand = (description) => {
|
|
1603
|
+
return new Command2("logout").description(description).option("-f, --force", "Skip confirmation prompt").action(logoutAction);
|
|
1604
|
+
};
|
|
1605
|
+
var logoutCommandAlias = makeLogoutCommand(
|
|
1606
|
+
`Alias for "${chalk4.bold("inworld auth logout")}"`
|
|
1607
|
+
);
|
|
1608
|
+
var logoutCommand = makeLogoutCommand(
|
|
1609
|
+
"Clear stored authentication credentials"
|
|
1610
|
+
);
|
|
1611
|
+
|
|
1612
|
+
// src/commands/auth/status_command.ts
|
|
1613
|
+
import chalk5 from "chalk";
|
|
1614
|
+
import { Command as Command3 } from "commander";
|
|
1615
|
+
var statusAction = async () => {
|
|
1616
|
+
try {
|
|
1617
|
+
const credentials = await authManager.getCredentials();
|
|
1618
|
+
header("\nInworld CLI Status\n");
|
|
1619
|
+
if (!credentials) {
|
|
1620
|
+
print("Not authenticated.");
|
|
1621
|
+
print(`Run \`${chalk5.white("inworld auth login")}\` to authenticate.`);
|
|
1622
|
+
if (process.env.INWORLD_API_KEY) {
|
|
1623
|
+
print(
|
|
1624
|
+
`
|
|
1625
|
+
INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KEY)} (active)`
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1628
|
+
process.exit(0);
|
|
1629
|
+
}
|
|
1630
|
+
printBright("Authentication:");
|
|
1631
|
+
print(` Email: ${credentials.email}`);
|
|
1632
|
+
if (credentials.env !== "PROD") {
|
|
1633
|
+
print(` Environment: ${credentials.env}`);
|
|
1634
|
+
}
|
|
1635
|
+
if (credentials.inworldToken) {
|
|
1636
|
+
const isExpired = credentials.expiresAt && Date.now() > credentials.expiresAt;
|
|
1637
|
+
const expirationDate = credentials.expiresAt ? new Date(credentials.expiresAt).toLocaleString() : "Unknown";
|
|
1638
|
+
console.log();
|
|
1639
|
+
printBright("Token Status:");
|
|
1640
|
+
print(
|
|
1641
|
+
` Inworld Token: ${credentials.inworldToken.substring(0, 20)}...`
|
|
1642
|
+
);
|
|
1643
|
+
print(` Expires At: ${expirationDate}`);
|
|
1644
|
+
print(` Status: ${isExpired ? "Expired" : "Valid"}`);
|
|
1645
|
+
} else {
|
|
1646
|
+
header("\nToken Status:");
|
|
1647
|
+
print(` Inworld Token: Not available`);
|
|
1648
|
+
}
|
|
1649
|
+
print(
|
|
1650
|
+
` Refresh Token: ${credentials.refreshToken.substring(0, 20)}...`
|
|
1651
|
+
);
|
|
1652
|
+
print(` Session Status: Active`);
|
|
1653
|
+
printBright("\nActive Workspace:");
|
|
1654
|
+
if (credentials.workspace) {
|
|
1655
|
+
print(` Workspace id: ${credentials.workspace}`);
|
|
1656
|
+
print(
|
|
1657
|
+
` Workspace link: ${chalk5.underline.dim.cyan(`${PLATFORM_URL}/v2/workspaces/${credentials.workspace}`)}`
|
|
1658
|
+
);
|
|
1659
|
+
} else {
|
|
1660
|
+
print(` No workspace activated`);
|
|
1661
|
+
print(` Run "inworld workspace activate" to select a workspace`);
|
|
1662
|
+
}
|
|
1663
|
+
printBright("\nAPI Key:");
|
|
1664
|
+
if (process.env.INWORLD_API_KEY) {
|
|
1665
|
+
print(
|
|
1666
|
+
` INWORLD_API_KEY environment variable: ${trimBase64Key(process.env.INWORLD_API_KEY)} (active)`
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
1669
|
+
if (credentials.apiKey) {
|
|
1670
|
+
const maskedKey = credentials.apiKey.length > 20 ? `${trimBase64Key(credentials.apiKey)}` : "***";
|
|
1671
|
+
print(` Stored API Key: ${maskedKey}`);
|
|
1672
|
+
} else {
|
|
1673
|
+
print(` No API key configured`);
|
|
1674
|
+
if (credentials.workspace) {
|
|
1675
|
+
print(` Run "inworld apikey select" to choose an API key`);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
console.log();
|
|
1679
|
+
process.exit(0);
|
|
1680
|
+
} catch (error) {
|
|
1681
|
+
console.log();
|
|
1682
|
+
printError("Failed to get status:");
|
|
1683
|
+
console.error(error);
|
|
1684
|
+
process.exit(1);
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
var makeStatusCommand = (description) => {
|
|
1688
|
+
return new Command3("status").description(description).action(statusAction);
|
|
1689
|
+
};
|
|
1690
|
+
var statusCommand = makeStatusCommand(
|
|
1691
|
+
"Display current authentication status and configuration"
|
|
1692
|
+
);
|
|
1693
|
+
var statusCommandAlias = makeStatusCommand(
|
|
1694
|
+
`Alias for "${chalk5.bold("inworld auth status")}"`
|
|
1695
|
+
);
|
|
1696
|
+
|
|
1697
|
+
// src/commands/auth_command.ts
|
|
1698
|
+
import { Command as Command6 } from "commander";
|
|
1699
|
+
|
|
1700
|
+
// src/commands/auth/print_access_token_command.ts
|
|
1701
|
+
import { Command as Command4 } from "commander";
|
|
1702
|
+
var printAccessTokenAction = async () => {
|
|
1703
|
+
try {
|
|
1704
|
+
const token = await authManager.getValidToken();
|
|
1705
|
+
if (token) {
|
|
1706
|
+
console.log(token);
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
process.exit(1);
|
|
1710
|
+
} catch (_error) {
|
|
1711
|
+
process.exit(1);
|
|
1712
|
+
}
|
|
1713
|
+
};
|
|
1714
|
+
var printAccessTokenCommand = new Command4("print-access-token").description("Print the current Inworld access token").action(printAccessTokenAction);
|
|
1715
|
+
|
|
1716
|
+
// src/commands/auth/print_api_key_command.ts
|
|
1717
|
+
import { Command as Command5 } from "commander";
|
|
1718
|
+
var printApiKeyAction = async () => {
|
|
1719
|
+
try {
|
|
1720
|
+
if (process.env.INWORLD_API_KEY) {
|
|
1721
|
+
console.log(process.env.INWORLD_API_KEY);
|
|
1722
|
+
return;
|
|
1723
|
+
}
|
|
1724
|
+
const credentials = await authManager.getCredentials();
|
|
1725
|
+
if (credentials?.apiKey) {
|
|
1726
|
+
console.log(credentials.apiKey);
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
process.exit(1);
|
|
1730
|
+
} catch (_error) {
|
|
1731
|
+
process.exit(1);
|
|
1732
|
+
}
|
|
1733
|
+
};
|
|
1734
|
+
var printApiKeyCommand = new Command5("print-api-key").description("Print the current API key").action(printApiKeyAction);
|
|
1735
|
+
|
|
1736
|
+
// src/commands/auth_command.ts
|
|
1737
|
+
var authCommand = new Command6("auth").description("Manage Inworld authentication").addCommand(loginCommand).addCommand(logoutCommand).addCommand(printAccessTokenCommand).addCommand(printApiKeyCommand).addCommand(statusCommand).action(() => {
|
|
1738
|
+
authCommand.help();
|
|
1739
|
+
});
|
|
1740
|
+
|
|
1741
|
+
// src/commands/graph/graph_deploy_command.ts
|
|
1742
|
+
import archiver from "archiver";
|
|
1743
|
+
import chalk8 from "chalk";
|
|
1744
|
+
import { Command as Command7 } from "commander";
|
|
1745
|
+
import fs2 from "fs";
|
|
1746
|
+
import os from "os";
|
|
1747
|
+
import path2 from "path";
|
|
1748
|
+
|
|
1749
|
+
// proto/generated/portal/ai/inworld/studio/v1/remote/configuration/graphs.pb.ts
|
|
1750
|
+
var GraphsService = class {
|
|
1751
|
+
static CreateGraph(req, initReq) {
|
|
1752
|
+
return fetchReq(`/studio/v1/${req["parent"]}/graphs`, {
|
|
1753
|
+
...initReq,
|
|
1754
|
+
method: "POST",
|
|
1755
|
+
body: JSON.stringify(req["graph"], replacer)
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
static DeployGraph(req, initReq) {
|
|
1759
|
+
return fetchReq(`/studio/v1/${req["parent"]}:deploy`, {
|
|
1760
|
+
...initReq,
|
|
1761
|
+
method: "POST",
|
|
1762
|
+
body: JSON.stringify(req, replacer)
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
static GetGraphDeployment(req, initReq) {
|
|
1766
|
+
return fetchReq(
|
|
1767
|
+
`/studio/v1/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
|
|
1768
|
+
{ ...initReq, method: "GET" }
|
|
1769
|
+
);
|
|
1770
|
+
}
|
|
1771
|
+
static GetGraph(req, initReq) {
|
|
1772
|
+
return fetchReq(
|
|
1773
|
+
`/studio/v1/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
|
|
1774
|
+
{ ...initReq, method: "GET" }
|
|
1775
|
+
);
|
|
1776
|
+
}
|
|
1777
|
+
static ListGraphs(req, initReq) {
|
|
1778
|
+
return fetchReq(
|
|
1779
|
+
`/studio/v1/${req["parent"]}/graphs?${renderURLSearchParams(req, ["parent"])}`,
|
|
1780
|
+
{ ...initReq, method: "GET" }
|
|
1781
|
+
);
|
|
1782
|
+
}
|
|
1783
|
+
static UpdateGraph(req, initReq) {
|
|
1784
|
+
return fetchReq(`/studio/v1/${req["graph"]["name"]}`, {
|
|
1785
|
+
...initReq,
|
|
1786
|
+
method: "PATCH",
|
|
1787
|
+
body: JSON.stringify(req["graph"], replacer)
|
|
1788
|
+
});
|
|
1789
|
+
}
|
|
1790
|
+
static DeleteGraph(req, initReq) {
|
|
1791
|
+
return fetchReq(
|
|
1792
|
+
`/studio/v1/${req["name"]}`,
|
|
1793
|
+
{ ...initReq, method: "DELETE" }
|
|
1794
|
+
);
|
|
1795
|
+
}
|
|
1796
|
+
static CreateGraphVariant(req, initReq) {
|
|
1797
|
+
return fetchReq(`/studio/v1/${req["parent"]}/variants`, {
|
|
1798
|
+
...initReq,
|
|
1799
|
+
method: "POST",
|
|
1800
|
+
body: JSON.stringify(req["graphVariant"], replacer)
|
|
1801
|
+
});
|
|
1802
|
+
}
|
|
1803
|
+
static GetGraphVariant(req, initReq) {
|
|
1804
|
+
return fetchReq(
|
|
1805
|
+
`/studio/v1/${req["name"]}?${renderURLSearchParams(req, ["name"])}`,
|
|
1806
|
+
{ ...initReq, method: "GET" }
|
|
1807
|
+
);
|
|
1808
|
+
}
|
|
1809
|
+
static ListGraphVariants(req, initReq) {
|
|
1810
|
+
return fetchReq(
|
|
1811
|
+
`/studio/v1/${req["parent"]}/variants?${renderURLSearchParams(req, ["parent"])}`,
|
|
1812
|
+
{ ...initReq, method: "GET" }
|
|
1813
|
+
);
|
|
1814
|
+
}
|
|
1815
|
+
static UpdateGraphVariant(req, initReq) {
|
|
1816
|
+
return fetchReq(`/studio/v1/${req["graphVariant"]["name"]}`, {
|
|
1817
|
+
...initReq,
|
|
1818
|
+
method: "PATCH",
|
|
1819
|
+
body: JSON.stringify(req["graphVariant"], replacer)
|
|
1820
|
+
});
|
|
1821
|
+
}
|
|
1822
|
+
static DeleteGraphVariant(req, initReq) {
|
|
1823
|
+
return fetchReq(
|
|
1824
|
+
`/studio/v1/${req["name"]}`,
|
|
1825
|
+
{ ...initReq, method: "DELETE" }
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
};
|
|
1829
|
+
|
|
1830
|
+
// src/utils/spinner.ts
|
|
1831
|
+
import chalk6 from "chalk";
|
|
1832
|
+
import ora from "ora";
|
|
1833
|
+
var PHRASES = [
|
|
1834
|
+
"Condensing time-space matter",
|
|
1835
|
+
"Starting particle collider",
|
|
1836
|
+
"Calibrating quantum flux capacitor",
|
|
1837
|
+
"Reversing polarity of neutron flow",
|
|
1838
|
+
"Aligning cosmic frequencies",
|
|
1839
|
+
"Compiling infinite loops",
|
|
1840
|
+
"Downloading more RAM",
|
|
1841
|
+
"Reticulating splines",
|
|
1842
|
+
"Generating witty loading messages",
|
|
1843
|
+
"Convincing electrons to cooperate",
|
|
1844
|
+
"Negotiating with the cloud overlords",
|
|
1845
|
+
"Bribing the API hamsters",
|
|
1846
|
+
"Warming up the server potatoes",
|
|
1847
|
+
"Untangling quantum entanglements",
|
|
1848
|
+
"Feeding the deployment gremlins",
|
|
1849
|
+
"Optimizing coffee-to-code ratio",
|
|
1850
|
+
"Summoning the deployment spirits",
|
|
1851
|
+
"Consulting the ancient scrolls",
|
|
1852
|
+
"Charging the flux compensators",
|
|
1853
|
+
"Stabilizing temporal anomalies",
|
|
1854
|
+
"Synchronizing parallel universes",
|
|
1855
|
+
"Decoding the matrix",
|
|
1856
|
+
"Activating turbo encabulator",
|
|
1857
|
+
"Adjusting the dilithium crystals"
|
|
1858
|
+
];
|
|
1859
|
+
var LROSpinner = class _LROSpinner {
|
|
1860
|
+
spinner;
|
|
1861
|
+
phraseInterval;
|
|
1862
|
+
currentPhraseIndex = 0;
|
|
1863
|
+
config;
|
|
1864
|
+
iterationCount = 0;
|
|
1865
|
+
startTime;
|
|
1866
|
+
constructor(config = {}) {
|
|
1867
|
+
this.config = {
|
|
1868
|
+
initialText: "Initializing deployment",
|
|
1869
|
+
phraseInterval: 1e4,
|
|
1870
|
+
showIterations: true,
|
|
1871
|
+
spinnerStyle: "dots8Bit",
|
|
1872
|
+
...config
|
|
1873
|
+
};
|
|
1874
|
+
this.spinner = ora({
|
|
1875
|
+
text: this.config.initialText,
|
|
1876
|
+
spinner: this.config.spinnerStyle,
|
|
1877
|
+
color: "cyan"
|
|
1878
|
+
});
|
|
1879
|
+
this.startTime = Date.now();
|
|
1880
|
+
}
|
|
1881
|
+
/**
|
|
1882
|
+
* Starts the spinner with rotating phrases
|
|
1883
|
+
*/
|
|
1884
|
+
start() {
|
|
1885
|
+
this.spinner.start();
|
|
1886
|
+
this.updateText();
|
|
1887
|
+
this.phraseInterval = setInterval(() => {
|
|
1888
|
+
this.updateText();
|
|
1889
|
+
}, this.config.phraseInterval);
|
|
1890
|
+
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Updates the spinner text with current phrase and optional iteration count
|
|
1893
|
+
*/
|
|
1894
|
+
updateText() {
|
|
1895
|
+
const phrase = _LROSpinner.getRandomPhrase();
|
|
1896
|
+
const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1e3);
|
|
1897
|
+
let text = chalk6.cyan(phrase);
|
|
1898
|
+
if (this.config.showIterations && this.iterationCount > 0) {
|
|
1899
|
+
text += chalk6.gray(
|
|
1900
|
+
` (iteration ${this.iterationCount}, ${elapsedSeconds}s)`
|
|
1901
|
+
);
|
|
1902
|
+
} else if (elapsedSeconds > 0) {
|
|
1903
|
+
text += chalk6.gray(` (${elapsedSeconds}s)`);
|
|
1904
|
+
}
|
|
1905
|
+
this.spinner.text = text;
|
|
1906
|
+
}
|
|
1907
|
+
/**
|
|
1908
|
+
* Updates the iteration count
|
|
1909
|
+
*/
|
|
1910
|
+
updateIteration(iteration) {
|
|
1911
|
+
this.iterationCount = iteration + 1;
|
|
1912
|
+
this.updateText();
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Updates spinner with custom text temporarily
|
|
1916
|
+
*/
|
|
1917
|
+
updateCustomText(text) {
|
|
1918
|
+
this.spinner.text = chalk6.yellow(text);
|
|
1919
|
+
}
|
|
1920
|
+
/**
|
|
1921
|
+
* Succeeds the spinner with a success message
|
|
1922
|
+
*/
|
|
1923
|
+
succeed(text) {
|
|
1924
|
+
this.cleanup();
|
|
1925
|
+
const elapsedSeconds = Math.floor((Date.now() - this.startTime) / 1e3);
|
|
1926
|
+
const successText = text || `Deployment completed successfully in ${elapsedSeconds}s`;
|
|
1927
|
+
this.spinner.succeed(chalk6.green(successText));
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Fails the spinner with an error message
|
|
1931
|
+
*/
|
|
1932
|
+
fail(text) {
|
|
1933
|
+
this.cleanup();
|
|
1934
|
+
const errorText = text || "Deployment failed";
|
|
1935
|
+
this.spinner.fail(chalk6.red(errorText));
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Warns the spinner with a warning message
|
|
1939
|
+
*/
|
|
1940
|
+
warn(text) {
|
|
1941
|
+
this.cleanup();
|
|
1942
|
+
const warnText = text || "Deployment completed with warnings";
|
|
1943
|
+
this.spinner.warn(chalk6.yellow(warnText));
|
|
1944
|
+
}
|
|
1945
|
+
/**
|
|
1946
|
+
* Stops the spinner without any status
|
|
1947
|
+
*/
|
|
1948
|
+
stop() {
|
|
1949
|
+
this.cleanup();
|
|
1950
|
+
this.spinner.stop();
|
|
1951
|
+
}
|
|
1952
|
+
/**
|
|
1953
|
+
* Cleans up intervals
|
|
1954
|
+
*/
|
|
1955
|
+
cleanup() {
|
|
1956
|
+
if (this.phraseInterval) {
|
|
1957
|
+
clearInterval(this.phraseInterval);
|
|
1958
|
+
this.phraseInterval = void 0;
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
/**
|
|
1962
|
+
* Gets a random phrase for one-off usage
|
|
1963
|
+
*/
|
|
1964
|
+
static getRandomPhrase() {
|
|
1965
|
+
return PHRASES[Math.floor(Math.random() * PHRASES.length)];
|
|
1966
|
+
}
|
|
1967
|
+
};
|
|
1968
|
+
function createLROSpinnerCallbacks(config) {
|
|
1969
|
+
let spinner = null;
|
|
1970
|
+
return {
|
|
1971
|
+
startCallback: (operationName) => {
|
|
1972
|
+
spinner = new LROSpinner({
|
|
1973
|
+
...config,
|
|
1974
|
+
initialText: `Starting operation: ${operationName}`
|
|
1975
|
+
});
|
|
1976
|
+
spinner.start();
|
|
1977
|
+
},
|
|
1978
|
+
iterationCallback: (operationName, _checkResponse, checkData) => {
|
|
1979
|
+
if (spinner) {
|
|
1980
|
+
spinner.updateIteration(checkData.checkIteration);
|
|
1981
|
+
if (checkData.checkIteration > checkData.checkLimit * 0.8) {
|
|
1982
|
+
spinner.updateCustomText(
|
|
1983
|
+
chalk6.yellow(
|
|
1984
|
+
`\u26A0\uFE0F Taking longer than expected... (${checkData.checkIteration}/${checkData.checkLimit})`
|
|
1985
|
+
)
|
|
1986
|
+
);
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
},
|
|
1990
|
+
doneCallback: (_operationName, _response) => {
|
|
1991
|
+
if (spinner) {
|
|
1992
|
+
spinner.succeed(`Operation completed.`);
|
|
1993
|
+
spinner = null;
|
|
1994
|
+
}
|
|
1995
|
+
},
|
|
1996
|
+
errorCallback: (operationName, error) => {
|
|
1997
|
+
if (spinner) {
|
|
1998
|
+
spinner.fail(`Operation ${operationName} failed: ${error}`);
|
|
1999
|
+
spinner = null;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
};
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
// src/services/deploy_service.ts
|
|
2006
|
+
var deployGraph = async (graphId, _archive) => {
|
|
2007
|
+
const workspaceId = await requireWorkspace();
|
|
2008
|
+
const graphResourceName = getGraphResourceName(workspaceId, graphId);
|
|
2009
|
+
try {
|
|
2010
|
+
await ensureGraphRegistered(workspaceId, graphId);
|
|
2011
|
+
} catch (error) {
|
|
2012
|
+
printError(
|
|
2013
|
+
`Error ensuring graph registration on workspace ${workspaceId}:`
|
|
2014
|
+
);
|
|
2015
|
+
console.error(error);
|
|
2016
|
+
process.exit(1);
|
|
2017
|
+
}
|
|
2018
|
+
try {
|
|
2019
|
+
const operation = await authenticatedInworldRequest(
|
|
2020
|
+
GraphsService.DeployGraph,
|
|
2021
|
+
{
|
|
2022
|
+
parent: graphResourceName,
|
|
2023
|
+
graph: {
|
|
2024
|
+
archive: _archive,
|
|
2025
|
+
archiveType: "zip"
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
);
|
|
2029
|
+
const gracefulShutdown = () => {
|
|
2030
|
+
process.exit(0);
|
|
2031
|
+
};
|
|
2032
|
+
for (const signal of [
|
|
2033
|
+
"SIGINT",
|
|
2034
|
+
"SIGTERM",
|
|
2035
|
+
"SIGQUIT",
|
|
2036
|
+
"SIGSEGV",
|
|
2037
|
+
"SIGBUS",
|
|
2038
|
+
"exit"
|
|
2039
|
+
]) {
|
|
2040
|
+
process.on(signal, gracefulShutdown);
|
|
2041
|
+
}
|
|
2042
|
+
const spinnerCallbacks = createLROSpinnerCallbacks({
|
|
2043
|
+
initialText: `Deploying graph "${graphId}" to Inworld platform`,
|
|
2044
|
+
showIterations: false,
|
|
2045
|
+
phraseInterval: 1e4
|
|
2046
|
+
// Change phrase every 10 seconds
|
|
2047
|
+
});
|
|
2048
|
+
await checkLRO({
|
|
2049
|
+
operationName: operation.name,
|
|
2050
|
+
checkLimit: 100,
|
|
2051
|
+
checkTimeout: 8e3,
|
|
2052
|
+
returnWithMetadata: true,
|
|
2053
|
+
pollOptions: spinnerCallbacks
|
|
2054
|
+
});
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
printError("Error deploying graph:");
|
|
2057
|
+
console.error(error);
|
|
2058
|
+
process.exit(1);
|
|
2059
|
+
}
|
|
2060
|
+
const deployment = await getGraphDeployment(graphResourceName);
|
|
2061
|
+
return deployment;
|
|
2062
|
+
};
|
|
2063
|
+
var getGraphDeployment = async (graphResourceName) => {
|
|
2064
|
+
requireAuth();
|
|
2065
|
+
return await authenticatedInworldRequest(GraphsService.GetGraphDeployment, {
|
|
2066
|
+
name: graphResourceName + "/deploy"
|
|
2067
|
+
});
|
|
2068
|
+
};
|
|
2069
|
+
var ensureGraphRegistered = async (workspaceId, graphId) => {
|
|
2070
|
+
requireAuth();
|
|
2071
|
+
const graphResourceName = getGraphResourceName(workspaceId, graphId);
|
|
2072
|
+
try {
|
|
2073
|
+
return await getGraph(graphResourceName);
|
|
2074
|
+
} catch (error) {
|
|
2075
|
+
if (isGrpcError(error) && error.code === 5 /* NOT_FOUND */) {
|
|
2076
|
+
print(
|
|
2077
|
+
`Graph "${graphId}" is not registered on the Inworld platform for workspace "${workspaceId}", registering now...`
|
|
2078
|
+
);
|
|
2079
|
+
await registerGraph(workspaceId, graphId);
|
|
2080
|
+
} else {
|
|
2081
|
+
throw error;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
};
|
|
2085
|
+
var getGraph = async (graphResourceName) => {
|
|
2086
|
+
requireAuth();
|
|
2087
|
+
return await authenticatedInworldRequest(GraphsService.GetGraph, {
|
|
2088
|
+
name: graphResourceName
|
|
2089
|
+
});
|
|
2090
|
+
};
|
|
2091
|
+
var registerGraph = async (workspaceId, graphId) => {
|
|
2092
|
+
requireAuth();
|
|
2093
|
+
const graphResourceName = getGraphResourceName(workspaceId, graphId);
|
|
2094
|
+
const workspaceResourceName = getWorkspaceResourceName(workspaceId);
|
|
2095
|
+
const operation = await authenticatedInworldRequest(
|
|
2096
|
+
GraphsService.CreateGraph,
|
|
2097
|
+
{
|
|
2098
|
+
parent: `${workspaceResourceName}`,
|
|
2099
|
+
graph: {
|
|
2100
|
+
name: graphResourceName,
|
|
2101
|
+
displayName: graphId,
|
|
2102
|
+
targeting: { rawContent: JSON.stringify({}) }
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
);
|
|
2106
|
+
const spinnerCallbacks = createLROSpinnerCallbacks({
|
|
2107
|
+
initialText: `Registering graph ${graphId} on Inworld platform`,
|
|
2108
|
+
showIterations: false
|
|
2109
|
+
});
|
|
2110
|
+
await checkLRO({
|
|
2111
|
+
operationName: operation.name,
|
|
2112
|
+
pollOptions: spinnerCallbacks
|
|
2113
|
+
});
|
|
2114
|
+
return getGraph(graphResourceName);
|
|
2115
|
+
};
|
|
2116
|
+
|
|
2117
|
+
// src/services/graph_loader.ts
|
|
2118
|
+
import chalk7 from "chalk";
|
|
2119
|
+
import * as esbuild from "esbuild";
|
|
2120
|
+
import fs from "fs";
|
|
2121
|
+
import { Module } from "module";
|
|
2122
|
+
import path from "path";
|
|
2123
|
+
var loadGraph = async (file) => {
|
|
2124
|
+
process.env.INWORLD_API_KEY = await requireApiKey();
|
|
2125
|
+
const filePath = path.resolve(process.cwd(), file);
|
|
2126
|
+
if (!fs.existsSync(filePath)) {
|
|
2127
|
+
console.error(`Error: File not found: ${filePath}`);
|
|
2128
|
+
process.exit(1);
|
|
2129
|
+
}
|
|
2130
|
+
console.log(`Packaging graph from: ${filePath}`);
|
|
2131
|
+
const packageJsonPath = findNearestPackageJson(path.dirname(filePath));
|
|
2132
|
+
if (!packageJsonPath) {
|
|
2133
|
+
console.error("Error: No package.json found in the project hierarchy");
|
|
2134
|
+
console.error(
|
|
2135
|
+
"Please ensure your graph file is in a proper Node.js project"
|
|
2136
|
+
);
|
|
2137
|
+
process.exit(1);
|
|
2138
|
+
}
|
|
2139
|
+
console.log(`Using package.json from: ${packageJsonPath}`);
|
|
2140
|
+
const originalPackageJson = JSON.parse(
|
|
2141
|
+
fs.readFileSync(packageJsonPath, "utf-8")
|
|
2142
|
+
);
|
|
2143
|
+
console.log("Bundling graph module with local dependencies...");
|
|
2144
|
+
let bundledCode;
|
|
2145
|
+
let module;
|
|
2146
|
+
if (!filePath.endsWith(".ts") && !filePath.endsWith(".js")) {
|
|
2147
|
+
console.error("Error: File must be a .ts or .js file");
|
|
2148
|
+
process.exit(1);
|
|
2149
|
+
}
|
|
2150
|
+
const result = await esbuild.build({
|
|
2151
|
+
entryPoints: [filePath],
|
|
2152
|
+
bundle: true,
|
|
2153
|
+
platform: "node",
|
|
2154
|
+
loader: { ".ts": "ts", ".js": "js" },
|
|
2155
|
+
target: "node18",
|
|
2156
|
+
format: "cjs",
|
|
2157
|
+
// Keep all npm packages external - they'll be installed via package.json
|
|
2158
|
+
packages: "external",
|
|
2159
|
+
sourcemap: "inline",
|
|
2160
|
+
write: false,
|
|
2161
|
+
logLevel: "error",
|
|
2162
|
+
resolveExtensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
|
|
2163
|
+
keepNames: true,
|
|
2164
|
+
minify: false
|
|
2165
|
+
});
|
|
2166
|
+
bundledCode = result.outputFiles[0].text;
|
|
2167
|
+
const moduleInstance = new Module(filePath, module);
|
|
2168
|
+
moduleInstance.filename = filePath;
|
|
2169
|
+
moduleInstance.paths = Module._nodeModulePaths(
|
|
2170
|
+
path.dirname(filePath)
|
|
2171
|
+
);
|
|
2172
|
+
moduleInstance._compile(bundledCode, filePath);
|
|
2173
|
+
module = moduleInstance.exports;
|
|
2174
|
+
if (!module.graph) {
|
|
2175
|
+
console.error('Error: The file must export a "graph" object');
|
|
2176
|
+
process.exit(1);
|
|
2177
|
+
}
|
|
2178
|
+
const graphId = module.graph.graphId;
|
|
2179
|
+
if (typeof graphId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(graphId)) {
|
|
2180
|
+
console.error(
|
|
2181
|
+
chalk7.red(
|
|
2182
|
+
"Error: Graph id must be a string containing only alphanumeric (latin) characters, dashes, or underscores."
|
|
2183
|
+
)
|
|
2184
|
+
);
|
|
2185
|
+
process.exit(1);
|
|
2186
|
+
}
|
|
2187
|
+
return {
|
|
2188
|
+
graph: module.graph,
|
|
2189
|
+
bundledCode,
|
|
2190
|
+
originalPackageJson,
|
|
2191
|
+
packageJsonPath
|
|
2192
|
+
};
|
|
2193
|
+
};
|
|
2194
|
+
function findNearestPackageJson(startDir) {
|
|
2195
|
+
let currentDir = startDir;
|
|
2196
|
+
const root = path.parse(currentDir).root;
|
|
2197
|
+
while (currentDir !== root) {
|
|
2198
|
+
const packageJsonPath = path.join(currentDir, "package.json");
|
|
2199
|
+
if (fs.existsSync(packageJsonPath)) {
|
|
2200
|
+
return packageJsonPath;
|
|
2201
|
+
}
|
|
2202
|
+
currentDir = path.dirname(currentDir);
|
|
2203
|
+
}
|
|
2204
|
+
const rootPackageJson = path.join(root, "package.json");
|
|
2205
|
+
if (fs.existsSync(rootPackageJson)) {
|
|
2206
|
+
return rootPackageJson;
|
|
2207
|
+
}
|
|
2208
|
+
return null;
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
// src/commands/graph/graph_deploy_command.ts
|
|
2212
|
+
function processPackageJson(originalPackageJson, graphFileName) {
|
|
2213
|
+
const packageJson = JSON.parse(JSON.stringify(originalPackageJson));
|
|
2214
|
+
packageJson.name = packageJson.name || "inworld-graph-deployment";
|
|
2215
|
+
packageJson.version = packageJson.version || "1.0.0";
|
|
2216
|
+
packageJson.description = packageJson.description || "Inworld Runtime Graph Deployment Package";
|
|
2217
|
+
packageJson.main = graphFileName;
|
|
2218
|
+
packageJson.scripts = packageJson.scripts || {};
|
|
2219
|
+
packageJson.scripts.start = `npx inworld serve --host 0.0.0.0 ${graphFileName}`;
|
|
2220
|
+
packageJson.scripts["run"] = `npx inworld run ${graphFileName}`;
|
|
2221
|
+
packageJson.dependencies = packageJson.dependencies || {};
|
|
2222
|
+
if (!packageJson.dependencies["@inworld/runtime"]) {
|
|
2223
|
+
packageJson.dependencies["@inworld/runtime"] = RUNTIME_VERSION;
|
|
2224
|
+
}
|
|
2225
|
+
if (!packageJson.dependencies["@inworld/cli"]) {
|
|
2226
|
+
packageJson.dependencies["@inworld/cli"] = "https://storage.googleapis.com/assets-inworld-ai/node-packages/inworld-cli-0.2.15.tgz";
|
|
2227
|
+
}
|
|
2228
|
+
if (!packageJson.dependencies["dotenv"]) {
|
|
2229
|
+
packageJson.dependencies["dotenv"] = "^17.2.1";
|
|
2230
|
+
}
|
|
2231
|
+
delete packageJson.devDependencies;
|
|
2232
|
+
delete packageJson.scripts.test;
|
|
2233
|
+
delete packageJson.scripts.lint;
|
|
2234
|
+
delete packageJson.scripts.build;
|
|
2235
|
+
delete packageJson.scripts.prepare;
|
|
2236
|
+
return packageJson;
|
|
2237
|
+
}
|
|
2238
|
+
var deployAction = async (file, options) => {
|
|
2239
|
+
try {
|
|
2240
|
+
const workspaceId = await requireWorkspace();
|
|
2241
|
+
const { graph, bundledCode, originalPackageJson, packageJsonPath } = await loadGraph(file);
|
|
2242
|
+
const graphResourceName = getGraphResourceName(workspaceId, graph.graphId);
|
|
2243
|
+
if (options.info) {
|
|
2244
|
+
const deployment2 = await getGraphDeployment(graphResourceName);
|
|
2245
|
+
console.log(deployment2);
|
|
2246
|
+
success("Inworld Cloud URI:");
|
|
2247
|
+
print(
|
|
2248
|
+
`${PLATFORM_URL.replace("platform", "api")}/cloud/${graphResourceName}/v1/graph:start`
|
|
2249
|
+
);
|
|
2250
|
+
process.exit(0);
|
|
2251
|
+
}
|
|
2252
|
+
const randomId = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
|
|
2253
|
+
const tempBaseDir = path2.join(os.tmpdir(), "inworld", randomId);
|
|
2254
|
+
if (!fs2.existsSync(tempBaseDir)) {
|
|
2255
|
+
fs2.mkdirSync(tempBaseDir, { recursive: true });
|
|
2256
|
+
}
|
|
2257
|
+
const outputPath = path2.join(tempBaseDir, "graph-deployment.zip");
|
|
2258
|
+
const output = fs2.createWriteStream(outputPath);
|
|
2259
|
+
const archive = archiver("zip", {
|
|
2260
|
+
zlib: { level: 9 }
|
|
2261
|
+
// Maximum compression
|
|
2262
|
+
});
|
|
2263
|
+
const archiveComplete = new Promise((resolve2, reject) => {
|
|
2264
|
+
output.on("close", () => {
|
|
2265
|
+
if (options.packageOnly) {
|
|
2266
|
+
let packageName;
|
|
2267
|
+
if (options.packageOnly === true) {
|
|
2268
|
+
packageName = "graph-deployment.zip";
|
|
2269
|
+
} else {
|
|
2270
|
+
packageName = options.packageOnly;
|
|
2271
|
+
}
|
|
2272
|
+
const destinationPath = path2.isAbsolute(packageName) ? packageName : path2.join(process.cwd(), packageName);
|
|
2273
|
+
fs2.copyFileSync(outputPath, destinationPath);
|
|
2274
|
+
success(`\u2705 Graph packaged successfully: ${destinationPath}`);
|
|
2275
|
+
process.exit(0);
|
|
2276
|
+
}
|
|
2277
|
+
success(`\u2705 Graph packaged successfully: ${outputPath}`);
|
|
2278
|
+
print(` Size: ${(archive.pointer() / 1024).toFixed(2)} KB`);
|
|
2279
|
+
console.log();
|
|
2280
|
+
print("Deployment should take around 5 minutes, please be patient.");
|
|
2281
|
+
print("Deploying...");
|
|
2282
|
+
console.log();
|
|
2283
|
+
resolve2();
|
|
2284
|
+
});
|
|
2285
|
+
archive.on("error", (err) => {
|
|
2286
|
+
reject(err);
|
|
2287
|
+
});
|
|
2288
|
+
output.on("error", (err) => {
|
|
2289
|
+
reject(err);
|
|
2290
|
+
});
|
|
2291
|
+
});
|
|
2292
|
+
archive.pipe(output);
|
|
2293
|
+
const graphFileName = path2.basename(file).replace(".ts", ".js");
|
|
2294
|
+
archive.append(bundledCode, { name: graphFileName });
|
|
2295
|
+
const packageJson = processPackageJson(originalPackageJson, graphFileName);
|
|
2296
|
+
archive.append(JSON.stringify(packageJson, null, 2), {
|
|
2297
|
+
name: "package.json"
|
|
2298
|
+
});
|
|
2299
|
+
const readme = `# Inworld Graph Deployment
|
|
2300
|
+
|
|
2301
|
+
This package contains an Inworld Runtime graph ready for deployment.
|
|
2302
|
+
|
|
2303
|
+
## Installation
|
|
2304
|
+
|
|
2305
|
+
\`\`\`bash
|
|
2306
|
+
npm install
|
|
2307
|
+
\`\`\`
|
|
2308
|
+
|
|
2309
|
+
## Running the Graph
|
|
2310
|
+
|
|
2311
|
+
### As a server (recommended):
|
|
2312
|
+
\`\`\`bash
|
|
2313
|
+
inworld serve ${graphFileName}
|
|
2314
|
+
\`\`\`
|
|
2315
|
+
|
|
2316
|
+
### Direct execution:
|
|
2317
|
+
\`\`\`bash
|
|
2318
|
+
inworld run ${graphFileName}
|
|
2319
|
+
\`\`\`
|
|
2320
|
+
|
|
2321
|
+
## Graph File
|
|
2322
|
+
- **Bundled File**: ${graphFileName}
|
|
2323
|
+
- **Original Source**: ${path2.basename(file)}
|
|
2324
|
+
- **Package source**: ${path2.relative(process.cwd(), packageJsonPath)}
|
|
2325
|
+
|
|
2326
|
+
## Notes
|
|
2327
|
+
- This graph module has been bundled with all local files (custom nodes, local imports, etc.)
|
|
2328
|
+
- NPM packages remain external and will be installed via package.json dependencies
|
|
2329
|
+
- The bundle includes all your custom code in a single file for easy deployment
|
|
2330
|
+
|
|
2331
|
+
## Requirements
|
|
2332
|
+
- Node.js >= 18.0.0
|
|
2333
|
+
- @inworld/cli package installed globally or locally
|
|
2334
|
+
`;
|
|
2335
|
+
archive.append(readme, { name: "README.md" });
|
|
2336
|
+
await archive.finalize();
|
|
2337
|
+
await archiveComplete;
|
|
2338
|
+
const deployment = await deployGraph(
|
|
2339
|
+
graph.graphId,
|
|
2340
|
+
new Uint8Array(fs2.readFileSync(outputPath))
|
|
2341
|
+
);
|
|
2342
|
+
if (!deployment) {
|
|
2343
|
+
printError("Deployment failed");
|
|
2344
|
+
try {
|
|
2345
|
+
fs2.rmSync(tempBaseDir, { recursive: true, force: true });
|
|
2346
|
+
} catch {
|
|
2347
|
+
}
|
|
2348
|
+
process.exit(1);
|
|
2349
|
+
}
|
|
2350
|
+
success("Deployment successful!");
|
|
2351
|
+
success("Inworld Cloud URI:");
|
|
2352
|
+
print(
|
|
2353
|
+
`${PLATFORM_URL.replace("platform", "api")}/cloud/${graphResourceName}/v1/graph:start`
|
|
2354
|
+
);
|
|
2355
|
+
try {
|
|
2356
|
+
fs2.rmSync(tempBaseDir, { recursive: true, force: true });
|
|
2357
|
+
} catch (_error) {
|
|
2358
|
+
}
|
|
2359
|
+
process.exit(0);
|
|
2360
|
+
} catch (error) {
|
|
2361
|
+
printError("Error packaging graph:");
|
|
2362
|
+
console.error(error);
|
|
2363
|
+
process.exit(1);
|
|
2364
|
+
}
|
|
2365
|
+
};
|
|
2366
|
+
var makeDeployCommand = (description) => {
|
|
2367
|
+
return new Command7("deploy").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").option("-i, --info", "Shows deployment info if any").option(
|
|
2368
|
+
"-p, --package-only [file]",
|
|
2369
|
+
"Output file path (if not specified, outputs to graph-deployment.zip in current directory)"
|
|
2370
|
+
).action(deployAction);
|
|
2371
|
+
};
|
|
2372
|
+
var deployCommand = makeDeployCommand(
|
|
2373
|
+
"Packages a graph for deployment to the Inworld Cloud."
|
|
2374
|
+
);
|
|
2375
|
+
var deployCommandAlias = makeDeployCommand(
|
|
2376
|
+
`Alias for "${chalk8.bold("inworld graph deploy")}"`
|
|
2377
|
+
);
|
|
2378
|
+
|
|
2379
|
+
// src/commands/graph/graph_init_command.ts
|
|
2380
|
+
import chalk9 from "chalk";
|
|
2381
|
+
import { Command as Command8 } from "commander";
|
|
2382
|
+
import fs3 from "fs";
|
|
2383
|
+
import path3 from "path";
|
|
2384
|
+
import * as readline4 from "readline";
|
|
2385
|
+
import { fileURLToPath } from "url";
|
|
2386
|
+
var __filename = fileURLToPath(import.meta.url);
|
|
2387
|
+
var __dirname = path3.dirname(__filename);
|
|
2388
|
+
function getTemplatePath() {
|
|
2389
|
+
const possiblePaths = [
|
|
2390
|
+
// Production: templates are copied to dist/templates (when code is bundled in dist/index.js)
|
|
2391
|
+
path3.join(__dirname, "templates"),
|
|
2392
|
+
// Development: templates are in src/templates (when running from src/)
|
|
2393
|
+
path3.join(__dirname, "..", "..", "templates"),
|
|
2394
|
+
// Alternative: if running from nested directory structure
|
|
2395
|
+
path3.join(__dirname, "..", "..", "..", "templates")
|
|
2396
|
+
];
|
|
2397
|
+
for (const templatePath of possiblePaths) {
|
|
2398
|
+
if (fs3.existsSync(templatePath)) {
|
|
2399
|
+
return templatePath;
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
throw new Error(
|
|
2403
|
+
"Template directory not found. Please ensure templates are properly installed."
|
|
2404
|
+
);
|
|
2405
|
+
}
|
|
2406
|
+
var TEMPLATE_PATH = getTemplatePath();
|
|
2407
|
+
function loadTemplateMetadata(templateDir, basePath) {
|
|
2408
|
+
const metadataPath = path3.join(basePath, templateDir, "metadata.json");
|
|
2409
|
+
if (fs3.existsSync(metadataPath)) {
|
|
2410
|
+
try {
|
|
2411
|
+
return JSON.parse(fs3.readFileSync(metadataPath, "utf-8"));
|
|
2412
|
+
} catch (err) {
|
|
2413
|
+
print(`Failed to parse metadata for ${templateDir}: ${err}`);
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
return {
|
|
2417
|
+
name: templateDir,
|
|
2418
|
+
displayName: templateDir.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
|
2419
|
+
description: `${templateDir} template`,
|
|
2420
|
+
tags: [],
|
|
2421
|
+
defaultProjectName: templateDir
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
2424
|
+
function getAvailableTemplatesWithMetadata() {
|
|
2425
|
+
const templates = [];
|
|
2426
|
+
try {
|
|
2427
|
+
const entries = fs3.readdirSync(TEMPLATE_PATH, { withFileTypes: true });
|
|
2428
|
+
const templateDirs = entries.filter((entry) => entry.isDirectory()).filter((dir) => {
|
|
2429
|
+
const graphPath = path3.join(TEMPLATE_PATH, dir.name, "graph.ts");
|
|
2430
|
+
return fs3.existsSync(graphPath);
|
|
2431
|
+
});
|
|
2432
|
+
for (const dir of templateDirs) {
|
|
2433
|
+
const metadata = loadTemplateMetadata(dir.name, TEMPLATE_PATH);
|
|
2434
|
+
if (metadata) {
|
|
2435
|
+
templates.push({
|
|
2436
|
+
directory: dir.name,
|
|
2437
|
+
metadata
|
|
2438
|
+
});
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
} catch (_err) {
|
|
2442
|
+
}
|
|
2443
|
+
return templates;
|
|
2444
|
+
}
|
|
2445
|
+
async function promptNpmInstall() {
|
|
2446
|
+
const rl = readline4.createInterface({
|
|
2447
|
+
input: process.stdin,
|
|
2448
|
+
output: process.stdout
|
|
2449
|
+
});
|
|
2450
|
+
return new Promise((resolve2) => {
|
|
2451
|
+
rl.question(
|
|
2452
|
+
"\n\u{1F4E6} Would you like to install dependencies now? (y/n) ",
|
|
2453
|
+
(answer) => {
|
|
2454
|
+
rl.close();
|
|
2455
|
+
resolve2(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
|
|
2456
|
+
}
|
|
2457
|
+
);
|
|
2458
|
+
});
|
|
2459
|
+
}
|
|
2460
|
+
async function runNpmInstall(directory) {
|
|
2461
|
+
const { spawn } = await import("child_process");
|
|
2462
|
+
return new Promise((resolve2, reject) => {
|
|
2463
|
+
console.log();
|
|
2464
|
+
print("\u{1F4E6} Installing dependencies...");
|
|
2465
|
+
console.log();
|
|
2466
|
+
const install = spawn("npm", ["install"], {
|
|
2467
|
+
cwd: directory,
|
|
2468
|
+
stdio: "inherit",
|
|
2469
|
+
shell: true
|
|
2470
|
+
});
|
|
2471
|
+
install.on("close", (code) => {
|
|
2472
|
+
if (code === 0) {
|
|
2473
|
+
console.log();
|
|
2474
|
+
success("\u2705 Dependencies installed successfully!");
|
|
2475
|
+
resolve2();
|
|
2476
|
+
} else {
|
|
2477
|
+
console.log();
|
|
2478
|
+
printError(`\u274C npm install failed with code ${code}`);
|
|
2479
|
+
reject(new Error(`npm install failed with code ${code}`));
|
|
2480
|
+
}
|
|
2481
|
+
});
|
|
2482
|
+
install.on("error", (err) => {
|
|
2483
|
+
console.log();
|
|
2484
|
+
printError(`\u274C Failed to run npm install: ${err.message}`);
|
|
2485
|
+
reject(err);
|
|
2486
|
+
});
|
|
2487
|
+
});
|
|
2488
|
+
}
|
|
2489
|
+
function createPackageJson(graphFileName) {
|
|
2490
|
+
const packageJson = {
|
|
2491
|
+
name: "inworld-graph-project",
|
|
2492
|
+
version: "1.0.0",
|
|
2493
|
+
description: "Inworld Runtime Graph Project",
|
|
2494
|
+
main: graphFileName,
|
|
2495
|
+
scripts: {
|
|
2496
|
+
start: `npx inworld serve ${graphFileName}`,
|
|
2497
|
+
run: `npx inworld run ${graphFileName}`
|
|
2498
|
+
},
|
|
2499
|
+
dependencies: {
|
|
2500
|
+
"@inworld/runtime": RUNTIME_VERSION
|
|
2501
|
+
},
|
|
2502
|
+
keywords: ["inworld", "ai", "graph", "runtime"],
|
|
2503
|
+
author: "",
|
|
2504
|
+
license: "MIT"
|
|
2505
|
+
};
|
|
2506
|
+
return packageJson;
|
|
2507
|
+
}
|
|
2508
|
+
function createGraphTemplate(templateName) {
|
|
2509
|
+
const availableTemplates = getAvailableTemplatesWithMetadata();
|
|
2510
|
+
if (!availableTemplates.find((template) => template.directory === templateName)) {
|
|
2511
|
+
throw new Error(
|
|
2512
|
+
`Unknown template: ${templateName}. Available templates: ${availableTemplates.map((template) => template.directory).join(", ")}`
|
|
2513
|
+
);
|
|
2514
|
+
}
|
|
2515
|
+
const templateFilePath = path3.join(TEMPLATE_PATH, templateName, "graph.ts");
|
|
2516
|
+
if (!fs3.existsSync(templateFilePath)) {
|
|
2517
|
+
throw new Error(
|
|
2518
|
+
`Template file not found: ${templateName}/graph.ts. Please ensure the template files are in the templates folder.`
|
|
2519
|
+
);
|
|
2520
|
+
}
|
|
2521
|
+
return fs3.readFileSync(templateFilePath, "utf-8");
|
|
2522
|
+
}
|
|
2523
|
+
function createReadme(templateName, graphFileName) {
|
|
2524
|
+
const readmePath = path3.join(TEMPLATE_PATH, templateName, "README.md");
|
|
2525
|
+
if (!fs3.existsSync(readmePath)) {
|
|
2526
|
+
printError(`README file not found: ${readmePath}`);
|
|
2527
|
+
process.exit(1);
|
|
2528
|
+
}
|
|
2529
|
+
const readmeContent = fs3.readFileSync(readmePath, "utf-8");
|
|
2530
|
+
return readmeContent.replace(/\{\{graphFileName\}\}/g, graphFileName);
|
|
2531
|
+
}
|
|
2532
|
+
var initAction = async (options) => {
|
|
2533
|
+
try {
|
|
2534
|
+
if (options.listTemplates) {
|
|
2535
|
+
const templates2 = getAvailableTemplatesWithMetadata();
|
|
2536
|
+
console.log();
|
|
2537
|
+
header("\u{1F4DA} Available templates:");
|
|
2538
|
+
console.log();
|
|
2539
|
+
for (const template of templates2) {
|
|
2540
|
+
listItem(`${chalk9.cyan.bold(template.metadata.name)}`);
|
|
2541
|
+
listItem(` ${template.metadata.description}`);
|
|
2542
|
+
if (template.metadata.tags && template.metadata.tags.length > 0) {
|
|
2543
|
+
listItem(` Tags: ${template.metadata.tags.join(", ")}`);
|
|
2544
|
+
}
|
|
2545
|
+
if (template.metadata.requirements?.apiKeys) {
|
|
2546
|
+
listItem(
|
|
2547
|
+
` Required API Keys: ${template.metadata.requirements.apiKeys.join(", ")}`
|
|
2548
|
+
);
|
|
2549
|
+
}
|
|
2550
|
+
console.log();
|
|
2551
|
+
}
|
|
2552
|
+
print(
|
|
2553
|
+
`Use ${chalk9.bold("inworld graph init")} to interactively select a template.`
|
|
2554
|
+
);
|
|
2555
|
+
console.log();
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2558
|
+
const templates = getAvailableTemplatesWithMetadata();
|
|
2559
|
+
if (templates.length === 0) {
|
|
2560
|
+
printError(
|
|
2561
|
+
"\u274C No templates found. Please ensure templates are properly installed."
|
|
2562
|
+
);
|
|
2563
|
+
process.exit(1);
|
|
2564
|
+
}
|
|
2565
|
+
let selectedTemplate = null;
|
|
2566
|
+
let projectName;
|
|
2567
|
+
if (!options.template) {
|
|
2568
|
+
console.log();
|
|
2569
|
+
header("\u{1F680} Welcome to Inworld Graph Project Initializer!");
|
|
2570
|
+
console.log();
|
|
2571
|
+
selectedTemplate = await selectItem({
|
|
2572
|
+
items: templates,
|
|
2573
|
+
getDisplayName: (item) => `${item.metadata.name} - ${item.metadata.description}`,
|
|
2574
|
+
getIdentifier: (item) => item.directory,
|
|
2575
|
+
prompt: "Select a template (enter number or id):",
|
|
2576
|
+
title: "\u{1F4CB} Available Templates:",
|
|
2577
|
+
noItemsMessage: "No templates found.",
|
|
2578
|
+
invalidSelectionMessage: "Invalid selection. Please try again."
|
|
2579
|
+
});
|
|
2580
|
+
if (!selectedTemplate) {
|
|
2581
|
+
console.log();
|
|
2582
|
+
print("\u26A0\uFE0F No template selected. Exiting.");
|
|
2583
|
+
return;
|
|
2584
|
+
}
|
|
2585
|
+
} else {
|
|
2586
|
+
selectedTemplate = templates.find((t) => t.directory === options.template) || null;
|
|
2587
|
+
if (!selectedTemplate) {
|
|
2588
|
+
printError(`\u274C Template not found: ${options.template}`);
|
|
2589
|
+
print(
|
|
2590
|
+
`Available templates: ${templates.map((t) => t.directory).join(", ")}`
|
|
2591
|
+
);
|
|
2592
|
+
process.exit(1);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
projectName = options.name || selectedTemplate.metadata.defaultProjectName || selectedTemplate.directory;
|
|
2596
|
+
if (!options.template && !options.name) {
|
|
2597
|
+
const rl = readline4.createInterface({
|
|
2598
|
+
input: process.stdin,
|
|
2599
|
+
output: process.stdout
|
|
2600
|
+
});
|
|
2601
|
+
const askProjectName = () => new Promise((resolve2) => {
|
|
2602
|
+
rl.question(
|
|
2603
|
+
`
|
|
2604
|
+
Project name (${selectedTemplate.metadata.defaultProjectName}): `,
|
|
2605
|
+
(answer) => {
|
|
2606
|
+
rl.close();
|
|
2607
|
+
resolve2(
|
|
2608
|
+
answer.trim() || selectedTemplate.metadata.defaultProjectName
|
|
2609
|
+
);
|
|
2610
|
+
}
|
|
2611
|
+
);
|
|
2612
|
+
});
|
|
2613
|
+
projectName = await askProjectName();
|
|
2614
|
+
}
|
|
2615
|
+
const currentDir = process.cwd();
|
|
2616
|
+
const projectDir = path3.join(currentDir, projectName);
|
|
2617
|
+
if (fs3.existsSync(projectDir)) {
|
|
2618
|
+
console.log();
|
|
2619
|
+
print(`\u26A0\uFE0F Directory '${projectName}' already exists.`);
|
|
2620
|
+
if (!options.template) {
|
|
2621
|
+
const rl = readline4.createInterface({
|
|
2622
|
+
input: process.stdin,
|
|
2623
|
+
output: process.stdout
|
|
2624
|
+
});
|
|
2625
|
+
const confirmOverwrite = await new Promise((resolve2) => {
|
|
2626
|
+
rl.question("Do you want to overwrite it? (y/n) ", (answer) => {
|
|
2627
|
+
rl.close();
|
|
2628
|
+
resolve2(
|
|
2629
|
+
answer.toLowerCase() === "y" || answer.toLowerCase() === "yes"
|
|
2630
|
+
);
|
|
2631
|
+
});
|
|
2632
|
+
});
|
|
2633
|
+
if (!confirmOverwrite) {
|
|
2634
|
+
print("\u26A0\uFE0F Initialization cancelled.");
|
|
2635
|
+
return;
|
|
2636
|
+
}
|
|
2637
|
+
fs3.rmSync(projectDir, { recursive: true, force: true });
|
|
2638
|
+
} else {
|
|
2639
|
+
print("Overwriting existing directory...");
|
|
2640
|
+
fs3.rmSync(projectDir, { recursive: true, force: true });
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
fs3.mkdirSync(projectDir, { recursive: true });
|
|
2644
|
+
const graphFileName = "graph.ts";
|
|
2645
|
+
const graphFilePath = path3.join(projectDir, graphFileName);
|
|
2646
|
+
const packageJsonPath = path3.join(projectDir, "package.json");
|
|
2647
|
+
const readmePath = path3.join(projectDir, "README.md");
|
|
2648
|
+
console.log();
|
|
2649
|
+
header(`\u{1F680} Initializing Inworld graph project: ${projectName}`);
|
|
2650
|
+
print(`\u{1F4C2} Creating project in: ${projectDir}`);
|
|
2651
|
+
print(`\u{1F4CB} Using template: ${selectedTemplate.metadata.displayName}`);
|
|
2652
|
+
console.log();
|
|
2653
|
+
print("\u{1F4DD} Creating graph file...");
|
|
2654
|
+
const graphContent = createGraphTemplate(selectedTemplate.directory);
|
|
2655
|
+
fs3.writeFileSync(graphFilePath, graphContent, "utf-8");
|
|
2656
|
+
if (!options.skipPackageJson) {
|
|
2657
|
+
print("\u{1F4E6} Creating package.json...");
|
|
2658
|
+
const packageJson = createPackageJson(graphFileName);
|
|
2659
|
+
packageJson.name = projectName;
|
|
2660
|
+
fs3.writeFileSync(
|
|
2661
|
+
packageJsonPath,
|
|
2662
|
+
JSON.stringify(packageJson, null, 2),
|
|
2663
|
+
"utf-8"
|
|
2664
|
+
);
|
|
2665
|
+
}
|
|
2666
|
+
if (!options.skipReadme) {
|
|
2667
|
+
print("\u{1F4DA} Creating README.md...");
|
|
2668
|
+
const readmeContent = createReadme(
|
|
2669
|
+
selectedTemplate.directory,
|
|
2670
|
+
graphFileName
|
|
2671
|
+
);
|
|
2672
|
+
fs3.writeFileSync(readmePath, readmeContent, "utf-8");
|
|
2673
|
+
}
|
|
2674
|
+
if (selectedTemplate.metadata.requirements?.apiKeys) {
|
|
2675
|
+
console.log();
|
|
2676
|
+
print("\u26A0\uFE0F This template requires the following API keys:");
|
|
2677
|
+
for (const key of selectedTemplate.metadata.requirements.apiKeys) {
|
|
2678
|
+
print(` \u2022 ${key}`);
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
if (selectedTemplate.metadata.examples?.curlCommand) {
|
|
2682
|
+
console.log();
|
|
2683
|
+
header("\u{1F4DD} Example usage:");
|
|
2684
|
+
print(` ${selectedTemplate.metadata.examples.curlCommand}`);
|
|
2685
|
+
}
|
|
2686
|
+
console.log();
|
|
2687
|
+
success("\u2705 Inworld graph project initialized successfully!");
|
|
2688
|
+
if (!options.skipInstall && !options.skipPackageJson) {
|
|
2689
|
+
const shouldInstall = await promptNpmInstall();
|
|
2690
|
+
if (shouldInstall) {
|
|
2691
|
+
try {
|
|
2692
|
+
await runNpmInstall(projectDir);
|
|
2693
|
+
} catch (_err) {
|
|
2694
|
+
console.log();
|
|
2695
|
+
print("\u26A0\uFE0F You can install dependencies manually by running:");
|
|
2696
|
+
print(` cd ${projectName} && npm install`);
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
console.log();
|
|
2701
|
+
header("\u{1F4CC} Next steps:");
|
|
2702
|
+
print(` 1. ${chalk9.bold(`cd ${projectName}`)}`);
|
|
2703
|
+
if (!options.skipInstall) {
|
|
2704
|
+
print(` 2. ${chalk9.bold("npm install")} (if not already done)`);
|
|
2705
|
+
print(
|
|
2706
|
+
` 3. ${chalk9.bold("npm start")} or ${chalk9.bold("npx inworld serve graph.ts")}`
|
|
2707
|
+
);
|
|
2708
|
+
} else {
|
|
2709
|
+
print(
|
|
2710
|
+
` 2. ${chalk9.bold("npm start")} or ${chalk9.bold("npx inworld serve graph.ts")}`
|
|
2711
|
+
);
|
|
2712
|
+
}
|
|
2713
|
+
if (selectedTemplate.metadata.requirements?.apiKeys) {
|
|
2714
|
+
console.log();
|
|
2715
|
+
print("\u{1F4A1} Remember to set your API keys before running!");
|
|
2716
|
+
}
|
|
2717
|
+
} catch (error) {
|
|
2718
|
+
printError("\u274C Error initializing project:");
|
|
2719
|
+
console.error(error);
|
|
2720
|
+
process.exit(1);
|
|
2721
|
+
}
|
|
2722
|
+
};
|
|
2723
|
+
var makeInitCommand = (description) => {
|
|
2724
|
+
const availableTemplates = getAvailableTemplatesWithMetadata();
|
|
2725
|
+
return new Command8("init").description(description).option("-n, --name <name>", "Name of the project directory").option(
|
|
2726
|
+
"-t, --template <template>",
|
|
2727
|
+
`Template to use: ${availableTemplates.map((t) => `"${t.directory}"`).join(" or ")}`
|
|
2728
|
+
).option("-l, --list-templates", "List all available templates").option("--skip-package-json", "Skip creating package.json file").option("--skip-readme", "Skip creating README.md file").option("--skip-install", "Skip npm install prompt").action(initAction);
|
|
2729
|
+
};
|
|
2730
|
+
var initCommand = makeInitCommand(
|
|
2731
|
+
"Initialize a new Inworld graph project (interactive if no options provided)"
|
|
2732
|
+
);
|
|
2733
|
+
var initCommandAlias = makeInitCommand(
|
|
2734
|
+
`Alias for "${chalk9.bold("inworld graph init")}"`
|
|
2735
|
+
);
|
|
2736
|
+
|
|
2737
|
+
// src/commands/graph/graph_run_command.ts
|
|
2738
|
+
import chalk10 from "chalk";
|
|
2739
|
+
import { Command as Command9 } from "commander";
|
|
2740
|
+
var runAction = async (file, request) => {
|
|
2741
|
+
try {
|
|
2742
|
+
const { graph } = await loadGraph(file);
|
|
2743
|
+
let requestJson;
|
|
2744
|
+
try {
|
|
2745
|
+
requestJson = JSON.parse(request);
|
|
2746
|
+
} catch (error) {
|
|
2747
|
+
console.error("Error parsing request:", error);
|
|
2748
|
+
process.exit(1);
|
|
2749
|
+
}
|
|
2750
|
+
const results = await graph.executeJsonRequest(requestJson);
|
|
2751
|
+
for await (const result of results) {
|
|
2752
|
+
console.log(result);
|
|
2753
|
+
}
|
|
2754
|
+
} catch (error) {
|
|
2755
|
+
console.error("Error starting server:", error);
|
|
2756
|
+
}
|
|
2757
|
+
};
|
|
2758
|
+
var makeRunCommand = (description) => {
|
|
2759
|
+
return new Command9("run").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").argument(
|
|
2760
|
+
"<request>",
|
|
2761
|
+
`
|
|
2762
|
+
Graph input, heavily depends on the exact graph. E.g.:
|
|
2763
|
+
|
|
2764
|
+
{"input": "Hello"}
|
|
2765
|
+
|
|
2766
|
+
Also acceptes execution id, user context and data store content:
|
|
2767
|
+
|
|
2768
|
+
'{
|
|
2769
|
+
"input": {"my_complicated_input_object": "not really"},
|
|
2770
|
+
"executionId": "123e4567-e89b-12d3-a456-426614174000",
|
|
2771
|
+
"userContext": {"targetingKey": "id", "attributes": {}},
|
|
2772
|
+
"dataStoreContent": {}
|
|
2773
|
+
}'
|
|
2774
|
+
|
|
2775
|
+
Mirrors the input format of the Inworld HTTP Graph Server.
|
|
2776
|
+
`
|
|
2777
|
+
).action(runAction);
|
|
2778
|
+
};
|
|
2779
|
+
var runCommand = makeRunCommand(
|
|
2780
|
+
"Runs single execution against provided Inworld graph. Uses same input and output protocol as http server."
|
|
2781
|
+
);
|
|
2782
|
+
var runCommandAlias = makeRunCommand(
|
|
2783
|
+
`Alias for "${chalk10.bold("inworld graph run")}"`
|
|
2784
|
+
);
|
|
2785
|
+
|
|
2786
|
+
// src/commands/graph/graph_serve_command.ts
|
|
2787
|
+
import chalk11 from "chalk";
|
|
2788
|
+
import { Command as Command10 } from "commander";
|
|
2789
|
+
var serveAction = async (file, options) => {
|
|
2790
|
+
try {
|
|
2791
|
+
const { graph } = await loadGraph(file);
|
|
2792
|
+
const port = parseInt(options.port, 10);
|
|
2793
|
+
const host = options.host;
|
|
2794
|
+
if (!["http", "grpc"].includes(options.transport)) {
|
|
2795
|
+
printError('Transport must be either "http" or "grpc"');
|
|
2796
|
+
process.exit(1);
|
|
2797
|
+
}
|
|
2798
|
+
await graph.serve({
|
|
2799
|
+
host,
|
|
2800
|
+
port,
|
|
2801
|
+
transport: options.transport,
|
|
2802
|
+
swagger: options.swagger
|
|
2803
|
+
});
|
|
2804
|
+
} catch (error) {
|
|
2805
|
+
printError("Error starting server:");
|
|
2806
|
+
console.error(error);
|
|
2807
|
+
process.exit(1);
|
|
2808
|
+
}
|
|
2809
|
+
};
|
|
2810
|
+
var makeServeCommand = (description) => {
|
|
2811
|
+
return new Command10("serve").description(description).argument("<file>", "Path to the graph file (e.g., test.ts)").option("-p, --port <port>", "Port to run the server on", "3000").option("--host <host>", "Host to bind the server to", "localhost").option(
|
|
2812
|
+
"-t, --transport <transport>",
|
|
2813
|
+
"Transport protocol (http or grpc)",
|
|
2814
|
+
"http"
|
|
2815
|
+
).option(
|
|
2816
|
+
"--swagger",
|
|
2817
|
+
"Enable Swagger UI documentation (HTTP transport only)",
|
|
2818
|
+
false
|
|
2819
|
+
).action(serveAction);
|
|
2820
|
+
};
|
|
2821
|
+
var serveCommand = makeServeCommand(
|
|
2822
|
+
"Start a server that wraps an Inworld Runtime graph"
|
|
2823
|
+
);
|
|
2824
|
+
var serveCommandAlias = makeServeCommand(
|
|
2825
|
+
`Alias for "${chalk11.bold("inworld graph serve")}"`
|
|
2826
|
+
);
|
|
2827
|
+
|
|
2828
|
+
// src/commands/graph_command.ts
|
|
2829
|
+
import { Command as Command16 } from "commander";
|
|
2830
|
+
|
|
2831
|
+
// src/commands/graph/graph_variant_command.ts
|
|
2832
|
+
import { Command as Command14 } from "commander";
|
|
2833
|
+
|
|
2834
|
+
// src/commands/graph/variant/graph_variant_list_command.ts
|
|
2835
|
+
import { Command as Command11 } from "commander";
|
|
2836
|
+
|
|
2837
|
+
// src/services/graph_variant_service.ts
|
|
2838
|
+
var listGraphVariants = async (graphId) => {
|
|
2839
|
+
const workspaceId = await requireWorkspace();
|
|
2840
|
+
const graphResourceName = getGraphResourceName(workspaceId, graphId);
|
|
2841
|
+
return await authenticatedInworldRequest(GraphsService.ListGraphVariants, {
|
|
2842
|
+
parent: graphResourceName
|
|
2843
|
+
});
|
|
2844
|
+
};
|
|
2845
|
+
function toAlphanumericDashUnderscore(input) {
|
|
2846
|
+
return input.replace(/\s+/g, "_").replace(/[^a-zA-Z0-9-_]/g, "").toLowerCase();
|
|
2847
|
+
}
|
|
2848
|
+
var registerGraphVariant = async (graphId, variantDisplayName, variantConfig, force = false) => {
|
|
2849
|
+
const request = force ? GraphsService.UpdateGraphVariant : GraphsService.CreateGraphVariant;
|
|
2850
|
+
const workspaceId = await requireWorkspace();
|
|
2851
|
+
const graphResourceName = getGraphResourceName(workspaceId, graphId);
|
|
2852
|
+
const variantResourceName = getGraphVariantResourceName(
|
|
2853
|
+
workspaceId,
|
|
2854
|
+
graphId,
|
|
2855
|
+
toAlphanumericDashUnderscore(variantDisplayName)
|
|
2856
|
+
);
|
|
2857
|
+
await ensureGraphRegistered(workspaceId, graphId);
|
|
2858
|
+
try {
|
|
2859
|
+
const operation = await authenticatedInworldRequest(request, {
|
|
2860
|
+
parent: graphResourceName,
|
|
2861
|
+
graphVariant: {
|
|
2862
|
+
config: {
|
|
2863
|
+
rawContent: variantConfig
|
|
2864
|
+
},
|
|
2865
|
+
displayName: variantDisplayName,
|
|
2866
|
+
name: variantResourceName,
|
|
2867
|
+
graph: graphResourceName
|
|
2868
|
+
}
|
|
2869
|
+
});
|
|
2870
|
+
await checkLRO({ operationName: operation.name });
|
|
2871
|
+
const graph = await ensureGraphRegistered(workspaceId, graphId);
|
|
2872
|
+
if (graph && graph.targeting?.rawContent === "{}") {
|
|
2873
|
+
console.log(
|
|
2874
|
+
`Graph "${graphId}" has no targeting, setting up registered variant as default...`
|
|
2875
|
+
);
|
|
2876
|
+
const operation2 = await authenticatedInworldRequest(
|
|
2877
|
+
GraphsService.UpdateGraph,
|
|
2878
|
+
{
|
|
2879
|
+
graph: {
|
|
2880
|
+
...graph,
|
|
2881
|
+
targeting: { rawContent: `{"if": ["${variantResourceName}"]}` }
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
);
|
|
2885
|
+
await checkLRO({ operationName: operation2.name });
|
|
2886
|
+
}
|
|
2887
|
+
} catch (error) {
|
|
2888
|
+
return error;
|
|
2889
|
+
}
|
|
2890
|
+
return true;
|
|
2891
|
+
};
|
|
2892
|
+
|
|
2893
|
+
// src/commands/graph/variant/graph_variant_list_command.ts
|
|
2894
|
+
var listVariantsAction = async (file) => {
|
|
2895
|
+
const workspaceId = await requireWorkspace();
|
|
2896
|
+
const { graph } = await loadGraph(file);
|
|
2897
|
+
const variants = await listGraphVariants(graph.graphId);
|
|
2898
|
+
if (!variants || variants.graphVariants?.length === 0) {
|
|
2899
|
+
console.log();
|
|
2900
|
+
print(
|
|
2901
|
+
`No registered variants of the graph "${graph.graphId}" found in workspace "${workspaceId}"`
|
|
2902
|
+
);
|
|
2903
|
+
return;
|
|
2904
|
+
}
|
|
2905
|
+
console.log();
|
|
2906
|
+
header(
|
|
2907
|
+
`Registered variants of the graph "${graph.graphId}" in workspace "${workspaceId}":`
|
|
2908
|
+
);
|
|
2909
|
+
variants.graphVariants?.forEach((variant) => {
|
|
2910
|
+
listItem(`${variant.name} - ${variant.displayName}`);
|
|
2911
|
+
});
|
|
2912
|
+
};
|
|
2913
|
+
var graphListVariantsCommand = new Command11("list").description("List all registered variants of the graph.").argument("<file>", "Path to the graph file (e.g., graph.ts)").action(listVariantsAction);
|
|
2914
|
+
|
|
2915
|
+
// src/commands/graph/variant/graph_variant_print_command.ts
|
|
2916
|
+
import { Command as Command12 } from "commander";
|
|
2917
|
+
import path4 from "path";
|
|
2918
|
+
var graphVariantPrintAction = async (file, options) => {
|
|
2919
|
+
try {
|
|
2920
|
+
const { graph } = await loadGraph(file);
|
|
2921
|
+
const jsonResult = await graph.toJSON();
|
|
2922
|
+
if (options.output) {
|
|
2923
|
+
const outputPath = path4.resolve(options.output);
|
|
2924
|
+
const fs4 = await import("fs/promises");
|
|
2925
|
+
await fs4.writeFile(options.output, jsonResult);
|
|
2926
|
+
success(`JSON saved to ${outputPath}`);
|
|
2927
|
+
} else {
|
|
2928
|
+
console.log(jsonResult);
|
|
2929
|
+
}
|
|
2930
|
+
} catch (error) {
|
|
2931
|
+
printError("Error converting graph to JSON:");
|
|
2932
|
+
console.error(error);
|
|
2933
|
+
process.exit(1);
|
|
2934
|
+
}
|
|
2935
|
+
};
|
|
2936
|
+
var graphVariantPrintCommand = new Command12("print").description("Print JSON representation of the graph variant").argument("<file>", "Path to the graph file (e.g., test.ts)").option(
|
|
2937
|
+
"-o, --output <file>",
|
|
2938
|
+
"Output file path (if not specified, outputs to console)"
|
|
2939
|
+
).action(graphVariantPrintAction);
|
|
2940
|
+
|
|
2941
|
+
// src/commands/graph/variant/graph_variant_register_command.ts
|
|
2942
|
+
import chalk12 from "chalk";
|
|
2943
|
+
import { Command as Command13 } from "commander";
|
|
2944
|
+
var registerVariantsAction = async (file, options) => {
|
|
2945
|
+
const workspaceId = await requireWorkspace();
|
|
2946
|
+
const { graph } = await loadGraph(file);
|
|
2947
|
+
let response = await registerGraphVariant(
|
|
2948
|
+
graph.graphId,
|
|
2949
|
+
options.displayName,
|
|
2950
|
+
graph.toJSON()
|
|
2951
|
+
);
|
|
2952
|
+
if (response !== true && isGrpcError(response) && response.code === 6 /* ALREADY_EXISTS */) {
|
|
2953
|
+
if (options.force) {
|
|
2954
|
+
response = await registerGraphVariant(
|
|
2955
|
+
graph.graphId,
|
|
2956
|
+
options.displayName,
|
|
2957
|
+
graph.toJSON(),
|
|
2958
|
+
true
|
|
2959
|
+
);
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
if (response === true) {
|
|
2963
|
+
const uri = `${PLATFORM_URL}/v2/${getGraphResourceName(workspaceId, graph.graphId)}/targeting`;
|
|
2964
|
+
console.log();
|
|
2965
|
+
success(
|
|
2966
|
+
`Variant "${options.displayName}" ${options.force ? "updated" : "registered"} successfully`
|
|
2967
|
+
);
|
|
2968
|
+
console.log();
|
|
2969
|
+
print(
|
|
2970
|
+
`Now you can open ${chalk12.cyan.underline(uri)} and setup targeting for different variants`
|
|
2971
|
+
);
|
|
2972
|
+
} else {
|
|
2973
|
+
if (isGrpcError(response) && response.code === 6 /* ALREADY_EXISTS */) {
|
|
2974
|
+
console.log();
|
|
2975
|
+
printError(
|
|
2976
|
+
`Variant "${options.displayName}" already registered for graph "${graph.graphId}" in workspace "${workspaceId}", use --force option to update it`
|
|
2977
|
+
);
|
|
2978
|
+
} else {
|
|
2979
|
+
printError(`Failed to register variant "${options.displayName}"`);
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
};
|
|
2983
|
+
var graphVariantRegisterCommand = new Command13("register").description("List all registered variants of the graph.").argument("<file>", "Path to the graph file (e.g., graph.ts)").requiredOption(
|
|
2984
|
+
"-d, --display-name <variantDisplayName>",
|
|
2985
|
+
"The display name of the variant"
|
|
2986
|
+
).option("-f, --force", "Updates the variant if it already exists", false).action(registerVariantsAction);
|
|
2987
|
+
|
|
2988
|
+
// src/commands/graph/graph_variant_command.ts
|
|
2989
|
+
var graphVariantCommand = new Command14("variant").description("Manage Inworld graph variants").addCommand(graphListVariantsCommand).addCommand(graphVariantRegisterCommand).addCommand(graphVariantPrintCommand).action(() => {
|
|
2990
|
+
graphVariantCommand.help();
|
|
2991
|
+
});
|
|
2992
|
+
|
|
2993
|
+
// src/commands/graph/graph_visualize_command.ts
|
|
2994
|
+
import { Command as Command15 } from "commander";
|
|
2995
|
+
import path5 from "path";
|
|
2996
|
+
var visualizeAction = async (file, options) => {
|
|
2997
|
+
try {
|
|
2998
|
+
const { graph } = await loadGraph(file);
|
|
2999
|
+
const outputPath = path5.resolve(options.output);
|
|
3000
|
+
print(`Storing graph visualization to ${outputPath}`);
|
|
3001
|
+
await graph.visualize(outputPath);
|
|
3002
|
+
} catch (error) {
|
|
3003
|
+
printError("Error visualizing graph:");
|
|
3004
|
+
console.error(error);
|
|
3005
|
+
process.exit(1);
|
|
3006
|
+
}
|
|
3007
|
+
};
|
|
3008
|
+
var visualizeCommand = new Command15("visualize").description("Generate a visualization of an Inworld Runtime graph").argument("<file>", "Path to the graph file (e.g., test.ts)").option(
|
|
3009
|
+
"-o, --output <file>",
|
|
3010
|
+
"Output file path (if not specified, outputs to graph.png in current directory)",
|
|
3011
|
+
"./graph.png"
|
|
3012
|
+
).action(visualizeAction);
|
|
3013
|
+
|
|
3014
|
+
// src/commands/graph_command.ts
|
|
3015
|
+
var graphCommand = new Command16("graph").description("Manage Inworld graph projects").addCommand(initCommand).addCommand(serveCommand).addCommand(runCommand).addCommand(deployCommand).addCommand(visualizeCommand).addCommand(graphVariantCommand).action(() => {
|
|
3016
|
+
graphCommand.help();
|
|
3017
|
+
});
|
|
3018
|
+
|
|
3019
|
+
// src/commands/tts_commands.ts
|
|
3020
|
+
import chalk13 from "chalk";
|
|
3021
|
+
import { Command as Command17 } from "commander";
|
|
3022
|
+
import { writeFile } from "fs/promises";
|
|
3023
|
+
import { resolve } from "path";
|
|
3024
|
+
|
|
3025
|
+
// src/services/tts_service.ts
|
|
3026
|
+
var TTSService = class {
|
|
3027
|
+
apiKey = null;
|
|
3028
|
+
/**
|
|
3029
|
+
* Ensures the API key is available
|
|
3030
|
+
* @private
|
|
3031
|
+
*/
|
|
3032
|
+
async ensureApiKey() {
|
|
3033
|
+
if (!this.apiKey) {
|
|
3034
|
+
this.apiKey = await requireApiKey();
|
|
3035
|
+
}
|
|
3036
|
+
return this.apiKey;
|
|
3037
|
+
}
|
|
3038
|
+
/**
|
|
3039
|
+
* Makes an authenticated request to the Inworld API
|
|
3040
|
+
* @private
|
|
3041
|
+
*/
|
|
3042
|
+
async makeRequest(endpoint, options = {}, trackMetrics = false) {
|
|
3043
|
+
const apiKey = await this.ensureApiKey();
|
|
3044
|
+
const url = `${PLATFORM_URL.replace("platform", "api")}${endpoint}`;
|
|
3045
|
+
const metrics = trackMetrics ? {
|
|
3046
|
+
startTime: Date.now(),
|
|
3047
|
+
ttfb: 0,
|
|
3048
|
+
totalTime: 0,
|
|
3049
|
+
responseSize: 0
|
|
3050
|
+
} : {};
|
|
3051
|
+
const response = await fetch(url, {
|
|
3052
|
+
...options,
|
|
3053
|
+
headers: {
|
|
3054
|
+
Authorization: `Basic ${apiKey}`,
|
|
3055
|
+
"Content-Type": "application/json",
|
|
3056
|
+
...options.headers
|
|
3057
|
+
}
|
|
3058
|
+
});
|
|
3059
|
+
if (trackMetrics) {
|
|
3060
|
+
metrics.ttfb = Date.now() - metrics.startTime;
|
|
3061
|
+
}
|
|
3062
|
+
const data = await response.json();
|
|
3063
|
+
if (trackMetrics) {
|
|
3064
|
+
metrics.totalTime = Date.now() - metrics.startTime;
|
|
3065
|
+
metrics.responseSize = JSON.stringify(data).length;
|
|
3066
|
+
}
|
|
3067
|
+
if (!response.ok) {
|
|
3068
|
+
const error = data;
|
|
3069
|
+
throw new Error(
|
|
3070
|
+
`TTS API Error [${error.code || response.status}]: ${error.message || "Unknown error"}`
|
|
3071
|
+
);
|
|
3072
|
+
}
|
|
3073
|
+
const result = data;
|
|
3074
|
+
if (trackMetrics) {
|
|
3075
|
+
result._metrics = metrics;
|
|
3076
|
+
}
|
|
3077
|
+
return result;
|
|
3078
|
+
}
|
|
3079
|
+
/**
|
|
3080
|
+
* Lists all available voices based on the provided filter
|
|
3081
|
+
* @param filter - Optional filter expression (e.g., "language=en")
|
|
3082
|
+
* @returns Promise resolving to the list of available voices
|
|
3083
|
+
* @example
|
|
3084
|
+
* ```typescript
|
|
3085
|
+
* const ttsService = new TTSService();
|
|
3086
|
+
* const voices = await ttsService.listVoices('language=en');
|
|
3087
|
+
* console.log(voices.voices);
|
|
3088
|
+
* ```
|
|
3089
|
+
*/
|
|
3090
|
+
async listVoices(filter) {
|
|
3091
|
+
const params = filter ? `?filter=${encodeURIComponent(filter)}` : "";
|
|
3092
|
+
return this.makeRequest(`/tts/v1/voices${params}`, {
|
|
3093
|
+
method: "GET"
|
|
3094
|
+
});
|
|
3095
|
+
}
|
|
3096
|
+
/**
|
|
3097
|
+
* Synthesizes speech from text
|
|
3098
|
+
* @param request - The synthesis request parameters
|
|
3099
|
+
* @returns Promise resolving to the synthesized audio data and optional timestamp information
|
|
3100
|
+
* @example
|
|
3101
|
+
* ```typescript
|
|
3102
|
+
* const ttsService = new TTSService();
|
|
3103
|
+
* const result = await ttsService.synthesizeSpeech({
|
|
3104
|
+
* text: 'Hello, world!',
|
|
3105
|
+
* voiceId: 'Dennis',
|
|
3106
|
+
* modelId: TTSModel.INWORLD_TTS_1,
|
|
3107
|
+
* timestampType: TimestampType.WORD,
|
|
3108
|
+
* });
|
|
3109
|
+
* // result.audioContent is base64 encoded audio data
|
|
3110
|
+
* ```
|
|
3111
|
+
*/
|
|
3112
|
+
async synthesizeSpeech(request) {
|
|
3113
|
+
return this.makeRequest("/tts/v1/voice", {
|
|
3114
|
+
method: "POST",
|
|
3115
|
+
body: JSON.stringify(request)
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* Synthesizes speech from text with performance metrics
|
|
3120
|
+
* @param request - The synthesis request parameters
|
|
3121
|
+
* @returns Promise resolving to the synthesized audio data with metrics
|
|
3122
|
+
*/
|
|
3123
|
+
async synthesizeSpeechWithMetrics(request) {
|
|
3124
|
+
return this.makeRequest(
|
|
3125
|
+
"/tts/v1/voice",
|
|
3126
|
+
{
|
|
3127
|
+
method: "POST",
|
|
3128
|
+
body: JSON.stringify(request)
|
|
3129
|
+
},
|
|
3130
|
+
true
|
|
3131
|
+
// trackMetrics
|
|
3132
|
+
);
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Synthesizes speech using streaming API
|
|
3136
|
+
* @param request - The synthesis request parameters
|
|
3137
|
+
* @param onChunk - Callback for each audio chunk received
|
|
3138
|
+
* @param trackMetrics - Whether to track streaming metrics
|
|
3139
|
+
* @returns Promise resolving when stream completes, with optional metrics
|
|
3140
|
+
*/
|
|
3141
|
+
async synthesizeSpeechStream(request, onChunk, trackMetrics = false) {
|
|
3142
|
+
const apiKey = await this.ensureApiKey();
|
|
3143
|
+
const url = `${PLATFORM_URL.replace("platform", "api")}/tts/v1/voice:stream`;
|
|
3144
|
+
const metrics = trackMetrics ? {
|
|
3145
|
+
startTime: Date.now(),
|
|
3146
|
+
timeToFirstChunk: 0,
|
|
3147
|
+
totalTime: 0,
|
|
3148
|
+
chunksReceived: 0,
|
|
3149
|
+
totalBytes: 0,
|
|
3150
|
+
chunkSizes: [],
|
|
3151
|
+
chunkIntervals: [],
|
|
3152
|
+
errorChunks: 0
|
|
3153
|
+
} : {};
|
|
3154
|
+
const response = await fetch(url, {
|
|
3155
|
+
method: "POST",
|
|
3156
|
+
headers: {
|
|
3157
|
+
Authorization: `Basic ${apiKey}`,
|
|
3158
|
+
"Content-Type": "application/json"
|
|
3159
|
+
},
|
|
3160
|
+
body: JSON.stringify(request)
|
|
3161
|
+
});
|
|
3162
|
+
if (!response.ok) {
|
|
3163
|
+
const error = await response.json();
|
|
3164
|
+
throw new Error(
|
|
3165
|
+
`TTS Stream API Error [${error.code || response.status}]: ${error.message || "Unknown error"}`
|
|
3166
|
+
);
|
|
3167
|
+
}
|
|
3168
|
+
if (!response.body) {
|
|
3169
|
+
throw new Error("No response body received from streaming endpoint");
|
|
3170
|
+
}
|
|
3171
|
+
const reader = response.body.getReader();
|
|
3172
|
+
const decoder = new TextDecoder();
|
|
3173
|
+
let buffer = "";
|
|
3174
|
+
let lastChunkTime = trackMetrics ? Date.now() : 0;
|
|
3175
|
+
let isFirstChunk = true;
|
|
3176
|
+
try {
|
|
3177
|
+
while (true) {
|
|
3178
|
+
const { done, value } = await reader.read();
|
|
3179
|
+
if (done) break;
|
|
3180
|
+
buffer += decoder.decode(value, { stream: true });
|
|
3181
|
+
const lines = buffer.split("\n");
|
|
3182
|
+
buffer = lines.pop() || "";
|
|
3183
|
+
for (const line of lines) {
|
|
3184
|
+
if (!line.trim()) continue;
|
|
3185
|
+
try {
|
|
3186
|
+
const data = JSON.parse(line);
|
|
3187
|
+
if (trackMetrics) {
|
|
3188
|
+
const now = Date.now();
|
|
3189
|
+
if (isFirstChunk) {
|
|
3190
|
+
metrics.timeToFirstChunk = now - metrics.startTime;
|
|
3191
|
+
isFirstChunk = false;
|
|
3192
|
+
} else {
|
|
3193
|
+
metrics.chunkIntervals.push(now - lastChunkTime);
|
|
3194
|
+
}
|
|
3195
|
+
lastChunkTime = now;
|
|
3196
|
+
metrics.chunksReceived++;
|
|
3197
|
+
if (data.result?.audioContent) {
|
|
3198
|
+
const chunkSize = data.result.audioContent.length;
|
|
3199
|
+
metrics.chunkSizes.push(chunkSize);
|
|
3200
|
+
metrics.totalBytes += chunkSize;
|
|
3201
|
+
}
|
|
3202
|
+
if (data.error) {
|
|
3203
|
+
metrics.errorChunks++;
|
|
3204
|
+
}
|
|
3205
|
+
}
|
|
3206
|
+
if (data.result) {
|
|
3207
|
+
onChunk(data.result);
|
|
3208
|
+
} else if (data.error) {
|
|
3209
|
+
onChunk({ error: data.error });
|
|
3210
|
+
}
|
|
3211
|
+
} catch (e) {
|
|
3212
|
+
console.error("Failed to parse streaming chunk:", e);
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
}
|
|
3216
|
+
if (buffer.trim()) {
|
|
3217
|
+
try {
|
|
3218
|
+
const data = JSON.parse(buffer);
|
|
3219
|
+
if (data.result) {
|
|
3220
|
+
onChunk(data.result);
|
|
3221
|
+
} else if (data.error) {
|
|
3222
|
+
onChunk({ error: data.error });
|
|
3223
|
+
}
|
|
3224
|
+
} catch (e) {
|
|
3225
|
+
console.error("Failed to parse final chunk:", e);
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
} finally {
|
|
3229
|
+
reader.releaseLock();
|
|
3230
|
+
}
|
|
3231
|
+
if (trackMetrics) {
|
|
3232
|
+
metrics.totalTime = Date.now() - metrics.startTime;
|
|
3233
|
+
}
|
|
3234
|
+
return trackMetrics ? { _metrics: metrics } : {};
|
|
3235
|
+
}
|
|
3236
|
+
/**
|
|
3237
|
+
* Helper method to synthesize speech with simple parameters
|
|
3238
|
+
* @param text - The text to synthesize
|
|
3239
|
+
* @param voiceId - The voice ID to use
|
|
3240
|
+
* @param modelId - The model ID to use (defaults to inworld-tts-1-max)
|
|
3241
|
+
* @returns Promise resolving to the synthesized audio data
|
|
3242
|
+
* @example
|
|
3243
|
+
* ```typescript
|
|
3244
|
+
* const ttsService = new TTSService();
|
|
3245
|
+
* const result = await ttsService.synthesize('Hello, world!', 'Dennis');
|
|
3246
|
+
* const audioBuffer = Buffer.from(result.audioContent, 'base64');
|
|
3247
|
+
* ```
|
|
3248
|
+
*/
|
|
3249
|
+
async synthesize(text, voiceId, modelId = "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */) {
|
|
3250
|
+
return this.synthesizeSpeech({
|
|
3251
|
+
text,
|
|
3252
|
+
voiceId,
|
|
3253
|
+
modelId
|
|
3254
|
+
});
|
|
3255
|
+
}
|
|
3256
|
+
/**
|
|
3257
|
+
* Saves synthesized audio to a file
|
|
3258
|
+
* @param audioContent - Base64 encoded audio content
|
|
3259
|
+
* @param filepath - Path where the audio file should be saved
|
|
3260
|
+
* @returns Promise that resolves when the file is written
|
|
3261
|
+
* @example
|
|
3262
|
+
* ```typescript
|
|
3263
|
+
* const ttsService = new TTSService();
|
|
3264
|
+
* const result = await ttsService.synthesize('Hello, world!', 'Dennis');
|
|
3265
|
+
* await ttsService.saveAudioToFile(result.audioContent, 'output.mp3');
|
|
3266
|
+
* ```
|
|
3267
|
+
*/
|
|
3268
|
+
async saveAudioToFile(audioContent, filepath) {
|
|
3269
|
+
const { writeFile: writeFile2 } = await import("fs/promises");
|
|
3270
|
+
const audioBuffer = Buffer.from(audioContent, "base64");
|
|
3271
|
+
await writeFile2(filepath, audioBuffer);
|
|
3272
|
+
}
|
|
3273
|
+
};
|
|
3274
|
+
var ttsService = new TTSService();
|
|
3275
|
+
|
|
3276
|
+
// src/commands/tts_commands.ts
|
|
3277
|
+
function wrapText(text, maxWidth) {
|
|
3278
|
+
const words = text.split(" ");
|
|
3279
|
+
const lines = [];
|
|
3280
|
+
let currentLine = "";
|
|
3281
|
+
for (const word of words) {
|
|
3282
|
+
if (currentLine.length + word.length + 1 <= maxWidth) {
|
|
3283
|
+
currentLine += (currentLine ? " " : "") + word;
|
|
3284
|
+
} else {
|
|
3285
|
+
if (currentLine) lines.push(currentLine);
|
|
3286
|
+
currentLine = word;
|
|
3287
|
+
}
|
|
3288
|
+
}
|
|
3289
|
+
if (currentLine) lines.push(currentLine);
|
|
3290
|
+
return lines;
|
|
3291
|
+
}
|
|
3292
|
+
var listVoicesCommand = new Command17("list-voices").description("List all available voices from the workspace").option("-f, --filter <filter>", 'Filter voices (e.g., "language=en")').option("-j, --json", "Output as JSON").option("-c, --compact", "Compact output (voice IDs only)").action(async (options) => {
|
|
3293
|
+
try {
|
|
3294
|
+
const response = await ttsService.listVoices(options.filter);
|
|
3295
|
+
if (options.json) {
|
|
3296
|
+
console.log(JSON.stringify(response, null, 2));
|
|
3297
|
+
process.exit(0);
|
|
3298
|
+
return;
|
|
3299
|
+
}
|
|
3300
|
+
if (!response.voices || response.voices.length === 0) {
|
|
3301
|
+
console.log(chalk13.yellow("\u26A0\uFE0F No voices found"));
|
|
3302
|
+
process.exit(0);
|
|
3303
|
+
return;
|
|
3304
|
+
}
|
|
3305
|
+
if (options.compact) {
|
|
3306
|
+
console.log("\n" + chalk13.bold.green("\u{1F3A4} Available Voice IDs:"));
|
|
3307
|
+
console.log(chalk13.gray("\u2500".repeat(50)));
|
|
3308
|
+
response.voices.sort((a, b) => a.voiceId.localeCompare(b.voiceId)).forEach((voice) => {
|
|
3309
|
+
console.log(` ${chalk13.cyan("\u2022")} ${voice.voiceId}`);
|
|
3310
|
+
});
|
|
3311
|
+
console.log();
|
|
3312
|
+
process.exit(0);
|
|
3313
|
+
return;
|
|
3314
|
+
}
|
|
3315
|
+
const voicesByLanguage = /* @__PURE__ */ new Map();
|
|
3316
|
+
response.voices.forEach((voice) => {
|
|
3317
|
+
const languages = voice.languages || [];
|
|
3318
|
+
const primaryLang = languages[0] || "unknown";
|
|
3319
|
+
if (!voicesByLanguage.has(primaryLang)) {
|
|
3320
|
+
voicesByLanguage.set(primaryLang, []);
|
|
3321
|
+
}
|
|
3322
|
+
voicesByLanguage.get(primaryLang).push(voice);
|
|
3323
|
+
});
|
|
3324
|
+
const sortedLanguages = Array.from(voicesByLanguage.keys()).sort();
|
|
3325
|
+
console.log("\n" + chalk13.bold.green("Available TTS Voices"));
|
|
3326
|
+
console.log(
|
|
3327
|
+
chalk13.gray(
|
|
3328
|
+
`Found ${response.voices.length} voices across ${sortedLanguages.length} languages`
|
|
3329
|
+
)
|
|
3330
|
+
);
|
|
3331
|
+
console.log(chalk13.gray("\u2500".repeat(80)));
|
|
3332
|
+
sortedLanguages.forEach((lang, langIndex) => {
|
|
3333
|
+
const voices = voicesByLanguage.get(lang);
|
|
3334
|
+
const languageFlags = {
|
|
3335
|
+
en: "\u{1F1EC}\u{1F1E7}",
|
|
3336
|
+
es: "\u{1F1EA}\u{1F1F8}",
|
|
3337
|
+
fr: "\u{1F1EB}\u{1F1F7}",
|
|
3338
|
+
de: "\u{1F1E9}\u{1F1EA}",
|
|
3339
|
+
it: "\u{1F1EE}\u{1F1F9}",
|
|
3340
|
+
pt: "\u{1F1F5}\u{1F1F9}",
|
|
3341
|
+
nl: "\u{1F1F3}\u{1F1F1}",
|
|
3342
|
+
pl: "\u{1F1F5}\u{1F1F1}",
|
|
3343
|
+
ru: "\u{1F1F7}\u{1F1FA}",
|
|
3344
|
+
ja: "\u{1F1EF}\u{1F1F5}",
|
|
3345
|
+
ko: "\u{1F1F0}\u{1F1F7}",
|
|
3346
|
+
zh: "\u{1F1E8}\u{1F1F3}"
|
|
3347
|
+
};
|
|
3348
|
+
const flag = languageFlags[lang] || "\u{1F310}";
|
|
3349
|
+
console.log(
|
|
3350
|
+
`
|
|
3351
|
+
${flag} ${chalk13.bold.yellow(lang.toUpperCase())} ${chalk13.gray(`(${voices.length} voices)`)}`
|
|
3352
|
+
);
|
|
3353
|
+
console.log(chalk13.gray("\u2500".repeat(80)));
|
|
3354
|
+
voices.sort((a, b) => a.voiceId.localeCompare(b.voiceId)).forEach((voice) => {
|
|
3355
|
+
const displayName = voice.displayName && voice.displayName !== voice.voiceId ? chalk13.gray(` (${voice.displayName})`) : "";
|
|
3356
|
+
console.log(
|
|
3357
|
+
` ${chalk13.cyan("\u25B8")} ${chalk13.bold.white(voice.voiceId)}${displayName}`
|
|
3358
|
+
);
|
|
3359
|
+
if (voice.description) {
|
|
3360
|
+
const maxWidth = 76;
|
|
3361
|
+
const descriptionLines = wrapText(voice.description, maxWidth);
|
|
3362
|
+
descriptionLines.forEach((line) => {
|
|
3363
|
+
console.log(` ${chalk13.gray(line)}`);
|
|
3364
|
+
});
|
|
3365
|
+
}
|
|
3366
|
+
});
|
|
3367
|
+
if (langIndex < sortedLanguages.length - 1) {
|
|
3368
|
+
console.log();
|
|
3369
|
+
}
|
|
3370
|
+
});
|
|
3371
|
+
console.log("\n" + chalk13.gray("\u2500".repeat(80)));
|
|
3372
|
+
console.log(chalk13.gray("Tips:"));
|
|
3373
|
+
console.log(
|
|
3374
|
+
chalk13.gray(' \u2022 Use --filter "language=<code>" to filter by language')
|
|
3375
|
+
);
|
|
3376
|
+
console.log(
|
|
3377
|
+
chalk13.gray(" \u2022 Use --compact for a simple list of voice IDs")
|
|
3378
|
+
);
|
|
3379
|
+
console.log(chalk13.gray(" \u2022 Use --json for machine-readable output"));
|
|
3380
|
+
console.log(
|
|
3381
|
+
chalk13.gray('\nExample: inworld tts list-voices --filter "language=en"')
|
|
3382
|
+
);
|
|
3383
|
+
console.log();
|
|
3384
|
+
} catch (error) {
|
|
3385
|
+
console.error(chalk13.red("\u274C Error listing voices:"), error);
|
|
3386
|
+
process.exit(1);
|
|
3387
|
+
}
|
|
3388
|
+
process.exit(0);
|
|
3389
|
+
});
|
|
3390
|
+
var synthesizeCommand = new Command17("synthesize").description("Synthesize text to speech").argument("<text>", "Text to synthesize (max 2000 characters)").requiredOption(
|
|
3391
|
+
"-v, --voice <voiceId>",
|
|
3392
|
+
"Voice ID to use for synthesis",
|
|
3393
|
+
"Dennis"
|
|
3394
|
+
).option("-o, --output <file>", "Output audio file path (default: output.mp3)").option(
|
|
3395
|
+
"-m, --model <model>",
|
|
3396
|
+
"TTS model to use (inworld-tts-1 or inworld-tts-1-max)",
|
|
3397
|
+
"inworld-tts-1"
|
|
3398
|
+
).option(
|
|
3399
|
+
"-t, --temperature <temp>",
|
|
3400
|
+
"Temperature (0.0-2.0, default: 1.1)",
|
|
3401
|
+
"1.1"
|
|
3402
|
+
).option("--format <format>", "Audio format (MP3, LINEAR16, OGG_OPUS)", "MP3").option("--timestamps <type>", "Include timestamps (WORD or CHARACTER)").option("-j, --json", "Output response as JSON (includes base64 audio)").option("--stats", "Show request performance statistics").option("--stream", "Use streaming API for synthesis").action(async (text, options) => {
|
|
3403
|
+
try {
|
|
3404
|
+
if (text.length > 2e3) {
|
|
3405
|
+
console.error(chalk13.red("\u274C Error: Text exceeds 2000 character limit"));
|
|
3406
|
+
console.log(chalk13.gray(`Current length: ${text.length} characters`));
|
|
3407
|
+
process.exit(1);
|
|
3408
|
+
}
|
|
3409
|
+
const temperature = parseFloat(options.temperature);
|
|
3410
|
+
if (isNaN(temperature) || temperature < 0 || temperature > 2) {
|
|
3411
|
+
console.error(
|
|
3412
|
+
chalk13.red("\u274C Error: Temperature must be between 0.0 and 2.0")
|
|
3413
|
+
);
|
|
3414
|
+
process.exit(1);
|
|
3415
|
+
}
|
|
3416
|
+
const modelMap = {
|
|
3417
|
+
"inworld-tts-1": "inworld-tts-1" /* INWORLD_TTS_1 */,
|
|
3418
|
+
"inworld-tts-1-max": "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */
|
|
3419
|
+
};
|
|
3420
|
+
const modelId = modelMap[options.model] || "inworld-tts-1-max" /* INWORLD_TTS_1_MAX */;
|
|
3421
|
+
console.log(chalk13.cyan("\u{1F399}\uFE0F Synthesizing speech..."));
|
|
3422
|
+
console.log(chalk13.gray(`Voice: ${options.voice}`));
|
|
3423
|
+
console.log(chalk13.gray(`Model: ${options.model}`));
|
|
3424
|
+
console.log(chalk13.gray(`Text length: ${text.length} characters`));
|
|
3425
|
+
const request = {
|
|
3426
|
+
text,
|
|
3427
|
+
voiceId: options.voice,
|
|
3428
|
+
modelId,
|
|
3429
|
+
temperature
|
|
3430
|
+
};
|
|
3431
|
+
if (options.format) {
|
|
3432
|
+
request.audioConfig = {
|
|
3433
|
+
audioEncoding: options.format
|
|
3434
|
+
};
|
|
3435
|
+
}
|
|
3436
|
+
if (options.timestamps) {
|
|
3437
|
+
request.timestampType = options.timestamps;
|
|
3438
|
+
}
|
|
3439
|
+
let response;
|
|
3440
|
+
let audioBuffer;
|
|
3441
|
+
let fileExtension = ".mp3";
|
|
3442
|
+
if (options.stream) {
|
|
3443
|
+
let streamFormat = options.format || "LINEAR16";
|
|
3444
|
+
fileExtension = ".wav";
|
|
3445
|
+
if (options.format === "MP3") {
|
|
3446
|
+
console.log(
|
|
3447
|
+
chalk13.yellow(
|
|
3448
|
+
"\u26A0\uFE0F Warning: MP3 streaming requires special handling."
|
|
3449
|
+
)
|
|
3450
|
+
);
|
|
3451
|
+
console.log(
|
|
3452
|
+
chalk13.yellow(" Audio chunks may not concatenate perfectly.")
|
|
3453
|
+
);
|
|
3454
|
+
console.log(
|
|
3455
|
+
chalk13.yellow(
|
|
3456
|
+
" Consider using LINEAR16 or OGG_OPUS for better streaming."
|
|
3457
|
+
)
|
|
3458
|
+
);
|
|
3459
|
+
fileExtension = ".mp3";
|
|
3460
|
+
} else if (options.format === "OGG_OPUS") {
|
|
3461
|
+
fileExtension = ".ogg";
|
|
3462
|
+
} else if (options.format === "ALAW" || options.format === "MULAW") {
|
|
3463
|
+
fileExtension = ".raw";
|
|
3464
|
+
} else if (!options.format || options.format === "LINEAR16") {
|
|
3465
|
+
streamFormat = "LINEAR16";
|
|
3466
|
+
fileExtension = ".wav";
|
|
3467
|
+
}
|
|
3468
|
+
console.log(chalk13.cyan("\u{1F504} Using streaming synthesis..."));
|
|
3469
|
+
console.log(chalk13.gray(`Format: ${streamFormat}${fileExtension}`));
|
|
3470
|
+
const streamRequest = {
|
|
3471
|
+
...request,
|
|
3472
|
+
audioConfig: {
|
|
3473
|
+
...request.audioConfig,
|
|
3474
|
+
audioEncoding: streamFormat
|
|
3475
|
+
}
|
|
3476
|
+
};
|
|
3477
|
+
const audioChunks = [];
|
|
3478
|
+
let timestampInfo = null;
|
|
3479
|
+
let streamError = null;
|
|
3480
|
+
let chunkCount = 0;
|
|
3481
|
+
let isFirstChunk = true;
|
|
3482
|
+
const allWordAlignments = {
|
|
3483
|
+
words: [],
|
|
3484
|
+
wordStartTimeSeconds: [],
|
|
3485
|
+
wordEndTimeSeconds: []
|
|
3486
|
+
};
|
|
3487
|
+
const allCharacterAlignments = {
|
|
3488
|
+
characters: [],
|
|
3489
|
+
characterStartTimeSeconds: [],
|
|
3490
|
+
characterEndTimeSeconds: []
|
|
3491
|
+
};
|
|
3492
|
+
const streamResult = await ttsService.synthesizeSpeechStream(
|
|
3493
|
+
streamRequest,
|
|
3494
|
+
(chunk) => {
|
|
3495
|
+
chunkCount++;
|
|
3496
|
+
if (chunk.error) {
|
|
3497
|
+
streamError = chunk.error;
|
|
3498
|
+
console.error(
|
|
3499
|
+
chalk13.red(`\u274C Stream error: ${chunk.error.message}`)
|
|
3500
|
+
);
|
|
3501
|
+
} else {
|
|
3502
|
+
if (chunk.audioContent) {
|
|
3503
|
+
const chunkBuffer = Buffer.from(chunk.audioContent, "base64");
|
|
3504
|
+
if (streamFormat === "LINEAR16") {
|
|
3505
|
+
if (!isFirstChunk) {
|
|
3506
|
+
const headerSize = 44;
|
|
3507
|
+
if (chunkBuffer.length > headerSize) {
|
|
3508
|
+
audioChunks.push(chunkBuffer.slice(headerSize));
|
|
3509
|
+
}
|
|
3510
|
+
} else {
|
|
3511
|
+
audioChunks.push(chunkBuffer);
|
|
3512
|
+
isFirstChunk = false;
|
|
3513
|
+
}
|
|
3514
|
+
} else if (streamFormat === "OGG_OPUS") {
|
|
3515
|
+
audioChunks.push(chunkBuffer);
|
|
3516
|
+
} else if (streamFormat === "MP3") {
|
|
3517
|
+
audioChunks.push(chunkBuffer);
|
|
3518
|
+
} else {
|
|
3519
|
+
audioChunks.push(chunkBuffer);
|
|
3520
|
+
}
|
|
3521
|
+
if (!options.json && !options.stats) {
|
|
3522
|
+
const chunkSizeKB = (chunkBuffer.length / 1024).toFixed(2);
|
|
3523
|
+
process.stdout.write(
|
|
3524
|
+
chalk13.gray(
|
|
3525
|
+
`\rReceived chunk ${chunkCount} (${chunkSizeKB} KB)...`
|
|
3526
|
+
)
|
|
3527
|
+
);
|
|
3528
|
+
}
|
|
3529
|
+
}
|
|
3530
|
+
if (chunk.timestampInfo) {
|
|
3531
|
+
if (chunk.timestampInfo.wordAlignment) {
|
|
3532
|
+
const wa = chunk.timestampInfo.wordAlignment;
|
|
3533
|
+
allWordAlignments.words.push(...wa.words || []);
|
|
3534
|
+
allWordAlignments.wordStartTimeSeconds.push(
|
|
3535
|
+
...wa.wordStartTimeSeconds || []
|
|
3536
|
+
);
|
|
3537
|
+
allWordAlignments.wordEndTimeSeconds.push(
|
|
3538
|
+
...wa.wordEndTimeSeconds || []
|
|
3539
|
+
);
|
|
3540
|
+
}
|
|
3541
|
+
if (chunk.timestampInfo.characterAlignment) {
|
|
3542
|
+
const ca = chunk.timestampInfo.characterAlignment;
|
|
3543
|
+
allCharacterAlignments.characters.push(
|
|
3544
|
+
...ca.characters || []
|
|
3545
|
+
);
|
|
3546
|
+
allCharacterAlignments.characterStartTimeSeconds.push(
|
|
3547
|
+
...ca.characterStartTimeSeconds || []
|
|
3548
|
+
);
|
|
3549
|
+
allCharacterAlignments.characterEndTimeSeconds.push(
|
|
3550
|
+
...ca.characterEndTimeSeconds || []
|
|
3551
|
+
);
|
|
3552
|
+
}
|
|
3553
|
+
}
|
|
3554
|
+
}
|
|
3555
|
+
},
|
|
3556
|
+
options.stats
|
|
3557
|
+
// trackMetrics
|
|
3558
|
+
);
|
|
3559
|
+
if (!options.json && !options.stats && chunkCount > 0) {
|
|
3560
|
+
process.stdout.write("\r" + " ".repeat(50) + "\r");
|
|
3561
|
+
}
|
|
3562
|
+
if (streamError) {
|
|
3563
|
+
throw new Error(`Stream error: ${streamError.message}`);
|
|
3564
|
+
}
|
|
3565
|
+
audioBuffer = Buffer.concat(audioChunks);
|
|
3566
|
+
if (allWordAlignments.words.length > 0 || allCharacterAlignments.characters.length > 0) {
|
|
3567
|
+
timestampInfo = {};
|
|
3568
|
+
if (allWordAlignments.words.length > 0) {
|
|
3569
|
+
timestampInfo.wordAlignment = {
|
|
3570
|
+
words: allWordAlignments.words,
|
|
3571
|
+
wordStartTimeSeconds: allWordAlignments.wordStartTimeSeconds,
|
|
3572
|
+
wordEndTimeSeconds: allWordAlignments.wordEndTimeSeconds
|
|
3573
|
+
};
|
|
3574
|
+
}
|
|
3575
|
+
if (allCharacterAlignments.characters.length > 0) {
|
|
3576
|
+
timestampInfo.characterAlignment = {
|
|
3577
|
+
characters: allCharacterAlignments.characters,
|
|
3578
|
+
characterStartTimeSeconds: allCharacterAlignments.characterStartTimeSeconds,
|
|
3579
|
+
characterEndTimeSeconds: allCharacterAlignments.characterEndTimeSeconds
|
|
3580
|
+
};
|
|
3581
|
+
}
|
|
3582
|
+
}
|
|
3583
|
+
const combinedAudioBase64 = audioBuffer.toString("base64");
|
|
3584
|
+
response = {
|
|
3585
|
+
audioContent: combinedAudioBase64,
|
|
3586
|
+
timestampInfo,
|
|
3587
|
+
_metrics: streamResult._metrics
|
|
3588
|
+
};
|
|
3589
|
+
if (options.json) {
|
|
3590
|
+
console.log(
|
|
3591
|
+
JSON.stringify(
|
|
3592
|
+
{
|
|
3593
|
+
audioContent: combinedAudioBase64,
|
|
3594
|
+
timestampInfo,
|
|
3595
|
+
streamMetrics: streamResult._metrics
|
|
3596
|
+
},
|
|
3597
|
+
null,
|
|
3598
|
+
2
|
|
3599
|
+
)
|
|
3600
|
+
);
|
|
3601
|
+
} else {
|
|
3602
|
+
const outputPath = resolve(
|
|
3603
|
+
options.output || `output${fileExtension}`
|
|
3604
|
+
);
|
|
3605
|
+
await writeFile(outputPath, audioBuffer);
|
|
3606
|
+
console.log(chalk13.green(`\u2705 Audio saved to: ${outputPath}`));
|
|
3607
|
+
console.log(
|
|
3608
|
+
chalk13.gray(
|
|
3609
|
+
`File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
|
|
3610
|
+
)
|
|
3611
|
+
);
|
|
3612
|
+
console.log(chalk13.gray(`Chunks received: ${chunkCount}`));
|
|
3613
|
+
if (allWordAlignments.words.length > 0) {
|
|
3614
|
+
console.log(
|
|
3615
|
+
chalk13.gray(
|
|
3616
|
+
`Word timestamps collected: ${allWordAlignments.words.length}`
|
|
3617
|
+
)
|
|
3618
|
+
);
|
|
3619
|
+
}
|
|
3620
|
+
if (allCharacterAlignments.characters.length > 0) {
|
|
3621
|
+
console.log(
|
|
3622
|
+
chalk13.gray(
|
|
3623
|
+
`Character timestamps collected: ${allCharacterAlignments.characters.length}`
|
|
3624
|
+
)
|
|
3625
|
+
);
|
|
3626
|
+
}
|
|
3627
|
+
}
|
|
3628
|
+
} else {
|
|
3629
|
+
console.log(chalk13.cyan("\u{1F399}\uFE0F Synthesizing speech..."));
|
|
3630
|
+
console.log(chalk13.gray(`Voice: ${options.voice}`));
|
|
3631
|
+
console.log(chalk13.gray(`Model: ${options.model}`));
|
|
3632
|
+
console.log(chalk13.gray(`Text length: ${text.length} characters`));
|
|
3633
|
+
console.log(chalk13.gray(`Format: ${options.format || "MP3 (default)"}`));
|
|
3634
|
+
if (options.format === "LINEAR16") {
|
|
3635
|
+
fileExtension = ".wav";
|
|
3636
|
+
} else if (options.format === "OGG_OPUS") {
|
|
3637
|
+
fileExtension = ".ogg";
|
|
3638
|
+
} else if (options.format === "ALAW" || options.format === "MULAW") {
|
|
3639
|
+
fileExtension = ".raw";
|
|
3640
|
+
} else {
|
|
3641
|
+
fileExtension = ".mp3";
|
|
3642
|
+
}
|
|
3643
|
+
response = options.stats ? await ttsService.synthesizeSpeechWithMetrics(request) : await ttsService.synthesizeSpeech(request);
|
|
3644
|
+
audioBuffer = Buffer.from(response.audioContent, "base64");
|
|
3645
|
+
if (options.json) {
|
|
3646
|
+
console.log(JSON.stringify(response, null, 2));
|
|
3647
|
+
} else {
|
|
3648
|
+
const outputPath = resolve(
|
|
3649
|
+
options.output || `output${fileExtension}`
|
|
3650
|
+
);
|
|
3651
|
+
await writeFile(outputPath, audioBuffer);
|
|
3652
|
+
console.log(chalk13.green(`\u2705 Audio saved to: ${outputPath}`));
|
|
3653
|
+
console.log(
|
|
3654
|
+
chalk13.gray(
|
|
3655
|
+
`File size: ${(audioBuffer.length / 1024).toFixed(2)} KB`
|
|
3656
|
+
)
|
|
3657
|
+
);
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
if (options.json) {
|
|
3661
|
+
process.exit(0);
|
|
3662
|
+
return;
|
|
3663
|
+
}
|
|
3664
|
+
if (options.stats && response._metrics) {
|
|
3665
|
+
const m = response._metrics;
|
|
3666
|
+
const isStreaming = "timeToFirstChunk" in m;
|
|
3667
|
+
if (isStreaming) {
|
|
3668
|
+
const sm = m;
|
|
3669
|
+
console.log(
|
|
3670
|
+
"\n" + chalk13.cyan("\u{1F4CA} Streaming Performance Statistics:")
|
|
3671
|
+
);
|
|
3672
|
+
console.log(chalk13.gray("\u2550".repeat(50)));
|
|
3673
|
+
console.log(chalk13.bold.white("\n Streaming Timeline:"));
|
|
3674
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3675
|
+
console.log(
|
|
3676
|
+
chalk13.white(" \u23F1\uFE0F Time to First Chunk: ") + chalk13.yellow(`${sm.timeToFirstChunk.toFixed(0)} ms`)
|
|
3677
|
+
);
|
|
3678
|
+
console.log(
|
|
3679
|
+
chalk13.white(" \u23F2\uFE0F Total Stream Time: ") + chalk13.bold.yellow(`${sm.totalTime.toFixed(0)} ms`)
|
|
3680
|
+
);
|
|
3681
|
+
console.log(chalk13.bold.white("\n Chunk Statistics:"));
|
|
3682
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3683
|
+
console.log(
|
|
3684
|
+
chalk13.white(" \u{1F4E6} Chunks Received: ") + chalk13.yellow(`${sm.chunksReceived}`)
|
|
3685
|
+
);
|
|
3686
|
+
if (sm.errorChunks > 0) {
|
|
3687
|
+
console.log(
|
|
3688
|
+
chalk13.white(" \u26A0\uFE0F Error Chunks: ") + chalk13.red(`${sm.errorChunks}`)
|
|
3689
|
+
);
|
|
3690
|
+
}
|
|
3691
|
+
if (sm.chunkSizes.length > 0) {
|
|
3692
|
+
const avgChunkSize = sm.chunkSizes.reduce((a, b) => a + b, 0) / sm.chunkSizes.length;
|
|
3693
|
+
const minChunkSize = Math.min(...sm.chunkSizes);
|
|
3694
|
+
const maxChunkSize = Math.max(...sm.chunkSizes);
|
|
3695
|
+
console.log(
|
|
3696
|
+
chalk13.white(" \u{1F4CF} Avg Chunk Size: ") + chalk13.yellow(`${(avgChunkSize / 1024).toFixed(2)} KB`)
|
|
3697
|
+
);
|
|
3698
|
+
console.log(
|
|
3699
|
+
chalk13.gray(" Min/Max: ") + chalk13.gray(
|
|
3700
|
+
`${(minChunkSize / 1024).toFixed(2)} - ${(maxChunkSize / 1024).toFixed(2)} KB`
|
|
3701
|
+
)
|
|
3702
|
+
);
|
|
3703
|
+
}
|
|
3704
|
+
if (sm.chunkIntervals.length > 0) {
|
|
3705
|
+
const avgInterval = sm.chunkIntervals.reduce((a, b) => a + b, 0) / sm.chunkIntervals.length;
|
|
3706
|
+
const minInterval = Math.min(...sm.chunkIntervals);
|
|
3707
|
+
const maxInterval = Math.max(...sm.chunkIntervals);
|
|
3708
|
+
console.log(
|
|
3709
|
+
chalk13.white(" \u23F3 Avg Chunk Interval: ") + chalk13.yellow(`${avgInterval.toFixed(0)} ms`)
|
|
3710
|
+
);
|
|
3711
|
+
console.log(
|
|
3712
|
+
chalk13.gray(" Min/Max: ") + chalk13.gray(
|
|
3713
|
+
`${minInterval.toFixed(0)} - ${maxInterval.toFixed(0)} ms`
|
|
3714
|
+
)
|
|
3715
|
+
);
|
|
3716
|
+
}
|
|
3717
|
+
console.log(chalk13.bold.white("\n Data Transfer:"));
|
|
3718
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3719
|
+
console.log(
|
|
3720
|
+
chalk13.white(" \u{1F4E5} Total Data: ") + chalk13.yellow(`${(sm.totalBytes / 1024).toFixed(2)} KB`)
|
|
3721
|
+
);
|
|
3722
|
+
console.log(
|
|
3723
|
+
chalk13.white(" \u{1F3B5} Audio File: ") + chalk13.yellow(
|
|
3724
|
+
`${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
|
|
3725
|
+
)
|
|
3726
|
+
);
|
|
3727
|
+
console.log(chalk13.bold.white("\n Performance Metrics:"));
|
|
3728
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3729
|
+
const throughputKBps = sm.totalBytes / 1024 / (sm.totalTime / 1e3);
|
|
3730
|
+
console.log(
|
|
3731
|
+
chalk13.white(" \u{1F4F6} Stream Throughput: ") + chalk13.yellow(`${throughputKBps.toFixed(2)} KB/s`)
|
|
3732
|
+
);
|
|
3733
|
+
const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
|
|
3734
|
+
const realTimeRatio = audioDuration / (sm.totalTime / 1e3);
|
|
3735
|
+
console.log(
|
|
3736
|
+
chalk13.white(" \u{1F3B5} Audio Duration: ") + chalk13.yellow(`${audioDuration.toFixed(2)} seconds`)
|
|
3737
|
+
);
|
|
3738
|
+
console.log(
|
|
3739
|
+
chalk13.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk13.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk13.yellow(`${realTimeRatio.toFixed(2)}x`))
|
|
3740
|
+
);
|
|
3741
|
+
const streamingEfficiency = (sm.totalTime - sm.timeToFirstChunk) / sm.totalTime * 100;
|
|
3742
|
+
console.log(
|
|
3743
|
+
chalk13.white(" \u{1F4C8} Stream Efficiency: ") + chalk13.yellow(`${streamingEfficiency.toFixed(1)}%`)
|
|
3744
|
+
);
|
|
3745
|
+
console.log(chalk13.gray("\u2550".repeat(50)));
|
|
3746
|
+
} else {
|
|
3747
|
+
console.log("\n" + chalk13.cyan("\u{1F4CA} Performance Statistics:"));
|
|
3748
|
+
console.log(chalk13.gray("\u2550".repeat(50)));
|
|
3749
|
+
console.log(chalk13.bold.white("\n Network Timing:"));
|
|
3750
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3751
|
+
console.log(
|
|
3752
|
+
chalk13.white(" \u23F1\uFE0F Time to First Byte: ") + chalk13.yellow(`${m.ttfb.toFixed(0)} ms`)
|
|
3753
|
+
);
|
|
3754
|
+
if (m.downloadTime !== void 0) {
|
|
3755
|
+
console.log(
|
|
3756
|
+
chalk13.white(" \u2B07\uFE0F Content Download: ") + chalk13.yellow(`${m.downloadTime.toFixed(0)} ms`)
|
|
3757
|
+
);
|
|
3758
|
+
}
|
|
3759
|
+
console.log(
|
|
3760
|
+
chalk13.white(" \u23F2\uFE0F Total Time: ") + chalk13.bold.yellow(`${m.totalTime.toFixed(0)} ms`)
|
|
3761
|
+
);
|
|
3762
|
+
console.log(chalk13.bold.white("\n Data Transfer:"));
|
|
3763
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3764
|
+
if (m.requestSize) {
|
|
3765
|
+
console.log(
|
|
3766
|
+
chalk13.white(" \u2B06\uFE0F Request Size: ") + chalk13.yellow(`${(m.requestSize / 1024).toFixed(2)} KB`)
|
|
3767
|
+
);
|
|
3768
|
+
}
|
|
3769
|
+
console.log(
|
|
3770
|
+
chalk13.white(" \u2B07\uFE0F Response Size: ") + chalk13.yellow(`${(m.responseSize / 1024).toFixed(2)} KB`)
|
|
3771
|
+
);
|
|
3772
|
+
console.log(
|
|
3773
|
+
chalk13.white(" \u{1F3B5} Audio File: ") + chalk13.yellow(
|
|
3774
|
+
`${((audioBuffer?.length || 0) / 1024).toFixed(2)} KB`
|
|
3775
|
+
)
|
|
3776
|
+
);
|
|
3777
|
+
console.log(chalk13.bold.white("\n Performance Metrics:"));
|
|
3778
|
+
console.log(chalk13.gray(" \u2500".repeat(23)));
|
|
3779
|
+
const audioDuration = (audioBuffer?.length || 0) / (128 * 125);
|
|
3780
|
+
const realTimeRatio = audioDuration / (m.totalTime / 1e3);
|
|
3781
|
+
const serverTime = m.ttfb;
|
|
3782
|
+
console.log(
|
|
3783
|
+
chalk13.white(" \u{1F5A5}\uFE0F Server Processing: ") + chalk13.yellow(`${Math.max(0, serverTime).toFixed(0)} ms`)
|
|
3784
|
+
);
|
|
3785
|
+
console.log(
|
|
3786
|
+
chalk13.white(" \u{1F3B5} Audio Duration: ") + chalk13.yellow(`${audioDuration.toFixed(2)} seconds`)
|
|
3787
|
+
);
|
|
3788
|
+
console.log(
|
|
3789
|
+
chalk13.white(" \u26A1 Real-time Factor: ") + (realTimeRatio > 1 ? chalk13.green(`${realTimeRatio.toFixed(2)}x faster`) : chalk13.yellow(`${realTimeRatio.toFixed(2)}x`))
|
|
3790
|
+
);
|
|
3791
|
+
const throughputMbps = (m.responseSize + (audioBuffer?.length || 0)) * 8 / (m.totalTime * 1e3);
|
|
3792
|
+
console.log(
|
|
3793
|
+
chalk13.white(" \u{1F4F6} Throughput: ") + chalk13.yellow(`${throughputMbps.toFixed(2)} Mbps`)
|
|
3794
|
+
);
|
|
3795
|
+
console.log(chalk13.gray("\u2550".repeat(50)));
|
|
3796
|
+
}
|
|
3797
|
+
}
|
|
3798
|
+
if (response.timestampInfo?.wordAlignment) {
|
|
3799
|
+
const alignment = response.timestampInfo.wordAlignment;
|
|
3800
|
+
console.log("\n" + chalk13.cyan("\u{1F4DD} Word Timestamps:"));
|
|
3801
|
+
alignment.words.forEach((word, i) => {
|
|
3802
|
+
const start = alignment.wordStartTimeSeconds[i].toFixed(3);
|
|
3803
|
+
const end = alignment.wordEndTimeSeconds[i].toFixed(3);
|
|
3804
|
+
console.log(chalk13.gray(` ${start}s - ${end}s: ${word}`));
|
|
3805
|
+
});
|
|
3806
|
+
}
|
|
3807
|
+
if (response.timestampInfo?.characterAlignment) {
|
|
3808
|
+
console.log("\n" + chalk13.cyan("\u{1F4DD} Character Timestamps:"));
|
|
3809
|
+
console.log(
|
|
3810
|
+
chalk13.gray(
|
|
3811
|
+
" (Too detailed to display - use --json to see full data)"
|
|
3812
|
+
)
|
|
3813
|
+
);
|
|
3814
|
+
}
|
|
3815
|
+
process.exit(0);
|
|
3816
|
+
} catch (error) {
|
|
3817
|
+
console.error(chalk13.red("\u274C Error synthesizing speech:"));
|
|
3818
|
+
console.error(chalk13.red(error.message || error));
|
|
3819
|
+
process.exit(1);
|
|
3820
|
+
}
|
|
3821
|
+
});
|
|
3822
|
+
var ttsCommand = new Command17("tts").description("Text-to-speech functionality").addCommand(listVoicesCommand).addCommand(synthesizeCommand).action(() => {
|
|
3823
|
+
ttsCommand.help();
|
|
3824
|
+
});
|
|
3825
|
+
|
|
3826
|
+
// src/commands/workspace_command.ts
|
|
3827
|
+
import { Command as Command18 } from "commander";
|
|
3828
|
+
var selectWorkspaceCommand = new Command18("select").description("Select a workspace for CLI operations").action(async () => {
|
|
3829
|
+
await requireAuth();
|
|
3830
|
+
try {
|
|
3831
|
+
await WorkspaceService.activateWorkspace();
|
|
3832
|
+
process.exit(0);
|
|
3833
|
+
} catch (_error) {
|
|
3834
|
+
printError("\nFailed to select workspace:");
|
|
3835
|
+
process.exit(1);
|
|
3836
|
+
}
|
|
3837
|
+
});
|
|
3838
|
+
var workspaceCommand = new Command18("workspace").description("Manage Inworld workspaces").alias("ws").addCommand(selectWorkspaceCommand).action(() => {
|
|
3839
|
+
workspaceCommand.help();
|
|
3840
|
+
});
|
|
3841
|
+
|
|
3842
|
+
// index.ts
|
|
3843
|
+
var version = CLI_VERSION;
|
|
3844
|
+
process.env.DISABLE_WELCOME_MESSAGE = "true";
|
|
3845
|
+
var InworldCLI = class {
|
|
3846
|
+
program;
|
|
3847
|
+
constructor() {
|
|
3848
|
+
this.program = new Command19();
|
|
3849
|
+
this.setupProgram();
|
|
3850
|
+
this.registerCommands();
|
|
3851
|
+
}
|
|
3852
|
+
setupProgram() {
|
|
3853
|
+
this.program.name("inworld").description("Inworld Runtime CLI").version(version, "--version").configureOutput({
|
|
3854
|
+
writeOut: (str) => process.stdout.write(str),
|
|
3855
|
+
writeErr: (str) => process.stderr.write(str),
|
|
3856
|
+
getOutHelpWidth: () => process.stdout.columns || 80,
|
|
3857
|
+
getErrHelpWidth: () => process.stderr.columns || 80
|
|
3858
|
+
});
|
|
3859
|
+
}
|
|
3860
|
+
registerCommands() {
|
|
3861
|
+
this.program.addCommand(loginCommandAlias);
|
|
3862
|
+
this.program.addCommand(logoutCommandAlias);
|
|
3863
|
+
this.program.addCommand(statusCommandAlias);
|
|
3864
|
+
this.program.addCommand(serveCommandAlias);
|
|
3865
|
+
this.program.addCommand(runCommandAlias);
|
|
3866
|
+
this.program.addCommand(deployCommandAlias);
|
|
3867
|
+
this.program.addCommand(initCommandAlias);
|
|
3868
|
+
this.program.addCommand(authCommand);
|
|
3869
|
+
this.program.addCommand(graphCommand);
|
|
3870
|
+
this.program.addCommand(ttsCommand);
|
|
3871
|
+
this.program.addCommand(workspaceCommand);
|
|
3872
|
+
this.program.command("help").description("Display help information").action(() => {
|
|
3873
|
+
this.program.help();
|
|
3874
|
+
});
|
|
3875
|
+
}
|
|
3876
|
+
async run(args) {
|
|
3877
|
+
try {
|
|
3878
|
+
await this.program.parseAsync(args);
|
|
3879
|
+
} catch (error) {
|
|
3880
|
+
console.error(
|
|
3881
|
+
chalk14.red("Error:"),
|
|
3882
|
+
error instanceof Error ? error.message : String(error)
|
|
3883
|
+
);
|
|
3884
|
+
process.exit(1);
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
};
|
|
3888
|
+
var cli = new InworldCLI();
|
|
3889
|
+
cli.run().catch((error) => {
|
|
3890
|
+
console.error(chalk14.red("Fatal error:"), error);
|
|
3891
|
+
process.exit(1);
|
|
3892
|
+
});
|
|
3893
|
+
//# sourceMappingURL=index.js.map
|